Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(ci): declare files tests read outside their package as turbo inputs (MUL-9992) (#11330)

Jiayuan Zhang59938da8ed9c
diff --git a/.github/actions/frontend-quality/action.yml b/.github/actions/frontend-quality/action.yml
index dd4dc0726b..0184859f30 100644
--- a/.github/actions/frontend-quality/action.yml
+++ b/.github/actions/frontend-quality/action.yml
@@ -25,6 +25,10 @@ runs:
shell: bash
run: node scripts/check-ui-focus-outlines.mjs
+ - name: Check tests declare the files they read outside their package
+ shell: bash
+ run: node scripts/check-test-cache-inputs.mjs
+
- name: Check shared dependencies use the pnpm catalog
shell: bash
run: node scripts/check-dependency-catalog.mjs
diff --git a/.github/ci-paths.json b/.github/ci-paths.json
index d061a65d58..07beff537a 100644
--- a/.github/ci-paths.json
+++ b/.github/ci-paths.json
@@ -6,6 +6,8 @@
"apps/collab/**",
"packages/**",
"server/internal/handler/testdata/quick_action_bodies.json",
+ "docs/theming.md",
+ "apps/*/package.json",
"package.json",
".npmrc",
"pnpm-lock.yaml",
diff --git a/AGENTS.md b/AGENTS.md
index f883dc3333..0a3a3f8c29 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -133,6 +133,7 @@ Workspace-scoped queries filter by `workspace_id`; membership gates access and `
- Give each behavior one canonical test layer: helper tests own parsing/state matrices; component tests cover wiring, accessibility, happy paths, and named regressions. Prefer a failing regression test before behavioral fixes.
- DOM-free `.test.ts` files start with `// @vitest-environment node`; do not use it if it would silently switch the code under test to an SSR path.
- Every workspace with jsdom suites loads `@multica/vitest-setup/web-storage` in its Vitest setup; do not add per-package `localStorage` shims.
+- A test that reads files outside its package and that package's workspace dependencies declares them as `$TURBO_ROOT$/...` in the package's `turbo.json` `tasks.test.inputs`, and in the CI path group that runs it (`.github/ci-paths.json`); otherwise CI replays a cached pass when only those files change. `scripts/check-test-cache-inputs.mjs` enforces this.
- Views tests must not mock `next/*` or `react-router-dom`. Mock stores with their Zustand callable shape plus `getState`; mock API calls at `@multica/core/api`.
- E2E setup/teardown uses `TestApiClient`.
- DB-backed Go tests use `server/internal/testutil` fixtures (`dbfx.Issue`, `dbfx.Task`, `dbfx.Insert`) and `testutil.Call(h, req).Want(status).JSON(&out)`. Keep product assertions and case-specific diagnostics in the test, not fixture helpers.
diff --git a/apps/docs/turbo.json b/apps/docs/turbo.json
index 407efd5478..4bcc0ba1a4 100644
--- a/apps/docs/turbo.json
+++ b/apps/docs/turbo.json
@@ -7,9 +7,19 @@
"$TURBO_ROOT$/server/internal/daemon/agents_probe.go",
"$TURBO_ROOT$/server/internal/daemon/config.go",
"$TURBO_ROOT$/server/pkg/agent/builtin_runtimes.go",
+ "$TURBO_ROOT$/server/pkg/agent/agent.go",
+ "$TURBO_ROOT$/server/pkg/agent/version.go",
"$TURBO_ROOT$/server/internal/featureflags/keys.go",
"$TURBO_ROOT$/packages/core/ai-traffic/**",
- "$TURBO_ROOT$/SELF_HOSTING_AI.md"
+ "$TURBO_ROOT$/SELF_HOSTING_AI.md",
+ "$TURBO_ROOT$/README.md",
+ "$TURBO_ROOT$/README.zh.md",
+ "$TURBO_ROOT$/README.ja.md",
+ "$TURBO_ROOT$/apps/web/features/landing/i18n/{en,zh,ja,ko}.ts",
+ "$TURBO_ROOT$/apps/web/features/landing/i18n/site-*.ts",
+ "$TURBO_ROOT$/apps/web/features/landing/site/cloud-page.tsx",
+ // lib/vercel-upload-coverage.test.ts hands it to `git ls-files`.
+ "$TURBO_ROOT$/.vercelignore"
]
}
}
diff --git a/apps/web/turbo.json b/apps/web/turbo.json
new file mode 100644
index 0000000000..c682e4581c
--- /dev/null
+++ b/apps/web/turbo.json
@@ -0,0 +1,10 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "test": {
+ // app/font-stacks, text-contrast and brand-variant-cascade read Desktop's
+ // stylesheet and scan its sources; web does not depend on Desktop.
+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/apps/desktop/src/**/*.{ts,tsx,css}"]
+ }
+ }
+}
diff --git a/package.json b/package.json
index e264f67e2e..889ce520ea 100644
--- a/package.json
+++ b/package.json
@@ -32,6 +32,7 @@
"check:ui-radii": "node scripts/check-ui-radius-tokens.mjs",
"check:ui-transitions": "node scripts/check-ui-transition-properties.mjs",
"check:deps-catalog": "node scripts/check-dependency-catalog.mjs",
+ "check:test-inputs": "node scripts/check-test-cache-inputs.mjs",
"theme:check": "node scripts/theme-check.mjs",
"theme:preview": "node scripts/theme-preview.mjs",
"clean": "turbo clean && rm -rf node_modules",
diff --git a/packages/core/turbo.json b/packages/core/turbo.json
index 92d66fd27e..8f63ffb0e1 100644
--- a/packages/core/turbo.json
+++ b/packages/core/turbo.json
@@ -4,7 +4,9 @@
"test": {
"inputs": [
"$TURBO_DEFAULT$",
- "$TURBO_ROOT$/server/internal/handler/testdata/quick_action_bodies.json"
+ "$TURBO_ROOT$/server/internal/handler/testdata/quick_action_bodies.json",
+ // appearance/theme-check.test.ts checks themes against the shipped palette.
+ "$TURBO_ROOT$/packages/ui/styles/tokens.css"
]
}
}
diff --git a/packages/eslint-config/turbo.json b/packages/eslint-config/turbo.json
new file mode 100644
index 0000000000..aabfebd8ec
--- /dev/null
+++ b/packages/eslint-config/turbo.json
@@ -0,0 +1,17 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "test": {
+ // The rule tests lint through the real configs of the workspaces that
+ // load this package, which none of them is a dependency of.
+ "inputs": [
+ "$TURBO_DEFAULT$",
+ "$TURBO_ROOT$/apps/desktop/eslint.config.mjs",
+ "$TURBO_ROOT$/apps/web/eslint.config.mjs",
+ "$TURBO_ROOT$/packages/core/eslint.config.mjs",
+ "$TURBO_ROOT$/packages/views/eslint.config.mjs",
+ "$TURBO_ROOT$/packages/views/eslint-i18n-guard.mjs"
+ ]
+ }
+ }
+}
diff --git a/packages/views/turbo.json b/packages/views/turbo.json
new file mode 100644
index 0000000000..ca6a8e6054
--- /dev/null
+++ b/packages/views/turbo.json
@@ -0,0 +1,24 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "test": {
+ "inputs": [
+ "$TURBO_DEFAULT$",
+ // common/theme-anchors, theme-variables and safe-area scan the app
+ // sources that consume views; embed-tokens and theme-variables keep
+ // docs/theming.md generated.
+ "$TURBO_ROOT$/apps/desktop/src/renderer/**/*.{ts,tsx,css}",
+ "$TURBO_ROOT$/apps/web/app/**/*.{ts,tsx}",
+ "$TURBO_ROOT$/apps/web/components/**/*.{ts,tsx}",
+ "$TURBO_ROOT$/docs/theming.md",
+ // locales/copy-hygiene.test.ts holds the EE locale files to the same rules.
+ "$TURBO_ROOT$/packages/ee/project-folders/locales/*.json",
+ // rich-content/package-exports.test.ts checks every workspace's export
+ // targets; ee's are the only ones outside views' dependencies.
+ "$TURBO_ROOT$/apps/*/package.json",
+ "$TURBO_ROOT$/packages/*/package.json",
+ "$TURBO_ROOT$/packages/ee/index.ts"
+ ]
+ }
+ }
+}
diff --git a/scripts/check-test-cache-inputs.mjs b/scripts/check-test-cache-inputs.mjs
new file mode 100644
index 0000000000..6ded9a837a
--- /dev/null
+++ b/scripts/check-test-cache-inputs.mjs
@@ -0,0 +1,397 @@
+#!/usr/bin/env node
+/**
+ * Fails when a test reads a file its package's turbo `test` hash cannot see.
+ *
+ * CI restores the turbo cache, and a package's `test` hash covers only its own
+ * files and, through turbo.json's `^cache-inputs` edge, its workspace
+ * dependencies. A test that reads anything else (a sibling app's stylesheet,
+ * docs/theming.md, another package's manifest) keeps the same hash when only
+ * that file changes, so CI replays the previous pass without running it. Such
+ * a read has to be declared as a `$TURBO_ROOT$/...` entry in the package's
+ * turbo.json `tasks.test.inputs` (MUL-9982, MUL-9992).
+ *
+ * A declared input is only half of it: the CI job that runs the package's
+ * tests is gated by a .github/ci-paths.json group, so the declared files must
+ * also be in that group or a PR touching only them skips the job.
+ *
+ * Reads are found statically. Each test file is parsed with the TypeScript
+ * parser and path expressions are folded where their parts are constants:
+ * `join`/`resolve` over `__dirname`, `import.meta.dirname`, `process.cwd()`
+ * (the package directory under turbo) and string constants, `new URL(x,
+ * import.meta.url)`, `fileURLToPath`, `dirname`. On top of that:
+ *
+ * - a string literal starting with `../` is resolved from the test file;
+ * - in a test that computes the repository root, a string literal naming an
+ * existing path from the root (`"apps/web/app"`, `"README.md"`) is a read,
+ * since such tests join it onto the root in a helper the folding can't
+ * follow.
+ *
+ * Only paths that exist count, which is what keeps fixture strings out. A
+ * directory or a template-literal prefix is satisfied by any declared input
+ * under or above it: which files beneath a scanned directory matter is the
+ * author's call, the check only makes sure one was made.
+ *
+ * Run: node scripts/check-test-cache-inputs.mjs [repo-root]
+ */
+
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import ts from "typescript";
+
+const repoRoot = resolve(process.argv[2] ?? resolve(import.meta.dirname, ".."));
+
+const TEST_FILE = /\.test\.[cm]?[jt]sx?$/;
+const SKIP_DIRS = new Set(["node_modules", ".git", ".next", ".turbo", ".source", "out", "dist", "build", "coverage"]);
+const IMPORT_EXTENSIONS = ["", ".ts", ".tsx", ".js", ".mjs", ".cjs", "/index.ts", "/index.tsx", "/index.js"];
+const DEPENDENCY_FIELDS = ["dependencies", "devDependencies", "optionalDependencies"];
+
+// Which .github/ci-paths.json group starts the CI job that runs a package's
+// tests (.github/workflows/ci.yml). `null`: CI does not run them.
+const CI_GROUP_DEFAULT = "frontend";
+const CI_GROUPS = new Map([
+ ["@multica/docs", "docs"],
+ ["@multica/mobile", null],
+]);
+
+const toPosix = (path) => path.split(sep).join("/");
+const repoRelative = (path) => toPosix(relative(repoRoot, path));
+const isInside = (path, dir) => path === dir || path.startsWith(dir + sep);
+
+function readJsonc(path) {
+ const { config, error } = ts.parseConfigFileTextToJson(path, readFileSync(path, "utf8"));
+ if (error) throw new Error(`${repoRelative(path)}: ${ts.flattenDiagnosticMessageText(error.messageText, "\n")}`);
+ return config;
+}
+
+/** Glob semantics of turbo inputs and ci-paths: `**`, `*`, `?`, `{a,b}`. */
+export function globToRegExp(glob) {
+ let out = "";
+ for (let i = 0; i < glob.length; i++) {
+ const c = glob[i];
+ if (c === "*" && glob[i + 1] === "*") {
+ i++;
+ if (glob[i + 1] === "/") {
+ i++;
+ out += "(?:.*/)?";
+ } else {
+ out += ".*";
+ }
+ } else if (c === "*") out += "[^/]*";
+ else if (c === "?") out += "[^/]";
+ else if (c === "{") out += "(?:";
+ else if (c === "}") out += ")";
+ else if (c === ",") out += "|";
+ else out += c.replace(/[.+^$()|[\]\\]/g, "\\$&");
+ }
+ return new RegExp(`^${out}$`);
+}
+
+/** The directory part of a glob before its first wildcard. */
+const staticBase = (glob) => {
+ const wild = glob.search(/[*?{]/);
+ if (wild < 0) return glob;
+ return glob.slice(0, glob.lastIndexOf("/", wild) + 1).replace(/\/$/, "");
+};
+
+/**
+ * Whether `glob` can match a file under directory `dir`. Segments are matched
+ * one by one, so `apps/*` + `/package.json` reaches into `apps` but not into
+ * `apps/desktop/src`; only `**` matches the levels below it.
+ */
+function reachesInto(glob, dir) {
+ const parts = glob.split("/");
+ const dirs = dir.split("/");
+ for (let i = 0; i < dirs.length; i++) {
+ if (i >= parts.length - 1) return false;
+ if (parts[i] === "**") return true;
+ if (!globToRegExp(parts[i]).test(dirs[i])) return false;
+ }
+ return true;
+}
+
+/** A read of `ref` is declared by `globs` (repo-relative). */
+export function covers(globs, ref) {
+ if (ref.kind === "file") return globs.some((glob) => globToRegExp(glob).test(ref.path));
+ return globs.some((glob) => reachesInto(glob, ref.path));
+}
+
+function workspacePackages() {
+ const manifest = readFileSync(join(repoRoot, "pnpm-workspace.yaml"), "utf8");
+ const groups = [...manifest.matchAll(/^\s+-\s+['"]?([^'"\s]+)\/\*['"]?\s*$/gm)].map((m) => m[1]);
+ const packages = [];
+ for (const group of groups) {
+ const groupDir = join(repoRoot, group);
+ if (!existsSync(groupDir)) continue;
+ for (const entry of readdirSync(groupDir).sort()) {
+ const manifestPath = join(groupDir, entry, "package.json");
+ if (!existsSync(manifestPath)) continue;
+ packages.push({ dir: join(groupDir, entry), manifest: JSON.parse(readFileSync(manifestPath, "utf8")) });
+ }
+ }
+ return packages;
+}
+
+function dependencyDirs(pkg, byName) {
+ const seen = new Set();
+ const queue = [pkg.manifest];
+ while (queue.length > 0) {
+ const manifest = queue.pop();
+ for (const field of DEPENDENCY_FIELDS) {
+ for (const name of Object.keys(manifest[field] ?? {})) {
+ const dep = byName.get(name);
+ if (!dep || seen.has(dep.dir)) continue;
+ seen.add(dep.dir);
+ queue.push(dep.manifest);
+ }
+ }
+ }
+ return [...seen];
+}
+
+function declaredInputs(pkg) {
+ const path = join(pkg.dir, "turbo.json");
+ if (!existsSync(path)) return [];
+ const inputs = readJsonc(path).tasks?.test?.inputs ?? [];
+ return inputs.filter((input) => input.startsWith("$TURBO_ROOT$/")).map((input) => input.slice("$TURBO_ROOT$/".length));
+}
+
+function walk(dir, keep, found = []) {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.isDirectory()) {
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) walk(join(dir, entry.name), keep, found);
+ } else if (keep(entry.name)) {
+ found.push(join(dir, entry.name));
+ }
+ }
+ return found;
+}
+
+const pathKind = (path) => {
+ try {
+ return statSync(path).isDirectory() ? "dir" : "file";
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * Folds path expressions in one test file. A value is `{ text, partial }`:
+ * `partial` means only a prefix is known (a template literal or a join whose
+ * tail is not a constant). Absolute `text` is a filesystem path; `file://`
+ * text is a URL.
+ */
+function pathReads(file, pkgDir) {
+ const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);
+ const fileDir = dirname(file);
+
+ const bindings = new Map();
+ const collect = (node) => {
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
+ bindings.set(node.name.text, bindings.has(node.name.text) ? null : node.initializer);
+ }
+ ts.forEachChild(node, collect);
+ };
+ collect(source);
+
+ const calleeName = (expr) =>
+ ts.isIdentifier(expr) ? expr.text : ts.isPropertyAccessExpression(expr) ? expr.name.text : null;
+ const isImportMeta = (node) =>
+ ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword && node.name.text === "meta";
+
+ const visiting = new Set();
+ function evaluate(node) {
+ if (!node) return null;
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isNonNullExpression(node)) {
+ return evaluate(node.expression);
+ }
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return { text: node.text, partial: false };
+ if (ts.isTemplateExpression(node)) {
+ let text = node.head.text;
+ for (const span of node.templateSpans) {
+ const value = evaluate(span.expression);
+ if (!value || value.partial) return { text, partial: true };
+ text += value.text + span.literal.text;
+ }
+ return { text, partial: false };
+ }
+ if (ts.isIdentifier(node)) {
+ if (node.text === "__dirname") return { text: fileDir, partial: false };
+ if (node.text === "__filename") return { text: file, partial: false };
+ const init = bindings.get(node.text);
+ if (!init || visiting.has(node.text)) return null;
+ visiting.add(node.text);
+ try {
+ return evaluate(init);
+ } finally {
+ visiting.delete(node.text);
+ }
+ }
+ if (ts.isPropertyAccessExpression(node) && isImportMeta(node.expression)) {
+ if (node.name.text === "dirname") return { text: fileDir, partial: false };
+ if (node.name.text === "filename") return { text: file, partial: false };
+ if (node.name.text === "url") return { text: pathToFileURL(file).href, partial: false };
+ return null;
+ }
+ if (ts.isNewExpression(node) && calleeName(node.expression) === "URL" && node.arguments?.length === 2) {
+ const [spec, base] = node.arguments.map(evaluate);
+ if (!spec || !base?.text.startsWith("file:")) return null;
+ return { text: new URL(spec.text, base.text).href, partial: spec.partial };
+ }
+ if (!ts.isCallExpression(node)) return null;
+
+ const name = calleeName(node.expression);
+ if (name === "cwd" && ts.isPropertyAccessExpression(node.expression)) return { text: pkgDir, partial: false };
+ const args = node.arguments.map(evaluate);
+ if (name === "fileURLToPath" && args[0]?.text.startsWith("file:")) {
+ return { text: fileURLToPath(args[0].text), partial: args[0].partial };
+ }
+ if (name === "dirname" && args[0] && isAbsolute(args[0].text) && !args[0].partial) {
+ return { text: dirname(args[0].text), partial: false };
+ }
+ if (name !== "join" && name !== "resolve") return null;
+ const known = [];
+ let partial = false;
+ for (const arg of args) {
+ if (!arg) {
+ partial = known.length > 0;
+ break;
+ }
+ known.push(arg.text);
+ if (arg.partial) {
+ partial = true;
+ break;
+ }
+ }
+ if (known.length === 0) return null;
+ const start = name === "resolve" ? known.findLastIndex((part) => isAbsolute(part)) : 0;
+ if (start < 0 || !isAbsolute(known[start])) return null;
+ const joined = join(...known.slice(start));
+ return { text: partial ? `${joined}/` : joined, partial };
+ }
+
+ const values = [];
+ let computesRoot = false;
+ const asPath = (value) => (value.text.startsWith("file:") ? { ...value, text: fileURLToPath(value.text) } : value);
+
+ const visit = (node) => {
+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
+ const value = evaluate(node);
+ if (value && (isAbsolute(value.text) || value.text.startsWith("file:"))) {
+ const path = asPath(value);
+ if (resolve(path.text) === repoRoot) computesRoot = true;
+ values.push({ ...path, node });
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+
+ const literals = [];
+ const visitLiterals = (node) => {
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) literals.push({ text: node.text, partial: false, node });
+ else if (ts.isTemplateExpression(node)) literals.push({ text: node.head.text, partial: true, node });
+ ts.forEachChild(node, visitLiterals);
+ };
+ visitLiterals(source);
+
+ const topLevel = new Set(readdirSync(repoRoot).filter((entry) => !SKIP_DIRS.has(entry)));
+ const reads = [];
+ const line = (node) => source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
+ const add = (path, partial, node) => {
+ const absolute = resolve(partial && !path.endsWith("/") ? dirname(path) : path);
+ const kind = partial ? (pathKind(absolute) === "dir" ? "dir" : null) : pathKind(absolute);
+ if (kind) reads.push({ path: absolute, kind, line: line(node) });
+ };
+
+ for (const value of values) add(value.text, value.partial, value.node);
+ for (const literal of literals) {
+ const text = literal.text.replace(/[?#].*$/, "");
+ // `"../.."` only climbs to a base that something else is joined onto.
+ if (/^\.\.(\/\.\.)*\/?$/.test(text)) continue;
+ if (text.startsWith("../")) {
+ const base = resolve(fileDir, text);
+ if (literal.partial) {
+ add(`${base}/`, true, literal.node);
+ continue;
+ }
+ const hit = IMPORT_EXTENSIONS.map((ext) => base + ext).find((candidate) => pathKind(candidate));
+ if (hit) add(hit, false, literal.node);
+ continue;
+ }
+ if (!computesRoot || !text || /^[./]|:|\s/.test(text) || !topLevel.has(text.split("/")[0])) continue;
+ // A bare name is ambiguous when the package has its own (`package.json`).
+ if (!text.includes("/") && (pathKind(join(pkgDir, text)) || pathKind(join(fileDir, text)))) continue;
+ add(join(repoRoot, text) + (literal.partial ? "/" : ""), literal.partial, literal.node);
+ }
+ return reads;
+}
+
+export function check() {
+ const packages = workspacePackages();
+ const byName = new Map(packages.map((pkg) => [pkg.manifest.name, pkg]));
+ const ciPaths = JSON.parse(readFileSync(join(repoRoot, ".github/ci-paths.json"), "utf8"));
+ const problems = [];
+
+ for (const pkg of packages) {
+ if (!pkg.manifest.scripts?.test) continue;
+ const name = pkg.manifest.name;
+ const pkgRel = repoRelative(pkg.dir);
+ const hashed = [pkg.dir, ...dependencyDirs(pkg, byName)];
+ const inputs = declaredInputs(pkg);
+
+ const missing = new Map();
+ for (const file of walk(pkg.dir, (entry) => TEST_FILE.test(entry))) {
+ for (const read of pathReads(file, pkg.dir)) {
+ if (!isInside(read.path, repoRoot) || read.path === repoRoot) continue;
+ if (read.path.split(sep).includes("node_modules")) continue;
+ if (hashed.some((dir) => isInside(read.path, dir))) continue;
+ const ref = { path: repoRelative(read.path), kind: read.kind };
+ if (covers(inputs, ref)) continue;
+ const key = `${ref.path}${ref.kind === "dir" ? "/" : ""}`;
+ if (!missing.has(key)) missing.set(key, `${repoRelative(file)}:${read.line}`);
+ }
+ }
+ for (const [path, at] of missing) {
+ problems.push(
+ `${name}: ${at} reads ${path}, which is outside ${pkgRel} and its workspace dependencies.\n` +
+ ` Add "$TURBO_ROOT$/${path}${path.endsWith("/") ? "**" : ""}" (or a narrower glob) to ` +
+ `tasks.test.inputs in ${pkgRel}/turbo.json.`,
+ );
+ }
+
+ const group = CI_GROUPS.has(name) ? CI_GROUPS.get(name) : CI_GROUP_DEFAULT;
+ if (group === null) continue;
+ const triggers = ciPaths[group] ?? [];
+ for (const input of inputs) {
+ const base = staticBase(input);
+ const files = pathKind(join(repoRoot, base)) === "dir"
+ ? walk(join(repoRoot, base), () => true).map(repoRelative).filter((path) => globToRegExp(input).test(path))
+ : [base];
+ const untriggered = files.filter((path) => !triggers.some((glob) => globToRegExp(glob).test(path)));
+ if (untriggered.length > 0) {
+ problems.push(
+ `${name}: ${pkgRel}/turbo.json declares $TURBO_ROOT$/${input}, but the "${group}" group in ` +
+ `.github/ci-paths.json does not match ${untriggered.slice(0, 3).join(", ")}` +
+ `${untriggered.length > 3 ? ` and ${untriggered.length - 3} more` : ""}, ` +
+ "so a PR changing only that skips the tests.",
+ );
+ }
+ }
+ }
+ return problems;
+}
+
+if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
+ const problems = check();
+ if (problems.length > 0) {
+ console.error(`Test reads the turbo cache cannot see (${problems.length}):\n`);
+ for (const problem of problems) console.error(` ${problem}\n`);
+ console.error(
+ "A cached pass is replayed when only an undeclared file changes. Declare the read where it is named, " +
+ "keeping the glob to what the test actually reads.",
+ );
+ process.exit(1);
+ }
+ console.log("Every file a test reads outside its package is a declared turbo input.");
+}
diff --git a/scripts/check-test-cache-inputs.test.mjs b/scripts/check-test-cache-inputs.test.mjs
new file mode 100644
index 0000000000..d0b06e91fe
--- /dev/null
+++ b/scripts/check-test-cache-inputs.test.mjs
@@ -0,0 +1,170 @@
+// An undeclared read is invisible by construction: the cached pass looks like
+// any other pass. These fixtures prove the check still sees each shape of read
+// the repository's tests use.
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import test from "node:test";
+import { covers, globToRegExp } from "./check-test-cache-inputs.mjs";
+
+const script = resolve(import.meta.dirname, "check-test-cache-inputs.mjs");
+
+// `views` depends on `ui`, which depends on `core`; `ee` and the apps are
+// outside its hash.
+function fixture(t) {
+ const root = mkdtempSync(join(tmpdir(), "cache-inputs-"));
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ const write = (rel, text) => {
+ mkdirSync(dirname(join(root, rel)), { recursive: true });
+ writeFileSync(join(root, rel), text);
+ };
+ const pkg = (dir, name, deps = {}, test = "vitest run") =>
+ write(`${dir}/package.json`, JSON.stringify({ name, scripts: test ? { test } : {}, dependencies: deps }));
+ const inputs = (dir, list) =>
+ write(`${dir}/turbo.json`, `{\n // comment\n "extends": ["//"],\n "tasks": { "test": { "inputs": ${JSON.stringify(["$TURBO_DEFAULT$", ...list])} } }\n}\n`);
+ const ciPaths = (groups) => write(".github/ci-paths.json", JSON.stringify(groups));
+
+ write("pnpm-workspace.yaml", "packages:\n - apps/*\n - packages/*\n");
+ ciPaths({ frontend: ["apps/web/**", "packages/**"], docs: ["apps/docs/**"] });
+ pkg("packages/core", "@multica/core");
+ pkg("packages/ui", "@multica/ui", { "@multica/core": "workspace:*" });
+ pkg("packages/views", "@multica/views", { "@multica/ui": "workspace:*" });
+ pkg("packages/ee", "@multica/ee", { "@multica/views": "workspace:*" }, null);
+ pkg("apps/web", "@multica/web", { "@multica/views": "workspace:*" });
+ pkg("apps/docs", "@multica/docs");
+ write("packages/core/tokens.css", ":root {}\n");
+ write("packages/ee/locales/en.json", "{}\n");
+ write("apps/web/app/globals.css", "body {}\n");
+ write("apps/web/app/page.tsx", "export {};\n");
+ write("docs/theming.md", "# Theming\n");
+ write("README.md", "# Repo\n");
+
+ const check = () => {
+ const result = spawnSync(process.execPath, [script, root], { encoding: "utf8" });
+ return { status: result.status, output: result.stdout + result.stderr };
+ };
+ const passes = (message) => {
+ const { status, output } = check();
+ assert.equal(status, 0, `${message}\n${output}`);
+ };
+ const failsNaming = (names, message) => {
+ const { status, output } = check();
+ assert.equal(status, 1, `${message}\n${output}`);
+ for (const name of names) assert.ok(output.includes(name), `should name ${name}\n${output}`);
+ };
+ return { write, inputs, ciPaths, passes, failsNaming };
+}
+
+const viewsTest = "packages/views/common/probe.test.ts";
+
+test("a relative read of a non-dependency fails until it is declared", (t) => {
+ const { write, inputs, passes, failsNaming } = fixture(t);
+ passes("a clean tree should pass");
+ write(viewsTest, 'const css = readFileSync(resolve(__dirname, "../../../apps/web/app/globals.css"), "utf8");\n');
+ failsNaming(["@multica/views", `${viewsTest}:1`, "apps/web/app/globals.css", "packages/views/turbo.json"], "an app stylesheet is outside views' hash");
+ inputs("packages/views", ["$TURBO_ROOT$/apps/web/app/*.css"]);
+ passes("a matching input should declare it");
+});
+
+test("reads of the package itself and of transitive dependencies need nothing", (t) => {
+ const { write, passes } = fixture(t);
+ write(viewsTest, [
+ 'readFileSync(new URL("../../core/tokens.css", import.meta.url));',
+ 'readFileSync(join(__dirname, "..", "package.json"));',
+ 'import x from "../../ui/package.json";',
+ ].join("\n"));
+ passes("core is a dependency of ui, which views depends on");
+});
+
+test("a root-relative path in a test that computes the repo root is a read", (t) => {
+ const { write, inputs, ciPaths, passes, failsNaming } = fixture(t);
+ ciPaths({ frontend: ["apps/web/**", "packages/**", "docs/theming.md", "README.md"] });
+ write(viewsTest, [
+ 'const REPO = join(__dirname, "../../..");',
+ "const read = (path) => readFileSync(join(REPO, path), \"utf8\");",
+ 'const docs = read("docs/theming.md");',
+ 'const ROOTS = ["packages/views", "apps/web/app"];',
+ "const readme = read(`README.md`);",
+ ].join("\n"));
+ failsNaming(["docs/theming.md", "apps/web/app/", "README.md"], "helpers joined onto the root still read the repo");
+ inputs("packages/views", [
+ "$TURBO_ROOT$/docs/theming.md",
+ "$TURBO_ROOT$/apps/web/app/**/*.tsx",
+ "$TURBO_ROOT$/README.md",
+ ]);
+ passes("a glob under a scanned directory declares the scan");
+});
+
+test("template prefixes and process.cwd() are followed", (t) => {
+ const { write, failsNaming } = fixture(t);
+ write("apps/web/app/probe.test.ts", [
+ 'const root = resolve(process.cwd(), "../..");',
+ "const locale = (l) => readFileSync(join(root, `packages/ee/locales/${l}.json`));",
+ ].join("\n"));
+ failsNaming(["@multica/web", "packages/ee/locales/"], "web does not depend on ee");
+});
+
+test("fixture strings, parent-dir steps and paths outside the repo are not reads", (t) => {
+ const { write, passes } = fixture(t);
+ write(viewsTest, [
+ 'const REPO = join(__dirname, "../../..");',
+ 'expect(parse("../../etc/passwd")).toBe(null);',
+ 'tagsIn(join(REPO, "fixture.tsx"), "apps/web/app/missing.tsx");',
+ 'resolve(REPO, "node_modules", ".bin");',
+ ].join("\n"));
+ passes("nothing here is a file the test reads from the repo");
+});
+
+test("a declared input must also start the CI job that runs the tests", (t) => {
+ const { write, inputs, ciPaths, passes, failsNaming } = fixture(t);
+ write(viewsTest, 'readFileSync(join(__dirname, "../../../docs/theming.md"));\n');
+ inputs("packages/views", ["$TURBO_ROOT$/docs/theming.md"]);
+ failsNaming(['"frontend" group', "docs/theming.md"], "a theming-only PR would skip the views tests");
+ ciPaths({ frontend: ["apps/web/**", "packages/**", "docs/theming.md"], docs: ["apps/docs/**"] });
+ passes("the frontend group now starts the job");
+
+ write("apps/docs/lib/probe.test.ts", 'readFileSync(join(__dirname, "../../../README.md"));\n');
+ inputs("apps/docs", ["$TURBO_ROOT$/README.md"]);
+ failsNaming(['"docs" group', "README.md"], "docs tests run under the docs group");
+});
+
+test("globs follow turbo and ci-paths semantics", () => {
+ assert.ok(globToRegExp("apps/desktop/src/**/*.{ts,tsx,css}").test("apps/desktop/src/renderer/src/globals.css"));
+ assert.ok(globToRegExp("apps/desktop/src/**/*.{ts,tsx,css}").test("apps/desktop/src/a.ts"));
+ assert.ok(!globToRegExp("apps/desktop/src/**/*.{ts,tsx,css}").test("apps/desktop/src/a.md"));
+ assert.ok(globToRegExp("apps/*/package.json").test("apps/web/package.json"));
+ assert.ok(!globToRegExp("apps/*/package.json").test("apps/web/node_modules/x/package.json"));
+ assert.ok(globToRegExp("README.md").test("README.md") && !globToRegExp("README.md").test("READMExmd"));
+ assert.ok(covers(["packages/*/package.json"], { path: "packages", kind: "dir" }));
+ assert.ok(covers(["apps/web/**/*.css"], { path: "apps/web/app", kind: "dir" }));
+ assert.ok(!covers(["apps/web/**/*.css"], { path: "apps/desktop", kind: "dir" }));
+ assert.ok(!covers(["apps/web/**/*.css"], { path: "apps/web/app/page.tsx", kind: "file" }));
+});
+
+test("a single-level wildcard does not declare the directories below it", () => {
+ const manifests = ["apps/*/package.json", "packages/*/package.json"];
+ for (const path of ["apps/mobile/src", "apps/desktop/src/renderer", "packages/ee/project-folders/locales"]) {
+ assert.ok(!covers(manifests, { path, kind: "dir" }), path);
+ }
+ assert.ok(covers(manifests, { path: "apps", kind: "dir" }), "the manifests are read from under apps/");
+ assert.ok(covers(manifests, { path: "apps/web", kind: "dir" }), "apps/web/package.json is under apps/web");
+ assert.ok(!covers(["README*.md"], { path: "apps/web", kind: "dir" }), "a root-level wildcard stays at the root");
+ assert.ok(covers(["**/*.css"], { path: "apps/web/app", kind: "dir" }));
+ assert.ok(covers(["packages/ee/project-folders/locales/*.json"], { path: "packages/ee/project-folders/locales", kind: "dir" }));
+ assert.ok(!covers(["packages/ee/project-folders/locales/*.json"], { path: "packages/ee/project-folders/locales/en", kind: "dir" }));
+});
+
+test("dropping a scanned directory from views' inputs fails even with workspace manifests declared", (t) => {
+ const { write, inputs, ciPaths, passes, failsNaming } = fixture(t);
+ ciPaths({ frontend: ["apps/**", "packages/**"] });
+ write(viewsTest, [
+ 'const REPO = join(__dirname, "../../..");',
+ 'const ROOTS = ["apps/web/app"];',
+ ].join("\n"));
+ inputs("packages/views", ["$TURBO_ROOT$/apps/*/package.json", "$TURBO_ROOT$/packages/*/package.json"]);
+ failsNaming(["apps/web/app/"], "apps/*/package.json does not declare the app sources");
+ inputs("packages/views", ["$TURBO_ROOT$/apps/*/package.json", "$TURBO_ROOT$/apps/web/app/**/*.tsx"]);
+ passes("the scan is declared once its own glob is");
+});
diff --git a/scripts/ci-scope.test.mjs b/scripts/ci-scope.test.mjs
index af0a1094a7..572ae43794 100644
--- a/scripts/ci-scope.test.mjs
+++ b/scripts/ci-scope.test.mjs
@@ -70,6 +70,8 @@ for (const [name, files, selected] of [
["PR evidence uploader", ["scripts/pr-shots"], ["quality"]],
["cross-module runtime contract", ["packages/core/runtimes/cli-version.ts"], ["frontend", "backend", "runtime", "quality", "e2e"]],
["inbox type contract", ["packages/core/types/inbox.ts"], ["frontend", "backend", "quality", "e2e"]],
+ ["theming reference generated by views tests", ["docs/theming.md"], ["frontend"]],
+ ["app manifest checked by views tests", ["apps/mobile/package.json"], ["frontend", "quality"]],
["shared quick action body contract", ["server/internal/handler/testdata/quick_action_bodies.json"], ["frontend", "backend", "runtime", "e2e"]],
["lockfile", ["pnpm-lock.yaml"], ["frontend", "quality", "docs", "e2e"]],
["workspace catalog", ["pnpm-workspace.yaml"], ["frontend", "quality", "docs", "e2e"]],