why.test.ts
This file
Path
apps/cli/test/local/why.test.ts
543 lines · 15.5 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–37why, one step back1import { 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,Merge build/1002oscabrielbefore adoption1a364b9
line 38why, one step back38 Struct,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 39–48why, one step back39} from "effect";40import { CliOutput } from "effect/cli";41import { RpcTest } from "effect/rpc";42import { TestConsole } from "effect/testing";4344import { WorkingDirectory, parseLocation } from "../../src/local/why.ts";45import { program } from "../../src/main.ts";46import { Output, OutputPlain } from "../../src/output.ts";47import { SignedOut } from "../signed-out.ts";48Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 49why, one step back49const project = ProjectName.make("oscabriel/datekit");Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 50–116why, one step back5051const alice = Handle.make("alice");5253const carol = Handle.make("carol");5455const message = [56 "Start the week on Monday",57 "",58 "Asked-by: carol",59 "Signed-off-by: alice",60 "Assisted-by: claude-code",61].join("\n");6263const aRepo = Effect.gen(function* () {64 const fs = yield* FileSystem.FileSystem;65 const path = yield* Path.Path;66 const dir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());67 const file = path.join(dir, "src", "week.ts");6869 yield* gitOk(dir, "init", "--quiet", "--initial-branch=main");70 yield* fs.makeDirectory(path.join(dir, "src"));71 yield* fs.writeFileString(72 file,73 "export const days = 7;\nexport const weekend = [6, 0];\n"74 );75 yield* gitOk(dir, "add", ".");76 yield* gitOk(dir, "commit", "--quiet", "-m", "Count the days of a week");7778 const first = CommitSha.make(yield* gitOk(dir, "rev-parse", "HEAD"));7980 yield* fs.writeFileString(81 file,82 "export const days = 7;\nexport const weekend = [6, 0];\nexport const firstDay = 1;\n"83 );84 yield* gitOk(dir, "commit", "--quiet", "-am", message);8586 const second = CommitSha.make(yield* gitOk(dir, "rev-parse", "HEAD"));8788 return { dir, first, second };89});9091type Asked = readonly { readonly project: string; readonly sha: string }[];9293const noCalls = Ref.make<Asked>([]);9495const landingOf = (sha: CommitSha): LandingView => ({96 ask: AskId.make("fix-week"),97 assisted: [{ harness: "claude-code", verified: false }],98 author: alice,99 credits: [100 { handle: carol, role: "Asked-by" },101 { handle: alice, role: "Signed-off-by" },102 ],103 landedAt: DateTime.makeUnsafe("2026-10-06T12:00:00Z"),104 project,105 sha: LandedSha.make(sha),106});107108const landingJson = (sha: string) => ({109 ask: "fix-week",110 assisted: [{ harness: "claude-code", verified: false }],111 author: "alice",112 credits: [113 { handle: "carol", role: "Asked-by" },114 { handle: "alice", role: "Signed-off-by" },115 ],116 landedAt: "2026-10-06T12:00:00.000Z",Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 117why, one step back117 project: "oscabriel/datekit",Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 118–233why, one step back118 sha,119});120121const platform = (122 answer: (payload: {123 readonly project: ProjectName;124 readonly sha: CommitSha;125 }) => Effect.Effect<126 { readonly landing: LandingView },127 UnknownCommit | UnknownProject128 >129) =>130 Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(131 Layer.provide([132 Layer.mergeAll(unanswered, Contracts.toLayerHandler("landing", answer)),133 asTester,134 ])135 );136137const platformKnowing = (138 landed: Option.Option<CommitSha>,139 calls: Ref.Ref<Asked>140) =>141 platform(({ project: asked, sha }) =>142 Ref.update(calls, (all) => [...all, { project: asked, sha }]).pipe(143 Effect.andThen(144 Option.exists(landed, (known) => known === sha)145 ? Effect.succeed({ landing: landingOf(sha) })146 : Effect.fail(new UnknownCommit({ sha }))147 )148 )149 );150151const OutputForAgent = Layer.succeed(Output)({152 mode: "agent",153 note: (text) => Console.error(text),154 plan: ({ payload }) => Console.log(JSON.stringify(payload)),155 refused: ({ refusals }) => Console.error(explain(refusals).join("\n")),156 success: ({ view }) => Console.log(view.markdown),157});158159const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>160 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));161162const run = (163 dir: string,164 args: readonly string[],165 client: Layer.Layer<Client>,166 output: Layer.Layer<Output> = OutputPlain167) =>168 Effect.gen(function* () {169 const exit = yield* Effect.exit(170 program(["why", ...args]).pipe(171 Effect.provideService(WorkingDirectory, dir)172 )173 );174175 return {176 code: exitCodeOf(exit),177 err: (yield* TestConsole.errorLines).map(String).join("\n"),178 out: (yield* TestConsole.logLines).map(String).join("\n"),179 };180 }).pipe(181 Effect.provide(182 Layer.mergeAll(183 TestConsole.layer,184 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),185 client,186 output,187 SignedOut188 )189 )190 );191192const decodeEnvelope = Schema.decodeEffect(193 Schema.fromJsonString(Envelope(Schema.Unknown))194);195196describe("a line's location", () => {197 it("is a path and a line number", () => {198 expect(parseLocation("src/week.ts:42")).toStrictEqual(199 Option.some({ line: 42, path: RepoPath.make("src/week.ts") })200 );201 });202203 it("splits at the last colon, so a path may hold one", () => {204 expect(parseLocation("docs/a:b.md:7")).toStrictEqual(205 Option.some({ line: 7, path: RepoPath.make("docs/a:b.md") })206 );207 });208209 it.each([210 "src/week.ts",211 "src/week.ts:",212 ":3",213 "src/week.ts:0",214 "src/week.ts:-1",215 "src/week.ts:+3",216 "src/week.ts:3.5",217 "src/week.ts:three",218 "src/week.ts:99999999999999999999",219 ])("is no line: %j", (text) => {220 expect(parseLocation(text)).toStrictEqual(Option.none());221 });222});223224describe(`${Brand.cli} why`, () => {225 it.live(226 "prints one envelope with the line's commit and the platform's landing record",227 () =>228 Effect.gen(function* () {229 const { dir, second } = yield* aRepo;230 const calls = yield* noCalls;231232 const ran = yield* run(233 dir,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 234why, one step back234 ["src/week.ts:3", "--project", "oscabriel/datekit", "--json"],Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 235–251why, one step back235 platformKnowing(Option.some(second), calls)236 );237238 expect(ran.code).toBe(0);239 expect(ran.err).toBe("");240 expect(yield* decodeEnvelope(ran.out)).toStrictEqual({241 command: "why",242 data: {243 landing: landingJson(second),244 line: 3,245 path: "src/week.ts",246 sha: second,247 },248 ok: true,249 v: 1,250 });251 expect(yield* Ref.get(calls)).toStrictEqual([Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 252why, one step back252 { project: "oscabriel/datekit", sha: second },Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 253–265why, one step back253 ]);254 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))255 );256257 it.live(258 "tells an agent, in Markdown, the ask, the author and each credit",259 () =>260 Effect.gen(function* () {261 const { dir, second } = yield* aRepo;262 const calls = yield* noCalls;263264 const ran = yield* run(265 dir,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 266why, one step back266 ["src/week.ts:3", "--project", "oscabriel/datekit"],Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 267–280why, one step back267 platformKnowing(Option.some(second), calls),268 OutputForAgent269 );270271 expect(ran.code).toBe(0);272 expect(ran.out.split("\n")).toStrictEqual(273 expect.arrayContaining([274 expect.stringContaining(`landing \`${second.slice(0, 7)}\``),275 "- Ask: `fix-week`",276 "- Author: alice",277 "- Asked-by: carol",278 "- Signed-off-by: alice",279 "- Assisted-by: claude-code (claimed)",280 ])Merge build/1002oscabrielbefore adoption1a364b9
lines 281–301why, one step back281 );282 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))283 );284285 it.live(286 'names the ask a line\'s landing opened in an "Opened" row, and no ask it answers',287 () =>288 Effect.gen(function* () {289 const { dir } = yield* aRepo;290291 const opening = platform(({ sha }) =>292 Effect.succeed({293 landing: {294 ...Struct.omit(landingOf(sha), ["ask"]),295 opened: AskId.make("format-ordinal"),296 },297 })298 );299300 const agent = yield* run(301 dir,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 302why, one step back302 ["src/week.ts:3", "--project", "oscabriel/datekit"],Merge build/1002oscabrielbefore adoption1a364b9
lines 303–314why, one step back303 opening,304 OutputForAgent305 );306307 expect(agent.code).toBe(0);308 expect(agent.out.split("\n")).toStrictEqual(309 expect.arrayContaining(["- Opened: `format-ordinal`"])310 );311 expect(agent.out).not.toContain("- Ask:");312313 const person = yield* run(314 dir,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 315why, one step back315 ["src/week.ts:3", "--project", "oscabriel/datekit"],Merge build/1002oscabrielbefore adoption1a364b9
lines 316–321why, one step back316 opening317 );318319 expect(person.code).toBe(0);320 expect(person.out.split("\n").map((line) => line.trim())).toStrictEqual(321 expect.arrayContaining(["Opened: format-ordinal"])Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 322–335why, one step back322 );323 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))324 );325326 it.live(327 "says a commit the platform did not land is none of its landings, and lists the trailers it carries",328 () =>329 Effect.gen(function* () {330 const { dir, second } = yield* aRepo;331 const calls = yield* noCalls;332 const unknowing = platformKnowing(Option.none(), calls);333334 const json = yield* run(335 dir,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 336why, one step back336 ["src/week.ts:3", "--project", "oscabriel/datekit", "--json"],Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 337–358why, one step back337 unknowing338 );339340 expect(json.code).toBe(0);341 expect(yield* decodeEnvelope(json.out)).toStrictEqual({342 command: "why",343 data: {344 line: 3,345 path: "src/week.ts",346 sha: second,347 trailers: [348 { key: "Asked-by", value: "carol" },349 { key: "Signed-off-by", value: "alice" },350 { key: "Assisted-by", value: "claude-code" },351 ],352 },353 ok: true,354 v: 1,355 });356357 const text = yield* run(358 dir,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 359why, one step back359 ["src/week.ts:3", "--project", "oscabriel/datekit"],Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 360–385why, one step back360 unknowing361 );362363 expect(text.code).toBe(0);364 expect(text.out.split("\n").map((line) => line.trim())).toStrictEqual(365 expect.arrayContaining([366 expect.stringContaining("which is not a platform landing"),367 "Asked-by: carol",368 "Signed-off-by: alice",369 "Assisted-by: claude-code",370 ])371 );372 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))373 );374375 it.live.each([376 { args: ["src/week.ts:4"], why: "a line past the file's end" },377 { args: ["src/month.ts:1"], why: "a file not in HEAD" },378 { args: ["src/week.ts"], why: "no line at all" },379 ])("refuses $why as a usage error (exit 2), asking nothing", ({ args }) =>380 Effect.gen(function* () {381 const { dir } = yield* aRepo;382 const calls = yield* noCalls;383384 const ran = yield* run(385 dir,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 386why, one step back386 [...args, "--project", "oscabriel/datekit"],Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 387–405why, one step back387 platformKnowing(Option.none(), calls)388 );389390 expect(ran.code).toBe(2);391 expect(ran.out).toBe("");392 expect(ran.err).toContain(args[0] ?? "");393 expect(yield* Ref.get(calls)).toStrictEqual([]);394 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))395 );396397 it.live(398 "from a folder inside the repo, takes the path from there and names it from the repo's root",399 () =>400 Effect.gen(function* () {401 const { dir, second } = yield* aRepo;402 const calls = yield* noCalls;403404 const ran = yield* run(405 `${dir}/src`,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 406why, one step back406 ["week.ts:3", "--project", "oscabriel/datekit", "--json"],Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 407–439why, one step back407 platformKnowing(Option.some(second), calls)408 );409410 expect(ran.code).toBe(0);411 expect(yield* decodeEnvelope(ran.out)).toMatchObject({412 data: { line: 3, path: "src/week.ts", sha: second },413 });414 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))415 );416417 it.live(418 "without --project, asks about the project the repo's platform remote names",419 () =>420 Effect.gen(function* () {421 const { dir, second } = yield* aRepo;422 const calls = yield* noCalls;423424 yield* gitOk(425 dir,426 "remote",427 "add",428 "origin",429 `https://${Brand.domain}/datekit.git`430 );431432 const ran = yield* run(433 dir,434 ["src/week.ts:3", "--json"],435 platformKnowing(Option.some(second), calls)436 );437438 expect(ran.code).toBe(0);439 expect(yield* Ref.get(calls)).toStrictEqual([Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 440why, one step back440 { project: "oscabriel/datekit", sha: second },Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 441–503why, one step back441 ]);442 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))443 );444445 it.live(446 "without --project or a platform remote, exits 2 asking for --project, and asks nothing",447 () =>448 Effect.gen(function* () {449 const { dir } = yield* aRepo;450 const calls = yield* noCalls;451452 const ran = yield* run(453 dir,454 ["src/week.ts:3"],455 platformKnowing(Option.none(), calls)456 );457458 expect(ran.code).toBe(2);459 expect(ran.err).toContain("--project");460 expect(yield* Ref.get(calls)).toStrictEqual([]);461 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))462 );463464 it.live("adds the verdict a fetched note carries on that commit", () =>465 Effect.gen(function* () {466 const { dir, first, second } = yield* aRepo;467 const calls = yield* noCalls;468469 const verdict: Verdict = {470 ask: AskId.make("fix-week"),471 at: DateTime.makeUnsafe("2026-10-06T11:59:00Z"),472 base: first,473 checkVersion: CheckVersion.make("checks@1"),474 head: second,475 heldBack: [],476 lanes: [477 {478 command: "bun test",479 durationMs: 1200,480 lane: LaneName.make("test"),481 result: "passed",482 },483 ],484 outcome: Outcome.cases.Landed.make({ sha: LandedSha.make(second) }),485 patchId: PatchId.make("a".repeat(64)),486 project,487 stage: "checks",488 tree: TreeSha.make(yield* gitOk(dir, "rev-parse", "HEAD^{tree}")),489 verifier: "platform",490 };491492 yield* gitOk(493 dir,494 "notes",495 `--ref=refs/notes/${Brand.slug}`,496 "add",497 "-m",498 yield* Schema.encodeEffect(Schema.fromJsonString(Verdict))(verdict),499 second500 );501502 const ran = yield* run(503 dir,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 504why, one step back504 ["src/week.ts:3", "--project", "oscabriel/datekit", "--json"],Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 505–523why, one step back505 platformKnowing(Option.some(second), calls)506 );507508 expect(ran.code).toBe(0);509 expect(yield* decodeEnvelope(ran.out)).toStrictEqual({510 command: "why",511 data: {512 landing: landingJson(second),513 line: 3,514 note: yield* Schema.encodeEffect(Verdict)(verdict),515 path: "src/week.ts",516 sha: second,517 },518 ok: true,519 v: 1,520 });521 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))522 );523Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862
lines 524–528why, one step back524 it.live(525 "prints a refusal from the platform once, and exits 66 for a name that names nothing",526 () =>527 Effect.gen(function* () {528 const { dir } = yield* aRepo;Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 529why, one step back529Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862
lines 530–531why, one step back530 const ran = yield* run(531 dir,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 532why, one step back532 ["src/week.ts:3", "--project", "oscabriel/datekit"],Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862
lines 533–534why, one step back533 platform(() => Effect.fail(new UnknownProject({ project })))534 );Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 535why, one step back535Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862
lines 536–541why, one step back536 expect(ran.code).toBe(66);537 expect(ran.out).toBe("");538 expect(ran.err).toBe(539 explain([new UnknownProject({ project })]).join("\n")540 );541 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 542–543why, one step back542 );543});