render.ts
This file
Path
apps/cli/src/render.ts
582 lines · 18.3 KiB · TypeScript
Last changed by
Merge build/imported-from into mainoscabrielbefore adoptionf224a14
History of this fileTake it
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 { IMPORTED_NOTE } from "@repo/agent-kit/docs/imported-note";7import { Brand } from "@repo/brand";8import type { View } from "@repo/protocol/cli";9import {10 Claim,11 Credits,12 Finish,13 FrontPage,14 LedgerOf,15 ListAsks,16 ListProjects,17 PolicyOf,18 ShowAsk,19 Status,20 SubmitAnswer,21 TodayOf,22 VerdictOf,23} from "@repo/protocol/contracts";24import type { Contract } from "@repo/protocol/contracts";25import { LandReceipt } from "@repo/protocol/domain/answer";26import type { AnswerReceipt } from "@repo/protocol/domain/answer";27import { DecisionSubject } from "@repo/protocol/domain/decision";28import { Outcome } from "@repo/protocol/domain/outcome";29import type {30 ImportSource,31 PolicyPending,32 PublicPolicy,33} from "@repo/protocol/domain/policy";34import { LedgerEntry } from "@repo/protocol/domain/visibility";35import type { Refusal } from "@repo/protocol/refusal";36import { receiptLine } from "@repo/protocol/render";37import { DateTime, Option, Result, Schema } from "effect";38import type { Rpc } from "effect/rpc";3940const short = (sha: string) => sha.slice(0, 7);4142const when = (at: DateTime.Utc) => DateTime.formatIso(at);4344const yesNo = (value: boolean) => (value ? "yes" : "no");4546/** A cell's text, safe inside a Markdown table row. */47const cell = (text: string) =>48 text.replaceAll("|", "\\|").replaceAll(/\s*\n\s*/gu, " ");4950/** `text` as a Markdown code span, fenced by one more backtick than its longest run. */51const codeSpan = (text: string) => {52 const longest = Math.max(53 0,54 ...(text.match(/`+/gu) ?? []).map((run) => run.length)55 );5657 const fence = "`".repeat(longest + 1);58 const pad = text.startsWith("`") || text.endsWith("`") ? " " : "";5960 return `${fence}${pad}${text}${pad}${fence}`;61};6263/**64 * Rows as a Markdown table, and as a padded plain table for a person.65 * `empty` stands in for both when there are no rows. The columns in `code`66 * hold literal text (a glob, a path) that Markdown shows as code, so `**`67 * never reads as emphasis; the plain table shows it as it is.68 */69const table = (70 headers: readonly string[],71 rows: readonly (readonly string[])[],72 empty: string,73 code: readonly number[] = []74): View => {75 if (rows.length === 0) {76 return { markdown: empty, text: empty };77 }7879 const widths = headers.map((header, column) =>80 Math.max(header.length, ...rows.map((row) => (row[column] ?? "").length))81 );8283 const padded = (row: readonly string[]) =>84 row85 .map((text, column) => text.padEnd(widths[column] ?? 0))86 .join(" ")87 .trimEnd();8889 return {90 markdown: [91 `| ${headers.join(" | ")} |`,92 `| ${headers.map(() => "---").join(" | ")} |`,93 ...rows.map(94 (row) =>95 `| ${row96 .map((text, column) =>97 code.includes(column) ? cell(codeSpan(text)) : cell(text)98 )99 .join(" | ")} |`100 ),101 ].join("\n"),102 text: [103 padded(headers.map((header) => header.toUpperCase())),104 ...rows.map(padded),105 ].join("\n"),106 };107};108109/** Labelled values, one a line: a Markdown list, and padded for a person. */110const fields = (rows: readonly (readonly [string, string])[]): View => {111 const width = Math.max(0, ...rows.map(([label]) => label.length));112113 return {114 markdown: rows.map(([label, value]) => `- ${label}: ${value}`).join("\n"),115 text: rows116 .map(([label, value]) => `${label.padEnd(width)} ${value}`)117 .join("\n"),118 };119};120121/** Views one after another, as sections. */122const joined = (...parts: readonly View[]): View => ({123 markdown: parts.map(({ markdown }) => markdown).join("\n\n"),124 text: parts.map(({ markdown, text }) => text ?? markdown).join("\n\n"),125});126127/** The same words for every reader. */128const prose = (text: string): View => ({ markdown: text });129130/** Where an answer stands, in a few words. */131const outcomeText = (outcome: Outcome) =>132 Outcome.match(outcome, {133 AwaitingDecision: ({ decision }) => `waits on decision ${decision}`,134 AwaitingFinish: () => "passed; waits for a decider's finish",135 Checking: ({ stage }) => `checking (${stage})`,136 Landed: ({ sha }) => `landed as ${short(sha)}`,137 Refused: ({ refusals }) =>138 `refused: ${refusals.map((refusal) => refusal._tag).join(", ")}`,139 WaitingOnParent: ({ ask }) => `passed; waits for ${ask} to land`,140 });141142/** What a decision is about, in a few words. */143const subjectText = (subject: DecisionSubject) =>144 DecisionSubject.match(subject, {145 Finish: ({ ask, head }) => `finish the answer to ${ask} at ${short(head)}`,146 OpenProposal: ({ proposal }) =>147 `open the ask proposal ${proposal} asks for`,148 PostureChange: ({ from, to }) => `change the posture from ${from} to ${to}`,149 ProxyWidened: ({ hosts, item }) =>150 `let ${item}'s placeholder reach ${hosts.join(", ")}`,151 RaiseRatchet: ({ after, before, ratchet, territory }) =>152 `raise the ${ratchet} ratchet in ${territory} from ${before} to ${after}`,153 SecretInTree: ({ ask, item }) =>154 `${item}'s write-only value showed up in an answer to ${ask}`,155 StrayPush: ({ after, before, ref }) =>156 `${ref} moved from ${short(before)} to ${short(after)} without a landing`,157 Vouch: ({ handle }) => `vouch for ${handle}`,158 Waiver: ({ at, marker, reason }) =>159 `allow ${marker} at ${at.path}:${at.line} ("${reason}")`,160 });161162/** One ledger entry, in a few words. */163const entryText = (entry: LedgerEntry) =>164 LedgerEntry.match(entry, {165 Admitted: ({ area, knownBadCaught, mainRuns, suite }) =>166 `held-back suite ${suite} admitted in ${area} after ${mainRuns} runs on main, catching ${knownBadCaught} known-bad trees`,167 CommitmentPublished: ({ area, authors, checks, suite }) =>168 `commitment ${suite} published for ${area}: ${checks} checks by ${authors} authors`,169 CountChanged: ({ area, count, layer }) =>170 `${layer} holds ${count} in ${area}`,171 LayerDeclared: ({ disclose, kinds, layer }) =>172 `layer ${layer} declared, holding ${kinds.join(", ")}, disclosing ${disclose}`,173 PostureChanged: ({ decision, from, to }) =>174 `posture changed from ${from} to ${to} by decision ${decision}`,175 Released: ({ by, landing, layer, paths }) =>176 `${by} released ${paths} paths from ${layer} in ${short(landing)}`,177 ValueSet: ({ by, key }) => `${by} set the write-only value of ${key}`,178 });179180/** A view that renders a success it can read, and none for anything else. */181const viewOf = <S extends Schema.Top>(182 schema: S,183 render: (success: S["Type"]) => View184) => {185 const is = Schema.is(schema);186187 return (success: Rpc.Success<Contract>): Option.Option<View> =>188 is(success) ? Option.some(render(success)) : Option.none();189};190191const asks = viewOf(ListAsks.successSchema, ({ asks: listed }) =>192 joined(193 table(194 ["ask", "kind", "territory", "want", "claimed"],195 listed.map(196 ({ ask, blockedBy, claimed, kind, reserve, territory, want }) => [197 ask,198 reserve === undefined ? kind : `${kind} (for ${reserve})`,199 territory,200 blockedBy.length === 0201 ? want202 : `${want} (waits on ${blockedBy.join(", ")})`,203 yesNo(claimed),204 ]205 ),206 "No open asks."207 ),208 prose(209 `Read one with \`${Brand.cli} ask <ask>\`; take one with \`${Brand.cli} claim <ask>\`.`210 )211 )212);213214const ask = viewOf(ShowAsk.successSchema, ({ brief }) => prose(brief));215216const claim = viewOf(Claim.successSchema, ({ claim: held }) => {217 const steps = [218 `git remote add ${Brand.slug} ${held.remote}`,219 `${Brand.cli} check`,220 `git push ${Brand.slug} HEAD:main`,221 ];222223 return {224 markdown: [225 `You hold the claim on \`${held.ask}\` in ${held.project} until ${when(held.lapsesAt)}; only a push keeps it alive.`,226 "",227 `Its fork: ${held.remote}`,228 "",229 "Next:",230 "",231 "```sh",232 ...steps,233 "```",234 "",235 `\`${Brand.cli} check\` runs \`${held.checkCommand}\` and the gate's checks locally, before you push.`,236 ].join("\n"),237 text: [238 `You hold the claim on ${held.ask} in ${held.project} until ${when(held.lapsesAt)}; only a push keeps it alive.`,239 `Its fork: ${held.remote}`,240 "Next:",241 ...steps.map((step) => ` ${step}`),242 ].join("\n"),243 };244});245246const status = viewOf(Status.successSchema, ({ answers, claims, handle }) =>247 joined(248 prose(`Signed in as ${handle}.`),249 prose("Claims:"),250 table(251 ["ask", "project", "state", "lapses", "fork"],252 claims.map((held) => [253 held.ask,254 held.project,255 held.state,256 when(held.lapsesAt),257 held.remote,258 ]),259 "No claims."260 ),261 prose("Answers:"),262 table(263 ["ask", "head", "outcome", "at"],264 answers.map((answer) => [265 answer.ask,266 short(answer.head),267 outcomeText(answer.outcome),268 when(answer.at),269 ]),270 "No answers."271 )272 )273);274275const verdict = viewOf(VerdictOf.successSchema, ({ verdict: found }) => {276 if (found === undefined) {277 return prose("No verdict yet.");278 }279280 return joined(281 prose(282 `${found.ask} at ${short(found.head)}: ${outcomeText(found.outcome)} (furthest stage: ${found.stage}).`283 ),284 table(285 ["lane", "result", "command", "ms"],286 found.lanes.map((lane) => [287 lane.lane,288 lane.result,289 lane.command,290 String(lane.durationMs),291 ]),292 "No lanes ran."293 ),294 ...(found.heldBack.length === 0295 ? []296 : [297 table(298 ["area", "held back", "suite"],299 found.heldBack.map((area) => [300 area.area,301 `${area.passed}/${area.total}`,302 area.suite,303 ]),304 ""305 ),306 ])307 );308});309310const today = viewOf(TodayOf.successSchema, (page) =>311 joined(312 prose(313 `Today for ${page.decider}: ${page.budget.used} of ${page.budget.total} decisions used${page.overflow === 0 ? "" : `; ${page.overflow} more wait beyond the budget`}.`314 ),315 table(316 ["decision", "project", "about", "default", "expires"],317 page.decisions.map((decision) => [318 decision.id,319 decision.project,320 subjectText(decision.subject),321 decision.default,322 when(decision.expiresAt),323 ]),324 "Nothing to decide."325 ),326 ...(page.decisions.length === 0327 ? []328 : [329 prose(330 `Take one with \`${Brand.cli} decide --project <project> --decision <decision> --choice <choice> --yes\`.`331 ),332 ])333 )334);335336const plural = (count: number, one: string, many: string) =>337 `${count} ${count === 1 ? one : many}`;338339/** How many a vouch file names, as the people page says none: "nobody". */340const countOf = (count: number) => (count === 0 ? "nobody" : `${count}`);341342const HOUR_MS = 3_600_000;343344/** A claim timing as the people page says it: whole hours up to two days, then days. */345const spanOf = (ms: number) => {346 if (ms % HOUR_MS !== 0) {347 return plural(Math.round(ms / 60_000), "minute", "minutes");348 }349350 const hours = ms / HOUR_MS;351352 return hours > 48 && hours % 24 === 0353 ? plural(hours / 24, "day", "days")354 : plural(hours, "hour", "hours");355};356357/** The config folder's `project.ts`. */358const PROJECT_FILE = `${Brand.configDir}/project.ts`;359360/** What a vouch gates, in the people page's words. */361const vouchModes = {362 all: "For everything: claiming an ask, offering a sealed answer and proposing an ask all need a vouch.",363 bansOnly:364 "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or propose.",365 forCode:366 "For code: claiming an ask or offering a sealed answer needs a vouch; anyone not denounced may propose an ask.",367} as const satisfies Record<PublicPolicy["vouch"]["mode"], string>;368369/** A policy at its landed commit, section by section, as the people page shows it. */370const evaluated = (policy: PublicPolicy) => {371 const { agents, budget, caps, claims, record, vouch, vouches } = policy;372 const denounced = vouches.filter((line) => line.denounced).length;373374 return joined(375 prose(376 policy.source === "config"377 ? `As of ${short(policy.at)}, the landed commit, from ${PROJECT_FILE}.`378 : `As of ${short(policy.at)}, the landed commit. This project has no ${PROJECT_FILE}: the person who set it up decides everything, under the platform's defaults.`379 ),380 prose("Deciders by path:"),381 table(382 ["paths", "deciders"],383 policy.deciders.map(({ handles, paths }) => [paths, handles.join(", ")]),384 "Nobody decides.",385 [0]386 ),387 prose(388 `Vouching: ${vouchModes[vouch.mode]} ${vouch.file} vouches for ${countOf(vouches.length - denounced)} and denounces ${countOf(denounced)}.`389 ),390 prose("Limits:"),391 fields([392 [393 "Claims",394 `${plural(caps.claimsPerPerson, "claim", "claims")} per person at once`,395 ],396 [397 "Proposals",398 caps.proposalsPerPerson === 0399 ? "Proposals are off"400 : `${plural(caps.proposalsPerPerson, "proposal", "proposals")} per person at once`,401 ],402 [403 "Budget",404 `${plural(budget.decisionsPerDay, "decision", "decisions")} a day per decider; an undecided one takes its default after ${plural(budget.expireDays, "day", "days")}`,405 ],406 [407 "Claim timing",408 `warned after ${spanOf(claims.warnAfterMs)} without a push; lapses after ${spanOf(claims.lapseAfterMs)}`,409 ],410 [411 "Record",412 `a landing counts ${413 record.countsAfterDays === 0414 ? "from the day it lands"415 : `once it has stood ${plural(record.countsAfterDays, "day", "days")}`416 }, for ${plural(record.windowDays, "day", "days")}`,417 ],418 ]),419 prose(420 agents === "trailer"421 ? "Agents: each landing names the agents its people worked through, in an Assisted-by: trailer."422 : "Agents: landings carry no Assisted-by: trailer."423 )424 );425};426427/**428 * Why the config at the landed commit has not evaluated, and the step that429 * makes it, as a terminal's lines. The view sees only the success, which430 * names no project, so the command names it as `<project>`.431 */432const pendingText = ({ at, reason }: PolicyPending) => {433 const notEvaluated = `The config at the landed commit ${short(at)} has not been evaluated`;434435 return reason === "noConfig"436 ? [437 `${notEvaluated}: there is no ${Brand.configDir}/ folder, and no test command in the project's CI or package files.`,438 `Run \`${Brand.cli} init --project <project> --dry-run\` in the project's repo to see the ${PROJECT_FILE} it proposes, then have a decider land it.`,439 ]440 : [441 `${notEvaluated}: ${Brand.configDir}/ at ${short(at)} did not evaluate.`,442 `Fix it by landing a change to ${Brand.configDir}/; it is evaluated again at every landing.`,443 ];444};445446/** Where an imported project came from, and what a copy is (ADR 0031). */447const importedText = ({ branch, url }: ImportSource) =>448 prose(449 `Imported from ${url}${branch === undefined ? "" : ` (branch ${branch})`}: this project is ${IMPORTED_NOTE}.`450 );451452/** The policy's own view: evaluated, why not yet, or nothing landed. */453const policyText = (read: typeof PolicyOf.successSchema.Type): View => {454 if (read.policy !== undefined) {455 return evaluated(read.policy);456 }457458 if (read.unevaluated === undefined) {459 return prose(460 "Nothing has landed yet. The config is evaluated at every landing."461 );462 }463464 const lines = pendingText(read.unevaluated);465466 return { markdown: lines.join("\n\n"), text: lines.join("\n") };467};468469const policy = viewOf(PolicyOf.successSchema, (read) =>470 read.importedFrom === undefined471 ? policyText(read)472 : joined(importedText(read.importedFrom), policyText(read))473);474475const ledger = viewOf(LedgerOf.successSchema, (book) =>476 joined(477 prose(`${book.project}: ${book.postureLabel}.`),478 table(479 ["#", "at", "entry"],480 book.entries.map((entry) => [481 String(entry.seq),482 when(entry.at),483 entryText(entry),484 ]),485 "The ledger is empty."486 )487 )488);489490const credits = viewOf(Credits.successSchema, ({ credits: counted }) =>491 table(492 ["project", "area", "role", "count"],493 counted.map((credit) => [494 credit.project,495 credit.area,496 credit.role,497 String(credit.count),498 ]),499 "No credits yet."500 )501);502503const projects = viewOf(ListProjects.successSchema, ({ projects: listed }) =>504 table(505 ["project", "posture", "open asks", "landed"],506 listed.map((listing) => [507 listing.project,508 listing.posture,509 String(listing.openAsks),510 listing.landedAt === undefined ? "never" : when(listing.landedAt),511 ]),512 "No projects yet."513 )514);515516const front = viewOf(FrontPage.successSchema, ({ entries }) =>517 table(518 ["project", "ask", "kind", "want", "takeable"],519 entries.map((entry) => [520 entry.project,521 entry.ask.ask,522 entry.ask.kind,523 entry.ask.want,524 yesNo(entry.takeable),525 ]),526 "No open asks anywhere."527 )528);529530/**531 * Where an offered answer stands, in the line git's `remote:` output gives a532 * push of the same answer. A refused one never reaches its view: its533 * refusals print as refusals (`refusalsIn`).534 */535const receipt = (offered: AnswerReceipt) =>536 prose(537 Result.getOrElse(receiptLine(offered), () => `${offered.ask} was refused`)538 );539540const submitted = viewOf(SubmitAnswer.successSchema, receipt);541542const finished = viewOf(Finish.successSchema, receipt);543544/** Any receipt: an answer's (`submit`, `finish`) has a landing's fields too. */545const isReceipt = Schema.is(LandReceipt);546547/**548 * The refusals a contract's success carries in place of a result: a refused549 * receipt's (`finish` and `land` refuse at stages 0–1 that way, and `submit`550 * gives a refused request's receipt back again). The command prints them as551 * refusals, once, and exits 1.552 */553export const refusalsIn = (554 success: Rpc.Success<Contract>555): readonly Refusal[] =>556 isReceipt(success) && Outcome.guards.Refused(success.outcome)557 ? success.outcome.refusals558 : [];559560/** Each contract's view, by tag. */561export const views = {562 claim,563 credits,564 finish: finished,565 frontPage: front,566 ledger,567 listAsks: asks,568 listProjects: projects,569 projectPolicy: policy,570 showAsk: ask,571 status,572 submitAnswer: submitted,573 today,574 verdict,575} as const satisfies Readonly<576 Partial<577 Record<578 Contract["_tag"],579 (success: Rpc.Success<Contract>) => Option.Option<View>580 >581 >582>;