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