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

check-changed.ts

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