Merge build/404-cli-projections-and-agent-policy: every contract is a CLI command that behaves well under an agent
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents a560b12, 80e98da · Browse files · 13 files·+3164 added−250 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+3164 added−250 removed
- tests:+1460 added−72 removed
- other:+1704 added−178 removed
Provenance
- Commit
03b20ff- Tree
d9918db- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
a560b12- Parent 2
80e98da
13 files changed+3164 added−250 removed
modified:apps/cli/src/main.ts+154 added-57 removed
123345667789910101112131415141516161718192021222324252627284 unmodified lines333435362930313233343536373839404137383943444546474849505152535455565758596061626364404142432 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111128081828384113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155871561571581591601611621631641651661671681691701711721731741751761771781798918018191929394959697182183184185186187188189190191192193194195/** * The CLI's command tree and the program that runs it. `bin.ts` runs * `program` with the real services; tests run it, or `root`, with theirs. * `program` with the real services (`CliServices`); tests run it, or `root`, * with theirs. */import { Brand } from "@repo/brand";import { toCommand } from "@repo/protocol/cli";import { Claim, Cli, Client, ListAsks } from "@repo/protocol/contracts";import { ApprovalNeeded, MissingValue, Reported } from "@repo/protocol/cli";import { Unauthenticated } from "@repo/protocol/principal";import { Refusal } from "@repo/protocol/refusal";import { Context, Effect, Schema } from "effect";import { CliError, Command } from "effect/cli";import { Console, Effect, Exit, Layer, Option, Runtime, Schema } from "effect";import { CliConfig, CliError, Command, GlobalFlag } from "effect/cli";
import { credential } from "./credential-helper.ts";import { CredentialsFile } from "./credentials.ts";import { hook } from "./hook.ts";import { local } from "./local/index.ts";import { Output, Reported } from "./output.ts";import { mcp } from "./surfaces.ts";import { holdStdout, Output, OutputLive } from "./output.ts";import { CurrentMode, Policy } from "./policy.ts";import { isTransportFailure, noPlatformOf, RemoteClient, transportMessage,} from "./remote.ts";import { commands, mcp, UnknownCommand } from "./surfaces.ts";
/** * The three commands that start any contribution, first in `--help`, so a * person or an agent who knows nothing else knows where to begin.4 unmodified lines ` ${Brand.cli} claim take one; you get a fork to push your answer to`, ` ${Brand.cli} check run the gate's checks locally before you push`,].join("\n");
/** * The contracts as commands, each named (and given its positional fields) * by its `Cli` annotation. Only the two the banner names, until issue 404 * projects every `cli` contract and merges their paths with `local`'s. */const projected = [ toCommand( ListAsks, Effect.service(Client), Context.get(ListAsks.annotations, Cli) ), toCommand(Claim, Effect.service(Client), Context.get(Claim.annotations, Cli)),] as const;/** The commands at the top: the contracts and the hand-written ones, then the servers. */const tree = [...commands, mcp, hook, credential];
/** `env`: the group `env set` (and, from 404, `env shape`) lives under. */const env = Command.make("env").pipe( Command.withDescription( "Read a project's env shape, or set a write-only value." ), Command.withSubcommands( local.filter(({ path }) => path[0] === "env").map(({ command }) => command) ));
/** The commands at the top: one word each. */const tree = [ ...projected, ...local .filter(({ path }) => path.length === 1) .map(({ command }) => command), env, mcp, hook, credential,];
export const root = Command.make(Brand.cli).pipe( Command.withDescription(banner), Command.withSubcommands(tree));2 unmodified lines * The CLI's version until issue 416's build stamps the release's own. */const version = "0.0.0";
/** * The command was misused and said so in one line on stderr: the program * exits 2 and prints nothing more. */export class Misused extends Schema.TaggedError<Misused>()("Misused", {}) { override readonly [Runtime.errorExitCode] = 2; override readonly [Runtime.errorReported] = false;}
const isRefusal = Schema.is(Refusal);
const isReported = Schema.is(Reported);
const isUnauthenticated = Schema.is(Unauthenticated);
/** Usage errors that are this CLI's own, beside effect/cli's. */const isUsage = Schema.is( Schema.Union([ApprovalNeeded, MissingValue, UnknownCommand]));
/** What to run when the platform does not know who is calling. */const signIn = [ "Unauthenticated: the platform does not know who you are", ` next: ${Brand.cli} login`, " retryable: no",].join("\n");
/** How running the tree can fail. */type Failure = Command.Error<typeof root> | CliError.CliError;
/** One line for a failure that is a misuse of the command; none otherwise. */const usageLine = (failure: Failure): Option.Option<string> => { if (CliError.isCliError(failure)) { return Option.some( Schema.is(CliError.ShowHelp)(failure) ? failure.errors.map((error) => error.message).join("; ") : failure.message ); }
if (isUsage(failure) || Schema.isSchemaError(failure)) { return Option.some(failure.message); }
return isTransportFailure(failure) ? Option.map(noPlatformOf(failure), ({ message }) => message) : Option.none();};
/** What to say on stderr about a failure nobody printed yet. */const noteFor = (failure: Failure) => { if (isUnauthenticated(failure)) { return signIn; }
if (isTransportFailure(failure)) { return `could not reach the platform: ${transportMessage(failure)}`; }
return String(failure);};
/** * Runs the command `argv` names. Every failure has been printed once by the * time it ends as `Reported` (exit 1): a parse error by effect/cli, a * refusal by the command, anything else here, as a note. Help asked for, or * shown for a group run without a subcommand, is a success. A defect (a * stub's "not built") is not caught: the runtime prints it, loudly. * Says once what nobody printed yet, and how the process ends: a misuse in * one line on stderr (exit 2); not being signed in with what to run next, * and a platform out of reach, on stderr (exit 1); a refusal or anything * `Reported`, nothing more (exit 1). */const settle = ( failure: Failure): Effect.Effect<never, Reported | Misused, Output> => Option.match(usageLine(failure), { onNone: () => isReported(failure) || isRefusal(failure) ? Effect.fail(new Reported()) : Output.use((output) => output.note(noteFor(failure))).pipe( Effect.andThen(Effect.fail(new Reported())) ), onSome: (line) => Output.use((output) => output.note(line)).pipe( Effect.andThen(Effect.fail(new Misused())) ), });
/** Whether a run ended in a misuse effect/cli found: a parse error. */const isMisuse = (failure: Failure) => Schema.is(CliError.ShowHelp)(failure) && failure.errors.length > 0;
/** * effect/cli's built-in flags for `mode`: the wizard prompts, so only a * person at a terminal gets it. */const builtInsFor = (policy: Option.Option<Policy["Service"]>) => Option.exists(policy, ({ mode }) => mode !== "human") ? GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Wizard) : GlobalFlag.BuiltIns;
/** * Runs the command `argv` names. Help asked for, or shown for a group run * without a subcommand, is a success. A misuse (a parse error, a missing * value, `--yes` left out) ends as `Misused` (exit 2) after one line on * stderr; every other failure ends as `Reported` (exit 1), printed once: a * refusal by the command, anything else here. A defect (a stub's "not * built") is not caught: the runtime prints it, loudly. */export const program = (argv: readonly string[]) => Command.runWith(root, { version })(argv).pipe( Effect.gen(function* () { const policy = yield* Effect.serviceOption(Policy); const stdout = holdStdout(yield* Console.Console);
const exit = yield* Effect.exit( Command.runWith(root.pipe(Command.provideEffectDiscard(stdout.open)), { renderErrors: false, version, })(argv).pipe( Effect.provideService( CliConfig.CliConfig, CliConfig.make({ builtIns: builtInsFor(policy) }) ), Effect.provideService(Console.Console, stdout.console) ) );
if (!Option.exists(Exit.findErrorOption(exit), isMisuse)) { yield* stdout.release; }
return yield* exit; }).pipe( Effect.catchTag("ShowHelp", (help) => help.errors.length === 0 ? Effect.void : Effect.fail(new Reported()) help.errors.length === 0 ? Effect.void : Effect.fail(help) ), // effect/cli printed its own errors, and a command its refusals. Effect.tapError((failure) => CliError.isCliError(failure) || isRefusal(failure) || isReported(failure) ? Effect.void : Output.use((output) => output.note(String(failure))) ), Effect.mapError(() => new Reported()) Effect.matchEffect({ onFailure: (failure) => settle(failure), onSuccess: () => Effect.void, }) );
/** * What `program` runs on in a real process, beside the host's own services * (`BunServices`): the stored credentials, the invocation policy, output in * its form, and the platform over HTTP as the stored profile. */export const CliServices = Layer.mergeAll(OutputLive, RemoteClient).pipe( Layer.provideMerge(Layer.mergeAll(CurrentMode, CredentialsFile)));modified:apps/cli/src/output.ts+174 added-37 removed
1 /**2 * The one way every command prints. A command hands its result, its3 * refusals or its plan to `Output`, which decides the form: text for a4- * person, Markdown for an agent, one `--json` envelope for a script. Notes5- * go to stderr only, so `--json` stdout is always exactly one document.4+ * person, Markdown for an agent or a script, one `--json` envelope when asked5+ * for. Notes go to stderr only, so `--json` stdout is always exactly one6+ * document.7 */8+import type { View } from "@repo/protocol/cli";9 import { Envelope } from "@repo/protocol/envelope";10 import type { Refusal } from "@repo/protocol/refusal";11 import { explain } from "@repo/protocol/render";10-import { Console, Context, Effect, Layer, Runtime, Schema } from "effect";12+import { Console, Context, Effect, Layer, Schema } from "effect";13 import type { Array } from "effect";14 13-/** Who is reading: a person at a terminal, an agent, or a script. */14-export type Mode = "human" | "agent" | "automation";15+import { Policy } from "./policy.ts";16+import type { Mode } from "./policy.ts";17 16-/** A result as prose: Markdown, and plain text where a person reads it. */17-export interface View {18- readonly markdown: string;19- readonly text?: string;20-}18+export { Reported } from "@repo/protocol/cli";19 20+export type { View } from "@repo/protocol/cli";21+22+export type { Mode } from "./policy.ts";23+24 export class Output extends Context.Service<25 Output,26 {27 readonly mode: Mode;20 unmodified lines48 readonly note: (text: string) => Effect.Effect<void>;49 }50 >()("cli/Output") {}51 50-/**51- * Everything a command printed has been printed: the program exits 1 and52- * prints nothing more, and the runtime reports nothing of its own.53- */54-export class Reported extends Schema.TaggedError<Reported>()("Reported", {}) {55- override readonly [Runtime.errorExitCode] = 1;56- override readonly [Runtime.errorReported] = false;57-}58-52 /** Any envelope's JSON: its data is already encoded. */53 const encodeEnvelope = Schema.encodeEffect(54 Schema.fromJsonString(Envelope(Schema.Unknown))55 );1 unmodified line57 /** One envelope, as the one document on stdout. */58 const printEnvelope = (envelope: Envelope<unknown>) =>59 encodeEnvelope(envelope).pipe(Effect.orDie, Effect.flatMap(Console.log));60 61+const capitalized = (word: string) =>62+ `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`;63+64 /**69- * Plain output, for a person: text on stdout, refusals on stderr, and70- * `--json` as one `Envelope` (`@repo/protocol/envelope`) on stdout and71- * nothing else there. Issue 404's agent policy chooses Markdown for agents72- * behind the same service.65+ * `explain`'s lines as a Markdown list: one item per refusal, its pointer,66+ * next command and `Retryable: yes|no` beneath it. The renderer stays the67+ * one source of the words; only the layout changes.68 */74-export const OutputPlain = Layer.succeed(Output)({75- mode: "human",69+const asMarkdownList = (lines: readonly string[]) =>70+ lines.map((line) => {71+ const detail = /^ {2}(?<key>[a-z]+): (?<value>.*)$/u.exec(line)?.groups;72+73+ if (detail?.key === undefined || detail.value === undefined) {74+ return `- ${line}`;75+ }76+77+ const value = detail.key === "next" ? `\`${detail.value}\`` : detail.value;78+79+ return ` - ${capitalized(detail.key)}: ${value}`;80+ });81+82+/** The JSON a plan sends, as a person reads it or as a Markdown block. */83+const planText = (mode: Mode, command: string, json: string) =>84+ mode === "human"85+ ? `${command} would send this, and sent nothing:\n${json}`86+ : [87+ `\`${command}\` would send this, and sent nothing (--dry-run):`,88+ "",89+ "```json",90+ json,91+ "```",92+ ].join("\n");93+94+/**95+ * Output for `mode`: a person reads `view.text` (or the Markdown when a view96+ * has no text) and refusals as `explain`'s lines; an agent or a script97+ * reads Markdown, with refusals as a Markdown list. Under `--json` stdout98+ * holds one `Envelope` and nothing else, refusals included.99+ */100+const outputFor = (mode: Mode): Output["Service"] => ({101+ mode,102 note: (text) => Console.error(text),103 plan: ({ command, json, payload }) =>104 json79- ? printEnvelope({ command, data: { dryRun: payload }, ok: true, v: 1 })80- : Console.log(81- `${command} would send:\n${JSON.stringify(payload, null, 2)}`82- ),83- refused: ({ command, json, refusals }) =>84- json85- ? printEnvelope({ command, ok: false, refusals, v: 1 })86- : Console.error(explain(refusals).join("\n")),87- success: ({ command, data, json, view }) =>88- json89- ? printEnvelope({ command, data, ok: true, v: 1 })90- : Console.log(view.text ?? view.markdown),105+ ? printEnvelope({106+ command,107+ data: { dryRun: true, payload },108+ ok: true,109+ v: 1,110+ })111+ : Console.log(planText(mode, command, JSON.stringify(payload, null, 2))),112+ refused: ({ command, json, refusals }) => {113+ if (json) {114+ return printEnvelope({ command, ok: false, refusals, v: 1 });115+ }116+117+ const lines = explain(refusals);118+119+ return Console.error(120+ (mode === "human" ? lines : asMarkdownList(lines)).join("\n")121+ );122+ },123+ success: ({ command, data, json, view }) => {124+ if (json) {125+ return printEnvelope({ command, data, ok: true, v: 1 });126+ }127+128+ return Console.log(129+ mode === "human" ? (view.text ?? view.markdown) : view.markdown130+ );131+ },132 });133+134+/** Output for a person, whatever the process: what tests of a command's text use. */135+export const OutputPlain = Layer.succeed(Output)(outputFor("human"));136+137+/** Output in the form the invocation policy chose for this process. */138+export const OutputLive: Layer.Layer<Output, never, Policy> = Layer.effect(139+ Output140+)(Effect.map(Effect.service(Policy), ({ mode }) => outputFor(mode)));141+142+/**143+ * Stdout held back until a command's handler runs. effect/cli prints help on144+ * stdout for a misuse too: held, that help is dropped after a misuse (whose145+ * one line goes to stderr), and printed when the run ends any other way146+ * (help asked for, the version, a group run bare).147+ */148+export const holdStdout = (real: Console.Console) => {149+ const held: (readonly unknown[])[] = [];150+ let open = false;151+152+ // Each method hands its call to the real console; only `log` waits.153+ const console: Console.Console = {154+ assert: (condition, ...args: readonly unknown[]) => {155+ real.assert(condition, ...args);156+ },157+ clear: () => {158+ real.clear();159+ },160+ count: (label) => {161+ real.count(label);162+ },163+ countReset: (label) => {164+ real.countReset(label);165+ },166+ debug: (...args: readonly unknown[]) => {167+ real.debug(...args);168+ },169+ dir: (item, options) => {170+ real.dir(item, options);171+ },172+ dirxml: (...args: readonly unknown[]) => {173+ real.dirxml(...args);174+ },175+ error: (...args: readonly unknown[]) => {176+ real.error(...args);177+ },178+ group: (...args: readonly unknown[]) => {179+ real.group(...args);180+ },181+ groupCollapsed: (...args: readonly unknown[]) => {182+ real.groupCollapsed(...args);183+ },184+ groupEnd: () => {185+ real.groupEnd();186+ },187+ info: (...args: readonly unknown[]) => {188+ real.info(...args);189+ },190+ log: (...args: readonly unknown[]) => {191+ if (open) {192+ real.log(...args);193+ } else {194+ held.push(args);195+ }196+ },197+ table: (data, properties) => {198+ real.table(data, properties);199+ },200+ time: (label) => {201+ real.time(label);202+ },203+ timeEnd: (label) => {204+ real.timeEnd(label);205+ },206+ timeLog: (label, ...args: readonly unknown[]) => {207+ real.timeLog(label, ...args);208+ },209+ trace: (...args: readonly unknown[]) => {210+ real.trace(...args);211+ },212+ warn: (...args: readonly unknown[]) => {213+ real.warn(...args);214+ },215+ };216+217+ return {218+ console,219+ open: Effect.sync(() => {220+ open = true;221+ }),222+ release: Effect.sync(() => {223+ for (const args of held.splice(0)) {224+ real.log(...args);225+ }226+ }),227+ };228+};added:apps/cli/src/policy.ts+125 added
1+/**2+ * The CLI's invocation policy: who is reading what it prints. Under a3+ * harness the CLI never prompts and prints Markdown; for a script (CI, or4+ * stdout piped) it never prompts either; only a person at a terminal reads5+ * plain text. Read once per process.6+ */7+import { detectHarness } from "@repo/protocol/audit";8+import { ConfigProvider, Context, Effect, Layer, Option, Stdio } from "effect";9+10+/** Who is reading: a person at a terminal, an agent, or a script. */11+export type Mode = "human" | "agent" | "automation";12+13+/** Who is reading, the harness when an agent is, and why the CLI thinks so. */14+export interface Invocation {15+ readonly mode: Mode;16+ readonly harness: Option.Option<string>;17+ readonly reason: string;18+}19+20+/** What the mode is read from. */21+export interface Surroundings {22+ readonly env: Readonly<Record<string, string | undefined>>;23+ readonly isTTY: boolean;24+}25+26+/** `value`, unless it is absent or empty. */27+const isSet = (value: string | undefined) =>28+ value !== undefined && value !== "";29+30+/**31+ * An agent when the env names a harness (`detectHarness`, the one table of32+ * harness markers); else a script when `CI` is set or stdout is not a33+ * terminal; else a person.34+ */35+export const detectMode = ({ env, isTTY }: Surroundings): Invocation => {36+ const harness = Option.fromNullishOr(detectHarness(env).harness);37+38+ if (Option.isSome(harness)) {39+ return {40+ harness,41+ mode: "agent",42+ reason: `the env names the harness ${harness.value}`,43+ };44+ }45+46+ if (isSet(env.CI)) {47+ return { harness, mode: "automation", reason: "CI is set" };48+ }49+50+ return isTTY51+ ? { harness, mode: "human", reason: "stdout is a terminal" }52+ : { harness, mode: "automation", reason: "stdout is not a terminal" };53+};54+55+/** Who is reading this process's output. */56+export class Policy extends Context.Service<Policy, Invocation>()(57+ "cli/Policy"58+) {}59+60+/** The policy for given surroundings: what tests run the CLI under. */61+export const policyFor = (surroundings: Surroundings): Layer.Layer<Policy> =>62+ Layer.succeed(Policy)(detectMode(surroundings));63+64+/** The names below a node of the env's tree: a record's keys, an array's indexes. */65+const childrenOf = (node: ConfigProvider.Node): readonly string[] => {66+ if ("keys" in node) {67+ return [...node.keys];68+ }69+70+ if ("length" in node) {71+ return Array.from({ length: node.length }, (_, index) => String(index));72+ }73+74+ return [];75+};76+77+/**78+ * Every variable the env provider holds, by its full name. The provider79+ * splits names on `_` into a tree, so this walks it back together.80+ */81+const envOf = (provider: ConfigProvider.ConfigProvider) => {82+ const walk = (83+ path: readonly string[]84+ ): Effect.Effect<85+ readonly (readonly [string, string])[],86+ ConfigProvider.SourceError87+ > =>88+ Effect.flatMap(provider.load(path), (node) => {89+ if (node === undefined) {90+ return Effect.succeed([]);91+ }92+93+ const here =94+ path.length > 0 && node.value !== undefined95+ ? [[path.join("_"), node.value] as const]96+ : [];97+98+ return Effect.map(99+ Effect.forEach(childrenOf(node), (key) => walk([...path, key])),100+ (below) => [...here, ...below.flat()]101+ );102+ });103+104+ return Effect.map(walk([]), (entries) => Object.fromEntries(entries));105+};106+107+/**108+ * The policy of this process: its env, read through the config provider,109+ * and whether stdout is a terminal. An env that cannot be read reads as110+ * empty, so the mode then rests on the terminal alone.111+ */112+export const CurrentMode: Layer.Layer<Policy, never, Stdio.Stdio> =113+ Layer.effect(Policy)(114+ Effect.gen(function* () {115+ const provider = yield* ConfigProvider.ConfigProvider;116+ const env = yield* Effect.orElseSucceed(envOf(provider), () => ({}));117+118+ const isTTY = yield* Effect.flatMap(119+ Stdio.Stdio,120+ (stdio) => stdio.stdoutIsTerminal121+ );122+123+ return detectMode({ env, isTTY });124+ })125+ );added:apps/cli/src/remote.ts+193 added
1+/**2+ * The platform as the CLI calls it: the contracts over HTTP at `/rpc`, as3+ * the stored profile. The token rides as the HTTP `authorization` header,4+ * which the platform merges into every call's headers (Rpc headers would5+ * ride in the body, where the gate never looks).6+ */7+import { Brand } from "@repo/brand";8+import { Client, Contracts } from "@repo/protocol/contracts";9+import { Authenticated, Unauthenticated } from "@repo/protocol/principal";10+import {11+ Config,12+ Effect,13+ Layer,14+ Option,15+ Predicate,16+ Redacted,17+ Schema,18+} from "effect";19+import {20+ FetchHttpClient,21+ HttpClient,22+ HttpClientError,23+ HttpClientRequest,24+} from "effect/http";25+import {26+ RpcClient,27+ RpcClientError,28+ RpcMiddleware,29+ RpcSerialization,30+} from "effect/rpc";31+32+import { Credentials } from "./credentials.ts";33+34+/** `<SLUG>_URL`: a platform to call as anyone, when no profile names one. */35+const URL_VARIABLE = `${Brand.slug.toUpperCase()}_URL`;36+37+/**38+ * No profile names a platform, and the env names none either. A usage39+ * error: nothing was called.40+ */41+export class NoPlatform extends Schema.TaggedError<NoPlatform>()("NoPlatform", {42+ variable: Schema.String,43+}) {44+ override get message() {45+ return `no platform to call: run ${Brand.cli} login, or set ${this.variable} to call one as anyone`;46+ }47+}48+49+const isClientError = Schema.is(RpcClientError.RpcClientError);50+51+const isDefect = Schema.is(RpcClientError.RpcClientDefect);52+53+const isNoPlatformError = Schema.is(NoPlatform);54+55+const isHttpFailure = Schema.is(HttpClientError.HttpClientErrorSchema);56+57+/** Whether a call failed in transit (not by the contract's own errors). */58+export const isTransportFailure = isClientError;59+60+/**61+ * What failed in transit, in words. An HTTP failure's own message is empty:62+ * its cause (the transport error, or the status and URL) says what failed.63+ */64+export const transportMessage = (failure: RpcClientError.RpcClientError) =>65+ isHttpFailure(failure.reason) &&66+ Predicate.hasProperty(failure.reason.cause, "message") &&67+ Predicate.isString(failure.reason.cause.message)68+ ? failure.reason.cause.message69+ : failure.message;70+71+/** The usage error a call failed with because no platform was there to call. */72+export const noPlatformOf = (73+ failure: RpcClientError.RpcClientError74+): Option.Option<NoPlatform> =>75+ isDefect(failure.reason) && isNoPlatformError(failure.reason.cause)76+ ? Option.some(failure.reason.cause)77+ : Option.none();78+79+/** Whether the platform's HTTP gate answered a call with a 401. */80+const isUnauthorized = (failure: RpcClientError.RpcClientError) =>81+ Predicate.hasProperty(failure.reason, "cause") &&82+ failure.reason.cause instanceof HttpClientError.StatusCodeError &&83+ failure.reason.cause.response.status === 401;84+85+/**86+ * The client side of `Authenticated`: a 401 from the platform's gate (a87+ * token it doesn't know) is the same `Unauthenticated` a contract gives a88+ * call without one, so the CLI says the same thing for both.89+ */90+const SignedIn = RpcMiddleware.layerClient(Authenticated, ({ next, request }) =>91+ next(request).pipe(92+ Effect.catchIf(93+ (failure) => isClientError(failure) && isUnauthorized(failure),94+ () => Effect.fail(new Unauthenticated())95+ )96+ )97+);98+99+/** The contracts at `origin`, with `token` as the bearer when there is one. */100+const over = (origin: string, token: Option.Option<Redacted.Redacted>) =>101+ Layer.effect(Client)(RpcClient.make(Contracts)).pipe(102+ Layer.provide(SignedIn),103+ Layer.provide(104+ Layer.effect(RpcClient.Protocol)(105+ Effect.flatMap(HttpClient.HttpClient, (client) =>106+ RpcClient.makeProtocolHttp(107+ client.pipe(108+ HttpClient.mapRequest(109+ HttpClientRequest.prependUrl(110+ `${origin.replace(/\/+$/u, "")}/rpc`111+ )112+ ),113+ HttpClient.mapRequest((request) =>114+ Option.match(token, {115+ onNone: () => request,116+ onSome: (bearer) =>117+ HttpClientRequest.bearerToken(118+ request,119+ Redacted.value(bearer)120+ ),121+ })122+ ),123+ // Any status but 2xx fails as itself, so a 401 is told apart.124+ HttpClient.filterStatusOk125+ )126+ )127+ )128+ )129+ ),130+ Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])131+ );132+133+const noPlatform = new NoPlatform({ variable: URL_VARIABLE });134+135+/**136+ * No platform: every call fails, before anything is sent, with a usage error137+ * naming `login`. Commands that call nothing (help among them) still run.138+ */139+const nowhere = Layer.effect(Client)(RpcClient.make(Contracts)).pipe(140+ Layer.provide(141+ Layer.effect(RpcClient.Protocol)(142+ Effect.flatMap(143+ Effect.service(RpcSerialization.RpcSerialization),144+ (serialization) =>145+ RpcClient.Protocol.make(() =>146+ Effect.succeed({147+ codecFor: serialization.codecFor,148+ send: () =>149+ Effect.fail(150+ new RpcClientError.RpcClientError({151+ reason: new RpcClientError.RpcClientDefect({152+ cause: noPlatform,153+ message: noPlatform.message,154+ }),155+ })156+ ),157+ supportsAck: false,158+ supportsTransferables: false,159+ })160+ )161+ )162+ )163+ ),164+ Layer.provide(RpcSerialization.layerJson)165+);166+167+/**168+ * The platform the stored profile names, as that person; else the one169+ * `<SLUG>_URL` names, as anyone (public contracts answer; the rest come back170+ * `Unauthenticated`); else nowhere.171+ */172+export const RemoteClient: Layer.Layer<Client, never, Credentials> =173+ Layer.unwrap(174+ Effect.gen(function* () {175+ const profile = yield* Effect.flatMap(176+ Effect.service(Credentials),177+ (credentials) => credentials.current178+ );179+180+ if (Option.isSome(profile)) {181+ return over(profile.value.url, Option.some(profile.value.token));182+ }183+184+ const url = yield* Config.option(185+ Config.NonEmptyString(URL_VARIABLE)186+ ).pipe(Effect.orElseSucceed(() => Option.none()));187+188+ return Option.match(url, {189+ onNone: () => nowhere,190+ onSome: (origin) => over(origin, Option.none()),191+ });192+ })193+ );added:apps/cli/src/render.ts+399 added
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+ */6+import { Brand } from "@repo/brand";7+import type { View } from "@repo/protocol/cli";8+import {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";22+import type { Contract } from "@repo/protocol/contracts";23+import { LandReceipt } from "@repo/protocol/domain/answer";24+import type { AnswerReceipt } from "@repo/protocol/domain/answer";25+import { DecisionSubject } from "@repo/protocol/domain/decision";26+import { Outcome } from "@repo/protocol/domain/outcome";27+import { LedgerEntry } from "@repo/protocol/domain/visibility";28+import type { Refusal } from "@repo/protocol/refusal";29+import { receiptLine } from "@repo/protocol/render";30+import { DateTime, Option, Result, Schema } from "effect";31+import type { Rpc } from "effect/rpc";32+33+const short = (sha: string) => sha.slice(0, 7);34+35+const when = (at: DateTime.Utc) => DateTime.formatIso(at);36+37+const yesNo = (value: boolean) => (value ? "yes" : "no");38+39+/** A cell's text, safe inside a Markdown table row. */40+const cell = (text: string) =>41+ text.replaceAll("|", "\\|").replaceAll(/\s*\n\s*/gu, " ");42+43+/**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+ */47+const 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+ }55+56+ const widths = headers.map((header, column) =>57+ Math.max(header.length, ...rows.map((row) => (row[column] ?? "").length))58+ );59+60+ const padded = (row: readonly string[]) =>61+ row62+ .map((text, column) => text.padEnd(widths[column] ?? 0))63+ .join(" ")64+ .trimEnd();65+66+ 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+};78+79+/** Views one after another, as sections. */80+const 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+});84+85+/** The same words for every reader. */86+const prose = (text: string): View => ({ markdown: text });87+88+/** Where an answer stands, in a few words. */89+const 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+ });99+100+/** What a decision is about, in a few words. */101+const 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+ });119+120+/** One ledger entry, in a few words. */121+const 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+ });137+138+/** A view that renders a success it can read, and none for anything else. */139+const viewOf = <S extends Schema.Top>(140+ schema: S,141+ render: (success: S["Type"]) => View142+) => {143+ const is = Schema.is(schema);144+145+ return (success: Rpc.Success<Contract>): Option.Option<View> =>146+ is(success) ? Option.some(render(success)) : Option.none();147+};148+149+const 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+);171+172+const ask = viewOf(ShowAsk.successSchema, ({ brief }) => prose(brief));173+174+const 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+ ];180+181+ 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+204+const status = viewOf(Status.successSchema, ({ answers, claims }) =>205+ joined(206+ prose("Claims:"),207+ table(208+ ["ask", "project", "state", "lapses", "fork"],209+ claims.map((held) => [210+ held.ask,211+ held.project,212+ held.state,213+ when(held.lapsesAt),214+ held.remote,215+ ]),216+ "No claims."217+ ),218+ prose("Answers:"),219+ table(220+ ["ask", "head", "outcome", "at"],221+ answers.map((answer) => [222+ answer.ask,223+ short(answer.head),224+ outcomeText(answer.outcome),225+ when(answer.at),226+ ]),227+ "No answers."228+ )229+ )230+);231+232+const verdict = viewOf(VerdictOf.successSchema, ({ verdict: found }) => {233+ if (found === undefined) {234+ return prose("No verdict yet.");235+ }236+237+ return joined(238+ prose(239+ `${found.ask} at ${short(found.head)}: ${outcomeText(found.outcome)} (furthest stage: ${found.stage}).`240+ ),241+ table(242+ ["lane", "result", "command", "ms"],243+ found.lanes.map((lane) => [244+ lane.lane,245+ lane.result,246+ lane.command,247+ String(lane.durationMs),248+ ]),249+ "No lanes ran."250+ ),251+ ...(found.heldBack.length === 0252+ ? []253+ : [254+ table(255+ ["area", "held back", "suite"],256+ found.heldBack.map((area) => [257+ area.area,258+ `${area.passed}/${area.total}`,259+ area.suite,260+ ]),261+ ""262+ ),263+ ])264+ );265+});266+267+const today = viewOf(TodayOf.successSchema, (page) =>268+ joined(269+ prose(270+ `Today for ${page.decider}: ${page.budget.used} of ${page.budget.total} decisions used${page.overflow === 0 ? "" : `; ${page.overflow} more wait beyond the budget`}.`271+ ),272+ table(273+ ["decision", "project", "about", "default", "expires"],274+ page.decisions.map((decision) => [275+ decision.id,276+ decision.project,277+ subjectText(decision.subject),278+ decision.default,279+ when(decision.expiresAt),280+ ]),281+ "Nothing to decide."282+ ),283+ ...(page.decisions.length === 0284+ ? []285+ : [286+ prose(287+ `Take one with \`${Brand.cli} decide --project <project> --decision <decision> --choice <choice> --yes\`.`288+ ),289+ ])290+ )291+);292+293+const ledger = viewOf(LedgerOf.successSchema, (book) =>294+ joined(295+ prose(`${book.project}: ${book.postureLabel}.`),296+ table(297+ ["#", "at", "entry"],298+ book.entries.map((entry) => [299+ String(entry.seq),300+ when(entry.at),301+ entryText(entry),302+ ]),303+ "The ledger is empty."304+ )305+ )306+);307+308+const credits = viewOf(Credits.successSchema, ({ credits: counted }) =>309+ table(310+ ["project", "area", "role", "count"],311+ counted.map((credit) => [312+ credit.project,313+ credit.area,314+ credit.role,315+ String(credit.count),316+ ]),317+ "No credits yet."318+ )319+);320+321+const projects = viewOf(ListProjects.successSchema, ({ projects: listed }) =>322+ table(323+ ["project", "posture", "open asks", "landed"],324+ listed.map((listing) => [325+ listing.project,326+ listing.posture,327+ String(listing.openAsks),328+ listing.landedAt === undefined ? "never" : when(listing.landedAt),329+ ]),330+ "No projects yet."331+ )332+);333+334+const front = viewOf(FrontPage.successSchema, ({ entries }) =>335+ table(336+ ["project", "ask", "kind", "want", "takeable"],337+ entries.map((entry) => [338+ entry.project,339+ entry.ask.ask,340+ entry.ask.kind,341+ entry.ask.want,342+ yesNo(entry.takeable),343+ ]),344+ "No open asks anywhere."345+ )346+);347+348+/**349+ * Where an offered answer stands, in the line git's `remote:` output gives a350+ * push of the same answer. A refused one never reaches its view: its351+ * refusals print as refusals (`refusalsIn`).352+ */353+const receipt = (offered: AnswerReceipt) =>354+ prose(355+ Result.getOrElse(receiptLine(offered), () => `${offered.ask} was refused`)356+ );357+358+const submitted = viewOf(SubmitAnswer.successSchema, receipt);359+360+const finished = viewOf(Finish.successSchema, receipt);361+362+/** Any receipt: an answer's (`submit`, `finish`) has a landing's fields too. */363+const isReceipt = Schema.is(LandReceipt);364+365+/**366+ * The refusals a contract's success carries in place of a result: a refused367+ * receipt's (`finish` and `land` refuse at stages 0–1 that way, and `submit`368+ * gives a refused request's receipt back again). The command prints them as369+ * refusals, once, and exits 1.370+ */371+export const refusalsIn = (372+ success: Rpc.Success<Contract>373+): readonly Refusal[] =>374+ isReceipt(success) && Outcome.guards.Refused(success.outcome)375+ ? success.outcome.refusals376+ : [];377+378+/** Each contract's view, by tag. */379+export const views = {380+ claim,381+ credits,382+ finish: finished,383+ frontPage: front,384+ ledger,385+ listAsks: asks,386+ listProjects: projects,387+ showAsk: ask,388+ status,389+ submitAnswer: submitted,390+ today,391+ verdict,392+} as const satisfies Readonly<393+ Partial<394+ Record<395+ Contract["_tag"],396+ (success: Rpc.Success<Contract>) => Option.Option<View>397+ >398+ >399+>;modified:apps/cli/src/surfaces.ts+269 added-3 removed
1+/**2+ * The CLI's surfaces: every contract served on the CLI as a command, merged3+ * with the hand-written ones by the words that reach them; `schema`, which4+ * prints a command's payload as JSON Schema; and `mcp`, the contracts as5+ * tools over stdio. The only place the CLI's projections are built.6+ */7 import { Brand } from "@repo/brand";2-import { Client, surfaced } from "@repo/protocol/contracts";8+import { commandName, toCommands } from "@repo/protocol/cli";9+import type { CommandRpc, Defaults } from "@repo/protocol/cli";10+import {11+ Client,12+ Contracts,13+ surfaced,14+ Surfaces,15+} from "@repo/protocol/contracts";16 import { toToolkit } from "@repo/protocol/mcp";4-import { Effect, Layer } from "effect";17+import {18+ Context,19+ Effect,20+ JsonSchema,21+ Layer,22+ Option,23+ Predicate,24+ Schema,25+ SchemaAST,26+ SchemaRepresentation,27+} from "effect";28 import { McpProtocol, McpServer } from "effect/ai";6-import { Command } from "effect/cli";29+import { Argument, Command, Flag } from "effect/cli";30+import type { ChildProcessSpawner } from "effect/process";31 32+import { local } from "./local/index.ts";33+import { Output } from "./output.ts";34+import { refusalsIn, views } from "./render.ts";35+import { repoContext } from "./repo-context.ts";36+37+/** The folder the CLI stands in: the process's own, unless a test says otherwise. */38+export const WorkingDirectory = Context.Reference<string>(39+ "cli/WorkingDirectory",40+ { defaultValue: () => "." }41+);42+43+/**44+ * The project a command is about when `--project` is left out: the one the45+ * repo the CLI stands in belongs to, by its remote's name (a project's own46+ * repo, a claim's fork or a working fork). None outside a platform's repo.47+ */48+export const fromRepoContext: Defaults<ChildProcessSpawner.ChildProcessSpawner> =49+ {50+ fields: { project: "the project of the repo you stand in" },51+ values: Effect.gen(function* () {52+ const here = yield* Effect.option(repoContext(yield* WorkingDirectory));53+54+ return Option.match(55+ Option.flatMap(here, ({ repo }) => repo),56+ {57+ onNone: () => ({}),58+ onSome: ({ project }) => ({ project }),59+ }60+ );61+ }),62+ };63+64+/** A command, and the words after the CLI's name that reach it. */65+export interface CommandEntry {66+ readonly path: readonly [string, ...string[]];67+ readonly command: Command.Command.Any;68+}69+70+/**71+ * Contracts that a hand-written command wraps: `init` creates the project72+ * after its local work, and `env set` reads the value from stdin so it never73+ * passes through an argument list or a transcript.74+ */75+const wrapped = ["initProject", "setEnv"];76+77+/** Every contract served on the CLI, but those wrapped, as a command. */78+const projected = toCommands(Contracts, Effect.service(Client), {79+ defaults: fromRepoContext,80+ exclude: wrapped,81+ output: Effect.service(Output),82+ refusalsIn,83+ views,84+});85+86+/** What a group of commands that is no command itself is for, by its word. */87+const groups = new Map([88+ ["env", "Read a project's env shape, or set a write-only value."],89+]);90+91+/**92+ * Entries as a tree: one command per first word, the rest of each path93+ * beneath it. A word that is a command and starts longer paths (`ask`, and94+ * `ask open`) is a command with subcommands; a word that only starts them95+ * (`env`) is a group.96+ */97+export const merge = (98+ all: readonly CommandEntry[]99+): readonly Command.Command.Any[] => {100+ const words = [...new Set(all.map(({ path: [word] }) => word))];101+102+ return words.map((word) => {103+ const here = all.filter(({ path: [first] }) => first === word);104+ const own = here.find(({ path }) => path.length === 1)?.command;105+106+ const below = here.flatMap(({ command, path: [, next, ...rest] }) =>107+ next === undefined108+ ? []109+ : [{ command, path: [next, ...rest] } satisfies CommandEntry]110+ );111+112+ if (below.length === 0 && own !== undefined) {113+ return own;114+ }115+116+ const parent =117+ own ??118+ Command.make(word).pipe(119+ Command.withDescription(groups.get(word) ?? `Commands under ${word}.`)120+ );121+122+ return Command.withSubcommands(parent, merge(below));123+ });124+};125+126+/** A command's words, as `schema` and its errors print them. */127+const spoken = (words: readonly string[]) => words.join(" ");128+129+/** `schema` was asked for a command that takes no payload, or none at all. */130+export class UnknownCommand extends Schema.TaggedError<UnknownCommand>()(131+ "UnknownCommand",132+ { words: Schema.String }133+) {134+ override get message() {135+ return `${Brand.cli} has no command "${this.words}" that takes a payload; run ${Brand.cli} --help to list them`;136+ }137+}138+139+/**140+ * Every contract served on the CLI, by its command's words, wrapped ones141+ * included: `schema env set` describes the payload `env set` sends.142+ */143+const byWords = new Map(144+ [...Contracts.requests.values()].flatMap((rpc) =>145+ Context.get(rpc.annotations, Surfaces).includes("cli")146+ ? [[commandName(rpc), rpc] as const]147+ : []148+ )149+);150+151+/** Whether a field's value is write-only: a `Redacted` on the decoded side. */152+const isWriteOnly = (ast: SchemaAST.AST) =>153+ SchemaAST.resolveAt<{ readonly id?: unknown }>("representation")(154+ SchemaAST.toType(ast)155+ )?.id === "effect/schema/Redacted";156+157+const WRITE_ONLY =158+ "Write-only: the platform keeps it and never returns or prints it, and no MCP tool takes it.";159+160+const decodeJson = Schema.decodeUnknownEffect(Schema.Json);161+162+/**163+ * A contract's payload as one JSON Schema document, made the way `bun run164+ * gen` makes `protocol.schema.json` (each root as JSON encodes it), with165+ * every write-only field marked `writeOnly` and described as such.166+ */167+export const payloadJsonSchema = (rpc: CommandRpc) => {168+ const payload = rpc.payloadSchema;169+170+ const { definitions, schemas } =171+ SchemaRepresentation.toJsonSchemaMultiDocument(172+ SchemaRepresentation.toRepresentations([Schema.toCodecJson(payload).ast])173+ );174+175+ const [root] = schemas;176+177+ const writeOnly = SchemaAST.isObjects(payload.ast)178+ ? payload.ast.propertySignatures.flatMap(({ name, type }) =>179+ Predicate.isString(name) && isWriteOnly(type) ? [name] : []180+ )181+ : [];182+183+ const properties = Predicate.isObject(root.properties)184+ ? Object.fromEntries(185+ Object.entries(root.properties).map(([name, field]) => [186+ name,187+ writeOnly.includes(name) && Predicate.isObject(field)188+ ? { ...field, description: WRITE_ONLY, writeOnly: true }189+ : field,190+ ])191+ )192+ : undefined;193+194+ const document = Object.fromEntries([195+ ["$schema", JsonSchema.META_SCHEMA_URI_DRAFT_2020_12],196+ ...Object.entries(root),197+ ...(properties === undefined ? [] : [["properties", properties] as const]),198+ ...(Object.keys(definitions).length === 0199+ ? []200+ : [["$defs", definitions] as const]),201+ ]);202+203+ return decodeJson(document).pipe(Effect.orDie);204+};205+206+/** `schema <command…>`: the payload a command sends, as JSON Schema. */207+export const schema = Command.make(208+ "schema",209+ {210+ json: Flag.Boolean("json").pipe(211+ Flag.withDefault(false),212+ Flag.withDescription(213+ "Print one versioned JSON envelope on stdout, and nothing else there"214+ )215+ ),216+ words: Argument.String("command").pipe(217+ Argument.variadic({ min: 1 }),218+ Argument.withDescription("The command's words: claim, ask open, env set")219+ ),220+ },221+ ({ json, words }) =>222+ Effect.gen(function* () {223+ const rpc = byWords.get(spoken(words));224+225+ if (rpc === undefined) {226+ return yield* new UnknownCommand({ words: spoken(words) });227+ }228+229+ const document = yield* payloadJsonSchema(rpc);230+ const text = JSON.stringify(document, null, 2);231+ const output = yield* Output;232+233+ return yield* output.success({234+ command: "schema",235+ data: document,236+ json,237+ view: { markdown: text },238+ });239+ })240+).pipe(241+ Command.withDescription(242+ "Print the JSON Schema of the payload a command sends."243+ )244+);245+246+/** Every command the CLI has, projected or hand-written, by its path. */247+export const entries: readonly CommandEntry[] = [248+ ...projected,249+ ...local,250+ { command: schema, path: ["schema"] },251+];252+253+/** Any command in the tree: what it may fail with, and what it needs. */254+type Every =255+ | (typeof projected)[number]["command"]256+ | (typeof local)[number]["command"]257+ | typeof schema;258+259+/**260+ * A command at the top of the tree. Merging erases each command's own type,261+ * so the tree states what all of them together may fail with and need.262+ */263+export type TreeCommand = Command.Command<264+ string,265+ never,266+ unknown,267+ Command.Error<Every>,268+ Command.Services<Every>269+>;270+271+/** The CLI's commands at the top, merged by path. */272+export const commands: readonly TreeCommand[] = merge(entries);273+274 const projection = toToolkit(surfaced("mcp"), Effect.service(Client));275 276 /**277 * The MCP-surfaced contracts as tools over stdio, in every protocol a harness may24 unmodified linesadded:apps/cli/test/policy.test.ts+160 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Brand } from "@repo/brand";3+import { Contracts } from "@repo/protocol/contracts";4+import { Envelope } from "@repo/protocol/envelope";5+import { AskId, KindName } from "@repo/protocol/ids";6+import { AskFull } from "@repo/protocol/refusal";7+import { explain } from "@repo/protocol/render";8+import { unanswered } from "@repo/protocol/testing";9+import { Effect, Layer, Option, Schema } from "effect";10+11+import { detectMode } from "../src/policy.ts";12+import { runProgram } from "./remote-server.ts";13+14+const fixWeek = AskId.make("fix-week");15+16+const listing = {17+ ask: fixWeek,18+ blockedBy: [],19+ claimed: false,20+ kind: KindName.make("fix"),21+ territory: "packages/week",22+ want: "Weeks start on the locale's first day",23+};24+25+/** `listAsks` lists one open ask; `claim` finds it taken. */26+const platform = Layer.mergeAll(27+ unanswered,28+ Contracts.toLayerHandler("listAsks", () =>29+ Effect.succeed({ asks: [listing] })30+ ),31+ Contracts.toLayerHandler("claim", ({ ask }) =>32+ Effect.fail(new AskFull({ ask }))33+ )34+);35+36+const agent = { CLAUDECODE: "1" };37+38+const decodeEnvelope = Schema.decodeEffect(39+ Schema.fromJsonString(Envelope(Schema.Unknown))40+);41+42+describe("who the CLI is talking to", () => {43+ it("is an agent when a harness's marker is set, even at a terminal", () => {44+ const detected = detectMode({ env: agent, isTTY: true });45+46+ expect([detected.mode, detected.harness]).toStrictEqual([47+ "agent",48+ Option.some("claude-code"),49+ ]);50+ });51+52+ it.each([53+ { env: {}, isTTY: false, mode: "automation" },54+ { env: { CI: "true" }, isTTY: true, mode: "automation" },55+ { env: {}, isTTY: true, mode: "human" },56+ { env: { AI_AGENT: "pi" }, isTTY: false, mode: "agent" },57+ ] as const)(58+ "is $mode with env $env and a terminal: $isTTY",59+ ({ env, isTTY, mode }) => {60+ const detected = detectMode({ env, isTTY });61+62+ expect(detected.mode).toBe(mode);63+ expect(detected.reason).not.toBe("");64+ }65+ );66+});67+68+describe("under an agent", () => {69+ it.effect("prints asks as a Markdown table and never prompts", () =>70+ Effect.gen(function* () {71+ const run = yield* runProgram(["asks", "--project", "datekit"], {72+ env: agent,73+ handlers: platform,74+ });75+76+ expect(run.out).toContain("| ask | kind | territory | want | claimed |");77+ expect(run.out.join("\n")).toContain("fix-week");78+ expect(run.prompts).toBe(0);79+ expect(run.code).toBe(0);80+ })81+ );82+83+ it.effect(84+ "prints exactly one versioned envelope under --json, and nothing on stderr",85+ () =>86+ Effect.gen(function* () {87+ const run = yield* runProgram(88+ ["asks", "--project", "datekit", "--json"],89+ { env: agent, handlers: platform }90+ );91+92+ expect(run.out).toHaveLength(1);93+ expect(run.err).toStrictEqual([]);94+ expect(yield* decodeEnvelope(run.out[0] ?? "")).toStrictEqual({95+ command: "asks",96+ data: { asks: [listing] },97+ ok: true,98+ v: 1,99+ });100+ })101+ );102+103+ it.effect(104+ "prints a refusal as one refused envelope under --json, and exits 1",105+ () =>106+ Effect.gen(function* () {107+ const run = yield* runProgram(108+ ["claim", "fix-week", "--project", "datekit", "--json"],109+ { env: agent, handlers: platform }110+ );111+112+ expect(run.out).toHaveLength(1);113+ expect(run.err).toStrictEqual([]);114+ expect(run.code).toBe(1);115+ expect(yield* decodeEnvelope(run.out[0] ?? "")).toStrictEqual({116+ command: "claim",117+ ok: false,118+ refusals: [new AskFull({ ask: fixWeek })],119+ v: 1,120+ });121+ })122+ );123+124+ it.effect(125+ "prints a refusal's explanation once on stderr without --json, and nothing on stdout",126+ () =>127+ Effect.gen(function* () {128+ const run = yield* runProgram(129+ ["claim", "fix-week", "--project", "datekit"],130+ { env: agent, handlers: platform }131+ );132+133+ const [reason = ""] = explain([new AskFull({ ask: fixWeek })]);134+ const printed = run.err.join("\n");135+136+ expect(run.out).toStrictEqual([]);137+ expect(run.code).toBe(1);138+ expect(printed.split(reason)).toHaveLength(2);139+ expect(run.err).toStrictEqual([140+ `- ${reason}`,141+ ` - Next: \`${Brand.cli} asks\``,142+ " - Retryable: yes",143+ ]);144+ })145+ );146+});147+148+describe("for a person at a terminal", () => {149+ it.effect("prints asks as text, not Markdown", () =>150+ Effect.gen(function* () {151+ const run = yield* runProgram(["asks", "--project", "datekit"], {152+ handlers: platform,153+ });154+155+ expect(run.out.join("\n")).toContain("fix-week");156+ expect(run.out.join("\n")).not.toContain("| ask |");157+ expect(run.prompts).toBe(0);158+ })159+ );160+});added:apps/cli/test/remote-server.ts+207 added
1+/**2+ * The platform as the CLI's tests meet it: in process, through a test3+ * client, for `program` runs; or over HTTP, as an `RpcServer` for the4+ * contracts on an ephemeral port, for the remote client.5+ */6+import { NodeHttpServer, NodeServices } from "@effect/platform-node";7+import { authenticated, bearerToken } from "@repo/protocol/authenticate";8+import { Client, Contracts } from "@repo/protocol/contracts";9+import { Handle } from "@repo/protocol/ids";10+import { Person } from "@repo/protocol/principal";11+import { asTester } from "@repo/protocol/testing";12+import type { Scope } from "effect";13+import {14+ Context,15+ Effect,16+ Exit,17+ Layer,18+ Option,19+ Ref,20+ Runtime,21+ Terminal,22+} from "effect";23+import { CliOutput } from "effect/cli";24+import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";25+import type { Rpc, RpcGroup } from "effect/rpc";26+import { RpcSerialization, RpcServer, RpcTest } from "effect/rpc";27+import { TestConsole } from "effect/testing";28+29+import { program } from "../src/main.ts";30+import { OutputLive } from "../src/output.ts";31+import { policyFor } from "../src/policy.ts";32+import { WorkingDirectory } from "../src/surfaces.ts";33+34+/** Handlers for every contract, as a test sets them up. */35+export type Handlers = Layer.Layer<36+ Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>37+>;38+39+/** A Terminal that counts every prompt it is asked for, and answers none. */40+const promptless = (prompts: Ref.Ref<number>) => {41+ const prompted = Ref.update(prompts, (count) => count + 1).pipe(42+ Effect.andThen(Effect.die("the CLI prompted"))43+ );44+45+ return Layer.succeed(Terminal.Terminal)(46+ Terminal.make({47+ columns: Effect.succeed(80),48+ display: () => prompted,49+ readInput: prompted,50+ readLine: prompted,51+ rows: Effect.succeed(24),52+ })53+ );54+};55+56+/** What was printed to a stream, one entry per line however it was written. */57+const lines = (output: Effect.Effect<readonly unknown[]>) =>58+ Effect.map(output, (all) =>59+ all.flatMap((chunk) => String(chunk).split("\n"))60+ );61+62+export interface Invocation {63+ /** The calls' handlers: the platform in process, as `tester`. */64+ readonly handlers: Handlers;65+ /** How the CLI reaches the platform instead, such as over HTTP. */66+ readonly client?: Layer.Layer<Client>;67+ /** The env the CLI reads its mode from. */68+ readonly env?: Readonly<Record<string, string>>;69+ /** Whether stdout is a terminal; it is, unless said otherwise. */70+ readonly isTTY?: boolean;71+ /** Where the CLI stands; the test process's own folder unless given. */72+ readonly cwd?: string;73+}74+75+/**76+ * Runs `program` on `args` as the process would: the mode from `env` and the77+ * TTY, the platform from `handlers`, and a terminal that fails any prompt.78+ * Returns what it printed, its exit code as the runtime would set it, and79+ * how many prompts it asked for.80+ */81+export const runProgram = (82+ args: readonly string[],83+ { client, cwd, env = {}, handlers, isTTY = true }: Invocation84+) =>85+ Effect.gen(function* () {86+ const prompts = yield* Ref.make(0);87+88+ const policy = policyFor({ env, isTTY });89+90+ const services = Layer.mergeAll(91+ NodeServices.layer,92+ TestConsole.layer,93+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),94+ client ??95+ Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(96+ Layer.provide([handlers, asTester])97+ ),98+ policy,99+ OutputLive.pipe(Layer.provide(policy)),100+ promptless(prompts)101+ );102+103+ const run = Effect.gen(function* () {104+ const exit = yield* Effect.exit(program(args));105+106+ return {107+ err: yield* lines(TestConsole.errorLines),108+ exit,109+ out: yield* lines(TestConsole.logLines),110+ };111+ }).pipe(112+ cwd === undefined113+ ? (effect) => effect114+ : Effect.provideService(WorkingDirectory, cwd),115+ Effect.provide(services)116+ );117+118+ const { err, exit, out } = yield* run;119+120+ let code = -1;121+122+ Runtime.defaultTeardown(exit, (set) => {123+ code = set;124+ });125+126+ return {127+ code,128+ err,129+ failure: Exit.findErrorOption(exit),130+ out,131+ prompts: yield* Ref.get(prompts),132+ };133+ });134+135+/** A person the HTTP platform knows by their token. */136+export const knownToken = "token-of-tester";137+138+/** The person a token names: `tester` for `knownToken`, nobody for any other. */139+const verify = (token: string) =>140+ Effect.succeed(141+ token === knownToken142+ ? Option.some(Person.make({ handle: Handle.make("tester") }))143+ : Option.none()144+ );145+146+/** `app` served on an ephemeral port for the test's scope: returns its origin. */147+const serving = <E>(148+ app: Effect.Effect<149+ HttpServerResponse.HttpServerResponse,150+ E,151+ HttpServerRequest.HttpServerRequest | Scope.Scope152+ >153+) =>154+ Effect.gen(function* () {155+ const server = yield* Layer.build(156+ HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))157+ ).pipe(Effect.orDie);158+159+ const { address } = Context.get(server, HttpServer.HttpServer);160+161+ return "port" in address162+ ? `http://127.0.0.1:${address.port}`163+ : yield* Effect.die("the test platform listens on a socket, not a port");164+ });165+166+/**167+ * The contracts over HTTP at `/rpc`, on an ephemeral port: `handlers` answer168+ * as the person `knownToken` names, or as anyone for a public contract when169+ * a request carries no credential. Any other bearer token is a 401 before170+ * the contracts see it, as at the platform's gate. Returns the origin, and171+ * every `authorization` header the server saw, in order.172+ */173+export const httpPlatform = (handlers: Handlers) =>174+ Effect.gen(function* () {175+ const seen = yield* Ref.make<readonly (string | undefined)[]>([]);176+177+ const rpc = yield* RpcServer.toHttpEffect(Contracts).pipe(178+ Effect.provide([179+ handlers,180+ authenticated(verify),181+ RpcSerialization.layerJson,182+ ])183+ );184+185+ const gate = Effect.gen(function* () {186+ const request = yield* HttpServerRequest.HttpServerRequest;187+ const { authorization } = request.headers;188+189+ yield* Ref.update(seen, (all) => [...all, authorization]);190+191+ const unknown = Option.exists(192+ bearerToken(authorization),193+ (token) => token !== knownToken194+ );195+196+ return unknown ? HttpServerResponse.empty({ status: 401 }) : yield* rpc;197+ });198+199+ return { origin: yield* serving(gate), seen: Ref.get(seen) };200+ });201+202+/**203+ * A platform that answers every request with `status` and an empty body, as204+ * a platform that is down does: returns its origin.205+ */206+export const failingPlatform = (status: number) =>207+ serving(Effect.succeed(HttpServerResponse.empty({ status })));added:apps/cli/test/remote.test.ts+164 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Brand } from "@repo/brand";3+import { Contracts } from "@repo/protocol/contracts";4+import { AskId, KindName } from "@repo/protocol/ids";5+import { unanswered } from "@repo/protocol/testing";6+import { ConfigProvider, Effect, Layer, Option, Redacted } from "effect";7+8+import { Credentials } from "../src/credentials.ts";9+import type { Profile } from "../src/credentials.ts";10+import { RemoteClient } from "../src/remote.ts";11+import {12+ failingPlatform,13+ httpPlatform,14+ knownToken,15+ runProgram,16+} from "./remote-server.ts";17+import type { Handlers } from "./remote-server.ts";18+19+/** `listAsks` (public) lists one ask; `status` (signed in) shows nothing yet. */20+const handlers: Handlers = Layer.mergeAll(21+ unanswered,22+ Contracts.toLayerHandler("listAsks", () =>23+ Effect.succeed({24+ asks: [25+ {26+ ask: AskId.make("fix-week"),27+ blockedBy: [],28+ claimed: false,29+ kind: KindName.make("fix"),30+ territory: "packages/week",31+ want: "Weeks start on the locale's first day",32+ },33+ ],34+ })35+ ),36+ Contracts.toLayerHandler("status", () =>37+ Effect.succeed({ answers: [], claims: [] })38+ )39+);40+41+/** Credentials holding `profile`, or none. */42+const holding = (profile: Option.Option<Profile>) =>43+ Layer.succeed(Credentials)({44+ current: Effect.succeed(profile),45+ forHost: () => Effect.succeed(profile),46+ put: () => Effect.void,47+ remove: () => Effect.succeed(false),48+ });49+50+const profileOn = (url: string, token: string): Profile => ({51+ token: Redacted.make(token),52+ url,53+});54+55+/** The remote client over `credentials`, with `env` as its whole env. */56+const remote = (57+ credentials: Layer.Layer<Credentials>,58+ env: Readonly<Record<string, string>> = {}59+) =>60+ RemoteClient.pipe(61+ Layer.provide([62+ credentials,63+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: { ...env } })),64+ ])65+ );66+67+const urlVariable = `${Brand.slug.toUpperCase()}_URL`;68+69+const signIn = `next: ${Brand.cli} login`;70+71+describe("the remote client", () => {72+ it.live("sends the stored profile's token as the HTTP bearer", () =>73+ Effect.gen(function* () {74+ const platform = yield* httpPlatform(handlers);75+76+ const run = yield* runProgram(["status", "--json"], {77+ client: remote(78+ holding(Option.some(profileOn(platform.origin, knownToken)))79+ ),80+ handlers,81+ });82+83+ expect(run.code).toBe(0);84+ expect(yield* platform.seen).toStrictEqual([`Bearer ${knownToken}`]);85+ }).pipe(Effect.scoped)86+ );87+88+ it.live(89+ "without a profile sends no credential: a public contract answers, a signed-in one says to log in",90+ () =>91+ Effect.gen(function* () {92+ const platform = yield* httpPlatform(handlers);93+94+ const client = remote(holding(Option.none()), {95+ [urlVariable]: platform.origin,96+ });97+98+ const asks = yield* runProgram(["asks", "--project", "datekit"], {99+ client,100+ handlers,101+ });102+103+ const status = yield* runProgram(["status"], { client, handlers });104+105+ expect([asks.code, status.code]).toStrictEqual([0, 1]);106+ expect(asks.out.join("\n")).toContain("fix-week");107+ expect(status.err.join("\n")).toContain(signIn);108+ expect(status.out).toStrictEqual([]);109+ expect(yield* platform.seen).toStrictEqual([undefined, undefined]);110+ }).pipe(Effect.scoped)111+ );112+113+ it.live("turns a 401 into the same words, not a stack trace", () =>114+ Effect.gen(function* () {115+ const platform = yield* httpPlatform(handlers);116+117+ const run = yield* runProgram(["status"], {118+ client: remote(119+ holding(Option.some(profileOn(platform.origin, "a-stale-token")))120+ ),121+ handlers,122+ });123+124+ expect(run.code).toBe(1);125+ expect(run.err).toStrictEqual([126+ "Unauthenticated: the platform does not know who you are",127+ ` ${signIn}`,128+ " retryable: no",129+ ]);130+ }).pipe(Effect.scoped)131+ );132+133+ it.live(134+ "says in one line what failed when the platform answers with an error",135+ () =>136+ Effect.gen(function* () {137+ const origin = yield* failingPlatform(503);138+139+ const run = yield* runProgram(["asks", "--project", "datekit"], {140+ client: remote(holding(Option.none()), { [urlVariable]: origin }),141+ handlers,142+ });143+144+ expect(run.code).toBe(1);145+ expect(run.out).toStrictEqual([]);146+ expect(run.err).toHaveLength(1);147+ expect(run.err[0]).toMatch(/^could not reach the platform: .*\b503\b/u);148+ expect(run.err[0]).toContain(`${origin}/rpc`);149+ }).pipe(Effect.scoped)150+ );151+152+ it.live("with no profile and no url, is a usage error naming login", () =>153+ Effect.gen(function* () {154+ const run = yield* runProgram(["asks", "--project", "datekit"], {155+ client: remote(holding(Option.none())),156+ handlers,157+ });158+159+ expect(run.code).toBe(2);160+ expect(run.err).toHaveLength(1);161+ expect(run.err[0]).toContain(`${Brand.cli} login`);162+ })163+ );164+});added:apps/cli/test/schema.test.ts+96 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Envelope } from "@repo/protocol/envelope";3+import { unanswered } from "@repo/protocol/testing";4+import { Effect, Schema } from "effect";5+6+import { runProgram } from "./remote-server.ts";7+8+/** What `schema` prints: a JSON Schema object, as far as these tests read it. */9+const PayloadSchema = Schema.fromJsonString(10+ Schema.Struct({11+ $schema: Schema.String,12+ properties: Schema.Record(13+ Schema.String,14+ Schema.Struct({15+ description: Schema.optionalKey(Schema.String),16+ type: Schema.optionalKey(Schema.String),17+ writeOnly: Schema.optionalKey(Schema.Boolean),18+ })19+ ),20+ required: Schema.Array(Schema.String),21+ type: Schema.Literal("object"),22+ })23+);24+25+const decodePayloadSchema = Schema.decodeEffect(PayloadSchema);26+27+/** `schema` asks the platform nothing. */28+const schemaOf = (words: readonly string[], env = {}) =>29+ runProgram(["schema", ...words], { env, handlers: unanswered });30+31+describe("schema <command>", () => {32+ it.effect("prints claim's payload: project and ask, both required", () =>33+ Effect.gen(function* () {34+ const run = yield* schemaOf(["claim"]);35+ const printed = yield* decodePayloadSchema(run.out.join("\n"));36+37+ expect(run.code).toBe(0);38+ expect(Object.keys(printed.properties)).toStrictEqual(39+ expect.arrayContaining(["project", "ask"])40+ );41+ expect(printed.required).toStrictEqual(42+ expect.arrayContaining(["project", "ask"])43+ );44+ })45+ );46+47+ it.effect("prints it as one document even for an agent", () =>48+ Effect.gen(function* () {49+ const run = yield* schemaOf(["ask", "open"], { CLAUDECODE: "1" });50+ const printed = yield* decodePayloadSchema(run.out.join("\n"));51+52+ expect(printed.required).toStrictEqual(53+ expect.arrayContaining(["project", "ask", "files"])54+ );55+ })56+ );57+58+ it.effect("describes env set's value as write-only", () =>59+ Effect.gen(function* () {60+ const run = yield* schemaOf(["env", "set"]);61+ const printed = yield* decodePayloadSchema(run.out.join("\n"));62+63+ const { key, value } = printed.properties;64+65+ expect([value?.type, value?.writeOnly]).toStrictEqual(["string", true]);66+ expect(value?.description).toContain("Write-only");67+ expect(key?.writeOnly).toBeUndefined();68+ })69+ );70+71+ it.effect("prints one envelope under --json", () =>72+ Effect.gen(function* () {73+ const run = yield* schemaOf(["claim", "--json"]);74+75+ const envelope = yield* Schema.decodeEffect(76+ Schema.fromJsonString(Envelope(Schema.Unknown))77+ )(run.out.join("\n"));78+79+ expect(envelope).toStrictEqual(80+ expect.objectContaining({ command: "schema", ok: true, v: 1 })81+ );82+ })83+ );84+85+ it.effect.each([["no-such-command"], ["check"], ["ask", "close"]])(86+ "exits 2 for a command with no payload: %j",87+ (words) =>88+ Effect.gen(function* () {89+ const run = yield* schemaOf(words);90+91+ expect(run.code).toBe(2);92+ expect(run.out).toStrictEqual([]);93+ expect(run.err).toHaveLength(1);94+ })95+ );96+});modified:apps/cli/test/surfaces.test.ts+358 added-3 removed
1+import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";2-import { Contracts, surfaced } from "@repo/protocol/contracts";3+import { Contracts, Surfaces, surfaced } from "@repo/protocol/contracts";4+import { Outcome } from "@repo/protocol/domain/outcome";5+import { Envelope } from "@repo/protocol/envelope";6 import {7 AskId,8 CommitSha,9+ DecisionId,10 ProjectName,11 RepoPath,12 RequestId,13 } from "@repo/protocol/ids";10-import { StaleBase } from "@repo/protocol/refusal";14+import { DecisionClosed, StaleBase } from "@repo/protocol/refusal";15+import { explain, receiptLine } from "@repo/protocol/render";16 import { unanswered } from "@repo/protocol/testing";12-import { Effect, Layer, Schema } from "effect";17+import { gitOk } from "@repo/testkit/git";18+import {19+ Context,20+ Effect,21+ FileSystem,22+ Layer,23+ Ref,24+ Result,25+ Schema,26+} from "effect";27+import type { Command } from "effect/cli";28 29+import { local } from "../src/local/index.ts";30+import { commands, entries } from "../src/surfaces.ts";31+import { runProgram } from "./remote-server.ts";32 import { session } from "./stdio.ts";33 34 const ask = AskId.make("fix-parser");35 137 unmodified lines173 );174 })175 );176 });177+178+/** The names of a command's subcommands, in order. */179+const subcommandsOf = (command: Command.Command.Any | undefined) =>180+ (command?.subcommands ?? []).flatMap(({ commands: group }) =>181+ group.map(({ name }) => name)182+ );183+184+const top = (name: string) => commands.find((command) => command.name === name);185+186+describe("the CLI's command tree", () => {187+ it("has one command per contract served on the CLI, every local one, and schema", () => {188+ const onCli = [...Contracts.requests.values()].filter((rpc) =>189+ Context.get(rpc.annotations, Surfaces).includes("cli")190+ );191+192+ const paths = entries.map(({ path: words }) => words.join(" "));193+194+ // `init` and `env set` are the local commands that wrap their contracts.195+ expect(paths).toHaveLength(onCli.length - 2 + local.length + 1);196+ expect(new Set(paths).size).toBe(paths.length);197+ expect(paths).toStrictEqual(198+ expect.arrayContaining([199+ "asks",200+ "ask",201+ "ask open",202+ "ask flag",203+ "env shape",204+ "env set",205+ "init",206+ "schema",207+ ])208+ );209+ });210+211+ it("puts ask open and ask flag under ask, and env shape beside env set", () => {212+ expect(subcommandsOf(top("ask"))).toStrictEqual(["open", "flag"]);213+ expect(subcommandsOf(top("env"))).toStrictEqual(["shape", "set"]);214+ });215+216+ it("leaves init and env set to their local commands", () => {217+ const [localInit, localEnvSet] = [218+ local.find(({ path }) => path.join(" ") === "init")?.command,219+ local.find(({ path }) => path.join(" ") === "env set")?.command,220+ ];221+222+ const envSet = top("env")223+ ?.subcommands.flatMap(({ commands: group }) => group)224+ .find(({ name }) => name === "set");225+226+ expect(top("init")).toBe(localInit);227+ expect(envSet).toBe(localEnvSet);228+ });229+});230+231+const decision = DecisionId.make("dec-000001");232+233+const decideArgs = [234+ "decide",235+ "--project",236+ "datekit",237+ "--decision",238+ decision,239+ "--choice",240+ "accept",241+];242+243+/** A platform that counts the decisions it is asked to take, and takes none. */244+const deciding = (calls: Ref.Ref<number>) =>245+ Layer.mergeAll(246+ unanswered,247+ Contracts.toLayerHandler("decide", () =>248+ Ref.update(calls, (count) => count + 1).pipe(249+ Effect.andThen(Effect.fail(new DecisionClosed({ decision })))250+ )251+ )252+ );253+254+const decodeEnvelope = Schema.decodeEffect(255+ Schema.fromJsonString(Envelope(Schema.Unknown))256+);257+258+describe("a command that needs approval", () => {259+ it.effect(260+ "exits 2 without --yes, in one line naming --yes, and calls nothing",261+ () =>262+ Effect.gen(function* () {263+ const calls = yield* Ref.make(0);264+265+ const run = yield* runProgram(decideArgs, {266+ handlers: deciding(calls),267+ });268+269+ expect(run.code).toBe(2);270+ expect(run.err).toHaveLength(1);271+ expect(run.err[0]).toContain("--yes");272+ expect(run.out).toStrictEqual([]);273+ expect(yield* Ref.get(calls)).toBe(0);274+ })275+ );276+277+ it.effect(278+ "prints the payload it would send under --dry-run, and calls nothing",279+ () =>280+ Effect.gen(function* () {281+ const calls = yield* Ref.make(0);282+283+ const run = yield* runProgram([...decideArgs, "--dry-run", "--json"], {284+ handlers: deciding(calls),285+ });286+287+ expect(run.code).toBe(0);288+ expect(run.out).toHaveLength(1);289+ expect(yield* decodeEnvelope(run.out[0] ?? "")).toStrictEqual({290+ command: "decide",291+ data: {292+ dryRun: true,293+ payload: { choice: "accept", decision, project: "datekit" },294+ },295+ ok: true,296+ v: 1,297+ });298+ expect(yield* Ref.get(calls)).toBe(0);299+ })300+ );301+302+ it.effect("prints the payload as text for a person under --dry-run", () =>303+ Effect.gen(function* () {304+ const calls = yield* Ref.make(0);305+306+ const run = yield* runProgram([...decideArgs, "--dry-run"], {307+ handlers: deciding(calls),308+ });309+310+ expect(run.out.join("\n")).toContain(`"decision": "${decision}"`);311+ expect(yield* Ref.get(calls)).toBe(0);312+ })313+ );314+315+ it.effect("calls the platform with --yes", () =>316+ Effect.gen(function* () {317+ const calls = yield* Ref.make(0);318+319+ const run = yield* runProgram([...decideArgs, "--yes"], {320+ handlers: deciding(calls),321+ });322+323+ expect(run.code).toBe(1);324+ expect(yield* Ref.get(calls)).toBe(1);325+ })326+ );327+});328+329+describe("a read", () => {330+ it.effect("has no --dry-run: asking for one is a usage error", () =>331+ Effect.gen(function* () {332+ const run = yield* runProgram(333+ ["asks", "--project", "datekit", "--dry-run"],334+ { handlers: unanswered }335+ );336+337+ expect(run.code).toBe(2);338+ expect(run.err.join("\n")).toContain("--dry-run");339+ })340+ );341+});342+343+/** A platform that lists no asks, recording the project each listing names. */344+const listing = (asked: Ref.Ref<readonly string[]>) =>345+ Layer.mergeAll(346+ unanswered,347+ Contracts.toLayerHandler("listAsks", ({ project: named }) =>348+ Ref.update(asked, (all) => [...all, named]).pipe(Effect.as({ asks: [] }))349+ )350+ );351+352+/** A fresh git repo whose `origin` is `url`, at its real path. */353+const repoWithOrigin = (url: string) =>354+ Effect.gen(function* () {355+ const fs = yield* FileSystem.FileSystem;356+ const dir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());357+358+ yield* gitOk(dir, "init", "--quiet");359+ yield* gitOk(dir, "remote", "add", "origin", url);360+361+ return dir;362+ });363+364+describe("the project a command is about", () => {365+ it.live("comes from the repo's remote when --project is left out", () =>366+ Effect.gen(function* () {367+ const asked = yield* Ref.make<readonly string[]>([]);368+369+ const cwd = yield* repoWithOrigin(370+ "https://platform-dev.example.workers.dev/datekit--fix-week--tester.git"371+ );372+373+ const run = yield* runProgram(["asks", "--json"], {374+ cwd,375+ handlers: listing(asked),376+ });377+378+ expect(run.code).toBe(0);379+ expect(yield* Ref.get(asked)).toStrictEqual(["datekit"]);380+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))381+ );382+383+ it.live("is a usage error outside a platform's repo, naming --project", () =>384+ Effect.gen(function* () {385+ const asked = yield* Ref.make<readonly string[]>([]);386+ const fs = yield* FileSystem.FileSystem;387+ const cwd = yield* fs.makeTempDirectoryScoped();388+389+ const run = yield* runProgram(["asks"], {390+ cwd,391+ handlers: listing(asked),392+ });393+394+ expect(run.code).toBe(2);395+ expect(run.err.join("\n")).toContain("--project");396+ expect(yield* Ref.get(asked)).toStrictEqual([]);397+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))398+ );399+});400+401+describe("a misuse", () => {402+ it.effect(403+ "prints one line on stderr and nothing on stdout, even with --json",404+ () =>405+ Effect.gen(function* () {406+ const run = yield* runProgram(407+ ["asks", "--project", "datekit", "--bogus", "--json"],408+ { env: { CLAUDECODE: "1" }, handlers: unanswered }409+ );410+411+ expect(run.code).toBe(2);412+ expect(run.out).toStrictEqual([]);413+ expect(run.err).toHaveLength(1);414+ expect(run.err[0]).toContain("--bogus");415+ })416+ );417+418+ it.effect("leaves help asked for on stdout", () =>419+ Effect.gen(function* () {420+ const run = yield* runProgram(["--help"], { handlers: unanswered });421+422+ expect(run.code).toBe(0);423+ expect(run.out.join("\n")).toContain("Start here:");424+ expect(run.err).toStrictEqual([]);425+ })426+ );427+});428+429+const submitArgs = [430+ "submit",431+ "--project",432+ project,433+ "--ask",434+ ask,435+ "--base",436+ base,437+ "--head",438+ head,439+ "--requestId",440+ requestId,441+];442+443+/** An answer's receipt, standing at `outcome`. */444+const receiptAt = (outcome: Outcome) => ({445+ ask,446+ base,447+ head,448+ outcome,449+ project,450+ requestId,451+});452+453+/** A platform whose `submitAnswer` gives `receipt` back. */454+const receiving = (receipt: ReturnType<typeof receiptAt>) =>455+ Layer.mergeAll(456+ unanswered,457+ Contracts.toLayerHandler("submitAnswer", () => Effect.succeed(receipt))458+ );459+460+describe("an answer offered with submit", () => {461+ it.effect("prints the same line git's remote: output gives its push", () =>462+ Effect.gen(function* () {463+ const offered = receiptAt(464+ Outcome.cases.Checking.make({ stage: "merge" })465+ );466+467+ const run = yield* runProgram(submitArgs, {468+ handlers: receiving(offered),469+ });470+471+ expect(run.code).toBe(0);472+ expect(Result.map(receiptLine(offered), (line) => [line])).toStrictEqual(473+ Result.succeed(run.out)474+ );475+ })476+ );477+478+ it.effect(479+ "prints a refused receipt as a refusal: once on stderr, nothing on stdout, exit 1",480+ () =>481+ Effect.gen(function* () {482+ const run = yield* runProgram(submitArgs, {483+ handlers: receiving(484+ receiptAt(Outcome.cases.Refused.make({ refusals: [refusal] }))485+ ),486+ });487+488+ expect(run.code).toBe(1);489+ expect(run.out).toStrictEqual([]);490+ expect(run.err).toStrictEqual(explain([refusal]));491+ })492+ );493+494+ it.effect("puts a refused receipt in one refused envelope under --json", () =>495+ Effect.gen(function* () {496+ const run = yield* runProgram([...submitArgs, "--json"], {497+ handlers: receiving(498+ receiptAt(Outcome.cases.Refused.make({ refusals: [refusal] }))499+ ),500+ });501+502+ expect(run.code).toBe(1);503+ expect(run.err).toStrictEqual([]);504+ expect(run.out).toHaveLength(1);505+ expect(yield* decodeEnvelope(run.out[0] ?? "")).toStrictEqual({506+ command: "submit",507+ ok: false,508+ refusals: [refusal],509+ v: 1,510+ });511+ })512+ );513+});modified:packages/protocol/src/cli.ts+390 added-81 removed
1 // Ported from joelhooks/rat-stack@fba26d8 `packages/capability/src/to-command.ts`2 // (MIT, LICENSES/rat-stack.MIT.txt). Changes are listed in PROVENANCE.md.3 import {4- Console,4+ Array,5 Context,6 Effect,7 Option,8 Predicate,9+ Runtime,10 Schema,11 SchemaAST,12 } from "effect";13 import { Argument, Command, Flag } from "effect/cli";13-import type { Rpc, RpcClient, RpcClientError } from "effect/rpc";14+import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";15 15-import { Description } from "./annotations.ts";16+import {17+ Cli,18+ Description,19+ NeedsApproval,20+ ReadOnly,21+ Surfaces,22+} from "./annotations.ts";23 import type { Unauthenticated } from "./principal.ts";24 import { Refusal } from "./refusal.ts";18-import { explain } from "./render.ts";25 26 /** How a call can fail before its handler runs: in transit, or unauthenticated. */27 type CallError = RpcClientError.RpcClientError | Unauthenticated;28 2 unmodified lines31 readonly DecodingServices: never;32 readonly EncodingServices: never;33 };34 29-/** An Rpc a command can project: its payload is a struct of plain fields. */35+/**36+ * An Rpc a command can project: its payload is a struct of plain fields, or37+ * a record that takes none (`listProjects`).38+ */39 export type CommandRpc = Rpc.AnyWithProps & {40 readonly errorSchema: Plain;32- readonly payloadSchema: Plain &33- Schema.Struct<Readonly<Record<string, Plain>>>;41+ readonly payloadSchema: Plain;42 readonly successSchema: Plain;43 };44 37-export interface ToCommandOptions<Success> {38- /** The command's name; the Rpc's tag by default. */39- readonly name?: string;40- /** Payload fields taken as positional arguments, in order, not flags. */41- readonly positional?: readonly string[];42- /** Text for a person; `--json` prints the encoded success instead. */43- readonly render?: (success: Success) => string;45+/** A result as prose: Markdown, and plain text where a person reads it. */46+export interface View {47+ readonly markdown: string;48+ readonly text?: string;49 }50 51+/**52+ * How a projected command prints. apps/cli's `Output` implements it, and53+ * decides the form: text for a person, Markdown for an agent, one `--json`54+ * envelope for a script.55+ */56+export interface CommandOutput {57+ /** The command's result; `data` is its encoded success. */58+ readonly success: (input: {59+ readonly command: string;60+ readonly json: boolean;61+ readonly data: unknown;62+ readonly view: View;63+ }) => Effect.Effect<void>;64+ /** The refusals the command met instead: printed there, and only there. */65+ readonly refused: (input: {66+ readonly command: string;67+ readonly json: boolean;68+ readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;69+ }) => Effect.Effect<void>;70+ /** What `--dry-run` would send; `payload` is encoded. */71+ readonly plan: (input: {72+ readonly command: string;73+ readonly json: boolean;74+ readonly payload: unknown;75+ }) => Effect.Effect<void>;76+}77+78+/**79+ * Values for payload fields a person may leave out, such as the project the80+ * repo they stand in belongs to.81+ */82+export interface Defaults<R> {83+ /** The fields it may fill, each with where its value comes from, for `--help`. */84+ readonly fields: Readonly<Record<string, string>>;85+ /**86+ * Their values, as typed on the command line. Read only when a required87+ * field it may fill was left out; a field it has no value for stays out.88+ */89+ readonly values: Effect.Effect<Readonly<Record<string, string>>, never, R>;90+}91+92+export interface ToCommandOptions<Success, OutputR, DefaultsR> {93+ /** Where the command prints its result, its refusals and its plan. */94+ readonly output: Effect.Effect<CommandOutput, never, OutputR>;95+ readonly defaults?: Defaults<DefaultsR> | undefined;96+ /** The result as prose; none, or none given, prints the encoded JSON. */97+ readonly render?: ((success: Success) => Option.Option<View>) | undefined;98+ /**99+ * The refusals a success carries in place of a result, such as a refused100+ * answer's receipt: they print as a refusal does, once, and the command101+ * fails with `Reported`.102+ */103+ readonly refusalsIn?: ((success: Success) => readonly Refusal[]) | undefined;104+}105+106+/**107+ * Each contract's result as prose, by tag. A view reads any contract's108+ * success and renders the one it knows; a contract with no view prints its109+ * encoded JSON.110+ */111+export type Views<Rpcs extends Rpc.Any> = Readonly<112+ Record<string, (success: Rpc.Success<Rpcs>) => Option.Option<View>>113+>;114+115+/**116+ * A command that changes something a person must approve ran without117+ * `--yes`. A usage error: nothing was called.118+ */119+export class ApprovalNeeded extends Schema.TaggedError<ApprovalNeeded>()(120+ "ApprovalNeeded",121+ { command: Schema.String }122+) {123+ override get message() {124+ return `${this.command} needs a person's approval: run it again with --yes, or with --dry-run to see what it would send`;125+ }126+}127+128+/**129+ * A required payload field was given neither on the command line nor by the130+ * defaults. A usage error: nothing was called, and nobody was asked for it.131+ */132+export class MissingValue extends Schema.TaggedError<MissingValue>()(133+ "MissingValue",134+ { command: Schema.String, flag: Schema.String }135+) {136+ override get message() {137+ return `${this.command} needs ${this.flag}: give it, since nothing here does`;138+ }139+}140+141+/**142+ * Everything a command printed has been printed: the program exits 1 and143+ * prints nothing more, and the runtime reports nothing of its own.144+ */145+export class Reported extends Schema.TaggedError<Reported>()("Reported", {}) {146+ override readonly [Runtime.errorExitCode] = 1;147+ override readonly [Runtime.errorReported] = false;148+}149+150 interface FieldSpec {151 readonly description: string | undefined;152 readonly kind: "string" | "number" | "boolean" | "literals" | "json";153 readonly literals: readonly string[];56 unmodified lines210 211 return { description, kind, literals: [], optional };212 };213 214+/**215+ * A payload's fields, by name: a struct's, or none for a payload that takes216+ * nothing (an empty record, which an MCP tool's input needs).217+ */218+const fieldsOf = (payload: Plain): readonly (readonly [string, Plain])[] =>219+ SchemaAST.isObjects(payload.ast)220+ ? payload.ast.propertySignatures.flatMap(({ name, type }) =>221+ Predicate.isString(name)222+ ? [[name, Schema.make<Schema.Codec<unknown>>(type)] as const]223+ : []224+ )225+ : [];226+227+/** Whether a person must give the field: a switch is off unless named. */228+const isRequired = (spec: FieldSpec) =>229+ !spec.optional && spec.kind !== "boolean";230+231 const jsonFlag = (name: string, field: Plain) =>232 Flag.String(name).pipe(233 Flag.withSchema(Schema.fromJsonString(field)),234 Flag.withMetavar("JSON")11 unmodified lines246 FieldSpec["kind"],247 (name: string, field: Plain, spec: FieldSpec) => Flag.Flag<unknown>248 >;249 129-const flagFor = (name: string, field: Plain): Flag.Flag<unknown> => {250+/** A field's help text, and where its default comes from when it has one. */251+const helpOf = (spec: FieldSpec, fallback: string | undefined) => {252+ if (fallback === undefined) {253+ return spec.description;254+ }255+256+ return spec.description === undefined257+ ? `Defaults to ${fallback}`258+ : `${spec.description}; defaults to ${fallback}`;259+};260+261+/**262+ * A field as a flag. It is optional when the payload says so, or when the263+ * defaults may fill it; the handler then says if it is still missing.264+ */265+const flagFor = (266+ name: string,267+ field: Plain,268+ fallback: string | undefined269+): Flag.Flag<unknown> => {270 const spec = describe(field);271 const base = flagBuilders[spec.kind](name, field, spec);272+ const help = helpOf(spec, fallback);273 274 const described =134- spec.description === undefined135- ? base136- : base.pipe(Flag.withDescription(spec.description));275+ help === undefined ? base : base.pipe(Flag.withDescription(help));276 138- return spec.optional && spec.kind !== "boolean"277+ return (spec.optional || fallback !== undefined) && spec.kind !== "boolean"278 ? described.pipe(Flag.optional, Flag.map(Option.getOrUndefined))279 : described;280 };281 15 unmodified lines297 >;298 299 const argumentFor = (300 name: string,162- field: Plain301+ field: Plain,302+ fallback: string | undefined303 ): Argument.Argument<unknown> => {304 const spec = describe(field);305 const base = argumentBuilders[spec.kind](name, field, spec);306+ const help = helpOf(spec, fallback);307 308 const described =168- spec.description === undefined169- ? base170- : base.pipe(Argument.withDescription(spec.description));309+ help === undefined ? base : base.pipe(Argument.withDescription(help));310 172- return spec.optional311+ return spec.optional || fallback !== undefined312 ? described.pipe(Argument.optional, Argument.map(Option.getOrUndefined))313 : described;314 };315 177-const JSON_FLAG = "json";316+/**317+ * The flags a projected command takes beside its payload's: `--json`318+ * always, `--yes` when a person approves it, and `--dry-run` unless it only319+ * reads.320+ */321+const controls = (approval: boolean, readOnly: boolean) =>322+ Object.fromEntries([323+ [324+ "json",325+ Flag.Boolean("json").pipe(326+ Flag.withDefault(false),327+ Flag.withDescription(328+ "Print one versioned JSON envelope on stdout, and nothing else there"329+ )330+ ),331+ ],332+ ...(approval333+ ? [334+ [335+ "yes",336+ Flag.Boolean("yes").pipe(337+ Flag.withDefault(false),338+ Flag.withDescription(339+ "Approve it: it runs only with --yes, since a person approves it first"340+ )341+ ),342+ ] as const,343+ ]344+ : []),345+ ...(readOnly346+ ? []347+ : [348+ [349+ "dryRun",350+ Flag.Boolean("dry-run").pipe(351+ Flag.withDefault(false),352+ Flag.withDescription(353+ "Print the payload it would send, and send nothing"354+ )355+ ),356+ ] as const,357+ ]),358+ ]);359 360 const isRefusal = Schema.is(Refusal);361 181-const encodeRefusal = Schema.encodeEffect(Refusal);362+/** The contract's command, as a person types it: `asks`, `ask open`. */363+export const commandName = (rpc: Rpc.AnyWithProps): string =>364+ Context.get(rpc.annotations, Cli).name ?? rpc._tag;365 183-/**184- * Says why a call was refused: as JSON on stdout for `--json`, or on stderr in185- * the same words git's `remote:` lines use.186- */187-const report = (refusal: Refusal, json: boolean) =>188- json189- ? encodeRefusal(refusal).pipe(190- Effect.flatMap((encoded) =>191- Console.log(JSON.stringify(encoded, null, 2))192- ),193- Effect.orDie194- )195- : Console.error(explain([refusal]).join("\n"));366+/** The words that reach the contract's command: `["ask", "open"]`. */367+export const commandPath = (368+ rpc: Rpc.AnyWithProps369+): readonly [string, ...string[]] => {370+ const [first = rpc._tag, ...rest] = commandName(rpc).split(" ");371 372+ return [first, ...rest];373+};374+375+/** JSON text as Markdown, and as itself for a person. */376+const asJson = (text: string): View => ({377+ markdown: ["```json", text, "```"].join("\n"),378+ text,379+});380+381 /**198- * Projects one contract onto a CLI command: payload fields become flags (or199- * positional arguments), and the command calls the Rpc through `client`.382+ * Projects one contract onto a CLI command. Its payload's fields become383+ * flags (or the positional arguments its `Cli` annotation names), and it is384+ * named by the last word of that annotation's name. Every command takes385+ * `--json`; one that needs approval takes `--yes` and runs only with it;386+ * one that changes something takes `--dry-run`, which prints the encoded387+ * payload and calls nothing. A refusal, or the refusals a success carries388+ * (`refusalsIn`), go to `output.refused` once, and the command fails with389+ * `Reported`.390 */201-export const toCommand = <R extends CommandRpc, Requirements>(391+export const toCommand = <392+ R extends CommandRpc,393+ ClientR,394+ OutputR,395+ DefaultsR = never,396+>(397 rpc: R,203- client: Effect.Effect<RpcClient.RpcClient<R, CallError>, never, Requirements>,204- options?: ToCommandOptions<Rpc.Success<R>>398+ client: Effect.Effect<RpcClient.RpcClient<R, CallError>, never, ClientR>,399+ options: ToCommandOptions<Rpc.Success<R>, OutputR, DefaultsR>400 ) => {206- const positional = new Set(options?.positional);207- const render = options?.render;401+ const cli = Context.get(rpc.annotations, Cli);402+ const command = commandName(rpc);403+ const positional = new Set(cli.positional);404+ const approval = Context.get(rpc.annotations, NeedsApproval);405+ const readOnly = Context.get(rpc.annotations, ReadOnly);406+ const filled = options.defaults?.fields ?? {};407+ const fields = fieldsOf(rpc.payloadSchema);408 409+ const required = fields.flatMap(([name, field]) =>410+ isRequired(describe(field)) ? [name] : []411+ );412+209- const config: Record<413+ const payload: Record<414 string,415 Flag.Flag<unknown> | Argument.Argument<unknown>416 > = {};417 214- for (const [name, field] of Object.entries(rpc.payloadSchema.fields)) {215- config[name] = positional.has(name)216- ? argumentFor(name, field)217- : flagFor(name, field);418+ for (const [name, field] of fields) {419+ const fallback = required.includes(name) ? filled[name] : undefined;420+421+ payload[name] = positional.has(name)422+ ? argumentFor(name, field, fallback)423+ : flagFor(name, field, fallback);424 }425 220- config[JSON_FLAG] = Flag.Boolean(JSON_FLAG).pipe(221- Flag.withDefault(false),222- Flag.withDescription("Print machine-readable JSON")223- );224-426 const decodePayload = Schema.decodeUnknownEffect(rpc.payloadSchema);427+ const encodePayload = Schema.encodeUnknownEffect(rpc.payloadSchema);428 const encodeSuccess = Schema.encodeUnknownEffect(rpc.successSchema);429 430+ /** The fields given, by name, then the defaults for required ones left out. */431+ const complete = (given: readonly (readonly [string, unknown])[]) =>432+ Effect.gen(function* () {433+ const provided = Object.fromEntries(434+ given.filter(([, value]) => value !== undefined)435+ );436+437+ const wanting = required.filter(438+ (name) => !Object.hasOwn(provided, name) && Object.hasOwn(filled, name)439+ );440+441+ const values: Readonly<Record<string, string>> =442+ wanting.length === 0 || options.defaults === undefined443+ ? {}444+ : yield* options.defaults.values;445+446+ const merged = {447+ ...provided,448+ ...Object.fromEntries(449+ wanting.flatMap((name) =>450+ values[name] === undefined ? [] : [[name, values[name]] as const]451+ )452+ ),453+ };454+455+ const missing = required.find((name) => !Object.hasOwn(merged, name));456+457+ if (missing !== undefined) {458+ return yield* new MissingValue({459+ command,460+ flag: positional.has(missing) ? `<${missing}>` : `--${missing}`,461+ });462+ }463+464+ return yield* decodePayload(merged);465+ });466+467 return Command.make(229- options?.name ?? rpc._tag,230- config,231- (232- parsed233- ): Effect.Effect<234- void,235- Schema.SchemaError | Rpc.Error<R> | CallError,236- Requirements237- > =>468+ commandPath(rpc).at(-1) ?? rpc._tag,469+ { control: controls(approval, readOnly), payload },470+ ({ control, payload: given }) =>471 Effect.gen(function* () {239- const { [JSON_FLAG]: json, ...fields } = parsed;472+ const json = control.json === true;473+ const dryRun = control.dryRun === true;474 241- const provided = Object.fromEntries(242- Object.entries(fields).filter(([, value]) => value !== undefined)243- );475+ if (approval && control.yes !== true && !dryRun) {476+ return yield* new ApprovalNeeded({ command });477+ }478 245- const payload = yield* decodePayload(provided);479+ const decoded = yield* complete(Object.entries(given));480+ const output = yield* options.output;481+482+ if (dryRun) {483+ const encoded = yield* Effect.orDie(encodePayload(decoded));484+485+ return yield* output.plan({ command, json, payload: encoded });486+ }487+488 const calls = yield* client;489 248- // SAFETY: an RpcClient for a group without prefixes has one method per tag, and `payload` was just decoded with that Rpc's payload schema.490+ // SAFETY: an RpcClient for a group without prefixes has one method per tag, and `decoded` was just decoded with that Rpc's payload schema.491 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the client's mapped type cannot be indexed by a generic tag; see SAFETY.492 const byTag = calls as Readonly<493 Record<494 string,495 (254- decoded: typeof payload496+ payload: typeof decoded497 ) => Effect.Effect<Rpc.Success<R>, Rpc.Error<R> | CallError>498 >499 >;500 501 const call =502 byTag[rpc._tag] ??503 (() => Effect.die(`The client has no method for ${rpc._tag}`));504 263- const success = yield* call(payload).pipe(264- Effect.tapError((error) =>265- isRefusal(error) ? report(error, json === true) : Effect.void505+ const success = yield* call(decoded).pipe(506+ Effect.catchIf(isRefusal, (refusal) =>507+ Effect.andThen(508+ output.refused({ command, json, refusals: [refusal] }),509+ Effect.fail(new Reported())510+ )511 )512 );513 269- const text =270- render !== undefined && json !== true271- ? render(success)272- : JSON.stringify(yield* encodeSuccess(success), null, 2);514+ const carried = options.refusalsIn?.(success) ?? [];515 274- yield* Console.log(text);516+ if (Array.isReadonlyArrayNonEmpty(carried)) {517+ yield* output.refused({ command, json, refusals: carried });518+519+ return yield* new Reported();520+ }521+522+ const data = yield* Effect.orDie(encodeSuccess(success));523+524+ const view = Option.getOrElse(525+ options.render === undefined526+ ? Option.none()527+ : options.render(success),528+ () => asJson(JSON.stringify(data, null, 2))529+ );530+531+ return yield* output.success({ command, data, json, view });532 }).pipe(Effect.withSpan(`protocol.${rpc._tag}`))276- ).pipe(Command.withDescription(Context.get(rpc.annotations, Description)));533+ ).pipe(534+ Command.withDescription(535+ [536+ Context.get(rpc.annotations, Description),537+ ...(readOnly ? ["It only reads."] : []),538+ ...(approval ? ["It runs only with --yes: a person approves it."] : []),539+ ].join(" ")540+ )541+ );542 };543+544+export interface ToCommandsOptions<Rpcs extends Rpc.Any, OutputR, DefaultsR> {545+ readonly output: Effect.Effect<CommandOutput, never, OutputR>;546+ readonly defaults?: Defaults<DefaultsR> | undefined;547+ readonly views?: Views<Rpcs> | undefined;548+ /** The refusals any contract's success carries in place of a result. */549+ readonly refusalsIn?:550+ | ((success: Rpc.Success<Rpcs>) => readonly Refusal[])551+ | undefined;552+ /** Tags a hand-written command wraps instead, such as `setEnv`'s `env set`. */553+ readonly exclude: readonly string[];554+}555+556+/**557+ * Every contract in `group` whose `Surfaces` include `cli`, but those558+ * `exclude` names, as a command at the path its `Cli` annotation names.559+ */560+export const toCommands = <561+ Rpcs extends CommandRpc,562+ ClientR,563+ OutputR,564+ DefaultsR = never,565+>(566+ group: RpcGroup.RpcGroup<Rpcs>,567+ client: Effect.Effect<RpcClient.RpcClient<Rpcs, CallError>, never, ClientR>,568+ options: ToCommandsOptions<Rpcs, OutputR, DefaultsR>569+) =>570+ [...group.requests.values()].flatMap((rpc) =>571+ Context.get(rpc.annotations, Surfaces).includes("cli") &&572+ !options.exclude.includes(rpc._tag)573+ ? [574+ {575+ command: toCommand(rpc, client, {576+ defaults: options.defaults,577+ output: options.output,578+ refusalsIn: options.refusalsIn,579+ render: options.views?.[rpc._tag],580+ }),581+ path: commandPath(rpc),582+ rpc,583+ },584+ ]585+ : []586+ );modified:packages/protocol/test/cli.test.ts+475 added-69 removed
1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3-import { Effect, Layer, Ref, Result, Schema } from "effect";3+import { Effect, Layer, Option, Ref, Result, Schema } from "effect";4 import { CliOutput, Command } from "effect/cli";5 import type { Rpc, RpcGroup } from "effect/rpc";6 import { RpcTest } from "effect/rpc";7 import { TestConsole } from "effect/testing";8 9-import { toCommand } from "../src/cli.ts";10-import { Client, Contracts, ListAsks, SubmitAnswer } from "../src/contracts.ts";11-import { CommitSha, KindName, ProjectName, RequestId } from "../src/ids.ts";12-import { StaleBase } from "../src/refusal.ts";9+import {10+ ApprovalNeeded,11+ MissingValue,12+ Reported,13+ toCommand,14+ toCommands,15+} from "../src/cli.ts";16+import type { CommandOutput } from "../src/cli.ts";17+import {18+ Claim,19+ Client,20+ Contracts,21+ Decide,22+ ListAsks,23+ ListProjects,24+ OpenAsk,25+ ShowAsk,26+ SubmitAnswer,27+} from "../src/contracts.ts";28+import { Outcome } from "../src/domain/outcome.ts";29+import {30+ AskId,31+ CommitSha,32+ DecisionId,33+ KindName,34+ ProjectName,35+ RequestId,36+} from "../src/ids.ts";37+import { AskFull, DecisionClosed, StaleBase } from "../src/refusal.ts";38 import { asTester, unanswered } from "../src/testing.ts";39 import { ask, base, main, path } from "./examples.ts";40 41 const head = CommitSha.make("3333333333333333333333333333333333333333");15 unmodified lines57 "--requestId",58 requestId,59 ];60 61+const listing = (territory: string) => ({62+ ask,63+ blockedBy: [],64+ claimed: false,65+ kind: KindName.make("fix"),66+ territory,67+ want: "Parse a comma",68+});69+70 /** `listAsks` echoes its project as the territory. */71 const quiet = Layer.mergeAll(72 unanswered,73 Contracts.toLayerHandler("listAsks", ({ project: echoed }) =>40- Effect.succeed({41- asks: [42- {43- ask,44- blockedBy: [],45- claimed: false,46- kind: KindName.make("fix"),47- territory: echoed,48- want: "Parse a comma",49- },50- ],51- })74+ Effect.succeed({ asks: [listing(echoed)] })75 )76 );77 78 /** Contracts whose answers always meet a moved main. */2 unmodified lines81 unanswered,82 Contracts.toLayerHandler("submitAnswer", () => Effect.fail(refusal))83 );84 85+type HandedTo<Method extends keyof CommandOutput> = Parameters<86+ CommandOutput[Method]87+>[0];88+89+/** What a command handed its output, in order. */90+type Printed =91+ | { readonly kind: "success"; readonly input: HandedTo<"success"> }92+ | { readonly kind: "refused"; readonly input: HandedTo<"refused"> }93+ | { readonly kind: "plan"; readonly input: HandedTo<"plan"> };94+95 /** What was printed, one entry per line however it was written. */96 const lines = (output: Effect.Effect<readonly unknown[]>) =>97 Effect.map(output, (all) =>98 all.flatMap((chunk) => String(chunk).split("\n"))99 );100 101 /**69- * Runs `command` on `args`, its calls answered by `handlers`, and returns how70- * it ended with what it printed to stdout and stderr.102+ * Runs the command `build` makes over a recording output on `args`, its103+ * calls answered by `handlers`. Returns how it ended, what it handed the104+ * output, and what it printed itself.105 */106 const run = <Name extends string, Input, E, R, ContextInput>(107 handlers: Layer.Layer<Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>>,108+ build: (109+ output: Effect.Effect<CommandOutput>74- command: Command.Command<Name, Input, ContextInput, E, R>,110+ ) => Command.Command<Name, Input, ContextInput, E, R>,111 args: readonly string[]112 ) =>113 Effect.gen(function* () {114+ const printed = yield* Ref.make<readonly Printed[]>([]);115+116+ const record = (entry: Printed) =>117+ Ref.update(printed, (all) => [...all, entry]);118+119+ const output: CommandOutput = {120+ plan: (input) => record({ input, kind: "plan" }),121+ refused: (input) => record({ input, kind: "refused" }),122+ success: (input) => record({ input, kind: "success" }),123+ };124+125 const result = yield* Effect.result(79- Command.runWith(command, { version: "0.0.0" })(args)126+ Command.runWith(build(Effect.succeed(output)), { version: "0.0.0" })(args)127 );128 129 return {130 err: yield* lines(TestConsole.errorLines),131 out: yield* lines(TestConsole.logLines),132+ printed: yield* Ref.get(printed),133 result,134 };135 }).pipe(136 Effect.provide(6 unmodified lines143 ).pipe(Layer.provideMerge(NodeServices.layer))144 )145 );146 99-const Json = Schema.fromJsonString(Schema.Unknown);147+/** A handler's answer, after counting the call in `calls`. */148+const counting = <A, E>(calls: Ref.Ref<number>, reply: Effect.Effect<A, E>) =>149+ Ref.update(calls, (count) => count + 1).pipe(Effect.andThen(reply));150 101-const submitAnswer = toCommand(SubmitAnswer, Effect.service(Client));151+const decision = DecisionId.make("dec-000001");152 103-describe("the contracts as CLI commands", () => {104- it.effect("takes the payload as flags and prints the success as JSON", () =>153+/** A decision someone else already took: the call fails, typed. */154+const decided = Effect.fail(new DecisionClosed({ decision }));155+156+describe("a contract as a CLI command", () => {157+ it.effect(158+ "takes the payload as flags and hands the encoded success to the output",159+ () =>160+ Effect.gen(function* () {161+ const { printed } = yield* run(162+ quiet,163+ (output) => toCommand(ListAsks, Effect.service(Client), { output }),164+ ["--project", "demo"]165+ );166+167+ const data = { asks: [listing("demo")] };168+169+ expect(printed).toStrictEqual([170+ {171+ input: {172+ command: "asks",173+ data,174+ json: false,175+ view: {176+ markdown: [177+ "```json",178+ JSON.stringify(data, null, 2),179+ "```",180+ ].join("\n"),181+ text: JSON.stringify(data, null, 2),182+ },183+ },184+ kind: "success",185+ },186+ ]);187+ })188+ );189+190+ it.effect("prints the success through the view it is given", () =>191 Effect.gen(function* () {106- const { out } = yield* run(192+ const { printed } = yield* run(193 quiet,108- toCommand(ListAsks, Effect.service(Client)),109- ["--project", "demo"]194+ (output) =>195+ toCommand(ListAsks, Effect.service(Client), {196+ output,197+ render: ({ asks }) =>198+ Option.some({ markdown: `**${asks.length}** open asks` }),199+ }),200+ ["--project", "demo", "--json"]201 );202 112- expect(yield* Schema.decodeEffect(Json)(out.join("\n"))).toStrictEqual({113- asks: [114- {115- ask: "fix-parser",116- blockedBy: [],117- claimed: false,118- kind: "fix",119- territory: "demo",120- want: "Parse a comma",203+ expect(printed).toStrictEqual([204+ {205+ input: {206+ command: "asks",207+ data: { asks: [listing("demo")] },208+ json: true,209+ view: { markdown: "**1** open asks" },210 },122- ],123- });211+ kind: "success",212+ },213+ ]);214 })215 );216 217+ it.effect(218+ "hands a refusal to the output once, prints nothing itself, and fails as reported",127- it.effect("prints a refusal as the renderer's text and fails with it", () =>128- Effect.gen(function* () {129- const refusal = new StaleBase({ base, conflicts: [path], main });219+ () =>220+ Effect.gen(function* () {221+ const refusal = new StaleBase({ base, conflicts: [path], main });222 131- const { err, result } = yield* run(stale(refusal), submitAnswer, answer);223+ const { err, out, printed, result } = yield* run(224+ stale(refusal),225+ (output) =>226+ toCommand(SubmitAnswer, Effect.service(Client), { output }),227+ [...answer, "--json"]228+ );229 133- expect(result).toStrictEqual(Result.fail(refusal));134- expect(err).toStrictEqual([135- "StaleBase: main moved to 2222222, past your base 1111111; conflicts in src/a.ts",136- " next: git pull --rebase",137- " retryable: yes",138- ]);139- })230+ expect(result).toStrictEqual(Result.fail(new Reported()));231+ expect(printed).toStrictEqual([232+ {233+ input: { command: "submit", json: true, refusals: [refusal] },234+ kind: "refused",235+ },236+ ]);237+ expect({ err, out }).toStrictEqual({ err: [], out: [] });238+ })239 );240 241+ it.effect(242+ "hands the refusals a success carries to the output once, and fails as reported",142- it.effect("with --json, prints the refusal as JSON that keeps its tag", () =>143- Effect.gen(function* () {144- const refusal = new StaleBase({ base, conflicts: [path], main });243+ () =>244+ Effect.gen(function* () {245+ const refusal = new StaleBase({ base, conflicts: [path], main });246 146- const { err, out, result } = yield* run(stale(refusal), submitAnswer, [147- ...answer,148- "--json",149- ]);247+ const refused = {248+ ask,249+ base,250+ head,251+ outcome: Outcome.cases.Refused.make({ refusals: [refusal] }),252+ project,253+ requestId,254+ };255 151- const printed = yield* Schema.decodeEffect(Json)(out.join("\n"));256+ const { printed, result } = yield* run(257+ Layer.mergeAll(258+ unanswered,259+ Contracts.toLayerHandler("submitAnswer", () =>260+ Effect.succeed(refused)261+ )262+ ),263+ (output) =>264+ toCommand(SubmitAnswer, Effect.service(Client), {265+ output,266+ refusalsIn: ({ outcome }) =>267+ Outcome.guards.Refused(outcome) ? outcome.refusals : [],268+ }),269+ answer270+ );271 153- expect(result).toStrictEqual(Result.fail(refusal));154- expect(err).toStrictEqual([]);155- expect(printed).toHaveProperty("_tag", "StaleBase");156- expect(157- yield* Schema.decodeUnknownEffect(StaleBase)(printed)158- ).toStrictEqual(refusal);159- })272+ expect(result).toStrictEqual(Result.fail(new Reported()));273+ expect(printed).toStrictEqual([274+ {275+ input: { command: "submit", json: false, refusals: [refusal] },276+ kind: "refused",277+ },278+ ]);279+ })280 );281 282 it.effect("refuses a malformed commit id before calling anything", () =>283 Effect.gen(function* () {2 unmodified lines286 const { err, result } = yield* run(287 Layer.mergeAll(288 unanswered,289 Contracts.toLayerHandler("submitAnswer", () =>170- Ref.update(calls, (count) => count + 1).pipe(171- Effect.andThen(Effect.die("a malformed answer reached the call"))290+ counting(calls, Effect.die("a malformed answer reached the call"))172- )291 )292 ),175- submitAnswer,293+ (output) => toCommand(SubmitAnswer, Effect.service(Client), { output }),294 answer.map((value) => (value === base ? "not-a-sha" : value))295 );296 297 expect(Result.isFailure(result)).toBeTruthy();298 expect(yield* Ref.get(calls)).toBe(0);299 expect(err.join("\n")).toContain("--base");300 })301 );302+303+ it.effect(304+ "is named by its Cli annotation, and takes the fields it names in order",305+ () =>306+ Effect.gen(function* () {307+ const claimed = yield* Ref.make<readonly unknown[]>([]);308+309+ const { result } = yield* run(310+ Layer.mergeAll(311+ unanswered,312+ Contracts.toLayerHandler("claim", (payload) =>313+ Ref.update(claimed, (all) => [...all, payload]).pipe(314+ Effect.andThen(Effect.fail(new AskFull({ ask: payload.ask })))315+ )316+ )317+ ),318+ (output) => toCommand(Claim, Effect.service(Client), { output }),319+ ["fix-week", "--project", project]320+ );321+322+ expect(result).toStrictEqual(Result.fail(new Reported()));323+ expect(yield* Ref.get(claimed)).toStrictEqual([324+ { ask: AskId.make("fix-week"), project },325+ ]);326+ })327+ );328+329+ it("takes the last word of a two-word name as its own", () => {330+ const output = Effect.succeed<CommandOutput>({331+ plan: () => Effect.void,332+ refused: () => Effect.void,333+ success: () => Effect.void,334+ });335+336+ expect(337+ [OpenAsk, ShowAsk, ListAsks].map(338+ (rpc) => toCommand(rpc, Effect.service(Client), { output }).name339+ )340+ ).toStrictEqual(["open", "ask", "asks"]);341+ });342+343+ it.effect("takes nothing when the contract takes nothing", () =>344+ Effect.gen(function* () {345+ const { printed } = yield* run(346+ Layer.mergeAll(347+ unanswered,348+ Contracts.toLayerHandler("listProjects", () =>349+ Effect.succeed({ projects: [] })350+ )351+ ),352+ (output) => toCommand(ListProjects, Effect.service(Client), { output }),353+ ["--json"]354+ );355+356+ expect(printed).toHaveLength(1);357+ expect(printed[0]?.input).toHaveProperty("data", { projects: [] });358+ })359+ );360 });361+362+describe("--yes and --dry-run", () => {363+ const decideArgs = [364+ "--project",365+ project,366+ "--decision",367+ decision,368+ "--choice",369+ "accept",370+ ];371+372+ it.effect(373+ "refuses a contract that needs approval without --yes, before calling it",374+ () =>375+ Effect.gen(function* () {376+ const calls = yield* Ref.make(0);377+378+ const { printed, result } = yield* run(379+ Layer.mergeAll(380+ unanswered,381+ Contracts.toLayerHandler("decide", () => counting(calls, decided))382+ ),383+ (output) => toCommand(Decide, Effect.service(Client), { output }),384+ decideArgs385+ );386+387+ expect(result).toStrictEqual(388+ Result.fail(new ApprovalNeeded({ command: "decide" }))389+ );390+ expect(yield* Ref.get(calls)).toBe(0);391+ expect(printed).toStrictEqual([]);392+ })393+ );394+395+ it.effect("calls it with --yes", () =>396+ Effect.gen(function* () {397+ const calls = yield* Ref.make(0);398+399+ yield* run(400+ Layer.mergeAll(401+ unanswered,402+ Contracts.toLayerHandler("decide", () => counting(calls, decided))403+ ),404+ (output) => toCommand(Decide, Effect.service(Client), { output }),405+ [...decideArgs, "--yes"]406+ );407+408+ expect(yield* Ref.get(calls)).toBe(1);409+ })410+ );411+412+ it.effect(413+ "hands the encoded payload to the output's plan under --dry-run, and calls nothing",414+ () =>415+ Effect.gen(function* () {416+ const calls = yield* Ref.make(0);417+418+ const { printed, result } = yield* run(419+ Layer.mergeAll(420+ unanswered,421+ Contracts.toLayerHandler("decide", () => counting(calls, decided))422+ ),423+ (output) => toCommand(Decide, Effect.service(Client), { output }),424+ [...decideArgs, "--dry-run", "--json"]425+ );426+427+ expect(Result.isSuccess(result)).toBeTruthy();428+ expect(yield* Ref.get(calls)).toBe(0);429+ expect(printed).toStrictEqual([430+ {431+ input: {432+ command: "decide",433+ json: true,434+ payload: { choice: "accept", decision, project },435+ },436+ kind: "plan",437+ },438+ ]);439+ })440+ );441+442+ it.effect(443+ "offers no --dry-run on a read, and no --yes where nobody approves",444+ () =>445+ Effect.gen(function* () {446+ const dryRead = yield* run(447+ quiet,448+ (output) => toCommand(ListAsks, Effect.service(Client), { output }),449+ ["--project", project, "--dry-run"]450+ );451+452+ const yesClaim = yield* run(453+ quiet,454+ (output) => toCommand(Claim, Effect.service(Client), { output }),455+ ["fix-week", "--project", project, "--yes"]456+ );457+458+ expect(dryRead.err.join("\n")).toContain("--dry-run");459+ expect(yesClaim.err.join("\n")).toContain("--yes");460+ expect([dryRead.printed, yesClaim.printed]).toStrictEqual([[], []]);461+ })462+ );463+});464+465+describe("defaults", () => {466+ it.effect(467+ "fill a required field left out, and are read only when one is",468+ () =>469+ Effect.gen(function* () {470+ const reads = yield* Ref.make(0);471+472+ const defaults = {473+ fields: { project: "the repo's project" },474+ values: Ref.update(reads, (count) => count + 1).pipe(475+ Effect.as({ project: "datekit" })476+ ),477+ };478+479+ const build = (output: Effect.Effect<CommandOutput>) =>480+ toCommand(ListAsks, Effect.service(Client), { defaults, output });481+482+ const filled = yield* run(quiet, build, ["--json"]);483+ const given = yield* run(quiet, build, ["--project", "demo", "--json"]);484+485+ expect(486+ [filled, given].map(({ printed }) => printed[0]?.input)487+ ).toStrictEqual([488+ expect.objectContaining({ data: { asks: [listing("datekit")] } }),489+ expect.objectContaining({ data: { asks: [listing("demo")] } }),490+ ]);491+ expect(yield* Ref.get(reads)).toBe(1);492+ })493+ );494+495+ it.effect(496+ "leave a field they have no value for missing, naming its flag",497+ () =>498+ Effect.gen(function* () {499+ const { printed, result } = yield* run(500+ quiet,501+ (output) =>502+ toCommand(ListAsks, Effect.service(Client), {503+ defaults: {504+ fields: { project: "the repo's project" },505+ values: Effect.succeed({}),506+ },507+ output,508+ }),509+ []510+ );511+512+ expect(result).toStrictEqual(513+ Result.fail(new MissingValue({ command: "asks", flag: "--project" }))514+ );515+ expect(printed).toStrictEqual([]);516+ })517+ );518+});519+520+/** The group's commands, with a view for `listAsks` only. */521+const commands = (built: Effect.Effect<CommandOutput>) =>522+ toCommands(Contracts, Effect.service(Client), {523+ exclude: [],524+ output: built,525+ views: {526+ listAsks: (success) =>527+ Schema.is(ListAsks.successSchema)(success)528+ ? Option.some({ markdown: `${success.asks.length} asks` })529+ : Option.none(),530+ },531+ });532+533+const root = (built: Effect.Effect<CommandOutput>) =>534+ Command.make("root").pipe(535+ Command.withSubcommands(commands(built).map(({ command }) => command))536+ );537+538+describe("the group as CLI commands", () => {539+ const output = Effect.succeed<CommandOutput>({540+ plan: () => Effect.void,541+ refused: () => Effect.void,542+ success: () => Effect.void,543+ });544+545+ it("projects each contract served on the CLI, but those excluded, at its path", () => {546+ const paths = toCommands(Contracts, Effect.service(Client), {547+ exclude: ["initProject", "setEnv"],548+ output,549+ }).map(({ path: words }) => words.join(" "));550+551+ expect(paths).toStrictEqual([552+ "projects",553+ "front",554+ "asks",555+ "ask",556+ "status",557+ "verdict",558+ "landing",559+ "credits",560+ "today",561+ "ledger",562+ "env shape",563+ "ask open",564+ "propose",565+ "ask flag",566+ "decide",567+ "claim",568+ "release",569+ "submit",570+ "finish",571+ "land",572+ "fork",573+ "vouch",574+ ]);575+ });576+577+ it.effect("renders each result with the view its tag names", () =>578+ Effect.gen(function* () {579+ const { printed } = yield* run(quiet, root, [580+ "asks",581+ "--project",582+ "demo",583+ ]);584+585+ expect(printed[0]?.input).toHaveProperty("view", {586+ markdown: "1 asks",587+ });588+ })589+ );590+});