Skip to content
Myr

render.ts

This file

Path

apps/cli/src/render.ts

400 lines · 11.9 KiB · TypeScript

Last changed by

Fold W4 together on main: the compiled CLI checks a TypeScript config folder by itself, status names the caller, and ask open and ask flag take the ask as ask doesoscabrielbefore adoption4ca0d3a

History of this file

Take it

Merge build/404-cli-projections-and-agent-policy: every contract is a CLI command that behaves well under an agentoscabrielbefore adoption03b20ff

lines 1–203why, one step back
1/**
2 * The CLI's prose for the contracts' results: Markdown for an agent (and a3 * script), and plain text for a person where a table reads better padded.4 * A contract without a view here prints its encoded JSON in a fenced block.5 */6import { Brand } from "@repo/brand";7import type { View } from "@repo/protocol/cli";8import {9 Claim,10 Credits,11 Finish,12 FrontPage,13 LedgerOf,14 ListAsks,15 ListProjects,16 ShowAsk,17 Status,18 SubmitAnswer,19 TodayOf,20 VerdictOf,21} from "@repo/protocol/contracts";22import type { Contract } from "@repo/protocol/contracts";23import { LandReceipt } from "@repo/protocol/domain/answer";24import type { AnswerReceipt } from "@repo/protocol/domain/answer";25import { DecisionSubject } from "@repo/protocol/domain/decision";26import { Outcome } from "@repo/protocol/domain/outcome";27import { LedgerEntry } from "@repo/protocol/domain/visibility";28import type { Refusal } from "@repo/protocol/refusal";29import { receiptLine } from "@repo/protocol/render";30import { DateTime, Option, Result, Schema } from "effect";31import type { Rpc } from "effect/rpc";3233const short = (sha: string) => sha.slice(0, 7);3435const when = (at: DateTime.Utc) => DateTime.formatIso(at);3637const yesNo = (value: boolean) => (value ? "yes" : "no");3839/** A cell's text, safe inside a Markdown table row. */40const cell = (text: string) =>41 text.replaceAll("|", "\\|").replaceAll(/\s*\n\s*/gu, " ");4243/**44 * Rows as a Markdown table, and as a padded plain table for a person.45 * `empty` stands in for both when there are no rows.46 */47const table = (48 headers: readonly string[],49 rows: readonly (readonly string[])[],50 empty: string51): View => {52 if (rows.length === 0) {53 return { markdown: empty, text: empty };54 }5556 const widths = headers.map((header, column) =>57 Math.max(header.length, ...rows.map((row) => (row[column] ?? "").length))58 );5960 const padded = (row: readonly string[]) =>61 row62 .map((text, column) => text.padEnd(widths[column] ?? 0))63 .join(" ")64 .trimEnd();6566 return {67 markdown: [68 `| ${headers.join(" | ")} |`,69 `| ${headers.map(() => "---").join(" | ")} |`,70 ...rows.map((row) => `| ${row.map(cell).join(" | ")} |`),71 ].join("\n"),72 text: [73 padded(headers.map((header) => header.toUpperCase())),74 ...rows.map(padded),75 ].join("\n"),76 };77};7879/** Views one after another, as sections. */80const joined = (...parts: readonly View[]): View => ({81 markdown: parts.map(({ markdown }) => markdown).join("\n\n"),82 text: parts.map(({ markdown, text }) => text ?? markdown).join("\n\n"),83});8485/** The same words for every reader. */86const prose = (text: string): View => ({ markdown: text });8788/** Where an answer stands, in a few words. */89const outcomeText = (outcome: Outcome) =>90 Outcome.match(outcome, {91 AwaitingDecision: ({ decision }) => `waits on decision ${decision}`,92 AwaitingFinish: () => "passed; waits for a decider's finish",93 Checking: ({ stage }) => `checking (${stage})`,94 Landed: ({ sha }) => `landed as ${short(sha)}`,95 Refused: ({ refusals }) =>96 `refused: ${refusals.map((refusal) => refusal._tag).join(", ")}`,97 WaitingOnParent: ({ ask }) => `passed; waits for ${ask} to land`,98 });99100/** What a decision is about, in a few words. */101const subjectText = (subject: DecisionSubject) =>102 DecisionSubject.match(subject, {103 Finish: ({ ask, head }) => `finish the answer to ${ask} at ${short(head)}`,104 OpenProposal: ({ proposal }) =>105 `open the ask proposal ${proposal} asks for`,106 PostureChange: ({ from, to }) => `change the posture from ${from} to ${to}`,107 ProxyWidened: ({ hosts, item }) =>108 `let ${item}'s placeholder reach ${hosts.join(", ")}`,109 RaiseRatchet: ({ after, before, ratchet, territory }) =>110 `raise the ${ratchet} ratchet in ${territory} from ${before} to ${after}`,111 SecretInTree: ({ ask, item }) =>112 `${item}'s write-only value showed up in an answer to ${ask}`,113 StrayPush: ({ after, before, ref }) =>114 `${ref} moved from ${short(before)} to ${short(after)} without a landing`,115 Vouch: ({ handle }) => `vouch for ${handle}`,116 Waiver: ({ at, marker, reason }) =>117 `allow ${marker} at ${at.path}:${at.line} ("${reason}")`,118 });119120/** One ledger entry, in a few words. */121const entryText = (entry: LedgerEntry) =>122 LedgerEntry.match(entry, {123 Admitted: ({ area, knownBadCaught, mainRuns, suite }) =>124 `held-back suite ${suite} admitted in ${area} after ${mainRuns} runs on main, catching ${knownBadCaught} known-bad trees`,125 CommitmentPublished: ({ area, authors, checks, suite }) =>126 `commitment ${suite} published for ${area}: ${checks} checks by ${authors} authors`,127 CountChanged: ({ area, count, layer }) =>128 `${layer} holds ${count} in ${area}`,129 LayerDeclared: ({ disclose, kinds, layer }) =>130 `layer ${layer} declared, holding ${kinds.join(", ")}, disclosing ${disclose}`,131 PostureChanged: ({ decision, from, to }) =>132 `posture changed from ${from} to ${to} by decision ${decision}`,133 Released: ({ by, landing, layer, paths }) =>134 `${by} released ${paths} paths from ${layer} in ${short(landing)}`,135 ValueSet: ({ by, key }) => `${by} set the write-only value of ${key}`,136 });137138/** A view that renders a success it can read, and none for anything else. */139const viewOf = <S extends Schema.Top>(140 schema: S,141 render: (success: S["Type"]) => View142) => {143 const is = Schema.is(schema);144145 return (success: Rpc.Success<Contract>): Option.Option<View> =>146 is(success) ? Option.some(render(success)) : Option.none();147};148149const asks = viewOf(ListAsks.successSchema, ({ asks: listed }) =>150 joined(151 table(152 ["ask", "kind", "territory", "want", "claimed"],153 listed.map(154 ({ ask, blockedBy, claimed, kind, reserve, territory, want }) => [155 ask,156 reserve === undefined ? kind : `${kind} (for ${reserve})`,157 territory,158 blockedBy.length === 0159 ? want160 : `${want} (waits on ${blockedBy.join(", ")})`,161 yesNo(claimed),162 ]163 ),164 "No open asks."165 ),166 prose(167 `Read one with \`${Brand.cli} ask <ask>\`; take one with \`${Brand.cli} claim <ask>\`.`168 )169 )170);171172const ask = viewOf(ShowAsk.successSchema, ({ brief }) => prose(brief));173174const claim = viewOf(Claim.successSchema, ({ claim: held }) => {175 const steps = [176 `git remote add ${Brand.slug} ${held.remote}`,177 `${Brand.cli} check`,178 `git push ${Brand.slug} HEAD:main`,179 ];180181 return {182 markdown: [183 `You hold the claim on \`${held.ask}\` in ${held.project} until ${when(held.lapsesAt)}; only a push keeps it alive.`,184 "",185 `Its fork: ${held.remote}`,186 "",187 "Next:",188 "",189 "```sh",190 ...steps,191 "```",192 "",193 `\`${Brand.cli} check\` runs \`${held.checkCommand}\` and the gate's checks locally, before you push.`,194 ].join("\n"),195 text: [196 `You hold the claim on ${held.ask} in ${held.project} until ${when(held.lapsesAt)}; only a push keeps it alive.`,197 `Its fork: ${held.remote}`,198 "Next:",199 ...steps.map((step) => ` ${step}`),200 ].join("\n"),201 };202});203

Fold W4 together on main: the compiled CLI checks a TypeScript config folder by itself, status names the caller, and ask open and ask flag take the ask as ask doesoscabrielbefore adoption4ca0d3a

line 204why, one step back
204const status = viewOf(Status.successSchema, ({ answers, claims, handle }) =>

Merge build/404-cli-projections-and-agent-policy: every contract is a CLI command that behaves well under an agentoscabrielbefore adoption03b20ff

line 205why, one step back
205 joined(

Fold W4 together on main: the compiled CLI checks a TypeScript config folder by itself, status names the caller, and ask open and ask flag take the ask as ask doesoscabrielbefore adoption4ca0d3a

line 206why, one step back
206 prose(`Signed in as ${handle}.`),

Merge build/404-cli-projections-and-agent-policy: every contract is a CLI command that behaves well under an agentoscabrielbefore adoption03b20ff

lines 207–400why, one step back
207 prose("Claims:"),
208 table(209 ["ask", "project", "state", "lapses", "fork"],210 claims.map((held) => [211 held.ask,212 held.project,213 held.state,214 when(held.lapsesAt),215 held.remote,216 ]),217 "No claims."218 ),219 prose("Answers:"),220 table(221 ["ask", "head", "outcome", "at"],222 answers.map((answer) => [223 answer.ask,224 short(answer.head),225 outcomeText(answer.outcome),226 when(answer.at),227 ]),228 "No answers."229 )230 )231);232233const verdict = viewOf(VerdictOf.successSchema, ({ verdict: found }) => {234 if (found === undefined) {235 return prose("No verdict yet.");236 }237238 return joined(239 prose(240 `${found.ask} at ${short(found.head)}: ${outcomeText(found.outcome)} (furthest stage: ${found.stage}).`241 ),242 table(243 ["lane", "result", "command", "ms"],244 found.lanes.map((lane) => [245 lane.lane,246 lane.result,247 lane.command,248 String(lane.durationMs),249 ]),250 "No lanes ran."251 ),252 ...(found.heldBack.length === 0253 ? []254 : [255 table(256 ["area", "held back", "suite"],257 found.heldBack.map((area) => [258 area.area,259 `${area.passed}/${area.total}`,260 area.suite,261 ]),262 ""263 ),264 ])265 );266});267268const today = viewOf(TodayOf.successSchema, (page) =>269 joined(270 prose(271 `Today for ${page.decider}: ${page.budget.used} of ${page.budget.total} decisions used${page.overflow === 0 ? "" : `; ${page.overflow} more wait beyond the budget`}.`272 ),273 table(274 ["decision", "project", "about", "default", "expires"],275 page.decisions.map((decision) => [276 decision.id,277 decision.project,278 subjectText(decision.subject),279 decision.default,280 when(decision.expiresAt),281 ]),282 "Nothing to decide."283 ),284 ...(page.decisions.length === 0285 ? []286 : [287 prose(288 `Take one with \`${Brand.cli} decide --project <project> --decision <decision> --choice <choice> --yes\`.`289 ),290 ])291 )292);293294const ledger = viewOf(LedgerOf.successSchema, (book) =>295 joined(296 prose(`${book.project}: ${book.postureLabel}.`),297 table(298 ["#", "at", "entry"],299 book.entries.map((entry) => [300 String(entry.seq),301 when(entry.at),302 entryText(entry),303 ]),304 "The ledger is empty."305 )306 )307);308309const credits = viewOf(Credits.successSchema, ({ credits: counted }) =>310 table(311 ["project", "area", "role", "count"],312 counted.map((credit) => [313 credit.project,314 credit.area,315 credit.role,316 String(credit.count),317 ]),318 "No credits yet."319 )320);321322const projects = viewOf(ListProjects.successSchema, ({ projects: listed }) =>323 table(324 ["project", "posture", "open asks", "landed"],325 listed.map((listing) => [326 listing.project,327 listing.posture,328 String(listing.openAsks),329 listing.landedAt === undefined ? "never" : when(listing.landedAt),330 ]),331 "No projects yet."332 )333);334335const front = viewOf(FrontPage.successSchema, ({ entries }) =>336 table(337 ["project", "ask", "kind", "want", "takeable"],338 entries.map((entry) => [339 entry.project,340 entry.ask.ask,341 entry.ask.kind,342 entry.ask.want,343 yesNo(entry.takeable),344 ]),345 "No open asks anywhere."346 )347);348349/**350 * Where an offered answer stands, in the line git's `remote:` output gives a351 * push of the same answer. A refused one never reaches its view: its352 * refusals print as refusals (`refusalsIn`).353 */354const receipt = (offered: AnswerReceipt) =>355 prose(356 Result.getOrElse(receiptLine(offered), () => `${offered.ask} was refused`)357 );358359const submitted = viewOf(SubmitAnswer.successSchema, receipt);360361const finished = viewOf(Finish.successSchema, receipt);362363/** Any receipt: an answer's (`submit`, `finish`) has a landing's fields too. */364const isReceipt = Schema.is(LandReceipt);365366/**367 * The refusals a contract's success carries in place of a result: a refused368 * receipt's (`finish` and `land` refuse at stages 0–1 that way, and `submit`369 * gives a refused request's receipt back again). The command prints them as370 * refusals, once, and exits 1.371 */372export const refusalsIn = (373 success: Rpc.Success<Contract>374): readonly Refusal[] =>375 isReceipt(success) && Outcome.guards.Refused(success.outcome)376 ? success.outcome.refusals377 : [];378379/** Each contract's view, by tag. */380export const views = {381 claim,382 credits,383 finish: finished,384 frontPage: front,385 ledger,386 listAsks: asks,387 listProjects: projects,388 showAsk: ask,389 status,390 submitAnswer: submitted,391 today,392 verdict,393} as const satisfies Readonly<394 Partial<395 Record<396 Contract["_tag"],397 (success: Rpc.Success<Contract>) => Option.Option<View>398 >399 >400>;