Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6import { expect } from "vite-plus/test";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as Option from "effect/Option";
9import { afterAll, assert, describe, it } from "@effect/vitest";
10import * as Clock from "effect/Clock";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Sink from "effect/Sink";
14import * as Stream from "effect/Stream";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16import * as TestClock from "effect/testing/TestClock";
17
18import {
19 comparisonBase,
20 defaultConcurrency,
21 docReaderTests,
22 gitLines,
23 ignoredCheckInputs,
24 runSteps,
25 splitTests,
26 type Step,
27} from "./check-changed.ts";
28import { decide, readWorkspace } from "../.github/scripts/ci-changes.cjs";
29
30const GiB = 1024 ** 3;
31
32describe("check:changed", () => {
33 it("bounds the default concurrency by the scarcer of cores and available memory", () => {
34 assert.strictEqual(defaultConcurrency(32, 128 * GiB), 16);
35 assert.strictEqual(defaultConcurrency(32, 20 * GiB), 3);
36 assert.strictEqual(defaultConcurrency(4, 15 * GiB), 2);
37 assert.strictEqual(defaultConcurrency(4, 2 * GiB), 1);
38 assert.strictEqual(defaultConcurrency(1, 64 * GiB), 1);
39 });
40
41 it("runs the server tests for the one guide they read and leaves other docs inert", () => {
42 const packages = readWorkspace();
43 assert.isTrue(
44 decide(["docs/user/t3-connect-troubleshooting.md"], packages, false).outputs.test_server,
45 );
46 assert.deepStrictEqual(docReaderTests(["docs/user/t3-connect-troubleshooting.md"]), [
47 "apps/server/src/cloud/ConnectReachability.test.ts",
48 ]);
49 assert.deepStrictEqual(decide(["docs/user/install.md"], packages, false).affected, []);
50 });
51
52 it.effect(
53 "keeps weighted steps within the budget, in order, and serial steps one at a time",
54 () =>
55 Effect.gen(function* () {
56 const startedAt: Record<string, number> = {};
57 let active = 0;
58 let maxActive = 0;
59 let serialActive = 0;
60 let maxSerial = 0;
61 const step = (
62 name: string,
63 options: { weight?: number; serial?: boolean } = {},
64 ): Step<never> => {
65 const slots = Math.min(options.weight ?? 1, 3);
66 return {
67 name,
68 ...options,
69 run: Effect.gen(function* () {
70 startedAt[name] = (yield* Clock.currentTimeMillis) / 1000;
71 active += slots;
72 maxActive = Math.max(maxActive, active);
73 if (options.serial) maxSerial = Math.max(maxSerial, ++serialActive);
74 yield* Effect.sleep("1 second");
75 active -= slots;
76 if (options.serial) serialActive--;
77 return { ok: true, output: "" };
78 }),
79 };
80 };
81 const fiber = yield* runSteps(
82 [
83 step("light 1"),
84 // Above the budget, so it holds every slot rather than never starting.
85 step("heavy", { weight: 5 }),
86 step("pair", { weight: 2 }),
87 step("light 2"),
88 step("test 1", { serial: true }),
89 step("test 2", { serial: true }),
90 ],
91 { concurrency: 3, timeoutSeconds: 60 },
92 ).pipe(Effect.forkChild);
93 yield* TestClock.adjust("10 seconds");
94 const results = yield* Fiber.join(fiber);
95
96 assert.deepStrictEqual(
97 results.map((result) => result.outcome),
98 ["pass", "pass", "pass", "pass", "pass", "pass"],
99 );
100 assert.strictEqual(maxActive, 3);
101 // Lighter steps queued behind the heavy one never start ahead of it.
102 assert.deepStrictEqual(startedAt, {
103 "light 1": 0,
104 heavy: 1,
105 pair: 2,
106 "light 2": 2,
107 "test 1": 3,
108 "test 2": 4,
109 });
110 assert.strictEqual(maxSerial, 1);
111 }),
112 );
113
114 it.effect("interrupts a step at its timeout and reports TIMEOUT, apart from FAIL", () =>
115 Effect.gen(function* () {
116 let interrupted = false;
117 const fiber = yield* runSteps(
118 [
119 {
120 name: "hangs",
121 run: Effect.never.pipe(
122 Effect.onInterrupt(() => Effect.sync(() => (interrupted = true))),
123 ),
124 },
125 { name: "fails", run: Effect.succeed({ ok: false, output: "error" }) },
126 { name: "passes", run: Effect.succeed({ ok: true, output: "" }) },
127 ],
128 { concurrency: 3, timeoutSeconds: 10 },
129 ).pipe(Effect.forkChild);
130 yield* TestClock.adjust("9 seconds");
131 assert.isFalse(interrupted);
132 yield* TestClock.adjust("1 second");
133 const results = yield* Fiber.join(fiber);
134
135 assert.isTrue(interrupted);
136 assert.deepStrictEqual(
137 results.map(({ name, outcome, time }) => [name, outcome, time]),
138 [
139 ["hangs", "TIMEOUT", "killed after 10s"],
140 ["fails", "FAIL", "0.0s"],
141 ["passes", "pass", "0.0s"],
142 ],
143 );
144 }),
145 );
146
147 it("runs the .github/scripts node:test files with node --test, not vitest", () => {
148 assert.deepStrictEqual(
149 splitTests([
150 "apps/server/src/ws.test.ts",
151 ".github/scripts/ci-changes.test.cjs",
152 ".github\\scripts\\thread-transfer-report.test.cjs",
153 "scripts/check-changed.test.ts",
154 ]),
155 {
156 vitestTests: ["apps/server/src/ws.test.ts", "scripts/check-changed.test.ts"],
157 nodeTests: [
158 ".github/scripts/ci-changes.test.cjs",
159 ".github\\scripts\\thread-transfer-report.test.cjs",
160 ],
161 },
162 );
163 });
164
165 it.effect("fails instead of returning an empty file list when git exits nonzero", () => {
166 const spawner = (exitCode: number) =>
167 ChildProcessSpawner.make(() =>
168 Effect.succeed(
169 ChildProcessSpawner.makeHandle({
170 pid: ChildProcessSpawner.ProcessId(1),
171 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
172 isRunning: Effect.succeed(false),
173 kill: () => Effect.void,
174 unref: Effect.succeed(Effect.void),
175 stdin: Sink.drain,
176 stdout: Stream.encodeText(Stream.make(exitCode === 0 ? "a.ts\nb.ts\n" : "")),
177 stderr: Stream.encodeText(
178 Stream.make(exitCode === 0 ? "" : "fatal: index file corrupt"),
179 ),
180 all: Stream.empty,
181 getInputFd: () => Sink.drain,
182 getOutputFd: () => Stream.empty,
183 }),
184 ),
185 );
186 return Effect.gen(function* () {
187 const listed = yield* gitLines("/repo", ["ls-files"]).pipe(
188 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(0)),
189 );
190 assert.deepStrictEqual(listed, ["a.ts", "b.ts"]);
191 const error = yield* gitLines("/repo", ["ls-files"]).pipe(
192 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(128)),
193 Effect.flip,
194 );
195 assert.strictEqual(
196 error,
197 "check:changed: git ls-files exited with 128: fatal: index file corrupt",
198 );
199 });
200 });
201
202 it("opens the built desktop app only for startup, settlement, and sidebar changes", () => {
203 const packages = readWorkspace();
204 const launches = (file: string) => decide([file], packages, false).outputs.desktop_launch;
205 for (const file of [
206 "apps/server/src/orchestration-v2/ThreadSettlementService.ts",
207 "apps/server/src/persistence/Migrations/054_ProjectionThreadsAutoSettleDisabledAt.ts",
208 "apps/web/src/components/sidebar/SidebarThreadRow.tsx",
209 "apps/desktop/src/backend/DesktopBackendManager.ts",
210 "apps/desktop/src/electron/ElectronProtocol.ts",
211 "packages/contracts/src/settings.ts",
212 "scripts/fixtures/desktop-launch/statev2.sqlite",
213 ]) {
214 assert.isTrue(launches(file), file);
215 }
216 for (const file of [
217 "apps/server/src/orchestration-v2/ThreadSettlementService.test.ts",
218 "apps/web/src/components/chat/ChatView.tsx",
219 "apps/desktop/src/updates/DesktopRemoteUpdates.ts",
220 "packages/contracts/src/orchestration.ts",
221 ]) {
222 assert.isFalse(launches(file), file);
223 }
224 // A script-only change still builds the app it opens.
225 assert.isTrue(decide(["scripts/smoke-desktop-app.ts"], packages, false).outputs.build);
226 });
227
228 it.each([
229 "packages/shared/src/testing/longTempDir.ts",
230 "packages/shared/src/testing/providerEnv.ts",
231 ])("tests every package when the shared test setup file %s changes", (file) => {
232 assert.strictEqual(decide([file], readWorkspace(), false).outputs.test_packages, "");
233 });
234});
235
236// Hooks export GIT_DIR and GIT_INDEX_FILE, and user config or the default
237// ~/.config/git/ignore can ignore or sign fixture files.
238// Git for Windows rejects the null device as a config path, so use an empty file.
239const emptyConfigDir = NodeFS.mkdtempSync(
240 NodePath.join(NodeOS.tmpdir(), "t3-check-changed-config-"),
241);
242const emptyConfig = NodePath.join(emptyConfigDir, "empty.gitconfig");
243NodeFS.writeFileSync(emptyConfig, "");
244afterAll(() => NodeFS.rmSync(emptyConfigDir, { recursive: true, force: true }));
245const fixtureConfig = {
246 "core.excludesFile": emptyConfig,
247 "user.name": "Fixture",
248 "user.email": "fixture@example.invalid",
249};
250const env = {
251 ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_"))),
252 GIT_CONFIG_GLOBAL: emptyConfig,
253 GIT_CONFIG_NOSYSTEM: "1",
254 GIT_CONFIG_COUNT: String(Object.keys(fixtureConfig).length),
255 ...Object.fromEntries(
256 Object.entries(fixtureConfig).flatMap(([key, value], index) => [
257 [`GIT_CONFIG_KEY_${index}`, key],
258 [`GIT_CONFIG_VALUE_${index}`, value],
259 ]),
260 ),
261};
262
263// History A -> B -> C, with HEAD at C. Each remote's main points at A or B.
264function fixture(remotes: Record<string, "A" | "B">) {
265 const root = NodeFS.realpathSync(
266 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-check-changed-")),
267 );
268 const commits: Record<string, string> = {};
269 try {
270 const write = (file: string, content: string) => {
271 const path = NodePath.join(root, file);
272 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
273 NodeFS.writeFileSync(path, content);
274 };
275 const git = (...args: Array<string>) =>
276 NodeChildProcess.execFileSync("git", args, { cwd: root, encoding: "utf8", env }).trim();
277 git("init");
278 for (const name of ["A", "B", "C"]) {
279 write(`${name}.txt`, name);
280 git("add", ".");
281 git("commit", "-m", name);
282 commits[name] = git("rev-parse", "HEAD");
283 }
284 for (const [remote, commit] of Object.entries(remotes)) {
285 git("remote", "add", remote, NodePath.join(root, "missing"));
286 git("update-ref", `refs/remotes/${remote}/main`, commits[commit]!);
287 }
288 } catch (error) {
289 NodeFS.rmSync(root, { recursive: true, force: true });
290 throw error;
291 }
292 return {
293 commits,
294 root,
295 [Symbol.dispose]() {
296 NodeFS.rmSync(root, { recursive: true, force: true });
297 },
298 };
299}
300
301const inFixture = <A, E>(effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>) =>
302 Effect.gen(function* () {
303 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
304 return yield* effect.pipe(
305 Effect.provideService(
306 ChildProcessSpawner.ChildProcessSpawner,
307 ChildProcessSpawner.make((command) => spawner.spawn(ChildProcess.setEnv(command, env))),
308 ),
309 );
310 }).pipe(Effect.provide(NodeServices.layer), Effect.runPromise);
311const compare = (root: string, ref: Option.Option<string>) => inFixture(comparisonBase(root, ref));
312
313it.each(["upstream", "team/upstream"])(
314 "compares against %s/main when the fork's origin/main lags it",
315 async (remote) => {
316 using project = fixture({ origin: "A", [remote]: "B" });
317 const result = await compare(project.root, Option.none());
318 assert.strictEqual(result.base, project.commits.B);
319 assert.strictEqual(result.ref, remote + "/main");
320 },
321);
322
323it("compares against an explicit ref instead of the closest remote main", async () => {
324 using project = fixture({ origin: "A", upstream: "B" });
325 const result = await compare(project.root, Option.some("origin/main"));
326 assert.strictEqual(result.base, project.commits.A);
327 assert.strictEqual(result.ref, "origin/main");
328});
329
330it("lists the ignored inputs that main's pathspecs list, without entering node_modules", async () => {
331 using project = fixture({});
332 const git = (...args: Array<string>) =>
333 NodeChildProcess.execFileSync("git", args, { cwd: project.root, encoding: "utf8", env });
334 const write = (file: string, content = "") => {
335 NodeFS.mkdirSync(NodePath.dirname(NodePath.join(project.root, file)), { recursive: true });
336 NodeFS.writeFileSync(NodePath.join(project.root, file), content);
337 };
338 write(".gitignore", "node_modules/\ndist/\n.generated/\n.env*\n*.gen.d.ts\nreplaced/\nskipped/");
339 for (const file of ["replaced", "skipped"]) write(file);
340 git("add", ".");
341 git("commit", "-m", "files that directories replace");
342 git("update-index", "--skip-worktree", "skipped");
343 for (const file of ["replaced", "skipped"]) NodeFS.rmSync(NodePath.join(project.root, file));
344 for (const file of [
345 ".env.local",
346 "src/types.gen.d.ts",
347 "src/.generated/routes.ts",
348 "dist/index.d.ts",
349 "dist/node_modules/pkg/index.d.ts",
350 "node_modules/pkg/index.d.ts",
351 // A package folder left behind by a branch switch.
352 "old/dist/a.d.ts",
353 "old/node_modules/pkg/index.d.ts",
354 "replaced/sub/a.d.ts",
355 "skipped/a.d.ts",
356 ])
357 write(file);
358 const command =
359 "ls-files -o -i --exclude-standard -- :(glob)**/.generated/** :(glob)**/.astro/** :(glob)**/*.d.ts :(glob)**/.env* :(exclude,glob)**/node_modules/**";
360 const old = git(...command.split(" "))
361 .split("\n")
362 .filter(Boolean)
363 .sort();
364 assert.includeMembers(old, ["old/dist/a.d.ts", "replaced/sub/a.d.ts", "skipped/a.d.ts"]);
365 assert.deepStrictEqual(await inFixture(ignoredCheckInputs(project.root)), old);
366});
367
368function launcherFixture() {
369 const root = NodeFS.realpathSync(
370 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3 checks & (fixture) ")),
371 );
372 const write = (file: string, content: string) => {
373 const path = NodePath.join(root, file);
374 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
375 NodeFS.writeFileSync(path, content);
376 };
377 for (const file of [
378 "scripts/check-changed.ts",
379 "scripts/check-changed-command.ts",
380 ".github/scripts/ci-changes.cjs",
381 ]) {
382 write(file, NodeFS.readFileSync(NodePath.join(import.meta.dirname, "..", file), "utf8"));
383 }
384 write(".gitignore", "node_modules/\nrecords/\n");
385 write("pnpm-workspace.yaml", "packages:\n - packages/*\n");
386 write(
387 "package.json",
388 JSON.stringify({
389 type: "module",
390 scripts: {
391 "knip:check:files": "knip --include files",
392 "knip:check:exports": "knip --exports",
393 },
394 }),
395 );
396 write("packages/example/package.json", JSON.stringify({ name: "example" }));
397 const source = "packages/example/space & (draft) %PATH% ! 研究.ts";
398 write(source, "export const value = 1;\n");
399 write(
400 "node_modules/vite-plus/package.json",
401 JSON.stringify({ type: "module", exports: { "./bin": "./cli.js" } }),
402 );
403 write(
404 "node_modules/vite-plus/cli.js",
405 `
406 import fs from 'node:fs';
407 import path from 'node:path';
408 const args = process.argv.slice(2);
409 fs.writeFileSync(path.join(process.env.RECORDS, process.pid + '.json'), JSON.stringify({ args, cwd: process.cwd() }));
410 console.log('fixture stdout: ' + args[0]);
411 console.error('fixture stderr: ' + args[0]);
412 process.exit(args[0] === process.env.FAIL_STEP ? 23 : 0);
413 `,
414 );
415 // Select the Windows launcher without changing the Effect runtime's host platform.
416 write(
417 "scripts/check-changed.ts",
418 NodeFS.readFileSync(NodePath.join(import.meta.dirname, "check-changed.ts"), "utf8").replace(
419 "vitePlusCommand(args, platform)",
420 'vitePlusCommand(args, "win32")',
421 ),
422 );
423 for (const name of ["effect", "@effect/platform-node", "@t3tools/shared"]) {
424 const dest = NodePath.join(root, "node_modules", name);
425 NodeFS.mkdirSync(NodePath.dirname(dest), { recursive: true });
426 NodeFS.symlinkSync(
427 NodeFS.realpathSync(NodePath.join(import.meta.dirname, "node_modules", name)),
428 dest,
429 "junction",
430 );
431 }
432 const git = (...args: Array<string>) =>
433 NodeChildProcess.execFileSync("git", args, { cwd: root, stdio: "pipe", env });
434 git("init");
435 git("add", ".");
436 git(
437 "-c",
438 "user.name=Fixture",
439 "-c",
440 "user.email=fixture@example.invalid",
441 "-c",
442 "commit.gpgsign=false",
443 "-c",
444 "core.hooksPath=",
445 "commit",
446 "-m",
447 "fixture",
448 );
449 const records = NodePath.join(root, "records");
450 NodeFS.mkdirSync(records);
451 return {
452 root,
453 source,
454 write,
455 run(failStep = "") {
456 return NodeChildProcess.spawnSync(process.execPath, ["scripts/check-changed.ts", "HEAD"], {
457 cwd: root,
458 encoding: "utf8",
459 env: { ...env, TEMP: NodeOS.tmpdir(), RECORDS: records, FAIL_STEP: failStep },
460 });
461 },
462 calls: (): Array<{ args: Array<string>; cwd: string }> =>
463 NodeFS.readdirSync(records).map((file) =>
464 JSON.parse(NodeFS.readFileSync(NodePath.join(records, file), "utf8")),
465 ),
466 [Symbol.dispose]() {
467 NodeFS.rmSync(root, { recursive: true, force: true });
468 },
469 };
470}
471
472it("checks changed source paths through the Windows launcher", () => {
473 using project = launcherFixture();
474 project.write(project.source, "export const value = 2;\n");
475 const result = project.run();
476 expect(result.status, result.stdout + result.stderr).toBe(0);
477 const calls = project.calls();
478 expect(calls.find(({ args }) => args[0] === "lint")).toEqual({
479 args: ["lint", "--no-error-on-unmatched-pattern", project.source],
480 cwd: project.root,
481 });
482 expect(calls.some(({ args }) => args[0] === "fmt" && args.includes(project.source))).toBe(true);
483 expect(calls.some(({ args }) => args[0] === "run" && args.includes("typecheck"))).toBe(true);
484 expect(calls.some(({ args }) => args[0] === "install")).toBe(false);
485 expect(result.stdout).toContain("fixture stdout: lint");
486 expect(result.stdout).toContain("fixture stderr: lint");
487});
488
489it("lints an Astro component and runs knip when only it changed", () => {
490 using project = launcherFixture();
491 const page = "packages/example/Page.astro";
492 project.write(page, "---\nconst title = 1;\n---\n<h1>{title}</h1>\n");
493 const result = project.run();
494 expect(result.status, result.stdout + result.stderr).toBe(0);
495 const calls = project.calls();
496 expect(calls.find(({ args }) => args[0] === "lint")?.args).toEqual([
497 "lint",
498 "--no-error-on-unmatched-pattern",
499 page,
500 ]);
501 const commands = calls.map(({ args }) => args);
502 expect(commands).toContainEqual(["exec", "knip", "--include", "files"]);
503 expect(commands).toContainEqual(["exec", "knip", "--exports"]);
504});
505
506it.each(["install", "lint"])("reports a failing %s step with its output", (step) => {
507 using project = launcherFixture();
508 project.write(project.source, "export const value = 2;\n");
509 project.write(
510 "packages/example/package.json",
511 JSON.stringify({ name: "example", version: "1.0.1" }),
512 );
513 const result = project.run(step);
514 expect(result.status, result.stdout + result.stderr).toBe(1);
515 const install = project.calls().find(({ args }) => args[0] === "install");
516 expect(install?.args, result.stdout + result.stderr).toEqual([
517 "install",
518 "--lockfile-only",
519 "--ignore-scripts",
520 ]);
521 expect(install?.cwd).not.toBe(project.root);
522 expect(result.stdout + result.stderr).toContain(`fixture stdout: ${step}`);
523 expect(result.stdout + result.stderr).toContain(`fixture stderr: ${step}`);
524 expect(result.stdout).toContain(step === "install" ? "FAIL unused patches" : "FAIL lint");
525 if (step === "lint") expect(result.stdout).toContain("pass unused patches");
526 expect(
527 NodeFS.existsSync(NodePath.join(project.root, "node_modules/.cache/check-changed.json")),
528 ).toBe(false);
529});