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.
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
Provenance
- Commit
80e98da- Tree
f28ced5- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
a449828
9 files changed+240 added−65 removed
modified:apps/cli/src/main.ts+7 added-2 removed
13 unmodified lines14151617181819202122232425262774 unmodified lines10210310410510110610710810911085 unmodified lines13 unmodified linesimport { CredentialsFile } from "./credentials.ts";import { hook } from "./hook.ts";import { holdStdout, Output, OutputLive } from "./output.ts";import { CurrentMode, Policy } from "./policy.ts";import { isTransportFailure, noPlatformOf, RemoteClient } from "./remote.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 a74 unmodified lines return signIn; }
if (isTransportFailure(failure)) { return `could not reach the platform: ${failure.message}`; return `could not reach the platform: ${transportMessage(failure)}`; }
return String(failure);};85 unmodified linesmodified:apps/cli/src/remote.ts+13 added
50 unmodified lines51 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> =>119 unmodified linesmodified:apps/cli/src/render.ts+25 added-12 removed
18 unmodified lines19 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";27-import { explain, receiptLine } from "@repo/protocol/render";28-import { Array, DateTime, Option, Result, Schema } from "effect";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 311 unmodified lines346 );347 348 /**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 */353 const 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+ );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,18 unmodified linesmodified:apps/cli/src/surfaces.ts+2 added-1 removed
29 unmodified lines30 import type { ChildProcessSpawner } from "effect/process";31 32 import { local } from "./local/index.ts";33 import { Output } from "./output.ts";34-import { views } from "./render.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 unmodified lines78 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. */215 unmodified linesmodified:apps/cli/test/remote-server.ts+29 added-14 removed
7 unmodified lines8 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,125 unmodified lines142 ? 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 before25 unmodified lines195 196 return unknown ? HttpServerResponse.empty({ status: 401 }) : yield* rpc;197 });198 178- const server = yield* Layer.build(179- HttpServer.serve(gate).pipe(Layer.provideMerge(NodeHttpServer.layerTest))180- ).pipe(Effect.orDie);181-182- const { address } = Context.get(server, HttpServer.HttpServer);183-184- 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- );190-191- return { origin, seen: Ref.get(seen) };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 })));modified:apps/cli/test/remote.test.ts+25 added-1 removed
6 unmodified lines7 8 import { Credentials } from "../src/credentials.ts";9 import type { Profile } from "../src/credentials.ts";10 import { RemoteClient } from "../src/remote.ts";11-import { httpPlatform, knownToken, runProgram } from "./remote-server.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(108 unmodified lines129 ]);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())),9 unmodified linesmodified:apps/cli/test/surfaces.test.ts+74 added-32 removed
10 unmodified lines11 RepoPath,12 RequestId,13 } from "@repo/protocol/ids";14 import { DecisionClosed, StaleBase } from "@repo/protocol/refusal";15-import { receiptLine } from "@repo/protocol/render";15+import { explain, receiptLine } from "@repo/protocol/render";16 import { unanswered } from "@repo/protocol/testing";17 import { gitOk } from "@repo/testkit/git";18 import {19 Context,405 unmodified lines425 })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* () {432- const offered = {433- ask,434- base,435- head,436- outcome: Outcome.cases.Checking.make({ stage: "merge" }),437- project,438- requestId,439- };440-441- 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 );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+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.3 import {4+ Array,5 Context,6 Effect,7 Option,8 Predicate,9 Runtime,10 Schema,11 SchemaAST,12 } from "effect";12-import type { Array } from "effect";13 import { Argument, Command, Flag } from "effect/cli";14 import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";15 16 import {77 unmodified lines94 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's275 unmodified lines383 * 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 */391 export const toCommand = <392 R extends CommandRpc,393 ClientR,116 unmodified lines510 )511 )512 );513 514+ const carried = options.refusalsIn?.(success) ?? [];515+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 === undefined18 unmodified lines544 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 18 unmodified lines574 {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 linesmodified:packages/protocol/test/cli.test.ts+42 added
23 unmodified lines24 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,204 unmodified lines237 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",243+ () =>244+ Effect.gen(function* () {245+ const refusal = new StaleBase({ base, conflicts: [path], main });246+247+ const refused = {248+ ask,249+ base,250+ head,251+ outcome: Outcome.cases.Refused.make({ refusals: [refusal] }),252+ project,253+ requestId,254+ };255+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+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* () {284 const calls = yield* Ref.make(0);285 305 unmodified lines