Skip to content
Myr

Merge build/313-on-push-workflow: any move of a canonical main the platform did not make becomes a decision

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 7026edb, 6e3dffd · Browse files · 5 files+1332 added−30 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+1332 added−30 removed

  • tests:+874 added−0 removed
  • other:+458 added−30 removed

5 files+1332 added−30 removed

added:apps/platform/src/workflows/on-push/classify.ts+125 added
1/**2 * What one push event means to the platform (spec §5 step 9), as a pure3 * function of the event and what the project's Durable Object says about it.4 * Pushes the platform made (landings, the landed mirror, parked composes,5 * verdict notes) and claim-fork pushes the gateway already recorded are6 * ignored; a claim-fork push the gateway never saw keeps its claim alive;7 * canonical `main` moved any other way is stray, for the deciders to adopt8 * or revert (CM §4).9 */10import { Brand } from "@repo/brand";11import { notesRef } from "@repo/git/notes";12import { RefNameText } from "@repo/protocol/domain/common";13import { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";14import { Schema } from "effect";1516import { RepoKind } from "../../repo-names.ts";17import { isZero } from "./event.ts";18import type { OnPushEvent } from "./event.ts";1920/** Why a push needs nothing from the platform. */21export const IgnoredReason = Schema.Literals([22 /** Canonical `main` moved to a commit the platform landed. */23 "own landing",24 /** A ref the platform writes beside `main`: under its prefix, or its notes. */25 "bookkeeping ref",26 /** A claim-fork push the gateway recorded when it forwarded it. */27 "seen",28 /** A repo no project of the platform's has. */29 "unknown repo",30 /** A ref whose moves the platform does not track: a canonical branch other than `main`, or a decider's working fork. */31 "not main",32 /** A claim fork's ref deleted: no commit to keep the claim alive with. */33 "deleted ref",34]);3536export type IgnoredReason = typeof IgnoredReason.Type;3738/** What the platform does about one push event. */39export const PushVerdict = Schema.TaggedUnion({40 /** A claim-fork push the gateway never recorded: record it, for its claim's liveness. */41 ForkPush: { ask: AskId, head: CommitSha, project: ProjectName },42 Ignored: { reason: IgnoredReason },43 /**44 * Canonical `main` moved without a landing: a `StrayPush` decision whose45 * default is revert. `after` is git's zero id when `main` was deleted,46 * `before` when it was created.47 */48 Stray: {49 after: CommitSha,50 before: CommitSha,51 project: ProjectName,52 ref: RefNameText,53 },54});5556export type PushVerdict = typeof PushVerdict.Type;5758/** What the project's Durable Object says about a push event, read before it is classified. */59export interface PushFacts {60 /** The repo, by its name; `Unknown` also when no project has that name. */61 readonly repo: RepoKind;62 /** Commits the platform landed on canonical `main`, among those the event names. */63 readonly landed: ReadonlySet<CommitSha>;64 /** Whether the gateway recorded this repo taking the event's `after`. */65 readonly seen: boolean;66}6768/** The one canonical ref the platform alone moves. */69export const mainRef = RefNameText.make("refs/heads/main");7071/**72 * A ref the platform writes beside `main`, in its own push after main's73 * (S1 change 1): the landed mirror and parked composes under its prefix,74 * and its verdict notes. Each fires its own event (S1 #13).75 */76export const isBookkeeping = (ref: string): boolean =>77 ref.startsWith(Brand.refsPrefix) || ref === notesRef;7879const ignored = (reason: IgnoredReason): PushVerdict =>80 PushVerdict.cases.Ignored.make({ reason });8182/** What `event` means, given what the project's Durable Object said of it. */83export const classifyPush = (84 event: OnPushEvent,85 facts: PushFacts86): PushVerdict => {87 const { after, before, ref } = event.payload;8889 return RepoKind.$match(facts.repo, {90 Canonical: ({ project }) => {91 if (isBookkeeping(ref)) {92 return ignored("bookkeeping ref");93 }9495 if (ref !== mainRef) {96 return ignored("not main");97 }9899 return facts.landed.has(after)100 ? ignored("own landing")101 : PushVerdict.cases.Stray.make({102 after,103 before,104 project,105 ref: mainRef,106 });107 },108 ClaimFork: ({ ask, project }) => {109 if (isBookkeeping(ref)) {110 return ignored("bookkeeping ref");111 }112113 if (isZero(after)) {114 return ignored("deleted ref");115 }116117 return facts.seen118 ? ignored("seen")119 : PushVerdict.cases.ForkPush.make({ ask, head: after, project });120 },121 Unknown: () => ignored("unknown repo"),122 WorkingFork: () =>123 isBookkeeping(ref) ? ignored("bookkeeping ref") : ignored("not main"),124 });125};
added:apps/platform/src/workflows/on-push/event.ts+58 added
added:apps/platform/src/workflows/on-push/facts.ts+115 added
1/**2 * What OnPush asks a project's Durable Object before it classifies a push3 * event: whether canonical `main`'s new commit is a landing the platform4 * made (`landing(platform, sha)`), and whether the gateway recorded a claim5 * fork taking the pushed commit. Each read is asked only of the events it6 * can change the verdict of.7 */8import { platformHandle } from "@repo/project/attention/effects";9import type { ProjectApi } from "@repo/project/project";10import { keptEvents } from "@repo/project/project-store";11import { Projects } from "@repo/project/projects";12import { ProjectEvent } from "@repo/protocol/domain/event";13import type { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";14import { Person } from "@repo/protocol/principal";15import { Effect, Option } from "effect";1617import { RepoKind, repoKind } from "../../repo-names.ts";18import { isBookkeeping, mainRef } from "./classify.ts";19import type { PushFacts } from "./classify.ts";20import { isZero } from "./event.ts";21import type { OnPushEvent } from "./event.ts";2223/** The platform itself, reading a project's public record. */24const platform = Person.make({ handle: platformHandle });2526/** The project a repo belongs to, when its name says. */27const projectOf = (kind: RepoKind): Option.Option<ProjectName> =>28 RepoKind.$match(kind, {29 Canonical: ({ project }) => Option.some(project),30 ClaimFork: ({ project }) => Option.some(project),31 Unknown: () => Option.none(),32 WorkingFork: ({ project }) => Option.some(project),33 });3435/** `sha` as a landing the platform made on the project's `main`, or none. */36const landedOf = (api: ProjectApi, sha: CommitSha) =>37 Effect.map(Effect.isSuccess(api.landing(platform, sha)), (landed) =>38 landed ? new Set([sha]) : new Set<CommitSha>()39 );4041/**42 * Whether the gateway recorded the claim's fork taking `head`: recording a43 * claimant's push keeps the claim alive and emits `Pushed`, which the44 * project keeps among its newest events.45 */46const seenBy = (47 api: ProjectApi,48 push: { readonly ask: AskId; readonly head: CommitSha }49) =>50 Effect.map(api.events(0, keptEvents), (rows) =>51 rows.some(52 ({ event }) =>53 ProjectEvent.guards.Pushed(event) &&54 event.ask === push.ask &&55 event.head === push.head56 )57 );5859const nothing = (repo: RepoKind): PushFacts => ({60 landed: new Set(),61 repo,62 seen: false,63});6465/** The project and the API of the repo `event` is about, when the platform has that project. */66export const projectFor = (event: OnPushEvent) =>67 Effect.gen(function* () {68 const kind = repoKind(event.source.repoName);69 const project = projectOf(kind);7071 if (Option.isNone(project)) {72 return Option.none();73 }7475 const api = yield* Effect.option(76 Projects.use((projects) => projects.get(project.value))77 );7879 return Option.map(api, (found) => ({ api: found, kind }));80 });8182/** What the project's Durable Object says about `event`. */83export const factsOf = (84 event: OnPushEvent85): Effect.Effect<PushFacts, never, Projects> =>86 Effect.gen(function* () {87 const { after, ref } = event.payload;88 const found = yield* projectFor(event);8990 if (Option.isNone(found)) {91 return nothing(RepoKind.Unknown());92 }9394 const { api, kind } = found.value;95 const moved = !isZero(after) && !isBookkeeping(ref);9697 return yield* RepoKind.$match(kind, {98 Canonical: () =>99 moved && ref === mainRef100 ? Effect.map(landedOf(api, after), (landed) => ({101 ...nothing(kind),102 landed,103 }))104 : Effect.succeed(nothing(kind)),105 ClaimFork: ({ ask }) =>106 moved107 ? Effect.map(seenBy(api, { ask, head: after }), (seen) => ({108 ...nothing(kind),109 seen,110 }))111 : Effect.succeed(nothing(kind)),112 Unknown: () => Effect.succeed(nothing(kind)),113 WorkingFork: () => Effect.succeed(nothing(kind)),114 });115 });
modified:apps/platform/src/workflows/on-push.ts+160 added-30 removed
added:apps/platform/test/workflows/on-push.test.ts+874 added
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, PushReport } 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 DecisionId,22 Handle,23 LandedSha,24 ProjectName,25 RepoName,26} from "@repo/protocol/ids";27import { Person } from "@repo/protocol/principal";28import {29 ProjectExists,30 UnknownCommit,31 UnknownProject,32} from "@repo/protocol/refusal";33import { RulesEvaluator } from "@repo/rules/rules-evaluator";34import { advanceTo } from "@repo/testkit/clock";35import { aProject, sha, withAsk, withVouches } from "@repo/testkit/scenarios";36import { untouchable } from "@repo/testkit/untouchable";37import { DateTime, Effect, Layer, Option, Ref, Schema } from "effect";3839import { RepoKind } from "../../src/repo-names.ts";40import { runInstance, runOnPush } from "../../src/workflows/on-push.ts";41import {42 classifyPush,43 PushVerdict,44} from "../../src/workflows/on-push/classify.ts";45import type {46 IgnoredReason,47 PushFacts,48} from "../../src/workflows/on-push/classify.ts";49import {50 isZero,51 OnPushEvent,52 ZeroSha,53} from "../../src/workflows/on-push/event.ts";54import { memoSteps, workflowSteps } from "../../src/workflows/step.ts";55import type { WorkflowSteps } from "../../src/workflows/step.ts";56import { fakeEnv, without } from "../fake-env.ts";5758/**59 * One `cf.artifacts.repo.pushed` event as Artifacts delivered it to the S160 * spike's Workflow (S1 #15, `results-s1workflow-1791317493.jsonl`, line 1),61 * verbatim but for the namespace and repo, renamed to a test project's.62 */63const deliveredLine =64 '{"id": "88018624-a405-49c4-ba41-7dc60e4a2c89", "type": "cf.artifacts.repo.pushed", "source": {"namespace": "projects-local", "repoName": "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}}';6566/**67 * The event S1 saw for a custom ref pushed beside `main` (line 5): its68 * `before` is git's all-zero id, since the push created the ref, and it69 * lists no commits (S1 #13).70 */71const createdLine =72 '{"id": "bc6f5f68-4f76-45a7-8258-ad4ffd465cae", "type": "cf.artifacts.repo.pushed", "source": {"namespace": "projects-local", "repoName": "datekit"}, "payload": {"ref": "refs/asked/ev", "before": "0000000000000000000000000000000000000000", "after": "8812c641c30d4a4633c6e77e3efe52c8f029f87d", "commits": [], "totalCommitsCount": 0, "commitsTruncated": false}}';7374const fromLine = Schema.decodeUnknownEffect(Schema.fromJsonString(OnPushEvent));7576describe(OnPushEvent, () => {77 it.effect("decodes the push event Artifacts delivered in S1", () =>78 Effect.gen(function* () {79 const event = yield* fromLine(deliveredLine);8081 expect({82 after: event.payload.after,83 before: event.payload.before,84 id: event.id,85 ref: event.payload.ref,86 repo: event.source.repoName,87 timestamps: event.payload.commits.map(({ timestamp }) => timestamp),88 }).toStrictEqual({89 after: CommitSha.make("88359ce33219db41afafbcad7adc19f4f4d84381"),90 before: CommitSha.make("cfc3cc308874a348d38c7143c9093c17a196e4af"),91 id: "88018624-a405-49c4-ba41-7dc60e4a2c89",92 ref: "refs/heads/main",93 repo: RepoName.make("datekit"),94 timestamps: [DateTime.makeUnsafe("2026-10-06T20:10:48.000Z")],95 });96 })97 );9899 it.effect("reads a created ref's all-zero before as git's zero id", () =>100 Effect.map(fromLine(createdLine), (event) => {101 expect([102 isZero(event.payload.before),103 isZero(event.payload.after),104 event.payload.commits,105 ]).toStrictEqual([true, false, []]);106 })107 );108});109110/** The delivered event, decoded: what every other event here is made from. */111const delivered = Schema.decodeSync(Schema.fromJsonString(OnPushEvent))(112 deliveredLine113);114115/** A push event like the delivered one, for `repo`'s `ref` moving to `after`. */116const pushed = (on: {117 readonly after: CommitSha;118 readonly before?: CommitSha;119 readonly id?: string;120 readonly ref?: string;121 readonly repo: string;122}): OnPushEvent => {123 const ref = on.ref ?? "refs/heads/main";124125 return {126 ...delivered,127 id: on.id ?? `${on.repo} ${ref} ${on.after}`,128 payload: {129 ...delivered.payload,130 after: on.after,131 before: on.before ?? delivered.payload.before,132 ref,133 },134 source: { ...delivered.source, repoName: RepoName.make(on.repo) },135 };136};137138const datekit = ProjectName.make("datekit");139140const parseIso = AskId.make("parse-iso");141142const mainText = RefNameText.make("refs/heads/main");143144const landedSha = sha("datekit:landed");145146const strayHead = sha("datekit:stray");147148const answerHead = sha("datekit:answer");149150const canonical = RepoKind.Canonical({ project: datekit });151152const canonicalRepo = RepoName.make(datekit);153154const bobsFork = RepoKind.ClaimFork({155 ask: parseIso,156 handle: Handle.make("bob"),157 project: datekit,158});159160/** What the DO said: nothing landed, nothing seen, unless a row says so. */161const facts = (repo: RepoKind, more: Partial<PushFacts> = {}): PushFacts => ({162 landed: new Set(),163 repo,164 seen: false,165 ...more,166});167168const ignored = (reason: IgnoredReason) =>169 PushVerdict.cases.Ignored.make({ reason });170171const table: readonly {172 readonly title: string;173 readonly event: OnPushEvent;174 readonly facts: PushFacts;175 readonly verdict: PushVerdict;176}[] = [177 {178 event: pushed({ after: landedSha, repo: "datekit" }),179 facts: facts(canonical, { landed: new Set([landedSha]) }),180 title: "canonical main moved to a commit the platform landed",181 verdict: ignored("own landing"),182 },183 {184 event: pushed({185 after: landedSha,186 ref: `${Brand.refsPrefix}landed`,187 repo: "datekit",188 }),189 facts: facts(canonical),190 title: "the landed mirror moved",191 verdict: ignored("bookkeeping ref"),192 },193 {194 event: pushed({195 after: strayHead,196 ref: `refs/notes/${Brand.slug}`,197 repo: "datekit",198 }),199 facts: facts(canonical),200 title: "the verdict notes moved",201 verdict: ignored("bookkeeping ref"),202 },203 {204 event: pushed({205 after: strayHead,206 ref: `${Brand.refsPrefix}compose/${"e".repeat(40)}`,207 repo: "datekit",208 }),209 facts: facts(canonical),210 title: "a composed commit was parked under the platform's prefix",211 verdict: ignored("bookkeeping ref"),212 },213 {214 event: pushed({215 after: strayHead,216 ref: "refs/heads/release",217 repo: "datekit",218 }),219 facts: facts(canonical),220 title: "a canonical branch other than main moved",221 verdict: ignored("not main"),222 },223 {224 event: pushed({ after: strayHead, before: landedSha, repo: "datekit" }),225 facts: facts(canonical, { landed: new Set([landedSha]) }),226 title: "canonical main moved to a commit no landing made",227 verdict: PushVerdict.cases.Stray.make({228 after: strayHead,229 before: landedSha,230 project: datekit,231 ref: mainText,232 }),233 },234 {235 event: pushed({ after: ZeroSha, before: landedSha, repo: "datekit" }),236 facts: facts(canonical, { landed: new Set([landedSha]) }),237 title: "canonical main was deleted",238 verdict: PushVerdict.cases.Stray.make({239 after: ZeroSha,240 before: landedSha,241 project: datekit,242 ref: mainText,243 }),244 },245 {246 event: pushed({ after: answerHead, repo: "datekit--parse-iso--bob" }),247 facts: facts(bobsFork, { seen: true }),248 title: "a claim fork took a push the gateway recorded",249 verdict: ignored("seen"),250 },251 {252 event: pushed({ after: answerHead, repo: "datekit--parse-iso--bob" }),253 facts: facts(bobsFork),254 title: "a claim fork took a push the gateway never recorded",255 verdict: PushVerdict.cases.ForkPush.make({256 ask: parseIso,257 head: answerHead,258 project: datekit,259 }),260 },261 {262 event: pushed({263 after: answerHead,264 ref: `refs/notes/${Brand.slug}`,265 repo: "datekit--parse-iso--bob",266 }),267 facts: facts(bobsFork),268 title: "a claim fork's verdict notes moved",269 verdict: ignored("bookkeeping ref"),270 },271 {272 event: pushed({273 after: ZeroSha,274 before: answerHead,275 repo: "datekit--parse-iso--bob",276 }),277 facts: facts(bobsFork),278 title: "a claim fork's branch was deleted",279 verdict: ignored("deleted ref"),280 },281 {282 event: pushed({ after: answerHead, repo: "datekit--me--alice" }),283 facts: facts(284 RepoKind.WorkingFork({ handle: Handle.make("alice"), project: datekit })285 ),286 title: "a decider's working fork took a push",287 verdict: ignored("not main"),288 },289 {290 event: pushed({ after: strayHead, repo: "Not.A.Project" }),291 facts: facts(RepoKind.Unknown()),292 title: "a repo no project has",293 verdict: ignored("unknown repo"),294 },295];296297describe(classifyPush, () => {298 it.each(table)("$title", ({ event, facts: said, verdict }) => {299 expect(classifyPush(event, said)).toStrictEqual(verdict);300 });301});302303/**304 * datekit at its landed commit, which the platform landed on top of its305 * first: alice decides everything, bob is vouched for, and `parse-iso` is306 * open.307 */308const scenario = aProject({ people: ["bob"] }).pipe(309 withVouches(["bob"]),310 withAsk({ id: "parse-iso", territory: "packages/parser" })311);312313const alice = Person.make({ handle: scenario.initializer });314315const bob = Person.make({ handle: Handle.make("bob") });316317/** The project's one landing: its landed commit. */318const theLanding: LandingView = {319 assisted: [],320 author: scenario.initializer,321 credits: [],322 landedAt: scenario.now,323 parent: LandedSha.make(sha("datekit:start")),324 project: datekit,325 sha: scenario.landed,326};327328/**329 * Every port the project's service runs on, in memory. The Lander, the330 * Checker, the rules and answer runs are never needed by a push event:331 * touching one fails the test.332 */333const ports = Layer.mergeAll(334 AlarmsMemory,335 ProjectionMemory,336 ProjectStoreMemory,337 RepoHostMemory,338 Layer.succeed(339 AnswerRuns,340 untouchable<typeof AnswerRuns.Service>("AnswerRuns")341 ),342 Layer.succeed(343 CheckRunner,344 untouchable<typeof CheckRunner.Service>("CheckRunner")345 ),346 Layer.succeed(Lander, untouchable<typeof Lander.Service>("Lander")),347 Layer.succeed(348 RulesEvaluator,349 untouchable<typeof RulesEvaluator.Service>("RulesEvaluator")350 )351);352353/** datekit live at its landed commit, with its one landing and its asks, as its store holds them. */354const seeded = Effect.gen(function* () {355 const store = yield* ProjectStore;356357 const policy = yield* Schema.encodeEffect(Schema.toCodecJson(Policy))(358 scenario.policy359 );360361 yield* store.commit({362 asks: scenario.policy.asks,363 landings: [theLanding],364 project: {365 createdAt: scenario.now,366 initializer: scenario.initializer,367 landed: scenario.landed,368 policy,369 policyAt: scenario.landed,370 project: datekit,371 state: "live",372 },373 });374});375376/** `Projects` in memory, holding datekit's service and no other project. */377const projectsOf = (api: ProjectApi) =>378 Layer.succeed(379 Projects,380 Projects.of({381 create: (project) => Effect.fail(new ProjectExists({ project })),382 get: (project) =>383 project === datekit384 ? Effect.succeed(api)385 : Effect.fail(new UnknownProject({ project })),386 })387 );388389/**390 * `api` whose `recordPush` of a push to canonical `main` records the push391 * event and opens a `StrayPush` decision, default revert, in one commit, so392 * the same event recorded twice opens one decision. That is the DO's part393 * 313 needs (its issue's Comments): W2's service runs the gate over such a394 * push and opens nothing, so this test stands in for it, writing the395 * decision as `packages/project/test/deciders.test.ts` does.396 */397const openingStrays = (api: ProjectApi) =>398 Effect.gen(function* () {399 const store = yield* ProjectStore;400401 const open = (report: PushReport) =>402 Effect.gen(function* () {403 const now = yield* DateTime.now;404 const { decisions } = yield* store.load();405 const number = String(decisions.length + 1).padStart(6, "0");406407 yield* store.commit({408 decisions: [409 {410 deciders: [scenario.initializer],411 default: "revert",412 evidence: [],413 expiresAt: DateTime.add(now, { days: 14 }),414 id: DecisionId.make(`dec-${number}`),415 openedAt: now,416 project: datekit,417 subject: DecisionSubject.cases.StrayPush.make({418 after: report.after,419 before: Option.getOrElse(report.before, () => ZeroSha),420 ref: RefNameText.make(report.ref),421 }),422 },423 ],424 pushEvents: [425 {426 after: report.after,427 at: now,428 eventId: report.eventId,429 ref: report.ref,430 repo: report.repo,431 ...Option.match(report.before, {432 onNone: () => ({}),433 onSome: (before) => ({ before }),434 }),435 },436 ],437 });438439 return [];440 });441442 return {443 ...api,444 recordPush: (report: PushReport) =>445 report.repo === canonicalRepo ? open(report) : api.recordPush(report),446 } satisfies ProjectApi;447 });448449/** datekit's service over its seeded store, and `Projects` holding it, at noon. */450const world = Effect.gen(function* () {451 yield* advanceTo("2026-10-07T12:00:00Z");452 yield* seeded;453454 const api = yield* openingStrays(yield* projectService(datekit));455456 return { api, projects: projectsOf(api), store: yield* ProjectStore };457}).pipe(Effect.provide(ports));458459/** OnPush's program over `event`, with a fresh record of steps. */460const onPush = (event: OnPushEvent, projects: Layer.Layer<Projects>) =>461 Effect.flatMap(memoSteps(), (steps) =>462 runOnPush(event).pipe(Effect.provide([steps, projects]))463 );464465/** `Projects` holding `api`, and the id of every push event the DO is told of. */466const telling = (api: ProjectApi) =>467 Effect.map(Ref.make<readonly string[]>([]), (told) => ({468 projects: projectsOf({469 ...api,470 recordPush: (report) =>471 Effect.andThen(472 Ref.update(told, (ids) => [...ids, report.eventId]),473 api.recordPush(report)474 ),475 }),476 told,477 }));478479/**480 * A Workflow engine's steps in memory, as the engine keeps them: each runs481 * once, and what it ended with, its JSON or its failure, is kept by name and482 * handed to a replay without running it again.483 */484const engineSteps = () => {485 const recorded = new Map<string, Promise<Schema.Json>>();486487 const steps: WorkflowSteps = {488 do: (name, _config, body) => {489 const kept = recorded.get(name) ?? body();490491 recorded.set(name, kept);492493 return kept;494 },495 };496497 return { recorded, steps };498};499500describe(runOnPush, () => {501 it.effect(502 "ignores main moved to the landing the platform made, and its bookkeeping refs",503 () =>504 Effect.gen(function* () {505 const { api, projects } = yield* world;506507 const verdicts = yield* Effect.forEach(508 [509 pushed({ after: scenario.landed, repo: "datekit" }),510 pushed({511 after: scenario.landed,512 ref: `${Brand.refsPrefix}landed`,513 repo: "datekit",514 }),515 pushed({516 after: strayHead,517 ref: `refs/notes/${Brand.slug}`,518 repo: "datekit",519 }),520 ],521 (event) => onPush(event, projects)522 );523524 expect(verdicts).toStrictEqual([525 ignored("own landing"),526 ignored("bookkeeping ref"),527 ignored("bookkeeping ref"),528 ]);529 expect((yield* api.today(alice)).decisions).toStrictEqual([]);530 })531 );532533 it.effect(534 "ignores a claim fork's push the gateway recorded, and records one it never saw as the claimant's",535 () =>536 Effect.gen(function* () {537 const { api, projects } = yield* world;538 const fork = "datekit--parse-iso--bob";539 const elsewhere = sha("datekit:elsewhere");540541 /** When bob's claim last heard a push, as he sees it. */542 const lastPush = Effect.map(api.status(bob), ({ claims }) =>543 claims.map(({ lastPushAt }) =>544 Option.map(Option.fromUndefinedOr(lastPushAt), DateTime.formatIso)545 )546 );547548 yield* api.claim(bob, parseIso);549550 // The gateway forwarded bob's push and recorded it.551 yield* advanceTo("2026-10-07T13:00:00Z");552 yield* api.recordPush({553 after: answerHead,554 before: Option.none(),555 eventId: `push-${answerHead}`,556 pusher: bob,557 ref: "refs/heads/main",558 repo: RepoName.make(fork),559 });560561 yield* advanceTo("2026-10-07T13:30:00Z");562563 const seen = yield* onPush(564 pushed({ after: answerHead, repo: fork }),565 projects566 );567568 const afterSeen = yield* lastPush;569570 // A commit that reached the fork without passing the gateway.571 yield* advanceTo("2026-10-07T14:00:00Z");572573 const unseen = yield* onPush(574 pushed({ after: elsewhere, before: answerHead, repo: fork }),575 projects576 );577578 expect([seen, unseen]).toStrictEqual([579 ignored("seen"),580 PushVerdict.cases.ForkPush.make({581 ask: parseIso,582 head: elsewhere,583 project: datekit,584 }),585 ]);586 expect([afterSeen, yield* lastPush]).toStrictEqual([587 [Option.some("2026-10-07T13:00:00.000Z")],588 [Option.some("2026-10-07T14:00:00.000Z")],589 ]);590 expect((yield* api.today(alice)).decisions).toStrictEqual([]);591 })592 );593594 it.effect(595 "opens a StrayPush decision on Today, revert by default, when main moved without a landing",596 () =>597 Effect.gen(function* () {598 const { api, projects } = yield* world;599600 const verdict = yield* onPush(601 pushed({602 after: strayHead,603 before: scenario.landed,604 repo: "datekit",605 }),606 projects607 );608609 const { decisions } = yield* api.today(alice);610611 expect(verdict).toStrictEqual(612 PushVerdict.cases.Stray.make({613 after: strayHead,614 before: scenario.landed,615 project: datekit,616 ref: mainText,617 })618 );619 expect(620 decisions.map((decision) => ({621 default: decision.default,622 subject: decision.subject,623 }))624 ).toStrictEqual([625 {626 default: "revert",627 subject: DecisionSubject.cases.StrayPush.make({628 after: strayHead,629 before: scenario.landed,630 ref: mainText,631 }),632 },633 ]);634 })635 );636637 it.effect(638 "opens one decision for one event, replayed over one record of steps or recorded twice",639 () =>640 Effect.gen(function* () {641 const { api } = yield* world;642 const { projects, told } = yield* telling(api);643644 const stray = pushed({645 after: strayHead,646 before: scenario.landed,647 id: "2027e2b8-96df-4364-a992-3be1b702d7f4",648 repo: "datekit",649 });650651 const steps = yield* memoSteps();652653 const replayed = runOnPush(stray).pipe(654 Effect.provide([steps, projects])655 );656657 // The same instance replayed, then the same event in a second instance.658 const verdicts = [659 yield* replayed,660 yield* replayed,661 yield* onPush(stray, projects),662 ];663664 const { decisions } = yield* api.today(alice);665666 expect(verdicts.map(({ _tag }) => _tag)).toStrictEqual([667 "Stray",668 "Stray",669 "Stray",670 ]);671 expect(yield* Ref.get(told)).toStrictEqual([stray.id, stray.id]);672 expect(decisions.map(({ subject }) => subject)).toStrictEqual([673 DecisionSubject.cases.StrayPush.make({674 after: strayHead,675 before: scenario.landed,676 ref: mainText,677 }),678 ]);679 })680 );681682 it.effect(683 "settles a stray main as a recorded value, so a run the engine replays after keeping the grace's failure still opens one decision",684 () =>685 Effect.gen(function* () {686 const { api } = yield* world;687 const { projects, told } = yield* telling(api);688 const engine = engineSteps();689690 const stray = pushed({691 after: strayHead,692 before: scenario.landed,693 repo: "datekit",694 });695696 // The instance's run, then the same run replayed by the engine.697 const run = runOnPush(stray).pipe(698 Effect.provide([workflowSteps(engine.steps), projects]),699 Effect.catchDefect(() => Effect.succeed("died"))700 );701702 const verdicts = [yield* run, yield* run];703 const { decisions } = yield* api.today(alice);704705 const verdict = PushVerdict.cases.Stray.make({706 after: strayHead,707 before: scenario.landed,708 project: datekit,709 ref: mainText,710 });711712 expect({713 decisions: decisions.map(({ subject }) => subject._tag),714 steps: [...engine.recorded.keys()],715 told: yield* Ref.get(told),716 verdicts,717 }).toStrictEqual({718 decisions: ["StrayPush"],719 steps: ["classify", "settle", "record"],720 told: [stray.id],721 verdicts: [verdict, verdict],722 });723 })724 );725726 it.effect(727 "asks again before calling main stray, so a landing the DO records a moment late is its own",728 () =>729 Effect.gen(function* () {730 const { api, store } = yield* world;731 const asked = yield* Ref.make(0);732733 // The platform pushed main; its DO records the landing just after the first ask.734 const late = Projects.of({735 create: (project) => Effect.fail(new ProjectExists({ project })),736 get: () =>737 Effect.succeed({738 ...api,739 landing: (caller, at) =>740 Effect.flatMap(741 Ref.getAndUpdate(asked, (n) => n + 1),742 (n) =>743 n === 0744 ? Effect.andThen(745 store.commit({746 landings: [747 {748 ...theLanding,749 parent: scenario.landed,750 sha: LandedSha.make(strayHead),751 },752 ],753 }),754 Effect.fail(new UnknownCommit({ sha: at }))755 )756 : api.landing(caller, at)757 ),758 }),759 });760761 const verdict = yield* onPush(762 pushed({763 after: strayHead,764 before: scenario.landed,765 repo: "datekit",766 }),767 Layer.succeed(Projects, late)768 );769770 expect([verdict, yield* Ref.get(asked)]).toStrictEqual([771 ignored("own landing"),772 2,773 ]);774 expect((yield* api.today(alice)).decisions).toStrictEqual([]);775 })776 );777778 it.effect(779 "calls a deleted main stray at once: no landing is in flight to wait for",780 () =>781 Effect.gen(function* () {782 const { api, projects } = yield* world;783 const engine = engineSteps();784785 const verdict = yield* runOnPush(786 pushed({ after: ZeroSha, before: scenario.landed, repo: "datekit" })787 ).pipe(Effect.provide([workflowSteps(engine.steps), projects]));788789 const { decisions } = yield* api.today(alice);790791 expect({792 decisions: decisions.map(({ subject }) => subject),793 steps: [...engine.recorded.keys()],794 verdict,795 }).toStrictEqual({796 decisions: [797 DecisionSubject.cases.StrayPush.make({798 after: ZeroSha,799 before: scenario.landed,800 ref: mainText,801 }),802 ],803 steps: ["classify", "record"],804 verdict: PushVerdict.cases.Stray.make({805 after: ZeroSha,806 before: scenario.landed,807 project: datekit,808 ref: mainText,809 }),810 });811 })812 );813814 it.effect("ignores a repo whose name no project of the platform's has", () =>815 Effect.gen(function* () {816 const { projects } = yield* world;817818 const verdicts = yield* Effect.forEach(819 ["Not.A.Project", "datekit--parse-iso", "elsewhere"],820 (repo) => onPush(pushed({ after: strayHead, repo }), projects)821 );822823 expect(verdicts).toStrictEqual([824 ignored("unknown repo"),825 ignored("unknown repo"),826 ignored("unknown repo"),827 ]);828 })829 );830});831832/** The delivered event as the engine hands it to an instance: its params. */833const sent = Schema.encodeSync(OnPushEvent)(delivered);834835describe(runInstance, () => {836 it.effect("decodes its params before it reads the env", () =>837 Effect.gen(function* () {838 // A ref name where a commit id belongs, and an env missing its stage.839 const failure = yield* runInstance(840 without(fakeEnv(), "STAGE"),841 { ...sent, payload: { ...sent.payload, after: "HEAD" } },842 engineSteps().steps843 ).pipe(Effect.flip);844845 expect(failure._tag).toBe("SchemaError");846 })847 );848849 it.effect(850 "answers a repo no project has without touching a binding, and records its step as JSON",851 () =>852 Effect.gen(function* () {853 const engine = engineSteps();854855 const output = yield* runInstance(856 fakeEnv(),857 { ...sent, source: { ...sent.source, repoName: "Not.A.Project" } },858 engine.steps859 );860861 const expected = yield* Schema.encodeEffect(PushVerdict)(862 ignored("unknown repo")863 );864865 expect([866 output,867 yield* Effect.promise(868 () => engine.recorded.get("classify") ?? Promise.resolve(null)869 ),870 [...engine.recorded.keys()],871 ]).toStrictEqual([expected, expected, ["classify"]]);872 })873 );874});