Add the web's propose form and proposal page, and show a proposal's files in its decision
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- /$project/proposals/new: a want, an optional territory (the project's top folders from listPaths, dot folders excluded) and "Let the platform's agent draft the ask", checked by default; prefilled from ?about&line&at as "In `<path>` line <n> at <short sha>: ". Signed out it offers sign-in and the CLI line, no form. Propose sends proposeAsk (draft: true only when checked; the contract has no draft: false) and goes to the proposal page once it is made; a refusal shows through RefusalView under the form. - /$project/proposals/$proposal: the loader reads showProposal on the server (404 for an unknown project or proposal); in the browser the project's watch re-reads it on ProposalDrafted. Shows the want, the proposer, the state badge, the drafted files (client-only Pierre File over a <pre> fallback), the red-first line, "drafted by <model>, attempt n of 3", the last refusal's tag when Failed, a link to the open decision from the reader's Today, and "Draft again" (draftAsk, optional note) for the proposer or a decider while open and not drafting. - DecisionCard: for an OpenProposal, evidence whose label is a path is a heading over its code instead of a <dt>, the card links the proposal page, and Accept is disabled with "Drafting..." while the draft is Drafting (a passed `draft`, else read live from showProposal). - Project page: "Propose an ask" beside Open asks, for signed-in people. - Decision: the live reads (who is signed in, a proposal's draft) live in features/propose/propose-link.tsx and features/proposal/live-draft.ts, because the routes that render ProjectView and DecisionCard are outside this issue's territory and features/project must import no transport (test/project.test.tsx). - Decision: navigation after Propose waits on a local "sent" flag, so a proposal the atom still holds from an earlier visit never moves the page. - Tests: test/propose.test.tsx, test/proposal.test.tsx, four new cases in test/decision.test.tsx; each red by assertion over empty views first. - ASSUMPTION: DRAFT_ATTEMPTS = 3 mirrors @repo/project's DRAFT_ROUNDS, which the web cannot import. - ASSUMPTION: a decision's evidence label is a file when it is one word with a slash (909 labels files by path, everything else by words).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+1642 added−77 removed
- tests:+377 added−1 removed
- other:+1265 added−76 removed
Provenance
- Commit
2d0e927- Tree
543dee9- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
bbe1442
15 files changed+1642 added−77 removed
added:apps/web/src/client/proposal.ts+61 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061/** * 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). 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";import { todayAtom } from "./today.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. */export const projectTodayAtom = Atom.family((project: ProjectName) => Atom.withServerValueInitial(todayAtom(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+60 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960/** * 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 } from "@repo/protocol/ids";import { Array, Effect, Option, Order, Schema } from "effect";import { 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); }) ) ) ));
/** 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+168 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, as the ask file's), where every other label is words.127+ */128+export const isFileFact = ({ label }: Fact) => /^\S+\/\S+$/u.test(label);129+130+/** The files an `OpenProposal` decision holds, shown as code; none for any other subject. */131+const filesOf = (decision: Decision): readonly Fact[] =>132+ opensAsk(decision.subject) ? decision.evidence.filter(isFileFact) : [];133+134+const Facts = ({ facts }: { readonly facts: readonly Fact[] }) => (135+ <dl className="grid grid-cols-1 gap-x-4 gap-y-1 sm:grid-cols-[minmax(8rem,auto)_1fr]">136+ {facts.map(({ href, label, value }) => (137+ <div className="contents" key={`${label}:${value}`}>138+ <dt className={`${LABEL} pt-0.5`}>{label}</dt>139+ <dd className="mb-1.5 text-sm [overflow-wrap:anywhere] sm:mb-0">140+ {href === undefined ? (141+ value142+ ) : (143+ <a144+ className="decoration-rule underline hover:decoration-current"145+ href={href}146+ >147+ {value}148+ </a>149+ )}150+ </dd>151+ </div>152+ ))}153+ </dl>154+);155+156 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);157+ // The diff is the finish page's; here it is only counted. A proposal's158+ // files are drawn as code below the facts.159+ const files = filesOf(decision);160 111- if (facts.length === 0) {112- return null;113- }161+ const facts = decision.evidence.filter(162+ (fact) => fact.label !== PATCH_LABEL && !files.includes(fact)163+ );164 165 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>166+ <>167+ {facts.length === 0 ? null : <Facts facts={facts} />}168+ {files.map(({ label, value }) => (169+ <DraftedCode content={value} heading="h4" key={label} path={label} />170 ))}134- </dl>171+ </>172 );173 };174 175 /** The way from a `Finish` decision on Today to its answer's diff. */17 unmodified lines193 </a>194 );195 };196 197+/** The way from an `OpenProposal` decision to the proposal's page: its draft and files. */198+const ProposalLink = ({199+ project,200+ proposal,201+}: {202+ readonly project: ProjectName;203+ readonly proposal: ProposalId;204+}) => (205+ <a206+ className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"207+ href={`/${project}/proposals/${proposal}`}208+ >209+ <FileText aria-hidden="true" className="size-4 shrink-0" />210+ Read the proposal211+ </a>212+);213+214+interface ChoicesProps {215+ readonly busy: boolean;216+ readonly choose: (choice: Choice) => void;217+ readonly decision: Decision;218+ readonly subject: string;219+}220+221+/** One button per choice; Accept waits while the proposal is drafting. */222+const Choices = ({223+ busy,224+ choose,225+ decision,226+ drafting,227+ subject,228+}: ChoicesProps & { readonly drafting: boolean }) => (229+ <fieldset className="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap">230+ <legend className="sr-only">Your choice: {subject}</legend>231+ {allowedChoices(decision.subject).map((choice) => {232+ const isDefault = choice === decision.default;233+ const held = drafting && choice === "accept";234+235+ return (236+ <Button237+ className="h-11 px-4 text-sm sm:h-9 sm:min-w-28"238+ data-choice={choice}239+ disabled={busy || held}240+ key={choice}241+ onClick={() => {242+ choose(choice);243+ }}244+ type="button"245+ variant={isDefault ? "outline" : "default"}246+ >247+ {held ? (248+ <>249+ <Spinner />250+ Drafting…251+ </>252+ ) : (253+ words[choice]254+ )}255+ {isDefault ? (256+ <span className="text-muted-foreground font-normal">default</span>257+ ) : null}258+ </Button>259+ );260+ })}261+ </fieldset>262+);263+264+/** The choices on a proposal whose draft state was not passed: read from `showProposal`. */265+const ProposalChoices = ({266+ proposal,267+ ...props268+}: ChoicesProps & { readonly proposal: ProposalId }) => {269+ const draft = useLiveDraft(props.decision.project, proposal);270+271+ return <Choices {...props} drafting={Option.exists(draft, isDraftingNow)} />;272+};273+274 export const DecisionCard = ({275 busy = false,276 children,277 decision,278+ draft,279 now,280 onDecide,281 soon = false,282 standalone = false,8 unmodified lines291 /** Whether it is shown on its own page, so its title needs no link there. */292 readonly standalone?: boolean;293 /** What its own page shows before the choices: for a finish, the diff. */294 readonly children?: ReactNode;295+ /**296+ * For an `OpenProposal`, where the proposal's draft stands: Accept waits297+ * while it is drafting. Read from `showProposal` when not passed.298+ */299+ readonly draft?: DraftState | undefined;300 }) => {301 const [note, setNote] = useState("");302 const noteId = useId();303 const subject = describeSubject(decision.subject);66 unmodified lines370 {isFinishDecision(decision) && !standalone ? (371 <FinishLink decision={decision} />372 ) : null}373 374+ {opensAsk(decision.subject) ? (375+ <ProposalLink376+ project={decision.project}377+ proposal={decision.subject.proposal}378+ />379+ ) : null}380+381 {children === undefined ? null : (382 <div className="border-rule mt-3 flex flex-col gap-8 border-t pt-6">383 {children}384 </div>15 unmodified lines400 value={note}401 />402 </details>403 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>404+ {opensAsk(decision.subject) && draft === undefined ? (405+ <ProposalChoices406+ busy={busy}407+ choose={choose}408+ decision={decision}409+ proposal={decision.subject.proposal}410+ subject={subject}411+ />412+ ) : (413+ <Choices414+ busy={busy}415+ choose={choose}416+ decision={decision}417+ drafting={draft !== undefined && isDraftingNow(draft)}418+ subject={subject}419+ />420+ )}421 </article>422 );423 };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+287 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 cannot import.34+ */35+export const DRAFT_ATTEMPTS = 3;36+37+/** The longest note `draftAsk` takes. */38+const NOTE_LIMIT = 2000;39+40+/** Where a proposal stands in one word: its draft's while it is open, else its own. */41+export const standing = (proposal: Proposal) =>42+ proposal.state === "open" && proposal.draft !== undefined43+ ? proposal.draft._tag44+ : proposal.state;45+46+const draftingNow = DraftState.isAnyOf(["Drafting"]);47+48+/** Whether the platform's agent is drafting the proposal's ask right now. */49+export const isDrafting = (proposal: Proposal) =>50+ proposal.draft !== undefined && draftingNow(proposal.draft);51+52+const LABEL = "text-muted-foreground text-xs font-medium";53+54+/** The badge each standing wears: an ending that opened nothing reads as refused. */55+const badgeVariant = {56+ Drafting: "outline",57+ Failed: "destructive",58+ Ready: "secondary",59+ accepted: "secondary",60+ declined: "destructive",61+ expired: "destructive",62+ open: "secondary",63+} as const satisfies Record<ReturnType<typeof standing>, string>;64+65+const StateBadge = ({ proposal }: { readonly proposal: Proposal }) => {66+ const word = standing(proposal);67+68+ return (69+ <Badge data-standing={word} variant={badgeVariant[word]}>70+ {word === "Drafting" ? <Spinner className="size-3" /> : null}71+ {word}72+ </Badge>73+ );74+};75+76+/** What the draft says: in progress, ready with its red-first run, or failed. */77+const DraftFacts = ({ draft }: { readonly draft: DraftState }) =>78+ DraftState.match(draft, {79+ Drafting: ({ round }) => (80+ <p className="flex items-start gap-2 text-sm" data-draft="Drafting">81+ <Spinner className="text-checking mt-0.5 shrink-0" />82+ <span>83+ Drafting (round {round}): the platform's agent is writing the ask84+ and a check, then running the check on main, where it must fail twice85+ the same way. This takes a few minutes; the page follows it.86+ </span>87+ </p>88+ ),89+ Failed: ({ attempts, model, refusal, round }) => (90+ <div className="flex flex-col gap-1 text-sm" data-draft="Failed">91+ <p className="flex items-start gap-2">92+ <OctagonX93+ aria-hidden="true"94+ className="text-refused mt-0.5 size-4 shrink-0"95+ />96+ <span>97+ The draft failed (round {round}), after {attempts} of{" "}98+ {DRAFT_ATTEMPTS} attempts by {model}. The last refusal:{" "}99+ <b className="text-refused font-mono font-semibold">{refusal}</b>100+ </span>101+ </p>102+ </div>103+ ),104+ Ready: ({ attempts, model, red }) => (105+ <dl106+ className="grid grid-cols-1 gap-x-4 gap-y-1 text-sm sm:grid-cols-[minmax(8rem,auto)_1fr]"107+ data-draft="Ready"108+ >109+ <dt className={`${LABEL} pt-0.5`}>Red first</dt>110+ <dd className="mb-1.5 flex items-start gap-2 [overflow-wrap:anywhere] sm:mb-0">111+ <CircleCheck112+ aria-hidden="true"113+ className="text-landed mt-0.5 size-4 shrink-0"114+ />115+ <span>116+ fails twice the same way in lane {red.lane}: {red.signature}117+ </span>118+ </dd>119+ <dt className={`${LABEL} pt-0.5`}>Drafted by</dt>120+ <dd className="mb-1.5 [overflow-wrap:anywhere] sm:mb-0">121+ drafted by {model}, attempt {attempts} of {DRAFT_ATTEMPTS}122+ </dd>123+ </dl>124+ ),125+ });126+127+/** "Draft again", with a note the agent reads. */128+const Redraft = ({129+ again,130+ busy,131+ onRedraft,132+}: {133+ readonly again: boolean;134+ readonly busy: boolean;135+ readonly onRedraft: (note: string | undefined) => void;136+}) => {137+ const [note, setNote] = useState("");138+ const noteId = useId();139+140+ return (141+ <section142+ aria-label="Draft again"143+ className="border-rule flex flex-col gap-3 border-t pt-4"144+ >145+ <details className="text-sm">146+ <summary className="text-muted-foreground hover:text-foreground w-fit cursor-pointer py-1 select-none">147+ Add a note for the agent148+ </summary>149+ <label className={`${LABEL} mt-2 block`} htmlFor={noteId}>150+ What the next draft should do differently151+ </label>152+ <Textarea153+ className="mt-1 text-sm md:text-sm"154+ id={noteId}155+ maxLength={NOTE_LIMIT}156+ onChange={(event) => {157+ setNote(event.target.value);158+ }}159+ value={note}160+ />161+ </details>162+ <Button163+ className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"164+ disabled={busy}165+ onClick={() => {166+ const written = note.trim();167+168+ onRedraft(written.length === 0 ? undefined : written);169+ }}170+ type="button"171+ variant="outline"172+ >173+ {again ? "Draft again" : "Let the platform's agent draft it"}174+ </Button>175+ </section>176+ );177+};178+179+/** The way to the open decision that would open the ask. */180+const DecisionLink = ({181+ decision,182+ project,183+}: {184+ readonly decision: DecisionId;185+ readonly project: ProjectName;186+}) => (187+ <a188+ className="decoration-rule flex w-fit items-center gap-2 text-sm font-medium underline hover:decoration-current"189+ data-decision={decision}190+ href={`/${project}/decisions/${decision}`}191+ >192+ <Scale aria-hidden="true" className="size-4 shrink-0" />193+ Decide it: {decision}194+ </a>195+);196+197+export const ProposalView = ({198+ busy = false,199+ children,200+ decision,201+ files,202+ mayRedraft,203+ onRedraft = constVoid,204+ project,205+ proposal,206+}: {207+ readonly project: ProjectName;208+ readonly proposal: Proposal;209+ /** The files the proposal holds (the ask file and its check), as `showProposal` read them. */210+ readonly files: readonly ConfigFile[];211+ /** The open decision on the proposal, when the reader's Today holds it. */212+ readonly decision: Option.Option<DecisionId>;213+ /** Whether the reader is its proposer or one of the project's deciders. */214+ readonly mayRedraft: boolean;215+ readonly onRedraft?: (note: string | undefined) => void;216+ /** Whether a "Draft again" is on its way: the button waits. */217+ readonly busy?: boolean;218+ /** What the last "Draft again" came back with, when it was refused. */219+ readonly children?: ReactNode;220+}): ReactNode => {221+ const open = proposal.state === "open";222+223+ return (224+ <article225+ aria-labelledby={`${proposal.id}-want`}226+ className="flex max-w-[90ch] min-w-0 flex-col gap-5"227+ data-proposal={proposal.id}228+ >229+ <header className="flex flex-col gap-2">230+ <p className="text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">231+ <span className="font-mono">{project}</span>232+ <span aria-hidden="true">·</span>233+ <span className="font-mono">{proposal.id}</span>234+ <StateBadge proposal={proposal} />235+ </p>236+ <h2237+ className="text-lg font-semibold text-balance [overflow-wrap:anywhere]"238+ id={`${proposal.id}-want`}239+ >240+ {proposal.want}241+ </h2>242+ <p className="text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-sm">243+ <span>244+ Proposed by <HandleLink handle={proposal.proposer} />245+ </span>246+ {proposal.territory === undefined ? null : (247+ <span>248+ in <code className="font-mono">{proposal.territory}</code>249+ </span>250+ )}251+ </p>252+ </header>253+254+ {proposal.draft === undefined ? null : (255+ <DraftFacts draft={proposal.draft} />256+ )}257+258+ {Option.isSome(decision) ? (259+ <DecisionLink decision={decision.value} project={project} />260+ ) : null}261+262+ {files.length === 0 ? null : (263+ <section264+ aria-labelledby={`${proposal.id}-files`}265+ className="flex min-w-0 flex-col gap-4"266+ >267+ <h2 className="text-base font-semibold" id={`${proposal.id}-files`}>268+ {proposal.draft === undefined ? "Proposed files" : "Drafted files"}269+ </h2>270+ {files.map(({ content, path }) => (271+ <DraftedCode content={content} key={path} path={path} />272+ ))}273+ </section>274+ )}275+276+ {children}277+278+ {mayRedraft && open && !isDrafting(proposal) ? (279+ <Redraft280+ again={proposal.draft !== undefined}281+ busy={busy}282+ onRedraft={onRedraft}283+ />284+ ) : null}285+ </article>286+ );287+};added:apps/web/src/features/propose/propose-link.tsx+38 added
1234567891011121314151617181920212223242526272829303132333435363738/** * 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";
/** The form's address for `project`. */export const proposeFormPath = (project: ProjectName) => `/${project}/proposals/new`;
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+215 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+/** The form's own address, for sign-in to come back to. */64+const proposePath = (project: ProjectName) => `/${project}/proposals/new`;65+66+const LABEL = "text-muted-foreground text-xs font-medium";67+68+const SignInFirst = ({ project }: { readonly project: ProjectName }) => (69+ <section70+ aria-label="Sign in to propose"71+ className="border-rule flex flex-col gap-3 border-t pt-4"72+ >73+ <p className="flex items-start gap-2 text-sm">74+ <LogIn aria-hidden="true" className="mt-0.5 size-4 shrink-0" />75+ <span>76+ Proposing an ask is for signed-in members.{" "}77+ <a78+ className="decoration-rule font-medium underline hover:decoration-current"79+ href={`/auth/signin?${new URLSearchParams({ return: proposePath(project) }).toString()}`}80+ >81+ Sign in82+ </a>{" "}83+ to propose one, or propose from your clone:84+ </span>85+ </p>86+ <CommandLine command={`${Brand.cli} propose --draft "<want>"`} />87+ </section>88+);89+90+export const ProposeView = ({91+ about,92+ busy = false,93+ children,94+ modules,95+ onPropose,96+ project,97+ signedIn,98+}: {99+ readonly project: ProjectName;100+ readonly signedIn: boolean;101+ readonly about: Option.Option<About>;102+ /** The project's top folders, each a territory to choose. */103+ readonly modules: readonly RepoPath[];104+ /** Sends the payload; the route goes to the proposal once it is made. */105+ readonly onPropose?: (payload: ProposePayload) => void;106+ /** Whether a proposal is on its way: the button waits. */107+ readonly busy?: boolean;108+ /** What the last proposal came back with, when it was refused. */109+ readonly children?: ReactNode;110+}): ReactNode => {111+ const id = useId();112+113+ const [want, setWant] = useState(() =>114+ Option.match(about, { onNone: () => "", onSome: wantAbout })115+ );116+117+ const [territory, setTerritory] = useState("");118+ const [draft, setDraft] = useState(true);119+120+ if (!signedIn) {121+ return <SignInFirst project={project} />;122+ }123+124+ const chosen = modules.find((module) => module === territory);125+ const written = want.trim().length > 0;126+127+ return (128+ <form129+ aria-label="Propose an ask"130+ className="flex max-w-[70ch] flex-col gap-5"131+ onSubmit={(event) => {132+ event.preventDefault();133+134+ if (written) {135+ onPropose?.(136+ proposalPayload(137+ chosen === undefined138+ ? { draft, project, want }139+ : { draft, project, territory: chosen, want }140+ )141+ );142+ }143+ }}144+ >145+ <div className="flex flex-col gap-1.5">146+ <label className={LABEL} htmlFor={`${id}-want`}>147+ What should the project do that it does not do now?148+ </label>149+ <Textarea150+ className="min-h-32 text-sm md:text-sm"151+ id={`${id}-want`}152+ name="want"153+ onChange={(event) => {154+ setWant(event.target.value);155+ }}156+ required157+ value={want}158+ />159+ </div>160+161+ <div className="flex flex-col gap-1.5">162+ <label className={LABEL} htmlFor={`${id}-territory`}>163+ Territory (optional)164+ </label>165+ <select166+ className="border-input bg-background h-9 w-full max-w-xs rounded-none border px-2 text-sm"167+ id={`${id}-territory`}168+ name="territory"169+ onChange={(event) => {170+ setTerritory(event.target.value);171+ }}172+ value={territory}173+ >174+ <option value="">Let the agent choose</option>175+ {modules.map((module) => (176+ <option key={module} value={module}>177+ {module}178+ </option>179+ ))}180+ </select>181+ </div>182+183+ <div className="flex items-start gap-2">184+ <Checkbox185+ checked={draft}186+ className="mt-0.5"187+ id={`${id}-draft`}188+ name="draft"189+ onCheckedChange={(checked) => {190+ setDraft(checked);191+ }}192+ />193+ <Label className="text-sm leading-snug" htmlFor={`${id}-draft`}>194+ Let the platform's agent draft the ask195+ </Label>196+ </div>197+ <p className="text-muted-foreground -mt-3 pl-6 text-xs">198+ It writes the ask file and a check that fails on main, runs it red199+ first, and puts the draft to a decider. Clear the box to propose the200+ want alone.201+ </p>202+203+ {children}204+205+ <Button206+ className="h-11 w-full px-4 text-sm sm:h-9 sm:w-fit sm:min-w-28"207+ disabled={busy || !written}208+ type="submit"209+ >210+ {busy ? <Spinner /> : null}211+ Propose212+ </Button>213+ </form>214+ );215+};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+123 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 { modulesAtom, proposeAtom } from "../../../client/propose.ts";9+import { whoAtom } from "../../../features/auth/who.ts";10+import { ProjectNav } from "../../../features/project/project-nav.tsx";11+import { UnknownProjectView } from "../../../features/project/unknown-project.tsx";12+import { ProposeView } from "../../../features/propose/propose-view.tsx";13+import type { About } from "../../../features/propose/propose-view.tsx";14+import { PageShell, pageTitle } from "../../../features/shared/layout.tsx";15+import { FailureView } from "../../../features/today/today-page.tsx";16 6-// The propose form: a want, for the platform's agent to draft into an ask. A stub until 911 builds it.17+// `/$project/proposals/new`: the propose form. Who is signed in and the18+// project's top folders are read in the browser (the server paints the19+// page while it checks); a proposal made goes to its own page, a refusal20+// shows under the form. `?about=<path>&line=<n>&at=<sha>` (the why page's21+// "Propose an ask about this line") starts the want at that line.22 8-const Page = () => {9- const { project } = Route.useParams();23+const decodeProject = Schema.decodeUnknownOption(ProjectName);24 25+/** The line a why page points at, when the address names all three parts. */26+const AboutParts = Schema.Struct({27+ about: RepoPath,28+ at: CommitSha,29+ line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),30+});31+32+const decodeAbout = Schema.decodeUnknownOption(AboutParts);33+34+const decodeText = Schema.decodeUnknownOption(Schema.String);35+36+const decodeLine = Schema.decodeUnknownOption(Schema.Int);37+38+/** The address's line, as the form takes it. */39+const aboutOf = (search: {40+ readonly about?: string | undefined;41+ readonly at?: string | undefined;42+ readonly line?: number | undefined;43+}): Option.Option<About> =>44+ Option.map(decodeAbout(search), ({ about, at, line }) => ({45+ at,46+ line,47+ path: about,48+ }));49+50+const Checking = () => (51+ <output className="text-muted-foreground block text-sm">52+ Checking who is signed in53+ </output>54+);55+56+/** The form for `project`, once the browser knows who is signed in. */57+const Propose = ({ project }: { readonly project: ProjectName }) => {58+ const navigate = useNavigate();59+ const search = Route.useSearch();60+ const who = useAtomValue(whoAtom);61+62+ const modules = Option.getOrElse(63+ AsyncResult.value(useAtomValue(modulesAtom(project))),64+ () => []65+ );66+67+ const [proposed, propose] = useAtom(proposeAtom);68+ // Set once this form sends: a proposal the atom still holds from an69+ // earlier visit never moves the page.70+ const [sent, setSent] = useState(false);71+72+ const made = sent73+ ? Option.getOrUndefined(AsyncResult.value(proposed))?.proposal.id74+ : undefined;75+76+ useEffect(() => {77+ if (made !== undefined) {78+ void navigate({79+ params: { project, proposal: made },80+ to: "/$project/proposals/$proposal",81+ });82+ }83+ }, [made, navigate, project]);84+85+ if (!AsyncResult.isSuccess(who)) {86+ return <Checking />;87+ }88+89 return (12- <NotBuilt13- issue="911"90+ <ProposeView91+ about={aboutOf(search)}92+ busy={proposed.waiting}93+ modules={modules}94+ onPropose={(payload) => {95+ setSent(true);96+ propose(payload);97+ }}98 project={project}15- title={`${project}: propose an ask`}16- />99+ signedIn={Option.isSome(who.value)}100+ >101+ {AsyncResult.isFailure(proposed) ? (102+ <div aria-live="polite">103+ <FailureView cause={proposed.cause} />104+ </div>105+ ) : null}106+ </ProposeView>107 );108 };109 110+const Page = () => {111+ const params = Route.useParams();112+113+ return Option.match(decodeProject(params.project), {114+ onNone: () => <UnknownProjectView name={params.project} />,115+ onSome: (project) => (116+ <PageShell title={`${project}: propose an ask`}>117+ <ProjectNav project={project} />118+ <Propose project={project} />119+ </PageShell>120+ ),121+ });122+};123+124 export const Route = createFileRoute("/$project/proposals/new")({125 component: Page,126+ validateSearch: (search: {127+ readonly about?: unknown;128+ readonly at?: unknown;129+ readonly line?: unknown;130+ }) => ({131+ about: Option.getOrUndefined(decodeText(search.about)),132+ at: Option.getOrUndefined(decodeText(search.at)),133+ line: Option.getOrUndefined(decodeLine(search.line)),134+ }),135 head: ({ params: { project } }) => ({136 meta: [{ title: pageTitle(`${project}: propose an ask`) }],137 }),138 });modified:apps/web/test/decision.test.tsx+93 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("links the proposal's page", () => {362+ expect(card(ready)).toContain('href="/datekit/proposals/prop-000007"');363+ });364+});added:apps/web/test/proposal.test.tsx+167 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 { ShowProposal } from "@repo/protocol/contracts";12+import { DraftState } from "@repo/protocol/domain/proposal";13+import { DecisionId, LaneName, ProjectName } from "@repo/protocol/ids";14+import { DateTime, Option, Schema } from "effect";15+16+import { ProposalView } from "../src/features/proposal/proposal-view.tsx";17+import { markupOf, plainText } from "./ask-fixtures.ts";18+19+const datekit = ProjectName.make("datekit");20+21+const decodeShown = Schema.decodeUnknownSync(ShowProposal.successSchema);22+23+const model = "@cf/moonshotai/kimi-k2.7-code";24+25+const askFile = `${Brand.configDir}/asks/format-keeps-offset.ask.ts`;26+27+const testFile = "src/format.offset.test.ts";28+29+type Shown = typeof ShowProposal.successSchema.Type;30+31+/** A proposal with no draft yet, as `showProposal` answers it, holding `files`. */32+const shownWith = (files: readonly string[]): Shown =>33+ decodeShown({34+ files: files.map((path) => ({ content: `// ${path}\n`, path })),35+ proposal: {36+ expiresAt: "2026-10-21T09:00:00.000Z",37+ files,38+ id: "prop-000007",39+ openedAt: "2026-10-07T09:00:00.000Z",40+ project: "datekit",41+ proposer: "lin-h",42+ state: "open",43+ want: "formatISO keeps the offset it was given.",44+ },45+ });46+47+/** `base` with its proposal's draft at `draft`. */48+const withDraft = (base: Shown, draft: DraftState): Shown => ({49+ ...base,50+ proposal: { ...base.proposal, draft },51+});52+53+const drafting = withDraft(54+ shownWith([]),55+ DraftState.cases.Drafting.make({56+ round: 1,57+ startedAt: DateTime.makeUnsafe("2026-10-07T09:00:01Z"),58+ })59+);60+61+const ready = withDraft(62+ shownWith([askFile, testFile]),63+ DraftState.cases.Ready.make({64+ attempts: 2,65+ model,66+ red: {67+ lane: LaneName.make("unit"),68+ signature: "expected '+02:00', got 'Z'",69+ },70+ round: 1,71+ })72+);73+74+const failed = withDraft(75+ shownWith([]),76+ DraftState.cases.Failed.make({77+ attempts: 3,78+ model,79+ refusal: "NotRedFirst",80+ round: 2,81+ })82+);83+84+const decision = DecisionId.make("dec-000003");85+86+const view = (87+ { files, proposal }: Shown,88+ linked: Option.Option<DecisionId> = Option.none()89+) =>90+ markupOf(91+ <ProposalView92+ decision={linked}93+ files={files}94+ mayRedraft95+ project={datekit}96+ proposal={proposal}97+ />98+ );99+100+const DRAFT_AGAIN = /<button[^>]*>[^<]*Draft again/u;101+102+describe(ProposalView, () => {103+ it("shows the want and the proposer", () => {104+ const text = plainText(view(drafting));105+106+ expect(text).toContain("formatISO keeps the offset it was given.");107+ expect(text).toContain("lin-h");108+ });109+110+ it("while drafting, shows the spinner and no Draft again", () => {111+ const markup = view(drafting);112+113+ expect(markup).toContain('data-slot="spinner"');114+ expect(plainText(markup)).toContain("Drafting");115+ expect(markup).not.toMatch(DRAFT_AGAIN);116+ });117+118+ it("once ready, shows both files, the red-first run, who drafted it and its decision", () => {119+ const markup = view(ready, Option.some(decision));120+ const text = plainText(markup);121+122+ expect(text).toContain(askFile);123+ expect(text).toContain(testFile);124+ expect(text).toContain(125+ "fails twice the same way in lane unit: expected '+02:00', got 'Z'"126+ );127+ expect(text).toContain(`drafted by ${model}, attempt 2 of 3`);128+ expect(markup).toContain('href="/datekit/decisions/dec-000003"');129+ });130+131+ it("once ready, shows no spinner", () => {132+ expect(view(ready)).not.toContain('data-slot="spinner"');133+ });134+135+ it("once failed, shows the last refusal's headline and Draft again", () => {136+ const markup = view(failed);137+138+ expect(plainText(markup)).toContain("NotRedFirst");139+ expect(markup).toMatch(DRAFT_AGAIN);140+ });141+142+ it("offers Draft again only to the proposer or a decider", () => {143+ const markup = markupOf(144+ <ProposalView145+ decision={Option.none()}146+ files={[]}147+ mayRedraft={false}148+ project={datekit}149+ proposal={failed.proposal}150+ />151+ );152+153+ expect(markup).not.toMatch(DRAFT_AGAIN);154+ });155+156+ it("once accepted, offers no button", () => {157+ const accepted: Shown = {158+ ...ready,159+ proposal: { ...ready.proposal, state: "accepted" },160+ };161+162+ const markup = view(accepted);163+164+ expect(plainText(markup)).toContain("accepted");165+ expect(markup).not.toContain("<button");166+ });167+});added:apps/web/test/propose.test.tsx+117 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 { ProposeAsk } from "@repo/protocol/contracts";11+import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";12+import { Option, Schema } from "effect";13+14+import {15+ ProposeView,16+ proposalPayload,17+} from "../src/features/propose/propose-view.tsx";18+import type { About } from "../src/features/propose/propose-view.tsx";19+import { markupOf, plainText } from "./ask-fixtures.ts";20+21+const datekit = ProjectName.make("datekit");22+23+const at = CommitSha.make("4c2e6a8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c");24+25+const modules = [RepoPath.make("docs"), RepoPath.make("src")];26+27+const signedIn = (about: Option.Option<About> = Option.none()) =>28+ markupOf(29+ <ProposeView about={about} modules={modules} project={datekit} signedIn />30+ );31+32+/** The want's textarea, as the server renders it: its opening tag and text. */33+const textareaOf = (markup: string) =>34+ /<textarea[^>]*>(?<text>[^<]*)<\/textarea>/u.exec(markup);35+36+describe(ProposeView, () => {37+ it("signed in, offers a want and the draft box, checked", () => {38+ const markup = signedIn();39+40+ expect(textareaOf(markup)?.[0]).toContain('name="want"');41+ expect(markup).toMatch(42+ /role="checkbox"[^>]*aria-checked="true"|aria-checked="true"[^>]*role="checkbox"/u43+ );44+ expect(plainText(markup)).toContain(45+ "Let the platform's agent draft the ask"46+ );47+ expect(markup).toMatch(/<button[^>]*type="submit"[^>]*>Propose/u);48+ });49+50+ it("offers each of the project's top folders as the territory", () => {51+ const markup = signedIn();52+53+ expect(markup).toContain('name="territory"');54+ expect(markup).toContain('<option value="src">src</option>');55+ expect(markup).toContain('<option value="docs">docs</option>');56+ });57+58+ it("starts the want at the line a why page names", () => {59+ const markup = signedIn(60+ Option.some({ at, line: 12, path: RepoPath.make("src/format.ts") })61+ );62+63+ expect(textareaOf(markup)?.groups?.text).toBe(64+ "In `src/format.ts` line 12 at 4c2e6a8: "65+ );66+ });67+68+ it("signed out, shows no form and links to sign in", () => {69+ const markup = markupOf(70+ <ProposeView71+ about={Option.none()}72+ modules={modules}73+ project={datekit}74+ signedIn={false}75+ />76+ );77+78+ expect(markup).not.toContain("<form");79+ expect(markup).not.toContain("<textarea");80+ expect(markup).toMatch(/<a[^>]*href="\/auth\/signin[^"]*"[^>]*>Sign in/u);81+ });82+});83+84+describe(proposalPayload, () => {85+ const isPayload = Schema.is(ProposeAsk.payloadSchema);86+87+ it("asks for a draft when the box is checked", () => {88+ const payload = proposalPayload({89+ draft: true,90+ project: datekit,91+ want: " formatISO keeps the offset. ",92+ });93+94+ expect(payload).toStrictEqual({95+ draft: true,96+ project: "datekit",97+ want: "formatISO keeps the offset.",98+ });99+ expect(isPayload(payload)).toBeTruthy();100+ });101+102+ it("carries no draft key when the box is clear, and the territory when named", () => {103+ const payload = proposalPayload({104+ draft: false,105+ project: datekit,106+ territory: RepoPath.make("src"),107+ want: "formatISO keeps the offset.",108+ });109+110+ expect(payload).toStrictEqual({111+ project: "datekit",112+ territory: "src",113+ want: "formatISO keeps the offset.",114+ });115+ expect(Object.hasOwn(payload, "draft")).toBeFalsy();116+ });117+});