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