explore-cross-call-dedup.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /**
  2. * Cross-call source dedup (CG-18).
  3. *
  4. * A later `codegraph_explore` call in a session must not re-send source an
  5. * earlier call already delivered — but every byte it withholds has to be
  6. * replaced by a POINTER, never a silence. That asymmetry is what this suite
  7. * guards, because the two failure directions cost wildly different amounts: a
  8. * duplicate range wastes a few thousand chars, while a response that reads as
  9. * "codegraph doesn't have it" costs a Read — and one or two of those early in a
  10. * session teach an agent to stop calling the tool at all.
  11. *
  12. * Three layers:
  13. * 1. the range algebra — what is withheld, and the thresholds that stop it
  14. * from shredding a block into slivers;
  15. * 2. the fingerprint gate — an edit between two calls must re-emit, since a
  16. * pointer to pre-edit source is worse than no dedup at all;
  17. * 3. the handler seam — a real second call against a real index: no duplicate
  18. * ranges, a pointer for everything withheld, the reclaimed budget spent on
  19. * source the agent has NOT seen, and never an all-pointer response.
  20. */
  21. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  22. import * as fs from 'fs';
  23. import * as path from 'path';
  24. import * as os from 'os';
  25. import CodeGraph from '../src/index';
  26. import { ToolHandler } from '../src/mcp/tools';
  27. import { ExploreSessionState, type ExploreProjectState } from '../src/mcp/explore-session-state';
  28. import {
  29. EXPLORE_DEDUP,
  30. dedupeRange,
  31. fileFingerprint,
  32. formatBackReference,
  33. intersectRange,
  34. mergeRanges,
  35. servedRangesForFile,
  36. subtractRange,
  37. symbolsInSpans,
  38. } from '../src/mcp/explore-dedup';
  39. const FIXTURE_SRC = path.join(__dirname, 'fixtures', 'payroll-go');
  40. const QUERY = 'how does payroll cycle create and calculate payslips?';
  41. const POINTER = 'Already sent earlier in this conversation';
  42. /** A prior-state shaped like the session tracker's, for the algebra tests. */
  43. function prior(files: Array<{ path: string; ranges: Array<[number, number]>; fingerprint?: string }>): ExploreProjectState {
  44. return {
  45. projectRoot: '/repo',
  46. callCount: 1,
  47. responseBytes: 1000,
  48. calls: [{
  49. index: 1,
  50. projectRoot: '/repo',
  51. query: 'q',
  52. sourceBytes: 500,
  53. responseBytes: 1000,
  54. files: files.map((f) => ({
  55. path: f.path,
  56. ranges: f.ranges.map(([start, end]) => ({ start, end })),
  57. bytes: 500,
  58. fingerprint: f.fingerprint,
  59. })),
  60. }],
  61. };
  62. }
  63. describe('range algebra', () => {
  64. it('subtracts a held span out of the middle of an intended one', () => {
  65. expect(subtractRange({ start: 1, end: 100 }, [{ start: 20, end: 40 }]))
  66. .toEqual([{ start: 1, end: 19 }, { start: 41, end: 100 }]);
  67. });
  68. it('subtracts held spans at either edge, and a full cover to nothing', () => {
  69. expect(subtractRange({ start: 10, end: 50 }, [{ start: 1, end: 20 }]))
  70. .toEqual([{ start: 21, end: 50 }]);
  71. expect(subtractRange({ start: 10, end: 50 }, [{ start: 30, end: 90 }]))
  72. .toEqual([{ start: 10, end: 29 }]);
  73. expect(subtractRange({ start: 10, end: 50 }, [{ start: 1, end: 90 }])).toEqual([]);
  74. });
  75. it('intersects to exactly what both sides hold', () => {
  76. expect(intersectRange({ start: 10, end: 50 }, [{ start: 1, end: 20 }, { start: 45, end: 80 }]))
  77. .toEqual([{ start: 10, end: 20 }, { start: 45, end: 50 }]);
  78. expect(intersectRange({ start: 10, end: 50 }, [{ start: 60, end: 80 }])).toEqual([]);
  79. });
  80. it('merges touching spans — two adjacent blocks are one block of source', () => {
  81. expect(mergeRanges([{ start: 5, end: 9 }, { start: 10, end: 12 }, { start: 40, end: 41 }]))
  82. .toEqual([{ start: 5, end: 12 }, { start: 40, end: 41 }]);
  83. });
  84. it('emits ONLY the delta when a later call wants a wider window', () => {
  85. // Call 1 sent the method; call 2 wants the class around it.
  86. const { emit, covered } = dedupeRange({ start: 80, end: 200 }, [{ start: 100, end: 140 }]);
  87. expect(covered).toEqual([{ start: 100, end: 140 }]);
  88. expect(emit).toEqual([{ start: 80, end: 99 }, { start: 141, end: 200 }]);
  89. });
  90. it('withholds nothing when the overlap is smaller than a chunk worth pointing at', () => {
  91. // Context padding and signature lines land here. Replacing them costs more
  92. // in pointer text than the source is worth, and shreds the block.
  93. const overlap = EXPLORE_DEDUP.MIN_COVERED_LINES - 1;
  94. const { emit, covered } = dedupeRange({ start: 1, end: 100 }, [{ start: 10, end: 10 + overlap - 1 }]);
  95. expect(covered).toEqual([]);
  96. expect(emit).toEqual([{ start: 1, end: 100 }]);
  97. });
  98. it('leaves an untouched span exactly as it was', () => {
  99. expect(dedupeRange({ start: 1, end: 50 }, [{ start: 200, end: 400 }]))
  100. .toEqual({ emit: [{ start: 1, end: 50 }], covered: [] });
  101. expect(dedupeRange({ start: 1, end: 50 }, []))
  102. .toEqual({ emit: [{ start: 1, end: 50 }], covered: [] });
  103. });
  104. });
  105. describe('the fingerprint gate', () => {
  106. const FP = fileFingerprint('package main\nfunc main() {}\n');
  107. it('returns the spans a call served for a file whose bytes are unchanged', () => {
  108. const state = prior([{ path: 'a.go', ranges: [[1, 40], [60, 80]], fingerprint: FP }]);
  109. expect(servedRangesForFile(state, 'a.go', FP)).toEqual([{ start: 1, end: 40 }, { start: 60, end: 80 }]);
  110. });
  111. it('returns NOTHING once the file has been edited — a pointer would be wrong', () => {
  112. const state = prior([{ path: 'a.go', ranges: [[1, 40]], fingerprint: FP }]);
  113. const edited = fileFingerprint('package main\nfunc main() { changed() }\n');
  114. expect(servedRangesForFile(state, 'a.go', edited)).toEqual([]);
  115. });
  116. it('ignores a record that cannot prove what it served', () => {
  117. const state = prior([{ path: 'a.go', ranges: [[1, 40]] }]);
  118. expect(servedRangesForFile(state, 'a.go', FP)).toEqual([]);
  119. });
  120. it('never crosses files, and is empty for an untracked session', () => {
  121. const state = prior([{ path: 'a.go', ranges: [[1, 40]], fingerprint: FP }]);
  122. expect(servedRangesForFile(state, 'b.go', FP)).toEqual([]);
  123. expect(servedRangesForFile(null, 'a.go', FP)).toEqual([]);
  124. });
  125. it('distinguishes two files that hash the same prefix but differ in length', () => {
  126. expect(fileFingerprint('abc')).not.toBe(fileFingerprint('abcd'));
  127. expect(fileFingerprint('abc')).toBe(fileFingerprint('abc'));
  128. });
  129. });
  130. describe('the back-reference itself', () => {
  131. const covered = [{ start: 100, end: 240 }];
  132. it('names the file, the span and the symbols, and says the copy is still good', () => {
  133. const text = formatBackReference('internal/x.go', covered, ['RunCycle', 'BuildPayslip'], { partial: false });
  134. expect(text).toContain('internal/x.go');
  135. expect(text).toContain('L100-240');
  136. expect(text).toContain('RunCycle, BuildPayslip');
  137. expect(text).toContain(POINTER);
  138. expect(text).toContain('unchanged on disk');
  139. });
  140. it('never tells the agent to Read, in either shape', () => {
  141. for (const partial of [true, false]) {
  142. const text = formatBackReference('x.go', covered, ['A'], { partial });
  143. expect(text).toMatch(/do NOT Read/i);
  144. expect(text).not.toMatch(/\bRead (this|the) file (for|to)\b/i);
  145. expect(text).not.toMatch(/omitted|unavailable|could not/i);
  146. }
  147. });
  148. it('says the block below is only the NEW lines when the call still sends some', () => {
  149. expect(formatBackReference('x.go', covered, [], { partial: true })).toContain('NEW lines');
  150. expect(formatBackReference('x.go', covered, [], { partial: false })).toContain('not repeated here');
  151. });
  152. it('names only symbols that actually fall in the withheld spans', () => {
  153. const nodes = [
  154. { name: 'InSpan', kind: 'function', startLine: 110, endLine: 130 },
  155. { name: 'Outside', kind: 'function', startLine: 300, endLine: 320 },
  156. { name: 'AnImport', kind: 'import', startLine: 105, endLine: 105 },
  157. ];
  158. expect(symbolsInSpans(nodes, covered)).toEqual(['InSpan']);
  159. });
  160. });
  161. describe('a second call against a real index', () => {
  162. let testDir: string;
  163. let cg: CodeGraph;
  164. let handler: ToolHandler;
  165. beforeAll(async () => {
  166. testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cg18-'));
  167. fs.cpSync(FIXTURE_SRC, testDir, { recursive: true });
  168. fs.rmSync(path.join(testDir, '.codegraph'), { recursive: true, force: true });
  169. cg = CodeGraph.initSync(testDir);
  170. await cg.indexAll();
  171. handler = new ToolHandler(cg);
  172. }, 120_000);
  173. afterAll(() => {
  174. if (cg) cg.destroy();
  175. if (testDir && fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
  176. });
  177. const explore = (query: string, session?: ExploreSessionState, args: Record<string, unknown> = {}) =>
  178. handler.execute('codegraph_explore', { query, ...args }, session).then((r) => r.content[0]!.text);
  179. /**
  180. * The line numbers actually inside each file's fenced source. Read off the
  181. * RESPONSE, not the bookkeeping — "no duplicate ranges" is a claim about what
  182. * the agent received, and checking it against the record we also wrote would
  183. * prove only that the two agree.
  184. */
  185. function fencedLines(text: string): Map<string, Set<number>> {
  186. const out = new Map<string, Set<number>>();
  187. let current: string | null = null;
  188. let inFence = false;
  189. for (const line of text.split('\n')) {
  190. const header = /^\*\*`([^`]+)`\*\*/.exec(line);
  191. if (header && !inFence) { current = header[1]!; continue; }
  192. if (!inFence && current && line.startsWith('```')) { inFence = true; continue; }
  193. if (inFence && line === '```') { inFence = false; continue; }
  194. if (!inFence || !current) continue;
  195. const numbered = /^(\d+)\t/.exec(line);
  196. if (!numbered) continue;
  197. if (!out.has(current)) out.set(current, new Set());
  198. out.get(current)!.add(Number(numbered[1]));
  199. }
  200. return out;
  201. }
  202. it('never re-sends a line it already sent, and points at every line it withholds', async () => {
  203. const session = new ExploreSessionState();
  204. const first = await explore(QUERY, session);
  205. const second = await explore(QUERY, session);
  206. const before = fencedLines(first);
  207. const after = fencedLines(second);
  208. expect(after.size).toBeGreaterThan(0);
  209. // Every file whose source the second call withheld carries a pointer, and
  210. // the pointer names it.
  211. expect(second).toContain(POINTER);
  212. for (const [file, lines] of before) {
  213. const repeated = [...(after.get(file) ?? [])].filter((n) => lines.has(n));
  214. if (repeated.length === 0) continue;
  215. // The only sanctioned repeat is the anti-abandonment restore, which fires
  216. // ONLY when the call found nothing new to say — and this one did.
  217. throw new Error(`call 2 re-sent ${file} lines ${repeated.slice(0, 5).join(',')}`);
  218. }
  219. }, 120_000);
  220. it('spends the reclaimed bytes on source the agent has not seen', async () => {
  221. const session = new ExploreSessionState();
  222. const first = await explore(QUERY, session);
  223. const second = await explore(QUERY, session);
  224. const before = fencedLines(first);
  225. const after = fencedLines(second);
  226. const fresh = [...after.entries()].reduce(
  227. (sum, [file, lines]) => sum + [...lines].filter((n) => !(before.get(file)?.has(n))).length, 0);
  228. // Not merely "smaller": a shrunken response is what dedup must NOT produce.
  229. // The freed budget has to come back as lines the first call never sent.
  230. expect(fresh).toBeGreaterThan(20);
  231. expect(second.length).toBeLessThan(first.length);
  232. }, 120_000);
  233. it('re-emits in full when the file changed between the two calls', async () => {
  234. const session = new ExploreSessionState();
  235. const target = path.join(testDir, 'internal/usecase/payroll/payslip_builder.go');
  236. const original = fs.readFileSync(target, 'utf-8');
  237. try {
  238. const first = await explore(QUERY, session);
  239. expect(fencedLines(first).has('internal/usecase/payroll/payslip_builder.go')).toBe(true);
  240. fs.writeFileSync(target, original.replace('func sumKind(', 'func sumKindRenamed('), 'utf-8');
  241. const second = await explore(QUERY, session);
  242. // The edited file is served again, whole — a pointer here would send the
  243. // agent to a copy of the file that no longer exists.
  244. const pointerLines = second.split('\n').filter((l) => l.includes(POINTER));
  245. expect(pointerLines.some((l) => l.includes('payslip_builder.go'))).toBe(false);
  246. expect(fencedLines(second).get('internal/usecase/payroll/payslip_builder.go')?.size ?? 0)
  247. .toBeGreaterThan(20);
  248. } finally {
  249. fs.writeFileSync(target, original, 'utf-8');
  250. }
  251. }, 120_000);
  252. it('always returns real source, even when the session already holds everything', async () => {
  253. const session = new ExploreSessionState();
  254. await explore(QUERY, session);
  255. await explore(QUERY, session);
  256. const third = await explore(QUERY, session);
  257. const fourth = await explore(QUERY, session);
  258. // An all-pointer response is the shape that reads as failure. Every call
  259. // keeps at least one real fenced block, however much the session holds.
  260. for (const [n, text] of [[3, third], [4, fourth]] as const) {
  261. const lines = [...fencedLines(text).values()].reduce((s, set) => s + set.size, 0);
  262. expect(lines, `call ${n} returned no source at all`).toBeGreaterThan(10);
  263. }
  264. }, 180_000);
  265. it('leaves the first call of a session untouched', async () => {
  266. const tracked = await explore(QUERY, new ExploreSessionState());
  267. const untracked = await explore(QUERY);
  268. expect(tracked).toBe(untracked);
  269. }, 120_000);
  270. it('keeps two sessions on one handler independent', async () => {
  271. const a = new ExploreSessionState();
  272. const b = new ExploreSessionState();
  273. const firstForA = await explore(QUERY, a);
  274. await explore(QUERY, a);
  275. // B's first call has seen nothing, whatever A has been served.
  276. expect(await explore(QUERY, b)).toBe(firstForA);
  277. }, 180_000);
  278. it('is off entirely under CODEGRAPH_EXPLORE_DEDUP=0', async () => {
  279. const session = new ExploreSessionState();
  280. const previous = process.env.CODEGRAPH_EXPLORE_DEDUP;
  281. process.env.CODEGRAPH_EXPLORE_DEDUP = '0';
  282. try {
  283. const first = await explore(QUERY, session);
  284. const second = await explore(QUERY, session);
  285. expect(second).toBe(first);
  286. expect(second).not.toContain(POINTER);
  287. } finally {
  288. if (previous === undefined) delete process.env.CODEGRAPH_EXPLORE_DEDUP;
  289. else process.env.CODEGRAPH_EXPLORE_DEDUP = previous;
  290. }
  291. }, 120_000);
  292. it('reports the reclaimed bytes through the CG-4 diagnostic', async () => {
  293. const sidecar = path.join(testDir, 'cg18-diagnostic.jsonl');
  294. const session = new ExploreSessionState();
  295. const previous = process.env.CODEGRAPH_EXPLORE_DEBUG;
  296. process.env.CODEGRAPH_EXPLORE_DEBUG = sidecar;
  297. try {
  298. await explore(QUERY, session);
  299. await explore(QUERY, session);
  300. } finally {
  301. if (previous === undefined) delete process.env.CODEGRAPH_EXPLORE_DEBUG;
  302. else process.env.CODEGRAPH_EXPLORE_DEBUG = previous;
  303. }
  304. const [one, two] = fs.readFileSync(sidecar, 'utf-8').trim().split('\n').map((l) => JSON.parse(l));
  305. expect(one.dedup.savedChars).toBe(0);
  306. expect(two.dedup.savedChars).toBeGreaterThan(1000);
  307. expect(two.dedup.backReferenced.length).toBeGreaterThan(0);
  308. // The reclamation is legible file by file: a back-referenced file spent
  309. // none of its reservation, and the response still filled its envelope.
  310. const backref = two.files.filter((f: { render: string }) => f.render === 'backref');
  311. for (const f of backref) {
  312. expect(f.emittedChars).toBe(0);
  313. expect(f.dedupSavedChars).toBeGreaterThan(0);
  314. expect(f.dedupCovered.length).toBeGreaterThan(0);
  315. }
  316. const spentOnFreshSource = two.files.reduce((s: number, f: { emittedChars: number }) => s + f.emittedChars, 0);
  317. expect(spentOnFreshSource).toBeGreaterThan(0);
  318. }, 120_000);
  319. });