Skip to content
Myr

seed-layer.test.ts

This file

Path

packages/config/test/seed-layer.test.ts

579 lines · 17.4 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4  Array,5  Effect,6  FileSystem,7  Layer,8  Option,9  Path,10  Schema,11  Stream,12} from "effect";13import { ChildProcess, ChildProcessSpawner } from "effect/process";1415import {16  MAIN_REF,17  planSeed,18  runSeed,19  SeedTarget,20  worldTarget,21} from "../../../scripts/lib/seed.ts";22import type { SeedFile, SeedPlan } from "../../../scripts/lib/seed.ts";23import { stepLine } from "../../../scripts/seed.ts";24import { Brand } from "../../brand/src/index.ts";25import { Client } from "../../protocol/src/contracts.ts";26import {27  LayerManifest,28  LedgerEntry,29  VisibilityPolicy,30} from "../../protocol/src/domain/visibility.ts";31import { Handle, keyOf, RepoName } from "../../protocol/src/ids.ts";32import { repoRoot } from "./root.ts";3334const config = Brand.configDir;3536const layerFiles = [37  `${config}/layer.json`,38  `${config}/layer.ts`,39  ".agents/maintainers/finish.md",40  "checks/held-back/export/offsets.test.ts",41  "checks/held-back/export/ordinal-in-patterns.test.ts",42  "checks/held-back/export/pass-through.test.ts",43  "checks/held-back/export/quote-escapes.test.ts",44  "checks/held-back/export/quoted-literals.test.ts",45  "checks/held-back/export/twelve-hour-clock.test.ts",46  "checks/held-back/export/unknown-letters.test.ts",47  "checks/held-back/parser/fraction-digits.test.ts",48  "checks/held-back/parser/never-throws.test.ts",49  "checks/held-back/parser/ordinal-dates.test.ts",50  "checks/held-back/parser/week-bounds.test.ts",51  "known-bad/export.patch",52  "known-bad/parser.patch",53];5455describe("planSeed, for a project with a layer", () => {56  it.effect(57    "plans datekit's maintainers layer from layers/maintainers, and keeps layers/ out of main",58    () =>59      Effect.gen(function* () {60        const plan = yield* planSeed("examples/datekit");6162        expect(63          plan.layers.map(({ files, layer, repo }) => ({64            files: files.map(({ path }) => path).toSorted(),65            layer,66            repo,67          }))68        ).toStrictEqual([69          {70            files: layerFiles.toSorted(),71            layer: "maintainers",72            repo: "datekit--maintainers",73          },74        ]);7576        expect(77          plan.initFiles78            .map(({ path }) => path)79            .filter(80              (path) =>81                path.startsWith("layers/") ||82                path.startsWith("checks/") ||83                path.startsWith(".agents/")84            )85        ).toStrictEqual([]);8687        expect(plan.initFiles.map(({ path }) => path)).toContain(88          `${config}/visibility.ts`89        );90      }).pipe(Effect.provide(NodeServices.layer))91  );9293  it.effect("plans no layer for burrow, which declares none", () =>94    Effect.map(planSeed("examples/burrow"), (plan) => {95      expect(plan.layers).toStrictEqual([]);96    }).pipe(Effect.provide(NodeServices.layer))97  );98});99100const example = "examples/datekit";101102const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>103  bytes.pipe(Stream.decodeText(), Stream.mkString);104105const run = (cwd: string, command: string, args: readonly string[]) =>106  Effect.scoped(107    Effect.gen(function* () {108      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;109110      const child = yield* spawner.spawn(111        ChildProcess.make(command, args, { cwd })112      );113114      const [stdout, stderr, code] = yield* Effect.all(115        [text(child.stdout), text(child.stderr), child.exitCode],116        { concurrency: "unbounded" }117      );118119      return { code: Number(code), output: `${stdout}\n${stderr}` };120    })121  );122123const exampleFile = (file: string) =>124  Effect.gen(function* () {125    const fs = yield* FileSystem.FileSystem;126    const path = yield* Path.Path;127128    return yield* fs.readFileString(path.join(yield* repoRoot, example, file));129  });130131const SDK = new RegExp(`(["'])${Brand.cliPackage}/rules\\1`, "gu");132133const defaultExportOf = (source: string) =>134  Effect.scoped(135    Effect.gen(function* () {136      const fs = yield* FileSystem.FileSystem;137      const path = yield* Path.Path;138      const sdk = path.join(yield* repoRoot, "packages/sdk/src/index.ts");139      const dir = yield* fs.makeTempDirectoryScoped({ prefix: "layer-608-" });140141      yield* fs.writeFileString(142        path.join(dir, "module.ts"),143        source.replaceAll(SDK, JSON.stringify(sdk))144      );145146      yield* fs.writeFileString(147        path.join(dir, "main.ts"),148        'import data from "./module.ts";\nprocess.stdout.write(JSON.stringify(data));\n'149      );150151      const ran = yield* run(dir, "bun", ["main.ts"]);152153      expect({154        code: ran.code,155        said: ran.code === 0 ? "" : ran.output,156      }).toStrictEqual({ code: 0, said: "" });157158      return yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown))(159        ran.output.split("\n")[0] ?? ""160      );161    })162  );163164const inLayer = (plan: SeedPlan, file: string) =>165  new TextDecoder().decode(166    plan.layers[0]?.files.find(({ path }) => path === file)?.content167  );168169const datekit = Effect.gen(function* () {170  const plan = yield* planSeed(example);171  const layer = yield* Effect.fromNullishOr(plan.layers[0]);172173  const manifest = yield* Schema.decodeUnknownEffect(LayerManifest)(174    yield* defaultExportOf(inLayer(plan, `${config}/layer.ts`))175  );176177  const policy = yield* Schema.decodeUnknownEffect(VisibilityPolicy)(178    yield* defaultExportOf(yield* exampleFile(`${config}/visibility.ts`))179  );180181  return { layer, manifest, plan, policy };182});183184const publicLanes = Effect.gen(function* () {185  const { run: block } = yield* Schema.decodeUnknownEffect(186    Schema.Struct({187      run: Schema.Struct({188        checks: Schema.Record(Schema.String, Schema.String),189      }),190    })191  )(yield* defaultExportOf(yield* exampleFile(`${config}/project.ts`)));192193  return Object.entries(block.checks);194});195196const anchorOf = (heading: string) =>197  heading198    .toLowerCase()199    .replaceAll(/[^\w\s-]/gu, "")200    .trim()201    .replaceAll(/\s+/gu, "-");202203const sectionsOf = (readme: string) => {204  const sections = new Map<string, string>();205  let current = "";206207  for (const line of readme.split("\n")) {208    const heading = /^#{1,6}\s+(?<title>.+)$/u.exec(line)?.groups?.title;209210    if (heading === undefined) {211      sections.set(current, `${sections.get(current) ?? ""}${line}\n`);212    } else {213      current = anchorOf(heading);214      sections.set(current, "");215    }216  }217218  return sections;219};220221describe("datekit's maintainers layer", () => {222  it.live(223    "states its manifest in layer.ts, as layer.json states it for the platform",224    () =>225      Effect.gen(function* () {226        const { manifest, plan } = yield* datekit;227228        const stated = yield* Schema.decodeEffect(229          Schema.fromJsonString(LayerManifest)230        )(inLayer(plan, `${config}/layer.json`));231232        expect(stated).toStrictEqual(manifest);233        expect(manifest.layer).toBe("maintainers");234      }).pipe(Effect.provide(NodeServices.layer)),235    30_000236  );237238  it.live(239    "holds seven export checks by three people and four parser checks, each a file of the layer in an area visibility.ts declares",240    () =>241      Effect.gen(function* () {242        const { layer, manifest, policy } = yield* datekit;243        const paths = new Set<string>(layer.files.map(({ path }) => path));244245        const byArea = Object.fromEntries(246          Object.keys(policy.checks?.areas ?? {}).map((area) => {247            const checks = manifest.checks.filter(248              (check) => check.area === area249            );250251            return [252              area,253              {254                authors: Array.dedupe(checks.map(({ author }) => author))255                  .length,256                checks: checks.length,257              },258            ];259          })260        );261262        expect(byArea).toStrictEqual({263          export: { authors: 3, checks: 7 },264          parser: { authors: 3, checks: 4 },265        });266267        expect(268          manifest.checks.filter(({ path }) => !paths.has(path))269        ).toStrictEqual([]);270271        expect({272          holds: policy.layers.map(({ disclose, holds, name }) => ({273            disclose,274            holds,275            name,276          })),277          suite: policy.checks?.layer,278        }).toStrictEqual({279          holds: [280            {281              disclose: "sealed",282              holds: ["checks", "notes"],283              name: "maintainers",284            },285          ],286          suite: "maintainers",287        });288      }).pipe(Effect.provide(NodeServices.layer)),289    30_000290  );291292  it.live(293    "cites for each check a clause its source says word for word: an ask's want, or a README section",294    () =>295      Effect.gen(function* () {296        const { manifest } = yield* datekit;297        const readme = sectionsOf(yield* exampleFile("README.md"));298299        const unquoted = yield* Effect.filter(manifest.checks, ({ clause }) =>300          Effect.gen(function* () {301            if (clause.source === "ask") {302              const ask = yield* exampleFile(303                `${config}/asks/${clause.ref}.ask.ts`304              ).pipe(Effect.flatMap(defaultExportOf));305306              const { brief } = yield* Schema.decodeUnknownEffect(307                Schema.Struct({ brief: Schema.Struct({ want: Schema.String }) })308              )(ask);309310              return !brief.want.includes(clause.quote);311            }312313            const [file, anchor = ""] = clause.ref.split("#");314315            return (316              file !== "README.md" ||317              !(readme.get(anchor) ?? "").includes(clause.quote)318            );319          })320        );321322        expect(unquoted).toStrictEqual([]);323324        expect(325          Array.dedupe(326            manifest.checks.map(({ clause }) => clause.source)327          ).toSorted()328        ).toStrictEqual(["ask", "doc"]);329      }).pipe(Effect.provide(NodeServices.layer)),330    60_000331  );332333  it.live(334    "carries one canary line in every held-back check, as visibility.ts promises",335    () =>336      Effect.gen(function* () {337        const { manifest, plan, policy } = yield* datekit;338339        const canaries = Array.dedupe(340          manifest.checks.map(341            ({ path }) =>342              /canary GUID (?<guid>[\da-f-]{36})/u.exec(343                inLayer(plan, path).split("\n")[0] ?? ""344              )?.groups?.guid ?? "none"345          )346        );347348        expect({349          canaries: canaries.length,350          canary: policy.checks?.canary,351        }).toStrictEqual({352          canaries: 1,353          canary: true,354        });355        expect(canaries).not.toContain("none");356      }).pipe(Effect.provide(NodeServices.layer)),357    30_000358  );359});360361const treeOf = (...trees: readonly (readonly SeedFile[])[]) =>362  Effect.gen(function* () {363    const fs = yield* FileSystem.FileSystem;364    const path = yield* Path.Path;365    const dir = yield* fs.makeTempDirectoryScoped({ prefix: "tree-608-" });366367    for (const { content, path: file } of trees.flat()) {368      yield* fs.makeDirectory(path.dirname(path.join(dir, file)), {369        recursive: true,370      });371      yield* fs.writeFile(path.join(dir, file), content);372    }373374    return dir;375  });376377describe("datekit's held-back checks, run", () => {378  it.live(379    "pass on main, every one of them",380    () =>381      Effect.gen(function* () {382        const { layer, manifest, plan } = yield* datekit;383        const dir = yield* treeOf(plan.initFiles, layer.files);384        const ran = yield* run(dir, "bun", ["test", "./checks/held-back"]);385386        expect({387          code: ran.code,388          files: /Ran \d+ tests? across (?<files>\d+) files?/u.exec(ran.output)389            ?.groups?.files,390        }).toStrictEqual({391          code: 0,392          files: String(manifest.checks.length),393        });394      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),395    60_000396  );397398  it.live(399    "fail in their area on each known-bad tree, which every public lane passes",400    () =>401      Effect.gen(function* () {402        const { layer } = yield* datekit;403        const lanes = yield* publicLanes;404405        const runs = yield* Effect.forEach(406          layer.knownBad,407          ({ branch, files }) =>408            Effect.gen(function* () {409              const area = branch.replace(/^known-bad\//u, "");410              const bad = yield* treeOf(files);411              const overlaid = yield* treeOf(files, layer.files);412413              const held = yield* run(overlaid, "bun", [414                "test",415                `./checks/held-back/${area}`,416              ]);417418              const failedLanes = yield* Effect.filter(lanes, ([, command]) =>419                Effect.map(420                  run(bad, "sh", ["-c", command]),421                  ({ code }) => code !== 0422                )423              );424425              return {426                area,427                failedLanes: failedLanes.map(([lane]) => lane),428                heldBackFailed:429                  held.code !== 0 && /\(fail\)/u.test(held.output),430              };431            })432        );433434        expect(lanes.map(([lane]) => lane)).toStrictEqual(["unit"]);435        expect(runs).toStrictEqual([436          { area: "export", failedLanes: [], heldBackFailed: true },437          { area: "parser", failedLanes: [], heldBackFailed: true },438        ]);439      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),440    60_000441  );442});443444const bram = Handle.make("bram");445446const isLayerPath = (path: string) =>447  ["layers/", "checks/held-back/", ".agents/maintainers/"].some((prefix) =>448    path.startsWith(prefix)449  );450451describe("runSeed, for a project with a layer", () => {452  it.live(453    "pushes datekit's maintainers layer to the private namespace as ines-v after the public project, out of a contributor's reach and the public tree, and a second run finds it done",454    () =>455      Effect.gen(function* () {456        const plan = yield* planSeed(example);457        const layer = yield* Effect.fromNullishOr(plan.layers[0]);458        const project = RepoName.make(keyOf(plan.project));459460        const story = Effect.gen(function* () {461          const target = yield* SeedTarget;462          const first = yield* runSeed(plan);463464          expect(first.map(stepLine)).toStrictEqual([465            "Init oscabriel/datekit: done",466            "Push oscabriel/datekit: done",467            "OpenAsk oscabriel/datekit/add-months-clamp: done",468            "OpenAsk oscabriel/datekit/format-ordinal: done",469            "OpenAsk oscabriel/datekit/parse-iso-week: done",470            "Layer datekit--maintainers: done",471          ]);472473          const refs = yield* Effect.flatMap(474            target.refsAt(layer.repo, plan.decider),475            Effect.fromOption476          );477478          const held = yield* target.pathsAt(479            layer.repo,480            MAIN_REF,481            plan.decider482          );483484          expect({485            knownBad: Object.fromEntries(486              [...refs].filter(([ref]) =>487                ref.startsWith("refs/heads/known-bad/")488              )489            ),490            paths: held.toSorted(),491            refs: [...refs.keys()].toSorted(),492          }).toStrictEqual({493            knownBad: Object.fromEntries(494              layer.knownBad.map(({ branch, commit }) => [495                `refs/heads/${branch}`,496                commit,497              ])498            ),499            paths: layer.files.map(({ path }) => path).toSorted(),500            refs: [501              "HEAD",502              "refs/heads/known-bad/export",503              "refs/heads/known-bad/parser",504              MAIN_REF,505            ].toSorted(),506          });507508          const refused = yield* Effect.flip(target.refsAt(layer.repo, bram));509510          const published = yield* target.pathsAt(511            project,512            MAIN_REF,513            target.operator514          );515516          expect({517            contributor: /\b403\b/u.test(refused.reason) ? 403 : refused.reason,518            layerPaths: published.filter(isLayerPath),519            visibility: published.some(520              (path) => path === `${config}/visibility.ts`521            ),522          }).toStrictEqual({523            contributor: 403,524            layerPaths: [],525            visibility: true,526          });527528          const ledger = yield* Client.use((client) =>529            client.ledger({ project: plan.project })530          ).pipe(Effect.provide(target.clientFor(bram)));531532          expect({533            declared: ledger.entries534              .filter(LedgerEntry.guards.LayerDeclared)535              .map(({ disclose, kinds, layer: name }) => ({536                disclose,537                kinds,538                name,539              })),540            layers: ledger.layers.map(({ name }) => name),541            posture: ledger.postureLabel,542          }).toStrictEqual({543            declared: [544              {545                disclose: "sealed",546                kinds: ["checks", "notes"],547                name: "maintainers",548              },549            ],550            layers: ["maintainers"],551            posture:552              "Open with sealed evidence · sealed checks in export, parser",553          });554555          const again = yield* runSeed(plan);556          const after = yield* target.refsAt(layer.repo, plan.decider);557558          expect({559            refs: Option.map(after, (listed) => [...listed]),560            steps: again.map(stepLine),561          }).toStrictEqual({562            refs: Option.some([...refs]),563            steps: first564              .map(stepLine)565              .map((line) => line.replace(/: done$/u, ": already")),566          });567        });568569        yield* story.pipe(570          Effect.provide(571            worldTarget([plan.decider, bram]).pipe(572              Layer.provide(NodeServices.layer)573            )574          )575        );576      }).pipe(Effect.provide(NodeServices.layer)),577    120_000578  );579});