Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): make two vacuous test guards able to fail (#4520)

Nick Gomez61fa23d72479
diff --git a/knip.config.ts b/knip.config.ts
index dd620604a..e902b1013 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -142,11 +142,15 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: ['yjs'],
+ ignoreDependencies: [
+ 'yjs',
+ ],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/playwright.a11y.config.ts b/packages/app/playwright.a11y.config.ts
index 97a290caf..9926e046a 100644
--- a/packages/app/playwright.a11y.config.ts
+++ b/packages/app/playwright.a11y.config.ts
@@ -40,6 +40,7 @@ const isCI = !!process.env.CI;
export default defineConfig({
testDir: './tests/a11y',
+ globalSetup: './tests/stress/_helpers/i18n-catalog-freshness.ts',
testMatch: /.*\.e2e\.ts$/,
timeout: 120_000,
expect: { timeout: EXPECT_TIMEOUT_MS },
diff --git a/packages/app/playwright.config.ts b/packages/app/playwright.config.ts
index 394ae9816..a1e7633f3 100644
--- a/packages/app/playwright.config.ts
+++ b/packages/app/playwright.config.ts
@@ -74,13 +74,16 @@ export const EXPECT_TIMEOUT_MS = isCI ? 15_000 : 5_000;
export default defineConfig({
testDir: './tests/stress',
testMatch: /.*\.e2e\.ts$/,
- // Build the per-run Vite optimizer seed cache once, before any worker
- // boots. Every fixture-spawned dev server copies it (see
- // tests/stress/_helpers/server-process.ts `VITE_E2E_SEED_DIR`) so no
- // server pays a cold dependency scan+optimize — the cold-optimizer
- // mid-test reload storms were the suite's dominant cross-cutting flake
- // class. Fail-open: a failed warm build logs and falls back to cold boots.
- globalSetup: './tests/stress/_helpers/global-warm-cache.ts',
+ globalSetup: [
+ './tests/stress/_helpers/i18n-catalog-freshness.ts',
+ // Build the per-run Vite optimizer seed cache once, before any worker
+ // boots. Every fixture-spawned dev server copies it (see
+ // tests/stress/_helpers/server-process.ts `VITE_E2E_SEED_DIR`) so no
+ // server pays a cold dependency scan+optimize — the cold-optimizer
+ // mid-test reload storms were the suite's dominant cross-cutting flake
+ // class. Fail-open: a failed warm build logs and falls back to cold boots.
+ './tests/stress/_helpers/global-warm-cache.ts',
+ ],
timeout: 120_000,
// Web-first assertions poll until this budget, not Playwright's 5s default.
// Under 4-worker CI load the suite's empirical convergence budget for
diff --git a/packages/app/playwright.visual.config.ts b/packages/app/playwright.visual.config.ts
index 2431fb75b..d3645b03d 100644
--- a/packages/app/playwright.visual.config.ts
+++ b/packages/app/playwright.visual.config.ts
@@ -36,6 +36,7 @@ const isCI = !!process.env.CI;
export default defineConfig({
testDir: './tests/visual',
+ globalSetup: './tests/stress/_helpers/i18n-catalog-freshness.ts',
testMatch: /.*\.e2e\.ts$/,
timeout: 120_000,
expect: { timeout: EXPECT_TIMEOUT_MS },
diff --git a/packages/app/tests/dom/select-all-probe.dom.test.ts b/packages/app/tests/dom/select-all-probe.dom.test.ts
index 735453658..1130e610c 100644
--- a/packages/app/tests/dom/select-all-probe.dom.test.ts
+++ b/packages/app/tests/dom/select-all-probe.dom.test.ts
@@ -1,5 +1,11 @@
+import { EditorState } from '@codemirror/state';
+import type { Page } from '@playwright/test';
import { afterEach, describe, expect, test, vi } from 'vitest';
-import { repairFocusAndReadProbe } from '../stress/_helpers/editor-state';
+import {
+ abandonedPollRefusal,
+ repairFocusAndReadProbe,
+ selectAllAndWaitForSelection,
+} from '../stress/_helpers/editor-state';
const SOURCE_CONTENT_SELECTOR = '.source-editor .cm-content';
const WYSIWYG_SELECTOR = '.ProseMirror:not(.composer-prosemirror)';
@@ -28,6 +34,46 @@ function mountCodeMirror(
return el;
}
+function mountRealCodeMirror(
+ doc: string,
+ selection?: { anchor: number; head: number },
+): { state: EditorState } {
+ const el = mount(SOURCE_MARKUP, SOURCE_CONTENT_SELECTOR);
+ const view = { state: EditorState.create({ doc, selection }) };
+ Object.assign(el, { cmTile: { root: { view } } });
+ return view;
+}
+
+function jsdomPage(onPress: (key: string) => void = () => {}, onRead: () => void = () => {}): Page {
+ return {
+ focus: async (selector: string) => {
+ document.querySelector<HTMLElement>(selector)?.focus({ preventScroll: true });
+ },
+ evaluate: async (fn: (arg: string) => unknown, arg: string) => {
+ onRead();
+ return fn(arg);
+ },
+ keyboard: { press: async (key: string) => onPress(key) },
+ } as unknown as Page;
+}
+
+function selectAllStub(
+ view: { state: EditorState },
+ landsOnPress: number,
+): { pressed: string[]; onPress: (key: string) => void } {
+ const pressed: string[] = [];
+ return {
+ pressed,
+ onPress: (key) => {
+ pressed.push(key);
+ if (key !== 'ControlOrMeta+a' || pressed.length < landsOnPress) return;
+ view.state = view.state.update({
+ selection: { anchor: 0, head: view.state.doc.length },
+ }).state;
+ },
+ };
+}
+
function mountProseMirror(selection: Reading, size: number): HTMLElement {
const el = mount(WYSIWYG_MARKUP, WYSIWYG_SELECTOR);
vi.stubGlobal('__activeEditor', {
@@ -43,18 +89,21 @@ afterEach(() => {
describe('select-all probe view classification', () => {
test.each([
- { outcome: 'covers-document', from: 0, to: 12, length: 12 },
- { outcome: 'covers-document', from: 0, to: 0, length: 0 },
- { outcome: 'partial', from: 2, to: 5, length: 12 },
- { outcome: 'partial', from: 0, to: 5, length: 12 },
- { outcome: 'partial', from: 3, to: 12, length: 12 },
- { outcome: 'empty', from: 4, to: 4, length: 12 },
- { outcome: 'unreadable', from: 0, to: undefined, length: 12 },
+ { outcome: 'covers-document', from: 0, to: 12, length: 12, docEnd: 12 },
+ { outcome: 'empty', from: 0, to: 0, length: 0, docEnd: 0 },
+ { outcome: 'partial', from: 2, to: 5, length: 12, docEnd: 12 },
+ { outcome: 'partial', from: 0, to: 5, length: 12, docEnd: 12 },
+ { outcome: 'partial', from: 3, to: 12, length: 12, docEnd: 12 },
+ { outcome: 'empty', from: 4, to: 4, length: 12, docEnd: 12 },
+ { outcome: 'unreadable', from: 0, to: undefined, length: 12, docEnd: null },
])(
- 'CodeMirror $from-$to over a $length-character document reads $outcome',
- ({ outcome, from, to, length }) => {
+ 'CodeMirror $from-$to over a $length-character document reads $outcome with docEnd $docEnd',
+ ({ outcome, from, to, length, docEnd }) => {
mountCodeMirror({ from, to }, length);
- expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR).viewSelection).toBe(outcome);
+ expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR)).toMatchObject({
+ viewSelection: outcome,
+ docEnd,
+ });
},
);
@@ -69,17 +118,20 @@ describe('select-all probe view classification', () => {
});
test.each([
- { outcome: 'covers-document', from: 0, to: 14, size: 14 },
- { outcome: 'covers-document', from: 0, to: 2, size: 2 },
- { outcome: 'partial', from: 1, to: 6, size: 14 },
- { outcome: 'partial', from: 4, to: 14, size: 14 },
- { outcome: 'empty', from: 3, to: 3, size: 14 },
- { outcome: 'unreadable', from: 0, to: undefined, size: 14 },
+ { outcome: 'covers-document', from: 0, to: 14, size: 14, docEnd: 14 },
+ { outcome: 'covers-document', from: 0, to: 2, size: 2, docEnd: 2 },
+ { outcome: 'partial', from: 1, to: 6, size: 14, docEnd: 14 },
+ { outcome: 'partial', from: 4, to: 14, size: 14, docEnd: 14 },
+ { outcome: 'empty', from: 3, to: 3, size: 14, docEnd: 14 },
+ { outcome: 'unreadable', from: 0, to: undefined, size: 14, docEnd: null },
])(
- 'ProseMirror $from-$to over a size-$size document reads $outcome',
- ({ outcome, from, to, size }) => {
+ 'ProseMirror $from-$to over a size-$size document reads $outcome with docEnd $docEnd',
+ ({ outcome, from, to, size, docEnd }) => {
mountProseMirror({ from, to }, size);
- expect(repairFocusAndReadProbe(WYSIWYG_SELECTOR).viewSelection).toBe(outcome);
+ expect(repairFocusAndReadProbe(WYSIWYG_SELECTOR)).toMatchObject({
+ viewSelection: outcome,
+ docEnd,
+ });
},
);
@@ -97,6 +149,162 @@ describe('select-all probe view classification', () => {
});
});
+describe('select-all barrier discrimination at zero document length', () => {
+ test('a real CodeMirror EditorState separates an empty-document caret from a select-all', () => {
+ mountRealCodeMirror('');
+ const emptyDoc = repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR);
+ expect(
+ emptyDoc,
+ 'a real empty CodeMirror document reports from, to and length as 0, 0, 0 — the triple the hand-shaped fixtures above only stand in for',
+ ).toMatchObject({ viewSelection: 'empty', docEnd: 0 });
+
+ mountRealCodeMirror('hello world', { anchor: 0, head: 11 });
+ expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR)).toMatchObject({
+ viewSelection: 'covers-document',
+ docEnd: 11,
+ });
+ });
+
+ test('the select-all barrier refuses a zero-length source document instead of polling for a selection no keystroke can produce', async () => {
+ mountRealCodeMirror('');
+ await expect(
+ selectAllAndWaitForSelection(jsdomPage(), SOURCE_CONTENT_SELECTOR, {
+ focusMs: 800,
+ selectionMs: 800,
+ }),
+ ).rejects.toThrow(/holds a zero-length document/);
+ });
+
+ test('the select-all barrier settles on the selection the select-all keystroke produced, not on one the fixture arrived with', async () => {
+ const { pressed, onPress } = selectAllStub(
+ mountRealCodeMirror('hello world', { anchor: 0, head: 0 }),
+ 1,
+ );
+ expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR)).toMatchObject({
+ viewSelection: 'empty',
+ docEnd: 11,
+ });
+
+ let reads = 0;
+ await expect(
+ selectAllAndWaitForSelection(
+ jsdomPage(onPress, () => {
+ reads += 1;
+ }),
+ SOURCE_CONTENT_SELECTOR,
+ { focusMs: 800, selectionMs: 800 },
+ ),
+ ).resolves.toBeUndefined();
+
+ expect(pressed).toEqual(['ControlOrMeta+a']);
+ expect(
+ reads,
+ 'a fixture whose select-all lands on the first press costs the barrier exactly two page reads: the probe the focus poll settles on and the probe taken after the keystroke. A third read means the barrier paid a cross-process round trip outside a poll iteration and threw the answer away',
+ ).toBe(2);
+ expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR)).toMatchObject({
+ viewSelection: 'covers-document',
+ docEnd: 11,
+ });
+ });
+
+ test('the select-all barrier presses again when the first keystroke leaves the selection unchanged', async () => {
+ const { pressed, onPress } = selectAllStub(
+ mountRealCodeMirror('hello world', { anchor: 0, head: 0 }),
+ 2,
+ );
+
+ await expect(
+ selectAllAndWaitForSelection(jsdomPage(onPress), SOURCE_CONTENT_SELECTOR, {
+ focusMs: 800,
+ selectionMs: 800,
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(pressed).toEqual(['ControlOrMeta+a', 'ControlOrMeta+a']);
+ });
+
+ test('a probe the barrier could not read is never reported as a zero-length document, even when the document is zero-length', async () => {
+ mountCodeMirror({ from: 0, to: undefined }, 0);
+ expect(repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR)).toMatchObject({
+ viewSelection: 'unreadable',
+ docEnd: null,
+ });
+
+ const pressed: string[] = [];
+ const failure = await selectAllAndWaitForSelection(
+ jsdomPage((key) => {
+ pressed.push(key);
+ }),
+ SOURCE_CONTENT_SELECTOR,
+ { focusMs: 800, selectionMs: 300 },
+ ).catch((error: unknown) => error);
+
+ if (!(failure instanceof Error)) {
+ throw new Error('the select-all barrier resolved on a probe it could not read');
+ }
+ expect(failure.message).not.toMatch(/zero-length document/);
+ expect(pressed).toContain('ControlOrMeta+a');
+ });
+});
+
+describe('select-all barrier refusal on an abandoned poll', () => {
+ test('the abandoned-poll refusal covers every window in which the poll can resolve on a reading its matcher rejects', () => {
+ mountRealCodeMirror('hello world', { anchor: 0, head: 11 });
+ const probe = repairFocusAndReadProbe(SOURCE_CONTENT_SELECTOR);
+ expect(probe).toMatchObject({ focusOwnedByEditor: true, viewSelection: 'covers-document' });
+
+ expect
+ .soft(
+ abandonedPollRefusal(SOURCE_CONTENT_SELECTOR, 'focus', undefined),
+ 'a focus poll that resolved before any probe was read was abandoned',
+ )
+ .toEqual(expect.stringMatching(/stopped being the running test/));
+ expect
+ .soft(
+ abandonedPollRefusal(SOURCE_CONTENT_SELECTOR, 'focus', {
+ ...probe,
+ focusOwnedByEditor: false,
+ }),
+ 'a focus poll that resolved holding a probe its own matcher rejects was abandoned on a later iteration, and the shipped settled-is-undefined predicate read that as success',
+ )
+ .toEqual(expect.stringMatching(/stopped being the running test/));
+ expect
+ .soft(
+ abandonedPollRefusal(SOURCE_CONTENT_SELECTOR, 'focus', {
+ ...probe,
+ focusOwnedByEditor: true,
+ }),
+ 'the probe shape a passing focus poll settles on must never be refused',
+ )
+ .toBeNull();
+
+ expect
+ .soft(
+ abandonedPollRefusal(SOURCE_CONTENT_SELECTOR, 'select-all', undefined),
+ 'a select-all poll that resolved before any probe was read was abandoned',
+ )
+ .toEqual(expect.stringMatching(/stopped being the running test/));
+ expect
+ .soft(
+ abandonedPollRefusal(SOURCE_CONTENT_SELECTOR, 'select-all', {
+ ...probe,
+ viewSelection: 'partial',
+ }),
+ 'a select-all poll that resolved on a partial selection was abandoned, and returning there means the barrier never observed a full-document selection',
+ )
+ .toEqual(expect.stringMatching(/stopped being the running test/));
+ expect
+ .soft(
+ abandonedPollRefusal(SOURCE_CONTENT_SELECTOR, 'select-all', {
+ ...probe,
+ viewSelection: 'covers-document',
+ }),
+ 'the probe shape a passing select-all poll settles on must never be refused',
+ )
+ .toBeNull();
+ });
+});
+
describe('select-all probe focus repair', () => {
test('the probe takes focus for an editor that does not own it on entry', () => {
mountCodeMirror({ from: 0, to: 12 }, 12);
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index 8a60e5826..a28cc2b18 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/e2e-stop-rules.test.ts b/packages/app/tests/integration/e2e-stop-rules.test.ts
index 3cfb5b954..a47103747 100644
--- a/packages/app/tests/integration/e2e-stop-rules.test.ts
+++ b/packages/app/tests/integration/e2e-stop-rules.test.ts
@@ -6,6 +6,14 @@
import { type Dirent, readdirSync, readFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
+import {
+ type CallExpression,
+ type Diagnostic,
+ type Node,
+ type ObjectLiteralExpression,
+ Project,
+ SyntaxKind,
+} from 'ts-morph';
import { describe, expect, test } from 'vitest';
import { DEV_GATED_WINDOW_WRITERS } from './dev-gate-allowlist';
@@ -21,6 +29,7 @@ const APP_SRC_DIR = join(__dirname, '..', '..', 'src');
interface FileLines {
path: string;
absPath: string;
+ source: string;
lines: string[];
}
@@ -46,7 +55,12 @@ function listE2eTsFiles(): FileLines[] {
if (!entry.isFile()) continue;
if (!entry.name.endsWith('.ts')) continue;
const source = readFileSync(abs, 'utf-8');
- out.push({ path: relative(REPO_ROOT, abs), absPath: abs, lines: source.split('\n') });
+ out.push({
+ path: relative(REPO_ROOT, abs),
+ absPath: abs,
+ source,
+ lines: source.split('\n'),
+ });
}
}
for (const dir of E2E_DIRS) walk(dir);
@@ -67,32 +81,396 @@ function listAppSrcTsFiles(): FileLines[] {
if (name.name.endsWith('.test.ts') || name.name.endsWith('.test.tsx')) continue;
if (name.name.endsWith('.spec.ts') || name.name.endsWith('.spec.tsx')) continue;
const source = readFileSync(abs, 'utf-8');
- out.push({ path: relative(REPO_ROOT, abs), absPath: abs, lines: source.split('\n') });
+ out.push({
+ path: relative(REPO_ROOT, abs),
+ absPath: abs,
+ source,
+ lines: source.split('\n'),
+ });
}
}
walk(APP_SRC_DIR);
return out;
}
-const SPAWN_BUN_PATTERN = /spawn\(\s*['"]bun['"]/;
const SPAWN_REQUIRED_ENV_KEYS = ['OK_TEST_VITE_CACHE_DIR', 'OK_TEST_SKIP_I18N_COMPILE'] as const;
+type RequiredSpawnEnvKey = (typeof SPAWN_REQUIRED_ENV_KEYS)[number];
+const SPAWN_CALLEE_NAMES = new Set(['spawn', 'spawnSync']);
+const DEV_SERVER_ARGV_TOKEN = 'dev';
+const PARENT_ENV_SPREAD = 'process.env';
+const CHILD_PROCESS_CALL_PATTERN =
+ /(?<![\w$])(?:spawnSync|spawn|execFileSync|execFile|execSync|fork)\s*\(|(?<![.\w$])exec\s*\(/;
+const MIRROR_EXCLUDED_INFIX = '.private.';
+const DEV_SERVER_SPAWN_SITES = [
+ 'packages/app/tests/stress/_helpers/fixtures.ts',
+ 'packages/app/tests/stress/_helpers/global-warm-cache.ts',
+] as const;
+const NON_DEV_SERVER_SPAWN_SITES = [
+ 'packages/app/tests/stress/_helpers/i18n-catalog-freshness.ts',
+ 'packages/app/tests/stress/okf-generated-index-settings.e2e.ts',
+] as const;
+const PINNED_SPAWN_SITES = [...DEV_SERVER_SPAWN_SITES, ...NON_DEV_SERVER_SPAWN_SITES].sort();
-function findSpawnIsolationViolations(
- lines: string[],
-): Array<{ line: number; missingKey: string }> {
- const spawnLines: number[] = [];
- for (let i = 0; i < lines.length; i++) {
- if (SPAWN_BUN_PATTERN.test(lines[i] ?? '')) spawnLines.push(i + 1);
+function isMirrorExcluded(path: string): boolean {
+ return path.includes(MIRROR_EXCLUDED_INFIX);
+}
+
+function mirroredFilesWithChildProcessCalls(files: FileLines[]): string[] {
+ const out = new Set<string>();
+ for (const file of files) {
+ if (isMirrorExcluded(file.path)) continue;
+ if (file.lines.some((line) => CHILD_PROCESS_CALL_PATTERN.test(line))) out.add(file.path);
+ }
+ return [...out].sort();
+}
+
+type SpawnIsolationViolation =
+ | { line: number; reason: 'missing-key'; missingKey: RequiredSpawnEnvKey }
+ | {
+ line: number;
+ reason: 'unconfirmed-key';
+ unconfirmedKey: RequiredSpawnEnvKey;
+ detail: string;
+ }
+ | { line: number; reason: 'cleared-key'; clearedKey: RequiredSpawnEnvKey }
+ | { line: number; reason: 'undeterminable'; detail: string };
+
+interface SpawnIsolationScan {
+ devServerSpawnLines: number[];
+ violations: SpawnIsolationViolation[];
+}
+
+type EnvKeyVerdict =
+ | { kind: 'declared' }
+ | { kind: 'shadowed'; spread: string }
+ | { kind: 'cleared' };
+
+type SpawnEnvResolution =
+ | {
+ kind: 'keys';
+ keys: ReadonlyMap<string, EnvKeyVerdict>;
+ unreadableSpread: string | null;
+ }
+ | { kind: 'undeterminable'; detail: string };
+
+const spawnScanProject = new Project({
+ useInMemoryFileSystem: true,
+ skipFileDependencyResolution: true,
+ skipLoadingLibFiles: true,
+ skipAddingFilesFromTsConfig: true,
+ compilerOptions: { noLib: true, allowJs: false },
+});
+
+function excerpt(node: Node): string {
+ const text = node.getText().replace(/\s+/g, ' ');
+ return text.length > 80 ? `${text.slice(0, 80)}...` : text;
+}
+
+function diagnosticText(diagnostic: Diagnostic): string {
+ const message = diagnostic.getMessageText();
+ return typeof message === 'string' ? message : message.getMessageText();
+}
+
+function stringLiteralValue(node: Node): string | null {
+ if (node.isKind(SyntaxKind.StringLiteral)) return node.getLiteralValue();
+ if (node.isKind(SyntaxKind.NoSubstitutionTemplateLiteral)) return node.getLiteralValue();
+ return null;
+}
+
+function propertyKey(nameNode: Node): string | null {
+ const literal = stringLiteralValue(nameNode);
+ if (literal !== null) return literal;
+ if (nameNode.isKind(SyntaxKind.Identifier)) return nameNode.getText();
+ if (nameNode.isKind(SyntaxKind.NumericLiteral)) return nameNode.getText();
+ if (nameNode.isKind(SyntaxKind.ComputedPropertyName)) {
+ return stringLiteralValue(nameNode.getExpression());
}
- if (spawnLines.length === 0) return [];
- const source = lines.join('\n');
- const violations: Array<{ line: number; missingKey: string }> = [];
- for (const key of SPAWN_REQUIRED_ENV_KEYS) {
- if (!source.includes(key)) {
- violations.push({ line: spawnLines[0] ?? 1, missingKey: key });
+ return null;
+}
+
+function isDevServerArgvToken(node: Node): boolean {
+ return stringLiteralValue(node) === DEV_SERVER_ARGV_TOKEN;
+}
+
+function isDevServerSpawnCall(call: CallExpression): boolean {
+ const callee = call.getExpression();
+ const name = callee.isKind(SyntaxKind.PropertyAccessExpression)
+ ? callee.getName()
+ : callee.getText();
+ if (!SPAWN_CALLEE_NAMES.has(name)) return false;
+ for (const arg of call.getArguments()) {
+ if (arg.isKind(SyntaxKind.ObjectLiteralExpression)) break;
+ if (isDevServerArgvToken(arg)) return true;
+ if (
+ arg.isKind(SyntaxKind.ArrayLiteralExpression) &&
+ arg.getElements().some(isDevServerArgvToken)
+ ) {
+ return true;
}
}
- return violations;
+ return false;
+}
+
+function resolvesToUndefined(node: Node | undefined): boolean {
+ if (node === undefined) return false;
+ if (node.isKind(SyntaxKind.VoidExpression)) return true;
+ return node.isKind(SyntaxKind.Identifier) && node.getText() === 'undefined';
+}
+
+function envKeysFromLiteral(env: ObjectLiteralExpression): SpawnEnvResolution {
+ const keys = new Map<string, EnvKeyVerdict>();
+ let unreadableSpread: string | null = null;
+ for (const prop of env.getProperties()) {
+ if (prop.isKind(SyntaxKind.SpreadAssignment)) {
+ const spread = prop.getExpression();
+ const spreadText = excerpt(spread);
+ if (spread.getText() !== PARENT_ENV_SPREAD) unreadableSpread ??= spreadText;
+ for (const key of keys.keys()) keys.set(key, { kind: 'shadowed', spread: spreadText });
+ continue;
+ }
+ if (prop.isKind(SyntaxKind.ShorthandPropertyAssignment)) {
+ keys.set(prop.getName(), { kind: 'declared' });
+ continue;
+ }
+ if (!prop.isKind(SyntaxKind.PropertyAssignment)) continue;
+ const key = propertyKey(prop.getNameNode());
+ if (key === null) {
+ return {
+ kind: 'undeterminable',
+ detail: `its \`env\` object has the computed key \`${excerpt(prop.getNameNode())}\`, which may or may not be an isolation key`,
+ };
+ }
+ keys.set(
+ key,
+ resolvesToUndefined(prop.getInitializer()) ? { kind: 'cleared' } : { kind: 'declared' },
+ );
+ }
+ return { kind: 'keys', keys, unreadableSpread };
+}
+
+function envKeysFromOptions(options: ObjectLiteralExpression): SpawnEnvResolution {
+ const props = options.getProperties();
+ let env: ObjectLiteralExpression | null = null;
+ let envIndex = -1;
+ for (const [index, prop] of props.entries()) {
+ if (prop.isKind(SyntaxKind.ShorthandPropertyAssignment)) {
+ if (prop.getName() !== 'env') continue;
+ return {
+ kind: 'undeterminable',
+ detail:
+ 'its options object passes `env` by shorthand (`{ env }`), so the env object is built elsewhere and is not readable at this call',
+ };
+ }
+ if (!prop.isKind(SyntaxKind.PropertyAssignment)) continue;
+ const key = propertyKey(prop.getNameNode());
+ if (key === null) {
+ return {
+ kind: 'undeterminable',
+ detail: `its options object has the computed key \`${excerpt(prop.getNameNode())}\`, which may or may not be \`env\``,
+ };
+ }
+ if (key !== 'env') continue;
+ const initializer = prop.getInitializer();
+ if (initializer === undefined || !initializer.isKind(SyntaxKind.ObjectLiteralExpression)) {
+ return {
+ kind: 'undeterminable',
+ detail: `its \`env\` is \`${excerpt(initializer ?? prop)}\`, not an object literal, so the keys it carries are not readable at this call`,
+ };
+ }
+ env = initializer;
+ envIndex = index;
+ }
+ if (env === null) {
+ if (props.some((prop) => prop.isKind(SyntaxKind.SpreadAssignment))) {
+ return {
+ kind: 'undeterminable',
+ detail:
+ 'its options object declares no own `env` and spreads another object, which may carry one',
+ };
+ }
+ return { kind: 'keys', keys: new Map(), unreadableSpread: null };
+ }
+ if (props.slice(envIndex + 1).some((prop) => prop.isKind(SyntaxKind.SpreadAssignment))) {
+ return {
+ kind: 'undeterminable',
+ detail:
+ 'its options object spreads another object after `env`, which may replace the env read here',
+ };
+ }
+ return envKeysFromLiteral(env);
+}
+
+function resolveSpawnEnv(call: CallExpression): SpawnEnvResolution {
+ const lastArg = call.getArguments().at(-1);
+ if (lastArg === undefined) return { kind: 'keys', keys: new Map(), unreadableSpread: null };
+ if (lastArg.isKind(SyntaxKind.ObjectLiteralExpression)) return envKeysFromOptions(lastArg);
+ if (stringLiteralValue(lastArg) !== null || lastArg.isKind(SyntaxKind.ArrayLiteralExpression)) {
+ return { kind: 'keys', keys: new Map(), unreadableSpread: null };
+ }
+ return {
+ kind: 'undeterminable',
+ detail: `its last argument is \`${excerpt(lastArg)}\` (${lastArg.getKindName()}), so the guard cannot tell whether it is an argv list or an options object carrying an env`,
+ };
+}
+
+function assertNeverEnvKeyVerdict(verdict: never): never {
+ throw new Error(`Unhandled EnvKeyVerdict kind: ${JSON.stringify(verdict)}`);
+}
+
+function scanSpawnIsolation(name: string, source: string): SpawnIsolationScan {
+ const sourceFile = spawnScanProject.createSourceFile(`/${name}`, source, { overwrite: true });
+ const syntaxError = spawnScanProject.getProgram().getSyntacticDiagnostics(sourceFile)[0];
+ if (syntaxError !== undefined) {
+ return {
+ devServerSpawnLines: [],
+ violations: [
+ {
+ line: syntaxError.getLineNumber() ?? 1,
+ reason: 'undeterminable',
+ detail: `the file does not parse (${diagnosticText(syntaxError)}), so no spawn call in it can be read`,
+ },
+ ],
+ };
+ }
+
+ const devServerSpawnLines: number[] = [];
+ const violations: SpawnIsolationViolation[] = [];
+ for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
+ if (!isDevServerSpawnCall(call)) continue;
+ const line = call.getStartLineNumber();
+ devServerSpawnLines.push(line);
+ const env = resolveSpawnEnv(call);
+ if (env.kind === 'undeterminable') {
+ violations.push({ line, reason: 'undeterminable', detail: env.detail });
+ continue;
+ }
+ for (const key of SPAWN_REQUIRED_ENV_KEYS) {
+ const verdict = env.keys.get(key);
+ if (verdict === undefined) {
+ if (env.unreadableSpread === null) {
+ violations.push({ line, reason: 'missing-key', missingKey: key });
+ continue;
+ }
+ violations.push({
+ line,
+ reason: 'unconfirmed-key',
+ unconfirmedKey: key,
+ detail: `the \`env\` object spreads \`${env.unreadableSpread}\`, which may carry it`,
+ });
+ continue;
+ }
+ switch (verdict.kind) {
+ case 'declared':
+ continue;
+ case 'shadowed':
+ violations.push({
+ line,
+ reason: 'unconfirmed-key',
+ unconfirmedKey: key,
+ detail: `the \`env\` object declares it and then spreads \`${verdict.spread}\`, which may replace it`,
+ });
+ continue;
+ case 'cleared':
+ violations.push({ line, reason: 'cleared-key', clearedKey: key });
+ continue;
+ default:
+ assertNeverEnvKeyVerdict(verdict);
+ }
+ }
+ }
+ return { devServerSpawnLines, violations };
+}
+
+const spawnScanCache = new Map<string, SpawnIsolationScan>();
+
+function scanFileSpawnIsolation(file: FileLines): SpawnIsolationScan {
+ const cached = spawnScanCache.get(file.path);
+ if (cached !== undefined) return cached;
+ const scan = scanSpawnIsolation(file.path, file.source);
+ spawnScanCache.set(file.path, scan);
+ return scan;
+}
+
+let plantedSpawnScanSeq = 0;
+
+function scanPlantedSpawnIsolation(lines: string[]): SpawnIsolationScan {
+ plantedSpawnScanSeq += 1;
+ return scanSpawnIsolation(`planted-${plantedSpawnScanSeq}.ts`, lines.join('\n'));
+}
+
+function assertNeverSpawnViolation(violation: never): never {
+ throw new Error(`Unhandled SpawnIsolationViolation reason: ${JSON.stringify(violation)}`);
+}
+
+function describeSpawnViolation(violation: SpawnIsolationViolation): string {
+ switch (violation.reason) {
+ case 'missing-key':
+ return `no ${violation.missingKey} in this spawn's own env option`;
+ case 'unconfirmed-key':
+ return `the guard could not establish that ${violation.unconfirmedKey} reaches the child process: ${violation.detail}, so it is unconfirmed rather than known-absent`;
+ case 'cleared-key':
+ return `this spawn's env option declares ${violation.clearedKey} as \`undefined\`, and Node ignores undefined values in \`env\`, so the key does not reach the child`;
+ case 'undeterminable':
+ return `this spawn's env could not be determined, so the isolation keys are unconfirmed rather than known-absent: ${violation.detail}`;
+ default:
+ return assertNeverSpawnViolation(violation);
+ }
+}
+
+function missingKeysOf(scan: SpawnIsolationScan): RequiredSpawnEnvKey[] {
+ return scan.violations
+ .filter((violation) => violation.reason === 'missing-key')
+ .map((violation) => violation.missingKey)
+ .sort();
+}
+
+function unconfirmedKeysOf(scan: SpawnIsolationScan): RequiredSpawnEnvKey[] {
+ return scan.violations
+ .filter((violation) => violation.reason === 'unconfirmed-key')
+ .map((violation) => violation.unconfirmedKey)
+ .sort();
+}
+
+function clearedKeysOf(scan: SpawnIsolationScan): RequiredSpawnEnvKey[] {
+ return scan.violations
+ .filter((violation) => violation.reason === 'cleared-key')
+ .map((violation) => violation.clearedKey)
+ .sort();
+}
+
+function undeterminableDetails(scan: SpawnIsolationScan): string[] {
+ return scan.violations
+ .filter((violation) => violation.reason === 'undeterminable')
+ .map((violation) => violation.detail);
+}
+
+function mirroredFilesWithDevServerSpawns(files: FileLines[]): string[] {
+ return files
+ .filter((file) => !isMirrorExcluded(file.path))
+ .filter((file) => scanFileSpawnIsolation(file).devServerSpawnLines.length > 0)
+ .map((file) => file.path)
+ .sort();
+}
+
+function requirePinnedSpawnFile(files: FileLines[], path: string): FileLines {
+ const file = files.find((candidate) => candidate.path === path);
+ if (file === undefined) {
+ throw new Error(
+ `${path} is pinned in DEV_SERVER_SPAWN_SITES but is not under the scanned e2e directories — it moved or was renamed, so its dev-server spawn stopped being checked. Point the path literal in DEV_SERVER_SPAWN_SITES at where the file lives now, and add its new parent to E2E_DIRS if the move left the scanned tree.`,
+ );
+ }
+ return file;
+}
+
+function devServerSpawnCallHead(files: FileLines[], path: string): string {
+ const file = requirePinnedSpawnFile(files, path);
+ const line = scanFileSpawnIsolation(file).devServerSpawnLines[0];
+ if (line === undefined) {
+ throw new Error(
+ `${path} is in the scanned corpus but the guard resolves no dev-server spawn call in it, so there is no real call head to harvest the fixture below from. Either the spawn moved — point DEV_SERVER_SPAWN_SITES at its new home — or the call-shape recogniser rotted: it selects a \`spawn\`/\`spawnSync\` call whose command or argv array carries the literal '${DEV_SERVER_ARGV_TOKEN}', so re-anchor SPAWN_CALLEE_NAMES and DEV_SERVER_ARGV_TOKEN on the shape this site now has.`,
+ );
+ }
+ return file.lines[line - 1] ?? '';
}
function isRemoteImageHost(line: string): boolean {
@@ -333,58 +711,446 @@ describe('E2E STOP rule — zero allowlist', () => {
test('e2e files that spawn a dev server must isolate shared mutable state (vite cache + i18n compile)', () => {
const violations: string[] = [];
- for (const file of e2eFiles) {
- for (const v of findSpawnIsolationViolations(file.lines)) {
+ for (const file of e2eTsFiles) {
+ for (const violation of scanFileSpawnIsolation(file).violations) {
violations.push(
- ` ${file.path}:${v.line} spawn('bun', …) without ${v.missingKey} anywhere in the file`,
+ ` ${file.path}:${violation.line} ${describeSpawnViolation(violation)}: ${(file.lines[violation.line - 1] ?? '').trim()}`,
);
}
}
if (violations.length > 0) {
throw new Error(
- `dev-server spawn without shared-state isolation — pass OK_TEST_VITE_CACHE_DIR (via prepareViteCacheDir from ./_helpers, removeAllDuringTeardown in teardown) and OK_TEST_SKIP_I18N_COMPILE: '1' in the spawn env:\n${violations.join('\n')}`,
+ `dev-server spawn without shared-state isolation — pass OK_TEST_VITE_CACHE_DIR (via prepareViteCacheDir from ./_helpers, removeAllDuringTeardown in teardown) and OK_TEST_SKIP_I18N_COMPILE: '1' in the spawn env. A line reported as unconfirmed rather than missing is one this guard could not settle: either it cannot read the spawn's env at all, so inline the env object at the call, or the key is absent from the env object's own properties while a spread may carry it, so declare the key at the call instead of leaving it to the spread, or the key is declared but a spread that follows it may replace it, so move the declaration after the last spread:\n${violations.join('\n')}`,
);
}
});
+ test('the spawn-isolation rule resolves a dev-server spawn in exactly the pinned sites', () => {
+ expect(
+ mirroredFilesWithDevServerSpawns(e2eTsFiles),
+ 'the files in which the guard resolves a dev-server spawn are no longer exactly the pinned dev-server spawn sites. Four causes, four different edits. (1) A pinned file moved or was renamed: update its path literal in DEV_SERVER_SPAWN_SITES, and add its new parent to E2E_DIRS if the move left the scanned tree — editing the call-shape recogniser will not bring it back. (2) The recogniser rotted against a call the corpus really has: it selects a `spawn`/`spawnSync` CallExpression whose command or argv array carries the literal argv token, so re-anchor SPAWN_CALLEE_NAMES and DEV_SERVER_ARGV_TOKEN on that shape. (3) A file listed in NON_DEV_SERVER_SPAWN_SITES now boots a dev server: move it to DEV_SERVER_SPAWN_SITES and give its spawn both isolation env keys. (4) A pinned file stopped parsing under the ts-morph program this guard runs, which is separate from the repo compiler: a file it cannot parse resolves no spawn call at all, and the isolation rule above reports that syntax error for the same file on the same run, so fix the syntax rather than either list. A site that drops out of this set carries no enforced isolation contract however its spawn env changes',
+ ).toEqual([...DEV_SERVER_SPAWN_SITES].sort());
+ });
+
+ test('every child-process call site under the e2e directories is pinned', () => {
+ expect(
+ mirroredFilesWithChildProcessCalls(e2eTsFiles),
+ 'the set of files spawning a child process no longer matches the pinned sites — one was added, renamed, or moved, and the isolation checks above stopped covering it. Add it to DEV_SERVER_SPAWN_SITES and give its spawn both isolation env keys, or, if it does not boot a dev server, add it to NON_DEV_SERVER_SPAWN_SITES. The two lists must stay disjoint: a file in NON_DEV_SERVER_SPAWN_SITES that boots a dev server reds the selection assertion above. Files carrying the mirror-excluded infix are outside this pin because they do not exist on the public mirror; the corpus-wide isolation rule above still scans them',
+ ).toEqual(PINNED_SPAWN_SITES);
+ });
+
+ test('the child-process completeness pin sees namespaced calls and not RegExp.prototype.exec', () => {
+ expect(CHILD_PROCESS_CALL_PATTERN.test("const proc = cp.spawn('pnpm', argv);")).toBe(true);
+ expect(
+ CHILD_PROCESS_CALL_PATTERN.test("childProcess.execFileSync('git', ['init', '-q']);"),
+ ).toBe(true);
+ expect(CHILD_PROCESS_CALL_PATTERN.test('const child = node.fork(workerPath);')).toBe(true);
+ expect(CHILD_PROCESS_CALL_PATTERN.test("execFileSync('git', ['init', '-q']);")).toBe(true);
+ expect(CHILD_PROCESS_CALL_PATTERN.test("exec('ls');")).toBe(true);
+
+ expect(CHILD_PROCESS_CALL_PATTERN.test('const match = re.exec(line);')).toBe(false);
+ expect(CHILD_PROCESS_CALL_PATTERN.test('const match = /a(b)/.exec(line);')).toBe(false);
+ expect(CHILD_PROCESS_CALL_PATTERN.test("const label = 'respawn(';")).toBe(false);
+ expect(CHILD_PROCESS_CALL_PATTERN.test('await page.waitForSelector(sel);')).toBe(false);
+ });
+
test('spawn-isolation rule fires on a planted violation and not on adjacent negatives', () => {
- const planted = [
- "const proc = spawn('bun', ['run', '--silent', 'dev'], {",
- ' env: { ...process.env, VITE_PORT: String(port) },',
- '});',
- ];
- const fired = findSpawnIsolationViolations(planted);
- expect(fired.length).toBe(2);
- expect(fired[0]?.line).toBe(1);
+ const spawnCallHead = devServerSpawnCallHead(e2eTsFiles, DEV_SERVER_SPAWN_SITES[0]);
+
+ const planted = [spawnCallHead, ' env: { ...process.env, VITE_PORT: String(port) },', '});'];
+ const fired = scanPlantedSpawnIsolation(planted);
+ expect(
+ missingKeysOf(fired),
+ `the rule did not report one violation per missing isolation key on ${DEV_SERVER_SPAWN_SITES[0]}'s own spawn call with both keys stripped`,
+ ).toEqual([...SPAWN_REQUIRED_ENV_KEYS].sort());
+ expect(fired.violations[0]?.line).toBe(1);
const compliant = [
- "const proc = spawn('bun', ['run', '--silent', 'dev'], {",
+ spawnCallHead,
" env: { OK_TEST_VITE_CACHE_DIR: dir, OK_TEST_SKIP_I18N_COMPILE: '1' },",
'});',
];
- expect(findSpawnIsolationViolations(compliant).length).toBe(0);
+ expect(scanPlantedSpawnIsolation(compliant).violations).toEqual([]);
const otherSpawn = ["const proc = spawn('node', ['script.js'], { env: {} });"];
- expect(findSpawnIsolationViolations(otherSpawn).length).toBe(0);
+ const otherSpawnScan = scanPlantedSpawnIsolation(otherSpawn);
+ expect(otherSpawnScan.devServerSpawnLines).toEqual([]);
+ expect(otherSpawnScan.violations).toEqual([]);
- const halfCompliant = [
- "const proc = spawn('bun', ['run', '--silent', 'dev'], {",
- ' env: { OK_TEST_VITE_CACHE_DIR: dir },',
- '});',
- ];
- const halfFired = findSpawnIsolationViolations(halfCompliant);
- expect(halfFired.length).toBe(1);
- expect(halfFired[0]?.missingKey).toBe('OK_TEST_SKIP_I18N_COMPILE');
+ const notASpawn = ["const cmd = 'pnpm run dev --host 127.0.0.1';"];
+ expect(scanPlantedSpawnIsolation(notASpawn).devServerSpawnLines).toEqual([]);
- const multiSpawn = [
- "const p1 = spawn('bun', ['run', '--silent', 'dev'], {",
+ const halfCompliant = [spawnCallHead, ' env: { OK_TEST_VITE_CACHE_DIR: dir },', '});'];
+ expect(missingKeysOf(scanPlantedSpawnIsolation(halfCompliant))).toEqual([
+ 'OK_TEST_SKIP_I18N_COMPILE',
+ ]);
+
+ const compliantSibling = [
+ spawnCallHead,
" env: { OK_TEST_VITE_CACHE_DIR: d, OK_TEST_SKIP_I18N_COMPILE: '1' },",
'});',
- "const p2 = spawn('bun', ['run', '--silent', 'dev'], {",
+ ];
+ const secondSpawnUnisolated = [
+ ...compliantSibling,
+ spawnCallHead.replace('const proc', 'const second'),
+ ' env: { VITE_PORT: String(port) },',
+ '});',
+ ];
+ const secondFired = scanPlantedSpawnIsolation(secondSpawnUnisolated);
+ expect(
+ secondFired.violations.map((violation) => violation.line),
+ 'an un-isolated second dev-server spawn is immunised by a compliant sibling in the same file, so the contract is enforced per file rather than per spawn',
+ ).toEqual([4, 4]);
+ expect(missingKeysOf(secondFired)).toEqual([...SPAWN_REQUIRED_ENV_KEYS].sort());
+
+ const twoCompliant = [
+ ...compliantSibling,
+ compliantSibling[0]?.replace('const proc', 'const second') ?? '',
+ ...compliantSibling.slice(1),
+ ];
+ expect(scanPlantedSpawnIsolation(twoCompliant).violations).toEqual([]);
+ });
+
+ test("spawn-isolation rule counts only the keys a spawn's own env object declares", () => {
+ const spawnCallHead = devServerSpawnCallHead(e2eTsFiles, DEV_SERVER_SPAWN_SITES[0]);
+ const bothKeysMissing = [...SPAWN_REQUIRED_ENV_KEYS].sort();
+
+ const keysOnlyInComment = [
+ spawnCallHead,
+ ` // ${SPAWN_REQUIRED_ENV_KEYS.join(' and ')} belong here`,
+ ` // ${SPAWN_REQUIRED_ENV_KEYS[1]}: pending`,
' env: { VITE_PORT: String(port) },',
'});',
];
- expect(findSpawnIsolationViolations(multiSpawn).length).toBe(0);
+ expect(
+ missingKeysOf(scanPlantedSpawnIsolation(keysOnlyInComment)),
+ 'a comment naming the isolation keys satisfied the contract, so the rule asked whether the source spells the key rather than whether the spawn declares it',
+ ).toEqual(bothKeysMissing);
+
+ const keysOnlyInString = [
+ spawnCallHead,
+ ` env: { BANNER: '${SPAWN_REQUIRED_ENV_KEYS[0]}: unset', VITE_PORT: String(port) },`,
+ '});',
+ ];
+ expect(
+ missingKeysOf(scanPlantedSpawnIsolation(keysOnlyInString)),
+ 'a string literal naming an isolation key satisfied the contract, so the rule asked whether the source spells the key rather than whether the spawn declares it',
+ ).toEqual(bothKeysMissing);
+
+ const keysOutsideEnv = [
+ spawnCallHead,
+ ` ${SPAWN_REQUIRED_ENV_KEYS[0]}: viteCacheDir,`,
+ ` ${SPAWN_REQUIRED_ENV_KEYS[1]}: '1',`,
+ ' env: { ...process.env },',
+ '});',
+ ];
+ expect(
+ missingKeysOf(scanPlantedSpawnIsolation(keysOutsideEnv)),
+ 'an isolation key spelled as a sibling of `env` rather than inside it satisfied the contract, so the spawn passes the guard while the child process never receives the variable',
+ ).toEqual(bothKeysMissing);
+
+ const inheritedEnvOnly = [spawnCallHead, ' env: { ...process.env },', '});'];
+ expect(
+ missingKeysOf(scanPlantedSpawnIsolation(inheritedEnvOnly)),
+ 'a bare `...process.env` spread satisfied the contract, but a spread declares no named key and the parent env is exactly the shared state this contract isolates against',
+ ).toEqual(bothKeysMissing);
+
+ const noOptionsArgument = ["const proc = spawn('pnpm', ['run', 'dev', '--host', '::1']);"];
+ expect(
+ missingKeysOf(scanPlantedSpawnIsolation(noOptionsArgument)),
+ 'a dev-server spawn with no options argument at all declares no env, so both keys are definitively absent rather than unreadable',
+ ).toEqual(bothKeysMissing);
+
+ const shorthandEntries = [
+ spawnCallHead,
+ ` env: { ...process.env, ${SPAWN_REQUIRED_ENV_KEYS[0]}, ${SPAWN_REQUIRED_ENV_KEYS[1]} },`,
+ '});',
+ ];
+ expect(
+ scanPlantedSpawnIsolation(shorthandEntries).violations,
+ 'shorthand env entries declare the keys just as a property assignment does, so reporting them missing would push authors off a legal form',
+ ).toEqual([]);
+
+ const quotedKeyNames = [
+ spawnCallHead,
+ ` env: { '${SPAWN_REQUIRED_ENV_KEYS[0]}': dir, '${SPAWN_REQUIRED_ENV_KEYS[1]}': '1' },`,
+ '});',
+ ];
+ expect(
+ scanPlantedSpawnIsolation(quotedKeyNames).violations,
+ 'string-literal property names declare the keys just as bare identifiers do',
+ ).toEqual([]);
+ });
+
+ test('spawn-isolation rule reports an env it cannot read as unconfirmed, not as a missing key', () => {
+ const spawnCallHead = devServerSpawnCallHead(e2eTsFiles, DEV_SERVER_SPAWN_SITES[0]);
+
+ const cases: Array<{ label: string; lines: string[]; detailIncludes: string }> = [
+ {
+ label: 'env built by a call expression',
+ lines: [spawnCallHead, ' env: buildWorkerEnv(port, viteCacheDir),', '});'],
+ detailIncludes: 'buildWorkerEnv(port, viteCacheDir)',
+ },
+ {
+ label: 'env passed by shorthand',
+ lines: [spawnCallHead, ' env,', '});'],
+ detailIncludes: 'shorthand',
+ },
+ {
+ label: 'options spread with no own env',
+ lines: [spawnCallHead, ' ...baseSpawnOptions,', ' cwd: APP_PACKAGE_ROOT,', '});'],
+ detailIncludes: 'declares no own `env`',
+ },
+ {
+ label: 'options spread after env',
+ lines: [
+ spawnCallHead,
+ " env: { OK_TEST_VITE_CACHE_DIR: d, OK_TEST_SKIP_I18N_COMPILE: '1' },",
+ ' ...overrides,',
+ '});',
+ ],
+ detailIncludes: 'after `env`',
+ },
+ {
+ label: 'computed env key',
+ lines: [
+ spawnCallHead,
+ " env: { [CACHE_DIR_VAR]: d, OK_TEST_SKIP_I18N_COMPILE: '1' },",
+ '});',
+ ],
+ detailIncludes: 'computed key',
+ },
+ {
+ label: 'call extent never closes',
+ lines: [
+ spawnCallHead,
+ " env: { OK_TEST_VITE_CACHE_DIR: d, OK_TEST_SKIP_I18N_COMPILE: '1',",
+ ],
+ detailIncludes: 'does not parse',
+ },
+ ];
+
+ for (const { label, lines, detailIncludes } of cases) {
+ const scan = scanPlantedSpawnIsolation(lines);
+ expect(
+ missingKeysOf(scan),
+ `${label}: reported as a missing isolation key, so the failure sends a reader looking for a key that is not the problem — the guard could not read this spawn's env at all`,
+ ).toEqual([]);
+ const details = undeterminableDetails(scan);
+ expect(
+ details.length,
+ `${label}: the guard read an env it has no way to read, so a spawn whose isolation cannot be established passes as compliant`,
+ ).toBe(1);
+ expect(details[0]).toContain(detailIncludes);
+ }
+
+ const unparseable = scanPlantedSpawnIsolation([
+ spawnCallHead,
+ " env: { OK_TEST_VITE_CACHE_DIR: d, OK_TEST_SKIP_I18N_COMPILE: '1',",
+ ]);
+ expect(
+ unparseable.devServerSpawnLines,
+ 'a file the guard cannot parse still resolved a dev-server spawn, so the gate-population anchor below would not drop such a file and the parse cause it names could never arise',
+ ).toEqual([]);
+ });
+
+ test('spawn-isolation rule reports a key a foreign env spread may carry as unconfirmed', () => {
+ const spawnCallHead = devServerSpawnCallHead(e2eTsFiles, DEV_SERVER_SPAWN_SITES[0]);
+
+ const foreignSpread = [
+ spawnCallHead,
+ ` env: { ...process.env, ...workerServerEnv, ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir },`,
+ '});',
+ ];
+ const scan = scanPlantedSpawnIsolation(foreignSpread);
+ expect(
+ missingKeysOf(scan),
+ "a key absent from an env object's own properties was reported known-absent while the object spreads another one that may carry it, so the failure sends a reader after a key the guard never looked for",
+ ).toEqual([]);
+ expect(
+ unconfirmedKeysOf(scan),
+ 'the key a foreign spread may carry was not reported at all, so a spawn whose isolation cannot be established passes as compliant',
+ ).toEqual([SPAWN_REQUIRED_ENV_KEYS[1]]);
+ expect(
+ scan.violations.map(describeSpawnViolation).join('\n'),
+ 'the unconfirmed verdict does not name the spread that hid the key, so a reader cannot tell why the guard could not see it',
+ ).toContain('workerServerEnv');
+
+ const declaredBesideForeignSpread = [
+ spawnCallHead,
+ ` env: { ...process.env, ...workerServerEnv, ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir, ${SPAWN_REQUIRED_ENV_KEYS[1]}: '1' },`,
+ '});',
+ ];
+ expect(
+ scanPlantedSpawnIsolation(declaredBesideForeignSpread).violations,
+ 'a foreign spread made a spawn that declares both isolation keys outright report as un-isolated, which is the shape the real worker fixture spawns with',
+ ).toEqual([]);
+
+ const trailingForeignSpread = [
+ spawnCallHead,
+ ` env: { ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir, ${SPAWN_REQUIRED_ENV_KEYS[1]}: '1', ...workerServerEnv },`,
+ '});',
+ ];
+ const trailingScan = scanPlantedSpawnIsolation(trailingForeignSpread);
+ expect(
+ missingKeysOf(trailingScan),
+ 'a key the env object declares outright was reported known-absent, so the failure sends a reader after a key that is spelled at the call',
+ ).toEqual([]);
+ expect(
+ unconfirmedKeysOf(trailingScan),
+ 'a foreign spread placed after both declared keys cleared the spawn, but a later spread overrides same-name properties and may hand the child an undefined the runtime then drops from its env, so the isolation this guard exists to establish is not established',
+ ).toEqual([...SPAWN_REQUIRED_ENV_KEYS].sort());
+ expect(
+ trailingScan.violations.map(describeSpawnViolation).join('\n'),
+ 'the unconfirmed verdict does not name the trailing spread or say that it may replace the declared key, so a reader is told the key is absent when the real problem is that the declaration is positioned before the spread',
+ ).toContain('workerServerEnv');
+ expect(
+ trailingScan.violations.map(describeSpawnViolation).join('\n'),
+ 'the unconfirmed verdict does not put the trailing spread on the replace axis, so the remedy a reader reaches for is to declare a key that is already declared',
+ ).toContain('may replace it');
+
+ const trailingParentEnvSpread = [
+ spawnCallHead,
+ ` env: { ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir, ${SPAWN_REQUIRED_ENV_KEYS[1]}: '1', ...${PARENT_ENV_SPREAD} },`,
+ '});',
+ ];
+ const trailingParentScan = scanPlantedSpawnIsolation(trailingParentEnvSpread);
+ expect(
+ missingKeysOf(trailingParentScan),
+ 'a key the env object declares outright was reported known-absent when the trailing spread is the parent env',
+ ).toEqual([]);
+ expect(
+ unconfirmedKeysOf(trailingParentScan),
+ 'a trailing `...process.env` cleared the spawn: the carve-out that lets a parent-env spread stand where no key is declared is about whether the parent can SUPPLY a key, and it does not extend to a parent env spread that REPLACES a declared key with exactly the shared value this contract isolates against',
+ ).toEqual([...SPAWN_REQUIRED_ENV_KEYS].sort());
+
+ const spreadBetweenDeclaredKeys = [
+ spawnCallHead,
+ ` env: { ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir, ...overrides, ${SPAWN_REQUIRED_ENV_KEYS[1]}: '1' },`,
+ '});',
+ ];
+ const betweenScan = scanPlantedSpawnIsolation(spreadBetweenDeclaredKeys);
+ expect(
+ missingKeysOf(betweenScan),
+ 'a key declared on either side of a spread was reported known-absent',
+ ).toEqual([]);
+ expect(
+ unconfirmedKeysOf(betweenScan),
+ 'the verdict is not positional: only the key declared BEFORE the spread can be replaced by it, so reporting the key declared after it too makes any spread poison the whole env object and the guard stops discriminating between the two positions',
+ ).toEqual([SPAWN_REQUIRED_ENV_KEYS[0]]);
+
+ const redeclaredAfterSpread = [
+ spawnCallHead,
+ ` env: { ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir, ...overrides, ${SPAWN_REQUIRED_ENV_KEYS[0]}: fallbackDir, ${SPAWN_REQUIRED_ENV_KEYS[1]}: '1' },`,
+ '});',
+ ];
+ expect(
+ scanPlantedSpawnIsolation(redeclaredAfterSpread).violations,
+ 're-declaring a key after the last spread is the escape hatch out of the shadowed verdict — the spread cannot replace what follows it — and closing it leaves an author who took the remedy the failure message prescribes with no way to green the guard',
+ ).toEqual([]);
+ });
+
+ test('spawn-isolation rule reports a key whose declared value is `undefined` as cleared', () => {
+ const spawnCallHead = devServerSpawnCallHead(e2eTsFiles, DEV_SERVER_SPAWN_SITES[0]);
+
+ const oneKeyCleared = [
+ spawnCallHead,
+ ` env: { ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir, ${SPAWN_REQUIRED_ENV_KEYS[1]}: undefined },`,
+ '});',
+ ];
+ const clearedScan = scanPlantedSpawnIsolation(oneKeyCleared);
+ expect(
+ clearedKeysOf(clearedScan),
+ 'a key spelled in the env object with the value `undefined` counted as declared, but Node drops undefined values out of `env` before the child starts, so the child runs against the shared vite cache and the shared i18n compile exactly as if the key had never been written',
+ ).toEqual([SPAWN_REQUIRED_ENV_KEYS[1]]);
+ expect(
+ clearedScan.violations.length,
+ 'a key cleared to `undefined` produced a verdict per required key rather than one for the key that is cleared, so the failure names a compliant key too',
+ ).toBe(1);
+ expect(
+ missingKeysOf(clearedScan),
+ 'a key the env object spells outright was reported known-absent, so the failure sends a reader looking for a key that is written at the call and points away from the value that drops it',
+ ).toEqual([]);
+ expect(
+ clearedScan.violations.map(describeSpawnViolation).join('\n'),
+ 'the cleared verdict does not say that the value is `undefined` and that Node drops it, so a reader who can see the key at the call has no way to tell what the guard objects to',
+ ).toContain('undefined');
+
+ const bothKeysCleared = [
+ spawnCallHead,
+ ` env: { ${SPAWN_REQUIRED_ENV_KEYS[0]}: undefined, ${SPAWN_REQUIRED_ENV_KEYS[1]}: undefined },`,
+ '});',
+ ];
+ expect(
+ clearedKeysOf(scanPlantedSpawnIsolation(bothKeysCleared)),
+ 'an env object that clears both isolation keys reported fewer than one verdict per cleared key, so an author who fixes the one that is named is told the spawn is compliant while the other key still never reaches the child',
+ ).toEqual([...SPAWN_REQUIRED_ENV_KEYS].sort());
+
+ const voidOperatorValue = [
+ spawnCallHead,
+ ` env: { ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir, ${SPAWN_REQUIRED_ENV_KEYS[1]}: void 0 },`,
+ '});',
+ ];
+ expect(
+ clearedKeysOf(scanPlantedSpawnIsolation(voidOperatorValue)),
+ 'a key written `void 0` counted as declared, but `void` evaluates to `undefined` whatever operand follows it, so Node drops the key out of `env` exactly as it drops a bare `undefined` and the child runs against the shared vite cache and the shared i18n compile',
+ ).toEqual([SPAWN_REQUIRED_ENV_KEYS[1]]);
+
+ const voidCallValue = [
+ spawnCallHead,
+ ` env: { ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir, ${SPAWN_REQUIRED_ENV_KEYS[1]}: void resolveFlag() },`,
+ '});',
+ ];
+ expect(
+ clearedKeysOf(scanPlantedSpawnIsolation(voidCallValue)),
+ 'a `void` whose operand is a call counted as declared, but the operand is discarded and only its side effects run, so the key reaches the child no more than `void 0` does and no reading of the operand could produce another verdict',
+ ).toEqual([SPAWN_REQUIRED_ENV_KEYS[1]]);
+
+ const clearedThenRedeclared = [
+ spawnCallHead,
+ ` env: { ${SPAWN_REQUIRED_ENV_KEYS[1]}: undefined, ${SPAWN_REQUIRED_ENV_KEYS[0]}: dir, ${SPAWN_REQUIRED_ENV_KEYS[1]}: '1' },`,
+ '});',
+ ];
+ expect(
+ scanPlantedSpawnIsolation(clearedThenRedeclared).violations,
+ 'a key cleared to `undefined` and then re-declared with a real value reported as cleared, but object literals are last-wins, so the child does receive the key and the guard reds a spawn that is isolated',
+ ).toEqual([]);
+ });
+
+ test('spawn-isolation rule clears compliant spawns whose env values carry operators or span lines', () => {
+ const spawnCallHead = devServerSpawnCallHead(e2eTsFiles, DEV_SERVER_SPAWN_SITES[0]);
+
+ const divisionInEnvValue = [
+ spawnCallHead,
+ ' env: {',
+ ' ...process.env,',
+ ' OK_TEST_VITE_CACHE_DIR: viteCacheDir,',
+ " OK_TEST_SKIP_I18N_COMPILE: '1',",
+ ' OK_TEST_BOOT_BUDGET_MS: String(budgetMs(workerCount) / 2),',
+ ' },',
+ '});',
+ ];
+ expect(
+ scanPlantedSpawnIsolation(divisionInEnvValue).violations,
+ 'a division operator in an env value made a fully compliant spawn report as un-isolated, so ordinary arithmetic in a spawn env reds this guard',
+ ).toEqual([]);
+
+ const multiLineTemplateEnvValue = [
+ spawnCallHead,
+ ' env: {',
+ ' ...process.env,',
+ ' OK_TEST_VITE_CACHE_DIR: viteCacheDir,',
+ " OK_TEST_SKIP_I18N_COMPILE: '1',",
+ ' OK_TEST_BANNER: `worker boot',
+ ` port \${port}`,
+ ` cache \${viteCacheDir}\`,`,
+ ' },',
+ '});',
+ ];
+ expect(
+ scanPlantedSpawnIsolation(multiLineTemplateEnvValue).violations,
+ 'an env value spelled as a multi-line template literal made a fully compliant spawn report as un-isolated',
+ ).toEqual([]);
});
test('dev-harness import rule fires on a static import and not on the sanctioned shapes', () => {
@@ -538,7 +1304,7 @@ describe('E2E STOP rule — zero allowlist', () => {
'scripts/i18n-compile-unless-skipped.sh (the OK_TEST_SKIP_I18N_COMPILE guard).',
);
}
- if (/\b(?:bun run i18n:compile|lingui compile)\b/.test(predev)) {
+ if (/i18n:compile|\blingui compile\b/.test(predev)) {
errors.push(
'packages/app/package.json "predev" invokes the i18n compile directly, bypassing the ' +
'OK_TEST_SKIP_I18N_COMPILE guard — every concurrent e2e dev-server boot then rewrites ' +
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 6fcdc23f2..4fc2c11f9 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 40b5cdfd6..9f2f6feb6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 93666af70..2a085742b 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 867598d34..878d5196b 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 0970ac12f..4ada3cf26 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index b632185e1..cbe2b705f 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,3 +1,4 @@
+
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index c530ce4ba..89bc9b4d9 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index d3767adc9..a78aeb0e4 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,3 +1,4 @@
+
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index b076f955c..e7cc69c3f 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 7935e35f8..9ddcd0730 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/meta/i18n-catalog-freshness.test.ts b/packages/app/tests/meta/i18n-catalog-freshness.test.ts
new file mode 100644
index 000000000..f5f32e304
--- /dev/null
+++ b/packages/app/tests/meta/i18n-catalog-freshness.test.ts
@@ -0,0 +1,311 @@
+import { spawnSync } from 'node:child_process';
+import {
+ copyFileSync,
+ cpSync,
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { createRequire } from 'node:module';
+import { dirname, join } from 'node:path';
+import { describe, expect, test, vi } from 'vitest';
+import {
+ assertI18nCatalogsFresh,
+ COMPILE_TIMEOUT_MS,
+ describeCompileFailure,
+ findStaleCatalogLocales,
+ linguiBinEntry,
+ linguiBinEntryFrom,
+} from '../stress/_helpers/i18n-catalog-freshness.ts';
+import { APP_PACKAGE_ROOT } from '../stress/_helpers/seed-key.ts';
+import { withTempDir } from '../temp-dir.test-helper.ts';
+
+vi.mock('node:fs', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:fs')>();
+ return { ...actual, rmSync: vi.fn(actual.rmSync) };
+});
+
+const { rmSync: actualRmSync } = await vi.importActual<typeof import('node:fs')>('node:fs');
+const mockedRm = vi.mocked(rmSync);
+
+const TEMP_DIR_PREFIX = 'ok-i18n-catalog-freshness-';
+const SCRATCH_DIR_MARKER = '.ok-i18n-freshness-';
+const EDITED_LOCALE = 'es';
+const UNCOMPILED_LOCALE = 'fr';
+const UNCONFIGURED_LOCALE = 'xx';
+const PROBE_TRANSLATION = 'catalog freshness probe';
+const PLAIN_MSGSTR = /^msgstr "([^"\\{}#]+)"$/m;
+
+function buildAppPackageFixture(fixtureRoot: string): string {
+ copyFileSync(join(APP_PACKAGE_ROOT, 'lingui.config.ts'), join(fixtureRoot, 'lingui.config.ts'));
+ cpSync(join(APP_PACKAGE_ROOT, 'src', 'locales'), join(fixtureRoot, 'src', 'locales'), {
+ recursive: true,
+ });
+ return fixtureRoot;
+}
+
+function editOneTranslation(fixtureRoot: string, locale: string): void {
+ const catalogPath = join(fixtureRoot, 'src', 'locales', locale, 'messages.po');
+ const catalog = readFileSync(catalogPath, 'utf-8');
+ const target = PLAIN_MSGSTR.exec(catalog);
+ expect(
+ target,
+ `the mutation this test relies on never landed: ${locale}/messages.po carries no single-line plain msgstr to edit, so a green result below would prove nothing`,
+ ).not.toBeNull();
+ writeFileSync(
+ catalogPath,
+ catalog.replace(PLAIN_MSGSTR, `msgstr "${PROBE_TRANSLATION}"`),
+ 'utf-8',
+ );
+}
+
+function raiseFrom(run: () => void): unknown {
+ try {
+ run();
+ } catch (err) {
+ return err;
+ }
+ return undefined;
+}
+
+describe('i18n catalog freshness', { timeout: COMPILE_TIMEOUT_MS + 30_000 }, () => {
+ test('an untouched checkout reports no stale locale', async () => {
+ await withTempDir(TEMP_DIR_PREFIX, async (fixtureRoot) => {
+ const appPackageRoot = buildAppPackageFixture(fixtureRoot);
+
+ expect(
+ findStaleCatalogLocales(appPackageRoot),
+ 'a locale named here on an unmodified copy of this checkout means either the predicate over-fires — which would red every local Playwright run — or the committed catalogs really are stale and `pnpm run i18n` was never re-run',
+ ).toEqual([]);
+ });
+ });
+
+ test('editing a translation without recompiling marks only that locale stale', async () => {
+ await withTempDir(TEMP_DIR_PREFIX, async (fixtureRoot) => {
+ const appPackageRoot = buildAppPackageFixture(fixtureRoot);
+
+ editOneTranslation(appPackageRoot, EDITED_LOCALE);
+
+ expect(
+ findStaleCatalogLocales(appPackageRoot),
+ 'an edited messages.po whose messages.json was never recompiled is exactly the case every Playwright dev-server spawn now skips the compile for, and a predicate that names sibling locales too would train readers to ignore it',
+ ).toEqual([EDITED_LOCALE]);
+ });
+ });
+
+ test('a compiled catalog that was never written marks its locale stale', async () => {
+ await withTempDir(TEMP_DIR_PREFIX, async (fixtureRoot) => {
+ const appPackageRoot = buildAppPackageFixture(fixtureRoot);
+
+ rmSync(join(appPackageRoot, 'src', 'locales', UNCOMPILED_LOCALE, 'messages.json'));
+
+ expect(
+ findStaleCatalogLocales(appPackageRoot),
+ 'a locale whose messages.json is absent has nothing for the app to serve, so treating a missing file as fresh would be the emptiest pass of all',
+ ).toEqual([UNCOMPILED_LOCALE]);
+ });
+ });
+
+ test('the failure names the stale locale and the command that fixes it', async () => {
+ await withTempDir(TEMP_DIR_PREFIX, async (fixtureRoot) => {
+ const appPackageRoot = buildAppPackageFixture(fixtureRoot);
+ editOneTranslation(appPackageRoot, EDITED_LOCALE);
+
+ const raised = raiseFrom(() => assertI18nCatalogsFresh(appPackageRoot));
+
+ expect(
+ raised,
+ 'a stale catalog that does not throw leaves the run serving committed copy while its assertions read like the edit landed',
+ ).toBeInstanceOf(Error);
+ expect(
+ (raised as Error).message,
+ 'the reader has to be told which locale drifted and which command recompiles it, or the failure points nowhere near its cause',
+ ).toContain(EDITED_LOCALE);
+ expect((raised as Error).message).toContain('pnpm run i18n');
+ expect((raised as Error).message).toContain(appPackageRoot);
+ });
+ });
+
+ test('a fresh checkout raises nothing', async () => {
+ await withTempDir(TEMP_DIR_PREFIX, async (fixtureRoot) => {
+ const appPackageRoot = buildAppPackageFixture(fixtureRoot);
+
+ expect(
+ () => assertI18nCatalogsFresh(appPackageRoot),
+ 'a guard that throws on a clean tree would be routed around within a day',
+ ).not.toThrow();
+ });
+ });
+
+ test('a source catalog no configured locale compiles is an outcome of its own, not a pass', async () => {
+ await withTempDir(TEMP_DIR_PREFIX, async (fixtureRoot) => {
+ const appPackageRoot = buildAppPackageFixture(fixtureRoot);
+ const orphanDir = join(appPackageRoot, 'src', 'locales', UNCONFIGURED_LOCALE);
+ mkdirSync(orphanDir, { recursive: true });
+ copyFileSync(
+ join(appPackageRoot, 'src', 'locales', UNCOMPILED_LOCALE, 'messages.po'),
+ join(orphanDir, 'messages.po'),
+ );
+
+ const raised = raiseFrom(() => assertI18nCatalogsFresh(appPackageRoot));
+
+ expect(
+ raised,
+ 'a locale absent from both sides compares null to null, so calling it fresh is a comparison whose only possible answer is pass — the shape this guard exists to close',
+ ).toBeInstanceOf(Error);
+ expect((raised as Error).message).toContain(UNCONFIGURED_LOCALE);
+ expect(
+ (raised as Error).message,
+ 'reporting it merely stale would prescribe `pnpm run i18n`, which is config-scoped and can never write a catalog for a locale the config omits, so the red would be unclearable',
+ ).toContain('does not list the locale');
+ expect((raised as Error).message).toContain('lingui.config.ts');
+ });
+ });
+
+ test('a malformed compiled catalog names the file that will not parse', async () => {
+ await withTempDir(TEMP_DIR_PREFIX, async (fixtureRoot) => {
+ const appPackageRoot = buildAppPackageFixture(fixtureRoot);
+ const malformed = join(appPackageRoot, 'src', 'locales', EDITED_LOCALE, 'messages.json');
+ writeFileSync(malformed, '{', 'utf-8');
+
+ const raised = raiseFrom(() => findStaleCatalogLocales(appPackageRoot));
+
+ expect(raised).toBeInstanceOf(Error);
+ expect(
+ (raised as Error).message,
+ 'up to 26 catalogs are read per run, so a bare SyntaxError with a character offset names none of them and the reader cannot tell which file to open',
+ ).toContain(malformed);
+ });
+ });
+
+ test('a scratch-directory cleanup failure does not mask the staleness it was cleaning up after', async () => {
+ await withTempDir(TEMP_DIR_PREFIX, async (fixtureRoot) => {
+ const appPackageRoot = buildAppPackageFixture(fixtureRoot);
+ editOneTranslation(appPackageRoot, EDITED_LOCALE);
+
+ const untolerated: NodeJS.ErrnoException = Object.assign(new Error('rm EMFILE'), {
+ code: 'EMFILE',
+ });
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ let removed: string | undefined;
+ mockedRm.mockImplementation((target, options) => {
+ actualRmSync(target, options);
+ if (String(target).includes(SCRATCH_DIR_MARKER)) {
+ removed = String(target);
+ throw untolerated;
+ }
+ });
+
+ let raised: unknown;
+ let warnings: string[] = [];
+ try {
+ raised = raiseFrom(() => assertI18nCatalogsFresh(appPackageRoot));
+ warnings = warn.mock.calls.map((call) => String(call[0]));
+ } finally {
+ mockedRm.mockImplementation(actualRmSync);
+ warn.mockRestore();
+ }
+
+ expect(
+ removed,
+ 'the errno never reached the cleanup path, so this test would pass without exercising anything',
+ ).toBeDefined();
+ expect(
+ (raised as Error | undefined)?.message,
+ 'an rm errno on a scratch dir under node_modules is not a freshness signal, and letting a finally-throw supersede the verdict hands the operator an unrelated filesystem error instead of the stale locale',
+ ).toContain('i18n catalogs are stale for');
+ expect(
+ warnings.join('\n'),
+ 'a scratch directory that could not be reclaimed has to leave a trace, or the downgrade turns a real leak into silence',
+ ).toContain(SCRATCH_DIR_MARKER);
+ });
+ });
+});
+
+describe('lingui entry-point resolution', () => {
+ test('resolves the entry the package manifest declares as its bin', () => {
+ const require_ = createRequire(import.meta.url);
+ const packageRoot = join(dirname(require_.resolve('@lingui/cli')), '..');
+ const manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf-8')) as {
+ bin: Record<string, string>;
+ };
+
+ expect(
+ linguiBinEntry(),
+ 'a path assembled from a literal dist filename is not part of the package contract, so a rename inside a caret-range bump would kill three tiers in globalSetup with no semver break to warn anyone',
+ ).toBe(join(packageRoot, manifest.bin.lingui));
+ expect(existsSync(linguiBinEntry())).toBe(true);
+ });
+
+ test('names the package and the root it assumed when the manifest is not where the depth assumption puts it', async () => {
+ await withTempDir(TEMP_DIR_PREFIX, async (root) => {
+ const movedRoot = join(root, 'moved');
+ const movedEntry = join(movedRoot, 'esm', 'index.js');
+
+ const raised = raiseFrom(() => linguiBinEntryFrom(movedRoot, movedEntry));
+
+ expect(
+ (raised as Error | undefined)?.message,
+ 'a globalSetup that dies on a bare ENOENT naming a package.json path lands ahead of any browser on three tiers and points at neither i18n freshness nor @lingui/cli resolution',
+ ).toContain('@lingui/cli');
+ expect((raised as Error).message).toContain('one directory above');
+ expect((raised as Error).message).toContain(movedEntry);
+ });
+ });
+});
+
+describe('compile-failure diagnosis', () => {
+ test('names the budget when the compile was killed for exceeding it', () => {
+ expect(
+ describeCompileFailure({
+ status: null,
+ signal: 'SIGTERM',
+ error: Object.assign(new Error('spawnSync ETIMEDOUT'), { code: 'ETIMEDOUT' }),
+ }),
+ 'a timeout that renders as a bare SIGTERM is indistinguishable from an external kill, and never names the budget it blew',
+ ).toContain(`did not finish within ${COMPILE_TIMEOUT_MS}ms`);
+ });
+
+ test('reports the raw exit for a kill it did not schedule', () => {
+ expect(describeCompileFailure({ status: null, signal: 'SIGTERM', error: undefined })).toBe(
+ 'lingui compile exited null on SIGTERM',
+ );
+ });
+
+ test('names the errno when the compile never ran', () => {
+ const launch = spawnSync(join(APP_PACKAGE_ROOT, 'no-such-lingui-bin'), [], {
+ encoding: 'utf-8',
+ });
+
+ expect(
+ launch.error,
+ 'the spawn succeeded, so this test would pass without exercising anything',
+ ).toBeDefined();
+ expect(
+ describeCompileFailure(launch),
+ 'a launch failure renders as a bare exit status while the child wrote none of the stdout/stderr the outer throw appends, so the operator gets an empty message and no cause',
+ ).toContain('ENOENT');
+ });
+
+ test('an output-overflow kill does not render as an external one', () => {
+ const overflow = spawnSync(
+ process.execPath,
+ ['-e', "process.stdout.write('x'.repeat(2000000))"],
+ {
+ encoding: 'utf-8',
+ maxBuffer: 1024,
+ },
+ );
+
+ expect(
+ overflow.signal,
+ 'the cap was not exceeded, so this test would pass without exercising anything',
+ ).toBe('SIGTERM');
+ expect(
+ describeCompileFailure(overflow),
+ 'spawnSync kills the child with SIGTERM on maxBuffer overflow, so an ENOBUFS compile is byte-identical to a kill nobody scheduled',
+ ).not.toBe('lingui compile exited null on SIGTERM');
+ });
+});
diff --git a/packages/app/tests/meta/i18n-freshness-gate-wiring.test.ts b/packages/app/tests/meta/i18n-freshness-gate-wiring.test.ts
new file mode 100644
index 000000000..179862973
--- /dev/null
+++ b/packages/app/tests/meta/i18n-freshness-gate-wiring.test.ts
@@ -0,0 +1,267 @@
+import { spawnSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+
+const APP_PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+const WORKSPACE_ROOT = join(APP_PACKAGE_ROOT, '..', '..');
+const APP_PACKAGE_NAME = '@inkeep/open-knowledge-app';
+const FRESHNESS_GLOBAL_SETUP = './tests/stress/_helpers/i18n-catalog-freshness.ts';
+const TURBO_DRY_RUN_TIMEOUT_MS = 120_000;
+const TURBO_DRY_RUN_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
+const TURBO_OUTPUT_HEAD_CHARS = 400;
+
+const PLAYWRIGHT_TIERS = {
+ e2e: {
+ configFile: 'playwright.config.ts',
+ turboTask: 'test:e2e',
+ load: () => import('../../playwright.config'),
+ },
+ a11y: {
+ configFile: 'playwright.a11y.config.ts',
+ turboTask: 'test:a11y',
+ load: () => import('../../playwright.a11y.config'),
+ },
+ visual: {
+ configFile: 'playwright.visual.config.ts',
+ turboTask: 'test:visual',
+ load: () => import('../../playwright.visual.config'),
+ },
+} as const;
+
+type TierName = keyof typeof PLAYWRIGHT_TIERS;
+const TIER_NAMES = Object.keys(PLAYWRIGHT_TIERS) as TierName[];
+
+type TurboTaskDefinition = Record<string, unknown>;
+type TurboDryRun = {
+ tasks: { taskId: string; dependencies: string[]; resolvedTaskDefinition?: TurboTaskDefinition }[];
+};
+
+const SCOPED_OVERRIDE_TASKS = ['test:a11y', 'test:visual'] as const;
+
+let unfilteredDefinitions: Map<string, TurboTaskDefinition> | undefined;
+
+let resolvedGraph: Map<string, string[]> | undefined;
+
+function turboOutputHead(stdout: string): string {
+ if (stdout.length === 0) return 'empty';
+ const head = stdout.slice(0, TURBO_OUTPUT_HEAD_CHARS);
+ return `${stdout.length} chars, of which the first ${head.length} are:\n${head}`;
+}
+
+export function parseTurboDryRun(stdout: string, invocation: string): TurboDryRun {
+ const objectStart = stdout.indexOf('{');
+ if (objectStart < 0) {
+ throw new Error(
+ `${invocation} exited 0 but wrote no "{" to stdout, so the Playwright tiers' build ordering was never checked. turbo documents no stream or shape contract for --dry=json (its machine-readable guarantees attach to --json and --log-file), so an upgrade inside the declared ^2.7.0 range may have moved the payload to stderr or dropped it. stdout was ${turboOutputHead(stdout)}`,
+ );
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(stdout.slice(objectStart));
+ } catch (cause) {
+ throw new Error(
+ `${invocation} wrote stdout that is not JSON from its first "{" onward, so the Playwright tiers' build ordering was never checked. turbo documents no shape contract for --dry=json, so an upgrade inside the declared ^2.7.0 range may have interleaved log lines into the payload. stdout was ${turboOutputHead(stdout)}`,
+ { cause },
+ );
+ }
+ const tasks = (parsed as { tasks?: unknown } | null)?.tasks;
+ if (!Array.isArray(tasks)) {
+ throw new Error(
+ `${invocation} produced JSON with no "tasks" array, so the Playwright tiers' build ordering was never checked. turbo's --dry=json field list is explicitly non-exhaustive and carries no shape contract, so an upgrade inside the declared ^2.7.0 range may have renamed or nested it. stdout was ${turboOutputHead(stdout)}`,
+ );
+ }
+ return parsed as TurboDryRun;
+}
+
+function turboResolvedGraph(): Map<string, string[]> {
+ if (resolvedGraph) return resolvedGraph;
+ const turboBin = join(WORKSPACE_ROOT, 'node_modules', '.bin', 'turbo');
+ const turboArgs = [
+ 'run',
+ ...TIER_NAMES.map((tier) => PLAYWRIGHT_TIERS[tier].turboTask),
+ '--dry=json',
+ `--filter=${APP_PACKAGE_NAME}`,
+ ];
+ const dryRun = spawnSync(turboBin, turboArgs, {
+ cwd: WORKSPACE_ROOT,
+ encoding: 'utf-8',
+ timeout: TURBO_DRY_RUN_TIMEOUT_MS,
+ maxBuffer: TURBO_DRY_RUN_MAX_BUFFER_BYTES,
+ });
+ if (dryRun.error || dryRun.status !== 0) {
+ throw new Error(
+ `could not resolve turbo's task graph, so this run cannot tell whether a Playwright tier races the app build that rewrites src/locales/*/messages.json — ${turboBin} exited ${String(dryRun.status)}${dryRun.signal ? ` on ${dryRun.signal}` : ''}${dryRun.error ? ` (${String(dryRun.error)})` : ''}:\n${dryRun.stderr ?? ''}${dryRun.stdout ?? ''}`,
+ );
+ }
+ const parsed = parseTurboDryRun(
+ dryRun.stdout ?? '',
+ `${turboBin} ${turboArgs.join(' ')} (cwd ${WORKSPACE_ROOT})`,
+ );
+ resolvedGraph = new Map(parsed.tasks.map((task) => [task.taskId, task.dependencies]));
+ return resolvedGraph;
+}
+
+function turboUnfilteredDefinitions(): Map<string, TurboTaskDefinition> {
+ if (unfilteredDefinitions) return unfilteredDefinitions;
+ const turboBin = join(WORKSPACE_ROOT, 'node_modules', '.bin', 'turbo');
+ const turboArgs = ['run', ...SCOPED_OVERRIDE_TASKS, '--dry=json'];
+ const dryRun = spawnSync(turboBin, turboArgs, {
+ cwd: WORKSPACE_ROOT,
+ encoding: 'utf-8',
+ timeout: TURBO_DRY_RUN_TIMEOUT_MS,
+ maxBuffer: TURBO_DRY_RUN_MAX_BUFFER_BYTES,
+ });
+ if (dryRun.error || dryRun.status !== 0) {
+ throw new Error(
+ `could not resolve turbo's unfiltered task graph, so this run cannot tell whether a scoped override has drifted from the global entry it replaces — ${turboBin} exited ${String(dryRun.status)}${dryRun.signal ? ` on ${dryRun.signal}` : ''}${dryRun.error ? ` (${String(dryRun.error)})` : ''}:\n${dryRun.stderr ?? ''}${dryRun.stdout ?? ''}`,
+ );
+ }
+ const parsed = parseTurboDryRun(
+ dryRun.stdout ?? '',
+ `${turboBin} ${turboArgs.join(' ')} (cwd ${WORKSPACE_ROOT})`,
+ );
+ unfilteredDefinitions = new Map(
+ parsed.tasks.flatMap((task) =>
+ task.resolvedTaskDefinition ? [[task.taskId, task.resolvedTaskDefinition] as const] : [],
+ ),
+ );
+ return unfilteredDefinitions;
+}
+
+function withoutDependsOn(definition: TurboTaskDefinition): TurboTaskDefinition {
+ const { dependsOn: _dependsOn, ...rest } = definition;
+ return rest;
+}
+
+function declaredGlobalSetups(globalSetup: string | string[] | undefined): string[] {
+ if (globalSetup === undefined) return [];
+ return Array.isArray(globalSetup) ? [...globalSetup] : [globalSetup];
+}
+
+describe('i18n catalog freshness gate wiring', () => {
+ test.each(TIER_NAMES)(
+ 'turbo orders the %s tier behind the app build that rewrites the catalogs',
+ (tier) => {
+ const { turboTask } = PLAYWRIGHT_TIERS[tier];
+ const taskId = `${APP_PACKAGE_NAME}#${turboTask}`;
+ const dependencies = turboResolvedGraph().get(taskId);
+ expect(
+ dependencies,
+ `turbo's resolved graph has no ${taskId}, so the ${tier} tier's ordering cannot be checked.`,
+ ).toBeDefined();
+ expect(
+ dependencies,
+ `${taskId} does not depend on ${APP_PACKAGE_NAME}#build, so turbo may run the app build concurrently with the ${tier} tier. That build runs "pnpm run i18n:compile", which truncates and rewrites all 13 src/locales/*/messages.json, and the ${tier} tier's globalSetup JSON.parses those same files. Add "build" to turbo.json "${turboTask}".dependsOn.`,
+ ).toContain(`${APP_PACKAGE_NAME}#build`);
+ },
+ TURBO_DRY_RUN_TIMEOUT_MS,
+ );
+
+ test.each(TIER_NAMES)('the %s tier declares the catalog freshness globalSetup', async (tier) => {
+ const { configFile, load } = PLAYWRIGHT_TIERS[tier];
+ const declared = declaredGlobalSetups((await load()).default.globalSetup);
+ expect(
+ declared,
+ `the ${tier} tier (packages/app/${configFile}) does not declare ${FRESHNESS_GLOBAL_SETUP} in globalSetup, so it would silently serve the committed src/locales/*/messages.json: every dev server it boots sets OK_TEST_SKIP_I18N_COMPILE, so nothing in the run recompiles them and every assertion reads the committed copy instead of the edit under test. Re-add that path to globalSetup in packages/app/${configFile}.`,
+ ).toContain(FRESHNESS_GLOBAL_SETUP);
+ expect(
+ declared[0],
+ `the ${tier} tier (packages/app/${configFile}) declares ${declared[0] ?? '(nothing)'} ahead of ${FRESHNESS_GLOBAL_SETUP} in globalSetup. Playwright runs globalSetup entries in declared order and skips every later one once an earlier one throws (playwright 1.59.1: lib/common/config.js:70 keeps the array's order, lib/runner/tasks.js:107 appends the setups in that order, lib/runner/taskRunner.js:53-76 awaits them one at a time and sets _interrupted on a throw), so anything ahead of the freshness gate either burns the run's setup budget before a failure that was deterministic from the first byte, or — if it writes src/locales/*/messages.json — repairs the staleness the gate exists to catch and leaves the gate reading what the entry ahead of it just wrote. Move ${FRESHNESS_GLOBAL_SETUP} back to the front of globalSetup in packages/app/${configFile}.`,
+ ).toBe(FRESHNESS_GLOBAL_SETUP);
+ expect(
+ existsSync(join(APP_PACKAGE_ROOT, FRESHNESS_GLOBAL_SETUP)),
+ `the ${tier} tier (packages/app/${configFile}) names ${FRESHNESS_GLOBAL_SETUP} in globalSetup but no such file exists under packages/app, so the tier declares a freshness gate Playwright cannot load and would silently serve the committed src/locales/*/messages.json under OK_TEST_SKIP_I18N_COMPILE. Point packages/app/${configFile} at the helper's real path.`,
+ ).toBe(true);
+ });
+});
+
+describe('turbo dry-run parse', () => {
+ const INVOCATION = '/ok/node_modules/.bin/turbo run test:e2e --dry=json (cwd /ok)';
+
+ function rejectionMessage(stdout: string): string {
+ let raised: unknown;
+ try {
+ parseTurboDryRun(stdout, INVOCATION);
+ } catch (error) {
+ raised = error;
+ }
+ expect(
+ raised,
+ `parseTurboDryRun accepted ${JSON.stringify(stdout)}, so this test would pass without exercising anything`,
+ ).toBeInstanceOf(Error);
+ return (raised as Error).message;
+ }
+
+ test('names the invocation and the output when turbo wrote no JSON object', () => {
+ const message = rejectionMessage('• turbo 2.10.4\n');
+ expect(
+ message,
+ 'indexOf misses, slice(-1) hands JSON.parse the final character, and the bare SyntaxError names neither the turbo invocation that produced the output nor the output itself',
+ ).toContain(INVOCATION);
+ expect(
+ message,
+ 'without a head of what turbo actually wrote, an operator cannot tell a moved payload from an empty one',
+ ).toContain('turbo 2.10.4');
+ });
+
+ test('names the invocation and the output when the JSON is malformed', () => {
+ const message = rejectionMessage('{"tasks":');
+ expect(
+ message,
+ "JSON.parse's bare SyntaxError reports a position in a string it does not quote and never names the turbo invocation that produced it",
+ ).toContain(INVOCATION);
+ expect(
+ message,
+ 'a position offset into unquoted output is not a diagnosis; the head is what says whether turbo interleaved a log line into the payload',
+ ).toContain('{"tasks":');
+ });
+
+ test('names the invocation and the output when the payload carries no tasks array', () => {
+ const message = rejectionMessage('{"packages":[]}');
+ expect(
+ message,
+ 'a renamed field surfaces one line later as "Cannot read properties of undefined (reading \'map\')", which names neither the turbo invocation nor the payload that lacked the field',
+ ).toContain(INVOCATION);
+ expect(
+ message,
+ 'the head is what shows an operator which fields turbo did send, so a rename is distinguishable from a truncation',
+ ).toContain('{"packages":[]}');
+ });
+});
+
+describe('scoped turbo overrides stay aligned with the global entries they replace', () => {
+ test.each(SCOPED_OVERRIDE_TASKS)(
+ "the app's %s override differs from the global entry only in dependsOn",
+ (task) => {
+ const definitions = turboUnfilteredDefinitions();
+ const scoped = definitions.get(`${APP_PACKAGE_NAME}#${task}`);
+ expect(
+ scoped,
+ `turbo resolved no definition for ${APP_PACKAGE_NAME}#${task}, so this row would certify nothing`,
+ ).toBeDefined();
+
+ const siblings = [...definitions.entries()].filter(
+ ([taskId]) => taskId.endsWith(`#${task}`) && !taskId.startsWith(`${APP_PACKAGE_NAME}#`),
+ );
+ expect(
+ siblings.length,
+ `no package other than ${APP_PACKAGE_NAME} resolves ${task}, so there is no global entry to compare against and this row would pass on anything`,
+ ).toBeGreaterThan(0);
+
+ for (const [taskId, sibling] of siblings) {
+ expect(
+ withoutDependsOn(scoped as TurboTaskDefinition),
+ `a root package#task entry overwrites the global task definition outright and inherits nothing, so "${APP_PACKAGE_NAME}#${task}" in turbo.json restates the global entry's fields by hand. ${taskId} resolves the global entry, and it has drifted from the scoped copy: a field added to one and not the other never reaches the package that actually runs this tier, and under turbo's strict env mode an undeclared variable is filtered out of the child process rather than merely omitted from the cache key`,
+ ).toEqual(withoutDependsOn(sibling));
+ }
+
+ const scopedDependsOn = (scoped as TurboTaskDefinition).dependsOn as string[];
+ expect(
+ scopedDependsOn,
+ `the scoped override exists to add the app build edge that keeps this tier from reading src/locales/*/messages.json while the build rewrites them, so dropping "build" from it silently restores the race`,
+ ).toContain('build');
+ },
+ );
+});
diff --git a/packages/app/tests/stress/_helpers/editor-state.ts b/packages/app/tests/stress/_helpers/editor-state.ts
index 821170606..be227d51c 100644
--- a/packages/app/tests/stress/_helpers/editor-state.ts
+++ b/packages/app/tests/stress/_helpers/editor-state.ts
@@ -4,12 +4,13 @@ export const SELECT_ALL_SETTLE_TIMEOUT_MS = process.env.CI ? 15_000 : 5_000;
type ViewSelectionState = 'covers-document' | 'partial' | 'empty' | 'unreadable';
-interface SelectAllProbe {
+export interface SelectAllProbe {
matches: number;
focusOwnedOnEntry: boolean;
focusOwnedByEditor: boolean;
activeElement: string;
viewSelection: ViewSelectionState;
+ docEnd: number | null;
}
export function repairFocusAndReadProbe(sel: string): SelectAllProbe {
@@ -30,20 +31,26 @@ export function repairFocusAndReadProbe(sel: string): SelectAllProbe {
focusOwnedByEditor: false,
activeElement: describe(document.activeElement),
viewSelection: 'unreadable',
+ docEnd: null,
};
}
const ownsFocus = (): boolean => document.activeElement === editor;
const focusOwnedOnEntry = ownsFocus();
if (!focusOwnedOnEntry && editor instanceof HTMLElement) editor.focus({ preventScroll: true });
- const classify = (from: unknown, to: unknown, docEnd: unknown): ViewSelectionState => {
- if (!Number.isInteger(from) || !Number.isInteger(to) || !Number.isInteger(docEnd)) {
+ const classify = (from: unknown, to: unknown, end: unknown): ViewSelectionState => {
+ if (!Number.isInteger(from) || !Number.isInteger(to) || !Number.isInteger(end)) {
return 'unreadable';
}
- if (from === 0 && to === docEnd) return 'covers-document';
- return from === to ? 'empty' : 'partial';
+ if (from === to) return 'empty';
+ return from === 0 && to === end ? 'covers-document' : 'partial';
};
let viewSelection: ViewSelectionState = 'unreadable';
+ let docEnd: number | null = null;
+ const read = (from: unknown, to: unknown, end: unknown): void => {
+ viewSelection = classify(from, to, end);
+ docEnd = viewSelection === 'unreadable' ? null : (end as number);
+ };
const prosemirror = (
window.__activeEditor as unknown as {
editorView?: {
@@ -56,7 +63,7 @@ export function repairFocusAndReadProbe(sel: string): SelectAllProbe {
} | null
)?.editorView;
if (prosemirror && prosemirror.dom === editor) {
- viewSelection = classify(
+ read(
prosemirror.state?.selection?.from,
prosemirror.state?.selection?.to,
prosemirror.state?.doc?.content?.size,
@@ -75,7 +82,7 @@ export function repairFocusAndReadProbe(sel: string): SelectAllProbe {
}
| undefined;
if (codemirror) {
- viewSelection = classify(
+ read(
codemirror.state?.selection?.main?.from,
codemirror.state?.selection?.main?.to,
codemirror.state?.doc?.length,
@@ -89,6 +96,7 @@ export function repairFocusAndReadProbe(sel: string): SelectAllProbe {
focusOwnedByEditor: ownsFocus(),
activeElement: describe(document.activeElement),
viewSelection,
+ docEnd,
};
}
@@ -96,6 +104,39 @@ function repairFocusAndProbe(page: Page, selector: string): Promise<SelectAllPro
return page.evaluate(repairFocusAndReadProbe, selector);
}
+const SETTLED_READING = {
+ focus: { focusOwnedByEditor: true },
+ 'select-all': { viewSelection: 'covers-document' },
+} as const satisfies { [S in 'focus' | 'select-all']: Partial<SelectAllProbe> };
+
+/* UPSTREAM(@playwright/[email protected]): lib/matchers/expect.js pollMatcher returns
+ { continuePolling: false } without ever calling the poll generator once the test that armed the
+ poll is no longer the running test, so the barrier resolves holding whatever reading the previous
+ iteration left — undefined if there was none. Neither the public expect.poll reference nor the
+ upstream test suite states this, so re-verify it on a Playwright bump. */
+export function abandonedPollRefusal(
+ selector: string,
+ stage: 'focus' | 'select-all',
+ settled: SelectAllProbe | undefined,
+): string | null {
+ const approved =
+ settled !== undefined &&
+ (Object.entries(SETTLED_READING[stage]) as [keyof SelectAllProbe, unknown][]).every(
+ ([field, expected]) => settled[field] === expected,
+ );
+ if (approved) return null;
+ return `selectAllAndWaitForSelection: the ${stage} poll for "${selector}" resolved on a reading its own matcher rejects, which Playwright does only once the test that armed this barrier has stopped being the running test — the page is no longer this test's to drive, so every reading taken from here on would describe someone else's run`;
+}
+
+function refusePollIfAbandoned(
+ selector: string,
+ stage: 'focus' | 'select-all',
+ settled: SelectAllProbe | undefined,
+): asserts settled is SelectAllProbe {
+ const refusal = abandonedPollRefusal(selector, stage, settled);
+ if (refusal !== null) throw new Error(refusal);
+}
+
/* Category C (select-all / focus flush) per precedent #20(a): the double-rAF yield this replaces
established neither that DOM focus was committed before the key dispatch nor that select-all
applied, so the helper could return with the view's selection in any state. */
@@ -107,22 +148,39 @@ export async function selectAllAndWaitForSelection(
const focusMs = budgets.focusMs ?? SELECT_ALL_SETTLE_TIMEOUT_MS;
const selectionMs = budgets.selectionMs ?? SELECT_ALL_SETTLE_TIMEOUT_MS;
await page.focus(selector);
+ let settled: SelectAllProbe | undefined;
await expect
- .poll(() => repairFocusAndProbe(page, selector), {
- message: `selectAllAndWaitForSelection: "${selector}" never took DOM focus, so ControlOrMeta+A would land outside the editor`,
- timeout: focusMs,
- })
+ .poll(
+ async () => {
+ settled = await repairFocusAndProbe(page, selector);
+ return settled;
+ },
+ {
+ message: `selectAllAndWaitForSelection: "${selector}" never took DOM focus, so ControlOrMeta+A would land outside the editor`,
+ timeout: focusMs,
+ },
+ )
.toMatchObject({
- focusOwnedByEditor: true,
+ ...SETTLED_READING.focus,
matches: expect.any(Number),
activeElement: expect.any(String),
});
+ refusePollIfAbandoned(selector, 'focus', settled);
+
+ if (settled.docEnd === 0) {
+ throw new Error(
+ `selectAllAndWaitForSelection: the view behind "${selector}" holds a zero-length document, so ControlOrMeta+A leaves exactly the 0,0 reading an untouched caret leaves and no select-all is observable — assert the editor has content before taking this barrier`,
+ );
+ }
+
+ let selected: SelectAllProbe | undefined;
await expect
.poll(
async () => {
await page.keyboard.press('ControlOrMeta+a');
- return repairFocusAndProbe(page, selector);
+ selected = await repairFocusAndProbe(page, selector);
+ return selected;
},
{
message: `selectAllAndWaitForSelection: ControlOrMeta+A left no full-document selection in the view behind "${selector}"`,
@@ -130,11 +188,13 @@ export async function selectAllAndWaitForSelection(
},
)
.toMatchObject({
- viewSelection: 'covers-document',
+ ...SETTLED_READING['select-all'],
focusOwnedOnEntry: expect.any(Boolean),
matches: expect.any(Number),
activeElement: expect.any(String),
});
+
+ refusePollIfAbandoned(selector, 'select-all', selected);
}
/** Category C (cursor / focus flush) per precedent #20(a). */
diff --git a/packages/app/tests/stress/_helpers/global-warm-cache.ts b/packages/app/tests/stress/_helpers/global-warm-cache.ts
index 0d1ac8769..d9a073641 100644
--- a/packages/app/tests/stress/_helpers/global-warm-cache.ts
+++ b/packages/app/tests/stress/_helpers/global-warm-cache.ts
@@ -60,6 +60,7 @@ async function buildSeedOnce(key: string): Promise<void> {
VITE_PORT: String(port),
OK_TEST_CONTENT_DIR: contentDir,
OK_TEST_VITE_CACHE_DIR: buildDir,
+ OK_TEST_SKIP_I18N_COMPILE: '1',
NO_COLOR: process.env.NO_COLOR ?? '1',
},
stdio: ['ignore', log.fd, log.fd],
diff --git a/packages/app/tests/stress/_helpers/i18n-catalog-freshness.ts b/packages/app/tests/stress/_helpers/i18n-catalog-freshness.ts
new file mode 100644
index 000000000..8760d4e26
--- /dev/null
+++ b/packages/app/tests/stress/_helpers/i18n-catalog-freshness.ts
@@ -0,0 +1,175 @@
+import { type SpawnSyncReturns, spawnSync } from 'node:child_process';
+import {
+ copyFileSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+} from 'node:fs';
+import { createRequire } from 'node:module';
+import { dirname, join } from 'node:path';
+import { APP_PACKAGE_ROOT } from './seed-key.ts';
+import { removeAllDuringTeardown } from './teardown-fs.ts';
+
+export const COMPILE_TIMEOUT_MS = 120_000;
+const SCRATCH_PREFIX = '.ok-i18n-freshness-';
+const CATALOG_SOURCE_FILENAME = 'messages.po';
+const CATALOG_COMPILED_FILENAME = 'messages.json';
+const LINGUI_CONFIG_FILENAME = 'lingui.config.ts';
+
+export function linguiBinEntry(): string {
+ const require = createRequire(import.meta.url);
+ const resolvedEntry = require.resolve('@lingui/cli');
+ return linguiBinEntryFrom(join(dirname(resolvedEntry), '..'), resolvedEntry);
+}
+
+export function linguiBinEntryFrom(packageRoot: string, resolvedEntry: string): string {
+ const manifestPath = join(packageRoot, 'package.json');
+ let manifest: { version?: string; bin?: Record<string, string> };
+ try {
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
+ } catch (err) {
+ throw new Error(
+ `could not read the @lingui/cli manifest at ${manifestPath}: this run took the package root to be one directory above the directory holding the resolved "." export (${resolvedEntry}), so a release that moved that entry leaves the root wrong and the i18n catalogs unchecked for staleness: ${String(err)}`,
+ );
+ }
+ const declared = manifest.bin?.lingui;
+ if (declared === undefined)
+ throw new Error(
+ `@lingui/cli@${manifest.version ?? 'unknown'} declares no "lingui" bin, so this run cannot compile the i18n catalogs to check them for staleness`,
+ );
+ return join(packageRoot, declared);
+}
+
+export function describeCompileFailure(
+ compiled: Pick<SpawnSyncReturns<string>, 'status' | 'signal' | 'error'>,
+): string {
+ const err = compiled.error as NodeJS.ErrnoException | undefined;
+ if (err?.code === 'ETIMEDOUT')
+ return `lingui compile did not finish within ${COMPILE_TIMEOUT_MS}ms and was killed`;
+ const exit = `lingui compile exited ${String(compiled.status)}${compiled.signal ? ` on ${compiled.signal}` : ''}`;
+ return err === undefined ? exit : `${exit}, and spawnSync reported ${String(err)}`;
+}
+
+function localesDirOf(appPackageRoot: string): string {
+ return join(appPackageRoot, 'src', 'locales');
+}
+
+function catalogLocales(appPackageRoot: string): string[] {
+ const localesDir = localesDirOf(appPackageRoot);
+ return readdirSync(localesDir, { withFileTypes: true })
+ .filter(
+ (entry) =>
+ entry.isDirectory() && existsSync(join(localesDir, entry.name, CATALOG_SOURCE_FILENAME)),
+ )
+ .map((entry) => entry.name)
+ .sort();
+}
+
+function canonicalize(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonicalize);
+ if (value !== null && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ .map(([key, entry]) => [key, canonicalize(entry)]),
+ );
+ }
+ return value;
+}
+
+function readCompiledCatalog(path: string): string | null {
+ if (!existsSync(path)) return null;
+ const raw = readFileSync(path, 'utf-8');
+ try {
+ return JSON.stringify(canonicalize(JSON.parse(raw)));
+ } catch (err) {
+ throw new Error(
+ `could not parse the compiled i18n catalog at ${path}, so this run cannot tell whether it would serve stale copy: ${String(err)}`,
+ );
+ }
+}
+
+function compileInto(scratchRoot: string, appPackageRoot: string, locales: string[]): void {
+ copyFileSync(
+ join(appPackageRoot, LINGUI_CONFIG_FILENAME),
+ join(scratchRoot, LINGUI_CONFIG_FILENAME),
+ );
+ for (const locale of locales) {
+ mkdirSync(join(scratchRoot, 'src', 'locales', locale), { recursive: true });
+ copyFileSync(
+ join(localesDirOf(appPackageRoot), locale, CATALOG_SOURCE_FILENAME),
+ join(scratchRoot, 'src', 'locales', locale, CATALOG_SOURCE_FILENAME),
+ );
+ }
+ const compiled = spawnSync(
+ process.execPath,
+ [
+ linguiBinEntry(),
+ 'compile',
+ '--namespace',
+ 'json',
+ /* UPSTREAM(@lingui/[email protected]): dist/api/typedPool.js points the worker pool at
+ compileWorkerWrapper.jiti.js when NODE_ENV === 'test', and the published package ships only
+ the .prod.js build, so the pool dies under any caller vitest started. --workers 1 takes
+ lingui's single-threaded path instead. */
+ '--workers',
+ '1',
+ '--config',
+ join(scratchRoot, LINGUI_CONFIG_FILENAME),
+ ],
+ { cwd: APP_PACKAGE_ROOT, encoding: 'utf-8', timeout: COMPILE_TIMEOUT_MS },
+ );
+ if (compiled.error !== undefined || compiled.status !== 0) {
+ throw new Error(
+ `could not compile the i18n catalogs of ${appPackageRoot} to check them for staleness, so this run cannot tell whether it would serve stale copy — ${describeCompileFailure(compiled)}:\n${compiled.stderr ?? ''}${compiled.stdout ?? ''}`,
+ );
+ }
+}
+
+export function findStaleCatalogLocales(appPackageRoot: string): string[] {
+ const locales = catalogLocales(appPackageRoot);
+ mkdirSync(join(APP_PACKAGE_ROOT, 'node_modules'), { recursive: true });
+ const scratchRoot = mkdtempSync(join(APP_PACKAGE_ROOT, 'node_modules', SCRATCH_PREFIX));
+ try {
+ compileInto(scratchRoot, appPackageRoot, locales);
+ const compiledDir = join(scratchRoot, 'src', 'locales');
+ const uncompiled = locales.filter(
+ (locale) => !existsSync(join(compiledDir, locale, CATALOG_COMPILED_FILENAME)),
+ );
+ if (uncompiled.length > 0)
+ throw new Error(
+ `nothing compiles the i18n catalogs of ${uncompiled.join(', ')}: src/locales/<locale>/${CATALOG_SOURCE_FILENAME} exists but ${LINGUI_CONFIG_FILENAME} does not list the locale, so this run cannot tell whether it would serve stale copy. ` +
+ `Fix: add the locale to the "locales" array in ${join(appPackageRoot, LINGUI_CONFIG_FILENAME)}, or delete ${join(localesDirOf(appPackageRoot), '<locale>')}.`,
+ );
+ return locales.filter(
+ (locale) =>
+ readCompiledCatalog(
+ join(localesDirOf(appPackageRoot), locale, CATALOG_COMPILED_FILENAME),
+ ) !== readCompiledCatalog(join(compiledDir, locale, CATALOG_COMPILED_FILENAME)),
+ );
+ } finally {
+ try {
+ removeAllDuringTeardown(scratchRoot);
+ } catch (err) {
+ console.warn(
+ `[i18n freshness] could not remove the scratch compile directory ${scratchRoot}, so it is left behind rather than masking the freshness verdict: ${String(err)}`,
+ );
+ }
+ }
+}
+
+export function assertI18nCatalogsFresh(appPackageRoot: string): void {
+ const stale = findStaleCatalogLocales(appPackageRoot);
+ if (stale.length === 0) return;
+ throw new Error(
+ `i18n catalogs are stale for ${stale.join(', ')}: src/locales/<locale>/${CATALOG_COMPILED_FILENAME} is not what ${CATALOG_SOURCE_FILENAME} compiles to. ` +
+ 'Every dev server a Playwright run boots sets OK_TEST_SKIP_I18N_COMPILE, so nothing in this run would recompile them and every assertion would read the committed copy instead of your edit. ' +
+ `Fix: run "pnpm run i18n" in ${appPackageRoot}, then re-run.`,
+ );
+}
+
+export default function globalAssertI18nCatalogsFresh(): void {
+ assertI18nCatalogsFresh(APP_PACKAGE_ROOT);
+}
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index bfbd5a2e8..20a68d2a1 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/turbo.json b/turbo.json
index 6f7162211..ce0dd8c4b 100644
--- a/turbo.json
+++ b/turbo.json
@@ -371,6 +371,10 @@
"dependsOn": ["^build"],
"cache": false
},
+ "@inkeep/open-knowledge-app#test:visual": {
+ "dependsOn": ["^build", "build"],
+ "cache": false
+ },
"test:perf": {
"dependsOn": [],
"cache": true,
@@ -390,6 +394,10 @@
"dependsOn": ["^build"],
"cache": false
},
+ "@inkeep/open-knowledge-app#test:a11y": {
+ "dependsOn": ["^build", "build"],
+ "cache": false
+ },
"test:perf:bench": {
"dependsOn": [],
"cache": false,