Skip to content
Myr

cli.test.ts

This file

Path

packages/protocol/test/cli.test.ts

631 lines · 17.3 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–24why, one step back
1import { NodeServices } from "@effect/platform-node";
2import { describe, expect, it } from "@effect/vitest";3import { Effect, Layer, Option, Ref, Result, Schema } from "effect";4import { CliOutput, Command } from "effect/cli";5import type { Rpc, RpcGroup } from "effect/rpc";6import { RpcTest } from "effect/rpc";7import { TestConsole } from "effect/testing";89import {10 ApprovalNeeded,11 MissingValue,12 Reported,13 toCommand,14 toCommands,15} from "../src/cli.ts";16import type { CommandOutput } from "../src/cli.ts";17import {18 Claim,19 Client,20 Contracts,21 Decide,22 ListAsks,23 ListProjects,24 OpenAsk,

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d

line 25why, one step back
25 ProposeAsk,

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 26–37why, one step back
26 ShowAsk,
27 SubmitAnswer,28} from "../src/contracts.ts";29import { Outcome } from "../src/domain/outcome.ts";30import {31 AskId,32 CommitSha,33 DecisionId,34 KindName,35 ProjectName,36 RequestId,37} from "../src/ids.ts";

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d

lines 38–43why, one step back
38import {
39 AskFull,40 CapReached,41 DecisionClosed,42 StaleBase,43} from "../src/refusal.ts";

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 44–48why, one step back
44import { asTester, unanswered } from "../src/testing.ts";
45import { ask, base, main, path } from "./examples.ts";4647const head = CommitSha.make("3333333333333333333333333333333333333333");48

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 49why, one step back
49const project = ProjectName.make("oscabriel/datekit");

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 50–157why, one step back
50
51const requestId = RequestId.make("answer-0001");5253const answer = [54 "--project",55 project,56 "--ask",57 ask,58 "--base",59 base,60 "--head",61 head,62 "--requestId",63 requestId,64];6566const listing = (territory: string) => ({67 ask,68 blockedBy: [],69 claimed: false,70 kind: KindName.make("fix"),71 territory,72 want: "Parse a comma",73});7475const quiet = Layer.mergeAll(76 unanswered,77 Contracts.toLayerHandler("listAsks", ({ project: echoed }) =>78 Effect.succeed({ asks: [listing(echoed)] })79 )80);8182const stale = (refusal: StaleBase) =>83 Layer.mergeAll(84 unanswered,85 Contracts.toLayerHandler("submitAnswer", () => Effect.fail(refusal))86 );8788type HandedTo<Method extends keyof CommandOutput> = Parameters<89 CommandOutput[Method]90>[0];9192type Printed =93 | { readonly kind: "success"; readonly input: HandedTo<"success"> }94 | { readonly kind: "refused"; readonly input: HandedTo<"refused"> }95 | { readonly kind: "plan"; readonly input: HandedTo<"plan"> };9697const lines = (output: Effect.Effect<readonly unknown[]>) =>98 Effect.map(output, (all) =>99 all.flatMap((chunk) => String(chunk).split("\n"))100 );101102const run = <Name extends string, Input, E, R, ContextInput>(103 handlers: Layer.Layer<Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>>,104 build: (105 output: Effect.Effect<CommandOutput>106 ) => Command.Command<Name, Input, ContextInput, E, R>,107 args: readonly string[]108) =>109 Effect.gen(function* () {110 const printed = yield* Ref.make<readonly Printed[]>([]);111112 const record = (entry: Printed) =>113 Ref.update(printed, (all) => [...all, entry]);114115 const output: CommandOutput = {116 plan: (input) => record({ input, kind: "plan" }),117 refused: (input) => record({ input, kind: "refused" }),118 success: (input) => record({ input, kind: "success" }),119 };120121 const result = yield* Effect.result(122 Command.runWith(build(Effect.succeed(output)), { version: "0.0.0" })(args)123 );124125 return {126 err: yield* lines(TestConsole.errorLines),127 out: yield* lines(TestConsole.logLines),128 printed: yield* Ref.get(printed),129 result,130 };131 }).pipe(132 Effect.provide(133 Layer.mergeAll(134 TestConsole.layer,135 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),136 Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(137 Layer.provide([handlers, asTester])138 )139 ).pipe(Layer.provideMerge(NodeServices.layer))140 )141 );142143const counting = <A, E>(calls: Ref.Ref<number>, reply: Effect.Effect<A, E>) =>144 Ref.update(calls, (count) => count + 1).pipe(Effect.andThen(reply));145146const decision = DecisionId.make("dec-000001");147148const decided = Effect.fail(new DecisionClosed({ decision }));149150describe("a contract as a CLI command", () => {151 it.effect(152 "takes the payload as flags and hands the encoded success to the output",153 () =>154 Effect.gen(function* () {155 const { printed } = yield* run(156 quiet,157 (output) => toCommand(ListAsks, Effect.service(Client), { output }),

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 158why, one step back
158 ["--project", "oscabriel/demo"]

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 159–160why, one step back
159 );
160

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 161why, one step back
161 const data = { asks: [listing("oscabriel/demo")] };

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 162–193why, one step back
162
163 expect(printed).toStrictEqual([164 {165 input: {166 command: "asks",167 data,168 json: false,169 view: {170 markdown: [171 "```json",172 JSON.stringify(data, null, 2),173 "```",174 ].join("\n"),175 text: JSON.stringify(data, null, 2),176 },177 },178 kind: "success",179 },180 ]);181 })182 );183184 it.effect("prints the success through the view it is given", () =>185 Effect.gen(function* () {186 const { printed } = yield* run(187 quiet,188 (output) =>189 toCommand(ListAsks, Effect.service(Client), {190 output,191 render: ({ asks }) =>192 Option.some({ markdown: `**${asks.length}** open asks` }),193 }),

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 194why, one step back
194 ["--project", "oscabriel/demo", "--json"]

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 195–200why, one step back
195 );
196197 expect(printed).toStrictEqual([198 {199 input: {200 command: "asks",

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 201why, one step back
201 data: { asks: [listing("oscabriel/demo")] },

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 202–223why, one step back
202 json: true,
203 view: { markdown: "**1** open asks" },204 },205 kind: "success",206 },207 ]);208 })209 );210211 it.effect(212 "hands a refusal to the output once, prints nothing itself, and fails as reported",213 () =>214 Effect.gen(function* () {215 const refusal = new StaleBase({ base, conflicts: [path], main });216217 const { err, out, printed, result } = yield* run(218 stale(refusal),219 (output) =>220 toCommand(SubmitAnswer, Effect.service(Client), { output }),221 [...answer, "--json"]222 );223

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

line 224why, one step back
224 expect(result).toStrictEqual(Result.fail(Reported.of([refusal])));

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 225–265why, one step back
225 expect(printed).toStrictEqual([
226 {227 input: { command: "submit", json: true, refusals: [refusal] },228 kind: "refused",229 },230 ]);231 expect({ err, out }).toStrictEqual({ err: [], out: [] });232 })233 );234235 it.effect(236 "hands the refusals a success carries to the output once, and fails as reported",237 () =>238 Effect.gen(function* () {239 const refusal = new StaleBase({ base, conflicts: [path], main });240241 const refused = {242 ask,243 base,244 head,245 outcome: Outcome.cases.Refused.make({ refusals: [refusal] }),246 project,247 requestId,248 };249250 const { printed, result } = yield* run(251 Layer.mergeAll(252 unanswered,253 Contracts.toLayerHandler("submitAnswer", () =>254 Effect.succeed(refused)255 )256 ),257 (output) =>258 toCommand(SubmitAnswer, Effect.service(Client), {259 output,260 refusalsIn: ({ outcome }) =>261 Outcome.guards.Refused(outcome) ? outcome.refusals : [],262 }),263 answer264 );265

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

line 266why, one step back
266 expect(result).toStrictEqual(Result.fail(Reported.of([refusal])));

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 267–315why, one step back
267 expect(printed).toStrictEqual([
268 {269 input: { command: "submit", json: false, refusals: [refusal] },270 kind: "refused",271 },272 ]);273 })274 );275276 it.effect("refuses a malformed commit id before calling anything", () =>277 Effect.gen(function* () {278 const calls = yield* Ref.make(0);279280 const { err, result } = yield* run(281 Layer.mergeAll(282 unanswered,283 Contracts.toLayerHandler("submitAnswer", () =>284 counting(calls, Effect.die("a malformed answer reached the call"))285 )286 ),287 (output) => toCommand(SubmitAnswer, Effect.service(Client), { output }),288 answer.map((value) => (value === base ? "not-a-sha" : value))289 );290291 expect(Result.isFailure(result)).toBeTruthy();292 expect(yield* Ref.get(calls)).toBe(0);293 expect(err.join("\n")).toContain("--base");294 })295 );296297 it.effect(298 "is named by its Cli annotation, and takes the fields it names in order",299 () =>300 Effect.gen(function* () {301 const claimed = yield* Ref.make<readonly unknown[]>([]);302303 const { result } = yield* run(304 Layer.mergeAll(305 unanswered,306 Contracts.toLayerHandler("claim", (payload) =>307 Ref.update(claimed, (all) => [...all, payload]).pipe(308 Effect.andThen(Effect.fail(new AskFull({ ask: payload.ask })))309 )310 )311 ),312 (output) => toCommand(Claim, Effect.service(Client), { output }),313 ["fix-week", "--project", project]314 );315

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

lines 316–320why, one step back
316 expect(result).toStrictEqual(
317 Result.fail(318 Reported.of([new AskFull({ ask: AskId.make("fix-week") })])319 )320 );

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 321–326why, one step back
321 expect(yield* Ref.get(claimed)).toStrictEqual([
322 { ask: AskId.make("fix-week"), project },323 ]);324 })325 );326

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d

lines 327–357why, one step back
327 it.effect(
328 "takes a switch as on when named, and leaves it out otherwise",329 () =>330 Effect.gen(function* () {331 const proposed = yield* Ref.make<readonly unknown[]>([]);332333 const propose = (args: readonly string[]) =>334 run(335 Layer.mergeAll(336 unanswered,337 Contracts.toLayerHandler("proposeAsk", (payload) =>338 Ref.update(proposed, (all) => [...all, payload]).pipe(339 Effect.andThen(Effect.fail(new CapReached({ cap: 2 })))340 )341 )342 ),343 (output) =>344 toCommand(ProposeAsk, Effect.service(Client), { output }),345 ["--project", project, "--want", "Parse ISO weeks.", ...args]346 );347348 yield* propose(["--draft"]);349 yield* propose([]);350351 expect(yield* Ref.get(proposed)).toStrictEqual([352 { draft: true, project, want: "Parse ISO weeks." },353 { project, want: "Parse ISO weeks." },354 ]);355 })356 );357

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 358–503why, one step back
358 it("takes the last word of a two-word name as its own", () => {
359 const output = Effect.succeed<CommandOutput>({360 plan: () => Effect.void,361 refused: () => Effect.void,362 success: () => Effect.void,363 });364365 expect(366 [OpenAsk, ShowAsk, ListAsks].map(367 (rpc) => toCommand(rpc, Effect.service(Client), { output }).name368 )369 ).toStrictEqual(["open", "ask", "asks"]);370 });371372 it.effect("takes nothing when the contract takes nothing", () =>373 Effect.gen(function* () {374 const { printed } = yield* run(375 Layer.mergeAll(376 unanswered,377 Contracts.toLayerHandler("listProjects", () =>378 Effect.succeed({ projects: [] })379 )380 ),381 (output) => toCommand(ListProjects, Effect.service(Client), { output }),382 ["--json"]383 );384385 expect(printed).toHaveLength(1);386 expect(printed[0]?.input).toHaveProperty("data", { projects: [] });387 })388 );389});390391describe("--yes and --dry-run", () => {392 const decideArgs = [393 "--project",394 project,395 "--decision",396 decision,397 "--choice",398 "accept",399 ];400401 it.effect(402 "refuses a contract that needs approval without --yes, before calling it",403 () =>404 Effect.gen(function* () {405 const calls = yield* Ref.make(0);406407 const { printed, result } = yield* run(408 Layer.mergeAll(409 unanswered,410 Contracts.toLayerHandler("decide", () => counting(calls, decided))411 ),412 (output) => toCommand(Decide, Effect.service(Client), { output }),413 decideArgs414 );415416 expect(result).toStrictEqual(417 Result.fail(new ApprovalNeeded({ command: "decide" }))418 );419 expect(yield* Ref.get(calls)).toBe(0);420 expect(printed).toStrictEqual([]);421 })422 );423424 it.effect("calls it with --yes", () =>425 Effect.gen(function* () {426 const calls = yield* Ref.make(0);427428 yield* run(429 Layer.mergeAll(430 unanswered,431 Contracts.toLayerHandler("decide", () => counting(calls, decided))432 ),433 (output) => toCommand(Decide, Effect.service(Client), { output }),434 [...decideArgs, "--yes"]435 );436437 expect(yield* Ref.get(calls)).toBe(1);438 })439 );440441 it.effect(442 "hands the encoded payload to the output's plan under --dry-run, and calls nothing",443 () =>444 Effect.gen(function* () {445 const calls = yield* Ref.make(0);446447 const { printed, result } = yield* run(448 Layer.mergeAll(449 unanswered,450 Contracts.toLayerHandler("decide", () => counting(calls, decided))451 ),452 (output) => toCommand(Decide, Effect.service(Client), { output }),453 [...decideArgs, "--dry-run", "--json"]454 );455456 expect(Result.isSuccess(result)).toBeTruthy();457 expect(yield* Ref.get(calls)).toBe(0);458 expect(printed).toStrictEqual([459 {460 input: {461 command: "decide",462 json: true,463 payload: { choice: "accept", decision, project },464 },465 kind: "plan",466 },467 ]);468 })469 );470471 it.effect(472 "offers no --dry-run on a read, and no --yes where nobody approves",473 () =>474 Effect.gen(function* () {475 const dryRead = yield* run(476 quiet,477 (output) => toCommand(ListAsks, Effect.service(Client), { output }),478 ["--project", project, "--dry-run"]479 );480481 const yesClaim = yield* run(482 quiet,483 (output) => toCommand(Claim, Effect.service(Client), { output }),484 ["fix-week", "--project", project, "--yes"]485 );486487 expect(dryRead.err.join("\n")).toContain("--dry-run");488 expect(yesClaim.err.join("\n")).toContain("--yes");489 expect([dryRead.printed, yesClaim.printed]).toStrictEqual([[], []]);490 })491 );492});493494describe("defaults", () => {495 it.effect(496 "fill a required field left out, and are read only when one is",497 () =>498 Effect.gen(function* () {499 const reads = yield* Ref.make(0);500501 const defaults = {502 fields: { project: "the repo's project" },503 values: Ref.update(reads, (count) => count + 1).pipe(

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 504why, one step back
504 Effect.as({ project: "oscabriel/datekit" })

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 505–512why, one step back
505 ),
506 };507508 const build = (output: Effect.Effect<CommandOutput>) =>509 toCommand(ListAsks, Effect.service(Client), { defaults, output });510511 const filled = yield* run(quiet, build, ["--json"]);512

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 513–518why, one step back
513 const given = yield* run(quiet, build, [
514 "--project",515 "oscabriel/demo",516 "--json",517 ]);518

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 519–521why, one step back
519 expect(
520 [filled, given].map(({ printed }) => printed[0]?.input)521 ).toStrictEqual([

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 522–527why, one step back
522 expect.objectContaining({
523 data: { asks: [listing("oscabriel/datekit")] },524 }),525 expect.objectContaining({526 data: { asks: [listing("oscabriel/demo")] },527 }),

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 528–599why, one step back
528 ]);
529 expect(yield* Ref.get(reads)).toBe(1);530 })531 );532533 it.effect(534 "leave a field they have no value for missing, naming its flag",535 () =>536 Effect.gen(function* () {537 const { printed, result } = yield* run(538 quiet,539 (output) =>540 toCommand(ListAsks, Effect.service(Client), {541 defaults: {542 fields: { project: "the repo's project" },543 values: Effect.succeed({}),544 },545 output,546 }),547 []548 );549550 expect(result).toStrictEqual(551 Result.fail(new MissingValue({ command: "asks", flag: "--project" }))552 );553 expect(printed).toStrictEqual([]);554 })555 );556});557558const commands = (built: Effect.Effect<CommandOutput>) =>559 toCommands(Contracts, Effect.service(Client), {560 exclude: [],561 output: built,562 views: {563 listAsks: (success) =>564 Schema.is(ListAsks.successSchema)(success)565 ? Option.some({ markdown: `${success.asks.length} asks` })566 : Option.none(),567 },568 });569570const root = (built: Effect.Effect<CommandOutput>) =>571 Command.make("root").pipe(572 Command.withSubcommands(commands(built).map(({ command }) => command))573 );574575describe("the group as CLI commands", () => {576 const output = Effect.succeed<CommandOutput>({577 plan: () => Effect.void,578 refused: () => Effect.void,579 success: () => Effect.void,580 });581582 it("projects each contract served on the CLI, but those excluded, at its path", () => {583 const paths = toCommands(Contracts, Effect.service(Client), {584 exclude: ["initProject", "setEnv"],585 output,586 }).map(({ path: words }) => words.join(" "));587588 expect(paths).toStrictEqual([589 "projects",590 "front",591 "asks",592 "ask",593 "status",594 "verdict",595 "landing",596 "credits",597 "today",598 "ledger",599 "env shape",

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d

lines 600–601why, one step back
600 "policy",
601 "proposal",

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 602–603why, one step back
602 "ask open",
603 "propose",

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d

line 604why, one step back
604 "ask draft",

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 605–622why, one step back
605 "ask flag",
606 "decide",607 "claim",608 "release",609 "submit",610 "finish",611 "land",612 "fork",613 "vouch",614 "evidence",615 ]);616 });617618 it.effect("renders each result with the view its tag names", () =>619 Effect.gen(function* () {620 const { printed } = yield* run(quiet, root, [621 "asks",622 "--project",

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 623why, one step back
623 "oscabriel/demo",

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 624–631why, one step back
624 ]);
625626 expect(printed[0]?.input).toHaveProperty("view", {627 markdown: "1 asks",628 });629 })630 );631});