1
0

explore-allocation-1500.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /**
  2. * Regression fixture for GitHub issue #1500 / epic CG-1 — relevance-proportional
  3. * explore budget allocation.
  4. *
  5. * The reporter's repo is a Go service whose GENERATED FKIT CRUD layer sits beside
  6. * the hand-written use-case that does the real work. Asking an architecture
  7. * question that doesn't name the exact use-case ("how does payroll cycle create
  8. * and calculate payslips?") spends the explore envelope on the generated CRUD,
  9. * because the generated layer name-collides on every term in the question while
  10. * the hand-written workflow is one big file that gets clipped.
  11. *
  12. * `__tests__/fixtures/payroll-go/` reproduces that shape permanently. This suite
  13. * is in two halves:
  14. *
  15. * 1. **Fixture shape** — green today. These pin the properties the fixture must
  16. * keep for the gate below to mean anything: the generated/hand-written split
  17. * (including the ordinary-named generated files only a CONTENT header betrays,
  18. * which is the #1500 case), the deliberate name collisions, and the
  19. * runPayrollCycleAll → BuildPayslip → Upsert chain resolving end-to-end. If
  20. * the fixture rots, these fail first and say so.
  21. *
  22. * 2. **Budget allocation** — the gate, written with `it.fails` because it
  23. * DOCUMENTS A BUG THAT IS STILL OPEN. Vitest passes an `it.fails` test only
  24. * while its body throws, so the suite is green today and goes RED the moment
  25. * allocation is fixed (CG-10 scoring + CG-12 proportional bytes).
  26. * **When it goes red, delete the `.fails` — do not delete the test.**
  27. *
  28. * The same assertions run outside vitest, against the built dist and with the
  29. * full CG-4 per-file diagnostic, via `node scripts/agent-eval/probe-allocation.mjs`
  30. * (declared in `scripts/agent-eval/allocation-fixtures.json`).
  31. */
  32. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  33. import * as fs from 'fs';
  34. import * as path from 'path';
  35. import * as os from 'os';
  36. import CodeGraph from '../src/index';
  37. import { ToolHandler } from '../src/mcp/tools';
  38. import { attributeSourceBytes } from '../src/mcp/explore-diagnostics';
  39. import { isGeneratedFile, hasGeneratedHeader } from '../src/extraction/generated-detection';
  40. const FIXTURE_SRC = path.join(__dirname, 'fixtures', 'payroll-go');
  41. /** The question a newcomer asks — names none of the symbols that answer it. */
  42. const QUERY = 'how does payroll cycle create and calculate payslips?';
  43. /** The hand-written workflow: what the query is actually about. */
  44. const ANSWER_PREFIXES = [
  45. 'internal/usecase/',
  46. 'internal/store/',
  47. 'internal/transport/',
  48. 'internal/domain/',
  49. 'cmd/',
  50. ];
  51. /** The generated CRUD/DTO layer: what wins the envelope today. */
  52. const GENERATED_PREFIX = 'internal/gen/';
  53. const startsWithAny = (p: string, prefixes: string[]) => prefixes.some((x) => p.startsWith(x));
  54. describe('#1500 — generated Go CRUD beside a hand-written payroll workflow', () => {
  55. let testDir: string;
  56. let cg: CodeGraph;
  57. let handler: ToolHandler;
  58. let response: string;
  59. /** Delivered source bytes per file, attributed from the final response. */
  60. let bytes: Map<string, number>;
  61. beforeAll(async () => {
  62. testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-1500-'));
  63. fs.cpSync(FIXTURE_SRC, testDir, { recursive: true });
  64. // A stray index in the checked-in tree would be copied in and reused.
  65. fs.rmSync(path.join(testDir, '.codegraph'), { recursive: true, force: true });
  66. cg = CodeGraph.initSync(testDir);
  67. await cg.indexAll();
  68. handler = new ToolHandler(cg);
  69. const result = await handler.execute('codegraph_explore', { query: QUERY });
  70. response = result.content?.[0]?.text ?? '';
  71. bytes = attributeSourceBytes(response);
  72. }, 120_000);
  73. afterAll(() => {
  74. if (cg) cg.destroy();
  75. if (testDir && fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
  76. });
  77. // ── 1. Fixture shape ──────────────────────────────────────────────────────
  78. describe('fixture shape', () => {
  79. it('indexes as a Go project with both layers present', () => {
  80. const files = cg.getFiles().map((f) => f.path);
  81. expect(files.filter((p) => p.endsWith('.go')).length).toBeGreaterThanOrEqual(15);
  82. expect(files.some((p) => p.startsWith(GENERATED_PREFIX))).toBe(true);
  83. expect(files.some((p) => p.startsWith('internal/usecase/'))).toBe(true);
  84. });
  85. it('flags every generated file and no hand-written one', () => {
  86. for (const file of cg.getFiles()) {
  87. expect(file.generated, `${file.path} generated flag`).toBe(
  88. file.path.startsWith(GENERATED_PREFIX),
  89. );
  90. }
  91. });
  92. it('carries generated files that ONLY a content header betrays — the #1500 case', () => {
  93. // Half the generated tree has ordinary names (`payslip.go`, `store.go`).
  94. // Path-only detection misses them; the CG-5 content check is what catches
  95. // them. Without these the fixture would be a .pb.go fixture, not a #1500 one.
  96. const contentOnly = [
  97. 'internal/gen/fkit/payroll/payslip.go',
  98. 'internal/gen/fkit/payroll/payroll_cycle.go',
  99. 'internal/gen/fkit/payroll/store.go',
  100. 'internal/gen/fkit/payroll/calculate.go',
  101. 'internal/gen/fkit/payroll/dto.go',
  102. 'internal/gen/fkit/employee/employee.go',
  103. 'internal/gen/fkit/timesheet/timesheet.go',
  104. ];
  105. for (const rel of contentOnly) {
  106. const source = fs.readFileSync(path.join(testDir, rel), 'utf-8');
  107. expect(isGeneratedFile(rel), `${rel} must NOT be detectable by path`).toBe(false);
  108. expect(hasGeneratedHeader(source), `${rel} must be detectable by header`).toBe(true);
  109. expect(cg.getFile(rel)?.generated, `${rel} indexed flag`).toBe(true);
  110. }
  111. // …beside the conventional path-detectable ones, so both channels are covered.
  112. expect(isGeneratedFile('internal/gen/payrollpb/payroll.pb.go')).toBe(true);
  113. });
  114. it('collides the generated layer with the hand-written one by name', () => {
  115. // A naive scorer sees two BuildPayslips and two Upserts and has no reason
  116. // to prefer the one that implements the business rule.
  117. for (const name of ['BuildPayslip', 'Upsert', 'Store']) {
  118. const files = new Set(cg.getNodesByName(name).map((n) => n.filePath));
  119. expect([...files].some((p) => p.startsWith(GENERATED_PREFIX)), `${name} generated`).toBe(true);
  120. expect([...files].some((p) => !p.startsWith(GENERATED_PREFIX)), `${name} hand-written`).toBe(true);
  121. }
  122. });
  123. it('resolves the hand-written workflow chain end-to-end in the graph', () => {
  124. const calleesOf = (name: string, file: string) => {
  125. const node = cg.getNodesByName(name).find((n) => n.filePath === file);
  126. expect(node, `${name} in ${file}`).toBeTruthy();
  127. return cg
  128. .getOutgoingEdges(node!.id)
  129. .filter((e) => e.kind === 'calls')
  130. .map((e) => cg.getNode(e.target))
  131. .filter((n): n is NonNullable<typeof n> => !!n);
  132. };
  133. // handler → use-case
  134. expect(
  135. calleesOf('RunCycle', 'internal/transport/httpapi/payroll_handler.go')
  136. .some((n) => n.name === 'RunCycle' && n.filePath === 'internal/usecase/payroll/cycle.go'),
  137. ).toBe(true);
  138. // use-case → the workflow
  139. expect(
  140. calleesOf('RunCycle', 'internal/usecase/payroll/cycle.go')
  141. .some((n) => n.name === 'runPayrollCycleAll'),
  142. ).toBe(true);
  143. // the workflow → build + persist
  144. const workflow = calleesOf('runPayrollCycleAll', 'internal/usecase/payroll/cycle.go');
  145. expect(
  146. workflow.some((n) => n.name === 'BuildPayslip' && n.filePath === 'internal/usecase/payroll/payslip_builder.go'),
  147. 'runPayrollCycleAll must reach the hand-written BuildPayslip',
  148. ).toBe(true);
  149. expect(workflow.some((n) => n.name === 'Upsert'), 'runPayrollCycleAll must reach an Upsert').toBe(true);
  150. });
  151. it('routes an HTTP entry point into the workflow', () => {
  152. const router = cg.getNodesInFile('internal/transport/httpapi/router.go');
  153. expect(router.some((n) => n.kind === 'route' || n.name === 'NewRouter')).toBe(true);
  154. });
  155. it('sizes the two layers so the size-driven render split actually bites', () => {
  156. // The mechanism the epic is about: a small file ships WHOLE, a large one
  157. // falls through to clipped clusters. The workflow file must stay above the
  158. // whole-file window and the generated files below it, or the fixture stops
  159. // reproducing anything.
  160. const lines = (rel: string) => fs.readFileSync(path.join(testDir, rel), 'utf-8').split('\n').length;
  161. expect(lines('internal/usecase/payroll/cycle.go')).toBeGreaterThan(220);
  162. for (const rel of ['internal/gen/fkit/payroll/payslip.go', 'internal/gen/fkit/payroll/payroll_cycle.go']) {
  163. expect(lines(rel)).toBeLessThan(220);
  164. }
  165. });
  166. it('answers the query at all', () => {
  167. expect(response.length).toBeGreaterThan(1000);
  168. expect(bytes.size).toBeGreaterThan(0);
  169. });
  170. });
  171. // ── 2. Budget allocation — the open bug ───────────────────────────────────
  172. describe('budget allocation', () => {
  173. const share = (predicate: (p: string) => boolean) => {
  174. let total = 0;
  175. for (const [file, n] of bytes) if (predicate(file)) total += n;
  176. return total / response.length;
  177. };
  178. const answerShare = () => share((p) => startsWithAny(p, ANSWER_PREFIXES));
  179. const generatedShare = () => share((p) => p.startsWith(GENERATED_PREFIX));
  180. /**
  181. * BASELINE 2026-08-03 (very-tiny tier, 13,000-char budget): 23,020 chars
  182. * allocated against it, cut to 16,011 by the 19,500 hard ceiling. The
  183. * generated CRUD delivers 57.4%; the hand-written layer delivers 25.6%, all
  184. * of it domain types. `cycle.go` is allocated the single largest slice
  185. * (7,052 chars, 30.6%) and delivers ZERO — the ceiling drops its whole
  186. * section — so runPayrollCycleAll, the hand-written BuildPayslip and the
  187. * real Upsert never reach the agent at all.
  188. *
  189. * Each `it.fails` below passes ONLY while that is still true.
  190. * ⚠ When one goes red, the bug is fixed: remove `.fails`, keep the test.
  191. */
  192. it.fails('CG-12 GATE: concentrates the envelope on the hand-written workflow', () => {
  193. expect(answerShare()).toBeGreaterThanOrEqual(0.55);
  194. });
  195. it.fails('CG-12 GATE: does not spend the envelope on the generated CRUD', () => {
  196. expect(generatedShare()).toBeLessThanOrEqual(0.25);
  197. });
  198. it.fails('CG-12 GATE: delivers the workflow file it allocated the most bytes to', () => {
  199. expect(bytes.get('internal/usecase/payroll/cycle.go') ?? 0).toBeGreaterThan(0);
  200. });
  201. it.fails('CG-12 GATE: delivers the calculation the question asks about', () => {
  202. expect(bytes.get('internal/usecase/payroll/payslip_builder.go') ?? 0).toBeGreaterThan(0);
  203. });
  204. it.fails('CG-12 GATE: puts the hand-written chain in the response, not its generated twin', () => {
  205. // Bare `BuildPayslip`/`Upsert` also match the generated collisions — these
  206. // needles are unique to the hand-written chain.
  207. expect(response).toContain('runPayrollCycleAll');
  208. expect(response).toContain('func (s *Service) BuildPayslip');
  209. expect(response).toContain('s.store.Upsert(ctx, slip)');
  210. });
  211. it('records the shape of the failure so a regression is legible', () => {
  212. // Not a gate — an assertion-free-ish snapshot of WHY the gates above fail,
  213. // so a future change that shifts the numbers shows up in the diff rather
  214. // than silently flipping an it.fails.
  215. const generated = generatedShare();
  216. const answer = answerShare();
  217. const workflow = bytes.get('internal/usecase/payroll/cycle.go') ?? 0;
  218. expect({
  219. generatedWinsEnvelope: generated > answer,
  220. workflowFileDeliversNothing: workflow === 0,
  221. }).toEqual({
  222. generatedWinsEnvelope: true,
  223. workflowFileDeliversNothing: true,
  224. });
  225. });
  226. });
  227. });