Skip to content
Myr

Explain a line with `<cli> why`, and store a write-only env value with `<cli> env set` that nobody can read back

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

W4 group A (414). Both stubs 401 left in apps/cli/src/local are replaced; local/index.ts and main.ts are unchanged. - `why <path:line> [--project] [--json]`: `parseLocation` splits at the last colon (a line from 1, no sign, safe integer); `git ls-tree --full-name HEAD` gives the repo-root path and `git blame --porcelain -L n,n HEAD` the commit; `landing({project, sha})` gives the record. UnknownCommit falls back to the commit's own trailers through @repo/git's parseTrailers and says it is not a platform landing. A verdict note under refs/notes/<slug>, when fetched, is added as `data.note`; the landing record stays the source. `data` is one schema (LineOrigin: path, line, sha, landing?, trailers?, note?) encoded once; the view is Markdown for agents (ask, author, each credit role, Assisted-by, verdict) and text for a person. - `env set <KEY> [--project] [--acknowledge-short] [--yes] [--dry-run] [--json]`: the value comes only from stdin, less one trailing newline (CRLF counts as one), as a Redacted straight into setEnv's payload. A person at a terminal gets Prompt.Hidden, not Prompt.Password: Password prints one `*` per character, which tells the length. Under an agent or a script a terminal on stdin is a usage error telling the person to pipe the value. A value typed as an argument is caught by a variadic `not-the-value` positional, since effect/cli's UnexpectedArgument message would quote it. Without --yes: exit 2, nothing read or called. --dry-run plans `{key, project, value: "<redacted>"}` (acknowledgeShort only when set, as the real payload) and reads nothing. Refusals (NotSensitive, ValueTooShort, …) print once through Output.refused and exit 1. The reply is only `{key, setBy, setAt}`. No read-back of any kind. - Usage errors print one stderr line through Output.note, then die with UsageError (Runtime.errorExitCode 2, errorReported false): 401's `program` turns every typed failure into Reported (exit 1) and lets defects through, and main.ts is 404's. 414's Comments ask the integrator to make it a typed failure once 404's program maps usage errors to exit 2. - Shared helpers sit in why.ts (the territory is two files) and env-set.ts imports them: WorkingDirectory (a Context.Reference, default "." so git runs in the process's folder; tests provide a temp repo), usage/UsageError, reportRefusals, projectOf (--project, else the repo's platform remote). 405 and 413 need the same; hoisting is in the Comments. - Outside the territory: apps/cli/test/main.test.ts drops the `why` and `env set` rows from the stub list, since they no longer die (merge note in the Comments). - Tests, each red by assertion first (the stubs died; parseLocation returned none): apps/cli/test/local/why.test.ts (parseLocation cases; it.live on a two-commit temp repo with Asked-by/Signed-off-by/Assisted-by trailers: one envelope with the landing record and the call's payload, Markdown rows for an agent, the UnknownCommit fallback in JSON and text, exit 2 for a line past the end, a file not in HEAD and no line with no call, a fetched note's verdict in data.note, UnknownProject printed once with exit 1) and apps/cli/test/local/env-set.test.ts (the exact payload with the value opened from its Redacted and no acknowledgeShort key, the success envelope, the value absent from stdout, stderr, every Output call, terminal frames and log lines recorded at level All; a value as an argument, no --yes, dry-run, NotSensitive and ValueTooShort once, --acknowledge-short, agent with a terminal on stdin never prompting, a hidden prompt that shows neither the value nor a mask). The platform is faked in process with RpcTest.makeClient(Contracts) over `unanswered` plus the one handler; exit codes are read from program(argv)'s Exit by the runtime's own rule. - ASSUMPTION: `why` numbers lines as committed at HEAD (blame of HEAD, not the work tree), so an uncommitted edit never yields a zero sha. - ASSUMPTION: an empty value is a usage error; emptiness is the only property of the value the CLI looks at. - bun run fix && bun run verify green: cli 71 tests (45 + 28 new − 2 stub rows); gen:check current, imports:check no violations, debt at baseline, brand:check no leaks, bytes platform 1,513,290 of 1,665,000.

authored by oscabriel · committed by oscabriel · parent 650cb35 · Browse files · 5 files+1432 added−12 removed
This commit

State

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

Diff stats

5 files+1432 added−12 removed

  • tests:+848 added−2 removed
  • other:+584 added−10 removed

5 files+1432 added−12 removed

modified:apps/cli/src/local/env-set.ts+179 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
added:apps/cli/test/local/env-set.test.ts+392 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 { program } from "../../src/main.ts";35import { Output, OutputPlain } from "../../src/output.ts";36import type { Mode } from "../../src/output.ts";3738/** A value no output, note or log line may ever hold. */39const secret = "sk_live_0123456789abcdef";4041const key = EnvKey.make("SENTRY_AUTH_TOKEN");4243const setAt = DateTime.makeUnsafe("2026-10-07T09:00:00Z");4445/** A person piping the value in, as `printf '…\n' |` does. */46const piped = Stream.make(new TextEncoder().encode(`${secret}\n`));4748type Payload = Rpc.Payload<typeof SetEnv>;4950/** What the platform answers `setEnv` with. */51type Answer = Effect.Effect<52 Rpc.Success<typeof SetEnv>,53 NotSensitive | ValueTooShort54>;5556const stored: Answer = Effect.succeed({57 key,58 setAt,59 setBy: Handle.make("alice"),60});6162/** One call through `Output`, as the command made it. */63interface Printed {64 readonly method: "success" | "refused" | "plan" | "note";65 /** The call's input: a note's text, or the others' object. */66 readonly input: object | string;67}6869/**70 * How one run went: its exit code, what reached stdout, stderr and the71 * logger, what the platform was asked, and what the command handed `Output`.72 */73interface Ran {74 readonly code: number;75 readonly out: string;76 readonly err: string;77 readonly logged: string;78 readonly calls: readonly Payload[];79 readonly printed: readonly Printed[];80 readonly shown: string;81}8283interface Setup {84 /** Who reads: 401's person at a terminal, or 404's agent policy. */85 readonly mode?: Mode;86 readonly stdin?: Stream.Stream<Uint8Array>;87 readonly stdinIsTerminal?: boolean;88 /** What a person types at the hidden prompt, key by key. */89 readonly typed?: string;90 readonly answer?: Answer;91}9293/** How the process would exit, by the runtime's own rule. */94const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>95 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));9697const press = (name: string, input: Option.Option<string>) => ({98 input,99 key: { ctrl: false, meta: false, name, shift: false },100});101102/**103 * Runs `<cli> env set …` with `setup`'s stdin, terminal and platform, and104 * returns everything it printed, logged and asked.105 */106const run = (args: readonly string[], setup: Setup = {}) =>107 Effect.gen(function* () {108 const calls = yield* Ref.make<readonly Payload[]>([]);109 const printed = yield* Ref.make<readonly Printed[]>([]);110 const shown = yield* Ref.make<readonly string[]>([]);111 const logged: string[] = [];112113 const record = (method: Printed["method"], input: Printed["input"]) =>114 Ref.update(printed, (all) => [...all, { input, method }]);115116 // 401's plain output, recorded, as whichever reader `setup` names.117 const output = Layer.effect(118 Output,119 Effect.gen(function* () {120 const plain = yield* Effect.service(Output);121122 return {123 mode: setup.mode ?? "human",124 note: (text) =>125 Effect.andThen(record("note", text), plain.note(text)),126 plan: (input) =>127 Effect.andThen(record("plan", input), plain.plan(input)),128 refused: (input) =>129 Effect.andThen(record("refused", input), plain.refused(input)),130 success: (input) =>131 Effect.andThen(record("success", input), plain.success(input)),132 } satisfies Output["Service"];133 })134 ).pipe(Layer.provide(OutputPlain));135136 const terminal = Layer.succeed(Terminal.Terminal)(137 Terminal.make({138 columns: Effect.succeed(80),139 display: (text) => Ref.update(shown, (all) => [...all, text]),140 readInput: Effect.gen(function* () {141 if (setup.typed === undefined) {142 return yield* Effect.die("prompted, where no prompt may run");143 }144145 const keys = yield* Queue.unbounded<Terminal.UserInput, Cause.Done>();146147 yield* Queue.offerAll(keys, [148 ...setup.typed149 .split("")150 .map((char) => press(char, Option.some(char))),151 press("enter", Option.none()),152 ]);153154 return keys;155 }),156 readLine: Effect.die("readLine is never used"),157 rows: Effect.succeed(24),158 })159 );160161 // The platform in process: `setEnv` records what it got and answers.162 const platform = Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(163 Layer.provide([164 Layer.mergeAll(165 unanswered,166 Contracts.toLayerHandler("setEnv", (payload) =>167 Ref.update(calls, (all) => [...all, payload]).pipe(168 Effect.andThen(setup.answer ?? stored)169 )170 )171 ),172 asTester,173 ])174 );175176 const exit = yield* Effect.exit(177 program(["env", "set", ...args]).pipe(178 Effect.provide(179 Layer.mergeAll(180 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),181 platform,182 output,183 terminal,184 Logger.layer([185 Logger.make((options) => {186 logged.push(Logger.formatSimple.log(options));187 }),188 ]),189 Stdio.layerTest({190 stdin: setup.stdin ?? piped,191 stdinIsTerminal: Effect.succeed(setup.stdinIsTerminal ?? false),192 })193 )194 ),195 Effect.provideService(References.MinimumLogLevel, "All")196 )197 );198199 return {200 calls: yield* Ref.get(calls),201 code: exitCodeOf(exit),202 err: (yield* TestConsole.errorLines).map(String).join("\n"),203 logged: logged.join("\n"),204 out: (yield* TestConsole.logLines).map(String).join("\n"),205 printed: yield* Ref.get(printed),206 shown: (yield* Ref.get(shown)).join(""),207 } satisfies Ran;208 }).pipe(Effect.provide(TestConsole.layer));209210/** Asserts the value reached no output, note, log line or terminal frame. */211const neverShown = (ran: Ran) => {212 for (const seen of [213 ran.out,214 ran.err,215 ran.logged,216 ran.shown,217 JSON.stringify(ran.printed),218 ]) {219 expect(seen).not.toContain(secret);220 expect(seen).not.toContain("0123456789abcdef");221 }222};223224const decodeEnvelope = Schema.decodeEffect(225 Schema.fromJsonString(Envelope(Schema.Unknown))226);227228/** The one call the platform got, with its value opened for the check. */229const onlyCall = (ran: Ran) => {230 expect(ran.calls).toHaveLength(1);231232 const [call] = ran.calls;233234 expect(call).toBeDefined();235 expect(Redacted.isRedacted(call?.value)).toBeTruthy();236237 return {238 ...call,239 value: call === undefined ? undefined : Redacted.value(call.value),240 };241};242243const always = ["--project", "datekit"];244245describe(`${Brand.cli} env set`, () => {246 it.live(247 "sends the piped value, less one newline, as a Redacted, and prints only who set which key and when",248 () =>249 Effect.gen(function* () {250 const ran = yield* run([key, ...always, "--yes", "--json"]);251252 expect(ran.code).toBe(0);253 expect(onlyCall(ran)).toStrictEqual({254 key: "SENTRY_AUTH_TOKEN",255 project: "datekit",256 value: secret,257 });258 expect(ran.err).toBe("");259 expect(yield* decodeEnvelope(ran.out)).toStrictEqual({260 command: "env set",261 data: {262 key: "SENTRY_AUTH_TOKEN",263 setAt: "2026-10-07T09:00:00.000Z",264 setBy: "alice",265 },266 ok: true,267 v: 1,268 });269 neverShown(ran);270 }).pipe(Effect.provide(NodeServices.layer))271 );272273 it.live(274 "refuses a value given as an argument, as a usage error that does not echo it",275 () =>276 Effect.gen(function* () {277 const ran = yield* run([key, secret, ...always, "--yes"]);278279 expect(ran.code).toBe(2);280 expect(ran.calls).toStrictEqual([]);281 expect(ran.err).toContain("stdin");282 neverShown(ran);283 }).pipe(Effect.provide(NodeServices.layer))284 );285286 it.live("without --yes, exits 2 naming it and calls nothing", () =>287 Effect.gen(function* () {288 const ran = yield* run([key, ...always]);289290 expect(ran.code).toBe(2);291 expect(ran.calls).toStrictEqual([]);292 expect(ran.err).toContain("--yes");293 neverShown(ran);294 }).pipe(Effect.provide(NodeServices.layer))295 );296297 it.live(298 "with --dry-run, hands over the payload it would send with the value redacted, and calls nothing",299 () =>300 Effect.gen(function* () {301 const ran = yield* run([key, ...always, "--dry-run", "--json"]);302303 expect(ran.code).toBe(0);304 expect(ran.calls).toStrictEqual([]);305 expect(ran.printed).toStrictEqual([306 {307 input: {308 command: "env set",309 json: true,310 payload: {311 key: "SENTRY_AUTH_TOKEN",312 project: "datekit",313 value: "<redacted>",314 },315 },316 method: "plan",317 },318 ]);319 neverShown(ran);320 }).pipe(Effect.provide(NodeServices.layer))321 );322323 it.live.each([324 { refusal: new NotSensitive({ key }) },325 { refusal: ValueTooShort.of(key, 12) },326 ])(327 "prints $refusal._tag from the platform once, and exits 1",328 ({ refusal }: { readonly refusal: NotSensitive | ValueTooShort }) =>329 Effect.gen(function* () {330 const ran = yield* run([key, ...always, "--yes"], {331 answer: Effect.fail(refusal),332 });333334 expect(ran.code).toBe(1);335 expect(ran.out).toBe("");336 expect(ran.err).toBe(explain([refusal]).join("\n"));337 neverShown(ran);338 }).pipe(Effect.provide(NodeServices.layer))339 );340341 it.live("with --acknowledge-short, asks to store a short value anyway", () =>342 Effect.gen(function* () {343 const ran = yield* run([key, ...always, "--yes", "--acknowledge-short"]);344345 expect(ran.code).toBe(0);346 expect(onlyCall(ran)).toStrictEqual({347 acknowledgeShort: true,348 key: "SENTRY_AUTH_TOKEN",349 project: "datekit",350 value: secret,351 });352 }).pipe(Effect.provide(NodeServices.layer))353 );354355 it.live(356 "under an agent with a terminal on stdin, never prompts: it tells the person to pipe the value",357 () =>358 Effect.gen(function* () {359 const ran = yield* run([key, ...always, "--yes"], {360 mode: "agent",361 stdinIsTerminal: true,362 });363364 expect(ran.code).toBe(2);365 expect(ran.calls).toStrictEqual([]);366 expect(ran.err).toContain("pipe");367 expect(ran.shown).toBe("");368 }).pipe(Effect.provide(NodeServices.layer))369 );370371 it.live(372 "asks a person at a terminal with a prompt that shows nothing typed, not even its length",373 () =>374 Effect.gen(function* () {375 const ran = yield* run([key, ...always, "--yes"], {376 stdin: Stream.empty,377 stdinIsTerminal: true,378 typed: secret,379 });380381 expect(ran.code).toBe(0);382 expect(onlyCall(ran)).toStrictEqual({383 key: "SENTRY_AUTH_TOKEN",384 project: "datekit",385 value: secret,386 });387 expect(ran.shown).toContain(key);388 expect(ran.shown).not.toContain("*");389 neverShown(ran);390 }).pipe(Effect.provide(NodeServices.layer))391 );392});
added:apps/cli/test/local/why.test.ts+456 added
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("adds the verdict a fetched note carries on that commit", () =>380 Effect.gen(function* () {381 const { dir, first, second } = yield* aRepo;382 const calls = yield* noCalls;383384 const verdict: Verdict = {385 ask: AskId.make("fix-week"),386 at: DateTime.makeUnsafe("2026-10-06T11:59:00Z"),387 base: first,388 checkVersion: CheckVersion.make("checks@1"),389 head: second,390 heldBack: [],391 lanes: [392 {393 command: "bun test",394 durationMs: 1200,395 lane: LaneName.make("test"),396 result: "passed",397 },398 ],399 outcome: Outcome.cases.Landed.make({ sha: LandedSha.make(second) }),400 patchId: PatchId.make("a".repeat(64)),401 project,402 stage: "checks",403 tree: TreeSha.make(yield* gitOk(dir, "rev-parse", "HEAD^{tree}")),404 verifier: "platform",405 };406407 yield* gitOk(408 dir,409 "notes",410 `--ref=refs/notes/${Brand.slug}`,411 "add",412 "-m",413 yield* Schema.encodeEffect(Schema.fromJsonString(Verdict))(verdict),414 second415 );416417 const ran = yield* run(418 dir,419 ["src/week.ts:3", "--project", "datekit", "--json"],420 platformKnowing(Option.some(second), calls)421 );422423 expect(ran.code).toBe(0);424 expect(yield* decodeEnvelope(ran.out)).toStrictEqual({425 command: "why",426 data: {427 landing: landingJson(second),428 line: 3,429 note: yield* Schema.encodeEffect(Verdict)(verdict),430 path: "src/week.ts",431 sha: second,432 },433 ok: true,434 v: 1,435 });436 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))437 );438439 it.live("prints a refusal from the platform once, and exits 1", () =>440 Effect.gen(function* () {441 const { dir } = yield* aRepo;442443 const ran = yield* run(444 dir,445 ["src/week.ts:3", "--project", "datekit"],446 platform(() => Effect.fail(new UnknownProject({ project })))447 );448449 expect(ran.code).toBe(1);450 expect(ran.out).toBe("");451 expect(ran.err).toBe(452 explain([new UnknownProject({ project })]).join("\n")453 );454 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))455 );456});
modified:apps/cli/test/main.test.ts-2 removed
96 unmodified lines
97 { args: ["logout"], issue: "412" },98 { args: ["credential"], issue: "412" },99 { args: ["init"], issue: "413" },100 { args: ["check"], issue: "405" },101 { args: ["why"], issue: "414" },102 { args: ["env", "set"], issue: "414" },101 { args: ["hook"], issue: "415" },102 ] as const;103104 it.effect.each(stubs)(
15 unmodified lines