context-ranking.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. /**
  2. * Context ranking: common-word precision + low-confidence handoff.
  3. *
  4. * Regression coverage for the failure where a prose query
  5. * ("capture intro onboarding screen flat object") surfaced an unrelated
  6. * constant named `FLAT` (in a download script) as a top entry point — because
  7. * the descriptive word "flat" exact-matched it and the +exact-name bonus was
  8. * exempt from single-term dampening. The fix: only distinctive identifiers earn
  9. * that exemption; an isolated common-word exact match is demoted, and a query
  10. * that resolves only to such weak matches is flagged low-confidence so the
  11. * response hands off to explore/trace instead of bluffing.
  12. */
  13. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  14. import * as fs from 'fs';
  15. import * as path from 'path';
  16. import * as os from 'os';
  17. import CodeGraph from '../src/index';
  18. import { LOW_CONFIDENCE_MARKER } from '../src/context';
  19. import { isDistinctiveIdentifier, scorePathRelevance } from '../src/search/query-utils';
  20. describe('isDistinctiveIdentifier', () => {
  21. it('treats plain dictionary words as non-distinctive', () => {
  22. for (const word of ['flat', 'object', 'screen', 'standing', 'capture']) {
  23. expect(isDistinctiveIdentifier(word)).toBe(false);
  24. }
  25. });
  26. it('treats leading-capital-only words (proper nouns / sentence start) as non-distinctive', () => {
  27. expect(isDistinctiveIdentifier('Screen')).toBe(false);
  28. expect(isDistinctiveIdentifier('Zustand')).toBe(false);
  29. });
  30. it('treats camelCase / PascalCase / snake_case / acronyms / digits as distinctive', () => {
  31. expect(isDistinctiveIdentifier('setLastEmail')).toBe(true);
  32. expect(isDistinctiveIdentifier('OrgUserStore')).toBe(true);
  33. expect(isDistinctiveIdentifier('user_store')).toBe(true);
  34. expect(isDistinctiveIdentifier('REST')).toBe(true);
  35. expect(isDistinctiveIdentifier('v2')).toBe(true);
  36. });
  37. });
  38. // A single PascalCase query word (notably a project name a user naturally
  39. // includes) splits into sub-tokens that all match the SAME path segment; summed
  40. // per sub-token it boosted that path 4×, burying the rest of the query's stack
  41. // (#720). Path relevance must count each original WORD once per level, while
  42. // still splitting it for cross-convention matching.
  43. describe('scorePathRelevance per-word scoring (#720)', () => {
  44. it('counts a single PascalCase word once per path level, not once per sub-token', () => {
  45. // "SuperBizAgent" → super/biz/agent/superbizagent all hit the dir, but it's
  46. // one concept: +5 (dir) once, not +20.
  47. expect(scorePathRelevance('SuperBizAgentFrontend/app.js', 'SuperBizAgent')).toBe(5);
  48. });
  49. it('still splits a word so it matches across naming conventions', () => {
  50. // getUserName must still match a snake_case path via its sub-tokens.
  51. expect(scorePathRelevance('get_user_name.go', 'getUserName')).toBeGreaterThanOrEqual(10);
  52. });
  53. it('still credits distinct query words matching different path segments', () => {
  54. // auth (dir) and handler (filename) are separate concepts — each counts.
  55. expect(scorePathRelevance('src/auth/login_handler.go', 'auth handler')).toBeGreaterThan(
  56. scorePathRelevance('src/auth/login_handler.go', 'auth')
  57. );
  58. });
  59. });
  60. describe('Context ranking — common-word precision & confidence', () => {
  61. let testDir: string;
  62. let cg: CodeGraph;
  63. beforeEach(async () => {
  64. testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-ctxrank-'));
  65. // The corroborated target: a capture-flow screen whose NAME alone matches
  66. // three query terms (capture + intro + screen), and which lives under a
  67. // matching directory.
  68. const captureDir = path.join(testDir, 'src', 'app', 'capture');
  69. fs.mkdirSync(captureDir, { recursive: true });
  70. fs.writeFileSync(
  71. path.join(captureDir, 'intro.tsx'),
  72. `export function CaptureIntroScreen() {
  73. // Onboarding screen shown before the user selects flat or standing object capture.
  74. return null;
  75. }
  76. `
  77. );
  78. // The trap: an unrelated constant literally named FLAT, in a totally
  79. // different area. "flat" in a prose query exact-matches it.
  80. const scriptsDir = path.join(testDir, 'scripts', 'dataset');
  81. fs.mkdirSync(scriptsDir, { recursive: true });
  82. fs.writeFileSync(
  83. path.join(scriptsDir, 'download.ts'),
  84. `export const FLAT = 'freiburg_flat_dataset';
  85. export function downloadDataset(name: string): string { return name; }
  86. `
  87. );
  88. cg = CodeGraph.initSync(testDir, {
  89. config: { include: ['**/*.ts', '**/*.tsx'], exclude: [] },
  90. });
  91. await cg.indexAll();
  92. });
  93. afterEach(() => {
  94. if (cg) cg.destroy();
  95. if (fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
  96. });
  97. it('does not let a common-word exact match (FLAT) outrank a corroborated symbol', async () => {
  98. const sg = await cg.findRelevantContext(
  99. 'capture intro onboarding screen flat object'
  100. );
  101. const rootNames = sg.roots.map((id) => sg.nodes.get(id)?.name);
  102. // The corroborated capture screen surfaces as an entry point...
  103. expect(rootNames).toContain('CaptureIntroScreen');
  104. // ...and the trap constant is never the lead result (the bug we fixed).
  105. expect(rootNames[0]).not.toBe('FLAT');
  106. const capIdx = rootNames.indexOf('CaptureIntroScreen');
  107. const flatIdx = rootNames.indexOf('FLAT');
  108. if (flatIdx >= 0) expect(capIdx).toBeLessThan(flatIdx);
  109. // And it's confidently answered (we located a corroborated symbol).
  110. expect(sg.confidence).toBe('high');
  111. });
  112. it('flags low confidence and emits the handoff when only common words match', async () => {
  113. const query = 'flat object thing';
  114. const sg = await cg.findRelevantContext(query);
  115. expect(sg.confidence).toBe('low');
  116. const md = await cg.buildContext(query, { format: 'markdown' });
  117. expect(typeof md).toBe('string');
  118. expect(md as string).toContain(LOW_CONFIDENCE_MARKER);
  119. // The handoff routes to the precise tools rather than claiming completeness.
  120. expect(md as string).toMatch(/codegraph_explore/);
  121. });
  122. it('does not emit the handoff for a precise, distinctive-symbol query', async () => {
  123. const sg = await cg.findRelevantContext('CaptureIntroScreen');
  124. expect(sg.confidence).toBe('high');
  125. const md = await cg.buildContext('CaptureIntroScreen', { format: 'markdown' });
  126. expect(md as string).not.toContain(LOW_CONFIDENCE_MARKER);
  127. });
  128. });