Skip to content
Myr

render.ts

This file

Path

apps/cli/src/render.ts

678 lines · 20.8 KiB · TypeScript

Last changed by

landed by oscarf7b8ef2

History of this file

Take it

1import { IMPORTED_NOTE } from "@repo/agent-kit/docs/imported-note";2import { Brand } from "@repo/brand";3import type { View } from "@repo/protocol/cli";4import {5  Claim,6  Credits,7  Finish,8  FrontPage,9  Land,10  LedgerOf,11  ListAsks,12  ListDiscussions,13  ListProjects,14  PolicyOf,15  PostDiscussion,16  ShowAsk,17  ShowDiscussion,18  Status,19  SubmitAnswer,20  TodayOf,21  VerdictOf,22  WhoAmI,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 type { ClaimView } from "@repo/protocol/domain/claim";28import { DecisionSubject } from "@repo/protocol/domain/decision";29import type { Discussion } from "@repo/protocol/domain/discussion";30import { Outcome } from "@repo/protocol/domain/outcome";31import type {32  ImportSource,33  PolicyPending,34  PublicPolicy,35} from "@repo/protocol/domain/policy";36import { LedgerEntry } from "@repo/protocol/domain/visibility";37import type { Refusal } from "@repo/protocol/refusal";38import { receiptLine } from "@repo/protocol/render";39import { DateTime, Option, Result, Schema } from "effect";40import type { Rpc } from "effect/rpc";4142import { parseRemote, parseRepoName } from "./repo-context.ts";43import type { Remote } from "./repo-context.ts";4445const short = (sha: string) => sha.slice(0, 7);4647const when = (at: DateTime.Utc) => DateTime.formatIso(at);4849const yesNo = (value: boolean) => (value ? "yes" : "no");5051const cell = (text: string) =>52  text.replaceAll("|", "\\|").replaceAll(/\s*\n\s*/gu, " ");5354const codeSpan = (text: string) => {55  const longest = Math.max(56    0,57    ...(text.match(/`+/gu) ?? []).map((run) => run.length)58  );5960  const fence = "`".repeat(longest + 1);61  const pad = text.startsWith("`") || text.endsWith("`") ? " " : "";6263  return `${fence}${pad}${text}${pad}${fence}`;64};6566/** Columns in `code` hold literal text (a glob, a path), shown as code so `**` never reads as emphasis. */67const table = (68  headers: readonly string[],69  rows: readonly (readonly string[])[],70  empty: string,71  code: readonly number[] = []72): View => {73  if (rows.length === 0) {74    return { markdown: empty, text: empty };75  }7677  const widths = headers.map((header, column) =>78    Math.max(header.length, ...rows.map((row) => (row[column] ?? "").length))79  );8081  const padded = (row: readonly string[]) =>82    row83      .map((text, column) => text.padEnd(widths[column] ?? 0))84      .join("  ")85      .trimEnd();8687  return {88    markdown: [89      `| ${headers.join(" | ")} |`,90      `| ${headers.map(() => "---").join(" | ")} |`,91      ...rows.map(92        (row) =>93          `| ${row94            .map((text, column) =>95              code.includes(column) ? cell(codeSpan(text)) : cell(text)96            )97            .join(" | ")} |`98      ),99    ].join("\n"),100    text: [101      padded(headers.map((header) => header.toUpperCase())),102      ...rows.map(padded),103    ].join("\n"),104  };105};106107const fields = (rows: readonly (readonly [string, string])[]): View => {108  const width = Math.max(0, ...rows.map(([label]) => label.length));109110  return {111    markdown: rows.map(([label, value]) => `- ${label}: ${value}`).join("\n"),112    text: rows113      .map(([label, value]) => `${label.padEnd(width)}  ${value}`)114      .join("\n"),115  };116};117118const joined = (...parts: readonly View[]): View => ({119  markdown: parts.map(({ markdown }) => markdown).join("\n\n"),120  text: parts.map(({ markdown, text }) => text ?? markdown).join("\n\n"),121});122123const prose = (text: string): View => ({ markdown: text });124125const outcomeText = (outcome: Outcome) =>126  Outcome.match(outcome, {127    AwaitingDecision: ({ decision }) => `waits on decision ${decision}`,128    AwaitingFinish: () => "passed; waits for a maintainer's finish",129    Checking: ({ stage }) => `checking (${stage})`,130    Landed: ({ sha }) => `landed as ${short(sha)}`,131    Refused: ({ refusals }) =>132      `refused: ${refusals.map((refusal) => refusal._tag).join(", ")}`,133    WaitingOnParent: ({ ask }) => `passed; waits for ${ask} to land`,134  });135136const subjectText = (subject: DecisionSubject) =>137  DecisionSubject.match(subject, {138    Finish: ({ ask, head }) => `finish the answer to ${ask} at ${short(head)}`,139    PostureChange: ({ from, to }) => `change the posture from ${from} to ${to}`,140    ProxyWidened: ({ hosts, item }) =>141      `let ${item}'s placeholder reach ${hosts.join(", ")}`,142    RaiseRatchet: ({ after, before, ratchet, territory }) =>143      `raise the ${ratchet} ratchet in ${territory} from ${before} to ${after}`,144    SecretInTree: ({ ask, item }) =>145      `${item}'s write-only value showed up in an answer to ${ask}`,146    StrayPush: ({ after, before, ref }) =>147      `${ref} moved from ${short(before)} to ${short(after)} without a landing`,148    Vouch: ({ handle }) => `vouch for ${handle}`,149    Waiver: ({ at, marker, reason }) =>150      `allow ${marker} at ${at.path}:${at.line} ("${reason}")`,151  });152153const entryText = (entry: LedgerEntry) =>154  LedgerEntry.match(entry, {155    Admitted: ({ area, knownBadCaught, mainRuns, suite }) =>156      `held-back suite ${suite} admitted in ${area} after ${mainRuns} runs on main, catching ${knownBadCaught} known-bad trees`,157    CommitmentPublished: ({ area, authors, checks, suite }) =>158      `commitment ${suite} published for ${area}: ${checks} checks by ${authors} authors`,159    CountChanged: ({ area, count, layer }) =>160      `${layer} holds ${count} in ${area}`,161    LayerDeclared: ({ disclose, kinds, layer }) =>162      `layer ${layer} declared, holding ${kinds.join(", ")}, disclosing ${disclose}`,163    PostureChanged: ({ decision, from, to }) =>164      `posture changed from ${from} to ${to} by decision ${decision}`,165    Released: ({ by, landing, layer, paths }) =>166      `${by} released ${paths} paths from ${layer} in ${short(landing)}`,167    ValueSet: ({ by, key }) => `${by} set the write-only value of ${key}`,168  });169170const viewOf = <S extends Schema.Top>(171  schema: S,172  render: (success: S["Type"]) => View173) => {174  const is = Schema.is(schema);175176  return (success: Rpc.Success<Contract>): Option.Option<View> =>177    is(success) ? Option.some(render(success)) : Option.none();178};179180const asks = viewOf(ListAsks.successSchema, ({ asks: listed }) =>181  joined(182    table(183      ["ask", "kind", "territory", "want", "claimed"],184      listed.map(185        ({ ask, blockedBy, claimed, kind, reserve, territory, want }) => [186          ask,187          reserve === undefined ? kind : `${kind} (for ${reserve})`,188          territory,189          blockedBy.length === 0190            ? want191            : `${want} (waits on ${blockedBy.join(", ")})`,192          yesNo(claimed),193        ]194      ),195      "No open asks."196    ),197    prose(198      `Read one with \`${Brand.cli} ask <ask>\`; take one with \`${Brand.cli} claim <ask>\`.`199    )200  )201);202203const ask = viewOf(ShowAsk.successSchema, ({ brief }) => prose(brief));204205const discussionStates = {206  asked: "became the ask",207  closed: "closed",208  open: "open",209} as const satisfies Record<Discussion["state"], string>;210211const discussions = viewOf(212  ListDiscussions.successSchema,213  ({ discussions: listed }) =>214    joined(215      table(216        ["discussion", "title", "opener", "posts", "last post", "state"],217        listed.map(218          ({ ask: became, id, lastPostAt, opener, posts, state, title }) => [219            id,220            title,221            opener,222            String(posts),223            when(lastPostAt),224            became === undefined225              ? discussionStates[state]226              : `${discussionStates[state]} ${became}`,227          ]228        ),229        "No discussions yet."230      ),231      prose(232        `Read one with \`${Brand.cli} discussion <discussion>\`; open one with \`${Brand.cli} discussion post --title "<title>" --body "<post>"\`.`233      )234    )235);236237const onward = (discussion: Discussion) => {238  if (discussion.state === "open") {239    return `Reply with \`${Brand.cli} discussion post ${discussion.id} --body "<post>"\`.`;240  }241242  return discussion.ask === undefined243    ? "This discussion is closed."244    : `This discussion became the ask ${discussion.ask}: read it with \`${Brand.cli} ask ${discussion.ask}\`.`;245};246247const thread = (discussion: Discussion): View =>248  joined(249    prose(`# ${discussion.title}`),250    fields([251      ["Discussion", discussion.id],252      ["Opened by", `${discussion.opener} at ${when(discussion.openedAt)}`],253      [254        "State",255        discussion.ask === undefined256          ? discussionStates[discussion.state]257          : `${discussionStates[discussion.state]} ${discussion.ask}`,258      ],259    ]),260    ...discussion.posts.map(({ at, body, by }) =>261      prose(`**${by}** at ${when(at)}\n\n${body}`)262    ),263    prose(onward(discussion))264  );265266const discussion = viewOf(267  ShowDiscussion.successSchema,268  ({ discussion: shown }) => thread(shown)269);270271const posted = viewOf(PostDiscussion.successSchema, ({ discussion: shown }) =>272  thread(shown)273);274275/** Where the receipt is read: in a clone of the project or not, and what the fork's remote may be called. */276export interface Place {277  readonly inClone: boolean;278  readonly remoteName: string;279  /** False when a remote of that name already points at the fork. */280  readonly addRemote: boolean;281}282283const sameProject = (held: ClaimView, url: string) =>284  Option.exists(parseRemote(url), ({ repo }) =>285    Option.exists(parseRepoName(repo), (ref) => ref.project === held.project)286  );287288/** Outside a repo, `remotes` is empty, so the receipt starts with a clone. */289export const placeOf = (held: ClaimView, remotes: readonly Remote[]): Place => {290  const named = remotes.find(({ name }) => name === Brand.slug);291292  if (named === undefined) {293    return {294      addRemote: true,295      inClone: remotes.some(({ url }) => sameProject(held, url)),296      remoteName: Brand.slug,297    };298  }299300  return named.url === held.remote301    ? { addRemote: false, inClone: true, remoteName: Brand.slug }302    : {303        addRemote: true,304        inClone: remotes.some(({ url }) => sameProject(held, url)),305        remoteName: `${Brand.slug}-${held.ask}`,306      };307};308309const cloneOf = (held: ClaimView) =>310  Option.map(parseRemote(held.remote), ({ origin, repo }) => {311    const [canonical = repo] = repo.split("--");312    const folder = canonical.slice(canonical.lastIndexOf("/") + 1);313314    return `git clone ${origin}/${canonical}.git && cd ${folder}`;315  });316317export const claimReceipt = (held: ClaimView, place: Place): View => {318  const steps = [319    ...(place.inClone ? [] : Option.toArray(cloneOf(held))),320    ...(place.addRemote321      ? [`git remote add ${place.remoteName} ${held.remote}`]322      : []),323    `git fetch ${place.remoteName}`,324    `${Brand.cli} check`,325    `git push ${place.remoteName} HEAD:main`,326  ];327328  return {329    markdown: [330      `You hold the claim on \`${held.ask}\` in ${held.project} until ${when(held.lapsesAt)}; only a push keeps it alive.`,331      "",332      `Its fork: ${held.remote}`,333      "",334      "Next:",335      "",336      "```sh",337      ...steps,338      "```",339      "",340      `\`${Brand.cli} check\` runs \`${held.checkCommand}\` and the gate's checks locally, before you push.`,341    ].join("\n"),342    text: [343      `You hold the claim on ${held.ask} in ${held.project} until ${when(held.lapsesAt)}; only a push keeps it alive.`,344      `Its fork: ${held.remote}`,345      "Next:",346      ...steps.map((step) => `  ${step}`),347    ].join("\n"),348  };349};350351export const isClaimed = Schema.is(Claim.successSchema);352353const whoami = viewOf(WhoAmI.successSchema, ({ handle }) =>354  prose(`Signed in as ${handle}.`)355);356357const status = viewOf(Status.successSchema, ({ answers, claims, handle }) =>358  joined(359    prose(`Signed in as ${handle}.`),360    prose("Claims:"),361    table(362      ["ask", "project", "state", "lapses", "fork"],363      claims.map((held) => [364        held.ask,365        held.project,366        held.state,367        when(held.lapsesAt),368        held.remote,369      ]),370      "No claims."371    ),372    prose("Answers:"),373    table(374      ["ask", "head", "outcome", "at"],375      answers.map((answer) => [376        answer.ask,377        short(answer.head),378        outcomeText(answer.outcome),379        when(answer.at),380      ]),381      "No answers."382    )383  )384);385386const verdict = viewOf(VerdictOf.successSchema, ({ verdict: found }) => {387  if (found === undefined) {388    return prose("No verdict yet.");389  }390391  return joined(392    prose(393      `${found.ask} at ${short(found.head)}: ${outcomeText(found.outcome)} (furthest stage: ${found.stage}).`394    ),395    table(396      ["lane", "result", "command", "ms"],397      found.lanes.map((lane) => [398        lane.lane,399        lane.result,400        lane.command,401        String(lane.durationMs),402      ]),403      "No lanes ran."404    ),405    ...(found.heldBack.length === 0406      ? []407      : [408          table(409            ["area", "held back", "suite"],410            found.heldBack.map((area) => [411              area.area,412              `${area.passed}/${area.total}`,413              area.suite,414            ]),415            ""416          ),417        ])418  );419});420421const plural = (count: number, one: string, many: string) =>422  `${count} ${count === 1 ? one : many}`;423424const today = viewOf(TodayOf.successSchema, (page) =>425  joined(426    prose(427      `Today for ${page.decider}: ${plural(page.decisions.length, "decision", "decisions")} waiting${page.expiringSoon.length === 0 ? "" : `, ${page.expiringSoon.length} due within a day`}; each takes its default if nobody decides first.`428    ),429    table(430      ["decision", "project", "about", "default", "expires"],431      page.decisions.map((decision) => [432        decision.id,433        decision.project,434        subjectText(decision.subject),435        decision.default,436        when(decision.expiresAt),437      ]),438      "Nothing to decide."439    ),440    ...(page.decisions.length === 0441      ? []442      : [443          prose(444            `Take one with \`${Brand.cli} decide --project <owner>/<name> --decision <decision> --choice <choice> --yes\`.`445          ),446        ])447  )448);449450const countOf = (count: number) => (count === 0 ? "nobody" : `${count}`);451452const HOUR_MS = 3_600_000;453454const spanOf = (ms: number) => {455  if (ms % HOUR_MS !== 0) {456    return plural(Math.round(ms / 60_000), "minute", "minutes");457  }458459  const hours = ms / HOUR_MS;460461  return hours > 48 && hours % 24 === 0462    ? plural(hours / 24, "day", "days")463    : plural(hours, "hour", "hours");464};465466const PROJECT_FILE = `${Brand.configDir}/project.ts`;467468const vouchModes = {469  all: "For everything, which today gates what for code does: claiming an ask needs a vouch; anyone not denounced may post in a discussion.",470  bansOnly:471    "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or post.",472  forCode:473    "For code: claiming an ask needs a vouch; anyone not denounced may post in discussions.",474} as const satisfies Record<PublicPolicy["vouch"]["mode"], string>;475476const evaluated = (policy: PublicPolicy) => {477  const { agents, caps, claims, decisions, record, vouch, vouches } = policy;478  const denounced = vouches.filter((line) => line.denounced).length;479480  return joined(481    prose(482      policy.source === "config"483        ? `As of ${short(policy.at)}, the landed commit, from ${PROJECT_FILE}.`484        : `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.`485    ),486    prose("Maintainers by path:"),487    table(488      ["paths", "maintainers"],489      policy.deciders.map(({ handles, paths }) => [paths, handles.join(", ")]),490      "Nobody decides.",491      [0]492    ),493    prose(494      `Vouching: ${vouchModes[vouch.mode]} ${vouch.file} vouches for ${countOf(vouches.length - denounced)} and denounces ${countOf(denounced)}.`495    ),496    prose("Limits:"),497    fields([498      [499        "Claims",500        `${plural(caps.claimsPerPerson, "claim", "claims")} at once for a person nobody has vouched for; a vouched person and a maintainer are never held`,501      ],502      [503        "Decisions",504        `an undecided one takes its default after ${plural(decisions.expireDays, "day", "days")}`,505      ],506      [507        "Claim timing",508        `warned after ${spanOf(claims.warnAfterMs)} without a push; lapses after ${spanOf(claims.lapseAfterMs)}`,509      ],510      [511        "Record",512        `a landing counts ${513          record.countsAfterDays === 0514            ? "from the day it lands"515            : `once it has stood ${plural(record.countsAfterDays, "day", "days")}`516        }, for ${plural(record.windowDays, "day", "days")}`,517      ],518    ]),519    prose(520      agents === "trailer"521        ? "Agents: each landing names the agents its people worked through, in an Assisted-by: trailer."522        : "Agents: landings carry no Assisted-by: trailer."523    )524  );525};526527/** The view sees only the success, which names no project, so the command names it as `<owner>/<name>`. */528const pendingText = ({ at, reason }: PolicyPending) => {529  const notEvaluated = `The config at the landed commit ${short(at)} has not been evaluated`;530531  return reason === "noConfig"532    ? [533        `${notEvaluated}: there is no ${Brand.configDir}/ folder, and no test command in the project's CI or package files.`,534        `Run \`${Brand.cli} init --project <owner>/<name> --dry-run\` in the project's repo to see the ${PROJECT_FILE} it proposes, then have a maintainer land it.`,535      ]536    : [537        `${notEvaluated}: ${Brand.configDir}/ at ${short(at)} did not evaluate.`,538        `Fix it by landing a change to ${Brand.configDir}/; it is evaluated again at every landing.`,539      ];540};541542const importedText = ({ branch, url }: ImportSource) =>543  prose(544    `Imported from ${url}${branch === undefined ? "" : ` (branch ${branch})`}: this project is ${IMPORTED_NOTE}.`545  );546547const policyText = (read: typeof PolicyOf.successSchema.Type): View => {548  if (read.policy !== undefined) {549    return evaluated(read.policy);550  }551552  if (read.unevaluated === undefined) {553    return prose(554      "Nothing has landed yet. The config is evaluated at every landing."555    );556  }557558  const lines = pendingText(read.unevaluated);559560  return { markdown: lines.join("\n\n"), text: lines.join("\n") };561};562563const policy = viewOf(PolicyOf.successSchema, (read) =>564  read.importedFrom === undefined565    ? policyText(read)566    : joined(importedText(read.importedFrom), policyText(read))567);568569const ledger = viewOf(LedgerOf.successSchema, (book) =>570  joined(571    prose(`${book.project}: ${book.postureLabel}.`),572    table(573      ["#", "at", "entry"],574      book.entries.map((entry) => [575        String(entry.seq),576        when(entry.at),577        entryText(entry),578      ]),579      "The ledger is empty."580    )581  )582);583584const credits = viewOf(Credits.successSchema, ({ credits: counted }) =>585  table(586    ["project", "area", "role", "count"],587    counted.map((credit) => [588      credit.project,589      credit.area,590      credit.role,591      String(credit.count),592    ]),593    "No credits yet."594  )595);596597const projects = viewOf(ListProjects.successSchema, ({ projects: listed }) =>598  table(599    ["project", "posture", "open asks", "landed"],600    listed.map((listing) => [601      listing.project,602      listing.posture,603      String(listing.openAsks),604      listing.landedAt === undefined ? "never" : when(listing.landedAt),605    ]),606    "No projects yet."607  )608);609610const front = viewOf(FrontPage.successSchema, ({ entries }) =>611  table(612    ["project", "ask", "kind", "want", "takeable"],613    entries.map((entry) => [614      entry.project,615      entry.ask.ask,616      entry.ask.kind,617      entry.ask.want,618      yesNo(entry.takeable),619    ]),620    "No open asks anywhere."621  )622);623624const receipt = (offered: AnswerReceipt) =>625  prose(626    Result.getOrElse(receiptLine(offered), () => `${offered.ask} was refused`)627  );628629const submitted = viewOf(SubmitAnswer.successSchema, receipt);630631const finished = viewOf(Finish.successSchema, receipt);632633// The checks run after `land` returns; the same request sent again reads where they stand.634const landing = viewOf(Land.successSchema, ({ head, outcome, requestId }) =>635  prose(636    Outcome.guards.Checking(outcome)637      ? `checking ${short(head)} (${outcome.stage}); follow with the same \`${Brand.cli} land\`, --requestId ${requestId} and all, which checks nothing twice`638      : `${short(head)}: ${outcomeText(outcome)}`639  )640);641642const isReceipt = Schema.is(LandReceipt);643644/** `finish` and `land` refuse stages 0–1 inside a success's receipt; the command prints them as refusals and exits 1. */645export const refusalsIn = (646  success: Rpc.Success<Contract>647): readonly Refusal[] =>648  isReceipt(success) && Outcome.guards.Refused(success.outcome)649    ? success.outcome.refusals650    : [];651652/** `claim`'s receipt looks at the repo it is printed in, so the CLI's surfaces add it. */653export const views = {654  credits,655  finish: finished,656  frontPage: front,657  land: landing,658  ledger,659  listAsks: asks,660  listDiscussions: discussions,661  listProjects: projects,662  postDiscussion: posted,663  projectPolicy: policy,664  showAsk: ask,665  showDiscussion: discussion,666  status,667  submitAnswer: submitted,668  today,669  verdict,670  whoami,671} as const satisfies Readonly<672  Partial<673    Record<674      Contract["_tag"],675      (success: Rpc.Success<Contract>) => Option.Option<View>676    >677  >678>;