Skip to content
Myr

generated.test.ts

This file

Path

apps/platform/test/generated.test.ts

503 lines · 14.6 KiB · TypeScript

Last changed by

Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";3import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";5import { Brand } from "@repo/brand";6import { CheckAt, CheckRunner } from "@repo/checks/check-runner";7import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";8import { authorLine, creditsOf, parseTrailers } from "@repo/git/trailers";9import { treeDiff } from "@repo/git/tree-diff";10import { AlarmsMemory } from "@repo/project/alarms/memory";11import { AnswerRunsInline } from "@repo/project/answer-runs/inline";12import { platformHandle } from "@repo/project/attention/effects";13import { Lander } from "@repo/project/lander";14import { LanderIsogit } from "@repo/project/lander/isogit";15import { ProjectionMemory } from "@repo/project/projection/memory";16import { Projects } from "@repo/project/projects";17import { ProjectsMemory } from "@repo/project/projects/memory";18import type { LaneResult } from "@repo/protocol/domain/answer";19import { Outcome } from "@repo/protocol/domain/outcome";20import { RunBlock } from "@repo/protocol/domain/run";21import type { CommitSha } from "@repo/protocol/ids";22import {23  LandedSha,24  LaneName,25  RepoName,26  RepoPath,27  RequestId,28  keyOf,29  TreeSha,30} from "@repo/protocol/ids";31import { Person } from "@repo/protocol/principal";32import { RepoBusy, VerifierBlocked } from "@repo/protocol/refusal";33import { RulesEvaluator } from "@repo/rules/rules-evaluator";34import { advanceTo } from "@repo/testkit/clock";35import { gitClient } from "@repo/testkit/git-client";36import type { Files } from "@repo/testkit/git-client";37import { aProject } from "@repo/testkit/scenarios";38import { Context, Effect, Exit, Layer, Option, Ref, Schema } from "effect";3940import { ProjectSkillGenerator } from "../src/workflows/generated.ts";4142const scenario = aProject();4344const { project } = scenario;4546const repo = RepoName.make(keyOf(project));4748const alice = Person.make({ handle: scenario.initializer });4950const mainRef = RefName.make("refs/heads/main");5152const runFile = `${Brand.configDir}/run.json`;5354const skill = `.agents/skills/${keyOf(project)}-contribute/SKILL.md`;5556const claudeSkill = `.claude/skills/${keyOf(project)}-contribute/SKILL.md`;5758const generatedPaths = [skill, claudeSkill, "AGENTS.md"];5960const lintOnly = { checks: { lint: "bun run lint" }, test: "bun test {path}" };6162const withUnit = {63  checks: { lint: "bun run lint", unit: "bun run test" },64  test: "bun test {path}",65};6667const start: Files = [68  ["package.json", '{ "name": "alice/datekit" }\n'],69  ["src/parse.ts", "export const parse = (s) => ({});\n"],70  [runFile, `${JSON.stringify(lintOnly)}\n`],71  ["AGENTS.md", "# Datekit\n\nOur own notes for agents.\n"],72];7374const decodeRun = Schema.decodeEffect(Schema.fromJsonString(RunBlock));7576const rules = Layer.succeed(77  RulesEvaluator,78  RulesEvaluator.of({79    call: () => Effect.succeed(false),80    evaluate: ({ at, modules }) =>81      Effect.map(82        Effect.orDie(83          decodeRun(modules.modules[runFile] ?? JSON.stringify(lintOnly))84        ),85        (run) => ({ ...scenario.policy, at, run })86      ),87  })88);8990class Passing extends Context.Service<91  Passing,92  {93    readonly on: (at: CheckAt, lanes: readonly string[]) => Effect.Effect<void>;94  }95>()("test/Passing") {}9697const checker = Layer.effectContext(98  Effect.gen(function* () {99    const script = new Map<string, readonly LaneResult[]>();100101    const memory = Context.get(102      yield* Layer.build(CheckRunnerMemory.layer(script)),103      CheckRunner104    );105106    return Context.make(CheckRunner, memory).pipe(107      Context.add(Passing, {108        on: (at, lanes) =>109          Effect.sync(() => {110            for (const name of lanes) {111              const lane = LaneName.make(name);112113              script.set(scriptKey(at, lane), [114                {115                  command: `run ${lane}`,116                  durationMs: 1,117                  lane,118                  result: "passed",119                },120              ]);121            }122          }),123      })124    );125  })126);127128type Mishap = "none" | "busy" | "lost";129130class Mishaps extends Context.Service<131  Mishaps,132  { readonly next: (mishap: Mishap) => Effect.Effect<void> }133>()("test/Mishaps") {}134135const mishapLander = Layer.effectContext(136  Effect.gen(function* () {137    const real = Context.get(yield* Layer.build(LanderIsogit), Lander);138    const next = yield* Ref.make<Mishap>("none");139140    const land: Lander["Service"]["land"] = (job) =>141      Effect.gen(function* () {142        const mishap = job.requestId.startsWith("gen-")143          ? yield* Ref.getAndSet(next, "none")144          : "none";145146        if (mishap === "busy") {147          return yield* new RepoBusy({});148        }149150        const landed = yield* real.land(job);151152        return mishap === "lost" ? yield* new VerifierBlocked({}) : landed;153      });154155    return Context.make(Lander, Lander.of({ ...real, land })).pipe(156      Context.add(Mishaps, { next: (mishap) => Ref.set(next, mishap) })157    );158  })159);160161class Pusher extends Context.Service<162  Pusher,163  {164    readonly push: (165      to: RepoName,166      parent: Option.Option<CommitSha>,167      files: Files168    ) => Effect.Effect<CommitSha>;169  }170>()("test/Pusher") {}171172const pusher = Layer.effect(173  Pusher,174  Effect.gen(function* () {175    const host = yield* RepoHost;176    const client = yield* gitClient(memoryFs());177178    return Pusher.of({179      push: (to, parent, files) =>180        Effect.gen(function* () {181          const sha = yield* client.commit(182            "Work",183            files,184            Option.toArray(parent)185          );186187          yield* host188            .push(to, client.source, [{ from: parent, ref: mainRef, to: sha }])189            .pipe(Effect.orDie);190191          return sha;192        }),193    });194  })195);196197const world = Layer.mergeAll(198  ProjectsMemory.pipe(Layer.provide(ProjectSkillGenerator)),199  pusher200).pipe(201  Layer.provideMerge(202    Layer.mergeAll(AnswerRunsInline, AlarmsMemory, ProjectionMemory, rules)203  ),204  Layer.provideMerge(Layer.merge(mishapLander, checker)),205  Layer.provideMerge(RepoHostMemory)206);207208const mainTip = Effect.gen(function* () {209  const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);210211  return LandedSha.make(212    Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))213  );214});215216const commitAt = (sha: CommitSha) =>217  Effect.flatMap(RepoHost, (host) =>218    host219      .readCommit(repo, sha)220      .pipe(Effect.orDie, Effect.flatMap(Effect.fromOption))221  ).pipe(Effect.orDie);222223const textAt = (sha: CommitSha, path: string) =>224  Effect.flatMap(RepoHost, (host) =>225    host226      .readFile(repo, Revision.Commit({ sha }), RepoPath.make(path))227      .pipe(228        Effect.orDie,229        Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes)))230      )231  );232233const changedBy = (sha: CommitSha) =>234  Effect.gen(function* () {235    const commit = yield* commitAt(sha);236    const parent = yield* commitAt(commit.parents[0] ?? sha);237238    const changes = yield* treeDiff(239      repo,240      TreeSha.make(parent.tree),241      TreeSha.make(commit.tree)242    ).pipe(Effect.orDie);243244    return changes.map(({ path }) => path).toSorted();245  });246247const followUpAt = (sha: CommitSha) =>248  Effect.gen(function* () {249    const commit = yield* commitAt(sha);250251    return {252      author: commit.author,253      changed: yield* changedBy(sha),254      credits: creditsOf(commit.message).credits,255      parent: commit.parents[0],256      requestId: parseTrailers(commit.message).find(257        ({ key }) => key === "Request-Id"258      )?.value,259      subject: commit.message.split("\n")[0],260    };261  });262263const filesAt = (sha: CommitSha, run: typeof RunBlock.Encoded) =>264  Effect.gen(function* () {265    const generated = yield* Effect.forEach(generatedPaths, (path) =>266      Effect.map(267        textAt(sha, path),268        (text) => [path, Option.getOrElse(text, () => "")] as const269      )270    );271272    return [273      ...start.filter(([path]) => path !== runFile && path !== "AGENTS.md"),274      [runFile, `${JSON.stringify(run)}\n`],275      ...generated,276    ] satisfies Files;277  });278279const firstPushed = Effect.gen(function* () {280  yield* advanceTo("2026-10-07T12:00:00Z");281282  const api = yield* Projects.use((each) => each.create(project)).pipe(283    Effect.orDie284  );285286  yield* api.initProject(alice, {}).pipe(Effect.orDie);287288  const first = yield* Pusher.use((each) =>289    each.push(repo, Option.none(), start)290  );291292  yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);293294  return { api, first };295});296297const aliceLands = (base: LandedSha, files: Files, requestId: string) =>298  Effect.gen(function* () {299    const api = yield* Projects.use((each) => each.get(project)).pipe(300      Effect.orDie301    );302303    const { fork } = yield* api.fork(alice).pipe(Effect.orDie);304305    const head = yield* Pusher.use((each) =>306      each.push(fork, Option.some(base), files)307    );308309    const merged = yield* Lander.use((lander) =>310      lander.merge({ base, fork, head, main: base, repo })311    ).pipe(Effect.orDie);312313    yield* Passing.use((passing) =>314      passing.on(CheckAt.cases.Tree.make({ tree: merged.tree }), [315        "lint",316        "unit",317      ])318    );319320    const request = {321      base,322      head,323      message: "Change the project",324      requestId: RequestId.make(requestId),325    };326327    return { api, land: () => api.land(alice, request).pipe(Effect.orDie) };328  });329330const landedSha = (outcome: Outcome) =>331  Outcome.guards.Landed(outcome) ? Option.some(outcome.sha) : Option.none();332333describe("the contribute skill, regenerated by the platform", () => {334  it.effect(335    "follows the first push with a landing of the generated files alone, credited to the initializer",336    () =>337      Effect.gen(function* () {338        const { api, first } = yield* firstPushed;339        const tip = yield* mainTip;340341        expect(yield* followUpAt(tip)).toStrictEqual({342          author: authorLine(platformHandle),343          changed: generatedPaths.toSorted(),344          credits: [{ handle: alice.handle, role: "Decided-by" }],345          parent: first,346          requestId: `gen-${first}`,347          subject: "Regenerate the contribute skill and the AGENTS.md block",348        });349350        const agents = Option.getOrElse(351          yield* textAt(tip, "AGENTS.md"),352          () => ""353        );354355        expect(agents).toMatch(356          /^# Datekit\n\nOur own notes for agents\.\n\n<!-- BEGIN /u357        );358        expect(yield* textAt(tip, skill)).toStrictEqual(359          yield* textAt(tip, claudeSkill)360        );361362        expect(363          yield* Effect.exit(api.recordFirstPush(alice, first))364        ).toStrictEqual(Exit.succeed({ landed: first }));365        expect(yield* mainTip).toBe(tip);366      }).pipe(Effect.provide(world))367  );368369  it.effect(370    "follows a landing that changed the run block with one more platform commit, and a replay lands nothing",371    () =>372      Effect.gen(function* () {373        yield* firstPushed;374375        const generatedOnce = yield* mainTip;376377        const changed = yield* aliceLands(378          generatedOnce,379          yield* filesAt(generatedOnce, withUnit),380          "land-alice-unit-lane"381        );382383        const landed = Option.getOrThrow(384          landedSha((yield* changed.land()).outcome)385        );386387        const tip = yield* mainTip;388389        expect(yield* changedBy(landed)).toStrictEqual([runFile]);390        expect(yield* followUpAt(tip)).toStrictEqual({391          author: authorLine(platformHandle),392          changed: generatedPaths.toSorted(),393          credits: [{ handle: alice.handle, role: "Decided-by" }],394          parent: landed,395          requestId: `gen-${landed}`,396          subject: "Regenerate the contribute skill and the AGENTS.md block",397        });398        expect(Option.getOrElse(yield* textAt(tip, skill), () => "")).toContain(399          "bun run test"400        );401402        const replayed = yield* changed.land();403404        expect(landedSha(replayed.outcome)).toStrictEqual(Option.some(landed));405        expect(yield* mainTip).toBe(tip);406      }).pipe(Effect.provide(world))407  );408409  it.effect(410    "lands nothing of its own after a landing that changed only src/",411    () =>412      Effect.gen(function* () {413        yield* firstPushed;414415        const generatedOnce = yield* mainTip;416        const files = yield* filesAt(generatedOnce, lintOnly);417418        const changed = yield* aliceLands(419          generatedOnce,420          files.map(([path, text]) =>421            path === "src/parse.ts"422              ? ([423                  path,424                  "export const parse = (s) => ({ year: 2026 });\n",425                ] as const)426              : ([path, text] as const)427          ),428          "land-alice-parse"429        );430431        const landed = landedSha((yield* changed.land()).outcome);432433        expect(Option.some(yield* mainTip)).toStrictEqual(landed);434      }).pipe(Effect.provide(world))435  );436437  it.effect(438    "leaves the landing it follows standing when the follow-up could not land",439    () =>440      Effect.gen(function* () {441        yield* firstPushed;442443        const generatedOnce = yield* mainTip;444445        const changed = yield* aliceLands(446          generatedOnce,447          yield* filesAt(generatedOnce, withUnit),448          "land-alice-unit-lane"449        );450451        yield* Mishaps.use((each) => each.next("busy"));452453        const landed = landedSha((yield* changed.land()).outcome);454455        expect(Option.some(yield* mainTip)).toStrictEqual(landed);456        expect(yield* changedBy(Option.getOrThrow(landed))).toStrictEqual([457          runFile,458        ]);459      }).pipe(Effect.provide(world))460  );461462  it.effect(463    "fails the call when the follow-up reached main but its answer was lost, and the call run again records both landings",464    () =>465      Effect.gen(function* () {466        yield* firstPushed;467468        const generatedOnce = yield* mainTip;469470        const changed = yield* aliceLands(471          generatedOnce,472          yield* filesAt(generatedOnce, withUnit),473          "land-alice-unit-lane"474        );475476        yield* Mishaps.use((each) => each.next("lost"));477478        const lost = yield* Effect.exit(changed.land());479        const tip = yield* mainTip;480        const followed = yield* followUpAt(tip);481        const again = yield* changed.land();482483        expect({484          followed: followed.requestId,485          lost: Exit.isFailure(lost),486          main: yield* mainTip,487        }).toStrictEqual({488          followed: `gen-${followed.parent}`,489          lost: true,490          main: tip,491        });492        expect(landedSha(again.outcome)).toStrictEqual(493          Option.some(followed.parent)494        );495496        const recorded = yield* changed.api497          .landing(alice, tip)498          .pipe(Effect.orDie);499500        expect(recorded.landing.requestId).toBe(`gen-${followed.parent}`);501      }).pipe(Effect.provide(world))502  );503});