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 96 to 97

Compare

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