Skip to content
Myr

Merge build/comments-web-features into main

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

authored by oscabriel · committed by oscabriel · parents 49efd2a, 9c0cf6e · Browse files · 167 files+276 added−3811 removed
This commit

State

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

Diff stats

167 files+276 added−3811 removed

  • other:+276 added−3811 removed

167 files+276 added−3811 removed

modified:apps/web/src/features/agents/catalog.ts-5 removed
modified:apps/web/src/features/agents/forward.ts-10 removed
modified:apps/web/src/features/agents/llms.ts+2 added-7 removed
modified:apps/web/src/features/agents/manifest.ts+2 added-10 removed
modified:apps/web/src/features/agents/reference.tsx+2 added-22 removed
1/**2 * The For agents page's reference sections, set like a man page: the3 * CLI's synopsis, the endpoints, the limits and the refusals. Every word4 * that is not a heading comes from `@repo/agent-kit` (`synopsis`,5 * `agentEndpoints`, `agentLimits`) or the refusal union itself, so the6 * page and `/agents.md` say the same. Mono only for what a terminal takes:7 * commands, addresses and tags.8 */1import type {2 Endpoint,3 Limit,4 SynopsisLine,
1 unmodified line
6import { groups } from "@repo/protocol/refusal";7import { Fragment } from "react";8import type { ReactNode } from "react";918/** A link in running text: the rule colour's underline, ink on hover. */10export const LINK =11 "decoration-rule underline underline-offset-[0.2em] hover:decoration-current";1222/** One section of the reference: its heading at Title size, in the sans, then its body. */13export const ReferenceSection = ({14 children,15 id,16 title,
10 unmodified lines
27 {children}28 </section>29);3041/**42 * A usage line that wraps only between its words, never inside a flag43 * (`[--json]` stays whole), so a phone reads it as typed.44 */31const Usage = ({ usage }: { readonly usage: string }) => (32 <code className="text-mono font-mono">33 {usage.split(" ").map((word, index) => (34 <Fragment key={index}>
3 unmodified lines
38 ))}39 </code>40);4156/** Every command as typed, each over what it does, set close like a man page's synopsis. */42export const Synopsis = ({43 lines,44}: {45 readonly lines: readonly SynopsisLine[];
7 unmodified lines
53 ))}54 </ul>55);5672/** Each address an agent reads, one line each, linked where a browser can open it. */57export const Endpoints = ({58 endpoints,59}: {60 readonly endpoints: readonly Endpoint[];
11 unmodified lines
72 className="border-rule flex min-w-0 flex-col gap-0.5 border-b py-2.5"73 key={url}74 >75 {readable ? (92 // A server's own text, not a page of the app.76 <a className={`${LINK} w-fit max-w-full`} href={url}>77 {address}78 </a>79 ) : (
5 unmodified lines
85 })}86 </ul>87);88106/** The limits, as a plain table. */89export const Limits = ({ limits }: { readonly limits: readonly Limit[] }) => (90 <table className="text-ui w-full max-w-[48rem] border-collapse text-left">91 <thead>92 <tr className="border-rule border-b">
18 unmodified lines
111 </table>112);113114/**133 * Where `/llms-full.txt` lists a refusal: a text fragment on its table row134 * (`` `Tag` | Group ``), which nothing else in the file reads. A dash ends135 * a fragment's word, so it is escaped as well.115 * A text fragment on the refusal's row in `/llms-full.txt` (`` `Tag` | Group116 * ``). A dash ends a fragment's word, so it is escaped as well.117 */118const rowOf = (tag: string, group: string) =>119 `/llms-full.txt#:~:text=${encodeURIComponent(`\`${tag}\` | ${group}`).replaceAll("-", "%2D")}`;120140/** Every refusal of the union, by group, each tag linked to its row. */121export const Refusals = () => (122 <>123 <p className="text-ui text-muted-foreground max-w-[70ch]">124 Each tag opens its row in{" "}
30 unmodified lines
modified:apps/web/src/features/agents/respond.ts-9 removed
modified:apps/web/src/features/agents/setup-page.tsx-20 removed
1/**2 * The For agents page: one reference, in the order a reader reaches for3 * it: the CLI's synopsis, the ways to connect, the endpoints, the limits4 * and the refusals. The inspector is its contents. Every snippet and every5 * line of reference is `@repo/agent-kit`'s (`agentSetup` and its6 * neighbours), so the page has no text of its own for any of them7 * (principle 4). A shell line is a `CommandLine`; JSON and text to paste8 * sit in a block with the same copy affordance. A view: the CLI's commands9 * and the two hosts' URLs in, markup out.10 */1import {2 agentEndpoints,3 agentLimits,4 agentSetup,
18 unmodified lines
23 Refusals,24 Synopsis,25} from "./reference.tsx";2637/** The reference's sections, in order: each one's anchor and heading. */27const SECTIONS = [28 { id: "synopsis", title: "Synopsis" },29 { id: "connect", title: "Connect" },30 { id: "endpoints", title: "Endpoints" },31 { id: "limits", title: "Limits" },32 { id: "refusals", title: "Refusals" },33] as const;3446/**47 * JSON or text to paste: whole, with a button that copies it. It keeps its48 * own lines and indentation and scrolls sideways where the screen is49 * narrower than a line, as code does everywhere on the web, rather than50 * wrapping a value under its key; the keyboard reaches it to scroll.51 */35const SnippetBlock = ({ snippet }: { readonly snippet: SetupSnippet }) => {36 const { copied, copy } = useCopy(snippet.text);3738 return (39 <div className="border-rule bg-surface flex max-w-full min-w-0 items-start gap-2 border py-1 pr-1 pl-3">40 <pre41 aria-label={snippet.label}42 className="text-mono leading-terminal min-w-0 flex-1 overflow-x-auto py-0.5 font-mono whitespace-pre"60 // A box that scrolls is a stop for Tab, so a keyboard can scroll it.43 // oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- a scrolling region must take focus to be scrolled without a pointer (WCAG 2.1.1)44 tabIndex={0}45 >46 <code className="select-all">{snippet.text}</code>
24 unmodified lines
71 )}72 </figure>73);7493/** One way to connect: its name, the agent it is for, and what to copy. */75const Channel = ({ channel }: { readonly channel: SetupChannel }) => (76 <div className="border-rule flex min-w-0 flex-col gap-3 border-t pt-4">77 <h3 className="text-want font-semibold">{channel.title}</h3>78 <p className="max-w-[70ch]">{channel.useWhen}</p>
4 unmodified lines
83 </div>84 </div>85);86106/** The inspector: the sections, as anchors. */87const Contents = () => (88 <nav aria-label="Contents">89 <ul className="flex flex-col">90 {SECTIONS.map(({ id, title }) => (
48 unmodified lines
modified:apps/web/src/features/answer/answer-page.tsx+2 added-69 removed
1/**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, how18 * 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 */1import { Brand } from "@repo/brand";2import type {3 HeldBackResult,4 LaneOutcome,
44 unmodified lines
49 roundOf,50 roundsAsTheyStand,51} from "./subject.ts";5275/** How long a lane ran: "640 ms", "8.3 s", "2 min 5 s". */53export const durationText = (millis: number) => {54 if (millis < 1000) {55 return `${millis} ms`;56 }
6 unmodified lines
6364 return `${Math.floor(seconds / 60)} min ${seconds % 60} s`;65};6690/** Each lane result as a mark, a word and its role colour: the word first. */67const results = {68 blocked: { mark: "waiting", tone: "text-waiting", word: "blocked" },69 failed: { mark: "refused", tone: "text-refused", word: "failed" },70 flaked: { mark: "retry", tone: "text-waiting", word: "flaked" },
3 unmodified lines
74 LaneOutcome,75 { readonly mark: StateMark; readonly tone: string; readonly word: string }76>;77102/** The page's trail: the project, its asks, the ask, then this answer. */78export const answerCrumbs = (ask: Ask): readonly Crumb[] => [79 { label: ask.project, to: `/${ask.project}` },80 { label: "Asks", to: `/${ask.project}` },81 { label: ask.id, mono: true, to: askPath(ask.project, ask.id) },82 { label: "Answer" },83];84110/** What reads a lane's log, when the platform kept one. */85const LaneLog = ({86 lane,87 project,88}: {
14 unmodified lines
103 />104 );105};106133/** One lane: its mark, name and command, its result in a word, and how long it ran. */107const LaneRow = ({108 lane,109 project,110}: {
31 unmodified lines
142 </li>143 );144};145173/** "6 lanes passed in 41 s": the lanes run one after another, so their times add up. */146const passedLine = (lanes: readonly LaneResult[]) =>147 `${lanes.length} ${lanes.length === 1 ? "lane" : "lanes"} passed in ${durationText(148 lanes.reduce((total, { durationMs }) => total + durationMs, 0)149 )}`;150179/** The lanes the platform ran on the merged tree: what failed, open and first; what passed, in one line. */151export const Lanes = ({152 checking = false,153 lanes,154 project,155}: {156 readonly lanes: readonly LaneResult[];157 readonly project: Ask["project"];187 /** The gate is still at work on the answer: its lanes may yet run. */158 readonly checking?: boolean;159}) => {160 if (lanes.length === 0) {161 return (
43 unmodified lines
205 </div>206 );207};208239/** Held-back checks: one line per area, as the landing's trailer spells it, and nothing else. */209export const HeldBackBits = ({210 results: areas,211}: {212 readonly results: readonly HeldBackResult[];
21 unmodified lines
234 ))}235 </ul>236);237269/** A git id, short as git prints it, whole on hover. */238const Sha = ({ sha }: { readonly sha: string }) => (239 <code className="text-mono font-mono" title={sha}>240 {shortSha(sha)}241 </code>242);243276/** Content the inspector shows, left out of the facts drawn inline in main below the shell's width. */244export const InspectorOnly = ({245 children,246}: {247 readonly children: ReactNode;
2 unmodified lines
250 {children}251 </div>252);253287/**288 * Every push the gate checked, newest first, the one the page reads289 * selected: first in main, once there is more than one, so a verdict is290 * read against its round.291 */254const RoundsRegion = ({255 ask,256 current,257 now,
2 unmodified lines
260}: {261 readonly ask: AskId;262 readonly project: ProjectName;263 readonly rounds: readonly Round[];302 /** The head the page shows. */264 readonly current: CommitSha | undefined;265 readonly now: DateTime.Utc;266}) => {306 // The page reads the last round at its head.267 const read =268 current === undefined269 ? 0270 : rounds.findLastIndex(({ head }) => head === current) + 1;
25 unmodified lines
296 </Region>297 );298};299340/**341 * What a waiting answer's contributor needs, from its rounds: there is342 * nothing to run, and what another push would start.343 */300const waitingSentence = (round: ReturnType<typeof roundOf>) =>301 round === undefined302 ? "Nothing for you to run."303 : `Nothing for you to run. Pushing again starts round ${round.of + 1}; this verdict stays as round ${round.number}.`;304349/** What the hero says before any answer was judged: who holds the ask, or how to take it. */305const NoAnswerYet = ({306 ask,307 now,308 states,
31 unmodified lines
340 />341 );342 }343389 // What it waits on must land before anyone can claim it.344 const waiting = ask.blockedBy.filter(345 (blocker) => states.get(blocker)?.landed === undefined346 ).length;347
24 unmodified lines
372 />373 );374};375422/**423 * The outcome, a step up: settled in when it changes while the page is424 * open (never on the first paint), and stamped once on a live landing.425 */376const Hero = ({377 ask,378 now,379 stamp,
6 unmodified lines
386 readonly states: ReadonlyMap<AskId, AskProgress>;387 readonly verdict: Verdict | undefined;388}) => {389 const tag = verdict?.outcome._tag ?? "none";440 // Only an outcome that replaced another while the page was open settles in.390 const [shown, setShown] = useState(tag);391 const [changed, setChanged] = useState(false);392393 if (shown !== tag) {
28 unmodified lines
422 </section>423 );424};425477/** The answer's run: the gate, the lanes, the held-back checks, and the landing. */426const Run = ({427 holds,428 landing,429 now,
2 unmodified lines
432}: {433 readonly holds: ReturnType<typeof holdsOf>;434 readonly landing: LandingView | undefined;435 readonly now: DateTime.Utc;488 /** Which round the verdict is, of how many. */436 readonly round: ReturnType<typeof roundOf>;437 readonly verdict: Verdict;438}) => (439 <>
44 unmodified lines
484 )}485486 {landing === undefined ? null : (487 <Region id="answer-landing" title="Landing">541 {/* The landing told as a sentence before it is shown as a hash:542 the page's job is to credit the people. */}488 {/* The landing told as a sentence before it is shown as a hash. */}489 <p className="text-title flex min-w-0 flex-wrap items-baseline gap-x-2 font-normal">490 <span className="flex items-center gap-2 font-semibold">491 <StateMarkIcon mark="landed" />492 <span className="text-landed">Landed</span>
54 unmodified lines
547 </AppLink>548 </Region>549 )}550605 {/* Below the shell's width the inspector's facts sit above the run, so606 the plumbing comes here, last. */}551 {/* Below the shell's width the inspector's facts sit above the run, so the plumbing comes here, last. */}552 <div className="shell:hidden">553 <ProvenanceFacts entries={verdictProvenance(verdict, now)} />554 </div>555 </>556);557558export interface AnswerViewProps {614 /** The ask the answer is to: its want titles the page. */559 readonly ask: Ask;616 /** The verdict on the answer; none before one was judged. */560 readonly verdict: Verdict | undefined;618 /** The landing it made, once it landed. */561 readonly landing?: LandingView | undefined;562 readonly now: DateTime.Utc;621 /** Where each ask stands, from the project's events (`askStates`). */563 readonly states?: ReadonlyMap<AskId, AskProgress>;623 /** The family's parent, when the ask is a member of one. */564 readonly parent?: Ask | undefined;625 /** The head the address names, when it names an earlier answer. */565 readonly head?: CommitSha | undefined;627 /** It landed while the page was open: stamp the landing's mark, once. */566 readonly stamp?: boolean;629 /** Who is reading, to tell the claimant the claim is theirs. */567 readonly viewer?: Handle | undefined;568}569570const NONE: ReadonlyMap<AskId, AskProgress> = new Map();571635/** The answer's facts: its state, claim, family, territory and check, then what was judged. */572const AnswerFacts = ({573 ask,574 now,575 parent,
55 unmodified lines
631 </>632 );633};634699/** The line under the hero's title: the ask, the round, when it was judged, and the way to the latest answer. */635const AnswerMeta = ({636 ask,637 head,638 now,
91 unmodified lines
730 }731 />732 }733 status={799 // The answer's head reads title, then which answer this is, then800 // the outcome: a refusal drawn whole would bury a line after it.734 <div className="flex min-w-0 flex-col gap-4">735 <div className="text-ui text-muted-foreground">736 <AnswerMeta737 ask={ask}
43 unmodified lines
modified:apps/web/src/features/answer/reads.ts-38 removed
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 */1import { Client } from "@repo/protocol/contracts";2import { Verdict } from "@repo/protocol/domain/answer";3import { Ask } from "@repo/protocol/domain/ask";4import { CheckSpec } from "@repo/protocol/domain/check";
13 unmodified lines
1819import { notFoundFor } from "../shared/refusals.ts";20import { keptEvents, readEvents, readParent } from "./subject.ts";2130/** An ask's address, not yet decoded. */22export interface AskAddress {23 readonly ask: string;24 readonly project: string;25}2636/** The address, decoded: names the platform could hold. */27const AskPath = Schema.Struct({ ask: AskId, project: ProjectName });2839/** The check's file, as the page carries it. */29const CheckRead = Schema.Struct({30 path: RepoPath,31 sha: BlobSha,32 text: Schema.String,33});3446/**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 */35export const AskPageData = Schema.Struct({36 ask: Ask,37 brief: Schema.NonEmptyString,38 check: Schema.UndefinedOr(CheckRead),
5 unmodified lines
44});4546export type AskPageData = typeof AskPageData.Type;4765/** The check's source on main, when the check is a file that reads as text; none when it cannot be read. */48const readCheck = (ask: Ask) =>49 Effect.gen(function* () {50 if (!CheckSpec.guards.RedThenGreen(ask.check)) {51 return Option.none<typeof CheckRead.Type>();
12 unmodified lines
64 Effect.orElseSucceed(() => Option.none<typeof CheckRead.Type>())65 );66 });6786/**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 */68export const readAsk = (params: AskAddress) =>69 Effect.gen(function* () {70 const path = yield* Schema.decodeEffect(AskPath)(params).pipe(71 Effect.mapError(() => notFound())
33 unmodified lines
105 ),106 });107 });108132/** The page's address, not yet decoded: the path's names and `?head=`. */109export interface AnswerAddress {110 readonly ask: string;111 readonly head?: string | undefined;112 readonly project: string;113}114139/** The address, decoded: names the platform could hold, and a commit id. */115const AnswerPath = Schema.Struct({116 ask: AskId,117 head: Schema.optionalKey(CommitSha),118 project: ProjectName,119});120146/**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 */121export const AnswerPageData = Schema.Struct({122 ...AnswerPath.fields,123 askRead: Ask,124 brief: Schema.NonEmptyString,
6 unmodified lines
131});132133export type AnswerPageData = typeof AnswerPageData.Type;134165/** The landing a verdict's answer made, when it landed. */135export const landedBy = (136 verdict: Verdict | undefined137): LandedSha | undefined =>138 verdict !== undefined && Outcome.isAnyOf(["Landed"])(verdict.outcome)139 ? verdict.outcome.sha140 : undefined;141173/** The landing at `sha`; none for no landing, or one the platform no longer finds. */142const readLanding = (project: ProjectName, sha: LandedSha | undefined) =>143 Effect.gen(function* () {144 if (sha === undefined) {145 return Option.none<LandingView>();
2 unmodified lines
148 const client = yield* Client;149150 return yield* client.landing({ project, sha }).pipe(151 Effect.map((found) => Option.some(found.landing)),184 // The verdict names a landing the platform no longer finds: show the verdict alone.152 Effect.catchTag("UnknownCommit", () => Effect.succeedNone)153 );154 });155189/**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 */156export const readAnswer = ({ ask, head, project }: AnswerAddress) =>157 Effect.gen(function* () {158 const path = yield* Schema.decodeEffect(AnswerPath)(159 head === undefined ? { ask, project } : { ask, head, project }
34 unmodified lines
modified:apps/web/src/features/answer/subject.ts+4 added-38 removed
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 */1import { Client } from "@repo/protocol/contracts";2import type { Verdict } from "@repo/protocol/domain/answer";3import type { Ask } from "@repo/protocol/domain/ask";4import { ProjectEvent } from "@repo/protocol/domain/event";
5 unmodified lines
10import { lastSeq } from "../shared/ask-progress.ts";11import type { AskProgress, Round } from "../shared/ask-progress.ts";12import type { StageHolds } from "../shared/outcome.tsx";1330/** The ask an event is about: one, or none. */14const askOf = (event: ProjectEvent): readonly AskId[] =>15 ProjectEvent.match(event, {16 AskClosed: ({ ask }) => [ask],17 AskOpened: ({ ask }) => [ask.ask],
9 unmodified lines
27 Released: ({ ask }) => [ask],28 Warned: ({ ask }) => [ask],29 });3048/** The events about `asks`, in the order given. */31export const eventsAbout = (32 events: readonly ProjectEvent[],33 asks: ReadonlySet<AskId>34): readonly ProjectEvent[] =>35 events.filter((event) => askOf(event).some((about) => asks.has(about)));3655/**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 */37/** The platform names a split's delete child after its parent. */38export const deleteChildOf = (parent: Ask): AskId | undefined =>39 parent.blockedBy.find((child) => child === `${parent.id}-delete`);4062/** The parent of the family `ask` is in: the one read for it, or the ask itself when it heads one. */41export const familyHead = (ask: Ask, parent: Ask | undefined) =>42 parent ?? (deleteChildOf(ask) === undefined ? undefined : ask);4366/** Every ask whose events the page needs: the ask, what it waits on, and its family. */44export const asksAround = (45 ask: Ask,46 parent: Ask | undefined47): ReadonlySet<AskId> =>
2 unmodified lines
50 ...ask.blockedBy,51 ...(parent === undefined ? [] : [parent.id, ...parent.blockedBy]),52 ]);5377/** The project's events from the first; none when they cannot be read. */54export const readEvents = (project: ProjectName) =>55 Effect.gen(function* () {56 const client = yield* Client;57
3 unmodified lines
6162 return events;63 });6489/** The parent ask of a family member; none for an ask in no family, or one the platform no longer finds. */65export const readParent = (ask: Ask) =>66 Effect.gen(function* () {67 if (ask.parent === undefined) {68 return Option.none<Ask>();
8 unmodified lines
77 Effect.orElseSucceed(() => Option.none<Ask>())78 );79 });80106/** What a page carries of the events: those about its asks, and the last number of all of them. */81export const keptEvents = (82 events: readonly ProjectEvent[],83 ask: Ask,84 parent: Ask | undefined
1 unmodified line
86 events: eventsAbout(events, asksAround(ask, parent)),87 lastSeq: lastSeq(events),88});89116/** Whether an outcome waited on a person: a decision, or a decider's finish. */90const waitedOnPerson = Outcome.isAnyOf(["AwaitingDecision", "AwaitingFinish"]);91119/**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 */92export const holdsOf = (93 verdict: Verdict,94 landing: LandingView | undefined,95 rounds: readonly Round[]
5 unmodified lines
101 ),102 heldBack: verdict.heldBack.length > 0,103});104137/** Which round the answer at `head` is, of how many: the last round judged at that head. */105export const roundOf = (106 rounds: readonly Round[],107 head: CommitSha108): { readonly number: number; readonly of: number } | undefined => {
2 unmodified lines
111 return index === -1 ? undefined : { number: index + 1, of: rounds.length };112};113114/**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.115 * A round's own event says what the gate said when it judged the push (often116 * still checking), so the verdict on that head, and the landing that closed the117 * ask, speak for it once they came.118 */119export const roundsAsTheyStand = (120 progress: AskProgress | undefined,121 verdict: Verdict | undefined
22 unmodified lines
modified:apps/web/src/features/ask/ask-page.tsx-55 removed
1/**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 */1import { Brand } from "@repo/brand";2import type { Verdict } from "@repo/protocol/domain/answer";3import type { Ask } from "@repo/protocol/domain/ask";4import { CheckSpec } from "@repo/protocol/domain/check";
38 unmodified lines
43import { When } from "../shared/time.tsx";44import { Region } from "./fields.tsx";45import { markdownPath } from "./markdown.ts";4665/** The check's file, as the page read it: enough to draw its source. */47export interface CheckSource {48 readonly path: string;68 /** The blob's id: the drawing's cache key. */49 readonly sha: string;50 readonly text: string;51}5253const LINK = "decoration-rule underline hover:decoration-current";5455const NONE: ReadonlyMap<AskId, AskProgress> = new Map();5677/** How many lines of the check show before the reader asks for the whole. */57const CHECK_LINES = 30;5880/** The page's trail: the project, its asks, then the ask. */59export const askCrumbs = (ask: Ask): readonly Crumb[] => [60 { label: ask.project, to: `/${ask.project}` },61 { label: "Asks", to: `/${ask.project}` },62 { label: ask.id, mono: true },63];6487/** The command that claims an ask, run in a clone of its project. */65export const claimCommand = (ask: Ask) =>66 `${Brand.cli} claim ${ask.id} --project ${ask.project}`;6791/** What judges an answer, by the check's kind, in words; its file linked when it has one. */68const CheckSummary = ({ ask }: { readonly ask: Ask }) =>69 CheckSpec.match(ask.check, {70 LintToZero: ({ rule, territory }) => (71 <>
39 unmodified lines
111 </>112 ),113 });114139/**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 */115const CheckFile = ({ source }: { readonly source: CheckSource }) => {116 const [whole, setWhole] = useState(false);117 const lines = linesOf(source.text);118 const long = lines.length > CHECK_LINES;
11 unmodified lines
130 {lines.length} {lines.length === 1 ? "line" : "lines"}131 </span>132 </figcaption>133 <ClientFile163 // Each cut of the file is its own drawing.134 fallback={<NumberedLines text={shown} />}135 key={whole ? "whole" : "head"}136 path={source.path}137 sha={whole || !long ? source.sha : `${source.sha}:${CHECK_LINES}`}
42 unmodified lines
180 ))}181 </ul>182);183214/** The brief's sections, as prose; the want is the page's title. */184const Brief = ({ ask }: { readonly ask: Ask }) => {185 const { context, current, outOfScope, terms } = ask.brief;186187 const parts = [
27 unmodified lines
215 </Region>216 );217};218250/** Every answer judged, one row each, oldest first, each linking its verdict. */219const Answers = ({220 ask,221 now,222 rounds,
35 unmodified lines
258 </AppLink>259 </Region>260);261294/** The asks an ask outside a family still waits on, each linked. */262const WaitsOn = ({263 asks,264 project,265}: {
23 unmodified lines
289 </span>290 </p>291);292326/**327 * What a family's parent waits on, in the fan's terms: how many of its328 * children have yet to land, then the delete step; never a list of ids329 * (the fan draws each child).330 */293const FamilyWaits = ({294 finale,295 parent,296 project,
38 unmodified lines
335};336337export interface AskViewProps {338 readonly ask: Ask;377 /** The brief as the platform renders it for an agent, in Markdown. */339 readonly brief: string;340 readonly now: DateTime.Utc;380 /** Where the project is cloned from. */341 readonly platformUrl: string;382 /** Where each ask stands, from the project's events (`askStates`). */342 readonly states?: ReadonlyMap<AskId, AskProgress>;384 /** The family's parent, when the ask is a member of one. */343 readonly parent?: Ask | undefined;386 /** The verdict on its latest answer, to say at which stage a refusal came. */344 readonly verdict?: Verdict | undefined;388 /** The check's source, when it is a file the page could read. */345 readonly check?: CheckSource | undefined;390 /** The project's posture, once the list of projects has it. */346 readonly posture?: Posture | undefined;392 /** Who is reading, to tell the claimant the claim is theirs. */347 readonly viewer?: Handle | undefined;348}349396/** Where the ask stands, as its status line reads it. */350const subjectOf = (351 ask: Ask,352 states: ReadonlyMap<AskId, AskProgress>,353 verdict: Verdict | undefined,
10 unmodified lines
364 project: ask.project,365 };366 }367415 // A refusal says at which stage it came, which only the verdict holds.368 const lastRound = progress?.rounds.at(-1);369370 if (371 latest !== undefined &&
22 unmodified lines
394 takeable,395 };396};397446/** Where an ask stands for its page: what it still waits on, whether it can be taken, and its family. */398const standing = (399 ask: Ask,400 states: ReadonlyMap<AskId, AskProgress>,401 parent: Ask | undefined
13 unmodified lines
415 held: progress?.claimant !== undefined || ask.state === "claimed",416 progress,417 remaining,418 takeable: ask.state === "open" && remaining.length === 0,468 // A family member says what it waits on in the family's terms, and a469 // wait the latest outcome already names needs no second line.419 waitsOn:420 ask.parent === undefined &&421 remaining.length > 0 &&422 !(latest !== undefined && Outcome.isAnyOf(["WaitingOnParent"])(latest)),423 };424};425477/** The ask's facts: its state, how to take it or who holds it, its territory and check, its family, its project's posture. */426const AskFacts = ({427 ask,428 now,429 parent,
58 unmodified lines
488 </>489 );490};491544/** The line under the title: the kind, who asked (and mentors), and when it opened. */492const AskMeta = ({493 ask,494 now,495}: {
17 unmodified lines
513 ]}514 />515);516570/** The Markdown an agent reads, shown whole on demand, and its own address. */517const ForAgents = ({518 ask,519 brief,520}: {
80 unmodified lines
601 {waitsOn && family !== ask ? (602 <WaitsOn asks={remaining} project={ask.project} />603 ) : null}604 {family === undefined ? null : (659 // Below the shell's width the family sits under the head, as a fan.605 <div className="shell:hidden mt-4">606 <FamilyStrip607 expanded={false}608 parent={family}
32 unmodified lines
modified:apps/web/src/features/ask/fields.tsx-16 removed
1/**2 * Labelled values, in two forms:3 *4 * - `Definitions` and `Definition`: a definition list, each term in the5 * label's style over its value, side by side from the shell's width;6 * the form records and agents' pages use (the ledger, the env shape, the7 * policy, For agents).8 * - `Fields` and `Field`: the grid of ruled rows the pages not yet moved9 * still use; from `lg` two fields share a row.10 *11 * Values that are code (ids, paths, SHAs) wrap anywhere, so a phone never12 * scrolls sideways.13 */1import type { ReactNode } from "react";23export const Fields = ({4 children,
22 unmodified lines
27 <dd className="min-w-0 [overflow-wrap:anywhere]">{children}</dd>28 </div>29);3044/** A list of terms and their values: one ruled row each. */31export const Definitions = ({32 children,33 label,34}: {
4 unmodified lines
39 {children}40 </dl>41);4257/** One term over its value; beside it from the shell's width. */43export const Definition = ({44 children,45 term,46}: {
5 unmodified lines
52 <dd className="text-ui min-w-0 [overflow-wrap:anywhere]">{children}</dd>53 </div>54);5571/** A titled region of a page: a heading over its content, 32 px from the next. */56export const Region = ({57 children,58 id,59 title,
12 unmodified lines
modified:apps/web/src/features/ask/markdown.ts+3 added-43 removed
1/**2 * An ask as Markdown, for agents: a harness reads an ask with one plain3 * fetch, either with `Accept: text/markdown` on the ask's own URL or at the4 * same URL with `.md`. The request decides; no user-agent list does.5 *6 * The brief is the platform's: `showAsk` renders it once, and the web only7 * serves it, with the banner that names the web's indexes under its title. A refusal is8 * set the way `git push` printed it, from `@repo/protocol/render`9 * (AGENTS.md principle 3), then its next command.10 * Pure: a `Request` or an `Exit` in, a string or a `Response` out.11 */1import { indexBanner, underTitle } from "@repo/agent-kit/host-doc";2import { Brand } from "@repo/brand";3import type { Visibility } from "@repo/protocol/annotations";4import type { ProjectName } from "@repo/protocol/ids";
2 unmodified lines
7import { Array, Cause, Exit, Option, Schema } from "effect";89const MARKDOWN = "text/markdown; charset=utf-8";1022/** A contract's `Visibility`: a `public` one's answer may be cached for a minute, a `maintainers` one's never. */11export type ContractVisibility = ReturnType<typeof Visibility.defaultValue>;1225/** One range of an `Accept` header: `text/markdown;q=0.8`. */13interface MediaRange {14 readonly quality: number;15 readonly subtype: string;16 readonly type: string;17}1832/** A q-value as RFC 9110 writes it: 0 to 1, at most three decimals; anything else is no range. */19/** A q-value as RFC 9110 writes it: 0 to 1, at most three decimals. */20const QUALITY = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;2122const rangesOf = (accept: string): readonly MediaRange[] =>23 accept.split(",").flatMap((entry) => {
9 unmodified lines
33 ? []34 : [{ quality: Number(quality), subtype, type }];35 });3650/** How closely `range` names `type/subtype`: 3 by name, 2 by `type/*`, 1 by `*\/*`, 0 not at all. */37const closeness = (range: MediaRange, type: string, subtype: string) => {38 if (range.type === type) {39 if (range.subtype === subtype) {40 return 3;
4 unmodified lines
4546 return range.type === "*" && range.subtype === "*" ? 1 : 0;47};4863/** The quality the closest range gives `type/subtype` (RFC 9110 §12.5.1), and how close it was. */49const preferenceFor = (50 ranges: readonly MediaRange[],51 type: string,52 subtype: string
11 unmodified lines
64 return best;65};6667/**83 * Whether the request asks for the ask as Markdown: it names `text/markdown`84 * itself, with a quality above zero and at least the quality it gives85 * `text/html`. A wildcard alone (`*\/*`, `text/*`, or no `Accept` at all)86 * gets the page, as a browser does.68 * A wildcard alone (`*\/*`, `text/*`, or no `Accept` at all) gets the page, as69 * a browser does.70 */71export const wantsMarkdown = (request: Request) => {72 const ranges = rangesOf(request.headers.get("accept") ?? "");73 const markdown = preferenceFor(ranges, "text", "markdown");
5 unmodified lines
79 markdown.quality >= html.quality80 );81};82100/** The longest run of backticks in `text`. */83const longestTicks = (text: string) =>84 Math.max(0, ...[...text.matchAll(/`+/gu)].map(([run]) => run.length));85104/** `text` as inline code, its delimiter longer than any backticks inside it. */86const inlineCode = (text: string) => {87 const ticks = longestTicks(text);88 const fence = "`".repeat(ticks + 1);8990 return ticks === 0 ? `${fence}${text}${fence}` : `${fence} ${text} ${fence}`;91};92112/**113 * Refusals as an agent reads them in Markdown: every refusal's `explain`114 * lines in one text block, verbatim (git's `remote:` lines, without the115 * prefix), then each distinct `next` command once, as its own paragraph.116 */93export const refusalsMarkdown = (94 refusals: Array.NonEmptyReadonlyArray<Refusal>95) => {96 const lines = explain(refusals);
19 unmodified lines
116 },117 status,118 });119144/** What a Markdown answer may be cached for, by its contract's visibility. */120const cacheFor = (visibility: ContractVisibility) =>121 visibility === "public" ? "public, max-age=60" : "private, no-store";122123const isRefusal = Schema.is(Refusal);124150/** What the web says when the platform gave neither the ask nor a refusal. */125const UNANSWERED = [126 "The platform did not answer, so the web cannot read this ask now. Ask again in a moment.",127 "",128].join("\n");129156/** Where the web's indexes are, for the banner under an ask's title. */130export interface AskIndex {131 readonly project: ProjectName;132 readonly webUrl: string;133}134162/**163 * How reading an ask ended, as the Markdown response: the brief (200,164 * cacheable as its contract's visibility allows), with the banner naming165 * `index`'s `llms.txt` files under its title; a refusal (404, its166 * Markdown, no banner); or no answer from the platform (502). Only a brief167 * is cached.168 */135export const askMarkdownResponse = <E>(136 result: Exit.Exit<{ readonly brief: string }, E>,137 visibility: ContractVisibility,138 index: AskIndex
12 unmodified lines
151 cacheFor(visibility)152 ),153 });154189/**190 * The answer to a path that can name no ask: a project's and an ask's names191 * are lowercase words joined by single dashes, so the platform is not asked.192 */155export const noAskAt = (path: string) =>156 markdown(157 [158 `No ask is at ${inlineCode(path)}: a project's and an ask's names are lowercase words joined by single dashes.`,
4 unmodified lines
163 404,164 "no-store"165 );166205/** Where an ask's Markdown lives: its page's URL with `.md`. */167export const markdownPath = (project: string, ask: string) =>168 `/${project}/asks/${ask}.md`;169209/** The `Link` header that names an ask page's Markdown as an alternate of it. */170export const markdownAlternate = (project: string, ask: string) =>171 `<${markdownPath(project, ask)}>; rel="alternate"; type="text/markdown"`;
modified:apps/web/src/features/ask/refused.tsx-20 removed
1/**2 * The page for an address that names no ask, or no answer: a 404 whose body3 * is the refusal the platform gave (`UnknownProject`, `UnknownAsk`), as4 * `git push` printed it, so a person reads what an agent reads in Markdown,5 * then the way onward: the project, when the address names one, and the6 * open asks. The refusals travel from the server in a not-found's data,7 * encoded as `Refusals`; `NoSuchAsk` decodes them where they arrive8 * (AGENTS.md principle 2).9 */1import { ProjectName } from "@repo/protocol/ids";2import { UnknownProject } from "@repo/protocol/refusal";3import type { Refusal } from "@repo/protocol/refusal";4import { Option, Schema } from "effect";
6 unmodified lines
11import { Refusals } from "../shared/refusals.ts";12import type { Crumb } from "../shared/shell/sections.ts";13import { Workspace } from "../shared/shell/workspace.tsx";1424/** What a 404 says when the address could name no ask, so no refusal came back. */15export const NAMES_ONLY =16 "Nothing is at this address: a project's and an ask's names are lowercase words joined by single dashes.";1718const LINK = "decoration-rule underline hover:decoration-current";1920const isUnknownProject = Schema.is(UnknownProject);2132/** Where to go from a page that names nothing: the project, then every open ask. */22const Onward = ({ project }: { readonly project: ProjectName | undefined }) => (23 <nav aria-label="Onward" className="text-ui flex flex-wrap gap-x-5 gap-y-1">24 {project === undefined ? null : (25 <AppLink className={LINK} to={projectPath(project)}>
12 unmodified lines
38 refusals,39 title,40}: {41 readonly nothing?: string;53 /** The project the address names, when it could be one. */42 readonly project?: ProjectName | undefined;43 readonly refusals: Array.NonEmptyReadonlyArray<Refusal> | undefined;44 readonly title: string;45}) => {58 // A project the platform says it lacks is no way onward.46 const known = refusals?.some(isUnknownProject) === true ? undefined : project;4761 // The trail goes as far as what exists: the project and its asks.48 const crumbs: readonly Crumb[] =49 known === undefined50 ? [{ label: "Asks", to: ASKS_PATH }, { label: title }]51 : [
17 unmodified lines
69const decodeRefusals = Schema.decodeUnknownOption(Refusals);7071const decodeProject = Schema.decodeUnknownOption(ProjectName);7287/**88 * A route's not-found page: the refusals its loader's not-found carried,89 * decoded; `nothing` when it carried none (the address could name no ask).90 * `project` is the address's own segment, linked only when a project could91 * have that name.92 */73export const NoSuchAsk = ({74 data,75 nothing = NAMES_ONLY,76 project,
12 unmodified lines
modified:apps/web/src/features/auth/session-slot.tsx+3 added-23 removed
1/**2 * The session, wherever the shell shows it (the rail's foot, the tablet's3 * top bar, the phone's More sheet): who is signed in, with sign-out, or a4 * link to sign in that comes back to this page. Signing in is only for5 * deciders (PRODUCT.md), so the slot stays quiet: the handle in ink, the6 * action in muted text.7 *8 * `SessionView` draws it from props; `SessionSlot` wires it to `whoAtom`9 * and the location. Sign-in is a server route, so its link is a plain10 * anchor that loads the document; the handle's page is the router's.11 */1import { useAtomValue } from "@effect/atom-react";2import type { Handle } from "@repo/protocol/ids";3import { useLocation } from "@tanstack/react-router";4import { Option } from "effect";
4 unmodified lines
9import { personPath } from "../shared/paths.ts";10import { whoAtom } from "./who.ts";1112/**24 * Where sign-in comes back to: the page the reader is on, without its25 * `#fragment`. The server never sees a fragment, so a link that carried one26 * would differ between the server's render and the browser's (`#L3`).13 * Without its `#fragment`: the server never sees one, so a link that carried it14 * would differ between the server's render and the browser's.15 */16export const hereOf = (location: {17 readonly pathname: string;18 readonly searchStr: string;19}) => `${location.pathname}${location.searchStr}`;2033/** Sign-in, coming back to `here` afterwards. */21export const signInHref = (here: string) =>22 `/auth/signin?${new URLSearchParams({ return: here }).toString()}`;2337/** The session's own action style: muted text, ink on hover. */24const ACTION =25 "text-muted-foreground hover:text-foreground text-ui inline-flex cursor-pointer items-center gap-1.5 no-underline transition-colors duration-150";2641/**42 * Where the slot sits: `rail` stacks the handle over its action in the43 * rail's foot and the More sheet; `bar` keeps both on the top bar's line.44 */27export type SessionLayout = "bar" | "rail";2829export const SessionView = ({30 handle,
22 unmodified lines
53 <p className="text-ui flex min-w-0 items-baseline gap-1">54 <span className="text-muted-foreground sr-only shrink-0">55 Signed in as56 </span>75 {/* A long handle is cut short for the line it shares; its title76 is whole. */}57 {/* A long handle is cut short; its title is whole. */}58 <AppLink59 className="decoration-rule hover:decoration-foreground max-w-[12rem] min-w-0 truncate font-medium underline-offset-4 hover:underline"60 title={signedIn}61 to={personPath(signedIn)}
26 unmodified lines
88 />89 );90};91111/** Whether someone is signed in, as far as this browser knows yet. */92export const useSignedIn = (): boolean => {93 const who = useAtomValue(whoAtom);9495 return AsyncResult.isSuccess(who) && Option.isSome(who.value);
1 unmodified line
modified:apps/web/src/features/auth/who.ts-12 removed
1/**2 * Who is signed in, as the browser learns it: the web's own `/auth/whoami`3 * (a same-origin server route that asks the platform with the session4 * cookie the page's JavaScript cannot read). It runs in the browser only:5 * on the server the slot renders as signed out, the page's first paint, and6 * the browser fills it in.7 *8 * Not a contract, so not an atom over `ContractsClient` (`src/surfaces.ts`):9 * the session is the web's, not the platform's.10 */1import { Handle } from "@repo/protocol/ids";2import { Effect, Option, Schema } from "effect";3import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";4import { Atom } from "effect/reactivity";516/** `/auth/whoami`'s answer: the handle signed in, or nothing. */6const Who = Schema.Struct({ handle: Schema.optionalKey(Handle) });719/** The handle signed in in this browser, once known; signed out on the server and on any failure. */8export const whoAtom = Atom.make(9 HttpClient.get("/auth/whoami").pipe(10 Effect.flatMap(HttpClientResponse.schemaBodyJson(Who)),11 Effect.map(({ handle }) => Option.fromUndefinedOr(handle)),
4 unmodified lines
modified:apps/web/src/features/code/address.ts+1 added-14 removed
1/**2 * A code page's address, decoded where it arrives (AGENTS.md principle 2):3 * the project's name, the revision's segment (`rev.ts`) and the repo path4 * after it. Each is none when the address cannot name one, which a page5 * answers with a 404 before it asks the platform anything.6 */1import { NoneOrMore } from "@repo/protocol/domain/common";2import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";3import { Option, Schema } from "effect";4
6 unmodified lines
11const decodeSha = Schema.decodeUnknownOption(CommitSha);1213export const projectOf = (segment: string) => decodeProject(segment);1421/** A revision's segment, decoded; none for one that names no revision. */15export const revisionOf = (segment: string) => revOf(segment);1624/** A repo path from the address's rest (a trailing slash dropped); none for the root. */17export const repoPathOf = (rest: string | undefined) =>18 rest === undefined || rest === ""19 ? Option.none()20 : decodePath(rest.replace(/\/+$/u, ""));2130/** A commit's id from the address. */22export const commitOf = (segment: string) => decodeSha(segment);2333/**34 * Where a page of a list starts, from its search parameter: the router35 * reads `?from=30` as the number 30; anything but a whole number from 0 is36 * none.37 */24/** The router reads `?from=30` as the number 30. */25export const offsetOf = Schema.decodeUnknownOption(NoneOrMore);
modified:apps/web/src/features/code/blob-view.tsx-21 removed
1/**2 * One file of a project at a revision, in Code mode (its Why mode is3 * `why/why-view.tsx`, the same page). The file header stays under the4 * context bar: the path once, the file in words, Code | Why, Raw,5 * Permalink (`y`) and Copy. The code takes the pane's whole width and6 * scrolls sideways inside itself, never wrapping: the server sends it7 * highlighted where it highlights its language and size (`ServerCode`,8 * ADR 0027), else as numbered, anchored plain text (`NumberedLines`), and9 * the browser's drawing (`code`, from `client-code.tsx`) replaces it in10 * place.11 *12 * A Markdown file is rendered (its source on `?plain=1`), an image is shown13 * from raw, and a binary file or one past the read cap says its size and14 * links its bytes. The inspector holds "This file".15 */1import type { CommitView, FileView } from "@repo/protocol/domain/code";2import type { ProjectName } from "@repo/protocol/ids";3import type { DateTime } from "effect";4import type { ReactNode } from "react";
13 unmodified lines
18} from "./paths.ts";1920const LINK = "decoration-rule underline hover:decoration-current";2137/** What the server shows of a file that has no text to number. */22const Bytes = ({23 file,24 project,25 words,
11 unmodified lines
37 </p>38 </div>39);4057/** The file's body: an image, Markdown, numbered text, or its size. */41const Body = ({42 code,43 file,44 plain,
66 unmodified lines
111export interface BlobViewProps {112 readonly file: FileView;113 readonly project: ProjectName;114 readonly rev: string;132 /** The browser's drawing of the text, holding `NumberedLines` as its fallback. */115 readonly code?: ReactNode;134 /** `?plain=1`: a Markdown file's source, not its rendering. */116 readonly plain?: boolean;136 /** The commit that last changed the file. */117 readonly last?: CommitView | undefined;118 readonly now: DateTime.Utc;139 /** The Files button, below the shell's width. */119 readonly files?: ReactNode;120}121122export const BlobView = ({
42 unmodified lines
modified:apps/web/src/features/code/client-code.tsx+10 added-27 removed
1/**2 * A file and a commit's diff, drawn in the browser over what the server3 * sent. The server renders `fallback`: the code it highlighted4 * (`ServerCode`), or numbered lines or the plain-text diff for code it5 * does not highlight. After hydration the browser loads the drawing,6 * starts the worker pool and highlights the code there first7 * (`prepareFile`, `prepareDiffs`); only then does the drawing take the8 * fallback's place, in one render, drawing the highlighted code at once.9 * So code the server highlighted never visibly changes, and plain code10 * changes once, to highlighted.11 *12 * The fallback stays where it is until then (no `ClientOnly`, whose13 * switch would mount a second copy of it without the server's drawing).14 * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic15 * imports below are dead code there and the Worker bundles none of the16 * drawings (`bytes:check`), as `features/finish/client-diff.tsx` does.2 * The drawing takes the fallback's place only once its code is highlighted, so3 * code the server highlighted never visibly changes (no `ClientOnly`, whose4 * switch would mount a second copy of the fallback). `import.meta.env.SSR` is5 * `true` in the Worker's build, so the dynamic imports below are dead code6 * there and the Worker bundles none of the drawings.7 */8import { Effect, Fiber } from "effect";9import { Suspense, useEffect, useRef, useState } from "react";10import type { ComponentType, ReactNode } from "react";1122// Type-only imports are erased, so the server bundles nothing of these.12import type { FileCodeProps } from "./code-view.tsx";13import type { DiffCodeProps } from "./diff-view.tsx";1426/** The file's drawing, once its module is loaded and the file highlighted in the pool; none on the server. */15const fileDrawing = import.meta.env.SSR16 ? undefined17 : (file: FileCodeProps) =>18 Effect.gen(function* () {
5 unmodified lines
2425 return FileCode;26 });2740/** The diff's drawing, once its module is loaded and its first files highlighted; none on the server. */28const diffDrawing = import.meta.env.SSR29 ? undefined30 : (files: Pick<DiffCodeProps, "drawn" | "files">) =>31 Effect.gen(function* () {
5 unmodified lines
3738 return DiffCode;39 });4054/** A drawing, held in state: a component is a function, which state would call. */41/**42 * A drawing, held in state: a component is a function, which state would call.43 */44interface Ready<P> {45 readonly Draw: ComponentType<P>;46}4759/**60 * Runs `ready` (load the drawing, prepare what it draws) and hands its61 * drawing to `done`; the returned function stops it, so a page left in62 * the meantime is not drawn. A drawing that cannot load leaves the63 * fallback in place.64 */48const start = <P, E>(49 ready: Effect.Effect<ComponentType<P>, E>,50 done: (ready: Ready<P>) => void51) => {
40 unmodified lines
92export const ClientDiffs = ({93 fallback,94 ...props95}: DiffCodeProps & { readonly fallback: ReactNode }) => {113 // The files as they first came: the drawing, once ready, follows any114 // change itself, so preparing is done once.96 // The drawing, once ready, follows any change itself, so preparing is done97 // once.98 const first = useRef({ drawn: props.drawn, files: props.files });99 const [ready, setReady] = useState<Ready<DiffCodeProps>>();100101 useEffect(
15 unmodified lines
modified:apps/web/src/features/code/client-tree.tsx-6 removed
1/**2 * The project's file tree, drawn in the browser only (`repo-tree.tsx`,3 * `@pierre/trees`), in the rail's slot or the Files sheet. The server4 * renders `fallback` (nothing), and the browser loads the tree after5 * hydration; the Worker bundles none of it, as `client-code.tsx` explains.6 */1import { ClientOnly } from "@tanstack/react-router";2import { lazy, Suspense } from "react";3import type { ReactNode } from "react";4
19 unmodified lines
modified:apps/web/src/features/code/code-view.tsx+2 added-28 removed
1/**2 * One file, drawn by `@pierre/diffs`: highlighted (Shiki's JavaScript3 * engine, never its WASM one), its lines selectable, the selection kept in4 * the address as `#L10` or `#L10-L20` (`line-hash.ts`) and scrolled to on5 * load. Its lines live in a shadow root, where a native `#L` fragment6 * cannot reach, so the drawing scrolls to the anchored line itself.7 *8 * It is Pierre's `File`, not its virtualized `CodeView`: a file is capped9 * at 1 MiB, it flows in the page's own scroll under the file header (so it10 * draws no header of its own), and past the shared limits (`pierre.ts`) it is11 * drawn without highlighting. Highlighting runs in the worker pool.12 *13 * The library and Shiki's grammars are megabytes, so only the browser14 * loads this module (`client-code.tsx`); the Worker never bundles it.2 * Its lines live in a shadow root, where a native `#L` fragment cannot reach,3 * so the drawing scrolls to the anchored line itself.4 */5import { File } from "@pierre/diffs/react";6import type { FileOptions, SelectedLineRange } from "@pierre/diffs/react";7import { Effect, Option } from "effect";
8 unmodified lines
16registerCodeTheme();1718export interface FileCodeProps {19 readonly path: string;31 /** The blob's id: the drawing's cache key. */20 readonly sha: string;21 readonly text: string;22}2336/** The lines the address names now, if any. */24const fromAddress = (): LineRange | null =>25 Option.getOrNull(parseLineHash(globalThis.location.hash));2640/** The drawing once it has rendered, and the line to bring into view in it. */27interface Pending {28 line?: number | undefined;29 node?: HTMLElement;30}3146/**47 * Scrolls the drawing to the pending line, once: the line clears when it48 * is found, so later renders leave the reader where they are.49 */32const reveal = (pending: Pending) => {33 const { line, node } = pending;3435 const row =
1 unmodified line
37 ? null38 : node?.shadowRoot?.querySelector(`[data-line="${line}"]`);3940 if (row instanceof HTMLElement) {59 // Whichever scrolls the code (main from the shell's width, the page60 // below it) brings the line to its middle, and only up or down: the61 // code's own sideways scroll stays where it is.41 row.scrollIntoView({ block: "center", inline: "nearest" });42 pending.line = undefined;43 }44};
62 unmodified lines
107 </CodePool>108 );109};110132/**133 * Ready to draw `file` highlighted at once: the pool up, and the file134 * highlighted in it, keyed as `FileCode` draws it. Settles either way; a135 * file the pool could not highlight is drawn as it would have been.136 */111export const prepareFile = (file: FileCodeProps) =>112 Effect.tryPromise(() => poolReady()).pipe(113 Effect.andThen(Effect.tryPromise(() => warmFile(file))),114 Effect.ignore
4 unmodified lines
modified:apps/web/src/features/code/commit-view.tsx+2 added-34 removed
1/**2 * One commit, read as a landing first and a diff second. The head: the3 * subject, the landing's status line ("Landed as 9b1c3e5 · answered4 * format-ordinal", the SHA and the ask linked), the body as prose, and5 * git's own metadata on one muted line. The inspector holds the typed6 * facts: this landing's state, its credit (the trailers, once), the diff's7 * stats split by path, and its provenance. Then the diff, file by file, in8 * a pane of its own: the server's plain text (`PlainDiff`), which the9 * browser's drawing (`drawing`, from `client-code.tsx`) replaces in place.10 *11 * A commit the platform did not land came in with the history the project12 * adopted, and says so; its trailers are listed as written, linking no one.13 */1import type {2 CommitDiff,3 CommitView as Commit,4} from "@repo/protocol/domain/code";
22 unmodified lines
27import { ChangeCounts, PlainDiff } from "./plain-diff.tsx";2829const LINK = "decoration-rule underline hover:decoration-current";3044/** A trailer line: `Key: value`, the key one word of letters and dashes. */31const TRAILER = /^[A-Za-z][\w-]*:\s/u;3233/**48 * The body without its trailers, which the Credit block shows: git's49 * trailer block is the last paragraph when every line of it is a50 * `Key: value`.34 * Git's trailer block is the last paragraph when every line of it is a `Key:35 * value`.36 */37export const bodyWithoutTrailers = (commit: Commit) => {38 const paragraphs = commit.body.trim().split(/\n\s*\n/u);39 const last = paragraphs.at(-1) ?? "";
4 unmodified lines
4445 return (trailers ? paragraphs.slice(0, -1) : paragraphs).join("\n\n").trim();46};4763/** Where the commit stands, in one line: landed as its SHA, and the ask it answered or opened. */48export const LandingStatus = ({49 commit,50 project,51}: {
45 unmodified lines
97 </p>98 );99};100117/** Git's own metadata, on one line: who wrote it, who committed it, its parents. */101const GitLine = ({102 commit,103 now,104 project,
51 unmodified lines
156 territory: "territory",157 tests: "tests",158} as const;159177/** The diff in numbers: files, lines added and removed, then split by path. */160export const DiffStatsFacts = ({ stats }: { readonly stats: DiffStats }) => (161 <FactBlock label="Diff stats">162 <p163 className="text-ui flex flex-wrap items-center gap-x-3 gap-y-1"
26 unmodified lines
190 )}191 </FactBlock>192);193212/** The trailers of a commit the platform did not land, as written, linking no one. */194const WrittenTrailers = ({ commit }: { readonly commit: Commit }) =>195 commit.trailers.length === 0 ? null : (196 <FactBlock label="Trailers">197 <ul className="text-mono leading-terminal flex flex-col gap-1 font-mono">
5 unmodified lines
203 </ul>204 </FactBlock>205 );206226/** A landing's credit from the record; a commit the platform did not land, its trailers as written. */207const LandingCredit = ({ commit }: { readonly commit: Commit }) =>208 commit.landing === undefined ? (209 <WrittenTrailers commit={commit} />210 ) : (
3 unmodified lines
214 heldBack={commit.landing.heldBackTrailer}215 />216 );217238/** Where the commit comes from: its id, its tree, its people and parents, and the landing's request. */218const provenanceOf = (commit: Commit): readonly ProvenanceEntry[] => [219 { label: "Commit", value: commit.sha },220 { label: "Tree", value: commit.tree },221 { label: "Author", value: `${commit.author.name} <${commit.author.email}>` },
12 unmodified lines
234 ? []235 : [{ label: "Request-Id", value: commit.landing.requestId }]),236];237259/** The inspector's facts for a commit. */238const CommitFacts = ({239 commit,240 project,241 stats,
31 unmodified lines
273 </>274 );275};276299/** A segmented pair of buttons, the pressed one in ink. */277const SEGMENT =278 "text-ui hover:bg-surface aria-pressed:bg-foreground aria-pressed:text-background aria-pressed:hover:bg-foreground flex h-7 cursor-pointer items-center gap-1.5 px-2.5 font-medium transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:size-3.5";279303/** The diff's toolbar: unified or split, fold or unfold every file, and the counts. */280export const DiffToolbar = ({281 allFolded,282 files,283 onFoldAll,
2 unmodified lines
286 stats,287}: {288 readonly split: boolean;289 readonly onSplit?: ((split: boolean) => void) | undefined;314 /** Whether every file is folded now. */290 readonly allFolded: boolean;291 readonly onFoldAll?: ((folded: boolean) => void) | undefined;292 readonly stats: DiffStats;318 /** The Files button, below the shell's width. */293 readonly files?: ReactNode;294}) => (295 <>296 {files === undefined ? null : (
43 unmodified lines
340export interface CommitViewProps {341 readonly diff: CommitDiff;342 readonly now: DateTime.Utc;343 readonly project: ProjectName;370 /** The ask's territory, when the commit landed an answer: the stats split by it. */344 readonly territory?: readonly string[] | undefined;372 /** Old and new side by side. */345 readonly split?: boolean;346 readonly onSplit?: ((split: boolean) => void) | undefined;375 /** The files folded now; each file's default when absent. */347 readonly folded?: ReadonlySet<string> | undefined;348 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;349 readonly onFoldAll?: ((folded: boolean) => void) | undefined;379 /** The browser's drawing of the diff, holding `PlainDiff` as its fallback. */350 readonly drawing?: ReactNode;381 /** The Files button, below the shell's width. */351 readonly files?: ReactNode;383 /** The diff's files already parsed (`drawnFiles`), so a page parses each once. */352 readonly drawn?: readonly DrawnFile[] | undefined;353}354355export const CommitView = ({
94 unmodified lines
modified:apps/web/src/features/code/copy.tsx-4 removed
1/**2 * A button that copies `text` and says so for two seconds, as the command3 * lines do (`shared/command.tsx`).4 */1import { Effect } from "effect";2import { Check, Copy } from "lucide-react";3import { useState } from "react";4
38 unmodified lines
modified:apps/web/src/features/code/diff-model.ts+3 added-50 removed
1/**2 * A commit's changed files as the diff draws them, worked out once by the3 * same parser the drawing uses (`@pierre/diffs`' `parseDiffFromFile`), so4 * the server's plain-text diff and the highlighted one the browser draws5 * over it hold the same hunks, line for line: the swap moves nothing.6 *7 * Also here: each file's `+n −m`, which files start folded (an added or8 * deleted file past `LONG_FILE` lines), the order a tree lists paths in,9 * and a commit's stats split by path (the ask's territory, its tests, the10 * rest), counted by rule, never by a model.11 *12 * No React and no DOM: the server's render and the browser's both read it.2 * Parsed by the same parser the drawing uses, so the server's plain-text diff3 * and the browser's highlighted one hold the same hunks, line for line. No4 * React and no DOM: both renders read it.5 */6import { parseDiffFromFile } from "@pierre/diffs";7import type { FileDiffMetadata } from "@pierre/diffs";8import type { ChangedFile } from "@repo/protocol/domain/code";9import { Option } from "effect";1019/** Past this many lines an added or deleted file starts folded. */11export const LONG_FILE = 80;1222/** A file's diff, parsed from both its texts; none for a binary or unsent file. */13export const fileDiffOf = (14 file: ChangedFile15): Option.Option<FileDiffMetadata> => {16 if (
20 unmodified lines
3738 return Option.some(diff);39};4051/** Each kind of change as the drawing names it. */41const CHANGE_TYPES = {42 added: "new",43 deleted: "deleted",44 modified: "change",45} as const satisfies Record<ChangedFile["status"], FileDiffMetadata["type"]>;4658/** A diff with no lines: a header alone, for a file whose lines are not shown. */47export const emptyDiffOf = (file: ChangedFile): FileDiffMetadata => ({48 additionLines: [],49 cacheKey: `diff:${file.before ?? "none"}:${file.after ?? "none"}`,50 deletionLines: [],
4 unmodified lines
55 type: CHANGE_TYPES[file.status],56 unifiedLineCount: 0,57});5871/** Lines a file's diff adds and removes. */59export interface Counts {60 readonly additions: number;61 readonly deletions: number;62}6364const NONE: Counts = { additions: 0, deletions: 0 };6579/** What `diff` adds and removes, line by line. */66export const countsOf = (diff: Option.Option<FileDiffMetadata>): Counts => {67 if (Option.isNone(diff)) {68 return NONE;69 }
8 unmodified lines
7879 return { additions, deletions };80};8196/** A changed file with its parsed diff and counts. */82export interface DrawnFile {83 readonly file: ChangedFile;84 readonly diff: Option.Option<FileDiffMetadata>;85 readonly counts: Counts;101 /** Whether it starts folded: added or deleted, past `LONG_FILE` lines. */86 readonly folded: boolean;87}88105/**106 * The order a file tree lists paths in: segment by segment, a folder107 * before a file at the same level, then by name.108 */89export const treeOrder = (left: string, right: string) => {90 const a = left.split("/");91 const b = right.split("/");92
15 unmodified lines
108109 return a.length - b.length;110};111132/** `files` in tree order, each parsed and counted. */112export const drawnFiles = (113 files: readonly ChangedFile[]114): readonly DrawnFile[] =>115 files
11 unmodified lines
127 counts.additions + counts.deletions > LONG_FILE,128 };129 });130152/** A test file, by its path: a test folder, or a `.test.` or `.spec.` name. */131export const isTestPath = (path: string) =>132 /(?:^|\/)(?:tests?|__tests__|spec)\//u.test(path) ||133 /\.(?:test|spec)\.[^/]+$/u.test(path);134157/** A territory glob (`src/format/**`, `src/*.ts`) as a test on a path. */135export const globTest = (glob: string): ((path: string) => boolean) => {136 const pattern = glob137 .replaceAll(/[.+^${}()|[\]\\]/gu, "\\$&")138 .replaceAll("**/", "\u0000")
2 unmodified lines
141 .replaceAll("?", "[^/]")142 .replaceAll("\u0000", "(?:.*/)?")143 .replaceAll("\u0001", ".*");144168 // A folder named without a pattern covers what is inside it.145 const whole = new RegExp(`^${pattern}(?:/.*)?$`, "u");146147 return (path) => whole.test(path);148};149174/** One part of a commit's stats: what its paths add and remove. */150export interface StatsPart extends Counts {151 readonly label: "other" | "territory" | "tests";152 readonly files: number;153}154180/** A commit's stats: files, lines added and removed, and the parts by path. */155export interface DiffStats extends Counts {156 readonly files: number;157 readonly parts: readonly StatsPart[];158}159186/**187 * The stats of `files`. With the ask's territory, a path it covers is the188 * territory's, a test file the tests', anything else the rest; without189 * one, a test file is the tests' and the rest is the rest. Empty parts are190 * left out.191 */160export const statsOf = (161 files: readonly DrawnFile[],162 territory: readonly string[] = []163): DiffStats => {
37 unmodified lines
201 parts,202 };203};204237/** One row of a plain diff, as unified or split draws it. */205export type PlainRow =206 | { readonly kind: "separator"; readonly lines: number }207 | {208 readonly kind: "context" | "addition" | "deletion";209 readonly number: number;210 readonly text: string;211 };212246/** A line as the diff stores it, without its line ending. */213const bare = (line: string | undefined) => (line ?? "").replace(/\r?\n$/u, "");214249/**250 * `diff` as unified rows: before each hunk the unchanged lines it skips251 * as one separator, then its lines (deletions before additions in a252 * change, each numbered on its own side), and after the last hunk the253 * unchanged lines left.254 */215export const unifiedRows = (diff: FileDiffMetadata): readonly PlainRow[] => {216 const rows: PlainRow[] = [];217 let lastAddition = 0;218
47 unmodified lines
266267 return rows;268};269310/** One numbered line of a plain diff. */270type Line = Extract<PlainRow, { readonly number: number }>;271313/** One row of a split diff: the old side and the new, either empty. */272export type SplitRow =273 | { readonly kind: "separator"; readonly lines: number }274 | {275 readonly kind: "pair";276 readonly left?: Line;277 readonly right?: Line;278 };279322/**323 * `diff` as split rows: a context line on both sides, and in a change the324 * deletions beside the additions, row for row, the longer side's rest325 * against nothing.326 */280export const splitRows = (diff: FileDiffMetadata): readonly SplitRow[] => {281 const rows: SplitRow[] = [];282 let lastAddition = 0;283
66 unmodified lines
modified:apps/web/src/features/code/diff-pane.tsx+3 added-21 removed
1/**2 * Where a commit's diff scrolls: a box the height of the screen below the3 * bars, which sticks under the toolbar once the page head has scrolled4 * away. The diff scrolls inside it (Pierre's `CodeView` needs a scroller5 * of its own to draw only what is in view), and its file headers stick at6 * its top.7 *8 * Until the box has reached the toolbar, the box does not scroll: a wheel9 * or a swipe over the diff moves the page instead, so the head scrolls10 * away first and nothing traps the reader. Once stuck, it scrolls; at its11 * top a further scroll up moves the page back. Without script it always12 * scrolls.2 * Until the box has stuck under the toolbar it does not scroll, so a wheel over3 * the diff moves the page and the head scrolls away first; once stuck it4 * scrolls (Pierre's `CodeView` needs a scroller of its own).5 */6import { useEffect, useRef, useState } from "react";7import type { ReactNode } from "react";817/** The box's place: under the toolbar, as tall as the screen below it (and above a phone's bottom bar). */9const PANE =10 "group/pane sticky top-[5.1875rem] h-[calc(100dvh-5.1875rem-3.5rem-env(safe-area-inset-bottom))] scroll-mt-[5.1875rem] tablet:top-[5.4375rem] tablet:h-[calc(100dvh-5.4375rem)] tablet:scroll-mt-[5.4375rem] shell:top-[5.1875rem] shell:h-[calc(100dvh-5.1875rem)] shell:scroll-mt-[5.1875rem] -mt-6 -mb-16 flex min-h-0 flex-col";1121/** What a scroller inside the box puts on itself: all the box's height, scrolling only once the box is stuck. */12export const PANE_SCROLLER =13 "min-h-0 flex-1 overflow-auto overscroll-y-auto group-data-[stuck=false]/pane:overflow-y-hidden";1425/** Pixels from a computed length (`83px`); nothing, none. */15const pixels = (length: string) => Number(/^-?[\d.]+/u.exec(length)?.[0] ?? 0);1628/**29 * Follow whether `box` has reached its sticky place, read on every scroll30 * (of main, or of the page below the shell's width), telling `stuck`; the31 * returned function stops.32 */17const followStuck = (box: HTMLElement, stuck: (now: boolean) => void) => {18 let frame = 0;1920 const read = () => {
23 unmodified lines
44 globalThis.removeEventListener("resize", onScroll);45 };46};4764/** Whether the box has reached its sticky place; none before the page runs. */48const useStuck = () => {49 const pane = useRef<HTMLDivElement>(null);50 const [stuck, setStuck] = useState<boolean>();51
10 unmodified lines
62 children,63 id,64}: {65 readonly children: ReactNode;83 /** Its anchor, for a link to the diff from the page's head. */66 readonly id?: string;67}) => {68 const { pane, stuck } = useStuck();69
13 unmodified lines
modified:apps/web/src/features/code/diff-view.tsx+3 added-55 removed
1/**2 * A set of changed files drawn by Pierre's `CodeView`: one scroller that3 * draws only the files in view, each file's header sticky at its top4 * (with a hairline only while it is stuck), unchanged runs folded into5 * "N unmodified lines" bars, changed words marked inside changed lines,6 * and highlighting done in the worker pool (`pool.tsx`). It sits in a7 * `DiffPane`, over the server's `PlainDiff` (the same hunks, the same8 * measures), which it replaces in place.9 *10 * Unified diffs mark each line `+` or `-`, so a change reads without11 * colour; split diffs mark the side with a bar. Each header has a chevron12 * that folds the file; an added or deleted file past 80 lines starts13 * folded. Lines can be selected, and the selection is kept in the address14 * (`#diff-<path>:L4-L7`); an address naming a file (the tree, `J`/`K`)15 * scrolls to its header.16 *17 * What a page adds, so the finish and waiver pages draw with it unedited:18 * `annotations` (a row under a line, on one side), and per file a header19 * slot (`slots[].header`, a "Mark read" button) and a status (`read`20 * marks the header with a check, `refused` with the refused cross).21 *22 * Only the browser loads this module (`client-code.tsx`).23 */1import type { CodeViewItem, DiffLineAnnotation } from "@pierre/diffs";2import { CodeView } from "@pierre/diffs/react";3import type { CodeViewHandle, CodeViewReactOptions } from "@pierre/diffs/react";4import type { ChangedFile } from "@repo/protocol/domain/code";
12 unmodified lines
17import { SERVER_FILES } from "./prerender.ts";1819registerCodeTheme();2044/** A row a page draws under one line of one file's diff, on one side. */21export interface DiffAnnotation {22 readonly path: string;23 readonly line: number;24 readonly side: "additions" | "deletions";25 readonly render: () => ReactNode;26}2752/** What a page adds to one file's header: a control, and the file's status. */28export interface DiffFileSlot {29 readonly path: string;30 readonly header?: ReactNode;31 readonly status?: "read" | "refused";
3 unmodified lines
35 readonly files: readonly ChangedFile[];36 readonly split: boolean;37 readonly annotations?: readonly DiffAnnotation[];38 readonly slots?: readonly DiffFileSlot[];64 /** The files folded now; each file's own default when absent. */39 readonly folded?: ReadonlySet<string> | undefined;66 /** A header's fold was pressed. */40 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;68 /**69 * The files already parsed, in the order to draw them: a decision's diff70 * comes as a patch, with no whole texts to parse `files` from.71 */41 readonly drawn?: readonly DrawnFile[] | undefined;42}4375/**76 * The header's hairline, only while it is stuck at the top (where the77 * browser can tell); a plain one where it cannot. Each header also carries78 * a hairline above it, parting one file from the next.79 */44const HEADER_CSS = `45[data-diffs-header] { box-shadow: inset 0 1px var(--rule); container-type: scroll-state; }46[data-diffs-header]::after { content: ""; position: absolute; inset-inline: 0; bottom: 0; height: 1px; background: transparent; }47@container scroll-state(stuck: top) { [data-diffs-header]::after { background: var(--rule); } }
3 unmodified lines
51const NO_ANNOTATIONS: readonly DiffAnnotation[] = [];5253const NO_SLOTS: readonly DiffFileSlot[] = [];5491/**92 * An item's version: it changes whenever what the item draws does (folded93 * or not, the lines its annotations sit on), so `CodeView` draws it again.94 */55/** Changes whenever what the item draws does, so `CodeView` draws it again. */56const versionOf = (57 folded: boolean,58 annotations: readonly DiffLineAnnotation<DiffAnnotation>[]59) => {
7 unmodified lines
6768 return hash * 2 + annotations.length;69};70110/** One file as `CodeView` holds it; a binary or unsent file as a header with no lines. */71const itemOf = (72 drawn: DrawnFile,73 folded: boolean,74 annotations: readonly DiffAnnotation[]
19 unmodified lines
94 version: versionOf(folded, mine),95 };96};97138/** The address's fragment, handed up as it changes; only inside a router. */98const HashFollower = ({99 onHash,100}: {101 readonly onHash: (hash: string) => void;
6 unmodified lines
108109 return null;110};111153/** Scroll the pane into place, then the file's header to its top. */112const reveal = (113 handle: CodeViewHandle<DiffAnnotation, undefined> | null,114 container: HTMLElement | null,115 path: string
36 unmodified lines
152 );153154 const slotOf = (path: string) => slots.find((slot) => slot.path === path);155198 // The folds as they are now, read when the address moves: a fold the199 // reader makes later must neither unfold the named file again nor200 // scroll back to it.156 // Read when the address moves: a fold made later must neither unfold the157 // named file again nor scroll back to it.158 const folds = useRef({ folded, onFold });159160 useEffect(() => {161 folds.current = { folded, onFold };162 });163207 // An address naming a file scrolls to it, and its lines are selected.164 useEffect(() => {165 const named = parseDiffHash(hash);166167 if (Option.isNone(named) || !byPath.has(named.value.path)) {
36 unmodified lines
204 }),205 [split]206 );207252 // A view drawn with no router around it (its own test) follows no address.208 const router = useRouter({ warn: false });209210 return (211 <CodePool>
28 unmodified lines
240 const file = byPath.get(item.id);241 const slot = slotOf(item.id);242243 return (289 // Pierre prints the counts itself; what it cannot say is here.244 <span className="flex items-center gap-3 font-sans">245 {file === undefined || Option.isSome(file.diff) ? null : (246 <span className="text-muted-foreground">247 {file.file.binary ? "binary" : "not shown"}
56 unmodified lines
304 </CodePool>305 );306};307354/**355 * Ready to draw the first files of a diff highlighted at once: the pool356 * up, and the files a reader sees first (those the server may have sent357 * highlighted) highlighted in it, keyed as `DiffCode` draws them. The rest358 * are highlighted as they scroll into view. Settles either way.359 */308export const prepareDiffs = ({309 drawn,310 files,311}: Pick<DiffCodeProps, "drawn" | "files">) =>
21 unmodified lines
modified:apps/web/src/features/code/file-facts.tsx-8 removed
1/**2 * The inspector's "This file": the path, the file in words (lines, size,3 * language), the landing that last touched it (ask and answer first, the4 * commit second), and where to take it: raw, a permalink, a copy, its5 * history. A file's page and its why page show the same block.6 */1import type { CommitView, FileView } from "@repo/protocol/domain/code";2import type { ProjectName } from "@repo/protocol/ids";3import { Option } from "effect";4import type { DateTime } from "effect";
15 unmodified lines
20 project,21 rev,22}: {23 readonly file: FileView;30 /** Which page shows the block: its permalink keeps the reader there. */24 readonly mode?: "code" | "why";32 /** The commit that last changed the file, with its landing; none when the read found none. */25 readonly last?: CommitView | undefined;26 readonly now: DateTime.Utc;27 readonly project: ProjectName;28 readonly rev: string;
57 unmodified lines
modified:apps/web/src/features/code/file-header.tsx+1 added-31 removed
1/**2 * The code pages' file header: the toolbar that stays under the context3 * bar while the code scrolls. Left to right: the Files button (below the4 * shell's width, where the tree is not in a rail), the path as a trail of5 * links with a button that copies it, the file's size in words ("12 lines6 * · 493 bytes · TypeScript"), the Code | Why toggle (one page, two modes,7 * each its own address), then Raw, Permalink (`y`) and Copy.8 *9 * Also here: the `y` key, which rewrites the address to the page at its10 * commit, and the words a file's facts are said in.11 */1import type { FileView } from "@repo/protocol/domain/code";2import type { ProjectName } from "@repo/protocol/ids";3import { Check, Copy, Link2 } from "lucide-react";4import { Fragment, useEffect } from "react";
14 unmodified lines
19 treeHref,20 whyHref,21} from "./paths.ts";2234/** A text's lines, without the empty one after its last newline. */23export const linesOf = (text: string): readonly string[] => {24 const lines = text.split("\n");2526 return lines.at(-1) === "" ? lines.slice(0, -1) : lines;27};2841/** The language a file is written in, by its name; none for one this list does not know. */29const LANGUAGES: readonly (readonly [RegExp, string])[] = [30 [/\.(?:c|m)?tsx?$/u, "TypeScript"],31 [/\.(?:c|m)?jsx?$/u, "JavaScript"],32 [/\.json$/u, "JSON"],
18 unmodified lines
5152export const languageOf = (path: string) =>53 LANGUAGES.find(([pattern]) => pattern.test(path))?.[1];5468/** A file in words: its lines, its size, its language. */55export const fileWords = (file: FileView): readonly string[] => [56 ...(file.text === undefined57 ? []58 : [
5 unmodified lines
64 ...(file.binary ? ["binary"] : []),65 ...(languageOf(file.path) === undefined ? [] : [languageOf(file.path) ?? ""]),66];6782/**83 * Whether `press` asks for the permalink: `y`, with no modifier, outside a84 * field, and only while the single keys are on (the switch in the keys85 * dialog turns this one off too).86 */68export const permalinkPress = (press: KeyPress, on: boolean) =>69 on &&70 press.key === "y" &&71 !press.inField &&72 !press.altKey &&73 !press.ctrlKey &&74 !press.metaKey;7595/** `y` rewrites the address to the page at its commit, keeping the line anchor. */76export const PermalinkKey = ({ href }: { readonly href: string }) => {77 const on = useKeys()?.on ?? true;7879 useEffect(() => {
37 unmodified lines
117118const CRUMB =119 "text-muted-foreground hover:text-foreground min-w-0 truncate no-underline transition-colors duration-[120ms]";120141/** A button that copies `text` with only its mark showing; its name says what it copies. */121const CopyMark = ({122 label,123 text,124}: {
20 unmodified lines
145 </button>146 );147};148170/** The path as links: the project, each folder at `rev`, then the name itself. */149export const PathTrail = ({150 path,151 project,152 rev,
11 unmodified lines
164 className="flex min-w-0 items-center gap-1"165 data-slot="breadcrumb"166 >167 <ol className="text-mono flex min-w-0 items-center gap-1 font-mono">190 {/* On a phone the toolbar has room for the name alone: the folders191 above it are the Files sheet's. */}168 {/* On a phone the toolbar has room for the name alone. */}169 <li170 className={`${here === undefined ? "flex" : "tablet:flex hidden"} min-w-0 shrink-0 items-center`}171 >172 {here === undefined ? (
53 unmodified lines
226227const SEGMENT =228 "text-ui hover:bg-surface aria-[current]:bg-foreground aria-[current]:text-background aria-[current]:hover:bg-foreground flex h-7 items-center px-2.5 font-medium no-underline transition-colors duration-150";229253/** Code | Why: the file, or why each of its lines is there; one page, two addresses. */230export const ModeToggle = ({231 mode,232 path,233 project,
27 unmodified lines
261 size: "sm",262 variant: "ghost",263});264289/** The file header, as the page's toolbar. */265export const FileHeader = ({266 file,267 files,268 mode,
2 unmodified lines
271 rev,272}: {273 readonly project: ProjectName;274 readonly rev: string;300 /** The folder or file the page is about; the root when absent. */275 readonly path?: string | undefined;302 /** Code or Why, on a file's page; nothing on a folder's. */276 readonly mode?: "code" | "why";304 /** The file, read: its size in words, its bytes and its text to copy. */277 readonly file?: FileView;306 /** The Files button, below the shell's width. */278 readonly files?: ReactNode;279}) => (280 <>281 {files === undefined ? null : (
1 unmodified line
283 )}284 <div className="flex min-w-0 flex-1 items-center gap-3">285 <PathTrail path={path} project={project} rev={rev} />286 {file === undefined ? null : (316 // From 1440 px the inspector says the same, beside the path.287 <p className="text-ui text-muted-foreground diffsplit:block codefacts:hidden hidden min-w-0 truncate tabular-nums">288 {fileWords(file).join(" · ")}289 </p>290 )}
32 unmodified lines
modified:apps/web/src/features/code/file-keys.ts+2 added-10 removed
1/**2 * `J` and `K` on the code pages: the next or the previous file, from the3 * one the page shows, in the tree's order (a file's page and its why page4 * move to the next file's; a commit's page scrolls its diff to the next5 * file's header). The keys mean what the shell's keys dialog says6 * (`intentOf`), and the switch that turns the single keys off turns these7 * off too. No key acts while focus is in a field or the tree's filter.8 */1import { useEffect, useRef } from "react";23import { inField, intentOf, useKeys } from "../shared/keys.tsx";413/** The file `step` away from `current` in `paths`; the first or last when the page shows none of them. */5export const stepFrom = (6 paths: readonly string[],7 current: string | undefined,8 step: 1 | -1
53 unmodified lines
62 now.onMove(next);63 }64 };6575 // Before the tree's own keys, which take letters to find a row.66 // Captured, to run before the tree's own keys, which take letters to find a67 // row.68 document.addEventListener("keydown", onKey, { capture: true });6970 return () => {71 document.removeEventListener("keydown", onKey, { capture: true });
3 unmodified lines
modified:apps/web/src/features/code/headers.ts-4 removed
1/**2 * Whether a revision names one commit for good: a whole 40-hex id, where3 * `main` or a tag moves with the next landing.4 */1export const isCommitId = (rev: string) => /^[0-9a-f]{40}$/u.test(rev);
modified:apps/web/src/features/code/line-hash.ts-16 removed
1/**2 * Line anchors on a file page: `#L10` names line 10 and `#L10-L20` lines3 * 10 to 20 (either end may come first). Lines count from 1, as git and4 * Pierre's `SelectedLineRange` do. Pure, so the file, why and propose pages5 * read and write anchors one way.6 */1import { Option } from "effect";29/** Lines `start` to `end`, both included, `start <= end`. */3export interface LineRange {4 readonly end: number;5 readonly start: number;6}715/** `L<n>` or `L<a>-L<b>`, with or without the `#` (the router's `hash` has none); no leading zero. */8const ANCHOR = /^#?L(?<first>[1-9]\d*)(?:-L(?<second>[1-9]\d*))?$/u;918/** The lines `hash` names, or none when it names no line. */10export const parseLineHash = (hash: string): Option.Option<LineRange> => {11 const groups = ANCHOR.exec(hash)?.groups;1213 if (groups?.first === undefined) {
8 unmodified lines
22 start: Math.min(first, second),23 });24};2535/** The anchor for `range`: `#L<n>` for one line, `#L<a>-L<b>` for more. */26export const lineHash = ({ end, start }: LineRange): string =>27 start === end ? `#L${start}` : `#L${start}-L${end}`;2839/** Lines on one side of one file's diff: the new side unless `deletions`. */29export interface DiffLines extends LineRange {30 readonly path: string;31 readonly side: "additions" | "deletions";32}
2 unmodified lines
35 /^#?diff-(?<path>[^:]+)(?::(?<lines>[DL]\d+(?:-[DL]\d+)?))?$/u;3637const decodePath = Option.liftThrowable(decodeURIComponent);3850/**51 * The file a commit page's hash names (`#diff-src%2Fparse.ts`), and its52 * lines when it names some (`…:L4-L7` on the new side, `…:D4` on the old).53 */39export const parseDiffHash = (40 hash: string41): Option.Option<{42 readonly path: string;
18 unmodified lines
61 }))62 );63};6480/** The hash naming `lines` of a file's diff, without the `#`. */65export const diffLinesHash = ({66 end,67 path,68 side,
9 unmodified lines
modified:apps/web/src/features/code/log-page.ts-1 removed
1/** How many commits a page of a log holds (the platform's default `limit`). */1export const LOG_PAGE = 30;
modified:apps/web/src/features/code/log-view.tsx+2 added-31 removed
1/**2 * The landings: the log from a revision along first parents, newest first,3 * a page at a time, under a sticky header per day (UTC). One row per4 * commit: its subject, then what it did (the ask it answered or opened),5 * its credit in one line, and "held back" with its lock when sealed checks6 * judged it; at the right its short id over its age. A commit the platform7 * did not land came in with the history the project adopted, and says so.8 *9 * The toolbar filters the page: every commit, the answers, or the asks'10 * openings. A landing reads as the platform recorded it11 * (`CommitView.landing`), never from a trailer.12 */1import type { CommitView } from "@repo/protocol/domain/code";2import type { ProjectName, RepoPath } from "@repo/protocol/ids";3import { DateTime, Option } from "effect";4import { LockKeyhole } from "lucide-react";
11 unmodified lines
16import { Pager } from "./pager.tsx";17import { blobHref, commitHref, commitsHref, shortSha } from "./paths.ts";18import { revLabel } from "./rev.ts";1932/** Which commits the page shows: all of them, the answers, or the asks' openings. */20export type LogShow = "all" | "answers" | "openings";2135/** A day as its header says it: "October 6, 2026". */22const dayWords = new Intl.DateTimeFormat("en", {23 dateStyle: "long",24 timeZone: "UTC",25});2641/** The commits of each day, in the order given, each day once. */27export const byDay = (commits: readonly CommitView[]) => {28 const days: { readonly day: string; readonly commits: CommitView[] }[] = [];2930 for (const commit of commits) {
9 unmodified lines
4041 return days;42};4359/** What a commit did: the ask it answered or opened, when it is a landing that did. */44const linkedOf = (commit: CommitView) =>45 commit.landing === undefined46 ? undefined47 : Option.getOrUndefined(askOf(commit.landing));4865/** Whether `commit` belongs on the page `show` asks for. */49export const shows = (show: LogShow, commit: CommitView) => {50 if (show === "all") {51 return true;52 }
6 unmodified lines
59};6061const LINK = "decoration-rule underline hover:decoration-current";6280/** A part of a row's second line that holds links: above the row's own link, so it can be pressed. */63const Raised = ({ children }: { readonly children: ReactNode }) => (64 <span className="relative z-[1]">{children}</span>65);6685/** One commit's row. */67const CommitRow = ({68 commit,69 now,70 project,
61 unmodified lines
132 );133};134135/**155 * Where the page before the one at `from` starts. A whole log's `from`156 * counts commits, so that page is one `LOG_PAGE` back. A path's history157 * counts the commits the platform scanned (up to 200 a call, most of158 * which may not touch the path), so where the page before began is not159 * known: Newer goes back to the newest.136 * A path's history counts the commits the platform scanned, not those shown, so137 * where the page before began is not known: Newer goes back to the newest.138 */139const newerPage = (from: number, path: RepoPath | undefined) =>140 path === undefined ? { from: Math.max(0, from - LOG_PAGE) } : { path };141
8 unmodified lines
150151const FILTER =152 "text-ui text-muted-foreground hover:text-foreground aria-[current]:text-foreground flex h-10 items-center border-b-2 border-transparent px-1 no-underline aria-[current]:border-current aria-[current]:font-semibold";153176/** The page's title: the landings at the revision, or one path's history. */154const titleOf = (path: RepoPath | undefined, rev: string) => {155 if (path !== undefined) {156 return `History of ${path}`;157 }158159 return rev === "main" ? "Landings" : `Landings on ${revLabel(rev)}`;160};161185/** The page's search with `show`: none for every commit. */162const searchFor = (query: string, show: LogShow) => {163 const search: Record<string, string> = Object.fromEntries(164 new URLSearchParams(query)165 );
6 unmodified lines
172};173174export interface LogViewProps {175 readonly commits: readonly CommitView[];200 /** Where this page starts. */176 readonly from: number;202 /** Where the next (older) page starts; absent on the last. */177 readonly next?: number | undefined;178 readonly now: DateTime.Utc;205 /** Only the commits that changed this path. */179 readonly path?: RepoPath | undefined;180 readonly project: ProjectName;181 readonly rev: string;209 /** Which commits of the page to show. */182 readonly show?: LogShow;183}184185export const LogView = ({
6 unmodified lines
192 rev,193 show = "all",194}: LogViewProps) => {195 const filter = path === undefined ? {} : { path };224 // The pager keeps the kind the page shows.196 const kind = show === "all" ? {} : { show };197 const shown = commits.filter((commit) => shows(show, commit));198 const base = commitsHref(project, rev, filter);199 const [to, query = ""] = base.split("?");
75 unmodified lines
modified:apps/web/src/features/code/media.ts+1 added-9 removed
1/**2 * Whether the screen is at least a width, kept current as the window3 * changes. The server and the page's first render say no, so the markup4 * matches; the browser then says what the screen is.5 */1import { useMemo, useSyncExternalStore } from "react";23const subscribe = (query: string) => (changed: () => void) => {4 const list = globalThis.matchMedia(query);
4 unmodified lines
9 list.removeEventListener("change", changed);10 };11};1218/** Whether `query` matches now, in the browser; never on the server. */13/** False on the server and on the first render, so the markup matches. */14export const useMedia = (query: string): boolean =>15 useSyncExternalStore(16 useMemo(() => subscribe(query), [query]),17 () => globalThis.matchMedia(query).matches,18 () => false19 );2026/** The shell's width, from which the rail holds the tree. */21export const SHELL_QUERY = "(min-width: 70rem)";2229/** The width from which a diff may set its sides apart. */23export const SPLIT_QUERY = "(min-width: 48rem)";2432/** A tablet's width and wider, where a sheet comes from the side rather than filling the screen. */25export const TABLET_QUERY = "(min-width: 40rem)";
modified:apps/web/src/features/code/not-found.tsx-10 removed
1import type { Refusal } from "@repo/protocol/refusal";2/**3 * A code page's 404. A path missing at a revision that exists lands softly4 * on the nearest folder that does, the platform's refusal (`UnknownPath`)5 * as its notice, verbatim, above the folder's entries. Any other refusal6 * (`UnknownProject`, `UnknownRevision`, `UnknownCommit`) is drawn as `git`7 * would print it, with a way onward; an address that can name nothing8 * says why in a sentence.9 */2import { Option, Schema } from "effect";3import type { Array } from "effect";4import type { ReactNode } from "react";5
14 unmodified lines
2021export const NOTHING =22 "Nothing is at this address: a code page names a project, then main, a whole 40-hex commit id or a tag, then a path in the project.";2332/** A refusal with no folder to land on: verbatim, then the ways onward. */24const Refused = ({25 refusals,26}: {27 readonly refusals: Array.NonEmptyReadonlyArray<Refusal> | undefined;
16 unmodified lines
44 data,45 files,46}: {47 readonly data?: unknown;57 /** The Files button, below the shell's width, on the folder a missing path lands on. */48 readonly files?: ReactNode;49}) =>50 Option.match(decodeLanding(data), {51 onNone: () => (
13 unmodified lines
modified:apps/web/src/features/code/numbered-lines.tsx+2 added-14 removed
1/**2 * A file as plain text, each line numbered and anchored (`#L42` scrolls3 * there with no script): what the server sends of a file, and what a4 * reader sees until the browser has drawn it highlighted over it. It takes5 * Pierre's measures for a file drawn without a header: 8 px above and6 * below the code, 13 px on 20 px lines, the gutter at least three figures7 * wide with two before them and one after, the text one column in. So the8 * highlighting arrives in place and nothing moves. Long lines scroll9 * sideways inside the code, never wrap.10 *11 * `bands` puts a row above a line (the why page's groups), as the drawing12 * puts its annotations.2 * Takes Pierre's measures for a file drawn without a header, so the3 * highlighting arrives in place and nothing moves.4 */5import type { ReactNode } from "react";67import { linesOf } from "./file-header.tsx";818/** How many lines the server sends; the browser's drawing shows them all. */9export const FALLBACK_LINES = 2000;1021/** Pierre's gutter: at least three figures, two before them and one after, then a 2 px gap. */11const GUTTER =12 "border-background text-muted-foreground hover:text-foreground min-w-[calc(6ch+2px)] border-r-2 pr-[1ch] pl-[2ch] text-right tabular-nums no-underline select-none";1314export const NumberedLines = ({15 bands,16 text,17}: {18 readonly text: string;30 /** A row to draw above each of these lines, by line number. */19 readonly bands?: ReadonlyMap<number, ReactNode>;20}) => {21 const lines = linesOf(text);22 const shown = lines.slice(0, FALLBACK_LINES);
46 unmodified lines
modified:apps/web/src/features/code/pager.tsx-4 removed
1/**2 * Newer and Older, for a list read a page at a time (the log, the tags).3 * Each is a plain link to its page; a side with no page shows nothing.4 */1import {2 Pagination,3 PaginationContent,4 PaginationItem,
29 unmodified lines
modified:apps/web/src/features/code/paths.ts+2 added-29 removed
1/**2 * The code browser's addresses, one function per page, so every link to a3 * folder, a file, its bytes, its history or a commit is spelled one way.4 * A revision is one URL segment (`revSegment`: a tag's `/` and `@` are5 * encoded); a repo path keeps its `/` and encodes each segment.6 */1import type { ProjectName } from "@repo/protocol/ids";23import { revSegment } from "./rev.ts";411/** `path` in a URL: each segment encoded, the slashes kept. */5export const pathSegments = (path: string): string =>6 path.split("/").map(encodeURIComponent).join("/");715/** `/<prefix>` followed by `/<path>` when there is one. */8const under = (prefix: string, path: string | undefined) =>9 path === undefined || path === ""10 ? prefix11 : `${prefix}/${pathSegments(path)}`;1221/** A folder at `rev`; the root when `path` is absent. */13export const treeHref = (project: ProjectName, rev: string, path?: string) =>14 under(`/${project}/tree/${revSegment(rev)}`, path);1525/** A file at `rev`. */16export const blobHref = (project: ProjectName, rev: string, path: string) =>17 under(`/${project}/blob/${revSegment(rev)}`, path);1829/** A file's bytes at `rev`, as the platform serves them. */19export const rawHref = (project: ProjectName, rev: string, path: string) =>20 under(`/${project}/raw/${revSegment(rev)}`, path);2133/** Why each line of a file at `rev` is there (the why page). */22export const whyHref = (project: ProjectName, rev: string, path: string) =>23 under(`/${project}/why/${revSegment(rev)}`, path);2425/**38 * The log from `rev`: only the commits that changed `path` when given, from39 * the `from`th. An `AppLink` takes the bare log as its `to` and the query40 * as its `search`, or the router reads the query as part of the revision.26 * An `AppLink` takes the bare log as its `to` and the query as its `search`, or27 * the router reads the query as part of the revision.28 */29export const commitsHref = (30 project: ProjectName,31 rev: string,
3 unmodified lines
35 show,36 }: {37 readonly from?: number;38 readonly path?: string;52 /** Only the answers or the asks' openings; every commit when absent. */39 readonly show?: "answers" | "openings";40 } = {}41) => {42 const query = new URLSearchParams();
14 unmodified lines
5758 return `/${project}/commits/${revSegment(rev)}${search === "" ? "" : `?${search}`}`;59};6075/** One commit. */61export const commitHref = (project: ProjectName, sha: string) =>62 `/${project}/commit/${sha}`;6379/** A commit's id as a person reads it. */64export const shortSha = (sha: string) => sha.slice(0, 7);6582/** The folder holding `path`: `""` for a file at the root. */66export const dirOf = (path: string) => {67 const slash = path.lastIndexOf("/");6869 return slash === -1 ? "" : path.slice(0, slash);70};7189/** Each folder above `path`, outermost first: `a/b/c` gives `a` and `a/b`. */72export const ancestorsOf = (path: string): readonly string[] =>73 path74 .split("/")75 .slice(0, -1)76 .map((_, index, parts) => parts.slice(0, index + 1).join("/"));7796/** A size as a person reads it: bytes, then KiB, MiB and GiB to one decimal. */78export const sizeInWords = (bytes: number) => {79 const units = ["KiB", "MiB", "GiB"] as const;8081 if (bytes < 1024) {
11 unmodified lines
93const IMAGE = /\.(?:png|jpe?g|gif|webp|avif|ico|svg)$/iu;9495const MARKDOWN = /\.(?:md|markdown|mdown)$/iu;96116/** Whether the platform serves `path` as an image a page may show inline. */97export const isImage = (path: string) => IMAGE.test(path);98119/** Whether `path` is Markdown, rendered on its page. */99export const isMarkdown = (path: string) => MARKDOWN.test(path);100122/**123 * Whether a file's page shows it as code: text it has, and not an image124 * or Markdown shown as itself (`?plain=1` shows their source). The server125 * highlights a file ahead only then.126 */101export const showsCode = (102 file: {103 readonly binary: boolean;104 readonly path: string;
4 unmodified lines
109 !file.binary &&110 file.text !== undefined &&111 (plain || !(isImage(file.path) || isMarkdown(file.path)));112139/** The id of a changed file's diff on its commit's page. */113export const diffAnchor = (path: string) => `diff-${encodeURIComponent(path)}`;
modified:apps/web/src/features/code/pierre.ts+12 added-51 removed
1/**2 * What every drawing of code shares: the options each `@pierre/diffs` view3 * spreads into its own (`File`, `MultiFileDiff`, `FileDiff`), the options4 * of the `@pierre/trees` file tree, and the colour theme they draw in.5 *6 * The theme reads CSS variables (`--diffs-token-*`, `--diffs-foreground`,7 * `--diffs-background`), which `styles.css` sets on every8 * `diffs-container` from the web's own tokens: code sits on the paper and9 * follows the system's light or dark setting with the page, in low-chroma10 * colours that never borrow a state's. It is named for both schemes, so11 * Pierre leaves the scheme to the page: a single theme name would fix it12 * to the theme's own type (Shiki calls a variable theme dark). Colour is13 * all it carries: Pierre resolves a token's weight and slant through14 * `light-dark()`, which takes colours only, so a two-scheme drawing drops15 * them.16 *17 * The limits are Pierre's own defaults, written out so a reader sees them:18 * past them a file (or a line, or a changed line's pair) is drawn as plain19 * text, so a minified bundle or a lockfile cannot stall the page.20 *21 * The server draws a file or a diff with these same options22 * (`prerender-server.ts`), so the browser's drawing takes the place of the23 * server's with nothing on the screen changing.24 *25 * No React and no DOM here: the module loads in Node for its test, in the26 * Worker for the server's drawing, and in the browser only through the27 * views that draw. A drawing hands its code boxes over once drawn, so code28 * too wide for its pane is a stop for Tab.2 * The theme reads CSS variables `styles.css` sets from the web's tokens. It is3 * named for both schemes, so Pierre leaves the scheme to the page (a single4 * name would fix it; Shiki calls a variable theme dark). It carries colour5 * only: Pierre resolves a token's weight and slant through `light-dark()`,6 * which takes colours only. The server draws with these same options, so the7 * browser's drawing replaces it with nothing changing.8 */9import {10 createCSSVariablesTheme,11 DEFAULT_TOKENIZE_MAX_LENGTH,12 formatCSSVariablePrefix,13 registerCustomTheme,14} from "@pierre/diffs";1537/** The token theme's registered name. */16export const CODE_THEME = "repo-tokens";1740/** A drawn file's code box: whether it scrolls, and whether Tab reaches it. */18interface CodeBox {19 readonly clientHeight: number;20 readonly clientWidth: number;21 readonly scrollHeight: number;22 readonly scrollWidth: number;23 tabIndex: number;24}2549/** A drawing as Pierre hands it over once drawn: its code boxes, in its shadow root. */26interface Drawn {27 readonly shadowRoot: {28 readonly querySelectorAll: (selectors: "code") => Iterable<CodeBox>;29 } | null;30}3132/**57 * Code that scrolls (a long line, a phone's width) is a stop for Tab, so a58 * keyboard can scroll it; code that fits is not, so a page of short files59 * adds no stops.33 * Code that scrolls is a stop for Tab, so a keyboard can scroll it; code that34 * fits is not.35 */36const reachScrolledCode = (node: Drawn) => {37 for (const code of node.shadowRoot?.querySelectorAll("code") ?? []) {38 code.tabIndex =
3 unmodified lines
42 : -1;43 }44};4571/**72 * The focus ring inside a drawing's shadow root, which the page's own73 * stylesheet does not reach: the page's ink, as everywhere else.74 */46/** The page's own stylesheet does not reach a drawing's shadow root. */47export const FOCUS_CSS =48 "code:focus-visible { outline: 2px solid var(--foreground); outline-offset: -2px; }";4978/** Spread first into a drawing's own options. */50export const diffsOptions = {51 maxLineDiffLength: 1000,52 onPostRender: reachScrolledCode,53 preferredHighlighter: "shiki-js",
3 unmodified lines
57 tokenizeMaxLineLength: 1000,58 unsafeCSS: FOCUS_CSS,59} as const;6090/** A file's drawing: no header of its own (the page's sits above it), its lines selectable, scrolling sideways. */61export const fileOptions = {62 ...diffsOptions,63 disableFileHeader: true,64 enableLineSelection: true,65 lineHoverHighlight: "number",66 overflow: "scroll",67} as const;6899/** A diff's drawing, unified or split: signs or side bars, changed words marked, unchanged runs folded into bars. */69export const diffOptionsFor = (split: boolean) =>70 ({71 ...diffsOptions,72 diffIndicators: split ? "bars" : "classic",
4 unmodified lines
77 lineHoverHighlight: "both",78 overflow: "scroll",79 }) as const;80112/** The file tree's look: compact rows, plain icons (`styles.css` greys them). */81export const treesOptions = { density: "compact", icons: "minimal" } as const;82115/**116 * Where a variable is not set (a drawing outside `diffs-container`'s117 * mapping), the page's own tokens stand in.118 */83const variableDefaults = {84 background: "var(--background)",85 foreground: "var(--foreground)",86 "token-comment": "var(--muted)",
7 unmodified lines
94 "token-string-expression": "var(--foreground)",95};9697/**134 * The token theme itself, made as Pierre's `registerCustomCSSVariableTheme`135 * makes it. The browser registers it by name; the server attaches it to136 * its highlighter directly, since Pierre refuses to resolve a theme by name137 * in a Worker's global scope.98 * The server attaches it to its highlighter directly: Pierre refuses to resolve99 * a theme by name in a Worker's global scope.100 */101export const codeTheme = () =>102 createCSSVariablesTheme({103 fontStyle: false,
1 unmodified line
105 variableDefaults,106 variablePrefix: formatCSSVariablePrefix("global"),107 });108147/** Whether this page has registered the theme yet; Pierre refuses a name twice. */109/** Pierre refuses a name registered twice. */110const registered = { done: false };111150/** Registers the token theme, once; each drawing calls it before it draws. */112export const registerCodeTheme = () => {113 if (!registered.done) {114 registered.done = true;115 registerCustomTheme(CODE_THEME, () => Promise.resolve(codeTheme()));
2 unmodified lines
modified:apps/web/src/features/code/plain-diff.tsx+2 added-50 removed
1/**2 * A commit's diff as plain text: what the server sends, and what a reader3 * sees until the browser has drawn the highlighted diff over it. It holds4 * the hunks the drawing holds (`diff-model.ts` parses both texts with the5 * drawing's own parser) and takes Pierre's measures: a 44 px file header,6 * 13 px code on 20 px lines, line numbers in a gutter of at least three7 * figures with two before and one after, a sign in the first of two8 * leading columns, unchanged runs as 32 px "N unmodified lines" bars. So9 * the highlighting arrives in place and nothing moves. The first files the10 * server highlights (`prerenderedPaths`, ADR 0027) are its drawing instead11 * of plain lines, under the same header.12 *13 * Each file is a disclosure whose summary is its header: folded, only the14 * header shows (an added or deleted file past 80 lines starts folded).15 * Additions and deletions take the diff's own tints, never the landed or16 * refused colour; a unified diff marks each line `+` or `-`, a split one17 * marks the side with a bar.2 * Holds the hunks the drawing holds and takes Pierre's measures, so the3 * highlighting arrives in place and nothing moves.4 */5import type { ChangedFile } from "@repo/protocol/domain/code";6import { Option } from "effect";7import { ChevronDown, SquareDot, SquareMinus, SquarePlus } from "lucide-react";
6 unmodified lines
14import { diffAnchor } from "./paths.ts";15import { diffDrawing } from "./prerender.ts";16import { ServerCode } from "./server-code.tsx";1732/** One numbered line: its text, and which side it is on. */18type Line = Extract<PlainRow, { readonly number: number }>;1935/** A line's ground and its number's colour, by what it is. */20const TONES = {21 addition: {22 line: "bg-diff-add-bg",23 number: "bg-diff-add-bg text-diff-add-sign",
7 unmodified lines
31 Line["kind"],32 { readonly line: string; readonly number: string }33>;3451/** Each line's sign in a unified diff, the mark that reads without colour. */35const SIGNS = { addition: "+", context: " ", deletion: "-" } as const;3654/** Pierre's gutter: at least three figures, two before them and one after, then a 2 px gap. */37const GUTTER =38 "border-background min-w-[calc(6ch+2px)] border-r-2 pr-[1ch] pl-[2ch] text-right tabular-nums select-none";3958/** An unchanged run between hunks: a 32 px bar saying how many lines it skips. */40const Separator = ({41 lines,42 span,43}: {
8 unmodified lines
52 {lines} unmodified {lines === 1 ? "line" : "lines"}53 </div>54);5575/** One line of a unified diff: its number, then its sign and text. */56const UnifiedLine = ({ line }: { readonly line: Line }) => (57 <>58 <span className={`${GUTTER} ${TONES[line.kind].number}`}>59 {line.number}
10 unmodified lines
70 </span>71 </>72);7394/** One side of a split diff's row: its number with the side's bar, then its text; empty when the side has none. */74const SplitSide = ({ line }: { readonly line: Line | undefined }) =>75 line === undefined ? (76 <>77 <span className={`${GUTTER} bg-surface`} />
23 unmodified lines
101 </span>102 </>103 );104126/** A file's lines, unified: one grid of gutter and code, scrolling sideways in itself. */105const UnifiedBody = ({ rows }: { readonly rows: readonly PlainRow[] }) => (106 <div className="overflow-x-auto pb-2">107 <code className="grid min-w-full grid-cols-[min-content_1fr]">108 {rows.map((row, index) =>
6 unmodified lines
115 </code>116 </div>117);118141/** A file's lines, split: old on the left, new on the right, row beside row. */119const SplitBody = ({ rows }: { readonly rows: readonly SplitRow[] }) => (120 <div className="overflow-x-auto pb-2">121 <code className="grid min-w-full grid-cols-[min-content_1fr_min-content_1fr]">122 {rows.map((row, index) =>
9 unmodified lines
132 </code>133 </div>134);135159/** What a file changed, in counts: `+n −m`, each in its tint, with words for a screen reader. */136export const ChangeCounts = ({137 additions,138 deletions,139 header = false,140}: {141 readonly additions: number;142 readonly deletions: number;167 /** As a diff's file header prints them: a hyphen, and no count of nothing. */143 readonly header?: boolean;144}) => (145 <span className="text-mono flex shrink-0 items-center gap-[1ch] font-mono tabular-nums">146 {header && additions === 0 ? null : (
11 unmodified lines
158 )}159 </span>160);161187/** Why a file has no lines to show: binary, or its text not sent. */162const Unshown = ({ file }: { readonly file: ChangedFile }) => (163 <p className="text-ui text-muted-foreground px-4 pb-3 font-sans">164 {file.binary ? "A binary file" : "Its text is not shown"}, {file.status}.165 </p>166);167194/**195 * A file's lines, unified or split; why it has none when it has none. A196 * file the server highlighted (unified, `prerenderedPaths`) is its drawing,197 * and the plain lines only where the document did not bring it.198 */168const FileBody = ({169 file,170 prerendered,171 split,
22 unmodified lines
194 plain195 );196};197229/** Each kind of change as the drawing's header marks it, in the diff's tints. */198const CHANGE_MARKS = {199 added: { icon: SquarePlus, tone: "text-diff-add-sign" },200 deleted: { icon: SquareMinus, tone: "text-diff-del-sign" },201 modified: { icon: SquareDot, tone: "text-muted-foreground" },
1 unmodified line
203 ChangedFile["status"],204 { readonly icon: LucideIcon; readonly tone: string }205>;206239/**240 * A file's header as the drawing draws it: the fold's chevron, the mark of241 * its change (with its word for a screen reader), its path, then its242 * counts and anything the page adds.243 */207export const FileHeaderLine = ({208 end,209 file,210}: {211 readonly file: DrawnFile;249 /** Anything a page puts at the header's end (a "Mark read" button). */212 readonly end?: ReactNode;213}) => {214 const { icon: Icon, tone } = CHANGE_MARKS[file.file.status];215
26 unmodified lines
242};243244export interface PlainDiffProps {245 readonly files: readonly ChangedFile[];284 /** Old and new side by side; unified when absent. */246 readonly split?: boolean;286 /** The files folded now; each file's own default (`folded`) when absent. */247 readonly folded?: ReadonlySet<string> | undefined;288 /** A header's fold was pressed. */248 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;290 /** `files` already parsed (`drawnFiles`), so a page parses each once. */249 readonly drawn?: readonly DrawnFile[] | undefined;292 /** The paths the server sends highlighted (`prerenderedPaths`); none when absent. */250 readonly prerendered?: ReadonlySet<string> | undefined;251}252296/**297 * The diff of `files`, plain, in the order a tree lists them. Server298 * markup: one `section[data-file]` per file, its header sticky at the top299 * of the pane that scrolls it.300 */253export const PlainDiff = ({254 drawn: parsed,255 files,256 folded,
47 unmodified lines
modified:apps/web/src/features/code/pool.tsx+5 added-31 removed
1/**2 * Highlighting off the main thread: Pierre's worker pool, which every3 * drawing of code under `CodePool` shares (`File`, `CodeView`). The pool is4 * made once for the tab, the first time a page draws code, and kept: the5 * next code page highlights in workers already warm, and a file drawn once6 * is not highlighted again (each drawing keys its file by blob id).7 *8 * The worker is Pierre's own module, bundled by Vite as a module worker.9 * Only the browser loads this file (through the lazy drawings).10 */1import { WorkerPoolContext } from "@pierre/diffs/react";2import { getOrCreateWorkerPoolSingleton } from "@pierre/diffs/worker";3import { Effect } from "effect";4import type { ReactNode } from "react";5import { use, useMemo } from "react";67import { diffsOptions, registerCodeTheme } from "./pierre.ts";819/** Two workers: a page draws one file or one diff at a time, and grammars load once per worker. */9const POOL_SIZE = 2;1022/** The tab's pool: made the first time code is drawn or warmed, the same after. */11export const workerPool = () => {12 registerCodeTheme();1314 return getOrCreateWorkerPoolSingleton({
5 unmodified lines
20 tokenizeMaxLineLength: diffsOptions.tokenizeMaxLineLength,21 },22 poolOptions: {23 onWorkerError: () => {36 // A worker that fails is Pierre's to replace; the code it was37 // drawing stays as plain text, which is what the page sent.24 // Pierre replaces a failed worker; its code stays as the page's plain text.25 },26 poolSize: POOL_SIZE,27 workerFactory: () =>28 new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {
8 unmodified lines
37/** One promise per pool, so `use` sees the same one on every render. */38const readiness = new WeakMap<Pool, Promise<void>>();3940/**54 * Settles once the pool's own highlighter is up (or has failed, when55 * Pierre draws on the main thread instead). Before that, Pierre draws a56 * file it would not highlight (a `.vm`, plain text) as nothing, and never57 * draws it again.41 * Before the pool's highlighter is up, Pierre draws a file it would not42 * highlight as nothing, and never draws it again.43 */44const readyOf = (pool: Pool) => {45 const known = readiness.get(pool);4647 if (known !== undefined) {48 return known;49 }5066 // A pool already up is marked settled the way React reads a promise it67 // has seen, so `use` does not hold the drawing back for a turn; one68 // still starting is marked so once it is up, whoever awaited it first.51 // Marked settled the way React reads a promise it has seen, so `use` does not52 // hold the drawing back for a turn.53 const made = pool.isInitialized()54 ? Object.assign(Promise.resolve(), { status: "fulfilled" })55 : Effect.runPromise(56 Effect.ignore(Effect.tryPromise(() => pool.initialize()))
8 unmodified lines
6566 return made;67};6885/**86 * Settles once the tab's pool is up (at once where there are no workers):87 * a drawing awaited on this then mounts with nothing left to wait for.88 */69export const poolReady = () =>70 "Worker" in globalThis ? readyOf(workerPool()) : Promise.resolve();7192/**93 * The pool, for the drawings under it; none outside a browser. Until the94 * pool is up the drawings wait in their `Suspense`, whose fallback is the95 * server's plain text.96 */72export const CodePool = ({ children }: { readonly children: ReactNode }) => {98 // Pierre keeps one pool for the tab: asking again hands back the same.73 const pool = useMemo(74 () => ("Worker" in globalThis ? workerPool() : undefined),75 []76 );
7 unmodified lines
modified:apps/web/src/features/code/prerender-server.ts+7 added-34 removed
1/**2 * Code highlighted on the server: a file, or one file of a diff, drawn by3 * `@pierre/diffs/ssr` with the browser's own options (`pierre.ts`) into4 * the HTML of the drawing's shadow root, which the page sends as a5 * declarative shadow root. The browser's drawing later takes its place6 * with the same highlighting, so the reader sees the code once.7 *8 * Shiki runs on its JavaScript engine (a Worker compiles no WebAssembly),9 * and only with the grammars named here: the Worker's build resolves10 * `shiki` to core alone (`vite.config.ts`), so no other grammar is11 * bundled. Pierre will not resolve a grammar or a theme by name in a12 * Worker's global scope, so each is loaded here and attached to its2 * Shiki runs on its JavaScript engine (a Worker compiles no WebAssembly), and3 * the Worker's build resolves `shiki` to core alone (`vite.config.ts`), so only4 * the grammars named here are bundled. Pierre will not resolve a grammar or a5 * theme by name in a Worker's global scope, so each is attached to its6 * highlighter directly, once per isolate.14 *15 * Loaded on the server only, by `prerender.ts`, on a page's first16 * highlighted code: the Worker's entry carries none of it.7 */8import {9 attachResolvedLanguages,10 attachResolvedThemes,
19 unmodified lines
30import type { ServerLanguage } from "./prerender.ts";3132type Grammar = () => Promise<{ readonly default: LanguageRegistration[] }>;3344/** Each server language's grammar, loaded on first use; `yml` and `zsh` are aliases Pierre names. */34const GRAMMARS: Record<ServerLanguage, Grammar> = {35 css: () => import("shiki/langs/css.mjs"),36 html: () => import("shiki/langs/html.mjs"),37 javascript: () => import("shiki/langs/javascript.mjs"),
7 unmodified lines
45 yml: () => import("shiki/langs/yaml.mjs"),46 zsh: () => import("shiki/langs/shellscript.mjs"),47};4860/** The shared highlighter, with the token theme and `language`'s grammar attached. */49const highlighterFor = (language: ServerLanguage) =>50 Effect.gen(function* () {51 const highlighter = yield* Effect.tryPromise(() =>52 getSharedHighlighter({
4 unmodified lines
57 );5859 const grammar = yield* Effect.tryPromise(GRAMMARS[language]);6073 // Each is attached once; Pierre skips one already attached. The theme74 // is normalized as Pierre normalizes a registered one.61 yield* Effect.try(() => {62 attachResolvedThemes(normalizeTheme(codeTheme()), highlighter);63 attachResolvedLanguages(64 { data: grammar.default, name: language },
1 unmodified line
66 );67 });68 });6984/**85 * A drawing in `language`; if it fails, the same drawing as plain text, so86 * the page still sends Pierre's markup; none if that fails too.87 */70const draw = <E1, E2>(71 language: Option.Option<ServerLanguage>,72 highlighted: Effect.Effect<string, E1>,73 plain: Effect.Effect<string, E2>
6 unmodified lines
80 Effect.catchCause(() => plain)81 ),82 }).pipe(Effect.orElseSucceed((): string | undefined => undefined));83102/** A file drawn as `FileCode` draws it. */84const fileHtml = (file: FileContents) =>85 Effect.tryPromise(() => preloadFile({ file, options: fileOptions })).pipe(86 Effect.map(({ prerenderedHTML }) => prerenderedHTML)87 );88108/** One file, as `FileCode` draws it. */89export const prerenderFile = (file: {90 readonly path: string;91 readonly sha: string;92 readonly text: string;
7 unmodified lines
100 );101};102103/**124 * A diff's body drawn without Pierre's header (the page's own sits above125 * it) sits as it does in the browser's drawing: Pierre drops the code's126 * top gap only after a header, so the lines would otherwise start 8 px127 * lower, and it takes a scrollbar's width from the bottom gap only once128 * its script has measured one, so the next file would start 6 px higher.104 * Pierre drops the code's top gap only after a header, and takes a scrollbar's105 * width from the bottom gap only once its script has measured one; this keeps a106 * headerless body where the browser's drawing puts it.107 */108const UNDER_HEADER_CSS =109 "[data-code] { padding-top: 0; padding-bottom: var(--diffs-gap-block, var(--diffs-gap-fallback)); }";110133/** A diff's body drawn unified, as `DiffCode` draws it, without a header. */111const diffHtml = (fileDiff: FileDiffMetadata) =>112 Effect.tryPromise(() =>113 preloadDiffHTML({114 fileDiff,
4 unmodified lines
119 },120 })121 );122146/**147 * One file of a diff's body, unified, as `DiffCode` draws it, under the148 * page's own header: none for a file with no lines.149 */123export const prerenderDiff = (file: DrawnFile) =>124 Option.match(file.diff, {125 onNone: () => Effect.sync((): string | undefined => undefined),126 onSome: (diff) =>
6 unmodified lines
modified:apps/web/src/features/code/prerender.ts+7 added-56 removed
1/**2 * Which code the server sends highlighted, and where its drawing waits3 * between the page's loader and its render.4 *5 * The server highlights a fixed set of languages (`SERVER_LANGUAGES`, the6 * grammars the Worker bundles) and only within its own limit, far below7 * the browser's: a page highlights at most `SERVER_LINES` lines of text8 * (a diff counts both sides, as Pierre highlights both whole files), and9 * no line longer than the drawing's own line limit, so a minified file is10 * never tokenized on the server. Anything else is sent as plain text, as11 * before, and the browser highlights it.12 *13 * Both sides decide alike from the page's own data, so the browser knows14 * which code arrived highlighted without being told.15 *16 * The drawing is made once per (blob, path) or (both blobs, path), so it17 * is kept here, keyed by those ids, which never change what they name: the18 * loader starts it and waits for it, and the render reads it at once. A19 * few are kept, within a byte budget, so a file read again is not drawn20 * again. Nothing here runs in the browser but the decision.2 * The server and the browser decide alike from the page's own data, so the3 * browser knows which code arrived highlighted without being told.4 */5import { getFiletypeFromFileName } from "@pierre/diffs";6import type { ChangedFile } from "@repo/protocol/domain/code";7import { Effect, Option } from "effect";
1 unmodified line
9import { drawnFiles } from "./diff-model.ts";10import type { DrawnFile } from "./diff-model.ts";11import { diffsOptions } from "./pierre.ts";1230/** The languages the Worker bundles a grammar for, by the names Pierre gives a file's type. */13export const SERVER_LANGUAGES = [14 "css",15 "html",16 "javascript",
9 unmodified lines
26] as const;2728export type ServerLanguage = (typeof SERVER_LANGUAGES)[number];2948/**49 * The most lines the server highlights for one page. Measured in the dev50 * world's workerd (ADR 0027), warm: 2,400 lines of TypeScript took about51 * 315 ms, 600 about 85 ms and 400 about 57 ms, so a page spends at most52 * some 60 ms highlighting, and a longer file is sent plain.53 */30/** Measured warm in workerd: 400 lines of TypeScript took about 57 ms. */31export const SERVER_LINES = 400;3256/** The most files of a diff the server highlights: those a reader sees first. */33export const SERVER_FILES = 8;3435const isServerLanguage = (name: string): name is ServerLanguage =>36 SERVER_LANGUAGES.some((language) => language === name);3762/** The language the server highlights `path` in, if it highlights it at all. */38export const serverLanguageOf = (39 path: string40): Option.Option<ServerLanguage> => {41 const name = getFiletypeFromFileName(path);4243 return isServerLanguage(name) ? Option.some(name) : Option.none();44};4571/** `text`'s lines, or none when one is longer than the drawing tokenizes. */46const linesWithin = (text: string): Option.Option<number> => {47 const lines = text.split("\n");4849 return lines.every(
2 unmodified lines
52 ? Option.some(lines.length)53 : Option.none();54};5582/** Whether the server sends this file highlighted. */56export const prerendersFile = (file: {57 readonly path: string;58 readonly text: string;59}) =>60 Option.isSome(serverLanguageOf(file.path)) &&61 file.text.length <= diffsOptions.tokenizeMaxLength &&62 Option.exists(linesWithin(file.text), (lines) => lines <= SERVER_LINES);6391/** A diff's lines on both sides, or none when a side has a line too long. */64const diffLines = (drawn: DrawnFile): Option.Option<number> => {65 const sides = [drawn.file.oldText, drawn.file.newText].flatMap((text) =>66 text === undefined ? [] : [linesWithin(text)]67 );
2 unmodified lines
70 Option.map((counts) => counts.reduce((sum, count) => sum + count, 0))71 );72};73102/**103 * The paths of a diff the server sends highlighted, unified: among the104 * first `SERVER_FILES` files that start open and have lines, those in a105 * server language, within `SERVER_LINES` together.106 */74export const prerenderedPaths = (75 drawn: readonly DrawnFile[]76): ReadonlySet<string> => {77 const paths = new Set<string>();
18 unmodified lines
9697 return paths;98};99133/** A drawing as React's `use` reads it: settled ones say so, so a render never waits on them. */100/** Settled ones say so, so a render never waits on them. */101type Drawing = Promise<string | undefined> & {102 status?: "fulfilled";103 value?: string | undefined;104};105139/** How many drawings are kept, and how many characters of HTML at most. */106const KEPT = { count: 24, size: 8_000_000 } as const;107142/** The drawings made, the oldest first; each id names what it draws for good. */108const kept = new Map<string, { readonly drawing: Drawing; size: number }>();109110const sizeOf = () =>111 [...kept.values()].reduce((sum, entry) => sum + entry.size, 0);112148/** Drops the oldest drawings past the count or the size. */113const trim = () => {114 for (const id of kept.keys()) {115 if (kept.size <= KEPT.count && sizeOf() <= KEPT.size) {116 return;
2 unmodified lines
119 kept.delete(id);120 }121};122159/** The drawing `id` names: the one kept, or one `make` starts now. */123const keptDrawing = <E>(124 id: string,125 make: Effect.Effect<string | undefined, E>126): Drawing => {
5 unmodified lines
132133 return known.drawing;134 }135173 // A drawing that fails is none: the page sends the plain text instead.136 const drawing: Drawing = Effect.runPromise(137 make.pipe(Effect.orElseSucceed((): string | undefined => undefined))138 );139140 const entry = { drawing, size: 0 };141142 kept.set(id, entry);181 // Settled, it says so (`use` then reads it without waiting) and counts182 // its size. Subscribed first, so whoever awaits it next finds it marked.143 // Subscribed first, so whoever awaits it next finds it marked.144 Effect.runFork(145 Effect.promise(() => drawing).pipe(146 Effect.andThen((html) =>147 Effect.sync(() => {
10 unmodified lines
158 return drawing;159};160161/**201 * The server's drawing module, on its first use. The browser's build has202 * none (`import.meta.env.SSR` is false there, so the import is dead code),203 * and draws nothing here.162 * `import.meta.env.SSR` is false in the browser's build, so this import is dead163 * code there.164 */165const server = () =>166 import.meta.env.SSR167 ? Effect.tryPromise(() => import("./prerender-server.ts"))168 : Effect.die("Only the server draws code ahead");169210/** The id a file's drawing is kept by: its blob and its path (which names its language). */170export const fileDrawingId = (file: {171 readonly path: string;172 readonly sha: string;173}) => `file:${file.sha}:${file.path}`;174216/** The id a diff's drawing is kept by: both its blobs and its path. */175export const diffDrawingId = (drawn: DrawnFile) =>176 `${drawn.file.before ?? "none"}:${drawn.file.after ?? "none"}:${drawn.file.path}`;177220/** A file highlighted by the server, as the HTML of its shadow root; none if it could not be. */178export const fileDrawing = (file: {179 readonly path: string;180 readonly sha: string;181 readonly text: string;
2 unmodified lines
184 fileDrawingId(file),185 server().pipe(Effect.andThen(({ prerenderFile }) => prerenderFile(file)))186 );187231/** A diff's file highlighted by the server, unified, as the HTML of its shadow root. */188export const diffDrawing = (drawn: DrawnFile) =>189 keptDrawing(190 diffDrawingId(drawn),191 server().pipe(Effect.andThen(({ prerenderDiff }) => prerenderDiff(drawn)))192 );193238/**239 * A page's file highlighted ahead of its render, which then finds it240 * drawn and waits for nothing; nothing to do for a file sent plain.241 */194export const drawFileAhead = ({195 path,196 sha,197 text,
9 unmodified lines
207 Effect.asVoid208 )209 );210259/** A diff's first files highlighted ahead of its render, as `drawFileAhead`. */211export const drawDiffAhead = (files: readonly ChangedFile[]) => {212 const drawn = drawnFiles(files);213 const paths = prerenderedPaths(drawn);214
8 unmodified lines
modified:apps/web/src/features/code/ref-switcher.tsx-13 removed
1/**2 * The code pages' ref line: the revision being read (main, a tag, or a3 * commit by its short id), and a switcher that opens the same page at4 * main or at any tag. Each choice is a link, so it can be opened in a new5 * tab, and the tags filter as the reader types. The list of tags arrives6 * after the page; until it has, only main is offered.7 */1import type { RefsView } from "@repo/protocol/domain/code";2import { GitBranch, GitCommitHorizontal, Tag } from "lucide-react";3import { useState } from "react";4
6 unmodified lines
11import { AppLink } from "../shared/link.tsx";12import { isCommitId } from "./headers.ts";13import { revLabel } from "./rev.ts";1422/** At most this many tags listed at once; the filter finds the rest. */15const SHOWN = 100;1625/** A ref's mark: a branch for main, a tag for a tag, a commit for a SHA. */17const RefMark = ({ rev }: { readonly rev: string }) => {18 if (rev === "main") {19 return (20 <GitBranch
14 unmodified lines
35 <Tag aria-hidden="true" className="size-4 shrink-0" strokeWidth={1.75} />36 );37};3848/** Under the list: that the tags are still being read, or how many the filter has left out. */39const ListFoot = ({40 count,41 read,42}: {
22 unmodified lines
65 hrefAt,66 refs,67 rev,68}: {79 /** The revision the page reads. */69 readonly rev: string;81 /** Main and the tags, once read. */70 readonly refs?: RefsView | undefined;83 /** The same page at another revision. */71 readonly hrefAt: (rev: string) => string;72}) => {73 const [filter, setFilter] = useState("");74 const [open, setOpen] = useState(false);
66 unmodified lines
modified:apps/web/src/features/code/refs-param.ts-5 removed
1/**2 * The refs page's `?package=`, decoded where the route reads it, in a3 * module with no view of its own.4 */1import { Schema } from "effect";27/** A `?package=` from the address, decoded; none for anything but a name. */3export const packageParamOf = Schema.decodeUnknownOption(4 Schema.NonEmptyString.check(Schema.isMaxLength(255))5);
modified:apps/web/src/features/code/refs-view.tsx+2 added-35 removed
1/**2 * A project's refs as a reader sees them, one row each: main at its landed3 * commit (it moves only by a landing), the tags (newest first, as4 * `listRefs` orders them, `TAGS_PAGE` a page), and the forks: each claim's5 * on one line with its answer, its claimant and the claim's state, then6 * each person's working fork. Only what `listRefs` returns is shown, so7 * the platform's own refs never appear. The page says tags, never8 * releases: a release is something else here.9 *10 * A monorepo's tags version several packages (`@changesets/cli@2.27.1`):11 * when they hold more than one, a list of packages, each with its newest12 * tag and its count, sits above the tags, and `?package=` lists one13 * package's tags alone.14 */1import { packageOf } from "@repo/protocol/domain/code";2import type {3 ForkRef,4 RefsView as Refs,
20 unmodified lines
25import { Workspace } from "../shared/shell/workspace.tsx";26import { Pager } from "./pager.tsx";27import { commitHref, shortSha, treeHref } from "./paths.ts";2843/** One package's tags: its name, its newest tag and how many it has. */29interface PackageRun {30 readonly count: number;31 readonly name: string;32 readonly newest: TagRef;33}3450/**51 * The packages the tags version, in the order `listRefs` gives their52 * runs (most tags first), each with the first, so newest, of its tags.53 */35const packagesOf = (tags: readonly TagRef[]): readonly PackageRun[] => {36 const runs = new Map<string, PackageRun>();3738 for (const tag of tags) {
12 unmodified lines
5152 return [...runs.values()];53};5474/** How many tags a page lists. */55export const TAGS_PAGE = 100;5677/** The refs page itself. */57const refsPath = (project: string) => `/${project}/refs`;5859/**81 * The refs page from the `from`th tag, of one package's tags or all. The82 * router writes the search, so a name it would read back as JSON (a83 * package called `2048`) is quoted and arrives as the name.60 * The router writes the search, so a name it would read back as JSON (a package61 * called `2048`) is quoted.62 */63const refsHref = (project: string, from: number, only?: string) =>64 `${refsPath(project)}${defaultStringifySearch({65 package: only,
2 unmodified lines
6869const plural = (count: number, one: string, many: string) =>70 `${count} ${count === 1 ? one : many}`;7194/** A link inside a row's metadata, raised over the row's own link. */72const META_LINK =73 "decoration-rule relative z-10 underline hover:decoration-current";7498/** A commit in a row's metadata: short, whole in its title, linked. */75const CommitLink = ({76 project,77 sha,78}: {
8 unmodified lines
87 {shortSha(sha)}88 </AppLink>89);90115/** Someone in a row's metadata, linked over the row's own link. */91const Person = ({ handle }: { readonly handle: ForkRef["handle"] }) => (92 <span className="relative z-10">93 <HandleLink handle={handle} />94 </span>95);96122/** A group of rows, or what it would hold said plainly when it holds none. */97const Group = ({98 children,99 counts,100 empty,
2 unmodified lines
103}: {104 readonly name: string;105 readonly counts?: string;106 readonly facts?: ReactNode;133 /** What the group would hold, when it holds nothing. */107 readonly empty?: string | undefined;108 readonly children: ReactNode;109}) => (110 <div className="flex min-w-0 flex-col gap-3">
9 unmodified lines
120 {empty === undefined ? null : <EmptyState title={empty} />}121 </div>122);123151/** main: where it stands, and that only a landing moves it. */124const MainRow = ({ refs }: { readonly refs: Refs }) => {125 const { landed, project } = refs;126127 return landed === undefined ? (
3 unmodified lines
131 ) : (132 <RowList label="main">133 <Row134 action={163 // At the top of the row, on the state word's line, not centred below it.135 <AppLink136 className={`text-ui shrink-0 self-start leading-6 font-medium ${META_LINK}`}137 to={treeHref(project, "main")}138 >
129 unmodified lines
268 title={fork.repo}269 />270);271301/** What an empty list of tags says: none at all, or none of one package. */272const noTags = (only: string | undefined) =>273 only === undefined ? "No tags." : `No tags for ${only}.`;274275const Facts = ({
24 unmodified lines
300 package: only,301 platformUrl,302 refs,303}: {334 /** The first tag this page lists. */304 readonly from?: number | undefined;336 /** The one package whose tags this page lists; all when none. */305 readonly package?: string | undefined;338 /** Where the project is cloned from. */306 readonly platformUrl: string;307 readonly refs: Refs;308}) => {309 const { forks, landed, project } = refs;
101 unmodified lines
modified:apps/web/src/features/code/repo-tree.tsx+6 added-47 removed
1/**2 * A project's files as a tree, drawn by `@pierre/trees`, in the UI's own3 * face: compact rows, plain grey icons, single-child folders flattened4 * into one row, the folders above the visible rows kept at the top as the5 * reader scrolls, and a filter above it. The current path is open, selected and in6 * view; when it changes (the reader moved to another file and the tree7 * stayed mounted), the tree follows.8 *9 * Choosing a file calls `onOpen`, which the page answers through the10 * router: the document is never reloaded, so the tree stays where it is.11 * On a commit's page the tree lists the changed files, open, each marked12 * A, M or D and with its `+n −m`.13 *14 * Only the browser loads this module (`client-tree.tsx`): the paths arrive15 * as plain strings and are prepared here.16 */1import { prepareFileTreeInput } from "@pierre/trees";2import type {3 FileTree,4 FileTreeDirectoryHandle,
12 unmodified lines
17import { treesOptions } from "./pierre.ts";1819export interface RepoTreeProps {20 readonly paths: readonly string[];37 /** The path the page shows, a file or a folder; none on a commit's page until one is chosen. */21 readonly current?: string | undefined;39 /** A file was chosen. */22 readonly onOpen: (path: string) => void;41 /** The files a commit changed, marked by how. */23 readonly status?: readonly GitStatusEntry[];43 /** What each changed file adds and removes, at its row's end. */24 readonly counts?: ReadonlyMap<string, Counts>;45 /** Every folder open from the start (a commit's few changed files). */25 readonly open?: boolean;26}2728const NO_STATUS: readonly GitStatusEntry[] = [];2951/**52 * The page's own row: its name set heavier than its neighbours'. A53 * flattened row (`src / parse`) mutes the folders it passes through and54 * keeps its last name in ink, so the name reads first.55 */30const TREE_CSS = [31 "[data-type='item'][aria-selected='true'] { font-weight: 600; color: var(--foreground); }",32 "[data-item-flattened-subitems] { color: var(--muted); }",33 "[data-item-flattened-subitem]:last-child { color: var(--foreground); }",34].join("\n");3562/** A folder's id in the tree: its path and a slash. */36const folderId = (path: string) => `${path}/`;3765/** What `current` opens: each folder above it, and itself when it is a folder. */38const openFor = (current: string | undefined) =>39 current === undefined || current === ""40 ? []41 : [...ancestorsOf(current), current].map(folderId);4271/** A changed file's `+n −m`, each part in the diff's own tint. */43const decorationOf = (counts: Counts): FileTreeRowDecoration => ({44 parts: [45 { color: "var(--diff-add-sign)", text: `+${counts.additions}` },75 // A no-break space: the row lays its parts out as boxes, where a76 // plain space between them collapses to nothing.46 // A no-break space: the row lays its parts out as boxes, where a plain47 // space collapses to nothing.48 { text: "\u00A0" },49 { color: "var(--diff-del-sign)", text: `−${counts.deletions}` },50 ],51 text: `+${counts.additions} −${counts.deletions}`,52 title: `${counts.additions} added, ${counts.deletions} removed`,53});5484/** The tree's options for `props`: its look, the page's path open and selected. */55export const treeOptionsFor = (56 props: Omit<RepoTreeProps, "onOpen">,57 preparedInput = prepareFileTreeInput(props.paths)58): FileTreeOptions => {
8 unmodified lines
67 initialExpandedPaths: openFor(current),68 initialExpansion: open ? "open" : "closed",69 initialSelectedPaths: current === undefined ? [] : [current],70 preparedInput,101 // The filter is a field above the tree (`filterTree`): a field inside102 // the tree's role would not be one of its rows to a screen reader.71 // A field inside the tree's role would not be one of its rows to a screen72 // reader.73 search: false,74 stickyFolders: true,105 // The selected row's fill is faint on paper: its name in ink at 600106 // says it too.75 unsafeCSS: TREE_CSS,76 };7778 if (counts !== undefined) {
6 unmodified lines
8586 return options;87};88121/**122 * Hand the page each file the reader chooses in `tree` (never a folder,123 * never the page's own file); the returned function stops.124 */89export const followChoices = (90 tree: Pick<FileTree, "getSelectedPaths" | "subscribe">,91 current: string | undefined,92 onOpen: (path: string) => void
5 unmodified lines
98 onOpen(path);99 }100 });101138/** Narrow `tree` to the paths that match `text`; an empty filter shows every path. */102export const filterTree = (tree: Pick<FileTree, "setSearch">, text: string) => {103 tree.setSearch(text.trim() === "" ? null : text);104};105143/** Whether a tree item is a folder, which opens. */106const isFolder = (item: FileTreeItemHandle): item is FileTreeDirectoryHandle =>107 item.isDirectory();108109export const RepoTree = (props: RepoTreeProps) => {110 const { current, onOpen } = props;111150 // The tree is made from its first options: the page keys it by project151 // and revision, so a new set of paths is a new tree.112 // Made from its first options: the page keys the tree by project and113 // revision.114 const preparedInput = useMemo(115 () => prepareFileTreeInput(props.paths),116 [props.paths]117 );
4 unmodified lines
122 () => followChoices(model, current, onOpen),123 [model, current, onOpen]124 );125164 // Follow the page: open the folders above its path, select it alone,165 // and bring it into view.126 useEffect(() => {127 if (current === undefined || current === "") {128 return;129 }
20 unmodified lines
150151 model.scrollToPath(current, { focus: false, offset: "nearest" });152 }, [model, current]);153194 // The tree scrolls inside itself, so it takes the height its box gives.154 return (155 <div className="flex h-full min-h-0 flex-col">156 <div className="shrink-0 px-3 pb-1.5">157 <Input
16 unmodified lines
modified:apps/web/src/features/code/rev.ts+2 added-15 removed
1/**2 * A revision as one segment of a code page's path3 * (`/$project/tree/$rev/$`): `main`, a 40-hex commit SHA, or a tag name.4 * A tag name may hold `/` and `@` (`@changesets/cli@2.27.1`), so it is5 * URL-encoded into one segment; `main` and a SHA encode to themselves.6 * Whether a revision names anything is the platform's to say (`readTree`7 * and the other code reads refuse with `UnknownRevision`).8 */1import { Rev } from "@repo/protocol/domain/code";2import { Option, Schema } from "effect";312/** `rev` as one path segment. */4/** A tag name may hold `/` and `@`, so it is encoded into one segment. */5export const revSegment = (rev: string): string => encodeURIComponent(rev);67const decodeSegment = Option.liftThrowable(decodeURIComponent);89const asRev = Schema.decodeUnknownOption(Rev);1019/**20 * The revision a path segment names: none for a segment that is not a21 * valid encoding (`%`) or not a revision at all (empty, too long). A22 * segment the router already decoded reads as itself.23 */11/** A segment the router already decoded reads as itself. */12export const revOf = (segment: string): Option.Option<string> =>13 Option.flatMap(decodeSegment(segment), asRev);1427/** The revision a page reads, beside its title: a commit by its short id. */15export const revLabel = (rev: string) =>16 /^[0-9a-f]{40}$/u.test(rev) ? rev.slice(0, 7) : rev;
modified:apps/web/src/features/code/server-code.tsx+5 added-24 removed
1/**2 * Code the server highlighted: Pierre's own host element, `diffs-container`,3 * whose shadow root the server sends as a declarative shadow root (a4 * `<template shadowrootmode="open">`), so the browser paints the5 * highlighted code with the document, before any script.6 *7 * The parser turns the template into the element's shadow root, so the8 * browser's render holds the same element with nothing in it: React9 * adopts it as it is, shadow root and all, until the page's drawing takes10 * its place. A page drawn in the browser alone (one reached by a link,11 * not loaded) has no drawing there, and shows `plain` instead, before it12 * paints.2 * The server sends the drawing's shadow root as a declarative shadow root, so3 * the browser paints it with the document. React adopts the host as it is,4 * shadow root and all, until the page's drawing takes its place.5 */6import { createElement, use, useCallback, useState } from "react";7import type { ReactNode } from "react";89import { NumberedLines } from "./numbered-lines.tsx";10import { fileDrawing, prerendersFile } from "./prerender.ts";1120/** Pierre's host element; its stylesheet and script come with the drawing. */12const HOST = "diffs-container";1323/** The drawing's HTML, in its shadow root; an empty host when there is none. */14const Prerendered = ({ html }: { readonly html: string | undefined }) =>15 createElement(16 HOST,17 { "data-prerendered": "" },
5 unmodified lines
23 shadowrootmode: "open",24 })25 );2637/** The server's drawing, kept as the document holds it; `plain` when it holds none. */27const Adopted = ({ plain }: { readonly plain: ReactNode }) => {28 const [kept, setKept] = useState(true);2941 // Read as the host mounts, before the page paints. The drawing's code,42 // not just a shadow root: once Pierre's element is defined (a page drawn43 // before), a new host gets an empty one at once.30 // Once Pierre's element is defined (a page drawn before), a new host gets an31 // empty shadow root at once, so check for the drawing's code.32 const adopt = useCallback((host: HTMLElement | null) => {33 if (34 host !== null &&35 (host.shadowRoot?.querySelector("pre") ?? null) === null
14 unmodified lines
50export const ServerCode = ({51 drawing,52 plain,53}: {66 /** The server's drawing (`prerender.ts`), settled before the page renders. */54 readonly drawing: () => Promise<string | undefined>;68 /** What the browser shows when the document did not bring the drawing. */55 readonly plain: ReactNode;56}) =>57 import.meta.env.SSR ? (58 <Prerendered html={use(drawing())} />59 ) : (60 <Adopted plain={plain} />61 );6277/**78 * A file as the server sends it, until the browser's drawing replaces it:79 * highlighted where the server highlights it (`prerendersFile`), else80 * numbered, anchored plain text.81 */63export const FileFallback = ({64 path,65 sha,66 text,
18 unmodified lines
modified:apps/web/src/features/code/soft-landing.ts-8 removed
1/**2 * What a code page's 404 carries when the path it named is missing at a3 * revision that exists: the platform's refusal (`UnknownPath`), and the4 * nearest folder above the path that does exist there, so the page lands5 * softly on that folder with the refusal's own words as its notice. Any6 * other refusal (no such project, revision or commit) travels alone, as7 * `Refusals`.8 */1import { TreeListing } from "@repo/protocol/domain/code";2import { ProjectName } from "@repo/protocol/ids";3import { Schema } from "effect";4
11 unmodified lines
modified:apps/web/src/features/code/tree-view.tsx-19 removed
1/**2 * One folder of a project at a revision. The tree in the rail is the3 * navigation; main lists the folder once, as rows: each entry's name (a4 * folder first, as `readTree` orders them), what last changed it (the ask5 * its landing answered, or the commit's subject) and how long ago, then6 * the folder's README below on the page's prose.7 *8 * What last changed each entry arrives after the page (`last`): its9 * column holds its place until then, so nothing moves.10 */1import type {2 CodeEntry,3 CommitView,4 FileView,
13 unmodified lines
18import { askOf } from "../why/rows.ts";19import { FileHeader } from "./file-header.tsx";20import { blobHref, commitsHref, treeHref } from "./paths.ts";2132/** Each kind of entry: its mark and the word a screen reader says for it. */22const kinds = Match.type<CodeEntry["type"]>().pipe(23 Match.when("tree", () => ({ icon: Folder, word: "Folder" })),24 Match.when("blob", () => ({ icon: File, word: "File" })),25 Match.when("symlink", () => ({ icon: FileSymlink, word: "Link" })),
3 unmodified lines
29 readonly icon: LucideIcon;30 readonly word: string;31};3244/** Where an entry's row links: a folder's page or a file's; a submodule's commit lives elsewhere. */33const entryHref = (project: ProjectName, rev: string, entry: CodeEntry) =>34 Match.value(entry.type).pipe(35 Match.when("tree", () => Option.some(treeHref(project, rev, entry.path))),36 Match.when("submodule", () => Option.none<string>()),37 Match.orElse(() => Option.some(blobHref(project, rev, entry.path)))38 );3952/** What last changed an entry, in a few words: the ask its landing answered or opened, or the commit's subject. */40const changeWords = (commit: CommitView) => {41 const linked =42 commit.landing === undefined43 ? undefined
8 unmodified lines
5253const LINK =54 "text-foreground no-underline outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:outline-2 focus-visible:after:-outline-offset-2 focus-visible:after:outline-ring focus-visible:after:outline-solid";5569/** One entry, one 40 px row: its mark, its name, what last changed it, and when. */56const EntryRow = ({57 entry,58 last,59 now,
43 unmodified lines
103 </li>104 );105};106121/** A folder's entries as rows, each linking its page at `rev` (a project's home lists its root so). */107export const EntriesTable = ({108 entries,109 project,110 rev,
12 unmodified lines
123export interface TreeViewProps {124 readonly listing: TreeListing;125 readonly project: ProjectName;126 readonly rev: string;142 /** The folder's README, read; absent when it has none. */127 readonly readme?: FileView | undefined;144 /** What last changed each entry, by path, once read. */128 readonly last?: ReadonlyMap<string, CommitView>;129 readonly now: DateTime.Utc;147 /** The Files button, below the shell's width. */130 readonly files?: ReactNode;149 /** A notice above the folder (the refusal a missing path landed here with). */131 readonly notice?: ReactNode;132}133134export const TreeView = ({
65 unmodified lines
modified:apps/web/src/features/code/warm.ts-12 removed
1/**2 * Highlighting a file before its page opens: when a pointer rests on a3 * link to a file, the router fetches the page's data ahead of the click4 * (its intent preload), and the file is then highlighted in the worker5 * pool, so the page draws it at once. Only a file under the highlighting6 * limit is warmed; past it the page draws plain text anyway. Loaded in the7 * browser only, on the first such hover.8 */1import { diffsOptions } from "./pierre.ts";2import { workerPool } from "./pool.tsx";312/**13 * Highlight `file` in the pool ahead of its page, keyed as the page will14 * draw it; settles once it has (at once for a file not warmed).15 */4export const warmFile = (file: {5 readonly path: string;6 readonly sha: string;7 readonly text?: string | undefined;
10 unmodified lines
modified:apps/web/src/features/decision/choices.tsx+2 added-22 removed
1/**2 * A decider's choices on one decision: one button per choice its subject3 * allows, each taken with one tap (there is no confirm and no undo, as the4 * platform has none), and under each, in a muted line, what the platform5 * then does. The default (what happens if nobody decides) is the outline6 * button, with the word "default" beside its name.7 *8 * Once taken, the record replaces the buttons: who chose what, when, the9 * note, and what it did, in the landed role only for a choice that made10 * something happen.11 */1import type { Choice, Decision } from "@repo/protocol/domain/decision";2import type { DateTime } from "effect";3import { Option } from "effect";4import { useId } from "react";
12 unmodified lines
17 takenWords,18 tookEffect,19} from "./subject.ts";2032/** Why a choice waits, and whether it waits on something that will come. */21export interface Held {22 readonly reason: string;23 readonly waiting: boolean;24}2538/** How the choices sit: two to a row (main, a phone's open row), or one under another (the inspector). */26export type ChoicesLayout = "grid" | "stack";2728const LAYOUTS = {29 grid: "grid grid-cols-2 gap-x-3 gap-y-3",
7 unmodified lines
37 layout = "grid",38 onChoose,39}: {40 readonly decision: Decision;54 /** A choice on its way: every button waits. */41 readonly busy: boolean;56 /** Why Accept waits, when it does (a proposal whose draft is not read yet). */42 readonly held?: Option.Option<Held>;43 readonly layout?: ChoicesLayout;44 readonly onChoose: (choice: Choice) => void;45}) => {
51 unmodified lines
97 </fieldset>98 );99};100116/** A choice taken, in one line: its word in its role, then what it did. */101export const TakenLine = ({102 choice,103 decision,104 stamp = false,105}: {106 readonly decision: Decision;107 readonly choice: Choice;124 /** Settle the mark once: the decider took it while the page was open. */108 readonly stamp?: boolean;109}) => {110 const effect = tookEffect(decision, choice);111
18 unmodified lines
130 </p>131 );132};133151/** The record of a taken decision: the line, then who, when and the note. */134export const DecisionRecord = ({135 decided,136 decision,137 now,
20 unmodified lines
158 )}159 </section>160);161180// Choices kept in sight while their decision is: on a phone, a bar fixed181// above the bottom bar (a bar that only stuck would stay below the screen182// while its decision starts low on the page), with main keeping room for183// it at its foot (`styles.css`); from a tablet's width, where they sit.162// Fixed, not sticky, on a phone: a bar that only stuck would stay below the163// screen while its decision starts low on the page.164export const stuckAboveBar = (node: ReactNode) => (165 <div166 className="border-rule bg-background tablet:static tablet:border-t-0 tablet:p-0 fixed inset-x-0 bottom-[calc(3.5rem+env(safe-area-inset-bottom))] z-[6] border-t px-4 py-2"167 data-choices-bar=""
4 unmodified lines
modified:apps/web/src/features/decision/decision-card.tsx+4 added-48 removed
1/**2 * One decision, as a decider takes it: when it expires and what happens if3 * nobody decides (the decision's own `default`), its evidence typed by its4 * subject, a note to keep with the choice, and the choices with what each5 * does. Once taken, the record replaces the choices. Today's inspector, a6 * phone's open row and the decision's own page each draw this one card.7 *8 * An `OpenProposal` holds Accept until its draft has been read, and while9 * the platform's agent is drafting it again: the draft is passed in, or10 * read from `showProposal` in the browser when it is not, so the server11 * never renders an Accept the browser might then hold.12 *13 * The subject's words follow GLOSSARY.md (ask, answer, landing, finish,14 * vouch). The default's word is the decision's `default` field as the15 * platform set it: the web keeps no table of defaults by subject.16 */1import type { Decide } from "@repo/protocol/contracts";2import { DecisionSubject } from "@repo/protocol/domain/decision";3import type { Choice, Decision } from "@repo/protocol/domain/decision";4import { DraftState } from "@repo/protocol/domain/proposal";
19 unmodified lines
24 describeDefault,25 describeSubject,26} from "./subject.ts";2744/** What a decider sends when they choose: the `decide` contract's payload, from its one schema. */28export type DecideInput = typeof Decide.payloadSchema.Type;2947/** Whether a decision opens a proposed ask. */30const opensAsk = DecisionSubject.isAnyOf(["OpenProposal"]);3150/** Whether a draft is still being written. */32const isDraftingNow = DraftState.isAnyOf(["Drafting"]);3353/**54 * Why Accept on a proposal waits, if it does: its draft not read yet, its55 * read failed, or the draft being written. Once read it may be accepted: a56 * ready draft, a want alone, or a failed round (which keeps an earlier57 * ready draft, or leaves the want alone).58 */34const acceptHeld = (read: DraftRead): Option.Option<Held> =>35 DraftRead.$match(read, {36 Read: ({ draft }) =>37 Option.exists(draft, isDraftingNow)
6 unmodified lines
44 : { reason: "Reading the draft…", waiting: true }45 ),46 });4773/** When it expires, and what happens if nobody decides. */48export const ExpiryLines = ({49 decision,50 now,51 soon,
27 unmodified lines
79 </p>80 </div>81);82109/** A note kept with the choice, behind a disclosure. */83const NoteField = ({84 note,85 onNote,86}: {
36 unmodified lines
123 readonly decision: Decision;124 readonly layout: ChoicesLayout;125}126154/** The choices on a proposal whose draft state was not passed: read from `showProposal`. */127/**128 * Read in the browser, so the server never renders an Accept the browser might129 * then hold.130 */131const ProposalChoices = ({132 proposal,133 ...props134}: ChoiceProps & { readonly proposal: ProposalId }) => {
9 unmodified lines
144 />145 );146};147172/**173 * What ends the card: the choices while the decision is open (a174 * proposal's held until its draft is read), the record once it is taken.175 */148const Ending = ({149 draft,150 now,151 stamp,
39 unmodified lines
191 />192 );193};194223/** How many files a finish's diff changes, when it carries one. */195export const finishFileCount = (decision: Decision): number | undefined =>196 Option.getOrUndefined(197 Option.map(patchOf(decision), (patch) => changedFiles(patch).length)198 );
14 unmodified lines
213}: {214 readonly decision: Decision;215 readonly now: DateTime.Utc;216 readonly onDecide: (input: DecideInput) => void;246 /** Whether it expires within the day (Today's `expiringSoon`). */217 readonly soon?: boolean;248 /** Whether a choice on it is on its way: its buttons wait. */218 readonly busy?: boolean;250 /** What a page shows after the evidence, before the note (a waiver's diff). */219 readonly children?: ReactNode;252 /**253 * Where the choices go: in place (the default), or handed to the page,254 * which puts them where they stay in sight (a phone's sticky bar).255 */220 readonly choices?: (node: ReactNode) => ReactNode;257 /** Whether it says when it expires and its default (off where the page says so already). */221 readonly expiry?: boolean;259 /** Whether a finish links to its own page, where its diff is (off on that page). */222 readonly finishLink?: boolean;223 readonly layout?: ChoicesLayout;262 /** Settle the record's mark once: the choice was taken while the page was open. */224 readonly stamp?: boolean;264 /**265 * For an `OpenProposal`, what has been read of the proposal's draft:266 * Accept waits until it is read, and while it is drafting. Read from267 * `showProposal` in the browser when not passed.268 */225 readonly draft?: DraftRead | undefined;226}) => {227 const [note, setNote] = useState("");228
46 unmodified lines
modified:apps/web/src/features/decision/decision-page.tsx-29 removed
1/**2 * One decision on its own page, every subject but a finish (which reads as3 * the code browser does, `features/finish/finish-view.tsx`). The title is4 * the subject in plain words; under it, when it expires, its default and5 * whose move it is. Main holds the evidence at the page's width (a6 * waiver's marker drawn at its line in the answer's diff, when the7 * decision carries the diff), a note, and the choices, each saying what8 * it does; on a phone the choices stay in a bar above the bottom bar.9 * The inspector holds the decision's own facts (its deciders, when it10 * opened and expires, its default), the ask or proposal it concerns, and,11 * for a posture change, the project's posture.12 *13 * Once taken, the record replaces the choices. Signed out, the page says14 * what a decision is and that its deciders take it on Today: no choices,15 * and nothing of its evidence.16 */1import { Brand } from "@repo/brand";2import type { Ask } from "@repo/protocol/domain/ask";3import { DecisionSubject } from "@repo/protocol/domain/decision";4import type { Decision } from "@repo/protocol/domain/decision";
33 unmodified lines
38const waives = DecisionSubject.isAnyOf(["Waiver"]);3940const finishes = DecisionSubject.isAnyOf(["Finish"]);4158/** No files: a decision that carries no diff. */42const NO_FILES: readonly PatchFile[] = [];4344const LINK = "decoration-rule underline hover:decoration-current";4563/** The trail to a decision: its project, Today, its id. */46const crumbsOf = (project: ProjectName, id: DecisionId) => [47 { label: project, to: `/${project}` },48 { label: "Today", to: "/today" },49 { label: id, mono: true },50];5170/** The decision's own facts: who decides it, when it opened and expires, its default. */52const DecisionFacts = ({53 decision,54 now,55 soon,
39 unmodified lines
95 </dl>96 </FactBlock>97);98118/** The ask a decision concerns: its want and its page. */99const AskFacts = ({ ask }: { readonly ask: Ask }) => (100 <FactBlock label="The ask">101 <p className="text-ui" data-said="">102 {ask.brief.want}
3 unmodified lines
106 </AppLink>107 </FactBlock>108);109130/** The proposal a decision would open: its want, who proposed it, its page. */110const ProposalFacts = ({ proposal }: { readonly proposal: Proposal }) => (111 <FactBlock label="The proposal">112 <p className="text-ui" data-said="">113 {proposal.want}
9 unmodified lines
123 </AppLink>124 </FactBlock>125);126148/** The waiver's marker drawn at its line, in the answer's diff of that file. */127export const WaiverDiff = ({128 decision,129 files,130}: {
27 unmodified lines
158 </section>159 );160};161184/** What a decision is, for a reader who does not decide it here. */162const ForAnyone = ({163 children,164 id,165 project,
22 unmodified lines
188export interface DecisionViewProps {189 readonly data: DecisionPageData;190 readonly onDecide: (input: DecideInput) => void;191 readonly busy?: boolean;215 /** The decision as the decider's choice left it, once taken here. */192 readonly taken?: Decision | undefined;217 /** The waiver's diff, parsed, when the decision carries one. */193 readonly files?: readonly PatchFile[];219 /** The page for a finish, when the decision is one (the route draws it whole). */194 readonly finish?: ReactNode;195 readonly here: string;222 /** What the reader's last choice came back with, when it failed: shown above the choices. */196 readonly failure?: ReactNode;197}198226/** A decision the reader may take, whole. */199const Found = ({200 busy,201 failure,202 files,
67 unmodified lines
270 </Workspace>271 );272};273302/** The page for a decision that cannot be shown whole, with why. */274const Apart = ({275 children,276 data,277}: {
72 unmodified lines
modified:apps/web/src/features/decision/evidence.tsx+3 added-32 removed
1import type { Evidence as Fact } from "@repo/protocol/domain/common";2// A decision's evidence, typed by what it is about: the commits a stray3// push moved between (each a link to its page), the proposal's draft and4// files, a ratchet's before and after, a waiver's marker at its line, a5// posture's from and to beside the ledger, the hosts a proxy may now reach,6// the item a stored value matched, the person a vouch admits, the answer a7// finish lands. Then whatever else the platform put on it, as label and8// value, the diff and the fork left to the finish.9//10// Every value that is code is mono; every link is the router's.2import { DecisionSubject } from "@repo/protocol/domain/decision";3import type { Decision } from "@repo/protocol/domain/decision";4import type { Posture } from "@repo/protocol/posture";5import { ArrowRight, FileDiff, FileText } from "lucide-react";
13 unmodified lines
1920const CODE = "text-mono font-mono [overflow-wrap:anywhere]";2122/**32 * Whether an evidence line holds a file: its label is a path (one word with33 * a slash or a dot, as the ask file under the config folder, or a check34 * at the root, `offset.test.ts`), where every other label is words.23 * A label that is a path: one word with a slash or a dot, where every other24 * label is words.25 */26const isFileFact = ({ label }: Fact) => /^\S*[./]\S*$/u.test(label);2728const opensAsk = DecisionSubject.isAnyOf(["OpenProposal"]);2940/** The files an `OpenProposal` decision holds, shown as code; none for any other subject. */30export const filesOf = (decision: Decision): readonly Fact[] =>31 opensAsk(decision.subject) ? decision.evidence.filter(isFileFact) : [];3244/** One fact: its label over (or beside) its value. */33const FactRow = ({34 children,35 label,36}: {37 readonly children: ReactNode;38 readonly label: string;39}) => (40 <div className="contents">53 {/* Sentence case, as every label on the page: the platform names some54 evidence in lower case ("answer"); the text stays the platform's. */}41 {/* Sentence case: the platform names some evidence in lower case. */}42 <dt className="text-label text-muted-foreground pt-0.5 first-letter:uppercase">43 {label}44 </dt>45 <dd className="text-ui mb-1.5 min-w-0 [overflow-wrap:anywhere] @lg:mb-0">
2 unmodified lines
48 </div>49);5051const FactList = ({ children }: { readonly children: ReactNode }) => (65 // Label beside value where the evidence has the width (main), label over66 // value where it has not (the inspector, a phone).52 <dl className="grid grid-cols-1 gap-x-4 gap-y-1.5 @lg:grid-cols-[minmax(7rem,auto)_1fr]">53 {children}54 </dl>55);5672/** A link to a page of the web, with its mark. */57const PageLink = ({58 children,59 icon: Icon,60 to,
10 unmodified lines
71 {children}72 </AppLink>73);7491/** A posture as a mark and its name, in its role. */75const PostureWord = ({ posture }: { readonly posture: Posture }) => (76 <span className="inline-flex items-center gap-1.5">77 <Mark look={POSTURE_MARKS[posture]} size="sm" />78 <code className={CODE}>{posture}</code>79 </span>80);8199/** From one value to another, the arrow hidden from a screen reader, which hears "to". */82const FromTo = ({83 from,84 to,85}: {
27 unmodified lines
113 {shortSha(sha)}114 </AppLink>115);116135/** The facts each subject carries in its own fields, typed. */117const SubjectFacts = ({ decision }: { readonly decision: Decision }) =>118 DecisionSubject.match(decision.subject, {119 Finish: ({ ask, head }) => (120 <FactList>
122 unmodified lines
243 </FactList>244 ),245 });246266/** A whole commit id in running evidence. */247const WHOLE_SHA = /\b[0-9a-f]{40}\b/u;248269/** `text` with each whole commit id cut to its first seven, whole in its title. */249const ShortShas = ({ text }: { readonly text: string }) =>250 text.split(/(?<sha>\b[0-9a-f]{40}\b)/u).map((part, index) =>251 WHOLE_SHA.test(part) ? (252 <code className={CODE} key={`${index}:${part}`} title={part}>
3 unmodified lines
256 part257 )258 );259281// The labels the subject's own facts already say (a waiver's escape, a282// ratchet's count), or the finish draws.260const SHOWN_ELSEWHERE: ReadonlySet<string> = new Set([261 PATCH_LABEL,262 FORK_LABEL,263 "escape",264 "ratchet",265]);266290/** The rest of what the platform put on the decision, as label and value. */267const OtherFacts = ({268 decision,269 files,270}: {
8 unmodified lines
279 <FactList>280 {facts.map(({ href, label, value }) => (281 <FactRow282 key={`${label}:${value}`}307 // Who pushed the answer, at which head: the subject's own row308 // is already the answer.283 label={label === "answer" ? "Pushed by" : label}284 >285 {href === undefined ? (286 <ShortShas text={value} />
7 unmodified lines
294 </FactList>295 );296};297324/** The way from a `Finish` decision to its answer's diff, with how many files it changes. */298export const FinishLink = ({299 decision,300 files,301}: {
8 unmodified lines
310 {files === undefined ? "" : ` (${files} ${files === 1 ? "file" : "files"})`}311 </PageLink>312);313341/** A decision's evidence: its subject's facts, the rest, and a proposal's files as code. */314export const DecisionEvidence = ({315 decision,316 heading = "h4",317}: {318 readonly decision: Decision;347 /** The heading level a proposal's file paths take. */319 readonly heading?: "h3" | "h4";320}) => {321 const files = filesOf(decision);322
15 unmodified lines
modified:apps/web/src/features/decision/read.ts+2 added-27 removed
1/**2 * What a decision's page reads, in a module with no view of its own: a3 * route's loader runs before its page's view loads, so the route reaches4 * these without carrying the page.5 *6 * The decision comes from the reader's Today in its project alone, read7 * with their own session: someone who decides nothing there gets why, and8 * no evidence. Beside it, what it concerns, each read on its own (one that9 * fails is left out): the ask, the proposal, the project's posture; for a10 * finish, the verdict on its head and, from the project's events, where11 * the answer's earlier rounds were refused and whether a newer head came.2 * Kept apart from the page's view: a route's loader runs before the view loads,3 * so the route reaches this without carrying the page.4 */5import { Client } from "@repo/protocol/contracts";6import { Verdict } from "@repo/protocol/domain/answer";7import { Ask } from "@repo/protocol/domain/ask";
10 unmodified lines
1819import { askStates } from "../shared/ask-progress.ts";20import { findDecision, readOfCause, TodayRead } from "../today/read.ts";2130/** A refusal from an answer's round that points at a line, as the page's loader sends it. */22export const Placed = Schema.Struct({23 line: Schema.Int,24 path: Schema.String,25 refusal: Refusal,26 round: Schema.Int,27});2838/** What the page read for its reader: the decision and what it concerns, or why there is none. */29export const DecisionRead = Schema.TaggedUnion({30 Found: {41 /** The ask it concerns, when it concerns one. */31 ask: Schema.optionalKey(Ask),32 decision: Decision,44 /** A head pushed to the answer after the one a finish names. */33 newerHead: Schema.optionalKey(CommitSha),46 /** Refusals from the answer's rounds that point at a line. */34 placed: Schema.Array(Placed),48 /** The project's posture, for a posture change. */35 posture: Schema.optionalKey(36 Schema.Struct({ label: Schema.String, posture: Posture })37 ),52 /** The proposal it would open, for an `OpenProposal`. */38 proposal: Schema.optionalKey(Proposal),39 soon: Schema.Boolean,55 /** The verdict on a finish's head. */40 verdict: Schema.optionalKey(Verdict),41 },42 NotOnToday: {},43 Refused: { refusal: Refusal },
4 unmodified lines
48export type DecisionRead = typeof DecisionRead.Type;4950export type FoundDecision = Extract<DecisionRead, { readonly _tag: "Found" }>;5168/** What a decision's loader sends: whose page, what it read, and when. */52export const DecisionPageData = Schema.Struct({53 decision: DecisionId,54 now: Schema.DateTimeUtcFromString,55 project: ProjectName,
1 unmodified line
57});5859export type DecisionPageData = typeof DecisionPageData.Type;6078/** The refusals among an outcome, when it refused. */61const refusalsOf = (outcome: Outcome): readonly Refusal[] =>62 Outcome.guards.Refused(outcome) ? outcome.refusals : [];6382/** Every refusal of an ask's rounds that points at a line, with the round it came from. */64const placedIn = (events: readonly ProjectEvent[], ask: AskId) =>65 (askStates(events).get(ask)?.rounds ?? []).flatMap(({ outcome }, index) =>66 refusalsOf(outcome).flatMap((refusal) =>67 refusal.at === undefined
8 unmodified lines
76 ]77 )78 );7999/** The head last pushed to `ask`, when it is not `head`. */80export const newerThan = (81 events: readonly ProjectEvent[],82 ask: AskId,83 head: CommitSha
2 unmodified lines
8687 return last === undefined || last === head ? undefined : last;88};89110/** The ask a subject concerns, when it concerns one. */90const askOf = DecisionSubject.match({91 Finish: ({ ask }) => Option.some(ask),92 OpenProposal: () => Option.none(),93 PostureChange: () => Option.none(),
4 unmodified lines
98 Vouch: () => Option.none(),99 Waiver: ({ ask }) => Option.some(ask),100});101123/** What a decision concerns, each read on its own: one that fails is left out. */102const concerning = (decision: Decision, soon: boolean) =>103 Effect.gen(function* () {104 const client = yield* Client;105 const { project, subject } = decision;
37 unmodified lines
143 Effect.orElseSucceed(() => Option.none())144 ),145 });146169 // A finish's rounds, from the project's events: where earlier rounds170 // were refused, and whether a newer head was pushed.147 const events = Option.isSome(finish)148 ? yield* Stream.runCollect(client.watch({ project, since: 0 })).pipe(149 Effect.map((all): readonly ProjectEvent[] => all),150 Effect.orElseSucceed((): readonly ProjectEvent[] => [])
33 unmodified lines
184 }),185 });186 });187212/** The decision for its page, and what it concerns, read with the reader's session. */188export const readDecision = (params: {189 readonly project: string;190 readonly decision: string;191}) =>
40 unmodified lines
modified:apps/web/src/features/decision/subject.ts+2 added-53 removed
1/**2 * What a decision is about and what each choice on it does, in words, with3 * no view of its own: Today's rows, the inspector, a decision's page and4 * its finish all say a subject the same way.5 *6 * - `describeSubject`: the subject as one plain sentence, the row's link.7 * - `allowedChoices`: the choices its deciders have, in its own words.8 * - `consequenceOf`: what the platform does once a choice is taken, one9 * line under each button, written from what the platform's code does for10 * that subject. Where a choice changes nothing anyone can see, the line11 * says so rather than promising something.12 *13 * Each table names every subject, so a new kind fails to compile until it14 * has its sentence, its choices and its lines.15 */1import { DecisionSubject } from "@repo/protocol/domain/decision";2import type { Choice, Decision } from "@repo/protocol/domain/decision";3import { DateTime, Match } from "effect";45const yesOrNo: readonly Choice[] = ["accept", "decline"];67/**23 * The choices a subject's deciders have: a stray push is adopted or24 * reverted, anything else accepted or declined. The platform reads `accept`25 * on a stray push as `adopt` too, but the page offers each subject its own26 * words only.8 * The platform reads `accept` on a stray push as `adopt` too, but the page9 * offers each subject its own words only.10 */11export const allowedChoices = DecisionSubject.match({12 Finish: () => yesOrNo,13 OpenProposal: () => yesOrNo,
7 unmodified lines
21});2223const short = (sha: string) => sha.slice(0, 7);2442/** A ref as people say it: `main` for `refs/heads/main`. */25export const refWords = (ref: string) => ref.replace(/^refs\/heads\//u, "");2645/** What a decision is about, in one plain sentence. */27export const describeSubject = DecisionSubject.match({28 Finish: ({ ask, head }) =>29 `Finish the passing answer to ${ask}, at ${short(head)}`,30 OpenProposal: ({ proposal }) => `Open the ask proposed in ${proposal}`,
11 unmodified lines
42 Waiver: ({ ask, at, marker, reason }) =>43 `Allow ${marker} at ${at.path}:${at.line} in the answer to ${ask}: ${reason}`,44});4565/** A subject's kind as a row's metadata names it. */46export const subjectKind = DecisionSubject.match({47 Finish: () => "finish",48 OpenProposal: () => "proposal",49 PostureChange: () => "posture change",
4 unmodified lines
54 Vouch: () => "vouch",55 Waiver: () => "waiver",56});5778/** What saying yes and saying no do, for one subject. */58interface Lines {59 readonly yes: string;60 readonly no: string;61}6284/** What the platform takes no step on: the choice is kept, and nothing else moves. */63const RECORDED =64 "Your choice is kept on the decision; the platform takes no other step on it.";6588/**89 * What each choice does, by subject, as the platform's code does it:90 *91 * - an accepted proposal opens its ask (its files land on main, decided by92 * the decider); a declined one closes;93 * - an accepted finish lands the answer at its head with the decider as94 * `Finished-by`; a declined one leaves it waiting;95 * - a waiver, a ratchet raise or a posture change holds an answer: yes lets96 * it go on with the decider as `Decided-by`, no refuses it with the97 * refusal the decision stood for;98 * - a stray push to main is adopted as a landing, or reverted by one, with99 * the decider as `Decided-by`; a push to another ref moves nothing;100 * - a vouch lands a line in the vouch file;101 * - a widened proxy or a stored value found in an answer is recorded, and102 * nothing else follows yet.103 */66const linesOf = (subject: DecisionSubject): Lines =>67 Match.value(subject).pipe(68 Match.tagsExhaustive({69 Finish: (): Lines => ({
34 unmodified lines
104 }),105 })106 );107146/** Whether a choice says yes, in any subject's words. */108const saysYes = {109 accept: true,110 adopt: true,111 decline: false,112 revert: false,113} as const satisfies Record<Choice, boolean>;114154/** What taking `choice` on `subject` does, in one line. */115export const consequenceOf = (116 subject: DecisionSubject,117 choice: Choice118): string => {
1 unmodified line
120121 return saysYes[choice] ? lines.yes : lines.no;122};123164/** Each choice as its button says it. */124export const choiceWords = {125 accept: "Accept",126 adopt: "Adopt",127 decline: "Decline",128 revert: "Revert",129} as const satisfies Record<Choice, string>;130172/** Each choice once taken. */131export const takenWords = {132 accept: "Accepted",133 adopt: "Adopted",134 decline: "Declined",135 revert: "Reverted",136} as const satisfies Record<Choice, string>;137180/**181 * Whether a taken choice made something happen: what lands, opens or is182 * put back is drawn in the landed role; a choice that leaves things as they183 * were is ink.184 */138export const tookEffect = (decision: Decision, choice: Choice): boolean =>139 saysYes[choice]140 ? consequenceOf(decision.subject, choice) !== RECORDED141 : DecisionSubject.guards.StrayPush(decision.subject) &&142 refWords(decision.subject.ref) === "main";143191/** An expiry as a decider reads it on any phone: weekday, date and time, in UTC. */144export const byWhen = (at: DateTime.Utc) =>145 `${DateTime.formatUtc(at, {146 day: "numeric",147 hour: "2-digit",
3 unmodified lines
151 month: "short",152 weekday: "short",153 })} UTC`;154203/** What happens when nobody decides in time: the decision's own default, and by when. */155export const describeDefault = (decision: Decision) =>156 `If nobody decides by ${byWhen(decision.expiresAt)}: ${decision.default}`;157207/** A decision's own page. */158export const decisionHref = (decision: Decision) =>159 `/${decision.project}/decisions/${decision.id}`;160211/** A decision's place in a Today that may hold several projects. */161export const decisionKey = ({ id, project }: Decision) => `${project}/${id}`;
modified:apps/web/src/features/docs/docs-view.tsx-10 removed
1/**2 * The docs on the web: the index, every page under Guides then Reference3 * with its summary, and one page, its Markdown under its title with the4 * pages listed in the inspector. Every word on them is `@repo/agent-kit`'s5 * (`docPages`); a view: pages in, markup out.6 */1import type { DocPage, DocPart } from "@repo/agent-kit/docs/index";23import { SiteMarkdown } from "../markdown/markdown.tsx";4import { AppLink } from "../shared/link.tsx";5import { docsPath } from "../shared/paths.ts";6import { Workspace } from "../shared/shell/workspace.tsx";7import { docsMarkdownPath } from "./head.ts";815/** Each part's heading, in the order the index shows them. */9const PARTS = [10 { part: "guide", title: "Guides" },11 { part: "reference", title: "Reference" },12] as const satisfies readonly { part: DocPart; title: string }[];1314const LINK =15 "decoration-rule hover:decoration-foreground underline underline-offset-4";1624/** Only the page itself is current. */17const EXACT = { exact: true, includeSearch: false } as const;1819export const DocsIndexView = ({20 pages,
25 unmodified lines
46 ))}47 </Workspace>48);4958/** The pages, for the inspector: the one being read is current. */50const Contents = ({ pages }: { readonly pages: readonly DocPage[] }) => (51 <nav aria-label="Docs">52 {PARTS.map(({ part, title }) => (53 <div className="mb-3" key={part}>
17 unmodified lines
71 ))}72 </nav>73);7484/** A page's Markdown past its title and summary, which the page head shows. */75const bodyOf = ({ markdown, summary, title }: DocPage) =>76 markdown.slice(`# ${title}\n\n${summary}\n\n`.length);7778export const DocsPageView = ({
27 unmodified lines
modified:apps/web/src/features/docs/head.ts+2 added-6 removed
1/**2 * What the docs' pages put in their head, in a module with no view of its3 * own: a route's `head` runs before its page's view loads, so the Markdown4 * renderer stays off every page's first load.2 * Kept apart from the view: a route's `head` runs before its page's view loads,3 * so the Markdown renderer stays off every page's first load.4 */5import type { DocEntry } from "@repo/agent-kit/docs/entries";67import { markdownAlternateLink } from "../front/markdown.ts";8import { pageHead } from "../shared/head.ts";9import { docsPath } from "../shared/paths.ts";1012/** Where a page's Markdown is. */11export const docsMarkdownPath = (slug: string) => `${docsPath(slug)}.md`;1215/** A page's head: its title, its summary, and its Markdown. */13export const docsHead = (page: DocEntry) => ({14 ...pageHead({ description: page.summary, title: page.title }),15 links: [markdownAlternateLink(docsMarkdownPath(page.slug))],16});1721/** The index's head. */18export const docsIndexHead = () =>19 pageHead({20 description: "Guides, and a reference read from the platform's schema.",21 title: "Docs",
1 unmodified line
modified:apps/web/src/features/env/env-page.tsx+2 added-43 removed
1/**2 * A project's env shape: every item its committed `.env.schema` declares,3 * parsed at the landed commit and never resolved (ADR 0009). The status4 * line counts the items and says who set the sensitive ones. Sensitive5 * items come first, each saying on its own line that it is sensitive and6 * who set its value and when (or that nobody has); then every item's type,7 * whether it is required, its `@proxy` hosts, tags, docs and description.8 * The inspector says where the schema was read and how a value is set.9 *10 * Never a value, and nothing that would take or show one: a value is set11 * only from a terminal (`setEnv` is RPC and CLI alone), so the page shows12 * that command line instead of a form. The placeholder unlanded code sees13 * is not shown either: it is not a value, but it reads like one.14 *15 * Props in, markup out: the route reads the env shape16 * (`src/client/env.ts`) and hands it here. (Lint keeps "shape" out of code17 * names, so the prop is the env schema's view: `schema`.)2 * Never a value, and nothing that would take or show one: `setEnv` is RPC and3 * CLI alone. Lint keeps "shape" out of code names, so the prop is `schema`.4 */5import { Brand } from "@repo/brand";6import type { EnvItem, EnvSchemaView } from "@repo/protocol/domain/env";7import type { ProjectName } from "@repo/protocol/ids";
12 unmodified lines
20import { AppLink } from "../shared/link.tsx";21import { Workspace } from "../shared/shell/workspace.tsx";22import { distanceInWords, When } from "../shared/time.tsx";2338/** Where varlock, whose `.env.schema` format this is, documents it. */24const VARLOCK = "https://varlock.dev";2526const LINK = "decoration-rule underline hover:decoration-current";27
5 unmodified lines
3334const plural = (count: number, one: string, many: string) =>35 `${count} ${count === 1 ? one : many}`;3652/**53 * When the env shape was read, at the latest: `now`, or the newest time a54 * value was set if that is later. The page keeps the `now` it was served55 * with while it reads the env shape again as values are set, and a value56 * that was set is never set in the future.57 */37const readAt = (schema: EnvSchemaView, now: DateTime.Utc) => {38 let latest = now;3940 for (const { value } of schema.items) {
4 unmodified lines
4546 return latest;47};4870/** The items, sensitive ones first; each kind in the schema's own order. */49const sensitiveFirst = (items: readonly EnvItem[]) => [50 ...items.filter(({ sensitive }) => sensitive),51 ...items.filter(({ sensitive }) => !sensitive),52];5376/** The newest value set among `items`, if any was. */54const newestSet = (items: readonly EnvItem[]) => {55 let newest: EnvItem["value"];5657 for (const { value } of items) {
8 unmodified lines
6667 return newest;68};6993/**94 * The sensitive items in words: "1 sensitive, set by ines-v 1 d ago",95 * "1 sensitive, not set", "3 sensitive: 2 set, latest by ines-v 1 d ago".96 */70const sensitiveWords = (items: readonly EnvItem[], now: DateTime.Utc) => {71 const sensitive = items.filter((item) => item.sensitive);72 const set = sensitive.filter(({ value }) => value !== undefined);73 const newest = newestSet(sensitive);
12 unmodified lines
86 ? `1 sensitive, set ${by}`87 : `${sensitive.length} sensitive: ${set.length} set, latest ${by}`;88};89117/** Whether `docs` is a web address, so a link to it can go nowhere else. */90const isWebAddress = (docs: string) => /^https?:\/\//iu.test(docs);9192const requiredWords = (required: EnvItem["required"]) => {93 if (required === "depends") {
2 unmodified lines
9697 return required ? "yes" : "no";98};99128/** The proxy's hosts, then what it is limited to: "sentry.io, only /api/**". */100const Proxy = ({101 proxy,102}: {103 readonly proxy: NonNullable<EnvItem["proxy"]>;
26 unmodified lines
130 ) : (131 <span className="[overflow-wrap:anywhere]">{docs}</span>132 );133163/** Who set a write-only value and when, or that nobody has; never the value. */134const Value = ({135 now,136 value,137}: {
8 unmodified lines
146 <When at={value.setAt} now={now} />147 </span>148 );149180/** The item's line: its key, then, for a sensitive one, the lock, the word and who set it. */150const ItemLine = ({151 item,152 now,153}: {
70 unmodified lines
224 </Definitions>225 </li>226);227259/** The caption that credits the format: "env shape: varlock's .env.schema format". */228const Caption = () => (229 <>230 env shape:{" "}231 <a className={LINK} href={VARLOCK} rel="noreferrer">
1 unmodified line
233 </a>234 </>235);236269/** One fact of where the schema was read, its label beside it. */237const Read = ({238 children,239 term,240}: {
7 unmodified lines
248 </dd>249 </div>250);251285/** How a decider sets a value: from a terminal, never here. */252const SetValueFacts = ({ project }: { readonly project: ProjectName }) => (253 <FactBlock label="Set a value">254 <p className="text-ui text-muted-foreground">255 A decider sets one from a terminal; nobody reads it back.
4 unmodified lines
260 />261 </FactBlock>262);263298/** The project's posture, once the list of projects has brought it. */264const PostureOf = ({265 posture,266 project,267}: {
53 unmodified lines
321 posture,322 schema,323}: {324 readonly now: DateTime.Utc;360 /** The project's posture, from the list of projects; it may come after the page. */325 readonly posture?: Posture | undefined;326 readonly schema: EnvSchemaView;327}) => {328 const { items } = schema;
23 unmodified lines
352 </Workspace>353 );354};355392/**393 * A project whose main has not landed yet: there is no landed394 * `.env.schema` to read, so there is no env shape, which is not the same as395 * no project.396 */356export const NothingLanded = ({357 project,358}: {359 readonly project: ProjectName;
8 unmodified lines
modified:apps/web/src/features/finish/annotation.tsx-11 removed
1/**2 * What a decider's diff marks under one of its lines: a refusal that3 * pointed there (in the rubric, its lines as `explain` printed them, the4 * round it came from), or a marker that waits on a decision (in ochre, the5 * marker and its reason). Compact, one block under the line, the same in6 * the server's plain diff and in the browser's drawing.7 */1import type { Refusal } from "@repo/protocol/refusal";2import { explain } from "@repo/protocol/render";3import { Hourglass, OctagonX, RotateCcw } from "lucide-react";412/** A refusal placed in a diff: its file and line, and the round it came from. */5export interface PlacedRefusal {6 readonly refusal: Refusal;7 readonly path: string;8 readonly line: number;17 /** The round it refused, counting from 1. */9 readonly round: number;10}1121/** A refusal under its line, as git printed it. */12export const RefusalNote = ({ placed }: { readonly placed: PlacedRefusal }) => {13 const [first = "", ...rest] = explain([placed.refusal]).filter(14 (line) => !line.startsWith(" at: ")15 );
31 unmodified lines
47 </div>48 );49};5061/** A marker that waits on a decider, under its line. */51export const MarkerNote = ({52 marker,53 reason,54}: {
18 unmodified lines
modified:apps/web/src/features/finish/files.ts-35 removed
1/**2 * The files a decision's diff changes, as its page draws them: parsed once3 * by the drawing's own parser (`@pierre/diffs`' `parsePatchFiles`), so the4 * server's plain text and the browser's drawing hold the same hunks; each5 * file's `+n −m`, its id for the read marks, and its part of the change.6 *7 * The order is a rule, never a model's: the ask's territory first, then8 * tests, then anything else, each part by path in the order a tree lists9 * them.10 *11 * A diff's lines are numbered from its hunk headers (a patch holds only12 * the hunks, not the whole files), so a refusal's `at` line finds the line13 * it names.14 *15 * No React and no DOM: the server's render and the browser's both read it.16 */1import { parsePatchFiles } from "@pierre/diffs";2import type { FileDiffMetadata } from "@pierre/diffs";3import type { ChangedFile } from "@repo/protocol/domain/code";4import { RepoPath } from "@repo/protocol/ids";
8 unmodified lines
13} from "../code/diff-model.ts";14import type { DrawnFile } from "../code/diff-model.ts";15import { fileBlocks, patchIdOf } from "./patch.ts";1633/** Which part of the change a file is in. */17export type Part = "territory" | "tests" | "other";1836/** A changed file as the finish page holds it. */19export interface PatchFile extends DrawnFile {20 readonly part: Part;39 /** This file's change, as an id: what a read mark is kept against. */21 readonly patchId: string;22}2324const STATUS = {
11 unmodified lines
36} as const satisfies Record<Part, number>;3738const decodePath = Schema.decodeUnknownOption(RepoPath);3959/** The part a path is in: the territory's, the tests', or the rest. */40export const partOf =41 (territory: readonly string[]) =>42 (path: string): Part => {43 if (isTestPath(path)) {
4 unmodified lines
48 ? "territory"49 : "other";50 };5172/** Whether a file's block holds no text lines to draw: git's binary notes. */52const isBinary = (block: string) =>53 /^(?:Binary files .* differ|GIT binary patch)$/mu.test(block);5476/**77 * The files `patch` changes, parsed and counted, territory first, then78 * tests, then the rest. `key` names the change, so the drawing caches each79 * file's highlighting once.80 */55export const patchFiles = (56 patch: string,57 territory: readonly string[],58 key: string
40 unmodified lines
99 treeOrder(a.file.path, b.file.path)100 );101};102129/** One numbered line of a patch, on its side. */103export interface PatchLine {104 readonly kind: "addition" | "context" | "deletion";132 /** Its number in the new file (context and additions) or the old one (deletions). */105 readonly number: number;106 readonly text: string;107}108137/** One row of a patch's unified view: a line, or the unchanged lines a hunk skips. */109export type PatchRow =110 | { readonly kind: "separator"; readonly lines: number }111 | PatchLine;112142/** A line as the diff stores it, without its line ending. */113const bare = (line: string | undefined) => (line ?? "").replace(/\r?\n$/u, "");114145/**146 * `diff` as unified rows, each line numbered from its hunk's header: a147 * context line and an addition by the new file, a deletion by the old.148 */115export const patchRows = (diff: FileDiffMetadata): readonly PatchRow[] => {116 const rows: PatchRow[] = [];117118 for (const hunk of diff.hunks) {
39 unmodified lines
158159 return rows;160};161196/** The new file's line numbers a diff draws: where an annotation at a line can sit. */162export const drawnLines = (diff: FileDiffMetadata): ReadonlySet<number> =>163 new Set(164 patchRows(diff).flatMap((row) =>165 row.kind === "addition" || row.kind === "context" ? [row.number] : []
2 unmodified lines
modified:apps/web/src/features/finish/finish-files-button.tsx+2 added-5 removed
1/**2 * The Files button on a finish's page below the shell's width, where the3 * rail is not drawn: it opens the changed files as a sheet from the left,4 * loaded on its first press. `import.meta.env.SSR` is `true` in the5 * Worker's build, so the Worker bundles none of the sheet.2 * `import.meta.env.SSR` is `true` in the Worker's build, so the Worker bundles3 * none of the sheet.4 */5import { FolderTree } from "lucide-react";6import { lazy, Suspense, useState } from "react";7
2 unmodified lines
10const Sheet = import.meta.env.SSR11 ? undefined12 : lazy(() => import("./finish-files-sheet.tsx"));1316/** The changed files below the shell's width: a Files button, and the list as a sheet, loaded on its first press. */14export const FinishFilesButton = () => {15 const [open, setOpen] = useState(false);1617 return (
20 unmodified lines
modified:apps/web/src/features/finish/finish-files-sheet.tsx-6 removed
1/**2 * A finish's changed files below the shell's width, as a sheet from the3 * left, loaded on the first press of Files (`finish-rail.tsx`). Choosing a4 * file moves the diff to it, and the sheet closes.5 */1import { Option } from "effect";23import { Sheet, SheetContent } from "../../components/ui/sheet.tsx";4import { FinishFiles, useFinish } from "./finish-rail-body.tsx";
12 unmodified lines
17 <SheetContent side="left" title="Changed files">18 <div19 className="flex h-full min-h-0 flex-col"20 onClick={(event) => {26 // A file chosen moves the diff to it: the sheet has done its work.21 if (22 event.target instanceof Element &&23 event.target.closest("a") !== null24 ) {
14 unmodified lines
modified:apps/web/src/features/finish/finish-files.tsx-11 removed
1/**2 * A finish's changed files as a list the rail (or, below the shell's3 * width, a sheet) holds: the ask's territory first, then tests, then the4 * rest, each a row with its change as a letter (A, M or D, in the diff's5 * tints), its path, its `+n −m`, whether this reader marked it read (a6 * muted check, the word for a screen reader) and whether a refusal pointed7 * into it (the refused cross). Choosing one scrolls the diff to it.8 */1import { Check, OctagonX } from "lucide-react";23import { diffAnchor } from "../code/paths.ts";4import { ChangeCounts } from "../code/plain-diff.tsx";
11 unmodified lines
16 territory: "In the territory",17 tests: "Tests",18} as const satisfies Record<Part, string>;1928/** A path as two parts: its name first, then its folder, muted, which gives way first. */20const PathWords = ({ path }: { readonly path: string }) => {21 const slash = path.lastIndexOf("/");2223 return (
15 unmodified lines
39 read,40 refused,41}: {42 readonly files: readonly PatchFile[];52 /** The page's own address, which each row adds its file's anchor to. */43 readonly href: string;44 readonly read: ReadonlySet<string>;45 readonly refused: ReadonlySet<string>;56 /** The file the diff stands at. */46 readonly current?: string | undefined;47}) => (48 <nav49 aria-label="Changed files"
75 unmodified lines
modified:apps/web/src/features/finish/finish-plain.tsx-16 removed
1/**2 * A decider's diff as plain text: what the server sends, and what a reader3 * sees until the browser has drawn the highlighted diff over it (or, on a4 * phone, the one file being read). It takes the code browser's measures5 * (a 44 px sticky file header, 13 px code on 20 px lines, the gutter, the6 * sign column, the diff's own tints), so the drawing arrives in place.7 *8 * Under a line it draws what the page puts there (a refusal that pointed9 * at it, a marker waiting on a decision); a note whose line the diff does10 * not show sits at the top of its file, saying which line it means.11 */1import { Option } from "effect";2import type { ReactNode } from "react";34import { diffAnchor } from "../code/paths.ts";
2 unmodified lines
7import type { PatchFile, PatchLine } from "./files.ts";8import { MarkRead } from "./mark-read.tsx";9import type { MarkedFile } from "./read-marks.ts";1022/** Something drawn under one line of one file. */11export interface LineNote {12 readonly path: string;13 readonly line: number;14 readonly node: ReactNode;
18 unmodified lines
3334const GUTTER =35 "border-background min-w-[calc(6ch+2px)] border-r-2 pr-[1ch] pl-[2ch] text-right tabular-nums select-none";3649/** The notes on one file: under a line it draws, and those it does not. */37const notesFor = (file: PatchFile, notes: readonly LineNote[]) => {38 const mine = notes.filter(({ path }) => path === file.file.path);3940 const shown = Option.match(file.diff, {
7 unmodified lines
48 elsewhere: mine.filter(({ line }) => !shown.has(line)),49 };50};5165/** One file's lines, with its notes under theirs. */52const Lines = ({53 file,54 notes,55}: {
69 unmodified lines
125 refused,126}: {127 readonly files: readonly PatchFile[];128 readonly notes: readonly LineNote[];143 /** The files this reader marked read; each header offers "Mark read" when given. */129 readonly read?: ReadonlySet<string> | undefined;130 readonly onMark?: ((file: MarkedFile, read: boolean) => void) | undefined;146 /** The files a refusal points into, marked in their headers. */131 readonly refused?: ReadonlySet<string> | undefined;132 readonly folded?: ReadonlySet<string> | undefined;133 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;134}) => (
59 unmodified lines
modified:apps/web/src/features/finish/finish-rail-body.tsx-12 removed
1/**2 * A finish's changed files, for the rail (`finish-rail.tsx`, which loads3 * this in the browser) and, below the shell's width, a sheet behind a4 * Files button in the diff's toolbar: territory first, each with its5 * change, its counts, this reader's read mark and the refused cross.6 *7 * Both read the page's own loader data (its match), so the list and the8 * diff come from one read, and the read marks from one store.9 */1import { DecisionSubject } from "@repo/protocol/domain/decision";2import { useLocation, useMatch } from "@tanstack/react-router";3import { Option, Schema } from "effect";4import { useMemo } from "react";
6 unmodified lines
11import { marksKey, useReadMarks } from "./read-marks.ts";1213const decode = Schema.decodeUnknownOption(DecisionPageData);1424/** The finish on the page, its files in order; none for any other page. */15export const useFinish = () => {16 const data: unknown = useMatch({17 from: "/$owner/$project/decisions/$decision",18 select: (match) => match.loaderData,
31 unmodified lines
50};5152export type Finish = Option.Option.Value<ReturnType<typeof useFinish>>;5364/** The finish's files, with this reader's marks and the file the diff stands at. */54export const FinishFiles = ({ finish }: { readonly finish: Finish }) => {55 const marked = useMemo(56 () =>57 finish.files.map(({ file, patchId }) => ({ patchId, path: file.path })),
30 unmodified lines
88 </>89 );90};91103/** The finish's changed files, in the rail's slot. */92export const FinishRailFiles = () =>93 Option.match(useFinish(), {94 onNone: () => null,95 onSome: (found) => <FinishFiles finish={found} />,
4 unmodified lines
modified:apps/web/src/features/finish/finish-rail.tsx+2 added-9 removed
1/**2 * The rail of a decision's page. A route's `staticData` loads with every3 * page, so this module stays light: it tells a finish from any other4 * decision by the shape of the page's data alone, holds the way back to5 * Today and to who decides for any other, and for a finish loads its6 * changed files in the browser7 * (`finish-rail-body.tsx`), with the list's place held until they come.2 * A route's `staticData` loads with every page, so this module stays light and3 * loads a finish's files in the browser.4 */5import { ClientOnly, useMatch } from "@tanstack/react-router";6import { Option, Schema } from "effect";7import { lazy, Suspense } from "react";89import { AppLink } from "../shared/link.tsx";10import { RailSlot } from "../shared/shell/rail-slot.tsx";1116/** A finish's page data, by its shape: found, and about a finish. */12const FinishPageData = Schema.Struct({13 read: Schema.TaggedStruct("Found", {14 decision: Schema.Struct({15 subject: Schema.TaggedStruct("Finish", {}),
2 unmodified lines
18});1920const isFinishPage = Schema.decodeUnknownOption(FinishPageData);2127/** A row of the slot, as the rail draws its rows. */22const ROW =23 "text-ui text-foreground hover:bg-surface mx-2 flex h-8 min-w-0 items-center px-2 no-underline transition-colors duration-[120ms] focus-visible:outline-offset-[-2px]";2425const Body = import.meta.env.SSR26 ? undefined27 : lazy(() => import("./finish-rail-body.tsx"));2835/** The list's place: its count line's height, until the list is drawn. */29const Placeholder = () => (30 <div aria-hidden="true" className="border-rule h-10 shrink-0 border-b" />31);32
43 unmodified lines
modified:apps/web/src/features/finish/finish-view.tsx+1 added-50 removed
1/**2 * A `Finish` decision's page: the one page where a decider reads an3 * answer's diff, laid out as the code browser is. The changed files sit in4 * the rail (territory first, then tests, then the rest); the diff fills5 * main, file by file under sticky headers, each with a "Mark read" button,6 * and a refusal from an earlier round sits under the line it pointed at.7 * The want, the verdict, the choices and the three lines that finish it8 * from a clone sit in the inspector from 1440 px; below that, the choices9 * stay in a bar at the foot of the diff. On a phone the page reads the10 * want, the verdict and the choices first, then the diff one file at a11 * time.12 *13 * The read marks are this browser's alone (`read-marks.ts`). A head pushed14 * to the answer while the page is open says so above the diff, and the15 * diff stays as it was until the reader reloads it.16 *17 * What the page reads from the decision's evidence: `patch`, the answer's18 * unified diff, and `fork`, the name of the answer's fork19 * (`<key>--<ask>--<handle>`), where a finish fetches the head and pushes20 * its commits. Without a patch the page shows the lines and no diff;21 * without a fork it names the fork by the claim fork's pattern and leaves22 * the answerer's handle for the decider to fill in. The web never calls23 * `finish` itself.24 */1/** The web never calls `finish` itself. */2import { Brand } from "@repo/brand";3import type { Verdict } from "@repo/protocol/domain/answer";4import type { Ask } from "@repo/protocol/domain/ask";5import type { ChangedFile } from "@repo/protocol/domain/code";
40 unmodified lines
46export type { FinishDecision } from "./patch.ts";4748const LINK = "decoration-rule underline hover:decoration-current";4973/** Where the answer's head lives: its fork's git URL on the platform. */50const remoteOf = (decision: FinishDecision, platformUrl: string) =>51 Arr.findFirst(decision.evidence, ({ label }) => label === FORK_LABEL).pipe(52 Option.map(53 ({ href, value }) => href ?? `${platformUrl}/${value.trim()}.git`
3 unmodified lines
57 `${platformUrl}/${decision.project}--${decision.subject.ask}--<answerer>.git`58 )59 );6085/** The three lines that take the answer's head into a clone, put the decider's commits on it, and finish it. */61export const finishLines = (62 decision: FinishDecision,63 platformUrl: string,64 verdict: Verdict | undefined
17 unmodified lines
82 },83 ] as const;84};85111/** The three finish lines, numbered, each under what it does. */86const FinishLines = ({87 decision,88 platformUrl,89 verdict,
18 unmodified lines
108 </p>109 </FactBlock>110);111138/** What the ask wants, in one paragraph, and the way to it. */112const WantFacts = ({ ask }: { readonly ask: Ask }) => (113 <FactBlock label="The ask wants">114 <p className="text-want font-normal" data-said="">115 {ask.brief.want}
3 unmodified lines
119 </AppLink>120 </FactBlock>121);122150/** The verdict on the head: its line, and the gate's stages in a strip. */123const VerdictFacts = ({ verdict }: { readonly verdict: Verdict }) => (124 <FactBlock label={`Verdict at ${shortSha(verdict.head)}`}>125 <div className="flex flex-col gap-2" data-outcome={verdict.outcome._tag}>126 <StatusLine
17 unmodified lines
144 readonly now: DateTime.Utc;145 readonly onDecide: (input: DecideInput) => void;146 readonly busy?: boolean;147 readonly soon?: boolean;176 /** The diff's files, territory first (`patchFiles`); none without a patch. */148 readonly files: readonly PatchFile[];178 /** Refusals from the answer's rounds that point into its files. */149 readonly placed?: readonly PlacedRefusal[];180 /** The head last pushed to the answer, when it is not the one decided on. */150 readonly newerHead?: CommitSha | undefined;182 /** The files this reader marked read. */151 readonly read?: ReadonlySet<string>;152 readonly onMark?: (file: MarkedFile, read: boolean) => void;153 readonly split?: boolean;154 readonly onSplit?: (split: boolean) => void;155 readonly folded?: ReadonlySet<string> | undefined;156 readonly onFold?: (path: string, folded: boolean) => void;157 readonly onFoldAll?: (folded: boolean) => void;190 /** Draw the diff in the browser over the plain text (the page does; a test reads the plain text). */158 readonly draw?: boolean;192 /** The Files button, below the shell's width. */159 readonly filesButton?: ReactNode;194 /** Settle the record's mark: the choice was taken while the page was open. */160 readonly stamp?: boolean;196 /** What the reader's last choice came back with, when it failed. */161 readonly failure?: ReactNode;162}163164const NO_FILES: ReadonlySet<string> = new Set();165166const NO_REFUSALS: readonly PlacedRefusal[] = [];167204/** No whole files: a decision's diff comes parsed from its patch. */168const NO_CHANGED: readonly ChangedFile[] = [];169207/** A file's state in its header: a refusal pointed into it, or this reader read it. */170const slotOf = (171 path: string,172 header: ReactNode,173 refused: ReadonlySet<string>,
5 unmodified lines
179180 return read.has(path) ? { header, path, status: "read" } : { header, path };181};182221/** The refusals among `placed`, as notes under their lines. */183const refusalNotes = (placed: readonly PlacedRefusal[]): readonly LineNote[] =>184 placed.map((each) => ({185 line: each.line,186 node: <RefusalNote placed={each} />,187 path: each.path,188 }));189229/** A head pushed after the one the decision names: said above the diff, never swapped in. */190const NewerHead = ({ head }: { readonly head: CommitSha }) => (191 <output192 className={`border-rule bg-surface flex flex-wrap items-center gap-x-3 gap-y-2 border-b py-2 ${GUTTER}`}193 data-newer-head={head}
15 unmodified lines
209 </Button>210 </output>211);212253/**254 * The choices kept at the foot of the diff below 1440 px, where the255 * inspector is a sheet; once taken, the choice's record in their place.256 */213const DecisionBar = ({214 busy,215 decision,216 now,
42 unmodified lines
259 )}260 </section>261);262307/** A choice that came back failed: said where the reader looks next, and politely. */263const Failure = ({264 children,265 className = "",266}: {
4 unmodified lines
271 {children}272 </div>273);274320/** On a phone: the diff one file at a time, with the way to the next and the one before. */275const OneFileAtATime = ({276 files,277 notes,278 onMark,
66 unmodified lines
345 </section>346 );347};348395/** The diff from a tablet's width: plain from the server, drawn over in the browser, the choices at its foot. */349const WideDiff = ({350 busy,351 decision,352 draw,
93 unmodified lines
446 </div>447 );448};449497/** On a phone: the want, the verdict and the choices first, then the diff a file at a time. */450const PhoneFinish = ({451 ask,452 busy,453 decision,
67 unmodified lines
521 )}522 </div>523);524573/** The inspector's facts: the want, the verdict, the decision, the lines that finish it, the diff's stats. */525const FinishFacts = ({526 ask,527 busy,528 decision,
138 unmodified lines
modified:apps/web/src/features/finish/mark-read.tsx-6 removed
1/**2 * A changed file's "Mark read" button, in its header: the word in sight3 * (never an icon alone), pressed once read, and the file's path for a4 * screen reader. A mark is this reader's alone (`read-marks.ts`).5 */1import { Check } from "lucide-react";23import type { PatchFile } from "./files.ts";4import type { MarkedFile } from "./read-marks.ts";511/** A file's "Mark read" button: its word in sight, and what it marks for a screen reader. */6export const MarkRead = ({7 file,8 onMark,9 read,
24 unmodified lines
modified:apps/web/src/features/finish/patch.ts+4 added-29 removed
1/**2 * The answer's diff, where a `Finish` decision carries it: the evidence3 * entry labelled `patch`, a unified diff (`git diff <base> <head>`). No other4 * decision carries one (`Decision.evidence` holds no diff unless5 * the kind allows a finish), and the web never fetches one another way.6 */1import { DecisionSubject } from "@repo/protocol/domain/decision";2import type { Decision } from "@repo/protocol/domain/decision";3import { Array as Arr, Option } from "effect";411/** The evidence label a `Finish` decision's diff travels under. */5export const PATCH_LABEL = "patch";614/** The evidence label naming the answer's fork, the repo a finish fetches from and pushes to. */7export const FORK_LABEL = "fork";817/** A decision whose subject is a finish. */9export type FinishDecision = Decision & {10 readonly subject: Extract<DecisionSubject, { readonly _tag: "Finish" }>;11};1213const finishes = DecisionSubject.isAnyOf(["Finish"]);1424/** Whether a decision is a finish: the one subject whose page shows a diff. */15export const isFinishDecision = (16 decision: Decision17): decision is FinishDecision => finishes(decision.subject);1829/** The diff a `Finish` decision carries, if it carries one; never another subject's. */19export const patchOf = (decision: Decision): Option.Option<string> =>20 isFinishDecision(decision)21 ? Option.map(22 Arr.findFirst(decision.evidence, ({ label }) => label === PATCH_LABEL),23 ({ value }) => value24 ).pipe(Option.filter((patch) => patch.trim().length > 0))25 : Option.none();2638// git ends a `---`/`+++` line with a tab when its path holds a space, and39// `diff -u` puts its timestamp after one: the path stops at the tab.27// git ends a `---`/`+++` line with a tab when its path holds a space, and `diff28// -u` puts its timestamp after one: the path stops at the tab.29const NEW_FILE = /^\+\+\+ (?:b\/)?(?<path>[^\t]+)(?:\t.*)?$/u;3031const OLD_FILE = /^--- (?:a\/)?(?<path>[^\t]+)(?:\t.*)?$/u;3233const RENAMED = /^rename to (?<path>.+)$/u;3435const HEADER = /^diff --git a\/.+ b\/(?<path>.+)$/u;3648/** One file's block of a unified diff: the path it ends up at (or the path it leaves). */37const pathOf = (block: readonly string[]): Option.Option<string> => {38 const first = (pattern: RegExp) =>39 Arr.findFirst(block, (line) => pattern.test(line)).pipe(40 Option.flatMap((line) =>
13 unmodified lines
54 Option.orElse(() => first(HEADER))55 );56};5770/** The text of each file's block of a unified diff, by the path it ends up at. */58export const fileBlocks = (patch: string): ReadonlyMap<string, string> => {59 const lines = patch.split("\n");60 const gitHeaders = lines.some((line) => HEADER.test(line));61
20 unmodified lines
82 )83 );84};8599/**100 * The files a unified diff changes, in its order: each `diff --git` block's101 * new path (its old path when the file is deleted). A diff without git's102 * headers counts as one block per `---`/`+++` pair.103 */86export const changedFiles = (patch: string): readonly string[] => [87 ...fileBlocks(patch).keys(),88];8990/**109 * A short, stable id for one file's change: a polynomial hash over its110 * block of the diff, kept under a 32-bit prime. A new head that changes111 * the file changes its id, so whatever was kept against the old one no112 * longer matches.91 * A new head that changes the file changes its id, so a mark kept against the92 * old one no longer matches.93 */94export const patchIdOf = (text: string): string => {95 let hash = 7;96
5 unmodified lines
102};103104const waives = DecisionSubject.isAnyOf(["Waiver"]);105126/**127 * The answer's diff a `Waiver` decision carries, when it carries one under128 * the same `patch` label a finish uses: the page draws the marker's file129 * from it, with the marker at its line.130 */106export const waiverPatchOf = (decision: Decision): Option.Option<string> =>107 waives(decision.subject)108 ? Option.map(109 Arr.findFirst(decision.evidence, ({ label }) => label === PATCH_LABEL),
3 unmodified lines
modified:apps/web/src/features/finish/read-marks.ts+3 added-25 removed
1/**2 * Which of a finish's files its reader has marked read: kept in this3 * browser alone, never sent anywhere, and about files, never a person. A4 * mark is kept against the decision, the file and that file's change (its5 * patch id), and the whole set against the answer's head: a new head6 * pushed to the answer clears them, and a file whose change differs reads7 * unread.8 *9 * The browser's storage may be missing, full or refused (a private window);10 * every read and write is tried, and a refused one keeps nothing, so the11 * page works the same with no marks.12 *13 * The rail and the diff both show the marks; a change made in one is told14 * to the other with an event on the window.2 * Kept in this browser alone, never sent anywhere. Storage may be missing, full3 * or refused (a private window), so every read and write is tried and a refused4 * one keeps nothing.5 */6import { Option, Result, Schema } from "effect";7import { useCallback, useEffect, useState } from "react";819/** What one decision's marks are kept as. */9const Kept = Schema.Struct({10 head: Schema.String,11 read: Schema.Record(Schema.String, Schema.String),12});1314const decodeKept = Schema.decodeUnknownOption(Schema.fromJsonString(Kept));1527/** Where one decision's marks are kept. */16export const marksKey = (project: string, decision: string) =>17 `finish.read:${project}/${decision}`;1831/** The event a change to the marks is told by. */19const CHANGED = "finish-read-marks";2034/** A file and its change, as a mark is kept against it. */21export interface MarkedFile {22 readonly path: string;23 readonly patchId: string;24}2540/** The paths marked read, at `head`, whose change is still the one marked. */26export const readMarks = (27 storage: Storage | undefined,28 key: string,29 head: string,
16 unmodified lines
46 : new Set(),47 });48};4965/** Mark `file` read or unread at `head`; marks kept at another head are dropped. A refused write keeps nothing. */50export const writeMark = (51 storage: Storage | undefined,52 key: string,53 head: string,
17 unmodified lines
7172 Result.try(() => storage?.setItem(key, JSON.stringify({ head, read: next })));73};7491/** The browser's storage, when there is one this page may use. */75const browserStorage = (): Storage | undefined =>76 Result.getOrUndefined(Result.try(() => globalThis.localStorage));7795/**96 * The marks on `files` at `head`, read once the page runs (the server97 * draws none), and the way to set one. Every view of the same decision98 * hears a change made in another.99 */78export const useReadMarks = (79 key: string,80 head: string,81 files: readonly MarkedFile[],
27 unmodified lines
modified:apps/web/src/features/front/facts.tsx+1 added-30 removed
1/**2 * The facts a list of asks shows beside it: with nothing selected on the3 * front page, where to start and every project with its posture; with an4 * ask selected (the front page and a project's home alike), that ask's5 * state, how to take it, where it may change things, its family and its6 * project's posture, and the way to its page.7 *8 * Only what the list read is needed to draw them; what the full ask adds9 * (its territory's paths, its check, its mentor) fills in once the browser10 * has read it, in a block of the same size.11 */1import { installCommand } from "@repo/agent-kit/install";2import { Brand } from "@repo/brand";3import type { Ask, AskListing } from "@repo/protocol/domain/ask";4import type { ProjectListing } from "@repo/protocol/domain/front-page";
16 unmodified lines
21import { StatusLine } from "../shared/status-line.tsx";2223const LINK = "decoration-rule underline hover:decoration-current";2436/** One numbered step: what it does, then its command. */25export const Step = ({26 command,27 label,28}: {
5 unmodified lines
34 <CommandLine command={command} numbered />35 </div>36);3750/** A link onward, at a block's foot. */38export const Onward = ({39 children,40 to,41}: {
8 unmodified lines
50 <ArrowRight aria-hidden="true" className="size-3.5" strokeWidth={1.75} />51 </AppLink>52);5367/** Where an agent reads the same thing: a server route, so a plain link. */54/** A server route, so a plain link. */55export const ForAgents = ({ href }: { readonly href: string }) => (56 <p className="text-ui text-muted-foreground border-rule border-t pt-3 first:border-t-0">57 For agents:{" "}58 <a className={`text-foreground text-mono font-mono ${LINK}`} href={href}>
1 unmodified line
60 </a>61 </p>62);6377/** The three ways in from the front page: the CLI, the asks it lists, a claim. */64export const StartHere = ({ webUrl }: { readonly webUrl: string }) => (65 <FactBlock label="Take an ask">66 <Step command={installCommand(webUrl)} label="Install the command line" />67 <Step command={`${Brand.cli} front`} label="List every open ask" />
4 unmodified lines
72 <ForAgents href="/llms.txt" />73 </FactBlock>74);7590/** A count and its noun: "1 open ask", "7 open asks". */76export const plural = (count: number, one: string, many: string) =>77 `${count} ${count === 1 ? one : many}`;7894/**95 * Every project the platform lists, by its open asks; bars until the list96 * arrives. Each project's posture is its group header's to say, once.97 */79export const ProjectsFacts = ({80 projects,81}: {82 readonly projects: readonly ProjectListing[] | undefined;
23 unmodified lines
106 </ul>107 </FactBlock>108 );109129/** Who may take an ask, from what its listing says (the full ask adds the mentor). */110const whoMayTake = (111 listing: AskListing,112 project: ProjectName,113 full: Ask | undefined
8 unmodified lines
122 ? "Held for people, not agents"123 : `Anyone vouched in ${project}, or with a record in its area`;124};125146/** A family the selected ask belongs to, as the page knows it. */126export interface SelectedFamily {127 readonly parent: Ask;128 readonly finale: AskId;129 readonly states: ReadonlyMap<AskId, AskProgress>;130}131153/** The selected ask's project posture, in the platform's words. */132export interface SelectedPosture {133 readonly label: string;134 readonly posture: Posture;135}136159/**160 * The selected ask: its state, how to take it (the claim numbered first),161 * where it may change things and what judges it, its family, its project's162 * posture, and its page.163 */137export const SelectedAskFacts = ({138 family,139 full,140 listing,
4 unmodified lines
145 takeable,146}: {147 readonly listing: AskListing;148 readonly project: ProjectName;176 /** Whether the viewer may take it (the front page knows); open and unheld when not known. */149 readonly takeable: boolean;178 /** The full ask, once the browser has read it. */150 readonly full: Ask | undefined;151 readonly progress: AskProgress | undefined;152 readonly family: SelectedFamily | undefined;153 readonly posture: SelectedPosture | undefined;
74 unmodified lines
modified:apps/web/src/features/front/families.ts+3 added-25 removed
1// Which listed asks form a family, read from the names a migrate ask's split2// gives its members: the platform opens a child per module as3// `<parent>-<module>` and a delete child as `<parent>-delete`, and the4// parent waits on all of them. A listing names no parent (the full ask does,5// one read away), so a family is read from what the list holds: an ask that6// waits on an ask named after it is a family's parent, and its members are7// the listed asks it waits on, and its delete child.8//9// An ask that waits on another not named after it (one fix after another)10// is no family: it stays a row of its own that reads as waiting.1// A listing names no parent, so a family is read from names: a split opens2// `<parent>-<module>` children and a `<parent>-delete` child, and the parent3// waits on all of them.4import type { AskListing } from "@repo/protocol/domain/ask";5import { AskId } from "@repo/protocol/ids";614/** One family, as a list holds it. */7export interface ListedFamily {8 readonly parent: AskId;17 /** Its members the list holds, in the list's order: the children still open, and the delete child. */9 readonly members: readonly AskId[];19 /** The delete child, which waits on every other child. */10 readonly finale: AskId;11}1223/** The delete child a split gives `parent`. */13export const finaleOf = (parent: AskId): AskId =>14 AskId.make(`${parent}-delete`);1527/** Whether `parent` waits on an ask named after it, as a split names its members. */16const isParent = ({ ask, blockedBy }: AskListing) =>17 blockedBy.some((blocker) => blocker.startsWith(`${ask}-`));1831/** Every family among `listings`, each at its parent's place in the list. */19export const familiesIn = (20 listings: readonly AskListing[]21): readonly ListedFamily[] =>22 listings.flatMap((parent) => {
14 unmodified lines
37 },38 ];39 });4054/** A list's item: an ask of its own, or a family drawn as one row. */41export type Arranged<L extends AskListing = AskListing> =42 | { readonly kind: "ask"; readonly listing: L }43 | {44 readonly kind: "family";
1 unmodified line
46 readonly members: readonly L[];47 readonly finale: AskId;48 };4964/**65 * `listings` as a list draws them: each family at its parent's place, its66 * members taken out of the list (they are drawn under the parent's fan),67 * every other ask where it was.68 */50export const arrange = <L extends AskListing>(51 listings: readonly L[]52): readonly Arranged<L>[] => {53 const families = familiesIn(listings);
23 unmodified lines
77 ];78 });79};80100// The listings with each ask's blockers cut to those still listed: an ask101// that landed has left the list, and nothing waits on it any more (as the102// front page's entries name only what they still wait on).81export const stillWaiting = <L extends AskListing>(listings: readonly L[]) => {82 const listed = new Set(listings.map(({ ask }) => ask));8384 return listings.map((listing) => ({
4 unmodified lines
modified:apps/web/src/features/front/filter.ts+2 added-26 removed
1/**2 * The front page's filter, read from its address3 * (`?kind=bug&take=open&project=datekit`), in a module with no view of its4 * own: the route decodes its search with it before the page's view loads.5 */1import { Reserve } from "@repo/protocol/domain/ask";2import type { FrontPageEntry } from "@repo/protocol/domain/front-page";3import { KindName, ProjectName } from "@repo/protocol/ids";4import { Option, Schema } from "effect";56import { ASKS_PATH } from "../shared/paths.ts";713/** Asks the viewer may take now: the one value `?take=` has. */8export const Take = Schema.Literal("open");910export type Take = typeof Take.Type;1118/**19 * What the front page is narrowed to: one kind; asks open to take, or held20 * for someone; one project.21 */12export interface FrontFilter {13 readonly kind?: KindName;14 readonly reserved?: Reserve;15 readonly take?: Take;16 readonly project?: ProjectName;17}1829/** A filter as an address may write it: a key set to `undefined` is no filter. */19export type FrontFilterInput = {20 readonly [Key in keyof FrontFilter]?: FrontFilter[Key] | undefined;21};22
4 unmodified lines
27const decodeTake = Schema.decodeUnknownOption(Take);2829const decodeProject = Schema.decodeUnknownOption(ProjectName);3042/** `{ [key]: value }` when there is a value, and nothing when there is none. */31const present = <A, B>(value: A | undefined, field: (a: A) => B) =>32 Option.match(Option.fromUndefinedOr(value), {33 onNone: () => ({}),34 onSome: field,35 });3649/** `input` with every key left undefined dropped. */37export const compact = (input: FrontFilterInput): FrontFilter => ({38 ...present(input.kind, (kind) => ({ kind })),39 ...present(input.project, (project) => ({ project })),40 ...present(input.reserved, (reserved) => ({ reserved })),41 ...present(input.take, (take) => ({ take })),42});4344/**58 * The filter in an address's search: each value that decodes is kept, and59 * one that does not is dropped, so a stale or mistyped link shows the whole60 * list rather than an error.45 * A value that does not decode is dropped, so a stale or mistyped link shows46 * the whole list rather than an error.47 */48export const readFilter = (search: {49 readonly kind?: unknown;50 readonly project?: unknown;
6 unmodified lines
57 reserved: Option.getOrUndefined(decodeReserve(search.reserved)),58 take: Option.getOrUndefined(decodeTake(search.take)),59 });6075/** The front page's address for `filter`, in one key order. */61export const frontPath = (filter: FrontFilterInput) => {62 const search = new URLSearchParams(63 (["kind", "take", "reserved", "project"] as const).flatMap((key) => {64 const value = filter[key];
4 unmodified lines
6970 return search === "" ? ASKS_PATH : `${ASKS_PATH}?${search}`;71};7288/** Whether `entry` passes every part of `filter`. */73export const passes = (filter: FrontFilter) => (entry: FrontPageEntry) =>74 (filter.kind === undefined || entry.ask.kind === filter.kind) &&75 (filter.reserved === undefined || entry.ask.reserve === filter.reserved) &&76 (filter.take === undefined || entry.takeable) &&77 (filter.project === undefined || entry.project === filter.project);7895/**96 * The entries `filter` keeps, the ones the viewer may take first; each group97 * keeps the order given (the platform's: newest ask first).98 */79export const filterEntries = (80 entries: readonly FrontPageEntry[],81 filter: FrontFilter82): readonly FrontPageEntry[] => {
4 unmodified lines
87 ...shown.filter(({ takeable }) => !takeable),88 ];89};90111/**112 * How many entries `filter` would keep with `part` set as given and the113 * rest of the filter as it is: the count beside each filter option.114 */91export const countWith = (92 entries: readonly FrontPageEntry[],93 filter: FrontFilter,94 part: FrontFilterInput
1 unmodified line
modified:apps/web/src/features/front/front-page.tsx+2 added-38 removed
1/**2 * The front page: the open asks of every project, grouped by project, the3 * ones the viewer may take first; a family drawn as one row with its fan;4 * a toolbar that narrows the list by kind, by who may take an ask and by5 * project; and beside it, where to start, or the selected ask's facts.6 * Props in, markup out: the route reads the entries, the families' parents7 * and their projects' events on the server, the list of projects in the8 * browser (it may arrive after the rows, and moves none of them), and9 * hands them here.10 *11 * Each project's posture is said once, on its group's header, from the12 * list of projects; a row says only its own state. The filter is a link13 * (`/asks?kind=bug&take=open`), so a filtered list is an address to share.14 */1import { Brand } from "@repo/brand";2import { Reserve } from "@repo/protocol/domain/ask";3import type { Ask } from "@repo/protocol/domain/ask";4import type { ProjectEvent } from "@repo/protocol/domain/event";
28 unmodified lines
33import { countWith, filterEntries, frontPath } from "./filter.ts";34import type { FrontFilter, FrontFilterInput } from "./filter.ts";35import { EXPLAINER } from "./head.ts";3651/** The list's count, as the context bar says it: "10 open asks, 8 open to take". */37export const frontCount = (shown: readonly FrontPageEntry[]) =>38 `${plural(shown.length, "open ask", "open asks")}, ${39 shown.filter(({ takeable }) => takeable).length40 } open to take`;
1 unmodified line
42export interface FrontPageProps {43 readonly entries: readonly FrontPageEntry[];44 readonly filter: FrontFilter;45 readonly now: DateTime.Utc;61 /** Each family's parent as the platform stores it: its children, all of them. */46 readonly parents: readonly Ask[];63 /** The events of each project that holds a family on the page. */47 readonly events: ReadonlyMap<ProjectName, readonly ProjectEvent[]>;65 /** The children that landed while the page was open, by project. */48 readonly stampsOf?: (project: ProjectName) => ReadonlySet<AskId>;67 /** Every project with its posture; none until the list arrives. */49 readonly projects: readonly ProjectListing[] | undefined;50 readonly platformUrl: string;51 readonly webUrl: string;71 /** The selected ask in full, once the browser has read it. */52 readonly selectedAsk?: Ask | undefined;53}5475/** The entries of each project, in the order its first entry comes. */55const byProject = (shown: readonly FrontPageEntry[]) => {56 const groups = new Map<ProjectName, FrontPageEntry[]>();5758 for (const entry of shown) {
2 unmodified lines
6162 return [...groups];63};6486/** One option of a filter: its words and its count, the current one marked. */65const FilterOption = ({66 count,67 current,68 label,
18 unmodified lines
87 </AppLink>88 </li>89);90113/** A filter's options, under its name for a screen reader. */91const Segment = ({92 children,93 label,94}: {
4 unmodified lines
99 {children}100 </ul>101);102126/** The kinds on the page, and the one filtered to, each once, by name. */103const kindsOf = (entries: readonly FrontPageEntry[], filter: FrontFilter) =>104 [105 ...new Set([106 ...entries.map(({ ask }) => ask.kind),107 ...(filter.kind === undefined ? [] : [filter.kind]),108 ]),109 ].toSorted();110135/** The projects on the page, and the one filtered to, each once, by name. */111const projectsOf = (entries: readonly FrontPageEntry[], filter: FrontFilter) =>112 [113 ...new Set([114 ...entries.map(({ project }) => project),
6 unmodified lines
121 people: "Held for people",122} as const satisfies Record<Reserve, string>;123124/**150 * The projects as a menu: a disclosure of links, so it opens and narrows151 * with no script. A new address closes it (its key is the filter's152 * project).125 * A disclosure of links, so it works with no script. Its key is the filter's126 * project, so a new address closes it.127 */128const ProjectMenu = ({129 entries,130 filter,
35 unmodified lines
166 </ul>167 </details>168);169196/** The toolbar: kind; open to take or held for newcomers; project. */170const Toolbar = ({171 entries,172 filter,173}: {
62 unmodified lines
236 </>237 );238};239267/**268 * The front page with no open ask: with no project yet, the command that269 * brings one; with projects, the command that opens an ask.270 */240const NoAsks = ({241 projects,242}: {243 readonly projects: readonly ProjectListing[] | undefined;
9 unmodified lines
253 title="No open asks on any project. A decider opens one from an ask file."254 />255 );256288/** A project's group of rows, as the page reads it. */257interface Group {258 readonly project: ProjectName;259 readonly entries: readonly FrontPageEntry[];260 readonly items: readonly Arranged[];261 readonly states: ReadonlyMap<AskId, AskProgress>;262}263296/** The row ids in the order the page shows them: what `j` and `k` walk. */264const rowIds = (groups: readonly Group[]) =>265 groups.flatMap(({ items }) =>266 items.map((item) =>267 item.kind === "ask" ? item.listing.ask : item.parent.ask268 )269 );270304/** A project's group: its header (name, posture once, counts), then its rows. */271const ProjectGroup = ({272 group,273 listing,274 now,
51 unmodified lines
326 const parent = parents.find(327 (ask) => ask.project === project && ask.id === item.parent.ask328 );329364 // A parent the platform did not give in full: its members stay rows.330 if (parent === undefined) {331 return [332 row(item.parent),333 ...item.members.map((member) => row(member)),
20 unmodified lines
354 </RowGroup>355 );356};357393/** The selected entry's facts, with its family when it is a member. */358const Selected = ({359 entry,360 full,361 parents,
159 unmodified lines
modified:apps/web/src/features/front/head.ts+2 added-12 removed
1/**2 * What the list pages put in their head and their first lines, in a module3 * with no view of its own: a route's `head` runs with the route, before its4 * page's view loads, so a view's imports (the Markdown renderer) stay out of5 * every page's first load.2 * Kept apart from the views: a route's `head` runs before its page's view3 * loads, so the Markdown renderer stays out of every page's first load.4 */58/** What an ask is, and how one lands: the page's one sentence. */6export const EXPLAINER =7 "Each ask is one change a project wants, with a check that fails on its main today. Claim one, make the check pass, and push: the gate lands it.";812/** A block that is no paragraph of prose: a heading, a quote, a table, a list, a fence, HTML, an image. */9const NOT_PROSE = /^(?:#|>|\||[-*+]\s|\d+[.)]\s|```|~~~|<|!\[|\[!\[)/u;1015/** A paragraph's inline Markdown as plain words: links and code as their text, emphasis dropped. */11const plainWords = (text: string) =>12 text13 .replaceAll(/!\[[^\]]*\]\([^)]*\)/gu, "")14 .replaceAll(/\[(?<label>[^\]]*)\]\([^)]*\)/gu, "$<label>")
4 unmodified lines
19 )20 .replaceAll(/\s+/gu, " ")21 .trim();2228/**29 * A README's first sentence, as plain words: the first paragraph of prose30 * (past its title, badges, quotes, tables and lists), to its first full31 * stop. None when the README opens with no paragraph of prose.32 */23export const ledeOf = (text: string): string | undefined => {24 const paragraph = text25 .split(/\n\s*\n/u)26 .map((block) => block.trim())
12 unmodified lines
modified:apps/web/src/features/front/markdown.ts-10 removed
1/**2 * A list page that also answers agents: the same URL gives the page to a3 * browser and Markdown to a request that asks for it (`Accept:4 * text/markdown`), so the answer varies by `Accept`, and the page names its5 * Markdown as an alternate, in its head and in a `Link` header.6 */78/** `response`, marked as one of several answers to its URL, chosen by `Accept`. */1export const variedByAccept = (response: Response): Response => {2 const headers = new Headers(response.headers);34 headers.set("vary", "Accept");56 return new Response(response.body, { headers, status: response.status });7};817/** The `Link` header naming `href` as the page's Markdown. */9export const markdownLink = (href: string) =>10 `<${href}>; rel="alternate"; type="text/markdown"`;1121/** The head's link naming `href` as the page's Markdown. */12export const markdownAlternateLink = (href: string) => ({13 href,14 rel: "alternate",15 type: "text/markdown",
1 unmodified line
modified:apps/web/src/features/front/stamps.ts+2 added-25 removed
1/**2 * Which landings an open page stamps: a child of a family that lands while3 * the page is open settles with the stamp, once, and a landing the page's4 * first read already held never does.5 *6 * The first read the page settles on sets `mountSeq` (the highest event7 * number it held); each later read stamps the asks it shows landed that the8 * read before did not, closed by an event after `mountSeq`9 * (`stampsFrom`). Whether the stream or a poll brought the later read, a10 * landing stamps once: the stamped set only grows, so a mark keeps its11 * stamp through every later render rather than settling again.12 */1import type { ProjectEvent } from "@repo/protocol/domain/event";2import type { AskId } from "@repo/protocol/ids";3import { useState } from "react";45import { askStates, lastSeq, stampsFrom } from "../shared/ask-progress.ts";6import type { AskProgress } from "../shared/ask-progress.ts";720/** What a page remembers between reads of one project's events. */8export interface StampMemory {22 /** The highest event number of the first read. */9 readonly mountSeq: number;24 /** Where each ask stood in the read before. */10 readonly previous: ReadonlyMap<AskId, AskProgress>;26 /** Every ask stamped so far. */11 readonly stamped: ReadonlySet<AskId>;12}1330/** The page's memory after one more read of `events`; the first read stamps nothing. */14export const stampStep = (15 memory: StampMemory | undefined,16 events: readonly ProjectEvent[]17): StampMemory => {
14 unmodified lines
32 : new Set([...memory.stamped, ...fresh]),33 };34};3553/** Each project's memory after one more read of each project's events. */36const stepAll = (37 memory: ReadonlyMap<string, StampMemory>,38 reads: ReadonlyMap<string, readonly ProjectEvent[]>39): ReadonlyMap<string, StampMemory> =>
3 unmodified lines
43 stampStep(memory.get(project), events),44 ])45 );4665/**66 * The asks each project's page should stamp, from its events as the page67 * reads them (a new map each time a read changes). A project's first read68 * stamps nothing.69 */47export const useStamps = (48 reads: ReadonlyMap<string, readonly ProjectEvent[]>49): ((project: string) => ReadonlySet<AskId>) => {50 const [seen, setSeen] = useState(reads);51 const [memory, setMemory] = useState(() => stepAll(new Map(), reads));5276 // A new read: step the memory now, in this render, as React's guide to77 // state from the previous render does, so the stamp draws with the read.53 // Step the memory in this render, as React's guide to state from the previous54 // render does, so the stamp draws with the read.55 let current = memory;5657 if (reads !== seen) {58 current = stepAll(memory, reads);
6 unmodified lines
modified:apps/web/src/features/home/home-page.tsx-21 removed
1/**2 * A signed-in reader's own page: their work (each claim, its ask's want and3 * where its answer stands, with the command that runs next); the decisions4 * waiting for them when they decide somewhere; the open asks they may take;5 * and the way to their record. No score and no count of credit (DESIGN.md).6 * Signed out, it says what the page is and how to sign in. A view: what the7 * server read, and the instant, in; markup out.8 */1import { Brand } from "@repo/brand";2import type { Today } from "@repo/protocol/domain/decision";3import type { FrontPageEntry } from "@repo/protocol/domain/front-page";4import { Outcome } from "@repo/protocol/domain/outcome";
42 unmodified lines
47 WORK_SHOWN,48} from "./read.ts";49import type { Work } from "./read.ts";5059/** What the page is, said to a reader who is not signed in. */51const WHAT_HOME_IS =52 "Home is your own page: the asks you hold and where each answer stands, the decisions waiting for you, and the asks you may take next.";5363/** The decisions the page lists; the rest are on Today. */54const DECISIONS_SHOWN = 5;5556const LINK =57 "decoration-rule hover:decoration-foreground font-medium underline underline-offset-4";5869/** A block's empty state, under its header like its rows would be. */59const Empty = (props: Parameters<typeof EmptyState>[0]) => (60 <li className="pt-3">61 <EmptyState {...props} />62 </li>63);6476/**77 * What runs next on a claim: a refusal's own `next`, or, while the claim78 * runs with nothing refused, its local check before a push.79 */65const nextOf = ({ answer, claim }: Work) => {66 if (answer !== undefined) {67 return Outcome.guards.Refused(answer.outcome)68 ? {
172 unmodified lines
241 {children}242 </RowGroup>243);244260/** A decider's waiting decisions, or that none waits. */245const Waiting = ({ today }: { readonly today: Today }) => {246 const waiting = today.decisions.length + today.overflow;247248 return (
9 unmodified lines
258 </DecisionsGroup>259 );260};261278/** The decisions block: a decider's waiting decisions; nothing for anyone else. */262const DecisionsBlock = ({ decisions }: { readonly decisions: Decisions }) =>263 Decisions.match(decisions, {264 Decides: ({ today }) => <Waiting today={today} />,265 NotDecider: () => null,
24 unmodified lines
290 Every open ask291 </AppLink>292);293311/** The asks block's empty state: none to take, or none came. */294const NoAsks = ({ title }: { readonly title: string }) => (295 <Empty command={`${Brand.cli} front`} onward={EVERY_ASK} title={title} />296);297316/** The asks the reader may take, or why none shows. */298const AskList = ({ asks }: { readonly asks: Takeable }) =>299 Takeable.match(asks, {300 Listed: ({ asks: listed }) =>301 listed.length === 0 ? (
15 unmodified lines
317 <AskList asks={asks} />318 </RowGroup>319);320340/** Who is signed in, the way to their record, and the way to import a repo. */321const Record = ({ handle }: { readonly handle: Handle }) => (322 <>323 Signed in as <HandleLink handle={handle} />.{" "}324 <AppLink className={LINK} to={personPath(handle)}>
26 unmodified lines
351 </div>352 </Workspace>353);354375/** Signed out: what the page is, the way in, and the command. */355const SignedOut = () => (356 <Workspace crumbs={[{ label: "Home" }]} title="Home">357 <div className="flex max-w-[70ch] flex-col items-start gap-3">358 <p className="text-body">{WHAT_HOME_IS}</p>
27 unmodified lines
modified:apps/web/src/features/home/read.ts-42 removed
1/**2 * What `/home` reads, in a module with no view of its own: a route's loader3 * runs before its page's view loads.4 *5 * - `HomeRead`: the reader's work (each claim from `status`, its ask's want6 * and its latest answer), their Today when they decide somewhere, the7 * open asks they may take (`frontPage`, read as them), or why there is8 * none of it.9 * - `readHome`: that read, made with whatever `Client` the caller gives10 * (the server's, carrying the reader's own session).11 */1import { Client } from "@repo/protocol/contracts";2import { AnswerView } from "@repo/protocol/domain/answer";3import { ClaimView } from "@repo/protocol/domain/claim";4import { Today } from "@repo/protocol/domain/decision";
13 unmodified lines
18} from "effect";1920import { isSignedOut } from "../today/read.ts";2133/** The asks the page lists: the first few the reader may take; the rest are at `/asks`. */22const ASKS_SHOWN = 8;2336/** The claims the page lists, running first, then the newest; the rest are in `status`. */24export const WORK_SHOWN = 10;2539/** How many reads of one kind the page makes at once. */26const AT_ONCE = 4;2742/** One claim of the reader's, its ask's want, and its latest answer. */28export const Work = Schema.Struct({29 answer: Schema.optionalKey(AnswerView),30 claim: ClaimView,46 /** Absent when the ask did not come: the row names it by its id. */31 want: Schema.optionalKey(Schema.NonEmptyString),32});3334export type Work = typeof Work.Type;3552/** The decisions block: the reader's Today, or why there is none. */36export const Decisions = Schema.TaggedUnion({37 Decides: { today: Today },38 NotDecider: {},39 Unreachable: {},40});4142export type Decisions = typeof Decisions.Type;4361/** The asks block: the first the reader may take, or that the list did not come. */44export const Takeable = Schema.TaggedUnion({45 Listed: { asks: Schema.Array(FrontPageEntry) },46 Unreachable: {},47});4849export type Takeable = typeof Takeable.Type;5069/** What the page read for its reader: their work, or why there is none. */51export const HomeRead = Schema.TaggedUnion({52 Read: {53 asks: Takeable,54 decisions: Decisions,55 handle: Handle,75 /** Every claim the reader holds, of which `work` is the first `WORK_SHOWN`. */56 held: Schema.Int,77 /** How many of those are still running. */57 running: Schema.Int,58 work: Schema.Array(Work),59 },60 SignedOut: {},
1 unmodified line
62});6364export type HomeRead = typeof HomeRead.Type;6587/** What the loader sends: the read, and the instant it was made. */66export const HomePageData = Schema.Struct({67 now: Schema.DateTimeUtcFromString,68 read: HomeRead,69});7071export type HomePageData = typeof HomePageData.Type;7295/** A claim still running: its holder's to push to. */73export const isRunning = (claim: ClaimView) =>74 claim.state === "live" || claim.state === "warned";7576const openedOrder = Order.mapInput(77 DateTime.Order,78 (claim: ClaimView) => claim.openedAt79);80104/** Running claims first, then the newest. */81const workOrder: Order.Order<ClaimView> = Order.combine(82 Order.mapInput(Order.Boolean, (claim: ClaimView) => !isRunning(claim)),83 Order.flip(openedOrder)84);
4 unmodified lines
89);9091const isNotDecider = Schema.is(NotDecider);92117/** Where a claim's ask lives: one key per (project, ask). */93export const askKey = ({ ask, project }: ClaimView) => `${project}/${ask}`;94120/**121 * The asks whose id the reader's claims hold in more than one project.122 * `status` names an answer's ask but not its project, so those asks' answers123 * are read again one project at a time.124 */95const sharedAsks = (claims: readonly ClaimView[]) =>96 new Set(97 Object.entries(Arr.groupBy(claims, ({ ask }) => ask)).flatMap(98 ([ask, holding]) =>99 new Set(holding.map(({ project }) => project)).size > 1 ? [ask] : []100 )101 );102133/** The reader's answers in each of `projects`; a project that did not answer gives none. */103const answersIn = (projects: readonly ProjectName[]) =>104 Effect.gen(function* () {105 const client = yield* Client;106
9 unmodified lines
116 )117 );118 });119151/** Each shown claim's ask's want, by `askKey`; an ask that did not come is left out. */120const wantsOf = (claims: readonly ClaimView[]) =>121 Effect.gen(function* () {122 const client = yield* Client;123 const asks = Arr.dedupeWith(claims, (a, b) => askKey(a) === askKey(b));
10 unmodified lines
134 ).pipe(Effect.map((found) => found.flat()))135 );136 });137170/** The claims the page lists: running first, then the newest, the first `WORK_SHOWN`. */138const shownOf = (claims: readonly ClaimView[]) =>139 Arr.sort(claims, workOrder).slice(0, WORK_SHOWN);140174/**175 * The reader's first claims, each with its want and its latest answer. An176 * answer belongs to the newest claim on its ask in its project; an older177 * claim on the same ask shows its own state. An ask whose id the reader178 * holds in two projects takes its answers from `again`, read per project.179 */141export const pairWork = ({142 again,143 answers,144 claims,
5 unmodified lines
150 readonly wants: ReadonlyMap<string, string>;151}): readonly Work[] => {152 const shared = sharedAsks(claims);153193 /** The claim each (project, ask) gives its answer to: the newest, set last. */154 const newest = new Map(155 Arr.sort(claims, openedOrder).map(156 (claim) => [askKey(claim), claim] as const157 )
27 unmodified lines
185 }),186 }));187};188229/** `pairWork` over what the platform answers: the wants, and answers read again where needed. */189const workOf = (claims: readonly ClaimView[], answers: readonly AnswerView[]) =>190 Effect.gen(function* () {191 const shown = shownOf(claims);192 const shared = sharedAsks(claims);
14 unmodified lines
207208 return pairWork({ again, answers, claims, wants });209 });210252/** The reader's home, or why there is none, encoded for the page. */211export const readHome = Effect.gen(function* () {212 const client = yield* Client;213214 const [status, today, front] = yield* Effect.all(
51 unmodified lines
modified:apps/web/src/features/import/client-owner.tsx-12 removed
1/**2 * The owner select, drawn in the browser only. The server renders its3 * stand-in: the trigger as it will look, holding the choice in sight and4 * in the form (a hidden input), never a native `<select>`; after5 * hydration the browser loads the kit's select over it6 * (`owner-select.tsx`), whose trigger takes the same `TRIGGER`.7 * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic8 * import below is dead code there and the Worker bundles none of it.9 */1import type { Owner } from "@repo/protocol/ids";2import { ClientOnly } from "@tanstack/react-router";3import { ChevronDown } from "lucide-react";4import { lazy, Suspense } from "react";56export interface OwnerSelectProps {16 /** The owners to choose from, the default first. */7 readonly choices: readonly Owner[];8 readonly labelledBy: string;9 readonly describedBy: string;10 readonly onChange: (value: Owner) => void;11 readonly value: Owner | undefined;12}1324/** The trigger's size, the kit's select and the stand-in alike. */14export const TRIGGER =15 "tablet:text-ui tablet:h-9 h-11 w-full max-w-sm text-base";1617const SelectLater = import.meta.env.SSR18 ? undefined19 : lazy(() => import("./owner-select.tsx"));2032/** The select's place before it is drawn: its trigger, showing the choice. */21const StandIn = ({ describedBy, labelledBy, value }: OwnerSelectProps) => (22 <>23 <button24 aria-describedby={describedBy}
30 unmodified lines
modified:apps/web/src/features/import/import-form.tsx-38 removed
1/**2 * The import form: a signed-in person pastes a public repo's HTTPS URL,3 * may name a branch, picks the owner and the name, and presses Import. The4 * owner and the name follow the URL until the person changes them: the5 * URL's source namespace (`github.com/pallets`) when its host is one the6 * platform knows, else their handle; the URL's last segment as the name.7 * At a source namespace's address the owner is the address's, fixed.8 * Signed out, it says what would be imported and links to sign-in, coming9 * back to `here`. Props in, markup out: the route reads who is signed in,10 * sends the payload, and goes to the project once it is made.11 *12 * Nothing is imported until Import is pressed; nothing here asks a host13 * anything.14 */1import { Brand } from "@repo/brand";2import type {3 Handle,4 Owner,
19 unmodified lines
24 prefillFrom,25} from "./prefill.ts";26import type { ImportPayload } from "./prefill.ts";2742/** What the form starts with: a URL, and the owner and name it gives. */28export interface ImportPrefill {29 readonly url: string;30 readonly owner?: SourceNamespace | undefined;31 readonly name?: ShortName | undefined;32}3349/** Who is importing, and what became of the last press. */34export interface Importer {51 /** The handle signed in in this browser; none signed out. */35 readonly handle: Option.Option<Handle>;53 /** Whether the browser is still learning who is signed in. */36 readonly checking?: boolean | undefined;55 /** Whether an import is on its way: the button waits. */37 readonly busy?: boolean | undefined;57 /** Sends the payload; the route goes to the project once it is made. */38 readonly onImport?: ((payload: ImportPayload) => void) | undefined;59 /** What the last import came back with, when it was refused. */39 readonly refusal?: ReactNode | undefined;40}4142export interface ImportFormProps extends Importer {43 readonly prefill?: ImportPrefill | undefined;65 /** The owner the address fixes, at a source namespace's address. */44 readonly fixedOwner?: SourceNamespace | undefined;67 /** The page's own address, where sign-in comes back to. */45 readonly here: string;46}4771/** The import as a command, for a reader in a terminal. */48export const importCommand = (project = "<owner>/<name>", url = "<url>") =>49 `${Brand.cli} init --project ${project} --import ${url}`;5051const LINK = "decoration-rule font-medium underline hover:decoration-current";5277/** A field's label and the words under it. */53const LABEL = "text-ui font-medium";5455const HINT = "text-label text-muted-foreground font-normal";5682/**83 * A text field in mono: 16 px on a phone, so it does not zoom on focus, and84 * without ligatures, as code shows what was typed (`://` stays three).85 */57const MONO_FIELD =58 "tablet:h-9 tablet:text-mono h-11 font-mono text-base [font-feature-settings:'calt'_0,'liga'_0]";5989/** What Import says, by where the form stands: why it waits, or what it does. */60const IMPORT_WORDS = {61 busy: "Importing…",62 noName: "Name the project",63 noOwner: "No owner you may import under",
2 unmodified lines
66} as const;6768type FormState = keyof typeof IMPORT_WORDS;69100/** Where the form stands: importing, waiting on a field, or ready. */70const formState = ({71 branch,72 busy,73 owner,
79 unmodified lines
153 </section>154 );155};156188/** The owner, fixed by the address: in sight, and in the form. */157const FixedOwner = ({158 hintId,159 owner,160}: {
7 unmodified lines
168 <input name="owner" type="hidden" value={owner} />169 </>170);171204/** What the hint under Owner says, by what may be chosen. */172const ownerHint = (fixed: boolean, choices: readonly Owner[]) => {173 if (fixed) {174 return "The address names it: the project keeps its source's account.";175 }
2 unmodified lines
178 ? "The URL's own account, or your handle."179 : "Your handle: this URL's host is not one a project may be owned by.";180};181215/** Under Name: the project's address once the name is one, else what a name is. */182const NameHint = ({183 payload,184}: {185 readonly payload: Option.Option<ImportPayload>;
73 unmodified lines
259 onChange={(event) => {260 setUrl(event.target.value);261 }}262 placeholder="https://github.com/pallets/click"297 // At a source namespace's address the URL is the address's own.263 readOnly={busy || fixedOwner !== undefined}264 required265 spellCheck={false}266 type="url"
76 unmodified lines
343 {refusal}344345 <div className="flex flex-col gap-2">346 <Button382 // Waiting for a URL or a name, it says so at full strength, dashed383 // like any field still to fill, rather than sitting grey.347 className={`tablet:h-9 tablet:w-fit h-11 w-full min-w-28 px-4 ${state === "ready" || state === "busy" ? "" : "text-muted-foreground border-dashed disabled:opacity-100"}`}348 data-state={state}349 disabled={state !== "ready"}350 type="submit"
13 unmodified lines
364 </form>365 );366};367405/** The form, the way to sign in, or the wait while the browser learns who is signed in. */368export const ImportForm = ({369 busy,370 checking = false,371 fixedOwner,
27 unmodified lines
modified:apps/web/src/features/import/import-offer.tsx-13 removed
1/**2 * The import a source namespace's address offers when nobody has made the3 * project (`/github.com/pallets/click`): the form prefilled with the URL4 * the address rebuilds (read-only), the owner fixed to the namespace, and5 * the name; signed out, the way to sign in. It never imports on its own.6 * The route draws it in place of the not-found when `offerFor` names the7 * address's project. Props in, markup out.8 */1import {2 isSourceNamespace,3 ownerOf,4 ProjectName,
7 unmodified lines
12import { sourceUrlOf } from "./prefill.ts";1314const decodeProject = Schema.decodeUnknownOption(ProjectName);1524/**25 * The project an address that names none offers to import: its name, when26 * its owner is a source namespace; none for a person's address and for27 * one that names no possible project.28 */16export const offerFor = (name: string): Option.Option<ProjectName> =>17 Option.filter(decodeProject(name), (project) =>18 isSourceNamespace(ownerOf(project))19 );
30 unmodified lines
modified:apps/web/src/features/import/import-page.tsx-12 removed
1/**2 * `/import`: the import form under the page's head, and beside it what an3 * import does and the same import as a command. A URL in the address4 * (`?url=`) fills the form. Props in, markup out: the route reads who is5 * signed in, sends the payload and goes to the project once it is made.6 */1import { CommandLine } from "../shared/command.tsx";2import { FactBlock } from "../shared/facts.tsx";3import { Workspace } from "../shared/shell/workspace.tsx";4import { ImportForm, importCommand } from "./import-form.tsx";5import type { Importer } from "./import-form.tsx";613/** What an import does, and the same import from a terminal. */7export const ImportFacts = () => (8 <>9 <FactBlock label="What an import does">10 <ul className="text-ui flex list-disc flex-col gap-1.5 pl-4">
18 unmodified lines
29 url = "",30 here,31 ...importer32}: Importer & {40 /** The URL the address carries, to fill the form with. */33 readonly url?: string | undefined;42 /** The page's own address, where sign-in comes back to. */34 readonly here: string;35}) => (45 // Below the shell's width the form comes first, and what an import does46 // follows it, rather than standing between the reader and the form.36 <div className="contents [&_[data-facts=inline]]:hidden">37 <Workspace38 crumbs={[{ label: "Import a repo" }]}39 facts={<ImportFacts />}
3 unmodified lines
43 >44 <ImportForm45 {...importer}46 here={here}58 // The name follows the URL until the person types one.47 prefill={url === "" ? undefined : { url }}48 />49 <div className="shell:hidden border-rule flex flex-col border-t pt-4">50 <ImportFacts />
4 unmodified lines
modified:apps/web/src/features/import/owner-select.tsx-9 removed
1/**2 * The owner an import is made under, chosen with the kit's select: the3 * URL's source namespace first when its host is one the platform knows,4 * then the person's handle. Drawn in the browser only (`client-owner.tsx`):5 * Base UI's select and its positioning are the browser's to run, and the6 * Worker bundles none of them.7 */1import {2 Select,3 SelectContent,4 SelectItem,
13 unmodified lines
18 <Select19 items={choices.map((choice) => ({ label: choice, value: choice }))}20 name="owner"21 onValueChange={(chosen) => {29 // The select hands back one of its items' values: find it, an owner.22 const owner = choices.find((choice) => choice === chosen);2324 if (owner !== undefined) {25 onChange(owner);
17 unmodified lines
43 </SelectContent>44 </Select>45);4655// `React.lazy` takes a module's default export.47export default OwnerSelect;
modified:apps/web/src/features/import/prefill.ts-33 removed
1/**2 * What the import form reads from a pasted URL, and what it sends. Pure:3 * no view, no transport. The owner is the URL's source namespace4 * (`github.com/pallets`) when its host is one the platform knows; the name5 * is the URL's last segment, without `.git`, lowercased. Nothing here asks6 * a host anything: the platform clones the URL when Import is pressed.7 */1import type { InitProject } from "@repo/protocol/contracts";2import { ImportSource } from "@repo/protocol/domain/policy";3import {4 Owner,
3 unmodified lines
8} from "@repo/protocol/ids";9import type { Handle, ProjectName, SourceNamespace } from "@repo/protocol/ids";10import { Array, Option, Schema } from "effect";1119/** What `initProject` takes, from its one schema. */12export type ImportPayload = typeof InitProject.payloadSchema.Type;1322/** What a URL prefills: the owner its host gives, and the name it ends in. */14export interface Prefill {15 readonly owner: Option.Option<SourceNamespace>;16 readonly name: Option.Option<ShortName>;17}1828// `https://<host>/<path>`: the path's last non-empty segment is the repo's.19const HTTPS_URL = /^https:\/\/[^/?#\s]+\/(?<path>[^?#\s]+)$/u;2021const decodeShortName = Schema.decodeUnknownOption(ShortName);2223const decodeOwner = Schema.decodeUnknownOption(Owner);2425const decodeSource = Schema.decodeUnknownOption(ImportSource);2637/** The name a URL ends in, without `.git` and lowercased; none when it is no name. */27const nameIn = (url: string): Option.Option<ShortName> => {28 const path = HTTPS_URL.exec(url.trim())?.groups?.path ?? "";29 const last = path.split("/").findLast((segment) => segment !== "") ?? "";3031 return decodeShortName(last.replace(/\.git$/u, "").toLowerCase());32};3345/** The owner and the name `url` prefills. */34export const prefillFrom = (url: string): Prefill => ({35 name: nameIn(url),36 owner: sourceNamespaceOf(url.trim()),37});3851/** A source namespace as an owner: every one is (a host is never a reserved word). */39export const ownerOfNamespace = (40 namespace: SourceNamespace41): Option.Option<Owner> => decodeOwner(namespace);4256/** A handle as an owner, lowercased; none for one no owner can spell. */43export const ownerOfHandle = (handle: Handle): Option.Option<Owner> =>44 decodeOwner(handle.toLowerCase());4560/**61 * The owners a person may import `url` under: the URL's source namespace62 * first when its host is one the platform knows (the default then), and63 * their own handle.64 */46export const ownerChoices = (47 handle: Option.Option<Handle>,48 url: string49): readonly Owner[] =>
1 unmodified line
51 ...Option.toArray(Option.flatMap(prefillFrom(url).owner, ownerOfNamespace)),52 ...Option.toArray(Option.flatMap(handle, ownerOfHandle)),53 ]);5474/**75 * The URL a source namespace's project was imported from:76 * `github.com/pallets/click` is `https://github.com/pallets/click`.77 */55export const sourceUrlOf = (project: ProjectName) => `https://${project}`;5680/**81 * The source the form names, as `initProject` takes it: the URL and the82 * branch trimmed, the branch only when named. None for a URL the contract83 * would refuse (no public HTTPS URL).84 */57export const importSourceOf = (form: {58 readonly url: string;59 readonly branch: string;60}): Option.Option<ImportSource> => {
2 unmodified lines
6364 return decodeSource(branch === "" ? { url } : { branch, url });65};6695/**96 * The form's fields as `initProject`'s payload: its source, and the97 * project the owner and the name make. None when the contract would refuse98 * the name or the URL before the platform ever read it.99 */67export const importPayload = (form: {68 readonly url: string;69 readonly branch: string;70 readonly owner: Owner;
8 unmodified lines
modified:apps/web/src/features/import/use-importer.tsx-20 removed
1/**2 * The import form's wiring, for the two pages that draw it (`/import` and3 * a source namespace's address nobody has made): who is signed in, read in4 * the browser; `importAtom`, sent only when Import is pressed; the move to5 * the project once it is made; and a refusal, drawn as the platform gave6 * it, under the form.7 */1import { useAtom, useAtomValue } from "@effect/atom-react";2import { ownerOf } from "@repo/protocol/ids";3import type { ProjectName } from "@repo/protocol/ids";4import { useLocation, useNavigate, useRouter } from "@tanstack/react-router";
6 unmodified lines
11import { whoAtom } from "../auth/who.ts";12import { ProposalFailure } from "../proposal/failure.tsx";13import type { Importer } from "./import-form.tsx";1422/**23 * Where an import that made `made` goes from a page at `at`: nowhere when24 * it is the project this address names (its page reads it again), else to25 * the project's page.26 */15export const afterImport = (made: ProjectName, at?: ProjectName) =>16 made === at17 ? Option.none()18 : Option.some({19 params: { owner: ownerOf(made), project: made },20 to: "/$owner/$project" as const,21 });2235/**36 * Who is importing and what became of the last press. `at` is the project37 * this page's address names, if any: a project made there is read again38 * where it stands; any other is gone to.39 */23export const useImporter = (at?: ProjectName): Importer => {24 const navigate = useNavigate();25 const router = useRouter();26 const here = useLocation({ select: hereOf });27 const who = useAtomValue(whoAtom);28 const [imported, send] = useAtom(importAtom);46 // Set once this page sends: a project the atom still holds from an47 // earlier visit never moves the page.29 const [sent, setSent] = useState(false);30 const made = sent ? Option.getOrUndefined(importMade(imported)) : undefined;3132 useEffect(() => {
1 unmodified line
34 return;35 }3637 Option.match(afterImport(made, at), {57 // The loader read this address as no project: it reads it again.38 onNone: () => {39 void router.invalidate();40 },41 onSome: (to) => {
20 unmodified lines
modified:apps/web/src/features/landing/landing-page.tsx-24 removed
1/**2 * The landing: what the platform is, said once, and the way to the open3 * asks first. Its evidence is the screen `git push` prints when the gate4 * refuses, set as git sets it, not a picture of one. Every sentence on it is5 * the README's or the glossary's. A view: the platform's address, the web's6 * own and the projects in; markup out.7 */1import { installCommand } from "@repo/agent-kit/install";2import { Brand } from "@repo/brand";3import type { ReactNode } from "react";4
16 unmodified lines
21import { LandingProjects } from "./projects.ts";22import { pushTranscript } from "./transcript.ts";23import { LEDE, WHAT_IT_IS } from "./words.ts";2432/** A link in a plain row (the top, the foot): ink, underlined only on hover. */25const ROW_LINK = "no-underline hover:underline";2635/** The primary action: an ink button that is a link. */27const PRIMARY = buttonVariants({ className: "no-underline" });2838/** Where an agent's reference is. */29const AGENTS_PATH = "/agents";3041/** Text git prints or takes, inside a sentence. */31const Code = ({ children }: { readonly children: ReactNode }) => (32 <code className={ID}>{children}</code>33);3446/** The branch's name, as git takes it. */35const MAIN = "main";3649/** The lede, its one branch name set as git takes it. */37const Lede = () => {38 const [before, after] = LEDE.split(MAIN);3940 return (
4 unmodified lines
45 </>46 );47};4862/** One part of the page under its name, parted from the last by a hairline. */49const Part = ({50 children,51 id,52 title,
12 unmodified lines
65 {children}66 </section>67);6883/** A noun a contributor meets, and what GLOSSARY.md says it is. */69interface Noun {70 readonly noun: string;71 readonly means: ReactNode;72}7389/** The four nouns, in the glossary's words. */74const NOUNS: readonly Noun[] = [75 {76 means: (77 <>
19 unmodified lines
97 noun: "Refusal",98 },99];100117/** The core loop, in the README's six lines. */101const LOOP: readonly ReactNode[] = [102 <>103 A decider opens an ask; <Code>{`${Brand.cli} ask open`}</Code> lands it only104 once its check fails on <Code>main</Code> twice the same way, by an
17 unmodified lines
122 every person, or answers with a refusal.123 </>,124];125143/** One thing a platform can do that a setting cannot: the README's lead, and its words. */126interface Power {127 readonly lead: string;128 readonly says: ReactNode;129}130149/** What a platform can do that a setting on a code host cannot, in the README's words. */131const POWERS: readonly Power[] = [132 {133 lead: "Judge with checks the answer cannot touch.",134 says: (
34 unmodified lines
169 ),170 },171];172192/** The wordmark and the ways in, as a plain row. */173const Top = () => (174 <header className="border-rule flex flex-wrap items-center justify-between gap-x-6 gap-y-2 border-b py-4">175 <AppLink className="text-want font-semibold no-underline" to="/">176 {Brand.name}
14 unmodified lines
191 </nav>192 </header>193);194215/** A line of the screen, with the refusal's tag in the refused colour wherever git names it. */195const Printed = ({196 tag,197 text,198}: {
17 unmodified lines
216 </>217 );218};219241/** The push, and what git prints back when the gate refuses it. */220const Transcript = ({ platformUrl }: { readonly platformUrl: string }) => {221 const { command, lines, tag } = pushTranscript(platformUrl);222223 return (
22 unmodified lines
246 </figure>247 );248};249272/** The projects on the platform, each with its posture, or that the list did not come. */250const Projects = ({ projects }: { readonly projects: LandingProjects }) =>251 LandingProjects.match(projects, {252 Listed: ({ projects: listed }) => (253 <ul className="flex flex-col">
16 unmodified lines
270 ),271 Unreachable: () => <UnreachableNotice />,272 });273297/** The landing, as everyone reads it. */274export const LandingView = ({275 platformUrl,276 projects,277 webUrl,
100 unmodified lines
modified:apps/web/src/features/landing/projects.ts-7 removed
1/**2 * The landing's projects block: the eight that lead (the most open asks3 * first, a tie by name), or that the list did not come. The read that4 * fills it is `read.ts`'s.5 */1import { ProjectListing } from "@repo/protocol/domain/front-page";2import { Schema } from "effect";34import { leadingProjects, PROJECTS_SHOWN } from "../shared/project-order.ts";511/** The projects block: the ones that lead, or that the list did not come. */6export const LandingProjects = Schema.TaggedUnion({7 Listed: { projects: Schema.Array(ProjectListing) },8 Unreachable: {},9});1011export type LandingProjects = typeof LandingProjects.Type;1219/** The block from a list that came: the eight that lead. */13export const listedProjects = (14 projects: readonly ProjectListing[]15): LandingProjects =>16 LandingProjects.cases.Listed.make({
2 unmodified lines
modified:apps/web/src/features/landing/read.ts+2 added-9 removed
1/**2 * The landing's read on the server, as nobody, by the route's loader: the3 * platform's project list, so the page arrives with its projects for every4 * reader (a crawler and a reader with no script included) and the edge may5 * keep it. The list ignores the caller, so nobody's read is everyone's.2 * The list ignores the caller, so nobody's read is everyone's and the edge may3 * keep it.4 */5import { Client } from "@repo/protocol/contracts";6import { Effect } from "effect";78import { LandingProjects, listedProjects } from "./projects.ts";912/**13 * The first few projects, or, when the platform did not answer (a refusal,14 * or a call that died on the way), the block that says so. It never fails:15 * the page leads to the asks either way.16 */10export const readLandingProjects: Effect.Effect<11 LandingProjects,12 never,13 Client
10 unmodified lines
modified:apps/web/src/features/landing/transcript.ts+3 added-11 removed
1/**2 * The landing's evidence: the screen `git push` prints when an answer3 * strays outside its ask's territory, as the platform's gateway writes it.4 * The refusal's lines come from the one renderer (`explain`, `headline`),5 * so they cannot drift from what the gateway sends; git's own lines around6 * them (`To`, `! [remote rejected]`, `error:`) and the fork are the README's7 * screen, which `apps/platform/test/core-loop.test.ts` asserts from real8 * git.2 * The refusal's lines come from the one renderer, so they cannot drift from3 * what the gateway sends; git's own lines around them are what4 * `apps/platform/test/core-loop.test.ts` asserts from real git.5 */6import { RepoPath } from "@repo/protocol/ids";7import { OutOfScope } from "@repo/protocol/refusal";8import { explain, headline } from "@repo/protocol/render";914/** The fork the push goes to: datekit's `parse-iso`, claimed by alice. */10const FORK = "datekit--parse-iso--alice.git";1112const refusals = [13 new OutOfScope({ paths: [RepoPath.make("README.md")] }),14] as const;1521/** One line of the screen, and whether git printed it as the platform's (`remote:`). */16export interface TranscriptLine {17 readonly text: string;18 readonly remote: boolean;19}2027/** The push and what git prints back, against the platform at `platformUrl`. */21export const pushTranscript = (platformUrl: string) => {22 const remote = `${platformUrl.replace(/\/+$/u, "")}/${FORK}`;23 const tag = headline(refusals);2425 return {26 command: "git push",34 /** The refusal's tag, which the page sets in the refused colour. */27 tag,28 lines: [29 ...explain(refusals).map((text): TranscriptLine => ({30 remote: true,
14 unmodified lines
modified:apps/web/src/features/landing/words.ts+2 added-5 removed
1/**2 * The landing's two opening sentences, the README's, in a module of their3 * own: the route's `head` unfurls with the lede, and a route's head is4 * bundled with the route tree every page loads, so it must pull in no view.2 * A module of their own: a route's head is bundled with the route tree every3 * page loads, so it must pull in no view.4 */57/** The README's opening line: what the platform is. */6export const WHAT_IT_IS =7 "A Git platform for the boundary between a project and everyone else.";811/** The README's lede, the sentence the page unfurls with when its link is shared. */9export const LEDE =10 "Everything a project ships is public, its contribution process is typed code on main, and a push lands only by passing a typed gate.";
modified:apps/web/src/features/ledger/areas.ts-32 removed
1/**2 * What a ledger says about its sealed areas, folded from its entries, and3 * the one sentence its page opens on: the posture label, then each area's4 * count and authors ("Open with sealed evidence. export: 7 sealed checks5 * by 3 people."). A module with no view of its own.6 */1import { LedgerEntry } from "@repo/protocol/domain/visibility";2import type { Ledger } from "@repo/protocol/domain/visibility";3import type { AreaName, SuiteRoot } from "@repo/protocol/ids";4import type { DateTime } from "effect";5import { Option } from "effect";613/** An admission's evidence: when, how many green runs on main, how many known-bad trees it failed. */7export interface Admission {8 readonly at: DateTime.Utc;9 readonly knownBadCaught: number;10 readonly mainRuns: number;11}1220/** One sealed area, as its entries leave it. */13export interface AreaSummary {22 /** The admission of the area's current root; none when that root joined without one. */14 readonly admission: Option.Option<Admission>;15 readonly area: AreaName;25 /** How many people wrote the suite, as its latest commitment counts them. */16 readonly authors: Option.Option<number>;27 /** When any entry about the area was last recorded. */17 readonly changedAt: DateTime.Utc;29 /** How many sealed checks the area holds, as its latest count or commitment says. */18 readonly checks: number;31 /** The suite's salted root, as its latest commitment or admission names it. */19 readonly root: Option.Option<SuiteRoot>;20}2135/** What one entry says about an area, if it is about one. */22interface AreaFact {23 readonly admitted: Option.Option<Admission & { readonly suite: SuiteRoot }>;24 readonly area: AreaName;25 readonly at: DateTime.Utc;
1 unmodified line
27 readonly checks: Option.Option<number>;28 readonly root: Option.Option<SuiteRoot>;29}3045/** A fact that says nothing yet: each kind of entry fills in what it knows. */31const noFact: Omit<AreaFact, "area" | "at"> = {32 admitted: Option.none(),33 authors: Option.none(),34 checks: Option.none(),
29 unmodified lines
64 Released: () => [],65 ValueSet: () => [],66 });6783/** The ledger's entries in the order they were recorded. */68const recorded = (ledger: Ledger) =>69 ledger.entries.toSorted((one, other) => one.seq - other.seq);7087/** An area as its facts so far leave it: each later fact overrides what it says. */71interface Folded {72 readonly admissions: ReadonlyMap<SuiteRoot, Admission>;73 readonly area: AreaName;74 readonly authors: Option.Option<number>;
14 unmodified lines
89 checks: Option.orElse(fact.checks, () => before?.checks ?? Option.none()),90 root: Option.orElse(fact.root, () => before?.root ?? Option.none()),91});92110/**111 * Each sealed area's latest count, authors and root, when it last changed,112 * and the admission of its current root, folded from the entries in the113 * order they were recorded; areas by name.114 */93export const areaSummaries = (ledger: Ledger): readonly AreaSummary[] => {94 const areas = new Map<AreaName, Folded>();9596 for (const fact of recorded(ledger).flatMap(factsOf)) {
16 unmodified lines
113114export const plural = (count: number, one: string, many: string) =>115 `${count} ${count === 1 ? one : many}`;116139/** "export: 7 sealed checks by 3 people". */117export const areaHeadline = ({ area, authors, checks }: AreaSummary) =>118 `${area}: ${plural(checks, "sealed check", "sealed checks")}${Option.match(119 authors,120 {
1 unmodified line
122 onSome: (count) => ` by ${plural(count, "person", "people")}`,123 }124 )}`;125149/** The ledger's head sentence: what leads it, and the rest. */126export interface LedgerHead {127 readonly lead: string;128 readonly rest: string;129}130155/**156 * The ledger in one sentence, in two parts: its lead, the posture label,157 * and the rest, every sealed area's headline, or what it holds back when158 * no area is counted yet. A label that names the sealed areas ("Open with159 * sealed evidence · sealed checks in export, parser") leads with its160 * posture alone when the areas follow with their counts, so no area is161 * named twice; any other label leads whole.162 */131export const ledgerHead = (ledger: Ledger): LedgerHead => {132 const areas = areaSummaries(ledger);133134 if (areas.length > 0) {
19 unmodified lines
modified:apps/web/src/features/ledger/ledger-page.tsx+3 added-31 removed
1/**2 * A project's ledger, facts first. Its status line is one sentence: the3 * posture label the platform computed, then each sealed area's count and4 * authors ("Open with sealed evidence. export: 7 sealed checks by 35 * people."). Then each declared layer (its audience, holdings, disclosure,6 * reason and who reads and writes it), each sealed area folded from the7 * entries (its salted root, its admission record, when it last changed),8 * and the history: one typed line per entry, newest first. The inspector9 * holds the posture, what is held back, the CLI line and what each10 * disclosure means.11 *12 * Props in, markup out: the route reads the ledger (`src/client/ledger.ts`)13 * and hands it here. The ledger carries no path, no check name and no file14 * name, and nothing here adds one; the layer read log is maintainers' data15 * and never reaches the public ledger.2 * The ledger carries no path, no check name and no file name, and nothing here3 * adds one; the layer read log is maintainers' data and never reaches the4 * public ledger.5 */6import { Brand } from "@repo/brand";7import { LedgerEntry } from "@repo/protocol/domain/visibility";8import type { Layer, Ledger, Members } from "@repo/protocol/domain/visibility";
24 unmodified lines
33import { When } from "../shared/time.tsx";34import { areaHeadline, areaSummaries, ledgerHead, plural } from "./areas.ts";35import type { AreaSummary } from "./areas.ts";3648/** A day as a reader skims it: "Oct 11", in UTC. */37const dayOf = (at: DateTime.Utc) =>38 DateTime.formatUtc(at, { day: "numeric", locale: "en-US", month: "short" });3952/**53 * When the ledger was read, at the latest: `now`, or its newest entry's54 * time if that is later. The page keeps the `now` it was served with while55 * it reads the ledger again as entries arrive, and a recorded entry is never56 * in the future.57 */40const readAt = (ledger: Ledger, now: DateTime.Utc) => {41 let latest = now;4243 for (const entry of ledger.entries) {
2 unmodified lines
4647 return latest;48};4968/** The ledger's entries, newest first. */50const newestFirst = (ledger: Ledger) =>51 ledger.entries.toSorted((one, other) => other.seq - one.seq);5253const Code = ({ children }: { readonly children: ReactNode }) => (
1 unmodified line
55 {children}56 </code>57);5878/** The posture label leads, in its role; the areas follow in ink. */59const postureTone = {60 open: "text-foreground",61 openCore: "text-sealed",62 openOnSchedule: "text-sealed",63 openWithSealedEvidence: "text-sealed",64 sourceAvailable: "text-foreground",65} as const satisfies Record<Ledger["posture"], string>;6687/** The ledger's status line: its posture, then every sealed area, in one sentence. */67const HeadSentence = ({ ledger }: { readonly ledger: Ledger }) => {68 const { lead, rest } = ledgerHead(ledger);6970 return (
12 unmodified lines
83 </p>84 );85};86108/** Handles, each linked to their page, comma-separated. */87const Handles = ({ handles }: { readonly handles: readonly Handle[] }) =>88 handles.map((handle, index) => (89 <Fragment key={handle}>90 {index === 0 ? null : ", "}
45 unmodified lines
136 </Definitions>137 </li>138);139162/** "admitted Oct 11; passes main 3/3; catches 2 known-bad", or why there is none. */140const admissionWords = (summary: AreaSummary) =>141 Option.match(summary.admission, {142 onNone: () => "joined without admission runs",143 onSome: ({ at, knownBadCaught, mainRuns }) =>
40 unmodified lines
184 </Definitions>185 </li>186);187211/** Each kind of entry's word, and whether it is about something sealed. */188const kindOf = Match.type<LedgerEntry>().pipe(189 Match.tagsExhaustive({190 Admitted: () => ({ sealed: true, word: "Admitted" }),191 CommitmentPublished: () => ({ sealed: true, word: "Commitment changed" }),
4 unmodified lines
196 ValueSet: () => ({ sealed: true, word: "Value set" }),197 })198);199224/** One entry in words, as the ledger records it; its root, if it names one, is apart. */200const EntryWords = ({201 entry,202 project,203}: {
48 unmodified lines
252 ),253 })254 );255281/** The salted root an entry names, if it names one. */256const rootOf = (entry: LedgerEntry): Option.Option<string> =>257 LedgerEntry.match(entry, {258 Admitted: ({ suite }) => Option.some(suite),259 CommitmentPublished: ({ suite }) => Option.some(suite),
3 unmodified lines
263 Released: () => Option.none(),264 ValueSet: () => Option.none(),265 });266293/** One entry on one line: when, its kind's word, what it says, and its root. */267const EntryRow = ({268 entry,269 now,270 project,
53 unmodified lines
324 ))}325 </ol>326 );327355/** What each disclosure lets the public learn, one line each. */328const Disclosures = () => (329 <FactBlock label="What each disclosure shows">330 <ul className="flex flex-col gap-1.5">331 {Object.values(disclosureWords).map((words) => (
92 unmodified lines
modified:apps/web/src/features/markdown/markdown.tsx+4 added-48 removed
1/**2 * A Markdown file from a project's repo, rendered: a README on the3 * project and tree pages, a `.md` file on the blob page. Its links and4 * images resolve against `dir` at the commit `at`, so they stay inside the5 * project at that commit. The site's own Markdown (the docs) is drawn the6 * same way by `SiteMarkdown`, with nothing to resolve.7 *8 * react-markdown builds React elements (no `dangerouslySetInnerHTML`), so9 * the same component renders in the Worker and in the browser. What may10 * reach the page is decided by the plugin chain in `pipeline.ts`; this11 * file only draws the elements that come out of it.12 */1import type { CommitSha, ProjectName } from "@repo/protocol/ids";2import type { AnyRouter, RegisteredRouter } from "@tanstack/react-router";3import { Link, useRouter } from "@tanstack/react-router";4import type { ComponentProps, ReactNode } from "react";
3 unmodified lines
8import { literalPath } from "../shared/link.tsx";9import { rehypePluginsFor, remarkPlugins, sitePlugins } from "./pipeline.ts";1011export interface RepoMarkdownProps {24 /** The commit the file was read at; links and images point there. */12 readonly at: CommitSha;26 /** The file's directory, relative to the repo root; `""` is the root. */13 readonly dir: string;14 readonly project: ProjectName;29 /** The file's text. */15 readonly source: string;16}1718type AnchorProps = ComponentProps<"a"> & ExtraProps;1935/** A path on this origin (`/p/blob/…`), as `resolve.ts` leaves every in-project link. */20const isSameOrigin = (href: string) =>21 href.startsWith("/") && !href.startsWith("//") && !href.startsWith("/\\");2239/**40 * A link inside the project: a router `Link` when a router is there (the41 * app), so it opens without a full load; a plain link when none is (a42 * view rendered on its own, as the pages' tests render it).43 */23const ProjectLink = ({24 children,25 href,26 // The sanitizer never lets a `target` through.
7 unmodified lines
34 <a {...props} href={href}>35 {children}36 </a>37 ) : (59 // `href`, not `to`: the router parses a built href into path, query60 // and fragment, where `to` would keep `?raw=1#L3` inside the path. Its61 // `$` and braces escaped (`literalPath`): a file's name, never a param62 // the router fills from the page being read. A `string` target makes63 // `to` optional in the Link's props.38 // `href`, not `to`: the router parses a built href into path, query and39 // fragment, where `to` would keep `?raw=1#L3` inside the path.40 // `literalPath` escapes its `$` and braces, so a file's name is never a41 // param.42 <Link<RegisteredRouter, string, string> {...props} href={literalPath(href)}>43 {children}44 </Link>45 );46};4770/** `a`: in-project links through the router; links that leave go with no referrer and no endorsement. */48const Anchor = ({ children, href, node: _node, ...props }: AnchorProps) => {49 if (href !== undefined && isSameOrigin(href)) {50 return (51 <ProjectLink {...props} href={href}>
16 unmodified lines
68 </a>69 );70};7195/** `img`: loaded when scrolled to, decoded off the main thread, and sent with no referrer. */72const Image = ({73 alt,74 node: _node,75 ...props
8 unmodified lines
84);8586const components: Components = { a: Anchor, img: Image };87112/**113 * A README in the page's own type: body text at 16 px on a 70-character114 * measure, headings under the page's headline, code in the mono size on115 * the surface, links in ink. Colours come from the tokens116 * (`prose-tokens` in `styles.css`), so both schemes share these classes.117 */88const PROSE = [89 "prose prose-tokens text-body max-w-[70ch] min-w-0",120 // Headings on the scale: h1 and h2 at the title size, so the page's own121 // headline leads, the h1 ruled beneath; h3 and h4 at the want's size.90 "prose-headings:font-semibold prose-headings:tracking-[-0.01em]",91 "prose-h1:text-title prose-h1:mb-3 prose-h1:border-b prose-h1:border-rule prose-h1:pb-2",92 "prose-h2:text-title prose-h2:mt-8 prose-h2:mb-3",93 "prose-h3:text-want prose-h4:text-want",126 // Inline code: the mono face on a surface field, without backticks.94 "prose-code:before:content-none prose-code:after:content-none prose-code:font-normal",95 "[&_:not(pre)>code]:bg-surface [&_:not(pre)>code]:text-mono [&_:not(pre)>code]:px-1 [&_:not(pre)>code]:py-px",129 // A code block: a field on the surface, ruled in a hairline.96 "prose-pre:bg-surface prose-pre:text-foreground prose-pre:border prose-pre:border-rule prose-pre:rounded-none",97 "prose-pre:text-mono prose-pre:leading-terminal prose-pre:px-4 prose-pre:py-3",132 // Links: ink, underlined in a hairline that darkens under the pointer.98 "prose-a:font-normal prose-a:decoration-input hover:prose-a:decoration-foreground",134 // Quotes as plain indented text, without the plugin's quotation marks.99 "prose-blockquote:font-normal prose-blockquote:not-italic",100 "[&_blockquote_p]:before:content-none [&_blockquote_p]:after:content-none",137 // Images inside the measure, set in the line as a README sets them.101 "prose-img:my-0 prose-img:inline-block prose-img:max-w-full",102 "prose-table:text-ui prose-th:font-semibold",103].join(" ");104
14 unmodified lines
119 </Markdown>120 </div>121);122160/**161 * The site's own Markdown (a page of the docs), in the README's type: its162 * links are the site's paths, through the router, and leave nothing to163 * resolve against a repo.164 */123export const SiteMarkdown = ({124 source,125}: {126 readonly source: string;
9 unmodified lines
136 </Markdown>137 </div>138);139182/** A README that is not Markdown (`README`, `README.txt`, `README.rst`): its text as written. */140export const RepoText = ({141 source,142}: {143 readonly source: string;
4 unmodified lines
148);149150const markdownExtension = /\.(?:markdown|md|mdown|mdwn|mkd|mkdn)$/iu;151195/** Whether a file renders as Markdown (`RepoMarkdown`) or as text (`RepoText`), by its name. */152export const isMarkdownPath = (path: string) => markdownExtension.test(path);
modified:apps/web/src/features/markdown/pipeline.ts+19 added-56 removed
1/**2 * The plugin chain that turns a project's Markdown into a safe tree, in3 * the one order that makes it safe (ADR 0019). It is the security property4 * of the README renderer, so it lives here alone and is tested whole5 * (`test/markdown.test.tsx`):6 *7 * 1. `remarkGfm`: tables, task lists, strikethrough, autolinks, footnotes;8 * 2. `rehypeRaw`: the README's own HTML (`<p align="center"><img …>`)9 * becomes elements, so everything after sees it;10 * 3. `rehypeRepoUrls`: relative links and media point into the project at11 * the SHA (`resolve.ts`), before the sanitizer judges them;12 * 4. `rehypeFootnoteIds`: the footnotes' ids and links lose the13 * `user-content-` remark-rehype gave them, since the sanitizer gives14 * every id that prefix next, and twice made `user-content-user-content-15 * fn-1` while the links named `user-content-fn-1`;16 * 5. `rehypeSanitize` with `schema`: GitHub's allow-list, the last gate on17 * what comes in (no script, no handler, no `javascript:` or `data:`18 * URL, no iframe, style or form; every `id` and `name` prefixed19 * `user-content-`, so a README cannot clobber the page's own globals);20 * 6. `rehypeSlug`: heading ids, after the sanitizer, so `#usage` finds21 * `## Usage` unprefixed;22 * 7. `rehypeFragmentLinks`: last, once every id is final, a `#x` link with23 * no `x` in the file points at `user-content-x` when that is there (a24 * footnote, a README's own `<a id>` or `<a name>`), as GitHub's page25 * script does. It only changes where a link inside the file points,26 * never an id.27 *28 * react-markdown's `defaultUrlTransform` stays on as a second net.2 * The order is the security property: 1. `remarkGfm`; 2. `rehypeRaw`, so3 * everything after sees the README's own HTML; 3. `rehypeRepoUrls`, before the4 * sanitizer judges the URLs; 4. `rehypeFootnoteIds`, dropping remark-rehype's5 * `user-content-` prefix, which the sanitizer adds next; 5. `rehypeSanitize`6 * with `schema`, the last gate (no script, handler, `javascript:` or `data:`7 * URL, iframe, style or form; every `id` and `name` prefixed, so a README8 * cannot clobber the page's globals); 6. `rehypeSlug`, after the sanitizer, so9 * `#usage` finds `## Usage` unprefixed; 7. `rehypeFragmentLinks`, last, once10 * every id is final. react-markdown's `defaultUrlTransform` stays on as a11 * second net.12 */13import { Predicate } from "effect";14import type { Element, Properties, Root } from "hast";15import type { Options } from "react-markdown";
6 unmodified lines
2223import { resolveRepoUrl } from "./resolve.ts";24import type { RepoUrlContext } from "./resolve.ts";2543/** A list of unified plugins, each with its options, as react-markdown takes them. */26export type PluggableList = NonNullable<Options["rehypePlugins"]>;2746/** Where a Markdown file was read: the project, the commit, and the file's directory (`""` is the root). */28export type MarkdownAt = Omit<RepoUrlContext, "kind">;2930/**50 * GitHub's allow-list (`hast-util-sanitize`'s `defaultSchema`), with a51 * code block's `language-…` class kept on `code`, and a `style` element52 * dropped with its CSS (the default drops only a `script` whole, so a53 * style's rules would show as text).31 * A code block's `language-…` class is kept, and a `style` element is dropped32 * with its CSS (the default drops only a `script` whole, so a style's rules33 * would show as text).34 */35export const schema: Schema = {36 ...defaultSchema,37 strip: [...(defaultSchema.strip ?? []), "style"],
5 unmodified lines
43 ],44 },45};4667/** Elements whose URL loads bytes into the page: they read the raw file. */47const media = new Set(["img", "source", "video"]);4870/** One `srcset` candidate (`url [descriptor]`), its URL resolved. */49const candidate = (value: string, at: RepoUrlContext) => {50 const [url = "", ...descriptor] = value.trim().split(/\s+/u);5152 return [resolveRepoUrl(url, at), ...descriptor].join(" ");53};5477/** Rewrite one URL property, when the element carries it as a string. */55const rewrite = (56 properties: Properties,57 key: "href" | "src" | "srcSet",58 to: (value: string) => string
18 unmodified lines
7778 const here = { ...at, kind: "media" } as const;7980 rewrite(node.properties, "src", (src) => resolveRepoUrl(src, here));104 // rehype-raw keeps `srcset` as written: one string, candidates split by commas.81 // rehype-raw keeps `srcset` as written: one string, candidates split by82 // commas.83 rewrite(node.properties, "srcSet", (srcSet) =>84 srcSet85 .split(",")86 .map((value) => candidate(value, here))87 .join(", ")88 );89};90113/**114 * A rehype plugin: every `a[href]` and every `img`, `video` and `source`115 * `src` (and `srcset`) resolved into the project at the SHA.116 */91export const rehypeRepoUrls = (at: MarkdownAt) => (tree: Root) => {92 visit(tree, "element", (node) => {93 resolveElement(node, at);94 });95};96123/** The prefix the sanitizer puts on every `id` and `name` (`hast-util-sanitize`'s default). */97const CLOBBER = schema.clobberPrefix ?? "user-content-";9899const unprefixed = (value: string, lead = "") =>100 value.startsWith(`${lead}${CLOBBER}`)101 ? `${lead}${value.slice(lead.length + CLOBBER.length)}`102 : value;103131/** Drop the prefix from one property, when the element carries it as a string. */104const unprefix = (properties: Properties, key: "href" | "id", lead = "") => {105 const value = properties[key];106107 if (Predicate.isString(value)) {
1 unmodified line
109 }110};111112/**141 * A rehype plugin: the footnotes remark-rehype made (a reference, a142 * footnote's item, a back-reference) lose the prefix it gave their ids and143 * links, so the sanitizer's prefix is their only one.113 * So the sanitizer's prefix is their only one; twice made114 * `user-content-user-content-fn-1`.115 */116export const rehypeFootnoteIds = () => (tree: Root) => {117 visit(tree, "element", (node, _index, parent) => {118 const { properties } = node;
21 unmodified lines
140 });141};142143/**173 * A rehype plugin, run last: a link to `#x` where the file has no `x` but174 * has `user-content-x` (the sanitizer's prefix) points there, so a175 * footnote and a README's own anchor jump. A target is an element's `id`176 * or an anchor's `name`, the two a browser scrolls to for a fragment.144 * As GitHub's page script does: a link to `#x` where the file has no `x` but145 * has `user-content-x` points there.146 */147export const rehypeFragmentLinks = () => (tree: Root) => {148 const ids = new Set<string>();149
29 unmodified lines
179};180181export const remarkPlugins: PluggableList = [remarkGfm];182214/** The rehype half of the chain for one file, in its fixed order. */183export const rehypePluginsFor = (at: MarkdownAt): PluggableList => [184 rehypeRaw,185 [rehypeRepoUrls, at],186 rehypeFootnoteIds,
1 unmodified line
188 rehypeSlug,189 rehypeFragmentLinks,190];191224/**225 * The rehype half of the chain for the site's own text (the docs): no raw226 * HTML and no repo to resolve links against, still sanitized, with heading227 * ids and fragment links as a README gets.228 */192export const sitePlugins: PluggableList = [193 [rehypeSanitize, schema],194 rehypeSlug,195 rehypeFragmentLinks,
1 unmodified line
modified:apps/web/src/features/markdown/resolve.ts+6 added-22 removed
1/**2 * Where a link or an image in a project's Markdown file points, inside the3 * web: the file was read at one commit, in one directory, so a relative4 * URL names a path in that commit's tree, as GitHub resolves a README's5 * links. The result always names the SHA, never `main`, so it reads the6 * same tree forever (and a raw image caches forever, ADR 0019).7 *8 * Pure, so the rules are table-tested on their own; `pipeline.ts` runs it9 * over the rendered tree before the sanitizer sees it.2 * The result always names the SHA, never `main`, so it reads the same tree3 * forever.4 */5import type { CommitSha, ProjectName } from "@repo/protocol/ids";613/** Where the file was read: the project, the commit, its directory, and what kind of URL this is. */7export interface RepoUrlContext {15 /** The file's directory, relative to the repo root; `""` is the root. */8 readonly dir: string;17 /** A link opens a page (`blob`, or `tree` for a folder); media loads the raw bytes. */9 readonly kind: "link" | "media";10 readonly project: ProjectName;11 readonly sha: CommitSha;12}1323/** A URL scheme (`https:`, `mailto:`, `javascript:` …): the URL leaves the repo, and the sanitizer judges it. */14/**15 * A URL scheme (`https:`, `mailto:`, `javascript:` …): the URL leaves the repo,16 * and the sanitizer judges it.17 */18const scheme = /^[a-z][a-z0-9+.-]*:/iu;1926/** A base no reader resolves against; only its path is kept. */20const base = "https://repo.invalid/";2122const edgeSlashes = /^\/+|\/+$/gu;2331/** Media reads raw bytes; a link opens a folder (`tree`) when its path ends in `/`, else a file (`blob`). */24const routeOf = (kind: RepoUrlContext["kind"], pathname: string) => {25 if (kind === "media") {26 return "raw";27 }
1 unmodified line
29 return pathname.endsWith("/") ? "tree" : "blob";30};3132/**41 * Resolve `url` against the file's directory at `sha`:42 *43 * - `#…`, `""`, `//host…` and anything with a scheme come back as written;44 * - `/x` starts at the repo root, anything else at `dir`; `..` stops at45 * the root (the URL parser clamps it), and a `?query` and `#hash` stay;46 * - a link becomes `/<project>/blob/<sha>/<path>`, or `/tree/` when it ends47 * in `/` (a folder); media becomes `/<project>/raw/<sha>/<path>`.48 *33 * Only the parsed path is kept, so a URL the parser reads as another host34 * (`/\host/x`) still lands inside the project.35 */36export const resolveRepoUrl = (url: string, at: RepoUrlContext): string => {
27 unmodified lines
modified:apps/web/src/features/people/person-page.tsx+2 added-23 removed
1/**2 * A person's page: their credit, read from the trailers on landed commits,3 * grouped by project and then by area, each area one sentence of the roles4 * they hold there ("Answered and asked in datekit/src"), linked to the5 * project's landings. Credit gates nothing and ranks no one (GLOSSARY.md6 * "Credit", "Record"): the read counts landings per role, and the page7 * draws none of those counts, orders by name, and adds nothing up.2 * Credit gates nothing and ranks no one: the page draws none of the read's3 * counts, orders by name, and adds nothing up.4 */5import { CreditRole } from "@repo/protocol/domain/credit";6import type { CreditSummary } from "@repo/protocol/domain/record";7import type { Handle, ProjectName } from "@repo/protocol/ids";
6 unmodified lines
14import { MetaCode, MetaLine, Row, RowGroup } from "../shared/row.tsx";15import { projectSections } from "../shared/shell/sections.ts";16import { Workspace } from "../shared/shell/workspace.tsx";1722/** One area of a project: each role a person holds there. */18export interface AreaCredit {19 readonly area: string;20 readonly roles: readonly CreditRole[];21}2228/** One project: the areas a person is credited in. */23export interface ProjectCredit {24 readonly areas: readonly AreaCredit[];25 readonly project: ProjectName;26}2734/** Each role as the sentence says it, in the past: the trailer names what they did. */28const ROLE_WORD = {29 "Advised-by": "advised",30 "Asked-by": "asked",31 "Decided-by": "decided",
2 unmodified lines
34 "Released-by": "released",35 "Signed-off-by": "answered",36} as const satisfies Record<CreditRole, string>;3745/**46 * The order a sentence names roles in: the answer first (it is the work47 * the landing is), then the trailers' own order.48 */38const SENTENCE_ORDER: readonly CreditRole[] = [39 "Signed-off-by",40 ...CreditRole.literals.filter((role) => role !== "Signed-off-by"),41];
1 unmodified line
43const bySentence = Order.mapInput(Order.Number, (role: CreditRole) =>44 SENTENCE_ORDER.indexOf(role)45);4658/** Words joined as a sentence lists them: `a`, `a and b`, `a, b and c`. */47const listed = (words: readonly string[]) =>48 words.length < 249 ? words.join("")50 : `${words.slice(0, -1).join(", ")} and ${words.at(-1) ?? ""}`;5164/** Where an area sits, in words: "the whole project" for its root. */52const whereOf = (project: string, area: string) =>53 area === "." || area === "" ? "the whole project" : `${project}/${area}`;5468/**69 * An area's roles as one sentence: "Answered and asked in datekit/src",70 * "Decided in the whole project".71 */55export const areaSentence = (56 project: string,57 area: string,58 roles: readonly CreditRole[]
6 unmodified lines
6566 return `${sentence.charAt(0).toUpperCase()}${sentence.slice(1)}`;67};6886/** `rows` grouped by `key`, the groups in the order their keys sort. */69const groupBy = <A,>(70 rows: readonly A[],71 key: (row: A) => string72): readonly Array.NonEmptyReadonlyArray<A>[] =>73 Object.entries(Array.groupBy(rows, key))74 .toSorted(([one], [other]) => one.localeCompare(other))75 .map(([, group]) => group);7695/** A person's credit by project, then by area (each by name), each area's roles once each. */77export const creditsByProject = (78 credits: readonly CreditSummary[]79): readonly ProjectCredit[] =>80 groupBy(credits, ({ project }) => project).map((inProject) => ({
8 unmodified lines
89 })),90 project: Array.headNonEmpty(inProject).project,91 }));92112/** The project's landings, where an area's credits are the trailers. */93const landingsOf = (project: ProjectName) =>94 projectSections(project).find(({ tab }) => tab === "landings")?.to ??95 projectPath(project);96
58 unmodified lines
155 </Workspace>156 );157};158179/** The page for an address whose last part cannot be a handle. */159export const NoSuchPersonView = () => (160 <PageShell title="No such person">161 <EmptyState162 onward={<AppLink to={ASKS_PATH}>Open asks</AppLink>}
4 unmodified lines
modified:apps/web/src/features/project/asks.tsx-15 removed
1/**2 * A project's open asks as rows: each ask its want first and its state at3 * the right, with its claim command when it is open; a family drawn as its4 * parent's row with the fan under it and its children listed, so a reader5 * sees how many of them landed and which wait.6 */1import type { Ask, AskListing } from "@repo/protocol/domain/ask";2import type { AskId, ProjectName } from "@repo/protocol/ids";3import type { DateTime } from "effect";4import type { ReactNode } from "react";
2 unmodified lines
7import type { AskProgress } from "../shared/ask-progress.ts";8import { FamilyStrip } from "../shared/family.tsx";9import { AskRow, RowList } from "../shared/row.tsx";1017/** Whether an ask is open to take as its listing says: nobody holds it, it waits on nothing, and it is held for nobody. */11export const openToTake = (listing: AskListing) =>12 !listing.claimed &&13 listing.blockedBy.length === 0 &&14 listing.reserve === undefined;1523/**24 * The asks a project counts as open: every one listed, but a family's25 * delete child while it waits on its siblings (it opens when they land).26 */16export const openAsks = (listings: readonly AskListing[]) => {17 const finales = new Set(18 arrange(listings).flatMap((item) =>19 item.kind === "family" ? [item.finale] : []
4 unmodified lines
24 ({ ask, blockedBy }) => !(finales.has(ask) && blockedBy.length > 0)25 );26};2739/** The project's asks, families as fans with their children listed. */28export const AskList = ({29 asks,30 now,31 onSelect,
5 unmodified lines
37}: {38 readonly asks: readonly AskListing[];39 readonly now: DateTime.Utc;40 readonly project: ProjectName;53 /** Each family's parent in full, which counts its children. */41 readonly parents: readonly Ask[];42 readonly states: ReadonlyMap<AskId, AskProgress>;43 readonly stamps: ReadonlySet<AskId>;44 readonly selected: string | undefined;
20 unmodified lines
65 }6667 const parent = parents.find(({ id }) => id === item.parent.ask);6882 // A parent the platform did not give in full: its members stay rows.69 if (parent === undefined) {70 return [71 row(item.parent),72 ...item.members.map((member) => row(member)),
20 unmodified lines
93 </RowList>94 );95};96111/** Row ids in the order `AskList` draws them: what `j` and `k` walk. */97export const askListIds = (asks: readonly AskListing[]) =>98 arrange(asks).map((item) =>99 item.kind === "ask" ? item.listing.ask : item.parent.ask100 );
modified:apps/web/src/features/project/landings.tsx+2 added-17 removed
1/**2 * A project's recent landings as one-line credits: what the landing did (the3 * ask it answered or opened), who is credited, in one sentence of roles,4 * and when. The full trailers are the landing's own, on its commit's page.5 */1import type { LandingView } from "@repo/protocol/domain/landing";2import { Option } from "effect";3import type { DateTime } from "effect";4
2 unmodified lines
7import { askPath } from "../shared/paths.ts";8import { When } from "../shared/time.tsx";9import { askOf } from "../why/rows.ts";1016/** How many landings the project's home shows. */11export const RECENT_SHOWN = 3;1213/**20 * A landing's subject line. The platform writes `Answer <ask>` on a landing21 * that answers an ask; `LandingView` carries no subject for the rest, so22 * those read by what they are: an ask's opening as `Open ask <ask>`, then a23 * decider's own landing and the first adoption.14 * `LandingView` carries a subject only for `Answer <ask>`, so the rest read by15 * what they are.16 */17export const landingSubject = (landing: LandingView) =>18 Option.match(askOf(landing), {19 onNone: () =>
1 unmodified line
21 onSome: ({ ask, kind }) =>22 kind === "opened" ? `Open ask ${ask}` : `Answer ${ask}`,23 });2433/**34 * The landings the project's home shows, newest first: the last three35 * answers once three have landed, so the landings that set the project up36 * (its first push, its openings) give way to the work people did; before37 * then, the last three of any kind.38 */25export const recentShown = (26 landings: readonly LandingView[]27): readonly LandingView[] => {28 const answers = landings.filter((landing) => landing.ask !== undefined);
41 unmodified lines
70 </li>71 );72};7388/** The landings given, each as one line of credit. */74export const LandingList = ({75 landings,76 now,77}: {
9 unmodified lines
modified:apps/web/src/features/project/posture-label.ts+3 added-11 removed
1/**2 * A posture in the words GLOSSARY.md gives it ("Posture"). The project list3 * and the front page carry only the literal; the fuller label the platform4 * computes from a project's visibility config ("Open · sealed checks in5 * parser") is the ledger's. Until a listing carries that6 * label, each posture reads as its own name, never as a claim about what is7 * sealed.2 * The project list carries only the literal; until it carries the platform's3 * full label, each posture reads as its own name, never as a claim about what4 * is sealed.5 */6import type { Posture } from "@repo/protocol/posture";78const labels = {
5 unmodified lines
14} as const satisfies Record<Posture, string>;1516export const postureLabel = (posture: Posture): string => labels[posture];1721/**22 * A posture in its short form: the one the rail and a project's head both23 * say, so a project reads the same in both places (the platform's full24 * label is its title).25 */18const words = {19 open: "Open",20 openCore: "Open core",21 openOnSchedule: "Open on schedule",
5 unmodified lines
modified:apps/web/src/features/project/project-nav.tsx-11 removed
1/**2 * A project's section row: Asks, Code, Landings, Refs, Policy, Ledger and3 * Env shape, one line under the page's head where the rail is not drawn4 * (below 1120 px; from there the rail lists them). The line scrolls5 * sideways inside itself and never wraps, so it never pushes the page6 * sideways. The page being read is marked `aria-current` and underlined in7 * ink; a page under none of them (a proposal) marks none.8 *9 * Its links are the router's (`AppLink`), so moving between sections never10 * reloads the page.11 */1import type { ProjectName } from "@repo/protocol/ids";2import type { ReactNode } from "react";34import { AppLink } from "../shared/link.tsx";
29 unmodified lines
modified:apps/web/src/features/project/project-page.tsx+5 added-65 removed
1/**2 * A project's home, which is its list of asks: its name, its posture and3 * when it last landed; its open asks, a family drawn as a fan with its4 * children listed; then its README. Beside them, how a change lands here:5 * the posture, the gate, who decides, what is held back, the commands that6 * take part, and the last landings; or the selected ask's facts, one Escape7 * from them. Props in, markup out: the route reads the asks, the ledger,8 * the events, the policy and the code on the server and keeps them live in9 * the browser, and hands them here.10 */1import { IMPORTED_NOTE } from "@repo/agent-kit/docs/imported-note";2import { Brand } from "@repo/brand";3import type { Ask, AskListing } from "@repo/protocol/domain/ask";4import type { FileView, TreeListing } from "@repo/protocol/domain/code";
38 unmodified lines
43import { postureLabel, postureWord } from "./posture-label.ts";44import { ProjectNav } from "./project-nav.tsx";45import { ReadmeSection } from "./readme-section.tsx";4657/** A project's code as its home reads it: the root folder at main, and its README. */47export interface ProjectCode {48 readonly readme?: FileView | undefined;49 readonly root: TreeListing;50}5163/** Who decides for which paths, as the project's policy says. */52export interface Deciders {53 readonly handles: readonly Handle[];54 readonly paths: Glob;55}5669/** One area a layer holds checks in, and how many. */57export interface HeldBackArea {58 readonly area: AreaName;72 /** How many sealed checks it holds. */59 readonly checks: number;60 readonly detail: string;61}6277/** An entry that says nothing about an area's count. */63const noCount = (): readonly (readonly [AreaName, number])[] => [];6480/**81 * What a project holds back, from its ledger: each sealed area and how many82 * checks it holds, as the latest count or commitment says.83 */65export const heldBackOf = (ledger: Ledger): readonly HeldBackArea[] => {66 const checks = new Map(67 ledger.entries68 .toSorted((a, b) => a.seq - b.seq)
21 unmodified lines
90 }));91};9293/**113 * The project as its home knows it: its name, its open asks, when it last114 * landed, and its posture once its own ledger has said it. Until then the115 * page says no posture, never one it was not told.94 * Until its own ledger has said it, the page says no posture, never one it was95 * not told.96 */97export type HomeListing = Omit<ProjectListing, "posture"> & {98 readonly posture?: Posture | undefined;99};100121/** The project for its home, from what was read: the posture only from its own ledger. */101export const homeListing = ({102 asks,103 ledger,104 project,
6 unmodified lines
111 posture: ledger?.posture,112 project,113});114136/** A posture known, in the platform's words. */115interface KnownPosture {116 readonly label: string;117 readonly posture: Posture;118}119120export interface ProjectViewProps {143 /** The open asks; none while they are read, and none when they could not be. */121 readonly asks: readonly AskListing[] | undefined;145 /** Whether the asks could not be read: the platform did not answer. */122 readonly unreachable?: boolean;147 /** The project's landings, newest first. */123 readonly landings: readonly LandingView[];149 /** The project: its posture (once its ledger is read), when it last landed, its open asks. */124 readonly listing: HomeListing;151 /** When it last landed, as its events say, over what the listing says. */125 readonly lastLanded?: DateTime.Utc | undefined;153 /** Its posture in the platform's words, from its own ledger. */126 readonly postureLabel?: string | undefined;155 /** What it holds back, from its ledger; none while it is read. */127 readonly heldBack?: readonly HeldBackArea[] | undefined;157 /** Who decides for which paths; none while the policy is read or when it has none. */128 readonly deciders?: readonly Deciders[] | undefined;159 /** Where it was imported from; none for a project that started empty, or while the policy is read. */129 readonly importedFrom?: ImportSource | undefined;130 readonly now: DateTime.Utc;131 readonly platformUrl: string;163 /** The root folder at main and its README, once read. */132 readonly code?: ProjectCode | undefined;165 /** Each family's parent in full, which counts its children. */133 readonly parents?: readonly Ask[];167 /** Where each ask stands, from the project's events. */134 readonly states?: ReadonlyMap<AskId, AskProgress>;169 /** The children that landed while the page was open. */135 readonly stamps?: ReadonlySet<AskId>;171 /** The selected ask in full, once the browser has read it. */136 readonly selectedAsk?: Ask | undefined;173 /** Whether someone is signed in, who may propose an ask. */137 readonly signedIn?: boolean;138}139177/** Who decides, one line per set of paths, at most three, then the policy. */140const WhoDecides = ({141 deciders,142 project,143}: {
29 unmodified lines
173 </FactBlock>174 );175};176215/** Where an imported project came from: its source, the branch adopted, and what a copy is. */177const ImportedFrom = ({ source }: { readonly source: ImportSource }) => (178 <FactBlock label="Imported from">179 <p className="text-ui">180 <a
15 unmodified lines
196 </p>197 </FactBlock>198);199239/** The four commands that take part, in the order a newcomer runs them. */200const TakePart = ({201 platformUrl,202 project,203}: {
20 unmodified lines
224 </FactBlock>225);226227/**268 * The last landings. Before the project's main first lands, the push that269 * lands it is its initializer's; after it, the replay may still hold no270 * landing event, since adopting main is not one: say so, never "nothing271 * landed".228 * Adopting main is not a landing event, so the replay may hold no landing:229 * never say "nothing landed".230 */231const RecentLandings = ({232 landedAt,233 landings,
33 unmodified lines
267268 return <FactBlock label="Recent landings">{shown}</FactBlock>;269};270313/** How a change lands here: the facts with nothing selected; the posture is the head's to say. */271const HowItLands = ({272 deciders,273 heldBack,274 importedFrom,
30 unmodified lines
305 <ForAgents href={`/${listing.project}/llms.txt`} />306 </>307);308352/**353 * How a change lands here, in one sentence built only from typed facts:354 * the gate, the paths deciders are set for, what is held back (the ledger355 * linked from it), and when it last landed. The one place the project's356 * own pages state it; the inspector carries the same as facts.357 */309const RuleSentence = ({310 deciders,311 heldBack,312 landedAt,
38 unmodified lines
351 </p>352 );353};354404/** The project line: its posture and its open asks; its README's first sentence; then its one rule sentence. */355const ProjectLine = ({356 count,357 lede,358 posture,
5 unmodified lines
364 readonly rule: ReactNode;365}) => (366 <div className="flex flex-col gap-3">367 <p className="text-ui text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1">418 {/* The posture in the short form the rail says, the platform's own419 label its title; its dot after it, so a line never opens on one. */}368 {/* Its dot after it, so a line never opens on one. */}369 {posture === undefined ? null : (370 <span className="flex items-center gap-x-2">371 <PostureBadge372 label={postureWord(posture.posture)}
13 unmodified lines
386 {rule}387 </div>388);389441/** The asks' place on the page, as far as they have been read. */390const AsksSection = ({391 asks,392 now,393 onSelect,
57 unmodified lines
451 </section>452 );453};454507/** Whichever facts the inspector shows: how a change lands here, or the selected ask's. */455const PageFacts = ({456 landedAt,457 picked,458 posture,
44 unmodified lines
503 />504 );505};506560/** A list's count at the context bar's end: "7 open asks, 6 open to take". */507const countOf = (open: readonly AskListing[]) =>508 `${plural(open.length, "open ask", "open asks")}, ${509 open.filter(openToTake).length510 } open to take`;511566/** The page, with the selection the list keeps (or none, outside a router). */512const ProjectPanes = ({513 props,514 select,515 selected,
100 unmodified lines
616617 return <ProjectPanes props={props} select={select} selected={selected} />;618};619675/**676 * The project's home. Inside the router its list selects (`?ask=`) and `j`677 * and `k` walk it; a view rendered alone draws the same page with nothing678 * selected.679 */620export const ProjectView = (given: ProjectViewProps) => {621 const props = {622 ...given,623 asks: given.asks && stillWaiting(given.asks),
8 unmodified lines
modified:apps/web/src/features/project/readme-section.tsx-6 removed
1/**2 * A README (or any Markdown file) under its own name, rendered on the3 * project's prose: a project's home shows its root README below its asks,4 * and a folder or a Markdown file shows its own. Its first sentence is the5 * project's lede, under the project's name (`ledeOf`, `features/front/head.ts`).6 */1import type { FileView } from "@repo/protocol/domain/code";2import type { ProjectName } from "@repo/protocol/ids";34import { dirOf } from "../code/paths.ts";
31 unmodified lines
modified:apps/web/src/features/project/unknown-project.tsx-7 removed
1/**2 * The page for an address that names no project: the platform's own3 * refusal, `UnknownProject`, as `git` and the CLI would print it, then the4 * way onward. An address that cannot be a project's name at all says so in5 * a sentence.6 */1import { ProjectName } from "@repo/protocol/ids";2import { UnknownProject } from "@repo/protocol/refusal";3import { Option, Schema } from "effect";4
6 unmodified lines
11const decodeProject = Schema.decodeUnknownOption(ProjectName);1213const LINK = "decoration-rule underline hover:decoration-current";1421/** Where to go instead: every open ask. */15const Onward = () => (16 <div className="text-ui flex flex-wrap gap-x-4 gap-y-1">17 <AppLink className={LINK} to={ASKS_PATH}>18 Open asks
24 unmodified lines
modified:apps/web/src/features/project-people/people-view.tsx-44 removed
1/**2 * A project's policy (its section reads "Policy"; its address stays3 * `/$project/people`), as its config folder states it at the landed4 * commit: who decides which paths, the vouch rule and the vouch file's5 * lines, the caps, budget and timings, and whether landings disclose6 * agents. The layers are one line that links the ledger, where who reads7 * and writes each one is told. The head says which commit and which file8 * it is read from; the inspector says how to change any of it.9 *10 * Props in, markup out: the route reads `projectPolicy` and `ledger`11 * (`src/client/{policy,ledger}.ts`) and hands them here. With no policy at12 * the landed commit, the page says why (`unevaluated`: no config folder, or13 * one that did not evaluate), names the commit and says what makes it14 * evaluate; with no reason either, nothing has landed yet. The page is15 * read-only: the one way to change any of it is to land a change to the16 * config folder, and it says so with the commands.17 */1import { Brand } from "@repo/brand";2import type { PolicyPending, PublicPolicy } from "@repo/protocol/domain/policy";3import type { Ledger } from "@repo/protocol/domain/visibility";4import type { Handle, ProjectName } from "@repo/protocol/ids";
13 unmodified lines
18import { Workspace } from "../shared/shell/workspace.tsx";1920type Vouches = PublicPolicy["vouches"];2139/** The project's config file, `project.ts` in the config folder. */22const PROJECT_FILE = `${Brand.configDir}/project.ts`;2342/** The config folder as a reader writes it: `<configDir>/`. */24const CONFIG_DIR = `${Brand.configDir}/`;2526const HOUR_MS = 3_600_000;27
1 unmodified line
2930const plural = (count: number, one: string, many: string) =>31 `${count} ${count === 1 ? one : many}`;3252/** A claim timing as a reader says it: whole hours up to two days, then days. */33const spanOf = (ms: number) => {34 if (ms % HOUR_MS !== 0) {35 return plural(Math.round(ms / 60_000), "minute", "minutes");36 }
4 unmodified lines
41 ? plural(hours / 24, "day", "days")42 : plural(hours, "hour", "hours");43};4465/** What a vouch gates, in words. */45const vouchModes = {46 all: "For everything: claiming an ask, offering a sealed answer and proposing an ask all need a vouch.",47 bansOnly:48 "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or propose.",
6 unmodified lines
55 {children}56 </code>57);5880/** A file or a commit in running text: mono, linked. */59const CodeLink = ({60 children,61 to,62}: {
4 unmodified lines
67 {children}68 </AppLink>69);7093/** Handles, each linked to their page, comma-separated. */71const Handles = ({ handles }: { readonly handles: readonly Handle[] }) =>72 handles.map((handle, index) => (73 <Fragment key={handle}>74 {index === 0 ? null : ", "}75 <HandleLink handle={handle} />76 </Fragment>77 ));78102/** "As of 71fda27, from <config folder>/project.ts", each linked; or the platform's defaults. */79const AsOf = ({80 policy,81 project,82}: {
17 unmodified lines
100 )}101 </>102);103128/** Who decides each path: the path in mono, then its deciders. */104const Deciders = ({105 deciders,106}: {107 readonly deciders: PublicPolicy["deciders"];
84 unmodified lines
192 </Region>193 );194};195221/** A number a reader compares: set in tabular figures. */196const Num = ({ children }: { readonly children: string }) => (197 <span className="tabular-nums">{children}</span>198);199
47 unmodified lines
247 </p>248 </Region>249);250277/** The layers' one line: each by name and disclosure, and a link to the ledger. */251const LayersLine = ({252 ledger,253 project,254}: {
33 unmodified lines
288 .289 </p>290 );291319/**320 * The layers in one line, under a heading of their own: each by name and321 * disclosure, held back, and the ledger, where who reads and writes each322 * one is told. Nothing else.323 */292const Layers = ({293 ledger,294 project,295}: {
4 unmodified lines
300 <LayersLine ledger={ledger} project={project} />301 </Region>302);303336/** The page over an evaluated policy: each of its sections. */304const Evaluated = ({305 ledger,306 policy,307 project,
15 unmodified lines
323 <Layers ledger={ledger} project={project} />324 </>325);326360/** The landed commit, short and linked: "The config at the landed commit <sha> has not been evaluated". */327const NotEvaluated = ({328 at,329 project,330}: {
6 unmodified lines
337 {" has not been evaluated"}338 </>339);340375/**376 * Why the config at the landed commit has not been evaluated, and what377 * makes it evaluate: a `project.ts` naming the test command, or a fix to378 * the folder that did not evaluate. Either way, it evaluates again at379 * every landing.380 */341const Pending = ({342 pending,343 project,344}: {
45 unmodified lines
390 </p>391 </div>392);393434/** One way to change the policy: what it does, then its command, a flag to a line. */394const Step = ({395 command,396 label,397}: {
5 unmodified lines
403 <CommandLine command={command} numbered />404 </div>405);406448/** `command`, then each flag with its value on a line of its own. */407const lines = (command: string, flags: readonly string[]) =>408 [command, ...flags].join(" \\\n ");409452/** How the policy changes: by a landing to the config folder, never here. */410const ChangeFacts = ({ project }: { readonly project: ProjectName }) => (411 <FactBlock label="How to change these">412 <p className="text-ui">413 {`Land a change to ${CONFIG_DIR}: open an ask for it, or, as a decider, land your own from a clone.`}
28 unmodified lines
442}: {443 readonly ledger: Ledger;444 readonly policy: Option.Option<PublicPolicy>;445 readonly project: ProjectName;489 /** Why there is no policy at the landed commit; none before the first landing. */446 readonly unevaluated: Option.Option<PolicyPending>;447}): ReactNode => (448 <Workspace449 facts={<ChangeFacts project={project} />}
22 unmodified lines
modified:apps/web/src/features/proposal/client-file.tsx+2 added-10 removed
1/**2 * A drafted file (the ask file or its check), drawn in the browser only.3 * The server renders the file's path as a heading and its text in a4 * `<pre>`; after hydration the browser loads `@pierre/diffs` and draws it5 * highlighted. `import.meta.env.SSR` is `true` in the Worker's build, so the6 * dynamic import below is dead code there and the Worker bundles none of it7 * (`bytes:check`), as `features/code/client-code.tsx` does.2 * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic import3 * below is dead code there and the Worker bundles none of it.4 */5import { ClientOnly } from "@tanstack/react-router";6import { lazy, Suspense } from "react";712// A type-only import is erased, so the server bundles nothing of it.8import type { DraftedFileProps } from "./drafted-file.tsx";910const DraftedFileLater = import.meta.env.SSR11 ? undefined12 : lazy(() => import("./drafted-file.tsx"));1319/** The file's text as the server and a reader without JavaScript see it. */14const Plain = ({ content }: { readonly content: string }) => (15 <pre className="border-rule bg-surface text-mono leading-code overflow-x-auto border px-3 py-2 font-mono">16 {content}17 </pre>18);1926/** One drafted file under its path: a heading, then the code. */20export const DraftedCode = ({21 content,22 heading: Heading = "h3",23 path,24}: DraftedFileProps & {32 /** The heading level the path takes in its page. */25 readonly heading?: "h3" | "h4";26}) => {27 const fallback = <Plain content={content} />;28
17 unmodified lines
modified:apps/web/src/features/proposal/drafted-file.tsx-10 removed
1/**2 * One drafted file, drawn by `@pierre/diffs`: the ask file or its check,3 * highlighted by Shiki's JavaScript engine (never its WASM one). Nothing is4 * selectable or anchored here: a page may hold several of these, and the5 * file's own page is the place for `#L` anchors.6 *7 * The library and Shiki's grammars are megabytes, so only the browser8 * loads this module (`client-file.tsx`); the Worker never bundles it.9 */1import { File } from "@pierre/diffs/react";2import type { FileOptions } from "@pierre/diffs/react";3import { useMemo } from "react";4
8 unmodified lines
13}1415const options: FileOptions<undefined, undefined> = {16 ...diffsOptions,26 // The page names the file in its own heading above the code.17 disableFileHeader: true,18 overflow: "scroll",19};20
17 unmodified lines
modified:apps/web/src/features/proposal/failure.tsx-10 removed
1/**2 * A call the propose, proposal or decision pages sent, failed. A session3 * that ended (or never began) asks the reader to sign in and come back to4 * the same address, so the form, the proposal or the decision is where5 * they left it; a refusal reads as the platform gave it, through6 * `RefusalView`; anything else is the platform not answering, in ink,7 * never as a refusal.8 */1import { Unauthenticated } from "@repo/protocol/principal";2import { Refusal } from "@repo/protocol/refusal";3import { Cause, Option, Schema } from "effect";4import { LogIn } from "lucide-react";
11 unmodified lines
16 doing,17 here,18}: {19 readonly cause: Cause.Cause<unknown>;28 /** What the reader was doing, as "Sign in to …" ends: `propose it`. */20 readonly doing: string;30 /** The page's own address (`hereOf`), where sign-in comes back to. */21 readonly here: string;22}) => {23 const error = Cause.findErrorOption(cause);24
28 unmodified lines
modified:apps/web/src/features/proposal/live-draft.ts-15 removed
1/**2 * Where a proposal's draft stands, read live for a view that is not handed3 * it: the decision card on Today holds Accept until the browser has read the4 * proposal's draft, and while the platform's agent drafts it again. The read5 * is `showProposal` (`client/proposal.ts`), which `ProposalDrafted`6 * refreshes; on the server, and until it answers, nothing is read yet.7 */1import { useAtomValue } from "@effect/atom-react";2import type { ShowProposal } from "@repo/protocol/contracts";3import type { DraftState } from "@repo/protocol/domain/proposal";4import type { ProjectName, ProposalId } from "@repo/protocol/ids";
1 unmodified line
6import { AsyncResult } from "effect/reactivity";78import { proposalAtom } from "../../client/proposal.ts";917/**18 * What the browser has read of a proposal's draft: nothing (`Unread`), yet19 * or because the read `failed`; or the draft it read, `None` for a20 * proposal no agent drafted (a want alone).21 */10export type DraftRead = Data.TaggedEnum<{11 Read: { readonly draft: Option.Option<DraftState> };12 Unread: { readonly failed: boolean };13}>;1427/** Constructors and guards for a draft read. */15export const DraftRead = Data.taggedEnum<DraftRead>();1630/** A draft read: `draft`, or none for a proposal no agent drafted. */17export const readDraft = (draft?: DraftState): DraftRead =>18 DraftRead.Read({ draft: Option.fromUndefinedOr(draft) });1934/** The draft a `showProposal` read holds: once it answered, or why there is none yet. */20export const draftReadOf = (21 result: AsyncResult.AsyncResult<22 typeof ShowProposal.successSchema.Type,23 unknown
11 unmodified lines
modified:apps/web/src/features/proposal/proposal-view.tsx+4 added-47 removed
1/**2 * One proposal, as its proposer and its deciders follow it. The title is3 * its want; under it, where the platform's draft stands in the outcome's4 * words: drafting (the checking role), ready and waiting for a decider (the5 * waiting role), or a failed round, drawn by `RefusalView` when the round6 * failed with a refusal the page can draw whole, else as an ink line. Then7 * the draft read as a guide, in the order it was made: the ask file (its8 * want, territory and kind as rows, its source behind a disclosure), the9 * check (its source), and red first (the run that failed twice the same10 * way, its assertion once).11 *12 * "Let the platform's agent draft it" (or "Draft again"), with a note for13 * the agent, is the proposer's or a decider's while the proposal is open14 * and not drafting; a decider also gets the way to the decision that would15 * open the ask. The inspector holds who proposed it, when it expires, the16 * decision, and the draft's round.17 *18 * Nothing here edits the drafted files: a member proposes again, or a19 * decider sends the draft back with a note.20 */1import { Brand } from "@repo/brand";2import type { ConfigFile } from "@repo/protocol/domain/common";3import { DraftState } from "@repo/protocol/domain/proposal";4import type { Proposal } from "@repo/protocol/domain/proposal";
19 unmodified lines
24import { When } from "../shared/time.tsx";25import { DraftedCode } from "./client-file.tsx";2627/**48 * How many attempts a draft round makes before it fails: the platform's49 * `DRAFT_ROUNDS` (`@repo/project/draft-runs`), which the web's production50 * code does not import; `test/proposal.test.tsx` holds the two equal.28 * The platform's `DRAFT_ROUNDS`, which the web's production code does not29 * import; `test/proposal.test.tsx` holds the two equal.30 */31export const DRAFT_ATTEMPTS = 3;3254/** The longest note `draftAsk` takes. */33const NOTE_LIMIT = 2000;3457/** Where a proposal stands in one word: its draft's while it is open, else its own. */35export const standing = (proposal: Proposal) =>36 proposal.state === "open" && proposal.draft !== undefined37 ? proposal.draft._tag38 : proposal.state;
1 unmodified line
40const draftingNow = DraftState.isAnyOf(["Drafting"]);4142const failedNow = DraftState.isAnyOf(["Failed"]);4367/** Whether the platform's agent is drafting the proposal's ask right now. */44export const isDrafting = (proposal: Proposal) =>45 proposal.draft !== undefined && draftingNow(proposal.draft);4671/** Every refusal of the union, to find one by the tag a failed draft kept. */47const refusalKinds = groups.flatMap(({ members }) => [...members]);4849/**75 * The refusal a failed round ended with, when its tag alone makes one: a76 * draft keeps only the tag, so a refusal that needs fields of its own77 * cannot be drawn whole, and is said in words instead.50 * A draft keeps only the tag, so a refusal that needs fields of its own cannot51 * be drawn whole.52 */53export const refusalOfTag = (tag: string): Option.Option<Refusal> =>54 Arr.findFirst(refusalKinds, (kind) => kind.identifier === tag).pipe(55 Option.flatMap((kind): Option.Option<Refusal> =>
2 unmodified lines
58 kind.makeOption({} as never)59 )60 );6188/** Whether a drafted file is the ask file: under the config folder, or named as one. */62const isAskFile = ({ path }: ConfigFile) =>63 path.startsWith(`${Brand.configDir}/`) || path.endsWith(".ask.ts");6492/** The draft's files in the order it made them: the ask file, the check, then what the check reads. */65const filesInOrder = (files: readonly ConfigFile[]) => {66 const askFile = files.find(isAskFile);67 const rest = files.filter((file) => file !== askFile);68 const checks = rest.filter(({ path }) => isTestPath(path));
1 unmodified line
7071 return { askFile, checks, others };72};73102/** The kind an ask file names (`kinds.fix`), when it names one plainly. */74const kindIn = (source: string) =>75 /\bkinds\.(?<kind>[A-Za-z]+)/u.exec(source)?.groups?.kind;7677const Step = ({
25 unmodified lines
103 <dd className="text-ui min-w-0 [overflow-wrap:anywhere]">{children}</dd>104 </div>105);106136/** The ask file: what it states, then its source behind a disclosure. */107const AskFileStep = ({108 file,109 proposal,110}: {
35 unmodified lines
146 </Step>147 );148};149180/** Red first: the run that failed twice the same way on main, its assertion once. */150const RedFirst = ({ draft }: { readonly draft: DraftState }) =>151 DraftState.match(draft, {152 Drafting: () => null,153 Failed: () => null,
15 unmodified lines
169 </Step>170 ),171 });172204/** A round that failed: the refusal whole when the page can draw it, else in words, in ink. */173const FailedRound = ({ draft }: { readonly draft: DraftState }) =>174 DraftState.match(draft, {175 Drafting: () => null,176 Failed: ({ attempts, model, refusal, round }) =>
24 unmodified lines
201 }),202 Ready: () => null,203 });204237/** "Draft again", with a note the agent reads. */205const Redraft = ({206 again,207 busy,208 onRedraft,
51 unmodified lines
260 </section>261 );262};263297/** The way to the open decision that would open the ask. */264const DecisionLink = ({265 decision,266 project,267}: {
9 unmodified lines
277 Decide it: {decision}278 </AppLink>279);280315/** The draft's round, in a line: its number and where it stands. */281const roundLine = (draft: DraftState) =>282 DraftState.match(draft, {283 Drafting: ({ round }) => `Round ${round}, drafting now`,284 Failed: ({ attempts, round }) =>
1 unmodified line
286 Ready: ({ attempts, round }) =>287 `Round ${round} ready after ${attempts} of ${DRAFT_ATTEMPTS} attempts`,288 });289325/** The inspector's facts: who proposed it, when it expires, its decision, the draft's round. */290const ProposalFacts = ({291 decision,292 now,293 project,
43 unmodified lines
337 )}338 </>339);340377/** Where the proposal stands, under its title: the status line, or a failed round; then what drafting means and its note. */341const ProposalStatus = ({ proposal }: { readonly proposal: Proposal }) => {342 const { draft } = proposal;343 const drafting = draft !== undefined && draftingNow(draft);344
28 unmodified lines
373 </div>374 );375};376414/** The draft as a guide, in the order it was made; a want alone says so. */377const DraftGuide = ({378 files,379 proposal,380}: {
47 unmodified lines
428 proposal,429}: {430 readonly project: ProjectName;431 readonly proposal: Proposal;470 /** The files the proposal holds (the ask file and its check), as `showProposal` read them. */432 readonly files: readonly ConfigFile[];472 /** The open decision on the proposal, when the reader's Today holds it. */433 readonly decision: Option.Option<DecisionId>;474 /** Whether the reader is its proposer or one of the project's deciders. */434 readonly mayRedraft: boolean;435 readonly onRedraft?: (note: string | undefined) => void;477 /** Whether a "Draft again" is on its way: the button waits. */436 readonly busy?: boolean;479 /** What the last "Draft again" came back with, when it was refused. */437 readonly children?: ReactNode;438 readonly now?: DateTime.Utc;439}): ReactNode => {440 const open = proposal.state === "open";
43 unmodified lines
modified:apps/web/src/features/propose/client-territory.tsx+2 added-8 removed
1/**2 * The territory select, drawn in the browser only. The server renders its3 * stand-in: the trigger as it will look, holding the choice in sight and4 * in the form (a hidden input), never a native `<select>`; after5 * hydration the browser loads the kit's select over it.6 * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic7 * import below is dead code there and the Worker bundles none of it.2 * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic import3 * below is dead code there and the Worker bundles none of it.4 */5import { ClientOnly } from "@tanstack/react-router";6import { ChevronDown } from "lucide-react";7import { lazy, Suspense } from "react";813// A type-only import is erased, so the server bundles nothing of it.9import type { TerritorySelectProps } from "./territory-select.tsx";1011const SelectLater = import.meta.env.SSR12 ? undefined13 : lazy(() => import("./territory-select.tsx"));1420/** The select's place before it is drawn: its trigger, showing the choice. */15const StandIn = ({ choices, labelledBy, value }: TerritorySelectProps) => (16 <>17 <button18 aria-labelledby={labelledBy}
29 unmodified lines
modified:apps/web/src/features/propose/propose-link.tsx+2 added-5 removed
1/**2 * The way to the propose form, for signed-in members only. Who is signed in3 * is the browser's to learn (`whoAtom`), after the first paint, so the4 * server renders no link and the browser adds it, as the header's session2 * Who is signed in is the browser's to learn, after the first paint, so the3 * server renders no link and the browser adds it.5 * slot does (`features/auth/session-slot.tsx`).4 */5import { useAtomValue } from "@effect/atom-react";6import type { ProjectName } from "@repo/protocol/ids";7import { Option } from "effect";
13 unmodified lines
21 Propose an ask22 </a>23);2427/** `ProposeLink` once the browser knows someone is signed in; nothing before or otherwise. */25export const SignedInProposeLink = ({26 project,27}: {28 readonly project: ProjectName;
4 unmodified lines
modified:apps/web/src/features/propose/propose-view.tsx+2 added-39 removed
1/**2 * The propose form: a signed-in member writes a want, may name the3 * territory it belongs to (one of the project's top folders), and lets the4 * platform's agent draft the ask file and its failing check from it,5 * checked by default. A line from the why page (`?about&line&at`) starts the6 * want with where it points. The inspector says what makes a good want and7 * gives the same proposal as a command. Props in, markup out: the route8 * reads who is signed in and the project's paths, sends the payload, and9 * goes to the proposal once it is made.10 *11 * Only the want, the territory and the draft box: the files are the12 * agent's to write, or a person's through `propose --files` in the CLI.13 * Propose waits until there is a want, and says so on itself.14 */1import { Brand } from "@repo/brand";2import type { ProposeAsk } from "@repo/protocol/contracts";3import type { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";4import { Option } from "effect";
11 unmodified lines
16import { FactBlock } from "../shared/facts.tsx";17import { Workspace } from "../shared/shell/workspace.tsx";18import { ClientTerritorySelect } from "./client-territory.tsx";1934/** What `proposeAsk` takes, from its one schema. */20export type ProposePayload = typeof ProposeAsk.payloadSchema.Type;2137/** A line a why page points at: the file, the line and the commit it was read at. */22export interface About {23 readonly path: RepoPath;24 readonly line: number;25 readonly at: CommitSha;26}2728/**45 * The form's fields as `proposeAsk`'s payload: the want trimmed, the46 * territory when one is named, and `draft: true` only when the box is47 * checked (the contract takes no `draft: false`).29 * `draft: true` only when the box is checked: the contract takes no `draft:30 * false`.31 */32export const proposalPayload = (form: {33 readonly project: ProjectName;34 readonly want: string;
9 unmodified lines
4445 return form.draft ? { ...named, draft: true } : named;46};4765/** How a want about one line starts: `In \`src/format.ts\` line 12 at 4c2e6a8: `. */48export const wantAbout = ({ at, line, path }: About) =>49 `In \`${path}\` line ${line} at ${at.slice(0, 7)}: `;5069/**70 * The form's address for `project`, at the line a why page names when it71 * names one: where the project page links, and where sign-in comes back to.72 */51export const proposeFormPath = (52 project: ProjectName,53 about: Option.Option<About> = Option.none()54) =>
2 unmodified lines
57 onSome: ({ at, line, path }) =>58 `/${project}/proposals/new?${new URLSearchParams({ about: path, at, line: String(line) }).toString()}`,59 });6083/** The value the territory takes when the agent chooses it. */61const AGENT_CHOOSES = "";6286/** The territories the form offers: the agent's choice first, then each top folder. */63export const territoryChoices = (modules: readonly RepoPath[]) => [64 { label: "Let the agent choose", value: AGENT_CHOOSES },65 ...modules.map((module) => ({ label: module, value: module })),66];6792/** What Propose says: why it waits, or what it does. */68const proposeWords = (written: boolean, busy: boolean) => {69 if (!written) {70 return "Write the want first";71 }7273 return busy ? "Proposing" : "Propose";74};75101/** The proposal as a command, for a reader in a terminal. */76const PROPOSE_COMMAND = `${Brand.cli} propose --draft "<want>"`;7778const SignInFirst = ({79 about,
31 unmodified lines
111 <CommandLine command={PROPOSE_COMMAND} />112 </section>113);114141/** What makes a good want, and the same proposal from a terminal. */115const GoodWant = () => (116 <>117 <FactBlock label="A good want">118 <ul className="text-ui flex list-disc flex-col gap-1.5 pl-4">
110 unmodified lines
229230 {children}231232 <Button260 // Waiting for a want, it says so at full strength, dashed like any261 // field still to fill, rather than sitting grey.233 className={`tablet:h-9 tablet:w-fit h-11 w-full min-w-28 px-4 ${written ? "" : "text-muted-foreground border-dashed disabled:opacity-100"}`}234 data-written={written}235 disabled={busy || !written}236 type="submit"
5 unmodified lines
242 </form>243 );244};245275/** The form, the way to sign in, or the wait while the browser learns who is signed in. */246const ProposeBody = ({247 about,248 busy,249 checking,
46 unmodified lines
296 signedIn,297}: {298 readonly project: ProjectName;299 readonly signedIn: boolean;330 /** Whether the browser is still learning who is signed in. */300 readonly checking?: boolean;301 readonly about: Option.Option<About>;333 /** The project's top folders, each a territory to choose. */302 readonly modules: readonly RepoPath[];335 /** Sends the payload; the route goes to the proposal once it is made. */303 readonly onPropose?: (payload: ProposePayload) => void;337 /** Whether a proposal is on its way: the button waits. */304 readonly busy?: boolean;339 /** What the last proposal came back with, when it was refused. */305 readonly children?: ReactNode;306}): ReactNode => (342 // Below the shell's width the form comes first, and what makes a good343 // want follows it, rather than standing between the reader and the form.307 <div className="contents [&_[data-facts=inline]]:hidden">308 <Workspace309 crumbs={[310 { label: project, to: `/${project}` },
24 unmodified lines
modified:apps/web/src/features/propose/territory-select.tsx-9 removed
1/**2 * The territory a proposal names, chosen with the kit's select: the agent's3 * choice first, then each of the project's top folders in mono. Drawn in4 * the browser only (`client-territory.tsx`): Base UI's select, its5 * positioning and its scroll lock are the browser's to run, and the Worker6 * bundles none of them.7 */1import {2 Select,3 SelectContent,4 SelectItem,
1 unmodified line
6 SelectValue,7} from "../../components/ui/select.tsx";89export interface TerritorySelectProps {17 /** What the select offers, the agent's choice (`""`) first. */10 readonly choices: readonly {11 readonly label: string;12 readonly value: string;13 }[];
1 unmodified line
15 readonly onChange: (value: string) => void;16 readonly value: string;17}1827/** The trigger's look, shared with the server's stand-in for it. */19export const TRIGGER =20 "tablet:text-ui tablet:h-9 h-11 w-full max-w-xs text-base";2122export const TerritorySelect = ({
32 unmodified lines
modified:apps/web/src/features/shared/shell/app-shell.tsx+2 added-19 removed
1/**2 * The shell every page sits in: the rail (where you are), main (what is3 * waiting) and, when a page has typed facts, the inspector (the thing in4 * hand), on one paper ground parted by hairlines. From 1120 px the three5 * are columns, each scrolling on its own; below it a top bar holds the way6 * around, and on a phone a bottom bar holds the sections. The page's own7 * panes come from its `Workspace`.8 *9 * The shell owns the overlays (the rail as a sheet, More, Projects, the10 * keys dialog), loaded once the page is up and closed whenever the reader11 * moves, and the keyboard's one listener.12 *13 * One page is drawn outside it: the landing, whose route names14 * `staticData: { shell: "bare" }`. There the shell gives the page alone.15 */1import { useHydrated, useLocation, useMatches } from "@tanstack/react-router";2import { Suspense, useCallback, useMemo, useState } from "react";3import type { ReactNode } from "react";4
7 unmodified lines
12import { TopBar } from "./top-bar.tsx";1314declare module "@tanstack/react-router" {15 interface StaticDataRouteOption {31 /** `"bare"`: the page is drawn alone, with no rail, bars or overlays. */16 readonly shell?: "bare";17 }18}1936/** Whether the address's page is drawn outside the shell. */20const useBare = () =>21 useMatches({22 select: (matches) =>23 matches.some(({ staticData }) => staticData.shell === "bare"),
7 unmodified lines
31 const pathname = useLocation({ select: (location) => location.pathname });32 const hydrated = useHydrated();33 const bare = useBare();3452 // An overlay belongs to the address it opened on: a link inside it moves53 // the reader on, and it is gone from the next page.35 // An overlay belongs to the address it opened on: it is gone from the next36 // page.37 const [opened, setOpened] = useState<{38 readonly at: string;39 readonly overlay: Overlay;40 }>();
52 unmodified lines
modified:apps/web/src/features/shared/shell/bottom-bar.tsx-7 removed
1/**2 * The phone's bottom bar, fixed above the home indicator: Home, Asks,3 * Today, Projects (the switcher, as a sheet) and More (Docs, For agents, the project's4 * sections, the keys and the session), each a mark over its word. The5 * current page's item is ink at 600 with a rule on its top edge; the rest6 * are muted.7 */1import { CalendarCheck, Ellipsis, Folders, House, List } from "lucide-react";2import type { LucideIcon } from "lucide-react";34import { AppLink } from "../link.tsx";
64 unmodified lines
modified:apps/web/src/features/shared/shell/context-bar.tsx-16 removed
1/**2 * Main's context bar, 44 px, on the same line as the rail's wordmark: the3 * trail to the page on the left (the project first, ids in mono, each a4 * link but the last), and on the right what the page is in a word (its5 * state, or a list's count) and its one command to copy. From the shell's6 * width it stays at the top of main while main scrolls.7 */1import { Check, Copy } from "lucide-react";2import type { ReactNode } from "react";34import { Button } from "../../../components/ui/button.tsx";
1 unmodified line
6import { useNumberedCommand } from "../keys.tsx";7import { AppLink } from "../link.tsx";8import type { Crumb } from "./sections.ts";917/** The trail to the page, as a breadcrumb: each step a link but the page itself. */10export const Breadcrumb = ({11 crumbs,12}: {13 readonly crumbs: readonly Crumb[];
4 unmodified lines
18 const last = index === crumbs.length - 1;19 const face = mono ? "text-mono font-mono" : "";2021 return (30 // On a phone the top bar's Back link names the page above, so31 // the trail keeps only the page itself, whole rather than cut.22 <li23 className={`${last ? "flex" : "tablet:flex hidden"} min-w-0 items-center gap-1.5`}24 key={`${index}:${label}`}25 >
29 unmodified lines
55 </ol>56 </nav>57);5869/**70 * The page's one command, as a copy button: the command itself is the71 * button's text for a screen reader and a crawler, and its number (when the72 * single keys are on) is in its title.73 */59export const CopyCommand = ({ command }: { readonly command: string }) => {60 const { copied, copy } = useCopy(command);61 const number = useNumberedCommand(command);62
29 unmodified lines
92 state,93}: {94 readonly count?: string | undefined;95 readonly crumbs: readonly Crumb[];111 /** Anything else the page's bar holds at its end (the code pages' Facts button). */96 readonly end?: ReactNode;97 readonly primaryCommand?: string | undefined;98 readonly state?: ReactNode;99}) => (
18 unmodified lines
modified:apps/web/src/features/shared/shell/context.ts-23 removed
1/**2 * What the shell lends the parts inside it: a way to open its overlays (the3 * rail as a sheet, the phone's More and Projects sheets, the keys dialog),4 * the project the address is in, and what the root route read for the rail5 * (the list of projects, the count on Today). The shell's parts are views:6 * the root route wires the reads (`src/routes/__root.tsx`).7 */1import type { ProjectListing } from "@repo/protocol/domain/front-page";2import { ProjectName } from "@repo/protocol/ids";3import { useMatch } from "@tanstack/react-router";4import { Schema } from "effect";5import { createContext, useContext } from "react";6import type { ReactNode } from "react";715/** One of the shell's overlays. */8export type Overlay = "keys" | "menu" | "more" | "projects";910export interface Shell {11 readonly open: (overlay: Overlay) => void;
4 unmodified lines
16 // Outside the shell (a view's own test) there is nothing to open.17 },18});1928/** The shell's overlays, from inside it. */20export const useShell = (): Shell => useContext(ShellContext);2122const isProjectName = Schema.is(ProjectName);2333/**34 * The project the address is in: the `$project` route's name, when it is35 * one a project could have. None on the site's own pages, and none for a36 * name no project may take (the page says so itself).37 */24export const useCurrentProject = (): ProjectName | undefined =>25 useMatch({26 from: "/$owner/$project",27 select: ({ params }) =>28 isProjectName(params.project) ? params.project : undefined,29 shouldThrow: false,30 });3146/** What the root route read for the rail. */32export interface ShellReads {48 /** Every listed project, once the list has arrived in the browser; nothing before. */33 readonly projects?: readonly ProjectListing[] | undefined;50 /** Today's count, drawn at the end of its row (`RailCount`); nothing for a reader who decides nothing. */34 readonly todayCount?: ReactNode;35}3637export const ShellReadsContext = createContext<ShellReads>({});3856/**57 * Every listed project, once the list has arrived: the server renders the58 * rail without them (the current project's name comes from the address),59 * and nothing on a page waits on the list.60 */39export const useProjectList = (): readonly ProjectListing[] | undefined =>40 useContext(ShellReadsContext).projects;4164/** Today's count for the rail, when there is one. */42export const useTodayCount = (): ReactNode =>43 useContext(ShellReadsContext).todayCount;
modified:apps/web/src/features/shared/shell/facts-sheet.tsx-5 removed
1/**2 * A code page's facts as a sheet from the right, where the code keeps the3 * width (below 1440 px). Loaded once the page is up, and mounted closed so4 * it slides in when the Facts button opens it.5 */1import type { ReactNode } from "react";23import { Sheet, SheetContent } from "../../../components/ui/sheet.tsx";4import { CommandSlotProvider } from "../keys.tsx";
22 unmodified lines
modified:apps/web/src/features/shared/shell/lazy-overlays.ts+2 added-4 removed
1/**2 * The shell's overlays (`overlays.tsx`) and a code page's facts sheet3 * (`facts-sheet.tsx`), fetched once the page is up: the Worker never4 * renders one (an overlay opens on a press), and no page's first load5 * carries their dialog, sheet and combobox code.2 * Fetched once the page is up: the Worker never renders one, and no page's3 * first load carries their dialog, sheet and combobox code.4 */5import { lazy } from "react";67export const LazyOverlays = import.meta.env.SSR
6 unmodified lines
modified:apps/web/src/features/shared/shell/overlays.tsx+1 added-25 removed
1/**2 * The shell's overlays, loaded once the page is up, so no page's first load3 * carries them: the rail as a sheet (Menu, below the shell's width), the4 * phone's More and Projects sheets, and the keys dialog. Each opens on a5 * press, slides in over 200 ms, traps focus, and closes on Escape, a press6 * outside or Close; following a link inside closes it too (the shell's open7 * overlay belongs to the address it opened on).8 */1import { Brand } from "@repo/brand";2import { useRouter } from "@tanstack/react-router";3import { BookOpen, Bot, FolderInput, Keyboard } from "lucide-react";4import { useRef } from "react";
28 unmodified lines
33 RailFoot,34} from "./rail.tsx";3536export interface OverlayProps {45 /** The overlay open now; none when all are closed. */37 readonly overlay: Overlay | undefined;38 readonly onClose: () => void;39}4050/** A sheet's or dialog's open state, as the shell holds it. */41const openState = (open: boolean, onClose: () => void) => ({42 onOpenChange: (next: boolean) => {43 if (!next) {44 onClose();
1 unmodified line
46 },47 open,48});4960/** Whether the screen is at least a tablet's width, read when an overlay opens. */50const atLeastTablet = () => globalThis.matchMedia("(min-width: 40rem)").matches;5163/**64 * Every project, with a typed filter: choosing one opens its asks. The65 * names, their posture and their open asks come from the list the rail66 * reads.67 */52const ProjectSwitcher = ({53 input,54 onChosen,55}: {72 /** The filter, which takes focus when the sheet opens. */56 readonly input: RefObject<HTMLInputElement | null>;57 readonly onChosen: () => void;58}) => {59 const listed = useProjectList();
40 unmodified lines
100 return (101 <ComboboxItem className="h-10 gap-3" key={name} value={name}>102 <span className="min-w-0 truncate font-medium">{name}</span>103 {listing === undefined ? null : (121 // One group at the row's end, so the count sits beside122 // the posture rather than midway along the row.104 <span className="ml-auto flex shrink-0 items-center gap-3">105 <span className="text-muted-foreground text-label tabular-nums">106 {listing.openAsks} open107 </span>
9 unmodified lines
117 </Combobox>118 );119};120140/** The Projects sheet's body: the switcher, and the way to import a repo at its foot. */121export const ProjectsSheetBody = ({122 input,123 onChosen,124}: {
14 unmodified lines
139 </div>140 </>141);142163/** The phone's More: Docs, For agents, the project's sections, the keys, the session. */143const More = () => {144 const project = useCurrentProject();145 const listed = useProjectList();146 const { open } = useShell();
87 unmodified lines
234 </Dialog>235 );236};237259/**260 * Every overlay the shell has, each closed until the shell opens it. They261 * stay mounted once loaded, so each one slides in from closed.262 */238/** They stay mounted once loaded, so each one slides in from closed. */239const ShellOverlays = ({ onClose, overlay }: OverlayProps) => {240 const filter = useRef<HTMLInputElement>(null);241242 return (
31 unmodified lines
modified:apps/web/src/features/shared/shell/rail-slot.tsx-22 removed
1/**2 * The rail's slot: room under the project's line for what a page keeps3 * beside it while the reader moves between its siblings (the code pages'4 * file tree). A route names the component that fills it in its5 * `staticData.rail`; the shell draws the deepest one the address matches,6 * on the server too. Sibling routes that name the same component keep one7 * mounted instance as the reader moves between them, since the rail itself8 * never leaves the page.9 *10 * ```tsx11 * const CodeRail = () => <RailSlot label="Files"><ProjectTree /></RailSlot>;12 *13 * export const Route = createFileRoute("/$owner/$project/blob/$rev/$")({14 * staticData: { rail: CodeRail },15 * });16 * ```17 */1import { useMatches } from "@tanstack/react-router";2import { createElement } from "react";3import type { ComponentType, ReactNode } from "react";45declare module "@tanstack/react-router" {6 interface StaticDataRouteOption {24 /** What fills the rail's slot on this route's pages, and on its children's. */7 readonly rail?: ComponentType;8 }9}1029/** The slot's frame: the rest of the rail's height, scrolling on its own. */11export const RailSlot = ({12 children,13 label = "Files",14}: {15 readonly children: ReactNode;35 /** What the slot holds, for a screen reader moving by region. */16 readonly label?: string;17}) => (18 <section19 aria-label={label}
3 unmodified lines
23 {children}24 </section>25);2647/** The component the deepest matched route puts in the slot, when one does. */27export const useRailContent = (): ComponentType | undefined =>28 useMatches({29 select: (matches) =>30 matches.findLast(({ staticData }) => staticData.rail !== undefined)31 ?.staticData.rail,32 });3355/** The slot's content for the address, or nothing. */34export const RailSlotOutlet = (): ReactNode => {35 const Content = useRailContent();3637 return Content === undefined ? null : createElement(Content);
1 unmodified line
modified:apps/web/src/features/shared/shell/rail.tsx+4 added-52 removed
1/**2 * The rail: where the reader is. Top to bottom, the wordmark, which leads3 * to the landing; the site's sections (Home, Asks, Today, Docs, For4 * agents), each a word beside its mark; the5 * projects, the current one first with its own sections under it; the6 * rail's slot on pages that fill it (the code pages' tree); and the session7 * with the Keys button at the foot.8 *9 * From the shell's width it is a column beside main; below it, the same10 * content opens as a sheet from the top bar's Menu (`RailContent`). The11 * current item is filled with the surface and set in ink at 600, never12 * coloured; the router marks a link to the page being read13 * `aria-current="page"`, and a section holding the page is marked14 * `aria-current="true"`.15 */1import { Brand } from "@repo/brand";2import type { ProjectListing } from "@repo/protocol/domain/front-page";3import type { ProjectName } from "@repo/protocol/ids";4import type { Posture } from "@repo/protocol/posture";
28 unmodified lines
33} from "./context.ts";34import { RailSlotOutlet, useRailContent } from "./rail-slot.tsx";35import { projectSections, sectionOf } from "./sections.ts";3652/** A row of the rail, before the fill that marks the current one. */37const RAIL_BASE =38 "text-ui text-foreground hover:bg-surface flex h-8 min-w-0 items-center gap-2.5 px-2 no-underline transition-colors duration-[120ms] focus-visible:outline-offset-[-2px] [&[aria-current]]:font-semibold [&[aria-current]>svg]:text-foreground";3956/** A row of the rail: a word (and its mark), 32 px, filled when current. */40export const RAIL_ROW = `${RAIL_BASE} [&[aria-current]]:bg-surface`;4159/** A row's mark: 16 px at the marks' stroke, muted until the row is current. */42const MARK = "text-muted-foreground size-4 shrink-0";4344const SITE = [45 { icon: House, label: "Home", to: HOME_PATH },
6 unmodified lines
52 readonly label: string;53 readonly to: string;54}[];5574/** Only the page itself is current; its search (a filter, a selection) does not count. */56const EXACT = { exact: true, includeSearch: false } as const;5777/** A count of things at a rail row's end, in tabular figures, with what it counts for a screen reader. */58export const RailCount = ({59 count,60 of,61}: {
5 unmodified lines
67 <span className="sr-only"> {of}</span>68 </span>69);7091/** Today's count, as the root route read it. */71const TodayCount = () => useTodayCount() ?? null;7294/** The wordmark, leading to the landing (which sends a signed-in reader home). */73export const Wordmark = ({74 className = "",75}: {76 readonly className?: string;
6 unmodified lines
83 {Brand.name}84 </AppLink>85);86109/** Home, Asks, Today, Docs and For agents. */87const SiteSections = () => (88 <ul className="flex flex-col gap-px">89 {SITE.map(({ icon: Icon, label, to }) => (90 <li key={to}>
6 unmodified lines
97 ))}98 </ul>99);100124/** A project's posture at its row's end: the mark in its role, its short form muted (the head's), the full label as its title. */101export const PostureMark = ({ posture }: { readonly posture: Posture }) => {102 const { icon: Icon, tone } = POSTURE_MARKS[posture];103104 return (
12 unmodified lines
117 </span>118 );119};120145/**146 * A project's row: its name, and its posture once the list has it. The147 * current project's is in ink at 600 but unfilled, so the page being read148 * (a section under it) is the one filled row.149 */121const ProjectRow = ({122 current,123 listing,124 project,
13 unmodified lines
138 {listing === undefined ? null : <PostureMark posture={listing.posture} />}139 </AppLink>140);141171/** The current project's sections, indented under it, the open asks counted beside Asks. */142export const ProjectSectionList = ({143 openAsks,144 project,145}: {
27 unmodified lines
173 </ul>174 );175};176207/** The list's place while it is read: three rows of the rail's height. */177const PLACEHOLDERS = ["w-24", "w-20", "w-28"] as const;178179const PlaceholderRows = () => (180 <li aria-hidden="true" className="flex flex-col gap-px">
5 unmodified lines
186 </li>187);188189/**221 * The projects: the current one first, its sections under it, so the list222 * arriving after the page moves nothing above it; then the others that223 * lead (the most open asks first, a tie by name), up to eight in all, and224 * the switcher for the rest.190 * The current one first, so the list arriving after the page moves nothing191 * above it.192 */193const Projects = () => {194 const current = useCurrentProject();195 const listed = useProjectList();
58 unmodified lines
254 );255};256257/**291 * A ghost button set in muted text, ink on hover. The colour comes from292 * around the button, not through its `className`: the kit merges classes,293 * reads an unknown `text-*` as a colour, and would drop the button's294 * `text-ui` size for a colour given there.258 * The colour comes from around the button: the kit merges classes, reads an259 * unknown `text-*` as a colour, and would drop the button's `text-ui` size.260 */261const Quiet = ({ children }: { readonly children: ReactNode }) => (262 <span className="text-muted-foreground flex shrink-0">{children}</span>263);264300/** The rail's foot: the session, and the Keys button that opens the `?` dialog. */265export const RailFoot = () => {266 const { open } = useShell();267268 return (
14 unmodified lines
283 </div>284 );285};286323/** The rail's sections and projects: the column's middle, and the Menu sheet's body. */287export const RailContent = (): ReactNode => (288 <div className="flex flex-col gap-2 px-2 py-2">289 <SiteSections />290 <Projects />291 </div>292);293331/**332 * The project's line in the code pages' rail: its name and the section333 * being read, opening to the project's sections, so the tree below gets334 * the height.335 */294const ProjectLine = ({ project }: { readonly project: ProjectName }) => {295 const listed = useProjectList();296297 const section = useLocation({
28 unmodified lines
326 </details>327 );328};329372/**373 * The rail as a column, from the shell's width. On a page that fills the374 * slot (the code pages) it gives the slot the height: the site's sections375 * and the projects fold into the wordmark row's Menu, and the project's376 * sections into its line.377 */330export const Rail = () => {331 const slotted = useRailContent() !== undefined;332 const project = useCurrentProject();333 const { open } = useShell();
37 unmodified lines
modified:apps/web/src/features/shared/shell/sections.ts-36 removed
1/**2 * Where a reader can be: the site's sections, a project's, and the trail of3 * crumbs from the site to the page at an address. The rail, the top bar,4 * the bottom bar, the section row and the context bar all read them here,5 * so one address names one place everywhere.6 */1import { projectAddressOf } from "@repo/protocol/ids";2import { Option } from "effect";34import { segmentsOf } from "../paths.ts";512/** Which of a project's pages is being read. */6export type ProjectTab =7 | "code"8 | "env"9 | "landings"
1 unmodified line
11 | "overview"12 | "people"13 | "refs";1422/** One of a project's sections: its word, its page, and the tab it is. */15export interface Section {16 readonly label: string;17 readonly tab: ProjectTab;18 readonly to: string;19}2029/**30 * A project's sections (`project` as the address names it), in the order31 * every list of them shows. The project's32 * home is its asks; its `people` page is its policy (who decides, vouches,33 * budgets), and reads so, at the address it has always had.34 */21export const projectSections = (project: string): readonly Section[] => [22 { label: "Asks", tab: "overview", to: `/${project}` },23 { label: "Code", tab: "code", to: `/${project}/tree/main` },24 { label: "Landings", tab: "landings", to: `/${project}/commits/main` },
2 unmodified lines
27 { label: "Ledger", tab: "ledger", to: `/${project}/ledger` },28 { label: "Env shape", tab: "env", to: `/${project}/env` },29];3045/** The first segment of each of a project's pages, by the section it sits in. */31const SECTION_OF = {32 answers: "overview",33 asks: "overview",34 blob: "code",
6 unmodified lines
41 tree: "code",42 why: "code",43} as const satisfies Record<string, ProjectTab>;4460/** The site's own first segments: every other one starts a project's address. */45const SITE = new Set([46 "agents",47 "asks",48 "docs",
2 unmodified lines
51 "people",52 "today",53]);5471/**72 * The project an address is in, as the address spells it, and the73 * segments of its page after the name; none on the site's own pages. The74 * name is read by the protocol's one reader of addresses, so75 * `/oscabriel/datekit/ledger` and `/github.com/pallets/click/tree/main` (or76 * the router's own `/github.com%2Fpallets/click/…`) each find theirs.77 */55const addressOf = (pathname: string) => {56 const segments = segmentsOf(pathname);57 const [first] = segments;58
1 unmodified line
60 ? undefined61 : Option.getOrUndefined(projectAddressOf(segments));62};6387/** The project an address is in; none on the site's own pages. */64export const projectOf = (pathname: string): string | undefined =>65 addressOf(pathname)?.spelled;6691/** The project section an address sits in; none for a page under none (a decision, a proposal). */67export const sectionOf = (pathname: string): ProjectTab | undefined => {68 const address = addressOf(pathname);6970 if (address === undefined) {
6 unmodified lines
77 ? "overview"78 : Object.entries(SECTION_OF).find(([segment]) => segment === page)?.[1];79};80106/** One step of the trail to a page: its word, its page (none for the page itself), and whether it is an id. */81export interface Crumb {82 readonly label: string;83 readonly mono?: boolean;84 readonly to?: string;
8 unmodified lines
93 people: "Policy",94 refs: "Refs",95} as const satisfies Record<ProjectTab, string>;96123/** A section's crumb, linked to its page when a page sits below it. */97const sectionCrumb = (98 project: string,99 tab: ProjectTab,100 below: boolean
3 unmodified lines
104105 return below && section !== undefined ? { label, to: section.to } : { label };106};107135/** A project's crumb, then its section's. */108const projectCrumbs = (109 project: string,110 tab: ProjectTab,111 below: boolean
1 unmodified line
113 { label: project, to: `/${project}` },114 sectionCrumb(project, tab, below),115];116145/** A code page's trail: Code, then the path in hand (none at the root). */117const pathCrumbs = (project: string, path: string): readonly Crumb[] =>118 path === ""119 ? projectCrumbs(project, "code", false)120 : [...projectCrumbs(project, "code", true), { label: path, mono: true }];121151/** The site's own pages' trails, by first segment. */122const SITE_CRUMBS = {123 agents: () => [{ label: "For agents" }],124 asks: () => [{ label: "Asks" }],125 docs: (page: string | undefined) =>
7 unmodified lines
133 string,134 (second: string | undefined) => readonly Crumb[]135>;136167/** A project's subject pages' trails (an ask, an answer, a commit, a path…), by second segment. */137const SUBJECT_CRUMBS = {138 answers: (project: string, ask: string) => [139 ...projectCrumbs(project, "overview", true),140 { label: ask, mono: true, to: `/${project}/asks/${ask}` },
26 unmodified lines
167 string,168 (project: string, third: string, rest: string) => readonly Crumb[]169>;170202/**203 * The trail from the site to the page at `pathname`: the project first, then204 * its section, then the thing in hand (an ask, a commit, a path), each a205 * link but the last. A page that knows better gives `Workspace` its own.206 */171export const crumbsFor = (pathname: string): readonly Crumb[] => {172 const [first, second] = segmentsOf(pathname);173174 if (first === undefined) {
35 unmodified lines
modified:apps/web/src/features/shared/shell/selection.ts+2 added-27 removed
1/**2 * A list's selected row, kept in the address's search (`?ask=format-ordinal`,3 * `?decision=dec-000001`), so the server renders the row selected with its4 * facts in the inspector, and a link to them can be shared. Selecting5 * replaces the history entry and keeps every pane's scroll; `Escape` clears6 * it (`useEscapeClears`).7 *8 * A route whose list selects keeps the param out of its loader: `loaderDeps`9 * leaves it out, so a selection never reads the list again, and10 * `shouldReload: reloadOnEnter` keeps a list from reading again on every11 * selection once it is stale.12 *13 * ```tsx14 * const { selected, select } = useSelection("ask");15 * const { focused } = useListKeys(ids, select);16 * <Workspace facts={selected === undefined ? <ProjectFacts /> : <AskFacts ask={selected} />} factsKey={selected} … />17 * ```2 * A route whose list selects leaves the param out of `loaderDeps`, so a3 * selection never reads the list again.4 */5import {6 defaultStringifySearch,7 useLocation,
3 unmodified lines
11import { useCallback } from "react";1213import { useEscapeClears } from "../keys.tsx";1429/** The search params a list selects by. */15export type SelectionParam = "ask" | "decision";1632/** A selection as an address's search carries it. */17const Selection = Schema.Struct({18 ask: Schema.optionalKey(Schema.String),19 decision: Schema.optionalKey(Schema.String),20});2122const decodeSelection = Schema.decodeUnknownOption(Selection);2340/**41 * `searchStr` (`?filter=…&ask=…`) with `param` set to `id`, or without it,42 * each value written as the router writes it.43 */24export const searchWith = (25 searchStr: string,26 param: SelectionParam,27 id?: string
53 unmodified lines
8182 return { clear, select, selected };83};84105/**106 * A route's `shouldReload` for a list that selects: read the list when the107 * reader comes to it (or a link to it is preloaded), not again on each108 * selection; its atoms keep it live.109 */85export const reloadOnEnter = ({ cause }: { readonly cause: string }) =>86 cause !== "stay";
modified:apps/web/src/features/shared/shell/top-bar.tsx-9 removed
1/**2 * The top bar, below the shell's width, where the rail is not drawn. On a3 * tablet (48 px): Menu (the rail as a sheet), the wordmark, the current4 * project as a switcher, and the session at the end. On a phone (44 px):5 * Back to the page above on a subject page (an ask, an answer, a commit),6 * else the wordmark, then the project's switcher; the bottom bar holds the7 * rest.8 */1import { useLocation } from "@tanstack/react-router";2import { ChevronLeft, ChevronsUpDown, Menu } from "lucide-react";34import { Button } from "../../../components/ui/button.tsx";
2 unmodified lines
7import { useCurrentProject, useShell } from "./context.ts";8import { Wordmark } from "./rail.tsx";9import { crumbsFor } from "./sections.ts";1019/** The page above a subject page (its crumb before last), when the address is one. */11const parentOf = (pathname: string) => {12 const crumbs = crumbsFor(pathname);13 const parent = crumbs.at(-2);14
65 unmodified lines
modified:apps/web/src/features/shared/shell/workspace.tsx-45 removed
1/**2 * One page's panes: main (the context bar, the page's head, its toolbar and3 * its content) and, when the page has typed facts, the inspector, both4 * rendered in one pass on the server. Every page renders one `Workspace`.5 *6 * From the shell's width main scrolls on its own and the inspector is a7 * column of its own scroll on the right, its heading announcing what it8 * describes as it changes. Below it, the facts sit in one slot after the9 * page's head: open on a subject's page, a disclosure on a list's (whose10 * summary keeps one fact in sight). Code pages keep the width for the code:11 * the inspector is a column from 1440 px and a sheet below, behind a Facts12 * button in the context bar.13 *14 * Rows and the head stop at 56 rem, left-aligned; prose at 70 ch is the15 * page's; code takes the whole pane.16 */1import { useHydrated, useLocation, useRouter } from "@tanstack/react-router";2import { Predicate } from "effect";3import { ChevronDown, PanelRight } from "lucide-react";4import { Suspense, useState } from "react";
7 unmodified lines
12import { crumbsFor } from "./sections.ts";13import type { Crumb } from "./sections.ts";1415export interface WorkspaceProps {32 /** The trail to the page; the address's when left out. */16 readonly crumbs?: readonly Crumb[];34 /** The page head's title: the headline, or a title when it runs long. */17 readonly title: ReactNode;36 /** The title is someone's own words (a want), shown as they wrote it. */18 readonly said?: boolean | undefined;38 /** A status line under the title. */19 readonly status?: ReactNode;40 /** A 14 px muted line under the status: kind, asker, age. */20 readonly meta?: ReactNode;42 /** The subject's state in a word and a mark, at the context bar's end. */21 readonly state?: ReactNode;44 /** A list's count, at the context bar's end ("10 open asks, 8 open to take"). */22 readonly count?: string;46 /** The page's one command, copied from the context bar. */23 readonly primaryCommand?: string;48 /** Filters, view toggles, sort: a bar that stays under the context bar. */24 readonly toolbar?: ReactNode;50 /** The inspector's fact blocks; inline below the shell's width. */25 readonly facts?: ReactNode;52 /** What the facts describe: "This ask", "Selected ask", "How a change lands here". */26 readonly factsHeading?: string;54 /** The one fact a list keeps in sight below the shell's width (its posture). */27 readonly factsSummary?: ReactNode;56 /** The facts' subject (a selected row's id): a new one settles in. */28 readonly factsKey?: string;58 /** A document (the default), a list, or code. */29 readonly variant?: "code" | "document" | "list";60 /** Main's content. */30 readonly children: ReactNode;31}3264/** Main's side padding at each width. */33export const GUTTER = "px-4 tablet:px-5 shell:px-6";3467/** How wide rows and the head run: 56 rem, from the left. */35export const MEASURE = "max-w-[56rem]";3670/** Past this many characters a title is set a step down, to stay within three lines. */37const LONG_TITLE = 80;3839const PageHead = ({40 meta,
18 unmodified lines
59 )}60 </div>61);6297/** The inspector's heading row: names what the facts describe, and announces it when it changes. */63const FactsHeading = ({ heading }: { readonly heading: string }) => (64 <div65 aria-live="polite"66 className="border-rule bg-background sticky top-0 z-10 flex h-11 shrink-0 items-center border-b px-4"
1 unmodified line
68 <h2 className="text-ui font-semibold">{heading}</h2>69 </div>70);71107/** The facts settling in when their subject changes: 120 ms of opacity, nothing that moves. */72const Settling = ({73 children,74 id,75}: {
4 unmodified lines
80 {children}81 </div>82);83120/** The facts in main, after the head, below the shell's width. */84const InlineFacts = ({85 facts,86 heading,87 list,
34 unmodified lines
122 <div className="flex flex-col">{facts}</div>123 </section>124 );125163/** A code page's Facts button, and its facts as a sheet from the right. */126const FactsSheet = ({127 facts,128 heading,129}: {
48 unmodified lines
178 toolbar,179 pathname,180 variant = "document",181}: WorkspaceProps & {220 /** The address, for the default trail; none outside a router. */182 readonly pathname: string;183}) => {184 const hasFacts = facts !== undefined && facts !== null;185 const code = variant === "code";
12 unmodified lines
198 count={count}199 crumbs={crumbs ?? crumbsFor(pathname)}200 end={201 code && hasFacts ? (241 // The sheet belongs to the page it opened on.202 <FactsSheet203 facts={facts}204 heading={factsHeading}205 key={pathname}
69 unmodified lines
275 pathname={useLocation({ select: (location) => location.pathname })}276 />277);278319/**320 * A page's panes. Inside the router its trail defaults to its address's; a321 * view rendered alone (its own test) draws the same panes with the trail322 * it is given.323 */279export const Workspace = (props: WorkspaceProps) =>280 Predicate.isNotNullish(useRouter({ warn: false })) ? (281 <AtAddress {...props} />282 ) : (
2 unmodified lines
modified:apps/web/src/features/shared/ask-progress.ts+8 added-47 removed
1/**2 * Where each ask of a project stands, folded from the project's events (the3 * `watch` replay its page already reads): who holds it, its rounds, its4 * latest outcome, whether it landed; whose move that leaves; a family's5 * marks against the parent's stored children; and which landings a page6 * that is open should stamp.7 *8 * Pure functions over events, with no transport, so a view can take what9 * they return (and their types) as props.10 */1import type { Ask } from "@repo/protocol/domain/ask";2import { ProjectEvent } from "@repo/protocol/domain/event";3import { Outcome } from "@repo/protocol/domain/outcome";4import type { AskId, CommitSha, Handle, LandedSha } from "@repo/protocol/ids";5import type { DateTime } from "effect";6import { constVoid, identity } from "effect/Function";718/** One answer checked: the commit pushed, what the gate said, and when. */8export interface Round {9 readonly at: DateTime.Utc;10 readonly head: CommitSha;11 readonly outcome: Outcome;12 readonly seq: number;13}1426/** Where one ask stands, as its events tell it. */15export interface AskProgress {28 /** Who holds it now: the last claim, until it is released, lapses or the ask closes. */16 readonly claimant?: Handle;30 /** The landing that closed it, and that event's number. */17 readonly landed?: { readonly sha: LandedSha; readonly seq: number };18 readonly lastPush?: { readonly at: DateTime.Utc; readonly head: CommitSha };33 /** The number of the last event about it. */19 readonly lastSeq: number;20 /**36 * The last outcome of the current attempt: a new claim, a release or a37 * lapse starts the ask over, so an earlier answerer's refusal no longer38 * speaks for it (its round stays in `rounds`).21 * A new claim, a release or a lapse starts the ask over, so an earlier22 * answerer's refusal no longer speaks for it.23 */24 readonly latest?: Outcome;41 /** When it was opened, once the events say so. */25 readonly opened?: DateTime.Utc;43 /** Every answer checked, oldest first. */26 readonly rounds: readonly Round[];27}2847/** One child's place in its family. */29export type Mark =30 | "checking"31 | "claimed"32 | "landed"33 | "open"34 | "refused"35 | "waiting";3656/** A family's progress: each stored child's mark, in order, and how many landed of how many. */37export interface Family {38 readonly children: readonly { readonly ask: AskId; readonly mark: Mark }[];39 readonly landed: number;40 readonly total: number;41}4263/** Who acts next on an ask. */43export type Move = "answerer" | "decider" | "none" | "parent" | "platform";4466/** The highest event number among `events`; 0 when there are none. */45export const lastSeq = (events: readonly ProjectEvent[]): number => {46 let highest = 0;4748 for (const { seq } of events) {
4 unmodified lines
53};5455const fresh: AskProgress = { lastSeq: 0, rounds: [] };5679/** `progress` with nobody holding the ask. */57const unclaimed = ({ claimant: _held, ...rest }: AskProgress): AskProgress =>58 rest;5983/** `progress` started over: nobody holds the ask, and no outcome speaks for it. */60const startedOver = ({61 claimant: _held,62 latest: _said,63 ...rest64}: AskProgress): AskProgress => rest;6590/** `event` applied to `states`, when it is about one ask. */66const apply = (states: Map<AskId, AskProgress>, event: ProjectEvent): void => {67 const change = (68 ask: AskId,69 step: (progress: AskProgress) => AskProgress
44 unmodified lines
114 });115};116117/**143 * Where each ask stands, from a project's events: applied in their number's144 * order, each number once, so a replay heard twice or out of order folds to145 * the same map.118 * Applied in their number's order, each number once, so a replay heard twice or119 * out of order folds to the same map.120 */121export const askStates = (122 events: readonly ProjectEvent[]123): ReadonlyMap<AskId, AskProgress> => {
9 unmodified lines
133134 return states;135};136163/**164 * Who acts next, from the latest outcome alone: a refusal leaves it to the165 * answerer, a wait on a decision or a finish to a decider, a check under166 * way to the platform, a wait on the parent to the rest of its family. With167 * nothing judged yet, a claimed ask is its answerer's to push and an open168 * one nobody's in particular.169 */137export const whoseMove = (latest?: Outcome, claimant?: Handle): Move => {138 if (latest === undefined) {139 return claimant === undefined ? "none" : "answerer";140 }
7 unmodified lines
148 WaitingOnParent: (): Move => "parent",149 });150};151185/** One child's mark: landed first, then what its latest outcome says, then whether someone holds it. */152export const markOf = (progress: AskProgress | undefined): Mark => {153 if (progress === undefined) {154 return "open";155 }
18 unmodified lines
174 return claimant === undefined ? "open" : "claimed";175};176177/**212 * A family's marks: one per child the parent stores (`showAsk(parent)`'s213 * `blockedBy`, in its order), and how many of them landed. A listing's214 * `blockedBy` names only the children still open, so it cannot count them.178 * A listing's `blockedBy` names only the children still open, so it cannot179 * count them.180 */181export const familyMarks = (182 parent: Ask,183 states: ReadonlyMap<AskId, AskProgress>
10 unmodified lines
194 };195};196197/**233 * The asks whose landing a page that is open should stamp: landed in234 * `next`, not in `previous` (the read before; none for the first read), and235 * closed by an event after the highest number of the first read the page236 * settled on (`mountSeq`). A replay that already held a landing never237 * stamps it, and a landing stamps once, whether the stream or the poll238 * brought it.198 * A replay that already held a landing never stamps it, and a landing stamps199 * once, whether the stream or the poll brought it.200 */201export const stampsFrom = (202 previous: ReadonlyMap<AskId, AskProgress> | undefined,203 next: ReadonlyMap<AskId, AskProgress>,
11 unmodified lines
modified:apps/web/src/features/shared/classes.ts+2 added-8 removed
1/**2 * The class strings many views share, in a module with no view of its own,3 * so a route that needs one never pulls a view (and what that view4 * imports) into the code every page loads.2 * A module with no view, so a route that needs a class never pulls a view into3 * the code every page loads.4 */57/** A section's heading, the "title" step of the type scale. */6export const SECTION = "text-lg font-semibold tracking-[-0.01em]";710/** The mono face for names a terminal prints: ids, kinds, territories. */8export const ID = "font-mono text-mono";913/** Text that is code: an id, a path, a SHA, a command's name; it wraps anywhere. */10export const CODE = "font-mono text-mono [overflow-wrap:anywhere]";1116/** A link in running text: underlined in the rule colour, darker on hover. */12export const LINK = "decoration-rule underline hover:decoration-current";1319/** A field's label: small, muted, above or beside its value. */14export const LABEL = "text-muted-foreground text-label font-medium";
modified:apps/web/src/features/shared/command.tsx+4 added-27 removed
1// A shell line a reader runs next: a refusal's `next`, a clone URL, the2// install line. The terminal is where work happens, so every page that3// suggests an action shows its command, whole and copyable, never a form.4//5// A page marks its main commands `numbered`: while the single keys are on,6// each shows its number before the `$`, and that number key copies it7// ("Copy (1)" in the button's title).1import { Check, Copy } from "lucide-react";2import { createContext, useContext } from "react";3import type { ReactNode } from "react";45import { Button } from "../../components/ui/button.tsx";6import { useCopy } from "./copy-action.tsx";7import { useNumberedCommand } from "./keys.tsx";816/**17 * Where a command line is drawn: a box hugging its command in main, or18 * the inspector's bleed form, pane-wide between two hairlines, where the19 * column is narrow and every character of the line counts.20 */9type Form = "bleed" | "box";1011const FormContext = createContext<Form>("box");1225/** Command lines under it take the inspector's bleed form. */13export const InspectorCommands = ({14 children,15}: {16 readonly children: ReactNode;17}) => <FormContext value="bleed">{children}</FormContext>;1832/** How far a line of the command hangs, in ch, when the column breaks it: less in the inspector's narrow column. */19const HANGS = { bleed: 2, box: 6 } as const satisfies Record<Form, number>;2035/** The box around the command, in each form. */21const BOXES = {22 bleed:23 "border-rule bg-surface text-mono leading-terminal -mx-4 flex min-w-0 items-start gap-2 border-y py-1 pr-1 pl-4 font-mono",24 box: "border-rule bg-surface text-mono leading-terminal flex w-fit max-w-full min-w-0 items-start gap-2 border py-1 pr-1 pl-3 font-mono",25} as const satisfies Record<Form, string>;2627/**43 * A line's hang: `hang` ch, or less on a line so short that its longest word44 * would not fit beside the hang. The box hugs its longest line, so a line's45 * room beside its hang is its own length less the hang; a word wider than46 * that room is broken in two (`<cli> today` read "tod" / "<cli> ay"). Such a47 * line fits whole wherever its box does, so its hang never shows.28 * The box hugs its longest line, so a word wider than the room beside the hang29 * would be broken in two; such a line fits whole wherever its box does.30 */31const hangOf = (hang: number, words: readonly string[], line: string) =>32 Math.min(33 hang,34 line.length - Math.max(0, ...words.map(({ length }) => length))35 );3655// The command's words, each kept whole on its line: a narrow column breaks56// the line between words, never after a word's own hyphen57// (`lint-heading-levels`, `--project`) nor before a closing ` \`; a word58// longer than the line (a URL) still breaks, anywhere. Each of the59// command's own lines hangs, so a line the column breaks reads as one line60// going on. The text is the command's, space for space.37// Breaks between words, never after a word's own hyphen (`--project`) nor38// before a closing ` \`.39const wordsOf = (command: string, form: Form) =>40 command.split("\n").map((line, at, lines) => {41 const parts = line.split(/(?<space>\s+)(?!\\$)/u);42
83 unmodified lines
126 command,127 numbered = false,128}: {129 readonly command: string;152 /** One of the page's main commands, which a number key copies. */130 readonly numbered?: boolean;131}) =>132 numbered ? (133 <NumberedLine command={command} />
3 unmodified lines
modified:apps/web/src/features/shared/copy-action.tsx+2 added-23 removed
1/**2 * A command copied with one press. The command itself is always text in3 * the page (inside the button, visually hidden where only the icon shows),4 * so an agent reading the HTML and a screen reader both get it, never only5 * a clipboard payload. After a copy the button shows a check and says6 * "Copied" for two seconds, once, in a polite live region.7 *8 * - `CopyAction`: a row's ghost button, 32 px square, named for what it9 * copies ("Copy claim command").10 * - `CommandChip`: the command shown whole, small, at the end of a status11 * line; pressing it copies it.12 *13 * Either can be numbered: while the single keys are on, its number copies14 * it, and shows in its title ("Copy claim command (1)").2 * The command is always text in the page, so an agent reading the HTML and a3 * screen reader both get it, never only a clipboard payload.4 */5import { Brand } from "@repo/brand";6import { Effect, Option } from "effect";7import { Check, Copy } from "lucide-react";8import { useState } from "react";910import { useCopiedCommand, useNumberedCommand } from "./keys.tsx";1123/** Copy `command`, then show it copied for two seconds. */12const copyFor = (command: string, shown: (copied: boolean) => void) =>13 Effect.tryPromise(() => navigator.clipboard.writeText(command)).pipe(14 Effect.andThen(15 Effect.sync(() => {
8 unmodified lines
24 ),25 Effect.ignore26 );2740/**41 * Copying `command`: whether it was just copied (by this control, or by its42 * number key), and the press that copies it.43 */28export const useCopy = (command: string) => {29 const [pressed, setPressed] = useState(false);30 const byKey = useCopiedCommand();31
6 unmodified lines
38};3940interface CopyProps {41 readonly command: string;58 /** What the button copies, as its accessible name: "Copy claim command". */42 readonly label: string;60 /** Whether the page's number keys reach it. */43 readonly numbered?: boolean;44}4546const ActionButton = ({
35 unmodified lines
82const NumberedAction = (props: Omit<CopyProps, "numbered">) => (83 <ActionButton {...props} number={useNumberedCommand(props.command)} />84);85104/** A row's copy button: the icon in sight, the command in the text. */86export const CopyAction = ({ numbered = false, ...props }: CopyProps) =>87 numbered ? (88 <NumberedAction {...props} />89 ) : (90 <ActionButton {...props} number={undefined} />91 );92112/** An open ask's claim command, as a row's copy button. */93export const ClaimAction = ({94 ask,95 project,96}: {
5 unmodified lines
102 label="Copy claim command"103 />104);105126/** A command shown whole and small (a status line's next step); pressing it copies it. */106export const CommandChip = ({ command }: { readonly command: string }) => {107 const { copied, copy } = useCopy(command);108 const Icon = copied ? Check : Copy;109
22 unmodified lines
modified:apps/web/src/features/shared/credits.tsx+1 added-21 removed
1/**2 * A landing's trailers, as the commit carries them: credit first, in the3 * order of `CreditRole`'s literals (`Asked-by` before `Signed-off-by`), one4 * `Role: handle` line per person; then the `Held-back:` commitment, if the5 * landing was judged by held-back checks; then, apart and labelled, the6 * agents people worked through. `Assisted-by` is a disclosure, never credit7 * (GLOSSARY.md "Credit").8 *9 * `CompactCredit` is the same credit in one line for a row ("Asked by10 * ines-v · answered by tamsin"): the roles in the same order, each person11 * linked, and never an agent.12 */1/** `Assisted-by` is a disclosure, never credit. */2import { CreditRole } from "@repo/protocol/domain/credit";3import type { AgentTrailer, Credit } from "@repo/protocol/domain/credit";4import { LockKeyhole } from "lucide-react";5import { Fragment } from "react";
1 unmodified line
7import { HandleLink } from "./handle.tsx";89const rank = (credit: Credit) => CreditRole.literals.indexOf(credit.role);1022/** Credits in trailer order; people in one role keep the order given. */11export const inTrailerOrder = (credits: readonly Credit[]) =>12 credits.toSorted((one, other) => rank(one) - rank(other));1326/** An `Assisted-by:` value as the landing's trailer spells it: `pi:opus-4 (claimed)`. */14export const assistedValue = ({ harness, model, verified }: AgentTrailer) =>15 `${harness}${model === undefined ? "" : `:${model}`} (${verified ? "verified" : "claimed"})`;1617const LINES = "flex flex-col gap-1 font-mono text-mono leading-terminal";
8 unmodified lines
26}: {27 readonly assisted: readonly AgentTrailer[];28 readonly credits: readonly Credit[];29 readonly heldBack?: string;43 /** "Credit" as a fact's label, or at Title weight, a region's own head (the Landed page). */30 readonly label?: "fact" | "title";31}) => (32 <div className="flex flex-col gap-4">33 {credits.length === 0 ? null : (
31 unmodified lines
65 )}66 </div>67);6883/** Each role as a row's line says it: the trailer, in words. */69const roleWords = {70 "Advised-by": "advised by",71 "Asked-by": "asked by",72 "Decided-by": "decided by",
2 unmodified lines
75 "Released-by": "released by",76 "Signed-off-by": "answered by",77} as const satisfies Record<CreditRole, string>;7894/** A sentence's first word with its first letter raised. */79const raised = (words: string) =>80 `${words.slice(0, 1).toUpperCase()}${words.slice(1)}`;8198/** What comes before the `index`th of `count` people in a list of words. */82const before = (index: number, count: number) => {83 if (index === 0) {84 return "";85 }8687 return index === count - 1 ? " and " : ", ";88};89107/** People in a list of words: "bram", "bram and tamsin", "bram, ines and tamsin". */90const Joined = ({ people }: { readonly people: readonly Credit[] }) =>91 people.map(({ handle }, index) => (92 <Fragment key={handle}>93 {before(index, people.length)}94 <HandleLink handle={handle} />95 </Fragment>96 ));97116/** A landing's credit in one line: each role once, in trailer order, its people linked. */98export const CompactCredit = ({99 credits,100 within = false,101}: {102 readonly credits: readonly Credit[];122 /** Inside a sentence, after a ` · `: its first word stays lower case. */103 readonly within?: boolean;104}) => {105 const roles = CreditRole.literals.flatMap((role) => {106 const people = credits.filter((credit) => credit.role === role);
17 unmodified lines
modified:apps/web/src/features/shared/disclosure.ts-5 removed
1/**2 * What people outside a layer's audience learn about what it holds, in3 * one set of words for every page that shows a layer (the ledger, the4 * people page).5 */1import type { Disclosure } from "@repo/protocol/domain/visibility";23export const disclosureWords = {4 counted: "counted: how many it holds, and when they open",
8 unmodified lines
modified:apps/web/src/features/shared/empty.tsx-8 removed
1/**2 * An empty list, said plainly, with the way onward: the command that would3 * fill it, or a link to where to go instead. A dashed hairline marks the4 * place the rows would be, an unfilled field rather than a dead end.5 */1import type { ReactNode } from "react";23import { CommandLine } from "./command.tsx";4
1 unmodified line
6 command,7 onward,8 title,9}: {15 /** The command that changes what is empty. */10 readonly command?: string;17 /** Where to go instead, when no command changes it: a link or two. */11 readonly onward?: ReactNode;19 /** One sentence saying what is empty. */12 readonly title: string;13}) => (14 <div className="border-rule flex flex-col items-start gap-3 border border-dashed px-4 py-5">15 <p className="text-ui text-foreground max-w-[70ch]">{title}</p>
6 unmodified lines
modified:apps/web/src/features/shared/facts.tsx+1 added-64 removed
1/**2 * The inspector's fact blocks: the typed facts of the thing in hand, each3 * under a label, in a fixed order per page. A block holds no box; a value4 * that is code is mono and wraps anywhere; a long SHA or root is shortened5 * (`7fbe4b2`, `sha256:7fbe4b…`), its whole value in its title and on copy.6 * Blocks never repeat the page's prose: they hold the facts it refers to.7 *8 * The blocks every page shares are here (State, Take it, Claim, Gate,9 * Posture, Held back, Family, Territory and check, Credit,10 * Provenance); a block only one page has is that page's own.11 */1import { Brand } from "@repo/brand";2import type { Verdict } from "@repo/protocol/domain/answer";3import type { Ask } from "@repo/protocol/domain/ask";4import { CheckSpec } from "@repo/protocol/domain/check";
26 unmodified lines
31import { StatusLine, readStatus, stageNames } from "./status-line.tsx";32import type { StatusSubject } from "./status-line.tsx";33import { When } from "./time.tsx";3446/** A block's frame: a hairline above every block but the first. */35const BLOCK =36 "@container border-rule flex min-w-0 flex-col gap-2.5 border-t py-3 first:border-t-0 first:pt-0";3738const LINK = "decoration-rule underline hover:decoration-current";3952/** One block: its label, then its facts. */40export const FactBlock = ({41 children,42 label,43}: {
5 unmodified lines
49 {children}50 </section>51);5266/**67 * A long hash as a person reads it: a 40- or 64-hex SHA to its first68 * seven, an `algorithm:hex` root to the algorithm and six; anything else as69 * it is.70 */53export const shortValue = (value: string) => {54 if (/^[0-9a-f]{40,64}$/u.test(value)) {55 return shortSha(value);56 }
7 unmodified lines
64 ? value65 : `${algorithm}:${hex.slice(0, 6)}…`;66};6786/** A value that is code: shortened, whole in its title. */68export const CodeValue = ({ value }: { readonly value: string }) => (69 <code className="text-mono font-mono [overflow-wrap:anywhere]" title={value}>70 {shortValue(value)}71 </code>72);7393/** The status line whole, and the command that runs next, numbered first. */74export const StateFacts = ({75 command,76 subject,77}: {78 readonly subject: StatusSubject;99 /** What runs next; a refusal's own `next` when left out. */79 readonly command?: string;80}) => {81 const next = command ?? readStatus(subject).next;82
4 unmodified lines
87 </FactBlock>88 );89};90112/** One numbered step: what it does, then its command. */91const Step = ({92 command,93 label,94}: {
5 unmodified lines
100 <CommandLine command={command} numbered />101 </div>102);103126/** Who may take an ask, in a sentence. */104const whoMayTake = (ask: Ask) => {105 if (ask.reserve === "newcomers") {106 return ask.mentor === undefined107 ? "Held for newcomers"
4 unmodified lines
112 ? "Held for people, not agents"113 : `Anyone vouched in ${ask.project}, or with a record in its area`;114};115139/** Who may take an open ask, then the three commands that start an answer. */116export const TakeItFacts = ({117 ask,118 platformUrl,119}: {120 readonly ask: Ask;145 /** Where the project is cloned from. */121 readonly platformUrl: string;122}) => (123 <FactBlock label="Take it">124 <p className="text-ui">{whoMayTake(ask)}</p>
8 unmodified lines
133 <Step command={`${Brand.cli} check`} label="Check before you push" />134 </FactBlock>135);136162/** Who holds a claim, in words: the viewer, someone, or nobody. */137const Holder = ({138 claimant,139 yours,140}: {
12 unmodified lines
153 </>154 );155};156183/**184 * Who holds a claim and when they last pushed. No read carries a claim's185 * deadline, so none is shown.186 */157/** No read carries a claim's deadline, so none is shown. */158export const ClaimFacts = ({159 claimant,160 lastPush,161 now,
1 unmodified line
163}: {164 readonly claimant?: Handle;165 readonly lastPush?: AskProgress["lastPush"];166 readonly now: DateTime.Utc;196 /** Who is reading, to tell the claimant it is theirs. */167 readonly viewer?: Handle;168}) => {169 const yours = claimant !== undefined && claimant === viewer;170
17 unmodified lines
188 </FactBlock>189 );190};191222/** What each stage runs, in one line. */192const runs = Match.type<StageName>().pipe(193 Match.when(194 "parse",195 () => "Who may push what: the branch, the pusher and their claim."
22 unmodified lines
218 ),219 Match.exhaustive220);221253/** Each stage's state as a mark and a word. */222const stageMarks = {223 current: { mark: "now", word: "now" },224 passed: { mark: "passed", word: "passed" },225 pending: { mark: "notYet", word: "not yet" },
3 unmodified lines
229 StageState,230 { readonly mark: StateMark; readonly word: string }231>;232265/**266 * The gate. On a project: the seven stages in the order of their cost, on267 * one line, and what each runs behind a disclosure. On an answer: each268 * stage's state, the one it stands at marked as the current step.269 */233export const GateFacts = (234 props:235 | { readonly outcome?: undefined }236 | {
74 unmodified lines
311 </FactBlock>312 );313};314352/** What each posture means, in one line. */315const glosses = {316 open: "Everything it ships is public.",317 openCore: "Some files it ships are kept in a layer, with no date to open.",318 openOnSchedule:
2 unmodified lines
321 "Everything it ships is public; some checks are kept in a layer and judge answers unseen.",322 sourceAvailable: "Its licence is not an open-source one.",323} as const satisfies Record<Posture, string>;324363/** A project's posture as the platform labels it, what it means, and its ledger. */325export const PostureFacts = ({326 label,327 posture,328 project,
10 unmodified lines
339 </AppLink>340 </FactBlock>341);342382/** What a project holds back: one sealed line per area, or that nothing is. */343export const HeldBackFacts = ({344 areas,345}: {346 readonly areas: readonly {347 readonly area: AreaName;388 /** What the area holds, in words: "7 sealed checks". */348 readonly detail: string;349 }[];350}) => (351 <FactBlock label="Held back">
21 unmodified lines
373 )}374 </FactBlock>375);376418/** The family a member belongs to, drawn top to bottom. */377export const FamilyFacts = (props: Parameters<typeof FamilyTree>[0]) => (378 <FactBlock label="Family">379 <FamilyTree {...props} />380 </FactBlock>381);382425/** The folder a territory's first path names, when it names one plainly. */383const folderOf = (ask: Ask) => {384 const [first] = ask.territory.paths;385 const folder = first.replace(/\/\*\*$|\/\*$|^\*\*$/u, "");386387 return /[*?[{]/u.test(folder) ? undefined : folder;388};389433/**434 * A territory: a module by name, linked to its folder when its first path435 * names one plainly; the whole project when it covers every path; or, in436 * a repo of one package, the paths themselves.437 */390const TerritoryLine = ({ ask }: { readonly ask: Ask }) => {391 const folder = folderOf(ask);392 const { module, paths } = ask.territory;393
24 unmodified lines
418 </AppLink>419 );420};421470/** What judges an answer, by the check's kind. */422const CheckLine = ({ ask }: { readonly ask: Ask }) =>423 CheckSpec.match(ask.check, {424 LintToZero: ({ rule }) => (425 <p className="text-ui">
35 unmodified lines
461 </p>462 ),463 });464514/** Where an answer may change things, and what judges it. */465export const TerritoryFacts = ({ ask }: { readonly ask: Ask }) => (466 <FactBlock label="Territory and check">467 <TerritoryLine ask={ask} />468 <CheckLine ask={ask} />469 </FactBlock>470);471522/** A landing's credit as the commit carries it, the agents apart. */472export const CreditFacts = (props: {473 readonly assisted: readonly AgentTrailer[];474 readonly credits: readonly Credit[];475 readonly heldBack?: string | undefined;
6 unmodified lines
482 />483 </div>484);485537/** One fact of provenance: its label, its whole value, and how it reads. */486export interface ProvenanceEntry {487 readonly label: string;488 readonly value: string;541 /** How it reads, when not as its shortened value (a time). */489 readonly shown?: ReactNode;490}491545/** What a verdict judged: the commits, the tree, the patch, the check, who judged it and when. */492export const verdictProvenance = (493 verdict: Verdict,494 now: DateTime.Utc495): readonly ProvenanceEntry[] => [
9 unmodified lines
505 value: DateTime.formatIso(verdict.at),506 },507];508563/** Where a landing comes from: its author, its parent, and the request that landed it. */509export const landingProvenance = (510 landing: LandingView511): readonly ProvenanceEntry[] => [512 { label: "Author", value: landing.author },
7 unmodified lines
520 ? []521 : [{ label: "Request-Id", value: landing.requestId }]),522];523579/**580 * The plumbing, last: each value shortened, whole in its title and on581 * copy. Below the shell's width it starts folded.582 */524export const ProvenanceFacts = ({525 entries,526}: {527 readonly entries: readonly ProvenanceEntry[];
21 unmodified lines
549 />550 </button>551 <dl className={`${open ? "flex" : "shell:flex hidden"} flex-col gap-1.5`}>552 {entries.map(({ label, shown, value }) => (612 // A label over its value, as every block is: never a key and613 // value grid.553 <div554 className="flex min-w-0 flex-col"555 data-provenance={label}556 key={label}
5 unmodified lines
562 </span>563 {shown === undefined ? (564 <CopyAction command={value} label={`Copy ${label}`} />565 ) : (627 // A time reads as words, its exact instant in its own628 // title: nothing here to paste into a terminal.566 <span aria-hidden="true" className="size-8 shrink-0" />567 )}568 </dd>569 </div>
5 unmodified lines
modified:apps/web/src/features/shared/family.tsx+1 added-41 removed
1/**2 * A family as a fan: a parent ask split into sibling children, one per3 * module, and a delete child that waits for all of them. The children are4 * siblings, so they are drawn side by side on one bus, never as a ladder,5 * with an arrow to the delete child at the end.6 *7 * - `FamilyStrip` is a parent row's third line: each child's mark and its8 * short name, the arrow to the delete child, "n of N landed", and a9 * button that lists the children as rows beneath. N is the children the10 * parent stores, never the listing's remaining blockers (a listing drops11 * the ones that landed).12 * - `FamilyTree` is the vertical form, for the inspector and the top of a13 * member's page: the parent, its children on a left bus, then the delete14 * child, the member being read marked.15 *16 * A child that lands while the page is open settles with the stamp, once17 * (the caller's `stamps`, from `stampsFrom`); the count changes with no18 * motion of its own, and with reduced motion nothing moves.19 */1import type { Ask } from "@repo/protocol/domain/ask";2import type { AskId, ProjectName } from "@repo/protocol/ids";3import { ArrowRight, ChevronDown } from "lucide-react";4import { useId, useState } from "react";
5 unmodified lines
10import { StateMarkIcon } from "./marks.tsx";11import type { StateMark } from "./marks.tsx";12import { askPath } from "./paths.ts";1333/** Each child's state in the words its node is read by. */14const words = {15 checking: "checking",16 claimed: "claimed",17 landed: "landed",
1 unmodified line
19 refused: "refused",20 waiting: "waiting",21} as const satisfies Record<Mark, string>;2243/** The fold's marks are named as the marks are. */23const markFor = (mark: Mark): StateMark => mark;2446/** The words of `id` after `prefix` and its dash, or `id` when it does not start so. */25const after = (id: string, prefix: string) =>26 id.startsWith(`${prefix}-`) ? id.slice(prefix.length + 1) : id;2750/**51 * Each child's short name: its id after the parent's, and after any word52 * every sibling shares ("drop-legacy-fetch-burrow-auth" reads "auth" when53 * every child is a burrow module).54 */28export const shortNames = (29 parent: AskId,30 children: readonly AskId[]31): ReadonlyMap<AskId, string> => {
16 unmodified lines
48 })49 );50};5179/** A family's children (the delete child apart), their marks and what the delete child waits on. */52const familyOf = (53 parent: Ask,54 states: ReadonlyMap<AskId, AskProgress>,55 finale: AskId | undefined
17 unmodified lines
73 total: children.length,74 };75};76105/** Where the delete child stands: its mark, and its state in words. */77interface FinaleState {78 readonly mark: StateMark;79 readonly words: string;80}81111/** The delete child's state: it waits until every child lands, then opens, then lands. */82const finaleOf = (83 finale: AskId,84 states: ReadonlyMap<AskId, AskProgress>,85 remaining: number
16 unmodified lines
102103const NODE =104 "text-label relative z-10 inline-flex min-w-0 items-center gap-1 no-underline hover:underline decoration-rule";105136/** A row's third line: the fan, the count, and the children as rows on demand. */106export const FamilyStrip = ({107 expanded,108 finale,109 parent,
3 unmodified lines
113 wants,114}: {115 readonly parent: Ask;116 readonly states: ReadonlyMap<AskId, AskProgress>;148 /** The delete child, when the family has one. */117 readonly finale?: AskId;150 /** Children that landed while the page was open. */118 readonly stamps: ReadonlySet<AskId>;119 readonly project: ProjectName;153 /** Whether the children start listed as rows. */120 readonly expanded: boolean;155 /** Each child's want, when the page has it, for the listed rows. */121 readonly wants?: ReadonlyMap<AskId, string>;122}) => {123 const [open, setOpen] = useState(expanded);124 const rowsId = useId();
80 unmodified lines
205 {open ? "Hide" : "Show"} {family.total} {plural}206 </span>207 </button>208 </div>244 {/* Folded, the rows stay in the page, hidden: each open child's245 claim command is text an agent reading the page still finds. */}209 {/* Folded, the rows stay in the page: each open child's claim command is text an agent still finds. */}210 <ul211 className="border-rule mt-1 ml-[0.4375rem] flex flex-col border-l pl-3"212 hidden={!open}213 id={rowsId}
38 unmodified lines
252 </div>253 );254};255292/** One member in the vertical form: its mark, its name, its state's word; the member being read filled. */256const Member = ({257 current,258 label,259 mark,
23 unmodified lines
283 </span>284 </AppLink>285);286324/** The family read top to bottom: the parent, its children on a bus, then the delete child. */287export const FamilyTree = ({288 current,289 finale,290 parent,
2 unmodified lines
293}: {294 readonly parent: Ask;295 readonly states: ReadonlyMap<AskId, AskProgress>;296 readonly finale?: AskId;335 /** The member whose page this is. */297 readonly current?: AskId;298 readonly project: ProjectName;299}) => {300 const family = familyOf(parent, states, finale);301 const progress = markOf(states.get(parent.id));302342 // An open parent waits while anything it waits on has not landed.303 const own =304 progress === "open" &&305 parent.blockedBy.some((ask) => states.get(ask)?.landed === undefined)306 ? "waiting"
49 unmodified lines
modified:apps/web/src/features/shared/handle.tsx-4 removed
1/**2 * A person, by handle, linking to their page of credits. People appear by3 * handle and role only: nothing here ranks or scores them.4 */1import type { Handle } from "@repo/protocol/ids";23import { AppLink } from "./link.tsx";4import { personPath } from "./paths.ts";
9 unmodified lines
modified:apps/web/src/features/shared/head.ts+2 added-14 removed
1/**2 * What a page puts in the document's head, in a module with no view of its3 * own: a route's `head` runs with the route, before its page's view loads.4 */1import { Brand } from "@repo/brand";27/** A page's `<title>`: the page, then the product. */3export const pageTitle = (title: string) => `${title} · ${Brand.name}`;45/**11 * A page's head: its `<title>`, and what a shared link unfurls with (the12 * description and the Open Graph title, description and type; no image).13 * The router keeps one meta per name or Open Graph property, the last a14 * route gives, so a page's replace the root's, and a page with no15 * description of its own unfurls with the root's.16 *17 * ```ts18 * head: ({ params }) => pageHead({ title: `${params.ask} · ${params.project}`, description: want }),19 * ```6 * The router keeps one meta per name or Open Graph property, the last a route7 * gives, so a page's replace the root's.8 */9export const pageHead = ({10 description,11 title,
18 unmodified lines
modified:apps/web/src/features/shared/keys.tsx+4 added-72 removed
1/**2 * The keyboard's single keys, one listener for the whole shell:3 *4 * - `?` opens the keys dialog, which lists them and holds the switch;5 * - `j` / `k` move through the page's list (its rows, `useListKeys`), and at6 * the shell's width select the row, so the inspector follows; `Enter`7 * opens the focused row, as a link does;8 * - `J` / `K` move between the page's files (`useFileKeys`);9 * - `1` to `9` copy the page's numbered commands, the inspector's first10 * (`useNumberedCommand`);11 * - `Escape` clears the selection (a sheet or a dialog closes itself).12 *13 * No key acts while focus is in a text field, a combobox or the tree's14 * search, or with Ctrl, Alt or Meta held. Every key has a twin a pointer15 * reaches: rows are links, files are the tree's rows, commands have their16 * copy buttons. The switch turns every key but `?` off (WCAG 2.2 SC 2.1.4)17 * and is the viewer's own: kept in this browser's storage, on until turned18 * off, and on whenever the storage cannot be read.2 * The switch turns every key but `?` off (WCAG 2.2 SC 2.1.4), and is on3 * whenever the storage cannot be read.4 */5import { Effect, Option, Result } from "effect";6import {7 createContext,
8 unmodified lines
16import type { ReactNode } from "react";1718import { Kbd } from "../../components/ui/kbd.tsx";1935/** A key pressed, as the listener reads it. */20export interface KeyPress {21 readonly altKey: boolean;22 readonly ctrlKey: boolean;39 /** Whether focus is in a text field, a combobox or a search. */23 readonly inField: boolean;24 readonly key: string;25 readonly metaKey: boolean;26}2745/** What a key asks for. */28export type KeyIntent =29 | { readonly index: number; readonly kind: "copy" }30 | {31 readonly kind:
13 unmodified lines
45} as const satisfies Record<string, KeyIntent["kind"]>;4647const DIGIT = /^[1-9]$/u;4867/** The shell's width, from which the rail and the inspector are columns. */49const SHELL_WIDTH = "(min-width: 70rem)";5070/**71 * What `press` asks for, with the single keys `on` or off; nothing for a72 * press in a text field, with a modifier held, or with no meaning here.73 */51export const intentOf = (52 press: KeyPress,53 on: boolean54): KeyIntent | undefined => {
21 unmodified lines
7677 return move === undefined ? undefined : { kind: move[1] };78};79103/** Where the switch is kept, in the browser's storage. */80const SWITCH = "keys.single";81106/** Whether the single keys are on: on unless `storage` says off, or cannot say. */82export const readShortcuts = (storage?: Storage): boolean =>83 storage === undefined ||84 Result.getOrElse(85 Result.try(() => storage.getItem(SWITCH) !== "off"),86 () => true87 );88114/** Keep the switch as `on` says; a storage that refuses keeps nothing. */89export const writeShortcuts = (storage: Storage | undefined, on: boolean) => {90 Result.try(() => storage?.setItem(SWITCH, on ? "on" : "off"));91};92119/** The browser's storage, when there is one this page may use. */93const localStorageOf = (): Storage | undefined =>94 Result.getOrUndefined(Result.try(() => globalThis.localStorage));95123/** The keys and what each does, as the dialog lists them. */96const KEYS = [97 { does: "Show these keys", keys: ["?"] },98 { does: "Next or previous row", keys: ["j", "k"] },99 { does: "Open the focused row", keys: ["Enter"] },
1 unmodified line
101 { does: "Copy the page's numbered command", keys: ["1", "…", "9"] },102 { does: "Close, or clear the selection", keys: ["Esc"] },103] as const;104133/** The switch's two settings, each a button that says whether it is pressed. */105const SETTINGS = [106 { label: "On", on: true },107 { label: "Off", on: false },108] as const;109139/**140 * The keys dialog's body: every key with what it does, and the switch. `?`141 * opens it even with the switch off, so the switch is always in reach.142 */110export const KeysHelp = ({111 on,112 onChange,113}: {
44 unmodified lines
158 </p>159 </div>160);161195/** Which part of the page a command sits in: the inspector's are numbered first. */162export type CommandSlot = "facts" | "main";163164const SlotContext = createContext<CommandSlot>("main");165200/** Commands under `slot` number as the inspector's or main's. */166export const CommandSlotProvider = ({167 children,168 slot,169}: {170 readonly children: ReactNode;171 readonly slot: CommandSlot;172}) => <SlotContext value={slot}>{children}</SlotContext>;173209/** A list the page lets `j` and `k` move through. */174interface ListRegistration {175 readonly focus: (id: string) => void;176 readonly read: () => {177 readonly ids: readonly string[];
1 unmodified line
179 };180 focused?: string;181}182219/** The files a page lets `J` and `K` move between. */183interface FileRegistration {184 readonly read: () => {185 readonly onMove: (path: string) => void;186 readonly paths: readonly string[];
6 unmodified lines
193 readonly id: string;194 readonly slot: CommandSlot;195}196234/** What the page registers with the listener; one for the shell's life. */197interface Registry {198 readonly clearers: Set<() => void>;199 readonly files: Set<FileRegistration>;200 readonly lists: Set<ListRegistration>;201 readonly register: (command: Command) => () => void;202}203242/** What the keys show: whether they are on, the numbers, the last copy. */204interface KeysState {205 readonly copied: string | undefined;206 readonly numbered: ReadonlyMap<string, number>;207 readonly on: boolean;
3 unmodified lines
211const RegistryContext = createContext<Registry | undefined>(undefined);212213const StateContext = createContext<KeysState | undefined>(undefined);214254/** The keys' state, for the dialog. */215export const useKeys = () => useContext(StateContext);216257/** `item` in `set` until the returned function takes it out. */217const held = <A,>(set: Set<A>, item: A) => {218 set.add(item);219220 return () => {221 set.delete(item);222 };223};224266/** The last registered of `set`: the page's own, over any that left late. */225/** The page's own, over any that left late. */226const lastOf = <A,>(set: ReadonlySet<A>): A | undefined => [...set].at(-1);227269/** Whether `event` was pressed inside something that takes typing. */228export const inField = (event: KeyboardEvent) => {229 const [target] = event.composedPath();230231 return (
4 unmodified lines
236 ) !== null)237 );238};239282/** Numbers commands 1 to 9: the inspector's first, each command once. */240const numberOf = (241 commands: readonly Command[]242): ReadonlyMap<string, number> => {243 const ordered = [
7 unmodified lines
251 unique.slice(0, 9).map((command, index) => [command, index + 1])252 );253};254298/** Copy `command`, then mark it copied for two seconds. */255const copyNumbered = (command: string, shown: (copied?: string) => void) =>256 Effect.tryPromise(() => navigator.clipboard.writeText(command)).pipe(257 Effect.andThen(258 Effect.sync(() => {
8 unmodified lines
267 ),268 Effect.ignore269 );270315/** The row a key moved to: focused, scrolled to, and selected at the shell's width. */271const moveTo = (list: ListRegistration, step: 1 | -1) => {272 const { ids, onSelect } = list.read();273 const at = list.focused === undefined ? -1 : ids.indexOf(list.focused);274
18 unmodified lines
293 row.focus({ preventScroll: true });294 row.scrollIntoView({ block: "nearest" });295 }296342 // The inspector is a column at the shell's width, so a move selects there.297 if (globalThis.matchMedia(SHELL_WIDTH).matches) {298 onSelect(next);299 }300};
8 unmodified lines
309 onMove(next);310 }311};312359/** What the listener reads when a key is pressed. */313interface Pressing {314 readonly copy: (command: string) => void;315 readonly numbered: ReadonlyMap<string, number>;316 readonly on: boolean;317 readonly openDialog: () => void;318 readonly registry: Registry;319}320368/** Do what `intent` asks; whether it did anything (so the browser does not too). */321const act = (intent: KeyIntent, now: Pressing): boolean => {322 const { registry } = now;323324 if (intent.kind === "keys") {
41 unmodified lines
366367 return files !== undefined;368};369418/**419 * The shell's one listener and the state behind it. `openDialog` opens the420 * keys dialog (the shell draws it).421 */370export const KeysProvider = ({371 children,372 openDialog,373}: {374 readonly children: ReactNode;375 readonly openDialog: () => void;376}) => {377 // The server has no storage and renders the keys on; nothing it renders430 // depends on them (a command's number comes once the page has run).378 // depends on them.379 const [on, setOn] = useState(() => readShortcuts(localStorageOf()));380 const [commands, setCommands] = useState<readonly Command[]>([]);381 const [copied, setCopied] = useState<string>();382
19 unmodified lines
402 }, []);403404 const numbered = useMemo(() => numberOf(commands), [commands]);405458 // The listener reads the latest of these, kept here after each render.406 const pressing = useRef<Pressing | null>(null);407408 useEffect(() => {409 pressing.current = {
54 unmodified lines
464 </RegistryContext>465 );466};467521/** `value`, kept current in a ref after each render, for a handler to read later. */468const useLatest = <A,>(value: A) => {469 const latest = useRef(value);470471 useEffect(() => {
2 unmodified lines
474475 return latest;476};477532/**533 * Let `j` and `k` move through `ids` (the page's rows, in order); at the534 * shell's width each move also selects the row (`onSelect`). Give each row's535 * link `data-list-key={id}` so the move focuses it and `Enter` opens it.536 * Returns the row the keys rest on, to draw as focused.537 */478export const useListKeys = (479 ids: readonly string[],480 onSelect: (id: string) => void481): { readonly focused?: string } => {
14 unmodified lines
496497 return focused === undefined ? {} : { focused };498};499560/** Let `J` and `K` move between `paths` (the page's files, in order), each move calling `onMove`. */500export const useFileKeys = (501 paths: readonly string[],502 onMove: (path: string) => void503): void => {
8 unmodified lines
512 [latest, registry]513 );514};515577/**578 * Number `command` among the page's commands: the digit that copies it, while579 * the single keys are on, to show before it ("Copy (1)"); nothing when they580 * are off or it is past the ninth.581 */516export const useNumberedCommand = (command: string): number | undefined => {517 const registry = useContext(RegistryContext);518 const state = useContext(StateContext);519 const slot = useContext(SlotContext);
6 unmodified lines
526527 return state?.on === true ? state.numbered.get(command) : undefined;528};529596/** The command a number key copied in the last two seconds, to show as copied. */530export const useCopiedCommand = (): Option.Option<string> =>531 Option.fromUndefinedOr(useContext(StateContext)?.copied);532600/** Let `Escape` call `clear` while the caller is on the page (the selection's). */533export const useEscapeClears = (clear: () => void): void => {534 const registry = useContext(RegistryContext);535 const latest = useLatest(clear);536
10 unmodified lines
modified:apps/web/src/features/shared/layout.tsx-8 removed
1/**2 * What every page renders inside the shell (`shell/app-shell.tsx`):3 * `PageShell`, a page with a title and no facts, drawn by the shell's4 * `Workspace` (its context bar names the page from its address), for the5 * pages that have not yet come to `Workspace` themselves; and the skip link6 * the shell puts first, so a keyboard passes the rail to the page.7 */1import type { ReactNode } from "react";23import { Workspace } from "./shell/workspace.tsx";4
4 unmodified lines
9 readonly children: ReactNode;10 readonly title: string;11}) => <Workspace title={title}>{children}</Workspace>;1220/** The first stop of a keyboard on every page: straight to main, past the rail. */13export const SkipLink = () => (14 <a15 className="bg-background text-ui sr-only z-50 px-3 py-2 font-medium focus:not-sr-only focus:fixed focus:top-2 focus:left-2"16 href="#main"
4 unmodified lines
modified:apps/web/src/features/shared/link.tsx+5 added-37 removed
1/**2 * The one link between the web's pages: the router's `Link`, so a click3 * moves without reloading the document, and a hover or focus fetches the4 * page's code and loader data first (the router's `defaultPreload` is5 * "intent", `src/router.tsx`). The router marks the link to the page being6 * read with `aria-current="page"` and `data-status="active"`.7 *8 * `to` is a path built whole, as `paths.ts` builds them (`askPath(project,9 * ask)`), with its search as `search`; the router reads its params from it10 * as it reads them from a typed address.11 *12 * A view rendered with no router around it (its own test, with13 * `renderToStaticMarkup`) draws the same address as a plain anchor, so its14 * markup reads the same either way; the shell's own test renders inside a15 * router (`test/render.tsx`) and checks its links are the router's.16 *17 * Only pages the router serves take an `AppLink`. A server route (sign-in,18 * a raw file, a `.md` twin, `llms.txt`) is a plain `<a>`, or the router would19 * look for a page that is not there.2 * A server route (sign-in, a raw file, a `.md` twin, `llms.txt`) is a plain3 * `<a>`, or the router would look for a page that is not there.4 */5import {6 defaultStringifySearch,7 Link,
3 unmodified lines
11import { Predicate } from "effect";12import { createElement } from "react";13import type { AnchorHTMLAttributes, ReactNode } from "react";1431/** An `AppLink`'s props: an anchor's, with the address as `to`. */15export interface AppLinkProps extends Omit<16 AnchorHTMLAttributes<HTMLAnchorElement>,17 "href" | "target"18> {36 /** The path, built whole: `/datekit/ledger`. */19 readonly to: string;38 /** The address's search, each value a string. */20 readonly search?: Readonly<Record<string, string>> | undefined;40 /** The fragment, without its `#`. */21 readonly hash?: string;42 /** How the router decides the link leads to the page being read. */22 readonly activeOptions?: ActiveOptions;44 /** `false` keeps the router from fetching the page ahead of a click. */23 readonly preload?: false;46 /** Replace the history entry rather than push one (a selection). */24 readonly replace?: boolean;48 /** Keep each pane's scroll where it is (a selection in a list). */25 readonly resetScroll?: boolean;26}2728/**53 * `path` with the router's own marks escaped: a `$` (a param, or the splat)54 * and the braces of an optional segment are, in a path built whole, part of55 * a name (a file at `routes/$project/$.tsx`), never a param for the router56 * to fill from the page being read. Escaped, they reach the address as57 * written, and the router decodes them back when it reads the page's params.29 * `$` and the braces of an optional segment are, in a path built whole, part of30 * a name (`routes/$project/$.tsx`), never a param for the router to fill.31 * Escaped, they reach the address as written.32 */33export const literalPath = (path: string): string =>34 path.replaceAll("$", "%24").replaceAll("{", "%7B").replaceAll("}", "%7D");3562/** The address an `AppLink` names, as the router would write it. */36export const hrefOf = ({37 hash,38 search,39 to,
3 unmodified lines
43 ? ""44 : defaultStringifySearch(search)45 }${hash === undefined ? "" : `#${hash}`}`;4674/**75 * `Link` over any router, whose `to` is any path: the router reads a path76 * built whole as it reads a typed address.77 */47const PathLink = Link<AnyRouter, string, string>;4849export const AppLink = (props: AppLinkProps): ReactNode => {50 const router = useRouter({ warn: false });
1 unmodified line
52 if (Predicate.isNotNullish(router)) {53 return <PathLink {...props} to={literalPath(props.to)} />;54 }5587 // A router is always there in the app; only a view rendered alone has none.56 const {57 activeOptions: _active,58 hash: _hash,59 preload: _preload,
9 unmodified lines
modified:apps/web/src/features/shared/mark-look.ts+2 added-7 removed
1/**2 * How a mark is drawn, and a posture's mark: kept apart from the states'3 * marks (`marks.tsx`) so the rail, on every page, carries only the three4 * icons a posture needs.2 * Kept apart from `marks.tsx` so the rail, on every page, carries only the3 * three icons a posture needs.4 */5import type { Posture } from "@repo/protocol/posture";6import { Eye, LockKeyhole, LockKeyholeOpen } from "lucide-react";7import type { LucideIcon } from "lucide-react";810/** How a mark is drawn: its icon, its role's colour, and whether its icon is filled. */9export interface MarkLook {10 readonly icon: LucideIcon;13 /** The role's colour, as a text class. */11 readonly tone: string;15 /** The icon's inner shape is filled (the checking dot, the claimed half). */12 readonly fill?: true;13}1419/** A project's posture as a mark: a lock in the sealed role when something is kept sealed. */15export const POSTURE_MARKS = {16 open: { icon: LockKeyholeOpen, tone: "text-muted-foreground" },17 openCore: { icon: LockKeyhole, tone: "text-sealed" },18 openOnSchedule: { icon: LockKeyhole, tone: "text-sealed" },
3 unmodified lines
modified:apps/web/src/features/shared/marks.tsx-24 removed
1/**2 * Every state the web draws, as one mark and one word: the same mark means3 * the same thing on every page. Marks are lucide's, 16 px at a 1.754 * stroke; the word always renders beside the mark or in its row, so the5 * mark is hidden from screen readers and a page read in grayscale says the6 * same thing. Colour is the state's role, and only for state:7 *8 * - landed green: on main (a landing, a stage that passed);9 * - checking blue: running now;10 * - waiting ochre: paused on a person, a parent or a retry;11 * - refused red: a refusal, and nothing else;12 * - sealed violet: held back;13 * - ink and muted for the rest (claimed, open, not needed, a default, and14 * a failure that is not a refusal, such as a draft that did not come).15 */1import {2 Check,3 CircleSmall,4 Circle,
8 unmodified lines
13} from "lucide-react";1415import type { MarkLook } from "./mark-look.ts";1632/** Every state a mark is drawn for. */17export const STATE_MARK_NAMES = [18 "landed",19 "passed",20 "checking",
11 unmodified lines
32] as const;3334export type StateMark = (typeof STATE_MARK_NAMES)[number];3552/** Each state's mark and its word, as it reads on its own. */36export const STATE_MARKS = {37 checking: {38 fill: true,39 icon: CircleSmall,
19 unmodified lines
59 sealed: { icon: LockKeyhole, tone: "text-sealed", word: "Sealed" },60 waiting: { icon: Hourglass, tone: "text-waiting", word: "Waiting" },61} as const satisfies Record<StateMark, MarkLook & { readonly word: string }>;6280/** A mark's size beside 14 and 16 px text, and one a step down for 13 px lines. */63const SIZES = { md: "size-4", sm: "size-3.5" } as const;6483/**84 * One mark, hidden from screen readers (its word is beside it). `stamp`85 * settles it once, as a landing's stamp does, when the viewer allows86 * motion.87 */65export const Mark = ({66 className = "",67 look,68 size = "md",
18 unmodified lines
87 />88 );89};90114/** The mark of a named state. */91export const StateMarkIcon = ({92 mark,93 ...rest94}: {
5 unmodified lines
modified:apps/web/src/features/shared/outcome.tsx+3 added-33 removed
1/**2 * Where an answer stands, read the same on every page that shows one.3 *4 * `OutcomeView` gives the outcome as the status line (`StatusLine`):5 * checking, waiting (on a decision, a finish or a parent ask) or landed,6 * each with its state as `data-state` ("waiting" or "final"); a refusal's7 * line is followed by the refusal itself, drawn whole by `RefusalView`.8 * Waiting is never shown as refusing.9 *10 * `StageStrip` is the gate's results row: one cell per stage, in the order11 * of cost, each marked passed, current, refused, pending or not needed by12 * a mark and a word, colour only third.13 */1import { Outcome, StageName } from "@repo/protocol/domain/outcome";2import type { Handle, ProjectName } from "@repo/protocol/ids";34import { StateMarkIcon } from "./marks.tsx";
10 unmodified lines
15 stage,16 stamp = false,17}: {18 readonly outcome: Outcome;32 /** Who holds the ask, to name whose move a refusal leaves. */19 readonly claimant?: Handle;34 /** The stage the verdict reached, to say where a refusal came from. */20 readonly stage?: StageName;36 /** The project, to link the landing or what the answer waits on. */21 readonly project?: ProjectName;38 /** The answer page's hero is a step up. */22 readonly size?: "body" | "title";40 /** Settle a landing's mark once: it landed while the page was open. */23 readonly stamp?: boolean;24}) => {25 const subject: StatusSubject = {26 claimant,
29 unmodified lines
56 </div>57 );58};5978/** A stage's place in the strip. */60export type StageState =61 | "passed"62 | "current"63 | "refused"64 | "pending"65 | "skipped";6686/** What a verdict holds beyond its stage: a decider's decision, and held-back results. */67export interface StageHolds {68 readonly decided: boolean;69 readonly heldBack: boolean;70}7172/**93 * Each stage's state, given the furthest stage the answer reached and its94 * outcome: stages before it passed; at it, current (checking or waiting),95 * refused, or passed (landed or waiting on its parent); after it, pending,96 * or skipped once the answer landed without them.97 *98 * A passing verdict reaches the decider stage whether or not a decider99 * took part, so with `holds` (what the verdict holds) a held-back or100 * decider stage that would read passed reads not needed when the verdict101 * holds no held-back results or no decision. Without it, every stage102 * before the reached one reads passed.73 * A passing verdict reaches the decider stage whether or not a decider took74 * part, so with `holds` a held-back or decider stage it never needed reads not75 * needed.76 */77export const stageStates = (78 reached: StageName,79 outcome: Outcome,
37 unmodified lines
117 ] as const;118 });119};120148/** Each state's mark and word in a cell; the current one's mark follows the outcome. */121const cellMarks = (outcome: Outcome) =>122 ({123 current: {124 mark: Outcome.isAnyOf(["Checking"])(outcome) ? "now" : "waiting",
7 unmodified lines
132 StageState,133 { readonly mark: StateMark; readonly word: string }134 >;135164/** A cell's word in its state's role; not yet and not needed stay muted. */136const wordTones = {137 current: "",138 passed: "text-landed",139 pending: "text-muted-foreground",
5 unmodified lines
145 holds,146 outcome,147 stage,148}: {178 /** What the verdict holds, so a stage it never needed reads not needed. */149 readonly holds?: StageHolds;150 readonly outcome: Outcome;151 readonly stage: StageName;152}) => {
51 unmodified lines
modified:apps/web/src/features/shared/paths.ts+1 added-17 removed
1/**2 * The site's addresses, in a module with no view of its own, so a route or3 * a view links to a page without carrying that page's view.4 */1import type {2 AskId,3 DecisionId,4 Handle,5 ProjectName,6} from "@repo/protocol/ids";7import { Result } from "effect";813/** The front page: every open ask, across every project. */9export const ASKS_PATH = "/asks";1016/** A signed-in reader's own page. */11export const HOME_PATH = "/home";1219/** The import page: a public repo made a project. */13export const IMPORT_PATH = "/import";1422/** The docs' index, or one of its pages. */15export const docsPath = (page?: string) =>16 page === undefined ? "/docs" : `/docs/${page}`;1726/** A project's page. */18export const projectPath = (project: ProjectName) => `/${project}`;1929/** An ask's page. */20export const askPath = (project: ProjectName, ask: AskId) =>21 `/${project}/asks/${ask}`;2233/** The page of the verdict on an ask's latest answer. */23export const answerPath = (project: ProjectName, ask: AskId) =>24 `/${project}/answers/${ask}`;2537/** A person's page: `/people/<handle>` (a handle is URL-safe by its schema). */26/** A handle is URL-safe by its schema. */27export const personPath = (handle: Handle) => `/people/${handle}`;2840/** A project's ledger. */29export const ledgerPath = (project: ProjectName) => `/${project}/ledger`;3043/** A project's env shape. */31export const envPath = (project: ProjectName) => `/${project}/env`;3246/** A decision's page. */33export const decisionPath = (project: ProjectName, decision: DecisionId) =>34 `/${project}/decisions/${decision}`;3550/** `segment` decoded, or as it came when it does not decode. */36const decoded = (segment: string) =>37 Result.getOrElse(38 Result.try(() => decodeURIComponent(segment)),39 () => segment40 );4157/** A pathname's segments, decoded, the empty ones dropped. */42export const segmentsOf = (pathname: string) =>43 pathname44 .split("/")45 .filter((segment) => segment !== "")
1 unmodified line
modified:apps/web/src/features/shared/pending.tsx+4 added-26 removed
1/**2 * What a page shows while its reads are on their way, when the platform3 * did not answer, and when nothing is at an address, each inside the shell4 * (the rail, the bars and the context bar stay):5 *6 * - `ReadingRows`: rows of a list's own height (64 px), each two hairline7 * bars, with no shimmer; `Reading` is a page of them under its title;8 * - `Unreachable`: the platform did not answer, said in ink with a way to9 * ask again. It is not a refusal (a refusal is the platform's answer, and10 * this is the absence of one), so it is never drawn in the refusal's red;11 * - `PendingPage`, `RouteError` and `NotFoundPage`: the router's own pending,12 * failure and missing pages (`src/router.tsx`).13 */1import type { ErrorComponentProps } from "@tanstack/react-router";2import { useLocation } from "@tanstack/react-router";3import { Unplug } from "lucide-react";4
6 unmodified lines
11import { RowSkeleton } from "./skeleton.tsx";1213const ROWS = ["first", "second", "third"] as const;1428/** Rows that hold a list's place while the platform answers: a row's height, two bars each. */15export const ReadingRows = () => (16 <div aria-busy="true" className="flex flex-col">17 <output className="sr-only">Reading from the platform</output>18 {ROWS.map((row) => (
11 unmodified lines
30const reload = () => {31 globalThis.location.reload();32};3348/** The platform did not answer: in ink, with a way to ask again. */34/**35 * Not a refusal (it is the absence of the platform's answer), so never in the36 * refused red.37 */38export const UnreachableNotice = () => (39 <div40 className="border-rule-strong flex max-w-[40rem] items-start gap-3 border p-4"41 role="alert"
21 unmodified lines
63 <UnreachableNotice />64 </PageShell>65);6678/** The page's name as its address gives it: the last step of its trail. */67const useAddressTitle = () =>68 useLocation({69 select: ({ pathname }) => crumbsFor(pathname).at(-1)?.label ?? "",70 });7184/**85 * A page the router is still loading, after 300 ms: its name from the86 * address over rows that hold its place, so a quick move never flashes and87 * a slow one keeps the shell where it is.88 */72export const PendingPage = () => (73 <PageShell title={useAddressTitle()}>74 <ReadingRows />75 </PageShell>76);7795/**96 * A page whose read failed on its way (the platform did not answer, or97 * answered with nothing the page could read), inside the shell.98 */78export const RouteError = (_props: ErrorComponentProps) => (79 <PageShell title={useAddressTitle()}>80 <UnreachableNotice />81 </PageShell>82);83105/** An address no page serves: the trail up to what exists, and the ways onward. */84export const NotFoundPage = () => {85 const pathname = useLocation({ select: (location) => location.pathname });86 const project = projectOf(pathname);87
40 unmodified lines
modified:apps/web/src/features/shared/posture.tsx+2 added-7 removed
1/**2 * A project's posture, as the honest label the platform computes from its3 * visibility config. The posture literal rides as `data-posture`, so tests4 * and styles key on it; the words are the label, never rewritten here.5 * It is a state badge: a lock in the sealed role when something is kept6 * sealed, then the label.2 * The posture literal rides as `data-posture`, so tests and styles key on it;3 * the words are the platform's label, never rewritten here.4 */5import type { Posture } from "@repo/protocol/posture";67import { POSTURE_MARKS } from "./mark-look.ts";8import { StateBadge } from "./state-badge.tsx";913/** The label's colour: sealed when something is kept sealed, ink when nothing is, muted for a licence that is not open. */10const wordTone = {11 open: "text-foreground",12 openCore: "text-sealed",13 openOnSchedule: "text-sealed",
7 unmodified lines
21 title,22}: {23 readonly label: string;24 readonly posture: Posture;29 /** The platform's full label, when the badge says a short form. */25 readonly title?: string | undefined;26}) => (27 <StateBadge28 className="text-ui items-start [&>svg]:mt-0.5"
9 unmodified lines
modified:apps/web/src/features/shared/project-order.ts-9 removed
1/**2 * Which projects a short list names: the rail's and the3 * landing's. The ones with the most open asks lead, a tie by name, so a4 * reader meets first the projects with work to take. The platform's own5 * list keeps its order; this is the web's.6 */1import type { ProjectListing } from "@repo/protocol/domain/front-page";2import { Array as Arr, Order } from "effect";310/** How many projects the rail and the landing name; the rest are a step away. */4export const PROJECTS_SHOWN = 8;513/** The most open asks first, then by name. */6const leading = Order.combine(7 Order.mapInput(8 Order.flip(Order.Number),9 ({ openAsks }: ProjectListing) => openAsks10 ),11 Order.mapInput(Order.String, ({ project }: ProjectListing) => project)12);1322/** The `n` projects that lead: the most open asks first, a tie by name. */14export const leadingProjects = (15 projects: readonly ProjectListing[],16 n: number17): readonly ProjectListing[] => Arr.take(Arr.sort(projects, leading), n);
modified:apps/web/src/features/shared/refusal.tsx+2 added-6 removed
1/**2 * A refusal, as `git push` printed it. The words are `@repo/protocol/render`'s3 * (`headline` and `explain`, the one renderer for git, the CLI, MCP and the4 * web, AGENTS.md principle 3); this view only sets them: each refusal's lines5 * verbatim, its tag in the rubric colour, then its `next` command to copy.6 * Whether retrying can help picks the mark, never the words.2 * The words are `@repo/protocol/render`'s; this view only sets them. Whether3 * retrying can help picks the mark, never the words.4 */5import type { Refusal } from "@repo/protocol/refusal";6import { explain, headline } from "@repo/protocol/render";7import type { Array } from "effect";8import { OctagonX, RotateCcw } from "lucide-react";910import { CommandLine } from "./command.tsx";1115/** One refusal's lines, with its tag set apart on the first. */12const Lines = ({ refusal }: { readonly refusal: Refusal }) => {13 const prefix = `${refusal._tag}:`;1415 return (
55 unmodified lines
modified:apps/web/src/features/shared/refusals.ts-9 removed
1/**2 * A loader's 404 that carries the platform's refusal to the page, in a3 * module with no view of its own: a route's loader runs before its page's4 * view loads. The refusals travel in a not-found's data, encoded as5 * `Refusals`; the page decodes them where they arrive (AGENTS.md6 * principle 2).7 */1import { Refusal } from "@repo/protocol/refusal";2import { notFound } from "@tanstack/react-router";3import { Effect, Schema } from "effect";412/** Refusals as a not-found carries them. */5export const Refusals = Schema.NonEmptyArray(Refusal);615/** A loader's 404 for `refusal`: a not-found that carries it, encoded, to the page. */7export const notFoundFor = (refusal: Refusal) =>8 Effect.flatMap(Schema.encodeEffect(Refusals)([refusal]), (data) =>9 Effect.fail(notFound({ data }))10 );
modified:apps/web/src/features/shared/row.tsx+4 added-91 removed
1/**2 * One row for every list: asks, decisions, landings, commits, refs, forks,3 * credits, rounds, history. Two lines, the thing first and its state at4 * the right:5 *6 * [mark] the want or subject, the link [state word] [copy]7 * kind · territory · id (metadata) [time]8 *9 * - Line 1 is the thing in its own words, one line, ellipsised, the whole10 * text its `title`; it is the link, never the id.11 * - Line 2 is metadata, parted by ` · `; a value that means nothing (the12 * whole repo's territory, ".") is left out (`MetaLine`).13 * - The state's mark sits in its own column, in its role's colour, and its14 * word at the right in ink (Refused and Landed keep theirs: DESIGN.md's15 * Mark Carries Rule); the mark is hidden from screen readers, the word16 * is not.17 * - A row with a command has one copy action, the command as text inside it.18 *19 * From the shell's width a click anywhere off the link selects the row20 * (its facts fill the inspector); below it the whole row is the link's to21 * press. `j` and `k` reach each row's link (`data-list-key`). Every22 * `data-*` a list carries sits on the row's `<li>`.23 */1import type { AskListing } from "@repo/protocol/domain/ask";2import type { ClaimState } from "@repo/protocol/domain/claim";3import { Outcome } from "@repo/protocol/domain/outcome";4import type { ProjectName } from "@repo/protocol/ids";
11 unmodified lines
16import { useSelection } from "./shell/selection.ts";17import type { SelectionParam } from "./shell/selection.ts";18import { When } from "./time.tsx";1943/** A row's state: its mark, its word, and when (a `When`, or words). */20export interface RowState {21 readonly mark: StateMark;22 readonly word: string;23 readonly time?: ReactNode;48 /** Settle the mark once: it landed while the page was open. */24 readonly stamp?: boolean;25}2627export interface RowProps {53 /** The thing's id: what selection and `j`/`k` name it by. */28 readonly id: string;55 /** Its page. */29 readonly href: string;57 /** The page's search, when the row names one state of it (`?head=`). */30 readonly search?: Readonly<Record<string, string>> | undefined;59 /** Line 1: the want, the subject, the commit's first line. */31 readonly title: string;61 /** Line 2 (or, one-line, after the title): metadata (`MetaLine`). */32 readonly meta?: ReactNode;33 readonly state?: RowState | undefined;64 /** A `CopyAction`, at the row's end. */34 readonly action?: ReactNode;66 /** A third line under the two: a family's fan. */35 readonly strip?: ReactNode;68 /**69 * What the row stands for, on its `<li>` (`data-ask`, `data-takeable`, …);70 * an attribute left undefined is left out.71 */36 readonly data?: Readonly<37 Record<`data-${string}`, string | boolean | undefined>38 >;39 readonly size?: "two-line" | "one-line";76 /** The row whose facts the inspector shows. */40 readonly selected?: boolean | undefined;78 /** Select the row, from the shell's width (`useRowSelection`). */41 readonly onSelect?: ((id: string) => void) | undefined;80 /** Line 1 is code (a ref, a fork's name): set it in mono. */42 readonly mono?: boolean;43}4484/** The shell's width, from which a row selects rather than opens. */45const SHELL_WIDTH = "(min-width: 70rem)";4647/**88 * The word's colour (DESIGN.md's Mark Carries Rule): ink, its role's colour89 * left to the mark, so a list of waiting asks is not an ochre stripe; a90 * refusal keeps red and a landing green. A refusal that can be retried91 * keeps its ochre mark, but its word is a refusal's, as the status line92 * says it.48 * Ink, the role's colour left to the mark, so a list of waiting asks is not an49 * ochre stripe; a refusal keeps red and a landing green.50 */51export const wordTone = (mark: StateMark) => {52 if (mark === "refused" || mark === "retry") {53 return STATE_MARKS.refused.tone;
1 unmodified line
5556 return mark === "landed" ? STATE_MARKS.landed.tone : "text-foreground";57};58102/** Whether a press on `target` was meant for a link or a control in the row. */59const onControl = (target: EventTarget) =>60 target instanceof Element &&61 target.closest("a, button, summary, input, select, textarea") !== null;62107/** Metadata parted by ` · `, with every empty part left out. */63export const MetaLine = ({64 parts,65}: {66 readonly parts: readonly (ReactNode | false | null | undefined)[];
10 unmodified lines
77 </Fragment>78 ));79};80126/** Code in a row's metadata: an id, a territory, a SHA. */81export const MetaCode = ({ children }: { readonly children: ReactNode }) => (82 <code className="text-mono font-mono">{children}</code>83);84131/** A territory as a row shows it: nothing for the whole repo. */85export const territoryPart = (territory: string) =>86 territory === "." || territory === "" ? undefined : (87 <MetaCode>{territory}</MetaCode>88 );8990const LINK =91 "text-foreground no-underline outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:outline-2 focus-visible:after:-outline-offset-2 focus-visible:after:outline-ring focus-visible:after:outline-solid";92140/** From the shell's width a row that selects lets a press off its link through to the row. */93const SELECTS = "shell:after:pointer-events-none";94143/** A press on the row, off its link and its controls, selects it from the shell's width. */95const selectOnPress =96 (id: string, onSelect: ((id: string) => void) | undefined) =>97 (event: MouseEvent<HTMLLIElement>) => {98 if (
4 unmodified lines
103 onSelect(id);104 }105 };106156/** The row's state at its end: the word in its role, over (or beside) its time. */107const StateEnd = ({108 state,109 stacked,110}: {
43 unmodified lines
154 <AppLink155 aria-current={selected ? "true" : undefined}156 className={onSelect === undefined ? LINK : `${LINK} ${SELECTS}`}157 data-list-key={id}208 // The thing in its own words: a want, a subject, a commit's line.158 data-said=""159 search={search}160 title={title}161 to={href}
6 unmodified lines
168 state === undefined ? null : (169 <StateMarkIcon mark={state.mark} stamp={state.stamp === true} />170 );171223 // `isolate` keeps the row's raised controls (its copy button, a fan's224 // nodes) inside the row, so a sticky header passes over them.172 // `isolate` keeps the row's raised controls inside the row, so a sticky173 // header passes over them.174 const rowClass = `group/row border-rule relative isolate -mx-2 border-b px-2 transition-colors duration-[120ms] ${175 selected ? "bg-surface hover:bg-surface-2" : "hover:bg-surface/50"176 }`;177
34 unmodified lines
212 </p>213 {meta === undefined && state === undefined ? null : (214 <p className="text-ui text-muted-foreground truncate leading-5">215 {state === undefined ? null : (267 // On a phone the want takes the width; its state leads line 2.216 <span217 className={`tablet:hidden font-medium ${wordTone(state.mark)}`}218 >219 {state.word}
18 unmodified lines
238 </li>239 );240};241294/** Where a group's header sticks: under the toolbar, or under the context bar when the list has none. */242const STICK = {243 bar: "top-[2.6875rem] tablet:top-[2.9375rem] shell:top-[2.6875rem]",244 toolbar: "top-[5.1875rem] tablet:top-[5.4375rem] shell:top-[5.1875rem]",245} as const;246300/** A list's group: a sticky header (its name as a link, its facts, its counts), then its rows. */247export const RowGroup = ({248 children,249 counts,250 facts,
1 unmodified line
252 name,253 under = "toolbar",254}: {255 readonly name: ReactNode;310 /** The group's facts after its name: a project's posture. */256 readonly facts?: ReactNode;312 /** Its counts at the end, in words: "7 open · 6 to take". */257 readonly counts?: string | undefined;314 /** The group's name in words, for its list (the name may be a link). */258 readonly label?: string;316 /** What the header sticks under. */259 readonly under?: keyof typeof STICK;260 readonly children: ReactNode;261}) => (262 <section aria-label={label} className="flex min-w-0 flex-col">263 <div322 // On a phone a long posture wraps under the name rather than losing323 // its last word; from a tablet the header is one 32 px line.264 className={`border-rule bg-background tablet:h-8 tablet:flex-nowrap tablet:py-0 sticky z-[5] -mx-2 flex min-h-8 min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5 border-b px-2 py-1 ${STICK[under]}`}265 >266 <h2 className="text-ui shrink-0 font-semibold [&_a]:no-underline [&_a:hover]:underline">267 {name}
12 unmodified lines
280 <ul className="flex flex-col">{children}</ul>281 </section>282);283344/** A list of rows with no groups. */284export const RowList = ({285 children,286 label,287}: {288 readonly children: ReactNode;289 readonly label: string;290}) => (352 // The top hairline runs as wide as the rows' own (each row reaches 8 px353 // past the list on either side, for its fill).291 <ul292 aria-label={label}293 className="border-rule -mx-2 flex flex-col border-t px-2"294 >295 {children}296 </ul>297);298362/**363 * A list's selection and keys together: the row selected (from the364 * address), the one `j`/`k` rest on, and the select to hand each row.365 */299export const useRowSelection = (300 ids: readonly string[],301 param: SelectionParam302) => {
2 unmodified lines
305306 return { clear, focused, select, selected };307};308376/** An answer's latest outcome as a row's state: a retryable refusal turns back. */309export const outcomeState = (outcome: Outcome): RowState =>310 Outcome.match(outcome, {311 AwaitingDecision: (): RowState => ({ mark: "waiting", word: "Waiting" }),312 AwaitingFinish: (): RowState => ({ mark: "waiting", word: "Waiting" }),
5 unmodified lines
318 }),319 WaitingOnParent: (): RowState => ({ mark: "waiting", word: "Waiting" }),320 });321390/** Each claim state as a row says it: its mark and its word. */322export const CLAIM_STATES = {323 answered: { mark: "landed", word: "Answered" },324 lapsed: { mark: "notNeeded", word: "Lapsed" },325 live: { mark: "claimed", word: "Claimed" },326 released: { mark: "notNeeded", word: "Given up" },327 warned: { mark: "waiting", word: "Warned, no push lately" },328} as const satisfies Record<ClaimState, RowState>;329399/** Who an ask is held for, as its state word. */330const reserveWords = {331 newcomers: "Held for newcomers",332 people: "Held for people",333} as const;334405/** Where an open ask stands for its reader, as a row's state. */335const askState = (336 listing: AskListing,337 takeable: boolean | undefined,338 progress: AskProgress | undefined
13 unmodified lines
352 if (listing.blockedBy.length > 0) {353 return { mark: "waiting", word: "Waiting" };354 }355427 // An ask held for someone says so wherever it is listed and whoever428 // reads it, before whether this reader may take it.356 if (listing.reserve !== undefined) {357 return { mark: "open", word: reserveWords[listing.reserve] };358 }359
1 unmodified line
361 ? { mark: "notYet", word: "Not open to you" }362 : { mark: "open", word: "Open to take" };363};364438/**439 * The time an ask row shows: its last push, else its last round, else its440 * opening, so a list scans by recency.441 */365const askTime = (progress: AskProgress | undefined) =>366 progress?.lastPush?.at ?? progress?.rounds.at(-1)?.at ?? progress?.opened;367445/**446 * An open ask as a row: its want, its kind, territory and id, where it447 * stands (from the listing, and the event fold when the page has it), and448 * the claim command when the reader may take it.449 */368export const AskRow = ({369 listing,370 now,371 onSelect,
5 unmodified lines
377 takeable,378}: {379 readonly listing: AskListing;380 readonly project: ProjectName;463 /** Whether the viewer may take it (the front page knows); a project's page does not say. */381 readonly takeable?: boolean | undefined;465 /** The ask's progress from the project's events, when the page folds them. */382 readonly progress?: AskProgress | undefined;383 readonly selected?: boolean | undefined;384 readonly onSelect?: ((id: string) => void) | undefined;469 /** Name the project in the metadata: a list across projects with no groups. */385 readonly showProject?: boolean;471 /** A family's fan, when the ask is a parent. */386 readonly strip?: ReactNode;473 /** The page's now, which the row's time is told against. */387 readonly now?: DateTime.Utc | undefined;388}) => {389 const at = askTime(progress);390 const standing = askState(listing, takeable, progress);
44 unmodified lines
modified:apps/web/src/features/shared/skeleton.tsx-9 removed
1/**2 * What holds a row's or a fact block's place while it is read in the3 * browser (a selection's facts, a live fold, a route change): the same4 * size as what replaces it, drawn as hairline bars at 1.5:1 or more, still.5 * No shimmer: the wait is a fact, not a show. The lists themselves arrive6 * with the page, so these are only for what the browser reads after it.7 */1import { Skeleton } from "../../components/ui/skeleton.tsx";210/** A two-line row's place: 64 px, the want's bar over the metadata's. */3export const RowSkeleton = () => (4 <div5 aria-hidden="true"6 className="border-rule flex h-16 flex-col justify-center gap-2.5 border-b pl-8"
2 unmodified lines
9 <Skeleton className="h-2.5 w-full max-w-[14rem]" />10 </div>11);1221/** The inspector's place: each block's label as it will read, its values as bars. */13export const FactsSkeleton = ({14 labels,15}: {16 readonly labels: readonly string[];
15 unmodified lines
modified:apps/web/src/features/shared/state-badge.tsx-12 removed
1/**2 * The one way the web shows a state in a word: its mark, then its word in3 * the state's role, at the size of the line it sits in. No pill, no fill,4 * no box: the mark and the word are the badge. A posture, a stage, an5 * ask's standing and a decision's default all draw through it.6 */1import { Predicate } from "effect";2import type { ReactNode } from "react";34import type { MarkLook } from "./mark-look.ts";5import { Mark, STATE_MARKS } from "./marks.tsx";6import type { StateMark } from "./marks.tsx";78export interface StateBadgeProps {15 /** A named state, or a look of its own (a posture's). */9 readonly mark: StateMark | MarkLook;17 /** The word, when the state's own word is not the one to say. */10 readonly word?: ReactNode;19 /** The word's colour, when it is not the mark's role (a posture's word is muted). */11 readonly wordTone?: string;21 /** A step down, for 13 px lines (a stage's cell). */12 readonly small?: boolean;23 /** Settle the mark once, as a landing's stamp does. */13 readonly stamp?: boolean;14 readonly className?: string;26 /** What the badge stands for, for tests and styles (`data-posture`, `data-state`). */15 readonly data?: Readonly<Record<`data-${string}`, string>>;16}1718export const StateBadge = ({
23 unmodified lines
modified:apps/web/src/features/shared/status-line.tsx+2 added-46 removed
1/**2 * Where a subject stands, in one sentence, the same on every page: under a3 * title, in the inspector's State block, and (compact: the mark and the4 * lead word) in the context bar.5 *6 * [mark] [Lead, in its role] [the rest, in ink] · [whose move] · [next command]7 *8 * A subject is an answer (its outcome), an ask (its state, who holds it and9 * its latest outcome), a decision or a proposal. Whose move it is comes10 * from the outcome alone (`whoseMove`): a refusal leaves it to the11 * answerer, a wait on a decision or a finish to a decider, a check under12 * way to the platform, a wait on a parent ask to the family.13 *14 * Two rules hold everywhere: waiting is never drawn in the refused role,15 * and a refusal is named by its tag (`headline`, the renderer git and the16 * CLI use) and never paraphrased; the refusal itself is `RefusalView`'s.2 * Waiting is never drawn in the refused role, and a refusal is named by its3 * tag, never paraphrased.4 */5import type { Ask } from "@repo/protocol/domain/ask";6import type { Choice, Decision } from "@repo/protocol/domain/decision";7import { Outcome } from "@repo/protocol/domain/outcome";
16 unmodified lines
24import type { StateMark } from "./marks.tsx";25import { askPath, decisionPath } from "./paths.ts";26import { distanceInWords } from "./time.tsx";2741/** Each stage as a cell heads it (`label`) and as a sentence names it (`words`). */28export const stageNames = Match.type<StageName>().pipe(29 Match.when("parse", () => ({ label: "Parse", words: "parse" })),30 Match.when("shape", () => ({ label: "Shape", words: "shape" })),31 Match.when("merge", () => ({ label: "Merge", words: "merge" })),
6 unmodified lines
38 Match.when("human", () => ({ label: "Decider", words: "decider" })),39 Match.exhaustive40);4156/** What a status line is about. */42export type StatusSubject =43 | {44 readonly kind: "answer";45 readonly outcome: Outcome;61 /** Who holds the ask, to name whose move a refusal leaves. */46 readonly claimant?: Handle | undefined;63 /** The stage the verdict reached, to say where a refusal came from. */47 readonly stage?: StageName | undefined;65 /** The project, to link the landing, the decision or the parent named. */48 readonly project?: ProjectName | undefined;49 }50 | {51 readonly kind: "ask";52 readonly ask: Ask;71 /** Whether the viewer may take it now. */53 readonly takeable: boolean;54 readonly claimant?: Handle | undefined;74 /** The current attempt's latest outcome, from the event fold. */55 readonly latest?: Outcome | undefined;76 /** The asks it waits on, as a family counts them (`familyMarks(ask, states)`). */56 readonly blockers?: Family | undefined;57 }58 | {59 readonly kind: "decision";60 readonly decision: Decision;61 readonly now: DateTime.Utc;83 /** Whether the viewer is one of its deciders. */62 readonly viewerDecides: boolean;63 }64 | { readonly kind: "proposal"; readonly proposal: Proposal };6588/** The role a line is drawn in; `ink` and `muted` are no state's colour. */66export type StatusTone =67 | "checking"68 | "ink"69 | "landed"
9 unmodified lines
79 refused: "text-refused",80 waiting: "text-waiting",81} as const satisfies Record<StatusTone, string>;82106/** A status line, read from its subject. */83interface Reading {84 readonly mark: StateMark;85 readonly tone: StatusTone;86 readonly lead: string;87 readonly rest?: ReactNode;112 /** Muted parts after the sentence: who it is held for, a default, whose move. */88 readonly after: readonly string[];114 /** The command that runs next, when the subject itself names one (a refusal's `next`). */89 readonly next?: string;90}9192const Code = ({ children }: { readonly children: ReactNode }) => (
1 unmodified line
94 {children}95 </code>96);97124/** `children` as a link to `to` when the project is known, as plain code when not. */98const CodeLink = ({99 children,100 to,101}: {
10 unmodified lines
112 {children}113 </AppLink>114 );115143/** Whose move, in words; nothing when it is no one's. */116const moveWords = (117 move: Move,118 {119 claimant,
10 unmodified lines
130 Match.when("decider", () => [131 decider === undefined ? "a decider's move" : `${decider}'s move`,132 ]),133 Match.when("platform", () => ["the platform's move"]),162 // The ask it waits on may be a family's or a lone one: its move.134 Match.when("parent", () => ["that ask's move"]),135 Match.when("none", () => []),136 Match.exhaustive137 );138168/** An answer's outcome as a line. */139const answerReading = ({140 claimant,141 outcome,142 project,
116 unmodified lines
259 }),260 });261};262293/** Who an ask is held for, when it is held for someone. */263const heldFor = (ask: Ask): readonly string[] => {264 if (ask.reserve === "newcomers") {265 return [266 ask.mentor === undefined
4 unmodified lines
271272 return ask.reserve === "people" ? ["held for people, not agents"] : [];273};274306/** What an ask that waits on others waits for, in its family's terms when the caller counted them. */275const waitingReading = (ask: Ask, blockers: Family | undefined): Reading => {276 if (blockers !== undefined && blockers.total > 0) {277 const remaining = blockers.total - blockers.landed;278
79 unmodified lines
358 tone: "ink",359 };360 }361394 // Not takeable while it waits on others: waiting, as its row says.362 return !takeable && ask.blockedBy.length > 0363 ? { after: [], lead: "Waiting", mark: "waiting", tone: "waiting" }364 : {365 after: heldFor(ask),
2 unmodified lines
368 tone: "muted",369 };370};371405/** A decider's choice in the past tense, and whether it took effect. */372const chosen = {373 accept: { effect: true, word: "Accepted" },374 adopt: { effect: true, word: "Adopted" },375 decline: { effect: false, word: "Declined" },
2 unmodified lines
378 Choice,379 { readonly effect: boolean; readonly word: string }380>;381416/** Whose move an open decision is: the viewer's, its one decider's, or any of its deciders'. */382const deciderMove = (decision: Decision, viewerDecides: boolean) => {383 if (viewerDecides) {384 return "your move";385 }
100 unmodified lines
486 }),487 });488};489525/** The line its subject reads as. */490export const readStatus: (subject: StatusSubject) => Reading =491 Match.type<StatusSubject>().pipe(492 Match.discriminator("kind")("answer", answerReading),493 Match.discriminator("kind")("ask", askReading),
10 unmodified lines
504} as const;505506export interface StatusLineProps {507 readonly subject: StatusSubject;544 /**545 * The command that runs next; a refusal's own `next` when left out, and546 * none at all with `false` (a refusal drawn whole below the line shows547 * its own).548 */508 readonly command?: string | false;550 /** Only the mark and the lead word (the context bar's). */509 readonly compact?: boolean;552 /** The outcome hero of an answer is a step up. */510 readonly size?: keyof typeof SIZE;554 /** Settle the mark once: a landing that happened while the page was open. */511 readonly stamp?: boolean;512}513514export const StatusLine = ({
60 unmodified lines
modified:apps/web/src/features/shared/theme.ts+2 added-3 removed
1/**2 * The paper colour of each theme, as hex for the places that cannot read a3 * CSS variable: the document's `theme-color` meta and the web app manifest.4 * They equal `--background` in `src/styles.css`.2 * For the places that cannot read a CSS variable (the `theme-color` meta, the3 * manifest). They equal `--background` in `src/styles.css`.4 */5export const themeColors = {6 dark: "#0e1114",7 light: "#f5f8fa",
1 unmodified line
modified:apps/web/src/features/shared/time.tsx-7 removed
1/**2 * A time as a short distance from now: "in 3 h", "2 d ago". `now` is a prop,3 * so a page and its test say the same thing; the exact time is the4 * element's `dateTime` and its tooltip.5 */1import { DateTime } from "effect";23const MINUTE = 60_000;45const HOUR = 60 * MINUTE;67const DAY = 24 * HOUR;814/** The largest whole unit in `millis`, as "5 min", "3 h" or "2 d". */9const span = (millis: number) => {10 if (millis < HOUR) {11 return `${Math.floor(millis / MINUTE)} min`;12 }
2 unmodified lines
15 ? `${Math.floor(millis / HOUR)} h`16 : `${Math.floor(millis / DAY)} d`;17};1825/** How far `at` is from `now`, in words. */19export const distanceInWords = (at: DateTime.Utc, now: DateTime.Utc) => {20 const millis = DateTime.toEpochMillis(at) - DateTime.toEpochMillis(now);2122 if (Math.abs(millis) < MINUTE) {
21 unmodified lines
modified:apps/web/src/features/today/read.ts+3 added-25 removed
1/**2 * What Today's page reads, in a module with no view of its own: a route's3 * loader runs before its page's view loads, so the route reaches these4 * without carrying the page.5 *6 * - `TodayRead`: the reader's Today, or why there is none (a refusal, no7 * session, no answer from the platform), as the loader sends it.8 * - `readToday`: that read, made with whatever `Client` the caller gives9 * (the server's, carrying the reader's own session).10 * - The order a decider takes decisions in: due within the day first, then11 * by expiry.12 */1import { Client } from "@repo/protocol/contracts";2import { Today } from "@repo/protocol/domain/decision";3import type { Decision } from "@repo/protocol/domain/decision";4import type { DecisionId, ProjectName } from "@repo/protocol/ids";
11 unmodified lines
16} from "effect";1718import { decisionKey } from "../decision/subject.ts";1932/** What the page read for its reader: their Today, or why there is none. */20export const TodayRead = Schema.TaggedUnion({21 Read: { today: Today },22 Refused: { refusal: Refusal },23 SignedOut: {},
1 unmodified line
25});2627export type TodayRead = typeof TodayRead.Type;2842/** What Today's loader sends: the read, and the instant it was made. */29export const TodayPageData = Schema.Struct({30 now: Schema.DateTimeUtcFromString,31 read: TodayRead,32});
3 unmodified lines
36const isRefusal = Schema.is(Refusal);3738const isUnauthenticated = Schema.is(Unauthenticated);3954/** Whether a read failed because its reader is not signed in. */40export const isSignedOut = (cause: Cause.Cause<unknown>) =>41 Option.exists(Cause.findErrorOption(cause), isUnauthenticated);4258/** A failed read of Today, as the page says it. */43export const readOfCause = (cause: Cause.Cause<unknown>): TodayRead => {44 const error = Cause.findErrorOption(cause);4546 if (Option.isSome(error) && isRefusal(error.value)) {
4 unmodified lines
51 ? TodayRead.cases.SignedOut.make({})52 : TodayRead.cases.Unreachable.make({});53};5471/** Soonest to expire first, then oldest, then by project and id: one order every time. */55export const expiryOrder: Order.Order<Decision> = Order.combineAll([56 Order.mapInput(DateTime.Order, ({ expiresAt }: Decision) => expiresAt),57 Order.mapInput(DateTime.Order, ({ openedAt }: Decision) => openedAt),58 Order.mapInput(Order.String, ({ project }: Decision) => project),59 Order.mapInput(Order.String, ({ id }: Decision) => id),60]);6162/**80 * The decisions `today.expiringSoon` names. Ids are minted per project, so a81 * Today across projects may hold two decisions with one id; where an id is82 * named `n` times, the `n` of its decisions that expire first are the ones83 * meant (a decision that expires within the day expires before any that84 * does not).63 * Ids are minted per project, so a Today across projects may hold two decisions64 * with one id; where an id is named `n` times, the `n` of its decisions that65 * expire first are the ones meant.66 */67export const expiringSoon = (today: Today): ReadonlySet<string> => {68 const named = Arr.groupBy(today.expiringSoon, (id) => id);69 const byExpiry = Arr.sort(today.decisions, expiryOrder);
7 unmodified lines
77 )78 );79};80100/** Today's decisions in the order a decider takes them: expiring soon first, then by expiry. */81export const orderDecisions = (today: Today): readonly Decision[] => {82 const soon = expiringSoon(today);8384 return Arr.sort(
7 unmodified lines
92 )93 );94};95116/** Where one decision stands on Today: listed (and whether it expires soon), or not there. */96export const findDecision = (97 today: Today,98 project: ProjectName,99 id: DecisionId
10 unmodified lines
110 }))111 );112};113135/** The reader's Today, or why there is none, encoded for the page. */114export const readToday = ({ project }: { readonly project?: ProjectName }) =>115 Effect.gen(function* () {116 const client = yield* Client;117
12 unmodified lines
modified:apps/web/src/features/today/today-page.tsx+1 added-52 removed
1/**2 * Today: a decider's day of decisions, not diffs, held to a budget said in3 * one sentence. The decisions sit in sections: those due within the day,4 * then the rest within the budget by expiry, then how many wait for5 * tomorrow (their ids are not in the read, so they have no rows). Below6 * them, the newcomers to welcome and a sample of landings that needed7 * nobody.8 *9 * Each row says its subject in plain words (the link to its page), its10 * project, kind and id, and when it expires over its default. From the11 * shell's width a row selects into the inspector, which holds the whole12 * decision: its evidence, a note, and its choices, each with what it does.13 * Below it a row opens in place, one at a time, its choices kept in sight14 * above the bottom bar while it is open.15 *16 * A choice taken leaves its row where it was, reading what it did; the17 * budget sentence moves with the next read. There is no toast.18 *19 * A failure reads as what it is: a refusal (`NotDecider` for a person who20 * decides nothing) through `RefusalView`, a missing sign-in as what Today21 * is and how to sign in, and an unreachable platform as that, never as an22 * empty day.23 */1import { Brand } from "@repo/brand";2import type { Decision, Today } from "@repo/protocol/domain/decision";3import type { LandingView } from "@repo/protocol/domain/landing";4import { Array as Arr, Option, Order } from "effect";
42 unmodified lines
47} from "./read.ts";4849const counted = (count: number) => (count === 0 ? "none" : String(count));5074/** The day's budget, in one sentence: decisions taken and left, and the finishes apart. */51export const budgetSentence = (budget: Today["budget"]) =>52 `Decisions: ${budget.used} taken, ${counted(Math.max(0, budget.total - budget.used))} left today. Finishes are counted apart: ${counted(budget.finishes)} taken.`;5378/** The budget for the context bar: what is left. */54const budgetShort = (budget: Today["budget"]) =>55 `${counted(Math.max(0, budget.total - budget.used))} left today`;5682/** What Today is, for someone it does not hold decisions for yet. */57const WHAT_TODAY_IS =58 "Today is a decider's page: the decisions you owe your projects each day, each with its evidence and a safe default if you leave it.";5986/** A decision on the page: listed, and whether it is due within the day. */60interface Listed {61 readonly decision: Decision;62 readonly soon: boolean;63}6492/** The choice a row's decision was taken with, when the decider took it here. */65const choiceOf = (decision: Decision) => decision.decided?.choice;6695/** Its expiry over its default, at the row's end; muted when it is not due within the day. */67const openState = (listed: Listed, now: DateTime.Utc) => ({68 mark: listed.soon ? ("waiting" as const) : ("notYet" as const),69 time: `default: ${listed.decision.default}`,70 word: distanceInWords(listed.decision.expiresAt, now),71});72102/** The way to open a row in place, below the shell's width. */73const OpenHere = ({74 decision,75 onToggle,76 open,
25 unmodified lines
102 readonly onSelect: ((key: string) => void) | undefined;103 readonly open: string | undefined;104 readonly onOpen: (key: string | undefined) => void;105 readonly selected: string | undefined;136 /** The decisions taken while the page was open, to stamp once. */106 readonly stamped: ReadonlySet<string>;107}108140/** One decision's row: its subject, where it stands, and (below the shell's width) the whole of it in place. */109const DecisionRow = ({110 listed,111 props,112}: {
96 unmodified lines
209210const plural = (count: number, one: string, many: string) =>211 `${count} ${count === 1 ? one : many}`;212245/** The decisions, due today then within the budget, each section only when it holds one. */213const DecisionSections = ({214 listed,215 props,216}: {
36 unmodified lines
253 </>254 );255};256290/** How many wait beyond the budget, as a sentence: their ids are not in the read. */257const Tomorrow = ({ overflow }: { readonly overflow: number }) =>258 overflow === 0 ? null : (259 <Section name="Waits for tomorrow">260 <li
62 unmodified lines
323 ))}324 </Section>325 );326361/** The decision the inspector holds, whole. */327const SelectedFacts = ({328 busy,329 listed,330 now,
40 unmodified lines
371 </FactBlock>372 </>373);374410/** Signed out: what Today is, the way in, and the command. */375const SignedOutNotice = ({ here }: { readonly here: string }) => (376 <div className="flex max-w-[70ch] flex-col items-start gap-3">377 <p className="text-body">{WHAT_TODAY_IS}</p>378 <p className="text-ui">
8 unmodified lines
387 <CommandLine command={`${Brand.cli} today`} />388 </div>389);390427/** What a choice that failed came back with: the refusal, or why there is none. */391const DecidedFailure = ({392 decided,393}: {394 readonly decided: AsyncResult.AsyncResult<unknown, unknown>;
11 unmodified lines
406 Unreachable: () => <UnreachableNotice />,407 });408};409447/** The page around a Today with no decisions to list: the reason, said whole. */410const Unlisted = ({ children }: { readonly children: ReactNode }) => (411 <Workspace crumbs={[{ label: "Today" }]} title="Today" variant="list">412 {children}413 </Workspace>414);415454/**455 * The decisions on the page: Today's, and any the decider took here that456 * the next read no longer lists, each where it was.457 */416const listedOf = (417 today: Today,418 taken: ReadonlyMap<string, Listed>419): readonly Listed[] => {
20 unmodified lines
440 )441 );442};443486/** `kept` with `decision`, taken, where it was listed. */444const withTaken = (445 kept: ReadonlyMap<string, Listed>,446 decision: Decision,447 soon: ReadonlySet<string>
5 unmodified lines
453 [key, { decision, soon: kept.get(key)?.soon ?? soon.has(key) }],454 ]);455};456500/** The decision a choice just came back with, when it was taken. */457const takenNow = (458 decided: AsyncResult.AsyncResult<{ readonly decision: Decision }, unknown>459): Option.Option<Decision> =>460 Option.filter(
23 unmodified lines
484 const [open, setOpen] = useState<string>();485 const soon = expiringSoon(today);486 const fresh = takenNow(decided);487532 // A choice taken stays on the page after the next read leaves it out:533 // kept as soon as it comes back, while this render draws it already.488 // A choice taken stays on the page after the next read leaves it out.489 if (490 Option.isSome(fresh) &&491 kept.get(decisionKey(fresh.value))?.decision.decided === undefined492 ) {
35 unmodified lines
528 onDecide,529 onOpen: setOpen,530 onSelect,531 open,577 // A row is drawn selected only when the address names it; with none578 // named the inspector holds the first, and no row looks chosen.532 selected,533 stamped,534 };535536 return (584 // Below the shell's width a row opens in place, so the inspector's585 // copy of the selected decision is not drawn in main as well.537 <div className="contents [&_[data-facts=inline]]:hidden">538 <Workspace539 count={budgetShort(today.budget)}540 crumbs={[{ label: "Today" }]}
52 unmodified lines
593}: {594 readonly read: TodayRead;595 readonly now: DateTime.Utc;596 readonly onDecide: (input: DecideInput) => void;646 /** The decider's last choice, as `decide` answered it. */597 readonly decided?: AsyncResult.AsyncResult<598 { readonly decision: Decision },599 unknown600 >;651 /** The decision the inspector holds (`project/id`); the first listed when none. */601 readonly selected?: string | undefined;602 readonly onSelect?: ((key: string) => void) | undefined;603}) =>604 TodayRead.match(read, {
28 unmodified lines
modified:apps/web/src/features/why/band.tsx-17 removed
1/**2 * Who put lines there, in one line, ask and answer first and the commit3 * second: "format-ordinal · answered by bram · 9b1c3e5 · 3 d ago". An4 * ask's opening reads "opened format-ordinal · by ines-v · …"; a decider's5 * own landing "landed by okonkwo · …"; a commit the project adopted, its6 * subject and author, "before adoption". Each part is a link: the ask, the7 * answer, the commit. No credit count and no colour by age: neither is a8 * state.9 *10 * Used by a why group's band, and by a file's facts for the landing that11 * last touched it.12 */1import type { CommitView } from "@repo/protocol/domain/code";2import type { LandingView } from "@repo/protocol/domain/landing";3import type { ProjectName } from "@repo/protocol/ids";4import { Option } from "effect";
10 unmodified lines
15const LINK = "decoration-rule underline hover:decoration-current";1617const CODE_LINK = `text-mono font-mono ${LINK}`;1831/** Parts parted by a muted ` · `. */19const Parted = ({ parts }: { readonly parts: readonly ReactElement[] }) =>20 parts.map((part, index) => (21 <Fragment key={String(part.key)}>22 {index === 0 ? null : (
4 unmodified lines
27 {part}28 </Fragment>29 ));3044/** What the landing did, ask first: answered, opened, or landed by a decider. */31const landingParts = (32 landing: LandingView,33 project: ProjectName34): readonly ReactElement[] => {
36 unmodified lines
71 </AppLink>,72 ];73};7489/** A commit the project adopted: its subject, its author, and that it came before adoption. */75const adoptedParts = (76 commit: CommitView | undefined77): readonly ReactElement[] => {78 const subject = commit?.subject ?? "";
8 unmodified lines
87 </span>,88 ];89};90106/** The line for a commit, and its landing when the platform landed it. */91export const LandingWords = ({92 commit,93 landing,94 now,95 project,96 sha,97}: {98 readonly project: ProjectName;115 /** The commit's id (all a line has when the walk did not return the commit). */99 readonly sha: string;100 readonly commit: Option.Option<CommitView>;101 readonly landing: Option.Option<LandingView>;102 readonly now: DateTime.Utc;
31 unmodified lines
modified:apps/web/src/features/why/client-why.tsx+2 added-8 removed
1/**2 * The "why" drawing, in the browser only: `@pierre/diffs` and Shiki's3 * grammars are megabytes and the drawing needs the DOM, so the server4 * renders `fallback` (the table of ranges beside the numbered lines) and5 * the browser loads the drawing after hydration. `import.meta.env.SSR` is6 * `true` in the Worker's build, so the dynamic import below is dead code7 * there and the Worker bundles none of it (`bytes:check`), as8 * `features/code/client-code.tsx` does.2 * `import.meta.env.SSR` is `true` in the Worker's build, so the dynamic import3 * below is dead code there and the Worker bundles none of it.4 */5import { ClientOnly } from "@tanstack/react-router";6import { lazy, Suspense } from "react";7import type { ReactNode } from "react";814// A type-only import is erased, so the server bundles nothing of it.9import type { WhyCodeProps } from "./why-code.tsx";1011const WhyLater = import.meta.env.SSR12 ? undefined
15 unmodified lines
modified:apps/web/src/features/why/range-summary.tsx-10 removed
1/**2 * A why group's band, shared by the server's plain text and the browser's3 * annotation rows: who put these lines there, ask and answer first4 * (`band.tsx`), then where to go from here: why, one step back (the same5 * page at the commit's parent) and a proposal about the group's first6 * line. `LandingDetails` is the landing whole, for the line dialog.7 */1import type { WhyView } from "@repo/protocol/domain/code";2import type { LandingView } from "@repo/protocol/domain/landing";3import type { ProjectName } from "@repo/protocol/ids";4import { DateTime, Option } from "effect";
16 unmodified lines
21const LINK = "decoration-rule underline hover:decoration-current";2223const LABEL = "text-label text-muted-foreground";2432/** Where to go from a group: why one step back, and a proposal about its first line. */25export const BandLinks = ({26 project,27 row,28 view,
31 unmodified lines
60 </span>61 );62};6372/** One group's band: who put its lines there, then where to go from here. */64export const WhyBand = ({65 now,66 project,67 row,
20 unmodified lines
88 <BandLinks project={project} row={row} view={view} />89 </div>90);91101/** A landing whole: its ask, author, verdict, when it landed, its credit and agents. */92export const LandingDetails = ({93 landing,94 project,95}: {
60 unmodified lines
modified:apps/web/src/features/why/rows.ts+1 added-22 removed
1/**2 * A "why" view as rows a reader scans: each range of lines with the commit3 * that brought it and, when the platform landed that commit, its landing4 * (the record's, never a trailer), plus the addresses each row links.5 */1import type { CommitView, WhyRange, WhyView } from "@repo/protocol/domain/code";2import type { LandingView } from "@repo/protocol/domain/landing";3import { Outcome } from "@repo/protocol/domain/outcome";4import type { AskId, ProjectName } from "@repo/protocol/ids";5import { Option } from "effect";67import { whyHref } from "../code/paths.ts";814/** One range of lines, the commit that brought it, and its landing when it is one. */9export interface WhyRow {10 readonly range: WhyRange;11 readonly commit: Option.Option<CommitView>;12 readonly landing: Option.Option<LandingView>;13}1421/** The view's ranges, in line order, each with its commit and landing. */15export const rowsOf = (view: WhyView): readonly WhyRow[] => {16 const commits = new Map<string, CommitView>(17 view.commits.map((commit) => [commit.sha, commit])18 );
8 unmodified lines
27 range,28 }));29};3038/**39 * The view's lines grouped by what brought them: consecutive ranges from40 * one commit form one group, so a landing's lines read as one band.41 */31export const groupsOf = (view: WhyView): readonly WhyRow[] => {32 const groups: WhyRow[] = [];3334 for (const row of rowsOf(view)) {
15 unmodified lines
5051 return groups;52};5365/** The row holding line `line`, numbered from 1. */54export const rowAt = (rows: readonly WhyRow[], line: number) =>55 Option.fromUndefinedOr(56 rows.find(({ range }) => range.start <= line && line <= range.end)57 );5871/** A range as a reader says it: "line 4", or "lines 1–3". */59export const linesWords = ({ end, start }: WhyRange) =>60 start === end ? `line ${start}` : `lines ${start}–${end}`;6175/**76 * The ask a landing links, and how: the one it answers, or the one it77 * opened (a migrate family's parent). An opening answers nothing, so it78 * has no answer page and its link never reads as an answer.79 */62/** An opening answers nothing, so it has no answer page. */63export type LandingAsk =64 | { readonly kind: "answers"; readonly ask: AskId }65 | { readonly kind: "opened"; readonly ask: AskId };6684/** Which ask `landing` links and how; none for a decider's own landing or an adoption. */67export const askOf = (landing: LandingView): Option.Option<LandingAsk> => {68 if (landing.ask !== undefined) {69 return Option.some({ ask: landing.ask, kind: "answers" });70 }
5 unmodified lines
76};7778const isLanded = Outcome.isAnyOf(["Landed"]);7998/** A landing's verdict in a word or two; none when it carries none. */80export const verdictWords = (landing: LandingView) =>81 Option.map(Option.fromUndefinedOr(landing.verdict), ({ outcome }) =>82 isLanded(outcome) ? "checked and landed" : outcome._tag83 );84104/** The page of this file as it was before `commit`: why at its first parent. */85export const priorHref = (86 project: ProjectName,87 commit: CommitView,88 path: string
1 unmodified line
90 Option.map(Option.fromUndefinedOr(commit.parents[0]), (parent) =>91 whyHref(project, parent, path)92 );93114/** The propose form, about line `line` of `path` at the commit `at`. */94export const proposeHref = (95 project: ProjectName,96 {97 at,
8 unmodified lines
modified:apps/web/src/features/why/why-code.tsx+2 added-12 removed
1/**2 * The file drawn by `@pierre/diffs`, with a band above each group of lines3 * one commit brought (`WhyBand`, the same the server's plain lines carry):4 * an annotation renders after its `lineNumber`, so a group starting at5 * line `n` sits at `n - 1`, and `0` is above line 1. Highlighting runs in6 * the worker pool. Clicking a line number opens a dialog with that line's7 * landing whole.8 *9 * It is Pierre's `File` (as `code-view.tsx` draws a file), which renders10 * on the server too, so its markup can be checked; the page loads it only11 * in the browser (`client-why.tsx`), and the Worker never bundles it.2 * An annotation renders after its `lineNumber`, so a group starting at line `n`3 * sits at `n - 1`, and `0` is above line 1.4 */5import { File } from "@pierre/diffs/react";6import type { FileOptions, LineAnnotation } from "@pierre/diffs/react";7import type { WhyView } from "@repo/protocol/domain/code";
21 unmodified lines
2930export interface WhyCodeProps {31 readonly now: DateTime.Utc;32 readonly project: ProjectName;41 /** The file's text at `view.at`. */33 readonly text: string;34 readonly view: WhyView;35}3646/** The dialog for one clicked line: its landing, or the commit the project adopted. */37const LineDialog = ({38 line,39 onClose,40 project,
103 unmodified lines
modified:apps/web/src/features/why/why-view.tsx-18 removed
1/**2 * A file in Why mode (ADR 0019): the same page as its Code mode, the code3 * with a band above each group of lines one commit brought, saying who4 * put them there, ask and answer first and the commit second, with why,5 * one step back. The server sends the bands among numbered plain lines;6 * the browser draws the file highlighted with the same bands as Pierre's7 * annotations (`code`, from `client-why.tsx`), where pressing a line8 * number opens that line's landing whole.9 *10 * A file the walk cannot read as text (binary, or past 1 MiB) has no11 * groups, and the page says so.12 */1import type { CommitView, FileView, WhyView } from "@repo/protocol/domain/code";2import type { ProjectName } from "@repo/protocol/ids";3import type { DateTime } from "effect";4import type { ReactNode } from "react";
8 unmodified lines
13import { groupsOf } from "./rows.ts";1415const LINK = "decoration-rule underline hover:decoration-current";1629/** The page's fallback: the numbered lines, each group's band above its first line. */17export const WhyFallback = ({18 now,19 project,20 text,
29 unmodified lines
50 readonly project: ProjectName;51 readonly rev: string;52 readonly view: WhyView;53 readonly now: DateTime.Utc;67 /** The file at `view.at`: its words, its bytes; absent when it could not be read. */54 readonly file?: FileView | undefined;69 /** The file's text at `view.at`; absent for a binary or too large file. */55 readonly text?: string;71 /** The browser's drawing, holding `WhyFallback` as its fallback. */56 readonly code?: ReactNode;73 /** The commit that last changed the file. */57 readonly last?: CommitView | undefined;75 /** The Files button, below the shell's width. */58 readonly files?: ReactNode;59}6061export const WhyLines = ({
80 unmodified lines