Skip to content
Myr

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

6 files+1682 added−16 removed

modified:apps/cli/src/local/env-set.ts+235 added-5 removed
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 */9import { notesRef } from "@repo/git/notes";10import { parseTrailers } from "@repo/git/trailers";11import type { Trailer } from "@repo/git/trailers";12import { Client } from "@repo/protocol/contracts";13import { Verdict } from "@repo/protocol/domain/answer";14import { LandingView } from "@repo/protocol/domain/landing";15import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";16import { Refusal } from "@repo/protocol/refusal";17import {18 Context,19 DateTime,20 Effect,21 Option,22 Runtime,23 Schema,24 Stream,1import { Effect } from "effect";2import { Command } from "effect/cli";25} from "effect";26import { Argument, Command, Flag } from "effect/cli";27import { ChildProcess, ChildProcessSpawner } from "effect/process";284/** `why`: issue 414 replaces this stub. */5export const why = Command.make("why", {}, () =>6 Effect.die("not built: issue 414")29import { Output, Reported } from "../output.ts";30import type { View } from "../output.ts";31import { repoContext } from "../repo-context.ts";32import type { RepoContext } from "../repo-context.ts";3334/**35 * Where a local command runs git: the process's own folder unless a caller36 * (a test) provides another. Shared with `env set`.37 */38export const WorkingDirectory = Context.Reference<string>(39 "cli/WorkingDirectory",40 { defaultValue: () => "." }41);4243/**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 */47export 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}5354/**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 */60export const usage = (reason: string) =>61 Output.use((output) => output.note(reason)).pipe(62 Effect.andThen(Effect.die(new UsageError({ reason })))63 );6465const isRefusal = Schema.is(Refusal);6667/**68 * Prints a refusal the platform answered with, once, through `Output`, and69 * ends with `Reported` (exit 1). Shared with `env set`.70 */71export 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 );8182/**83 * The project a command acts on: `--project`, else the one the repo's84 * platform remote names. Shared with `env set`.85 */86export 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 );104105// 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.107const LOCATION = /^(?<path>.+):(?<line>[1-9][0-9]*)$/u;108109/** A line of a file as people and compilers write it: `src/week.ts:42`. */110export 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);115116 return groups?.path === undefined || !Number.isSafeInteger(line)117 ? Option.none()118 : Option.some({ line, path: RepoPath.make(groups.path) });119};120121/** What `why` found: the line's commit and what is known of it. */122const 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});135136type LineOrigin = typeof LineOrigin.Type;137138const encodeOrigin = Schema.encodeEffect(LineOrigin);139140const decodeNote = Schema.decodeOption(Schema.fromJsonString(Verdict));141142const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>143 bytes.pipe(Stream.decodeText(), Stream.mkString);144145/** Runs git in `cwd` to the end: its stdout and exit code; stderr is dropped. */146const git = (cwd: string, args: readonly string[]) =>147 Effect.scoped(148 Effect.gen(function* () {149 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;150151 const child = yield* spawner.spawn(152 ChildProcess.make("git", args, {153 cwd,154 stderr: "ignore",155 stdin: "ignore",156 })157 );158159 const [stdout, exitCode] = yield* Effect.all(160 [text(child.stdout), child.exitCode],161 { concurrency: "unbounded" }162 );163164 return { exitCode, stdout };165 })166 );167168/** The line is in no file committed at HEAD. */169const 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 );173174/** `path` as the repo names it from its root, if HEAD holds it. */175const 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 !== "");188189 return exitCode === 0 && only !== undefined && more.length === 0190 ? Effect.succeed(RepoPath.make(only))191 : noSuchLine(location);192 }193 );194195// git blame's porcelain opens with the line's commit, then its line numbers.196const BLAMED = /^(?<sha>[0-9a-f]{40}) /u;197198/** The commit that last changed line `line` of `path` at HEAD. */199const 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;212213 return exitCode === 0 && sha !== undefined214 ? Effect.succeed(CommitSha.make(sha))215 : noSuchLine(location);216 }217 );218219/** The trailers `sha`'s author wrote, as git reads them. */220const trailersOf = (cwd: string, sha: CommitSha) =>221 Effect.map(git(cwd, ["log", "-1", "--format=%B", sha]), ({ stdout }) =>222 parseTrailers(stdout)223 );224225/** The verdict note on `sha`, if one was fetched and it reads as a verdict. */226const 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 }233234 const note = decodeNote(stdout.trim());235236 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 );245246const short = (sha: string) => sha.slice(0, 7);247248/** One fact about the line, as a list item. */249interface Row {250 readonly label: string;251 readonly value: string;252 /** Code in Markdown: an id or a path. */253 readonly code?: boolean;254}255256const 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});263264const 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];281282const trailerRows = (trailers: readonly Trailer[]): readonly Row[] =>283 trailers.map(({ key, value }) => ({ label: key, value }));284285/** The line's story, in Markdown for agents and plain text for a person. */286const 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;290291 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 );304305 const rows = [306 ...(origin.landing === undefined ? [] : landingRows(origin.landing)),307 ...trailerRows(origin.trailers ?? []),308 ...(verdict === undefined ? [] : [verdictRow(verdict)]),309 ];310311 const empty =312 origin.landing === undefined && (origin.trailers ?? []).length === 0313 ? ["It carries no trailers."]314 : [];315316 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};333334export 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 });364365 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;371372 const landing = yield* client.landing({ project: name, sha }).pipe(373 Effect.map(({ landing: found }) => Option.some(found)),374 Effect.catchTag("UnknownCommit", () => Effect.succeedNone)375 );376377 const trailers = Option.isNone(landing)378 ? Option.some(yield* trailersOf(cwd, sha))379 : Option.none();380381 const note = yield* noteOn(cwd, sha);382383 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 };400401 const data = yield* encodeOrigin(origin).pipe(Effect.orDie);402403 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 line
modified:apps/cli/src/main.ts+9 added-4 removed
11 unmodified lines
1213import { credential } from "./credential-helper.ts";14import { CredentialsFile } from "./credentials.ts";15import { hook } from "./hook.ts";16import { refuseStrangeFlags } from "./local/env-set.ts";17import { holdStdout, Output, OutputLive } from "./output.ts";18import { CurrentMode, Policy } from "./policy.ts";19import {20 isTransportFailure,
137 unmodified lines
158/**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 */169export const program = (argv: readonly string[]) =>170 Effect.gen(function* () {171 yield* refuseStrangeFlags(argv);172173 const policy = yield* Effect.serviceOption(Policy);174 const stdout = holdStdout(yield* Console.Console);175176 const exit = yield* Effect.exit(
35 unmodified lines
added:apps/cli/test/local/env-set.test.ts+510 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Client, Contracts } from "@repo/protocol/contracts";5import type { SetEnv } from "@repo/protocol/contracts";6import { Envelope } from "@repo/protocol/envelope";7import { EnvKey, Handle } from "@repo/protocol/ids";8import { NotSensitive, ValueTooShort } from "@repo/protocol/refusal";9import { explain } from "@repo/protocol/render";10import { asTester, unanswered } from "@repo/protocol/testing";11import {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";29import { CliOutput } from "effect/cli";30import { RpcTest } from "effect/rpc";31import type { Rpc } from "effect/rpc";32import { TestConsole } from "effect/testing";3334import { refuseStrangeFlags } from "../../src/local/env-set.ts";35import { program } from "../../src/main.ts";36import { Output, OutputPlain } from "../../src/output.ts";37import type { Mode } from "../../src/output.ts";3839/** A value no output, note or log line may ever hold. */40const secret = "sk_live_0123456789abcdef";4142const key = EnvKey.make("SENTRY_AUTH_TOKEN");4344const setAt = DateTime.makeUnsafe("2026-10-07T09:00:00Z");4546/** A person piping the value in, as `printf '…\n' |` does. */47const piped = Stream.make(new TextEncoder().encode(`${secret}\n`));4849type Payload = Rpc.Payload<typeof SetEnv>;5051/** What the platform answers `setEnv` with. */52type Answer = Effect.Effect<53 Rpc.Success<typeof SetEnv>,54 NotSensitive | ValueTooShort55>;5657const stored: Answer = Effect.succeed({58 key,59 setAt,60 setBy: Handle.make("alice"),61});6263/** One call through `Output`, as the command made it. */64interface 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}6970/**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 */74interface 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}8384interface 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}9394/** How the process would exit, by the runtime's own rule. */95const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>96 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));9798const press = (name: string, input: Option.Option<string>) => ({99 input,100 key: { ctrl: false, meta: false, name, shift: false },101});102103/**104 * Runs `<cli> env set …` with `setup`'s stdin, terminal and platform, and105 * returns everything it printed, logged and asked.106 */107const 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[] = [];113114 const record = (method: Printed["method"], input: Printed["input"]) =>115 Ref.update(printed, (all) => [...all, { input, method }]);116117 // 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);122123 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));136137 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 }145146 const keys = yield* Queue.unbounded<Terminal.UserInput, Cause.Done>();147148 yield* Queue.offerAll(keys, [149 ...setup.typed150 .split("")151 .map((char) => press(char, Option.some(char))),152 press("enter", Option.none()),153 ]);154155 return keys;156 }),157 readLine: Effect.die("readLine is never used"),158 rows: Effect.succeed(24),159 })160 );161162 // 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 );176177 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 );199200 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));210211/** Asserts the value reached no output, note, log line or terminal frame. */212const 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};224225const decodeEnvelope = Schema.decodeEffect(226 Schema.fromJsonString(Envelope(Schema.Unknown))227);228229/** The one call the platform got, with its value opened for the check. */230const onlyCall = (ran: Ran) => {231 expect(ran.calls).toHaveLength(1);232233 const [call] = ran.calls;234235 expect(call).toBeDefined();236 expect(Redacted.isRedacted(call?.value)).toBeTruthy();237238 return {239 ...call,240 value: call === undefined ? undefined : Redacted.value(call.value),241 };242};243244const always = ["--project", "datekit"];245246describe(`${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"]);252253 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 );273274 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"]);279280 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 );286287 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"]);303304 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 );314315 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);326327 expect(ran.code).toBe(0);328 expect(ran.out).toContain(shows);329 }).pipe(Effect.provide(NodeServices.layer))330 );331332 it.live("screens out no flag that `env set --help` names", () =>333 Effect.gen(function* () {334 const help = yield* run(["--help"]);335336 const named = help.out.split("\n").flatMap((line) => {337 const flags = /^\s+(?<flags>-[^\s,]+(?:, -[^\s,]+)*)/u.exec(line)338 ?.groups?.flags;339340 return flags === undefined ? [] : flags.split(", ");341 });342343 expect(named).toStrictEqual(344 expect.arrayContaining(["--yes", "--project", "--help", "-h"])345 );346347 const screened = yield* Effect.filter(named, (flag) =>348 Effect.map(349 Effect.exit(refuseStrangeFlags(["env", "set", key, flag])),350 Exit.isFailure351 )352 );353354 expect(screened).toStrictEqual([]);355 }).pipe(356 Effect.provide([NodeServices.layer, OutputPlain, TestConsole.layer])357 )358 );359360 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 });369370 expect(ran.code).toBe(0);371 expect(onlyCall(ran).value).toBe(kept);372 }).pipe(Effect.provide(NodeServices.layer))373 );374375 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 });385386 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 );391392 it.live("without --yes, exits 2 naming it and calls nothing", () =>393 Effect.gen(function* () {394 const ran = yield* run([key, ...always]);395396 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 );402403 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"]);408409 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 );440441 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 });451452 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 );458459 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"]);462463 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 );472473 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 });481482 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 );488489 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 });498499 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
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Client, Contracts } from "@repo/protocol/contracts";5import { Verdict } from "@repo/protocol/domain/answer";6import type { LandingView } from "@repo/protocol/domain/landing";7import { Outcome } from "@repo/protocol/domain/outcome";8import { Envelope } from "@repo/protocol/envelope";9import {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";21import { UnknownCommit, UnknownProject } from "@repo/protocol/refusal";22import { explain } from "@repo/protocol/render";23import { asTester, unanswered } from "@repo/protocol/testing";24import { gitOk } from "@repo/testkit/git";25import {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";39import { CliOutput } from "effect/cli";40import { RpcTest } from "effect/rpc";41import { TestConsole } from "effect/testing";4243import { WorkingDirectory, parseLocation } from "../../src/local/why.ts";44import { program } from "../../src/main.ts";45import { Output, OutputPlain } from "../../src/output.ts";4647const project = ProjectName.make("datekit");4849const alice = Handle.make("alice");5051const carol = Handle.make("carol");5253/** The second commit's message: its trailers, as an answerer wrote them. */54const 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");6162/**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 */66const 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");7172 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");8081 const first = CommitSha.make(yield* gitOk(dir, "rev-parse", "HEAD"));8283 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);8889 const second = CommitSha.make(yield* gitOk(dir, "rev-parse", "HEAD"));9091 return { dir, first, second };92});9394/** What the platform was asked: each `landing` call's payload. */95type Asked = readonly { readonly project: string; readonly sha: string }[];9697/** A record of `landing` calls, none yet. */98const noCalls = Ref.make<Asked>([]);99100/** The platform's record of the second commit's landing. */101const 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});113114/** The same landing as `--json` prints it. */115const 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});127128/**129 * The platform in process, answering `landing` with `answer` and every130 * other contract never: a test reaching one fails.131 */132const 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 );147148/**149 * A platform that knows `landed` as a landing and no other commit, and150 * records every `landing` call it is asked.151 */152const 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 );165166/**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 */170const 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});177178/** How the process would exit, by the runtime's own rule. */179const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>180 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));181182/**183 * Runs `<cli> why …` in `dir` against `client`, printing through `output`,184 * and returns its exit code, stdout and stderr.185 */186const 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 );198199 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 );214215const decodeEnvelope = Schema.decodeEffect(216 Schema.fromJsonString(Envelope(Schema.Unknown))217);218219describe("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 });225226 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 });231232 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});246247describe(`${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;254255 const ran = yield* run(256 dir,257 ["src/week.ts:3", "--project", "datekit", "--json"],258 platformKnowing(Option.some(second), calls)259 );260261 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 );279280 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;286287 const ran = yield* run(288 dir,289 ["src/week.ts:3", "--project", "datekit"],290 platformKnowing(Option.some(second), calls),291 OutputForAgent292 );293294 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 );307308 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);315316 const json = yield* run(317 dir,318 ["src/week.ts:3", "--project", "datekit", "--json"],319 unknowing320 );321322 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 });338339 const text = yield* run(340 dir,341 ["src/week.ts:3", "--project", "datekit"],342 unknowing343 );344345 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 );356357 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;365366 const ran = yield* run(367 dir,368 [...args, "--project", "datekit"],369 platformKnowing(Option.none(), calls)370 );371372 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 );378379 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;385386 const ran = yield* run(387 `${dir}/src`,388 ["week.ts:3", "--project", "datekit", "--json"],389 platformKnowing(Option.some(second), calls)390 );391392 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 );398399 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;405406 yield* gitOk(407 dir,408 "remote",409 "add",410 "origin",411 `https://${Brand.domain}/datekit.git`412 );413414 const ran = yield* run(415 dir,416 ["src/week.ts:3", "--json"],417 platformKnowing(Option.some(second), calls)418 );419420 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 );426427 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;433434 const ran = yield* run(435 dir,436 ["src/week.ts:3"],437 platformKnowing(Option.none(), calls)438 );439440 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 );445446 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;450451 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 };473474 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 );483484 const ran = yield* run(485 dir,486 ["src/week.ts:3", "--project", "datekit", "--json"],487 platformKnowing(Option.some(second), calls)488 );489490 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 );505506 it.live("prints a refusal from the platform once, and exits 1", () =>507 Effect.gen(function* () {508 const { dir } = yield* aRepo;509510 const ran = yield* run(511 dir,512 ["src/week.ts:3", "--project", "datekit"],513 platform(() => Effect.fail(new UnknownProject({ project })))514 );515516 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 lines
94});9596describe("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;100101 it.effect.each(stubs)(
15 unmodified lines