Skip to content
Myr

contracts.test.ts

This file

Path

packages/protocol/test/contracts.test.ts

641 lines · 15.4 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { Context, Option, Redacted, Schema, SchemaAST } from "effect";3import { RpcSchema } from "effect/rpc";4import { expectTypeOf } from "vitest";56import {7  Audience,8  Cli,9  Description,10  Destructive,11  Idempotent,12  NeedsApproval,13  ReadOnly,14  SurfaceName,15  Surfaces,16  Visibility,17} from "../src/annotations.ts";18import {19  Contracts,20  partsOf,21  ProposeAsk,22  SetEnv,23  surfaced,24  Watch,25} from "../src/contracts.ts";26import type { Contract, TagOn } from "../src/contracts.ts";27import { ProjectEvent } from "../src/domain/event.ts";28import { toJsonSchema } from "../src/mcp.ts";29import { examples } from "./contract-examples.ts";30import type { Example } from "./contract-examples.ts";3132/**33 * The contracts table, row by row and in its order. CLI: the command's name,34 * then the fields it takes in order; `none` for a contract with no command.35 * Flags: R reads only, I idempotent, D destructive, A needs a person's36 * approval. Surfaces: R rpc, M mcp, C cli, W web.37 */38const table = [39  {40    audience: "public",41    cli: "projects",42    errors: [],43    flags: "RI",44    on: "RMCW",45    tag: "listProjects",46  },47  {48    audience: "public",49    cli: "none",50    errors: [],51    flags: "RI",52    on: "RMW",53    tag: "recentLandings",54  },55  {56    audience: "public",57    cli: "front",58    errors: [],59    flags: "RI",60    on: "RMCW",61    tag: "frontPage",62  },63  {64    audience: "public",65    cli: "asks",66    errors: ["UnknownProject"],67    flags: "RI",68    on: "RMCW",69    tag: "listAsks",70  },71  {72    audience: "public",73    cli: "ask <ask>",74    errors: ["UnknownProject", "UnknownAsk"],75    flags: "RI",76    on: "RMCW",77    tag: "showAsk",78  },79  {80    audience: "signedIn",81    cli: "status",82    errors: ["UnknownProject"],83    flags: "RI",84    on: "RMCW",85    tag: "status",86  },87  {88    audience: "public",89    cli: "verdict <ask>",90    errors: ["UnknownProject", "UnknownAsk"],91    flags: "RI",92    on: "RMCW",93    tag: "verdict",94  },95  {96    audience: "public",97    cli: "landing",98    errors: ["UnknownProject", "UnknownCommit"],99    flags: "RI",100    on: "RMCW",101    tag: "landing",102  },103  {104    audience: "public",105    cli: "credits",106    errors: [],107    flags: "RI",108    on: "RMCW",109    tag: "credits",110  },111  {112    audience: "decider",113    cli: "today",114    errors: ["NotDecider", "UnknownProject"],115    flags: "RI",116    on: "RMCW",117    tag: "today",118  },119  {120    audience: "public",121    cli: "ledger",122    errors: ["UnknownProject"],123    flags: "RI",124    on: "RMCW",125    tag: "ledger",126  },127  {128    audience: "public",129    cli: "env shape",130    errors: ["UnknownProject"],131    flags: "RI",132    on: "RMCW",133    tag: "envShape",134  },135  {136    audience: "public",137    cli: "none",138    errors: ["UnknownProject"],139    flags: "R",140    on: "RW",141    tag: "watch",142  },143  {144    audience: "public",145    cli: "none",146    errors: ["UnknownProject"],147    flags: "RI",148    on: "RMW",149    tag: "listRefs",150  },151  {152    audience: "public",153    cli: "none",154    errors: ["UnknownProject", "UnknownRevision", "UnknownPath"],155    flags: "RI",156    on: "RMW",157    tag: "readTree",158  },159  {160    audience: "public",161    cli: "none",162    errors: ["UnknownProject", "UnknownRevision"],163    flags: "RI",164    on: "RW",165    tag: "listPaths",166  },167  {168    audience: "public",169    cli: "none",170    errors: ["UnknownProject", "UnknownRevision", "UnknownPath"],171    flags: "RI",172    on: "RMW",173    tag: "readFile",174  },175  {176    audience: "public",177    cli: "none",178    errors: ["UnknownProject", "UnknownRevision"],179    flags: "RI",180    on: "RMW",181    tag: "log",182  },183  {184    audience: "public",185    cli: "none",186    errors: ["UnknownProject", "UnknownCommit", "UnknownRevision"],187    flags: "RI",188    on: "RW",189    tag: "showCommit",190  },191  {192    audience: "public",193    cli: "none",194    errors: ["UnknownProject", "UnknownRevision", "UnknownPath"],195    flags: "RI",196    on: "RMW",197    tag: "why",198  },199  {200    audience: "public",201    cli: "policy",202    errors: ["UnknownProject"],203    flags: "RI",204    on: "RMCW",205    tag: "projectPolicy",206  },207  {208    audience: "public",209    cli: "proposal <proposal>",210    errors: ["UnknownProject", "UnknownProposal"],211    flags: "RI",212    on: "RMCW",213    tag: "showProposal",214  },215  {216    audience: "signedIn",217    cli: "init",218    errors: ["ProjectExists", "NotYourNamespace", "ImportFailed"],219    flags: "A",220    on: "RMCW",221    tag: "initProject",222  },223  {224    audience: "decider",225    cli: "ask open <ask>",226    errors: [227      "UnknownProject",228      "NotDecider",229      "NotRedFirst",230      "WeakCheck",231      "IncompleteBrief",232      "TouchedJudge",233      "VerifierBlocked",234      "StaleBase",235    ],236    flags: "A",237    on: "RMC",238    tag: "openAsk",239  },240  {241    audience: "signedIn",242    cli: "propose",243    errors: ["UnknownProject", "Denounced", "CapReached", "NotVouched"],244    flags: "",245    on: "RMCW",246    tag: "proposeAsk",247  },248  {249    audience: "signedIn",250    cli: "ask draft <proposal>",251    errors: [252      "UnknownProject",253      "UnknownProposal",254      "ProposalClosed",255      "NotDecider",256      "DraftInProgress",257      "CapReached",258    ],259    flags: "",260    on: "RMCW",261    tag: "draftAsk",262  },263  {264    audience: "signedIn",265    cli: "ask flag <ask>",266    errors: ["UnknownProject", "UnknownAsk", "Denounced", "CapReached"],267    flags: "",268    on: "RMC",269    tag: "flagAsk",270  },271  {272    audience: "decider",273    cli: "decide",274    errors: [275      "UnknownProject",276      "UnknownDecision",277      "DecisionClosed",278      "NotDecider",279      "VerifierBlocked",280      "StaleBase",281    ],282    flags: "A",283    on: "RMCW",284    tag: "decide",285  },286  {287    audience: "signedIn",288    cli: "claim <ask>",289    errors: [290      "UnknownProject",291      "UnknownAsk",292      "AskFull",293      "AskBlocked",294      "CapReached",295      "NotVouched",296      "Denounced",297    ],298    flags: "I",299    on: "RMC",300    tag: "claim",301  },302  {303    audience: "signedIn",304    cli: "release <ask>",305    errors: ["UnknownProject", "NotClaimed"],306    flags: "I",307    on: "RMC",308    tag: "release",309  },310  {311    audience: "signedIn",312    cli: "submit <ask>",313    errors: [314      "UnknownProject",315      "NotClaimed",316      "ClaimLapsed",317      "StaleBase",318      "RepoBusy",319      "OutOfScope",320      "TouchedJudge",321      "Weakened",322      "ReachedInternals",323      "PrivatePathInPublicTree",324    ],325    flags: "I",326    on: "RMC",327    tag: "submitAnswer",328  },329  {330    audience: "decider",331    cli: "finish <ask>",332    errors: [333      "UnknownProject",334      "NotDecider",335      "StaleBase",336      "RepoBusy",337      "TouchedJudge",338    ],339    flags: "IA",340    on: "RMC",341    tag: "finish",342  },343  {344    audience: "decider",345    cli: "land",346    errors: ["UnknownProject", "NotDecider", "StaleBase", "RepoBusy"],347    flags: "IA",348    on: "RMC",349    tag: "land",350  },351  {352    audience: "signedIn",353    cli: "fork",354    errors: ["UnknownProject", "NotVouched", "Denounced"],355    flags: "I",356    on: "RMC",357    tag: "fork",358  },359  {360    audience: "decider",361    cli: "vouch",362    errors: ["UnknownProject", "NotDecider", "StaleBase"],363    flags: "A",364    on: "RMC",365    tag: "vouch",366  },367  {368    audience: "signedIn",369    cli: "evidence <ref>",370    errors: ["UnknownProject", "NotDecider"],371    flags: "RI",372    on: "RC",373    tag: "evidence",374  },375  {376    audience: "decider",377    cli: "env set",378    errors: [379      "UnknownProject",380      "NotDecider",381      "UnknownEnvItem",382      "NotSensitive",383      "ValueTooShort",384    ],385    flags: "IA",386    on: "RC",387    tag: "setEnv",388  },389] as const;390391const decodes = (payload: typeof Schema.Json.Type) =>392  Schema.decodeUnknownOption(ProposeAsk.payloadSchema)(payload)._tag;393394type CodeRead =395  | "listPaths"396  | "listRefs"397  | "log"398  | "readFile"399  | "readTree"400  | "showCommit"401  | "why";402403type UncappedRead = "listPaths" | "showCommit";404405const letterOf = {406  cli: "C",407  mcp: "M",408  rpc: "R",409  web: "W",410} as const satisfies Record<SurfaceName, string>;411412const surfacesOf = (letters: string): readonly SurfaceName[] =>413  SurfaceName.literals.filter((surface) => letters.includes(letterOf[surface]));414415const contracts = [...Contracts.requests.values()];416417const commandOf = (rpc: Contract) => {418  const cli = Context.getOrUndefined(rpc.annotations, Cli);419420  if (cli?.name === undefined) {421    return "none";422  }423424  return [425    cli.name,426    ...(cli.positional ?? []).map((field) => `<${field}>`),427  ].join(" ");428};429430const refusalsOf = (error: Schema.Top) => {431  const { ast } = error;432433  if (SchemaAST.isNever(ast)) {434    return [];435  }436437  return (SchemaAST.isUnion(ast) ? ast.types : [ast]).map(438    SchemaAST.resolveIdentifier439  );440};441442const roundTrip = (rpc: Contract, example: Example) => {443  const { success } = partsOf(rpc);444445  return {446    payload: Schema.encodeSync(rpc.payloadSchema)(447      Schema.decodeUnknownSync(rpc.payloadSchema)(example.payload)448    ),449    success: Schema.encodeSync(success)(450      Schema.decodeUnknownSync(success)(example.success)451    ),452  };453};454455describe("the contracts group", () => {456  it("holds every contract of the spec's table, in its order", () => {457    expect([...Contracts.requests.keys()]).toStrictEqual(458      table.map(({ tag }) => tag)459    );460  });461462  it("describes every contract", () => {463    const undescribed = contracts.flatMap((rpc) =>464      Context.get(rpc.annotations, Description).trim() === "" ? [rpc._tag] : []465    );466467    expect(contracts).toHaveLength(table.length);468    expect(undescribed).toStrictEqual([]);469  });470471  // Each is set explicitly: MCP reads a tool with no hints as destructive.472  it("sets each contract's hints and approval explicitly, as the table flags them", () => {473    expect(474      contracts.map((rpc) => ({475        destructive: Context.getOrUndefined(rpc.annotations, Destructive),476        idempotent: Context.getOrUndefined(rpc.annotations, Idempotent),477        needsApproval: Context.getOrUndefined(rpc.annotations, NeedsApproval),478        readOnly: Context.getOrUndefined(rpc.annotations, ReadOnly),479        tag: rpc._tag,480      }))481    ).toStrictEqual(482      table.map(({ flags, tag }) => ({483        destructive: flags.includes("D"),484        idempotent: flags.includes("I"),485        needsApproval: flags.includes("A"),486        readOnly: flags.includes("R"),487        tag,488      }))489    );490  });491492  it("says who may call each contract and which surfaces serve it", () => {493    expect(494      contracts.map((rpc) => ({495        audience: Context.getOrUndefined(rpc.annotations, Audience),496        surfaces: Context.getOrUndefined(rpc.annotations, Surfaces),497        tag: rpc._tag,498      }))499    ).toStrictEqual(500      table.map(({ audience, on, tag }) => ({501        audience,502        surfaces: surfacesOf(on),503        tag,504      }))505    );506  });507508  it("names each contract's command, and the fields it takes in order", () => {509    expect(510      contracts.map((rpc) => ({ cli: commandOf(rpc), tag: rpc._tag }))511    ).toStrictEqual(table.map(({ cli, tag }) => ({ cli, tag })));512  });513514  it("sets each contract's visibility explicitly, keeping only a maintainer's Today and decisions, and a lane's log, to maintainers", () => {515    expect(516      contracts.flatMap((rpc) => {517        const visibility = Context.getOrUndefined(rpc.annotations, Visibility);518519        return visibility === "public" ? [] : [{ tag: rpc._tag, visibility }];520      })521    ).toStrictEqual([522      { tag: "today", visibility: "maintainers" },523      { tag: "decide", visibility: "maintainers" },524      { tag: "evidence", visibility: "maintainers" },525    ]);526  });527528  it("lets each contract refuse only with its own subset of refusals", () => {529    expect(530      contracts.map((rpc) => ({531        errors: refusalsOf(partsOf(rpc).error),532        tag: rpc._tag,533      }))534    ).toStrictEqual(table.map(({ errors, tag }) => ({ errors, tag })));535  });536537  it.each(table)(538    "$tag decodes its example payload and success, and encodes them back unchanged",539    ({ tag }) => {540      const example = Option.fromUndefinedOr(examples.get(tag));541542      const rpc = Option.fromUndefinedOr(Contracts.requests.get(tag));543544      expect(Option.isSome(example)).toBeTruthy();545      expect(Option.zipWith(rpc, example, roundTrip)).toStrictEqual(example);546    }547  );548549  // A bare number admits "Infinity" and "NaN", and `Schema.optional` admits550  // null; MCP tool schemas would carry both.551  it("gives every payload and success a JSON Schema with no non-finite number and no null", () => {552    const leaky = contracts.flatMap((rpc) => {553      const { success } = partsOf(rpc);554555      return [556        [`${rpc._tag}.payload`, rpc.payloadSchema] as const,557        [`${rpc._tag}.success`, success] as const,558      ].flatMap(([name, schema]) => {559        const json = JSON.stringify(toJsonSchema(schema));560561        return ['"Infinity"', '"NaN"', '"null"'].flatMap((leak) =>562          json.includes(leak) ? [`${name} admits ${leak}`] : []563        );564      });565    });566567    expect(contracts).toHaveLength(table.length);568    expect(leaky).toStrictEqual([]);569  });570571  it("takes setEnv's value as the raw string on the wire, and never prints it", () => {572    const sent = examples.get("setEnv")?.payload;573574    const decoded = Schema.decodeUnknownSync(SetEnv.payloadSchema)(sent);575    const encoded = Schema.encodeSync(SetEnv.payloadSchema)(decoded);576577    expect(Redacted.isRedacted(decoded.value)).toBeTruthy();578    expect(encoded).toStrictEqual(sent);579    expect(encoded.value).toBe("not-a-real-value-0123456789abcdef");580    expect(JSON.stringify(decoded)).toContain('"value":"<redacted>"');581    expect(JSON.stringify(decoded)).not.toContain(encoded.value);582  });583584  it("takes a drafted proposal with no files and no sealed answer", () => {585    const want = { project: "datekit", want: "Parse ISO weeks." };586587    const files = [{ content: "x", path: "config/asks/a.ask.ts" }];588589    const sealed = { head: "3".repeat(40) };590591    expect([592      decodes({ ...want, draft: true }),593      decodes({ ...want, draft: true, files }),594      decodes({ ...want, draft: true, sealed }),595      decodes({ ...want, files }),596      decodes({ ...want, draft: false }),597    ]).toStrictEqual(["Some", "None", "None", "Some", "None"]);598  });599600  it("streams a project's events from watch", () => {601    expect(RpcSchema.isStreamSchema(Watch.successSchema)).toBeTruthy();602    expect(Watch.successSchema.success).toBe(ProjectEvent);603  });604});605606describe("the group a surface serves", () => {607  it.each(SurfaceName.literals)(608    "%s carries exactly the contracts the table puts on it",609    (surface) => {610      expect([...surfaced(surface).requests.keys()]).toStrictEqual(611        table.flatMap(({ on, tag }) =>612          on.includes(letterOf[surface]) ? [tag] : []613        )614      );615    }616  );617618  // Compile-time: each surface's group is typed by the table its619  // annotations come from, so a tool or command the type names exists.620  it("types each surface's group as the contracts on it", () => {621    expectTypeOf<TagOn<"rpc">>().toEqualTypeOf<Contract["_tag"]>();622    expectTypeOf<TagOn<"mcp">>().toEqualTypeOf<623      Exclude<Contract["_tag"], UncappedRead | "evidence" | "setEnv" | "watch">624    >();625    expectTypeOf<TagOn<"cli">>().toEqualTypeOf<626      Exclude<Contract["_tag"], CodeRead | "recentLandings" | "watch">627    >();628  });629630  it("never gives MCP a stream, a contract that carries a write-only value, or a lane's log", () => {631    const mcp = [...surfaced("mcp").requests.values()];632633    expect(mcp.map(({ _tag }) => _tag)).not.toContain("setEnv");634    expect(mcp.map(({ _tag }) => _tag)).not.toContain("evidence");635    expect(636      mcp.flatMap((rpc) =>637        RpcSchema.isStreamSchema(rpc.successSchema) ? [rpc._tag] : []638      )639    ).toStrictEqual([]);640  });641});