Skip to content
Myr

Merge build/1221-front-and-project-home

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

authored by oscabriel · committed by oscabriel · parents 2e6b5a5, 417bfb1 · Browse files · 26 files+4135 added−1288 removed
This commit

State

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

Diff stats

26 files+4135 added−1288 removed

  • tests:+1395 added−366 removed
  • other:+2740 added−922 removed

26 files+4135 added−1288 removed

modified:apps/web/src/client/front.ts+7 added-5 removed
modified:apps/web/src/client/project.ts+78 added-7 removed
added:apps/web/src/features/front/facts.tsx+261 added
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 */12import { Brand } from "@repo/brand";13import type { Ask, AskListing } from "@repo/protocol/domain/ask";14import type { ProjectListing } from "@repo/protocol/domain/front-page";15import type { AskId, ProjectName } from "@repo/protocol/ids";16import type { Posture } from "@repo/protocol/posture";17import { ArrowRight } from "lucide-react";1819import { postureLabel } from "../project/posture-label.ts";20import type { AskProgress } from "../shared/ask-progress.ts";21import { CommandLine } from "../shared/command.tsx";22import {23 FactBlock,24 FamilyFacts,25 PostureFacts,26 TerritoryFacts,27} from "../shared/facts.tsx";28import { AppLink } from "../shared/link.tsx";29import { askPath, projectPath } from "../shared/paths.ts";30import { PostureBadge } from "../shared/posture.tsx";31import { MetaCode } from "../shared/row.tsx";32import { FactsSkeleton } from "../shared/skeleton.tsx";33import { StatusLine } from "../shared/status-line.tsx";3435const LINK = "decoration-rule underline hover:decoration-current";3637/** One numbered step: what it does, then its command. */38export const Step = ({39 command,40 label,41}: {42 readonly command: string;43 readonly label: string;44}) => (45 <div className="flex min-w-0 flex-col gap-1">46 <p className="text-label text-muted-foreground">{label}</p>47 <CommandLine command={command} numbered />48 </div>49);5051/** A link onward, at a block's foot. */52export const Onward = ({53 children,54 to,55}: {56 readonly children: string;57 readonly to: string;58}) => (59 <AppLink60 className="text-ui decoration-rule inline-flex items-center gap-1.5 self-start underline hover:decoration-current"61 to={to}62 >63 {children}64 <ArrowRight aria-hidden="true" className="size-3.5" strokeWidth={1.75} />65 </AppLink>66);6768/** Where an agent reads the same thing: a server route, so a plain link. */69export const ForAgents = ({ href }: { readonly href: string }) => (70 <p className="text-ui text-muted-foreground border-rule border-t pt-3 first:border-t-0">71 For agents:{" "}72 <a className={`text-foreground text-mono font-mono ${LINK}`} href={href}>73 {href.slice(1)}74 </a>75 </p>76);7778/** The three ways in from the front page: the CLI, the asks it lists, a claim. */79export const StartHere = ({ webUrl }: { readonly webUrl: string }) => (80 <FactBlock label="Take an ask">81 <Step82 command={`curl -fsSL ${webUrl}/install.sh | sh`}83 label="Install the command line"84 />85 <Step command={`${Brand.cli} front`} label="List every open ask" />86 <Step87 command={`${Brand.cli} claim <ask> --project <project>`}88 label="Claim one you may take"89 />90 <ForAgents href="/llms.txt" />91 </FactBlock>92);9394/** A count and its noun: "1 open ask", "7 open asks". */95export const plural = (count: number, one: string, many: string) =>96 `${count} ${count === 1 ? one : many}`;9798/** Every project the platform lists, its posture and its open asks; bars until the list arrives. */99export const ProjectsFacts = ({100 projects,101}: {102 readonly projects: readonly ProjectListing[] | undefined;103}) =>104 projects === undefined ? (105 <FactsSkeleton labels={["Projects"]} />106 ) : (107 <FactBlock label="Projects">108 <ul className="flex flex-col">109 {projects.map((listing) => (110 <li111 className="flex min-h-11 min-w-0 flex-col justify-center gap-0.5 py-1"112 data-project={listing.project}113 key={listing.project}114 >115 <span className="flex min-w-0 items-baseline justify-between gap-3">116 <AppLink117 className="text-ui decoration-rule truncate font-semibold no-underline hover:underline"118 to={projectPath(listing.project)}119 >120 {listing.project}121 </AppLink>122 <span className="text-label text-muted-foreground shrink-0 tabular-nums">123 {plural(listing.openAsks, "open ask", "open asks")}124 </span>125 </span>126 <PostureBadge127 label={postureLabel(listing.posture)}128 posture={listing.posture}129 />130 </li>131 ))}132 </ul>133 </FactBlock>134 );135136/** Who may take an ask, from what its listing says (the full ask adds the mentor). */137const whoMayTake = (138 listing: AskListing,139 project: ProjectName,140 full: Ask | undefined141) => {142 if (listing.reserve === "newcomers") {143 return full?.mentor === undefined144 ? "Held for newcomers"145 : `Held for newcomers, mentored by ${full.mentor}`;146 }147148 return listing.reserve === "people"149 ? "Held for people, not agents"150 : `Anyone vouched in ${project}, or with a record in its area`;151};152153/** A family the selected ask belongs to, as the page knows it. */154export interface SelectedFamily {155 readonly parent: Ask;156 readonly finale: AskId;157 readonly states: ReadonlyMap<AskId, AskProgress>;158}159160/** The selected ask's project posture, in the platform's words. */161export interface SelectedPosture {162 readonly label: string;163 readonly posture: Posture;164}165166/**167 * The selected ask: its state, how to take it (the claim numbered first),168 * where it may change things and what judges it, its family, its project's169 * posture, and its page.170 */171export const SelectedAskFacts = ({172 family,173 full,174 listing,175 platformUrl,176 posture,177 progress,178 project,179 takeable,180}: {181 readonly listing: AskListing;182 readonly project: ProjectName;183 /** Whether the viewer may take it (the front page knows); open and unheld when not known. */184 readonly takeable: boolean;185 /** The full ask, once the browser has read it. */186 readonly full: Ask | undefined;187 readonly progress: AskProgress | undefined;188 readonly family: SelectedFamily | undefined;189 readonly posture: SelectedPosture | undefined;190 readonly platformUrl: string;191}) => {192 const claim = `${Brand.cli} claim ${listing.ask} --project ${project}`;193194 return (195 <>196 <FactBlock label="State">197 {full === undefined ? (198 <p className="text-want font-medium">{listing.want}</p>199 ) : (200 <StatusLine201 command={false}202 subject={{203 ask: full,204 claimant: progress?.claimant,205 kind: "ask",206 latest: progress?.latest,207 takeable,208 }}209 />210 )}211 <p className="text-ui text-muted-foreground">212 {listing.kind} · <MetaCode>{listing.ask}</MetaCode>213 </p>214 </FactBlock>215 <FactBlock label="Take it">216 <p className="text-ui">{whoMayTake(listing, project, full)}</p>217 {takeable ? (218 <>219 <Step command={claim} label="Claim it" />220 <Step221 command={`git clone ${platformUrl}/${project}.git`}222 label="Clone the project to answer in"223 />224 <Step225 command={`${Brand.cli} check`}226 label="Check your answer before you push"227 />228 </>229 ) : (230 <p className="text-ui text-muted-foreground">231 Not open to you now: its page says why.232 </p>233 )}234 </FactBlock>235 {full === undefined ? (236 <FactsSkeleton labels={["Territory and check"]} />237 ) : (238 <TerritoryFacts ask={full} />239 )}240 {family === undefined ? null : (241 <FamilyFacts242 current={listing.ask}243 finale={family.finale}244 parent={family.parent}245 project={project}246 states={family.states}247 />248 )}249 {posture === undefined ? null : (250 <PostureFacts251 label={posture.label}252 posture={posture.posture}253 project={project}254 />255 )}256 <FactBlock label="Its page">257 <Onward to={askPath(project, listing.ask)}>Open the ask</Onward>258 </FactBlock>259 </>260 );261};
added:apps/web/src/features/front/families.ts+100 added
1/**2 * Which listed asks form a family, read from the names a migrate ask's split3 * gives its members: the platform opens a child per module as4 * `<parent>-<module>` and a delete child as `<parent>-delete`, and the5 * parent waits on all of them. A listing names no parent (the full ask does,6 * one read away), so a family is read from what the list holds: an ask that7 * waits on an ask named after it is a family's parent, and its members are8 * the listed asks it waits on, and its delete child.9 *10 * An ask that waits on another not named after it (one fix after another)11 * is no family: it stays a row of its own that reads as waiting.12 */13import type { AskListing } from "@repo/protocol/domain/ask";14import { AskId } from "@repo/protocol/ids";1516/** One family, as a list holds it. */17export interface ListedFamily {18 readonly parent: AskId;19 /** Its members the list holds, in the list's order: the children still open, and the delete child. */20 readonly members: readonly AskId[];21 /** The delete child, which waits on every other child. */22 readonly finale: AskId;23}2425/** The delete child a split gives `parent`. */26export const finaleOf = (parent: AskId): AskId =>27 AskId.make(`${parent}-delete`);2829/** Whether `parent` waits on an ask named after it, as a split names its members. */30const isParent = ({ ask, blockedBy }: AskListing) =>31 blockedBy.some((blocker) => blocker.startsWith(`${ask}-`));3233/** Every family among `listings`, each at its parent's place in the list. */34export const familiesIn = (35 listings: readonly AskListing[]36): readonly ListedFamily[] =>37 listings.flatMap((parent) => {38 if (!isParent(parent)) {39 return [];40 }4142 const finale = finaleOf(parent.ask);43 const waits = new Set<string>([...parent.blockedBy, finale]);4445 return [46 {47 finale,48 members: listings.flatMap(({ ask }) =>49 ask !== parent.ask && waits.has(ask) ? [ask] : []50 ),51 parent: parent.ask,52 },53 ];54 });5556/** A list's item: an ask of its own, or a family drawn as one row. */57export type Arranged<L extends AskListing = AskListing> =58 | { readonly kind: "ask"; readonly listing: L }59 | {60 readonly kind: "family";61 readonly parent: L;62 readonly members: readonly L[];63 readonly finale: AskId;64 };6566/**67 * `listings` as a list draws them: each family at its parent's place, its68 * members taken out of the list (they are drawn under the parent's fan),69 * every other ask where it was.70 */71export const arrange = <L extends AskListing>(72 listings: readonly L[]73): readonly Arranged<L>[] => {74 const families = familiesIn(listings);75 const members = new Set(families.flatMap((family) => family.members));76 const byId = new Map(listings.map((listing) => [listing.ask, listing]));7778 return listings.flatMap((listing): readonly Arranged<L>[] => {79 if (members.has(listing.ask)) {80 return [];81 }8283 const family = families.find(({ parent }) => parent === listing.ask);8485 return family === undefined86 ? [{ kind: "ask", listing }]87 : [88 {89 kind: "family",90 finale: family.finale,91 members: family.members.flatMap((member) => {92 const found = byId.get(member);9394 return found === undefined ? [] : [found];95 }),96 parent: listing,97 },98 ];99 });100};
modified:apps/web/src/features/front/filter.ts+80 added-34 removed
modified:apps/web/src/features/front/front-page.tsx+465 added-213 removed
1/**2 * The front page: the open asks of every project, the ones the viewer may3 * take first, each other one with the reason it is not theirs to take; a4 * filter by kind and by who an ask is held for; then every project with its5 * posture. Props in, markup out: the route reads the entries and projects6 * (`src/client/front.ts`) and the filter from the address, and hands them7 * here.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 *9 * The filter is a plain link (`/?kind=bug`), so a filtered list is an10 * address a newcomer can share.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 * (`/?kind=bug&take=open`), so a filtered list is an address to share.14 */15import { Brand } from "@repo/brand";16import { Reserve } from "@repo/protocol/domain/ask";17import type { Ask } from "@repo/protocol/domain/ask";18import type { ProjectEvent } from "@repo/protocol/domain/event";19import type {20 FrontPageEntry,21 ProjectListing,22} from "@repo/protocol/domain/front-page";18import type { KindName } from "@repo/protocol/ids";23import type { AskId, KindName, ProjectName } from "@repo/protocol/ids";24import type { DateTime } from "effect";25import { ChevronDown } from "lucide-react";26import { useMemo } from "react";27import type { ReactNode } from "react";2822import { AskFields, AskStanding } from "../project/asks.tsx";29import { postureLabel } from "../project/posture-label.ts";24import { ID, SECTION } from "../shared/classes.ts";25import { CommandLine } from "../shared/command.tsx";30import { askStates } from "../shared/ask-progress.ts";31import type { AskProgress } from "../shared/ask-progress.ts";32import { EmptyState } from "../shared/empty.tsx";27import { PageShell } from "../shared/layout.tsx";28import { askPath, projectPath } from "../shared/paths.ts";33import { FamilyStrip } from "../shared/family.tsx";34import { AppLink } from "../shared/link.tsx";35import { projectPath } from "../shared/paths.ts";36import { PostureBadge } from "../shared/posture.tsx";30import { When } from "../shared/time.tsx";31import { filterEntries, frontPath } from "./filter.ts";32import type { FrontFilter } from "./filter.ts";37import { AskRow, RowGroup, useRowSelection } from "../shared/row.tsx";38import { Workspace } from "../shared/shell/workspace.tsx";39import {40 ProjectsFacts,41 SelectedAskFacts,42 StartHere,43 plural,44} from "./facts.tsx";45import { arrange, finaleOf } from "./families.ts";46import type { Arranged } from "./families.ts";47import { countWith, filterEntries, frontPath } from "./filter.ts";48import type { FrontFilter, FrontFilterInput } from "./filter.ts";49import { EXPLAINER } from "./head.ts";5034const Entry = ({ entry }: { readonly entry: FrontPageEntry }) => {35 const { ask, posture, project, takeable } = entry;51/** The list's count, as the context bar says it: "10 open asks, 8 open to take". */52export const frontCount = (shown: readonly FrontPageEntry[]) =>53 `${plural(shown.length, "open ask", "open asks")}, ${54 shown.filter(({ takeable }) => takeable).length55 } open to take`;5637 return (38 <li39 className="border-rule flex flex-col gap-2 border-t py-4"40 data-ask={ask.ask}41 data-project={project}42 data-takeable={takeable}43 >44 <div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-1">45 <p className="flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm">46 <a47 className="decoration-rule font-semibold underline hover:decoration-current"48 href={projectPath(project)}49 >50 {project}51 </a>52 <span aria-hidden="true" className="text-muted-foreground">53 /54 </span>55 <a56 className={`${ID} decoration-rule underline hover:decoration-current`}57 href={askPath(project, ask.ask)}58 >59 {ask.ask}60 </a>61 </p>62 <AskStanding listing={ask} project={project} takeable={takeable} />63 </div>64 <p className="max-w-[70ch] text-base">{ask.want}</p>65 <div className="flex flex-wrap items-center gap-x-5 gap-y-2">66 <AskFields listing={ask} />67 <PostureBadge label={postureLabel(posture)} posture={posture} />68 </div>69 {takeable ? (70 <CommandLine71 command={`${Brand.cli} claim ${ask.ask} --project ${project}`}72 />73 ) : null}74 </li>75 );57export interface FrontPageProps {58 readonly entries: readonly FrontPageEntry[];59 readonly filter: FrontFilter;60 readonly now: DateTime.Utc;61 /** Each family's parent as the platform stores it: its children, all of them. */62 readonly parents: readonly Ask[];63 /** The events of each project that holds a family on the page. */64 readonly events: ReadonlyMap<ProjectName, readonly ProjectEvent[]>;65 /** The children that landed while the page was open, by project. */66 readonly stampsOf?: (project: ProjectName) => ReadonlySet<AskId>;67 /** Every project with its posture; none until the list arrives. */68 readonly projects: readonly ProjectListing[] | undefined;69 readonly platformUrl: string;70 readonly webUrl: string;71 /** The selected ask in full, once the browser has read it. */72 readonly selectedAsk?: Ask | undefined;73}7475/** The entries of each project, in the order its first entry comes. */76const byProject = (shown: readonly FrontPageEntry[]) => {77 const groups = new Map<ProjectName, FrontPageEntry[]>();7879 for (const entry of shown) {80 groups.set(entry.project, [...(groups.get(entry.project) ?? []), entry]);81 }8283 return [...groups];84};8578/** One filter option: a link, the current one marked as the page. */86/** One option of a filter: its words and its count, the current one marked. */87const FilterOption = ({88 count,89 current,81 href,90 label,91 search,92}: {93 readonly count: number;94 readonly current: boolean;85 readonly href: string;95 readonly label: string;96 readonly search: FrontFilterInput;97}) => (88 <li>89 <a98 <li className="shrink-0">99 <AppLink100 activeOptions={{ exact: true, includeSearch: true }}101 aria-current={current ? "page" : undefined}91 className="text-muted-foreground hover:text-foreground aria-[current=page]:border-rule-strong aria-[current=page]:text-foreground inline-flex min-h-8 items-center border-b-2 border-transparent text-sm no-underline aria-[current=page]:font-medium"92 href={href}102 className="text-ui text-muted-foreground hover:text-foreground aria-[current=page]:border-foreground aria-[current=page]:text-foreground flex h-10 items-center gap-1.5 border-b-2 border-transparent whitespace-nowrap no-underline transition-colors duration-[120ms] focus-visible:outline-offset-[-2px] aria-[current=page]:font-semibold"103 to={frontPath(search)}104 >105 {label}95 </a>106 <span className="text-label text-muted-foreground font-normal tabular-nums">107 {count}108 </span>109 </AppLink>110 </li>111);11299const FilterRow = ({113/** A filter's options, under its name for a screen reader. */114const Segment = ({115 children,116 label,117}: {118 readonly children: ReactNode;119 readonly label: string;120}) => (106 <div className="flex flex-col gap-x-4 sm:flex-row sm:items-baseline">107 <span className="text-muted-foreground w-20 shrink-0 text-xs font-medium">108 {label}109 </span>110 <ul className="flex flex-wrap gap-x-4">{children}</ul>111 </div>121 <ul aria-label={label} className="flex shrink-0 items-center gap-4">122 {children}123 </ul>124);125114const Filters = ({126/** The kinds on the page, and the one filtered to, each once, by name. */127const kindsOf = (entries: readonly FrontPageEntry[], filter: FrontFilter) =>128 [129 ...new Set([130 ...entries.map(({ ask }) => ask.kind),131 ...(filter.kind === undefined ? [] : [filter.kind]),132 ]),133 ].toSorted();134135/** The projects on the page, and the one filtered to, each once, by name. */136const projectsOf = (entries: readonly FrontPageEntry[], filter: FrontFilter) =>137 [138 ...new Set([139 ...entries.map(({ project }) => project),140 ...(filter.project === undefined ? [] : [filter.project]),141 ]),142 ].toSorted();143144const reserveWords = {145 newcomers: "Held for newcomers",146 people: "Held for people",147} as const satisfies Record<Reserve, string>;148149/**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).153 */154const ProjectMenu = ({155 entries,156 filter,116 kinds,157}: {158 readonly entries: readonly FrontPageEntry[];159 readonly filter: FrontFilter;119 readonly kinds: readonly KindName[];160}) => (121 <nav122 aria-label="Filter the asks"123 className="border-rule flex flex-col gap-2 border-y py-3"161 <details162 className="group relative shrink-0"163 key={filter.project ?? "every project"}164 >125 <FilterRow label="Kind">126 <FilterOption127 current={filter.kind === undefined}128 href={frontPath({ ...filter, kind: undefined })}129 label="All kinds"165 <summary className="text-ui hover:bg-surface flex h-8 cursor-pointer list-none items-center gap-1.5 px-2 whitespace-nowrap transition-colors duration-[120ms] [&::-webkit-details-marker]:hidden">166 <span className="text-muted-foreground">Project</span>167 <span className="font-semibold">{filter.project ?? "All"}</span>168 <ChevronDown169 aria-hidden="true"170 className="text-muted-foreground size-4 transition-transform duration-150 group-open:rotate-180"171 strokeWidth={1.75}172 />131 {kinds.map((kind) => (132 <FilterOption133 current={filter.kind === kind}134 href={frontPath({ ...filter, kind })}135 key={kind}136 label={kind}137 />138 ))}139 </FilterRow>140 <FilterRow label="Reserved">141 <FilterOption142 current={filter.reserved === undefined}143 href={frontPath({ ...filter, reserved: undefined })}144 label="All asks"145 />146 {Reserve.literals.map((reserved) => (147 <FilterOption148 current={filter.reserved === reserved}149 href={frontPath({ ...filter, reserved })}150 key={reserved}151 label={152 reserved === "newcomers"153 ? "For newcomers"154 : "For people, not agents"155 }156 />157 ))}158 </FilterRow>159 </nav>160);161162const Projects = ({163 now,164 projects,165}: {166 readonly now: DateTime.Utc;167 readonly projects: readonly ProjectListing[];168}) => (169 <section aria-labelledby="projects" className="flex flex-col gap-3">170 <h2 className={SECTION} id="projects">171 Projects172 </h2>173 <ul className="border-rule flex flex-col border-y">174 {projects.map((listing) => (175 <li176 className="border-rule flex flex-wrap items-center gap-x-4 gap-y-1.5 border-t py-3 first:border-t-0"177 key={listing.project}178 >179 <a180 className="decoration-rule font-semibold underline hover:decoration-current"181 href={projectPath(listing.project)}173 </summary>174 <ul175 aria-label="Projects"176 className="border-rule bg-popover absolute top-full right-0 z-30 mt-1 flex max-h-80 w-56 flex-col overflow-y-auto border py-1"177 >178 {[undefined, ...projectsOf(entries, filter)].map((project) => (179 <li key={project ?? "every project"}>180 <AppLink181 aria-current={filter.project === project ? "page" : undefined}182 className="text-ui hover:bg-surface aria-[current=page]:bg-surface flex h-9 items-center justify-between gap-3 px-3 no-underline aria-[current=page]:font-semibold"183 to={frontPath({ ...filter, project })}184 >183 {listing.project}184 </a>185 <PostureBadge186 label={postureLabel(listing.posture)}187 posture={listing.posture}188 />189 <span className="text-muted-foreground text-sm">190 {listing.openAsks} open {listing.openAsks === 1 ? "ask" : "asks"}191 {listing.landedAt === undefined ? null : (192 <>193 {" · last landed "}194 <When at={listing.landedAt} now={now} />195 </>196 )}197 </span>185 <span className="truncate">{project ?? "Every project"}</span>186 <span className="text-label text-muted-foreground font-normal tabular-nums">187 {countWith(entries, filter, { project })}188 </span>189 </AppLink>190 </li>191 ))}192 </ul>201 </section>193 </details>194);195204/** The kinds on the page, and the one filtered to, each once, by name. */205const kindsOf = (entries: readonly FrontPageEntry[], filter: FrontFilter) =>206 [207 ...new Set([208 ...entries.map(({ ask }) => ask.kind),209 ...(filter.kind === undefined ? [] : [filter.kind]),210 ]),211 ].toSorted();196/** The toolbar: kind; open to take or held for newcomers; project. */197const Toolbar = ({198 entries,199 filter,200}: {201 readonly entries: readonly FrontPageEntry[];202 readonly filter: FrontFilter;203}) => {204 const held = Reserve.literals.filter((reserved) =>205 entries.some(({ ask }) => ask.reserve === reserved)206 );207208 return (209 <>210 <nav211 aria-label="Filter the asks"212 className="max-shell:pr-8 max-shell:[mask-image:linear-gradient(to_right,#000_calc(100%-2rem),transparent)] flex min-w-0 flex-1 [scrollbar-width:none] items-center gap-6 overflow-x-auto overscroll-x-contain"213 >214 <Segment label="Kind">215 <FilterOption216 count={countWith(entries, filter, { kind: undefined })}217 current={filter.kind === undefined}218 label="All"219 search={{ ...filter, kind: undefined }}220 />221 {kindsOf(entries, filter).map((kind: KindName) => (222 <FilterOption223 count={countWith(entries, filter, { kind })}224 current={filter.kind === kind}225 key={kind}226 label={kind}227 search={{ ...filter, kind }}228 />229 ))}230 </Segment>231 <span aria-hidden="true" className="bg-rule h-4 w-px shrink-0" />232 <Segment label="Who may take it">233 <FilterOption234 count={countWith(entries, filter, {235 reserved: undefined,236 take: undefined,237 })}238 current={filter.take === undefined && filter.reserved === undefined}239 label="Any"240 search={{ ...filter, reserved: undefined, take: undefined }}241 />242 <FilterOption243 count={countWith(entries, filter, {244 reserved: undefined,245 take: "open",246 })}247 current={filter.take === "open"}248 label="Open to take"249 search={{ ...filter, reserved: undefined, take: "open" }}250 />251 {held.map((reserved) => (252 <FilterOption253 count={countWith(entries, filter, { reserved, take: undefined })}254 current={filter.reserved === reserved}255 key={reserved}256 label={reserveWords[reserved]}257 search={{ ...filter, reserved, take: undefined }}258 />259 ))}260 </Segment>261 </nav>262 <ProjectMenu entries={entries} filter={filter} />263 </>264 );265};266267/**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 */271const NoAsks = ({272 projects,273}: {220 readonly projects: readonly ProjectListing[];274 readonly projects: readonly ProjectListing[] | undefined;275}) =>222 projects.length === 0 ? (276 projects?.length === 0 ? (277 <EmptyState278 command={`${Brand.cli} init`}279 title="No open asks, and no project yet. Run init in a repo to bring it here."280 />
3 unmodified lines
284 title="No open asks on any project. A decider opens one from an ask file."285 />286 );287234const countOf = (count: number, one: string, many: string) =>235 `${count} ${count === 1 ? one : many}`;288/** A project's group of rows, as the page reads it. */289interface Group {290 readonly project: ProjectName;291 readonly entries: readonly FrontPageEntry[];292 readonly items: readonly Arranged[];293 readonly states: ReadonlyMap<AskId, AskProgress>;294}295296/** The row ids in the order the page shows them: what `j` and `k` walk. */297const rowIds = (groups: readonly Group[]) =>298 groups.flatMap(({ items }) =>299 items.map((item) =>300 item.kind === "ask" ? item.listing.ask : item.parent.ask301 )302 );303304/** A project's group: its header (name, posture once, counts), then its rows. */305const ProjectGroup = ({306 group,307 listing,308 onSelect,309 parents,310 selected,311 stamps,312}: {313 readonly group: Group;314 readonly listing: ProjectListing | undefined;315 readonly parents: readonly Ask[];316 readonly selected: string | undefined;317 readonly onSelect: (id: string) => void;318 readonly stamps: ReadonlySet<AskId>;319}) => {320 const { entries, items, project, states } = group;321 const takeable = new Map(entries.map((entry) => [entry.ask.ask, entry]));322323 const row = (listingOf: FrontPageEntry["ask"], strip?: ReactNode) => (324 <AskRow325 key={listingOf.ask}326 listing={listingOf}327 onSelect={onSelect}328 progress={states.get(listingOf.ask)}329 project={project}330 selected={selected === listingOf.ask}331 strip={strip}332 takeable={takeable.get(listingOf.ask)?.takeable}333 />334 );335336 return (337 <RowGroup338 counts={`${entries.length} open · ${339 entries.filter((entry) => entry.takeable).length340 } to take`}341 facts={342 listing === undefined ? undefined : (343 <PostureBadge344 label={postureLabel(listing.posture)}345 posture={listing.posture}346 />347 )348 }349 label={project}350 name={<AppLink to={projectPath(project)}>{project}</AppLink>}351 >352 {items.flatMap((item) => {353 if (item.kind === "ask") {354 return [row(item.listing)];355 }356357 const parent = parents.find(358 (ask) => ask.project === project && ask.id === item.parent.ask359 );360361 // A parent the platform did not give in full: its members stay rows.362 if (parent === undefined) {363 return [364 row(item.parent),365 ...item.members.map((member) => row(member)),366 ];367 }368369 return [370 row(371 item.parent,372 <FamilyStrip373 expanded={false}374 finale={item.finale}375 parent={parent}376 project={project}377 stamps={stamps}378 states={states}379 wants={380 new Map(item.members.map((member) => [member.ask, member.want]))381 }382 />383 ),384 ];385 })}386 </RowGroup>387 );388};389390/** The selected entry's facts, with its family when it is a member. */391const Selected = ({392 entry,393 full,394 parents,395 platformUrl,396 projects,397 states,398}: {399 readonly entry: FrontPageEntry;400 readonly full: Ask | undefined;401 readonly parents: readonly Ask[];402 readonly platformUrl: string;403 readonly projects: readonly ProjectListing[] | undefined;404 readonly states: ReadonlyMap<AskId, AskProgress>;405}) => {406 const { ask, project, takeable } = entry;407408 const parent = parents.find(409 (each) =>410 each.project === project &&411 (each.id === ask.ask || each.blockedBy.includes(ask.ask))412 );413414 const listed = projects?.find((each) => each.project === project);415416 return (417 <SelectedAskFacts418 family={419 parent === undefined420 ? undefined421 : {422 finale: finaleOf(parent.id),423 parent,424 states,425 }426 }427 full={full?.id === ask.ask && full.project === project ? full : undefined}428 listing={ask}429 platformUrl={platformUrl}430 posture={431 listed === undefined432 ? undefined433 : { label: postureLabel(listed.posture), posture: listed.posture }434 }435 progress={states.get(ask.ask)}436 project={project}437 takeable={takeable}438 />439 );440};441442export const FrontPageView = ({443 entries,444 events,445 filter,240 now,446 parents,447 platformUrl,448 projects,242}: {243 readonly entries: readonly FrontPageEntry[];244 readonly filter: FrontFilter;245 readonly now: DateTime.Utc;246 readonly projects: readonly ProjectListing[];247}) => {449 selectedAsk,450 stampsOf,451 webUrl,452}: FrontPageProps) => {453 const shown = filterEntries(entries, filter);249 const takeable = shown.filter((entry) => entry.takeable).length;454455 const states = useMemo(456 () =>457 new Map(458 [...events].map(459 ([project, read]) => [project, askStates(read)] as const460 )461 ),462 [events]463 );464465 const groups: readonly Group[] = byProject(shown).map(466 ([project, grouped]) => ({467 entries: grouped,468 items: arrange(grouped.map(({ ask }) => ask)),469 project,470 states: states.get(project) ?? new Map(),471 })472 );473474 const { select, selected } = useRowSelection(rowIds(groups), "ask");475 const picked = entries.find(({ ask }) => ask.ask === selected);476477 return (252 <PageShell title="Open asks">253 <div className="flex flex-col gap-4">254 <p className="text-muted-foreground max-w-[70ch]">255 Each ask is one change a project wants, with a check that fails on its256 main today. Claim one, make the check pass, and push: the gate lands257 it.478 <Workspace479 count={frontCount(shown)}480 crumbs={[{ label: "Asks" }]}481 facts={482 picked === undefined ? (483 <>484 <StartHere webUrl={webUrl} />485 <ProjectsFacts projects={projects} />486 </>487 ) : (488 <Selected489 entry={picked}490 full={selectedAsk}491 parents={parents}492 platformUrl={platformUrl}493 projects={projects}494 states={states.get(picked.project) ?? new Map()}495 />496 )497 }498 factsHeading={picked === undefined ? "Start here" : "Selected ask"}499 {...(selected === undefined ? {} : { factsKey: selected })}500 factsSummary={501 picked === undefined502 ? "Install the command line, list the asks, claim one"503 : picked.ask.want504 }505 status={506 <p className="text-want text-muted-foreground max-w-[70ch]">507 {EXPLAINER}508 </p>259 {entries.length === 0 ? null : (260 <Filters filter={filter} kinds={kindsOf(entries, filter)} />261 )}262 </div>263 <section aria-label="Asks" className="flex flex-col gap-3">264 {entries.length === 0 ? <NoAsks projects={projects} /> : null}265 {entries.length > 0 && shown.length === 0 ? (266 <div className="flex flex-col gap-2">267 <EmptyState title="No open asks match this filter." />268 <a269 className="decoration-rule self-start text-sm underline hover:decoration-current"270 href={frontPath({})}509 }510 title="Open asks"511 toolbar={512 entries.length === 0 ? undefined : (513 <Toolbar entries={entries} filter={filter} />514 )515 }516 variant="list"517 >518 {entries.length === 0 ? <NoAsks projects={projects} /> : null}519 {entries.length > 0 && shown.length === 0 ? (520 <EmptyState521 onward={522 <AppLink523 className="decoration-rule underline hover:decoration-current"524 to={frontPath({})}525 >526 Show every open ask273 </a>274 </div>275 ) : null}276 {shown.length === 0 ? null : (277 <>278 <p className="text-muted-foreground text-sm">279 {countOf(shown.length, "open ask", "open asks")}280 {", "}281 {takeable} open to take282 </p>283 <ol className="border-rule flex flex-col border-b">284 {shown.map((entry) => (285 <Entry286 entry={entry}287 key={`${entry.project}/${entry.ask.ask}`}288 />289 ))}290 </ol>291 </>292 )}293 </section>294 {projects.length === 0 ? null : (295 <Projects now={now} projects={projects} />527 </AppLink>528 }529 title="No open asks match this filter."530 />531 ) : null}532 {groups.length === 0 ? null : (533 <div className="flex flex-col gap-6">534 {groups.map((group) => (535 <ProjectGroup536 group={group}537 key={group.project}538 listing={projects?.find(539 ({ project }) => project === group.project540 )}541 onSelect={select}542 parents={parents}543 selected={selected}544 stamps={stampsOf?.(group.project) ?? new Set()}545 />546 ))}547 </div>548 )}297 </PageShell>549 </Workspace>550 );551};
added:apps/web/src/features/front/head.ts+48 added
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.6 */78/** What an ask is, and how one lands: the page's one sentence. */9export const EXPLAINER =10 "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.";1112/** A block that is no paragraph of prose: a heading, a quote, a table, a list, a fence, HTML, an image. */13const NOT_PROSE = /^(?:#|>|\||[-*+]\s|\d+[.)]\s|```|~~~|<|!\[|\[!\[)/u;1415/** A paragraph's inline Markdown as plain words: links and code as their text, emphasis dropped. */16const plainWords = (text: string) =>17 text18 .replaceAll(/!\[[^\]]*\]\([^)]*\)/gu, "")19 .replaceAll(/\[(?<label>[^\]]*)\]\([^)]*\)/gu, "$<label>")20 .replaceAll(/`(?<code>[^`]*)`/gu, "$<code>")21 .replaceAll(22 /(?<mark>\*\*|__|\*|_)(?<words>\S(?:.*?\S)?)\k<mark>/gu,23 "$<words>"24 )25 .replaceAll(/\s+/gu, " ")26 .trim();2728/**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 */33export const ledeOf = (text: string): string | undefined => {34 const paragraph = text35 .split(/\n\s*\n/u)36 .map((block) => block.trim())37 .find((block) => block !== "" && !NOT_PROSE.test(block));3839 if (paragraph === undefined) {40 return undefined;41 }4243 const words = plainWords(paragraph);44 const end = /[.!?](?=\s|$)/u.exec(words);45 const sentence = end === null ? words : words.slice(0, end.index + 1);4647 return sentence === "" ? undefined : sentence;48};
added:apps/web/src/features/front/markdown.ts+26 added
added:apps/web/src/features/front/stamps.ts+87 added
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 */13import type { ProjectEvent } from "@repo/protocol/domain/event";14import type { AskId } from "@repo/protocol/ids";15import { useState } from "react";1617import { askStates, lastSeq, stampsFrom } from "../shared/ask-progress.ts";18import type { AskProgress } from "../shared/ask-progress.ts";1920/** What a page remembers between reads of one project's events. */21export interface StampMemory {22 /** The highest event number of the first read. */23 readonly mountSeq: number;24 /** Where each ask stood in the read before. */25 readonly previous: ReadonlyMap<AskId, AskProgress>;26 /** Every ask stamped so far. */27 readonly stamped: ReadonlySet<AskId>;28}2930/** The page's memory after one more read of `events`; the first read stamps nothing. */31export const stampStep = (32 memory: StampMemory | undefined,33 events: readonly ProjectEvent[]34): StampMemory => {35 const states = askStates(events);3637 if (memory === undefined) {38 return { mountSeq: lastSeq(events), previous: states, stamped: new Set() };39 }4041 const fresh = stampsFrom(memory.previous, states, memory.mountSeq);4243 return {44 mountSeq: memory.mountSeq,45 previous: states,46 stamped:47 fresh.size === 048 ? memory.stamped49 : new Set([...memory.stamped, ...fresh]),50 };51};5253/** Each project's memory after one more read of each project's events. */54const stepAll = (55 memory: ReadonlyMap<string, StampMemory>,56 reads: ReadonlyMap<string, readonly ProjectEvent[]>57): ReadonlyMap<string, StampMemory> =>58 new Map(59 [...reads].map(([project, events]) => [60 project,61 stampStep(memory.get(project), events),62 ])63 );6465/**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 */70export const useStamps = (71 reads: ReadonlyMap<string, readonly ProjectEvent[]>72): ((project: string) => ReadonlySet<AskId>) => {73 const [seen, setSeen] = useState(reads);74 const [memory, setMemory] = useState(() => stepAll(new Map(), reads));7576 // 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.78 let current = memory;7980 if (reads !== seen) {81 current = stepAll(memory, reads);82 setSeen(reads);83 setMemory(current);84 }8586 return (project) => current.get(project)?.stamped ?? new Set<AskId>();87};
modified:apps/web/src/features/project/asks.tsx+89 added-138 removed
1/**2 * The pieces an ask's row repeats wherever asks are listed (a project's3 * page, the front page): where it stands, said with a mark and a word, and4 * its kind and territory as fields. An ask waiting on others is blocked,5 * which is waiting, never refusing: the asks it waits on are links, so a6 * reader can go and land them.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 */8import type { AskListing, Reserve } from "@repo/protocol/domain/ask";7import type { Ask, AskListing } from "@repo/protocol/domain/ask";8import type { AskId, ProjectName } from "@repo/protocol/ids";10import {11 Circle,12 Hand,13 Hourglass,14 LockKeyhole,15 Sprout,16 UserRound,17} from "lucide-react";18import type { LucideIcon } from "lucide-react";19import { Fragment } from "react";9import type { ReactNode } from "react";1022import { ID } from "../shared/classes.ts";23import { askPath } from "../shared/paths.ts";11import { arrange } from "../front/families.ts";12import type { AskProgress } from "../shared/ask-progress.ts";13import { FamilyStrip } from "../shared/family.tsx";14import { AskRow, RowList } from "../shared/row.tsx";1525/** Who a reserved ask is held for, in the words of the ask's page. */26const heldFor = {27 newcomers: { icon: Sprout, words: "Held for newcomers" },28 people: { icon: Hand, words: "Held for people, not agents" },29} as const satisfies Record<30 Reserve,31 { readonly icon: LucideIcon; readonly words: string }32>;16/** Whether an ask is open to take as its listing says: nobody holds it, it waits on nothing, and it is held for nobody. */17export const openToTake = (listing: AskListing) =>18 !listing.claimed &&19 listing.blockedBy.length === 0 &&20 listing.reserve === undefined;2134const Line = ({35 children,36 icon: Icon,37 tone,38}: {39 readonly children: ReactNode;40 readonly icon: LucideIcon;41 /** The role colour of the mark and word, as a text class. */42 readonly tone: string;43}) => (44 <li className={`flex items-start gap-1.5 ${tone}`}>45 <Icon aria-hidden="true" className="mt-[0.2rem] size-3.5 shrink-0" />46 <span className="min-w-0">{children}</span>47 </li>48);22/**23 * The asks a project counts as open: every one listed, but a family's24 * delete child while it waits on its siblings (it opens when they land).25 */26export const openAsks = (listings: readonly AskListing[]) => {27 const finales = new Set(28 arrange(listings).flatMap((item) =>29 item.kind === "family" ? [item.finale] : []30 )31 );3250/** What goes before the ask at `index` of `count` in "a, b and c". */51const separator = (index: number, count: number) => {52 if (index === 0) {53 return "";54 }5556 return index === count - 1 ? " and " : ", ";33 return listings.filter(34 ({ ask, blockedBy }) => !(finales.has(ask) && blockedBy.length > 0)35 );36};3759/** The asks `blockedBy` names, each a link, as "a, b and c". */60const Waits = ({38/** The project's asks, families as fans with their children listed. */39export const AskList = ({40 asks,41 onSelect,42 parents,43 project,44 selected,45 stamps,46 states,47}: {64 readonly asks: readonly AskId[];48 readonly asks: readonly AskListing[];49 readonly project: ProjectName;66}) =>67 asks.map((ask, index) => (68 <Fragment key={ask}>69 {separator(index, asks.length)}70 <a71 className={`${ID} decoration-rule underline hover:decoration-current`}72 href={askPath(project, ask)}73 >74 {ask}75 </a>76 </Fragment>77 ));7879/**80 * Where an ask stands for its reader. With `takeable` (the front page, which81 * knows the viewer), an ask they may take reads "Open to take" and one they82 * may not gives each reason it is not theirs: claimed, blocked, held for83 * someone, or, when none of those applies, their vouch or record. Without84 * it (a project's page), an ask reads open when nothing holds it.85 */86export const AskStanding = ({87 listing,88 project,89 takeable,90}: {91 readonly listing: AskListing;92 readonly project: ProjectName;93 readonly takeable?: boolean;50 /** Each family's parent in full, which counts its children. */51 readonly parents: readonly Ask[];52 readonly states: ReadonlyMap<AskId, AskProgress>;53 readonly stamps: ReadonlySet<AskId>;54 readonly selected: string | undefined;55 readonly onSelect: ((id: string) => void) | undefined;56}) => {95 const held =96 listing.reserve === undefined ? undefined : heldFor[listing.reserve];57 const row = (listing: AskListing, strip?: ReactNode) => (58 <AskRow59 key={listing.ask}60 listing={listing}61 onSelect={onSelect}62 progress={states.get(listing.ask)}63 project={project}64 selected={selected === listing.ask}65 strip={strip}66 />67 );6898 const reasons = [99 listing.claimed ? (100 <Line icon={UserRound} key="claimed" tone="text-muted-foreground">101 Claimed102 </Line>103 ) : null,104 listing.blockedBy.length === 0 ? null : (105 <Line icon={Hourglass} key="blocked" tone="text-waiting">106 <strong className="font-semibold">Blocked</strong> until{" "}107 <span className="text-foreground">108 <Waits asks={listing.blockedBy} project={project} />109 </span>{" "}110 {listing.blockedBy.length === 1 ? "lands" : "land"}111 </Line>112 ),113 ].filter((line) => line !== null);69 return (70 <RowList label="Open asks">71 {arrange(asks).flatMap((item) => {72 if (item.kind === "ask") {73 return [row(item.listing)];74 }75115 const open = takeable ?? (reasons.length === 0 && held === undefined);76 const parent = parents.find(({ id }) => id === item.parent.ask);77117 const holder =118 held === undefined ? null : (119 <Line icon={held.icon} key="held" tone="text-muted-foreground">120 {held.words}121 </Line>122 );78 // A parent the platform did not give in full: its members stay rows.79 if (parent === undefined) {80 return [81 row(item.parent),82 ...item.members.map((member) => row(member)),83 ];84 }85124 const lines = open125 ? [126 <Line icon={Circle} key="open" tone="text-foreground font-medium">127 Open to take128 </Line>,129 holder,130 ]131 : [...reasons, holder];132133 const shown = lines.filter((line) => line !== null);134135 return (136 <ul className="flex flex-col gap-0.5 text-sm" data-standing="">137 {shown.length > 0 ? (138 shown139 ) : (140 <Line icon={LockKeyhole} tone="text-muted-foreground">141 Not open to you yet: it needs a vouch or a record in its area142 </Line>143 )}144 </ul>86 return [87 row(88 item.parent,89 <FamilyStrip90 expanded91 finale={item.finale}92 parent={parent}93 project={project}94 stamps={stamps}95 states={states}96 wants={97 new Map(item.members.map((member) => [member.ask, member.want]))98 }99 />100 ),101 ];102 })}103 </RowList>104 );105};106148/** An ask's kind and territory, as labelled fields. */149export const AskFields = ({ listing }: { readonly listing: AskListing }) => (150 <dl className="flex flex-wrap gap-x-5 gap-y-1 text-sm">151 <div className="flex items-baseline gap-1.5">152 <dt className="text-muted-foreground text-xs font-medium">Kind</dt>153 <dd className={ID}>{listing.kind}</dd>154 </div>155 <div className="flex min-w-0 items-baseline gap-1.5">156 <dt className="text-muted-foreground text-xs font-medium">Territory</dt>157 <dd className={`${ID} [overflow-wrap:anywhere]`}>{listing.territory}</dd>158 </div>159 </dl>160);107/** Row ids in the order `AskList` draws them: what `j` and `k` walk. */108export const askListIds = (asks: readonly AskListing[]) =>109 arrange(asks).map((item) =>110 item.kind === "ask" ? item.listing.ask : item.parent.ask111 );
modified:apps/web/src/features/project/landings.tsx+46 added-43 removed
1/**2 * A project's recent landings, newest first: each one's subject line, its3 * commit, when it landed, its author, and its trailers exactly as the commit4 * carries them (`CreditTrailers`: credit, then `Held-back:`, then the agents5 * used, apart, since they are never credit).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 */6import type { LandingView } from "@repo/protocol/domain/landing";7import { Option } from "effect";8import type { DateTime } from "effect";911import { ID } from "../shared/classes.ts";12import { CreditTrailers } from "../shared/credits.tsx";13import { HandleLink } from "../shared/handle.tsx";10import { CompactCredit } from "../shared/credits.tsx";11import { AppLink } from "../shared/link.tsx";12import { askPath } from "../shared/paths.ts";13import { When } from "../shared/time.tsx";14import { askOf } from "../why/rows.ts";1516/** How many landings the project's home shows. */17export const RECENT_SHOWN = 3;1819/**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 a
6 unmodified lines
29 onSome: ({ ask, kind }) =>30 kind === "opened" ? `Open ask ${ask}` : `Answer ${ask}`,31 });3232const short = (sha: string) => sha.slice(0, 7);33/**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 */39export const recentShown = (40 landings: readonly LandingView[]41): readonly LandingView[] => {42 const answers = landings.filter((landing) => landing.ask !== undefined);4344 return (answers.length >= RECENT_SHOWN ? answers : landings).slice(45 0,46 RECENT_SHOWN47 );48};4950const Landing = ({51 landing,52 now,53}: {54 readonly landing: LandingView;55 readonly now: DateTime.Utc;56}) => {57 const linked = Option.getOrUndefined(askOf(landing));58 const subject = landingSubject(landing);5960 return (61 <li45 className="border-rule flex flex-col gap-3 border-t py-4"62 className="text-ui flex min-w-0 flex-col gap-0.5 py-1.5"63 data-landing={landing.sha}64 >48 <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">49 <h3 className="text-base font-semibold [overflow-wrap:anywhere]">50 {linked === undefined ? (51 landingSubject(landing)52 ) : (53 <a54 className="decoration-rule underline hover:decoration-current"55 href={askPath(landing.project, linked.ask)}56 >57 {landingSubject(landing)}58 </a>59 )}60 </h3>61 <p className="text-muted-foreground flex items-baseline gap-2 text-sm">62 <code className={ID} title={landing.sha}>63 {short(landing.sha)}64 </code>65 <span aria-hidden="true">·</span>65 <span className="flex min-w-0 items-baseline justify-between gap-3">66 {linked === undefined ? (67 <span className="truncate font-medium">{subject}</span>68 ) : (69 <AppLink70 className="decoration-rule truncate font-medium no-underline hover:underline"71 title={subject}72 to={askPath(landing.project, linked.ask)}73 >74 {subject}75 </AppLink>76 )}77 <span className="text-label text-muted-foreground shrink-0 tabular-nums">78 <When at={landing.landedAt} now={now} />67 </p>68 </div>69 <p className="text-sm">70 <span className="text-muted-foreground text-xs font-medium">71 Author72 </span>{" "}73 <HandleLink handle={landing.author} />74 </p>75 <CreditTrailers76 assisted={landing.assisted}77 credits={landing.credits}78 {...(landing.heldBackTrailer === undefined79 ? {}80 : { heldBack: landing.heldBackTrailer })}81 />79 </span>80 </span>81 <span className="text-muted-foreground min-w-0 truncate">82 <CompactCredit credits={landing.credits} />83 </span>84 </li>85 );86};8788/** The landings given, each as one line of credit. */89export const LandingList = ({90 landings,91 now,92}: {93 readonly landings: readonly LandingView[];94 readonly now: DateTime.Utc;95}) => (93 <ol className="border-rule flex flex-col border-b">96 <ol className="flex flex-col">97 {landings.map((landing) => (98 <Landing key={landing.sha} landing={landing} now={now} />99 ))}100 </ol>
1 unmodified line
modified:apps/web/src/features/project/project-page.tsx+544 added-217 removed
1/**2 * A project's page: its posture, how to take part, its open asks, and its3 * recent landings with their credit trailers. Props in, markup out: the4 * route reads the listing, the asks and the landings (`src/client/project.ts`, `src/client/events.ts`),5 * the code (its loader on the server, then `src/client/code.ts`) and the6 * platform URL (the root loader), and hands them here. "Propose an7 * ask" shows for signed-in members only, once the browser knows who that is8 * (`features/propose/propose-link.tsx`).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 */11import { Brand } from "@repo/brand";11import type { AskListing } from "@repo/protocol/domain/ask";12import type { Ask, AskListing } from "@repo/protocol/domain/ask";13import type { FileView, TreeListing } from "@repo/protocol/domain/code";14import type { Glob } from "@repo/protocol/domain/common";15import type { ProjectListing } from "@repo/protocol/domain/front-page";16import type { LandingView } from "@repo/protocol/domain/landing";17import { LedgerEntry } from "@repo/protocol/domain/visibility";18import type { Ledger } from "@repo/protocol/domain/visibility";15import type { ProjectName } from "@repo/protocol/ids";19import type { AreaName, AskId, Handle, ProjectName } from "@repo/protocol/ids";20import type { Posture } from "@repo/protocol/posture";21import { useRouter } from "@tanstack/react-router";22import { Option, Predicate } from "effect";23import type { DateTime } from "effect";24import type { ReactNode } from "react";2518import { EntriesTable } from "../code/tree-view.tsx";19import { SignedInProposeLink } from "../propose/propose-link.tsx";20import { ID, SECTION } from "../shared/classes.ts";26import {27 ForAgents,28 Onward,29 SelectedAskFacts,30 Step,31 plural,32} from "../front/facts.tsx";33import { finaleOf } from "../front/families.ts";34import { ledeOf } from "../front/head.ts";35import { ProposeLink } from "../propose/propose-link.tsx";36import type { AskProgress } from "../shared/ask-progress.ts";37import { CommandLine } from "../shared/command.tsx";38import { EmptyState } from "../shared/empty.tsx";23import { PageShell } from "../shared/layout.tsx";24import { askPath } from "../shared/paths.ts";25import { ReadingRows } from "../shared/pending.tsx";39import {40 FactBlock,41 GateFacts,42 HeldBackFacts,43 PostureFacts,44} from "../shared/facts.tsx";45import { ReadingRows, UnreachableNotice } from "../shared/pending.tsx";46import { PostureBadge } from "../shared/posture.tsx";47import { MetaCode, useRowSelection } from "../shared/row.tsx";48import { Workspace } from "../shared/shell/workspace.tsx";49import { FactsSkeleton } from "../shared/skeleton.tsx";50import { When } from "../shared/time.tsx";28import { AskFields, AskStanding } from "./asks.tsx";29import { LandingList } from "./landings.tsx";51import { AskList, askListIds, openAsks, openToTake } from "./asks.tsx";52import { LandingList, recentShown } from "./landings.tsx";53import { postureLabel } from "./posture-label.ts";54import { ProjectNav } from "./project-nav.tsx";55import { ReadmeSection } from "./readme-section.tsx";5634const AskRow = ({35 listing,36 project,37}: {38 readonly listing: AskListing;39 readonly project: ProjectName;40}) => (41 <li42 className="border-rule flex flex-col gap-2 border-t py-4"43 data-ask={listing.ask}44 >45 <div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-1">46 <a47 className={`${ID} decoration-rule font-medium underline hover:decoration-current`}48 href={askPath(project, listing.ask)}49 >50 {listing.ask}51 </a>52 <AskStanding listing={listing} project={project} />53 </div>54 <p className="max-w-[70ch] text-base">{listing.want}</p>55 <AskFields listing={listing} />56 </li>57);57/** A project's code as its home reads it: the root folder at main, and its README. */58export interface ProjectCode {59 readonly readme?: FileView | undefined;60 readonly root: TreeListing;61}6263/** Who decides for which paths, as the project's policy says. */64export interface Deciders {65 readonly handles: readonly Handle[];66 readonly paths: Glob;67}6869/** One area a layer holds checks in, and how many. */70export interface HeldBackArea {71 readonly area: AreaName;72 readonly detail: string;73}7475/** An entry that says nothing about an area's count. */76const noCount = (): readonly (readonly [AreaName, number])[] => [];7778/**60 * The landings section with none to show. Before the project's main first61 * lands, the push that lands it is its initializer's (`init` would refuse62 * now: the project exists). After it, the replay may still hold no landing63 * event, since adopting main is not one: say so, never "nothing landed".79 * What a project holds back, from its ledger: each sealed area and how many80 * checks it holds, as the latest count or commitment says.81 */65const NoLandings = ({66 listing,67 platformUrl,68}: {69 readonly listing: ProjectListing;70 readonly platformUrl: string;71}) =>72 listing.landedAt === undefined ? (73 <EmptyState74 command={`git push ${platformUrl}/${listing.project}.git HEAD:main`}75 title="Nothing has landed yet. The first push to main, by whoever ran init, lands it."76 />77 ) : (78 <EmptyState title="No landings among the project's recent events." />82export const heldBackOf = (ledger: Ledger): readonly HeldBackArea[] => {83 const checks = new Map(84 ledger.entries85 .toSorted((a, b) => a.seq - b.seq)86 .flatMap((entry) =>87 LedgerEntry.match(entry, {88 Admitted: noCount,89 CommitmentPublished: ({ area, checks: count }) => [90 [area, count] as const,91 ],92 CountChanged: ({ area, count }) => [[area, count] as const],93 LayerDeclared: noCount,94 PostureChanged: noCount,95 Released: noCount,96 ValueSet: noCount,97 })98 )99 );10081/** The steps that take a newcomer from a clone (the box above) to a checked answer. */82const steps = (project: ProjectName) =>83 [84 {85 command: `${Brand.cli} asks --project ${project}`,86 label: "See what it asks for",87 },88 { command: `${Brand.cli} claim <ask>`, label: "Claim one, in the clone" },89 {90 command: `${Brand.cli} check`,91 label: "Check your answer before you push",92 },93 ] as const;101 return [...checks]102 .toSorted(([a], [b]) => a.localeCompare(b))103 .map(([area, count]) => ({104 area,105 detail: `${count} sealed ${count === 1 ? "check" : "checks"}`,106 }));107};10895/** A project's code as its page shows it: the root folder at main, and its README. */96export interface ProjectCode {97 readonly readme?: FileView | undefined;98 readonly root: TreeListing;99}109/**110 * The project as its home knows it: its name, its open asks, when it last111 * landed, and its posture once its own ledger has said it. Until then the112 * page says no posture, never one it was not told.113 */114export type HomeListing = Omit<ProjectListing, "posture"> & {115 readonly posture?: Posture | undefined;116};117101/** The clone line, whole and copyable, and where to go once cloned. */102const CloneBox = ({103 platformUrl,118/** The project for its home, from what was read: the posture only from its own ledger. */119export const homeListing = ({120 asks,121 ledger,122 project,123}: {124 readonly asks: readonly AskListing[] | undefined;125 readonly ledger: Ledger | undefined;126 readonly project: ProjectName;127}): HomeListing => ({128 openAsks: asks?.length ?? 0,129 posture: ledger?.posture,130 project,131});132133/** A posture known, in the platform's words. */134interface KnownPosture {135 readonly label: string;136 readonly posture: Posture;137}138139export interface ProjectViewProps {140 /** The open asks; none while they are read, and none when they could not be. */141 readonly asks: readonly AskListing[] | undefined;142 /** Whether the asks could not be read: the platform did not answer. */143 readonly unreachable?: boolean;144 /** The project's landings, newest first. */145 readonly landings: readonly LandingView[];146 /** The project: its posture (once its ledger is read), when it last landed, its open asks. */147 readonly listing: HomeListing;148 /** When it last landed, as its events say, over what the listing says. */149 readonly lastLanded?: DateTime.Utc | undefined;150 /** Its posture in the platform's words, from its own ledger. */151 readonly postureLabel?: string | undefined;152 /** What it holds back, from its ledger; none while it is read. */153 readonly heldBack?: readonly HeldBackArea[] | undefined;154 /** Who decides for which paths; none while the policy is read or when it has none. */155 readonly deciders?: readonly Deciders[] | undefined;156 readonly now: DateTime.Utc;157 readonly platformUrl: string;158 /** The root folder at main and its README, once read. */159 readonly code?: ProjectCode | undefined;160 /** Each family's parent in full, which counts its children. */161 readonly parents?: readonly Ask[];162 /** Where each ask stands, from the project's events. */163 readonly states?: ReadonlyMap<AskId, AskProgress>;164 /** The children that landed while the page was open. */165 readonly stamps?: ReadonlySet<AskId>;166 /** The selected ask in full, once the browser has read it. */167 readonly selectedAsk?: Ask | undefined;168 /** Whether someone is signed in, who may propose an ask. */169 readonly signedIn?: boolean;170}171172/** Who decides, one line per set of paths, at most three, then the policy. */173const WhoDecides = ({174 deciders,175 project,176}: {177 readonly deciders: readonly Deciders[] | undefined;178 readonly project: ProjectName;108}) => (109 <section110 aria-label="Clone"111 className="border-rule bg-surface flex flex-col gap-2 border px-4 py-3"112 data-clone=""113 >114 <h2 className="text-muted-foreground text-xs font-medium">115 Clone it with plain git116 </h2>117 <CommandLine command={`git clone ${platformUrl}/${project}.git`} />118 </section>119);179}) => {180 const shown = deciders?.slice(0, 3) ?? [];181 const more = (deciders?.length ?? 0) - shown.length;182121/** The root folder's entries at main, and the README below them. */122const CodeSection = ({123 code,183 return (184 <FactBlock label="Who decides">185 {deciders === undefined || deciders.length === 0 ? (186 <p className="text-ui text-muted-foreground">187 Its policy names who decides for which paths.188 </p>189 ) : (190 <ul className="flex flex-col gap-1">191 {shown.map(({ handles, paths }) => (192 <li className="text-ui min-w-0" key={paths}>193 <MetaCode>{paths}</MetaCode>194 <span className="text-muted-foreground"> · </span>195 {handles.join(", ")}196 </li>197 ))}198 {more > 0 ? (199 <li className="text-ui text-muted-foreground">200 and {plural(more, "set of paths", "sets of paths")} more201 </li>202 ) : null}203 </ul>204 )}205 <Onward to={`/${project}/people`}>Policy</Onward>206 </FactBlock>207 );208};209210/** The four commands that take part, in the order a newcomer runs them. */211const TakePart = ({212 platformUrl,213 project,214}: {126 readonly code: ProjectCode;215 readonly platformUrl: string;216 readonly project: ProjectName;217}) => (129 <section aria-labelledby="code" className="flex min-w-0 flex-col gap-3">130 <h2 className={SECTION} id="code">131 <a132 className="decoration-rule underline hover:decoration-current"133 href={`/${project}/tree/main`}134 >135 Code136 </a>137 </h2>138 <EntriesTable entries={code.root.entries} project={project} rev="main" />139 {code.readme === undefined ? null : (140 <ReadmeSection file={code.readme} project={project} />141 )}142 </section>218 <FactBlock label="Take part">219 <Step220 command={`git clone ${platformUrl}/${project}.git`}221 label="Clone it with plain git"222 />223 <Step224 command={`${Brand.cli} asks --project ${project}`}225 label="See what it asks for"226 />227 <Step228 command={`${Brand.cli} claim <ask>`}229 label="Claim one, in the clone"230 />231 <Step232 command={`${Brand.cli} check`}233 label="Check your answer before you push"234 />235 </FactBlock>236);237145export const ProjectView = ({146 asks,147 code,238/**239 * The last landings. Before the project's main first lands, the push that240 * lands it is its initializer's; after it, the replay may still hold no241 * landing event, since adopting main is not one: say so, never "nothing242 * landed".243 */244const RecentLandings = ({245 landedAt,246 landings,247 listing,248 now,249 platformUrl,250}: {153 readonly asks: readonly AskListing[];154 /** The root folder at main and its README, once read; nothing is shown before. */155 readonly code?: ProjectCode | undefined;251 readonly landedAt: DateTime.Utc | undefined;252 readonly landings: readonly LandingView[];157 readonly listing: ProjectListing;253 readonly listing: HomeListing;254 readonly now: DateTime.Utc;255 readonly platformUrl: string;256}) => {257 let shown: ReactNode;258259 if (landings.length > 0) {260 shown = <LandingList landings={recentShown(landings)} now={now} />;261 } else if (landedAt === undefined) {262 shown = (263 <>264 <p className="text-ui">265 Nothing has landed yet. The first push to main, by whoever ran init,266 lands it.267 </p>268 <CommandLine269 command={`git push ${platformUrl}/${listing.project}.git HEAD:main`}270 />271 </>272 );273 } else {274 shown = (275 <p className="text-ui text-muted-foreground">276 No landings among the recent events of {listing.project}.277 </p>278 );279 }280281 return <FactBlock label="Recent landings">{shown}</FactBlock>;282};283284/** How a change lands here: the facts with nothing selected. */285const HowItLands = ({286 deciders,287 heldBack,288 landedAt,289 landings,290 listing,291 now,292 platformUrl,293 posture,294}: Pick<295 ProjectViewProps,296 "deciders" | "heldBack" | "landings" | "listing" | "now" | "platformUrl"297> & {298 readonly posture: KnownPosture | undefined;299 readonly landedAt: DateTime.Utc | undefined;300}) => (301 <>302 {posture === undefined ? (303 <FactsSkeleton labels={["Posture"]} />304 ) : (305 <PostureFacts306 label={posture.label}307 posture={posture.posture}308 project={listing.project}309 />310 )}311 <GateFacts />312 <WhoDecides deciders={deciders} project={listing.project} />313 {heldBack === undefined ? null : <HeldBackFacts areas={heldBack} />}314 <TakePart platformUrl={platformUrl} project={listing.project} />315 <RecentLandings316 landedAt={landedAt}317 landings={landings}318 listing={listing}319 now={now}320 platformUrl={platformUrl}321 />322 <ForAgents href={`/${listing.project}/llms.txt`} />323 </>324);325326/** The project line: its posture, its open asks, when it last landed; then its README's first sentence. */327const ProjectLine = ({328 count,329 landedAt,330 lede,331 now,332 posture,333}: {334 readonly count: number;335 readonly posture: KnownPosture | undefined;336 readonly landedAt: DateTime.Utc | undefined;337 readonly lede: string | undefined;338 readonly now: DateTime.Utc;339}) => (340 <div className="flex flex-col gap-3">341 <p className="text-ui text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1">342 {posture === undefined ? null : (343 <>344 <PostureBadge label={posture.label} posture={posture.posture} />345 <span aria-hidden="true">·</span>346 </>347 )}348 <span className="tabular-nums">349 {plural(count, "open ask", "open asks")}350 </span>351 <span aria-hidden="true">·</span>352 <span>353 {landedAt === undefined ? (354 "nothing landed yet"355 ) : (356 <>357 last landed <When at={landedAt} now={now} />358 </>359 )}360 </span>361 </p>362 {lede === undefined ? null : (363 <p className="text-want max-w-[70ch]">{lede}</p>364 )}365 </div>366);367368/** The asks' place on the page, as far as they have been read. */369const AsksSection = ({370 asks,371 onSelect,372 parents,373 project,374 selected,375 signedIn,376 stamps,377 states,378 unreachable,379}: {380 readonly asks: readonly AskListing[] | undefined;381 readonly unreachable: boolean;382 readonly project: ProjectName;383 readonly parents: readonly Ask[];384 readonly states: ReadonlyMap<AskId, AskProgress>;385 readonly stamps: ReadonlySet<AskId>;386 readonly selected: string | undefined;387 readonly onSelect: ((id: string) => void) | undefined;388 readonly signedIn: boolean;389}) => {390 let list: ReactNode;391392 if (asks === undefined) {393 list = unreachable ? <UnreachableNotice /> : <ReadingRows />;394 } else if (asks.length === 0) {395 list = (396 <EmptyState397 command={`${Brand.cli} ask open <ask> --files <files>`}398 title="No open asks. A decider opens one from an ask file."399 />400 );401 } else {402 list = (403 <AskList404 asks={asks}405 onSelect={onSelect}406 parents={parents}407 project={project}408 selected={selected}409 stamps={stamps}410 states={states}411 />412 );413 }414415 return (416 <section417 aria-labelledby="open-asks"418 className="flex min-w-0 flex-col gap-2"419 >420 <div className="flex min-h-8 flex-wrap items-center justify-between gap-x-6 gap-y-1">421 <h2 className="text-title" id="open-asks">422 Open asks423 </h2>424 {signedIn ? <ProposeLink project={project} /> : null}425 </div>426 {list}427 </section>428 );429};430431/** Whichever facts the inspector shows: how a change lands here, or the selected ask's. */432const PageFacts = ({433 landedAt,434 picked,435 posture,436 props,437 states,438}: {439 readonly props: ProjectViewProps;440 readonly picked: AskListing | undefined;441 readonly posture: KnownPosture | undefined;442 readonly landedAt: DateTime.Utc | undefined;443 readonly states: ReadonlyMap<AskId, AskProgress>;444}) => {445 const { listing, parents = [], platformUrl, selectedAsk } = props;446447 if (picked === undefined) {448 return (449 <HowItLands450 deciders={props.deciders}451 heldBack={props.heldBack}452 landedAt={landedAt}453 landings={props.landings}454 listing={listing}455 now={props.now}456 platformUrl={platformUrl}457 posture={posture}458 />459 );460 }461462 const family = parents.find(463 ({ blockedBy, id }) => id === picked.ask || blockedBy.includes(picked.ask)464 );465466 return (467 <SelectedAskFacts468 family={469 family === undefined470 ? undefined471 : { finale: finaleOf(family.id), parent: family, states }472 }473 full={selectedAsk?.id === picked.ask ? selectedAsk : undefined}474 listing={picked}475 platformUrl={platformUrl}476 posture={posture}477 progress={states.get(picked.ask)}478 project={listing.project}479 takeable={openToTake(picked)}480 />481 );482};483484/** A list's count at the context bar's end: "7 open asks, 6 open to take". */485const countOf = (open: readonly AskListing[]) =>486 `${plural(open.length, "open ask", "open asks")}, ${487 open.filter(openToTake).length488 } open to take`;489490/** The page, with the selection the list keeps (or none, outside a router). */491const ProjectPanes = ({492 props,493 select,494 selected,495}: {496 readonly props: ProjectViewProps;497 readonly selected: string | undefined;498 readonly select: ((id: string) => void) | undefined;499}) => {500 const { asks, code, listing } = props;501 const states = props.states ?? new Map<AskId, AskProgress>();502 const { project } = listing;503504 const posture = Option.getOrUndefined(505 Option.map(506 Option.fromUndefinedOr(listing.posture),507 (known): KnownPosture => ({508 label: props.postureLabel ?? postureLabel(known),509 posture: known,510 })511 )512 );513514 const landedAt = props.lastLanded ?? listing.landedAt;515 const open = Option.map(Option.fromUndefinedOr(asks), openAsks);516 const text = code?.readme?.text;517518 return (164 <PageShell title={project}>165 <ProjectNav current="overview" project={project} />166 <div className="text-muted-foreground -mt-2 flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">167 <PostureBadge168 label={postureLabel(listing.posture)}169 posture={listing.posture}519 <Workspace520 {...Option.match(open, {521 onNone: () => ({}),522 onSome: (each) => ({ count: countOf(each) }),523 })}524 crumbs={[{ label: project, to: `/${project}` }, { label: "Asks" }]}525 facts={526 <PageFacts527 landedAt={landedAt}528 picked={asks?.find(({ ask }) => ask === selected)}529 posture={posture}530 props={props}531 states={states}532 />171 <span>172 {listing.openAsks} open {listing.openAsks === 1 ? "ask" : "asks"}173 </span>174 <span>175 {listing.landedAt === undefined ? (176 "Nothing landed yet"177 ) : (178 <>179 Last landed <When at={listing.landedAt} now={now} />180 </>181 )}182 </span>183 </div>184 <CloneBox platformUrl={platformUrl} project={project} />185 <div className="grid gap-x-12 gap-y-10 lg:grid-cols-[minmax(0,1fr)_22rem]">186 <section187 aria-labelledby="open-asks"188 className="flex min-w-0 flex-col gap-3 lg:col-start-1"189 >190 <div className="flex flex-wrap items-baseline justify-between gap-x-6 gap-y-1">191 <h2 className={SECTION} id="open-asks">192 Open asks193 </h2>194 <SignedInProposeLink project={project} />195 </div>196 {asks.length === 0 ? (197 <EmptyState198 command={`${Brand.cli} ask open <ask> --files <files>`}199 title="No open asks. A decider opens one from an ask file."200 />201 ) : (202 <ol className="border-rule flex flex-col border-b">203 {asks.map((ask) => (204 <AskRow key={ask.ask} listing={ask} project={project} />205 ))}206 </ol>207 )}208 </section>209 <aside210 aria-labelledby="take-part"211 className="flex min-w-0 flex-col gap-3 lg:col-start-2 lg:row-span-2 lg:row-start-1"212 >213 <h2 className={SECTION} id="take-part">214 Take part215 </h2>216 <ol className="border-rule flex flex-col gap-4 border-t pt-4">217 {steps(project).map(({ command, label }) => (218 <li className="flex min-w-0 flex-col gap-1.5" key={command}>219 <span className="text-muted-foreground text-xs font-medium">220 {label}221 </span>222 <CommandLine command={command} />223 </li>224 ))}225 </ol>226 </aside>227 <section228 aria-labelledby="recent-landings"229 className="flex min-w-0 flex-col gap-3 lg:col-start-1"230 >231 <h2 className={SECTION} id="recent-landings">232 Recent landings233 </h2>234 {landings.length === 0 ? (235 <NoLandings listing={listing} platformUrl={platformUrl} />236 ) : (237 <LandingList landings={landings} now={now} />238 )}239 </section>240 </div>241 {code === undefined ? null : (242 <CodeSection code={code} project={project} />533 }534 factsHeading={535 asks?.some(({ ask }) => ask === selected) === true536 ? "Selected ask"537 : "How a change lands here"538 }539 {...Option.match(Option.fromUndefinedOr(selected), {540 onNone: () => ({}),541 onSome: (factsKey) => ({ factsKey }),542 })}543 factsSummary={posture?.label ?? "Posture, gate, who decides, take part"}544 status={545 <ProjectLine546 count={Option.match(open, {547 onNone: () => listing.openAsks,548 onSome: (each) => each.length,549 })}550 landedAt={landedAt}551 lede={Predicate.isString(text) ? ledeOf(text) : undefined}552 now={props.now}553 posture={posture}554 />555 }556 title={project}557 variant="list"558 >559 <ProjectNav current="overview" project={project} />560 <AsksSection561 asks={asks}562 onSelect={select}563 parents={props.parents ?? []}564 project={project}565 selected={selected}566 signedIn={props.signedIn === true}567 stamps={props.stamps ?? new Set()}568 states={states}569 unreachable={props.unreachable === true}570 />571 {code?.readme === undefined ? null : (572 <ReadmeSection file={code.readme} project={project} />573 )}244 </PageShell>574 </Workspace>575 );576};577578const Selectable = ({ props }: { readonly props: ProjectViewProps }) => {579 const { select, selected } = useRowSelection(580 props.asks === undefined ? [] : askListIds(props.asks),581 "ask"582 );583584 return <ProjectPanes props={props} select={select} selected={selected} />;585};586587/**249 * The page as the server sends it, while the browser reads the asks and250 * landings: the clone line, rows holding their place, and the code the251 * server read with the page (its root folder and README), so a reader252 * without JavaScript, and a crawler, still gets the README.588 * The project's home. Inside the router its list selects (`?ask=`) and `j`589 * and `k` walk it; a view rendered alone draws the same page with nothing590 * selected.591 */254export const ProjectReadingView = ({255 code,256 platformUrl,257 project,258}: {259 /** The root folder at main and its README, when the server could read them. */260 readonly code?: ProjectCode | undefined;261 readonly platformUrl: string;262 readonly project: ProjectName;263}) => (264 <PageShell title={project}>265 <ProjectNav current="overview" project={project} />266 <CloneBox platformUrl={platformUrl} project={project} />267 <ReadingRows />268 {code === undefined ? null : <CodeSection code={code} project={project} />}269 </PageShell>270);592export const ProjectView = (props: ProjectViewProps) =>593 Predicate.isNotNullish(useRouter({ warn: false })) ? (594 <Selectable props={props} />595 ) : (596 <ProjectPanes props={props} select={undefined} selected={undefined} />597 );
modified:apps/web/src/features/project/readme-section.tsx+2 added-1 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.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 */7import type { FileView } from "@repo/protocol/domain/code";8import type { ProjectName } from "@repo/protocol/ids";9
32 unmodified lines
modified:apps/web/src/features/project/unknown-project.tsx+28 added-8 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. An address4 * that cannot be a project's name at all says so in a sentence.3 * 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 */7import { ProjectName } from "@repo/protocol/ids";8import { UnknownProject } from "@repo/protocol/refusal";9import { Option, Schema } from "effect";1011import { EmptyState } from "../shared/empty.tsx";11import { PageShell } from "../shared/layout.tsx";12import { AppLink } from "../shared/link.tsx";13import { RefusalView } from "../shared/refusal.tsx";14import { Workspace } from "../shared/shell/workspace.tsx";1516const decodeProject = Schema.decodeUnknownOption(ProjectName);1718const LINK = "decoration-rule underline hover:decoration-current";1920/** Where to go instead: every open ask. */21const Onward = () => (22 <div className="text-ui flex flex-wrap gap-x-4 gap-y-1">23 <AppLink className={LINK} to="/">24 Open asks25 </AppLink>26 </div>27);2829export const UnknownProjectView = ({ name }: { readonly name: string }) =>30 Option.match(decodeProject(name), {31 onNone: () => (19 <PageShell title="No such project">20 <EmptyState title="A project's name is lowercase words joined by single dashes, and this address names none." />21 </PageShell>32 <Workspace33 crumbs={[{ label: "No such project" }]}34 title="No such project"35 >36 <EmptyState37 onward={<Onward />}38 title="A project's name is lowercase words joined by single dashes, and this address names none."39 />40 </Workspace>41 ),42 onSome: (project) => (24 <PageShell title={project}>43 <Workspace crumbs={[{ label: project }]} title="No such project">44 <RefusalView refusals={[new UnknownProject({ project })]} />26 </PageShell>45 <Onward />46 </Workspace>47 ),48 });
modified:apps/web/src/routes/$project/index.tsx+252 added-140 removed
1import { useAtomMount, useAtomValue } from "@effect/atom-react";2import { FileView, TreeListing } from "@repo/protocol/domain/code";3import type { ProjectListing } from "@repo/protocol/domain/front-page";4import { ProjectName } from "@repo/protocol/ids";5import { UnknownProject } from "@repo/protocol/refusal";6import { createFileRoute, getRouteApi, notFound } from "@tanstack/react-router";2import type { Ask } from "@repo/protocol/domain/ask";3import { AskId } from "@repo/protocol/ids";4import type { ProjectName } from "@repo/protocol/ids";5import {6 createFileRoute,7 getRouteApi,8 useHydrated,9} from "@tanstack/react-router";10import { createServerFn } from "@tanstack/react-start";11import { env } from "cloudflare:workers";9import { DateTime, Effect, Option, Schema } from "effect";12import { Effect, Option, Predicate, Schema } from "effect";13import { AsyncResult } from "effect/reactivity";14import { useMemo } from "react";15import type { ReactNode } from "react";1617import { askAtom } from "../../client/ask.ts";18import { projectCodeAtom } from "../../client/code.ts";13import { recentLandingsAtom } from "../../client/events.ts";14import { projectsAtom } from "../../client/front.ts";15import { asksAtom } from "../../client/project.ts";19import { projectEventsAtom, recentLandings } from "../../client/events.ts";20import {21 asksAtom,22 projectLedgerAtom,23 projectPolicyAtom,24} from "../../client/project.ts";25import { SeededAtoms, seedSuccess } from "../../client/seeded.ts";26import type { Seed } from "../../client/seeded.ts";27import { watchAtom } from "../../client/watch.ts";28import { useSignedIn } from "../../features/auth/session-slot.tsx";29import { ledeOf } from "../../features/front/head.ts";30import {18 ProjectReadingView,31 markdownAlternateLink,32 markdownLink,33} from "../../features/front/markdown.ts";34import { useStamps } from "../../features/front/stamps.ts";35import {36 ProjectView,37 heldBackOf,38 homeListing,39} from "../../features/project/project-page.tsx";40import { UnknownProjectView } from "../../features/project/unknown-project.tsx";41import { askStates } from "../../features/shared/ask-progress.ts";42import { pageHead } from "../../features/shared/head.ts";23import { Unreachable } from "../../features/shared/pending.tsx";43import { reloadOnEnter } from "../../features/shared/shell/selection.ts";44import { branchPage } from "../../server/cache-headers.ts";45import { serverClient } from "../../server/client.ts";25import { readFolderWithReadme } from "../../server/folder.ts";46import {47 ProjectPageData,48 decodeName,49 projectPageHandler,50 readProjectPage,51} from "../../server/project-page.ts";5227// A project's page. The loader asks the platform, on the server, for the28// project's root folder at main and its README, so the page arrives with29// its code and a crawler reads the README; the same read says whether the30// project exists, so an address naming none is a 404 that shows the31// platform's `UnknownProject` refusal. The page's other reads (asks,32// landings, the listing) are atoms the browser calls, and the code's atom33// keeps it live once it has a value.53// A project's home, which is its list of asks. The loader reads, on the54// server and at once, the project's asks, its own ledger (its posture), its55// events (each ask's progress, a family's marks, its landings), its policy56// (who decides) and its root folder with its README, then each family's57// parent in full; so the page, and an agent fetching it, arrive with the58// asks and the README. A read the platform cannot give now leaves its59// section to the browser; an address naming no project is a 404 that shows60// the platform's `UnknownProject` refusal. The list of projects is never61// read here. The same URL answers `Accept: text/markdown` with the62// project's `llms.txt`.6335const decodeName = Schema.decodeUnknownOption(ProjectName);3637const isUnknownProject = Schema.is(UnknownProject);3839/** What the loader hands the page: the project's code, when it could be read. */40export const ProjectPageData = Schema.Struct({41 code: Schema.optionalKey(42 Schema.Struct({43 readme: Schema.optionalKey(FileView),44 root: TreeListing,45 })46 ),47});4849const encodePage = Schema.encodeEffect(ProjectPageData);5051/**52 * The project's page data, read over `Client`, or a not-found for a name53 * that is none or a project the platform does not know. A project whose54 * main has not landed, or whose code the platform cannot read now, has a55 * page without its code; when the platform did not answer, the page's own56 * reads say so.57 */58export const readProjectPage = (name: string) =>59 Effect.gen(function* () {60 const project = yield* Effect.fromOption(decodeName(name));6162 const code = yield* readFolderWithReadme({63 path: Option.none(),64 project,65 rev: "main",66 }).pipe(67 Effect.map(({ listing, readme }) =>68 Option.some({69 root: listing,70 ...Option.match(readme, {71 onNone: () => ({}),72 onSome: (file) => ({ readme: file }),73 }),74 })75 ),76 Effect.catchTag("UnknownProject", () => Effect.fail(notFound())),77 Effect.catchTag(78 ["RpcClientError", "Unauthenticated", "UnknownPath", "UnknownRevision"],79 () => Effect.succeedNone80 )81 );8283 // What the platform sent decoded, so it encodes; a failure is a defect.84 return yield* encodePage(85 Option.match(code, {86 onNone: () => ({}),87 onSome: (read) => ({ code: read }),88 })89 ).pipe(Effect.orDie);90 }).pipe(Effect.catchTag("NoSuchElementError", () => Effect.fail(notFound())));9164const projectPage = createServerFn({ method: "GET" })65 .validator((name: string) => name)66 .handler(({ data }) =>67 Effect.runPromise(68 readProjectPage(data).pipe(Effect.provide(serverClient(env)))69 )70 );71100const root = getRouteApi("__root__");72/** Where a project's Markdown is; none for a name that can name no project. */73const markdownOf = (name: string) =>74 Option.map(decodeName(name), (project) => `/${project}/llms.txt`);7576/**103 * The project as listed, its posture the one its own ledger stands at (the104 * list reads it from each project); a project the list has not heard from105 * yet (its projection catches up after its first event) reads open, as106 * the projection lists a project before any posture is projected.77 * The page's headers: varied by `Accept`; for a name that can be a78 * project's, kept briefly with its Markdown named. A path that cannot names79 * nothing, so no raw path text reaches a header.80 */108const listingOf = (109 project: ProjectName,110 projects: readonly ProjectListing[],111 openAsks: number112): ProjectListing =>113 projects.find((listed) => listed.project === project) ?? {114 openAsks,115 posture: "open",116 project,81export const projectPageHeaders = ({82 params,83}: {84 readonly params: { readonly project: string };85}): Readonly<Record<string, string>> =>86 Option.match(markdownOf(params.project), {87 onNone: () => ({ vary: "Accept" }),88 onSome: (href) => ({89 ...branchPage,90 link: markdownLink(href),91 vary: "Accept",92 }),93 });9495/** The page's head: its name, its README's first sentence, and its Markdown. */96export const projectPageHead = ({97 loaderData,98 params,99}: {100 readonly params: { readonly project: string };101 readonly loaderData?: typeof ProjectPageData.Encoded | undefined;102}) => {103 const text = loaderData?.code?.readme?.text;104 const lede = Predicate.isString(text) ? ledeOf(text) : undefined;105106 return {107 ...pageHead({108 title: params.project,109 ...Option.match(Option.fromUndefinedOr(lede), {110 onNone: () => ({}),111 onSome: (description) => ({ description }),112 }),113 }),114 links: Option.match(markdownOf(params.project), {115 onNone: () => [],116 onSome: (href) => [markdownAlternateLink(href)],117 }),118 };119};120119const decodePage = Schema.decodeSync(ProjectPageData);121const root = getRouteApi("__root__");122121const ProjectBody = ({ project }: { readonly project: ProjectName }) => {122 const { platformUrl } = root.useLoaderData();123 const read = decodePage(Route.useLoaderData());123/** The selected ask in full, read in the browser once it is selected. */124const WithFull = ({125 ask,126 children,127 project,128}: {129 readonly ask: AskId;130 readonly project: ProjectName;131 readonly children: (full: Ask | undefined) => ReactNode;132}) => {133 const read = useAtomValue(askAtom(project, ask));134135 return children(AsyncResult.isSuccess(read) ? read.value.ask : undefined);136};137138const decodeAsk = Schema.decodeUnknownOption(AskId);139140/** An atom's value once it has one, else what the loader read. */141const valueOr = <A, E, B>(142 read: AsyncResult.AsyncResult<A, E>,143 seeded: B | undefined,144 pick: (value: A) => B145): B | undefined =>146 Option.getOrElse(Option.map(AsyncResult.value(read), pick), () => seeded);147148/** The page over its atoms, each section as its read arrives, all kept live. */149const LiveProject = ({150 data,151 platformUrl,152 selected,153 signedIn,154}: {155 readonly data: ProjectPageData;156 readonly platformUrl: string;157 readonly selected: string | undefined;158 readonly signedIn: boolean;159}) => {160 const { project } = data;161 const hydrated = useHydrated();162163 // Live: each event the project commits makes these reads fetch again.164 useAtomMount(watchAtom(project));165128 const reads = AsyncResult.all({129 asks: useAtomValue(asksAtom(project)),130 landings: useAtomValue(recentLandingsAtom(project)),131 listed: useAtomValue(projectsAtom),132 });166 const asksRead = useAtomValue(asksAtom(project));167 const asks = valueOr(asksRead, data.asks, ({ asks: listed }) => listed);168134 // The root folder and README: the loader's, read on the server, until the135 // atom has its own (it reads again on each landing). A project whose main136 // has not landed (or whose code cannot be read now) shows its page137 // without them.138 const code = Option.getOrElse(139 AsyncResult.value(useAtomValue(projectCodeAtom(project))),140 () => read.code169 const events = valueOr(170 useAtomValue(projectEventsAtom(project)),171 data.events,172 (read) => read173 );174143 return AsyncResult.matchWithError(reads, {144 onDefect: () => <Unreachable title={project} />,145 onError: (error) =>146 isUnknownProject(error) ? (147 <UnknownProjectView name={project} />148 ) : (149 <Unreachable title={project} />150 ),151 onInitial: () => (152 <ProjectReadingView153 code={code}154 platformUrl={platformUrl}155 project={project}156 />157 ),158 onSuccess: ({ value: { asks, landings, listed } }) => (159 <ProjectView160 asks={asks.asks}161 code={code}162 landings={landings}163 listing={listingOf(project, listed.projects, asks.asks.length)}164 now={DateTime.nowUnsafe()}165 platformUrl={platformUrl}166 />167 ),168 });175 const ledger = valueOr(176 useAtomValue(projectLedgerAtom(project)),177 data.ledger,178 (read) => read179 );180181 const code = valueOr(182 useAtomValue(projectCodeAtom(project)),183 data.code,184 (read) => read185 );186187 const deciders = valueOr(188 useAtomValue(projectPolicyAtom(project)),189 data.policy,190 (read) => read191 )?.policy?.deciders;192193 const reads = useMemo(194 () => new Map(events === undefined ? [] : [[project, events]]),195 [events, project]196 );197198 const stamps = useStamps(reads)(project);199 const states = useMemo(() => askStates(events ?? []), [events]);200 const landings = useMemo(() => recentLandings(events ?? []), [events]);201 const [latest] = landings;202203 const view = (selectedAsk?: Ask) => (204 <ProjectView205 asks={asks}206 code={code}207 deciders={deciders}208 heldBack={ledger === undefined ? undefined : heldBackOf(ledger)}209 landings={landings}210 lastLanded={latest?.landedAt}211 listing={homeListing({ asks, ledger, project })}212 now={data.now}213 parents={data.parents}214 platformUrl={platformUrl}215 postureLabel={ledger?.postureLabel}216 selectedAsk={selectedAsk}217 signedIn={signedIn}218 stamps={stamps}219 states={states}220 unreachable={AsyncResult.isFailure(asksRead)}221 />222 );223224 const picked = Option.filter(decodeAsk(selected), (ask) =>225 (asks ?? []).some((listing) => listing.ask === ask)226 );227228 return hydrated && Option.isSome(picked) ? (229 <WithFull ask={picked.value} project={project}>230 {view}231 </WithFull>232 ) : (233 view()234 );235};236171/** The page, for a name the loader found; a name that is none reads as unknown. */237const ProjectPage = () => {173 const { project } = Route.useParams();238 const loaded = Route.useLoaderData();239175 return Option.match(decodeName(project), {176 onNone: () => <UnknownProjectView name={project} />,177 onSome: (name) => <ProjectBody project={name} />,178 });240 const data = useMemo(241 () => Schema.decodeSync(ProjectPageData)(loaded),242 [loaded]243 );244245 const { ask } = Route.useSearch();246 const { platformUrl } = root.useLoaderData();247 const signedIn = useSignedIn();248 const { project } = data;249250 const seeds: readonly Seed[] = [251 ...(data.asks === undefined252 ? []253 : [seedSuccess(asksAtom(project), { asks: data.asks })]),254 ...(data.events === undefined255 ? []256 : [seedSuccess(projectEventsAtom(project), data.events)]),257 ...(data.ledger === undefined258 ? []259 : [seedSuccess(projectLedgerAtom(project), data.ledger)]),260 ...(data.code === undefined261 ? []262 : [seedSuccess(projectCodeAtom(project), data.code)]),263 ...(data.policy === undefined264 ? []265 : [seedSuccess(projectPolicyAtom(project), data.policy)]),266 ];267268 return (269 <SeededAtoms id={project} seeds={seeds}>270 <LiveProject271 data={data}272 platformUrl={platformUrl}273 selected={ask}274 signedIn={signedIn}275 />276 </SeededAtoms>277 );278};279280const Unknown = () => {281 const { project } = Route.useParams();
1 unmodified line
283 return <UnknownProjectView name={project} />;284};285286export const Route = createFileRoute("/$project/")({188 component: ProjectPage,189 head: ({ params }) => pageHead({ title: params.project }),287 // TanStack infers each option from the ones before it.288 validateSearch: ({ ask }: { readonly ask?: unknown }) =>289 Predicate.isString(ask) ? { ask } : {},290 loader: ({ params }) => projectPage({ data: params.project }),291 shouldReload: reloadOnEnter,292 head: projectPageHead,293 headers: projectPageHeaders,294 component: ProjectPage,295 notFoundComponent: Unknown,296 server: {297 handlers: {298 GET: projectPageHandler(299 (request) => serverClient(env, request),300 env.PUBLIC_PLATFORM_URL301 ),302 },303 },304});
modified:apps/web/src/routes/$project/llms[.]txt.ts+6 added-61 removed
1import { Client } from "@repo/protocol/contracts";2import { ProjectName } from "@repo/protocol/ids";1import { createFileRoute } from "@tanstack/react-router";2import { env } from "cloudflare:workers";5import { Array as Arr, Effect, Option, Schema } from "effect";37import { commands } from "../../features/agents/catalog.ts";8import { missingProjectLlms, projectLlms } from "../../features/agents/llms.ts";9import { markdown, unavailable } from "../../features/agents/respond.ts";4import { serverClient } from "../../server/client.ts";5import { projectLlmsHandler } from "../../server/llms.ts";612const decodeProject = Schema.decodeUnknownOption(ProjectName);1314/**15 * `/<project>/llms.txt`: one project for an agent, as the platform lists16 * it, with its open asks. A name the platform does not list is not found.17 */18const llms = (request: Request, name: string) =>19 Effect.gen(function* () {20 const webUrl = new URL(request.url).origin;21 const project = decodeProject(name);2223 const missing = () =>24 markdown(missingProjectLlms({ project, webUrl }), 404);2526 if (Option.isNone(project)) {27 return missing();28 }2930 const client = yield* Client;31 const { projects } = yield* client.listProjects({});3233 const listing = Arr.findFirst(34 projects,35 (each) => each.project === project.value36 );3738 if (Option.isNone(listing)) {39 return missing();40 }4142 const asks = yield* client.listAsks({ project: project.value }).pipe(43 Effect.map((listed) => Option.some(listed.asks)),44 Effect.catchTag("UnknownProject", () => Effect.succeedNone)45 );4647 if (Option.isNone(asks)) {48 return missing();49 }5051 return markdown(52 projectLlms({53 asks: asks.value,54 commands,55 listing: listing.value,56 platformUrl: env.PUBLIC_PLATFORM_URL,57 webUrl,58 })59 );60 }).pipe(61 Effect.orElseSucceed(unavailable),62 Effect.provide(serverClient(env, request))63 );647// `/<project>/llms.txt`: one project for an agent (`server/llms.ts`).8export const Route = createFileRoute("/$project/llms.txt")({9 server: {10 handlers: {68 GET: ({ params, request }) =>69 Effect.runPromise(llms(request, params.project)),11 GET: projectLlmsHandler(12 (request) => serverClient(env, request),13 env.PUBLIC_PLATFORM_URL14 ),15 },16 },17});
modified:apps/web/src/routes/index.tsx+220 added-27 removed
1import { useAtomValue } from "@effect/atom-react";2import { createFileRoute } from "@tanstack/react-router";3import { DateTime } from "effect";1import { useAtomMount, useAtomRefresh, useAtomValue } from "@effect/atom-react";2import type { Ask } from "@repo/protocol/domain/ask";3import type { ProjectListing } from "@repo/protocol/domain/front-page";4import { AskId } from "@repo/protocol/ids";5import type { ProjectName } from "@repo/protocol/ids";6import {7 createFileRoute,8 getRouteApi,9 useHydrated,10 useRouter,11} from "@tanstack/react-router";12import { createServerFn } from "@tanstack/react-start";13import { env } from "cloudflare:workers";14import { Array as Arr, Effect, Option, Predicate, Schema } from "effect";15import { AsyncResult } from "effect/reactivity";16import { useEffect, useMemo } from "react";17import type { ReactNode } from "react";1819import { askAtom } from "../client/ask.ts";20import { projectEventsAtom } from "../client/events.ts";21import { frontPageAtom, projectsAtom } from "../client/front.ts";22import {23 familyEventsAtom,24 followedAtom,25 projectsKey,26} from "../client/project.ts";27import { SeededAtoms, seedSuccess } from "../client/seeded.ts";28import type { Seed } from "../client/seeded.ts";29import { useSignedIn } from "../features/auth/session-slot.tsx";30import { readFilter } from "../features/front/filter.ts";31import type { FrontFilter } from "../features/front/filter.ts";32import { FrontPageView } from "../features/front/front-page.tsx";33import { EXPLAINER } from "../features/front/head.ts";34import {35 markdownAlternateLink,36 markdownLink,37} from "../features/front/markdown.ts";38import { useStamps } from "../features/front/stamps.ts";39import { pageHead } from "../features/shared/head.ts";10import { Reading, Unreachable } from "../features/shared/pending.tsx";40import { reloadOnEnter } from "../features/shared/shell/selection.ts";41import { branchPage } from "../server/cache-headers.ts";42import { serverClient } from "../server/client.ts";43import {44 FrontPageData,45 frontPageHandler,46 readFrontPage,47} from "../server/front-page.ts";4812// The front page: every open ask, read once, filtered here by the address's13// `?kind=` and `?reserved=` (each decoded with its schema; one that does not14// decode is dropped). The whole list is read, so the filter offers every15// kind on the platform.49// The front page: every open ask, read on the server by the loader, so the50// page (and an agent fetching it) arrives with its asks; narrowed here by51// the address's search. The whole list is read, so the filter offers every52// kind. The list of projects (each group's posture) is the browser's read,53// never the loader's: it may arrive after the rows, and moves none of them.54// The same URL answers `Accept: text/markdown` with `llms.txt`.5556const TITLE = "Open asks";5719/** Every open ask, unfiltered: the page narrows it, so its filter can offer every kind. */58/** Where the page's Markdown is. */59const MARKDOWN = "/llms.txt";6061const frontPageData = createServerFn({ method: "GET" }).handler(() =>62 Effect.runPromise(readFrontPage.pipe(Effect.provide(serverClient(env))))63);6465/** The page's headers: kept briefly, varied by `Accept`, its Markdown named. */66export const frontPageHeaders = () => ({67 ...branchPage,68 link: markdownLink(MARKDOWN),69 vary: "Accept",70});7172/** The page's head: its title, its one sentence, and its Markdown. */73export const frontPageHead = () => ({74 ...pageHead({ description: EXPLAINER, title: TITLE }),75 links: [markdownAlternateLink(MARKDOWN)],76});7778/** The open asks, unfiltered: the page narrows them, so its filter can offer every kind. */79const everyAsk = frontPageAtom({});8081const root = getRouteApi("__root__");8283/** The selected ask in full, read in the browser once it is selected. */84const WithFull = ({85 ask,86 children,87 project,88}: {89 readonly ask: AskId;90 readonly project: ProjectName;91 readonly children: (full: Ask | undefined) => ReactNode;92}) => {93 const read = useAtomValue(askAtom(project, ask));9495 return children(AsyncResult.isSuccess(read) ? read.value.ask : undefined);96};9798const decodeAsk = Schema.decodeUnknownOption(AskId);99100/** The page over its atoms, which start from what the loader read and stay live. */101const LiveFront = ({102 data,103 filter,104 platformUrl,105 projects,106 selected,107 signedIn,108 webUrl,109}: {110 readonly data: FrontPageData;111 readonly filter: FrontFilter;112 readonly platformUrl: string;113 readonly projects: readonly ProjectListing[] | undefined;114 readonly selected: string | undefined;115 readonly signedIn: boolean;116 readonly webUrl: string;117}) => {118 const hydrated = useHydrated();119 const key = projectsKey(data.events.map(({ project }) => project));120 const refresh = useAtomRefresh(everyAsk);121122 // Live: each family's project, followed while the page is open.123 useAtomMount(followedAtom(key));124125 // The loader read as anyone; once someone is signed in, read who may take what for them.126 useEffect(() => {127 if (signedIn) {128 refresh();129 }130 }, [refresh, signedIn]);131132 const { entries } = Option.getOrElse(133 AsyncResult.value(useAtomValue(everyAsk)),134 () => data135 );136137 const events = useAtomValue(familyEventsAtom(key));138 const stampsOf = useStamps(events);139140 const picked = Option.flatMap(decodeAsk(selected), (ask) =>141 Option.map(142 Arr.findFirst(entries, (entry) => entry.ask.ask === ask),143 (entry) => ({ ask, project: entry.project })144 )145 );146147 const view = (selectedAsk?: Ask) => (148 <FrontPageView149 entries={entries}150 events={events}151 filter={filter}152 now={data.now}153 parents={data.parents}154 platformUrl={platformUrl}155 projects={projects}156 selectedAsk={selectedAsk}157 stampsOf={stampsOf}158 webUrl={webUrl}159 />160 );161162 return hydrated && Option.isSome(picked) ? (163 <WithFull ask={picked.value.ask} project={picked.value.project}>164 {view}165 </WithFull>166 ) : (167 view()168 );169};170171const FrontPage = () => {23 const filter = Route.useSearch();172 const { ask, ...filter } = Route.useSearch();173 const loaded = Route.useLoaderData();17425 const read = AsyncResult.all({26 front: useAtomValue(everyAsk),27 listed: useAtomValue(projectsAtom),28 });175 const data = useMemo(176 () => Schema.decodeSync(FrontPageData)(loaded),177 [loaded]178 );17930 return AsyncResult.matchWithError(read, {31 onDefect: () => <Unreachable title={TITLE} />,32 onError: () => <Unreachable title={TITLE} />,33 onInitial: () => <Reading title={TITLE} />,34 onSuccess: ({ value: { front, listed } }) => (35 <FrontPageView36 entries={front.entries}180 const { platformUrl } = root.useLoaderData();181 const { origin } = useRouter();182183 // The root's own reads, in the registry it shares with the shell.184 const listed = useAtomValue(projectsAtom);185 const signedIn = useSignedIn();186187 const seeds: readonly Seed[] = [188 seedSuccess(everyAsk, { entries: data.entries }),189 ...data.events.map(({ events, project }) =>190 seedSuccess(projectEventsAtom(project), events)191 ),192 ];193194 return (195 <SeededAtoms id="front" seeds={seeds}>196 <LiveFront197 data={data}198 filter={filter}38 now={DateTime.nowUnsafe()}39 projects={listed.projects}199 platformUrl={platformUrl}200 projects={201 AsyncResult.isSuccess(listed) ? listed.value.projects : undefined202 }203 selected={ask}204 signedIn={signedIn}205 webUrl={origin}206 />41 ),42 });207 </SeededAtoms>208 );209};210211/** The filter, and the selected ask, from the address. */212const readSearch = (search: {213 readonly ask?: unknown;214 readonly kind?: unknown;215 readonly project?: unknown;216 readonly reserved?: unknown;217 readonly take?: unknown;218}) => ({219 ...readFilter(search),220 ...Option.match(Option.liftPredicate(search.ask, Predicate.isString), {221 onNone: () => ({}),222 onSome: (ask) => ({ ask }),223 }),224});225226export const Route = createFileRoute("/")({227 // TanStack infers each option from the ones before it.228 validateSearch: readSearch,229 loader: () => frontPageData(),230 shouldReload: reloadOnEnter,231 head: frontPageHead,232 headers: frontPageHeaders,233 component: FrontPage,47 head: () => pageHead({ title: TITLE }),48 validateSearch: readFilter,234 server: {235 handlers: {236 GET: frontPageHandler(237 (request) => serverClient(env, request),238 env.PUBLIC_PLATFORM_URL239 ),240 },241 },242});
modified:apps/web/src/routes/llms[.]txt.ts+6 added-28 removed
1import { Client } from "@repo/protocol/contracts";1import { createFileRoute } from "@tanstack/react-router";2import { env } from "cloudflare:workers";4import { Effect } from "effect";36import { commands } from "../features/agents/catalog.ts";7import { frontLlms } from "../features/agents/llms.ts";8import { markdown, unavailable } from "../features/agents/respond.ts";4import { serverClient } from "../server/client.ts";5import { frontLlmsHandler } from "../server/llms.ts";611/**12 * `/llms.txt`: the platform for an agent, with the projects it lists now,13 * read through the same backend the browser's calls take.14 */15const llms = (request: Request) =>16 Effect.gen(function* () {17 const client = yield* Client;18 const { projects } = yield* client.listProjects({});1920 return markdown(21 frontLlms({22 commands,23 platformUrl: env.PUBLIC_PLATFORM_URL,24 projects,25 webUrl: new URL(request.url).origin,26 })27 );28 }).pipe(29 Effect.orElseSucceed(unavailable),30 Effect.provide(serverClient(env, request))31 );327// `/llms.txt`: the platform for an agent (`server/llms.ts`).8export const Route = createFileRoute("/llms.txt")({9 server: {10 handlers: {36 GET: ({ request }) => Effect.runPromise(llms(request)),11 GET: frontLlmsHandler(12 (request) => serverClient(env, request),13 env.PUBLIC_PLATFORM_URL14 ),15 },16 },17});
added:apps/web/src/server/front-page.ts+107 added
1/**2 * The front page's reads on the server, and its answer to an agent: what3 * its loader reads (the open asks, each family's parent in full, and the4 * events of each project that holds a family), and its GET, which gives a5 * request for Markdown `llms.txt`.6 */7import { Client } from "@repo/protocol/contracts";8import { Ask } from "@repo/protocol/domain/ask";9import { ProjectEvent } from "@repo/protocol/domain/event";10import { FrontPageEntry } from "@repo/protocol/domain/front-page";11import { ProjectName } from "@repo/protocol/ids";12import { Array as Arr, DateTime, Effect, Option, Schema, Stream } from "effect";1314import { wantsMarkdown } from "../features/ask/markdown.ts";15import { familiesIn } from "../features/front/families.ts";16import { variedByAccept } from "../features/front/markdown.ts";17import { frontLlmsHandler } from "./llms.ts";18import type { ClientFor } from "./llms.ts";1920/** What the loader carries from the server: the asks, the families' parents in full, and their projects' events. */21export const FrontPageData = Schema.Struct({22 entries: Schema.Array(FrontPageEntry),23 events: Schema.Array(24 Schema.Struct({ events: Schema.Array(ProjectEvent), project: ProjectName })25 ),26 now: Schema.DateTimeUtcFromString,27 parents: Schema.Array(Ask),28});2930export type FrontPageData = typeof FrontPageData.Type;3132/** Four reads at once: a page holds a few families, each read once. */33const AT_ONCE = 4;3435/** Each family on the page, by its project: `[project, parent]`. */36const familiesOf = (entries: readonly FrontPageEntry[]) =>37 Arr.dedupe(entries.map(({ project }) => project)).flatMap((project) =>38 familiesIn(39 entries.flatMap((entry) => (entry.project === project ? [entry.ask] : []))40 ).map(({ parent }) => [project, parent] as const)41 );4243/**44 * The front page's data, as the anonymous viewer reads it (so the page may45 * be kept by a cache; the browser reads again once someone signs in): the46 * open asks; each family's parent in full, which counts its children; and47 * the events of each project that holds a family, which mark them. A48 * parent or a replay the platform cannot give now leaves its family drawn49 * as plain rows. The list of projects is never read here.50 */51export const readFrontPage = Effect.gen(function* () {52 const client = yield* Client;53 const { entries } = yield* client.frontPage({});54 const families = familiesOf(entries);5556 const parents = yield* Effect.forEach(57 families,58 ([project, ask]) =>59 client.showAsk({ ask, project }).pipe(60 Effect.map((read) => Option.some(read.ask)),61 Effect.orElseSucceed(() => Option.none<Ask>())62 ),63 { concurrency: AT_ONCE }64 );6566 const events = yield* Effect.forEach(67 Arr.dedupe(families.map(([project]) => project)),68 (project) =>69 Stream.runCollect(client.watch({ project, since: 0 })).pipe(70 Effect.map((read) => Option.some({ events: read, project })),71 Effect.orElseSucceed(() => Option.none())72 ),73 { concurrency: AT_ONCE }74 );7576 return yield* Schema.encodeEffect(FrontPageData)({77 entries,78 events: Arr.getSomes(events),79 now: yield* DateTime.now,80 parents: Arr.getSomes(parents),81 });82});8384/**85 * The page's GET, as a function of its client: a request that asks for86 * Markdown gets `llms.txt`, varied by `Accept`; any other falls through to87 * the page.88 */89export const frontPageHandler =90 (clientFor: ClientFor, platformUrl: string) =>91 <Next>({92 next,93 request,94 }: {95 readonly next: () => Next;96 readonly request: Request;97 }): Promise<Response> | Next =>98 wantsMarkdown(request)99 ? Effect.runPromise(100 Effect.map(101 Effect.promise(() =>102 frontLlmsHandler(clientFor, platformUrl)({ request })103 ),104 variedByAccept105 )106 )107 : next();
added:apps/web/src/server/llms.ts+111 added
1/**2 * The agents' indexes as handlers of a request, each a function of its3 * client and the platform's URL: `/llms.txt` for the platform and4 * `/<project>/llms.txt` for one project. Their routes serve them, and the5 * front page and a project's page answer a request for Markdown with them,6 * so the text is written once.7 */8import { Client } from "@repo/protocol/contracts";9import { ProjectName } from "@repo/protocol/ids";10import { Array as Arr, Effect, Option, Schema } from "effect";11import type { Layer } from "effect";1213import { commands } from "../features/agents/catalog.ts";14import {15 frontLlms,16 missingProjectLlms,17 projectLlms,18} from "../features/agents/llms.ts";19import { markdown, unavailable } from "../features/agents/respond.ts";2021/** A route's client, for the request it answers. */22export type ClientFor = (request: Request) => Layer.Layer<Client>;2324/**25 * `/llms.txt`: the platform for an agent, with the projects it lists now,26 * read through the same backend the browser's calls take.27 */28export const frontLlmsHandler =29 (clientFor: ClientFor, platformUrl: string) =>30 ({ request }: { readonly request: Request }): Promise<Response> =>31 Effect.runPromise(32 Effect.gen(function* () {33 const client = yield* Client;34 const { projects } = yield* client.listProjects({});3536 return markdown(37 frontLlms({38 commands,39 platformUrl,40 projects,41 webUrl: new URL(request.url).origin,42 })43 );44 }).pipe(45 Effect.orElseSucceed(unavailable),46 Effect.provide(clientFor(request))47 )48 );4950const decodeProject = Schema.decodeUnknownOption(ProjectName);5152/**53 * `/<project>/llms.txt`: one project for an agent, as the platform lists54 * it, with its open asks. A name the platform does not list is not found.55 */56export const projectLlmsHandler =57 (clientFor: ClientFor, platformUrl: string) =>58 ({59 params,60 request,61 }: {62 readonly params: { readonly project: string };63 readonly request: Request;64 }): Promise<Response> =>65 Effect.runPromise(66 Effect.gen(function* () {67 const webUrl = new URL(request.url).origin;68 const project = decodeProject(params.project);6970 const missing = () =>71 markdown(missingProjectLlms({ project, webUrl }), 404);7273 if (Option.isNone(project)) {74 return missing();75 }7677 const client = yield* Client;78 const { projects } = yield* client.listProjects({});7980 const listing = Arr.findFirst(81 projects,82 (each) => each.project === project.value83 );8485 if (Option.isNone(listing)) {86 return missing();87 }8889 const asks = yield* client.listAsks({ project: project.value }).pipe(90 Effect.map((listed) => Option.some(listed.asks)),91 Effect.catchTag("UnknownProject", () => Effect.succeedNone)92 );9394 if (Option.isNone(asks)) {95 return missing();96 }9798 return markdown(99 projectLlms({100 asks: asks.value,101 commands,102 listing: listing.value,103 platformUrl,104 webUrl,105 })106 );107 }).pipe(108 Effect.orElseSucceed(unavailable),109 Effect.provide(clientFor(request))110 )111 );
added:apps/web/src/server/project-page.ts+177 added
1/**2 * A project's home's reads on the server, and its answer to an agent: what3 * its loader reads (its asks, its own ledger, its events, its policy, its4 * root folder and README, then each family's parent in full), and its GET,5 * which gives a request for Markdown the project's `llms.txt`.6 */7import { Client } from "@repo/protocol/contracts";8import { Ask, AskListing } from "@repo/protocol/domain/ask";9import { FileView, TreeListing } from "@repo/protocol/domain/code";10import { ProjectEvent } from "@repo/protocol/domain/event";11import { PolicyPending, PublicPolicy } from "@repo/protocol/domain/policy";12import { Ledger } from "@repo/protocol/domain/visibility";13import { ProjectName } from "@repo/protocol/ids";14import { UnknownProject } from "@repo/protocol/refusal";15import { notFound } from "@tanstack/react-router";16import {17 Array as Arr,18 Cause,19 DateTime,20 Effect,21 Option,22 Schema,23 Stream,24} from "effect";2526import { wantsMarkdown } from "../features/ask/markdown.ts";27import { familiesIn } from "../features/front/families.ts";28import { variedByAccept } from "../features/front/markdown.ts";29import { readFolderWithReadme } from "./folder.ts";30import { projectLlmsHandler } from "./llms.ts";31import type { ClientFor } from "./llms.ts";3233export const decodeName = Schema.decodeUnknownOption(ProjectName);3435/** What the loader carries from the server, each read there when the platform gave it. */36export const ProjectPageData = Schema.Struct({37 asks: Schema.optionalKey(Schema.Array(AskListing)),38 code: Schema.optionalKey(39 Schema.Struct({40 readme: Schema.optionalKey(FileView),41 root: TreeListing,42 })43 ),44 events: Schema.optionalKey(Schema.Array(ProjectEvent)),45 ledger: Schema.optionalKey(Ledger),46 now: Schema.DateTimeUtcFromString,47 parents: Schema.Array(Ask),48 /** The project's policy, as `projectPolicy` gives it. */49 policy: Schema.optionalKey(50 Schema.Struct({51 policy: Schema.optionalKey(PublicPolicy),52 unevaluated: Schema.optionalKey(PolicyPending),53 })54 ),55 project: ProjectName,56});5758export type ProjectPageData = typeof ProjectPageData.Type;5960const isUnknownProject = Schema.is(UnknownProject);6162/**63 * A read the page can do without: its value, or none when the platform64 * cannot give it now (whatever went wrong on the way); a project it does65 * not know is a 404.66 */67const optional = <A, E, R>(read: Effect.Effect<A, E, R>) =>68 read.pipe(69 Effect.asSome,70 Effect.catchCause((cause) =>71 Option.exists(Cause.findErrorOption(cause), isUnknownProject)72 ? Effect.fail(notFound())73 : Effect.succeed(Option.none<A>())74 )75 );7677/** Four reads at once: a project holds a few families, each read once. */78const AT_ONCE = 4;7980/**81 * The project's home, read over `Client`, or a not-found for a name that is82 * none or a project the platform does not know.83 */84export const readProjectPage = (name: string) =>85 Effect.gen(function* () {86 const project = yield* Effect.fromOption(decodeName(name));87 const client = yield* Client;8889 const read = yield* Effect.all(90 {91 asks: optional(client.listAsks({ project })),92 code: optional(93 readFolderWithReadme({ path: Option.none(), project, rev: "main" })94 ),95 events: optional(96 Stream.runCollect(client.watch({ project, since: 0 }))97 ),98 ledger: optional(client.ledger({ project })),99 policy: optional(client.projectPolicy({ project })),100 },101 { concurrency: "unbounded" }102 );103104 const asks = Option.map(read.asks, (listed) => listed.asks);105106 const parents = yield* Effect.forEach(107 familiesIn(Option.getOrElse(asks, () => [])),108 ({ parent }) =>109 client.showAsk({ ask: parent, project }).pipe(110 Effect.map((shown) => Option.some(shown.ask)),111 Effect.orElseSucceed(() => Option.none<Ask>())112 ),113 { concurrency: AT_ONCE }114 );115116 // What the platform sent decoded, so it encodes; a failure is a defect.117 return yield* Schema.encodeEffect(ProjectPageData)({118 ...Option.match(asks, {119 onNone: () => ({}),120 onSome: (listed) => ({ asks: listed }),121 }),122 ...Option.match(read.code, {123 onNone: () => ({}),124 onSome: ({ listing, readme }) => ({125 code: {126 root: listing,127 ...Option.match(readme, {128 onNone: () => ({}),129 onSome: (file) => ({ readme: file }),130 }),131 },132 }),133 }),134 ...Option.match(read.policy, {135 onNone: () => ({}),136 onSome: (policy) => ({ policy }),137 }),138 ...Option.match(read.events, {139 onNone: () => ({}),140 onSome: (events) => ({ events }),141 }),142 ...Option.match(read.ledger, {143 onNone: () => ({}),144 onSome: (ledger) => ({ ledger }),145 }),146 now: yield* DateTime.now,147 parents: Arr.getSomes(parents),148 project,149 }).pipe(Effect.orDie);150 }).pipe(Effect.catchTag("NoSuchElementError", () => Effect.fail(notFound())));151152/**153 * The page's GET, as a function of its client: a request that asks for154 * Markdown gets the project's `llms.txt`, varied by `Accept`; any other155 * falls through to the page.156 */157export const projectPageHandler =158 (clientFor: ClientFor, platformUrl: string) =>159 <Next>({160 next,161 params,162 request,163 }: {164 readonly next: () => Next;165 readonly params: { readonly project: string };166 readonly request: Request;167 }): Promise<Response> | Next =>168 wantsMarkdown(request)169 ? Effect.runPromise(170 Effect.map(171 Effect.promise(() =>172 projectLlmsHandler(clientFor, platformUrl)({ params, request })173 ),174 variedByAccept175 )176 )177 : next();
modified:apps/web/test/client-project.test.ts+28 added
2 unmodified lines
3 * and its events, replayed and folded.4 * Over the dev world in process (`dev-browser.ts`).5 */6import { describe, expect, it } from "@effect/vitest";7import { ProjectName } from "@repo/protocol/ids";8import { Effect, Exit } from "effect";910import {11 projectEventsAtom,12 recentLandings,13 recentLandingsAtom,14} from "../src/client/events.ts";15import { keys } from "../src/client/keys.ts";16import { familyEventsAtom, projectsKey } from "../src/client/project.ts";17import { ContractsClient } from "../src/surfaces.ts";18import { datekit, registryAs, seededWorld, settled } from "./dev-browser.ts";1920const burrow = ProjectName.make("burrow");2122describe("a project's page, through the web's atoms", seededWorld, () => {23 it.live("lists a project's asks", () =>24 Effect.gen(function* () {25 const registry = registryAs();
33 unmodified lines
59 ).toStrictEqual(recentLandings(replayed).map(({ sha }) => sha));60 })61 );62});6364describe(65 "the events of the projects a page's families are in",66 seededWorld,67 () => {68 it.live(69 "reads each project's replay once, keyed by the projects together",70 () =>71 Effect.gen(function* () {72 const registry = registryAs();73 const key = projectsKey([burrow, datekit]);7475 yield* settled(registry, projectEventsAtom(burrow));76 yield* settled(registry, projectEventsAtom(datekit));7778 const read = registry.get(familyEventsAtom(key));7980 expect(key).toBe("burrow datekit");81 expect([...read.keys()]).toStrictEqual([burrow, datekit]);82 expect(read.get(datekit)?.length).toBeGreaterThan(0);83 })84 );85 }86);
modified:apps/web/test/front.test.tsx+555 added-100 removed
1/**2 * The front page, rendered to HTML with `react-dom/server` from fixtures3 * decoded with the protocol's own schemas: open asks across projects, the4 * ones a viewer may take first, each other one with the reason it is not5 * theirs to take, narrowed by kind and by who an ask is held for.2 * The front page: the open asks of every project, read on the server by the3 * route's loader and rendered inside the router, grouped by project with4 * each project's posture said once on its group's header, a family drawn5 * as one fan row, each ask the viewer may take with its claim command as6 * text, narrowed by kind, by whether it is open to take or held for7 * newcomers, and by project.8 */9import { describe, expect, it } from "@effect/vitest";10import { Brand } from "@repo/brand";11import { deleteChildId, splitFamily } from "@repo/project/migrate";12import { Client, Contracts } from "@repo/protocol/contracts";13import { AskListing } from "@repo/protocol/domain/ask";14import type { Ask } from "@repo/protocol/domain/ask";15import { CheckSpec } from "@repo/protocol/domain/check";16import { Command, Glob, SymbolName } from "@repo/protocol/domain/common";17import {18 FrontPageEntry,19 ProjectListing,20} from "@repo/protocol/domain/front-page";13import { KindName } from "@repo/protocol/ids";14import { DateTime, Schema } from "effect";15import type { ReactElement } from "react";16import { renderToStaticMarkup } from "react-dom/server";21import { AskId, KindName, ProjectName } from "@repo/protocol/ids";22import { asTester, unanswered } from "@repo/protocol/testing";23import { DateTime, Effect, Layer, Option, Schema } from "effect";24import { FetchHttpClient } from "effect/http";25import { RpcClient, RpcSerialization, RpcTest } from "effect/rpc";2618import { filterEntries, readFilter } from "../src/features/front/filter.ts";27import { devServer } from "../src/dev/server.ts";28import { arrange, familiesIn } from "../src/features/front/families.ts";29import {30 filterEntries,31 frontPath,32 readFilter,33} from "../src/features/front/filter.ts";34import type { FrontFilter } from "../src/features/front/filter.ts";35import { FrontPageView } from "../src/features/front/front-page.tsx";36import type { FrontPageProps } from "../src/features/front/front-page.tsx";37import { FrontPageData, readFrontPage } from "../src/server/front-page.ts";38import { ask as parseIsoWeek } from "./ask-fixtures.ts";39import { textIn } from "./markup.ts";40import { renderAt } from "./render.tsx";41import { reachingTransport } from "./transport.ts";4223const markupOf = (element: ReactElement) => renderToStaticMarkup(element);2425/** What a reader sees: the markup without its tags, entities decoded. */26const textOf = (element: ReactElement) =>27 markupOf(element)28 .replaceAll(/<[^>]+>/gu, "")29 .replaceAll("&#x27;", "'")30 .replaceAll("&quot;", '"')31 .replaceAll("&lt;", "<")32 .replaceAll("&gt;", ">")33 .replaceAll("&amp;", "&");3443const kind = Schema.decodeSync(KindName);4437/** The markup of the row for `ask`: from its `<li>` to the next ask's row. */45/** The markup of the row for `ask`: from its `<li>` to the next row or group. */46const rowOf = (markup: string, ask: string) => {47 const start = markup.indexOf(`data-ask="${ask}"`);40 const next = markup.indexOf("data-ask=", start + 1);4842 return start === -143 ? ""44 : markup.slice(start, next === -1 ? undefined : next);49 const ends = ["data-ask=", "<section", "</main>"].flatMap((end) => {50 const at = markup.indexOf(end, start + 1);5152 return at === -1 ? [] : [at];53 });5455 return start === -1 ? "" : markup.slice(start, Math.min(...ends));56};5758/** The ask ids of the rows on the page, top to bottom. */59const rowsIn = (markup: string) =>60 [...markup.matchAll(/<li\b[^>]*data-ask="(?<ask>[^"]+)"/gu)].map(61 (row) => row.groups?.ask62 );6364/** The markup of each project group's sticky header, by its project. */65const headersIn = (markup: string) =>66 [67 ...markup.matchAll(68 /<section aria-label="(?<project>[^"]+)"[^>]*>(?<header><div\b[\s\S]*?<\/div><\/div>)/gu69 ),70 ].map((match) => [match.groups?.project, match.groups?.header] as const);7172/** The list itself: from the toolbar to the end of main, the facts left out. */73const listIn = (markup: string) =>74 markup.slice(markup.indexOf("data-toolbar"), markup.indexOf("</main>"));7576const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");7778const platformUrl = "https://platform-test.example.workers.dev";7980const webUrl = "https://web-test.example.workers.dev";8182const entries = Schema.decodeSync(Schema.Array(FrontPageEntry))([83 {84 ask: {85 ask: "explain-iso-week",
48 unmodified lines
134135const asksOf = (shown: readonly FrontPageEntry[]) =>136 shown.map(({ ask }) => ask.ask);137105/** The ask ids of the rows on the page, top to bottom. */106const rowsOf = (element: ReactElement) =>107 [...markupOf(element).matchAll(/<li\b[^>]*data-ask="(?<ask>[^"]+)"/gu)].map(108 (row) => row.groups?.ask138/** The page's props, with nothing the loader read beyond `entries`. */139const props = (140 filter: FrontFilter,141 more: Partial<FrontPageProps> = {}142): FrontPageProps => ({143 entries,144 events: new Map(),145 filter,146 now,147 parents: [],148 platformUrl,149 projects,150 webUrl,151 ...more,152});153154const front = (filter: FrontFilter, more: Partial<FrontPageProps> = {}) =>155 renderAt(156 filter.kind === undefined ? "/" : frontPath(filter),157 <FrontPageView {...props(filter, more)} />158 );159111const front = (filter: FrontFilter) => (112 <FrontPageView113 entries={entries}114 filter={filter}115 now={now}116 projects={projects}117 />118);119160describe(filterEntries, () => {161 it("puts the asks the viewer may take first, keeping the order given", () => {162 expect(asksOf(filterEntries(entries, {}))).toStrictEqual([163 "fix-week-start",
12 unmodified lines
176 expect(177 asksOf(filterEntries(entries, { reserved: "newcomers" }))178 ).toStrictEqual(["explain-iso-week"]);179 });180181 it("narrows the list to the asks open to take", () => {182 expect(asksOf(filterEntries(entries, { take: "open" }))).toStrictEqual([183 "fix-week-start",184 "split-format",185 ]);186 });187188 it("narrows the list to one project", () => {189 expect(190 asksOf(filterEntries(entries, { project: ProjectName.make("burrow") }))191 ).toStrictEqual(["split-format"]);192 });193});194195describe(readFilter, () => {143 it("keeps a valid kind and reserve from the address, and drops what is not one", () => {144 expect(readFilter({ kind: "bug", reserved: "newcomers" })).toStrictEqual({196 it("keeps a valid kind, reserve, take and project from the address, and drops what is not one", () => {197 expect(198 readFilter({199 kind: "bug",200 project: "datekit",201 reserved: "newcomers",202 take: "open",203 })204 ).toStrictEqual({205 kind: "bug",206 project: "datekit",207 reserved: "newcomers",208 take: "open",209 });210 expect(149 readFilter({ kind: "Not A Kind", reserved: "everyone" })211 readFilter({212 kind: "Not A Kind",213 project: "Not_A_Project",214 reserved: "everyone",215 take: "all",216 })217 ).toStrictEqual({});218 });219});220154describe(FrontPageView, () => {155 it("shows the asks the viewer may take first", () => {156 expect(rowsOf(front({}))).toStrictEqual([157 "fix-week-start",158 "split-format",159 "explain-iso-week",160 ]);221/** A listing as the contracts return one. */222const listing = (id: string, blockedBy: readonly string[] = []) =>223 Schema.decodeSync(AskListing)({224 ask: id,225 blockedBy,226 claimed: false,227 kind: "migrate",228 territory: ".",229 want: `The want of ${id}.`,230 });231163 it("marks an ask the viewer may not take with the reason", () => {164 const markup = markupOf(front({}));165 const row = rowOf(markup, "explain-iso-week");232describe(familiesIn, () => {233 const children = ["drop-fetch-auth", "drop-fetch-kit"];234167 expect(row).toContain('data-takeable="false"');168 expect(row).toContain("Held for newcomers");169 expect(row).not.toContain("Open to take");170 expect(row).not.toContain(`${Brand.cli} claim explain-iso-week`);171 expect(rowOf(markup, "fix-week-start")).toContain("Open to take");235 it("reads a family from a parent waiting on asks named after it, with its delete child", () => {236 const listed = [237 listing("drop-fetch", [...children, "drop-fetch-delete"]),238 listing("drop-fetch-auth"),239 listing("drop-fetch-kit"),240 listing("drop-fetch-delete", children),241 listing("fix-week-start"),242 ];243244 expect(familiesIn(listed)).toStrictEqual([245 {246 finale: "drop-fetch-delete",247 members: ["drop-fetch-auth", "drop-fetch-kit", "drop-fetch-delete"],248 parent: "drop-fetch",249 },250 ]);251 });252174 it("shows each ask's project, want, kind and territory, and links its project", () => {175 const row = rowOf(markupOf(front({})), "split-format");253 it("reads one where the list leaves its delete child out, or holds only it", () => {254 expect(255 familiesIn([256 listing("drop-fetch", children),257 listing("drop-fetch-auth"),258 listing("drop-fetch-kit"),259 ]).map(({ members }) => members)260 ).toStrictEqual([children]);261 expect(262 familiesIn([263 listing("drop-fetch", ["drop-fetch-delete"]),264 listing("drop-fetch-delete"),265 ]).map(({ members }) => members)266 ).toStrictEqual([["drop-fetch-delete"]]);267 });268177 expect(row).toContain('href="/burrow"');178 expect(row).toContain('href="/burrow/asks/split-format"');179 expect(row).toContain("The format package calls the new parser.");180 expect(row).toMatch(/>Kind<\/dt><dd\b[^>]*>migrate<\/dd>/u);181 expect(row).toMatch(/>Territory<\/dt><dd\b[^>]*>format<\/dd>/u);269 it("reads no family from an ask that waits on an ask not named after it", () => {270 expect(271 familiesIn([272 listing("footnote-backrefs", ["number-footnotes"]),273 listing("number-footnotes"),274 ])275 ).toStrictEqual([]);276 });277184 it("gives an ask the viewer may take the command that claims it", () => {185 expect(textOf(front({}))).toContain(186 `${Brand.cli} claim fix-week-start --project datekit`278 it("finds the family the platform's split opens, by the names it gives", () => {279 const migrateParent: Ask = {280 ...parseIsoWeek,281 blockedBy: [],282 brief: { want: "Replace legacyFetch with http.get." },283 check: CheckSpec.cases.Migrate.make({284 count: Command.make("bun run count"),285 from: SymbolName.make("legacyFetch"),286 to: SymbolName.make("http.get"),287 }),288 id: AskId.make("drop-fetch"),289 kind: KindName.make("migrate"),290 project: ProjectName.make("burrow"),291 territory: { module: ".", paths: [Glob.make("packages/**")] },292 };293294 const counted = Option.getOrThrow(295 splitFamily({296 configDir: Brand.configDir,297 counts: { byModule: { auth: 2, kit: 1 }, total: 3 },298 modules: [299 { module: "auth", paths: [Glob.make("packages/auth/**")] },300 { module: "kit", paths: [Glob.make("packages/kit/**")] },301 ],302 parent: migrateParent,303 })304 );188 });305190 it("narrows the list by kind, and offers every kind on the page as a filter", () => {191 const markup = markupOf(front({ kind: kind("migrate") }));306 const listed = [307 counted.parent,308 ...counted.children,309 counted.deleteChild,310 ].map((ask) => listing(ask.id, ask.blockedBy));311193 expect(rowsOf(front({ kind: kind("migrate") }))).toStrictEqual([194 "split-format",312 expect(familiesIn(listed)).toStrictEqual([313 {314 finale: deleteChildId(counted.parent.id),315 members: [316 ...counted.children.map(({ id }) => id),317 counted.deleteChild.id,318 ],319 parent: counted.parent.id,320 },321 ]);196 expect(markup).toContain('href="/?kind=bug"');197 expect(markup).toContain('href="/?kind=migrate"');198 expect(markup).toContain('href="/?kind=migrate&amp;reserved=newcomers"');199 expect(markupOf(front({}))).toContain('href="/?reserved=newcomers"');322 });323});324202 it("lists every project with its posture label and open asks", () => {203 const markup = markupOf(front({}));204 const listed = markup.slice(markup.indexOf('aria-labelledby="projects"'));325describe(arrange, () => {326 it("puts each family at its parent's place, its members out of the list", () => {327 const listed = [328 listing("fix-week-start"),329 listing("drop-fetch-auth"),330 listing("drop-fetch", ["drop-fetch-auth"]),331 listing("parse-iso"),332 ];333206 expect(markup).toContain('aria-labelledby="projects"');207 expect(listed).toMatch(208 /href="\/burrow"[^>]*>burrow<\/a>.*?Open with sealed evidence.*?1 open ask\b/u209 );210 expect(listed).toMatch(211 /href="\/datekit"[^>]*>datekit<\/a>.*?>Open<.*?2 open asks/u212 );334 expect(335 arrange(listed).map((item) =>336 item.kind === "family"337 ? `${item.parent.ask}: ${item.members.map(({ ask }) => ask).join(", ")}`338 : item.listing.ask339 )340 ).toStrictEqual([341 "fix-week-start",342 "drop-fetch: drop-fetch-auth",343 "parse-iso",344 ]);345 });346});347215 it("says an empty front page is empty, with the command that starts a project", () => {216 const text = textOf(217 <FrontPageView entries={[]} filter={{}} now={now} projects={[]} />218 );348describe(FrontPageView, () => {349 it.effect(350 "shows the asks the viewer may take first, grouped by project",351 () =>352 Effect.gen(function* () {353 expect(rowsIn(yield* front({}))).toStrictEqual([354 "fix-week-start",355 "explain-iso-week",356 "split-format",357 ]);358 })359 );360220 expect(text).toContain("No open asks");221 expect(text).toContain(`${Brand.cli} init`);222 });361 it.effect(362 "says each project's posture once, on its group's header, and on no row",363 () =>364 Effect.gen(function* () {365 const markup = yield* front({});366 const headers = headersIn(markup);367224 it("says a front page with projects but no asks needs an ask opened", () => {225 const text = textOf(226 <FrontPageView entries={[]} filter={{}} now={now} projects={projects} />227 );368 const [datekit, burrow] = headers.map(([, header]) => header ?? "");369370 expect(headers.map(([project]) => project)).toStrictEqual([371 "datekit",372 "burrow",373 ]);374 expect({375 burrowLink: burrow?.includes('href="/burrow"'),376 burrowPosture: burrow?.includes(377 'data-posture="openWithSealedEvidence"'378 ),379 burrowWords: textIn(burrow ?? "").includes(380 "Open with sealed evidence"381 ),382 datekitCounts: textIn(datekit ?? "").includes("2 open · 1 to take"),383 }).toStrictEqual({384 burrowLink: true,385 burrowPosture: true,386 burrowWords: true,387 datekitCounts: true,388 });389 expect(listIn(markup).match(/data-posture=/gu)).toHaveLength(2);390 expect(391 ["fix-week-start", "explain-iso-week", "split-format"].filter((ask) =>392 rowOf(markup, ask).includes("data-posture")393 )394 ).toStrictEqual([]);395 })396 );397398 it.effect(399 "draws its rows when the list of projects has not arrived, with no posture yet",400 () =>401 Effect.gen(function* () {402 const markup = yield* front({}, { projects: undefined });403404 expect(rowsIn(markup)).toHaveLength(3);405 expect(listIn(markup)).not.toContain("data-posture=");406 })407 );408409 it.effect(410 "marks an ask the viewer may not take with the reason, and no command",411 () =>412 Effect.gen(function* () {413 const markup = yield* front({});414 const row = rowOf(markup, "explain-iso-week");415416 expect(row).toContain('data-takeable="false"');417 expect(textIn(row)).toMatch(418 /Not open to you[\s\S]*held for newcomers/u419 );420 expect(row).not.toContain("Open to take");421 expect(row).not.toContain(`${Brand.cli} claim explain-iso-week`);422 expect(rowOf(markup, "fix-week-start")).toContain("Open to take");423 })424 );425426 it.effect("links each ask's want, and shows its kind, territory and id", () =>427 Effect.gen(function* () {428 const row = rowOf(yield* front({}), "split-format");429430 expect(row).toMatch(431 /<a\b[^>]*href="\/burrow\/asks\/split-format"[^>]*>The format package calls the new parser\.<\/a>/u432 );433 expect(textIn(row)).toContain("migrate · format · split-format");434 })435 );436437 it.effect(438 "gives an ask the viewer may take its claim command as text in its copy button, with no command box",439 () =>440 Effect.gen(function* () {441 const row = rowOf(yield* front({}), "fix-week-start");442443 expect(row).toMatch(444 new RegExp(445 `<button[^>]*aria-label="Copy claim command"[\\s\\S]*?<code[^>]*>${Brand.cli} claim fix-week-start --project datekit</code>`,446 "u"447 )448 );449 // A command box's text is selectable whole; a row's command is a button's.450 expect(row).not.toContain("select-all");451 })452 );453454 it.effect("counts the asks shown, and those open to take", () =>455 Effect.gen(function* () {456 expect(textIn(yield* front({}))).toContain("3 open asks, 2 open to take");457 })458 );459460 it.effect(461 "narrows by kind, offering each kind, who an ask is for, and each project, with counts",462 () =>463 Effect.gen(function* () {464 const markup = yield* front({ kind: kind("migrate") });465 const all = yield* front({});466 const toolbar = all.slice(all.indexOf("data-toolbar"));467468 expect(rowsIn(markup)).toStrictEqual(["split-format"]);469 expect(470 [471 'href="/?kind=bug"',472 'href="/?kind=migrate&amp;reserved=newcomers"',473 ].filter((href) => !markup.includes(href))474 ).toStrictEqual([]);475 expect(476 [477 'href="/?reserved=newcomers"',478 'href="/?take=open"',479 'href="/?project=burrow"',480 ].filter((href) => !all.includes(href))481 ).toStrictEqual([]);482 expect(textIn(toolbar)).toMatch(483 /Open to take\s*2[\s\S]*Held for newcomers\s*1/u484 );485 expect(486 ["Reserved", "For people, not agents"].filter((words) =>487 textIn(toolbar).includes(words)488 )489 ).toStrictEqual([]);490 })491 );492493 it.effect(494 "with nothing selected, says where to start and lists every project with its posture",495 () =>496 Effect.gen(function* () {497 const markup = yield* front({});498 const facts = markup.slice(markup.indexOf('data-facts="inspector"'));499 const text = textIn(facts);500501 expect(502 [503 "Start here",504 `curl -fsSL ${webUrl}/install.sh | sh`,505 `${Brand.cli} claim <ask> --project <project>`,506 ].filter((words) => !text.includes(words))507 ).toStrictEqual([]);508 expect(facts).toContain('href="/llms.txt"');509 expect(facts).toMatch(510 /href="\/burrow"[\s\S]*?1 open ask\b[\s\S]*?Open with sealed evidence/u511 );512 expect(facts).toMatch(513 /href="\/datekit"[\s\S]*?2 open asks[\s\S]*?>Open</u514 );515 })516 );517518 it.effect(519 "with an ask selected, shows its state, the claim numbered first, and a link to it",520 () =>521 Effect.gen(function* () {522 const markup = yield* renderAt(523 "/?ask=fix-week-start",524 <FrontPageView {...props({})} />525 );526527 const facts = markup.slice(markup.indexOf('data-facts="inspector"'));528529 expect(textIn(facts)).toContain("Selected ask");530 expect(textIn(facts)).toContain(531 `${Brand.cli} claim fix-week-start --project datekit`532 );533 expect(facts).toContain('href="/datekit/asks/fix-week-start"');534 expect(textIn(facts)).toContain("Open the ask");535 })536 );537538 it.effect("never uses the words a forge's lists use", () =>539 Effect.gen(function* () {540 const text = textIn(yield* front({})).toLowerCase();541542 for (const word of ["queue", "inbox", "explore", "trending"]) {543 expect(text).not.toContain(word);544 }545 })546 );547548 it.effect(549 "says an empty front page is empty, with the command that starts a project",550 () =>551 Effect.gen(function* () {552 const text = textIn(yield* front({}, { entries: [], projects: [] }));553554 expect(text).toContain("No open asks");555 expect(text).toContain(`${Brand.cli} init`);556 })557 );558559 it.effect(560 "says a front page with projects but no asks needs an ask opened",561 () =>562 Effect.gen(function* () {563 const text = textIn(yield* front({}, { entries: [] }));564229 expect(text).toContain("No open asks");230 expect(text).toContain(`${Brand.cli} ask open`);231 });565 expect(text).toContain("No open asks");566 expect(text).toContain(`${Brand.cli} ask open`);567 })568 );569});570571/** The contracts over HTTP, each request answered by `answer`. */572const clientOver = (answer: (request: Request) => Promise<Response>) =>573 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(574 Layer.provide(RpcClient.layerProtocolHttp({ url: "http://localhost/rpc" })),575 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),576 Layer.provide(577 Layer.succeed(FetchHttpClient.Fetch, (input, init) =>578 answer(new Request(input, init))579 )580 )581 );582583/** The contracts over a fresh dev world; the world ends with the scope. */584const devWorld = Layer.unwrap(585 Effect.gen(function* () {586 const { dispose, handler } = devServer();587588 yield* Effect.addFinalizer(() => Effect.promise(dispose));589590 return clientOver(handler);591 })592);593594/** A platform that answers the front page and never answers the list of projects. */595const projectsNeverAnswer = Layer.effect(596 Client,597 RpcTest.makeClient(Contracts)598).pipe(599 Layer.provide([600 Layer.mergeAll(601 unanswered,602 Contracts.toLayerHandler("frontPage", () => Effect.succeed({ entries })),603 Contracts.toLayerHandler("listProjects", () => Effect.never)604 ),605 asTester,606 ])607);608609const decodeData = Schema.decodeEffect(FrontPageData);610611/** A fresh dev world seeds itself first, which a full test run can slow past 5 s. */612const seededWorld = { timeout: 30_000 };613614/** The page as the route renders it from what its loader read. */615const sentFrom = (data: FrontPageData, filter: FrontFilter = {}) =>616 renderAt(617 "/",618 <FrontPageView619 entries={data.entries}620 events={621 new Map(data.events.map(({ events, project }) => [project, events]))622 }623 filter={filter}624 now={data.now}625 parents={data.parents}626 platformUrl={platformUrl}627 projects={undefined}628 webUrl={webUrl}629 />630 );631632describe("the front page as the server sends it", () => {633 it.effect(634 "holds every open ask's want as a link, grouped by project, burrow's family as one fan row",635 () =>636 Effect.gen(function* () {637 const data = yield* readFrontPage.pipe(638 Effect.flatMap(decodeData),639 Effect.provide(devWorld)640 );641642 const markup = yield* sentFrom(data);643 const text = textIn(markup);644645 expect(listIn(markup)).not.toContain("Reading from the platform");646 expect(markup).toMatch(647 /<a\b[^>]*href="\/datekit\/asks\/add-months-clamp"[^>]*>[^<]+<\/a>/u648 );649 expect(headersIn(markup).map(([project]) => project)).toStrictEqual([650 "burrow",651 "datekit",652 ]);653 expect(text).toContain("10 open asks, 7 open to take");654655 const family = rowOf(markup, "drop-legacy-fetch");656 const nodes = family.match(/<li class="flex items-center gap-1.5"/gu);657658 expect({659 familyRows: rowsIn(markup).filter(660 (ask) => ask?.startsWith("drop-legacy-fetch") === true661 ),662 nodes: nodes?.length,663 noCommandBox: !listIn(markup).includes("select-all"),664 strip: /0 of 6 landed[\s\S]*Show 6 children/u.test(textIn(family)),665 }).toStrictEqual({666 familyRows: ["drop-legacy-fetch"],667 nodes: 6,668 noCommandBox: true,669 strip: true,670 });671 }),672 seededWorld673 );674675 it.effect(676 "is read without the list of projects, which may never answer",677 () =>678 Effect.gen(function* () {679 const data = yield* readFrontPage.pipe(680 Effect.flatMap(decodeData),681 Effect.provide(projectsNeverAnswer)682 );683684 expect(rowsIn(yield* sentFrom(data))).toHaveLength(3);685 })686 );687});688689describe("the front page's views", () => {690 const sources: Readonly<Record<string, string>> = import.meta.glob(691 "../src/features/front/**/*.{ts,tsx}",692 { eager: true, import: "default", query: "?raw" }
7 unmodified lines
modified:apps/web/test/landings.test.tsx+13 added-1 removed
1/**2 * A project's landings list, rendered to HTML: each landing's subject says3 * what it is and links the ask it answers or the ask it opened; one that4 * did neither reads as what it is.4 * did neither reads as what it is. Its credit is one line of roles, never5 * the trailers again.6 */7import { describe, expect, it } from "@effect/vitest";8import type { LandingView } from "@repo/protocol/domain/landing";9import { AskId, LandedSha } from "@repo/protocol/ids";
55 unmodified lines
65 hrefsOf(item).filter((href) => href.includes("/asks/"))66 ).toStrictEqual([]);67 });68});6970describe("a landing's credit in the list", () => {71 it("is one line of roles in trailer order, each person linked, with no trailer lines", () => {72 const item = itemOf(markup, landing.sha);73 const credit = plainText(item);7475 expect(credit).toMatch(/Asked by ines-v[\s\S]*answered by okafor/u);76 expect(credit).not.toContain("Asked-by:");77 expect(hrefsOf(item)).toContain("/people/ines-v");78 });79});
modified:apps/web/test/llms.test.ts+151 added
24 unmodified lines
25 mcpCard,26 missingProjectLlms,27 projectLlms,28} from "../src/features/agents/llms.ts";29import {30 projectPageHead,31 projectPageHeaders,32} from "../src/routes/$project/index.tsx";33import { frontPageHead, frontPageHeaders } from "../src/routes/index.tsx";34import { llmsFullHandler } from "../src/routes/llms-full[.]txt.ts";35import { frontPageHandler } from "../src/server/front-page.ts";36import { projectPageHandler } from "../src/server/project-page.ts";3738const platformUrl = "https://platform-test.example.workers.dev";3940const webUrl = "https://web-test.example.workers.dev";
403 unmodified lines
444 transport: { endpoint: `${platformUrl}/mcp`, type: "streamable-http" },445 });446 });447});448449/** A platform that lists `listed` as its projects and `listedAsks` as datekit's asks. */450const listingWithAsks =451 (listed: readonly ProjectListing[], listedAsks: readonly AskListing[]) =>452 () =>453 Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(454 Layer.provide([455 Layer.mergeAll(456 unanswered,457 Contracts.toLayerHandler("listProjects", () =>458 Effect.succeed({ projects: listed })459 ),460 Contracts.toLayerHandler("listAsks", () =>461 Effect.succeed({ asks: listedAsks })462 )463 ),464 asTester,465 ])466 );467468/** A request for `path` on the web host, accepting `accept`. */469const getAt = (path: string, accept: string) =>470 new Request(`${webUrl}${path}`, { headers: { accept } });471472const BROWSER =473 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";474475/** What a handler answered: a response, or the page it fell through to. */476const answered = (result: Promise<Response> | "the page") =>477 result === "the page"478 ? Effect.void479 : Effect.flatMap(480 Effect.promise(() => result),481 (response) =>482 Effect.map(read(response), (seen) => ({483 ...seen,484 vary: response.headers.get("vary"),485 }))486 );487488/** The head's link naming `href` as a page's Markdown. */489const alternate = (href: string) => ({490 href,491 rel: "alternate",492 type: "text/markdown",493});494495describe("the list pages, asked for Markdown", () => {496 it.effect("answers / with llms.txt, varied by Accept", () =>497 Effect.gen(function* () {498 const seen = yield* answered(499 frontPageHandler(500 listing(projects),501 platformUrl502 )({503 next: () => "the page" as const,504 request: getAt("/", "text/markdown"),505 })506 );507508 expect(seen).toStrictEqual({509 body: frontLlms({ commands: catalog, platformUrl, projects, webUrl }),510 contentType: "text/markdown; charset=utf-8",511 status: 200,512 vary: "Accept",513 });514 })515 );516517 it.effect(518 "answers /datekit with the project's llms.txt, varied by Accept",519 () =>520 Effect.gen(function* () {521 const seen = yield* answered(522 projectPageHandler(523 listingWithAsks(projects, asks),524 platformUrl525 )({526 next: () => "the page" as const,527 params: { project: "datekit" },528 request: getAt("/datekit", "text/markdown"),529 })530 );531532 expect(seen).toStrictEqual({533 body: projectLlms({534 asks,535 commands: catalog,536 listing: { openAsks: 3, posture: "open", project: datekit },537 platformUrl,538 webUrl,539 }),540 contentType: "text/markdown; charset=utf-8",541 status: 200,542 vary: "Accept",543 });544 })545 );546547 it("gives a browser the page", () => {548 expect(549 frontPageHandler(550 listing(projects),551 platformUrl552 )({553 next: () => "the page" as const,554 request: getAt("/", BROWSER),555 })556 ).toBe("the page");557 expect(558 projectPageHandler(559 listing(projects),560 platformUrl561 )({562 next: () => "the page" as const,563 params: { project: "datekit" },564 request: getAt("/datekit", BROWSER),565 })566 ).toBe("the page");567 });568569 it("names each page's Markdown as an alternate, in its head and its Link header", () => {570 expect(frontPageHeaders()).toMatchObject({571 link: '</llms.txt>; rel="alternate"; type="text/markdown"',572 vary: "Accept",573 });574 expect(frontPageHead().links).toContainEqual(alternate("/llms.txt"));575 expect(576 projectPageHeaders({ params: { project: "datekit" } })577 ).toMatchObject({578 link: '</datekit/llms.txt>; rel="alternate"; type="text/markdown"',579 vary: "Accept",580 });581 expect(582 projectPageHead({ params: { project: "datekit" } }).links583 ).toContainEqual(alternate("/datekit/llms.txt"));584 });585586 it("names no Markdown for a path that can name no project", () => {587 expect(588 projectPageHeaders({ params: { project: "Not_A_Project" } })589 ).toStrictEqual({ vary: "Accept" });590 });591});
modified:apps/web/test/project.test.tsx+648 added-265 removed
1/**2 * A project's page, rendered to HTML with `react-dom/server` from fixtures3 * decoded with the protocol's own schemas: its posture label, how to take4 * part, its open asks (a blocked one names what it waits on) and its recent5 * landings, each with its author and its credit trailers as the commit6 * carries them.2 * A project's home, which is its list of asks: read on the server by the3 * route's loader (its asks, its own ledger, its events, its policy, its4 * README) and rendered inside the router. Its asks come first, a family5 * expanded as a fan with its children listed; then its README; beside them,6 * how a change lands here, with the commands that take part and the last7 * landings as one-line credits. A child that lands while the page is open8 * stamps its node once.9 */10import { describe, expect, it } from "@effect/vitest";11import { Brand } from "@repo/brand";12import { Client, Contracts } from "@repo/protocol/contracts";13import { AskListing } from "@repo/protocol/domain/ask";14import type { Ask } from "@repo/protocol/domain/ask";15import { FileView, TreeListing } from "@repo/protocol/domain/code";16import { Glob } from "@repo/protocol/domain/common";17import type { ProjectEvent } from "@repo/protocol/domain/event";18import { ProjectListing } from "@repo/protocol/domain/front-page";19import { LandingView } from "@repo/protocol/domain/landing";20import { LedgerEntry } from "@repo/protocol/domain/visibility";21import type { Ledger } from "@repo/protocol/domain/visibility";22import {23 AreaName,24 AskId,25 Handle,26 KindName,27 LayerName,28 ProjectName,29} from "@repo/protocol/ids";30import { UnknownRevision } from "@repo/protocol/refusal";31import { asTester, unanswered } from "@repo/protocol/testing";32import { isNotFound } from "@tanstack/react-router";18import { DateTime, Effect, Layer, Schema } from "effect";33import { DateTime, Duration, Effect, Layer, Ref, Schema, Stream } from "effect";34import { FetchHttpClient } from "effect/http";35import { RpcClient, RpcSerialization, RpcTest } from "effect/rpc";21import type { ReactElement } from "react";22import { renderToStaticMarkup } from "react-dom/server";3637import { recentLandings } from "../src/client/events.ts";38import type { DevWorldOptions } from "../src/dev/server.ts";39import { devServer } from "../src/dev/server.ts";40import { ledeOf } from "../src/features/front/head.ts";41import { stampStep } from "../src/features/front/stamps.ts";42import { recentShown } from "../src/features/project/landings.tsx";43import {26 ProjectReadingView,44 ProjectView,45 heldBackOf,46 homeListing,47} from "../src/features/project/project-page.tsx";48import type { ProjectViewProps } from "../src/features/project/project-page.tsx";49import { UnknownProjectView } from "../src/features/project/unknown-project.tsx";50import { askStates } from "../src/features/shared/ask-progress.ts";51import {52 ProjectPageData,53 readProjectPage,33} from "../src/routes/$project/index.tsx";54} from "../src/server/project-page.ts";55import { ask as parseIsoWeek } from "./ask-fixtures.ts";56import { markupOf, textIn, textOf } from "./markup.ts";57import { renderAt } from "./render.tsx";58import { reachingTransport } from "./transport.ts";5936const markupOf = (element: ReactElement) => renderToStaticMarkup(element);3738/** What a reader sees: the markup without its tags, entities decoded. */39const textOf = (element: ReactElement) =>40 markupOf(element)41 .replaceAll(/<[^>]+>/gu, "")42 .replaceAll("&#x27;", "'")43 .replaceAll("&quot;", '"')44 .replaceAll("&lt;", "<")45 .replaceAll("&gt;", ">")46 .replaceAll("&amp;", "&");4748/** The markup of the row for `ask`: from its `<li>` to the next ask's row. */60/** The markup of the row for `ask`: from its `<li>` to the next row or the list's end. */61const rowOf = (markup: string, ask: string) => {62 const start = markup.indexOf(`data-ask="${ask}"`);51 const next = markup.indexOf("data-ask=", start + 1);6353 return start === -154 ? ""55 : markup.slice(start, next === -1 ? undefined : next);64 const ends = ['data-ask="', "</ul></section>", "</main>"].flatMap((end) => {65 const at = markup.indexOf(end, start + 1);6667 return at === -1 ? [] : [at];68 });6970 return start === -1 ? "" : markup.slice(start, Math.min(...ends));71};7273/** Which of `parts` `text` does not hold. */74const missingFrom = (text: string, parts: readonly string[]) =>75 parts.filter((part) => !text.includes(part));7677/** Which of `parts` `text` holds. */78const foundIn = (text: string, parts: readonly string[]) =>79 parts.filter((part) => text.includes(part));8081/** The page's main pane, the inline facts left in (they sit after its head). */82const mainOf = (markup: string) =>83 markup.slice(markup.indexOf("<main"), markup.indexOf("</main>"));8485/** The inspector, as the shell's width shows it. */86const inspectorOf = (markup: string) =>87 markup.slice(markup.indexOf('data-facts="inspector"'));8889const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");9091const platformUrl = "https://platform-test.example.workers.dev";92
14 unmodified lines
107 want: "A week starts on the locale's first day, not always on Sunday.",108 },109 {110 ask: "drop-legacy-parse",80 blockedBy: ["split-core", "split-format"],111 blockedBy: [112 "drop-legacy-parse-core",113 "drop-legacy-parse-format",114 "drop-legacy-parse-delete",115 ],116 claimed: false,117 kind: "migrate",83 territory: "parse",118 territory: ".",119 want: "Nothing calls the legacy parser any more.",120 },121 {122 ask: "drop-legacy-parse-core",123 blockedBy: [],124 claimed: false,125 kind: "migrate",126 territory: "core",127 want: "core: 2 callers of legacyParse → parse",128 },129 {130 ask: "drop-legacy-parse-format",131 blockedBy: [],132 claimed: true,133 kind: "migrate",134 territory: "format",135 want: "format: 1 caller of legacyParse → parse",136 },137 {138 ask: "drop-legacy-parse-delete",139 blockedBy: ["drop-legacy-parse-core", "drop-legacy-parse-format"],140 claimed: false,141 kind: "migrate",142 territory: ".",143 want: "Delete legacyParse: nothing calls it any more",144 },145 {146 ask: "trim-week-names",147 blockedBy: ["fix-week-start"],148 claimed: false,149 kind: "bug",150 reserve: "newcomers",151 territory: "core",152 want: "Week names are trimmed.",153 },154]);15588const landings = Schema.decodeSync(Schema.Array(LandingView))([89 {90 ask: "parse-iso-week",91 assisted: [{ harness: "claude-code", verified: true }],92 author: "bram",156const parent: Ask = {157 ...parseIsoWeek,158 blockedBy: [159 AskId.make("drop-legacy-parse-core"),160 AskId.make("drop-legacy-parse-format"),161 AskId.make("drop-legacy-parse-delete"),162 ],163 brief: { want: "Nothing calls the legacy parser any more." },164 id: AskId.make("drop-legacy-parse"),165 kind: KindName.make("migrate"),166};167168/** A landing of `ask` (or an opening of it), credited to `answerer`. */169const landingOf = (170 sha: string,171 more: { readonly ask?: string; readonly opened?: string },172 answerer?: string173) =>174 Schema.decodeSync(LandingView)({175 ...more,176 assisted: [],177 author: answerer ?? "ines-v",178 credits: [94 { handle: "bram", role: "Signed-off-by" },179 { handle: "ines-v", role: "Asked-by" },180 ...(answerer === undefined181 ? []182 : [{ handle: answerer, role: "Signed-off-by" as const }]),183 ],184 landedAt: "2026-10-06T09:00:00.000Z",98 parent: "1111111111111111111111111111111111111111",185 parent: "2".repeat(40),186 project: "datekit",100 sha: "9b1c3e5d7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c",101 },102 {103 ask: "format-era",104 assisted: [],105 author: "okonkwo",106 credits: [107 { handle: "okonkwo", role: "Signed-off-by" },108 { handle: "lin-h", role: "Asked-by" },109 ],110 landedAt: "2026-10-04T09:00:00.000Z",111 parent: "2222222222222222222222222222222222222222",112 project: "datekit",113 sha: "1111111111111111111111111111111111111111",114 },115]);187 sha: sha.repeat(40),188 });189117const page = (118 <ProjectView119 asks={asks}120 landings={landings}121 listing={listing}122 now={now}123 platformUrl={platformUrl}124 />125);190const landings = [191 landingOf("a", { ask: "parse-iso-week" }, "bram"),192 landingOf("b", { opened: "format-ordinal" }),193 landingOf("c", { ask: "format-era" }, "okonkwo"),194 landingOf("d", { opened: "add-months-clamp" }),195];196197const AT = "a".repeat(40);198199const root = Schema.decodeSync(TreeListing)({200 at: AT,201 entries: [202 {203 mode: "040000",204 name: "src",205 path: "src",206 sha: "b".repeat(40),207 type: "tree",208 },209 {210 mode: "100644",211 name: "README.md",212 path: "README.md",213 sha: "c".repeat(40),214 type: "blob",215 },216 ],217 readme: { path: "README.md", sha: "c".repeat(40) },218});219220const readme = Schema.decodeSync(FileView)({221 at: AT,222 binary: false,223 path: "README.md",224 sha: "c".repeat(40),225 size: 26,226 text: "# datekit\n\nDates, kept.\n",227 truncated: false,228});229230const vellumLedger: Ledger = {231 entries: [232 LedgerEntry.cases.CountChanged.make({233 area: AreaName.make("export"),234 at: now,235 count: 7,236 layer: LayerName.make("maintainers"),237 seq: 1,238 }),239 ],240 layers: [],241 posture: "openWithSealedEvidence",242 postureLabel: "Open with sealed evidence",243 project: ProjectName.make("vellum"),244};245246const props = (more: Partial<ProjectViewProps> = {}): ProjectViewProps => ({247 asks,248 landings,249 listing,250 now,251 parents: [parent],252 platformUrl,253 ...more,254});255256const page = (more: Partial<ProjectViewProps> = {}) =>257 renderAt("/datekit", <ProjectView {...props(more)} />);258259describe(ProjectView, () => {128 it("shows each landing's subject line and links its author to their page", () => {129 const text = textOf(page);130 const markup = markupOf(page);260 it.effect(261 "lists every open ask with its want as the link, then its kind, territory and id",262 () =>263 Effect.gen(function* () {264 const row = rowOf(yield* page(), "fix-week-start");265132 expect(text).toContain("Answer parse-iso-week");133 expect(text).toContain("Answer format-era");134 expect(markup).toMatch(/<a\b[^>]*href="\/people\/bram"[^>]*>bram<\/a>/u);135 expect(markup).toMatch(136 /<a\b[^>]*href="\/people\/okonkwo"[^>]*>okonkwo<\/a>/u137 );138 });266 expect(row).toMatch(267 /<a\b[^>]*href="\/datekit\/asks\/fix-week-start"[^>]*>A week starts on the locale&#x27;s first day, not always on Sunday\.<\/a>/u268 );269 expect(textIn(row)).toContain("bug · core · fix-week-start");270 expect(textIn(row)).toContain("Open to take");271 expect(textIn(row)).toContain(272 `${Brand.cli} claim fix-week-start --project datekit`273 );274 })275 );276140 it("shows each landing's credit trailers as the commit carries them, Assisted-by apart", () => {141 const text = textOf(page);277 it.effect(278 "draws a family as its parent's row with the fan, its children listed under it",279 () =>280 Effect.gen(function* () {281 const markup = yield* page();282 const family = rowOf(markup, "drop-legacy-parse");283143 const at = [144 "Asked-by: ines-v",145 "Signed-off-by: bram",146 "not credit",147 "Assisted-by: claude-code (verified)",148 "Asked-by: lin-h",149 "Signed-off-by: okonkwo",150 ].map((part) => text.indexOf(part));284 expect(family).toContain('data-family="drop-legacy-parse"');285 expect(286 missingFrom(textIn(family), [287 "0 of 2 landed",288 "Hide 2 children",289 "core: 2 callers of legacyParse → parse",290 "delete waits for 2",291 ])292 ).toStrictEqual([]);293 expect(family.match(/data-family-child="/gu)).toHaveLength(2);294 // Its members are drawn in the fan, not again as rows of their own.295 expect(296 foundIn(markup, [297 'data-ask="drop-legacy-parse-core"',298 'data-ask="drop-legacy-parse-delete"',299 ])300 ).toStrictEqual([]);301 })302 );303152 // Each landing's credit in trailer order, then its agents, apart.153 expect(at.every((position) => position >= 0)).toBeTruthy();154 expect(at.toSorted((one, other) => one - other)).toStrictEqual(at);155 });304 it.effect(305 "reads an ask that waits on another as waiting, with the one it waits on listed",306 () =>307 Effect.gen(function* () {308 const markup = yield* page();309 const row = rowOf(markup, "trim-week-names");310157 it("shows a blocked ask as blocked, linking every ask it waits on", () => {158 const markup = markupOf(page);159 const row = rowOf(markup, "drop-legacy-parse");311 expect(textIn(row)).toContain("Waiting");312 expect(row).not.toContain(`${Brand.cli} claim trim-week-names`);313 expect(markup).toContain('data-ask="fix-week-start"');314 })315 );316161 expect(row).toMatch(/Blocked/u);162 expect(row).toContain('href="/datekit/asks/split-core"');163 expect(row).toContain('href="/datekit/asks/split-format"');164 });317 it.effect(318 "says its posture once, in the platform's words, then its open asks and when it last landed",319 () =>320 Effect.gen(function* () {321 const markup = yield* page({322 postureLabel: "Open with sealed evidence · sealed checks in export",323 });324166 it("lists every open ask with its want, kind and territory", () => {167 const row = rowOf(markupOf(page), "fix-week-start");325 const head = markup.slice(326 markup.indexOf("<h1"),327 markup.indexOf('id="open-asks"')328 );329169 expect(row).toContain('href="/datekit/asks/fix-week-start"');170 expect(row).toContain(171 "A week starts on the locale&#x27;s first day, not always on Sunday."172 );173 expect(row).toMatch(/>Kind<\/dt><dd\b[^>]*>bug<\/dd>/u);174 expect(row).toMatch(/>Territory<\/dt><dd\b[^>]*>core<\/dd>/u);175 });330 expect(head).toContain('data-posture="openWithSealedEvidence"');331 expect(textIn(head)).toContain(332 "Open with sealed evidence · sealed checks in export"333 );334 expect(textIn(head)).toContain("5 open asks");335 expect(textIn(head)).toContain("last landed 1 d ago");336 // The delete child waits on its siblings, so it is not counted open yet.337 expect(textIn(markup)).toContain("5 open asks, 2 open to take");338 })339 );340177 it("shows the posture label of the project as it is listed", () => {178 const markup = markupOf(page);341 it.effect(342 "says how a change lands here: the posture, the gate, who decides, what is held back",343 () =>344 Effect.gen(function* () {345 const facts = inspectorOf(346 yield* page({347 deciders: [348 {349 handles: [Handle.make("ines-v"), Handle.make("okonkwo")],350 paths: Glob.make("src/**"),351 },352 ],353 heldBack: heldBackOf(vellumLedger),354 })355 );356180 expect(markup).toContain('data-posture="openWithSealedEvidence"');181 expect(textOf(page)).toContain("Open with sealed evidence");182 });357 const text = textIn(facts);358184 it("shows how to take part: clone over plain git, then the CLI's asks, claim and check", () => {185 const text = textOf(page);359 expect(360 missingFrom(text, [361 "How a change lands here",362 "Parse · Shape · Merge · Cheap · Checks · Held-back · Decider",363 "export: 7 sealed checks",364 ])365 ).toStrictEqual([]);366 expect(text).toMatch(/src\/\*\*\s*·\s*ines-v, okonkwo/u);367 expect(368 missingFrom(facts, [369 'href="/datekit/people"',370 'href="/datekit/llms.txt"',371 ])372 ).toStrictEqual([]);373 })374 );375187 expect(text).toContain(`git clone ${platformUrl}/datekit.git`);188 expect(text).toContain(`${Brand.cli} asks --project datekit`);189 expect(text).toContain(`${Brand.cli} claim <ask>`);190 expect(text).toContain(`${Brand.cli} check`);191 });376 it.effect(377 "gives the four commands that take part, numbered, and the last three landings as one-line credits",378 () =>379 Effect.gen(function* () {380 const facts = inspectorOf(yield* page());381 const text = textIn(facts);382193 it("says an empty project is empty, with the commands that would fill it", () => {194 const { landedAt: _landed, ...unlanded } = listing;383 const steps = [384 `git clone ${platformUrl}/datekit.git`,385 `${Brand.cli} asks --project datekit`,386 `${Brand.cli} claim <ask>`,387 `${Brand.cli} check`,388 ].map((command) => text.indexOf(command));389196 const text = textOf(197 <ProjectView198 asks={[]}199 landings={[]}200 listing={{ ...unlanded, openAsks: 0 }}201 now={now}202 platformUrl={platformUrl}203 />204 );390 expect(steps.every((at) => at >= 0)).toBeTruthy();391 expect(steps.toSorted((a, b) => a - b)).toStrictEqual(steps);392 expect(facts.match(/data-landing="/gu)).toHaveLength(3);393 expect(394 missingFrom(text, [395 "Answer parse-iso-week",396 "Asked by ines-v · answered by bram",397 ])398 ).toStrictEqual([]);399 expect(text).not.toContain("Asked-by: ines-v");400 })401 );402206 expect(text).toContain("No open asks");207 expect(text).toContain(`${Brand.cli} ask open`);208 expect(text).toContain("Nothing has landed");209 // The project exists, so `init` would refuse it: its first push lands main.210 expect(text).toContain(`git push ${platformUrl}/datekit.git HEAD:main`);211 expect(text).not.toContain(`${Brand.cli} init`);212 });403 it.effect(404 "has no code table and no clone box: the Code section has those",405 () =>406 Effect.gen(function* () {407 const markup = yield* page({ code: { readme, root } });408 const main = mainOf(markup);409214 it("never says nothing has landed on a project whose main has landed", () => {215 const text = textOf(216 <ProjectView217 asks={asks}218 landings={[]}219 listing={listing}220 now={now}221 platformUrl={platformUrl}222 />223 );410 expect(main).not.toContain('href="/datekit/tree/main/src"');411 expect(main).not.toContain("data-clone");412 expect(main).toContain('data-readme="README.md"');413 expect(textIn(main)).toContain("Dates, kept.");414 // The README comes after the asks.415 expect(main.indexOf('id="open-asks"')).toBeLessThan(416 main.indexOf("data-readme")417 );418 })419 );420225 expect(text).toContain("Last landed");226 expect(text).not.toContain("Nothing has landed");227 expect(text).not.toContain("git push");228 });229});421 it.effect(422 "says an empty project is empty, with the commands that would fill it",423 () =>424 Effect.gen(function* () {425 const { landedAt: _landed, ...unlanded } = listing;426231describe("the project's code on its page", () => {232 const AT = "a".repeat(40);427 const text = textIn(428 yield* page({429 asks: [],430 landings: [],431 listing: { ...unlanded, openAsks: 0 },432 })433 );434234 const root = Schema.decodeSync(TreeListing)({235 at: AT,236 entries: [237 {238 mode: "040000",239 name: "src",240 path: "src",241 sha: "b".repeat(40),242 type: "tree",243 },244 {245 mode: "100644",246 name: "README.md",247 path: "README.md",248 sha: "c".repeat(40),249 type: "blob",250 },251 ],252 readme: { path: "README.md", sha: "c".repeat(40) },253 });435 expect(text).toContain("No open asks");436 expect(text).toContain(`${Brand.cli} ask open`);437 expect(text).toContain("Nothing has landed");438 // The project exists, so `init` would refuse it: its first push lands main.439 expect(text).toContain(`git push ${platformUrl}/datekit.git HEAD:main`);440 expect(text).not.toContain(`${Brand.cli} init`);441 })442 );443255 const readme = Schema.decodeSync(FileView)({256 at: AT,257 binary: false,258 path: "README.md",259 sha: "c".repeat(40),260 size: 26,261 text: "# datekit\n\nDates, kept.\n",262 truncated: false,263 });444 it.effect(445 "never says nothing has landed on a project whose main has landed",446 () =>447 Effect.gen(function* () {448 const text = textIn(yield* page({ landings: [] }));449265 const withCode = (266 <ProjectView267 asks={asks}268 code={{ readme, root }}269 landings={landings}270 listing={listing}271 now={now}272 platformUrl={platformUrl}273 />450 expect(text).toContain("last landed");451 expect(text).not.toContain("Nothing has landed");452 expect(text).not.toContain("git push");453 })454 );455276 it("shows the clone line in a box of its own, above the asks", () => {277 const markup = markupOf(withCode);278 const clone = markup.indexOf('data-clone=""');456 it("draws the same page with no router around it, nothing selected", () => {457 const text = textOf(<ProjectView {...props()} />);458280 expect(clone).toBeGreaterThan(-1);281 expect(282 markup.indexOf(`git clone ${platformUrl}/datekit.git`, clone)283 ).toBeGreaterThan(clone);284 expect(clone).toBeLessThan(markup.indexOf('id="open-asks"'));459 expect(text).toContain("How a change lands here");460 expect(text).toContain("fix-week-start");461 });462});463287 it("lists the root's entries, each linking its page at main", () => {288 const markup = markupOf(withCode);464describe(recentShown, () => {465 it("shows the last three answers once three have landed, the setup's landings dropped", () => {466 const answers = [467 landingOf("1", { ask: "one" }, "bram"),468 landingOf("2", { opened: "two" }),469 landingOf("3", { ask: "three" }, "bram"),470 landingOf("4", { ask: "four" }, "bram"),471 landingOf("5", {}),472 ];473290 expect(markup).toContain('href="/datekit/tree/main/src"');291 expect(markup).toContain('href="/datekit/blob/main/README.md"');474 expect(recentShown(answers).map(({ ask }) => ask)).toStrictEqual([475 "one",476 "three",477 "four",478 ]);479 });480294 it("renders the root README", () => {295 expect(markupOf(withCode)).toContain('data-readme="README.md"');296 expect(textOf(withCode)).toContain("Dates, kept.");481 it("shows the last three of any kind before three answers have landed", () => {482 expect(recentShown(landings).map(({ sha }) => sha[0])).toStrictEqual([483 "a",484 "b",485 "c",486 ]);487 });488});489299 it("shows no code section before the code is read", () => {300 expect(markupOf(page)).not.toContain("data-readme=");490describe(ledeOf, () => {491 it("is a README's first sentence, past its title, as plain words", () => {492 expect(493 ledeOf(494 "# datekit\n\nSmall, dependency-free date helpers for `TypeScript`. datekit reads ISO 8601 text.\n"495 )496 ).toBe("Small, dependency-free date helpers for TypeScript.");497 expect(498 ledeOf(499 "# burrow\n\nThe services behind [burrow's](https://x.test) shop: six packages.\n"500 )501 ).toBe("The services behind burrow's shop: six packages.");502 });503504 it("is none when the README opens with no prose", () => {505 expect(ledeOf("# title\n\n| a | b |\n| - | - |\n")).toBeUndefined();506 });507});508509/** The contracts over HTTP, each request answered by `answer`. */510const clientOver = (answer: (request: Request) => Promise<Response>) =>
7 unmodified lines
518 )519 );520521/**317 * The contracts over a fresh dev world, as the Worker's loader reaches318 * them in process; the world ends with the scope.522 * `handler`, but with the list of projects failing when `listed` counts its523 * calls.524 */320const devWorld = Layer.unwrap(321 Effect.gen(function* () {322 const { dispose, handler } = devServer();525const failingProjects =526 (527 handler: (request: Request) => Promise<Response>,528 listed: Ref.Ref<number> | undefined529 ) =>530 (request: Request) =>531 Effect.runPromise(532 Effect.gen(function* () {533 const body = yield* Effect.promise(() => request.clone().text());534324 yield* Effect.addFinalizer(() => Effect.promise(dispose));535 if (listed !== undefined && body.includes('"listProjects"')) {536 yield* Ref.update(listed, (count) => count + 1);537326 return clientOver(handler);327 })328);538 return new Response("", { status: 503 });539 }540541 return yield* Effect.promise(() => handler(request));542 })543 );544545/**546 * A fresh dev world with `options`, served; with `listed`, its list of547 * projects fails and each call to it is counted. The world ends with the548 * scope.549 */550const devWorldWith = (options: DevWorldOptions, listed?: Ref.Ref<number>) =>551 Layer.unwrap(552 Effect.gen(function* () {553 const { dispose, handler } = devServer(options);554555 yield* Effect.addFinalizer(() => Effect.promise(dispose));556557 return clientOver(failingProjects(handler, listed));558 })559 );560561const devWorld = devWorldWith({});562563/** A platform that does not answer: every call comes back a 503. */564const unanswering = clientOver(() =>565 Promise.resolve(new Response("", { status: 503 }))566);
4 unmodified lines
571 Layer.mergeAll(572 unanswered,573 Contracts.toLayerHandler("readTree", ({ at }) =>574 Effect.fail(new UnknownRevision({ rev: at ?? "main" }))342 )575 ),576 Contracts.toLayerHandler("listAsks", () => Effect.succeed({ asks: [] }))577 ),578 asTester,579 ])580);
2 unmodified lines
583584/** A fresh dev world seeds itself first, which a full test run can slow past 5 s. */585const seededWorld = { timeout: 30_000 };586587/** The page as the route draws it from what its loader read. */588const sentFrom = (589 data: ProjectPageData,590 more: Partial<ProjectViewProps> = {}591) => {592 const events = data.events ?? [];593 const [latest] = recentLandings(events);594595 return renderAt(596 `/${data.project}`,597 <ProjectView598 asks={data.asks}599 code={data.code}600 deciders={data.policy?.policy?.deciders}601 heldBack={data.ledger === undefined ? undefined : heldBackOf(data.ledger)}602 landings={recentLandings(events)}603 lastLanded={latest?.landedAt}604 listing={homeListing({605 asks: data.asks,606 ledger: data.ledger,607 project: data.project,608 })}609 now={data.now}610 parents={data.parents}611 platformUrl={platformUrl}612 postureLabel={data.ledger?.postureLabel}613 states={askStates(events)}614 {...more}615 />616 );617};618619const readFrom = (name: string, world: Layer.Layer<Client>) =>620 readProjectPage(name).pipe(Effect.flatMap(decodePage), Effect.provide(world));621353describe("the project's page as the server sends it", () => {622describe("the project's home as the server sends it", () => {623 it.effect(355 "carries datekit's README and its root entries, read on the server",624 "carries datekit's asks and its README, with no code table and no clone box",625 () =>626 Effect.gen(function* () {358 const { code } = yield* readProjectPage("datekit").pipe(359 Effect.flatMap(decodePage),360 Effect.provide(devWorld)361 );627 const data = yield* readFrom("datekit", devWorld);628 const markup = yield* sentFrom(data);629 const main = mainOf(markup);630363 const sent = (364 <ProjectReadingView365 code={code}366 platformUrl={platformUrl}367 project={listing.project}368 />631 expect(main).toMatch(632 /<a\b[^>]*href="\/datekit\/asks\/add-months-clamp"[^>]*>[^<]+<\/a>/u633 );634 expect(635 missingFrom(main, [636 "Small, dependency-free date helpers",637 'data-readme="README.md"',638 ])639 ).toStrictEqual([]);640 expect(641 foundIn(main, [642 'href="/datekit/tree/main/src"',643 "data-clone",644 "Reading from the platform",645 ])646 ).toStrictEqual([]);647371 expect(textOf(sent)).toContain("Small, dependency-free date helpers");372 expect(markupOf(sent)).toContain('data-readme="README.md"');373 expect(markupOf(sent)).toContain('href="/datekit/tree/main/src"');374 expect(textOf(sent)).toContain(`git clone ${platformUrl}/datekit.git`);648 const facts = inspectorOf(markup);649650 expect(textIn(facts)).toContain("How a change lands here");651 expect(652 (facts.match(/data-landing="/gu) ?? []).length653 ).toBeLessThanOrEqual(3);654 }),655 seededWorld656 );657658 it.effect(380 "shows a project whose main has not landed with no code, and no error",659 "draws burrow's family expanded, its six children listed",660 () =>661 Effect.gen(function* () {383 const { code } = yield* readProjectPage("datekit").pipe(384 Effect.flatMap(decodePage),385 Effect.provide(nothingLanded)662 const data = yield* readFrom("burrow", devWorld);663664 const family = rowOf(665 mainOf(yield* sentFrom(data)),666 "drop-legacy-fetch"667 );668388 expect(code).toBeUndefined();669 expect(family.match(/data-family-child="/gu)).toHaveLength(6);670 expect(textIn(family)).toContain("0 of 6 landed");671 expect(textIn(family)).toContain("Hide 6 children");672 }),673 seededWorld674 );675390 const sent = (391 <ProjectReadingView392 code={code}393 platformUrl={platformUrl}394 project={listing.project}395 />396 );676 it.effect(677 "takes its posture from the project's own ledger, never the list of projects",678 () =>679 Effect.gen(function* () {680 const listed = yield* Ref.make(0);681398 const shown = (399 <ProjectView400 asks={asks}401 code={code}402 landings={[]}403 listing={listing}404 now={now}405 platformUrl={platformUrl}406 />682 const data = yield* readFrom(683 "vellum",684 devWorldWith({ fixtures: "on" }, listed)685 );686409 expect(markupOf(sent)).not.toContain('id="code"');410 expect(markupOf(shown)).not.toContain('id="code"');411 expect(rowOf(markupOf(shown), "fix-week-start")).toContain(412 'href="/datekit/asks/fix-week-start"'413 );414 })687 const head = mainOf(yield* sentFrom(data));688689 expect(yield* Ref.get(listed)).toBe(0);690 expect(head).toContain('data-posture="openWithSealedEvidence"');691 expect(textIn(head)).toContain("Open with sealed evidence");692 }),693 seededWorld694 );695696 it.effect(418 "is sent without its code, not as a not-found, when the platform does not answer",697 "says no posture while its own ledger is unread, never one it was not told",698 () =>699 Effect.gen(function* () {421 const { code } = yield* readProjectPage("datekit").pipe(422 Effect.flatMap(decodePage),423 Effect.provide(unanswering)700 const { ledger: _unread, ...data } = yield* readFrom(701 "vellum",702 devWorldWith({ fixtures: "on" })703 );704705 const markup = yield* sentFrom(data);706707 expect({708 badges: markup.match(/data-posture="/gu)?.length ?? 0,709 open: textIn(inspectorOf(markup)).includes("Everything it ships"),710 }).toStrictEqual({ badges: 0, open: false });711 }),712 seededWorld713 );714715 it.effect(716 "is sent without its asks and code, not as a not-found, when the platform does not answer",717 () =>718 Effect.gen(function* () {719 const { asks: read, code } = yield* readFrom("datekit", unanswering);720721 expect(read).toBeUndefined();722 expect(code).toBeUndefined();723 })724 );725726 it.effect(727 "shows a project whose main has not landed with no code, and no error",728 () =>729 Effect.gen(function* () {730 const data = yield* readFrom("datekit", nothingLanded);731732 expect(data.code).toBeUndefined();733 expect(mainOf(yield* sentFrom(data))).not.toContain("data-readme");734 })735 );736737 it.effect.each(["no-such-project", "Not_A_Project"])(738 "is a not-found for %s, which the platform does not know",739 (name) =>740 Effect.gen(function* () {
6 unmodified lines
747 seededWorld748 );749});750751const vellum = ProjectName.make("vellum");752753describe("a family child landing while the page is open", () => {754 it.live(755 "stamps nothing the first read holds, then stamps the child that landed, once, and moves the count",756 () =>757 Effect.gen(function* () {758 const world = devWorldWith({759 fixtures: "live",760 liveAfter: Duration.zero,761 });762763 const [data, later] = yield* Effect.gen(function* () {764 const first = yield* readProjectPage("vellum").pipe(765 Effect.flatMap(decodePage)766 );767768 const client = yield* Client;769770 const second: readonly ProjectEvent[] = yield* Stream.runCollect(771 client.watch({ project: vellum, since: 0 })772 );773774 return [first, second] as const;775 }).pipe(Effect.provide(world));776777 const mounted = stampStep(undefined, data.events ?? []);778 const read = stampStep(mounted, later);779 const again = stampStep(read, later);780781 expect([...mounted.stamped]).toStrictEqual([]);782 expect([...read.stamped]).toStrictEqual([783 "retire-old-tokenizer-vellum-lint",784 ]);785 expect(again.stamped).toBe(read.stamped);786787 const before = rowOf(788 mainOf(yield* sentFrom(data, { stamps: mounted.stamped })),789 "retire-old-tokenizer"790 );791792 const after = rowOf(793 mainOf(794 yield* sentFrom(795 { ...data, events: later },796 { stamps: read.stamped }797 )798 ),799 "retire-old-tokenizer"800 );801802 expect({803 after: textIn(after).includes("3 of 6 landed"),804 before: textIn(before).includes("2 of 6 landed"),805 stampedAfter: after.match(/animate-stamp/gu)?.length,806 stampedBefore: before.includes("animate-stamp"),807 }).toStrictEqual({808 after: true,809 before: true,810 // The child's node in the fan, and its row in the list under it.811 stampedAfter: 2,812 stampedBefore: false,813 });814 }),815 seededWorld816 );817});818819describe(UnknownProjectView, () => {445 it("shows the platform's UnknownProject refusal for a name that could be a project", () => {446 const markup = markupOf(<UnknownProjectView name="no-such-project" />);820 it.effect(821 "shows the platform's UnknownProject refusal for a name that could be a project, and the way onward",822 () =>823 Effect.gen(function* () {824 const markup = yield* renderAt(825 "/no-such-project",826 <UnknownProjectView name="no-such-project" />827 );828448 expect(markup).toContain('data-refusal="UnknownProject"');449 expect(markup).toContain("no-such-project");450 });829 expect(markup).toContain('data-refusal="UnknownProject"');830 expect(markup).toContain("no-such-project");831 expect(markup).toMatch(/<a\b[^>]*href="\/"[^>]*>Open asks<\/a>/u);832 })833 );834835 it("says in a sentence that an address naming no possible project names none", () => {836 const markup = markupOf(<UnknownProjectView name="Not_A_Project" />);837
18 unmodified lines