Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

check-changed.ts

600 lines25.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - hashes inputs with node:crypto and sizes the budget with node:os.
2// Runs CI's fast checks for this branch's changes: format and lint of the
3// changed files, knip, generated GraphQL operations, typecheck of the affected
4// packages and their dependents, the test files beside the changed files, and
5// the cross-file checks those miss (agent context budget, React Compiler
6// coverage of the changed client files).
7// A dependency change also gets the unused-patch install check below. CI still
8// runs the full test suites and the jobs listed in the summary.
9//
10// vp run check:changed compare against the closest merge base with any remote main
11// vp run check:changed <ref> compare against the merge base with <ref>
12// vp run check:changed --concurrency 1 run the steps one at a time
13//
14// Uncommitted and untracked files count. Affected packages come from
15// .github/scripts/ci-changes.cjs, the same mapping CI uses to gate its jobs.
16// The steps run side by side within a budget derived from the machine's cores
17// and available memory, and each prints its output when it finishes. A step
18// running past the timeout is killed with its process group and reported as
19// TIMEOUT. A rerun on exactly the files of the last passing run prints that
20// run's summary.
21import * as NodeCrypto from "node:crypto";
22import * as NodeOS from "node:os";
23​
24import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
25import * as NodeServices from "@effect/platform-node/NodeServices";
26import * as HostProcess from "@t3tools/shared/HostProcess";
27import * as Clock from "effect/Clock";
28import * as Config from "effect/Config";
29import * as Console from "effect/Console";
30import * as Effect from "effect/Effect";
31import * as FileSystem from "effect/FileSystem";
32import * as Option from "effect/Option";
33import * as Path from "effect/Path";
34import type * as PlatformError from "effect/PlatformError";
35import * as Schema from "effect/Schema";
36import * as Semaphore from "effect/Semaphore";
37import * as Stream from "effect/Stream";
38import { Argument, Command, Flag } from "effect/cli";
39import { ChildProcess, ChildProcessSpawner } from "effect/process";
40​
41import { decide, readWorkspace } from "../.github/scripts/ci-changes.cjs";
42​
43const GiB = 1024 ** 3;
44​
45// A typecheck or test step can take several cores and gigabytes of memory, so
46// allow one step per two cores and per 6 GiB of available memory.
47export const defaultConcurrency = (cores: number, availableBytes: number) =>
48 Math.max(1, Math.min(Math.floor(cores / 2), Math.floor(availableBytes / (6 * GiB))));
49​
50export type Outcome = "pass" | "FAIL" | "TIMEOUT";
51​
52export interface Step<R> {
53 readonly name: string;
54 readonly run: Effect.Effect<{ readonly ok: boolean; readonly output: string }, never, R>;
55 // Budget slots the step holds: one per worker it runs in parallel.
56 readonly weight?: number;
57 // Vitest runs started together race to rebuild node_modules/.vitest-cache (ENOTEMPTY).
58 readonly serial?: boolean;
60​
61// Interrupting a step at its timeout closes the scopes of the processes it
62// spawned, which kills each one's process group.
63export const runSteps = Effect.fn("checkChanged.runSteps")(function* <R>(
64 steps: ReadonlyArray<Step<R>>,
65 options: { readonly concurrency: number; readonly timeoutSeconds: number },
66) {
67 const budget = yield* Semaphore.make(options.concurrency);
68 // Steps claim budget one at a time, in order: Semaphore lets a light request
69 // take free slots ahead of a waiting heavier one, which would delay typecheck.
70 const admission = yield* Semaphore.make(1);
71 const serial = yield* Semaphore.make(1);
72 return yield* Effect.forEach(
73 steps,
74 (step) => {
75 const timed = Effect.gen(function* () {
76 const started = yield* Clock.currentTimeMillis;
77 const result = yield* Effect.timeoutOption(step.run, `${options.timeoutSeconds} seconds`);
78 const seconds = ((yield* Clock.currentTimeMillis) - started) / 1000;
79 const outcome: Outcome = Option.match(result, {
80 onNone: () => "TIMEOUT",
81 onSome: ({ ok }) => (ok ? "pass" : "FAIL"),
82 });
83 const time =
84 outcome === "TIMEOUT"
85 ? `killed after ${options.timeoutSeconds}s`
86 : `${seconds.toFixed(1)}s`;
87 yield* Console.log(`\n> vp ${step.name} ${outcome} ${time}`);
88 const output = Option.getOrUndefined(result)?.output.trimEnd();
89 if (output) yield* Console.log(output);
90 return { name: step.name, outcome, time };
91 });
92 const slots = Math.min(step.weight ?? 1, options.concurrency);
93 const limited = Effect.acquireUseRelease(
94 admission.withPermit(budget.take(slots)),
95 () => timed,
96 () => budget.release(slots),
97 );
98 return step.serial ? serial.withPermit(limited) : limited;
99 },
100 { concurrency: "unbounded" },
101 );
102});
103​
104const CacheEntry = Schema.fromJsonString(
105 Schema.Struct({ key: Schema.String, summary: Schema.Array(Schema.String) }),
106);
107const decodeCacheEntry = Schema.decodeEffect(CacheEntry);
108const encodeCacheEntry = Schema.encodeEffect(CacheEntry);
109const decodeRootPackageJson = Schema.decodeEffect(
110 Schema.fromJsonString(Schema.Struct({ scripts: Schema.Struct({ "knip:check": Schema.String }) })),
111);
112​
113const collectBytes = (stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>) =>
114 Stream.runCollect(stream).pipe(Effect.map((chunks) => Buffer.concat(chunks)));
115​
116// Fails on a nonzero exit: an empty file list from a broken index would
117// otherwise pass as "no changes". quotePath=false keeps non-ASCII paths as real
118// paths instead of quoted escapes.
119export const git = Effect.fn("checkChanged.git")(function* (
120 cwd: string,
121 args: ReadonlyArray<string>,
122) {
123 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
124 return yield* Effect.scoped(
125 Effect.gen(function* () {
126 const handle = yield* spawner.spawn(
127 ChildProcess.make("git", ["-c", "core.quotePath=false", ...args], { cwd }),
128 );
129 const [stdout, stderr, exitCode] = yield* Effect.all(
130 [collectBytes(handle.stdout), collectBytes(handle.stderr), handle.exitCode],
131 { concurrency: "unbounded" },
132 );
133 if (exitCode !== 0) {
134 return yield* Effect.fail(
135 `check:changed: git ${args.join(" ")} exited with ${exitCode}: ${stderr.toString().trim()}`,
136 );
137 }
138 return stdout;
139 }),
140 );
141});
142export const gitLines = (cwd: string, args: ReadonlyArray<string>) =>
143 git(cwd, args).pipe(Effect.map((stdout) => stdout.toString().split("\n").filter(Boolean)));
144​
145export const comparisonBase = Effect.fn("checkChanged.comparisonBase")(function* (
146 root: string,
147 explicitRef: Option.Option<string>,
148) {
149 const candidates = Option.isSome(explicitRef)
150 ? [{ ref: explicitRef.value, rev: explicitRef.value }]
151 : (yield* gitLines(root, ["remote"])).map((name) => ({
152 ref: name + "/main",
153 rev: "refs/remotes/" + name + "/main",
154 }));
155 let closest: { ref: string; base: string; ahead: number } | undefined;
156 for (const { ref, rev } of candidates) {
157 const base = yield* git(root, ["merge-base", "HEAD", rev]).pipe(
158 Effect.map((stdout) => stdout.toString().trim()),
159 Effect.orElseSucceed(() => undefined),
160 );
161 if (!base) continue;
162 const ahead = Number((yield* git(root, ["rev-list", "--count", base + "..HEAD"])).toString());
163 if (!closest || ahead < closest.ahead) closest = { ref, base, ahead };
164 }
165 if (!closest) {
166 const tried = candidates.map(({ ref }) => ref).join(", ") || "a remote main";
167 return yield* Effect.fail(
168 "check:changed: no merge base with " + tried + ". Run git fetch or pass a ref.",
169 );
170 }
171 return closest;
172});
173​
174const CODE = /\.[cm]?[jt]sx?$/;
175const TEST = /\.test\.[cm]?[jt]sx?$/;
176// CI runs the .github/scripts tests with `node --test`; vitest passes a failing node:test file.
177const NODE_TEST = /^\.github[/\\]scripts[/\\]/;
178export const splitTests = (tests: Iterable<string>) => {
179 const all = [...tests];
180 return {
181 vitestTests: all.filter((file) => !NODE_TEST.test(file)),
182 nodeTests: all.filter((file) => NODE_TEST.test(file)),
183 };
184};
185const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
186​
187// A flag wins over its environment variable; either must be a positive integer.
188const override = Effect.fn("checkChanged.override")(function* (
189 flagName: string,
190 flag: Option.Option<number>,
191 envName: string,
192) {
193 const [name, value] = Option.isSome(flag)
194 ? [`--${flagName}`, flag]
195 : [envName, yield* Config.option(Config.Int(envName))];
196 if (Option.isSome(value) && value.value < 1) {
197 return yield* Effect.fail(`check:changed: ${name} must be a positive integer.`);
198 }
199 return value;
200});
201​
202const checkChanged = Effect.fn("checkChanged")(function* (input: {
203 readonly ref: Option.Option<string>;
204 readonly concurrency: Option.Option<number>;
205 readonly timeout: Option.Option<number>;
206}) {
207 const fs = yield* FileSystem.FileSystem;
208 const path = yield* Path.Path;
209 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
210 const root = yield* path.fromFileUrl(new URL("..", import.meta.url));
211 const inRoot = (file: string) => path.join(root, file);
212​
213 // macOS counts its file cache as used, so available memory there would
214 // starve a large Mac. Elsewhere availableMemory() honors a cgroup limit.
215 const platform = yield* HostProcess.Platform;
216 const concurrency = Option.getOrElse(
217 yield* override("concurrency", input.concurrency, "CHECK_CHANGED_CONCURRENCY"),
218 () =>
219 defaultConcurrency(
220 NodeOS.availableParallelism(),
221 platform === "darwin" ? NodeOS.totalmem() : process.availableMemory(),
222 ),
223 );
224 const timeoutSeconds = Option.getOrElse(
225 yield* override("timeout", input.timeout, "CHECK_CHANGED_TIMEOUT"),
226 () => 900,
227 );
228​
229 const lines = (...args: Array<string>) => gitLines(root, args);
230​
231 const { ref, base } = yield* comparisonBase(root, input.ref);
232 // --no-renames lists a rename as its old and new path, as CI does.
233 const changedFiles = lines("diff", "--name-only", "--no-renames", base, "--");
234 const untrackedFiles = lines("ls-files", "--others", "--exclude-standard");
235 const files = [...new Set([...(yield* changedFiles), ...(yield* untrackedFiles)])].sort();
236​
237 if (files.length === 0) {
238 yield* Console.log(`check:changed: no changes since ${base.slice(0, 12)} (${ref}).`);
239 return true;
240 }
241 yield* Console.log(`check:changed: ${files.length} files since ${base.slice(0, 12)} (${ref})`);
242​
243 // Ignored generated sources, declarations, env files, and install state affect check results.
244 // Include them in the key, but skip large ignored folders that no check reads.
245 // Recompute after a passing run so edits made during it are never cached as passing.
246 const ci = Option.getOrElse(yield* Config.option(Config.String("CI")), () => "");
247 const inputKey = Effect.gen(function* () {
248 const hash = NodeCrypto.createHash("sha256");
249 // CI changes test behavior (vite.config.ts rejects .only under CI).
250 hash.update(`${process.version}\0${base}\0${ci}\0`);
251 hash.update(
252 yield* git(root, [
253 "diff",
254 "--binary",
255 "--no-renames",
256 "--no-ext-diff",
257 "--no-textconv",
258 base,
259 "--",
260 ]),
261 );
262 const ignored = yield* lines(
263 "ls-files",
264 "--others",
265 "--ignored",
266 "--exclude-standard",
267 "--",
268 ":(glob)**/.generated/**",
269 ":(glob)**/.astro/**",
270 ":(glob)**/*.d.ts",
271 ":(glob)**/.env*",
272 ":(exclude,glob)**/node_modules/**",
273 );
274 for (const file of [
275 // Raw bytes of changed files too: .gitattributes normalizes line endings in
276 // the diff, but the formatter reads the file as it is on disk.
277 ...(yield* changedFiles),
278 ...(yield* untrackedFiles),
279 ...ignored,
280 "node_modules/.modules.yaml",
281 "node_modules/.pnpm/lock.yaml",
282 ]) {
283 hash.update(`\0${file}\0`);
284 // Untracked nested repositories are listed as directories.
285 const info = yield* Effect.option(fs.stat(inRoot(file)));
286 if (Option.isSome(info) && info.value.type === "File") {
287 hash.update(yield* fs.readFile(inRoot(file)));
288 }
289 }
290 return hash.digest("hex");
291 });
292 const key = yield* inputKey;
293 const cachePath = inRoot("node_modules/.cache/check-changed.json");
294 // A missing or unreadable cache is a miss, never a failure.
295 const cached = yield* fs
296 .readFileString(cachePath)
297 .pipe(Effect.flatMap(decodeCacheEntry), Effect.option);
298 if (Option.isSome(cached) && cached.value.key === key) {
299 yield* Console.log("Nothing changed since the last passing run.\n");
300 for (const line of cached.value.summary) yield* Console.log(line);
301 return true;
302 }
303​
304 const present = yield* Effect.filter(files, (file) => fs.exists(inRoot(file)));
305 const code = present.filter((file) => CODE.test(file));
306 const packages = readWorkspace();
307 const { affected, outputs } = decide(files, packages, false);
308​
309 // Changed test files, and the test files beside a changed source file
310 // (foo.ts -> foo.test.ts, foo.browser.test.tsx). Vitest's import-graph
311 // `related` reaches most of a package: one leaf server file pulled in 252 of
312 // 406 server test files and took 7 minutes. CI runs the rest.
313 const tests = new Set(code.filter((file) => TEST.test(file)));
314 for (const file of code) {
315 const dir = path.dirname(file);
316 const prefix = `${path.basename(file).replace(CODE, "")}.`;
317 for (const entry of yield* fs.readDirectory(inRoot(dir))) {
318 if (entry.startsWith(prefix) && TEST.test(entry)) tests.add(path.join(dir, entry));
319 }
320 }
321 // It reads files other than the ones beside it, so no changed file selects it.
322 if (affected.includes("t3")) tests.add("apps/server/src/provider/AgentContextBudget.test.ts");
323 const { vitestTests, nodeTests } = splitTests(tests);
324​
325 // React Compiler coverage compiles every client source file, so run only the
326 // changed files' cases, in one extra step: a -t filter in the main test step
327 // would drop every other test. An app is skipped when the main step already
328 // runs its coverage file unfiltered. File filters mirror each coverage test.
329 const compilerApps = [
330 {
331 test: "apps/web/src/reactCompilerCoverage.test.ts",
332 root: "apps/web/src/",
333 // Test names keep the repo-relative path.
334 name: (file: string) => file,
335 compiled: (file: string) =>
336 /\.tsx?$/.test(file) && !/\.(test|browser)\.tsx?$/.test(file) && !file.endsWith(".gen.ts"),
337 // Web has only per-file cases.
338 always: [],
339 },
340 {
341 test: "apps/mobile/src/reactCompilerCoverage.test.ts",
342 root: "apps/mobile/src/",
343 name: (file: string) => file.slice("apps/mobile/".length),
344 compiled: (file: string) => /\.tsx?$/.test(file) && !/\.(test\.tsx?|d\.ts)$/.test(file),
345 // The Metro, cache, and stale-allowlist cases check more than one file, deletions included.
346 always: ["^(?!.*compiles )"],
347 },
348 ].flatMap(({ test, root: appRoot, name, compiled, always }) => {
349 const changed = files.filter((file) => file.startsWith(appRoot) && compiled(file));
350 if (changed.length === 0 || tests.has(test)) return [];
351 const names = changed
352 .filter((file) => present.includes(file))
353 .map((file) => `compiles ${escapeRegExp(name(file))}$`);
354 const pattern = [...names, ...always];
355 return pattern.length > 0 ? [{ test, names, pattern }] : [];
356 });
357​
358 // knip:check cannot be scoped to a package. Any code change can leave a file,
359 // export, or dependency unused (removing the last import of a helper does), so
360 // it runs whenever code or a manifest changes.
361 const runKnip = files.some(
362 (file) => CODE.test(file) || path.basename(file) === "package.json" || file === "knip.jsonc",
363 );
364 // CI runs knip:check as one script of `knip ... && knip ...` passes. The passes
365 // do not depend on each other, so they run side by side here.
366 const rootPackage = yield* fs
367 .readFileString(inRoot("package.json"))
368 .pipe(Effect.flatMap(decodeRootPackageJson), Effect.orDie);
369 const knipCheck = rootPackage.scripts["knip:check"];
370 const knipPasses: Array<Array<string>> = [];
371 for (const command of knipCheck.split(" && ")) {
372 const [bin, ...args] = command.trim().split(/\s+/);
373 if (bin !== "knip" || /["'$\\|;&<>]/.test(command)) {
374 return yield* Effect.fail(`check:changed cannot split knip:check: ${command}`);
375 }
376 knipPasses.push(["exec", "knip", ...args]);
377 }
378​
379 // A version bump can leave a patch unused, causing pnpm to reject the install
380 // with ERR_PNPM_UNUSED_PATCH. Check it here as Release Smoke does in CI.
381 const runPatchCheck = files.some(
382 (file) =>
383 file === "pnpm-workspace.yaml" ||
384 file === "pnpm-lock.yaml" ||
385 file === ".pnpmfile.cjs" ||
386 file.startsWith("patches/") ||
387 file.startsWith("apps/mobile/deps/") ||
388 path.basename(file) === "package.json",
389 );
390​
391 // Output is piped, so keep the colors a terminal would get.
392 const env = process.stdout.isTTY ? { FORCE_COLOR: "1" } : {};
393 const vp = (args: ReadonlyArray<string>, cwd = root) =>
394 Effect.scoped(
395 Effect.gen(function* () {
396 const handle = yield* spawner.spawn(
397 ChildProcess.make("vp", args, { cwd, env, extendEnv: true, forceKillAfter: "5 seconds" }),
398 );
399 const [output, exitCode] = yield* Effect.all(
400 [Stream.mkString(Stream.decodeText(handle.all)), handle.exitCode],
401 { concurrency: 2 },
402 );
403 return { ok: exitCode === 0, output };
404 }),
405 ).pipe(Effect.catch((error) => Effect.succeed({ ok: false, output: error.message })));
406​
407 // Resolve without the lockfile in a temp copy to preserve the working tree and lockfile.
408 // Copy mobile modules too: they are file: dependencies, not workspace packages.
409 // Cached registry metadata limits this to patches stranded by local changes, not registry drift.
410 const checkPatches = Effect.scoped(
411 Effect.gen(function* () {
412 const temp = yield* fs.makeTempDirectoryScoped({ prefix: "t3-patch-check-" });
413 const copy = Effect.fnUntraced(function* (relative: string) {
414 const dest = path.join(temp, relative);
415 yield* fs.makeDirectory(path.dirname(dest), { recursive: true });
416 yield* fs.copy(inRoot(relative), dest);
417 });
418 yield* copy("package.json");
419 yield* copy("pnpm-workspace.yaml");
420 for (const pkg of packages) yield* copy(`${pkg.dir}/package.json`);
421 const modulesDir = "apps/mobile/modules";
422 if (yield* fs.exists(inRoot(modulesDir))) {
423 for (const entry of yield* fs.readDirectory(inRoot(modulesDir))) {
424 const manifest = `${modulesDir}/${entry}/package.json`;
425 if (yield* fs.exists(inRoot(manifest))) yield* copy(manifest);
426 }
427 }
428 for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) {
429 if (yield* fs.exists(inRoot(extra))) yield* copy(extra);
430 }
431 const result = yield* vp(["install", "--lockfile-only", "--ignore-scripts"], temp);
432 if (result.ok || !result.output.includes("ERR_PNPM_UNUSED_PATCH")) return result;
433 return {
434 ok: false,
435 output:
436 `${result.output}\nUnused dependency patches: remove each patch named above from ` +
437 "patchedDependencies in pnpm-workspace.yaml and from patches/, " +
438 "update it to the version the install resolves, " +
439 "or pin the dependency that pulls it in to the patched version.",
440 };
441 }),
442 ).pipe(Effect.catch((error) => Effect.succeed({ ok: false, output: error.message })));
443​
444 // CI's Lint job checks that generated GraphQL operations match their sources.
445 const graphql = ["apps/server", "packages/source-control-github"].filter((dir) =>
446 files.some((file) => file.startsWith(`${dir}/`)),
447 );
448 const filters = (names: ReadonlyArray<string>) => names.flatMap((name) => ["--filter", name]);
449 const typecheckWorkers = Math.min(concurrency, affected.length);
450 const command = (name: string, args: ReadonlyArray<string>) => ({ name, run: vp(args) });
451 const compilerFiles = compilerApps.reduce((count, app) => count + app.names.length, 0);
452​
453 const steps: Array<Step<never>> = [
454 ...(runPatchCheck ? [{ name: "unused patches", run: checkPatches }] : []),
455 ...(present.length > 0
456 ? [command("format", ["fmt", "--check", "--no-error-on-unmatched-pattern", ...present])]
457 : []),
458 ...(code.length > 0 ? [command("lint", ["lint", ...code])] : []),
459 ...(runKnip
460 ? knipPasses.map((args, index) => command(`knip ${index + 1}/${knipPasses.length}`, args))
461 : []),
462 ...graphql.map((dir) =>
463 command(`graphql (${dir})`, ["run", "--filter", `./${dir}`, "generate", "--check"]),
464 ),
465 ...(affected.length > 0
466 ? [
467 {
468 // `tsc --noEmit` writes nothing another package reads, so dependency order
469 // only made dependents wait: --parallel cut a contracts change from 13 s to 9 s.
470 ...command(`typecheck (${affected.length} packages)`, [
471 "run",
472 "--cache",
473 "--parallel",
474 "--concurrency-limit",
475 String(typecheckWorkers),
476 ...filters(affected),
477 "typecheck",
478 ]),
479 weight: typecheckWorkers,
480 },
481 ]
482 : []),
483 // From the repo root, the root vite.config.ts hands each file to its package's config.
484 ...(vitestTests.length > 0
485 ? [
486 {
487 ...command(`test (${vitestTests.length} files)`, [
488 "test",
489 "run",
490 "--passWithNoTests",
491 ...vitestTests,
492 ]),
493 serial: true,
494 },
495 ]
496 : []),
497 ...(nodeTests.length > 0
498 ? [
499 command(`node --test (${nodeTests.length} files)`, [
500 "exec",
501 "node",
502 "--test",
503 ...nodeTests,
504 ]),
505 ]
506 : []),
507 ...(compilerApps.length > 0
508 ? [
509 {
510 ...command(`react compiler (${compilerFiles} files)`, [
511 "test",
512 "run",
513 ...compilerApps.map((app) => app.test),
514 "-t",
515 compilerApps.flatMap((app) => app.pattern).join("|"),
516 ]),
517 serial: true,
518 },
519 ]
520 : []),
521 ];
522​
523 const results = yield* runSteps(steps, { concurrency, timeoutSeconds });
524​
525 const summary = ["check:changed summary"];
526 for (const result of results) {
527 summary.push(` ${result.outcome} ${result.name} ${result.time}`);
528 }
529 if (results.some((result) => result.outcome === "TIMEOUT")) {
530 summary.push(
531 ` TIMEOUT: ran past ${timeoutSeconds}s and was killed; this is not a check failure. ` +
532 "Raise --timeout or lower --concurrency.",
533 );
534 }
535 const ciOnly = Object.entries({
536 "full test suites": outputs.test || outputs.test_web || outputs.test_server,
537 build: outputs.build,
538 rust: outputs.rust,
539 "mobile native lint": outputs.mobile_native,
540 "release smoke": outputs.release_smoke,
541 }).flatMap(([job, runs]) => (runs ? [job] : []));
542 if (ciOnly.length > 0) summary.push(` CI also runs: ${ciOnly.join(", ")}`);
543 if (!runPatchCheck) summary.push(" unused patch check skipped: no dependency files changed");
544 if (!runKnip) summary.push(" knip skipped: no code or manifest changed");
545 yield* Console.log(`\n${summary.join("\n")}`);
546​
547 if (results.some((result) => result.outcome !== "pass")) return false;
548 if ((yield* inputKey) !== key) {
549 yield* Console.log(" pass not cached: files changed during the run");
550 return true;
551 }
552 // Write then rename, so a concurrent run never reads half a file.
553 const temp = `${cachePath}.${process.pid}`;
554 yield* Effect.gen(function* () {
555 yield* fs.makeDirectory(path.dirname(cachePath), { recursive: true });
556 yield* fs.writeFileString(temp, yield* encodeCacheEntry({ key, summary }));
557 yield* fs.rename(temp, cachePath);
558 }).pipe(Effect.catch((error) => Console.warn(` pass not cached: ${error.message}`)));
559 return true;
560});
561​
562export const checkChangedCommand = Command.make(
563 "check-changed",
564 {
565 ref: Argument.String("ref").pipe(
566 Argument.withDescription("Compare against the merge base with this ref."),
567 Argument.optional,
568 ),
569 concurrency: Flag.Int("concurrency").pipe(
570 Flag.withDescription(
571 "Budget of parallel steps and typecheck workers; also CHECK_CHANGED_CONCURRENCY. Defaults to one per two cores and per 6 GiB of available memory.",
572 ),
573 Flag.optional,
574 ),
575 timeout: Flag.Int("timeout").pipe(
576 Flag.withDescription(
577 "Seconds before a step is killed; also CHECK_CHANGED_TIMEOUT. Defaults to 900.",
578 ),
579 Flag.optional,
580 ),
581 },
582 (input) =>
583 checkChanged(input).pipe(
584 Effect.catch((message) => Console.error(message).pipe(Effect.as(false))),
585 // exitCode, not a failed exit: runMain calls process.exit() on failure, and
586 // piped stdout is asynchronous on macOS, so it would cut off step output.
587 Effect.flatMap((ok) =>
588 Effect.sync(() => {
589 if (!ok) process.exitCode = 1;
590 }),
591 ),
592 ),
593).pipe(Command.withDescription("Run CI's fast checks for this branch's changes."));
594​
595if (import.meta.main) {
596 Command.run(checkChangedCommand, { version: "0.0.0" }).pipe(
597 Effect.provide(NodeServices.layer),
598 NodeRuntime.runMain,
599 );