Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Turn four more source-text checks into structural rules (#5293)
Nick Gomezab8f4fe43eb7
diff --git a/.github/scripts/point-release-plan.test.mjs b/.github/scripts/point-release-plan.test.mjsindex b5b3365a5..9085636f0 100644--- a/.github/scripts/point-release-plan.test.mjs+++ b/.github/scripts/point-release-plan.test.mjs@@ -1,4 +1,5 @@import { readFileSync } from 'node:fs';+import { Project, ts } from 'ts-morph';import { describe, expect, test } from 'vitest';import {deriveEntryLevelResolution,@@ -18,6 +19,38 @@ import {verifyWorkspaceMatchesLockfile,} from './point-release-plan.mjs';+function inspectGitEscapes(source) {+ const project = new Project({ useInMemoryFileSystem: true, skipLoadingLibFiles: true });+ const file = project.createSourceFile('/point-release-plan.ts', source);+ const census = Object.entries({+ syntax:+ project.getProgram().compilerObject.getSyntacticDiagnostics(file.compilerNode).length === 0,+ realIo: !!file.getFunction('realIo')?.getBody(),+ runPointRelease: !!file.getFunction('runPointRelease')?.getBody(),+ forwarding: file+ .getExportDeclarations()+ .every((declaration) => !declaration.getModuleSpecifier()),+ }).flatMap(([name, holds]) => (holds ? [] : [name]));+ const escapes = file.getDescendants().flatMap((node) => {+ const literal = node.compilerNode;+ if (+ !ts.isStringLiteralLike(literal) &&+ !ts.isTemplateHead(literal) &&+ !ts.isTemplateMiddle(literal) &&+ !ts.isTemplateTail(literal) &&+ !ts.isRegularExpressionLiteral(literal)+ )+ return [];+ const value = literal.text;+ return /--strategy|-Xours|-Xtheirs|'ours'|'theirs'|--skip|--abort|--no-commit/.test(value) ||+ value === 'ours' ||+ value === 'theirs'+ ? [value]+ : [];+ });+ return { census, escapes };+}+const membership = (...members) => {const set = new Set(members);return (value) => {@@ -39,13 +72,19 @@ describe('guardAnchor', () => {});test('propagates a malformed anchor instead of reporting it as drift', () => {- expect(() => guardAnchor({ anchorVersion: 'not-a-version', latestStableTag: 'v0.32.1' })).toThrow();+ expect(() =>+ guardAnchor({ anchorVersion: 'not-a-version', latestStableTag: 'v0.32.1' }),+ ).toThrow();});});describe('parseFixRefs', () => {test('splits on commas and whitespace, trims, and dedupes', () => {- expect(parseFixRefs(' abc123 , def456\ndef456\tghi789 ')).toEqual(['abc123', 'def456', 'ghi789']);+ expect(parseFixRefs(' abc123 , def456\ndef456\tghi789 ')).toEqual([+ 'abc123',+ 'def456',+ 'ghi789',+ ]);});test('throws when no ref survives parsing', () => {@@ -72,7 +111,9 @@ describe('guardRefsOnMain', () => {});test('propagates an ancestry infra error instead of reading it as not-on-main', () => {- expect(() => guardRefsOnMain({ fixRefs: ['THROW'], isOnMain: membership() })).toThrow(/infra error/);+ expect(() => guardRefsOnMain({ fixRefs: ['THROW'], isOnMain: membership() })).toThrow(+ /infra error/,+ );});});@@ -169,7 +210,7 @@ describe('guardNativeConfigProvenance', () => {expect(r.message).toContain('prebuild');});- test('refuses with the selector\'s own account of why nothing qualified', () => {+ test("refuses with the selector's own account of why nothing qualified", () => {const r = guardNativeConfigProvenance({selection: { headSha: '', reason: 'newest green run 42 @ abc123 does not' },});@@ -193,7 +234,10 @@ describe('guardNativeConfigProvenance', () => {describe('guardMainResetDeltaIds', () => {test('passes on a non-empty delta', () => {- expect(guardMainResetDeltaIds({ deltaIds: ['brave-pandas-sing'] })).toMatchObject({ ok: true, code: null });+ expect(guardMainResetDeltaIds({ deltaIds: ['brave-pandas-sing'] })).toMatchObject({+ ok: true,+ code: null,+ });});test('refuses an empty array, which main-reset reads as consolidate-everything', () => {@@ -203,7 +247,10 @@ describe('guardMainResetDeltaIds', () => {});test('refuses an absent delta for the same reason', () => {- expect(guardMainResetDeltaIds({ deltaIds: null })).toMatchObject({ ok: false, code: 'empty-delta-ids' });+ expect(guardMainResetDeltaIds({ deltaIds: null })).toMatchObject({+ ok: false,+ code: 'empty-delta-ids',+ });});});@@ -269,7 +316,9 @@ describe('parseResolvePaths', () => {});test('splits and dedupes like the sibling list inputs', () => {- expect(parseResolvePaths('pnpm-workspace.yaml, pnpm-workspace.yaml')).toEqual(['pnpm-workspace.yaml']);+ expect(parseResolvePaths('pnpm-workspace.yaml, pnpm-workspace.yaml')).toEqual([+ 'pnpm-workspace.yaml',+ ]);});});@@ -288,7 +337,11 @@ describe('guardResolvePathsAllowlisted', () => {test('refuses a source path, naming every offender', () => {const r = guardResolvePathsAllowlisted({- resolvePaths: ['pnpm-workspace.yaml', 'packages/app/src/main.tsx', '.github/workflows/release.yml'],+ resolvePaths: [+ 'pnpm-workspace.yaml',+ 'packages/app/src/main.tsx',+ '.github/workflows/release.yml',+ ],});expect(r.ok).toBe(false);expect(r.code).toBe('resolve-path-not-allowlisted');@@ -297,8 +350,12 @@ describe('guardResolvePathsAllowlisted', () => {});test('refuses a glob or a parent directory rather than expanding it', () => {- expect(guardResolvePathsAllowlisted({ resolvePaths: ['*'] }).code).toBe('resolve-path-not-allowlisted');- expect(guardResolvePathsAllowlisted({ resolvePaths: ['.'] }).code).toBe('resolve-path-not-allowlisted');+ expect(guardResolvePathsAllowlisted({ resolvePaths: ['*'] }).code).toBe(+ 'resolve-path-not-allowlisted',+ );+ expect(guardResolvePathsAllowlisted({ resolvePaths: ['.'] }).code).toBe(+ 'resolve-path-not-allowlisted',+ );});});@@ -309,9 +366,13 @@ describe('deriveEntryLevelResolution', () => {fixBefore: WS_FIX_PARENT,fixAfter: WS_FIX,});- expect(added).toEqual([" '[email protected]': patches/[email protected]"]);+ expect(added).toEqual([+ " '[email protected]': patches/[email protected]",+ ]);expect(removed).toEqual([]);- expect(resolved).toContain("'[email protected]': patches/[email protected]");+ expect(resolved).toContain(+ "'[email protected]': patches/[email protected]",+ );expect(resolved).not.toContain('@lingui/core');expect(resolved).toBe(`${WS_STABLE} '[email protected]': patches/[email protected]\n`,@@ -332,7 +393,10 @@ describe('deriveEntryLevelResolution', () => {});test('carries a removal through as a deletion of that exact entry', () => {- const fixAfter = WS_FIX_PARENT.replace(" '[email protected]': patches/[email protected]\n", '');+ const fixAfter = WS_FIX_PARENT.replace(+ " '[email protected]': patches/[email protected]\n",+ '',+ );const { resolved, added, removed } = deriveEntryLevelResolution({base: WS_STABLE,fixBefore: WS_FIX_PARENT,@@ -349,33 +413,42 @@ describe('deriveEntryLevelResolution', () => {" '@pierre/[email protected]': patches/@pierre%[email protected]"," '[email protected]': patches/[email protected]",);- expect(() => deriveEntryLevelResolution({ base, fixBefore: WS_FIX_PARENT, fixAfter: WS_FIX })).toThrow(- /CHANGES that entry/,- );+ expect(() =>+ deriveEntryLevelResolution({ base, fixBefore: WS_FIX_PARENT, fixAfter: WS_FIX }),+ ).toThrow(/CHANGES that entry/);});test('refuses when the block the entry belongs to is not in the stable file', () => {const base = "packages:\n - 'packages/*'\n";- expect(() => deriveEntryLevelResolution({ base, fixBefore: WS_FIX_PARENT, fixAfter: WS_FIX })).toThrow(- /not in the last stable/,- );+ expect(() =>+ deriveEntryLevelResolution({ base, fixBefore: WS_FIX_PARENT, fixAfter: WS_FIX }),+ ).toThrow(/not in the last stable/);});test.each([['a new top-level key', `${WS_FIX_PARENT}ignorePatchFailures: false\n`],- ['a comment inside the block', WS_FIX_PARENT.replace('patchedDependencies:\n', 'patchedDependencies:\n # note\n')],- ['a sequence item', WS_FIX_PARENT.replace(" - 'packages/*'\n", " - 'packages/*'\n - 'apps/*'\n")],+ [+ 'a comment inside the block',+ WS_FIX_PARENT.replace('patchedDependencies:\n', 'patchedDependencies:\n # note\n'),+ ],+ [+ 'a sequence item',+ WS_FIX_PARENT.replace(" - 'packages/*'\n", " - 'packages/*'\n - 'apps/*'\n"),+ ],])('refuses %s, which is not an indented mapping entry', (_label, fixAfter) => {- expect(() => deriveEntryLevelResolution({ base: WS_STABLE, fixBefore: WS_FIX_PARENT, fixAfter })).toThrow(- /not an indented mapping entry/,- );+ expect(() =>+ deriveEntryLevelResolution({ base: WS_STABLE, fixBefore: WS_FIX_PARENT, fixAfter }),+ ).toThrow(/not an indented mapping entry/);});test('refuses to remove a line the stable no longer has', () => {- const fixAfter = WS_FIX_PARENT.replace(" '@lingui/[email protected]': patches/@lingui%[email protected]\n", '');- expect(() => deriveEntryLevelResolution({ base: WS_STABLE, fixBefore: WS_FIX_PARENT, fixAfter })).toThrow(- /does not appear exactly once in the last stable/,+ const fixAfter = WS_FIX_PARENT.replace(+ " '@lingui/[email protected]': patches/@lingui%[email protected]\n",+ '',);+ expect(() =>+ deriveEntryLevelResolution({ base: WS_STABLE, fixBefore: WS_FIX_PARENT, fixAfter }),+ ).toThrow(/does not appear exactly once in the last stable/);});test('refuses when the fix does not touch the file at all', () => {@@ -424,22 +497,31 @@ describe('verifyWorkspaceMatchesLockfile', () => {});test('reads through the two files differing quote styles rather than calling them a mismatch', () => {- expect(verifyWorkspaceMatchesLockfile({ resolved, readWorktreeFile: () => LOCK_AFTER_MERGE })).toContain(- 'overrides',- );+ expect(+ verifyWorkspaceMatchesLockfile({ resolved, readWorktreeFile: () => LOCK_AFTER_MERGE }),+ ).toContain('overrides');});test('checks overrides too, not just patch registrations', () => {- const withExtraOverride = resolved.replace(" 'radix-ui': 1.4.3", " 'radix-ui': 1.4.3\n 'left-pad': 1.3.0");+ const withExtraOverride = resolved.replace(+ " 'radix-ui': 1.4.3",+ " 'radix-ui': 1.4.3\n 'left-pad': 1.3.0",+ );expect(() =>- verifyWorkspaceMatchesLockfile({ resolved: withExtraOverride, readWorktreeFile: () => LOCK_AFTER_MERGE }),+ verifyWorkspaceMatchesLockfile({+ resolved: withExtraOverride,+ readWorktreeFile: () => LOCK_AFTER_MERGE,+ }),).toThrow(/overrides.*left-pad/s);});test('catches an overrides VALUE that drifted, not just a missing key', () => {const bumped = resolved.replace(" 'radix-ui': 1.4.3", " 'radix-ui': 1.9.9");expect(() =>- verifyWorkspaceMatchesLockfile({ resolved: bumped, readWorktreeFile: () => LOCK_AFTER_MERGE }),+ verifyWorkspaceMatchesLockfile({+ resolved: bumped,+ readWorktreeFile: () => LOCK_AFTER_MERGE,+ }),).toThrow(/radix-ui: 1\.9\.9/);});@@ -558,7 +640,9 @@ function makeIo(overrides = {}) {},gh: {selectNativeConfigPrebuild: () =>- typeof nativeConfigSelection === 'function' ? nativeConfigSelection() : nativeConfigSelection,+ typeof nativeConfigSelection === 'function'+ ? nativeConfigSelection()+ : nativeConfigSelection,createRelease: (r) => {calls.createRelease++;releases.push(r);@@ -627,7 +711,10 @@ describe('runPointRelease dry run', () => {'fix2^': ['keep-a', 'fix1-cs'],},});- const plan = runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1', 'fix2'], dryRun: true }, io);+ const plan = runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1', 'fix2'], dryRun: true },+ io,+ );expect(plan.addedIds).toEqual(['fix1-cs', 'fix2-cs']);expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });});@@ -691,7 +778,11 @@ describe('runPointRelease cascade', () => {{repo: 'inkeep/agents-private',eventType: 'main-reset',- clientPayload: { stable_version: '0.32.1', delta_ids: ['shiny-fix'], dispatched_by: 'https://run/1' },+ clientPayload: {+ stable_version: '0.32.1',+ delta_ids: ['shiny-fix'],+ dispatched_by: 'https://run/1',+ },},]);});@@ -700,7 +791,11 @@ describe('runPointRelease cascade', () => {const io = cherryPickIo();runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: false }, io);expect(io.calls).toMatchObject({ tag: 1, pushTag: 1, createRelease: 1 });- expect(io.releases[0]).toMatchObject({ tag: 'v0.32.1', targetSha: 'synthetic-sha', draft: true });+ expect(io.releases[0]).toMatchObject({+ tag: 'v0.32.1',+ targetSha: 'synthetic-sha',+ draft: true,+ });});test('the release notes quote each added changeset the way a stable body does', () => {@@ -759,7 +854,8 @@ describe('runPointRelease cascade', () => {'fix1^': ['keep-a'],},changesetContents: {- 'shiny-fix': '---\n"@inkeep/open-knowledge": patch\n---\n\nChips no longer balloon into ovals.\n',+ 'shiny-fix':+ '---\n"@inkeep/open-knowledge": patch\n---\n\nChips no longer balloon into ovals.\n',},});const plan = runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: true }, io);@@ -781,7 +877,10 @@ describe('runPointRelease cascade', () => {test('revert forwards the changeset the operator landed to represent it', () => {const io = makeIo();- runPointRelease({ mode: 'revert', fixRefs: ['bad1'], anchorDeltaIds: '["undo-bad"]', dryRun: false }, io);+ runPointRelease(+ { mode: 'revert', fixRefs: ['bad1'], anchorDeltaIds: '["undo-bad"]', dryRun: false },+ io,+ );const mainReset = io.dispatches.find((d) => d.eventType === 'main-reset');expect(mainReset.clientPayload.delta_ids).toEqual(['undo-bad']);});@@ -790,7 +889,10 @@ describe('runPointRelease cascade', () => {const io = makeIo();let refusal;try {- runPointRelease({ mode: 'revert', fixRefs: ['bad1'], anchorDeltaIds: '[]', dryRun: false }, io);+ runPointRelease(+ { mode: 'revert', fixRefs: ['bad1'], anchorDeltaIds: '[]', dryRun: false },+ io,+ );} catch (err) {refusal = err;}@@ -800,7 +902,10 @@ describe('runPointRelease cascade', () => {test('skips main-reset when the cross-repo bridge App is absent, without failing the run', () => {const io = cherryPickIo();- const plan = runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: false, bridgeConfigured: false }, io);+ const plan = runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: false, bridgeConfigured: false },+ io,+ );expect(plan.mainReset).toMatchObject({ dispatch: false, skipReason: 'bridge-not-configured' });expect(io.dispatches.map((d) => d.eventType)).toEqual(['desktop-release']);expect(plan.warnings.join(' ')).toContain('shiny-fix');@@ -856,22 +961,27 @@ describe('runPointRelease refusals', () => {],];- test.each(cases)('refuses with %s and mutates nothing, even in a real run', (code, ioOpts, runOpts) => {- const io = makeIo(ioOpts);- let refusal;- try {- runPointRelease({ ...runOpts, dryRun: false }, io);- } catch (err) {- refusal = err;- }- expect(refusal?.code).toBe(code);- expect(refusal?.message).toBeTruthy();- expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });- });+ test.each(cases)(+ 'refuses with %s and mutates nothing, even in a real run',+ (code, ioOpts, runOpts) => {+ const io = makeIo(ioOpts);+ let refusal;+ try {+ runPointRelease({ ...runOpts, dryRun: false }, io);+ } catch (err) {+ refusal = err;+ }+ expect(refusal?.code).toBe(code);+ expect(refusal?.message).toBeTruthy();+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });+ },+ );test('a failing anchor guard stops before the synthetic commit is even built', () => {const io = makeIo({ anchorVersion: '0.31.0' });- expect(() => runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: false }, io)).toThrow();+ expect(() =>+ runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: false }, io),+ ).toThrow();expect(io.checkedOut).toEqual([]);expect(io.applied).toEqual([]);});@@ -973,10 +1083,7 @@ describe('runPointRelease refusals', () => {test('offers no side-picking escape hatch to reach for', () => {const source = readFileSync(new URL('./point-release-plan.mjs', import.meta.url), 'utf8');- const escapes = ['--strategy', '-Xours', '-Xtheirs', "'ours'", "'theirs'", '--skip', '--abort', '--no-commit'];- for (const escape of escapes) {- expect(source).not.toContain(escape);- }+ expect(inspectGitEscapes(source)).toEqual({ census: [], escapes: [] });});test('the resolvable-path allowlist admits config registries only, never behavior', () => {@@ -989,7 +1096,9 @@ describe('runPointRelease refusals', () => {test('rejects a mode it does not recognize rather than defaulting to cherry-pick', () => {const io = makeIo();- expect(() => runPointRelease({ mode: 'rebase', fixRefs: ['bad1'], dryRun: true }, io)).toThrow(/not one of/);+ expect(() => runPointRelease({ mode: 'rebase', fixRefs: ['bad1'], dryRun: true }, io)).toThrow(+ /not one of/,+ );expect(io.applied).toEqual([]);});});@@ -1020,7 +1129,10 @@ describe('runPointRelease with an authorized config path', () => {test('the derivation reads the stable from HEAD, not from the tag', () => {const io = conflictIo();- runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: true }, io);+ runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: true },+ io,+ );expect(io.reads).toContain('HEAD:pnpm-workspace.yaml');expect(io.reads).not.toContain('stable-sha:pnpm-workspace.yaml');});@@ -1080,7 +1192,10 @@ describe('runPointRelease with an authorized config path', () => {});let refusal;try {- runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false },+ io,+ );} catch (err) {refusal = err;}@@ -1095,12 +1210,16 @@ describe('runPointRelease with an authorized config path', () => {const io = conflictIo();const real = io.git.fileAt;io.git.fileAt = (rev, path) => {- if (rev === 'fix1') throw new Error(`fatal: path '${path}' exists on disk, but not in 'fix1'`);+ if (rev === 'fix1')+ throw new Error(`fatal: path '${path}' exists on disk, but not in 'fix1'`);return real(rev, path);};let refusal;try {- runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false },+ io,+ );} catch (err) {refusal = err;}@@ -1116,7 +1235,10 @@ describe('runPointRelease with an authorized config path', () => {};let caught;try {- runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false },+ io,+ );} catch (err) {caught = err;}@@ -1159,7 +1281,10 @@ importers:`,},});- runPointRelease({ mode: 'revert', fixRefs: ['bad1'], resolvePaths: authorized, dryRun: false }, io);+ runPointRelease(+ { mode: 'revert', fixRefs: ['bad1'], resolvePaths: authorized, dryRun: false },+ io,+ );expect(io.written['pnpm-workspace.yaml']).not.toContain('@pierre/trees');expect(io.written['pnpm-workspace.yaml']).toContain('y-prosemirror');expect(io.continued).toEqual(['revert']);@@ -1184,7 +1309,9 @@ importers:{ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: true },io,);- expect(plan.guards.some((g) => g.message.includes('Re-derived pnpm-workspace.yaml'))).toBe(true);+ expect(plan.guards.some((g) => g.message.includes('Re-derived pnpm-workspace.yaml'))).toBe(+ true,+ );const warning = plan.warnings.join(' ');expect(warning).toContain('did not apply cleanly');expect(warning).toContain('[email protected]');@@ -1194,7 +1321,10 @@ importers:const io = conflictIo({ conflicts: ['pnpm-workspace.yaml', 'packages/app/src/main.tsx'] });let refusal;try {- runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false },+ io,+ );} catch (err) {refusal = err;}@@ -1207,12 +1337,18 @@ importers:test('refuses when the re-derived file disagrees with the merged lockfile', () => {const io = conflictIo({worktree: {- 'pnpm-lock.yaml': LOCK_AFTER_MERGE.replace(/ {2}react-resizable-panels@4\.12\.1:\n.*\n.*\n/, ''),+ 'pnpm-lock.yaml': LOCK_AFTER_MERGE.replace(+ / {2}react-resizable-panels@4\.12\.1:\n.*\n.*\n/,+ '',+ ),},});let refusal;try {- runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false }, io);+ runPointRelease(+ { mode: 'cherry-pick', fixRefs: ['fix1'], resolvePaths: authorized, dryRun: false },+ io,+ );} catch (err) {refusal = err;}@@ -1260,7 +1396,9 @@ describe('point-release.yml contract with this script', () => {const read = [...source.matchAll(/process\.env\.([A-Z][A-Z0-9_]*)/g)].map((m) => m[1]);expect(read.length).toBeGreaterThan(0);- expect([...new Set(read)].filter((name) => !provided.has(name) && !fromRunner.has(name))).toEqual([]);+ expect(+ [...new Set(read)].filter((name) => !provided.has(name) && !fromRunner.has(name)),+ ).toEqual([]);});test('reads back only step outputs this script writes', () => {@@ -1268,7 +1406,9 @@ describe('point-release.yml contract with this script', () => {const emitted = new Set([...outputBlock.matchAll(/`([a-z_]+)=\$\{/g)].map((m) => m[1]));expect(emitted.size).toBeGreaterThan(0);- const consumed = [...new Set([...workflow.matchAll(/steps\.plan\.outputs\.([a-z_]+)/g)].map((m) => m[1]))];+ const consumed = [+ ...new Set([...workflow.matchAll(/steps\.plan\.outputs\.([a-z_]+)/g)].map((m) => m[1])),+ ];expect(consumed.length).toBeGreaterThan(0);expect(consumed.filter((name) => !emitted.has(name))).toEqual([]);@@ -1276,7 +1416,10 @@ describe('point-release.yml contract with this script', () => {test('defaults to a dry run and passes that default through to the script', () => {const inputStart = workflow.indexOf(' dry_run:');- const input = workflow.slice(inputStart, workflow.indexOf('\n dispatched_by:', inputStart));+ const input = workflow.slice(+ inputStart,+ workflow.indexOf('\n dispatched_by:', inputStart),+ );expect(input).toContain('type: boolean');expect(input).toContain('default: true');@@ -1317,3 +1460,50 @@ describe('formatReleaseNotes "Applied" line', () => {).toBe(`Applied: ${SHA}, hotfix-tag (${other})`);});});++describe('git escape rule self-test', () => {+ const declarations = 'function realIo() {} export function runPointRelease() {}';+ test('flags a forbidden literal and accepts the adjacent command', () => {+ expect(inspectGitEscapes(`${declarations} const args = ['--skip'];`)).toEqual({+ census: [],+ escapes: ['--skip'],+ });+ expect(inspectGitEscapes(`${declarations} const args = ['--continue'];`)).toEqual({+ census: [],+ escapes: [],+ });+ });+ test.each([+ ["['--strategy']", ['--strategy']],+ ["['-Xours']", ['-Xours']],+ ["['-Xtheirs']", ['-Xtheirs']],+ [`"-X 'ours'"`, ["-X 'ours'"]],+ [`"-X 'theirs'"`, ["-X 'theirs'"]],+ ["['--abort']", ['--abort']],+ ["['--no-commit']", ['--no-commit']],+ ["['-X', 'ours']", ['ours']],+ ["['-X', 'theirs']", ['theirs']],+ ['`--skip`', ['--skip']],+ [`\`--skip \${ref}\``, ['--skip ']],+ [`\`\${ref} --skip \${ref}\``, [' --skip ']],+ [`\`\${ref} --skip\``, [' --skip']],+ ['/--skip/', ['/--skip/']],+ ])('flags the forbidden side-picking or abort token in %s', (literal, escapes) => {+ expect(inspectGitEscapes(`${declarations} const args = ${literal};`)).toEqual({+ census: [],+ escapes,+ });+ });+ test('ignores comments and rejects relocation or unparseable source', () => {+ expect(inspectGitEscapes(`${declarations} /* --skip */`)).toEqual({+ census: [],+ escapes: [],+ });+ expect(inspectGitEscapes("export * from './moved.mjs';").census).toEqual([+ 'realIo',+ 'runPointRelease',+ 'forwarding',+ ]);+ expect(inspectGitEscapes(`${declarations} const = ;`).census).toEqual(['syntax']);+ });+});diff --git a/.github/scripts/retry-transient.test.mjs b/.github/scripts/retry-transient.test.mjsindex cd062c432..5bfdb0449 100644--- a/.github/scripts/retry-transient.test.mjs+++ b/.github/scripts/retry-transient.test.mjs@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { PassThrough } from 'node:stream';import { fileURLToPath } from 'node:url';+import { Node, Project, SyntaxKind } from 'ts-morph';import { afterAll, afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import {createFuseFailure,@@ -80,16 +81,96 @@ beforeEach(() => {const nodeCmd = (src) => [process.execPath, '-e', src];const childSelfExitMs = 60_000;const readinessTimeoutDefaultMs = 5_000;-const sourceSection = (source, start, end) => {- const startIndex = source.indexOf(start);- const endIndex = source.indexOf(end, startIndex);- if (startIndex === -1 || endIndex === -1) throw new Error(`missing source section: ${start}`);- return source.slice(startIndex, endIndex);-};-const throwTargets = (source) =>- new Set(- [...source.matchAll(/\bthrow\s+((?:new\s+)?[A-Za-z_$][\w$]*)/g)].map((match) => match[1]),- );+function inspectFuseThrows(source, ownedFunctions, boundaryName) {+ const project = new Project({ useInMemoryFileSystem: true, skipLoadingLibFiles: true });+ const file = project.createSourceFile('/fuses.ts', source);+ const imported = file+ .getImportDeclaration('./packaging-diagnostics.mjs')+ ?.getNamedImports()+ .find((specifier) => specifier.getName() === 'createFuseFailure');+ const factory = (imported?.getAliasNode() ?? imported?.getNameNode())?.getSymbol();+ const unwrap = (node) => {+ while (+ node &&+ (Node.isParenthesizedExpression(node) ||+ Node.isAsExpression(node) ||+ Node.isSatisfiesExpression(node) ||+ Node.isNonNullExpression(node) ||+ Node.isTypeAssertion(node) ||+ Node.isExpressionWithTypeArguments(node))+ )+ node = node.getExpression();+ return node;+ };+ const resolve = (input, seen = new Set()) => {+ const node = unwrap(input);+ if (!node || seen.has(node)) return undefined;+ const next = new Set(seen).add(node);+ if (Node.isIdentifier(node)) {+ const declaration = node.getSymbol()?.getDeclarations()[0];+ if (+ declaration &&+ Node.isVariableDeclaration(declaration) &&+ declaration.getVariableStatement()?.getDeclarationKind() === 'const'+ )+ return resolve(declaration.getInitializer(), next);+ if (declaration && Node.isBindingElement(declaration)) {+ const owner = declaration.getParent().getParent();+ const object = Node.isVariableDeclaration(owner)+ ? unwrap(owner.getInitializer())+ : undefined;+ const key =+ declaration.getPropertyNameNode()?.getSymbol()?.getName() ?? declaration.getName();+ const property =+ object && Node.isObjectLiteralExpression(object)+ ? object.getType().getProperty(key)?.getDeclarations()[0]+ : undefined;+ if (property && Node.isPropertyAssignment(property))+ return resolve(property.getInitializer(), next);+ }+ }+ return node;+ };+ const statements = file.getStatements();+ const roots = ownedFunctions.map((name) => file.getFunction(name));+ const start = statements.indexOf(roots[0]);+ const end = statements.indexOf(file.getFunction(boundaryName));+ const throws = statements+ .slice(start, end)+ .flatMap((statement) =>+ [statement, ...statement.getDescendantsOfKind(SyntaxKind.ThrowStatement)].filter(+ Node.isThrowStatement,+ ),+ );+ const census = Object.entries({+ createFuseFailure: !!factory,+ ...Object.fromEntries(+ ownedFunctions.map((name, index) => [+ name,+ !!roots[index]?.getBody() &&+ roots[index].getDescendantsOfKind(SyntaxKind.ThrowStatement).length > 0 &&+ (index > 0 || end < 0 || start < end),+ ]),+ ),+ [boundaryName]: end >= 0,+ forwarding: file+ .getExportDeclarations()+ .every((declaration) => !declaration.getModuleSpecifier()),+ syntax: project.getProgram().getSyntacticDiagnostics(file).length === 0,+ }).flatMap(([name, holds]) => (holds ? [] : [name]));+ const violations = throws+ .filter((statement) => {+ const value = resolve(statement.getExpression());+ return (+ !value ||+ !Node.isCallExpression(value) ||+ resolve(value.getExpression())?.getSymbol() !== factory+ );+ })+ .map((statement) => statement.getStartLineNumber());+ return { census, throws: throws.length, violations };+}+const run = (overrides = {}) => {const lines = [];const now = Date.now();@@ -236,18 +317,14 @@ describe('failure evidence classification', () => {});test('routes every throw in the owned fuse functions through the shared factory', () => {- const afterPackFuseFunction = sourceSection(- afterPackSource,- 'async function flipElectronFuses',- '\n\nexport default async function afterPack',- );- const afterSignFuseFunction = sourceSection(- afterSignSource,- 'async function verifyFuses',- '\n\nexport default async function afterSign',- );- expect(throwTargets(afterPackFuseFunction)).toEqual(new Set(['createFuseFailure']));- expect(throwTargets(afterSignFuseFunction)).toEqual(new Set(['createFuseFailure']));+ for (const [source, owned, boundary, minimum] of [+ [afterPackSource, ['flipElectronFuses', 'assertAdHocSealCoversBundle'], 'afterPack', 3],+ [afterSignSource, ['verifyFuses'], 'afterSign', 2],+ ]) {+ const result = inspectFuseThrows(source, owned, boundary);+ expect(result, `${boundary}.mjs`).toMatchObject({ census: [], violations: [] });+ expect(result.throws, `${boundary}.mjs`).toBeGreaterThanOrEqual(minimum);+ }});test.each([@@ -2032,3 +2109,82 @@ describe('workflow wiring', () => {}});});++describe('fuse throw rule self-test', () => {+ const source = (body) => `+ import { createFuseFailure as failure } from './packaging-diagnostics.mjs';+ async function verifyFuses() { ${body} }+ export default async function afterSign() {}+ `;+ const inspectThrows = (body) => inspectFuseThrows(source(body), ['verifyFuses'], 'afterSign');+ test('rejects the adjacent unmarked throw and resolves the imported factory', () => {+ expect(inspectThrows("throw new Error('detail');")).toMatchObject({ census: [], throws: 1 });+ expect(inspectThrows("throw new Error('detail');").violations).toHaveLength(1);+ expect(inspectThrows("throw wrapFailure('detail');").violations).toHaveLength(1);+ expect(+ inspectThrows(+ "const {error} = {error: (failure<string>)('detail')}; throw (error as Error)!;",+ ),+ ).toEqual({ census: [], throws: 1, violations: [] });+ });+ test('rejects a runtime await wrapper while accepting a direct factory call', () => {+ expect(inspectThrows("throw await failure('detail');").violations).toHaveLength(1);+ expect(inspectThrows("throw failure('detail');").violations).toEqual([]);+ });+ test('includes nested throws but ignores quoted throw text', () => {+ expect(+ inspectThrows("throw failure('detail'); function nested() { throw new Error('nested'); }")+ .violations,+ ).toHaveLength(1);+ expect(+ inspectThrows(+ "throw failure('detail'); /* throw new Error */ const prose = 'throw new Error';",+ ),+ ).toEqual({ census: [], throws: 1, violations: [] });+ });+ test('fails its census on removed throws, forwarding, or syntax errors', () => {+ expect(inspectThrows('').census).toEqual(['verifyFuses']);+ expect(+ inspectFuseThrows("export * from './moved.mjs';", ['verifyFuses'], 'afterSign').census,+ ).toEqual(['createFuseFailure', 'verifyFuses', 'afterSign', 'forwarding']);+ expect(inspectThrows("throw failure('detail'); const = ;").census).toEqual(['syntax']);+ });+ test.each([+ [+ 'renamed',+ source("throw failure('detail');").replace('function verifyFuses', 'function renamedFuses'),+ ],+ [+ 'declared after the boundary',+ `+ import { createFuseFailure as failure } from './packaging-diagnostics.mjs';+ export default async function afterSign() {}+ async function verifyFuses() { throw failure('detail'); }+ `,+ ],+ ])('names only the owned function when it is %s', (_label, input) => {+ expect(inspectFuseThrows(input, ['verifyFuses'], 'afterSign').census).toEqual(['verifyFuses']);+ });+ test('names only the boundary when it is renamed', () => {+ const renamed = source("throw failure('detail');").replace(+ 'function afterSign',+ 'function renamedSign',+ );+ expect(inspectFuseThrows(renamed, ['verifyFuses'], 'afterSign').census).toEqual(['afterSign']);+ });+ test('names only the first of two owned functions when it follows the boundary', () => {+ const reordered = `+ import { createFuseFailure as failure } from './packaging-diagnostics.mjs';+ async function assertAdHocSealCoversBundle() { throw failure('detail'); }+ export default async function afterPack() {}+ async function flipElectronFuses() { throw failure('detail'); }+ `;+ expect(+ inspectFuseThrows(+ reordered,+ ['flipElectronFuses', 'assertAdHocSealCoversBundle'],+ 'afterPack',+ ).census,+ ).toEqual(['flipElectronFuses']);+ });+});diff --git a/.github/scripts/write-back.test.mjs b/.github/scripts/write-back.test.mjsindex 1db7c47d6..24be484c2 100644--- a/.github/scripts/write-back.test.mjs+++ b/.github/scripts/write-back.test.mjs@@ -1,6 +1,7 @@/* biome-ignore-all lint/suspicious/noTemplateCurlyInString: GitHub expression fixtures must remain literal. *//* biome-ignore-all lint/suspicious/noUndeclaredEnvVars: Tests exercise the GitHub Actions environment outside Turbo. */import { readFileSync } from 'node:fs';+import { Node, Project, SyntaxKind, ts } from 'ts-morph';import { describe, expect, test } from 'vitest';import { parse } from 'yaml';import { deriveChannel } from './published-release-tags.mjs';@@ -73,6 +74,99 @@ function harness(overrides = {}) {return { deps, logs, writes, run: () => runWriteBack(deps) };}+function inspectWriteBackBoundaries(source) {+ const project = new Project({+ useInMemoryFileSystem: true,+ skipLoadingLibFiles: true,+ compilerOptions: { allowJs: true },+ });+ const boundaries = [+ ['published-release-tags', 'realPublishedReleaseTags'],+ ['resolve-shipped-version', 'resolveShippedVersion'],+ ['tag-containment', 'createTagContainment'],+ ].map(([module, name]) =>+ project+ .createSourceFile(+ `/${module}.mjs`,+ readFileSync(new URL(`./${module}.mjs`, import.meta.url), 'utf8'),+ )+ .getFunctionOrThrow(name)+ .getSymbolOrThrow(),+ );+ const file = project.createSourceFile('/write-back.ts', source);+ const value = (node, seen = new Set()) => {+ if (!node || seen.has(node)) return undefined;+ const next = new Set(seen).add(node);+ if (Node.isParenthesizedExpression(node)) return value(node.getExpression(), next);+ if (Node.isVariableDeclaration(node) || Node.isPropertyAssignment(node))+ return value(node.getInitializer(), next);+ if (Node.isShorthandPropertyAssignment(node))+ return value(node.getValueSymbol()?.getDeclarations()[0], next);+ if (Node.isIdentifier(node)) return value(node.getSymbol()?.getDeclarations()[0], next);+ return node;+ };+ const isCallOf = (node, symbol) =>+ !!node && Node.isCallExpression(node) && node.getExpression().getType().getSymbol() === symbol;+ const main = file.getFunction('main');+ const derive = file.getFunction('deriveVersionForFixRefs');+ const createVersion = file.getFunction('createVersionFor');+ const census = Object.entries({+ main: !!main?.getBody(),+ deriveVersionForFixRefs: !!derive?.getBody(),+ createVersionFor: !!createVersion?.getBody(),+ forwarding: file+ .getExportDeclarations()+ .every((declaration) => !declaration.getModuleSpecifier()),+ syntax: project.getProgram().getSyntacticDiagnostics(file).length === 0,+ }).flatMap(([name, holds]) => (holds ? [] : [name]));+ const consumers = (main?.getDescendantsOfKind(SyntaxKind.CallExpression) ?? []).filter((call) =>+ isCallOf(call, createVersion?.getSymbol()),+ );+ const input = (call, key) =>+ value(call.getArguments()[0]?.getType().getProperty(key)?.getDeclarations()[0]);+ const localTags = file+ .getDescendantsOfKind(SyntaxKind.FunctionDeclaration)+ .some((fn) => ['realStableTags', 'realReleaseTags'].includes(fn.getName()));+ const filterBindings = new Set(+ file+ .getDescendantsOfKind(SyntaxKind.Identifier)+ .filter((node) => ts.idText(node.compilerNode) === 'STABLE_TAG_RE')+ .map((node) => node.getSymbol()),+ );+ const localFilters = file+ .getDescendantsOfKind(SyntaxKind.CallExpression)+ .some((call) =>+ call+ .getDescendantsOfKind(SyntaxKind.Identifier)+ .some((node) => filterBindings.has(node.getSymbol())),+ );++ const tags =+ consumers.length > 0 &&+ !localTags &&+ !localFilters &&+ consumers.every((call) => isCallOf(input(call, 'stableTags'), boundaries[0]));+ const localContainment = file.getDescendants().some((node) => {+ const literal = node.compilerNode;+ return (+ (ts.isStringLiteralLike(literal) ||+ ts.isTemplateHead(literal) ||+ ts.isTemplateMiddle(literal) ||+ ts.isTemplateTail(literal) ||+ ts.isRegularExpressionLiteral(literal)) &&+ /merge-base|--contains/.test(literal.text)+ );+ });+ const containment =+ !localContainment &&+ consumers.length > 0 &&+ consumers.every((call) => isCallOf(input(call, 'contains'), boundaries[2])) &&+ !!derive+ ?.getDescendantsOfKind(SyntaxKind.CallExpression)+ .some((call) => isCallOf(call, boundaries[1]));+ return { census, tags, containment };+}+describe('candidate enumeration', () => {test('the candidate page proves whether a child lookup is necessary without filtering child states', () => {expect(CANDIDATE_QUERY).toContain(@@ -110,18 +204,12 @@ describe('candidate enumeration', () => {test('the tag list comes from the shared boundary, never a private copy of it', () => {const source = readFileSync(new URL('./write-back.mjs', import.meta.url), 'utf8');- expect(source).toMatch(- /import \{[^}]*\brealPublishedReleaseTags\b[^}]*\} from '\.\/published-release-tags\.mjs'/,- );- expect(source).not.toMatch(/^function real(?:Stable|Release)Tags/m);- expect(source).not.toMatch(/Tags[^\n]*\.filter\([^\n]*STABLE_TAG_RE/);+ expect(inspectWriteBackBoundaries(source)).toMatchObject({ census: [], tags: true });});test('the module imports the shared shipped-version resolver rather than reimplementing containment', () => {const source = readFileSync(new URL('./write-back.mjs', import.meta.url), 'utf8');- expect(source).toMatch(/from '\.\/resolve-shipped-version\.mjs'/);- expect(source).toContain('resolveShippedVersion');- expect(source.match(/merge-base/g)?.length ?? 0).toBeLessThanOrEqual(2);+ expect(inspectWriteBackBoundaries(source)).toMatchObject({ census: [], containment: true });});});@@ -1700,3 +1788,68 @@ describe('the beta leg', () => {);});});++describe('write-back boundary rule self-test', () => {+ const source = (tags = 'published()', contains = 'containment()') => `+ import { realPublishedReleaseTags as published } from './published-release-tags.mjs';+ import { resolveShippedVersion as resolveVersion } from './resolve-shipped-version.mjs';+ import { createTagContainment as containment } from './tag-containment.mjs';+ function main() { const stableTags = ${tags}; const contains = ${contains}; createVersionFor({stableTags, contains}); }+ function createVersionFor(options) { return options; }+ function deriveVersionForFixRefs() { return resolveVersion({}); }+ `;+ test('resolves the shared boundary and rejects an adjacent private list or predicate', () => {+ expect(inspectWriteBackBoundaries(source())).toEqual({+ census: [],+ tags: true,+ containment: true,+ });+ expect(+ inspectWriteBackBoundaries(source().replace('return resolveVersion({});', 'return {};')),+ ).toEqual({ census: [], tags: true, containment: false });+ expect(inspectWriteBackBoundaries(source('[]'))).toEqual({+ census: [],+ tags: false,+ containment: true,+ });+ expect(inspectWriteBackBoundaries(source('published()', '() => true'))).toEqual({+ census: [],+ tags: true,+ containment: false,+ });+ expect(+ inspectWriteBackBoundaries(source().replace('createVersionFor({stableTags, contains});', '')),+ ).toEqual({ census: [], tags: false, containment: false });+ });+ test.each([+ 'function realStableTags() { return []; }',+ 'function legacyTags(allTags, STABLE_TAG_RE) { return allTags.filter(tag => STABLE_TAG_RE.test(tag)); }',+ 'function legacyTags(allTags) { return allTags.filter(tag => STABLE_TAG_RE.test(tag)); }',+ 'function realReleaseTags() { return []; }',+ 'const STABLE_TAG_RE = /^v/; function legacyTags(allTags) { return allTags.filter(tag => STABLE_TAG_RE.test(tag)); }',+ ])('rejects a local tag boundary: %s', (local) => {+ expect(inspectWriteBackBoundaries(`${source()} ${local}`).tags).toBe(false);+ expect(+ inspectWriteBackBoundaries(`${source()} function unrelatedTags() { return []; }`).tags,+ ).toBe(true);+ });+ test('rejects local containment values and ignores their comment spelling', () => {+ expect(+ inspectWriteBackBoundaries(`${source()} const command = 'merge-base';`).containment,+ ).toBe(false);+ expect(inspectWriteBackBoundaries(`${source()} /* merge-base */`)).toEqual({+ census: [],+ tags: true,+ containment: true,+ });+ });+ test('rejects forwarding or syntax errors instead of an empty census', () => {+ expect(inspectWriteBackBoundaries("export * from './moved.mjs';").census).toEqual([+ 'main',+ 'deriveVersionForFixRefs',+ 'createVersionFor',+ 'forwarding',+ ]);+ expect(inspectWriteBackBoundaries(`${source()} const = ;`).census).toEqual(['syntax']);+ });+});diff --git a/knip.config.ts b/knip.config.tsindex 37d9ce912..be41ab16c 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -145,15 +145,11 @@ 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/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.tsindex a28cc2b18..8a60e5826 100644--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts@@ -1,4 +1,3 @@-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/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.tsindex 4fc2c11f9..6fcdc23f2 100644--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts@@ -1,4 +1,3 @@-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.tsindex 9f2f6feb6..40b5cdfd6 100644--- a/packages/app/tests/integration/interior-edit-freshness.test.ts+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts@@ -1,4 +1,3 @@-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.tsindex 2a085742b..93666af70 100644--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts@@ -1,4 +1,3 @@-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.tsindex 878d5196b..867598d34 100644--- a/packages/app/tests/integration/producer-guard-wiring.test.ts+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts@@ -1,4 +1,3 @@-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.tsindex 4ada3cf26..0970ac12f 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,4 +1,3 @@-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.tsindex cbe2b705f..b632185e1 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,4 +1,3 @@-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.tsindex 89bc9b4d9..c530ce4ba 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,4 +1,3 @@-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.tsindex a78aeb0e4..d3767adc9 100644--- a/packages/app/tests/integration/undo-after-rollback.test.ts+++ b/packages/app/tests/integration/undo-after-rollback.test.ts@@ -1,4 +1,3 @@-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.tsindex e7cc69c3f..b076f955c 100644--- a/packages/app/tests/integration/undo-recycle-reset.test.ts+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts@@ -1,4 +1,3 @@-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.tsindex 9ddcd0730..7935e35f8 100644--- a/packages/app/tests/integration/undo-rederive-survival.test.ts+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts@@ -1,4 +1,3 @@-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/integration/vite-worker-cachedir-isolation.test.ts b/packages/app/tests/integration/vite-worker-cachedir-isolation.test.tsindex 1d5bcafd3..808c407d1 100644--- a/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts+++ b/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts@@ -1,5 +1,6 @@+import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { type Node, Project, SyntaxKind } from 'ts-morph';+import { Node, Project, SyntaxKind, ts } from 'ts-morph';import { loadConfigFromFile } from 'vite';import { describe, expect, test } from 'vitest';@@ -9,14 +10,152 @@ const WORKER_FIXTURES = resolve(APP_PACKAGE_ROOT, 'tests/stress/_helpers/fixtureconst CACHE_DIR_ENV_VAR = 'OK_TEST_VITE_CACHE_DIR';-function parseSource(filePath: string) {- const project = new Project({- skipFileDependencyResolution: true,- skipLoadingLibFiles: true,- skipAddingFilesFromTsConfig: true,- compilerOptions: { noLib: true, allowJs: false },- });- return project.addSourceFileAtPath(filePath);+function inspectWorkerCache(source: string) {+ const project = new Project({ useInMemoryFileSystem: true, compilerOptions: { noLib: true } });+ const syntax = project.createSourceFile('/input.ts', source);+ const file = project.createSourceFile(+ '/fixtures.ts',+ ts.transpile(source, {+ target: ts.ScriptTarget.ESNext,+ module: ts.ModuleKind.ESNext,+ verbatimModuleSyntax: true,+ }),+ );+ const imported = (module: string, name: string) => {+ const declaration =+ file.getImportDeclaration(module) ?? file.getImportDeclaration(module.replace('node:', ''));+ const entry = declaration?.getNamedImports().find((item) => item.getName() === name);+ return (entry?.getAliasNode() ?? entry?.getNameNode())?.getSymbol();+ };+ const returned = new Map<import('ts-morph').Symbol, Node>();+ const value = (node: Node | undefined, seen = new Set<Node>()): Node | undefined => {+ if (!node || seen.has(node)) return undefined;+ const next = new Set(seen).add(node);+ if (Node.isParenthesizedExpression(node) || Node.isAwaitExpression(node))+ return value(node.getExpression(), next);+ if (Node.isVariableDeclaration(node))+ return value(node.getInitializer() ?? returned.get(node.getSymbolOrThrow()), next);+ if (Node.isPropertyAssignment(node)) return value(node.getInitializer(), next);+ if (Node.isShorthandPropertyAssignment(node))+ return value(node.getValueSymbol()?.getDeclarations()[0], next);+ if (Node.isIdentifier(node)) {+ const declaration = node.getSymbol()?.getDeclarations()[0];+ return declaration &&+ (Node.isVariableDeclaration(declaration) || Node.isBindingElement(declaration))+ ? value(declaration, next)+ : node;+ }+ if (Node.isBindingElement(node)) {+ const owner = node.getParent().getParent();+ const object = Node.isVariableDeclaration(owner)+ ? value(owner.getInitializer(), next)+ : undefined;+ const name = node.getPropertyNameNode();+ const key = name && Node.isIdentifier(name) ? ts.idText(name.compilerNode) : node.getName();+ const field = object?.getType().getProperty(key)?.getDeclarations()[0];+ return field ? value(field, next) : node;+ }+ return node;+ };+ const property = (node: Node | undefined, key: string) =>+ value(+ value(node)+ ?.asKind(SyntaxKind.ObjectLiteralExpression)+ ?.getProperties()+ .find((field) => field.getSymbol()?.getName() === key),+ );+ const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression);+ const phase = file.getFunction('spendOnBudgetPhase')?.getSymbol();+ for (const call of calls) {+ if (!phase || value(call.getExpression())?.getSymbol() !== phase) continue;+ const callback = call.getArguments()[1];+ const result = callback+ ?.getDescendantsOfKind(SyntaxKind.ReturnStatement)+ .find(+ (statement) =>+ statement.getFirstAncestor((node) => ts.isFunctionLike(node.compilerNode)) === callback,+ )+ ?.getExpression();+ const assignment = call.getFirstAncestorByKind(SyntaxKind.BinaryExpression);+ const binding = assignment?.getLeft().getSymbol();+ if (result && binding && assignment?.getOperatorToken().getKind() === SyntaxKind.EqualsToken)+ returned.set(binding, result);+ }+ const declaration = file.getVariableDeclaration('test');+ const extend = declaration?.getInitializerIfKind(SyntaxKind.CallExpression);+ const callee = extend?.getExpression().asKind(SyntaxKind.PropertyAccessExpression);+ const fixture = property(extend?.getArguments()[0], 'workerServer')+ ?.asKind(SyntaxKind.ArrayLiteralExpression)+ ?.getElements()[0]+ ?.asKind(SyntaxKind.ArrowFunction);+ const base = imported('@playwright/test', 'test');+ const worker = fixture?.getParameters()[2]?.getSymbol();+ const spawn = imported('node:child_process', 'spawn');+ const fresh = imported('node:fs', 'mkdtempSync');+ const removals = [+ imported('node:fs', 'rmSync'),+ imported('./teardown-fs.ts', 'removeAllDuringTeardown'),+ ].filter((symbol) => symbol !== undefined);+ const spawns = (fixture?.getDescendantsOfKind(SyntaxKind.CallExpression) ?? []).filter(+ (call) => spawn && value(call.getExpression())?.getSymbol() === spawn,+ );+ const census = Object.entries({+ syntax: project.getProgram().getSyntacticDiagnostics(syntax).length === 0,+ test: !!declaration?.getVariableStatement()?.isExported(),+ extend: callee?.getName() === 'extend' && !!base && callee.getExpression().getSymbol() === base,+ workerServer: !!fixture,+ workerInfo: !!worker,+ spawn: spawns.length > 0,+ }).flatMap(([name, holds]) => (holds ? [] : [name]));+ const unique = (input: Node | undefined): boolean => {+ const node = value(input);+ return (+ !!node &&+ [node, ...node.getDescendants()].some(+ (part) =>+ (Node.isCallExpression(part) &&+ !!fresh &&+ value(part.getExpression())?.getSymbol() === fresh) ||+ (Node.isPropertyAccessExpression(part) &&+ part.getName() === 'workerIndex' &&+ value(part.getExpression())?.getSymbol() === worker),+ )+ );+ };+ const cacheProperties = file+ .getDescendants()+ .filter(+ (node) =>+ (Node.isPropertyAssignment(node) || Node.isShorthandPropertyAssignment(node)) &&+ node.getSymbol()?.getName() === CACHE_DIR_ENV_VAR,+ );+ const nonUnique = cacheProperties.filter((node) => !unique(node)).length;+ let missingEnv = 0,+ missingCleanup = 0,+ teardowns = 0;+ const reclaims = calls.filter((call) =>+ removals.some((symbol) => value(call.getExpression())?.getSymbol() === symbol),+ );+ const blocksOf = (resource: Node | undefined) =>+ resource+ ? reclaims+ .filter((call) => call.getArguments().some((arg) => value(arg) === resource))+ .map((call) => call.getFirstAncestorByKind(SyntaxKind.Block))+ : [];+ for (const call of spawns) {+ const env = property(call.getArguments()[2], 'env');+ const cache = property(env, CACHE_DIR_ENV_VAR);+ if (!cache) {+ missingEnv++;+ continue;+ }+ const contents = blocksOf(property(env, 'OK_TEST_CONTENT_DIR'));+ const caches = new Set(blocksOf(cache));+ teardowns += contents.length;+ missingCleanup +=+ Number(contents.length < 2) + contents.filter((block) => !block || !caches.has(block)).length;+ }+ return { census, missingEnv, nonUnique, missingCleanup, spawns: spawns.length, teardowns };}async function withEnv<T>(@@ -35,52 +174,6 @@ async function withEnv<T>(}}-function classifyPerWorkerExpression(node: Node): { ok: boolean; why: string } {- const text = node.getText();- if (text.includes('workerInfo.workerIndex')) {- return { ok: true, why: 'references workerInfo.workerIndex' };- }- if (text.includes('mkdtempSync')) {- return {- ok: true,- why: 'uses mkdtempSync (fresh dir per call → per-worker unique by construction)',- };- }- if (node.isKind(SyntaxKind.Identifier)) {- const ident = node.asKindOrThrow(SyntaxKind.Identifier);- const symbol = ident.getSymbol();- if (!symbol) {- return {- ok: false,- why: `identifier ${text} has no resolvable symbol; cannot trace declaration`,- };- }- for (const decl of symbol.getDeclarations()) {- const declText = decl.getText();- if (declText.includes('workerInfo.workerIndex')) {- return {- ok: true,- why: `identifier ${text} declared at line ${decl.getStartLineNumber()}; declaration references workerInfo.workerIndex`,- };- }- if (declText.includes('mkdtempSync')) {- return {- ok: true,- why: `identifier ${text} declared at line ${decl.getStartLineNumber()}; declaration uses mkdtempSync`,- };- }- }- return {- ok: false,- why: `identifier ${text} traced to declaration(s) that do NOT reference workerInfo.workerIndex or mkdtempSync — a static string variable does not provide per-worker uniqueness`,- };- }- return {- ok: false,- why: `expression ${text.slice(0, 100)}${text.length > 100 ? '…' : ''} is not a recognized per-worker-unique form (expected to reference workerInfo.workerIndex or mkdtempSync, either inline or via a single-level identifier)`,- };-}-describe('per-worker Vite cacheDir isolation — vite.config.ts side', () => {test('A1: resolves cacheDir from OK_TEST_VITE_CACHE_DIR env var', async () => {const expected = '/tmp/ok-vite-cachedir-isolation-test-a1';@@ -120,138 +213,128 @@ describe('per-worker Vite cacheDir isolation — vite.config.ts side', () => {});describe('per-worker Vite cacheDir isolation — workerServer fixture side', () => {+ const inspect = () => inspectWorkerCache(readFileSync(WORKER_FIXTURES, 'utf8'));test(`B1: workerServer spawn() env declares ${CACHE_DIR_ENV_VAR}`, () => {- const sf = parseSource(WORKER_FIXTURES);- const matches = sf- .getDescendantsOfKind(SyntaxKind.PropertyAssignment)- .filter((prop) => prop.getName() === CACHE_DIR_ENV_VAR);- if (matches.length === 0) {- throw new Error(- `tests/stress/_helpers/fixtures.ts must declare an \`${CACHE_DIR_ENV_VAR}\` env entry on the workerServer fixture's spawn() call.\n` +- `Without it, every worker's Vite dev server resolves its cacheDir to the default <root>/node_modules/.vite — a shared directory that the dependency optimizer is single-writer over.\n` +- `See PR #1146 body for the AC-T3 / F1 e2e flake class this contract closes.`,- );- }- expect(matches.length).toBeGreaterThan(0);+ const result = inspect();+ expect(result.census).toEqual([]);+ expect(+ result.missingEnv,+ `Declare ${CACHE_DIR_ENV_VAR} on the workerServer fixture's spawn env. Otherwise workers share Vite's default node_modules/.vite cache, whose optimizer is single-writer. See PR #1146 AC-T3 / F1.`,+ ).toBe(0);});-test(`B2: ${CACHE_DIR_ENV_VAR} value is per-worker unique (references workerInfo.workerIndex or mkdtempSync)`, () => {- const sf = parseSource(WORKER_FIXTURES);- const props = sf- .getDescendantsOfKind(SyntaxKind.PropertyAssignment)- .filter((prop) => prop.getName() === CACHE_DIR_ENV_VAR);- if (props.length === 0) {- throw new Error(- `B2 prerequisite missing: no \`${CACHE_DIR_ENV_VAR}\` property in fixtures.ts (B1 should have failed first).`,- );- }- const failures: string[] = [];- for (const prop of props) {- const initializer = prop.getInitializer();- if (!initializer) {- failures.push(`${prop.getName()} at line ${prop.getStartLineNumber()} has no initializer`);- continue;- }- const verdict = classifyPerWorkerExpression(initializer);- if (!verdict.ok) {- failures.push(`${CACHE_DIR_ENV_VAR} at line ${prop.getStartLineNumber()}: ${verdict.why}`);- }- }- if (failures.length > 0) {- throw new Error(- [- `\`${CACHE_DIR_ENV_VAR}\` value must be per-worker unique. Acceptable shapes:`,- ` - Template literal referencing workerInfo.workerIndex, e.g.:`,- ` \`${CACHE_DIR_ENV_VAR}: join(APP_PACKAGE_ROOT, 'node_modules', \\\`.vite-w\${workerInfo.workerIndex}\\\`)\``,- ` - Computed via mkdtempSync, e.g.:`,- ` \`OK_TEST_VITE_CACHE_DIR: mkdtempSync(join(APP_PACKAGE_ROOT, 'node_modules', \\\`.vite-w\${workerInfo.workerIndex}-\\\`))\``,- ` - Bound to a local variable (single-level identifier) whose declaration matches one of the above`,- ``,- `Violations:`,- ...failures.map((f) => ` - ${f}`),- ].join('\n'),- );- }- expect(failures).toEqual([]);+ const result = inspect();+ expect(result.census).toEqual([]);+ expect(result.missingEnv).toBe(0);+ expect(+ result.nonUnique,+ `${CACHE_DIR_ENV_VAR} must be, or be bound through variables to, an expression that itself calls the imported mkdtempSync or reads the fixture's workerInfo.workerIndex. A static string does not isolate workers, and an index first read into another variable is not followed.`,+ ).toBe(0);});-test(`B3: workerServer teardown reclaims the per-worker ${CACHE_DIR_ENV_VAR} at both teardown sites`, () => {- const sf = parseSource(WORKER_FIXTURES);-- const props = sf- .getDescendantsOfKind(SyntaxKind.PropertyAssignment)- .filter((prop) => prop.getName() === CACHE_DIR_ENV_VAR);- if (props.length === 0) {- throw new Error(- `B3 prerequisite missing: no \`${CACHE_DIR_ENV_VAR}\` property in fixtures.ts (B1 should have failed first).\n` +- `Without the property, there is no identifier to hand the removal at teardown — so the per-worker Vite cacheDir cannot be reclaimed and CI accumulates orphan directories under tmpdir() until the runner's filesystem fills.`,- );- }- const initializer = props[0]?.getInitializer();- if (!initializer) {- throw new Error(- `B3 prerequisite missing: \`${CACHE_DIR_ENV_VAR}\` property at line ${props[0]?.getStartLineNumber()} has no initializer.`,- );- }- if (!initializer.isKind(SyntaxKind.Identifier)) {- throw new Error(- `B3 requires \`${CACHE_DIR_ENV_VAR}\` to be bound to a named local variable so the workerServer fixture can reclaim the same path at teardown.\n` +- `Found initializer at line ${initializer.getStartLineNumber()}: \`${initializer.getText().slice(0, 80)}\` (kind: ${initializer.getKindName()}).\n` +- `Acceptable shape: \`const viteCacheDir = mkdtempSync(...); ...; ${CACHE_DIR_ENV_VAR}: viteCacheDir,\`.`,- );- }- const cacheDirVar = initializer.getText();+ const result = inspect();+ expect(result.census).toEqual([]);+ expect(result.missingEnv).toBe(0);+ expect(+ result.missingCleanup,+ `Bind ${CACHE_DIR_ENV_VAR} to a local variable and reclaim the same resource alongside contentDir at BOTH failure and happy teardown sites. Recognised primitives are node:fs rmSync and teardown-fs removeAllDuringTeardown; admit a new removal primitive by adding its import to the removals list in inspectWorkerCache. Missing cleanup leaves orphan Vite cache directories under packages/app/node_modules.`,+ ).toBe(0);+ expect(result.teardowns).toBeGreaterThanOrEqual(2);+ });+});- const REMOVAL_CALLEES = new Set(['rmSync', 'removeAllDuringTeardown']);- const allCalls = sf.getDescendantsOfKind(SyntaxKind.CallExpression);- const reclaimsOf = (targetName: string) =>- allCalls.filter((call) => {- if (!REMOVAL_CALLEES.has(call.getExpression().getText())) return false;- return call- .getArguments()- .some((arg) => arg.isKind(SyntaxKind.Identifier) && arg.getText() === targetName);- });- const contentDirTeardowns = reclaimsOf('contentDir');- const cacheDirTeardowns = reclaimsOf(cacheDirVar);+const workerFixture = `import { test as base } from '@playwright/test';+ import { spawn } from 'node:child_process';+ import { mkdtempSync, rmSync } from 'node:fs';+ export const test = base.extend({ workerServer: [async ({}, use, workerInfo) => {+ const contentDir = mkdtempSync('content');+ const viteCacheDir = mkdtempSync('cache');+ spawn('pnpm', [], { env: { OK_TEST_CONTENT_DIR: contentDir, OK_TEST_VITE_CACHE_DIR: viteCacheDir } });+ try { await use(); } catch { rmSync(contentDir); rmSync(viteCacheDir); }+ rmSync(contentDir); rmSync(viteCacheDir);+ }, { scope: 'worker' }] });`;- if (contentDirTeardowns.length < 2) {- throw new Error(- `B3 expected at least 2 removal calls reclaiming \`contentDir\` to anchor the failure-path + happy-path teardown sites; found ${contentDirTeardowns.length}.\n` +- `Recognised removal primitives: ${[...REMOVAL_CALLEES].join(', ')}.\n` +- `If the fixture now reclaims through a different primitive, add it to REMOVAL_CALLEES rather than reverting the fixture — the invariant is that both directories are reclaimed at both teardown sites, not which function does it.`,- );- }-- const missing: string[] = [];- for (const cTeardown of contentDirTeardowns) {- const parentBlock = cTeardown.getFirstAncestorByKind(SyntaxKind.Block);- if (!parentBlock) {- missing.push(- `removal call reclaiming \`contentDir\` at line ${cTeardown.getStartLineNumber()} has no Block ancestor; cannot locate the ${cacheDirVar} reclaim for that site`,- );- continue;- }- const sibling = cacheDirTeardowns.find(- (cdt) => cdt.getFirstAncestorByKind(SyntaxKind.Block) === parentBlock,- );- if (!sibling) {- missing.push(- `teardown site at line ${cTeardown.getStartLineNumber()} reclaims \`contentDir\` but nothing in the same block reclaims \`${cacheDirVar}\``,- );- }- }+const phasedFixture = `import { test as base } from '@playwright/test';+ import { spawn } from 'node:child_process';+ import { mkdtempSync, rmSync } from 'node:fs';+ async function spendOnBudgetPhase(phase, body) { return body(); }+ export const test = base.extend({ workerServer: [async ({}, use, workerInfo) => {+ let started;+ started = await spendOnBudgetPhase(0, async () => {+ const contentDir = mkdtempSync('content');+ const viteCacheDir = mkdtempSync('cache');+ const log = () => { return 0; };+ try { spawn('pnpm', [], { env: { OK_TEST_CONTENT_DIR: contentDir, OK_TEST_VITE_CACHE_DIR: viteCacheDir } }); }+ catch { rmSync(contentDir); rmSync(viteCacheDir); }+ return { contentDir, viteCacheDir };+ });+ const { contentDir, viteCacheDir } = started;+ await use();+ rmSync(contentDir); rmSync(viteCacheDir);+ }, { scope: 'worker' }] });`;- if (missing.length > 0) {- throw new Error(- [- `tests/stress/_helpers/fixtures.ts must reclaim \`${cacheDirVar}\` at BOTH teardown sites — the failure-path catch block AND the happy-path after-\`use\` block — alongside the \`contentDir\` reclaim already there.`,- `Without cleanup at both sites, CI accumulates orphan per-worker Vite cache directories under tmpdir() until the runner's filesystem fills.`,- ``,- `Missing:`,- ...missing.map((m) => ` - ${m}`),- ].join('\n'),- );+describe('worker cache rule self-test', () => {+ test('accepts a unique reclaimed cache and rejects the adjacent shared cache', () => {+ expect(inspectWorkerCache(workerFixture)).toEqual({+ census: [],+ missingEnv: 0,+ nonUnique: 0,+ missingCleanup: 0,+ spawns: 1,+ teardowns: 2,+ });+ expect(+ inspectWorkerCache(workerFixture.replace("mkdtempSync('cache')", "'shared'")).nonUnique,+ ).toBe(1);+ expect(+ inspectWorkerCache(+ workerFixture+ .replace("mkdtempSync('cache')", "'shared'; const OK_TEST_VITE_CACHE_DIR = viteCacheDir")+ .replace('OK_TEST_VITE_CACHE_DIR: viteCacheDir', 'OK_TEST_VITE_CACHE_DIR'),+ ),+ ).toMatchObject({ missingEnv: 0, nonUnique: 1, missingCleanup: 0 });+ for (const shared of [+ "prepareViteCacheDir('shared')",+ "'cache-' + ({ workerIndex: 0 }).workerIndex",+ ]) {+ expect(+ inspectWorkerCache(workerFixture.replace("mkdtempSync('cache')", shared)).nonUnique,+ shared,+ ).toBe(1);}- expect(missing).toEqual([]);+ });+ test('requires the spawn entry and both cleanup sites', () => {+ expect(+ inspectWorkerCache(workerFixture.replace('OK_TEST_VITE_CACHE_DIR:', 'OTHER:')).missingEnv,+ ).toBe(1);+ expect(+ inspectWorkerCache(workerFixture.replace('rmSync(viteCacheDir);', '')).missingCleanup,+ ).toBe(1);+ expect(+ inspectWorkerCache(workerFixture.replace('rmSync(viteCacheDir);\n', '\n')).missingCleanup,+ ).toBe(1);+ });+ test('reads the setup phase result past a nested block-bodied return', () => {+ expect(inspectWorkerCache(phasedFixture)).toEqual({+ census: [],+ missingEnv: 0,+ nonUnique: 0,+ missingCleanup: 0,+ spawns: 1,+ teardowns: 2,+ });+ });+ test('ignores comments and refuses a forwarding or unparseable fixture', () => {+ expect(+ inspectWorkerCache(`${workerFixture} /* OK_TEST_VITE_CACHE_DIR: 'shared' */`).nonUnique,+ ).toBe(0);+ expect(inspectWorkerCache("export {test} from './moved.ts';").census).toEqual([+ 'test',+ 'extend',+ 'workerServer',+ 'workerInfo',+ 'spawn',+ ]);+ expect(inspectWorkerCache(`${workerFixture} const = ;`).census).toEqual(['syntax']);});});diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 2a597ec3d..f4cc8a286 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,4 +1,3 @@-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.tsindex 01ef76a9f..8fb428b90 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-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.tsindex fb0ba5a7c..fc267cbea 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-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.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-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.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');