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("passes each test once when git and the sibling scan spell it with different separators", () => {
166 assert.deepStrictEqual(
167 splitTests([
168 "scripts/check-changed.test.ts",
169 NodePath.win32.join("scripts", "check-changed.test.ts"),
170 ".github/scripts/ci-changes.test.cjs",
171 NodePath.win32.join(".github", "scripts", "ci-changes.test.cjs"),
172 ]),
173 {
174 vitestTests: ["scripts/check-changed.test.ts"],
175 nodeTests: [".github/scripts/ci-changes.test.cjs"],
176 },
177 );
178 });
179
180 it.effect("fails instead of returning an empty file list when git exits nonzero", () => {
181 const spawner = (exitCode: number) =>
182 ChildProcessSpawner.make(() =>
183 Effect.succeed(
184 ChildProcessSpawner.makeHandle({
185 pid: ChildProcessSpawner.ProcessId(1),
186 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
187 exitStatus: Effect.succeed({
188 _tag: "Exited",
189 code: ChildProcessSpawner.ExitCode(exitCode),
190 }),
191 isRunning: Effect.succeed(false),
192 kill: () => Effect.void,
193 unref: Effect.succeed(Effect.void),
194 stdin: Sink.drain,
195 stdout: Stream.encodeText(Stream.make(exitCode === 0 ? "a.ts\nb.ts\n" : "")),
196 stderr: Stream.encodeText(
197 Stream.make(exitCode === 0 ? "" : "fatal: index file corrupt"),
198 ),
199 all: Stream.empty,
200 getInputFd: () => Sink.drain,
201 getOutputFd: () => Stream.empty,
202 }),
203 ),
204 );
205 return Effect.gen(function* () {
206 const listed = yield* gitLines("/repo", ["ls-files"]).pipe(
207 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(0)),
208 );
209 assert.deepStrictEqual(listed, ["a.ts", "b.ts"]);
210 const error = yield* gitLines("/repo", ["ls-files"]).pipe(
211 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(128)),
212 Effect.flip,
213 );
214 assert.strictEqual(
215 error,
216 "check:changed: git ls-files exited with 128: fatal: index file corrupt",
217 );
218 });
219 });
220
221 it("opens the built desktop app only for startup, settlement, and sidebar changes", () => {
222 const packages = readWorkspace();
223 const launches = (file: string) => decide([file], packages, false).outputs.desktop_launch;
224 for (const file of [
225 "apps/server/src/orchestration-v2/ThreadSettlementService.ts",
226 "apps/server/src/persistence/Migrations/054_ProjectionThreadsAutoSettleDisabledAt.ts",
227 "apps/web/src/components/sidebar/SidebarThreadRow.tsx",
228 "apps/desktop/src/backend/DesktopBackendManager.ts",
229 "apps/desktop/src/electron/ElectronProtocol.ts",
230 "packages/contracts/src/settings.ts",
231 "scripts/fixtures/desktop-launch/statev2.sqlite",
232 ]) {
233 assert.isTrue(launches(file), file);
234 }
235 for (const file of [
236 "apps/server/src/orchestration-v2/ThreadSettlementService.test.ts",
237 "apps/web/src/components/chat/ChatView.tsx",
238 "apps/desktop/src/updates/DesktopRemoteUpdates.ts",
239 "packages/contracts/src/orchestration.ts",
240 ]) {
241 assert.isFalse(launches(file), file);
242 }
243 // A script-only change still builds the app it opens.
244 assert.isTrue(decide(["scripts/smoke-desktop-app.ts"], packages, false).outputs.build);
245 });
246
247 it.each([
248 "packages/shared/src/testing/longTempDir.ts",
249 "packages/shared/src/testing/providerEnv.ts",
250 "packages/shared/src/testing/gitEnv.ts",
251 "packages/shared/src/testing/gitRepositoryEnv.ts",
252 ])("tests every package when the shared test setup file %s changes", (file) => {
253 assert.strictEqual(decide([file], readWorkspace(), false).outputs.test_packages, "");
254 });
255});
256
257// Hooks export GIT_DIR and GIT_INDEX_FILE, and user config or the default
258// ~/.config/git/ignore can ignore or sign fixture files.
259// Git for Windows rejects the null device as a config path, so use an empty file.
260const emptyConfigDir = NodeFS.mkdtempSync(
261 NodePath.join(NodeOS.tmpdir(), "t3-check-changed-config-"),
262);
263const emptyConfig = NodePath.join(emptyConfigDir, "empty.gitconfig");
264NodeFS.writeFileSync(emptyConfig, "");
265afterAll(() => NodeFS.rmSync(emptyConfigDir, { recursive: true, force: true }));
266const fixtureConfig = {
267 "core.excludesFile": emptyConfig,
268 "user.name": "Fixture",
269 "user.email": "fixture@example.invalid",
270};
271const env = {
272 ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_"))),
273 GIT_CONFIG_GLOBAL: emptyConfig,
274 GIT_CONFIG_NOSYSTEM: "1",
275 GIT_CONFIG_COUNT: String(Object.keys(fixtureConfig).length),
276 ...Object.fromEntries(
277 Object.entries(fixtureConfig).flatMap(([key, value], index) => [
278 [`GIT_CONFIG_KEY_${index}`, key],
279 [`GIT_CONFIG_VALUE_${index}`, value],
280 ]),
281 ),
282};
283
284// History A -> B -> C, with HEAD at C. Each remote's main points at A or B.
285function fixture(remotes: Record<string, "A" | "B">) {
286 const root = NodeFS.realpathSync(
287 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-check-changed-")),
288 );
289 const commits: Record<string, string> = {};
290 try {
291 const write = (file: string, content: string) => {
292 const path = NodePath.join(root, file);
293 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
294 NodeFS.writeFileSync(path, content);
295 };
296 const git = (...args: Array<string>) =>
297 NodeChildProcess.execFileSync("git", args, { cwd: root, encoding: "utf8", env }).trim();
298 git("init");
299 for (const name of ["A", "B", "C"]) {
300 write(`${name}.txt`, name);
301 git("add", ".");
302 git("commit", "-m", name);
303 commits[name] = git("rev-parse", "HEAD");
304 }
305 for (const [remote, commit] of Object.entries(remotes)) {
306 git("remote", "add", remote, NodePath.join(root, "missing"));
307 git("update-ref", `refs/remotes/${remote}/main`, commits[commit]!);
308 }
309 } catch (error) {
310 NodeFS.rmSync(root, { recursive: true, force: true });
311 throw error;
312 }
313 return {
314 commits,
315 root,
316 [Symbol.dispose]() {
317 NodeFS.rmSync(root, { recursive: true, force: true });
318 },
319 };
320}
321
322const inFixture = <A, E>(effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>) =>
323 Effect.gen(function* () {
324 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
325 return yield* effect.pipe(
326 Effect.provideService(
327 ChildProcessSpawner.ChildProcessSpawner,
328 ChildProcessSpawner.make((command) => spawner.spawn(ChildProcess.setEnv(command, env))),
329 ),
330 );
331 }).pipe(Effect.provide(NodeServices.layer), Effect.runPromise);
332const compare = (root: string, ref: Option.Option<string>) => inFixture(comparisonBase(root, ref));
333
334it.each(["upstream", "team/upstream"])(
335 "compares against %s/main when the fork's origin/main lags it",
336 async (remote) => {
337 using project = fixture({ origin: "A", [remote]: "B" });
338 const result = await compare(project.root, Option.none());
339 assert.strictEqual(result.base, project.commits.B);
340 assert.strictEqual(result.ref, remote + "/main");
341 },
342);
343
344it("compares against an explicit ref instead of the closest remote main", async () => {
345 using project = fixture({ origin: "A", upstream: "B" });
346 const result = await compare(project.root, Option.some("origin/main"));
347 assert.strictEqual(result.base, project.commits.A);
348 assert.strictEqual(result.ref, "origin/main");
349});
350
351it("lists the ignored inputs that main's pathspecs list, without entering node_modules", async () => {
352 using project = fixture({});
353 const git = (...args: Array<string>) =>
354 NodeChildProcess.execFileSync("git", args, { cwd: project.root, encoding: "utf8", env });
355 const write = (file: string, content = "") => {
356 NodeFS.mkdirSync(NodePath.dirname(NodePath.join(project.root, file)), { recursive: true });
357 NodeFS.writeFileSync(NodePath.join(project.root, file), content);
358 };
359 write(".gitignore", "node_modules/\ndist/\n.generated/\n.env*\n*.gen.d.ts\nreplaced/\nskipped/");
360 for (const file of ["replaced", "skipped"]) write(file);
361 git("add", ".");
362 git("commit", "-m", "files that directories replace");
363 git("update-index", "--skip-worktree", "skipped");
364 for (const file of ["replaced", "skipped"]) NodeFS.rmSync(NodePath.join(project.root, file));
365 for (const file of [
366 ".env.local",
367 "src/types.gen.d.ts",
368 "src/.generated/routes.ts",
369 "dist/index.d.ts",
370 "dist/node_modules/pkg/index.d.ts",
371 "node_modules/pkg/index.d.ts",
372 // A package folder left behind by a branch switch.
373 "old/dist/a.d.ts",
374 "old/node_modules/pkg/index.d.ts",
375 "replaced/sub/a.d.ts",
376 "skipped/a.d.ts",
377 ])
378 write(file);
379 const command =
380 "ls-files -o -i --exclude-standard -- :(glob)**/.generated/** :(glob)**/.astro/** :(glob)**/*.d.ts :(glob)**/.env* :(exclude,glob)**/node_modules/**";
381 const old = git(...command.split(" "))
382 .split("\n")
383 .filter(Boolean)
384 .sort();
385 assert.includeMembers(old, ["old/dist/a.d.ts", "replaced/sub/a.d.ts", "skipped/a.d.ts"]);
386 assert.deepStrictEqual(await inFixture(ignoredCheckInputs(project.root)), old);
387});
388
389function launcherFixture() {
390 const root = NodeFS.realpathSync(
391 NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3 checks & (fixture) ")),
392 );
393 const write = (file: string, content: string) => {
394 const path = NodePath.join(root, file);
395 NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true });
396 NodeFS.writeFileSync(path, content);
397 };
398 for (const file of [
399 "scripts/check-changed.ts",
400 "scripts/check-changed-command.ts",
401 ".github/scripts/ci-changes.cjs",
402 ]) {
403 write(file, NodeFS.readFileSync(NodePath.join(import.meta.dirname, "..", file), "utf8"));
404 }
405 write(".gitignore", "node_modules/\nrecords/\n");
406 write("pnpm-workspace.yaml", "packages:\n - packages/*\n");
407 write("package.json", JSON.stringify({ type: "module" }));
408 write("packages/example/package.json", JSON.stringify({ name: "example" }));
409 const source = "packages/example/space & (draft) %PATH% ! 研究.ts";
410 write(source, "export const value = 1;\n");
411 write(
412 "node_modules/vite-plus/package.json",
413 JSON.stringify({ type: "module", exports: { "./bin": "./cli.js" } }),
414 );
415 write(
416 "node_modules/vite-plus/cli.js",
417 `
418 import fs from 'node:fs';
419 import path from 'node:path';
420 const args = process.argv.slice(2);
421 fs.writeFileSync(path.join(process.env.RECORDS, process.pid + '.json'), JSON.stringify({ args, cwd: process.cwd() }));
422 console.log('fixture stdout: ' + args[0]);
423 console.error('fixture stderr: ' + args[0]);
424 process.exit(args[0] === process.env.FAIL_STEP ? 23 : 0);
425 `,
426 );
427 // Select the Windows launcher without changing the Effect runtime's host platform.
428 write(
429 "scripts/check-changed.ts",
430 NodeFS.readFileSync(NodePath.join(import.meta.dirname, "check-changed.ts"), "utf8").replace(
431 "vitePlusCommand(args, platform)",
432 'vitePlusCommand(args, "win32")',
433 ),
434 );
435 for (const name of ["effect", "@effect/platform-node", "@t3tools/shared"]) {
436 const dest = NodePath.join(root, "node_modules", name);
437 NodeFS.mkdirSync(NodePath.dirname(dest), { recursive: true });
438 NodeFS.symlinkSync(
439 NodeFS.realpathSync(NodePath.join(import.meta.dirname, "node_modules", name)),
440 dest,
441 "junction",
442 );
443 }
444 const git = (...args: Array<string>) =>
445 NodeChildProcess.execFileSync("git", args, { cwd: root, stdio: "pipe", env });
446 git("init");
447 git("add", ".");
448 git(
449 "-c",
450 "user.name=Fixture",
451 "-c",
452 "user.email=fixture@example.invalid",
453 "-c",
454 "commit.gpgsign=false",
455 "-c",
456 "core.hooksPath=",
457 "commit",
458 "-m",
459 "fixture",
460 );
461 const records = NodePath.join(root, "records");
462 NodeFS.mkdirSync(records);
463 return {
464 root,
465 source,
466 write,
467 run(failStep = "") {
468 return NodeChildProcess.spawnSync(process.execPath, ["scripts/check-changed.ts", "HEAD"], {
469 cwd: root,
470 encoding: "utf8",
471 env: { ...env, TEMP: NodeOS.tmpdir(), RECORDS: records, FAIL_STEP: failStep },
472 });
473 },
474 calls: (): Array<{ args: Array<string>; cwd: string }> =>
475 NodeFS.readdirSync(records).map((file) =>
476 JSON.parse(NodeFS.readFileSync(NodePath.join(records, file), "utf8")),
477 ),
478 [Symbol.dispose]() {
479 NodeFS.rmSync(root, { recursive: true, force: true });
480 },
481 };
482}
483
484it("checks changed source paths through the Windows launcher", () => {
485 using project = launcherFixture();
486 project.write(project.source, "export const value = 2;\n");
487 const result = project.run();
488 expect(result.status, result.stdout + result.stderr).toBe(0);
489 const calls = project.calls();
490 expect(calls.find(({ args }) => args[0] === "lint")).toEqual({
491 args: ["lint", "--no-error-on-unmatched-pattern", project.source],
492 cwd: project.root,
493 });
494 expect(calls.some(({ args }) => args[0] === "fmt" && args.includes(project.source))).toBe(true);
495 expect(calls.some(({ args }) => args[0] === "run" && args.includes("typecheck"))).toBe(true);
496 expect(calls.some(({ args }) => args[0] === "install")).toBe(false);
497 expect(result.stdout).toContain("fixture stdout: lint");
498 expect(result.stdout).toContain("fixture stderr: lint");
499});
500
501it("lints an Astro component and runs knip when only it changed", () => {
502 using project = launcherFixture();
503 const page = "packages/example/Page.astro";
504 project.write(page, "---\nconst title = 1;\n---\n<h1>{title}</h1>\n");
505 const result = project.run();
506 expect(result.status, result.stdout + result.stderr).toBe(0);
507 const calls = project.calls();
508 expect(calls.find(({ args }) => args[0] === "lint")?.args).toEqual([
509 "lint",
510 "--no-error-on-unmatched-pattern",
511 page,
512 ]);
513 expect(calls.map(({ args }) => args)).toContainEqual(["run", "knip:check"]);
514});
515
516it.each(["install", "lint"])("reports a failing %s step with its output", (step) => {
517 using project = launcherFixture();
518 project.write(project.source, "export const value = 2;\n");
519 project.write(
520 "packages/example/package.json",
521 JSON.stringify({ name: "example", version: "1.0.1" }),
522 );
523 const result = project.run(step);
524 expect(result.status, result.stdout + result.stderr).toBe(1);
525 const install = project.calls().find(({ args }) => args[0] === "install");
526 expect(install?.args, result.stdout + result.stderr).toEqual([
527 "install",
528 "--lockfile-only",
529 "--ignore-scripts",
530 ]);
531 expect(install?.cwd).not.toBe(project.root);
532 expect(result.stdout + result.stderr).toContain(`fixture stdout: ${step}`);
533 expect(result.stdout + result.stderr).toContain(`fixture stderr: ${step}`);
534 expect(result.stdout).toContain(step === "install" ? "FAIL unused patches" : "FAIL lint");
535 if (step === "lint") expect(result.stdout).toContain("pass unused patches");
536 expect(
537 NodeFS.existsSync(NodePath.join(project.root, "node_modules/.cache/check-changed.json")),
538 ).toBe(false);
539});