Skip to content
Myr

commands-doc.test.ts

This file

Path

apps/cli/test/commands-doc.test.ts

235 lines · 7.2 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1–93why, one step back
1import { NodeServices } from "@effect/platform-node";
2import { describe, expect, it } from "@effect/vitest";3import { commandDocs, contractCommandDocs } from "@repo/agent-kit/command-doc";4import type { CommandDoc } from "@repo/agent-kit/command-doc";5import { Client, Contracts } from "@repo/protocol/contracts";6import { toJsonSchema } from "@repo/protocol/mcp";7import { Effect, Layer, Schema } from "effect";8import { CliOutput, Command } from "effect/cli";9import type { HelpDoc } from "effect/cli";10import { TestConsole } from "effect/testing";1112import { root } from "../src/main.ts";13import { OutputPlain } from "../src/output.ts";14import { SignedOut } from "./signed-out.ts";1516const Takes = Schema.Struct({17 args: Schema.Array(18 Schema.Struct({ name: Schema.String, required: Schema.Boolean })19 ),20 flags: Schema.Array(21 Schema.Struct({22 name: Schema.String,23 required: Schema.Boolean,24 type: Schema.String,25 })26 ),27});2829type Takes = typeof Takes.Type;3031const encodeTakes = Schema.encodeSync(Schema.fromJsonString(Takes));3233const decodeTakes = Schema.decodeSync(Schema.fromJsonString(Takes));3435const takesOf = (doc: HelpDoc.HelpDoc) =>36 encodeTakes({37 args: (doc.args ?? []).map(({ name, required }) => ({ name, required })),38 flags: doc.flags.map(({ name, required, type }) => ({39 name,40 required,41 type,42 })),43 });4445const plain = CliOutput.defaultFormatter({ colors: false });4647const formatter: CliOutput.Formatter = {48 formatCliError: (error) => plain.formatCliError(error),49 formatError: (error) => plain.formatError(error),50 formatErrors: (errors) => plain.formatErrors(errors),51 formatHelpDoc: takesOf,52 formatVersion: (name, version) => plain.formatVersion(name, version),53};5455const services = Layer.mergeAll(56 TestConsole.layer,57 CliOutput.layer(formatter),58 Layer.mock(Client)({}),59 SignedOut,60 OutputPlain61).pipe(Layer.provideMerge(NodeServices.layer));6263const helpOf = (path: readonly string[]) =>64 Effect.gen(function* () {65 yield* Command.runWith(root, { version: "0.0.0" })([...path, "--help"]);6667 // The console is the test's, so the help just printed is its last line.68 const lines = yield* TestConsole.logLines;6970 return decodeTakes(String(lines.at(-1)));71 }).pipe(Effect.provide(services), Effect.orDie);7273interface Node {74 readonly path: readonly string[];75 readonly command: Command.Command.Any;76 readonly takes: Takes;77}7879const below = (80 command: Command.Command.Any,81 path: readonly string[]82): Effect.Effect<readonly Node[]> =>83 Effect.forEach(84 command.subcommands.flatMap(({ commands }) => commands),85 (sub) =>86 Effect.gen(function* () {87 const here = [...path, sub.name];88 const node = { command: sub, path: here, takes: yield* helpOf(here) };8990 return [node, ...(yield* below(sub, here))];91 })92 ).pipe(Effect.map((nodes) => nodes.flat()));93

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 94why, one step back
94// A word that only groups commands (`env`) takes nothing; `ask <ask>` beside `ask open` does.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 95–111why, one step back
95const isRunnable = ({ command, takes }: Node) =>
96 command.subcommands.length === 0 ||97 takes.args.length + takes.flags.length > 0;9899const runnable = below(root, []).pipe(100 Effect.map(101 (nodes) =>102 new Map(103 nodes.filter(isRunnable).map((node) => [node.path.join(" "), node])104 )105 )106);107108const rows: readonly CommandDoc[] = commandDocs(Contracts);109110const words = ({ path }: CommandDoc) => path.join(" ");111

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 112why, one step back
112// `--no-push` names the boolean flag `push`, unless the command has a flag of that very name.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 113–235why, one step back
113const declared = (row: CommandDoc, takes: Takes) => {
114 const names = new Set(takes.flags.map(({ name }) => name));115116 const switches = new Set(117 takes.flags.flatMap(({ name, type }) => (type === "boolean" ? [name] : []))118 );119120 return new Set(121 row.flags.map((flag) => {122 const name = flag.replace(/^--/u, "");123 const negated = name.replace(/^no-/u, "");124125 return !names.has(name) && switches.has(negated) ? negated : name;126 })127 );128};129130const PayloadFields = Schema.Struct({131 properties: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),132 required: Schema.optionalKey(Schema.Array(Schema.String)),133});134135const decodePayloadFields = Schema.decodeUnknownSync(PayloadFields);136137const payloadOf = (row: CommandDoc) => {138 const rpc = Contracts.requests.get(row.contract ?? "");139140 return rpc === undefined141 ? {}142 : decodePayloadFields(toJsonSchema(rpc.payloadSchema));143};144145const isBoolean = Schema.is(Schema.Struct({ type: Schema.Literal("boolean") }));146147const isSwitch = (field: Schema.Json | undefined) =>148 field !== undefined && isBoolean(field);149150const filledFromRepo = new Set(["project"]);151152describe("the command rows against the CLI", () => {153 it.effect(154 "name exactly the commands the CLI has: none without a row, no row without a command",155 () =>156 Effect.gen(function* () {157 const commands = yield* runnable;158159 expect([...commands.keys()].toSorted()).toStrictEqual(160 rows.map(words).toSorted()161 );162 // Known commands, so an empty tree and an empty list can't agree.163 expect(commands.has("asks")).toBeTruthy();164 expect(commands.has("env set")).toBeTruthy();165 expect(commands.has("env")).toBeFalsy();166 }),167 30_000168 );169170 it.effect(171 "give each command exactly the flags it takes, and its required arguments in order",172 () =>173 Effect.gen(function* () {174 const commands = yield* runnable;175176 const differ = rows.flatMap((row) => {177 const { takes } = commands.get(words(row)) ?? {178 takes: { args: [], flags: [] },179 };180181 const flags = [...declared(row, takes)].toSorted();182 const real = takes.flags.map(({ name }) => name).toSorted();183184 const positional = takes.args.flatMap(({ name, required }) =>185 required ? [name] : []186 );187188 return flags.join(" ") === real.join(" ") &&189 positional.join(" ") === row.positional.join(" ")190 ? []191 : [{ command: words(row), flags, positional, real }];192 });193194 expect(differ).toStrictEqual([]);195 }),196 30_000197 );198199 it.effect(200 "require a contract's required fields as flags, all but the --project the repo fills",201 () =>202 Effect.gen(function* () {203 const commands = yield* runnable;204205 const differ = contractCommandDocs(Contracts).flatMap((row) => {206 const { properties = {}, required = [] } = payloadOf(row);207208 const asked = required.filter(209 (field) =>210 !row.positional.includes(field) &&211 !isSwitch(properties[field]) &&212 !filledFromRepo.has(field)213 );214215 const real = (commands.get(words(row))?.takes.flags ?? []).flatMap(216 ({ name, required: needed }) => (needed ? [name] : [])217 );218219 return asked.toSorted().join(" ") === real.toSorted().join(" ")220 ? []221 : [{ asked, command: words(row), real }];222 });223224 // Known fills, so a CLI that requires `--project` everywhere and a225 // list that fills nothing can't agree.226 expect(227 contractCommandDocs(Contracts).filter((row) =>228 (payloadOf(row).required ?? []).includes("project")229 )230 ).not.toHaveLength(0);231 expect(differ).toStrictEqual([]);232 }),233 30_000234 );235});