explore-declaration-only.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /**
  2. * Regression gate for DECLARATION-ONLY files in explore ranking (task CG-28).
  3. *
  4. * A file that holds nothing but type declarations — an ambient `.d.ts`, vendored
  5. * typings, a `types.ts` of pure interfaces — cannot answer a FLOW question: no
  6. * bodies, no call edges, no behaviour. But the identifiers it declares are
  7. * exactly the generic ones a prose question uses (`Body`, `Message`,
  8. * `ImageMetadata`, `ReadableStream`), so on term overlap it out-scored the
  9. * implementation and took the envelope. Measured on this fixture before the fix:
  10. * rank #1 and 51% of delivered source on a prose flow query.
  11. *
  12. * CG-25 already covers the file that STARTED this — a Wrangler
  13. * `worker-configuration.d.ts`, which announces itself with a generated banner.
  14. * `docs/benchmarks/explore-declaration-only-cg28.md` has that measurement; the
  15. * banner alone is worth 15–46 points of envelope share. What it does not cover
  16. * is a declaration file with no banner at all, which is what this fixture's
  17. * `platform-shims.d.ts` is, and what the damping in `rankPenalty` addresses.
  18. *
  19. * Two claims, and BOTH have to hold — the counter-case is why the penalty is
  20. * guarded rather than flat:
  21. *
  22. * 1. a prose flow query must not let a declaration-only file outrank the
  23. * implementation files that answer it;
  24. * 2. a query genuinely ABOUT a declared type must still reach the declaration
  25. * at full weight.
  26. *
  27. * The suppression the issue explicitly forbids is also pinned: a damped file is
  28. * still a candidate and still named in the response, so one follow-up explore
  29. * fetches it.
  30. */
  31. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  32. import * as fs from 'fs';
  33. import * as path from 'path';
  34. import * as os from 'os';
  35. import CodeGraph from '../src/index';
  36. import { ToolHandler } from '../src/mcp/tools';
  37. import type { ExploreDiagnosticReport, ExploreDiagnosticFile } from '../src/mcp/explore-diagnostics';
  38. const FIXTURE_SRC = path.join(__dirname, 'fixtures', 'ambient-decls-ts');
  39. /** Declaration-only, hand-written, NO generated banner — the surviving gap. */
  40. const HANDWRITTEN_DECL = 'types/platform-shims.d.ts';
  41. /** Declaration-only WITH a Wrangler banner — the CG-25 control in the same run. */
  42. const GENERATED_DECL = 'types/worker-configuration.d.ts';
  43. /** Declaration-only but IMPORTED by the storage layer — must never be damped. */
  44. const SHARED_TYPES = 'src/storage/types.ts';
  45. /** Prose, naming no symbol — the query shape that let the original file in. */
  46. const FLOW_QUERY =
  47. 'how does an upload request stream the file body to storage and record image metadata';
  48. /** Prose that DOES name a declared type — the counter-case. */
  49. const TYPE_QUERY = 'what does the UploadStorage interface declare for putting an object';
  50. describe('CG-28 — a declaration-only file does not outrank implementation on a flow query', () => {
  51. let testDir: string;
  52. let cg: CodeGraph;
  53. let sidecar: string;
  54. /** One explore call; returns its diagnostic report plus the response text. */
  55. const explore = async (query: string): Promise<{ report: ExploreDiagnosticReport; text: string }> => {
  56. fs.rmSync(sidecar, { force: true });
  57. const previous = process.env.CODEGRAPH_EXPLORE_DEBUG;
  58. process.env.CODEGRAPH_EXPLORE_DEBUG = sidecar;
  59. let text: string;
  60. try {
  61. text = (await new ToolHandler(cg).execute('codegraph_explore', { query })).content?.[0]?.text ?? '';
  62. } finally {
  63. if (previous === undefined) delete process.env.CODEGRAPH_EXPLORE_DEBUG;
  64. else process.env.CODEGRAPH_EXPLORE_DEBUG = previous;
  65. }
  66. const written = fs.readFileSync(sidecar, 'utf-8').trim().split('\n').filter(Boolean);
  67. return { report: JSON.parse(written[written.length - 1]!) as ExploreDiagnosticReport, text };
  68. };
  69. const fileOf = (report: ExploreDiagnosticReport, p: string): ExploreDiagnosticFile | undefined =>
  70. report.files.find((f) => f.path === p);
  71. let flow: { report: ExploreDiagnosticReport; text: string };
  72. let typed: { report: ExploreDiagnosticReport; text: string };
  73. beforeAll(async () => {
  74. testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cg28-'));
  75. fs.cpSync(FIXTURE_SRC, testDir, { recursive: true });
  76. fs.rmSync(path.join(testDir, '.codegraph'), { recursive: true, force: true });
  77. sidecar = path.join(testDir, 'explore-diag.jsonl');
  78. cg = CodeGraph.initSync(testDir);
  79. await cg.indexAll();
  80. flow = await explore(FLOW_QUERY);
  81. typed = await explore(TYPE_QUERY);
  82. }, 120_000);
  83. afterAll(() => {
  84. if (cg) cg.destroy();
  85. if (testDir && fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
  86. });
  87. /**
  88. * Type-level for the purposes of this gate: a type declaration, or a member
  89. * an interface declares.
  90. *
  91. * The second half is not a loosening. Since #1638 a `method_signature` /
  92. * `property_signature` is indexed as a `method` / `property` node, so a file
  93. * of nothing but interfaces no longer reads as nothing but `interface` kinds
  94. * — but a bodiless signature is on the same side of the line as the interface
  95. * that owns it, which is exactly how `getAmbientDeclarationPathsAmong` counts
  96. * it. What this still catches, and is here to catch, is a `function` or a
  97. * `class` creeping into the fixture: that would silently exempt the file and
  98. * make every assertion below vacuous.
  99. */
  100. const isTypeLevel = (n: { id: string; kind: string }, filePath: string): boolean => {
  101. if (n.kind === 'interface' || n.kind === 'type_alias') return true;
  102. if (n.kind !== 'method' && n.kind !== 'property') return false;
  103. const interfaceIds = new Set(
  104. cg.getNodesInFile(filePath).filter((x) => x.kind === 'interface').map((x) => x.id),
  105. );
  106. return cg.getIncomingEdges(n.id)
  107. .some((e) => e.kind === 'contains' && interfaceIds.has(e.source));
  108. };
  109. describe('fixture shape — if this rots, the gate below means nothing', () => {
  110. it('holds two declaration-only files that differ only in the banner', () => {
  111. for (const p of [HANDWRITTEN_DECL, GENERATED_DECL]) {
  112. const nodes = cg.getNodesInFile(p).filter((n) => n.kind !== 'file' && n.kind !== 'import');
  113. expect(nodes.length, `${p} declares nothing`).toBeGreaterThan(10);
  114. // Nothing with a body — the structural test the penalty keys on.
  115. expect(nodes.every((n) => isTypeLevel(n, p)), `${p} has a non-type symbol`).toBe(true);
  116. }
  117. // Only one of them announces itself, so the CG-25 penalty is the ONLY
  118. // difference between the two — that is what makes them comparable.
  119. expect(cg.getFile(GENERATED_DECL)?.generated).toBe(true);
  120. expect(cg.getFile(HANDWRITTEN_DECL)?.generated).toBeFalsy();
  121. });
  122. it('holds a pure-type module the code IMPORTS, as the safety control', () => {
  123. // Identical to the ambient files on kinds and bodies; different only in
  124. // that the storage layer is typed by it. This is the shape the penalty
  125. // must NOT catch — a `types.ts` the codebase depends on is part of the
  126. // structure of any answer about that code.
  127. const nodes = cg.getNodesInFile(SHARED_TYPES).filter((n) => n.kind !== 'file' && n.kind !== 'import');
  128. expect(nodes.length).toBeGreaterThan(0);
  129. expect(nodes.every((n) => isTypeLevel(n, SHARED_TYPES))).toBe(true);
  130. expect(cg.getFile(SHARED_TYPES)?.generated).toBeFalsy();
  131. });
  132. it('holds implementation files that DO answer the flow question', () => {
  133. for (const p of ['src/routes/upload.ts', 'src/storage/stream.ts', 'src/storage/metadata.ts']) {
  134. expect(cg.getNodesInFile(p).some((n) => n.kind === 'function'), `${p} has no functions`).toBe(true);
  135. }
  136. });
  137. });
  138. describe('the gate — a prose flow query', () => {
  139. it('damps the un-bannered declaration file rather than letting it rank free', () => {
  140. const rec = fileOf(flow.report, HANDWRITTEN_DECL);
  141. expect(rec, 'the declaration file is not even a candidate — fixture drifted').toBeDefined();
  142. expect(rec!.ambientDeclaration).toBe(true);
  143. expect(rec!.penalty).toBeLessThan(1);
  144. });
  145. it('does not let it outrank the implementation files', () => {
  146. const decl = fileOf(flow.report, HANDWRITTEN_DECL)!;
  147. const impl = flow.report.files.filter((f) => f.path.startsWith('src/') && f.finalChars > 0);
  148. expect(impl.length, 'no implementation file delivered anything').toBeGreaterThanOrEqual(2);
  149. // Measured before the fix: the declaration file was rank #1 with score 53
  150. // against the best implementation file's 34. The bar is that at least one
  151. // implementation file now ranks above it — ordinary budget movement must
  152. // not fail the suite, but the inversion coming back must.
  153. expect(impl.some((f) => f.rank < decl.rank), 'declaration file still ranks first').toBe(true);
  154. });
  155. it('still names it in the response, so one follow-up call fetches it', () => {
  156. // The issue forbids suppression: a damped file must remain reachable.
  157. expect(flow.text).toContain(HANDWRITTEN_DECL);
  158. });
  159. it('leaves the implementation files at full weight', () => {
  160. for (const f of flow.report.files.filter((x) => x.path.startsWith('src/'))) {
  161. expect(f.ambientDeclaration, `${f.path} was misread as an ambient declaration`).toBe(false);
  162. expect(f.penalty).toBe(1);
  163. }
  164. });
  165. it('does not damp a pure-type module the codebase imports', () => {
  166. // The condition that keeps this narrow enough to be safe. Without it the
  167. // same rule demotes `displacement-ts`'s pipeline `types.ts` — pure
  168. // interfaces, but 13 inbound imports — and breaks the CG-31 gate.
  169. const rec = flow.report.files.find((f) => f.path === SHARED_TYPES);
  170. if (rec) {
  171. expect(rec.ambientDeclaration, `${SHARED_TYPES} was flagged ambient`).toBe(false);
  172. expect(rec.penalty).toBe(1);
  173. }
  174. // Independent of whether this query ranked it: the predicate itself must
  175. // separate the two shapes.
  176. const isAmbient = cg.ambientDeclarationFilePredicate([SHARED_TYPES, HANDWRITTEN_DECL]);
  177. expect(isAmbient(SHARED_TYPES)).toBe(false);
  178. expect(isAmbient(HANDWRITTEN_DECL)).toBe(true);
  179. });
  180. it('still flags a shim whose interfaces now contribute method/property nodes', () => {
  181. // The silent-failure guard for #1638. Interface members are indexed, so a
  182. // pure-interface `.d.ts` no longer holds only `interface` kinds — and the
  183. // ambient rule is spelled as "EVERY declared symbol is type-level". Read
  184. // literally that stops flagging the moment the extractor improves, and
  185. // nothing else fails: the file just quietly ranks undamped again.
  186. //
  187. // Pinned from both ends on purpose. The `toBeGreaterThan(0)` half is what
  188. // keeps the other half honest — assert only the flag and this test would
  189. // still pass on an index where the members were never extracted at all,
  190. // which is precisely the state it exists to detect a regression FROM.
  191. const members = cg.getNodesInFile(HANDWRITTEN_DECL)
  192. .filter((n) => n.kind === 'method' || n.kind === 'property');
  193. expect(members.length, 'interface members are not indexed — see #1638').toBeGreaterThan(0);
  194. expect(cg.ambientDeclarationFilePredicate([HANDWRITTEN_DECL])(HANDWRITTEN_DECL)).toBe(true);
  195. });
  196. });
  197. describe('the counter-case — a query that NAMES a declared type', () => {
  198. it('reaches the declaration at full weight, undamped', () => {
  199. const rec = fileOf(typed.report, HANDWRITTEN_DECL);
  200. expect(rec, 'the named type\'s file is not a candidate').toBeDefined();
  201. expect(rec!.ambientDeclaration).toBe(true);
  202. // Detected as declaration-only, but EXEMPT — the query asked for it.
  203. expect(rec!.penalty).toBe(1);
  204. });
  205. it('ranks it first and delivers its source', () => {
  206. const rec = fileOf(typed.report, HANDWRITTEN_DECL)!;
  207. expect(rec.rank).toBe(1);
  208. expect(rec.finalChars).toBeGreaterThan(0);
  209. });
  210. });
  211. describe('the two penalties do not stack', () => {
  212. it('charges a generated declaration file once, at the stronger rate', () => {
  213. // A file that is BOTH generated and declaration-only has ONE property two
  214. // signals happen to see. Penalising twice (0.3 * 0.5 = 0.15) is how a file
  215. // gets cliffed out of answers where it is genuinely relevant.
  216. const rec = flow.report.files.find((f) => f.generated && f.ambientDeclaration);
  217. if (!rec) return; // not a candidate for this query — nothing to assert
  218. expect(rec.penalty).toBeGreaterThanOrEqual(0.3);
  219. });
  220. });
  221. });