Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:white_check_mark: Select the tests a change can reach

Jeffrey Chend9b04bde80b2
diff --git a/AGENTS.md b/AGENTS.md
index 69856c2334..7ca3418382 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -41,7 +41,7 @@ Unambiguous mechanical edits with no behavioral or compatibility impact need no
3. **Kernel development:** After modifying Go code, run `gofmt`, but do not compile the kernel binary or restart a running kernel; the developer handles both manually. Isolated regression tests and contract generation are allowed; they must not replace the product binary or restart the running instance
4. **Git:** **NEVER** run `git commit` / `git push` unless explicitly asked — no exceptions
5. **UI verification in a browser:** Open `/stage/build/desktop/` directly instead of `/`. The kernel selects the frontend bundle by User-Agent in `kernel/server/serve.go`, and a UA containing `Electron` is redirected to the Electron-only `/stage/build/app/`, which fails in a plain browser with `require is not defined`; VSCode's built-in browser sends such a UA. The Electron main window does not expose a remote debugging port by default
-6. **Verification scope:** Run the checks and regression tests applicable to the changed behavior, including non-API Go code, frontend interactions, and scripts. Select scope according to impact and risk; a full suite is not required for every task, and lint or formatting alone does not establish behavioral correctness. Use `app/scripts/test.mjs` and the relevant maintenance guides to identify test discovery and commands. For documentation-only changes, check accuracy, links, language alignment, and the diff rather than running auto-fixing code checks. Report passed, failed, and unrun checks with their limits; do not infer that tests passed solely from a successful CI job or release
+6. **Verification scope:** Run the checks and regression tests applicable to the changed behavior, including non-API Go code, frontend interactions, and scripts. Select scope according to impact and risk; a full suite is not required for every task, and lint or formatting alone does not establish behavioral correctness. Use `app/scripts/test.mjs` and the relevant maintenance guides to identify test discovery and commands. For frontend changes, `pnpm run test:affected` from `app/` derives the affected tests from the changed files (it follows both imports and the source paths that tests read and evaluate themselves) and runs only those; `pnpm run test:changed` lists them without running. Fall back to the full suite when a change crosses many modules or touches shared setup, and say which scope you ran. For documentation-only changes, check accuracy, links, language alignment, and the diff rather than running auto-fixing code checks. Report passed, failed, and unrun checks with their limits; do not infer that tests passed solely from a successful CI job or release
7. **Test synchronization:** Whenever code or files change, handle the corresponding tests and fixtures in the same change rather than leaving them for later
- Rename, move, merge, split, or delete a test file together with its source, and keep the file name reflecting the code it covers; a test file whose source no longer exists or whose name no longer matches is stale and must be repaired or removed
- When behavior changes intentionally, update the affected assertions, case names, and comments to the new contract instead of dropping the coverage; when behavior is removed, delete only the cases that cover the removed behavior and keep adjacent assertions
diff --git a/app/package.json b/app/package.json
index 6dc7ce88c9..2a65a8db26 100644
--- a/app/package.json
+++ b/app/package.json
@@ -18,6 +18,8 @@
"api:generate": "node scripts/api-contracts.mjs",
"api:check": "node scripts/api-contracts.mjs --check",
"test": "node scripts/test.mjs",
+ "test:changed": "node scripts/test-changed.mjs",
+ "test:affected": "node scripts/test-changed.mjs --run",
"dev": "webpack --mode development --config webpack.config.js",
"dev:mobile": "webpack --mode development --config webpack.mobile.js",
"dev:desktop": "webpack --mode development --config webpack.desktop.js",
diff --git a/app/scripts/test-changed.mjs b/app/scripts/test-changed.mjs
new file mode 100644
index 0000000000..54c0fa1226
--- /dev/null
+++ b/app/scripts/test-changed.mjs
@@ -0,0 +1,158 @@
+// 只运行受改动影响的前端测试,避免每次运行完整套件(本机约 8 分钟)。
+//
+// 测试与源码的关联有两种形态,都必须覆盖:真实的 `import`,以及大量测试用字符串路径读取源码后再转译执行
+// (`load("src/x.ts")`、`readFileSync(path.join(__dirname, "../x.ts"))`)。只看 import 图会漏掉后者,
+// 而漏掉的正是共享模块改动这类最容易出回归的地方。
+import {execFileSync, spawnSync} from "node:child_process";
+import {existsSync, readFileSync, readdirSync, statSync} from "node:fs";
+import {createRequire} from "node:module";
+import {availableParallelism} from "node:os";
+import path from "node:path";
+
+const appRoot = path.resolve(import.meta.dirname, "..");
+// 与 scripts/test.mjs 的 glob 覆盖范围一致。
+const testRoots = ["src", "tests", "electron", "scripts"];
+const moduleExtensions = [".ts", ".js", ".mjs", ".scss", ".tpl"];
+
+export const isTestFile = (file) => /\.test\.(?:ts|js|mjs)$/.test(file);
+
+const walk = (directory) => readdirSync(directory).flatMap(name => {
+ const target = path.join(directory, name);
+ return statSync(target).isDirectory() ? walk(target) : [target];
+});
+
+// 取出文件里所有可能指向另一个文件的字符串:模块说明符,以及形如路径的字面量。
+export const scanReferences = (text) => {
+ const references = new Set();
+ for (const match of text.matchAll(/(?:from|require\s*\(|import\s*\()\s*["']([^"'\n]+)["']/g)) {
+ references.add(match[1]);
+ }
+ for (const match of text.matchAll(/["']((?:\.\.?\/)?(?:src|tests|electron|scripts)\/[^"'\n]+?\.(?:ts|js|mjs|scss|tpl))["']/g)) {
+ references.add(match[1]);
+ }
+ return [...references];
+};
+
+// 把说明符或路径字面量解析成 app 内的绝对路径;外部模块返回 undefined。
+export const resolveReference = (fromFile, reference, root = appRoot) => {
+ let base;
+ if (reference.startsWith(".")) {
+ base = path.resolve(path.dirname(fromFile), reference);
+ } else if (/^(?:src|tests|electron|scripts)\//.test(reference)) {
+ base = path.resolve(root, reference);
+ } else {
+ return undefined;
+ }
+ const candidates = [base];
+ for (const extension of moduleExtensions) {
+ candidates.push(base + extension, path.join(base, "index" + extension));
+ }
+ // `./x.js` 在实际源码里可能只存在 `./x.ts`。
+ if (base.endsWith(".js")) {
+ candidates.push(base.replace(/\.js$/, ".ts"));
+ }
+ return candidates.find(candidate => existsSync(candidate) && statSync(candidate).isFile());
+};
+
+// 收集 file -> 它直接引用的文件的依赖边。
+export const buildGraph = (files, root = appRoot) => {
+ const edges = new Map();
+ for (const file of files) {
+ let text;
+ try {
+ text = readFileSync(file, "utf8");
+ } catch {
+ continue;
+ }
+ const targets = new Set();
+ for (const reference of scanReferences(text)) {
+ const resolved = resolveReference(file, reference, root);
+ if (resolved && resolved !== file) {
+ targets.add(resolved);
+ }
+ }
+ edges.set(file, targets);
+ }
+ return edges;
+};
+
+// 从改动文件出发反向遍历,找出直接或间接引用它们的测试文件。
+export const selectTests = (changedFiles, allFiles, root = appRoot) => {
+ const reverse = new Map();
+ for (const [file, targets] of buildGraph(allFiles, root)) {
+ for (const target of targets) {
+ const list = reverse.get(target) ?? [];
+ list.push(file);
+ reverse.set(target, list);
+ }
+ }
+ const changed = new Set(changedFiles.map(file => path.resolve(file)));
+ const selected = new Set([...changed].filter(isTestFile));
+ const visited = new Set(changed);
+ const queue = [...changed];
+ while (queue.length > 0) {
+ for (const referrer of reverse.get(queue.pop()) ?? []) {
+ if (visited.has(referrer)) {
+ continue;
+ }
+ visited.add(referrer);
+ queue.push(referrer);
+ if (isTestFile(referrer)) {
+ selected.add(referrer);
+ }
+ }
+ }
+ return [...selected].sort();
+};
+
+export const listFiles = () => testRoots
+ .map(root => path.join(appRoot, root))
+ .filter(directory => existsSync(directory))
+ .flatMap(walk)
+ .filter(file => moduleExtensions.some(extension => file.endsWith(extension)));
+
+const repositoryRoot = path.resolve(appRoot, "..");
+
+const changedFiles = (base) => {
+ // `git diff --name-only <base>` 覆盖已提交的分支改动,未跟踪文件需单独收集。
+ const run = (arguments_) => execFileSync("git", arguments_, {cwd: repositoryRoot, encoding: "utf8"});
+ const files = [
+ ...run(["diff", "--name-only", base]).split("\n"),
+ ...run(["ls-files", "--others", "--exclude-standard"]).split("\n"),
+ ].filter(Boolean);
+ return files.map(file => path.resolve(repositoryRoot, file)).filter(file => existsSync(file));
+};
+
+const main = () => {
+ const arguments_ = process.argv.slice(2);
+ const baseIndex = arguments_.indexOf("--base");
+ const base = baseIndex >= 0 ? arguments_[baseIndex + 1] : "HEAD";
+ const touched = changedFiles(base).filter(file =>
+ testRoots.some(root => file.startsWith(path.join(appRoot, root) + path.sep)));
+ if (touched.length === 0) {
+ console.log("src/tests/electron/scripts 没有改动");
+ return 0;
+ }
+ const selected = selectTests(touched, listFiles());
+ if (selected.length === 0) {
+ console.log("改动没有影响任何测试");
+ return 0;
+ }
+ const relative = selected.map(file => path.relative(appRoot, file).replaceAll("\\", "/"));
+ relative.forEach(file => console.log(file));
+ if (!arguments_.includes("--run")) {
+ return 0;
+ }
+ // 不能复用 scripts/test.mjs:它把四组 glob 无条件追加在参数之后,传文件等于跑全量。
+ // 这里直接调用 node --test,但保留它在启动前安装 Electron 的前提(并行 worker 会同时解压同一运行时)。
+ createRequire(import.meta.url)("electron");
+ const concurrency = Math.min(4, availableParallelism());
+ const result = spawnSync(process.execPath, [
+ "--import", "tsx", "--test", `--test-concurrency=${concurrency}`, ...relative,
+ ], {cwd: appRoot, stdio: "inherit"});
+ return result.status ?? 1;
+};
+
+if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(import.meta.filename)) {
+ process.exitCode = main();
+}
diff --git a/app/scripts/test-changed.test.js b/app/scripts/test-changed.test.js
new file mode 100644
index 0000000000..9241353dab
--- /dev/null
+++ b/app/scripts/test-changed.test.js
@@ -0,0 +1,57 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const {test} = require("node:test");
+const {selectTests, scanReferences} = require("./test-changed.mjs");
+
+const fixture = t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-test-changed-"));
+ t.after(() => fs.rmSync(root, {recursive: true, force: true}));
+ const write = (name, content) => {
+ const target = path.join(root, name);
+ fs.mkdirSync(path.dirname(target), {recursive: true});
+ fs.writeFileSync(target, content);
+ return target;
+ };
+ return {root, write};
+};
+
+test("module specifiers and source path literals are both treated as dependencies", () => {
+ const references = scanReferences([
+ 'import {a} from "./a";',
+ 'const b = require("../b.ts");',
+ 'const text = readFileSync("src/c.ts", "utf8");',
+ 'const css = "src/d.scss";',
+ 'import("src/e.ts");',
+ 'const url = "https://example.com/x.ts";',
+ ].join("\n"));
+ assert.deepEqual(references.sort(), ["../b.ts", "./a", "src/c.ts", "src/d.scss", "src/e.ts"]);
+});
+
+test("changed sources select tests that reach them through other sources", t => {
+ const {root, write} = fixture(t);
+ // leaf 被中间模块引用,测试只引用中间模块:改动 leaf 必须能顺着依赖链找到该测试。
+ const leaf = write("src/leaf.ts", "export const leaf = 1;");
+ const middle = write("src/middle.ts", 'import {leaf} from "./leaf";\nexport const middle = leaf;');
+ const direct = write("src/direct.test.ts", 'import {leaf} from "./leaf";');
+ const indirect = write("src/indirect.test.ts", 'import {middle} from "./middle";');
+ const stringLoader = write("tests/stringLoader.test.js",
+ 'const {middle} = load("src/middle.ts");');
+ const unrelated = write("src/unrelated.test.ts", 'import {other} from "./other";');
+ write("src/other.ts", "export const other = 2;");
+ const all = [leaf, middle, direct, indirect, stringLoader, unrelated];
+
+ assert.deepEqual(selectTests([leaf], all, root), [direct, indirect, stringLoader].sort());
+ // 改动测试文件本身时只选它自己。
+ assert.deepEqual(selectTests([unrelated], all, root), [unrelated]);
+ // 改动没有被引用的源文件时不选任何测试。
+ assert.deepEqual(selectTests([write("src/isolated.ts", "export {};")], all, root), []);
+});
+
+test("an undetectable dependency reports no tests instead of guessing", t => {
+ const {root, write} = fixture(t);
+ const source = write("src/source.ts", "export const value = 1;");
+ const testFile = write("src/source.test.ts", "// 只由运行期字符串拼接决定加载目标\nconst name = \"source\";");
+ assert.deepEqual(selectTests([source], [source, testFile], root), []);
+});