Explain a line with `<cli> why`, and store a write-only env value with `<cli> env set` that nobody can read back
Before adoption: this commit came in with the history the project adopted, so no landing records it.
W4 group A (414). Both stubs 401 left in apps/cli/src/local are replaced; local/index.ts and main.ts are unchanged. - `why <path:line> [--project] [--json]`: `parseLocation` splits at the last colon (a line from 1, no sign, safe integer); `git ls-tree --full-name HEAD` gives the repo-root path and `git blame --porcelain -L n,n HEAD` the commit; `landing({project, sha})` gives the record. UnknownCommit falls back to the commit's own trailers through @repo/git's parseTrailers and says it is not a platform landing. A verdict note under refs/notes/<slug>, when fetched, is added as `data.note`; the landing record stays the source. `data` is one schema (LineOrigin: path, line, sha, landing?, trailers?, note?) encoded once; the view is Markdown for agents (ask, author, each credit role, Assisted-by, verdict) and text for a person. - `env set <KEY> [--project] [--acknowledge-short] [--yes] [--dry-run] [--json]`: the value comes only from stdin, less one trailing newline (CRLF counts as one), as a Redacted straight into setEnv's payload. A person at a terminal gets Prompt.Hidden, not Prompt.Password: Password prints one `*` per character, which tells the length. Under an agent or a script a terminal on stdin is a usage error telling the person to pipe the value. A value typed as an argument is caught by a variadic `not-the-value` positional, since effect/cli's UnexpectedArgument message would quote it. Without --yes: exit 2, nothing read or called. --dry-run plans `{key, project, value: "<redacted>"}` (acknowledgeShort only when set, as the real payload) and reads nothing. Refusals (NotSensitive, ValueTooShort, …) print once through Output.refused and exit 1. The reply is only `{key, setBy, setAt}`. No read-back of any kind. - Usage errors print one stderr line through Output.note, then die with UsageError (Runtime.errorExitCode 2, errorReported false): 401's `program` turns every typed failure into Reported (exit 1) and lets defects through, and main.ts is 404's. 414's Comments ask the integrator to make it a typed failure once 404's program maps usage errors to exit 2. - Shared helpers sit in why.ts (the territory is two files) and env-set.ts imports them: WorkingDirectory (a Context.Reference, default "." so git runs in the process's folder; tests provide a temp repo), usage/UsageError, reportRefusals, projectOf (--project, else the repo's platform remote). 405 and 413 need the same; hoisting is in the Comments. - Outside the territory: apps/cli/test/main.test.ts drops the `why` and `env set` rows from the stub list, since they no longer die (merge note in the Comments). - Tests, each red by assertion first (the stubs died; parseLocation returned none): apps/cli/test/local/why.test.ts (parseLocation cases; it.live on a two-commit temp repo with Asked-by/Signed-off-by/Assisted-by trailers: one envelope with the landing record and the call's payload, Markdown rows for an agent, the UnknownCommit fallback in JSON and text, exit 2 for a line past the end, a file not in HEAD and no line with no call, a fetched note's verdict in data.note, UnknownProject printed once with exit 1) and apps/cli/test/local/env-set.test.ts (the exact payload with the value opened from its Redacted and no acknowledgeShort key, the success envelope, the value absent from stdout, stderr, every Output call, terminal frames and log lines recorded at level All; a value as an argument, no --yes, dry-run, NotSensitive and ValueTooShort once, --acknowledge-short, agent with a terminal on stdin never prompting, a hidden prompt that shows neither the value nor a mask). The platform is faked in process with RpcTest.makeClient(Contracts) over `unanswered` plus the one handler; exit codes are read from program(argv)'s Exit by the runtime's own rule. - ASSUMPTION: `why` numbers lines as committed at HEAD (blame of HEAD, not the work tree), so an uncommitted edit never yields a zero sha. - ASSUMPTION: an empty value is a usage error; emptiness is the only property of the value the CLI looks at. - bun run fix && bun run verify green: cli 71 tests (45 + 28 new − 2 stub rows); gen:check current, imports:check no violations, debt at baseline, brand:check no leaks, bytes platform 1,513,290 of 1,665,000.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+1432 added−12 removed
- tests:+848 added−2 removed
- other:+584 added−10 removed
Provenance
- Commit
77bb849- Tree
09792b3- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
650cb35
5 files changed+1432 added−12 removed
modified:apps/cli/src/local/env-set.ts+179 added-5 removed
12123456789101112131415161718192021224562324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185import { Effect } from "effect";import { Command } from "effect/cli";/** * `<cli> env set <KEY>`: stores a write-only value for a project's * `@sensitive` env item. The value arrives on stdin (or, for a person at a * terminal, through a prompt that shows nothing typed) and leaves only as * the `setEnv` payload's `Redacted`: it is never an argument, never printed, * logged, hashed or measured, and nothing reads it back. The reply says who * set which key, and when. */import { Brand } from "@repo/brand";import { Client, SetEnv } from "@repo/protocol/contracts";import { EnvKey, ProjectName } from "@repo/protocol/ids";import { DateTime, Effect, Option, Redacted, Schema, Stdio, Stream,} from "effect";import { Argument, Command, Flag, Prompt } from "effect/cli";
/** `env set`: issue 414 replaces this stub. */export const envSet = Command.make("set", {}, () => Effect.die("not built: issue 414")import { Output } from "../output.ts";import type { Mode } from "../output.ts";import { repoContext } from "../repo-context.ts";import { WorkingDirectory, projectOf, reportRefusals, usage } from "./why.ts";
const command = "env set";
const encodeSet = Schema.encodeEffect(SetEnv.successSchema);
/** How a value is piped in, for the person who tried another way. */const pipeHint = (key: EnvKey) => `printf '%s\\n' "$VALUE" | ${Brand.cli} ${command} ${key} --yes`;
/** * The value from a person at a terminal, through a prompt that shows nothing * typed (not even a mask, which would tell its length). An agent or a * script must never be prompted, so it is told to pipe the value instead. */const prompted = (key: EnvKey, mode: Mode) => mode === "human" ? Prompt.run( Prompt.Hidden({ message: `Value for ${key} (nothing you type is shown)`, }) ) : usage( `${Brand.cli} never prompts an agent or a script, so pipe the value of ${key} on stdin: ${pipeHint(key)}` );
/** * The value from stdin, less one trailing newline; a terminal on stdin means * nobody piped it, so a person is prompted and anyone else told to pipe it. */const readValue = (key: EnvKey, mode: Mode) => Effect.gen(function* () { const stdio = yield* Stdio.Stdio;
const value = (yield* stdio.stdinIsTerminal) ? yield* prompted(key, mode) : yield* stdio.stdin.pipe( Stream.decodeText(), Stream.mkString, Effect.map((text) => Redacted.make(text.replace(/\r?\n$/u, ""))) );
// Whether anything arrived at all; nothing else about it is looked at. return Redacted.value(value) === "" ? yield* usage(`No value for ${key} arrived: ${pipeHint(key)}`) : value; });
/** The project named, or the one the repo's platform remote names. */const projectFor = (named: Option.Option<ProjectName>) => Effect.gen(function* () { if (Option.isSome(named)) { return named.value; }
const cwd = yield* WorkingDirectory;
const context = yield* repoContext(cwd).pipe( Effect.asSome, Effect.catchTag("NotARepo", () => Effect.succeedNone) );
return yield* projectOf(named, context); });
export const envSet = Command.make( "set", { acknowledgeShort: Flag.Boolean("acknowledge-short").pipe( Flag.withDefault(false), Flag.withDescription( "Store a value shorter than the item's minimum anyway" ) ), dryRun: Flag.Boolean("dry-run").pipe( Flag.withDefault(false), Flag.withDescription( "Print what would be sent, value redacted; send nothing" ) ), json: Flag.Boolean("json").pipe( Flag.withDefault(false), Flag.withDescription("Print machine-readable JSON") ), key: Argument.String("key").pipe( Argument.withSchema(EnvKey), Argument.withDescription("The @sensitive env item to set") ), project: Flag.String("project").pipe( Flag.withSchema(ProjectName), Flag.optional, Flag.withDescription( "The project; the repo's platform remote names it by default" ) ), // Caught here, so the parser never echoes a value typed as an argument. stray: Argument.String("not-the-value").pipe( Argument.variadic(), Argument.withDescription( "Refused: the value is read from stdin, never from arguments" ) ), yes: Flag.Boolean("yes").pipe( Flag.withDefault(false), Flag.withDescription("Store the value (it needs approval)") ), }, ({ acknowledgeShort, dryRun, json, key, project, stray, yes }) => Effect.gen(function* () { if (stray.length > 0) { return yield* usage( `${Brand.cli} ${command} takes the value on stdin, never as an argument, so it stays out of shell history and process lists: ${pipeHint(key)}` ); }
const name = yield* projectFor(project); const output = yield* Output; const acknowledged = acknowledgeShort ? { acknowledgeShort } : {};
if (dryRun) { return yield* output.plan({ command, json, payload: { ...acknowledged, key, project: name, value: "<redacted>" }, }); }
if (!yes) { return yield* usage( `${command} stores a value for ${key}: add --yes to store it, or --dry-run to see what would be sent.` ); }
const value = yield* readValue(key, output.mode); const client = yield* Client;
const set = yield* client.setEnv({ ...acknowledged, key, project: name, value, });
const at = DateTime.formatIso(set.setAt);
return yield* output.success({ command, data: yield* encodeSet(set).pipe(Effect.orDie), json, view: { markdown: `\`${set.key}\` on ${name} was set by ${set.setBy} at ${at}. Nobody can read it back.`, text: `${set.key} on ${name} was set by ${set.setBy} at ${at}. Nobody can read it back.`, }, }); }).pipe(reportRefusals(command, json))).pipe( Command.withDescription( "Set a sensitive env item's value from stdin; nobody can read it back." ));modified:apps/cli/src/local/why.ts+405 added-5 removed
1+/**2+ * `<cli> why <path>:<line>`: which landing put a line there, and why. git3+ * blame names the commit; the platform's landing record names the ask, the4+ * accountable author, every credit and the verdict. A commit the platform5+ * did not land is said to be none of its landings, with the trailers its6+ * author wrote. A verdict note fetched from the platform rides along, but7+ * the landing record is the source.8+ */9+import { notesRef } from "@repo/git/notes";10+import { parseTrailers } from "@repo/git/trailers";11+import type { Trailer } from "@repo/git/trailers";12+import { Client } from "@repo/protocol/contracts";13+import { Verdict } from "@repo/protocol/domain/answer";14+import { LandingView } from "@repo/protocol/domain/landing";15+import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";16+import { Refusal } from "@repo/protocol/refusal";17+import {18+ Context,19+ DateTime,20+ Effect,21+ Option,22+ Runtime,23+ Schema,24+ Stream,1-import { Effect } from "effect";2-import { Command } from "effect/cli";25+} from "effect";26+import { Argument, Command, Flag } from "effect/cli";27+import { ChildProcess, ChildProcessSpawner } from "effect/process";28 4-/** `why`: issue 414 replaces this stub. */5-export const why = Command.make("why", {}, () =>6- Effect.die("not built: issue 414")29+import { Output, Reported } from "../output.ts";30+import type { View } from "../output.ts";31+import { repoContext } from "../repo-context.ts";32+import type { RepoContext } from "../repo-context.ts";33+34+/**35+ * Where a local command runs git: the process's own folder unless a caller36+ * (a test) provides another. Shared with `env set`.37+ */38+export const WorkingDirectory = Context.Reference<string>(39+ "cli/WorkingDirectory",40+ { defaultValue: () => "." }41+);42+43+/**44+ * A command used wrongly: its one line is already on stderr, and the45+ * process exits 2 with nothing more printed. Shared with `env set`.46+ */47+export class UsageError extends Schema.TaggedError<UsageError>()("UsageError", {48+ reason: Schema.String,49+}) {50+ override readonly [Runtime.errorExitCode] = 2;51+ override readonly [Runtime.errorReported] = false;52+}53+54+/**55+ * Prints `reason` once on stderr and ends the command with exit 2. It ends56+ * as a defect only because `program` turns every typed failure into57+ * `Reported` (exit 1) and lets defects through; 414's Comments ask for a58+ * typed failure once `program` maps usage errors to exit 2 (issue 404).59+ */60+export const usage = (reason: string) =>61+ Output.use((output) => output.note(reason)).pipe(62+ Effect.andThen(Effect.die(new UsageError({ reason })))63+ );64+65+const isRefusal = Schema.is(Refusal);66+67+/**68+ * Prints a refusal the platform answered with, once, through `Output`, and69+ * ends with `Reported` (exit 1). Shared with `env set`.70+ */71+export const reportRefusals =72+ (command: string, json: boolean) =>73+ <A, E, R>(effect: Effect.Effect<A, E, R>) =>74+ effect.pipe(75+ Effect.catchIf(isRefusal, (refusal) =>76+ Output.use((output) =>77+ output.refused({ command, json, refusals: [refusal] })78+ ).pipe(Effect.andThen(Effect.fail(new Reported())))79+ )80+ );81+82+/**83+ * The project a command acts on: `--project`, else the one the repo's84+ * platform remote names. Shared with `env set`.85+ */86+export const projectOf = (87+ named: Option.Option<ProjectName>,88+ context: Option.Option<RepoContext>89+) =>90+ Option.match(91+ Option.orElse(named, () =>92+ Option.flatMap(context, ({ repo }) =>93+ Option.map(repo, ({ project }) => project)94+ )95+ ),96+ {97+ onNone: () =>98+ usage(99+ "Name the project with --project <name>: this repo has no remote on a platform."100+ ),101+ onSome: Effect.succeed,102+ }103+ );104+105+// A path, then a line number from 1 with no sign or leading zero. The path106+// takes everything before the last colon, so a path may hold one.107+const LOCATION = /^(?<path>.+):(?<line>[1-9][0-9]*)$/u;108+109+/** A line of a file as people and compilers write it: `src/week.ts:42`. */110+export const parseLocation = (111+ text: string112+): Option.Option<{ readonly path: RepoPath; readonly line: number }> => {113+ const groups = LOCATION.exec(text)?.groups;114+ const line = Number(groups?.line);115+116+ return groups?.path === undefined || !Number.isSafeInteger(line)117+ ? Option.none()118+ : Option.some({ line, path: RepoPath.make(groups.path) });119+};120+121+/** What `why` found: the line's commit and what is known of it. */122+const LineOrigin = Schema.Struct({123+ /** The platform's record, when the commit is one of its landings. */124+ landing: Schema.optionalKey(LandingView),125+ line: Schema.Int,126+ /** The verdict note on the commit, when one was fetched. */127+ note: Schema.optionalKey(Verdict),128+ path: RepoPath,129+ sha: CommitSha,130+ /** The commit's own trailers, when the platform did not land it. */131+ trailers: Schema.optionalKey(132+ Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.String }))133+ ),134+});135+136+type LineOrigin = typeof LineOrigin.Type;137+138+const encodeOrigin = Schema.encodeEffect(LineOrigin);139+140+const decodeNote = Schema.decodeOption(Schema.fromJsonString(Verdict));141+142+const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>143+ bytes.pipe(Stream.decodeText(), Stream.mkString);144+145+/** Runs git in `cwd` to the end: its stdout and exit code; stderr is dropped. */146+const git = (cwd: string, args: readonly string[]) =>147+ Effect.scoped(148+ Effect.gen(function* () {149+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;150+151+ const child = yield* spawner.spawn(152+ ChildProcess.make("git", args, {153+ cwd,154+ stderr: "ignore",155+ stdin: "ignore",156+ })157+ );158+159+ const [stdout, exitCode] = yield* Effect.all(160+ [text(child.stdout), child.exitCode],161+ { concurrency: "unbounded" }162+ );163+164+ return { exitCode, stdout };165+ })166+ );167+168+/** The line is in no file committed at HEAD. */169+const noSuchLine = (location: string) =>170+ usage(171+ `${location} is not a line of a file committed at HEAD: ${location.replace(/:[0-9]+$/u, "")} is not there, or is shorter.`172+ );173+174+/** `path` as the repo names it from its root, if HEAD holds it. */175+const pathAtHead = (cwd: string, path: RepoPath, location: string) =>176+ Effect.flatMap(177+ git(cwd, [178+ "ls-tree",179+ "--full-name",180+ "--name-only",181+ "-z",182+ "HEAD",183+ "--",184+ path,185+ ]),186+ ({ exitCode, stdout }) => {187+ const [only, ...more] = stdout.split("\0").filter((name) => name !== "");188+189+ return exitCode === 0 && only !== undefined && more.length === 0190+ ? Effect.succeed(RepoPath.make(only))191+ : noSuchLine(location);192+ }193+ );194+195+// git blame's porcelain opens with the line's commit, then its line numbers.196+const BLAMED = /^(?<sha>[0-9a-f]{40}) /u;197+198+/** The commit that last changed line `line` of `path` at HEAD. */199+const blamed = (cwd: string, path: RepoPath, line: number, location: string) =>200+ Effect.flatMap(201+ git(cwd, [202+ "blame",203+ "--porcelain",204+ "-L",205+ `${line},${line}`,206+ "HEAD",207+ "--",208+ path,209+ ]),210+ ({ exitCode, stdout }) => {211+ const sha = BLAMED.exec(stdout)?.groups?.sha;212+213+ return exitCode === 0 && sha !== undefined214+ ? Effect.succeed(CommitSha.make(sha))215+ : noSuchLine(location);216+ }217+ );218+219+/** The trailers `sha`'s author wrote, as git reads them. */220+const trailersOf = (cwd: string, sha: CommitSha) =>221+ Effect.map(git(cwd, ["log", "-1", "--format=%B", sha]), ({ stdout }) =>222+ parseTrailers(stdout)223+ );224+225+/** The verdict note on `sha`, if one was fetched and it reads as a verdict. */226+const noteOn = (cwd: string, sha: CommitSha) =>227+ Effect.flatMap(228+ git(cwd, ["notes", `--ref=${notesRef}`, "show", sha]),229+ ({ exitCode, stdout }) => {230+ if (exitCode !== 0) {231+ return Effect.succeedNone;232+ }233+234+ const note = decodeNote(stdout.trim());235+236+ return Option.isSome(note)237+ ? Effect.succeed(note)238+ : Output.use((output) =>239+ output.note(240+ `The note on ${sha} in ${notesRef} is not a verdict; it is left out.`241+ )242+ ).pipe(Effect.as(Option.none<Verdict>()));243+ }244+ );245+246+const short = (sha: string) => sha.slice(0, 7);247+248+/** One fact about the line, as a list item. */249+interface Row {250+ readonly label: string;251+ readonly value: string;252+ /** Code in Markdown: an id or a path. */253+ readonly code?: boolean;254+}255+256+const verdictRow = (verdict: Verdict): Row => ({257+ label: "Verdict",258+ value: [259+ `${verdict.outcome._tag} at the ${verdict.stage} stage`,260+ ...verdict.lanes.map(({ lane, result }) => `${lane} ${result}`),261+ ].join(", "),262+});263+264+const landingRows = (landing: LandingView): readonly Row[] => [265+ landing.ask === undefined266+ ? { label: "Ask", value: "none (a decider's own landing)" }267+ : { code: true, label: "Ask", value: landing.ask },268+ { label: "Author", value: landing.author },269+ ...landing.credits.map(({ handle, role }) => ({270+ label: role,271+ value: handle,272+ })),273+ ...landing.assisted.map(({ harness, model, verified }) => ({274+ label: "Assisted-by",275+ value: `${harness}${model === undefined ? "" : `:${model}`} (${verified ? "verified" : "claimed"})`,276+ })),277+ ...(landing.heldBackTrailer === undefined278+ ? []279+ : [{ label: "Held-back", value: landing.heldBackTrailer }]),280+];281+282+const trailerRows = (trailers: readonly Trailer[]): readonly Row[] =>283+ trailers.map(({ key, value }) => ({ label: key, value }));284+285+/** The line's story, in Markdown for agents and plain text for a person. */286+const viewOf = (origin: LineOrigin): View => {287+ const at = `${origin.path}:${origin.line}`;288+ const commit = short(origin.sha);289+ const verdict = origin.note ?? origin.landing?.verdict;290+291+ const [markdown, plain] = Option.match(292+ Option.fromUndefinedOr(origin.landing),293+ {294+ onNone: () => [295+ `\`${at}\` comes from commit \`${commit}\`, which is not a platform landing: the platform keeps no record of it, so its trailers are only what its author wrote.`,296+ `${at} comes from commit ${commit}, which is not a platform landing: the platform keeps no record of it, so its trailers are only what its author wrote.`,297+ ],298+ onSome: ({ landedAt }) => [299+ `\`${at}\` came to main in landing \`${commit}\`, on ${DateTime.formatIso(landedAt)}.`,300+ `${at} came to main in landing ${commit}, on ${DateTime.formatIso(landedAt)}.`,301+ ],302+ }303+ );304+305+ const rows = [306+ ...(origin.landing === undefined ? [] : landingRows(origin.landing)),307+ ...trailerRows(origin.trailers ?? []),308+ ...(verdict === undefined ? [] : [verdictRow(verdict)]),309+ ];310+311+ const empty =312+ origin.landing === undefined && (origin.trailers ?? []).length === 0313+ ? ["It carries no trailers."]314+ : [];315+316+ return {317+ markdown: [318+ markdown,319+ "",320+ ...rows.map(321+ ({ code, label, value }) =>322+ `- ${label}: ${code === true ? `\`${value}\`` : value}`323+ ),324+ ...empty,325+ ].join("\n"),326+ text: [327+ plain,328+ ...rows.map(({ label, value }) => ` ${label}: ${value}`),329+ ...empty,330+ ].join("\n"),331+ };332+};333+334+export const why = Command.make(335+ "why",336+ {337+ json: Flag.Boolean("json").pipe(338+ Flag.withDefault(false),339+ Flag.withDescription("Print machine-readable JSON")340+ ),341+ location: Argument.String("location").pipe(342+ Argument.withMetavar("path:line"),343+ Argument.withDescription(344+ "A line of a file as committed at HEAD, such as src/week.ts:42"345+ )346+ ),347+ project: Flag.String("project").pipe(348+ Flag.withSchema(ProjectName),349+ Flag.optional,350+ Flag.withDescription(351+ "The project whose landings to ask about; the repo's platform remote names it by default"352+ )353+ ),354+ },355+ ({ json, location, project }) =>356+ Effect.gen(function* () {357+ const at = yield* Option.match(parseLocation(location), {358+ onNone: () =>359+ usage(360+ `${location} is not path:line; write one such as src/week.ts:42.`361+ ),362+ onSome: Effect.succeed,363+ });364+365+ const cwd = yield* WorkingDirectory;366+ const context = yield* repoContext(cwd);367+ const name = yield* projectOf(project, Option.some(context));368+ const path = yield* pathAtHead(cwd, at.path, location);369+ const sha = yield* blamed(cwd, at.path, at.line, location);370+ const client = yield* Client;371+372+ const landing = yield* client.landing({ project: name, sha }).pipe(373+ Effect.map(({ landing: found }) => Option.some(found)),374+ Effect.catchTag("UnknownCommit", () => Effect.succeedNone)375+ );376+377+ const trailers = Option.isNone(landing)378+ ? Option.some(yield* trailersOf(cwd, sha))379+ : Option.none();380+381+ const note = yield* noteOn(cwd, sha);382+383+ const origin: LineOrigin = {384+ line: at.line,385+ path,386+ sha,387+ ...Option.match(landing, {388+ onNone: () => ({}),389+ onSome: (found) => ({ landing: found }),390+ }),391+ ...Option.match(note, {392+ onNone: () => ({}),393+ onSome: (verdict) => ({ note: verdict }),394+ }),395+ ...Option.match(trailers, {396+ onNone: () => ({}),397+ onSome: (found) => ({ trailers: found }),398+ }),399+ };400+401+ const data = yield* encodeOrigin(origin).pipe(Effect.orDie);402+403+ yield* Output.use((output) =>404+ output.success({ command: "why", data, json, view: viewOf(origin) })405+ );406+ }).pipe(reportRefusals("why", json))407 ).pipe(408 Command.withDescription(409 "Explain a line: the ask, the answer and the people that landed it."410 )1 unmodified lineadded:apps/cli/test/local/env-set.test.ts+392 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import { Client, Contracts } from "@repo/protocol/contracts";5+import type { SetEnv } from "@repo/protocol/contracts";6+import { Envelope } from "@repo/protocol/envelope";7+import { EnvKey, Handle } from "@repo/protocol/ids";8+import { NotSensitive, ValueTooShort } from "@repo/protocol/refusal";9+import { explain } from "@repo/protocol/render";10+import { asTester, unanswered } from "@repo/protocol/testing";11+import {12+ Cause,13+ DateTime,14+ Effect,15+ Exit,16+ Layer,17+ Logger,18+ Option,19+ Queue,20+ Redacted,21+ Ref,22+ References,23+ Runtime,24+ Schema,25+ Stdio,26+ Stream,27+ Terminal,28+} from "effect";29+import { CliOutput } from "effect/cli";30+import { RpcTest } from "effect/rpc";31+import type { Rpc } from "effect/rpc";32+import { TestConsole } from "effect/testing";33+34+import { program } from "../../src/main.ts";35+import { Output, OutputPlain } from "../../src/output.ts";36+import type { Mode } from "../../src/output.ts";37+38+/** A value no output, note or log line may ever hold. */39+const secret = "sk_live_0123456789abcdef";40+41+const key = EnvKey.make("SENTRY_AUTH_TOKEN");42+43+const setAt = DateTime.makeUnsafe("2026-10-07T09:00:00Z");44+45+/** A person piping the value in, as `printf '…\n' |` does. */46+const piped = Stream.make(new TextEncoder().encode(`${secret}\n`));47+48+type Payload = Rpc.Payload<typeof SetEnv>;49+50+/** What the platform answers `setEnv` with. */51+type Answer = Effect.Effect<52+ Rpc.Success<typeof SetEnv>,53+ NotSensitive | ValueTooShort54+>;55+56+const stored: Answer = Effect.succeed({57+ key,58+ setAt,59+ setBy: Handle.make("alice"),60+});61+62+/** One call through `Output`, as the command made it. */63+interface Printed {64+ readonly method: "success" | "refused" | "plan" | "note";65+ /** The call's input: a note's text, or the others' object. */66+ readonly input: object | string;67+}68+69+/**70+ * How one run went: its exit code, what reached stdout, stderr and the71+ * logger, what the platform was asked, and what the command handed `Output`.72+ */73+interface Ran {74+ readonly code: number;75+ readonly out: string;76+ readonly err: string;77+ readonly logged: string;78+ readonly calls: readonly Payload[];79+ readonly printed: readonly Printed[];80+ readonly shown: string;81+}82+83+interface Setup {84+ /** Who reads: 401's person at a terminal, or 404's agent policy. */85+ readonly mode?: Mode;86+ readonly stdin?: Stream.Stream<Uint8Array>;87+ readonly stdinIsTerminal?: boolean;88+ /** What a person types at the hidden prompt, key by key. */89+ readonly typed?: string;90+ readonly answer?: Answer;91+}92+93+/** How the process would exit, by the runtime's own rule. */94+const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>95+ Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));96+97+const press = (name: string, input: Option.Option<string>) => ({98+ input,99+ key: { ctrl: false, meta: false, name, shift: false },100+});101+102+/**103+ * Runs `<cli> env set …` with `setup`'s stdin, terminal and platform, and104+ * returns everything it printed, logged and asked.105+ */106+const run = (args: readonly string[], setup: Setup = {}) =>107+ Effect.gen(function* () {108+ const calls = yield* Ref.make<readonly Payload[]>([]);109+ const printed = yield* Ref.make<readonly Printed[]>([]);110+ const shown = yield* Ref.make<readonly string[]>([]);111+ const logged: string[] = [];112+113+ const record = (method: Printed["method"], input: Printed["input"]) =>114+ Ref.update(printed, (all) => [...all, { input, method }]);115+116+ // 401's plain output, recorded, as whichever reader `setup` names.117+ const output = Layer.effect(118+ Output,119+ Effect.gen(function* () {120+ const plain = yield* Effect.service(Output);121+122+ return {123+ mode: setup.mode ?? "human",124+ note: (text) =>125+ Effect.andThen(record("note", text), plain.note(text)),126+ plan: (input) =>127+ Effect.andThen(record("plan", input), plain.plan(input)),128+ refused: (input) =>129+ Effect.andThen(record("refused", input), plain.refused(input)),130+ success: (input) =>131+ Effect.andThen(record("success", input), plain.success(input)),132+ } satisfies Output["Service"];133+ })134+ ).pipe(Layer.provide(OutputPlain));135+136+ const terminal = Layer.succeed(Terminal.Terminal)(137+ Terminal.make({138+ columns: Effect.succeed(80),139+ display: (text) => Ref.update(shown, (all) => [...all, text]),140+ readInput: Effect.gen(function* () {141+ if (setup.typed === undefined) {142+ return yield* Effect.die("prompted, where no prompt may run");143+ }144+145+ const keys = yield* Queue.unbounded<Terminal.UserInput, Cause.Done>();146+147+ yield* Queue.offerAll(keys, [148+ ...setup.typed149+ .split("")150+ .map((char) => press(char, Option.some(char))),151+ press("enter", Option.none()),152+ ]);153+154+ return keys;155+ }),156+ readLine: Effect.die("readLine is never used"),157+ rows: Effect.succeed(24),158+ })159+ );160+161+ // The platform in process: `setEnv` records what it got and answers.162+ const platform = Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(163+ Layer.provide([164+ Layer.mergeAll(165+ unanswered,166+ Contracts.toLayerHandler("setEnv", (payload) =>167+ Ref.update(calls, (all) => [...all, payload]).pipe(168+ Effect.andThen(setup.answer ?? stored)169+ )170+ )171+ ),172+ asTester,173+ ])174+ );175+176+ const exit = yield* Effect.exit(177+ program(["env", "set", ...args]).pipe(178+ Effect.provide(179+ Layer.mergeAll(180+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),181+ platform,182+ output,183+ terminal,184+ Logger.layer([185+ Logger.make((options) => {186+ logged.push(Logger.formatSimple.log(options));187+ }),188+ ]),189+ Stdio.layerTest({190+ stdin: setup.stdin ?? piped,191+ stdinIsTerminal: Effect.succeed(setup.stdinIsTerminal ?? false),192+ })193+ )194+ ),195+ Effect.provideService(References.MinimumLogLevel, "All")196+ )197+ );198+199+ return {200+ calls: yield* Ref.get(calls),201+ code: exitCodeOf(exit),202+ err: (yield* TestConsole.errorLines).map(String).join("\n"),203+ logged: logged.join("\n"),204+ out: (yield* TestConsole.logLines).map(String).join("\n"),205+ printed: yield* Ref.get(printed),206+ shown: (yield* Ref.get(shown)).join(""),207+ } satisfies Ran;208+ }).pipe(Effect.provide(TestConsole.layer));209+210+/** Asserts the value reached no output, note, log line or terminal frame. */211+const neverShown = (ran: Ran) => {212+ for (const seen of [213+ ran.out,214+ ran.err,215+ ran.logged,216+ ran.shown,217+ JSON.stringify(ran.printed),218+ ]) {219+ expect(seen).not.toContain(secret);220+ expect(seen).not.toContain("0123456789abcdef");221+ }222+};223+224+const decodeEnvelope = Schema.decodeEffect(225+ Schema.fromJsonString(Envelope(Schema.Unknown))226+);227+228+/** The one call the platform got, with its value opened for the check. */229+const onlyCall = (ran: Ran) => {230+ expect(ran.calls).toHaveLength(1);231+232+ const [call] = ran.calls;233+234+ expect(call).toBeDefined();235+ expect(Redacted.isRedacted(call?.value)).toBeTruthy();236+237+ return {238+ ...call,239+ value: call === undefined ? undefined : Redacted.value(call.value),240+ };241+};242+243+const always = ["--project", "datekit"];244+245+describe(`${Brand.cli} env set`, () => {246+ it.live(247+ "sends the piped value, less one newline, as a Redacted, and prints only who set which key and when",248+ () =>249+ Effect.gen(function* () {250+ const ran = yield* run([key, ...always, "--yes", "--json"]);251+252+ expect(ran.code).toBe(0);253+ expect(onlyCall(ran)).toStrictEqual({254+ key: "SENTRY_AUTH_TOKEN",255+ project: "datekit",256+ value: secret,257+ });258+ expect(ran.err).toBe("");259+ expect(yield* decodeEnvelope(ran.out)).toStrictEqual({260+ command: "env set",261+ data: {262+ key: "SENTRY_AUTH_TOKEN",263+ setAt: "2026-10-07T09:00:00.000Z",264+ setBy: "alice",265+ },266+ ok: true,267+ v: 1,268+ });269+ neverShown(ran);270+ }).pipe(Effect.provide(NodeServices.layer))271+ );272+273+ it.live(274+ "refuses a value given as an argument, as a usage error that does not echo it",275+ () =>276+ Effect.gen(function* () {277+ const ran = yield* run([key, secret, ...always, "--yes"]);278+279+ expect(ran.code).toBe(2);280+ expect(ran.calls).toStrictEqual([]);281+ expect(ran.err).toContain("stdin");282+ neverShown(ran);283+ }).pipe(Effect.provide(NodeServices.layer))284+ );285+286+ it.live("without --yes, exits 2 naming it and calls nothing", () =>287+ Effect.gen(function* () {288+ const ran = yield* run([key, ...always]);289+290+ expect(ran.code).toBe(2);291+ expect(ran.calls).toStrictEqual([]);292+ expect(ran.err).toContain("--yes");293+ neverShown(ran);294+ }).pipe(Effect.provide(NodeServices.layer))295+ );296+297+ it.live(298+ "with --dry-run, hands over the payload it would send with the value redacted, and calls nothing",299+ () =>300+ Effect.gen(function* () {301+ const ran = yield* run([key, ...always, "--dry-run", "--json"]);302+303+ expect(ran.code).toBe(0);304+ expect(ran.calls).toStrictEqual([]);305+ expect(ran.printed).toStrictEqual([306+ {307+ input: {308+ command: "env set",309+ json: true,310+ payload: {311+ key: "SENTRY_AUTH_TOKEN",312+ project: "datekit",313+ value: "<redacted>",314+ },315+ },316+ method: "plan",317+ },318+ ]);319+ neverShown(ran);320+ }).pipe(Effect.provide(NodeServices.layer))321+ );322+323+ it.live.each([324+ { refusal: new NotSensitive({ key }) },325+ { refusal: ValueTooShort.of(key, 12) },326+ ])(327+ "prints $refusal._tag from the platform once, and exits 1",328+ ({ refusal }: { readonly refusal: NotSensitive | ValueTooShort }) =>329+ Effect.gen(function* () {330+ const ran = yield* run([key, ...always, "--yes"], {331+ answer: Effect.fail(refusal),332+ });333+334+ expect(ran.code).toBe(1);335+ expect(ran.out).toBe("");336+ expect(ran.err).toBe(explain([refusal]).join("\n"));337+ neverShown(ran);338+ }).pipe(Effect.provide(NodeServices.layer))339+ );340+341+ it.live("with --acknowledge-short, asks to store a short value anyway", () =>342+ Effect.gen(function* () {343+ const ran = yield* run([key, ...always, "--yes", "--acknowledge-short"]);344+345+ expect(ran.code).toBe(0);346+ expect(onlyCall(ran)).toStrictEqual({347+ acknowledgeShort: true,348+ key: "SENTRY_AUTH_TOKEN",349+ project: "datekit",350+ value: secret,351+ });352+ }).pipe(Effect.provide(NodeServices.layer))353+ );354+355+ it.live(356+ "under an agent with a terminal on stdin, never prompts: it tells the person to pipe the value",357+ () =>358+ Effect.gen(function* () {359+ const ran = yield* run([key, ...always, "--yes"], {360+ mode: "agent",361+ stdinIsTerminal: true,362+ });363+364+ expect(ran.code).toBe(2);365+ expect(ran.calls).toStrictEqual([]);366+ expect(ran.err).toContain("pipe");367+ expect(ran.shown).toBe("");368+ }).pipe(Effect.provide(NodeServices.layer))369+ );370+371+ it.live(372+ "asks a person at a terminal with a prompt that shows nothing typed, not even its length",373+ () =>374+ Effect.gen(function* () {375+ const ran = yield* run([key, ...always, "--yes"], {376+ stdin: Stream.empty,377+ stdinIsTerminal: true,378+ typed: secret,379+ });380+381+ expect(ran.code).toBe(0);382+ expect(onlyCall(ran)).toStrictEqual({383+ key: "SENTRY_AUTH_TOKEN",384+ project: "datekit",385+ value: secret,386+ });387+ expect(ran.shown).toContain(key);388+ expect(ran.shown).not.toContain("*");389+ neverShown(ran);390+ }).pipe(Effect.provide(NodeServices.layer))391+ );392+});added:apps/cli/test/local/why.test.ts+456 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import { Client, Contracts } from "@repo/protocol/contracts";5+import { Verdict } from "@repo/protocol/domain/answer";6+import type { LandingView } from "@repo/protocol/domain/landing";7+import { Outcome } from "@repo/protocol/domain/outcome";8+import { Envelope } from "@repo/protocol/envelope";9+import {10+ AskId,11+ CheckVersion,12+ CommitSha,13+ Handle,14+ LandedSha,15+ LaneName,16+ PatchId,17+ ProjectName,18+ RepoPath,19+ TreeSha,20+} from "@repo/protocol/ids";21+import { UnknownCommit, UnknownProject } from "@repo/protocol/refusal";22+import { explain } from "@repo/protocol/render";23+import { asTester, unanswered } from "@repo/protocol/testing";24+import { gitOk } from "@repo/testkit/git";25+import {26+ Cause,27+ Console,28+ DateTime,29+ Effect,30+ Exit,31+ FileSystem,32+ Layer,33+ Option,34+ Path,35+ Ref,36+ Runtime,37+ Schema,38+} from "effect";39+import { CliOutput } from "effect/cli";40+import { RpcTest } from "effect/rpc";41+import { TestConsole } from "effect/testing";42+43+import { WorkingDirectory, parseLocation } from "../../src/local/why.ts";44+import { program } from "../../src/main.ts";45+import { Output, OutputPlain } from "../../src/output.ts";46+47+const project = ProjectName.make("datekit");48+49+const alice = Handle.make("alice");50+51+const carol = Handle.make("carol");52+53+/** The second commit's message: its trailers, as an answerer wrote them. */54+const message = [55+ "Start the week on Monday",56+ "",57+ "Asked-by: carol",58+ "Signed-off-by: alice",59+ "Assisted-by: claude-code",60+].join("\n");61+62+/**63+ * A repo with two commits: the first writes `src/week.ts` lines 1 and 2,64+ * the second adds line 3 with `message`.65+ */66+const aRepo = Effect.gen(function* () {67+ const fs = yield* FileSystem.FileSystem;68+ const path = yield* Path.Path;69+ const dir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());70+ const file = path.join(dir, "src", "week.ts");71+72+ yield* gitOk(dir, "init", "--quiet", "--initial-branch=main");73+ yield* fs.makeDirectory(path.join(dir, "src"));74+ yield* fs.writeFileString(75+ file,76+ "export const days = 7;\nexport const weekend = [6, 0];\n"77+ );78+ yield* gitOk(dir, "add", ".");79+ yield* gitOk(dir, "commit", "--quiet", "-m", "Count the days of a week");80+81+ const first = CommitSha.make(yield* gitOk(dir, "rev-parse", "HEAD"));82+83+ yield* fs.writeFileString(84+ file,85+ "export const days = 7;\nexport const weekend = [6, 0];\nexport const firstDay = 1;\n"86+ );87+ yield* gitOk(dir, "commit", "--quiet", "-am", message);88+89+ const second = CommitSha.make(yield* gitOk(dir, "rev-parse", "HEAD"));90+91+ return { dir, first, second };92+});93+94+/** What the platform was asked: each `landing` call's payload. */95+type Asked = readonly { readonly project: string; readonly sha: string }[];96+97+/** A record of `landing` calls, none yet. */98+const noCalls = Ref.make<Asked>([]);99+100+/** The platform's record of the second commit's landing. */101+const landingOf = (sha: CommitSha): LandingView => ({102+ ask: AskId.make("fix-week"),103+ assisted: [{ harness: "claude-code", verified: false }],104+ author: alice,105+ credits: [106+ { handle: carol, role: "Asked-by" },107+ { handle: alice, role: "Signed-off-by" },108+ ],109+ landedAt: DateTime.makeUnsafe("2026-10-06T12:00:00Z"),110+ project,111+ sha: LandedSha.make(sha),112+});113+114+/** The same landing as `--json` prints it. */115+const landingJson = (sha: string) => ({116+ ask: "fix-week",117+ assisted: [{ harness: "claude-code", verified: false }],118+ author: "alice",119+ credits: [120+ { handle: "carol", role: "Asked-by" },121+ { handle: "alice", role: "Signed-off-by" },122+ ],123+ landedAt: "2026-10-06T12:00:00.000Z",124+ project: "datekit",125+ sha,126+});127+128+/**129+ * The platform in process, answering `landing` with `answer` and every130+ * other contract never: a test reaching one fails.131+ */132+const platform = (133+ answer: (payload: {134+ readonly project: ProjectName;135+ readonly sha: CommitSha;136+ }) => Effect.Effect<137+ { readonly landing: LandingView },138+ UnknownCommit | UnknownProject139+ >140+) =>141+ Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(142+ Layer.provide([143+ Layer.mergeAll(unanswered, Contracts.toLayerHandler("landing", answer)),144+ asTester,145+ ])146+ );147+148+/**149+ * A platform that knows `landed` as a landing and no other commit, and150+ * records every `landing` call it is asked.151+ */152+const platformKnowing = (153+ landed: Option.Option<CommitSha>,154+ calls: Ref.Ref<Asked>155+) =>156+ platform(({ project: asked, sha }) =>157+ Ref.update(calls, (all) => [...all, { project: asked, sha }]).pipe(158+ Effect.andThen(159+ Option.exists(landed, (known) => known === sha)160+ ? Effect.succeed({ landing: landingOf(sha) })161+ : Effect.fail(new UnknownCommit({ sha }))162+ )163+ )164+ );165+166+/**167+ * Output as 404's agent policy gives it when `CLAUDECODE=1`: Markdown for168+ * results, refusals and notes on stderr. 401's `OutputPlain` is the person's.169+ */170+const OutputForAgent = Layer.succeed(Output)({171+ mode: "agent",172+ note: (text) => Console.error(text),173+ plan: ({ payload }) => Console.log(JSON.stringify(payload)),174+ refused: ({ refusals }) => Console.error(explain(refusals).join("\n")),175+ success: ({ view }) => Console.log(view.markdown),176+});177+178+/** How the process would exit, by the runtime's own rule. */179+const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>180+ Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));181+182+/**183+ * Runs `<cli> why …` in `dir` against `client`, printing through `output`,184+ * and returns its exit code, stdout and stderr.185+ */186+const run = (187+ dir: string,188+ args: readonly string[],189+ client: Layer.Layer<Client>,190+ output: Layer.Layer<Output> = OutputPlain191+) =>192+ Effect.gen(function* () {193+ const exit = yield* Effect.exit(194+ program(["why", ...args]).pipe(195+ Effect.provideService(WorkingDirectory, dir)196+ )197+ );198+199+ return {200+ code: exitCodeOf(exit),201+ err: (yield* TestConsole.errorLines).map(String).join("\n"),202+ out: (yield* TestConsole.logLines).map(String).join("\n"),203+ };204+ }).pipe(205+ Effect.provide(206+ Layer.mergeAll(207+ TestConsole.layer,208+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),209+ client,210+ output211+ )212+ )213+ );214+215+const decodeEnvelope = Schema.decodeEffect(216+ Schema.fromJsonString(Envelope(Schema.Unknown))217+);218+219+describe("a line's location", () => {220+ it("is a path and a line number", () => {221+ expect(parseLocation("src/week.ts:42")).toStrictEqual(222+ Option.some({ line: 42, path: RepoPath.make("src/week.ts") })223+ );224+ });225+226+ it("splits at the last colon, so a path may hold one", () => {227+ expect(parseLocation("docs/a:b.md:7")).toStrictEqual(228+ Option.some({ line: 7, path: RepoPath.make("docs/a:b.md") })229+ );230+ });231+232+ it.each([233+ "src/week.ts",234+ "src/week.ts:",235+ ":3",236+ "src/week.ts:0",237+ "src/week.ts:-1",238+ "src/week.ts:+3",239+ "src/week.ts:3.5",240+ "src/week.ts:three",241+ "src/week.ts:99999999999999999999",242+ ])("is no line: %j", (text) => {243+ expect(parseLocation(text)).toStrictEqual(Option.none());244+ });245+});246+247+describe(`${Brand.cli} why`, () => {248+ it.live(249+ "prints one envelope with the line's commit and the platform's landing record",250+ () =>251+ Effect.gen(function* () {252+ const { dir, second } = yield* aRepo;253+ const calls = yield* noCalls;254+255+ const ran = yield* run(256+ dir,257+ ["src/week.ts:3", "--project", "datekit", "--json"],258+ platformKnowing(Option.some(second), calls)259+ );260+261+ expect(ran.code).toBe(0);262+ expect(ran.err).toBe("");263+ expect(yield* decodeEnvelope(ran.out)).toStrictEqual({264+ command: "why",265+ data: {266+ landing: landingJson(second),267+ line: 3,268+ path: "src/week.ts",269+ sha: second,270+ },271+ ok: true,272+ v: 1,273+ });274+ expect(yield* Ref.get(calls)).toStrictEqual([275+ { project: "datekit", sha: second },276+ ]);277+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))278+ );279+280+ it.live(281+ "tells an agent, in Markdown, the ask, the author and each credit",282+ () =>283+ Effect.gen(function* () {284+ const { dir, second } = yield* aRepo;285+ const calls = yield* noCalls;286+287+ const ran = yield* run(288+ dir,289+ ["src/week.ts:3", "--project", "datekit"],290+ platformKnowing(Option.some(second), calls),291+ OutputForAgent292+ );293+294+ expect(ran.code).toBe(0);295+ expect(ran.out.split("\n")).toStrictEqual(296+ expect.arrayContaining([297+ expect.stringContaining(`landing \`${second.slice(0, 7)}\``),298+ "- Ask: `fix-week`",299+ "- Author: alice",300+ "- Asked-by: carol",301+ "- Signed-off-by: alice",302+ "- Assisted-by: claude-code (claimed)",303+ ])304+ );305+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))306+ );307+308+ it.live(309+ "says a commit the platform did not land is none of its landings, and lists the trailers it carries",310+ () =>311+ Effect.gen(function* () {312+ const { dir, second } = yield* aRepo;313+ const calls = yield* noCalls;314+ const unknowing = platformKnowing(Option.none(), calls);315+316+ const json = yield* run(317+ dir,318+ ["src/week.ts:3", "--project", "datekit", "--json"],319+ unknowing320+ );321+322+ expect(json.code).toBe(0);323+ expect(yield* decodeEnvelope(json.out)).toStrictEqual({324+ command: "why",325+ data: {326+ line: 3,327+ path: "src/week.ts",328+ sha: second,329+ trailers: [330+ { key: "Asked-by", value: "carol" },331+ { key: "Signed-off-by", value: "alice" },332+ { key: "Assisted-by", value: "claude-code" },333+ ],334+ },335+ ok: true,336+ v: 1,337+ });338+339+ const text = yield* run(340+ dir,341+ ["src/week.ts:3", "--project", "datekit"],342+ unknowing343+ );344+345+ expect(text.code).toBe(0);346+ expect(text.out.split("\n").map((line) => line.trim())).toStrictEqual(347+ expect.arrayContaining([348+ expect.stringContaining("which is not a platform landing"),349+ "Asked-by: carol",350+ "Signed-off-by: alice",351+ "Assisted-by: claude-code",352+ ])353+ );354+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))355+ );356+357+ it.live.each([358+ { args: ["src/week.ts:4"], why: "a line past the file's end" },359+ { args: ["src/month.ts:1"], why: "a file not in HEAD" },360+ { args: ["src/week.ts"], why: "no line at all" },361+ ])("refuses $why as a usage error (exit 2), asking nothing", ({ args }) =>362+ Effect.gen(function* () {363+ const { dir } = yield* aRepo;364+ const calls = yield* noCalls;365+366+ const ran = yield* run(367+ dir,368+ [...args, "--project", "datekit"],369+ platformKnowing(Option.none(), calls)370+ );371+372+ expect(ran.code).toBe(2);373+ expect(ran.out).toBe("");374+ expect(ran.err).toContain(args[0] ?? "");375+ expect(yield* Ref.get(calls)).toStrictEqual([]);376+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))377+ );378+379+ it.live("adds the verdict a fetched note carries on that commit", () =>380+ Effect.gen(function* () {381+ const { dir, first, second } = yield* aRepo;382+ const calls = yield* noCalls;383+384+ const verdict: Verdict = {385+ ask: AskId.make("fix-week"),386+ at: DateTime.makeUnsafe("2026-10-06T11:59:00Z"),387+ base: first,388+ checkVersion: CheckVersion.make("checks@1"),389+ head: second,390+ heldBack: [],391+ lanes: [392+ {393+ command: "bun test",394+ durationMs: 1200,395+ lane: LaneName.make("test"),396+ result: "passed",397+ },398+ ],399+ outcome: Outcome.cases.Landed.make({ sha: LandedSha.make(second) }),400+ patchId: PatchId.make("a".repeat(64)),401+ project,402+ stage: "checks",403+ tree: TreeSha.make(yield* gitOk(dir, "rev-parse", "HEAD^{tree}")),404+ verifier: "platform",405+ };406+407+ yield* gitOk(408+ dir,409+ "notes",410+ `--ref=refs/notes/${Brand.slug}`,411+ "add",412+ "-m",413+ yield* Schema.encodeEffect(Schema.fromJsonString(Verdict))(verdict),414+ second415+ );416+417+ const ran = yield* run(418+ dir,419+ ["src/week.ts:3", "--project", "datekit", "--json"],420+ platformKnowing(Option.some(second), calls)421+ );422+423+ expect(ran.code).toBe(0);424+ expect(yield* decodeEnvelope(ran.out)).toStrictEqual({425+ command: "why",426+ data: {427+ landing: landingJson(second),428+ line: 3,429+ note: yield* Schema.encodeEffect(Verdict)(verdict),430+ path: "src/week.ts",431+ sha: second,432+ },433+ ok: true,434+ v: 1,435+ });436+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))437+ );438+439+ it.live("prints a refusal from the platform once, and exits 1", () =>440+ Effect.gen(function* () {441+ const { dir } = yield* aRepo;442+443+ const ran = yield* run(444+ dir,445+ ["src/week.ts:3", "--project", "datekit"],446+ platform(() => Effect.fail(new UnknownProject({ project })))447+ );448+449+ expect(ran.code).toBe(1);450+ expect(ran.out).toBe("");451+ expect(ran.err).toBe(452+ explain([new UnknownProject({ project })]).join("\n")453+ );454+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))455+ );456+});modified:apps/cli/test/main.test.ts-2 removed
96 unmodified lines97 { args: ["logout"], issue: "412" },98 { args: ["credential"], issue: "412" },99 { args: ["init"], issue: "413" },100 { args: ["check"], issue: "405" },101- { args: ["why"], issue: "414" },102- { args: ["env", "set"], issue: "414" },101 { args: ["hook"], issue: "415" },102 ] as const;103 104 it.effect.each(stubs)(15 unmodified lines