Merge branch 'build/911-web-propose-and-proposal'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents a0c8f4f, 91bdc90 · Browse files · 15 files·+1997 added−77 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+1997 added−77 removed
- tests:+692 added−1 removed
- other:+1305 added−76 removed
Provenance
- Commit
bcb4cd9- Tree
e9e774c- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
a0c8f4f- Parent 2
91bdc90
15 files changed+1997 added−77 removed
added:apps/web/src/client/proposal.ts+71 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071/** * A proposal's reads and its one write. `proposalAtom` reads `showProposal` * (its draft's state and the files it holds), keyed by `keys.proposal`, * which a `ProposalDrafted` event invalidates (`watch.ts`), so the page * follows a draft from Drafting to Ready or Failed. `draftAtom` is the * proposer's or a decider's "Draft again" over `draftAsk`. * * The decider's Today in one project lives here too, as the proposal page * reads it: it holds the open decision on the proposal (within the day's * budget), and it answers only a decider (`NotDecider` otherwise); it reads * again when the project's keys change, as a settled draft changes them. Each read * renders as waiting on the server, so the Worker reads none of them for a * page that draws them in the browser. */import type { DraftAsk } from "@repo/protocol/contracts";import type { ProjectName, ProposalId } from "@repo/protocol/ids";import { Effect } from "effect";import { Atom, Reactivity } from "effect/reactivity";
import { ContractsClient } from "../surfaces.ts";import { keys } from "./keys.ts";
/** One proposal and the files it holds: `proposalAtom(project)(proposal)`. */export const proposalAtom = Atom.family((project: ProjectName) => Atom.family((proposal: ProposalId) => Atom.withServerValueInitial( ContractsClient.query( "showProposal", { project, proposal }, { reactivityKeys: keys.proposal(project, proposal) } ) ) ));
/** * The reader's Today in `project`, when they decide there. A draft that * settles puts its decision up, so the project's keys (which a * `ProposalDrafted` changes, through `keys.proposal`) read it again too. */export const projectTodayAtom = Atom.family((project: ProjectName) => Atom.withServerValueInitial( ContractsClient.query( "today", { project }, { reactivityKeys: [...keys.today(), ...keys.project(project)] } ) ));
/** * Draft a proposal's ask again: `{ project, proposal, note? }`, answered * with the proposal as it now stands (Drafting). The proposal reads again * on success, and on `DraftInProgress` or `ProposalClosed` too, since then * the page shows a stale state. */export const draftAtom = ContractsClient.runtime.fn< typeof DraftAsk.payloadSchema.Type>()( Effect.fnUntraced(function* (input) { const client = yield* ContractsClient; const changed = keys.proposal(input.project, input.proposal);
return yield* client("draftAsk", input).pipe( Reactivity.mutation(changed), Effect.tapErrorTag(["DraftInProgress", "ProposalClosed"], () => Reactivity.invalidate(changed) ) ); }));added:apps/web/src/client/propose.ts+72 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172/** * The propose form's read and write. `modulesAtom` lists the territories * the form offers: the project's top folders at main, from `listPaths` * (dot folders, the config folder among them, are no territory). A project * with nothing landed yet refuses the read, and the form offers none. * `proposeAtom` sends `proposeAsk`; the project's proposals change, so its * key reads again. */import type { ProposeAsk } from "@repo/protocol/contracts";import { RepoPath } from "@repo/protocol/ids";import type { ProjectName, ProposalId } from "@repo/protocol/ids";import { Array, Effect, Option, Order, Schema } from "effect";import { AsyncResult, Atom, Reactivity } from "effect/reactivity";
import { ContractsClient } from "../surfaces.ts";import { keys } from "./keys.ts";
const decodePath = Schema.decodeUnknownOption(RepoPath);
/** The top folders among `paths`, sorted, without dot folders. */export const topFolders = (paths: readonly RepoPath[]): readonly RepoPath[] => { const folders = paths.flatMap((path): readonly RepoPath[] => { const slash = path.indexOf("/");
return slash <= 0 || path.startsWith(".") ? [] : Option.toArray(decodePath(path.slice(0, slash))); });
return Array.sort(Array.dedupe(folders), Order.String);};
/** The project's top folders at main, each a territory the form offers. */export const modulesAtom = Atom.family((project: ProjectName) => Atom.withServerValueInitial( ContractsClient.runtime.factory.withReactivity(keys.code(project))( ContractsClient.runtime.atom( Effect.gen(function* () { const client = yield* ContractsClient; const { paths } = yield* client("listPaths", { at: "main", project });
return topFolders(paths); }) ) ) ));
/** * The proposal the last send made, once it answered. While a later send is * on its way, or after it was refused, the atom still holds an earlier * send's proposal, which names none here: the form never moves to it. */export const proposalMade = ( result: AsyncResult.AsyncResult<typeof ProposeAsk.successSchema.Type, unknown>): Option.Option<ProposalId> => AsyncResult.isSuccess(result) && !result.waiting ? Option.some(result.value.proposal.id) : Option.none();
/** Propose an ask: `proposeAsk`'s payload, answered with the proposal. */export const proposeAtom = ContractsClient.runtime.fn< typeof ProposeAsk.payloadSchema.Type>()( Effect.fnUntraced(function* (input) { const client = yield* ContractsClient;
return yield* client("proposeAsk", input).pipe( Reactivity.mutation(keys.project(input.project)) ); }));modified:apps/web/src/features/decision/decision-card.tsx+169 added-51 removed
3 unmodified lines4 * and when, and one button per choice its subject allows. A note is5 * optional. A `Finish` decision links to the answer's diff; no other6 * decision shows one, and the card never shows the diff itself.7 *8+ * An `OpenProposal` shows the files the proposal would add (the ask file and9+ * its check) as code under their paths, links the proposal's page, and holds10+ * Accept while the platform's agent is drafting the proposal again: the11+ * draft state is passed in, or read from `showProposal` when it is not.12+ *13 * The subject's words follow GLOSSARY.md (ask, answer, landing, finish,14 * vouch). The default's word is the decision's `default` field as the15 * platform set it: the web keeps no table of defaults by subject.16 */17 import type { Decide } from "@repo/protocol/contracts";18+import type { Evidence as Fact } from "@repo/protocol/domain/common";19 import { DecisionSubject } from "@repo/protocol/domain/decision";20 import type { Choice, Decision } from "@repo/protocol/domain/decision";21+import { DraftState } from "@repo/protocol/domain/proposal";22+import type { ProjectName, ProposalId } from "@repo/protocol/ids";23 import { DateTime, Option } from "effect";16-import { FileDiff, Hourglass, ShieldCheck } from "lucide-react";24+import { FileDiff, FileText, Hourglass, ShieldCheck } from "lucide-react";25 import { useId, useState } from "react";26 import type { ReactNode } from "react";27 28 import { Button } from "../../components/ui/button.tsx";29+import { Spinner } from "../../components/ui/spinner.tsx";30 import { Textarea } from "../../components/ui/textarea.tsx";31 import {32 changedFiles,33 isFinishDecision,34 PATCH_LABEL,35 patchOf,36 } from "../finish/patch.ts";37+import { DraftedCode } from "../proposal/client-file.tsx";38+import { useLiveDraft } from "../proposal/live-draft.ts";39 import { When } from "../shared/time.tsx";40 41 /** What a decider sends when they choose: the `decide` contract's payload, from its one schema. */42 export type DecideInput = typeof Decide.payloadSchema.Type;71 unmodified lines114 decline: "Decline",115 revert: "Revert",116 } as const satisfies Record<Choice, string>;117 118+/** Whether a decision opens a proposed ask. */119+const opensAsk = DecisionSubject.isAnyOf(["OpenProposal"]);120+121+/** Whether a draft is still being written. */122+const isDraftingNow = DraftState.isAnyOf(["Drafting"]);123+124+/**125+ * Whether an evidence line holds a file: its label is a path (one word with126+ * a slash or a dot, as the ask file under the config folder, or a check127+ * at the root, `offset.test.ts`), where every other label is words.128+ */129+const isFileFact = ({ label }: Fact) => /^\S*[./]\S*$/u.test(label);130+131+/** The files an `OpenProposal` decision holds, shown as code; none for any other subject. */132+const filesOf = (decision: Decision): readonly Fact[] =>133+ opensAsk(decision.subject) ? decision.evidence.filter(isFileFact) : [];134+135+const Facts = ({ facts }: { readonly facts: readonly Fact[] }) => (136+ <dl className="grid grid-cols-1 gap-x-4 gap-y-1 sm:grid-cols-[minmax(8rem,auto)_1fr]">137+ {facts.map(({ href, label, value }) => (138+ <div className="contents" key={`${label}:${value}`}>139+ <dt className={`${LABEL} pt-0.5`}>{label}</dt>140+ <dd className="mb-1.5 text-sm [overflow-wrap:anywhere] sm:mb-0">141+ {href === undefined ? (142+ value143+ ) : (144+ <a145+ className="decoration-rule underline hover:decoration-current"146+ href={href}147+ >148+ {value}149+ </a>150+ )}151+ </dd>152+ </div>153+ ))}154+ </dl>155+);156+157 const Evidence = ({ decision }: { readonly decision: Decision }) => {108- // The diff is the finish page's; here it is only counted.109- const facts = decision.evidence.filter(({ label }) => label !== PATCH_LABEL);158+ // The diff is the finish page's; here it is only counted. A proposal's159+ // files are drawn as code below the facts.160+ const files = filesOf(decision);161 111- if (facts.length === 0) {112- return null;113- }162+ const facts = decision.evidence.filter(163+ (fact) => fact.label !== PATCH_LABEL && !files.includes(fact)164+ );165 166 return (116- <dl className="grid grid-cols-1 gap-x-4 gap-y-1 sm:grid-cols-[minmax(8rem,auto)_1fr]">117- {facts.map(({ href, label, value }) => (118- <div className="contents" key={`${label}:${value}`}>119- <dt className={`${LABEL} pt-0.5`}>{label}</dt>120- <dd className="mb-1.5 text-sm [overflow-wrap:anywhere] sm:mb-0">121- {href === undefined ? (122- value123- ) : (124- <a125- className="decoration-rule underline hover:decoration-current"126- href={href}127- >128- {value}129- </a>130- )}131- </dd>132- </div>167+ <>168+ {facts.length === 0 ? null : <Facts facts={facts} />}169+ {files.map(({ label, value }) => (170+ <DraftedCode content={value} heading="h4" key={label} path={label} />171 ))}134- </dl>172+ </>173 );174 };175 176 /** The way from a `Finish` decision on Today to its answer's diff. */17 unmodified lines194 </a>195 );196 };197 198+/** The way from an `OpenProposal` decision to the proposal's page: its draft and files. */199+const ProposalLink = ({200+ project,201+ proposal,202+}: {203+ readonly project: ProjectName;204+ readonly proposal: ProposalId;205+}) => (206+ <a207+ className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"208+ href={`/${project}/proposals/${proposal}`}209+ >210+ <FileText aria-hidden="true" className="size-4 shrink-0" />211+ Read the proposal212+ </a>213+);214+215+interface ChoicesProps {216+ readonly busy: boolean;217+ readonly choose: (choice: Choice) => void;218+ readonly decision: Decision;219+ readonly subject: string;220+}221+222+/** One button per choice; Accept waits while the proposal is drafting. */223+const Choices = ({224+ busy,225+ choose,226+ decision,227+ drafting,228+ subject,229+}: ChoicesProps & { readonly drafting: boolean }) => (230+ <fieldset className="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap">231+ <legend className="sr-only">Your choice: {subject}</legend>232+ {allowedChoices(decision.subject).map((choice) => {233+ const isDefault = choice === decision.default;234+ const held = drafting && choice === "accept";235+236+ return (237+ <Button238+ className="h-11 px-4 text-sm sm:h-9 sm:min-w-28"239+ data-choice={choice}240+ disabled={busy || held}241+ key={choice}242+ onClick={() => {243+ choose(choice);244+ }}245+ type="button"246+ variant={isDefault ? "outline" : "default"}247+ >248+ {held ? (249+ <>250+ <Spinner />251+ Drafting…252+ </>253+ ) : (254+ words[choice]255+ )}256+ {isDefault ? (257+ <span className="text-muted-foreground font-normal">default</span>258+ ) : null}259+ </Button>260+ );261+ })}262+ </fieldset>263+);264+265+/** The choices on a proposal whose draft state was not passed: read from `showProposal`. */266+const ProposalChoices = ({267+ proposal,268+ ...props269+}: ChoicesProps & { readonly proposal: ProposalId }) => {270+ const draft = useLiveDraft(props.decision.project, proposal);271+272+ return <Choices {...props} drafting={Option.exists(draft, isDraftingNow)} />;273+};274+275 export const DecisionCard = ({276 busy = false,277 children,278 decision,279+ draft,280 now,281 onDecide,282 soon = false,283 standalone = false,8 unmodified lines292 /** Whether it is shown on its own page, so its title needs no link there. */293 readonly standalone?: boolean;294 /** What its own page shows before the choices: for a finish, the diff. */295 readonly children?: ReactNode;296+ /**297+ * For an `OpenProposal`, where the proposal's draft stands: Accept waits298+ * while it is drafting. Read from `showProposal` when not passed.299+ */300+ readonly draft?: DraftState | undefined;301 }) => {302 const [note, setNote] = useState("");303 const noteId = useId();304 const subject = describeSubject(decision.subject);66 unmodified lines371 {isFinishDecision(decision) && !standalone ? (372 <FinishLink decision={decision} />373 ) : null}374 375+ {opensAsk(decision.subject) ? (376+ <ProposalLink377+ project={decision.project}378+ proposal={decision.subject.proposal}379+ />380+ ) : null}381+382 {children === undefined ? null : (383 <div className="border-rule mt-3 flex flex-col gap-8 border-t pt-6">384 {children}385 </div>15 unmodified lines401 value={note}402 />403 </details>404 277- <fieldset className="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap">278- <legend className="sr-only">Your choice: {subject}</legend>279- {allowedChoices(decision.subject).map((choice) => {280- const isDefault = choice === decision.default;281-282- return (283- <Button284- className="h-11 px-4 text-sm sm:h-9 sm:min-w-28"285- data-choice={choice}286- disabled={busy}287- key={choice}288- onClick={() => {289- choose(choice);290- }}291- type="button"292- variant={isDefault ? "outline" : "default"}293- >294- {words[choice]}295- {isDefault ? (296- <span className="text-muted-foreground font-normal">297- default298- </span>299- ) : null}300- </Button>301- );302- })}303- </fieldset>405+ {opensAsk(decision.subject) && draft === undefined ? (406+ <ProposalChoices407+ busy={busy}408+ choose={choose}409+ decision={decision}410+ proposal={decision.subject.proposal}411+ subject={subject}412+ />413+ ) : (414+ <Choices415+ busy={busy}416+ choose={choose}417+ decision={decision}418+ drafting={draft !== undefined && isDraftingNow(draft)}419+ subject={subject}420+ />421+ )}422 </article>423 );424 };modified:apps/web/src/features/project/project-page.tsx+10 added-4 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`)5- * and the platform URL (the root loader), and hands them here.5+ * and the platform URL (the root loader), and hands them here. "Propose an6+ * ask" shows for signed-in members only, once the browser knows who that is7+ * (`features/propose/propose-link.tsx`).8 */9 import { Brand } from "@repo/brand";10 import type { AskListing } from "@repo/protocol/domain/ask";11 import type { FileView, TreeListing } from "@repo/protocol/domain/code";2 unmodified lines14 import type { ProjectName } from "@repo/protocol/ids";15 import type { DateTime } from "effect";16 17 import { EntriesTable, ReadmeSection } from "../code/tree-view.tsx";18+import { SignedInProposeLink } from "../propose/propose-link.tsx";19 import { CommandLine } from "../shared/command.tsx";20 import { EmptyState } from "../shared/empty.tsx";21 import { PageShell } from "../shared/layout.tsx";22 import { PostureBadge } from "../shared/posture.tsx";161 unmodified lines184 <section185 aria-labelledby="open-asks"186 className="flex min-w-0 flex-col gap-3 lg:col-start-1"187 >188+ <div className="flex flex-wrap items-baseline justify-between gap-x-6 gap-y-1">185- <h2 className={SECTION} id="open-asks">186- Open asks187- </h2>189+ <h2 className={SECTION} id="open-asks">190+ Open asks191+ </h2>192+ <SignedInProposeLink project={project} />193+ </div>194 {asks.length === 0 ? (195 <EmptyState196 command={`${Brand.cli} ask open <ask> --files <files>`}197 title="No open asks. A decider opens one from an ask file."47 unmodified linesadded:apps/web/src/features/proposal/client-file.tsx+53 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253/** * A drafted file (the ask file or its check), drawn in the browser only. * The server renders the file's path as a heading and its text in a * `<pre>`; after hydration the browser loads `@pierre/diffs` and draws it * highlighted. `import.meta.env.SSR` is `true` in the Worker's build, so the * dynamic import below is dead code there and the Worker bundles none of it * (`bytes:check`), as `features/code/client-code.tsx` does. */import { ClientOnly } from "@tanstack/react-router";import { lazy, Suspense } from "react";
// A type-only import is erased, so the server bundles nothing of it.import type { DraftedFileProps } from "./drafted-file.tsx";
const DraftedFileLater = import.meta.env.SSR ? undefined : lazy(() => import("./drafted-file.tsx"));
/** The file's text as the server and a reader without JavaScript see it. */const Plain = ({ content }: { readonly content: string }) => ( <pre className="border-rule bg-surface overflow-x-auto border px-3 py-2 font-mono text-[0.8125rem] leading-5"> {content} </pre>);
/** One drafted file under its path: a heading, then the code. */export const DraftedCode = ({ content, heading: Heading = "h3", path,}: DraftedFileProps & { /** The heading level the path takes in its page. */ readonly heading?: "h3" | "h4";}) => { const fallback = <Plain content={content} />;
return ( <section className="flex min-w-0 flex-col gap-1.5" data-file={path}> <Heading className="font-mono text-sm font-medium [overflow-wrap:anywhere]"> {path} </Heading> {DraftedFileLater === undefined ? ( fallback ) : ( <ClientOnly fallback={fallback}> <Suspense fallback={fallback}> <DraftedFileLater content={content} path={path} /> </Suspense> </ClientOnly> )} </section> );};added:apps/web/src/features/proposal/drafted-file.tsx+41 added
1234567891011121314151617181920212223242526272829303132333435363738394041/** * One drafted file, drawn by `@pierre/diffs`: the ask file or its check, * highlighted by Shiki's JavaScript engine (never its WASM one). Nothing is * selectable or anchored here: a page may hold several of these, and the * file's own page is the place for `#L` anchors. * * The library and Shiki's grammars are megabytes, so only the browser * loads this module (`client-file.tsx`); the Worker never bundles it. */import { DEFAULT_THEMES } from "@pierre/diffs";import { File } from "@pierre/diffs/react";import type { FileOptions } from "@pierre/diffs/react";import { useMemo } from "react";
export interface DraftedFileProps { readonly path: string; readonly content: string;}
const options: FileOptions<undefined, undefined> = { overflow: "scroll", preferredHighlighter: "shiki-js", theme: DEFAULT_THEMES, themeType: "system",};
export const DraftedFile = ({ content, path }: DraftedFileProps) => { const file = useMemo( () => ({ contents: content, name: path }), [content, path] );
return ( <div className="border-rule min-w-0 border" data-code="pierre"> <File file={file} options={options} /> </div> );};
// `React.lazy` takes a module's default export.export default DraftedFile;added:apps/web/src/features/proposal/live-draft.ts+23 added
1234567891011121314151617181920212223/** * Where a proposal's draft stands, read live for a view that is not handed * it: the decision card on Today holds Accept while the platform's agent * drafts the proposal again. The read is `showProposal` (`client/proposal.ts`), * which `ProposalDrafted` refreshes; on the server, and until it answers, * the draft is unknown (`Option.none`). */import { useAtomValue } from "@effect/atom-react";import type { DraftState } from "@repo/protocol/domain/proposal";import type { ProjectName, ProposalId } from "@repo/protocol/ids";import { Option } from "effect";import { AsyncResult } from "effect/reactivity";
import { proposalAtom } from "../../client/proposal.ts";
export const useLiveDraft = ( project: ProjectName, proposal: ProposalId): Option.Option<DraftState> => Option.flatMap( AsyncResult.value(useAtomValue(proposalAtom(project)(proposal))), (shown) => Option.fromUndefinedOr(shown.proposal.draft) );added:apps/web/src/features/proposal/proposal-view.tsx+288 added
1+/**2+ * One proposal, as its proposer and its deciders follow it: the want and3+ * who proposed it, where the platform's draft of its ask stands (drafting,4+ * ready after its check ran red first, or failed with the last refusal),5+ * the drafted files, and the way to the decision that would open the ask.6+ * "Draft again" (with an optional note for the agent) is the proposer's or7+ * a decider's while the proposal is open and not drafting. Props in, markup8+ * out: the route reads `showProposal`, who is signed in and the decider's9+ * Today, and sends `draftAsk`.10+ *11+ * Nothing here edits the drafted files: a member proposes again, or a12+ * decider sends the draft back with a note.13+ */14+import type { ConfigFile } from "@repo/protocol/domain/common";15+import { DraftState } from "@repo/protocol/domain/proposal";16+import type { Proposal } from "@repo/protocol/domain/proposal";17+import type { DecisionId, ProjectName } from "@repo/protocol/ids";18+import { Option } from "effect";19+import { constVoid } from "effect/Function";20+import { CircleCheck, OctagonX, Scale } from "lucide-react";21+import { useId, useState } from "react";22+import type { ReactNode } from "react";23+24+import { Badge } from "../../components/ui/badge.tsx";25+import { Button } from "../../components/ui/button.tsx";26+import { Spinner } from "../../components/ui/spinner.tsx";27+import { Textarea } from "../../components/ui/textarea.tsx";28+import { HandleLink } from "../shared/handle.tsx";29+import { DraftedCode } from "./client-file.tsx";30+31+/**32+ * How many attempts a draft round makes before it fails: the platform's33+ * `DRAFT_ROUNDS` (`@repo/project/draft-runs`), which the web's production34+ * code does not import; `test/proposal.test.tsx` holds the two equal.35+ */36+export const DRAFT_ATTEMPTS = 3;37+38+/** The longest note `draftAsk` takes. */39+const NOTE_LIMIT = 2000;40+41+/** Where a proposal stands in one word: its draft's while it is open, else its own. */42+export const standing = (proposal: Proposal) =>43+ proposal.state === "open" && proposal.draft !== undefined44+ ? proposal.draft._tag45+ : proposal.state;46+47+const draftingNow = DraftState.isAnyOf(["Drafting"]);48+49+/** Whether the platform's agent is drafting the proposal's ask right now. */50+export const isDrafting = (proposal: Proposal) =>51+ proposal.draft !== undefined && draftingNow(proposal.draft);52+53+const LABEL = "text-muted-foreground text-xs font-medium";54+55+/** The badge each standing wears: an ending that opened nothing reads as refused. */56+const badgeVariant = {57+ Drafting: "outline",58+ Failed: "destructive",59+ Ready: "secondary",60+ accepted: "secondary",61+ declined: "destructive",62+ expired: "destructive",63+ open: "secondary",64+} as const satisfies Record<ReturnType<typeof standing>, string>;65+66+const StateBadge = ({ proposal }: { readonly proposal: Proposal }) => {67+ const word = standing(proposal);68+69+ return (70+ <Badge data-standing={word} variant={badgeVariant[word]}>71+ {word === "Drafting" ? <Spinner className="size-3" /> : null}72+ {word}73+ </Badge>74+ );75+};76+77+/** What the draft says: in progress, ready with its red-first run, or failed. */78+const DraftFacts = ({ draft }: { readonly draft: DraftState }) =>79+ DraftState.match(draft, {80+ Drafting: ({ round }) => (81+ <p className="flex items-start gap-2 text-sm" data-draft="Drafting">82+ <Spinner className="text-checking mt-0.5 shrink-0" />83+ <span>84+ Drafting (round {round}): the platform's agent is writing the ask85+ and a check, then running the check on main, where it must fail twice86+ the same way. This takes a few minutes; the page follows it.87+ </span>88+ </p>89+ ),90+ Failed: ({ attempts, model, refusal, round }) => (91+ <div className="flex flex-col gap-1 text-sm" data-draft="Failed">92+ <p className="flex items-start gap-2">93+ <OctagonX94+ aria-hidden="true"95+ className="text-refused mt-0.5 size-4 shrink-0"96+ />97+ <span>98+ The draft failed (round {round}), after {attempts} of{" "}99+ {DRAFT_ATTEMPTS} attempts by {model}. The last refusal:{" "}100+ <b className="text-refused font-mono font-semibold">{refusal}</b>101+ </span>102+ </p>103+ </div>104+ ),105+ Ready: ({ attempts, model, red }) => (106+ <dl107+ className="grid grid-cols-1 gap-x-4 gap-y-1 text-sm sm:grid-cols-[minmax(8rem,auto)_1fr]"108+ data-draft="Ready"109+ >110+ <dt className={`${LABEL} pt-0.5`}>Red first</dt>111+ <dd className="mb-1.5 flex items-start gap-2 [overflow-wrap:anywhere] sm:mb-0">112+ <CircleCheck113+ aria-hidden="true"114+ className="text-landed mt-0.5 size-4 shrink-0"115+ />116+ <span>117+ fails twice the same way in lane {red.lane}: {red.signature}118+ </span>119+ </dd>120+ <dt className={`${LABEL} pt-0.5`}>Drafted by</dt>121+ <dd className="mb-1.5 [overflow-wrap:anywhere] sm:mb-0">122+ drafted by {model}, attempt {attempts} of {DRAFT_ATTEMPTS}123+ </dd>124+ </dl>125+ ),126+ });127+128+/** "Draft again", with a note the agent reads. */129+const Redraft = ({130+ again,131+ busy,132+ onRedraft,133+}: {134+ readonly again: boolean;135+ readonly busy: boolean;136+ readonly onRedraft: (note: string | undefined) => void;137+}) => {138+ const [note, setNote] = useState("");139+ const noteId = useId();140+141+ return (142+ <section143+ aria-label="Draft again"144+ className="border-rule flex flex-col gap-3 border-t pt-4"145+ >146+ <details className="text-sm">147+ <summary className="text-muted-foreground hover:text-foreground w-fit cursor-pointer py-1 select-none">148+ Add a note for the agent149+ </summary>150+ <label className={`${LABEL} mt-2 block`} htmlFor={noteId}>151+ What the next draft should do differently152+ </label>153+ <Textarea154+ className="mt-1 text-sm md:text-sm"155+ id={noteId}156+ maxLength={NOTE_LIMIT}157+ onChange={(event) => {158+ setNote(event.target.value);159+ }}160+ value={note}161+ />162+ </details>163+ <Button164+ className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"165+ disabled={busy}166+ onClick={() => {167+ const written = note.trim();168+169+ onRedraft(written.length === 0 ? undefined : written);170+ }}171+ type="button"172+ variant="outline"173+ >174+ {again ? "Draft again" : "Let the platform's agent draft it"}175+ </Button>176+ </section>177+ );178+};179+180+/** The way to the open decision that would open the ask. */181+const DecisionLink = ({182+ decision,183+ project,184+}: {185+ readonly decision: DecisionId;186+ readonly project: ProjectName;187+}) => (188+ <a189+ className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"190+ data-decision={decision}191+ href={`/${project}/decisions/${decision}`}192+ >193+ <Scale aria-hidden="true" className="size-4 shrink-0" />194+ Decide it: {decision}195+ </a>196+);197+198+export const ProposalView = ({199+ busy = false,200+ children,201+ decision,202+ files,203+ mayRedraft,204+ onRedraft = constVoid,205+ project,206+ proposal,207+}: {208+ readonly project: ProjectName;209+ readonly proposal: Proposal;210+ /** The files the proposal holds (the ask file and its check), as `showProposal` read them. */211+ readonly files: readonly ConfigFile[];212+ /** The open decision on the proposal, when the reader's Today holds it. */213+ readonly decision: Option.Option<DecisionId>;214+ /** Whether the reader is its proposer or one of the project's deciders. */215+ readonly mayRedraft: boolean;216+ readonly onRedraft?: (note: string | undefined) => void;217+ /** Whether a "Draft again" is on its way: the button waits. */218+ readonly busy?: boolean;219+ /** What the last "Draft again" came back with, when it was refused. */220+ readonly children?: ReactNode;221+}): ReactNode => {222+ const open = proposal.state === "open";223+224+ return (225+ <article226+ aria-labelledby={`${proposal.id}-want`}227+ className="flex max-w-[90ch] min-w-0 flex-col gap-5"228+ data-proposal={proposal.id}229+ >230+ <header className="flex flex-col gap-2">231+ <p className="text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">232+ <span className="font-mono">{project}</span>233+ <span aria-hidden="true">·</span>234+ <span className="font-mono">{proposal.id}</span>235+ <StateBadge proposal={proposal} />236+ </p>237+ <h2238+ className="text-lg font-semibold text-balance [overflow-wrap:anywhere]"239+ id={`${proposal.id}-want`}240+ >241+ {proposal.want}242+ </h2>243+ <p className="text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-sm">244+ <span>245+ Proposed by <HandleLink handle={proposal.proposer} />246+ </span>247+ {proposal.territory === undefined ? null : (248+ <span>249+ in <code className="font-mono">{proposal.territory}</code>250+ </span>251+ )}252+ </p>253+ </header>254+255+ {proposal.draft === undefined ? null : (256+ <DraftFacts draft={proposal.draft} />257+ )}258+259+ {Option.isSome(decision) ? (260+ <DecisionLink decision={decision.value} project={project} />261+ ) : null}262+263+ {files.length === 0 ? null : (264+ <section265+ aria-labelledby={`${proposal.id}-files`}266+ className="flex min-w-0 flex-col gap-4"267+ >268+ <h2 className="text-base font-semibold" id={`${proposal.id}-files`}>269+ {proposal.draft === undefined ? "Proposed files" : "Drafted files"}270+ </h2>271+ {files.map(({ content, path }) => (272+ <DraftedCode content={content} key={path} path={path} />273+ ))}274+ </section>275+ )}276+277+ {children}278+279+ {mayRedraft && open && !isDrafting(proposal) ? (280+ <Redraft281+ again={proposal.draft !== undefined}282+ busy={busy}283+ onRedraft={onRedraft}284+ />285+ ) : null}286+ </article>287+ );288+};added:apps/web/src/features/propose/propose-link.tsx+35 added
1234567891011121314151617181920212223242526272829303132333435/** * The way to the propose form, for signed-in members only. Who is signed in * is the browser's to learn (`whoAtom`), after the first paint, so the * server renders no link and the browser adds it, as the header's session * slot does (`features/auth/session-slot.tsx`). */import { useAtomValue } from "@effect/atom-react";import type { ProjectName } from "@repo/protocol/ids";import { Option } from "effect";import { AsyncResult } from "effect/reactivity";import { MessageSquarePlus } from "lucide-react";
import { whoAtom } from "../auth/who.ts";import { proposeFormPath } from "./propose-view.tsx";
export const ProposeLink = ({ project }: { readonly project: ProjectName }) => ( <a className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current" data-propose="" href={proposeFormPath(project)} > <MessageSquarePlus aria-hidden="true" className="size-4 shrink-0" /> Propose an ask </a>);
/** `ProposeLink` once the browser knows someone is signed in; nothing before or otherwise. */export const SignedInProposeLink = ({ project,}: { readonly project: ProjectName;}) => Option.isSome(Option.flatten(AsyncResult.value(useAtomValue(whoAtom)))) ? ( <ProposeLink project={project} /> ) : null;added:apps/web/src/features/propose/propose-view.tsx+232 added
1+/**2+ * The propose form: a signed-in member writes a want, may name the3+ * territory it belongs to (one of the project's top folders), and lets the4+ * platform's agent draft the ask file and its failing check from it,5+ * checked by default. A line from the why page (`?about&line&at`) starts the6+ * want with where it points. Props in, markup out: the route reads who is7+ * signed in and the project's paths, sends the payload, and goes to the8+ * proposal once it is made.9+ *10+ * Only the want, the territory and the draft box: the files are the11+ * agent's to write, or a person's through `propose --files` in the CLI.12+ */13+import { Brand } from "@repo/brand";14+import type { ProposeAsk } from "@repo/protocol/contracts";15+import type { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";16+import { Option } from "effect";17+import { LogIn } from "lucide-react";18+import { useId, useState } from "react";19+import type { ReactNode } from "react";20+21+import { Button } from "../../components/ui/button.tsx";22+import { Checkbox } from "../../components/ui/checkbox.tsx";23+import { Label } from "../../components/ui/label.tsx";24+import { Spinner } from "../../components/ui/spinner.tsx";25+import { Textarea } from "../../components/ui/textarea.tsx";26+import { CommandLine } from "../shared/command.tsx";27+28+/** What `proposeAsk` takes, from its one schema. */29+export type ProposePayload = typeof ProposeAsk.payloadSchema.Type;30+31+/** A line a why page points at: the file, the line and the commit it was read at. */32+export interface About {33+ readonly path: RepoPath;34+ readonly line: number;35+ readonly at: CommitSha;36+}37+38+/**39+ * The form's fields as `proposeAsk`'s payload: the want trimmed, the40+ * territory when one is named, and `draft: true` only when the box is41+ * checked (the contract takes no `draft: false`).42+ */43+export const proposalPayload = (form: {44+ readonly project: ProjectName;45+ readonly want: string;46+ readonly territory?: RepoPath;47+ readonly draft: boolean;48+}): ProposePayload => {49+ const want = form.want.trim();50+51+ const named =52+ form.territory === undefined53+ ? { project: form.project, want }54+ : { project: form.project, territory: form.territory, want };55+56+ return form.draft ? { ...named, draft: true } : named;57+};58+59+/** How a want about one line starts: `In \`src/format.ts\` line 12 at 4c2e6a8: `. */60+export const wantAbout = ({ at, line, path }: About) =>61+ `In \`${path}\` line ${line} at ${at.slice(0, 7)}: `;62+63+/**64+ * The form's address for `project`, at the line a why page names when it65+ * names one: where the project page links, and where sign-in comes back to.66+ */67+export const proposeFormPath = (68+ project: ProjectName,69+ about: Option.Option<About> = Option.none()70+) =>71+ Option.match(about, {72+ onNone: () => `/${project}/proposals/new`,73+ onSome: ({ at, line, path }) =>74+ `/${project}/proposals/new?${new URLSearchParams({ about: path, at, line: String(line) }).toString()}`,75+ });76+77+const LABEL = "text-muted-foreground text-xs font-medium";78+79+const SignInFirst = ({80+ about,81+ project,82+}: {83+ readonly about: Option.Option<About>;84+ readonly project: ProjectName;85+}) => (86+ <section87+ aria-label="Sign in to propose"88+ className="border-rule flex flex-col gap-3 border-t pt-4"89+ >90+ <p className="flex items-start gap-2 text-sm">91+ <LogIn aria-hidden="true" className="mt-0.5 size-4 shrink-0" />92+ <span>93+ Proposing an ask is for signed-in members.{" "}94+ <a95+ className="decoration-rule font-medium underline hover:decoration-current"96+ href={`/auth/signin?${new URLSearchParams({ return: proposeFormPath(project, about) }).toString()}`}97+ >98+ Sign in99+ </a>{" "}100+ to propose one, or propose from your clone:101+ </span>102+ </p>103+ <CommandLine command={`${Brand.cli} propose --draft "<want>"`} />104+ </section>105+);106+107+export const ProposeView = ({108+ about,109+ busy = false,110+ children,111+ modules,112+ onPropose,113+ project,114+ signedIn,115+}: {116+ readonly project: ProjectName;117+ readonly signedIn: boolean;118+ readonly about: Option.Option<About>;119+ /** The project's top folders, each a territory to choose. */120+ readonly modules: readonly RepoPath[];121+ /** Sends the payload; the route goes to the proposal once it is made. */122+ readonly onPropose?: (payload: ProposePayload) => void;123+ /** Whether a proposal is on its way: the button waits. */124+ readonly busy?: boolean;125+ /** What the last proposal came back with, when it was refused. */126+ readonly children?: ReactNode;127+}): ReactNode => {128+ const id = useId();129+130+ const [want, setWant] = useState(() =>131+ Option.match(about, { onNone: () => "", onSome: wantAbout })132+ );133+134+ const [territory, setTerritory] = useState("");135+ const [draft, setDraft] = useState(true);136+137+ if (!signedIn) {138+ return <SignInFirst about={about} project={project} />;139+ }140+141+ const chosen = modules.find((module) => module === territory);142+ const written = want.trim().length > 0;143+144+ return (145+ <form146+ aria-label="Propose an ask"147+ className="flex max-w-[70ch] flex-col gap-5"148+ onSubmit={(event) => {149+ event.preventDefault();150+151+ if (written) {152+ onPropose?.(153+ proposalPayload(154+ chosen === undefined155+ ? { draft, project, want }156+ : { draft, project, territory: chosen, want }157+ )158+ );159+ }160+ }}161+ >162+ <div className="flex flex-col gap-1.5">163+ <label className={LABEL} htmlFor={`${id}-want`}>164+ What should the project do that it does not do now?165+ </label>166+ <Textarea167+ className="min-h-32 text-sm md:text-sm"168+ id={`${id}-want`}169+ name="want"170+ onChange={(event) => {171+ setWant(event.target.value);172+ }}173+ required174+ value={want}175+ />176+ </div>177+178+ <div className="flex flex-col gap-1.5">179+ <label className={LABEL} htmlFor={`${id}-territory`}>180+ Territory (optional)181+ </label>182+ <select183+ className="border-input bg-background h-9 w-full max-w-xs rounded-none border px-2 text-sm"184+ id={`${id}-territory`}185+ name="territory"186+ onChange={(event) => {187+ setTerritory(event.target.value);188+ }}189+ value={territory}190+ >191+ <option value="">Let the agent choose</option>192+ {modules.map((module) => (193+ <option key={module} value={module}>194+ {module}195+ </option>196+ ))}197+ </select>198+ </div>199+200+ <div className="flex items-start gap-2">201+ <Checkbox202+ checked={draft}203+ className="mt-0.5"204+ id={`${id}-draft`}205+ name="draft"206+ onCheckedChange={(checked) => {207+ setDraft(checked);208+ }}209+ />210+ <Label className="text-sm leading-snug" htmlFor={`${id}-draft`}>211+ Let the platform's agent draft the ask212+ </Label>213+ </div>214+ <p className="text-muted-foreground -mt-3 pl-6 text-xs">215+ It writes the ask file and a check that fails on main, runs it red216+ first, and puts the draft to a decider. Clear the box to propose the217+ want alone.218+ </p>219+220+ {children}221+222+ <Button223+ className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"224+ disabled={busy || !written}225+ type="submit"226+ >227+ {busy ? <Spinner /> : null}228+ Propose229+ </Button>230+ </form>231+ );232+};modified:apps/web/src/routes/$project/proposals/$proposal.tsx+186 added-11 removed
1+import {2+ RegistryProvider,3+ useAtom,4+ useAtomMount,5+ useAtomValue,6+} from "@effect/atom-react";7+import { Client, ShowProposal } from "@repo/protocol/contracts";8+import { DecisionSubject } from "@repo/protocol/domain/decision";9+import type { Today } from "@repo/protocol/domain/decision";10+import type { Proposal } from "@repo/protocol/domain/proposal";11+import { ProjectName, ProposalId } from "@repo/protocol/ids";12+import type { DecisionId, Handle } from "@repo/protocol/ids";1-import { createFileRoute } from "@tanstack/react-router";13+import { createFileRoute, notFound } from "@tanstack/react-router";14+import { createServerFn } from "@tanstack/react-start";15+import { env } from "cloudflare:workers";16+import { Array, Effect, Option, Schema } from "effect";17+import { AsyncResult, Atom } from "effect/reactivity";18 3-import { pageTitle } from "../../../features/shared/layout.tsx";4-import { NotBuilt } from "../../../features/shared/not-built.tsx";19+import {20+ draftAtom,21+ projectTodayAtom,22+ proposalAtom,23+} from "../../../client/proposal.ts";24+import { watchAtom } from "../../../client/watch.ts";25+import { whoAtom } from "../../../features/auth/who.ts";26+import { ProjectNav } from "../../../features/project/project-nav.tsx";27+import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";28+import { ProposalView } from "../../../features/proposal/proposal-view.tsx";29+import { EmptyState } from "../../../features/shared/empty.tsx";30+import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";31+import { FailureView } from "../../../features/today/today-page.tsx";32+import { serverClient } from "../../../server/client.ts";33 6-// A proposal: its draft, the drafted files and the red-first evidence. A stub until 911 builds it.34+// `/$project/proposals/$proposal`: one proposal and the platform's draft of35+// its ask. The loader reads `showProposal` on the server, so the page36+// arrives whole and an address naming no project or proposal is a 404; in37+// the browser it reads again on each `ProposalDrafted` (the project's38+// watch), so a draft moves from Drafting to Ready or Failed on screen.39+// Who is signed in and the reader's Today (a decider's: it holds the open40+// decision on the proposal) are read in the browser only.41 8-const Page = () => {9- const { project, proposal } = Route.useParams();42+type Shown = typeof ShowProposal.successSchema.Type;43 44+/** The proposal `name/id` names, encoded for the page; a not-found when there is none. */45+export const readProposal = (name: string, id: string) =>46+ Effect.gen(function* () {47+ const project = yield* Schema.decodeEffect(ProjectName)(name).pipe(48+ Effect.mapError(() => notFound())49+ );50+51+ const proposal = yield* Schema.decodeEffect(ProposalId)(id).pipe(52+ Effect.mapError(() => notFound())53+ );54+55+ const client = yield* Client;56+57+ const shown = yield* client.showProposal({ project, proposal }).pipe(58+ Effect.catchTags({59+ UnknownProject: () => Effect.fail(notFound()),60+ UnknownProposal: () => Effect.fail(notFound()),61+ })62+ );63+64+ return yield* Schema.encodeEffect(ShowProposal.successSchema)(shown);65+ });66+67+const proposalPage = createServerFn({ method: "GET" })68+ .validator(69+ (params: { readonly project: string; readonly proposal: string }) => params70+ )71+ .handler(({ data }) =>72+ Effect.runPromise(73+ readProposal(data.project, data.proposal).pipe(74+ Effect.provide(serverClient(env))75+ )76+ )77+ );78+79+/** The open decision on `proposal` in the reader's Today, if it is there. */80+const decisionOn = (81+ today: AsyncResult.AsyncResult<Today, unknown>,82+ proposal: Proposal83+): Option.Option<DecisionId> =>84+ Option.flatMap(AsyncResult.value(today), ({ decisions }) =>85+ Array.findFirst(86+ decisions,87+ ({ decided, project, subject }) =>88+ decided === undefined &&89+ project === proposal.project &&90+ DecisionSubject.guards.OpenProposal(subject) &&91+ subject.proposal === proposal.id92+ ).pipe(Option.map(({ id }) => id))93+ );94+95+/** Whether `who` is the proposer, or the reader decides in the project (their Today answered). */96+const mayRedraftAs = (97+ who: AsyncResult.AsyncResult<Option.Option<Handle>, unknown>,98+ today: AsyncResult.AsyncResult<Today, unknown>,99+ proposal: Proposal100+) =>101+ AsyncResult.isSuccess(today) ||102+ Option.exists(103+ Option.flatten(AsyncResult.value(who)),104+ (handle) => handle.toLowerCase() === proposal.proposer.toLowerCase()105+ );106+107+/** The page over the proposal's atom, which starts from what the loader read. */108+const FreshProposal = ({109+ project,110+ read,111+}: {112+ readonly project: ProjectName;113+ readonly read: Shown;114+}) => {115+ // Live: a `ProposalDrafted` re-reads the proposal.116+ useAtomMount(watchAtom(project));117+118+ const { files, proposal } = Option.getOrElse(119+ AsyncResult.value(useAtomValue(proposalAtom(project)(read.proposal.id))),120+ () => read121+ );122+123+ const who = useAtomValue(whoAtom);124+ const today = useAtomValue(projectTodayAtom(project));125+ const [redrafted, redraft] = useAtom(draftAtom);126+127 return (12- <NotBuilt13- issue="911"128+ <ProposalView129+ busy={redrafted.waiting}130+ decision={decisionOn(today, proposal)}131+ files={files}132+ mayRedraft={mayRedraftAs(who, today, proposal)}133+ onRedraft={(note) => {134+ redraft(135+ note === undefined136+ ? { project, proposal: proposal.id }137+ : { note, project, proposal: proposal.id }138+ );139+ }}140 project={project}15- title={`${project}: proposal ${proposal}`}16- />141+ proposal={proposal}142+ >143+ {AsyncResult.isFailure(redrafted) ? (144+ <div aria-live="polite">145+ <FailureView cause={redrafted.cause} />146+ </div>147+ ) : null}148+ </ProposalView>149 );150 };151 152+const ProposalPage = () => {153+ const read = Schema.decodeSync(ShowProposal.successSchema)(154+ Route.useLoaderData()155+ );156+157+ const { id, project } = read.proposal;158+159+ return (160+ <PageShell title={`${project}: proposal ${id}`}>161+ <ProjectNav project={project} />162+ <RegistryProvider163+ initialValues={[164+ Atom.initialValue(165+ proposalAtom(project)(id),166+ AsyncResult.success(read)167+ ),168+ ]}169+ key={`${project}/${id}`}170+ >171+ <FreshProposal project={project} read={read} />172+ </RegistryProvider>173+ </PageShell>174+ );175+};176+177+const Unknown = () => {178+ const { project, proposal } = Route.useParams();179+180+ return Option.match(Schema.decodeUnknownOption(ProjectName)(project), {181+ onNone: () => <UnknownProjectView name={project} />,182+ onSome: (name) => (183+ <PageShell title={`${name}: proposal ${proposal}`}>184+ <ProjectNav project={name} />185+ <EmptyState186+ title={`${name} has no proposal ${proposal}, or no such project exists.`}187+ />188+ </PageShell>189+ ),190+ });191+};192+193 export const Route = createFileRoute("/$project/proposals/$proposal")({21- component: Page,194+ loader: ({ params }) => proposalPage({ data: params }),195 head: ({ params: { project, proposal } }) => ({196 meta: [{ title: pageTitle(`${project}: proposal ${proposal}`) }],197 }),198+ component: ProposalPage,199+ notFoundComponent: Unknown,200 });modified:apps/web/src/routes/$project/proposals/new.tsx+125 added-10 removed
1+import { useAtom, useAtomValue } from "@effect/atom-react";2+import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";1-import { createFileRoute } from "@tanstack/react-router";3+import { createFileRoute, useNavigate } from "@tanstack/react-router";4+import { Option, Schema } from "effect";5+import { AsyncResult } from "effect/reactivity";6+import { useEffect, useState } from "react";7 3-import { pageTitle } from "../../../features/shared/layout.tsx";4-import { NotBuilt } from "../../../features/shared/not-built.tsx";8+import {9+ modulesAtom,10+ proposalMade,11+ proposeAtom,12+} from "../../../client/propose.ts";13+import { whoAtom } from "../../../features/auth/who.ts";14+import { ProjectNav } from "../../../features/project/project-nav.tsx";15+import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";16+import { ProposeView } from "../../../features/propose/propose-view.tsx";17+import type { About } from "../../../features/propose/propose-view.tsx";18+import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";19+import { FailureView } from "../../../features/today/today-page.tsx";20 6-// The propose form: a want, for the platform's agent to draft into an ask. A stub until 911 builds it.21+// `/$project/proposals/new`: the propose form. Who is signed in and the22+// project's top folders are read in the browser (the server paints the23+// page while it checks); a proposal made goes to its own page, a refusal24+// shows under the form. `?about=<path>&line=<n>&at=<sha>` (the why page's25+// "Propose an ask about this line") starts the want at that line.26 8-const Page = () => {9- const { project } = Route.useParams();27+const decodeProject = Schema.decodeUnknownOption(ProjectName);28 29+/** The line a why page points at, when the address names all three parts. */30+const AboutParts = Schema.Struct({31+ about: RepoPath,32+ at: CommitSha,33+ line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),34+});35+36+const decodeAbout = Schema.decodeUnknownOption(AboutParts);37+38+const decodeText = Schema.decodeUnknownOption(Schema.String);39+40+const decodeLine = Schema.decodeUnknownOption(Schema.Int);41+42+/** The address's line, as the form takes it. */43+const aboutOf = (search: {44+ readonly about?: string | undefined;45+ readonly at?: string | undefined;46+ readonly line?: number | undefined;47+}): Option.Option<About> =>48+ Option.map(decodeAbout(search), ({ about, at, line }) => ({49+ at,50+ line,51+ path: about,52+ }));53+54+const Checking = () => (55+ <output className="text-muted-foreground block text-sm">56+ Checking who is signed in57+ </output>58+);59+60+/** The form for `project`, once the browser knows who is signed in. */61+const Propose = ({ project }: { readonly project: ProjectName }) => {62+ const navigate = useNavigate();63+ const search = Route.useSearch();64+ const who = useAtomValue(whoAtom);65+66+ const modules = Option.getOrElse(67+ AsyncResult.value(useAtomValue(modulesAtom(project))),68+ () => []69+ );70+71+ const [proposed, propose] = useAtom(proposeAtom);72+ // Set once this form sends: a proposal the atom still holds from an73+ // earlier visit never moves the page.74+ const [sent, setSent] = useState(false);75+76+ const made = sent ? Option.getOrUndefined(proposalMade(proposed)) : undefined;77+78+ useEffect(() => {79+ if (made !== undefined) {80+ void navigate({81+ params: { project, proposal: made },82+ to: "/$project/proposals/$proposal",83+ });84+ }85+ }, [made, navigate, project]);86+87+ if (!AsyncResult.isSuccess(who)) {88+ return <Checking />;89+ }90+91 return (12- <NotBuilt13- issue="911"92+ <ProposeView93+ about={aboutOf(search)}94+ busy={proposed.waiting}95+ modules={modules}96+ onPropose={(payload) => {97+ setSent(true);98+ propose(payload);99+ }}100 project={project}15- title={`${project}: propose an ask`}16- />101+ signedIn={Option.isSome(who.value)}102+ >103+ {AsyncResult.isFailure(proposed) ? (104+ <div aria-live="polite">105+ <FailureView cause={proposed.cause} />106+ </div>107+ ) : null}108+ </ProposeView>109 );110 };111 112+const Page = () => {113+ const params = Route.useParams();114+115+ return Option.match(decodeProject(params.project), {116+ onNone: () => <UnknownProjectView name={params.project} />,117+ onSome: (project) => (118+ <PageShell title={`${project}: propose an ask`}>119+ <ProjectNav project={project} />120+ <Propose project={project} />121+ </PageShell>122+ ),123+ });124+};125+126 export const Route = createFileRoute("/$project/proposals/new")({127 component: Page,128+ validateSearch: (search: {129+ readonly about?: unknown;130+ readonly at?: unknown;131+ readonly line?: unknown;132+ }) => ({133+ about: Option.getOrUndefined(decodeText(search.about)),134+ at: Option.getOrUndefined(decodeText(search.at)),135+ line: Option.getOrUndefined(decodeLine(search.line)),136+ }),137 head: ({ params: { project } }) => ({138 meta: [{ title: pageTitle(`${project}: propose an ask`) }],139 }),140 });modified:apps/web/test/decision.test.tsx+114 added-1 removed
8 unmodified lines9 * own client over in-process handlers that record each call (`RpcTest`); no10 * HTTP and no platform.11 */12 import { describe, expect, it } from "@effect/vitest";13+import { Brand } from "@repo/brand";14 import { Contracts } from "@repo/protocol/contracts";15 import { RefNameText } from "@repo/protocol/domain/common";16 import { DecisionSubject } from "@repo/protocol/domain/decision";17 import type { Choice, Decision, Today } from "@repo/protocol/domain/decision";17-import { CommitSha, DecisionId, Handle, ProjectName } from "@repo/protocol/ids";18+import { DraftState } from "@repo/protocol/domain/proposal";19+import {20+ CommitSha,21+ DecisionId,22+ Handle,23+ LaneName,24+ ProjectName,25+ ProposalId,26+} from "@repo/protocol/ids";27 import { DecisionClosed } from "@repo/protocol/refusal";28 import type { UnknownDecision } from "@repo/protocol/refusal";29 import { asTester, unanswered } from "@repo/protocol/testing";30 import { DateTime, Effect, Exit, Layer, Ref } from "effect";4 unmodified lines35 36 import { decideAtom } from "../src/client/decide.ts";37 import { keys } from "../src/client/keys.ts";38 import { todayAtom } from "../src/client/today.ts";39+import { DecisionCard } from "../src/features/decision/decision-card.tsx";40 import { RefusalView } from "../src/features/shared/refusal.tsx";41 import { TodayView } from "../src/features/today/today-page.tsx";42 import { ContractsClient, webContracts } from "../src/surfaces.ts";43 235 unmodified lines279 expect(markup).not.toContain('data-decision="dec-000002"');280 })281 );282 });283+284+/** The Accept button's opening tag. */285+const acceptOf = (markup: string) =>286+ /<button[^>]*data-choice="accept"[^>]*>/u.exec(markup)?.[0] ?? "";287+288+describe("DecisionCard for an OpenProposal", () => {289+ const askFile = `${Brand.configDir}/asks/x.ask.ts`;290+291+ const proposal = ProposalId.make("prop-000007");292+293+ const opening: Decision = {294+ deciders: [okonkwo],295+ default: "decline",296+ evidence: [297+ { label: "want", value: "formatISO keeps the offset it was given." },298+ {299+ label: askFile,300+ value: 'export default ask({ id: "x", kind: kinds.fix });\n',301+ },302+ { label: "red first", value: "unit: expected '+02:00', got 'Z'" },303+ ],304+ expiresAt: DateTime.makeUnsafe("2026-10-08T10:00:00Z"),305+ id: DecisionId.make("dec-000003"),306+ openedAt: DateTime.makeUnsafe("2026-10-06T10:00:00Z"),307+ project: datekit,308+ subject: DecisionSubject.cases.OpenProposal.make({ proposal }),309+ };310+311+ const card = (draft: DraftState) =>312+ markupOf(313+ <DecisionCard314+ decision={opening}315+ draft={draft}316+ now={now}317+ onDecide={() => {}}318+ />319+ );320+321+ const drafting = DraftState.cases.Drafting.make({322+ round: 2,323+ startedAt: now,324+ });325+326+ const ready = DraftState.cases.Ready.make({327+ attempts: 1,328+ model: "@cf/moonshotai/kimi-k2.7-code",329+ red: { lane: LaneName.make("unit"), signature: "expected '+02:00'" },330+ round: 1,331+ });332+333+ it("shows a file's path as a heading and its content in a pre", () => {334+ const markup = card(ready);335+336+ expect(markup).toMatch(new RegExp(`<h4[^>]*>${askFile}</h4>`, "u"));337+ expect(markup).toMatch(338+ /<pre[^>]*>export default ask\(\{ id: "x", kind: kinds\.fix \}\);\n<\/pre>/u339+ );340+ expect(markup).not.toMatch(new RegExp(`<dt[^>]*>${askFile}</dt>`, "u"));341+ expect(markup).toMatch(/<dt[^>]*>red first<\/dt>/u);342+ });343+344+ it("holds Accept while the proposal's draft is drafting", () => {345+ const markup = card(drafting);346+347+ expect(acceptOf(markup)).toContain('disabled=""');348+ expect(markup).toContain("Drafting…");349+ expect(350+ /<button[^>]*data-choice="decline"[^>]*>/u.exec(markup)?.[0]351+ ).not.toContain('disabled=""');352+ });353+354+ it("offers Accept once the draft is ready", () => {355+ const markup = card(ready);356+357+ expect(acceptOf(markup)).not.toContain('disabled=""');358+ expect(markup).not.toContain("Drafting…");359+ });360+361+ it("shows a check at the repo's root as code too", () => {362+ const markup = markupOf(363+ <DecisionCard364+ decision={{365+ ...opening,366+ evidence: [367+ ...opening.evidence,368+ { label: "offset.test.ts", value: "test('keeps +02:00');\n" },369+ ],370+ }}371+ draft={ready}372+ now={now}373+ onDecide={() => {}}374+ />375+ );376+377+ expect(markup).toMatch(/<h4[^>]*>offset\.test\.ts<\/h4>/u);378+ expect(markup).not.toMatch(/<dt[^>]*>offset\.test\.ts<\/dt>/u);379+ expect(markup).toMatch(/<dt[^>]*>want<\/dt>/u);380+ });381+382+ it("links the proposal's page", () => {383+ expect(card(ready)).toContain('href="/datekit/proposals/prop-000007"');384+ });385+});added:apps/web/test/proposal.test.tsx+367 added
1+/**2+ * A proposal's page, rendered to HTML with `react-dom/server` from a3+ * `showProposal` answer decoded with the protocol's own schema: the want and4+ * its proposer, where the platform's draft stands, the drafted files, the5+ * red-first evidence and who drafted it, the last refusal when it failed,6+ * "Draft again" for the proposer or a decider while it is open and not7+ * drafting, and the way to its decision when one is open.8+ */9+import { describe, expect, it } from "@effect/vitest";10+import { Brand } from "@repo/brand";11+import { DRAFT_ROUNDS } from "@repo/project/draft-runs";12+import { Client, Contracts, ShowProposal } from "@repo/protocol/contracts";13+import { ProjectEvent } from "@repo/protocol/domain/event";14+import { DraftState } from "@repo/protocol/domain/proposal";15+import { DecisionId, Handle, LaneName, ProjectName } from "@repo/protocol/ids";16+import { UnknownProject, UnknownProposal } from "@repo/protocol/refusal";17+import { asTester, unanswered } from "@repo/protocol/testing";18+import { isNotFound } from "@tanstack/react-router";19+import { DateTime, Effect, Layer, Option, Ref, Schema } from "effect";20+import { Atom, AtomRegistry, Reactivity } from "effect/reactivity";21+import { RpcTest } from "effect/rpc";22+23+import { projectTodayAtom } from "../src/client/proposal.ts";24+import { keysOf } from "../src/client/watch.ts";25+import {26+ DRAFT_ATTEMPTS,27+ ProposalView,28+} from "../src/features/proposal/proposal-view.tsx";29+import { readProposal } from "../src/routes/$project/proposals/$proposal.tsx";30+import { ContractsClient, webContracts } from "../src/surfaces.ts";31+import { markupOf, plainText } from "./ask-fixtures.ts";32+33+const datekit = ProjectName.make("datekit");34+35+const decodeShown = Schema.decodeUnknownSync(ShowProposal.successSchema);36+37+const model = "@cf/moonshotai/kimi-k2.7-code";38+39+const askFile = `${Brand.configDir}/asks/format-keeps-offset.ask.ts`;40+41+const testFile = "src/format.offset.test.ts";42+43+type Shown = typeof ShowProposal.successSchema.Type;44+45+/** A proposal with no draft yet, as `showProposal` answers it, holding `files`. */46+const shownWith = (files: readonly string[]): Shown =>47+ decodeShown({48+ files: files.map((path) => ({ content: `// ${path}\n`, path })),49+ proposal: {50+ expiresAt: "2026-10-21T09:00:00.000Z",51+ files,52+ id: "prop-000007",53+ openedAt: "2026-10-07T09:00:00.000Z",54+ project: "datekit",55+ proposer: "lin-h",56+ state: "open",57+ want: "formatISO keeps the offset it was given.",58+ },59+ });60+61+/** `base` with its proposal's draft at `draft`. */62+const withDraft = (base: Shown, draft: DraftState): Shown => ({63+ ...base,64+ proposal: { ...base.proposal, draft },65+});66+67+const drafting = withDraft(68+ shownWith([]),69+ DraftState.cases.Drafting.make({70+ round: 1,71+ startedAt: DateTime.makeUnsafe("2026-10-07T09:00:01Z"),72+ })73+);74+75+const ready = withDraft(76+ shownWith([askFile, testFile]),77+ DraftState.cases.Ready.make({78+ attempts: 2,79+ model,80+ red: {81+ lane: LaneName.make("unit"),82+ signature: "expected '+02:00', got 'Z'",83+ },84+ round: 1,85+ })86+);87+88+const failed = withDraft(89+ shownWith([]),90+ DraftState.cases.Failed.make({91+ attempts: 3,92+ model,93+ refusal: "NotRedFirst",94+ round: 2,95+ })96+);97+98+const decision = DecisionId.make("dec-000003");99+100+const view = (101+ { files, proposal }: Shown,102+ linked: Option.Option<DecisionId> = Option.none()103+) =>104+ markupOf(105+ <ProposalView106+ decision={linked}107+ files={files}108+ mayRedraft109+ project={datekit}110+ proposal={proposal}111+ />112+ );113+114+const DRAFT_AGAIN = /<button[^>]*>[^<]*Draft again/u;115+116+describe(ProposalView, () => {117+ it("shows the want and the proposer", () => {118+ const text = plainText(view(drafting));119+120+ expect(text).toContain("formatISO keeps the offset it was given.");121+ expect(text).toContain("lin-h");122+ });123+124+ it("while drafting, shows the spinner and no Draft again", () => {125+ const markup = view(drafting);126+127+ expect(markup).toContain('data-slot="spinner"');128+ expect(plainText(markup)).toContain("Drafting");129+ expect(markup).not.toMatch(DRAFT_AGAIN);130+ });131+132+ it("once ready, shows both files, the red-first run, who drafted it and its decision", () => {133+ const markup = view(ready, Option.some(decision));134+ const text = plainText(markup);135+136+ expect(text).toContain(askFile);137+ expect(text).toContain(testFile);138+ expect(text).toContain(139+ "fails twice the same way in lane unit: expected '+02:00', got 'Z'"140+ );141+ expect(text).toContain(`drafted by ${model}, attempt 2 of 3`);142+ expect(markup).toContain('href="/datekit/decisions/dec-000003"');143+ });144+145+ it("once ready, shows no spinner", () => {146+ expect(view(ready)).not.toContain('data-slot="spinner"');147+ });148+149+ it("once failed, shows the last refusal's headline and Draft again", () => {150+ const markup = view(failed);151+152+ expect(plainText(markup)).toContain("NotRedFirst");153+ expect(markup).toMatch(DRAFT_AGAIN);154+ });155+156+ it("offers Draft again only to the proposer or a decider", () => {157+ const markup = markupOf(158+ <ProposalView159+ decision={Option.none()}160+ files={[]}161+ mayRedraft={false}162+ project={datekit}163+ proposal={failed.proposal}164+ />165+ );166+167+ expect(markup).not.toMatch(DRAFT_AGAIN);168+ });169+170+ it("counts attempts out of the platform's own number of draft attempts", () => {171+ expect(DRAFT_ATTEMPTS).toBe(DRAFT_ROUNDS);172+ });173+174+ it("once accepted, offers no button", () => {175+ const accepted: Shown = {176+ ...ready,177+ proposal: { ...ready.proposal, state: "accepted" },178+ };179+180+ const markup = view(accepted);181+182+ expect(plainText(markup)).toContain("accepted");183+ expect(markup).not.toContain("<button");184+ });185+});186+187+/** A platform that knows datekit's prop-000007 only, counting what it is asked. */188+const platformHandlers = (189+ asked: Ref.Ref<{ proposal: number; today: number }>190+) =>191+ Layer.mergeAll(192+ unanswered,193+ Contracts.toLayerHandler("showProposal", ({ project, proposal }) =>194+ Effect.gen(function* () {195+ yield* Ref.update(asked, (seen) => ({196+ ...seen,197+ proposal: seen.proposal + 1,198+ }));199+200+ if (project !== datekit) {201+ return yield* new UnknownProject({ project });202+ }203+204+ if (proposal !== ready.proposal.id) {205+ return yield* new UnknownProposal({ proposal });206+ }207+208+ return ready;209+ })210+ ),211+ Contracts.toLayerHandler("today", () =>212+ Ref.update(asked, (seen) => ({ ...seen, today: seen.today + 1 })).pipe(213+ Effect.as({214+ budget: { finishes: 0, total: 5, used: 0 },215+ decider: Handle.make("okonkwo"),216+ decisions: [],217+ expiringSoon: [],218+ newcomers: [],219+ overflow: 0,220+ unattended: [],221+ })222+ )223+ ),224+ asTester225+ );226+227+const counted = () => Ref.make({ proposal: 0, today: 0 });228+229+describe(readProposal, () => {230+ it.effect("reads the proposal and its files, encoded for the page", () =>231+ Effect.gen(function* () {232+ const asked = yield* counted();233+234+ const read = yield* readProposal("datekit", "prop-000007").pipe(235+ Effect.provide(236+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(237+ Layer.provide(platformHandlers(asked))238+ )239+ )240+ );241+242+ expect(decodeShown(read).files.map(({ path }) => path)).toStrictEqual([243+ askFile,244+ testFile,245+ ]);246+ })247+ );248+249+ it.effect(250+ "is a not-found for a proposal or a project the platform does not know",251+ () =>252+ Effect.gen(function* () {253+ const asked = yield* counted();254+255+ const platform = Layer.effect(256+ Client,257+ RpcTest.makeClient(Contracts)258+ ).pipe(Layer.provide(platformHandlers(asked)));259+260+ const noProposal = yield* Effect.flip(261+ readProposal("datekit", "prop-000099").pipe(Effect.provide(platform))262+ );263+264+ const noProject = yield* Effect.flip(265+ readProposal("burrow", "prop-000007").pipe(Effect.provide(platform))266+ );267+268+ expect(isNotFound(noProposal)).toBeTruthy();269+ expect(isNotFound(noProject)).toBeTruthy();270+ expect((yield* Ref.get(asked)).proposal).toBe(2);271+ })272+ );273+274+ it.effect(275+ "is a not-found, asking nothing, for an address that names no proposal",276+ () =>277+ Effect.gen(function* () {278+ const asked = yield* counted();279+280+ const refused = yield* Effect.flip(281+ readProposal("datekit", "not a proposal").pipe(282+ Effect.provide(283+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(284+ Layer.provide(platformHandlers(asked))285+ )286+ )287+ )288+ );289+290+ expect(isNotFound(refused)).toBeTruthy();291+ expect((yield* Ref.get(asked)).proposal).toBe(0);292+ })293+ );294+});295+296+/** Lets the atoms' fibers run until `done` holds, or long enough that it would have. */297+const runUntil = (done: Effect.Effect<boolean>) =>298+ Effect.yieldNow.pipe(299+ Effect.andThen(done),300+ Effect.repeat({ times: 200, until: (held) => held })301+ );302+303+describe("the proposal page's Today", () => {304+ it.effect(305+ "reads again when the proposal's draft settles, so its new decision is linked",306+ () =>307+ Effect.gen(function* () {308+ const asked = yield* counted();309+310+ // One browser tab whose `ContractsClient` reaches the stub platform in process.311+ const registry = yield* Effect.acquireRelease(312+ Effect.sync(() =>313+ AtomRegistry.make({314+ initialValues: [315+ Atom.initialValue(316+ ContractsClient.runtime.layer,317+ Layer.effect(318+ ContractsClient,319+ RpcTest.makeClient(webContracts, { flatten: true })320+ ).pipe(321+ Layer.provide(platformHandlers(asked)),322+ Layer.provideMerge(Reactivity.layer)323+ )324+ ),325+ ],326+ })327+ ),328+ (made) =>329+ Effect.sync(() => {330+ made.dispose();331+ })332+ );333+334+ const today = projectTodayAtom(datekit);335+336+ registry.mount(today);337+ yield* AtomRegistry.getResult(registry, today, {338+ suspendOnWaiting: true,339+ });340+341+ // What the watch does on `ProposalDrafted` (`keysOf` in `watch.ts`).342+ yield* AtomRegistry.getResult(343+ registry,344+ ContractsClient.runtime.atom(345+ Reactivity.invalidate(346+ keysOf(347+ datekit,348+ ProjectEvent.cases.ProposalDrafted.make({349+ at: DateTime.makeUnsafe("2026-10-07T09:05:00Z"),350+ proposal: ready.proposal.id,351+ ready: true,352+ seq: 4,353+ })354+ )355+ )356+ ),357+ { suspendOnWaiting: true }358+ );359+360+ expect(361+ yield* runUntil(362+ Ref.get(asked).pipe(Effect.map(({ today: seen }) => seen > 1))363+ )364+ ).toBeTruthy();365+ })366+ );367+});added:apps/web/test/propose.test.tsx+211 added
1+/**2+ * The propose form, rendered to HTML with `react-dom/server`: a signed-in3+ * member writes a want, may name a territory from the project's top4+ * folders, and lets the platform's agent draft the ask (checked by5+ * default). A line from the why page arrives as `?about&line&at` and starts6+ * the want. Signed out, the page offers sign-in and no form. What the form7+ * sends is the `proposeAsk` contract's own payload.8+ */9+import { describe, expect, it } from "@effect/vitest";10+import { Brand } from "@repo/brand";11+import { ProposeAsk } from "@repo/protocol/contracts";12+import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";13+import { CapReached } from "@repo/protocol/refusal";14+import { Option, Schema } from "effect";15+import { AsyncResult } from "effect/reactivity";16+17+import { proposalMade, topFolders } from "../src/client/propose.ts";18+import {19+ ProposeView,20+ proposalPayload,21+} from "../src/features/propose/propose-view.tsx";22+import type { About } from "../src/features/propose/propose-view.tsx";23+import { markupOf, plainText } from "./ask-fixtures.ts";24+25+const datekit = ProjectName.make("datekit");26+27+const at = CommitSha.make("4c2e6a8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c");28+29+const modules = [RepoPath.make("docs"), RepoPath.make("src")];30+31+const signedIn = (about: Option.Option<About> = Option.none()) =>32+ markupOf(33+ <ProposeView about={about} modules={modules} project={datekit} signedIn />34+ );35+36+/** The want's textarea, as the server renders it: its opening tag and text. */37+const textareaOf = (markup: string) =>38+ /<textarea[^>]*>(?<text>[^<]*)<\/textarea>/u.exec(markup);39+40+describe(ProposeView, () => {41+ it("signed in, offers a want and the draft box, checked", () => {42+ const markup = signedIn();43+44+ expect(textareaOf(markup)?.[0]).toContain('name="want"');45+ expect(markup).toMatch(46+ /role="checkbox"[^>]*aria-checked="true"|aria-checked="true"[^>]*role="checkbox"/u47+ );48+ expect(plainText(markup)).toContain(49+ "Let the platform's agent draft the ask"50+ );51+ expect(markup).toMatch(/<button[^>]*type="submit"[^>]*>Propose/u);52+ });53+54+ it("offers each of the project's top folders as the territory", () => {55+ const markup = signedIn();56+57+ expect(markup).toContain('name="territory"');58+ expect(markup).toContain('<option value="src">src</option>');59+ expect(markup).toContain('<option value="docs">docs</option>');60+ });61+62+ it("starts the want at the line a why page names", () => {63+ const markup = signedIn(64+ Option.some({ at, line: 12, path: RepoPath.make("src/format.ts") })65+ );66+67+ expect(textareaOf(markup)?.groups?.text).toBe(68+ "In `src/format.ts` line 12 at 4c2e6a8: "69+ );70+ });71+72+ it("signed out, shows no form and links to sign in", () => {73+ const markup = markupOf(74+ <ProposeView75+ about={Option.none()}76+ modules={modules}77+ project={datekit}78+ signedIn={false}79+ />80+ );81+82+ expect(markup).not.toContain("<form");83+ expect(markup).not.toContain("<textarea");84+ expect(markup).toMatch(/<a[^>]*href="\/auth\/signin[^"]*"[^>]*>Sign in/u);85+ });86+});87+88+describe(proposalPayload, () => {89+ const isPayload = Schema.is(ProposeAsk.payloadSchema);90+91+ it("asks for a draft when the box is checked", () => {92+ const payload = proposalPayload({93+ draft: true,94+ project: datekit,95+ want: " formatISO keeps the offset. ",96+ });97+98+ expect(payload).toStrictEqual({99+ draft: true,100+ project: "datekit",101+ want: "formatISO keeps the offset.",102+ });103+ expect(isPayload(payload)).toBeTruthy();104+ });105+106+ it("carries no draft key when the box is clear, and the territory when named", () => {107+ const payload = proposalPayload({108+ draft: false,109+ project: datekit,110+ territory: RepoPath.make("src"),111+ want: "formatISO keeps the offset.",112+ });113+114+ expect(payload).toStrictEqual({115+ project: "datekit",116+ territory: "src",117+ want: "formatISO keeps the offset.",118+ });119+ expect(Object.hasOwn(payload, "draft")).toBeFalsy();120+ });121+});122+123+describe(topFolders, () => {124+ it("offers each top folder once, sorted, and no dot folder or root file", () => {125+ expect(126+ topFolders(127+ [128+ "src/format.ts",129+ "README.md",130+ `${Brand.configDir}/asks/x.ask.ts`,131+ "test/format.test.ts",132+ "src/parse/iso.ts",133+ ".github/workflows/ci.yml",134+ "docs/guide.md",135+ ].map((path) => RepoPath.make(path))136+ )137+ ).toStrictEqual(["docs", "src", "test"]);138+ });139+});140+141+/** `proposeAsk`'s answer: the proposal `id`, made. */142+const made = (id: string) =>143+ Schema.decodeUnknownSync(ProposeAsk.successSchema)({144+ proposal: {145+ expiresAt: "2026-10-21T09:00:00.000Z",146+ files: [],147+ id,148+ openedAt: "2026-10-07T09:00:00.000Z",149+ project: "datekit",150+ proposer: "lin-h",151+ state: "open",152+ want: "formatISO keeps the offset.",153+ },154+ });155+156+describe(proposalMade, () => {157+ const earlier = AsyncResult.success(made("prop-000004"));158+159+ it("names the proposal a send made, once it answered", () => {160+ expect(161+ proposalMade(AsyncResult.success(made("prop-000005")))162+ ).toStrictEqual(Option.some("prop-000005"));163+ });164+165+ it("names none while a later send is on its way, or after it was refused", () => {166+ expect(proposalMade(AsyncResult.waiting(earlier))).toStrictEqual(167+ Option.none()168+ );169+ expect(170+ proposalMade(171+ AsyncResult.fail(new CapReached({ cap: 3 }), {172+ previousSuccess: Option.some(earlier),173+ })174+ )175+ ).toStrictEqual(Option.none());176+ });177+});178+179+describe("the sign-in link", () => {180+ it("comes back to the form, at the line a why page named", () => {181+ const markup = markupOf(182+ <ProposeView183+ about={Option.some({184+ at,185+ line: 12,186+ path: RepoPath.make("src/format.ts"),187+ })}188+ modules={modules}189+ project={datekit}190+ signedIn={false}191+ />192+ );193+194+ const href = /href="(?<href>\/auth\/signin[^"]*)"/u195+ .exec(markup)196+ ?.groups?.href?.replaceAll("&", "&");197+198+ const back = new URL(href ?? "/", "https://web.test").searchParams.get(199+ "return"200+ );201+202+ const there = new URL(back ?? "/", "https://web.test");203+204+ expect(there.pathname).toBe("/datekit/proposals/new");205+ expect(Object.fromEntries(there.searchParams)).toStrictEqual({206+ about: "src/format.ts",207+ at,208+ line: "12",209+ });210+ });211+});