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
Provenance
- Commit
24805b9- Tree
068db90- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
7026edb- Parent 2
6e3dffd
5 files changed+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+ */10+import { Brand } from "@repo/brand";11+import { notesRef } from "@repo/git/notes";12+import { RefNameText } from "@repo/protocol/domain/common";13+import { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";14+import { Schema } from "effect";15+16+import { RepoKind } from "../../repo-names.ts";17+import { isZero } from "./event.ts";18+import type { OnPushEvent } from "./event.ts";19+20+/** Why a push needs nothing from the platform. */21+export 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+]);35+36+export type IgnoredReason = typeof IgnoredReason.Type;37+38+/** What the platform does about one push event. */39+export 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+});55+56+export type PushVerdict = typeof PushVerdict.Type;57+58+/** What the project's Durable Object says about a push event, read before it is classified. */59+export 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+}67+68+/** The one canonical ref the platform alone moves. */69+export const mainRef = RefNameText.make("refs/heads/main");70+71+/**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+ */76+export const isBookkeeping = (ref: string): boolean =>77+ ref.startsWith(Brand.refsPrefix) || ref === notesRef;78+79+const ignored = (reason: IgnoredReason): PushVerdict =>80+ PushVerdict.cases.Ignored.make({ reason });81+82+/** What `event` means, given what the project's Durable Object said of it. */83+export const classifyPush = (84+ event: OnPushEvent,85+ facts: PushFacts86+): PushVerdict => {87+ const { after, before, ref } = event.payload;88+89+ return RepoKind.$match(facts.repo, {90+ Canonical: ({ project }) => {91+ if (isBookkeeping(ref)) {92+ return ignored("bookkeeping ref");93+ }94+95+ if (ref !== mainRef) {96+ return ignored("not main");97+ }98+99+ 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+ }112+113+ if (isZero(after)) {114+ return ignored("deleted ref");115+ }116+117+ 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758/** * What Artifacts sends the `OnPush` Workflow for every ref a push moved in * the public namespace: S1 #15's `cf.artifacts.repo.pushed` event, verbatim * (S1 change 7). The Workflow decodes its params with it before anything * else (principle 2); its `id` is the Workflow's instance id, so a * redelivered event cannot start a second run (S1 change 6). */import { CommitSha, RepoName } from "@repo/protocol/ids";import { Schema } from "effect";
/** A commit's author or committer, as git records one. */const GitIdentity = Schema.Struct({ email: Schema.String, name: Schema.String,});
/** One commit the push brought, as Artifacts lists it. */const PushedCommit = Schema.Struct({ author: GitIdentity, committer: GitIdentity, id: CommitSha, message: Schema.String, messageTruncated: Schema.Boolean, parents: Schema.Array(CommitSha), timestamp: Schema.DateTimeUtcFromString,});
export const OnPushEvent = Schema.Struct({ id: Schema.NonEmptyString, payload: Schema.Struct({ /** Where the ref points now: git's zero id when the push deleted it. */ after: CommitSha, /** Where the ref pointed before: git's zero id when the push created it. */ before: CommitSha, /** Empty for a ref moved to a commit the repo already held (S1 #13). */ commits: Schema.Array(PushedCommit), commitsTruncated: Schema.Boolean, /** The one ref this event is about: each ref a push moves fires its own (S1 #13). */ ref: Schema.NonEmptyString, totalCommitsCount: Schema.Int, }), source: Schema.Struct({ namespace: Schema.NonEmptyString, repoName: RepoName, }), type: Schema.Literal("cf.artifacts.repo.pushed"),});
export type OnPushEvent = typeof OnPushEvent.Type;
/** * git's all-zero id: the `before` of a ref a push created, the `after` of * one it deleted. It names no commit. */export const ZeroSha = CommitSha.make("0".repeat(40));
/** Whether `sha` is git's zero id, which stands for "no commit". */export const isZero = (sha: CommitSha): boolean => sha === ZeroSha;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+ */8+import { platformHandle } from "@repo/project/attention/effects";9+import type { ProjectApi } from "@repo/project/project";10+import { keptEvents } from "@repo/project/project-store";11+import { Projects } from "@repo/project/projects";12+import { ProjectEvent } from "@repo/protocol/domain/event";13+import type { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";14+import { Person } from "@repo/protocol/principal";15+import { Effect, Option } from "effect";16+17+import { RepoKind, repoKind } from "../../repo-names.ts";18+import { isBookkeeping, mainRef } from "./classify.ts";19+import type { PushFacts } from "./classify.ts";20+import { isZero } from "./event.ts";21+import type { OnPushEvent } from "./event.ts";22+23+/** The platform itself, reading a project's public record. */24+const platform = Person.make({ handle: platformHandle });25+26+/** The project a repo belongs to, when its name says. */27+const 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+ });34+35+/** `sha` as a landing the platform made on the project's `main`, or none. */36+const landedOf = (api: ProjectApi, sha: CommitSha) =>37+ Effect.map(Effect.isSuccess(api.landing(platform, sha)), (landed) =>38+ landed ? new Set([sha]) : new Set<CommitSha>()39+ );40+41+/**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+ */46+const 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+ );58+59+const nothing = (repo: RepoKind): PushFacts => ({60+ landed: new Set(),61+ repo,62+ seen: false,63+});64+65+/** The project and the API of the repo `event` is about, when the platform has that project. */66+export const projectFor = (event: OnPushEvent) =>67+ Effect.gen(function* () {68+ const kind = repoKind(event.source.repoName);69+ const project = projectOf(kind);70+71+ if (Option.isNone(project)) {72+ return Option.none();73+ }74+75+ const api = yield* Effect.option(76+ Projects.use((projects) => projects.get(project.value))77+ );78+79+ return Option.map(api, (found) => ({ api: found, kind }));80+ });81+82+/** What the project's Durable Object says about `event`. */83+export 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);89+90+ if (Option.isNone(found)) {91+ return nothing(RepoKind.Unknown());92+ }93+94+ const { api, kind } = found.value;95+ const moved = !isZero(after) && !isBookkeeping(ref);96+97+ 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
1234523456789101112131415161718910111213141516171819202122232425262728293031323334353637383940414243444546474821224950515253242526272829303132333435365455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615738158159160161162163164165166167168/** * The `OnPush` Workflow: Artifacts starts one for every pushed ref in the * public namespace (`triggers.events`, S1 #12), with the event's id as its * instance id. A stub until W3 313 builds it: it has no `run` yet, so an * instance fails at once. The class name is frozen. * The `OnPush` Workflow, the platform's backstop (spec §5 step 9): Artifacts * starts one for every ref a push moved in the public namespace * (`triggers.events`, S1 #12 and #13), with the event's id as the instance * id, so a redelivered event starts nothing (S1 change 6). Each run reads * what the project's Durable Object knows of the push, classifies it, and * records what needs recording through the DO: a claim-fork push the * gateway never saw keeps its claim alive, and canonical `main` moved * without a landing becomes a `StrayPush` decision whose default is revert * (CM §4). It reverts nothing itself. The class name is frozen. */import type { PushReport } from "@repo/project/project";import type { Projects } from "@repo/project/projects";import { Anonymous, Person } from "@repo/protocol/principal";import { WorkflowEntrypoint } from "cloudflare:workers";import type { WorkflowEvent, WorkflowStep } from "cloudflare:workers";import { Data, Effect, Layer, Option, Schema } from "effect";
/** A commit in a push event, as Artifacts sends it. */interface PushedCommit { readonly id: string; readonly message: string; readonly messageTruncated: boolean; readonly timestamp: string; readonly author: { readonly name: string; readonly email: string }; readonly committer: { readonly name: string; readonly email: string }; readonly parents: readonly string[];}import { decodeEnv } from "../platform.ts";import { workerPorts } from "../ports.ts";import { RepoKind } from "../repo-names.ts";import { classifyPush, PushVerdict } from "./on-push/classify.ts";import { isZero, OnPushEvent } from "./on-push/event.ts";import { factsOf, projectFor } from "./on-push/facts.ts";import { StepRunner, workflowSteps } from "./step.ts";import type { StepRetry, WorkflowSteps } from "./step.ts";
/** What the gate said of a recorded push, by tag: for whoever reads the run. */const Recorded = Schema.Array(Schema.String);
/** `event` as the project's DO records a push: under the event's own id. */const reportOf = ( event: OnPushEvent, pusher: PushReport["pusher"]): PushReport => { const { after, before, ref } = event.payload;
return { after, before: isZero(before) ? Option.none() : Option.some(before), eventId: event.id, pusher, ref, repo: event.source.repoName, };};
/** * The `cf.artifacts.repo.pushed` event as S1 #15 recorded it, typed loosely * until 313 decodes it with a schema. * `event` recorded by its project's DO, under the event's id, so the DO acts * on it once: a claim fork's push as its claimant's, which keeps the claim * alive; canonical `main`'s from nobody the platform knows, which opens the * `StrayPush` decision. */export interface OnPushEventEncoded { readonly id: string; readonly type: "cf.artifacts.repo.pushed"; readonly source: { readonly namespace: string; readonly repoName: string }; readonly payload: { readonly ref: string; readonly before: string; readonly after: string; readonly commits: readonly PushedCommit[]; readonly totalCommitsCount: number; readonly commitsTruncated: boolean; };}const recordOf = (event: OnPushEvent) => Effect.gen(function* () { const found = yield* projectFor(event);
if (Option.isNone(found)) { return []; }
const { api, kind } = found.value;
const pusher = RepoKind.$is("ClaimFork")(kind) ? Person.make({ handle: kind.handle }) : Anonymous.make({});
const refusals = yield* api.recordPush(reportOf(event, pusher));
return refusals.map(({ _tag }) => _tag); });
/** `main` moved to a commit no landing made, as far as the DO knew when it was asked. */class LooksStray extends Data.TaggedError("LooksStray") {}
/** * How long a `main` that looks stray is asked about again before it is * called stray. The platform pushes `main` before its DO records the * landing (S1 change 1), and the event can arrive in between (S1 #14): a * stray verdict on the platform's own landing would ask the deciders to * revert it. Four more reads, 15 s to 2 min apart: about four minutes. */const strayGrace: StepRetry = { backoff: "exponential", delayMs: 15_000, limit: 4,};
/** What `event` means, from what the DO says of it now. */const verdictOf = (event: OnPushEvent) => Effect.map(factsOf(event), (facts) => classifyPush(event, facts));
/** * What `event` means; a `main` moved to a commit that may yet be recorded * as a landing fails, so the step asks again. A deleted `main` is no * landing in flight: it is stray at once. */const classified = (event: OnPushEvent) => Effect.flatMap(verdictOf(event), (verdict) => PushVerdict.guards.Stray(verdict) && !isZero(verdict.after) ? Effect.fail(new LooksStray()) : Effect.succeed(verdict) );
/** * What `event` means, then what is recorded of it, each a step run once per * instance (principle 8). `classify` asks again during `strayGrace` while * `main` looks stray. A `main` still stray after it is the step's last * failure, which the engine keeps and throws again, unrun, in every replay * (where the step's own failure is gone, so it arrives as a defect); * either way `settle` asks once more and records the verdict as a value, * which every replay reads back. `record` tells the DO of a push it must * hear of. */export const runOnPush = ( event: OnPushEvent): Effect.Effect<PushVerdict, never, StepRunner | Projects> => Effect.gen(function* () { const { step } = yield* StepRunner;
const verdict = yield* step( "classify", PushVerdict, classified(event), strayGrace ).pipe( Effect.catchCause(() => step("settle", PushVerdict, verdictOf(event))) );
if (!PushVerdict.guards.Ignored(verdict)) { yield* step("record", Recorded, recordOf(event)); }
return verdict; });
/** * One instance's run: its params decoded before anything else (principle * 2), then the env, then the program over the stage's ports and the * engine's own steps. It answers the verdict as JSON, the instance's output. */export const runInstance = ( env: Env, params: typeof OnPushEvent.Encoded, steps: WorkflowSteps) => Effect.gen(function* () { const event = yield* Schema.decodeEffect(OnPushEvent)(params); const config = yield* decodeEnv(env);
const verdict = yield* runOnPush(event).pipe( Effect.provide(Layer.merge(workerPorts(config), workflowSteps(steps))) );
return yield* Effect.orDie(Schema.encodeEffect(PushVerdict)(verdict)); });
export class OnPush extends WorkflowEntrypoint<Env, OnPushEventEncoded> {}export class OnPush extends WorkflowEntrypoint< Env, typeof OnPushEvent.Encoded> { override run( event: Readonly<WorkflowEvent<typeof OnPushEvent.Encoded>>, step: WorkflowStep ): Promise<typeof PushVerdict.Encoded> { return Effect.runPromise(runInstance(this.env, event.payload, step)); }}added:apps/platform/test/workflows/on-push.test.ts+874 added
1+import { describe, expect, it } from "@effect/vitest";2+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3+import { Brand } from "@repo/brand";4+import { CheckRunner } from "@repo/checks/check-runner";5+import { AlarmsMemory } from "@repo/project/alarms/memory";6+import { AnswerRuns } from "@repo/project/answer-runs";7+import { Lander } from "@repo/project/lander";8+import { projectService } from "@repo/project/project";9+import type { ProjectApi, PushReport } from "@repo/project/project";10+import { ProjectStore } from "@repo/project/project-store";11+import { ProjectStoreMemory } from "@repo/project/project-store/memory";12+import { ProjectionMemory } from "@repo/project/projection/memory";13+import { Projects } from "@repo/project/projects";14+import { RefNameText } from "@repo/protocol/domain/common";15+import { DecisionSubject } from "@repo/protocol/domain/decision";16+import type { LandingView } from "@repo/protocol/domain/landing";17+import { Policy } from "@repo/protocol/domain/policy";18+import {19+ AskId,20+ CommitSha,21+ DecisionId,22+ Handle,23+ LandedSha,24+ ProjectName,25+ RepoName,26+} from "@repo/protocol/ids";27+import { Person } from "@repo/protocol/principal";28+import {29+ ProjectExists,30+ UnknownCommit,31+ UnknownProject,32+} from "@repo/protocol/refusal";33+import { RulesEvaluator } from "@repo/rules/rules-evaluator";34+import { advanceTo } from "@repo/testkit/clock";35+import { aProject, sha, withAsk, withVouches } from "@repo/testkit/scenarios";36+import { untouchable } from "@repo/testkit/untouchable";37+import { DateTime, Effect, Layer, Option, Ref, Schema } from "effect";38+39+import { RepoKind } from "../../src/repo-names.ts";40+import { runInstance, runOnPush } from "../../src/workflows/on-push.ts";41+import {42+ classifyPush,43+ PushVerdict,44+} from "../../src/workflows/on-push/classify.ts";45+import type {46+ IgnoredReason,47+ PushFacts,48+} from "../../src/workflows/on-push/classify.ts";49+import {50+ isZero,51+ OnPushEvent,52+ ZeroSha,53+} from "../../src/workflows/on-push/event.ts";54+import { memoSteps, workflowSteps } from "../../src/workflows/step.ts";55+import type { WorkflowSteps } from "../../src/workflows/step.ts";56+import { fakeEnv, without } from "../fake-env.ts";57+58+/**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+ */63+const 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}}';65+66+/**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+ */71+const 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}}';73+74+const fromLine = Schema.decodeUnknownEffect(Schema.fromJsonString(OnPushEvent));75+76+describe(OnPushEvent, () => {77+ it.effect("decodes the push event Artifacts delivered in S1", () =>78+ Effect.gen(function* () {79+ const event = yield* fromLine(deliveredLine);80+81+ 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+ );98+99+ 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+});109+110+/** The delivered event, decoded: what every other event here is made from. */111+const delivered = Schema.decodeSync(Schema.fromJsonString(OnPushEvent))(112+ deliveredLine113+);114+115+/** A push event like the delivered one, for `repo`'s `ref` moving to `after`. */116+const 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";124+125+ 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+};137+138+const datekit = ProjectName.make("datekit");139+140+const parseIso = AskId.make("parse-iso");141+142+const mainText = RefNameText.make("refs/heads/main");143+144+const landedSha = sha("datekit:landed");145+146+const strayHead = sha("datekit:stray");147+148+const answerHead = sha("datekit:answer");149+150+const canonical = RepoKind.Canonical({ project: datekit });151+152+const canonicalRepo = RepoName.make(datekit);153+154+const bobsFork = RepoKind.ClaimFork({155+ ask: parseIso,156+ handle: Handle.make("bob"),157+ project: datekit,158+});159+160+/** What the DO said: nothing landed, nothing seen, unless a row says so. */161+const facts = (repo: RepoKind, more: Partial<PushFacts> = {}): PushFacts => ({162+ landed: new Set(),163+ repo,164+ seen: false,165+ ...more,166+});167+168+const ignored = (reason: IgnoredReason) =>169+ PushVerdict.cases.Ignored.make({ reason });170+171+const 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+];296+297+describe(classifyPush, () => {298+ it.each(table)("$title", ({ event, facts: said, verdict }) => {299+ expect(classifyPush(event, said)).toStrictEqual(verdict);300+ });301+});302+303+/**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+ */308+const scenario = aProject({ people: ["bob"] }).pipe(309+ withVouches(["bob"]),310+ withAsk({ id: "parse-iso", territory: "packages/parser" })311+);312+313+const alice = Person.make({ handle: scenario.initializer });314+315+const bob = Person.make({ handle: Handle.make("bob") });316+317+/** The project's one landing: its landed commit. */318+const 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+};327+328+/**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+ */333+const 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+);352+353+/** datekit live at its landed commit, with its one landing and its asks, as its store holds them. */354+const seeded = Effect.gen(function* () {355+ const store = yield* ProjectStore;356+357+ const policy = yield* Schema.encodeEffect(Schema.toCodecJson(Policy))(358+ scenario.policy359+ );360+361+ 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+});375+376+/** `Projects` in memory, holding datekit's service and no other project. */377+const 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+ );388+389+/**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+ */397+const openingStrays = (api: ProjectApi) =>398+ Effect.gen(function* () {399+ const store = yield* ProjectStore;400+401+ 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");406+407+ 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+ });438+439+ return [];440+ });441+442+ return {443+ ...api,444+ recordPush: (report: PushReport) =>445+ report.repo === canonicalRepo ? open(report) : api.recordPush(report),446+ } satisfies ProjectApi;447+ });448+449+/** datekit's service over its seeded store, and `Projects` holding it, at noon. */450+const world = Effect.gen(function* () {451+ yield* advanceTo("2026-10-07T12:00:00Z");452+ yield* seeded;453+454+ const api = yield* openingStrays(yield* projectService(datekit));455+456+ return { api, projects: projectsOf(api), store: yield* ProjectStore };457+}).pipe(Effect.provide(ports));458+459+/** OnPush's program over `event`, with a fresh record of steps. */460+const onPush = (event: OnPushEvent, projects: Layer.Layer<Projects>) =>461+ Effect.flatMap(memoSteps(), (steps) =>462+ runOnPush(event).pipe(Effect.provide([steps, projects]))463+ );464+465+/** `Projects` holding `api`, and the id of every push event the DO is told of. */466+const 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+ }));478+479+/**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+ */484+const engineSteps = () => {485+ const recorded = new Map<string, Promise<Schema.Json>>();486+487+ const steps: WorkflowSteps = {488+ do: (name, _config, body) => {489+ const kept = recorded.get(name) ?? body();490+491+ recorded.set(name, kept);492+493+ return kept;494+ },495+ };496+497+ return { recorded, steps };498+};499+500+describe(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;506+507+ 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+ );523+524+ 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+ );532+533+ 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");540+541+ /** 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+ );547+548+ yield* api.claim(bob, parseIso);549+550+ // 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+ });560+561+ yield* advanceTo("2026-10-07T13:30:00Z");562+563+ const seen = yield* onPush(564+ pushed({ after: answerHead, repo: fork }),565+ projects566+ );567+568+ const afterSeen = yield* lastPush;569+570+ // A commit that reached the fork without passing the gateway.571+ yield* advanceTo("2026-10-07T14:00:00Z");572+573+ const unseen = yield* onPush(574+ pushed({ after: elsewhere, before: answerHead, repo: fork }),575+ projects576+ );577+578+ 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+ );593+594+ 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;599+600+ const verdict = yield* onPush(601+ pushed({602+ after: strayHead,603+ before: scenario.landed,604+ repo: "datekit",605+ }),606+ projects607+ );608+609+ const { decisions } = yield* api.today(alice);610+611+ 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+ );636+637+ 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);643+644+ const stray = pushed({645+ after: strayHead,646+ before: scenario.landed,647+ id: "2027e2b8-96df-4364-a992-3be1b702d7f4",648+ repo: "datekit",649+ });650+651+ const steps = yield* memoSteps();652+653+ const replayed = runOnPush(stray).pipe(654+ Effect.provide([steps, projects])655+ );656+657+ // 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+ ];663+664+ const { decisions } = yield* api.today(alice);665+666+ 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+ );681+682+ 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();689+690+ const stray = pushed({691+ after: strayHead,692+ before: scenario.landed,693+ repo: "datekit",694+ });695+696+ // 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+ );701+702+ const verdicts = [yield* run, yield* run];703+ const { decisions } = yield* api.today(alice);704+705+ const verdict = PushVerdict.cases.Stray.make({706+ after: strayHead,707+ before: scenario.landed,708+ project: datekit,709+ ref: mainText,710+ });711+712+ 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+ );725+726+ 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);732+733+ // 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+ });760+761+ const verdict = yield* onPush(762+ pushed({763+ after: strayHead,764+ before: scenario.landed,765+ repo: "datekit",766+ }),767+ Layer.succeed(Projects, late)768+ );769+770+ expect([verdict, yield* Ref.get(asked)]).toStrictEqual([771+ ignored("own landing"),772+ 2,773+ ]);774+ expect((yield* api.today(alice)).decisions).toStrictEqual([]);775+ })776+ );777+778+ 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();784+785+ const verdict = yield* runOnPush(786+ pushed({ after: ZeroSha, before: scenario.landed, repo: "datekit" })787+ ).pipe(Effect.provide([workflowSteps(engine.steps), projects]));788+789+ const { decisions } = yield* api.today(alice);790+791+ 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+ );813+814+ it.effect("ignores a repo whose name no project of the platform's has", () =>815+ Effect.gen(function* () {816+ const { projects } = yield* world;817+818+ const verdicts = yield* Effect.forEach(819+ ["Not.A.Project", "datekit--parse-iso", "elsewhere"],820+ (repo) => onPush(pushed({ after: strayHead, repo }), projects)821+ );822+823+ expect(verdicts).toStrictEqual([824+ ignored("unknown repo"),825+ ignored("unknown repo"),826+ ignored("unknown repo"),827+ ]);828+ })829+ );830+});831+832+/** The delivered event as the engine hands it to an instance: its params. */833+const sent = Schema.encodeSync(OnPushEvent)(delivered);834+835+describe(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);844+845+ expect(failure._tag).toBe("SchemaError");846+ })847+ );848+849+ 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();854+855+ const output = yield* runInstance(856+ fakeEnv(),857+ { ...sent, source: { ...sent.source, repoName: "Not.A.Project" } },858+ engine.steps859+ );860+861+ const expected = yield* Schema.encodeEffect(PushVerdict)(862+ ignored("unknown repo")863+ );864+865+ 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+});