Merge build/414-cli-why-and-env-set: `<cli> why` explains a line, and `<cli> env set` stores a value nobody can read back
Before adoption: this commit came in with the history the project adopted, so no landing records it.
# Conflicts: # apps/cli/src/main.ts # apps/cli/test/main.test.ts
authored by oscabriel · committed by oscabriel · parents 90a806c, 93c5ef2 · Browse files · 6 files·+1682 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+1682 added−16 removed
- tests:+1033 added−2 removed
- other:+649 added−14 removed
Provenance
- Commit
c92f070- Tree
b1a06c9- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
90a806c- Parent 2
93c5ef2
6 files changed+1682 added−16 removed
modified:apps/cli/src/local/env-set.ts+235 added-5 removed
12123456789101112131415161718192021224562324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241import { 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: string) => `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); });
/** * Every spelling of a flag `env set` takes: its own, and effect/cli's * built-in ones. A boolean's `--no-` form counts as its own spelling. A test * holds this list to the flags `env set --help` names. */const spellings: ReadonlySet<string> = new Set([ "--acknowledge-short", "--completions", "--dry-run", "--help", "--json", "--log-level", "--project", "--version", "--wizard", "--yes", "-h", "-v",]);
/** A word that reads as a flag, but as none `env set` takes. */const strangeFlag = (word: string) => { const [flag = word] = word.split("=", 1);
return ( word.startsWith("-") && word !== "-" && !spellings.has(flag.replace(/^--no-/u, "--")) );};
/** * Refuses `<cli> env set` with a word that reads as a flag it does not take, * before effect/cli parses the words. The parser would print such a word * back (`-abc` a letter per error), or act on a `-h` or `-v` inside it, and * a value typed there by mistake must never show, so the line repeats none * of it. `program` runs this first. Words after `--` reach the command, * which refuses them as `not-the-value`. */export const refuseStrangeFlags = ( argv: readonly string[]): Effect.Effect<void, never, Output> => { const end = argv.indexOf("--"); const words = end === -1 ? argv : argv.slice(0, end);
const at = words.findIndex( (word, index) => word === "env" && words[index + 1] === "set" );
return at !== -1 && words.slice(at + 2).some(strangeFlag) ? usage( `${Brand.cli} ${command} was given a flag it does not take, not repeated here in case it holds the value; the value is read from stdin, never from arguments: ${pipeHint("<KEY>")}` ) : Effect.void;};
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 linemodified:apps/cli/src/main.ts+9 added-4 removed
11 unmodified lines12 13 import { credential } from "./credential-helper.ts";14 import { CredentialsFile } from "./credentials.ts";15 import { hook } from "./hook.ts";16+import { refuseStrangeFlags } from "./local/env-set.ts";17 import { holdStdout, Output, OutputLive } from "./output.ts";18 import { CurrentMode, Policy } from "./policy.ts";19 import {20 isTransportFailure,137 unmodified lines158 /**159 * Runs the command `argv` names. Help asked for, or shown for a group run160 * without a subcommand, is a success. A misuse (a parse error, a missing161 * value, `--yes` left out, any failure whose `Runtime.errorExitCode` is 2)161- * ends as `Misused` (exit 2) after one line on162- * stderr; every other failure ends as `Reported` (exit 1), printed once: a163- * refusal by the command, anything else here. A defect (a stub's "not164- * built") is not caught: the runtime prints it, loudly.162+ * ends as `Misused` (exit 2) after one line on stderr; every other failure163+ * ends as `Reported` (exit 1), printed once: a refusal by the command,164+ * anything else here. A defect (a stub's "not built") is not caught: the165+ * runtime prints it, loudly. `env set`'s words are screened before166+ * effect/cli parses them, so a value typed where a flag goes is never167+ * printed back.168 */169 export const program = (argv: readonly string[]) =>170 Effect.gen(function* () {171+ yield* refuseStrangeFlags(argv);172+173 const policy = yield* Effect.serviceOption(Policy);174 const stdout = holdStdout(yield* Console.Console);175 176 const exit = yield* Effect.exit(35 unmodified linesadded:apps/cli/test/local/env-set.test.ts+510 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 { refuseStrangeFlags } from "../../src/local/env-set.ts";35+import { program } from "../../src/main.ts";36+import { Output, OutputPlain } from "../../src/output.ts";37+import type { Mode } from "../../src/output.ts";38+39+/** A value no output, note or log line may ever hold. */40+const secret = "sk_live_0123456789abcdef";41+42+const key = EnvKey.make("SENTRY_AUTH_TOKEN");43+44+const setAt = DateTime.makeUnsafe("2026-10-07T09:00:00Z");45+46+/** A person piping the value in, as `printf '…\n' |` does. */47+const piped = Stream.make(new TextEncoder().encode(`${secret}\n`));48+49+type Payload = Rpc.Payload<typeof SetEnv>;50+51+/** What the platform answers `setEnv` with. */52+type Answer = Effect.Effect<53+ Rpc.Success<typeof SetEnv>,54+ NotSensitive | ValueTooShort55+>;56+57+const stored: Answer = Effect.succeed({58+ key,59+ setAt,60+ setBy: Handle.make("alice"),61+});62+63+/** One call through `Output`, as the command made it. */64+interface Printed {65+ readonly method: "success" | "refused" | "plan" | "note";66+ /** The call's input: a note's text, or the others' object. */67+ readonly input: object | string;68+}69+70+/**71+ * How one run went: its exit code, what reached stdout, stderr and the72+ * logger, what the platform was asked, and what the command handed `Output`.73+ */74+interface Ran {75+ readonly code: number;76+ readonly out: string;77+ readonly err: string;78+ readonly logged: string;79+ readonly calls: readonly Payload[];80+ readonly printed: readonly Printed[];81+ readonly shown: string;82+}83+84+interface Setup {85+ /** Who reads: 401's person at a terminal, or 404's agent policy. */86+ readonly mode?: Mode;87+ readonly stdin?: Stream.Stream<Uint8Array>;88+ readonly stdinIsTerminal?: boolean;89+ /** What a person types at the hidden prompt, key by key. */90+ readonly typed?: string;91+ readonly answer?: Answer;92+}93+94+/** How the process would exit, by the runtime's own rule. */95+const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>96+ Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));97+98+const press = (name: string, input: Option.Option<string>) => ({99+ input,100+ key: { ctrl: false, meta: false, name, shift: false },101+});102+103+/**104+ * Runs `<cli> env set …` with `setup`'s stdin, terminal and platform, and105+ * returns everything it printed, logged and asked.106+ */107+const run = (args: readonly string[], setup: Setup = {}) =>108+ Effect.gen(function* () {109+ const calls = yield* Ref.make<readonly Payload[]>([]);110+ const printed = yield* Ref.make<readonly Printed[]>([]);111+ const shown = yield* Ref.make<readonly string[]>([]);112+ const logged: string[] = [];113+114+ const record = (method: Printed["method"], input: Printed["input"]) =>115+ Ref.update(printed, (all) => [...all, { input, method }]);116+117+ // 401's plain output, recorded, as whichever reader `setup` names.118+ const output = Layer.effect(119+ Output,120+ Effect.gen(function* () {121+ const plain = yield* Effect.service(Output);122+123+ return {124+ mode: setup.mode ?? "human",125+ note: (text) =>126+ Effect.andThen(record("note", text), plain.note(text)),127+ plan: (input) =>128+ Effect.andThen(record("plan", input), plain.plan(input)),129+ refused: (input) =>130+ Effect.andThen(record("refused", input), plain.refused(input)),131+ success: (input) =>132+ Effect.andThen(record("success", input), plain.success(input)),133+ } satisfies Output["Service"];134+ })135+ ).pipe(Layer.provide(OutputPlain));136+137+ const terminal = Layer.succeed(Terminal.Terminal)(138+ Terminal.make({139+ columns: Effect.succeed(80),140+ display: (text) => Ref.update(shown, (all) => [...all, text]),141+ readInput: Effect.gen(function* () {142+ if (setup.typed === undefined) {143+ return yield* Effect.die("prompted, where no prompt may run");144+ }145+146+ const keys = yield* Queue.unbounded<Terminal.UserInput, Cause.Done>();147+148+ yield* Queue.offerAll(keys, [149+ ...setup.typed150+ .split("")151+ .map((char) => press(char, Option.some(char))),152+ press("enter", Option.none()),153+ ]);154+155+ return keys;156+ }),157+ readLine: Effect.die("readLine is never used"),158+ rows: Effect.succeed(24),159+ })160+ );161+162+ // The platform in process: `setEnv` records what it got and answers.163+ const platform = Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(164+ Layer.provide([165+ Layer.mergeAll(166+ unanswered,167+ Contracts.toLayerHandler("setEnv", (payload) =>168+ Ref.update(calls, (all) => [...all, payload]).pipe(169+ Effect.andThen(setup.answer ?? stored)170+ )171+ )172+ ),173+ asTester,174+ ])175+ );176+177+ const exit = yield* Effect.exit(178+ program(["env", "set", ...args]).pipe(179+ Effect.provide(180+ Layer.mergeAll(181+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),182+ platform,183+ output,184+ terminal,185+ Logger.layer([186+ Logger.make((options) => {187+ logged.push(Logger.formatSimple.log(options));188+ }),189+ ]),190+ Stdio.layerTest({191+ stdin: setup.stdin ?? piped,192+ stdinIsTerminal: Effect.succeed(setup.stdinIsTerminal ?? false),193+ })194+ )195+ ),196+ Effect.provideService(References.MinimumLogLevel, "All")197+ )198+ );199+200+ return {201+ calls: yield* Ref.get(calls),202+ code: exitCodeOf(exit),203+ err: (yield* TestConsole.errorLines).map(String).join("\n"),204+ logged: logged.join("\n"),205+ out: (yield* TestConsole.logLines).map(String).join("\n"),206+ printed: yield* Ref.get(printed),207+ shown: (yield* Ref.get(shown)).join(""),208+ } satisfies Ran;209+ }).pipe(Effect.provide(TestConsole.layer));210+211+/** Asserts the value reached no output, note, log line or terminal frame. */212+const neverShown = (ran: Ran) => {213+ for (const seen of [214+ ran.out,215+ ran.err,216+ ran.logged,217+ ran.shown,218+ JSON.stringify(ran.printed),219+ ]) {220+ expect(seen).not.toContain(secret);221+ expect(seen).not.toContain("0123456789abcdef");222+ }223+};224+225+const decodeEnvelope = Schema.decodeEffect(226+ Schema.fromJsonString(Envelope(Schema.Unknown))227+);228+229+/** The one call the platform got, with its value opened for the check. */230+const onlyCall = (ran: Ran) => {231+ expect(ran.calls).toHaveLength(1);232+233+ const [call] = ran.calls;234+235+ expect(call).toBeDefined();236+ expect(Redacted.isRedacted(call?.value)).toBeTruthy();237+238+ return {239+ ...call,240+ value: call === undefined ? undefined : Redacted.value(call.value),241+ };242+};243+244+const always = ["--project", "datekit"];245+246+describe(`${Brand.cli} env set`, () => {247+ it.live(248+ "sends the piped value, less one newline, as a Redacted, and prints only who set which key and when",249+ () =>250+ Effect.gen(function* () {251+ const ran = yield* run([key, ...always, "--yes", "--json"]);252+253+ expect(ran.code).toBe(0);254+ expect(onlyCall(ran)).toStrictEqual({255+ key: "SENTRY_AUTH_TOKEN",256+ project: "datekit",257+ value: secret,258+ });259+ expect(ran.err).toBe("");260+ expect(yield* decodeEnvelope(ran.out)).toStrictEqual({261+ command: "env set",262+ data: {263+ key: "SENTRY_AUTH_TOKEN",264+ setAt: "2026-10-07T09:00:00.000Z",265+ setBy: "alice",266+ },267+ ok: true,268+ v: 1,269+ });270+ neverShown(ran);271+ }).pipe(Effect.provide(NodeServices.layer))272+ );273+274+ it.live(275+ "refuses a value given as an argument, as a usage error that does not echo it",276+ () =>277+ Effect.gen(function* () {278+ const ran = yield* run([key, secret, ...always, "--yes"]);279+280+ expect(ran.code).toBe(2);281+ expect(ran.calls).toStrictEqual([]);282+ expect(ran.err).toContain("stdin");283+ neverShown(ran);284+ }).pipe(Effect.provide(NodeServices.layer))285+ );286+287+ it.live.each([288+ {289+ typed: `-${secret}`,290+ why: "a value that starts with a dash, holding a v that would read as --version",291+ },292+ {293+ typed: "-Zq8_w0rd5ecret",294+ why: "a value effect/cli would read as short flags and print back letter by letter",295+ },296+ { typed: `--${secret}`, why: "a value that reads as a long flag" },297+ { typed: `--token=${secret}`, why: "a value given to a flag it lacks" },298+ ])(299+ "refuses $why as a usage error, in one line that repeats none of it",300+ ({ typed }) =>301+ Effect.gen(function* () {302+ const ran = yield* run([key, typed, ...always, "--yes"]);303+304+ expect(ran.code).toBe(2);305+ expect(ran.calls).toStrictEqual([]);306+ expect(ran.out).toBe("");307+ expect(ran.err.split("\n")).toStrictEqual([308+ expect.stringContaining("stdin"),309+ ]);310+ expect(ran.err).not.toContain(typed.slice(1, 4));311+ neverShown(ran);312+ }).pipe(Effect.provide(NodeServices.layer))313+ );314+315+ it.live.each([316+ { args: [key, "--project=datekit", "--yes"], shows: "set by alice" },317+ {318+ args: [key, ...always, "--yes", "--log-level", "debug"],319+ shows: "set by alice",320+ },321+ { args: [key, "-h"], shows: "--acknowledge-short" },322+ { args: [key, "--no-json", ...always, "--yes"], shows: "set by alice" },323+ ])("still takes its own flags and effect/cli's: $args", ({ args, shows }) =>324+ Effect.gen(function* () {325+ const ran = yield* run(args);326+327+ expect(ran.code).toBe(0);328+ expect(ran.out).toContain(shows);329+ }).pipe(Effect.provide(NodeServices.layer))330+ );331+332+ it.live("screens out no flag that `env set --help` names", () =>333+ Effect.gen(function* () {334+ const help = yield* run(["--help"]);335+336+ const named = help.out.split("\n").flatMap((line) => {337+ const flags = /^\s+(?<flags>-[^\s,]+(?:, -[^\s,]+)*)/u.exec(line)338+ ?.groups?.flags;339+340+ return flags === undefined ? [] : flags.split(", ");341+ });342+343+ expect(named).toStrictEqual(344+ expect.arrayContaining(["--yes", "--project", "--help", "-h"])345+ );346+347+ const screened = yield* Effect.filter(named, (flag) =>348+ Effect.map(349+ Effect.exit(refuseStrangeFlags(["env", "set", key, flag])),350+ Exit.isFailure351+ )352+ );353+354+ expect(screened).toStrictEqual([]);355+ }).pipe(356+ Effect.provide([NodeServices.layer, OutputPlain, TestConsole.layer])357+ )358+ );359+360+ it.live.each([361+ { kept: `${secret}\n`, sent: `${secret}\n\n`, why: "only one newline" },362+ { kept: secret, sent: `${secret}\r\n`, why: "a CRLF as one newline" },363+ { kept: secret, sent: secret, why: "nothing from a value with no newline" },364+ ])("strips $why from the piped value", ({ kept, sent }) =>365+ Effect.gen(function* () {366+ const ran = yield* run([key, ...always, "--yes"], {367+ stdin: Stream.make(new TextEncoder().encode(sent)),368+ });369+370+ expect(ran.code).toBe(0);371+ expect(onlyCall(ran).value).toBe(kept);372+ }).pipe(Effect.provide(NodeServices.layer))373+ );374+375+ it.live.each([376+ { sent: "", why: "nothing piped" },377+ { sent: "\n", why: "an empty line piped" },378+ ])(379+ "with $why, exits 2 telling how to pipe the value, and calls nothing",380+ ({ sent }) =>381+ Effect.gen(function* () {382+ const ran = yield* run([key, ...always, "--yes"], {383+ stdin: Stream.make(new TextEncoder().encode(sent)),384+ });385+386+ expect(ran.code).toBe(2);387+ expect(ran.calls).toStrictEqual([]);388+ expect(ran.err).toContain(`| ${Brand.cli} env set ${key}`);389+ }).pipe(Effect.provide(NodeServices.layer))390+ );391+392+ it.live("without --yes, exits 2 naming it and calls nothing", () =>393+ Effect.gen(function* () {394+ const ran = yield* run([key, ...always]);395+396+ expect(ran.code).toBe(2);397+ expect(ran.calls).toStrictEqual([]);398+ expect(ran.err).toContain("--yes");399+ neverShown(ran);400+ }).pipe(Effect.provide(NodeServices.layer))401+ );402+403+ it.live(404+ "with --dry-run, hands over the payload it would send with the value redacted, and calls nothing",405+ () =>406+ Effect.gen(function* () {407+ const ran = yield* run([key, ...always, "--dry-run", "--json"]);408+409+ expect(ran.code).toBe(0);410+ expect(ran.calls).toStrictEqual([]);411+ expect(ran.printed).toStrictEqual([412+ {413+ input: {414+ command: "env set",415+ json: true,416+ payload: {417+ key: "SENTRY_AUTH_TOKEN",418+ project: "datekit",419+ value: "<redacted>",420+ },421+ },422+ method: "plan",423+ },424+ ]);425+ expect(yield* decodeEnvelope(ran.out)).toStrictEqual({426+ command: "env set",427+ data: {428+ dryRun: {429+ key: "SENTRY_AUTH_TOKEN",430+ project: "datekit",431+ value: "<redacted>",432+ },433+ },434+ ok: true,435+ v: 1,436+ });437+ neverShown(ran);438+ }).pipe(Effect.provide(NodeServices.layer))439+ );440+441+ it.live.each([442+ { refusal: new NotSensitive({ key }) },443+ { refusal: ValueTooShort.of(key, 12) },444+ ])(445+ "prints $refusal._tag from the platform once, and exits 1",446+ ({ refusal }: { readonly refusal: NotSensitive | ValueTooShort }) =>447+ Effect.gen(function* () {448+ const ran = yield* run([key, ...always, "--yes"], {449+ answer: Effect.fail(refusal),450+ });451+452+ expect(ran.code).toBe(1);453+ expect(ran.out).toBe("");454+ expect(ran.err).toBe(explain([refusal]).join("\n"));455+ neverShown(ran);456+ }).pipe(Effect.provide(NodeServices.layer))457+ );458+459+ it.live("with --acknowledge-short, asks to store a short value anyway", () =>460+ Effect.gen(function* () {461+ const ran = yield* run([key, ...always, "--yes", "--acknowledge-short"]);462+463+ expect(ran.code).toBe(0);464+ expect(onlyCall(ran)).toStrictEqual({465+ acknowledgeShort: true,466+ key: "SENTRY_AUTH_TOKEN",467+ project: "datekit",468+ value: secret,469+ });470+ }).pipe(Effect.provide(NodeServices.layer))471+ );472+473+ it.live(474+ "under an agent with a terminal on stdin, never prompts: it tells the person to pipe the value",475+ () =>476+ Effect.gen(function* () {477+ const ran = yield* run([key, ...always, "--yes"], {478+ mode: "agent",479+ stdinIsTerminal: true,480+ });481+482+ expect(ran.code).toBe(2);483+ expect(ran.calls).toStrictEqual([]);484+ expect(ran.err).toContain("pipe");485+ expect(ran.shown).toBe("");486+ }).pipe(Effect.provide(NodeServices.layer))487+ );488+489+ it.live(490+ "asks a person at a terminal with a prompt that shows nothing typed, not even its length",491+ () =>492+ Effect.gen(function* () {493+ const ran = yield* run([key, ...always, "--yes"], {494+ stdin: Stream.empty,495+ stdinIsTerminal: true,496+ typed: secret,497+ });498+499+ expect(ran.code).toBe(0);500+ expect(onlyCall(ran)).toStrictEqual({501+ key: "SENTRY_AUTH_TOKEN",502+ project: "datekit",503+ value: secret,504+ });505+ expect(ran.shown).toContain(key);506+ expect(ran.shown).not.toContain("*");507+ neverShown(ran);508+ }).pipe(Effect.provide(NodeServices.layer))509+ );510+});added:apps/cli/test/local/why.test.ts+523 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(380+ "from a folder inside the repo, takes the path from there and names it from the repo's root",381+ () =>382+ Effect.gen(function* () {383+ const { dir, second } = yield* aRepo;384+ const calls = yield* noCalls;385+386+ const ran = yield* run(387+ `${dir}/src`,388+ ["week.ts:3", "--project", "datekit", "--json"],389+ platformKnowing(Option.some(second), calls)390+ );391+392+ expect(ran.code).toBe(0);393+ expect(yield* decodeEnvelope(ran.out)).toMatchObject({394+ data: { line: 3, path: "src/week.ts", sha: second },395+ });396+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))397+ );398+399+ it.live(400+ "without --project, asks about the project the repo's platform remote names",401+ () =>402+ Effect.gen(function* () {403+ const { dir, second } = yield* aRepo;404+ const calls = yield* noCalls;405+406+ yield* gitOk(407+ dir,408+ "remote",409+ "add",410+ "origin",411+ `https://${Brand.domain}/datekit.git`412+ );413+414+ const ran = yield* run(415+ dir,416+ ["src/week.ts:3", "--json"],417+ platformKnowing(Option.some(second), calls)418+ );419+420+ expect(ran.code).toBe(0);421+ expect(yield* Ref.get(calls)).toStrictEqual([422+ { project: "datekit", sha: second },423+ ]);424+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))425+ );426+427+ it.live(428+ "without --project or a platform remote, exits 2 asking for --project, and asks nothing",429+ () =>430+ Effect.gen(function* () {431+ const { dir } = yield* aRepo;432+ const calls = yield* noCalls;433+434+ const ran = yield* run(435+ dir,436+ ["src/week.ts:3"],437+ platformKnowing(Option.none(), calls)438+ );439+440+ expect(ran.code).toBe(2);441+ expect(ran.err).toContain("--project");442+ expect(yield* Ref.get(calls)).toStrictEqual([]);443+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))444+ );445+446+ it.live("adds the verdict a fetched note carries on that commit", () =>447+ Effect.gen(function* () {448+ const { dir, first, second } = yield* aRepo;449+ const calls = yield* noCalls;450+451+ const verdict: Verdict = {452+ ask: AskId.make("fix-week"),453+ at: DateTime.makeUnsafe("2026-10-06T11:59:00Z"),454+ base: first,455+ checkVersion: CheckVersion.make("checks@1"),456+ head: second,457+ heldBack: [],458+ lanes: [459+ {460+ command: "bun test",461+ durationMs: 1200,462+ lane: LaneName.make("test"),463+ result: "passed",464+ },465+ ],466+ outcome: Outcome.cases.Landed.make({ sha: LandedSha.make(second) }),467+ patchId: PatchId.make("a".repeat(64)),468+ project,469+ stage: "checks",470+ tree: TreeSha.make(yield* gitOk(dir, "rev-parse", "HEAD^{tree}")),471+ verifier: "platform",472+ };473+474+ yield* gitOk(475+ dir,476+ "notes",477+ `--ref=refs/notes/${Brand.slug}`,478+ "add",479+ "-m",480+ yield* Schema.encodeEffect(Schema.fromJsonString(Verdict))(verdict),481+ second482+ );483+484+ const ran = yield* run(485+ dir,486+ ["src/week.ts:3", "--project", "datekit", "--json"],487+ platformKnowing(Option.some(second), calls)488+ );489+490+ expect(ran.code).toBe(0);491+ expect(yield* decodeEnvelope(ran.out)).toStrictEqual({492+ command: "why",493+ data: {494+ landing: landingJson(second),495+ line: 3,496+ note: yield* Schema.encodeEffect(Verdict)(verdict),497+ path: "src/week.ts",498+ sha: second,499+ },500+ ok: true,501+ v: 1,502+ });503+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))504+ );505+506+ it.live("prints a refusal from the platform once, and exits 1", () =>507+ Effect.gen(function* () {508+ const { dir } = yield* aRepo;509+510+ const ran = yield* run(511+ dir,512+ ["src/week.ts:3", "--project", "datekit"],513+ platform(() => Effect.fail(new UnknownProject({ project })))514+ );515+516+ expect(ran.code).toBe(1);517+ expect(ran.out).toBe("");518+ expect(ran.err).toBe(519+ explain([new UnknownProject({ project })]).join("\n")520+ );521+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))522+ );523+});modified:apps/cli/test/main.test.ts-2 removed
93 unmodified lines94 });95 96 describe("each command a later issue builds", () => {97 const stubs = [98- { args: ["why"], issue: "414" },99- { args: ["env", "set"], issue: "414" },98 { args: ["hook"], issue: "415" },99 ] as const;100 101 it.effect.each(stubs)(15 unmodified lines