mcp-stale-slice.test.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /**
  2. * Disk-drift guard on code-slice renders (issue #1474).
  3. *
  4. * codegraph_node / codegraph_explore read CURRENT bytes from disk but slice
  5. * them at INDEXED line ranges. When a file changed after its last index sync,
  6. * that slice is a DIFFERENT symbol's code served under the requested name —
  7. * `isError: false`, introduced by the "verbatim … do not Read" guarantee. The
  8. * watcher-based pending banner (#403) cannot cover a project reached via
  9. * `projectPath` (cross-project instances have no watcher, by construction).
  10. *
  11. * The fix verifies freshness at the point of emission from data the index
  12. * already stores (files.size / modified_at, content_hash on stat mismatch):
  13. * a drifted file is never rendered as a slice — small files ship whole and
  14. * current (Read-parity), large ones are omitted with an explicit notice.
  15. *
  16. * These tests exercise the full real path: real index + real
  17. * ToolHandler.execute(), including the cross-project `projectPath` form the
  18. * issue was filed against.
  19. */
  20. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  21. import * as fs from 'fs';
  22. import * as path from 'path';
  23. import * as os from 'os';
  24. import CodeGraph from '../src/index';
  25. import { ToolHandler, __setLoadCodeGraphForTests } from '../src/mcp/tools';
  26. /** ~1,100-line file: handler0…handler79 plus `orchestrate` at the bottom —
  27. * mirrors the issue's fixture. Big enough that explore takes the clustered
  28. * render and codegraph_node's whole-file stale fallback does NOT fit. */
  29. function bigFileContent(): string {
  30. const parts: string[] = [];
  31. for (let h = 0; h < 80; h++) {
  32. parts.push(`/** handler number ${h} */`);
  33. parts.push(`export function handler${h}(input: string): string {`);
  34. for (let s = 0; s < 8; s++) {
  35. parts.push(` const v${s} = input + "-step${s}-h${h}";`);
  36. }
  37. parts.push(` return v7;`);
  38. parts.push(`}`);
  39. parts.push('');
  40. }
  41. parts.push(`export function orchestrate(input: string): string {`);
  42. parts.push(` handler0(input);`);
  43. parts.push(` handler1(input);`);
  44. parts.push(` handler2(input);`);
  45. parts.push(` handler3(input);`);
  46. parts.push(` return input;`);
  47. parts.push(`}`);
  48. parts.push('');
  49. return parts.join('\n');
  50. }
  51. /** 45 lines of new helpers inserted at the top — shifts every symbol down. */
  52. function insertedPrelude(): string {
  53. const parts: string[] = [];
  54. for (let h = 0; h < 4; h++) {
  55. parts.push(`/** inserted helper ${h} */`);
  56. parts.push(`export function insertedHelper${h}(x: number): number {`);
  57. for (let s = 0; s < 7; s++) {
  58. parts.push(` x = x + ${s};`);
  59. }
  60. parts.push(` return x;`);
  61. parts.push(`}`);
  62. }
  63. parts.push('');
  64. return parts.join('\n') + '\n';
  65. }
  66. function getText(result: { content: Array<{ type: string; text?: string }>; isError?: boolean }): string {
  67. return result.content.map((c) => c.text ?? '').join('\n');
  68. }
  69. describe('MCP stale-slice guard (#1474)', () => {
  70. let fixtureDir: string; // the project that goes stale
  71. let otherDir: string; // a different indexed project — the server's default
  72. let cgFixture: CodeGraph;
  73. let cgOther: CodeGraph;
  74. let handler: ToolHandler;
  75. beforeEach(async () => {
  76. fixtureDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-stale-slice-fx-'));
  77. otherDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-stale-slice-other-'));
  78. fs.mkdirSync(path.join(fixtureDir, 'src'));
  79. fs.mkdirSync(path.join(otherDir, 'src'));
  80. fs.writeFileSync(path.join(fixtureDir, 'src', 'big.ts'), bigFileContent());
  81. fs.writeFileSync(
  82. path.join(fixtureDir, 'src', 'small.ts'),
  83. 'export function smallTarget(n: number): number {\n return n * 2;\n}\n',
  84. );
  85. fs.writeFileSync(
  86. path.join(otherDir, 'src', 'unrelated.ts'),
  87. 'export function unrelated() { return 0; }\n',
  88. );
  89. cgFixture = CodeGraph.initSync(fixtureDir, { config: { include: ['**/*.ts'], exclude: [] } });
  90. await cgFixture.indexAll();
  91. cgOther = CodeGraph.initSync(otherDir, { config: { include: ['**/*.ts'], exclude: [] } });
  92. await cgOther.indexAll();
  93. // The issue's exact topology: the server's default project is a DIFFERENT
  94. // project; the stale one is reached via `projectPath` and therefore has no
  95. // watcher — the #403/#876 banners cannot fire for it by construction.
  96. // (The seam services ToolHandler's lazy cross-project require, which
  97. // vitest's module transform can't resolve.)
  98. __setLoadCodeGraphForTests(CodeGraph);
  99. handler = new ToolHandler(cgOther);
  100. });
  101. afterEach(() => {
  102. __setLoadCodeGraphForTests(null);
  103. try { handler.closeAll(); } catch { /* ignore */ }
  104. try { cgFixture.close(); } catch { /* ignore */ }
  105. try { cgOther.close(); } catch { /* ignore */ }
  106. for (const dir of [fixtureDir, otherDir]) {
  107. if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
  108. }
  109. });
  110. function shiftBigFile(): void {
  111. const p = path.join(fixtureDir, 'src', 'big.ts');
  112. fs.writeFileSync(p, insertedPrelude() + fs.readFileSync(p, 'utf-8'));
  113. }
  114. it('codegraph_node never serves another symbol\'s body from a drifted file (cross-project)', async () => {
  115. shiftBigFile();
  116. const result = await handler.execute('codegraph_node', {
  117. symbol: 'orchestrate',
  118. includeCode: true,
  119. projectPath: fixtureDir,
  120. });
  121. const text = getText(result);
  122. expect(result.isError).toBeFalsy();
  123. // The pre-fix failure: the indexed range now lands in handler76/handler77.
  124. expect(text).not.toContain('-h76');
  125. expect(text).not.toContain('handler77');
  126. // The drift is announced and the agent is pointed at trustworthy reads.
  127. expect(text).toContain('changed on disk after it was last indexed');
  128. expect(text).toContain('orchestrate');
  129. });
  130. it('codegraph_node serves the full CURRENT source of a small drifted file (Read-parity fallback)', async () => {
  131. const p = path.join(fixtureDir, 'src', 'small.ts');
  132. fs.writeFileSync(p, '/** new first line */\nexport const shift = 1;\n' + fs.readFileSync(p, 'utf-8'));
  133. const result = await handler.execute('codegraph_node', {
  134. symbol: 'smallTarget',
  135. includeCode: true,
  136. projectPath: fixtureDir,
  137. });
  138. const text = getText(result);
  139. expect(result.isError).toBeFalsy();
  140. expect(text).toContain('full CURRENT source');
  141. // Current content, including the just-inserted lines the index knows nothing about.
  142. expect(text).toContain('new first line');
  143. expect(text).toContain('smallTarget');
  144. });
  145. it('an identical rewrite (mtime churn, same bytes) does not trip the guard', async () => {
  146. const p = path.join(fixtureDir, 'src', 'big.ts');
  147. fs.writeFileSync(p, fs.readFileSync(p, 'utf-8'));
  148. const result = await handler.execute('codegraph_node', {
  149. symbol: 'orchestrate',
  150. includeCode: true,
  151. projectPath: fixtureDir,
  152. });
  153. const text = getText(result);
  154. expect(text).not.toContain('changed on disk');
  155. expect(text).toContain('export function orchestrate');
  156. });
  157. it('codegraph_explore omits (never mis-slices) a big drifted file and flags line refs', async () => {
  158. shiftBigFile();
  159. const result = await handler.execute('codegraph_explore', {
  160. query: 'orchestrate handler3',
  161. projectPath: fixtureDir,
  162. });
  163. const text = getText(result);
  164. expect(result.isError).toBeFalsy();
  165. expect(text).toContain('changed on disk after the last index sync');
  166. // No sliced body from the drifted file — its step lines must not appear.
  167. expect(text).not.toMatch(/-step\d-h\d/);
  168. // Line-reference caveat for the drifted file.
  169. expect(text).toContain('may be shifted');
  170. });
  171. it('re-syncing the project restores normal output with no drift markers', async () => {
  172. shiftBigFile();
  173. await cgFixture.sync();
  174. // Fresh handler: the drift verdict is briefly memoized per handler.
  175. const freshHandler = new ToolHandler(cgOther);
  176. try {
  177. const result = await freshHandler.execute('codegraph_node', {
  178. symbol: 'orchestrate',
  179. includeCode: true,
  180. projectPath: fixtureDir,
  181. });
  182. const text = getText(result);
  183. expect(text).not.toContain('changed on disk');
  184. expect(text).toContain('export function orchestrate');
  185. // Location reflects the post-shift position (45 inserted lines).
  186. expect(text).toMatch(/Location:\*\* src\/big\.ts:\d+/);
  187. } finally {
  188. try { freshHandler.closeAll(); } catch { /* ignore */ }
  189. }
  190. });
  191. it('the guard also fires on the default project when no watcher is running', async () => {
  192. shiftBigFile();
  193. const direct = new ToolHandler(cgFixture);
  194. try {
  195. const result = await direct.execute('codegraph_node', {
  196. symbol: 'orchestrate',
  197. includeCode: true,
  198. });
  199. const text = getText(result);
  200. expect(text).not.toContain('handler77');
  201. expect(text).toContain('changed on disk after it was last indexed');
  202. } finally {
  203. try { direct.closeAll(); } catch { /* ignore */ }
  204. }
  205. });
  206. });