Skip to content
Myr

on-push.test.ts

This file

Path

apps/platform/test/workflows/on-push.test.ts

787 lines · 22.9 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3import { Brand } from "@repo/brand";4import { CheckRunner } from "@repo/checks/check-runner";5import { AlarmsMemory } from "@repo/project/alarms/memory";6import { AnswerRuns } from "@repo/project/answer-runs";7import { Lander } from "@repo/project/lander";8import { projectService } from "@repo/project/project";9import type { ProjectApi } from "@repo/project/project";10import { ProjectStore } from "@repo/project/project-store";11import { ProjectStoreMemory } from "@repo/project/project-store/memory";12import { ProjectionMemory } from "@repo/project/projection/memory";13import { Projects } from "@repo/project/projects";14import { RefNameText } from "@repo/protocol/domain/common";15import { DecisionSubject } from "@repo/protocol/domain/decision";16import type { LandingView } from "@repo/protocol/domain/landing";17import { Policy } from "@repo/protocol/domain/policy";18import {19  AskId,20  CommitSha,21  Handle,22  LandedSha,23  ProjectName,24  RepoName,25} from "@repo/protocol/ids";26import { Person } from "@repo/protocol/principal";27import {28  ProjectExists,29  UnknownCommit,30  UnknownProject,31} from "@repo/protocol/refusal";32import { RulesEvaluator } from "@repo/rules/rules-evaluator";33import { advanceTo } from "@repo/testkit/clock";34import { aProject, sha, withAsk, withVouches } from "@repo/testkit/scenarios";35import { untouchable } from "@repo/testkit/untouchable";36import { DateTime, Effect, Layer, Option, Ref, Schema } from "effect";3738import { RepoKind } from "../../src/repo-names.ts";39import { runInstance, runOnPush } from "../../src/workflows/on-push.ts";40import {41  classifyPush,42  PushVerdict,43} from "../../src/workflows/on-push/classify.ts";44import type {45  IgnoredReason,46  PushFacts,47} from "../../src/workflows/on-push/classify.ts";48import {49  isZero,50  OnPushEvent,51  ZeroSha,52} from "../../src/workflows/on-push/event.ts";53import { memoSteps, workflowSteps } from "../../src/workflows/step.ts";54import type { WorkflowSteps } from "../../src/workflows/step.ts";55import { fakeEnv, without } from "../fake-env.ts";5657const deliveredLine =58  '{"id": "88018624-a405-49c4-ba41-7dc60e4a2c89", "type": "cf.artifacts.repo.pushed", "source": {"namespace": "projects-local", "repoName": "alice__datekit"}, "payload": {"ref": "refs/heads/main", "before": "cfc3cc308874a348d38c7143c9093c17a196e4af", "after": "88359ce33219db41afafbcad7adc19f4f4d84381", "commits": [{"id": "88359ce33219db41afafbcad7adc19f4f4d84381", "message": "ev-0", "messageTruncated": false, "timestamp": "2026-10-06T20:10:48.000Z", "author": {"name": "probe", "email": "probe@invalid"}, "committer": {"name": "probe", "email": "probe@invalid"}, "parents": ["cfc3cc308874a348d38c7143c9093c17a196e4af"]}], "totalCommitsCount": 1, "commitsTruncated": false}}';5960const createdLine =61  '{"id": "bc6f5f68-4f76-45a7-8258-ad4ffd465cae", "type": "cf.artifacts.repo.pushed", "source": {"namespace": "projects-local", "repoName": "alice__datekit"}, "payload": {"ref": "refs/asked/ev", "before": "0000000000000000000000000000000000000000", "after": "8812c641c30d4a4633c6e77e3efe52c8f029f87d", "commits": [], "totalCommitsCount": 0, "commitsTruncated": false}}';6263const fromLine = Schema.decodeUnknownEffect(Schema.fromJsonString(OnPushEvent));6465describe(OnPushEvent, () => {66  it.effect("decodes the push event Artifacts delivered in S1", () =>67    Effect.gen(function* () {68      const event = yield* fromLine(deliveredLine);6970      expect({71        after: event.payload.after,72        before: event.payload.before,73        id: event.id,74        ref: event.payload.ref,75        repo: event.source.repoName,76        timestamps: event.payload.commits.map(({ timestamp }) => timestamp),77      }).toStrictEqual({78        after: CommitSha.make("88359ce33219db41afafbcad7adc19f4f4d84381"),79        before: CommitSha.make("cfc3cc308874a348d38c7143c9093c17a196e4af"),80        id: "88018624-a405-49c4-ba41-7dc60e4a2c89",81        ref: "refs/heads/main",82        repo: RepoName.make("alice__datekit"),83        timestamps: [DateTime.makeUnsafe("2026-10-06T20:10:48.000Z")],84      });85    })86  );8788  it.effect("reads a created ref's all-zero before as git's zero id", () =>89    Effect.map(fromLine(createdLine), (event) => {90      expect([91        isZero(event.payload.before),92        isZero(event.payload.after),93        event.payload.commits,94      ]).toStrictEqual([true, false, []]);95    })96  );97});9899const delivered = Schema.decodeSync(Schema.fromJsonString(OnPushEvent))(100  deliveredLine101);102103const pushed = (on: {104  readonly after: CommitSha;105  readonly before?: CommitSha;106  readonly id?: string;107  readonly ref?: string;108  readonly repo: string;109}): OnPushEvent => {110  const ref = on.ref ?? "refs/heads/main";111112  return {113    ...delivered,114    id: on.id ?? `${on.repo} ${ref} ${on.after}`,115    payload: {116      ...delivered.payload,117      after: on.after,118      before: on.before ?? delivered.payload.before,119      ref,120    },121    source: { ...delivered.source, repoName: RepoName.make(on.repo) },122  };123};124125const datekit = ProjectName.make("alice/datekit");126127const parseIso = AskId.make("parse-iso");128129const mainText = RefNameText.make("refs/heads/main");130131const landedSha = sha("datekit:landed");132133const strayHead = sha("datekit:stray");134135const answerHead = sha("datekit:answer");136137const canonical = RepoKind.Canonical({ project: datekit });138139const bobsFork = RepoKind.ClaimFork({140  ask: parseIso,141  handle: Handle.make("bob"),142  project: datekit,143});144145const facts = (repo: RepoKind, more: Partial<PushFacts> = {}): PushFacts => ({146  landed: new Set(),147  repo,148  seen: false,149  ...more,150});151152const ignored = (reason: IgnoredReason) =>153  PushVerdict.cases.Ignored.make({ reason });154155const table: readonly {156  readonly title: string;157  readonly event: OnPushEvent;158  readonly facts: PushFacts;159  readonly verdict: PushVerdict;160}[] = [161  {162    event: pushed({ after: landedSha, repo: "alice__datekit" }),163    facts: facts(canonical, { landed: new Set([landedSha]) }),164    title: "canonical main moved to a commit the platform landed",165    verdict: ignored("own landing"),166  },167  {168    event: pushed({169      after: landedSha,170      ref: `${Brand.refsPrefix}landed`,171      repo: "alice__datekit",172    }),173    facts: facts(canonical),174    title: "the landed mirror moved",175    verdict: ignored("bookkeeping ref"),176  },177  {178    event: pushed({179      after: strayHead,180      ref: `refs/notes/${Brand.slug}`,181      repo: "alice__datekit",182    }),183    facts: facts(canonical),184    title: "the verdict notes moved",185    verdict: ignored("bookkeeping ref"),186  },187  {188    event: pushed({189      after: strayHead,190      ref: `${Brand.refsPrefix}compose/${"e".repeat(40)}`,191      repo: "alice__datekit",192    }),193    facts: facts(canonical),194    title: "a composed commit was parked under the platform's prefix",195    verdict: ignored("bookkeeping ref"),196  },197  {198    event: pushed({199      after: strayHead,200      ref: "refs/heads/release",201      repo: "alice__datekit",202    }),203    facts: facts(canonical),204    title: "a canonical branch other than main moved",205    verdict: ignored("not main"),206  },207  {208    event: pushed({209      after: strayHead,210      before: landedSha,211      repo: "alice__datekit",212    }),213    facts: facts(canonical, { landed: new Set([landedSha]) }),214    title: "canonical main moved to a commit no landing made",215    verdict: PushVerdict.cases.Stray.make({216      after: strayHead,217      before: landedSha,218      project: datekit,219      ref: mainText,220    }),221  },222  {223    event: pushed({224      after: ZeroSha,225      before: landedSha,226      repo: "alice__datekit",227    }),228    facts: facts(canonical, { landed: new Set([landedSha]) }),229    title: "canonical main was deleted",230    verdict: PushVerdict.cases.Stray.make({231      after: ZeroSha,232      before: landedSha,233      project: datekit,234      ref: mainText,235    }),236  },237  {238    event: pushed({239      after: answerHead,240      repo: "alice__datekit--parse-iso--bob",241    }),242    facts: facts(bobsFork, { seen: true }),243    title: "a claim fork took a push the gateway recorded",244    verdict: ignored("seen"),245  },246  {247    event: pushed({248      after: answerHead,249      repo: "alice__datekit--parse-iso--bob",250    }),251    facts: facts(bobsFork),252    title: "a claim fork took a push the gateway never recorded",253    verdict: PushVerdict.cases.ForkPush.make({254      ask: parseIso,255      head: answerHead,256      project: datekit,257    }),258  },259  {260    event: pushed({261      after: answerHead,262      ref: `refs/notes/${Brand.slug}`,263      repo: "alice__datekit--parse-iso--bob",264    }),265    facts: facts(bobsFork),266    title: "a claim fork's verdict notes moved",267    verdict: ignored("bookkeeping ref"),268  },269  {270    event: pushed({271      after: ZeroSha,272      before: answerHead,273      repo: "alice__datekit--parse-iso--bob",274    }),275    facts: facts(bobsFork),276    title: "a claim fork's branch was deleted",277    verdict: ignored("deleted ref"),278  },279  {280    event: pushed({ after: answerHead, repo: "alice__datekit--me--alice" }),281    facts: facts(282      RepoKind.WorkingFork({ handle: Handle.make("alice"), project: datekit })283    ),284    title: "a maintainer's working fork took a push",285    verdict: ignored("not main"),286  },287  {288    event: pushed({ after: strayHead, repo: "Not.A.Project" }),289    facts: facts(RepoKind.Unknown()),290    title: "a repo no project has",291    verdict: ignored("unknown repo"),292  },293];294295describe(classifyPush, () => {296  it.each(table)("$title", ({ event, facts: said, verdict }) => {297    expect(classifyPush(event, said)).toStrictEqual(verdict);298  });299});300301const scenario = aProject({ people: ["bob"] }).pipe(302  withVouches(["bob"]),303  withAsk({ id: "parse-iso", territory: "packages/parser" })304);305306const alice = Person.make({ handle: scenario.initializer });307308const bob = Person.make({ handle: Handle.make("bob") });309310const theLanding: LandingView = {311  assisted: [],312  author: scenario.initializer,313  credits: [],314  landedAt: scenario.now,315  parent: LandedSha.make(sha("datekit:start")),316  project: datekit,317  sha: scenario.landed,318};319320const ports = Layer.mergeAll(321  AlarmsMemory,322  ProjectionMemory,323  ProjectStoreMemory,324  RepoHostMemory,325  Layer.succeed(326    AnswerRuns,327    untouchable<typeof AnswerRuns.Service>("AnswerRuns")328  ),329  Layer.succeed(330    CheckRunner,331    untouchable<typeof CheckRunner.Service>("CheckRunner")332  ),333  Layer.succeed(Lander, untouchable<typeof Lander.Service>("Lander")),334  Layer.succeed(335    RulesEvaluator,336    untouchable<typeof RulesEvaluator.Service>("RulesEvaluator")337  )338);339340const seeded = Effect.gen(function* () {341  const store = yield* ProjectStore;342343  const policy = yield* Schema.encodeEffect(Schema.toCodecJson(Policy))(344    scenario.policy345  );346347  yield* store.commit({348    asks: scenario.policy.asks,349    landings: [theLanding],350    project: {351      createdAt: scenario.now,352      initializer: scenario.initializer,353      landed: scenario.landed,354      policy,355      policyAt: scenario.landed,356      project: datekit,357      state: "live",358    },359  });360});361362const projectsOf = (api: ProjectApi) =>363  Layer.succeed(364    Projects,365    Projects.of({366      create: (project) => Effect.fail(new ProjectExists({ project })),367      get: (project) =>368        project === datekit369          ? Effect.succeed(api)370          : Effect.fail(new UnknownProject({ project })),371    })372  );373374const world = Effect.gen(function* () {375  yield* advanceTo("2026-10-07T12:00:00Z");376  yield* seeded;377378  const api = yield* projectService(datekit);379380  return { api, projects: projectsOf(api), store: yield* ProjectStore };381}).pipe(Effect.provide(ports));382383const onPush = (event: OnPushEvent, projects: Layer.Layer<Projects>) =>384  Effect.flatMap(memoSteps(), (steps) =>385    runOnPush(event).pipe(Effect.provide([steps, projects]))386  );387388const telling = (api: ProjectApi) =>389  Effect.map(Ref.make<readonly string[]>([]), (told) => ({390    projects: projectsOf({391      ...api,392      recordPush: (report) =>393        Effect.andThen(394          Ref.update(told, (ids) => [...ids, report.eventId]),395          api.recordPush(report)396        ),397    }),398    told,399  }));400401const engineSteps = () => {402  const recorded = new Map<string, Promise<Schema.Json>>();403404  const steps: WorkflowSteps = {405    do: (name, _config, body) => {406      const kept = recorded.get(name) ?? body();407408      recorded.set(name, kept);409410      return kept;411    },412  };413414  return { recorded, steps };415};416417describe(runOnPush, () => {418  it.effect(419    "ignores main moved to the landing the platform made, and its bookkeeping refs",420    () =>421      Effect.gen(function* () {422        const { api, projects } = yield* world;423424        const verdicts = yield* Effect.forEach(425          [426            pushed({ after: scenario.landed, repo: "alice__datekit" }),427            pushed({428              after: scenario.landed,429              ref: `${Brand.refsPrefix}landed`,430              repo: "alice__datekit",431            }),432            pushed({433              after: strayHead,434              ref: `refs/notes/${Brand.slug}`,435              repo: "alice__datekit",436            }),437          ],438          (event) => onPush(event, projects)439        );440441        expect(verdicts).toStrictEqual([442          ignored("own landing"),443          ignored("bookkeeping ref"),444          ignored("bookkeeping ref"),445        ]);446        expect((yield* api.today(alice)).decisions).toStrictEqual([]);447      })448  );449450  it.effect(451    "ignores a claim fork's push the gateway recorded, and records one it never saw as the claimant's",452    () =>453      Effect.gen(function* () {454        const { api, projects } = yield* world;455        const fork = "alice__datekit--parse-iso--bob";456        const elsewhere = sha("datekit:elsewhere");457458        const lastPush = Effect.map(api.status(bob), ({ claims }) =>459          claims.map(({ lastPushAt }) =>460            Option.map(Option.fromUndefinedOr(lastPushAt), DateTime.formatIso)461          )462        );463464        yield* api.claim(bob, parseIso);465466        yield* advanceTo("2026-10-07T13:00:00Z");467        yield* api.recordPush({468          after: answerHead,469          before: Option.none(),470          eventId: `push-${answerHead}`,471          pusher: bob,472          ref: "refs/heads/main",473          repo: RepoName.make(fork),474        });475476        yield* advanceTo("2026-10-07T13:30:00Z");477478        const seen = yield* onPush(479          pushed({ after: answerHead, repo: fork }),480          projects481        );482483        const afterSeen = yield* lastPush;484485        yield* advanceTo("2026-10-07T14:00:00Z");486487        const unseen = yield* onPush(488          pushed({ after: elsewhere, before: answerHead, repo: fork }),489          projects490        );491492        expect([seen, unseen]).toStrictEqual([493          ignored("seen"),494          PushVerdict.cases.ForkPush.make({495            ask: parseIso,496            head: elsewhere,497            project: datekit,498          }),499        ]);500        expect([afterSeen, yield* lastPush]).toStrictEqual([501          [Option.some("2026-10-07T13:00:00.000Z")],502          [Option.some("2026-10-07T14:00:00.000Z")],503        ]);504        expect((yield* api.today(alice)).decisions).toStrictEqual([]);505      })506  );507508  it.effect(509    "opens a StrayPush decision on Today, revert by default, when main moved without a landing",510    () =>511      Effect.gen(function* () {512        const { api, projects } = yield* world;513514        const verdict = yield* onPush(515          pushed({516            after: strayHead,517            before: scenario.landed,518            repo: "alice__datekit",519          }),520          projects521        );522523        const { decisions } = yield* api.today(alice);524525        expect(verdict).toStrictEqual(526          PushVerdict.cases.Stray.make({527            after: strayHead,528            before: scenario.landed,529            project: datekit,530            ref: mainText,531          })532        );533        expect(534          decisions.map((decision) => ({535            default: decision.default,536            subject: decision.subject,537          }))538        ).toStrictEqual([539          {540            default: "revert",541            subject: DecisionSubject.cases.StrayPush.make({542              after: strayHead,543              before: scenario.landed,544              ref: mainText,545            }),546          },547        ]);548      })549  );550551  it.effect(552    "opens one decision for one event, replayed over one record of steps or recorded twice",553    () =>554      Effect.gen(function* () {555        const { api } = yield* world;556        const { projects, told } = yield* telling(api);557558        const stray = pushed({559          after: strayHead,560          before: scenario.landed,561          id: "2027e2b8-96df-4364-a992-3be1b702d7f4",562          repo: "alice__datekit",563        });564565        const steps = yield* memoSteps();566567        const replayed = runOnPush(stray).pipe(568          Effect.provide([steps, projects])569        );570571        const verdicts = [572          yield* replayed,573          yield* replayed,574          yield* onPush(stray, projects),575        ];576577        const { decisions } = yield* api.today(alice);578579        expect(verdicts.map(({ _tag }) => _tag)).toStrictEqual([580          "Stray",581          "Stray",582          "Stray",583        ]);584        expect(yield* Ref.get(told)).toStrictEqual([stray.id, stray.id]);585        expect(decisions.map(({ subject }) => subject)).toStrictEqual([586          DecisionSubject.cases.StrayPush.make({587            after: strayHead,588            before: scenario.landed,589            ref: mainText,590          }),591        ]);592      })593  );594595  it.effect(596    "settles a stray main as a recorded value, so a run the engine replays after keeping the grace's failure still opens one decision",597    () =>598      Effect.gen(function* () {599        const { api } = yield* world;600        const { projects, told } = yield* telling(api);601        const engine = engineSteps();602603        const stray = pushed({604          after: strayHead,605          before: scenario.landed,606          repo: "alice__datekit",607        });608609        const run = runOnPush(stray).pipe(610          Effect.provide([workflowSteps(engine.steps), projects]),611          Effect.catchDefect(() => Effect.succeed("died"))612        );613614        const verdicts = [yield* run, yield* run];615        const { decisions } = yield* api.today(alice);616617        const verdict = PushVerdict.cases.Stray.make({618          after: strayHead,619          before: scenario.landed,620          project: datekit,621          ref: mainText,622        });623624        expect({625          decisions: decisions.map(({ subject }) => subject._tag),626          steps: [...engine.recorded.keys()],627          told: yield* Ref.get(told),628          verdicts,629        }).toStrictEqual({630          decisions: ["StrayPush"],631          steps: ["classify", "settle", "record"],632          told: [stray.id],633          verdicts: [verdict, verdict],634        });635      })636  );637638  it.effect(639    "asks again before calling main stray, so a landing the DO records a moment late is its own",640    () =>641      Effect.gen(function* () {642        const { api, store } = yield* world;643        const asked = yield* Ref.make(0);644645        const late = Projects.of({646          create: (project) => Effect.fail(new ProjectExists({ project })),647          get: () =>648            Effect.succeed({649              ...api,650              landing: (caller, at) =>651                Effect.flatMap(652                  Ref.getAndUpdate(asked, (n) => n + 1),653                  (n) =>654                    n === 0655                      ? Effect.andThen(656                          store.commit({657                            landings: [658                              {659                                ...theLanding,660                                parent: scenario.landed,661                                sha: LandedSha.make(strayHead),662                              },663                            ],664                          }),665                          Effect.fail(new UnknownCommit({ sha: at }))666                        )667                      : api.landing(caller, at)668                ),669            }),670        });671672        const verdict = yield* onPush(673          pushed({674            after: strayHead,675            before: scenario.landed,676            repo: "alice__datekit",677          }),678          Layer.succeed(Projects, late)679        );680681        expect([verdict, yield* Ref.get(asked)]).toStrictEqual([682          ignored("own landing"),683          2,684        ]);685        expect((yield* api.today(alice)).decisions).toStrictEqual([]);686      })687  );688689  it.effect(690    "calls a deleted main stray at once: no landing is in flight to wait for",691    () =>692      Effect.gen(function* () {693        const { api, projects } = yield* world;694        const engine = engineSteps();695696        const verdict = yield* runOnPush(697          pushed({698            after: ZeroSha,699            before: scenario.landed,700            repo: "alice__datekit",701          })702        ).pipe(Effect.provide([workflowSteps(engine.steps), projects]));703704        const { decisions } = yield* api.today(alice);705706        expect({707          decisions: decisions.map(({ subject }) => subject),708          steps: [...engine.recorded.keys()],709          verdict,710        }).toStrictEqual({711          decisions: [712            DecisionSubject.cases.StrayPush.make({713              after: ZeroSha,714              before: scenario.landed,715              ref: mainText,716            }),717          ],718          steps: ["classify", "record"],719          verdict: PushVerdict.cases.Stray.make({720            after: ZeroSha,721            before: scenario.landed,722            project: datekit,723            ref: mainText,724          }),725        });726      })727  );728729  it.effect("ignores a repo whose name no project of the platform's has", () =>730    Effect.gen(function* () {731      const { projects } = yield* world;732733      const verdicts = yield* Effect.forEach(734        ["Not.A.Project", "alice__datekit--parse-iso", "elsewhere"],735        (repo) => onPush(pushed({ after: strayHead, repo }), projects)736      );737738      expect(verdicts).toStrictEqual([739        ignored("unknown repo"),740        ignored("unknown repo"),741        ignored("unknown repo"),742      ]);743    })744  );745});746747const sent = Schema.encodeSync(OnPushEvent)(delivered);748749describe(runInstance, () => {750  it.effect("decodes its params before it reads the env", () =>751    Effect.gen(function* () {752      const failure = yield* runInstance(753        without(fakeEnv(), "STAGE"),754        { ...sent, payload: { ...sent.payload, after: "HEAD" } },755        engineSteps().steps756      ).pipe(Effect.flip);757758      expect(failure._tag).toBe("SchemaError");759    })760  );761762  it.effect(763    "answers a repo no project has without touching a binding, and records its step as JSON",764    () =>765      Effect.gen(function* () {766        const engine = engineSteps();767768        const output = yield* runInstance(769          fakeEnv(),770          { ...sent, source: { ...sent.source, repoName: "Not.A.Project" } },771          engine.steps772        );773774        const expected = yield* Schema.encodeEffect(PushVerdict)(775          ignored("unknown repo")776        );777778        expect([779          output,780          yield* Effect.promise(781            () => engine.recorded.get("classify") ?? Promise.resolve(null)782          ),783          [...engine.recorded.keys()],784        ]).toStrictEqual([expected, expected, ["classify"]]);785      })786  );787});