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

check-changed.ts

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