Merge perf/gate-path into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents c007606, 2f2c840 · Browse files · 9 files·+694 added−37 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+694 added−37 removed
- tests:+462 added−3 removed
- other:+232 added−34 removed
Provenance
- Commit
3704c58- Tree
5fff114- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
c007606- Parent 2
2f2c840
9 files changed+694 added−37 removed
modified:apps/platform/src/workflows/answer/lanes.ts+48 added-22 removed
305 unmodified lines306 readonly counts: readonly MeasuredCount[];307 readonly uncounted: Option.Option<RatchetName>;308 }309 310+/** What the lane running a command printed, or nothing. */311+const printedBy =312+ (lanes: readonly CheckLane[], ran: CheckRun) => (command: string) =>313+ Option.getOrElse(314+ Option.flatMap(315+ Option.fromUndefinedOr(lanes.find((lane) => lane.command === command)),316+ ({ lane }) => outputOf(ran, lane)317+ ),318+ () => ""319+ );320+321+/** The ratchets' counts, read from the lanes a run printed. */310-const countRatchets = <E, R>(322+const countRatchets = (323 run: AnswerRun,312- job: (lanes: readonly CheckLane[]) => Effect.Effect<CheckRun, E, R>313-): Effect.Effect<Counted, E, R> =>324+ lanes: readonly CheckLane[],325+ ran: CheckRun326+): Effect.Effect<Counted> =>327 Effect.gen(function* () {328 const specs = run.counts?.ratchets ?? [];329 330 if (!Array.isReadonlyArrayNonEmpty(specs)) {331 return { counts: [], uncounted: Option.none() };332 }333 321- const lanes = countLanes(specs);334+ const printed = printedBy(lanes, ran);335 323- const ran = yield* job(lanes);324-325- const printed = (command: string) =>326- Option.getOrElse(327- Option.flatMap(328- Option.fromUndefinedOr(329- lanes.find((lane) => lane.command === command)330- ),331- ({ lane }) => outputOf(ran, lane)332- ),333- () => ""334- );335-336 const counts = yield* Effect.forEach(specs, (spec) =>337 measure(338 spec,339 (command) => Effect.succeed({ code: 0, stdout: printed(command) }),6 unmodified lines346 onSuccess: (all) => ({ counts: all.flat(), uncounted: Option.none() }),347 });348 });349 350+/** The ratchets' lanes, counted in the cheap stage. */351+const countingLanesOf = (run: AnswerRun, stage: Stage): readonly CheckLane[] =>352+ stage === "cheap" && run.counts !== undefined353+ ? countLanes(run.counts.ratchets)354+ : [];355+356+const namesApart = (357+ lanes: readonly CheckLane[],358+ counting: readonly CheckLane[]359+) => counting.every((count) => lanes.every(({ lane }) => lane !== count.lane));360+361 const countFields = (counted: Counted): Pick<Ran, "counts" | "uncounted"> =>362 Option.match(counted.uncounted, {363 onNone: () => ({ counts: counted.counts }),364 onSome: (uncounted) => ({ counts: counted.counts, uncounted }),23 unmodified lines388 const remerges = LandingState.guards.Checking(run.state)389 ? run.state.remerges390 : 0;391 381- const counting = stage === "cheap" && run.counts !== undefined;392+ const counting = countingLanesOf(run, stage);393 383- if (!Array.isReadonlyArrayNonEmpty(lanes) && !counting) {394+ if (395+ !Array.isReadonlyArrayNonEmpty(lanes) &&396+ !Array.isReadonlyArrayNonEmpty(counting)397+ ) {398 return StageRun.cases.Ran.make({ checked, lanes: [] });399 }400 401 const block = yield* runBlockOf(checked);9 unmodified lines411 run: block,412 })413 .pipe(Effect.flatMap((ran) => countedAskLane(run, ran)));414 401- const counts = counting402- ? countFields(yield* countRatchets(run, job))415+ // The ratchets are counted in the stage's own job, one container for416+ // both, unless a ratchet is named as a lane is: then it runs apart.417+ const together =418+ !Array.isReadonlyArrayNonEmpty(lanes) || namesApart(lanes, counting);419+420+ const firstRun = yield* job(together ? [...lanes, ...counting] : lanes);421+422+ const counts = Array.isReadonlyArrayNonEmpty(counting)423+ ? countFields(424+ yield* countRatchets(425+ run,426+ counting,427+ together ? firstRun : yield* job(counting)428+ )429+ )430 : {};431 432 if (!Array.isReadonlyArrayNonEmpty(lanes)) {433 return StageRun.cases.Ran.make({2 unmodified lines436 ...counts,437 });438 }439 413- const firstRun = yield* job(lanes);440 const first = byLane(firstRun);441 442 const troubled = lanes.filter(({ lane }) =>443 isTrouble(first.results.get(lane)?.result ?? "blocked")131 unmodified linesmodified:apps/platform/src/workflows/answer/program.ts+13 added-8 removed
243 unmodified lines244 if (!StageRun.guards.Ran(ran)) {245 return { ran, refusals: [] };246 }247 248+ // Each lane's comparison is its own container job and its own step, so249+ // they run at once: a step's name is its lane's, replayed or not.250+ const onMain = yield* Effect.forEach(251+ toCompareOnMain(ran),248- const onMain = yield* Effect.forEach(toCompareOnMain(ran), (lane) =>249- Effect.map(250- step(251- `main:${ran.checked.main}:${lane.lane}`,252- LaneOutcome,253- laneOnMain(ran.checked, lane)252+ (lane) =>253+ Effect.map(254+ step(255+ `main:${ran.checked.main}:${lane.lane}`,256+ LaneOutcome,257+ laneOnMain(ran.checked, lane)258+ ),259+ (outcome) => [lane.lane, outcome] as const260 ),255- (outcome) => [lane.lane, outcome] as const256- )261+ { concurrency: "unbounded" }262 );263 264 return {265 ran,399 unmodified linesmodified:apps/platform/test/workflows/answer.fixtures.ts+37 added-2 removed
1 import { RefName, RepoHost } from "@repo/artifacts/repo-host";2 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";4 import { CheckAt, CheckRunner, shaOf } from "@repo/checks/check-runner";5-import type { CheckJob, LaneEvidence } from "@repo/checks/check-runner";5+import type {6+ CheckJob,7+ LaneEvidence,8+ LaneOutput,9+} from "@repo/checks/check-runner";10 import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";11 import { AlarmsMemory } from "@repo/project/alarms/memory";12 import { AnswerRuns } from "@repo/project/answer-runs";13 import type { AnswerReport } from "@repo/project/answer-runs";134 unmodified lines148 lane: LaneName,149 runs: readonly ScriptedRun[]150 ) => Effect.Effect<void>;151 readonly jobs: Effect.Effect<readonly CheckJob[]>;152+ /** What a lane prints on its stdout at a tree, for a ratchet's count. */153+ readonly print: (154+ at: CheckAt,155+ lane: LaneName,156+ stdout: string157+ ) => Effect.Effect<void>;158 }159 >()("test/Checker") {}160 161 const keyOf = (at: CheckAt, lane: LaneName) => `${shaOf(at)}:${lane}`;5 unmodified lines167 >(new Map());168 169 const served = yield* Ref.make<ReadonlyMap<string, number>>(new Map());170 const jobs = yield* Ref.make<readonly CheckJob[]>([]);171+ const printed = yield* Ref.make<ReadonlyMap<string, string>>(new Map());172 173 const next = (174 key: string,175 runs: Array.NonEmptyReadonlyArray<ScriptedRun>49 unmodified lines225 ? [{ lane: lane.lane }]226 : [{ lane: lane.lane, signature: one.signature }];227 });228 218- return { durationMs: lanes.length, evidence, heldBack: [], lanes };229+ const outputs = yield* Effect.map(Ref.get(printed), (texts) =>230+ ran.flatMap(({ lane }): LaneOutput[] =>231+ lane.output === "stdout"232+ ? [233+ {234+ lane: lane.lane,235+ stdout: texts.get(keyOf(job.at, lane.lane)) ?? "",236+ },237+ ]238+ : []239+ )240+ );241+242+ const result = {243+ durationMs: lanes.length,244+ evidence,245+ heldBack: [],246+ lanes,247+ };248+249+ return outputs.length === 0 ? result : { ...result, outputs };250 });251 252 return Context.make(CheckRunner, { run }).pipe(253 Context.add(Checker, {254 jobs: Ref.get(jobs),255+ print: (at, lane, stdout) =>256+ Ref.update(printed, (texts) =>257+ new Map(texts).set(keyOf(at, lane), stdout)258+ ),259 script: (at, lane, runs) =>260 Ref.update(scripts, (known) =>261 new Map(known).set(keyOf(at, lane), runs)262 ),347 unmodified linesmodified:apps/platform/test/workflows/answer.test.ts+50 added-1 removed
13 unmodified lines14 import type { Lander } from "@repo/project/lander";15 import { LanderJob } from "@repo/project/lander/memory";16 import { Projects } from "@repo/project/projects";17 import { Verdict } from "@repo/protocol/domain/answer";18+import { RatchetMeasure } from "@repo/protocol/domain/check";19+import { Command, JsonPath } from "@repo/protocol/domain/common";20 import { ProjectEvent } from "@repo/protocol/domain/event";21 import { Outcome } from "@repo/protocol/domain/outcome";22+import type { Policy } from "@repo/protocol/domain/policy";20-import { keyOf, LaneName, RequestId } from "@repo/protocol/ids";23+import { keyOf, LaneName, RatchetName, RequestId } from "@repo/protocol/ids";24 import type { CommitSha, LandedSha } from "@repo/protocol/ids";25 import {26 ChecksFailed,27 Flake,136 unmodified lines164 });165 166 const landedAt = (sha: LandedSha) => Outcome.cases.Landed.make({ sha });167 168+const sized = RatchetName.make("bundle-bytes");169+170+const sizedLane = LaneName.make(sized);171+172+/** The project's policy with one ratchet, read as a metric off a command's JSON. */173+const withRatchet: Policy = {174+ ...policy,175+ ratchets: [176+ {177+ measure: RatchetMeasure.cases.Metric.make({178+ command: Command.make("bun run size"),179+ path: JsonPath.make("$.bytes"),180+ }),181+ name: sized,182+ },183+ ],184+};185+186 const cleanAnswer = Effect.tap(admitted(), (answer) => allGreen(answer.merged));187 188 const withoutMessage = Layer.effect(189 Projects,238 unmodified lines428 }).pipe(Effect.provide(world))429 );430 431 it.effect(432+ "3. the cheap stage counts the policy's ratchets in its own job, one container for the lanes and the counts",433+ () =>434+ Effect.gen(function* () {435+ const answer = yield* admitted();436+437+ yield* allGreen(answer.merged);438+ yield* Checker.use((script) =>439+ Effect.andThen(440+ script.script(answer.merged, sizedLane, [{ result: "passed" }]),441+ script.print(answer.merged, sizedLane, '{ "bytes": 0 }')442+ )443+ );444+445+ const outcome = yield* run(answer, yield* freshSteps());446+447+ expect(outcome).toStrictEqual(landedAt(yield* mainTip));448+ expect(449+ (yield* jobsOn(answer.merged)).map(({ lanes }) =>450+ lanes.map(({ lane }) => lane)451+ )452+ ).toStrictEqual([453+ [lint, "types", sizedLane],454+ [askLane, unit],455+ ]);456+ }).pipe(Effect.provide(worldWith(withRatchet)))457+ );458+459+ it.effect(460 "3. a lane that never got going and then fails on its fresh run is the answer's failure",461 () =>462 Effect.gen(function* () {463 const answer = yield* admitted();585 unmodified linesmodified:packages/project/src/outbox.ts+48 added-2 removed
1 import { RefName, RepoHost } from "@repo/artifacts/repo-host";2+import { CheckAt, CheckRunner } from "@repo/checks/check-runner";3 import { Verdict } from "@repo/protocol/domain/answer";4 import type { ProjectEvent } from "@repo/protocol/domain/event";5+import { RunBlock } from "@repo/protocol/domain/run";6 import {7 CommitSha,8 Handle,9 LandedSha,10+ ProjectName,11 RepoName,12 RequestId,13 TreeSha,14 } from "@repo/protocol/ids";12-import type { ProjectName } from "@repo/protocol/ids";15 import { Array, DateTime, Effect, Option, Order, Schema, Struct } from "effect";16 17 import { AnswerRuns } from "./answer-runs.ts";18 import type { AnswerQueue } from "./answer-runs.ts";19 import { DraftParams, DraftRuns } from "./draft-runs.ts";20+import { noRunEnv } from "./env-port.ts";21 import { Lander, Rebuild } from "./lander.ts";22 import { backoff } from "./landing.ts";23 import { MetricPoint, Metrics } from "./metrics.ts";24 import type { OutboxRow } from "./project-store/rows.ts";26 unmodified lines51 Schema.TaggedStruct("StartDraft", DraftParams.fields),52 Schema.TaggedStruct("Measured", {53 points: Schema.NonEmptyArray(MetricPoint),54 }),55+ /**56+ * One Checker job with no lanes on a landed commit, so its setup snapshot57+ * is there before the next answer: the Checker keeps a snapshot only for58+ * the project's own commits, and an answer's tree alone never makes one.59+ */60+ Schema.TaggedStruct("WarmSetup", {61+ at: LandedSha,62+ project: ProjectName,63+ repo: RepoName,64+ run: RunBlock,65+ }),66 ]).pipe(Schema.toTaggedUnion("_tag"));67 68 export type OutboxBody = typeof OutboxBody.Type;69 63 unmodified lines133 Array.of134 )135 : Effect.succeed([]);136 137+/** Kept in the commit that keeps the landing, under the landing's SHA: one job per landing, however often it is heard. */138+export const warmRow = (139+ job: Omit<Extract<OutboxBody, { readonly _tag: "WarmSetup" }>, "_tag">,140+ at: DateTime.Utc141+) =>142+ outboxRow(`warm:${job.at}`, OutboxBody.cases.WarmSetup.make(job), at);143+144 export const isDue = (row: OutboxRow, now: DateTime.Utc) =>145 DateTime.isLessThanOrEqualTo(row.notBefore, now);146 147 export interface OutboxRun {76 unmodified lines224 claim: (ids: readonly string[]) => Effect.Effect<readonly string[]>225 ): Effect.Effect<226 OutboxRun,227 never,207- AnswerRuns | Lander | Projection | RepoHost228+ AnswerRuns | CheckRunner | Lander | Projection | RepoHost229 > =>230 Effect.gen(function* () {231 const decoded = yield* Effect.forEach(rows, (row) =>232 Effect.map(Effect.orDie(decodeBody(row.body)), (body) => ({ body, row }))62 unmodified lines295 ({ body, row }) =>296 Effect.as(metrics.write(body.points), ran(row, true, now))297 );298 299+ // Best effort, once: a setup the Checker could not keep is installed300+ // again by the next answer, as it would have been.301+ const warmed = yield* Effect.forEach(of("WarmSetup"), ({ body, row }) =>302+ Effect.as(303+ CheckRunner.use((runner) =>304+ runner.run({305+ ...noRunEnv,306+ at: CheckAt.cases.Commit.make({ commit: body.at }),307+ lanes: [],308+ project: body.project,309+ repo: body.repo,310+ run: body.run,311+ })312+ ).pipe(313+ Effect.catchTag("VerifierBlocked", () =>314+ Effect.logWarning("the setup snapshot was not warmed").pipe(315+ Effect.annotateLogs({ landed: body.at, project: body.project })316+ )317+ )318+ ),319+ ran(row, true, now)320+ )321+ );322+323 const runs = yield* Effect.forEach(of("StartAnswer"), ({ body, row }) =>324 Effect.as(325 AnswerRuns.use((answers) => answers.start(body.requestId, queue)),326 ran(row, true, now)6 unmodified lines333 ...kept,334 ...planned,335 ...drafts,336 ...measured,337+ ...warmed,338 ...runs,339 ]);340 });modified:packages/project/src/project.ts+46 added-2 removed
277 unmodified lines278 OutboxBody,279 projectedRows,280 runOutbox,281 startRow,282+ warmRow,283 } from "./outbox.ts";284 import { ProjectStore } from "./project-store.ts";285 import type { ProjectSnapshot, ProjectWrites } from "./project-store.ts";286 import type {15 unmodified lines302 import type { Projection } from "./projection.ts";303 import { askToLand, holdsSlot, leave, queueOf, storedQueue } from "./queue.ts";304 import { afterLanding, decideRaise } from "./ratchets.ts";305 import type { RatchetBaseline } from "./ratchets.ts";306+import { bundleKeyAt, bundleThrough } from "./rules-bundle.ts";307 import {308 AdmissionPlan,309 AdmissionReport,310 HeldBackJob,1722 unmodified lines2033 withPorts(facts).pipe(2034 Effect.flatMap((found) => layered(snapshotNow(h, writes), found))2035 );2036 2037+ /**2038+ * One Checker job per landing whose policy has a setup, so the setup2039+ * snapshot for the landed lockfiles is there before the next answer;2040+ * nothing when the policy runs no setup, since no snapshot is kept then.2041+ */2042+ const warmRows = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2043+ Effect.gen(function* () {2044+ if (!Array.isReadonlyArrayNonEmpty(writes.landings)) {2045+ return [];2046+ }2047+2048+ const row = writes.project.get("row");2049+2050+ const policy =2051+ row?.policy === undefined2052+ ? h.policy2053+ : Option.some(yield* Effect.orDie(decodePolicy(row.policy)));2054+2055+ if (Option.isNone(policy) || policy.value.run.setup === undefined) {2056+ return [];2057+ }2058+2059+ const { run } = policy.value;2060+2061+ return yield* Effect.forEach(writes.landings, ({ sha }) =>2062+ warmRow({ at: sha, project: name, repo, run }, now)2063+ );2064+ });2065+2066 const commit = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2067 Effect.gen(function* () {2068 if (isEmpty(writes)) {2069 return [];10 unmodified lines2080 now2081 )2082 );2083 2053- const outbox = [...writes.outbox, ...landed.flat(), ...projected];2084+ const warmed = yield* warmRows(h, writes, now);2085 2086+ const outbox = [2087+ ...writes.outbox,2088+ ...landed.flat(),2089+ ...warmed,2090+ ...projected,2091+ ];2092+2093 const queue = yield* Effect.forEach(writes.queue.values(), (each) =>2094 storedQueue(each)2095 );2096 287 unmodified lines2384 Option.map(previous, ({ vouch }) => vouch.file),2385 () => RepoPath.make(`${Brand.configDir}/vouched.td`)2386 );2387 2388+ // Bundled once per change to the config folder: a landing that leaves2389+ // the folder's tree as it was reads the bundle the last one kept.2350- const bundle = yield* Effect.option(lander.bundleRules({ at, repo }));2390+ const bundle = yield* Effect.option(2391+ Effect.flatMap(withPorts(bundleKeyAt(repo, at)), (key) =>2392+ bundleThrough(key, lander.bundleRules({ at, repo }))2393+ )2394+ );2395 2396 if (Option.isNone(bundle)) {2397 yield* Effect.logWarning(2398 `the config folder at ${at} could not be read`3263 unmodified linesadded:packages/project/src/rules-bundle.ts+77 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677/** * A commit's rules bundle, kept by its config folder's tree id: the Lander * bundles only the files under `<configDir>/` against one SDK, so two commits * whose folders are one tree bundle to one bundle, and a landing that leaves * the folder as it was bundles nothing. Keys: * `<repo>/rules-bundle/v<version>/<sdkVersion>/<tree id>`, under a canonical * repo alone; a commit without the folder is keyed `none`. */import { RepoHost } from "@repo/artifacts/repo-host";import type { ObjectId } from "@repo/artifacts/repo-host";import { Brand } from "@repo/brand";import type { CommitSha, RepoName } from "@repo/protocol/ids";import { ConfigBundle, sdkVersion } from "@repo/rules/rules-evaluator";import { Effect, Option } from "effect";
import { throughHistory } from "./code/history.ts";import type { Kept } from "./code/history.ts";
export const BUNDLE_VERSION = 1;
export const rulesBundleKept: Kept<ConfigBundle> = { kind: "rules-bundle", schema: ConfigBundle, version: BUNDLE_VERSION,};
const NO_FOLDER = "none";
/** The config folder's tree id at a commit; `none` without the folder, and no key when the commit can't be read. */export const bundleKeyAt = ( repo: RepoName, at: CommitSha): Effect.Effect<Option.Option<string>, never, RepoHost> => Effect.gen(function* () { const host = yield* RepoHost; const commit = yield* host.readCommit(repo, at);
if (Option.isNone(commit)) { return Option.none<string>(); }
const folder = yield* Effect.reduce( Brand.configDir.split("/"), (): Option.Option<ObjectId> => Option.some(commit.value.tree), (found, segment) => Option.match(found, { onNone: () => Effect.succeedNone, onSome: (tree) => Effect.map(host.readTree(repo, tree), (entries) => Option.flatMap(entries, (listed) => Option.map( Option.fromUndefinedOr( listed.find( (entry) => entry.name === segment && entry.type === "tree" ) ), ({ sha }) => sha ) ) ), }) );
return Option.some( `${repo}/${rulesBundleKept.kind}/v${BUNDLE_VERSION}/${sdkVersion}/${Option.getOrElse(folder, () => NO_FOLDER)}` ); }).pipe(Effect.orElseSucceed(() => Option.none<string>()));
/** Bundles only when no bundle is kept under the key; a bundle it made is kept. */export const bundleThrough = <E, R>( key: Option.Option<string>, bundle: Effect.Effect<ConfigBundle, E, R>): Effect.Effect<ConfigBundle, E, R> => Option.match(key, { onNone: () => bundle, onSome: (found) => throughHistory(rulesBundleKept, found, bundle), });added:packages/project/test/rules-bundle.test.ts+277 added
1+import { describe, expect, it } from "@effect/vitest";2+import { RefName, RepoHost } from "@repo/artifacts/repo-host";3+import { Brand } from "@repo/brand";4+import { CheckSpec } from "@repo/protocol/domain/check";5+import {6+ AskId,7+ CommitSha,8+ keyOf,9+ LandedSha,10+ LaneName,11+ RepoName,12+} from "@repo/protocol/ids";13+import { Person } from "@repo/protocol/principal";14+import type { ConfigBundle } from "@repo/rules/rules-evaluator";15+import { advanceTo } from "@repo/testkit/clock";16+import type { Files } from "@repo/testkit/git-client";17+import { aProject, withAsk } from "@repo/testkit/scenarios";18+import { Array, Context, Effect, Layer, Option, Ref, Schema } from "effect";19+20+import { CodeStore } from "../src/code-store.ts";21+import { CodeStoreMemory } from "../src/code-store/memory.ts";22+import { Lander } from "../src/lander.ts";23+import type { ProjectApi } from "../src/project.ts";24+import { projectService } from "../src/project.ts";25+import {26+ bundleKeyAt,27+ bundleThrough,28+ rulesBundleKept,29+} from "../src/rules-bundle.ts";30+import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";31+32+const scenario = aProject().pipe(33+ withAsk({ id: "parse-iso", territory: "packages/parser" }),34+ withAsk({ id: "trim-input", territory: "." })35+);36+37+const { policy } = scenario;38+39+const repo = RepoName.make(keyOf(scenario.project));40+41+const mainRef = RefName.make("refs/heads/main");42+43+const alice = Person.make({ handle: scenario.initializer });44+45+const start: Files = [46+ [47+ "package.json",48+ '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',49+ ],50+ ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],51+ ["src/trim.ts", "export const trim = (s) => s;\n"],52+];53+54+class BundleCount extends Context.Service<55+ BundleCount,56+ { readonly count: Effect.Effect<number> }57+>()("test/BundleCount") {}58+59+/** The world's Lander, each bundle it makes counted. */60+const counted = Layer.effectContext(61+ Effect.gen(function* () {62+ const inner = yield* Lander;63+ const count = yield* Ref.make(0);64+65+ const lander = Lander.of({66+ ...inner,67+ bundleRules: (job) =>68+ Effect.andThen(69+ Ref.update(count, (n) => n + 1),70+ inner.bundleRules(job)71+ ),72+ });73+74+ return Context.make(Lander, lander).pipe(75+ Context.add(BundleCount, { count: Ref.get(count) })76+ );77+ })78+).pipe(Layer.provideMerge(worldOf({ policy }, "memory")));79+80+const mainTip = Effect.gen(function* () {81+ const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);82+83+ return LandedSha.make(84+ Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))85+ );86+});87+88+const openAsk = (api: ProjectApi, id: string) =>89+ Effect.gen(function* () {90+ const ask = Option.getOrThrow(91+ Array.findFirst(policy.asks, (each) => each.id === id)92+ );93+94+ if (!CheckSpec.guards.RedThenGreen(ask.check)) {95+ return yield* Effect.die(`${id}'s check is not red-then-green`);96+ }97+98+ const files = Array.make(99+ { content: `export default "${id}";\n`, path: ask.file },100+ { content: `it("${id}", () => {});\n`, path: ask.check.path }101+ );102+103+ const landed = yield* mainTip;104+105+ yield* CheckScript.use(106+ Effect.fnUntraced(function* (checker) {107+ yield* checker.script(108+ yield* composedAt(repo, landed, files),109+ LaneName.make("redThenGreen"),110+ ["failed", "failed"]111+ );112+ })113+ );114+115+ return yield* api.openAsk(alice, { ask: AskId.make(id), files });116+ });117+118+const bundle: ConfigBundle = {119+ entry: `${Brand.configDir}/project.ts`,120+ modules: { [`${Brand.configDir}/policy.json`]: "{}" },121+ sdkVersion: "0.0.0",122+};123+124+describe("a commit's rules bundle", () => {125+ it.effect(126+ "is keyed by its config folder's tree, so a commit that keeps the folder shares the key",127+ () =>128+ Effect.gen(function* () {129+ const push = (parent: Option.Option<CommitSha>, files: Files) =>130+ Pusher.use((pusher) => pusher.push(repo, parent, files));131+132+ yield* advanceTo("2026-10-07T12:00:00Z");133+ yield* (yield* projectService(scenario.project)).initProject(alice, {});134+135+ const bare = yield* push(Option.none(), start);136+137+ const configured = yield* push(Option.some(bare), [138+ ...start,139+ [`${Brand.configDir}/policy.json`, "{}\n"],140+ ]);141+142+ const sameFolder = yield* push(Option.some(configured), [143+ ...start,144+ ["src/trim.ts", "export const trim = (s) => s.trim();\n"],145+ [`${Brand.configDir}/policy.json`, "{}\n"],146+ ]);147+148+ const changedFolder = yield* push(Option.some(sameFolder), [149+ ...start,150+ [`${Brand.configDir}/policy.json`, '{ "kinds": [] }\n'],151+ ]);152+153+ const keys = yield* Effect.all([154+ bundleKeyAt(repo, bare),155+ bundleKeyAt(repo, configured),156+ bundleKeyAt(repo, sameFolder),157+ bundleKeyAt(repo, changedFolder),158+ ]);159+160+ const unknown = yield* bundleKeyAt(161+ repo,162+ CommitSha.make("0000000000000000000000000000000000000000")163+ );164+165+ expect({166+ bareIsNone: keys[0],167+ changedDiffers:168+ Option.getOrThrow(keys[3]) !== Option.getOrThrow(keys[1]),169+ configuredDiffers:170+ Option.getOrThrow(keys[1]) !== Option.getOrThrow(keys[0]),171+ prefixed: Option.getOrThrow(keys[1]).startsWith(172+ `${repo}/rules-bundle/v`173+ ),174+ sameShares: keys[2],175+ unknown,176+ }).toStrictEqual({177+ bareIsNone: Option.map(keys[0], (key) =>178+ key.replace(/[^/]+$/u, "none")179+ ),180+ changedDiffers: true,181+ configuredDiffers: true,182+ prefixed: true,183+ sameShares: keys[1],184+ unknown: Option.none(),185+ });186+ }).pipe(Effect.provide(worldOf({ policy }, "memory")))187+ );188+189+ it.effect(190+ "is kept once made, and a kept one that no longer decodes is made again",191+ () =>192+ Effect.gen(function* () {193+ const store = yield* CodeStore;194+ const made = yield* Ref.make(0);195+ const key = Option.some(`${repo}/rules-bundle/test`);196+197+ const make = Effect.andThen(198+ Ref.update(made, (n) => n + 1),199+ Effect.succeed(bundle)200+ );201+202+ const first = yield* bundleThrough(key, make);203+ const second = yield* bundleThrough(key, make);204+ const madeOnce = yield* Ref.get(made);205+206+ yield* store.put(Option.getOrThrow(key), '{"entry":"no modules"}');207+208+ const replaced = yield* bundleThrough(key, make);209+ const madeAgain = yield* Ref.get(made);210+211+ const kept = Option.flatMap(212+ yield* store.get(Option.getOrThrow(key)),213+ Schema.decodeUnknownOption(214+ Schema.fromJsonString(rulesBundleKept.schema)215+ )216+ );217+218+ // Without a key (the commit could not be read) every call bundles.219+ const unkeyed = yield* bundleThrough(Option.none(), make);220+ const madeUnkeyed = yield* Ref.get(made);221+222+ expect({223+ first,224+ kept,225+ madeAgain,226+ madeOnce,227+ madeUnkeyed,228+ replaced,229+ second,230+ unkeyed,231+ }).toStrictEqual({232+ first: bundle,233+ kept: Option.some(bundle),234+ madeAgain: 2,235+ madeOnce: 1,236+ madeUnkeyed: 3,237+ replaced: bundle,238+ second: bundle,239+ unkeyed: bundle,240+ });241+ }).pipe(Effect.provide(CodeStoreMemory))242+ );243+244+ it.effect(245+ "is made once per change to the folder across a project's landings: an ask's composed commit and its landing share one",246+ () =>247+ Effect.gen(function* () {248+ yield* advanceTo("2026-10-07T12:00:00Z");249+250+ const { count } = yield* BundleCount;251+ const api = yield* projectService(scenario.project);252+253+ yield* api.initProject(alice, {});254+255+ const first = yield* Pusher.use((pusher) =>256+ pusher.push(repo, Option.none(), start, "Start")257+ );258+259+ yield* api.recordFirstPush(alice, first);260+261+ const afterFirst = yield* count;262+263+ yield* openAsk(api, "parse-iso");264+265+ const afterOne = yield* count;266+267+ yield* openAsk(api, "trim-input");268+269+ const afterTwo = yield* count;270+271+ // One bundle for the first push's tree, and one per opening: the272+ // ask's composed commit is bundled and its landing, the same273+ // folder, reads it back.274+ expect([afterFirst, afterOne, afterTwo]).toStrictEqual([1, 2, 3]);275+ }).pipe(Effect.provide(Layer.merge(counted, CodeStoreMemory)))276+ );277+});added:packages/project/test/warm-setup.test.ts+98 added
1+import { describe, expect, it } from "@effect/vitest";2+import { CheckAt } from "@repo/checks/check-runner";3+import type { CheckJob } from "@repo/checks/check-runner";4+import { Command } from "@repo/protocol/domain/common";5+import type { Policy } from "@repo/protocol/domain/policy";6+import { keyOf, RepoName } from "@repo/protocol/ids";7+import { Person } from "@repo/protocol/principal";8+import { advanceTo } from "@repo/testkit/clock";9+import type { Files } from "@repo/testkit/git-client";10+import { aProject } from "@repo/testkit/scenarios";11+import { Effect, Option } from "effect";12+13+import { projectService } from "../src/project.ts";14+import { CheckScript, Pusher, worldOf } from "./world.ts";15+16+const scenario = aProject();17+18+const repo = RepoName.make(keyOf(scenario.project));19+20+const alice = Person.make({ handle: scenario.initializer });21+22+const start: Files = [23+ ["package.json", '{ "name": "alice/datekit", "private": true }\n'],24+ ["bun.lock", "{}\n"],25+ ["src/trim.ts", "export const trim = (s) => s;\n"],26+];27+28+const installing: Policy = {29+ ...scenario.policy,30+ run: {31+ ...scenario.policy.run,32+ setup: Command.make("bun install --frozen-lockfile"),33+ },34+};35+36+const shape = ({ at, lanes, project, repo: on, run }: CheckJob) => ({37+ at,38+ lanes,39+ project,40+ repo: on,41+ setup: run.setup,42+});43+44+const firstLanding = Effect.gen(function* () {45+ yield* advanceTo("2026-10-07T12:00:00Z");46+47+ const api = yield* projectService(scenario.project);48+49+ yield* api.initProject(alice, {});50+51+ const first = yield* Pusher.use((pusher) =>52+ pusher.push(repo, Option.none(), start, "Start")53+ );54+55+ yield* api.recordFirstPush(alice, first);56+57+ return { api, first };58+});59+60+const jobs = CheckScript.use((script) => script.jobs);61+62+describe("a landing's setup snapshot", () => {63+ it.effect(64+ "is warmed by one Checker job with no lanes on the landed commit, once however often the outbox runs",65+ () =>66+ Effect.gen(function* () {67+ const { api, first } = yield* firstLanding;68+69+ const afterLanding = (yield* jobs).map(shape);70+71+ yield* api.onAlarm();72+ yield* api.onAlarm();73+74+ const afterAlarms = (yield* jobs).map(shape);75+76+ expect({ afterAlarms, afterLanding }).toStrictEqual({77+ afterAlarms: afterLanding,78+ afterLanding: [79+ {80+ at: CheckAt.cases.Commit.make({ commit: first }),81+ lanes: [],82+ project: scenario.project,83+ repo,84+ setup: "bun install --frozen-lockfile",85+ },86+ ],87+ });88+ }).pipe(Effect.provide(worldOf({ policy: installing }, "memory")))89+ );90+91+ it.effect("is not warmed when the policy runs no setup", () =>92+ Effect.gen(function* () {93+ yield* firstLanding;94+95+ expect(yield* jobs).toStrictEqual([]);96+ }).pipe(Effect.provide(worldOf({ policy: scenario.policy }, "memory")))97+ );98+});