Skip to content
Myr

render.ts

This file

Path

apps/cli/src/render.ts

540 lines · 16.4 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

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  LedgerOf,10  ListAsks,11  ListProjects,12  PolicyOf,13  ShowAsk,14  Status,15  SubmitAnswer,16  TodayOf,17  VerdictOf,18} from "@repo/protocol/contracts";19import type { Contract } from "@repo/protocol/contracts";20import { LandReceipt } from "@repo/protocol/domain/answer";21import type { AnswerReceipt } from "@repo/protocol/domain/answer";22import { DecisionSubject } from "@repo/protocol/domain/decision";23import { Outcome } from "@repo/protocol/domain/outcome";24import type {25  ImportSource,26  PolicyPending,27  PublicPolicy,28} from "@repo/protocol/domain/policy";29import { LedgerEntry } from "@repo/protocol/domain/visibility";30import type { Refusal } from "@repo/protocol/refusal";31import { receiptLine } from "@repo/protocol/render";32import { DateTime, Option, Result, Schema } from "effect";33import type { Rpc } from "effect/rpc";3435const short = (sha: string) => sha.slice(0, 7);3637const when = (at: DateTime.Utc) => DateTime.formatIso(at);3839const yesNo = (value: boolean) => (value ? "yes" : "no");4041const cell = (text: string) =>42  text.replaceAll("|", "\\|").replaceAll(/\s*\n\s*/gu, " ");4344const codeSpan = (text: string) => {45  const longest = Math.max(46    0,47    ...(text.match(/`+/gu) ?? []).map((run) => run.length)48  );4950  const fence = "`".repeat(longest + 1);51  const pad = text.startsWith("`") || text.endsWith("`") ? " " : "";5253  return `${fence}${pad}${text}${pad}${fence}`;54};5556/** Columns in `code` hold literal text (a glob, a path), shown as code so `**` never reads as emphasis. */57const table = (58  headers: readonly string[],59  rows: readonly (readonly string[])[],60  empty: string,61  code: readonly number[] = []62): View => {63  if (rows.length === 0) {64    return { markdown: empty, text: empty };65  }6667  const widths = headers.map((header, column) =>68    Math.max(header.length, ...rows.map((row) => (row[column] ?? "").length))69  );7071  const padded = (row: readonly string[]) =>72    row73      .map((text, column) => text.padEnd(widths[column] ?? 0))74      .join("  ")75      .trimEnd();7677  return {78    markdown: [79      `| ${headers.join(" | ")} |`,80      `| ${headers.map(() => "---").join(" | ")} |`,81      ...rows.map(82        (row) =>83          `| ${row84            .map((text, column) =>85              code.includes(column) ? cell(codeSpan(text)) : cell(text)86            )87            .join(" | ")} |`88      ),89    ].join("\n"),90    text: [91      padded(headers.map((header) => header.toUpperCase())),92      ...rows.map(padded),93    ].join("\n"),94  };95};9697const fields = (rows: readonly (readonly [string, string])[]): View => {98  const width = Math.max(0, ...rows.map(([label]) => label.length));99100  return {101    markdown: rows.map(([label, value]) => `- ${label}: ${value}`).join("\n"),102    text: rows103      .map(([label, value]) => `${label.padEnd(width)}  ${value}`)104      .join("\n"),105  };106};107108const joined = (...parts: readonly View[]): View => ({109  markdown: parts.map(({ markdown }) => markdown).join("\n\n"),110  text: parts.map(({ markdown, text }) => text ?? markdown).join("\n\n"),111});112113const prose = (text: string): View => ({ markdown: text });114115const outcomeText = (outcome: Outcome) =>116  Outcome.match(outcome, {117    AwaitingDecision: ({ decision }) => `waits on decision ${decision}`,118    AwaitingFinish: () => "passed; waits for a maintainer's finish",119    Checking: ({ stage }) => `checking (${stage})`,120    Landed: ({ sha }) => `landed as ${short(sha)}`,121    Refused: ({ refusals }) =>122      `refused: ${refusals.map((refusal) => refusal._tag).join(", ")}`,123    WaitingOnParent: ({ ask }) => `passed; waits for ${ask} to land`,124  });125126const subjectText = (subject: DecisionSubject) =>127  DecisionSubject.match(subject, {128    Finish: ({ ask, head }) => `finish the answer to ${ask} at ${short(head)}`,129    OpenProposal: ({ proposal }) =>130      `open the ask proposal ${proposal} asks for`,131    PostureChange: ({ from, to }) => `change the posture from ${from} to ${to}`,132    ProxyWidened: ({ hosts, item }) =>133      `let ${item}'s placeholder reach ${hosts.join(", ")}`,134    RaiseRatchet: ({ after, before, ratchet, territory }) =>135      `raise the ${ratchet} ratchet in ${territory} from ${before} to ${after}`,136    SecretInTree: ({ ask, item }) =>137      `${item}'s write-only value showed up in an answer to ${ask}`,138    StrayPush: ({ after, before, ref }) =>139      `${ref} moved from ${short(before)} to ${short(after)} without a landing`,140    Vouch: ({ handle }) => `vouch for ${handle}`,141    Waiver: ({ at, marker, reason }) =>142      `allow ${marker} at ${at.path}:${at.line} ("${reason}")`,143  });144145const entryText = (entry: LedgerEntry) =>146  LedgerEntry.match(entry, {147    Admitted: ({ area, knownBadCaught, mainRuns, suite }) =>148      `held-back suite ${suite} admitted in ${area} after ${mainRuns} runs on main, catching ${knownBadCaught} known-bad trees`,149    CommitmentPublished: ({ area, authors, checks, suite }) =>150      `commitment ${suite} published for ${area}: ${checks} checks by ${authors} authors`,151    CountChanged: ({ area, count, layer }) =>152      `${layer} holds ${count} in ${area}`,153    LayerDeclared: ({ disclose, kinds, layer }) =>154      `layer ${layer} declared, holding ${kinds.join(", ")}, disclosing ${disclose}`,155    PostureChanged: ({ decision, from, to }) =>156      `posture changed from ${from} to ${to} by decision ${decision}`,157    Released: ({ by, landing, layer, paths }) =>158      `${by} released ${paths} paths from ${layer} in ${short(landing)}`,159    ValueSet: ({ by, key }) => `${by} set the write-only value of ${key}`,160  });161162const viewOf = <S extends Schema.Top>(163  schema: S,164  render: (success: S["Type"]) => View165) => {166  const is = Schema.is(schema);167168  return (success: Rpc.Success<Contract>): Option.Option<View> =>169    is(success) ? Option.some(render(success)) : Option.none();170};171172const asks = viewOf(ListAsks.successSchema, ({ asks: listed }) =>173  joined(174    table(175      ["ask", "kind", "territory", "want", "claimed"],176      listed.map(177        ({ ask, blockedBy, claimed, kind, reserve, territory, want }) => [178          ask,179          reserve === undefined ? kind : `${kind} (for ${reserve})`,180          territory,181          blockedBy.length === 0182            ? want183            : `${want} (waits on ${blockedBy.join(", ")})`,184          yesNo(claimed),185        ]186      ),187      "No open asks."188    ),189    prose(190      `Read one with \`${Brand.cli} ask <ask>\`; take one with \`${Brand.cli} claim <ask>\`.`191    )192  )193);194195const ask = viewOf(ShowAsk.successSchema, ({ brief }) => prose(brief));196197const claim = viewOf(Claim.successSchema, ({ claim: held }) => {198  const steps = [199    `git remote add ${Brand.slug} ${held.remote}`,200    `${Brand.cli} check`,201    `git push ${Brand.slug} HEAD:main`,202  ];203204  return {205    markdown: [206      `You hold the claim on \`${held.ask}\` in ${held.project} until ${when(held.lapsesAt)}; only a push keeps it alive.`,207      "",208      `Its fork: ${held.remote}`,209      "",210      "Next:",211      "",212      "```sh",213      ...steps,214      "```",215      "",216      `\`${Brand.cli} check\` runs \`${held.checkCommand}\` and the gate's checks locally, before you push.`,217    ].join("\n"),218    text: [219      `You hold the claim on ${held.ask} in ${held.project} until ${when(held.lapsesAt)}; only a push keeps it alive.`,220      `Its fork: ${held.remote}`,221      "Next:",222      ...steps.map((step) => `  ${step}`),223    ].join("\n"),224  };225});226227const status = viewOf(Status.successSchema, ({ answers, claims, handle }) =>228  joined(229    prose(`Signed in as ${handle}.`),230    prose("Claims:"),231    table(232      ["ask", "project", "state", "lapses", "fork"],233      claims.map((held) => [234        held.ask,235        held.project,236        held.state,237        when(held.lapsesAt),238        held.remote,239      ]),240      "No claims."241    ),242    prose("Answers:"),243    table(244      ["ask", "head", "outcome", "at"],245      answers.map((answer) => [246        answer.ask,247        short(answer.head),248        outcomeText(answer.outcome),249        when(answer.at),250      ]),251      "No answers."252    )253  )254);255256const verdict = viewOf(VerdictOf.successSchema, ({ verdict: found }) => {257  if (found === undefined) {258    return prose("No verdict yet.");259  }260261  return joined(262    prose(263      `${found.ask} at ${short(found.head)}: ${outcomeText(found.outcome)} (furthest stage: ${found.stage}).`264    ),265    table(266      ["lane", "result", "command", "ms"],267      found.lanes.map((lane) => [268        lane.lane,269        lane.result,270        lane.command,271        String(lane.durationMs),272      ]),273      "No lanes ran."274    ),275    ...(found.heldBack.length === 0276      ? []277      : [278          table(279            ["area", "held back", "suite"],280            found.heldBack.map((area) => [281              area.area,282              `${area.passed}/${area.total}`,283              area.suite,284            ]),285            ""286          ),287        ])288  );289});290291const today = viewOf(TodayOf.successSchema, (page) =>292  joined(293    prose(294      `Today for ${page.decider}: ${page.budget.used} of ${page.budget.total} decisions used${page.overflow === 0 ? "" : `; ${page.overflow} more wait beyond the budget`}.`295    ),296    table(297      ["decision", "project", "about", "default", "expires"],298      page.decisions.map((decision) => [299        decision.id,300        decision.project,301        subjectText(decision.subject),302        decision.default,303        when(decision.expiresAt),304      ]),305      "Nothing to decide."306    ),307    ...(page.decisions.length === 0308      ? []309      : [310          prose(311            `Take one with \`${Brand.cli} decide --project <owner>/<name> --decision <decision> --choice <choice> --yes\`.`312          ),313        ])314  )315);316317const plural = (count: number, one: string, many: string) =>318  `${count} ${count === 1 ? one : many}`;319320const countOf = (count: number) => (count === 0 ? "nobody" : `${count}`);321322const HOUR_MS = 3_600_000;323324const spanOf = (ms: number) => {325  if (ms % HOUR_MS !== 0) {326    return plural(Math.round(ms / 60_000), "minute", "minutes");327  }328329  const hours = ms / HOUR_MS;330331  return hours > 48 && hours % 24 === 0332    ? plural(hours / 24, "day", "days")333    : plural(hours, "hour", "hours");334};335336const PROJECT_FILE = `${Brand.configDir}/project.ts`;337338const vouchModes = {339  all: "For everything: claiming an ask, offering a sealed answer and proposing an ask all need a vouch.",340  bansOnly:341    "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or propose.",342  forCode:343    "For code: claiming an ask or offering a sealed answer needs a vouch; anyone not denounced may propose an ask.",344} as const satisfies Record<PublicPolicy["vouch"]["mode"], string>;345346const evaluated = (policy: PublicPolicy) => {347  const { agents, budget, caps, claims, record, vouch, vouches } = policy;348  const denounced = vouches.filter((line) => line.denounced).length;349350  return joined(351    prose(352      policy.source === "config"353        ? `As of ${short(policy.at)}, the landed commit, from ${PROJECT_FILE}.`354        : `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.`355    ),356    prose("Maintainers by path:"),357    table(358      ["paths", "maintainers"],359      policy.deciders.map(({ handles, paths }) => [paths, handles.join(", ")]),360      "Nobody decides.",361      [0]362    ),363    prose(364      `Vouching: ${vouchModes[vouch.mode]} ${vouch.file} vouches for ${countOf(vouches.length - denounced)} and denounces ${countOf(denounced)}.`365    ),366    prose("Limits:"),367    fields([368      [369        "Claims",370        `${plural(caps.claimsPerPerson, "claim", "claims")} per person at once`,371      ],372      [373        "Proposals",374        caps.proposalsPerPerson === 0375          ? "Proposals are off"376          : `${plural(caps.proposalsPerPerson, "proposal", "proposals")} per person at once`,377      ],378      [379        "Budget",380        `${plural(budget.decisionsPerDay, "decision", "decisions")} a day per maintainer; an undecided one takes its default after ${plural(budget.expireDays, "day", "days")}`,381      ],382      [383        "Claim timing",384        `warned after ${spanOf(claims.warnAfterMs)} without a push; lapses after ${spanOf(claims.lapseAfterMs)}`,385      ],386      [387        "Record",388        `a landing counts ${389          record.countsAfterDays === 0390            ? "from the day it lands"391            : `once it has stood ${plural(record.countsAfterDays, "day", "days")}`392        }, for ${plural(record.windowDays, "day", "days")}`,393      ],394    ]),395    prose(396      agents === "trailer"397        ? "Agents: each landing names the agents its people worked through, in an Assisted-by: trailer."398        : "Agents: landings carry no Assisted-by: trailer."399    )400  );401};402403/** The view sees only the success, which names no project, so the command names it as `<owner>/<name>`. */404const pendingText = ({ at, reason }: PolicyPending) => {405  const notEvaluated = `The config at the landed commit ${short(at)} has not been evaluated`;406407  return reason === "noConfig"408    ? [409        `${notEvaluated}: there is no ${Brand.configDir}/ folder, and no test command in the project's CI or package files.`,410        `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.`,411      ]412    : [413        `${notEvaluated}: ${Brand.configDir}/ at ${short(at)} did not evaluate.`,414        `Fix it by landing a change to ${Brand.configDir}/; it is evaluated again at every landing.`,415      ];416};417418const importedText = ({ branch, url }: ImportSource) =>419  prose(420    `Imported from ${url}${branch === undefined ? "" : ` (branch ${branch})`}: this project is ${IMPORTED_NOTE}.`421  );422423const policyText = (read: typeof PolicyOf.successSchema.Type): View => {424  if (read.policy !== undefined) {425    return evaluated(read.policy);426  }427428  if (read.unevaluated === undefined) {429    return prose(430      "Nothing has landed yet. The config is evaluated at every landing."431    );432  }433434  const lines = pendingText(read.unevaluated);435436  return { markdown: lines.join("\n\n"), text: lines.join("\n") };437};438439const policy = viewOf(PolicyOf.successSchema, (read) =>440  read.importedFrom === undefined441    ? policyText(read)442    : joined(importedText(read.importedFrom), policyText(read))443);444445const ledger = viewOf(LedgerOf.successSchema, (book) =>446  joined(447    prose(`${book.project}: ${book.postureLabel}.`),448    table(449      ["#", "at", "entry"],450      book.entries.map((entry) => [451        String(entry.seq),452        when(entry.at),453        entryText(entry),454      ]),455      "The ledger is empty."456    )457  )458);459460const credits = viewOf(Credits.successSchema, ({ credits: counted }) =>461  table(462    ["project", "area", "role", "count"],463    counted.map((credit) => [464      credit.project,465      credit.area,466      credit.role,467      String(credit.count),468    ]),469    "No credits yet."470  )471);472473const projects = viewOf(ListProjects.successSchema, ({ projects: listed }) =>474  table(475    ["project", "posture", "open asks", "landed"],476    listed.map((listing) => [477      listing.project,478      listing.posture,479      String(listing.openAsks),480      listing.landedAt === undefined ? "never" : when(listing.landedAt),481    ]),482    "No projects yet."483  )484);485486const front = viewOf(FrontPage.successSchema, ({ entries }) =>487  table(488    ["project", "ask", "kind", "want", "takeable"],489    entries.map((entry) => [490      entry.project,491      entry.ask.ask,492      entry.ask.kind,493      entry.ask.want,494      yesNo(entry.takeable),495    ]),496    "No open asks anywhere."497  )498);499500const receipt = (offered: AnswerReceipt) =>501  prose(502    Result.getOrElse(receiptLine(offered), () => `${offered.ask} was refused`)503  );504505const submitted = viewOf(SubmitAnswer.successSchema, receipt);506507const finished = viewOf(Finish.successSchema, receipt);508509const isReceipt = Schema.is(LandReceipt);510511/** `finish` and `land` refuse stages 0–1 inside a success's receipt; the command prints them as refusals and exits 1. */512export const refusalsIn = (513  success: Rpc.Success<Contract>514): readonly Refusal[] =>515  isReceipt(success) && Outcome.guards.Refused(success.outcome)516    ? success.outcome.refusals517    : [];518519export const views = {520  claim,521  credits,522  finish: finished,523  frontPage: front,524  ledger,525  listAsks: asks,526  listProjects: projects,527  projectPolicy: policy,528  showAsk: ask,529  status,530  submitAnswer: submitted,531  today,532  verdict,533} as const satisfies Readonly<534  Partial<535    Record<536      Contract["_tag"],537      (success: Rpc.Success<Contract>) => Option.Option<View>538    >539  >540>;