Skip to content
Myr

Print a refused receipt as a refusal that exits 1, and name what failed when the platform can't be reached

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Review of 404 against its issue and AGENTS.md. Two findings, fixed here. - A refused receipt was printed as a success. `finish` and `land` return stage 0–1 refusals as a receipt whose outcome is `Refused`, and `submit` gives a refused request's receipt back on a replay. The CLI printed those on stdout, exited 0, and under `--json` wrote an `ok: true` envelope. The issue says "A refusal is printed once, and the process exits 1". - `toCommand`/`toCommands` take `refusalsIn`: the refusals a success carries go to `output.refused` once, then the command fails with `Reported`. - `apps/cli/src/render.ts` `refusalsIn` reads any receipt (`LandReceipt`'s fields, which an answer's receipt has too). - The submit/finish view keeps only `receiptLine`'s success line. - A transport failure read `could not reach the platform: HttpError: ` with nothing after it, because effect's HTTP reason carries an empty message. `remote.ts` `transportMessage` prints the reason's cause instead: the transport error, or the status and URL. - Tests, each red by assertion first: - protocol `cli.test.ts`: a success carrying refusals goes to `refused` once and fails as `Reported`. - `surfaces.test.ts`: a refused `submit` receipt prints `explain` once on stderr with nothing on stdout and exits 1; under `--json` it is one `ok: false` envelope. - `remote.test.ts`: a platform answering 503 gives one stderr line naming 503 and `/rpc`, and exits 1. `remote-server.ts` gains `failingPlatform` and a shared `serving` helper. - Left for the integrator (in the issue's Comments): `output.ts` re-lays `explain`'s lines as Markdown by matching their text. A Markdown form of `explain` belongs in `protocol/render.ts`, which 402 owns in this group. - bun run fix && bun run verify: green. Debt is at its baseline, gen:check is current, and docs/reference is unchanged.

authored by oscabriel · committed by oscabriel · parent a449828 · Browse files · 9 files+240 added−65 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+240 added−65 removed

  • tests:+170 added−47 removed
  • other:+70 added−18 removed

9 files+240 added−65 removed

modified:apps/cli/src/main.ts+7 added-2 removed
modified:apps/cli/src/remote.ts+13 added
50 unmodified lines
51const isDefect = Schema.is(RpcClientError.RpcClientDefect);5253const isNoPlatformError = Schema.is(NoPlatform);5455const isHttpFailure = Schema.is(HttpClientError.HttpClientErrorSchema);5657/** Whether a call failed in transit (not by the contract's own errors). */58export const isTransportFailure = isClientError;5960/**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 */64export 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;7071/** The usage error a call failed with because no platform was there to call. */72export const noPlatformOf = (73 failure: RpcClientError.RpcClientError74): Option.Option<NoPlatform> =>
119 unmodified lines
modified:apps/cli/src/render.ts+25 added-12 removed
18 unmodified lines
19 TodayOf,20 VerdictOf,21} from "@repo/protocol/contracts";22import type { Contract } from "@repo/protocol/contracts";23import { LandReceipt } from "@repo/protocol/domain/answer";24import type { AnswerReceipt } from "@repo/protocol/domain/answer";25import { DecisionSubject } from "@repo/protocol/domain/decision";26import { Outcome } from "@repo/protocol/domain/outcome";27import { LedgerEntry } from "@repo/protocol/domain/visibility";28import type { Refusal } from "@repo/protocol/refusal";27import { explain, receiptLine } from "@repo/protocol/render";28import { Array, DateTime, Option, Result, Schema } from "effect";29import { receiptLine } from "@repo/protocol/render";30import { DateTime, Option, Result, Schema } from "effect";31import type { Rpc } from "effect/rpc";3233const short = (sha: string) => sha.slice(0, 7);34
311 unmodified lines
346);347348/**349 * Where an offered answer stands, in the line git's `remote:` output gives a348 * push of the same answer; a refused one, as its refusals' explanation.350 * push of the same answer. A refused one never reaches its view: its351 * refusals print as refusals (`refusalsIn`).352 */353const receipt = (offered: AnswerReceipt) =>351 Result.match(receiptLine(offered), {352 onFailure: (refusals) =>353 prose(354 Array.isReadonlyArrayNonEmpty(refusals)355 ? explain(refusals).join("\n")356 : `${offered.ask} was refused`357 ),358 onSuccess: prose,359 });354 prose(355 Result.getOrElse(receiptLine(offered), () => `${offered.ask} was refused`)356 );357358const submitted = viewOf(SubmitAnswer.successSchema, receipt);359360const finished = viewOf(Finish.successSchema, receipt);361362/** Any receipt: an answer's (`submit`, `finish`) has a landing's fields too. */363const isReceipt = Schema.is(LandReceipt);364365/**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 */371export const refusalsIn = (372 success: Rpc.Success<Contract>373): readonly Refusal[] =>374 isReceipt(success) && Outcome.guards.Refused(success.outcome)375 ? success.outcome.refusals376 : [];377378/** Each contract's view, by tag. */379export const views = {380 claim,381 credits,
18 unmodified lines
modified:apps/cli/src/surfaces.ts+2 added-1 removed
29 unmodified lines
30import type { ChildProcessSpawner } from "effect/process";3132import { local } from "./local/index.ts";33import { Output } from "./output.ts";34import { views } from "./render.ts";34import { refusalsIn, views } from "./render.ts";35import { repoContext } from "./repo-context.ts";3637/** The folder the CLI stands in: the process's own, unless a test says otherwise. */38export const WorkingDirectory = Context.Reference<string>(
39 unmodified lines
78const projected = toCommands(Contracts, Effect.service(Client), {79 defaults: fromRepoContext,80 exclude: wrapped,81 output: Effect.service(Output),82 refusalsIn,83 views,84});8586/** What a group of commands that is no command itself is for, by its word. */
215 unmodified lines
modified:apps/cli/test/remote-server.ts+29 added-14 removed
7 unmodified lines
8import { Client, Contracts } from "@repo/protocol/contracts";9import { Handle } from "@repo/protocol/ids";10import { Person } from "@repo/protocol/principal";11import { asTester } from "@repo/protocol/testing";12import type { Scope } from "effect";13import {14 Context,15 Effect,16 Exit,
125 unmodified lines
142 ? Option.some(Person.make({ handle: Handle.make("tester") }))143 : Option.none()144 );145146/** `app` served on an ephemeral port for the test's scope: returns its origin. */147const 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);158159 const { address } = Context.get(server, HttpServer.HttpServer);160161 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 });165166/**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 before
25 unmodified lines
195196 return unknown ? HttpServerResponse.empty({ status: 401 }) : yield* rpc;197 });198178 const server = yield* Layer.build(179 HttpServer.serve(gate).pipe(Layer.provideMerge(NodeHttpServer.layerTest))180 ).pipe(Effect.orDie);181182 const { address } = Context.get(server, HttpServer.HttpServer);183184 const origin =185 "port" in address186 ? `http://127.0.0.1:${address.port}`187 : yield* Effect.die(188 "the test platform listens on a socket, not a port"189 );190191 return { origin, seen: Ref.get(seen) };199 return { origin: yield* serving(gate), seen: Ref.get(seen) };200 });201202/**203 * A platform that answers every request with `status` and an empty body, as204 * a platform that is down does: returns its origin.205 */206export const failingPlatform = (status: number) =>207 serving(Effect.succeed(HttpServerResponse.empty({ status })));
modified:apps/cli/test/remote.test.ts+25 added-1 removed
6 unmodified lines
78import { Credentials } from "../src/credentials.ts";9import type { Profile } from "../src/credentials.ts";10import { RemoteClient } from "../src/remote.ts";11import { httpPlatform, knownToken, runProgram } from "./remote-server.ts";11import {12 failingPlatform,13 httpPlatform,14 knownToken,15 runProgram,16} from "./remote-server.ts";17import type { Handlers } from "./remote-server.ts";1819/** `listAsks` (public) lists one ask; `status` (signed in) shows nothing yet. */20const handlers: Handlers = Layer.mergeAll(
108 unmodified lines
129 ]);130 }).pipe(Effect.scoped)131 );132133 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);138139 const run = yield* runProgram(["asks", "--project", "datekit"], {140 client: remote(holding(Option.none()), { [urlVariable]: origin }),141 handlers,142 });143144 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 );151152 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())),
9 unmodified lines
modified:apps/cli/test/surfaces.test.ts+74 added-32 removed
10 unmodified lines
11 RepoPath,12 RequestId,13} from "@repo/protocol/ids";14import { DecisionClosed, StaleBase } from "@repo/protocol/refusal";15import { receiptLine } from "@repo/protocol/render";15import { explain, receiptLine } from "@repo/protocol/render";16import { unanswered } from "@repo/protocol/testing";17import { gitOk } from "@repo/testkit/git";18import {19 Context,
405 unmodified lines
425 })426 );427});428429const submitArgs = [430 "submit",431 "--project",432 project,433 "--ask",434 ask,435 "--base",436 base,437 "--head",438 head,439 "--requestId",440 requestId,441];442443/** An answer's receipt, standing at `outcome`. */444const receiptAt = (outcome: Outcome) => ({445 ask,446 base,447 head,448 outcome,449 project,450 requestId,451});452453/** A platform whose `submitAnswer` gives `receipt` back. */454const receiving = (receipt: ReturnType<typeof receiptAt>) =>455 Layer.mergeAll(456 unanswered,457 Contracts.toLayerHandler("submitAnswer", () => Effect.succeed(receipt))458 );459460describe("an answer offered with submit", () => {461 it.effect("prints the same line git's remote: output gives its push", () =>462 Effect.gen(function* () {432 const offered = {433 ask,434 base,435 head,436 outcome: Outcome.cases.Checking.make({ stage: "merge" }),437 project,438 requestId,439 };440441 const run = yield* runProgram(442 [443 "submit",444 "--project",445 project,446 "--ask",447 ask,448 "--base",449 base,450 "--head",451 head,452 "--requestId",453 requestId,454 ],455 {456 handlers: Layer.mergeAll(457 unanswered,458 Contracts.toLayerHandler("submitAnswer", () =>459 Effect.succeed(offered)460 )461 ),462 }463 const offered = receiptAt(464 Outcome.cases.Checking.make({ stage: "merge" })465 );466467 const run = yield* runProgram(submitArgs, {468 handlers: receiving(offered),469 });470471 expect(run.code).toBe(0);472 expect(Result.map(receiptLine(offered), (line) => [line])).toStrictEqual(473 Result.succeed(run.out)474 );475 })476 );477478 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 });487488 expect(run.code).toBe(1);489 expect(run.out).toStrictEqual([]);490 expect(run.err).toStrictEqual(explain([refusal]));491 })492 );493494 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 });501502 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+23 added-3 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.3import {4 Array,5 Context,6 Effect,7 Option,8 Predicate,9 Runtime,10 Schema,11 SchemaAST,12} from "effect";12import type { Array } from "effect";13import { Argument, Command, Flag } from "effect/cli";14import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";1516import {
77 unmodified lines
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}105106/**107 * Each contract's result as prose, by tag. A view reads any contract's
275 unmodified lines
383 * 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 encoded381 * payload and calls nothing. A refusal goes to `output.refused` once, and382 * the command fails with `Reported`.387 * 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 */391export const toCommand = <392 R extends CommandRpc,393 ClientR,
116 unmodified lines
510 )511 )512 );513514 const carried = options.refusalsIn?.(success) ?? [];515516 if (Array.isReadonlyArrayNonEmpty(carried)) {517 yield* output.refused({ command, json, refusals: carried });518519 return yield* new Reported();520 }521522 const data = yield* Effect.orDie(encodeSuccess(success));523524 const view = Option.getOrElse(525 options.render === undefined
18 unmodified lines
544export 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
18 unmodified lines
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,
4 unmodified lines
modified:packages/protocol/test/cli.test.ts+42 added
23 unmodified lines
24 OpenAsk,25 ShowAsk,26 SubmitAnswer,27} from "../src/contracts.ts";28import { Outcome } from "../src/domain/outcome.ts";29import {30 AskId,31 CommitSha,32 DecisionId,
204 unmodified lines
237 expect({ err, out }).toStrictEqual({ err: [], out: [] });238 })239 );240241 it.effect(242 "hands the refusals a success carries to the output once, and fails as reported",243 () =>244 Effect.gen(function* () {245 const refusal = new StaleBase({ base, conflicts: [path], main });246247 const refused = {248 ask,249 base,250 head,251 outcome: Outcome.cases.Refused.make({ refusals: [refusal] }),252 project,253 requestId,254 };255256 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 );271272 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 );281282 it.effect("refuses a malformed commit id before calling anything", () =>283 Effect.gen(function* () {284 const calls = yield* Ref.make(0);285
305 unmodified lines