kernel-tsjs-parity.test.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /**
  2. * Kernel↔wasm TS/JS extraction parity (R2 of the kernel migration).
  3. *
  4. * Asserts the native walker (codegraph-kernel/src/tsjs/) produces the SAME
  5. * ExtractionResult as the wasm TreeSitterExtractor — nodes, edges, and
  6. * unresolved refs compared as canonicalized multisets — over:
  7. * - the checked-in torture fixtures (every ported feature: components/HOCs,
  8. * stores, RTK, vuex, fn-refs, value-ref shadowing, decorators, enums,
  9. * type-alias members/tuple contracts, re-exports, JSX, field methods), and
  10. * - this repo's own extraction sources (real-world TS).
  11. *
  12. * The full-repo sweep lives in scripts/kernel-parity.mjs (excalidraw et al.,
  13. * run for the §5 gate); this suite keeps the invariant alive in `npm test`.
  14. * Skips when no kernel binary is staged; CODEGRAPH_KERNEL_EXPECT=1 turns that
  15. * into a failure (wired in kernel-scaffold.test.ts).
  16. */
  17. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  18. import * as fs from 'fs';
  19. import * as path from 'path';
  20. import { extractFromSource } from '../src/extraction';
  21. import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars';
  22. import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel';
  23. import type { ExtractionResult, Language } from '../src/types';
  24. const KERNEL_PATH = path.join(
  25. __dirname,
  26. '..',
  27. 'codegraph-kernel',
  28. 'prebuilds',
  29. `${process.platform}-${process.arch}`,
  30. 'codegraph-kernel.node'
  31. );
  32. const kernelBuilt = fs.existsSync(KERNEL_PATH);
  33. const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'kernel-parity');
  34. const REAL_SOURCES = [
  35. 'src/extraction/kernel/loader.ts',
  36. 'src/extraction/kernel/decode.ts',
  37. 'src/extraction/parse-pool.ts',
  38. 'src/extraction/function-ref.ts',
  39. 'src/mcp/tools.ts',
  40. ];
  41. function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } {
  42. return {
  43. nodes: result.nodes
  44. .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort()))
  45. .sort(),
  46. edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(),
  47. refs: result.unresolvedReferences
  48. .map((r) => JSON.stringify(r, Object.keys(r).sort()))
  49. .sort(),
  50. };
  51. }
  52. const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const;
  53. let savedEnv: Record<string, string | undefined>;
  54. describe.skipIf(!kernelBuilt)('kernel TS/JS extraction parity', () => {
  55. beforeAll(async () => {
  56. await initGrammars();
  57. await loadGrammarsForLanguages(['typescript', 'tsx', 'javascript', 'jsx', 'java', 'python', 'go']);
  58. });
  59. beforeEach(() => {
  60. savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
  61. resetKernelForTests();
  62. });
  63. afterEach(() => {
  64. for (const k of ENV_KEYS) {
  65. if (savedEnv[k] === undefined) delete process.env[k];
  66. else process.env[k] = savedEnv[k];
  67. }
  68. resetKernelForTests();
  69. });
  70. function assertParity(filePath: string, source: string, language: Language): void {
  71. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  72. delete process.env.CODEGRAPH_KERNEL;
  73. const viaKernel = tryKernelExtract(filePath, source, language);
  74. expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull();
  75. process.env.CODEGRAPH_KERNEL = '0';
  76. const viaWasm = extractFromSource(filePath, source, language);
  77. delete process.env.CODEGRAPH_KERNEL;
  78. const k = canon(viaKernel!);
  79. const w = canon(viaWasm);
  80. expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes);
  81. expect(k.edges, `${filePath}: edges`).toEqual(w.edges);
  82. expect(k.refs, `${filePath}: refs`).toEqual(w.refs);
  83. // Meaningful comparison, not empty-vs-empty.
  84. expect(viaWasm.nodes.length).toBeGreaterThan(3);
  85. }
  86. it('torture fixture (tsx): components, stores, RTK, fn-refs, value-refs, decorators', () => {
  87. const file = path.join(FIXTURE_DIR, 'torture.tsx');
  88. assertParity('fixtures/torture.tsx', fs.readFileSync(file, 'utf8'), 'tsx');
  89. });
  90. it('torture fixture (js): field methods, wrappers, vuex module shape', () => {
  91. const file = path.join(FIXTURE_DIR, 'torture.js');
  92. assertParity('fixtures/torture.js', fs.readFileSync(file, 'utf8'), 'javascript');
  93. });
  94. it('torture fixture (java): Lombok, anonymous classes, method refs, chains', () => {
  95. const file = path.join(FIXTURE_DIR, 'Torture.java');
  96. assertParity('fixtures/Torture.java', fs.readFileSync(file, 'utf8'), 'java');
  97. });
  98. it('torture fixture (python): decorators, self fn-refs, imports, shadowing', () => {
  99. const file = path.join(FIXTURE_DIR, 'torture.py');
  100. assertParity('fixtures/torture.py', fs.readFileSync(file, 'utf8'), 'python');
  101. });
  102. it('torture fixture (go): receivers, embedding, interfaces, composite literals', () => {
  103. const file = path.join(FIXTURE_DIR, 'torture.go');
  104. assertParity('fixtures/torture.go', fs.readFileSync(file, 'utf8'), 'go');
  105. });
  106. it.each(REAL_SOURCES)('real source parity: %s', (rel) => {
  107. const file = path.join(__dirname, '..', rel);
  108. assertParity(rel, fs.readFileSync(file, 'utf8'), 'typescript');
  109. });
  110. // Every torture fixture again with CRLF line endings — the shape every
  111. // Windows autocrlf checkout has. Derived in memory (not a checked-in CRLF
  112. // file) so no platform or editor can silently normalize it away. Pins the
  113. // JS-multiline-^ semantics in the kernel's docstring cleaning: JS `^`/m
  114. // anchors after \r too, so the block-continuation `\s*` eats the `\n` and
  115. // the cleaned docstring keeps a bare `\r` (caught on the Windows VM leg of
  116. // the O2 gate; diverged in the kernel until docstring.rs mirrored it).
  117. it.each([
  118. ['torture.tsx', 'tsx'],
  119. ['torture.js', 'javascript'],
  120. ['Torture.java', 'java'],
  121. ['torture.py', 'python'],
  122. ['torture.go', 'go'],
  123. ] as const)('torture fixture CRLF parity: %s', (name, lang) => {
  124. const file = path.join(FIXTURE_DIR, name);
  125. const crlf = fs.readFileSync(file, 'utf8').replace(/(?<!\r)\n/g, '\r\n');
  126. assertParity(`fixtures/${name} (crlf)`, crlf, lang);
  127. });
  128. it('files with parse errors defer to the wasm extractor (recovery is encoding-dependent)', () => {
  129. // tree-sitter error RECOVERY differs between UTF-8 (native) and UTF-16
  130. // (web-tree-sitter) parsing — same grammar, same core version — so the
  131. // kernel defers any erroring file to keep routing graph-neutral.
  132. const broken = 'export function f( {\n return }} 12 (\n';
  133. process.env.CODEGRAPH_KERNEL_LANGS = 'all';
  134. delete process.env.CODEGRAPH_KERNEL;
  135. expect(tryKernelExtract('src/broken.ts', broken, 'typescript')).toBeNull();
  136. // The seam still serves the file — through the wasm path.
  137. process.env.CODEGRAPH_KERNEL = '0';
  138. const viaWasm = extractFromSource('src/broken.ts', broken, 'typescript');
  139. delete process.env.CODEGRAPH_KERNEL;
  140. expect(viaWasm.nodes.some((n) => n.kind === 'file')).toBe(true);
  141. });
  142. it('typescript fixture parsed as plain typescript variant', () => {
  143. // Same content through the non-tsx grammar exercises the typescript
  144. // (vs tsx) LangSpec pairing.
  145. const file = path.join(__dirname, '..', 'src/extraction/kernel/index.ts');
  146. assertParity('src/extraction/kernel/index.ts', fs.readFileSync(file, 'utf8'), 'typescript');
  147. });
  148. });