Skip to content
Myr

surfaces.test.ts

This file

Path

apps/cli/test/surfaces.test.ts

626 lines · 17.5 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take 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–41why, one step back
1import { NodeServices } from "@effect/platform-node";
2import { describe, expect, it } from "@effect/vitest";3import { Contracts, Surfaces, surfaced } from "@repo/protocol/contracts";4import { Outcome } from "@repo/protocol/domain/outcome";5import { Envelope } from "@repo/protocol/envelope";6import {7 AskId,8 CommitSha,9 DecisionId,10 ProjectName,11 RepoPath,12 RequestId,13} from "@repo/protocol/ids";14import { DecisionClosed, StaleBase } from "@repo/protocol/refusal";15import { explain, receiptLine } from "@repo/protocol/render";16import { unanswered } from "@repo/protocol/testing";17import { gitOk } from "@repo/testkit/git";18import {19 Context,20 Effect,21 FileSystem,22 Layer,23 Ref,24 Result,25 Schema,26} from "effect";27import type { Command } from "effect/cli";2829import { local } from "../src/local/index.ts";30import { commands, entries } from "../src/surfaces.ts";31import { runProgram } from "./remote-server.ts";32import { session } from "./stdio.ts";3334const ask = AskId.make("fix-parser");3536const base = CommitSha.make("1111111111111111111111111111111111111111");3738const main = CommitSha.make("2222222222222222222222222222222222222222");3940const head = CommitSha.make("3333333333333333333333333333333333333333");41

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 42why, one step back
42const 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 43–207why, one step back
43
44const requestId = RequestId.make("answer-0001");4546const refusal = new StaleBase({47 base,48 conflicts: [RepoPath.make("src/a.ts")],49 main,50});5152const stale = Layer.mergeAll(53 unanswered,54 Contracts.toLayerHandler("submitAnswer", () => Effect.fail(refusal))55);5657const clientInfo = { name: "test", version: "0.0.0" };5859const initialize = (protocolVersion: string) => ({60 id: 1,61 jsonrpc: "2.0",62 method: "initialize",63 params: { capabilities: {}, clientInfo, protocolVersion },64});6566const Initialized = Schema.Struct({ protocolVersion: Schema.String });6768const ToolResult = Schema.Struct({69 content: Schema.Tuple([70 Schema.Struct({71 text: Schema.fromJsonString(Schema.Unknown),72 type: Schema.Literal("text"),73 }),74 ]),75 isError: Schema.Boolean,76});7778describe("the CLI's MCP server over stdio", () => {79 it.effect("agrees each session-based protocol a client asks for", () =>80 Effect.gen(function* () {81 const versions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];8283 const agreed = yield* Effect.forEach(versions, (version) =>84 session(stale, [initialize(version)]).pipe(85 Effect.flatMap((replies) =>86 Schema.decodeUnknownEffect(Initialized)(replies.get(1))87 ),88 Effect.map((result) => result.protocolVersion)89 )90 );9192 expect(agreed).toStrictEqual(versions);93 })94 );9596 it.effect("answers discovery in the stateless 2026-07-28 protocol", () =>97 Effect.gen(function* () {98 const replies = yield* session(stale, [99 {100 id: 1,101 jsonrpc: "2.0",102 method: "server/discover",103 params: {104 _meta: {105 "io.modelcontextprotocol/clientCapabilities": {},106 "io.modelcontextprotocol/clientInfo": clientInfo,107 "io.modelcontextprotocol/protocolVersion": "2026-07-28",108 },109 },110 },111 ]);112113 const discovered = yield* Schema.decodeUnknownEffect(114 Schema.Struct({ supportedVersions: Schema.Array(Schema.String) })115 )(replies.get(1));116117 expect(discovered.supportedVersions).toContain("2026-07-28");118 })119 );120121 // A stream has no tool form, and a write-only value must never pass122 // through an agent's transcript.123 it.effect("lists the MCP-surfaced contracts only: no watch, no setEnv", () =>124 Effect.gen(function* () {125 const replies = yield* session(stale, [126 initialize("2025-11-25"),127 { jsonrpc: "2.0", method: "notifications/initialized" },128 { id: 2, jsonrpc: "2.0", method: "tools/list", params: {} },129 ]);130131 const { tools } = yield* Schema.decodeUnknownEffect(132 Schema.Struct({133 tools: Schema.Array(Schema.Struct({ name: Schema.String })),134 })135 )(replies.get(2));136137 const names = tools.map(({ name }) => name);138139 expect(names).toStrictEqual([...surfaced("mcp").requests.keys()]);140 expect(names).not.toContain("watch");141 expect(names).not.toContain("setEnv");142 })143 );144145 it.effect("returns a refusal as JSON that keeps its tag", () =>146 Effect.gen(function* () {147 const replies = yield* session(stale, [148 initialize("2025-11-25"),149 { jsonrpc: "2.0", method: "notifications/initialized" },150 {151 id: 2,152 jsonrpc: "2.0",153 method: "tools/call",154 params: {155 arguments: { ask, base, head, project, requestId },156 name: "submitAnswer",157 },158 },159 ]);160161 const result = yield* Schema.decodeUnknownEffect(ToolResult)(162 replies.get(2)163 );164165 const [{ text }] = result.content;166167 expect(result.isError).toBeTruthy();168 expect(text).toHaveProperty("_tag", "StaleBase");169 expect(yield* Schema.decodeUnknownEffect(StaleBase)(text)).toStrictEqual(170 refusal171 );172 })173 );174});175176const subcommandsOf = (command: Command.Command.Any | undefined) =>177 (command?.subcommands ?? []).flatMap(({ commands: group }) =>178 group.map(({ name }) => name)179 );180181const top = (name: string) => commands.find((command) => command.name === name);182183describe("the CLI's command tree", () => {184 it("has one command per contract served on the CLI, every local one, and schema", () => {185 const onCli = [...Contracts.requests.values()].filter((rpc) =>186 Context.get(rpc.annotations, Surfaces).includes("cli")187 );188189 const paths = entries.map(({ path: words }) => words.join(" "));190191 // `init` and `env set` are the local commands that wrap their contracts.192 expect(paths).toHaveLength(onCli.length - 2 + local.length + 1);193 expect(new Set(paths).size).toBe(paths.length);194 expect(paths).toStrictEqual(195 expect.arrayContaining([196 "asks",197 "ask",198 "ask open",199 "ask flag",200 "env shape",201 "env set",202 "init",203 "schema",204 ])205 );206 });207

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d

lines 208–209why, one step back
208 it("puts ask open, ask draft and ask flag under ask, and env shape beside env set", () => {
209 expect(subcommandsOf(top("ask"))).toStrictEqual(["open", "draft", "flag"]);

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 210–232why, one step back
210 expect(subcommandsOf(top("env"))).toStrictEqual(["shape", "set"]);
211 });212213 it("leaves init and env set to their local commands", () => {214 const [localInit, localEnvSet] = [215 local.find(({ path }) => path.join(" ") === "init")?.command,216 local.find(({ path }) => path.join(" ") === "env set")?.command,217 ];218219 const envSet = top("env")220 ?.subcommands.flatMap(({ commands: group }) => group)221 .find(({ name }) => name === "set");222223 expect(top("init")).toBe(localInit);224 expect(envSet).toBe(localEnvSet);225 });226});227228const decision = DecisionId.make("dec-000001");229230const decideArgs = [231 "decide",232 "--project",

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 233why, one step back
233 "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 234–288why, one step back
234 "--decision",
235 decision,236 "--choice",237 "accept",238];239240const deciding = (calls: Ref.Ref<number>) =>241 Layer.mergeAll(242 unanswered,243 Contracts.toLayerHandler("decide", () =>244 Ref.update(calls, (count) => count + 1).pipe(245 Effect.andThen(Effect.fail(new DecisionClosed({ decision })))246 )247 )248 );249250const decodeEnvelope = Schema.decodeEffect(251 Schema.fromJsonString(Envelope(Schema.Unknown))252);253254describe("a command that needs approval", () => {255 it.effect(256 "exits 2 without --yes, in one line naming --yes, and calls nothing",257 () =>258 Effect.gen(function* () {259 const calls = yield* Ref.make(0);260261 const run = yield* runProgram(decideArgs, {262 handlers: deciding(calls),263 });264265 expect(run.code).toBe(2);266 expect(run.err).toHaveLength(1);267 expect(run.err[0]).toContain("--yes");268 expect(run.out).toStrictEqual([]);269 expect(yield* Ref.get(calls)).toBe(0);270 })271 );272273 it.effect(274 "prints the payload it would send under --dry-run, and calls nothing",275 () =>276 Effect.gen(function* () {277 const calls = yield* Ref.make(0);278279 const run = yield* runProgram([...decideArgs, "--dry-run", "--json"], {280 handlers: deciding(calls),281 });282283 expect(run.code).toBe(0);284 expect(run.out).toHaveLength(1);285 expect(yield* decodeEnvelope(run.out[0] ?? "")).toStrictEqual({286 command: "decide",287 data: {288 dryRun: true,

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 289–293why, one step back
289 payload: {
290 choice: "accept",291 decision,292 project: "oscabriel/datekit",293 },

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 294–322why, one step back
294 },
295 ok: true,296 v: 1,297 });298 expect(yield* Ref.get(calls)).toBe(0);299 })300 );301302 it.effect("prints the payload as text for a person under --dry-run", () =>303 Effect.gen(function* () {304 const calls = yield* Ref.make(0);305306 const run = yield* runProgram([...decideArgs, "--dry-run"], {307 handlers: deciding(calls),308 });309310 expect(run.out.join("\n")).toContain(`"decision": "${decision}"`);311 expect(yield* Ref.get(calls)).toBe(0);312 })313 );314315 it.effect("calls the platform with --yes", () =>316 Effect.gen(function* () {317 const calls = yield* Ref.make(0);318319 const run = yield* runProgram([...decideArgs, "--yes"], {320 handlers: deciding(calls),321 });322

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

lines 323–324why, one step back
323 // DecisionClosed: the decision named no longer stands open.
324 expect(run.code).toBe(66);

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 325–333why, one step back
325 expect(yield* Ref.get(calls)).toBe(1);
326 })327 );328});329330describe("a read", () => {331 it.effect("has no --dry-run: asking for one is a usage error", () =>332 Effect.gen(function* () {333 const run = yield* runProgram(

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 334why, one step back
334 ["asks", "--project", "oscabriel/datekit", "--dry-run"],

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 335–377why, one step back
335 { handlers: unanswered }
336 );337338 expect(run.code).toBe(2);339 expect(run.err.join("\n")).toContain("--dry-run");340 })341 );342});343344const listing = (asked: Ref.Ref<readonly string[]>) =>345 Layer.mergeAll(346 unanswered,347 Contracts.toLayerHandler("listAsks", ({ project: named }) =>348 Ref.update(asked, (all) => [...all, named]).pipe(Effect.as({ asks: [] }))349 )350 );351352const repoWithOrigin = (url: string) =>353 Effect.gen(function* () {354 const fs = yield* FileSystem.FileSystem;355 const dir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());356357 yield* gitOk(dir, "init", "--quiet");358 yield* gitOk(dir, "remote", "add", "origin", url);359360 return dir;361 });362363describe("the project a command is about", () => {364 it.live("comes from the repo's remote when --project is left out", () =>365 Effect.gen(function* () {366 const asked = yield* Ref.make<readonly string[]>([]);367368 const cwd = yield* repoWithOrigin(369 "https://platform-dev.example.workers.dev/datekit--fix-week--tester.git"370 );371372 const run = yield* runProgram(["asks", "--json"], {373 cwd,374 handlers: listing(asked),375 });376377 expect(run.code).toBe(0);

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 378why, one step back
378 expect(yield* Ref.get(asked)).toStrictEqual(["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 379–405why, one step back
379 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))
380 );381382 it.live("is a usage error outside a platform's repo, naming --project", () =>383 Effect.gen(function* () {384 const asked = yield* Ref.make<readonly string[]>([]);385 const fs = yield* FileSystem.FileSystem;386 const cwd = yield* fs.makeTempDirectoryScoped();387388 const run = yield* runProgram(["asks"], {389 cwd,390 handlers: listing(asked),391 });392393 expect(run.code).toBe(2);394 expect(run.err.join("\n")).toContain("--project");395 expect(yield* Ref.get(asked)).toStrictEqual([]);396 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))397 );398});399400describe("a misuse", () => {401 it.effect(402 "prints one line on stderr and nothing on stdout, even with --json",403 () =>404 Effect.gen(function* () {405 const run = yield* runProgram(

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 406why, one step back
406 ["asks", "--project", "oscabriel/datekit", "--bogus", "--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–591why, one step back
407 { env: { CLAUDECODE: "1" }, handlers: unanswered }
408 );409410 expect(run.code).toBe(2);411 expect(run.out).toStrictEqual([]);412 expect(run.err).toHaveLength(1);413 expect(run.err[0]).toContain("--bogus");414 })415 );416417 it.effect("leaves help asked for on stdout", () =>418 Effect.gen(function* () {419 const run = yield* runProgram(["--help"], { handlers: unanswered });420421 expect(run.code).toBe(0);422 expect(run.out.join("\n")).toContain("Start here:");423 expect(run.err).toStrictEqual([]);424 })425 );426});427428const submitArgs = [429 "submit",430 "--project",431 project,432 "--ask",433 ask,434 "--base",435 base,436 "--head",437 head,438 "--requestId",439 requestId,440];441442const receiptAt = (outcome: Outcome) => ({443 ask,444 base,445 head,446 outcome,447 project,448 requestId,449});450451const receiving = (receipt: ReturnType<typeof receiptAt>) =>452 Layer.mergeAll(453 unanswered,454 Contracts.toLayerHandler("submitAnswer", () => Effect.succeed(receipt))455 );456457const naming = {458 finish: [459 "--project",460 project,461 "--base",462 base,463 "--head",464 head,465 "--requestId",466 requestId,467 "--yes",468 ],469 release: ["--project", project],470 submit: [471 "--project",472 project,473 "--base",474 base,475 "--head",476 head,477 "--requestId",478 requestId,479 ],480 verdict: ["--project", project],481} as const satisfies Readonly<Record<string, readonly string[]>>;482483const recordingAsks = (named: Ref.Ref<readonly string[]>) => {484 const record = (given: string) => Ref.update(named, (all) => [...all, given]);485486 const receipt = receiptAt(Outcome.cases.Checking.make({ stage: "merge" }));487488 return Layer.mergeAll(489 unanswered,490 Contracts.toLayerHandler("verdict", (payload) =>491 record(payload.ask).pipe(Effect.as({}))492 ),493 Contracts.toLayerHandler("release", (payload) =>494 record(payload.ask).pipe(Effect.as({ released: true }))495 ),496 Contracts.toLayerHandler("submitAnswer", (payload) =>497 record(payload.ask).pipe(Effect.as(receipt))498 ),499 Contracts.toLayerHandler("finish", (payload) =>500 record(payload.ask).pipe(Effect.as(receipt))501 )502 );503};504505describe("the ask a command is about", () => {506 it.effect(507 "is its first argument on verdict, release, submit and finish, as on claim",508 () =>509 Effect.gen(function* () {510 const named = yield* Ref.make<readonly string[]>([]);511512 const codes = yield* Effect.forEach(513 Object.entries(naming),514 ([command, rest]) =>515 Effect.map(516 runProgram([command, ask, ...rest], {517 handlers: recordingAsks(named),518 }),519 ({ code }) => [command, code] as const520 )521 );522523 expect(codes).toStrictEqual(524 Object.keys(naming).map((command) => [command, 0])525 );526 expect(yield* Ref.get(named)).toStrictEqual([ask, ask, ask, ask]);527 })528 );529530 it.effect(531 "still comes from --ask, which help no longer shows and which prints nothing more",532 () =>533 Effect.gen(function* () {534 const named = yield* Ref.make<readonly string[]>([]);535536 const runs = yield* Effect.forEach(537 Object.entries(naming),538 ([command, rest]) =>539 runProgram([command, "--ask", ask, ...rest], {540 handlers: recordingAsks(named),541 })542 );543544 expect(runs.map(({ code }) => code)).toStrictEqual([0, 0, 0, 0]);545 expect(runs.flatMap(({ err }) => err)).toStrictEqual([]);546 expect(yield* Ref.get(named)).toStrictEqual([ask, ask, ask, ask]);547548 const help = yield* runProgram(["verdict", "--help"], {549 handlers: unanswered,550 });551552 expect(help.out.join("\n")).toContain("<ask>");553 expect(help.out.join("\n")).not.toContain("--ask");554 })555 );556557 it.effect("is a usage error naming <ask> when neither form gives it", () =>558 Effect.gen(function* () {559 const named = yield* Ref.make<readonly string[]>([]);560561 const run = yield* runProgram(["verdict", ...naming.verdict], {562 handlers: recordingAsks(named),563 });564565 expect(run.code).toBe(2);566 expect(run.err).toHaveLength(1);567 expect(run.err[0]).toContain("<ask>");568 expect(yield* Ref.get(named)).toStrictEqual([]);569 })570 );571});572573describe("an answer offered with submit", () => {574 it.effect("prints the same line git's remote: output gives its push", () =>575 Effect.gen(function* () {576 const offered = receiptAt(577 Outcome.cases.Checking.make({ stage: "merge" })578 );579580 const run = yield* runProgram(submitArgs, {581 handlers: receiving(offered),582 });583584 expect(run.code).toBe(0);585 expect(Result.map(receiptLine(offered), (line) => [line])).toStrictEqual(586 Result.succeed(run.out)587 );588 })589 );590591 it.effect(

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

line 592why, one step back
592 "prints a refused receipt as a refusal: once on stderr, nothing on stdout, exit 75 for a moved main",

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 593–600why, one step back
593 () =>
594 Effect.gen(function* () {595 const run = yield* runProgram(submitArgs, {596 handlers: receiving(597 receiptAt(Outcome.cases.Refused.make({ refusals: [refusal] }))598 ),599 });600

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

line 601why, one step back
601 expect(run.code).toBe(75);

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 602–614why, one step back
602 expect(run.out).toStrictEqual([]);
603 expect(run.err).toStrictEqual(explain([refusal]));604 })605 );606607 it.effect("puts a refused receipt in one refused envelope under --json", () =>608 Effect.gen(function* () {609 const run = yield* runProgram([...submitArgs, "--json"], {610 handlers: receiving(611 receiptAt(Outcome.cases.Refused.make({ refusals: [refusal] }))612 ),613 });614

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

line 615why, one step back
615 expect(run.code).toBe(75);

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 616–626why, one step back
616 expect(run.err).toStrictEqual([]);
617 expect(run.out).toHaveLength(1);618 expect(yield* decodeEnvelope(run.out[0] ?? "")).toStrictEqual({619 command: "submit",620 ok: false,621 refusals: [refusal],622 v: 1,623 });624 })625 );626});