Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed

Versions 8 to 318

Compare

+259 −0 in 1 place
new file, 259 lines
1+// The check for what a change reaches, for running by hand before a publish. The full check (abso.json's)
2+// still runs on every publish, in the merge queue; this one is only the quick local run, so agents don't run
3+// the whole suite by hand.
4+//
5+// npm run check:changed [-- file ...] (paths from the repo root; none: this folder's draft, from abso diff
6+// and abso status) --list says what it would run and runs nothing.
7+//
8+// What it runs, for the changed files:
9+// - tests: every test file that imports a changed file, through any number of imports, plus changed test
10+// files themselves. A changed file that isn't code (a fixture, a saved log) brings in the test files that
11+// name it.
12+// - typecheck: tsconfig.json, when it includes a changed file or anything that imports one, incrementally
13+// (its build info under node_modules/.cache), so a second run reads only what changed.
14+// - biome: the changed files only.
15+// A change to setup (package.json, the lockfile, tsconfig.json, abso.json, biome.json) runs the full check.
16+import { spawn, spawnSync } from "node:child_process";
17+import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
18+import { createRequire } from "node:module";
19+import { availableParallelism } from "node:os";
20+import { dirname, extname, join, matchesGlob, relative, resolve, sep } from "node:path";
21+import { fileURLToPath } from "node:url";
23+const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
25+/** Test runs: a folder, the test globs its npm test uses (from that folder), and node's extra arguments. */
26+const TESTS = [
27+ {
28+ cwd: ".",
29+ globs: [
30+ "src/**/*.test.ts",
31+ "worker/project/**/*.test.ts",
32+ "client/test/**/*.test.ts",
33+ "scripts/**/*.test.ts",
34+ "server/test/**/*.test.ts",
35+ ],
36+ args: ["--import", "./client/test/setup.ts"],
37+ },
38+];
39+/** Typechecks: a tsconfig, from the repo root. */
40+const TYPECHECKS = [{ tsconfig: "tsconfig.json" }, { tsconfig: "server/tsconfig.json" }];
41+/** Files whose change can reach anything: the full check runs instead. */
42+const SETUP = [
43+ "**/package.json",
44+ "**/package-lock.json",
45+ "**/tsconfig*.json",
46+ "abso.json",
47+ "biome.json",
48+ "biome.jsonc",
49+ "client/test/setup.ts",
50+];
51+const SKIP_DIRS = new Set(["node_modules", ".abso", ".wrangler", "dist", ".git"]);
52+const CODE = new Set([".ts", ".tsx", ".mts", ".mjs", ".js", ".cjs"]);
54+const posix = (p) => p.split(sep).join("/");
55+const matches = (path, globs) => globs.some((g) => matchesGlob(path, g));
57+/** Every file under the repo, posix paths from the root, skipping dependency and build folders. */
58+function allFiles(dir = root, out = []) {
59+ for (const name of readdirSync(dir)) {
60+ if (SKIP_DIRS.has(name)) continue;
61+ const p = join(dir, name);
62+ const s = statSync(p);
63+ if (s.isDirectory()) allFiles(p, out);
64+ else out.push(posix(relative(root, p)));
65+ }
66+ return out;
67+}
69+/**
70+ * Each code file's imports, kept between runs in node_modules/.cache by the file's time and size, so a run
71+ * reads only the files that changed since the last one.
72+ */
73+const CACHE = join(root, "node_modules/.cache/check-changed.json");
74+function importGraph(code, known) {
75+ let cache = {};
76+ try {
77+ cache = JSON.parse(readFileSync(CACHE, "utf8"));
78+ } catch {}
79+ const next = {};
80+ const importers = new Map();
81+ for (const f of code) {
82+ const s = statSync(join(root, f));
83+ const hit = cache[f];
84+ const imports = hit && hit.t === s.mtimeMs && hit.n === s.size ? hit.i : importsOf(f, known);
85+ next[f] = { t: s.mtimeMs, n: s.size, i: imports };
86+ for (const i of imports) (importers.get(i) ?? importers.set(i, new Set()).get(i)).add(f);
87+ }
88+ try {
89+ mkdirSync(dirname(CACHE), { recursive: true });
90+ writeFileSync(CACHE, JSON.stringify(next));
91+ } catch {}
92+ return importers;
93+}
95+/** The files a code file imports, as repo paths (relative imports only; packages can't change in a draft). */
96+function importsOf(file, known) {
97+ const text = readFileSync(join(root, file), "utf8");
98+ const out = [];
99+ const re = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["'](\.{1,2}\/[^"']+)["']/g;
100+ for (const m of text.matchAll(re)) {
101+ const base = posix(join(dirname(file), m[1]));
102+ const stem = base.replace(/\.(m?js|cjs)$/, "");
103+ for (const c of [base, `${stem}.ts`, `${stem}.tsx`, `${stem}.mts`, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`])
104+ if (known.has(c)) {
105+ out.push(c);
106+ break;
107+ }
108+ }
109+ return out;
110+}
112+/** This folder's changed files: the draft's, from abso diff, and edits not yet recorded, from abso status. */
113+function draftFiles() {
114+ const run = (args) => {
115+ // One command string: abso is a .cmd on Windows, which needs a shell, and the args are fixed words.
116+ const r = spawnSync(`abso ${args.join(" ")}`, { cwd: root, encoding: "utf8", shell: true });
117+ if (r.status !== 0) throw new Error(`abso ${args.join(" ")} failed: ${(r.stderr || r.stdout).trim()}`);
118+ return r.stdout;
119+ };
120+ const files = new Set();
121+ for (const m of run(["diff"]).matchAll(/^(?:\+\+\+ b|--- a)\/(.+)$/gm)) files.add(m[1].trim());
122+ const unrecorded = /^Not yet recorded[^:]*:\s*(.+)$/m.exec(run(["status"]));
123+ if (unrecorded) for (const f of unrecorded[1].split(/,\s*/)) files.add(f.trim());
124+ return [...files].filter(Boolean);
125+}
127+/**
128+ * A tsconfig's JSON. Plain JSON is read as it is; one with comments goes through TypeScript's reader, loaded
129+ * only then, since loading TypeScript takes seconds on a busy machine.
130+ */
131+function readTsconfig(path) {
132+ const text = readFileSync(path, "utf8");
133+ try {
134+ return JSON.parse(text);
135+ } catch {
136+ const ts = createRequire(join(root, "package.json"))("typescript");
137+ return ts.parseConfigFileTextToJson(path, text).config ?? {};
138+ }
139+}
141+/** What the changed files reach: test files to run per test group, tsconfigs to check, files for biome. */
142+export function plan(changed, files = allFiles()) {
143+ const known = new Set(files);
144+ if (changed.some((f) => matches(f, SETUP))) return { full: changed.filter((f) => matches(f, SETUP)) };
145+ const code = files.filter((f) => CODE.has(extname(f)) && !f.endsWith(".d.ts"));
146+ const importers = importGraph(code, known);
147+ // Everything that imports a changed file, through any number of imports.
148+ const reached = new Set(changed.filter((f) => known.has(f)));
149+ const queue = [...reached];
150+ while (queue.length)
151+ for (const by of importers.get(queue.pop()) ?? []) if (!reached.has(by)) reached.add(by), queue.push(by);
152+ // A changed file that isn't code: the test files that name it.
153+ const tests = TESTS.map((t) => ({ ...t, files: [] }));
154+ const owner = (f) =>
155+ tests.find(
156+ (t) =>
157+ (t.cwd === "." || f.startsWith(`${t.cwd}/`)) && matches(t.cwd === "." ? f : f.slice(t.cwd.length + 1), t.globs),
158+ );
159+ const allTests = files.filter((f) => owner(f));
160+ for (const f of changed.filter((c) => known.has(c) && !CODE.has(extname(c)))) {
161+ const name = f.split("/").pop();
162+ for (const t of allTests) if (readFileSync(join(root, t), "utf8").includes(name)) reached.add(t);
163+ }
164+ for (const f of reached) {
165+ const t = owner(f);
166+ if (t) t.files.push(t.cwd === "." ? f : f.slice(t.cwd.length + 1));
167+ }
168+ const typechecks = TYPECHECKS.filter((c) => {
169+ const cfg = readTsconfig(join(root, c.tsconfig));
170+ const dir = posix(dirname(c.tsconfig));
171+ const inc = (cfg.include ?? ["**/*"]).map((g) => posix(join(dir, g)));
172+ const exc = (cfg.exclude ?? []).map((g) => posix(join(dir, g)));
173+ return [...reached].some((f) => matches(f, inc) && !matches(f, exc));
174+ });
175+ const lint = changed.filter((f) => known.has(f) && /\.(m?[jt]sx?|cjs|json|jsonc|css)$/.test(f));
176+ return { tests: tests.filter((t) => t.files.length), typechecks, lint };
177+}
179+/** Runs one command, its output kept, and resolves with its exit and time. */
180+function runOne(name, cmd, args, cwd) {
181+ const started = Date.now();
182+ return new Promise((done) => {
183+ const child = spawn(cmd, args, { cwd: join(root, cwd) });
184+ let out = "";
185+ child.stdout.on("data", (d) => (out += d));
186+ child.stderr.on("data", (d) => (out += d));
187+ child.on("close", (code) => done({ name, code, out, ms: Date.now() - started }));
188+ });
189+}
191+async function main() {
192+ const argv = process.argv.slice(2);
193+ const listOnly = argv.includes("--list");
194+ const given = argv.filter((a) => a !== "--list").map((a) => posix(a).replace(/^\.\//, ""));
195+ const changed = given.length ? given : draftFiles();
196+ if (!changed.length) {
197+ console.log("Nothing changed in this folder: nothing to check.");
198+ return;
199+ }
200+ const p = plan(changed);
201+ if (p.full) {
202+ console.log(`Setup changed (${p.full.join(", ")}): running the full check.`);
203+ if (listOnly) return;
204+ const { check } = JSON.parse(readFileSync(join(root, "abso.json"), "utf8"));
205+ const r = spawnSync(check, { cwd: root, stdio: "inherit", shell: true });
206+ process.exit(r.status ?? 1);
207+ }
208+ const jobs = [];
209+ for (const t of p.tests)
210+ jobs.push({
211+ name: `test ${t.cwd} (${t.files.length} files)`,
212+ cmd: process.execPath,
213+ args: [...t.args, "--test", ...t.files],
214+ cwd: t.cwd,
215+ });
216+ for (const c of p.typechecks) {
217+ const info = `node_modules/.cache/tsc/${c.tsconfig.replace(/[/\\]/g, "_")}.tsbuildinfo`;
218+ jobs.push({
219+ name: `typecheck ${c.tsconfig}`,
220+ cmd: process.execPath,
221+ args: [
222+ join(root, "node_modules/typescript/bin/tsc"),
223+ "--noEmit",
224+ "-p",
225+ c.tsconfig,
226+ "--incremental",
227+ "--tsBuildInfoFile",
228+ info,
229+ ],
230+ cwd: ".",
231+ });
232+ }
233+ if (p.lint.length)
234+ jobs.push({
235+ name: `biome (${p.lint.length} files)`,
236+ cmd: process.execPath,
237+ args: [join(root, "node_modules/@biomejs/biome/bin/biome"), "check", "--no-errors-on-unmatched", ...p.lint],
238+ cwd: ".",
239+ });
240+ console.log(`Changed: ${changed.join(", ")}`);
241+ for (const j of jobs)
242+ console.log(
243+ ` ${j.name}${j.name.startsWith("test") ? `: ${j.args.filter((a) => /\.test\./.test(a)).join(" ")}` : ""}`,
244+ );
245+ if (listOnly || !jobs.length) return;
246+ const started = Date.now();
247+ const slots = Math.max(1, Number(process.env.ABSO_CHECK_SLOTS) || availableParallelism());
248+ const results = [];
249+ for (let i = 0; i < jobs.length; i += slots)
250+ results.push(...(await Promise.all(jobs.slice(i, i + slots).map((j) => runOne(j.name, j.cmd, j.args, j.cwd)))));
251+ for (const r of results.filter((r) => r.code !== 0)) console.log(`\n--- ${r.name} failed ---\n${r.out.trimEnd()}`);
252+ console.log("");
253+ for (const r of results)
254+ console.log(`${r.code === 0 ? "ok " : "FAIL"} ${(r.ms / 1000).toFixed(1).padStart(6)} s ${r.name}`);
255+ console.log(`${((Date.now() - started) / 1000).toFixed(1)} s in all. The full check runs when you push.`);
256+ if (results.some((r) => r.code !== 0)) process.exitCode = 1;
257+}
259+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();
MCP
compare on this site's /mcp
CLI
abso diff 8 318 scripts/check-changed.mjs --json
JSON
/christopher/abso-core/compare/8..318?file=scripts%2Fcheck-changed.mjs&format=json