@devries-cameron20 / t3code Mirror · read-only / commits / 8970a32104
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 12:00 UTC

fix(scripts): bound check:changed concurrency and step time (#27227)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

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