@dreamtree-org/graphify 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,554 @@
1
+ import {
2
+ validateGraphPath
3
+ } from "./chunk-6JLEILYF.js";
4
+
5
+ // src/graphStore.ts
6
+ import * as fs from "fs/promises";
7
+ import * as path from "path";
8
+ import Graph from "graphology";
9
+ async function loadGraph(outDir = path.join(process.cwd(), "graphify-out")) {
10
+ const jsonPath = validateGraphPath("graph.json", outDir);
11
+ const raw = await fs.readFile(jsonPath, "utf-8");
12
+ const data = JSON.parse(raw);
13
+ return Graph.from(data);
14
+ }
15
+
16
+ // src/query.ts
17
+ var STOPWORDS = /* @__PURE__ */ new Set([
18
+ "a",
19
+ "an",
20
+ "the",
21
+ "is",
22
+ "are",
23
+ "was",
24
+ "were",
25
+ "do",
26
+ "does",
27
+ "did",
28
+ "how",
29
+ "what",
30
+ "where",
31
+ "when",
32
+ "why",
33
+ "who",
34
+ "which",
35
+ "to",
36
+ "of",
37
+ "in",
38
+ "on",
39
+ "for",
40
+ "and",
41
+ "or",
42
+ "this",
43
+ "that",
44
+ "it",
45
+ "does",
46
+ "that's"
47
+ ]);
48
+ function splitCamelCase(text) {
49
+ return text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2");
50
+ }
51
+ function tokenize(text) {
52
+ return splitCamelCase(text).toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 1 && !STOPWORDS.has(token));
53
+ }
54
+ function subtokenize(text) {
55
+ return splitCamelCase(text).toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 1);
56
+ }
57
+ var FUZZY_MIN_TOKEN_LEN = 3;
58
+ var FUZZY_THRESHOLD = 0.7;
59
+ var SUBTOKEN_MATCH_SCORE = 1;
60
+ var SUBSTRING_MATCH_SCORE = 0.6;
61
+ var FUZZY_MATCH_WEIGHT = 0.5;
62
+ function osaDistance(a, b) {
63
+ let prev2 = [];
64
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
65
+ let curr = new Array(b.length + 1).fill(0);
66
+ for (let i = 1; i <= a.length; i++) {
67
+ curr[0] = i;
68
+ for (let j = 1; j <= b.length; j++) {
69
+ const substitution = a[i - 1] === b[j - 1] ? 0 : 1;
70
+ let best = Math.min(
71
+ prev[j] + 1,
72
+ curr[j - 1] + 1,
73
+ prev[j - 1] + substitution
74
+ );
75
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
76
+ best = Math.min(best, prev2[j - 2] + 1);
77
+ }
78
+ curr[j] = best;
79
+ }
80
+ [prev2, prev, curr] = [prev, curr, new Array(b.length + 1).fill(0)];
81
+ }
82
+ return prev[b.length];
83
+ }
84
+ function fuzzySimilarity(a, b) {
85
+ if (a === b) return 1;
86
+ const maxLen = Math.max(a.length, b.length);
87
+ if (maxLen === 0) return 1;
88
+ if (Math.abs(a.length - b.length) / maxLen > 1 - FUZZY_THRESHOLD) return 0;
89
+ return 1 - osaDistance(a, b) / maxLen;
90
+ }
91
+ function scoreNodes(graph, query) {
92
+ const tokens = tokenize(query);
93
+ const matches = [];
94
+ graph.forEachNode((id, attributes) => {
95
+ const label = attributes.label ?? id;
96
+ const haystack = `${label} ${id}`.toLowerCase();
97
+ const subtokens = new Set(subtokenize(`${label} ${id}`));
98
+ let score = 0;
99
+ for (const token of tokens) {
100
+ if (subtokens.has(token)) {
101
+ score += SUBTOKEN_MATCH_SCORE;
102
+ continue;
103
+ }
104
+ if (haystack.includes(token)) {
105
+ score += SUBSTRING_MATCH_SCORE;
106
+ continue;
107
+ }
108
+ if (token.length >= FUZZY_MIN_TOKEN_LEN) {
109
+ let best = 0;
110
+ for (const subtoken of subtokens) {
111
+ const similarity = fuzzySimilarity(token, subtoken);
112
+ if (similarity > best) best = similarity;
113
+ }
114
+ if (best >= FUZZY_THRESHOLD) score += best * FUZZY_MATCH_WEIGHT;
115
+ }
116
+ }
117
+ if (score > 0) matches.push({ id, label, score });
118
+ });
119
+ matches.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
120
+ return matches;
121
+ }
122
+ function resolveNode(graph, query) {
123
+ const matches = scoreNodes(graph, query);
124
+ return matches[0] ?? null;
125
+ }
126
+ var DEFAULT_MAX_DEPTH = 2;
127
+ var DEFAULT_MAX_SEEDS = 5;
128
+ var DEFAULT_BUDGET = 40;
129
+ var DEFAULT_TOKEN_BUDGET = 2e3;
130
+ var NODES_PER_TOKEN = 1 / 10;
131
+ function nodeTokenCost(graph, id) {
132
+ const attrs = graph.getNodeAttributes(id);
133
+ const label = attrs.label ?? id;
134
+ const sourceFile = attrs.sourceFile ?? "";
135
+ return Math.ceil((id.length * 2 + label.length + sourceFile.length + 24) / 4);
136
+ }
137
+ function queryGraph(graph, question, options = {}) {
138
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
139
+ const maxSeeds = options.maxSeeds ?? DEFAULT_MAX_SEEDS;
140
+ const tokenBudget = options.tokenBudget ?? DEFAULT_TOKEN_BUDGET;
141
+ const budget = options.budget ?? Math.max(DEFAULT_BUDGET, Math.ceil(tokenBudget * NODES_PER_TOKEN));
142
+ const allMatches = scoreNodes(graph, question);
143
+ const seeds = allMatches.length > 0 ? allMatches.slice(0, maxSeeds) : [];
144
+ const visited = /* @__PURE__ */ new Map();
145
+ const frontier = seeds.map((s) => ({ id: s.id, depth: 0 }));
146
+ let spentTokens = 0;
147
+ for (const seed of seeds) {
148
+ visited.set(seed.id, 0);
149
+ spentTokens += nodeTokenCost(graph, seed.id);
150
+ }
151
+ while (frontier.length > 0 && visited.size < budget && spentTokens < tokenBudget) {
152
+ const current = options.dfs ? frontier.pop() : frontier.shift();
153
+ if (current.depth >= maxDepth) continue;
154
+ const neighbors = [...graph.neighbors(current.id)].sort((a, b) => a.localeCompare(b));
155
+ for (const neighbor of neighbors) {
156
+ if (visited.has(neighbor) || visited.size >= budget || spentTokens >= tokenBudget) continue;
157
+ visited.set(neighbor, current.depth + 1);
158
+ spentTokens += nodeTokenCost(graph, neighbor);
159
+ frontier.push({ id: neighbor, depth: current.depth + 1 });
160
+ }
161
+ }
162
+ const visitedNodes = [...visited.entries()].map(([id, depth]) => {
163
+ const attrs = graph.getNodeAttributes(id);
164
+ return {
165
+ id,
166
+ label: attrs.label ?? id,
167
+ sourceFile: attrs.sourceFile ?? "",
168
+ sourceLocation: attrs.sourceLocation ?? "",
169
+ depth
170
+ };
171
+ }).sort((a, b) => a.depth - b.depth || a.id.localeCompare(b.id));
172
+ const edges = [];
173
+ graph.forEachEdge((_edge, attrs, source, target) => {
174
+ if (visited.has(source) && visited.has(target)) {
175
+ edges.push({
176
+ source,
177
+ target,
178
+ relation: String(attrs.relation),
179
+ confidence: String(attrs.confidence)
180
+ });
181
+ }
182
+ });
183
+ edges.sort(
184
+ (a, b) => a.source.localeCompare(b.source) || a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation)
185
+ );
186
+ return enforceTokenBudget({ seeds, visited: visitedNodes, edges }, tokenBudget);
187
+ }
188
+ function enforceTokenBudget(result, tokenBudget) {
189
+ const cost = (value) => Math.ceil(JSON.stringify(value).length / 4);
190
+ const visited = [...result.visited];
191
+ let edges = [...result.edges];
192
+ let total = cost(result.seeds) + visited.reduce((s, n) => s + cost(n), 0) + edges.reduce((s, e) => s + cost(e), 0);
193
+ const seedIds = new Set(result.seeds.map((s) => s.id));
194
+ while (total > tokenBudget && visited.length > 0) {
195
+ const last = visited[visited.length - 1];
196
+ if (seedIds.has(last.id)) break;
197
+ visited.pop();
198
+ total -= cost(last);
199
+ const remaining = [];
200
+ for (const edge of edges) {
201
+ if (edge.source === last.id || edge.target === last.id) {
202
+ total -= cost(edge);
203
+ } else {
204
+ remaining.push(edge);
205
+ }
206
+ }
207
+ edges = remaining;
208
+ }
209
+ return { seeds: result.seeds, visited, edges };
210
+ }
211
+ function shortestPath(graph, fromQuery, toQuery) {
212
+ const from = resolveNode(graph, fromQuery);
213
+ const to = resolveNode(graph, toQuery);
214
+ if (!from || !to) return null;
215
+ if (from.id === to.id) {
216
+ return { from, to, found: true, path: [from.id], edges: [] };
217
+ }
218
+ const predecessor = /* @__PURE__ */ new Map();
219
+ const visited = /* @__PURE__ */ new Set([from.id]);
220
+ const queue = [from.id];
221
+ while (queue.length > 0) {
222
+ const current = queue.shift();
223
+ if (current === to.id) break;
224
+ const neighbors = [...graph.neighbors(current)].sort((a, b) => a.localeCompare(b));
225
+ for (const neighbor of neighbors) {
226
+ if (visited.has(neighbor)) continue;
227
+ visited.add(neighbor);
228
+ predecessor.set(neighbor, current);
229
+ queue.push(neighbor);
230
+ }
231
+ }
232
+ if (!visited.has(to.id)) {
233
+ return { from, to, found: false, path: [], edges: [] };
234
+ }
235
+ const path2 = [to.id];
236
+ let cursor = to.id;
237
+ while (cursor !== from.id) {
238
+ const prev = predecessor.get(cursor);
239
+ if (!prev) break;
240
+ path2.unshift(prev);
241
+ cursor = prev;
242
+ }
243
+ const edges = [];
244
+ for (let i = 0; i < path2.length - 1; i++) {
245
+ const a = path2[i];
246
+ const b = path2[i + 1];
247
+ const key = graph.edges(a, b)[0] ?? graph.edges(b, a)[0];
248
+ if (key) {
249
+ const attrs = graph.getEdgeAttributes(key);
250
+ edges.push({ source: a, target: b, relation: String(attrs.relation), confidence: String(attrs.confidence) });
251
+ }
252
+ }
253
+ return { from, to, found: true, path: path2, edges };
254
+ }
255
+ function explainNode(graph, query) {
256
+ const match = resolveNode(graph, query);
257
+ if (!match) return null;
258
+ const attrs = graph.getNodeAttributes(match.id);
259
+ const outgoing = [];
260
+ const incoming = [];
261
+ graph.forEachOutEdge(match.id, (_edge, edgeAttrs, source, target) => {
262
+ outgoing.push({ source, target, relation: String(edgeAttrs.relation), confidence: String(edgeAttrs.confidence) });
263
+ });
264
+ graph.forEachInEdge(match.id, (_edge, edgeAttrs, source, target) => {
265
+ incoming.push({ source, target, relation: String(edgeAttrs.relation), confidence: String(edgeAttrs.confidence) });
266
+ });
267
+ outgoing.sort((a, b) => a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation));
268
+ incoming.sort((a, b) => a.source.localeCompare(b.source) || a.relation.localeCompare(b.relation));
269
+ return {
270
+ id: match.id,
271
+ label: match.label,
272
+ sourceFile: attrs.sourceFile ?? "",
273
+ sourceLocation: attrs.sourceLocation ?? "",
274
+ communityLabel: attrs.communityLabel,
275
+ outgoing,
276
+ incoming
277
+ };
278
+ }
279
+
280
+ // src/impact.ts
281
+ var DEPENDENCY_RELATIONS = /* @__PURE__ */ new Set([
282
+ "calls",
283
+ "imports",
284
+ "imports_from",
285
+ "inherits",
286
+ "implements",
287
+ "mixes_in",
288
+ "embeds",
289
+ "references",
290
+ "re_exports",
291
+ "method",
292
+ "contains"
293
+ ]);
294
+ var DEFAULT_IMPACT_DEPTH = 3;
295
+ var DEFAULT_IMPACT_LIMIT = 200;
296
+ var CONFIDENCE_RANK = { EXTRACTED: 3, INFERRED: 2, AMBIGUOUS: 1 };
297
+ function affectedBy(graph, nodeQuery, options = {}) {
298
+ const target = resolveNode(graph, nodeQuery);
299
+ if (!target) return null;
300
+ const maxDepth = options.maxDepth ?? DEFAULT_IMPACT_DEPTH;
301
+ const limit = options.limit ?? DEFAULT_IMPACT_LIMIT;
302
+ const affected = [];
303
+ const visited = /* @__PURE__ */ new Set([target.id]);
304
+ let frontier = [target.id];
305
+ let truncated = false;
306
+ for (let depth = 1; depth <= maxDepth && frontier.length > 0 && !truncated; depth++) {
307
+ const nextFrontier = /* @__PURE__ */ new Map();
308
+ for (const current of [...frontier].sort((a, b) => a.localeCompare(b))) {
309
+ graph.forEachInEdge(current, (_edge, edgeAttrs, source) => {
310
+ if (visited.has(source)) return;
311
+ const relation = edgeAttrs.relation;
312
+ if (!DEPENDENCY_RELATIONS.has(relation)) return;
313
+ const confidence = edgeAttrs.confidence;
314
+ const existing = nextFrontier.get(source);
315
+ if (existing && CONFIDENCE_RANK[existing.via.confidence] >= CONFIDENCE_RANK[confidence]) return;
316
+ const attrs = graph.getNodeAttributes(source);
317
+ nextFrontier.set(source, {
318
+ id: source,
319
+ label: attrs.label ?? source,
320
+ sourceFile: attrs.sourceFile ?? "",
321
+ sourceLocation: attrs.sourceLocation ?? "",
322
+ depth,
323
+ via: { relation, confidence, dependsOn: current }
324
+ });
325
+ });
326
+ }
327
+ const roundNodes = [...nextFrontier.values()].sort((a, b) => a.id.localeCompare(b.id));
328
+ for (const node of roundNodes) {
329
+ if (affected.length >= limit) {
330
+ truncated = true;
331
+ break;
332
+ }
333
+ visited.add(node.id);
334
+ affected.push(node);
335
+ }
336
+ frontier = roundNodes.filter((n) => visited.has(n.id)).map((n) => n.id);
337
+ }
338
+ const byConfidence = { EXTRACTED: 0, INFERRED: 0, AMBIGUOUS: 0 };
339
+ for (const node of affected) byConfidence[node.via.confidence] += 1;
340
+ return { target, affected, byConfidence, maxDepth, truncated };
341
+ }
342
+
343
+ // src/context.ts
344
+ var DEFAULT_CONTEXT_BUDGET = 4e3;
345
+ var DEFAULT_MAX_SEEDS2 = 8;
346
+ var DEFAULT_MAX_SNIPPET_LINES = 60;
347
+ var NEIGHBOR_DECAY = 0.4;
348
+ var tokensOf = (text) => Math.ceil(text.length / 4);
349
+ function lineNumberOf(sourceLocation) {
350
+ const match = /^L(\d+)$/.exec(sourceLocation);
351
+ return match ? Number(match[1]) : null;
352
+ }
353
+ function isReadableFile(sourceFile) {
354
+ return sourceFile !== "" && !sourceFile.startsWith("<") && !sourceFile.includes("://");
355
+ }
356
+ function rankForTask(graph, task, maxSeeds = DEFAULT_MAX_SEEDS2) {
357
+ const seeds = scoreNodes(graph, task).slice(0, maxSeeds);
358
+ const ranked = /* @__PURE__ */ new Map();
359
+ for (const seed of seeds) {
360
+ ranked.set(seed.id, { id: seed.id, score: seed.score, reason: "matches the task" });
361
+ }
362
+ for (const seed of seeds) {
363
+ graph.forEachEdge(seed.id, (_edge, attrs, source, target) => {
364
+ const neighbor = source === seed.id ? target : source;
365
+ if (ranked.has(neighbor)) return;
366
+ const relation = String(attrs.relation);
367
+ const direction = source === seed.id ? `${relation} ->` : `<- ${relation}`;
368
+ ranked.set(neighbor, {
369
+ id: neighbor,
370
+ score: seed.score * NEIGHBOR_DECAY,
371
+ reason: `${direction} ${seed.label}`
372
+ });
373
+ });
374
+ }
375
+ return [...ranked.values()].sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
376
+ }
377
+ function snippetRange(startLine, fileLineCount, entityStartsInFile, maxLines) {
378
+ const nextStart = entityStartsInFile.find((l) => l > startLine);
379
+ const hardEnd = nextStart !== void 0 ? nextStart - 1 : fileLineCount;
380
+ return { start: startLine, end: Math.min(hardEnd, startLine + maxLines - 1) };
381
+ }
382
+ async function buildContextPack(graph, task, readFile2, options = {}) {
383
+ const tokenBudget = options.tokenBudget ?? DEFAULT_CONTEXT_BUDGET;
384
+ const maxSnippetLines = options.maxSnippetLines ?? DEFAULT_MAX_SNIPPET_LINES;
385
+ const ranked = rankForTask(graph, task, options.maxSeeds);
386
+ const entityStarts = /* @__PURE__ */ new Map();
387
+ graph.forEachNode((_id, attrs) => {
388
+ const file = attrs.sourceFile;
389
+ const line = lineNumberOf(attrs.sourceLocation ?? "");
390
+ if (file && line !== null) {
391
+ const starts = entityStarts.get(file) ?? [];
392
+ starts.push(line);
393
+ entityStarts.set(file, starts);
394
+ }
395
+ });
396
+ for (const starts of entityStarts.values()) starts.sort((a, b) => a - b);
397
+ const fileCache = /* @__PURE__ */ new Map();
398
+ const readLines = async (file) => {
399
+ const cached = fileCache.get(file);
400
+ if (cached !== void 0) return cached;
401
+ let lines;
402
+ try {
403
+ lines = (await readFile2(file)).split("\n");
404
+ } catch {
405
+ lines = null;
406
+ }
407
+ fileCache.set(file, lines);
408
+ return lines;
409
+ };
410
+ const snippets = [];
411
+ const overflow = [];
412
+ const coveredRanges = /* @__PURE__ */ new Map();
413
+ let tokens = 0;
414
+ for (const node of ranked) {
415
+ const attrs = graph.getNodeAttributes(node.id);
416
+ const file = attrs.sourceFile ?? "";
417
+ const startLine = lineNumberOf(attrs.sourceLocation ?? "");
418
+ if (!isReadableFile(file) || startLine === null) continue;
419
+ const lines = await readLines(file);
420
+ if (lines === null) continue;
421
+ const { start, end } = snippetRange(startLine, lines.length, entityStarts.get(file) ?? [], maxSnippetLines);
422
+ const covered = (coveredRanges.get(file) ?? []).some((r) => start >= r.start && end <= r.end);
423
+ if (covered) continue;
424
+ const code = lines.slice(start - 1, end).join("\n");
425
+ const cost = tokensOf(code) + 15;
426
+ if (tokens + cost > tokenBudget) {
427
+ overflow.push({ nodeId: node.id, file: `${file}:L${startLine}` });
428
+ continue;
429
+ }
430
+ tokens += cost;
431
+ snippets.push({
432
+ nodeId: node.id,
433
+ label: attrs.label ?? node.id,
434
+ file,
435
+ startLine: start,
436
+ endLine: end,
437
+ code,
438
+ reason: node.reason,
439
+ score: node.score
440
+ });
441
+ const ranges = coveredRanges.get(file) ?? [];
442
+ ranges.push({ start, end });
443
+ coveredRanges.set(file, ranges);
444
+ }
445
+ return { task, snippets, tokens, tokenBudget, overflow };
446
+ }
447
+ function renderContextPack(pack) {
448
+ const lines = [
449
+ `# Context pack: ${pack.task}`,
450
+ "",
451
+ `_~${pack.tokens} of ${pack.tokenBudget} token budget, ${pack.snippets.length} snippet(s)._`,
452
+ ""
453
+ ];
454
+ if (pack.snippets.length === 0) {
455
+ lines.push("No matching code found \u2014 try different keywords.");
456
+ return lines.join("\n");
457
+ }
458
+ for (const snippet of pack.snippets) {
459
+ lines.push(`## ${snippet.label} \u2014 \`${snippet.file}:L${snippet.startLine}-L${snippet.endLine}\``);
460
+ lines.push(`_${snippet.reason}_`);
461
+ lines.push("```");
462
+ lines.push(snippet.code);
463
+ lines.push("```");
464
+ lines.push("");
465
+ }
466
+ if (pack.overflow.length > 0) {
467
+ lines.push(`## Didn't fit the budget (${pack.overflow.length})`);
468
+ for (const item of pack.overflow.slice(0, 15)) {
469
+ lines.push(`- ${item.nodeId} (${item.file})`);
470
+ }
471
+ lines.push("");
472
+ }
473
+ return lines.join("\n");
474
+ }
475
+
476
+ // src/testmap.ts
477
+ var TEST_FILE_PATTERNS = [
478
+ /(^|\/)tests?\//,
479
+ // tests/ or test/ directory
480
+ /(^|\/)__tests__\//,
481
+ /(^|\/)spec\//,
482
+ /\.test\.[cm]?[jt]sx?$/,
483
+ /\.spec\.[cm]?[jt]sx?$/,
484
+ /(^|\/)test_[^/]+\.py$/,
485
+ /_test\.py$/,
486
+ /_test\.go$/,
487
+ /Tests?\.(java|cs)$/,
488
+ /_spec\.rb$/,
489
+ /_test\.rb$/
490
+ ];
491
+ function isTestFile(path2) {
492
+ return TEST_FILE_PATTERNS.some((p) => p.test(path2));
493
+ }
494
+ var TEST_REACH_DEPTH = 4;
495
+ var TEST_REACH_LIMIT = 2e3;
496
+ function selectionFromImpact(graph, targetIds, targetLabel) {
497
+ const best = /* @__PURE__ */ new Map();
498
+ let affectedNodeCount = 0;
499
+ for (const id of targetIds) {
500
+ const impact = affectedBy(graph, id, { maxDepth: TEST_REACH_DEPTH, limit: TEST_REACH_LIMIT });
501
+ if (!impact) continue;
502
+ affectedNodeCount += impact.affected.length;
503
+ for (const node of impact.affected) {
504
+ if (!isTestFile(node.sourceFile)) continue;
505
+ const existing = best.get(node.sourceFile);
506
+ if (!existing || node.depth < existing.depth) {
507
+ best.set(node.sourceFile, { depth: node.depth, via: node.via.dependsOn });
508
+ }
509
+ }
510
+ }
511
+ const testFiles = [...best.entries()].map(([file, info]) => ({ file, depth: info.depth, via: info.via })).sort((a, b) => a.depth - b.depth || a.file.localeCompare(b.file));
512
+ return { target: targetLabel, testFiles, affectedNodeCount };
513
+ }
514
+ function testsForNode(graph, nodeQuery) {
515
+ const match = resolveNode(graph, nodeQuery);
516
+ if (!match) return null;
517
+ return selectionFromImpact(graph, [match.id], match.id);
518
+ }
519
+ function testsForChangedFiles(graph, changedFiles) {
520
+ const fileIds = [];
521
+ const selfSelected = /* @__PURE__ */ new Map();
522
+ for (const file of changedFiles) {
523
+ if (isTestFile(file)) {
524
+ selfSelected.set(file, { depth: 0, via: "(changed directly)" });
525
+ continue;
526
+ }
527
+ if (graph.hasNode(file)) fileIds.push(file);
528
+ }
529
+ const selection = selectionFromImpact(graph, fileIds, changedFiles.join(", "));
530
+ for (const [file, info] of selfSelected) {
531
+ if (!selection.testFiles.some((t) => t.file === file)) {
532
+ selection.testFiles.push({ file, depth: info.depth, via: info.via });
533
+ }
534
+ }
535
+ selection.testFiles.sort((a, b) => a.depth - b.depth || a.file.localeCompare(b.file));
536
+ return selection;
537
+ }
538
+
539
+ export {
540
+ loadGraph,
541
+ scoreNodes,
542
+ resolveNode,
543
+ queryGraph,
544
+ shortestPath,
545
+ explainNode,
546
+ affectedBy,
547
+ rankForTask,
548
+ buildContextPack,
549
+ renderContextPack,
550
+ isTestFile,
551
+ testsForNode,
552
+ testsForChangedFiles
553
+ };
554
+ //# sourceMappingURL=chunk-YT7B6DOD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/graphStore.ts","../src/query.ts","../src/impact.ts","../src/context.ts","../src/testmap.ts"],"sourcesContent":["import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport Graph from 'graphology';\nimport { validateGraphPath } from './security.js';\n\n/**\n * Load a previously-exported graph.json back into a graphology Graph.\n * Always goes through security.validateGraphPath() (path-traversal guard —\n * see SECURITY.md) so a caller-supplied `outDir`/CLI arg can never make\n * this read outside the graphify-out/ directory it resolves to.\n */\nexport async function loadGraph(outDir: string = path.join(process.cwd(), 'graphify-out')): Promise<Graph> {\n const jsonPath = validateGraphPath('graph.json', outDir);\n const raw = await fs.readFile(jsonPath, 'utf-8');\n const data: unknown = JSON.parse(raw);\n return Graph.from(data as Parameters<typeof Graph.from>[0]);\n}\n","import type Graph from 'graphology';\n\n/**\n * Library-level graph queries shared by the CLI (`graphify query/path/\n * explain`) and the MCP server tools of the same name. None of this is an\n * LLM call — it's lexical node matching + graph traversal, so it works\n * fully offline and deterministically.\n */\n\nconst STOPWORDS = new Set([\n 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'do', 'does', 'did', 'how',\n 'what', 'where', 'when', 'why', 'who', 'which', 'to', 'of', 'in', 'on',\n 'for', 'and', 'or', 'this', 'that', 'it', 'does', 'that\\'s',\n]);\n\n/** Insert spaces at camelCase boundaries so identifier words become separate tokens. */\nfunction splitCamelCase(text: string): string {\n return text\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');\n}\n\nfunction tokenize(text: string): string[] {\n return splitCamelCase(text)\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((token) => token.length > 1 && !STOPWORDS.has(token));\n}\n\n/**\n * Split an identifier-ish string (node label/id) into its word subtokens:\n * camelCase, snake_case, kebab-case, dots, and path separators all become\n * boundaries, so `src/a/fileStorage.js::saveAttachment` yields\n * `src, file, storage, js, save, attachment`.\n */\nfunction subtokenize(text: string): string[] {\n return splitCamelCase(text)\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((token) => token.length > 1);\n}\n\n/** Don't run the fuzzy tier on tokens this short — too many false positives. */\nconst FUZZY_MIN_TOKEN_LEN = 3;\n/** Minimum similarity for a fuzzy match to count at all. */\nconst FUZZY_THRESHOLD = 0.7;\nconst SUBTOKEN_MATCH_SCORE = 1;\nconst SUBSTRING_MATCH_SCORE = 0.6;\nconst FUZZY_MATCH_WEIGHT = 0.5;\n\n/**\n * Optimal-string-alignment Damerau-Levenshtein distance. Chosen over\n * bigram-set similarity because the common code-search typo is a\n * transposition (\"sorceNodes\"), which OSA counts as one edit but bigram\n * overlap punishes brutally.\n */\nfunction osaDistance(a: string, b: string): number {\n let prev2: number[] = [];\n let prev: number[] = Array.from({ length: b.length + 1 }, (_, j) => j);\n let curr: number[] = new Array<number>(b.length + 1).fill(0);\n\n for (let i = 1; i <= a.length; i++) {\n curr[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const substitution = a[i - 1] === b[j - 1] ? 0 : 1;\n let best = Math.min(\n (prev[j] as number) + 1,\n (curr[j - 1] as number) + 1,\n (prev[j - 1] as number) + substitution,\n );\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n best = Math.min(best, (prev2[j - 2] as number) + 1);\n }\n curr[j] = best;\n }\n [prev2, prev, curr] = [prev, curr, new Array<number>(b.length + 1).fill(0)];\n }\n return prev[b.length] as number;\n}\n\n/** Normalized similarity in [0, 1]; short-circuits pairs whose length gap alone puts them under FUZZY_THRESHOLD. */\nfunction fuzzySimilarity(a: string, b: string): number {\n if (a === b) return 1;\n const maxLen = Math.max(a.length, b.length);\n if (maxLen === 0) return 1;\n if (Math.abs(a.length - b.length) / maxLen > 1 - FUZZY_THRESHOLD) return 0;\n return 1 - osaDistance(a, b) / maxLen;\n}\n\nexport interface NodeMatch {\n id: string;\n label: string;\n score: number;\n}\n\n/**\n * Score every node against the query's tokens. Identifier-aware and\n * typo-tolerant, in three tiers per token (best tier wins):\n *\n * 1. exact subtoken match (camelCase/snake_case-split word of the label\n * or id) — \"storage\" matches `fileStorage.js`;\n * 2. plain substring of the label/id (the original v1 behavior);\n * 3. fuzzy (Damerau-Levenshtein) match against a subtoken — \"sorce\"\n * still finds `scoreNodes`.\n *\n * Still fully lexical and deterministic — no LLM, no randomness.\n */\nexport function scoreNodes(graph: Graph, query: string): NodeMatch[] {\n const tokens = tokenize(query);\n const matches: NodeMatch[] = [];\n\n graph.forEachNode((id, attributes) => {\n const label = (attributes.label as string | undefined) ?? id;\n const haystack = `${label} ${id}`.toLowerCase();\n const subtokens = new Set(subtokenize(`${label} ${id}`));\n let score = 0;\n for (const token of tokens) {\n if (subtokens.has(token)) {\n score += SUBTOKEN_MATCH_SCORE;\n continue;\n }\n if (haystack.includes(token)) {\n score += SUBSTRING_MATCH_SCORE;\n continue;\n }\n if (token.length >= FUZZY_MIN_TOKEN_LEN) {\n let best = 0;\n for (const subtoken of subtokens) {\n const similarity = fuzzySimilarity(token, subtoken);\n if (similarity > best) best = similarity;\n }\n if (best >= FUZZY_THRESHOLD) score += best * FUZZY_MATCH_WEIGHT;\n }\n }\n if (score > 0) matches.push({ id, label, score });\n });\n\n matches.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return matches;\n}\n\n/**\n * Best-effort single-node resolution: the highest-scoring lexical match,\n * or null if nothing in the graph matches at all. Deliberately does *not*\n * fall back to \"the most connected node\" — path/explain name a specific\n * node by intent, and silently substituting an unrelated one would be\n * more misleading than clearly saying \"no match\".\n */\nexport function resolveNode(graph: Graph, query: string): NodeMatch | null {\n const matches = scoreNodes(graph, query);\n return matches[0] ?? null;\n}\n\nexport interface VisitedNode {\n id: string;\n label: string;\n sourceFile: string;\n sourceLocation: string;\n depth: number;\n}\n\nexport interface TraversalEdge {\n source: string;\n target: string;\n relation: string;\n confidence: string;\n}\n\nexport interface QueryResult {\n seeds: NodeMatch[];\n visited: VisitedNode[];\n edges: TraversalEdge[];\n}\n\nexport interface QueryOptions {\n dfs?: boolean;\n /** Hard cap on how many nodes to include. Defaults to a generous ceiling derived from `tokenBudget`. */\n budget?: number;\n /** Approximate cap, in tokens (~4 chars each), on the serialized size of the result. Default 2000. */\n tokenBudget?: number;\n maxDepth?: number;\n maxSeeds?: number;\n}\n\nconst DEFAULT_MAX_DEPTH = 2;\nconst DEFAULT_MAX_SEEDS = 5;\nconst DEFAULT_BUDGET = 40;\nconst DEFAULT_TOKEN_BUDGET = 2000;\n/** When only tokenBudget is given, allow up to this many nodes per budgeted token-decile as a safety ceiling. */\nconst NODES_PER_TOKEN = 1 / 10;\n\n/**\n * Estimated token contribution of one node to the rendered result: its own\n * line (label, file, location) plus a rough allowance for the edge lines\n * that mention its id. Chars/4 is the usual serviceable approximation.\n */\nfunction nodeTokenCost(graph: Graph, id: string): number {\n const attrs = graph.getNodeAttributes(id);\n const label = (attrs.label as string | undefined) ?? id;\n const sourceFile = (attrs.sourceFile as string | undefined) ?? '';\n return Math.ceil((id.length * 2 + label.length + sourceFile.length + 24) / 4);\n}\n\n/**\n * BFS (default, broad context) or DFS (--dfs, trace a specific path)\n * traversal from the nodes whose label best matches `question`'s\n * keywords. This is lexical retrieval, not natural-language\n * understanding — it surfaces the neighborhood of the graph an agent (or\n * a human) should look at to answer the question, it does not itself\n * compose an answer.\n */\nexport function queryGraph(graph: Graph, question: string, options: QueryOptions = {}): QueryResult {\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;\n const maxSeeds = options.maxSeeds ?? DEFAULT_MAX_SEEDS;\n const tokenBudget = options.tokenBudget ?? DEFAULT_TOKEN_BUDGET;\n const budget = options.budget ?? Math.max(DEFAULT_BUDGET, Math.ceil(tokenBudget * NODES_PER_TOKEN));\n\n const allMatches = scoreNodes(graph, question);\n const seeds = allMatches.length > 0 ? allMatches.slice(0, maxSeeds) : [];\n\n const visited = new Map<string, number>(); // id -> depth\n const frontier: Array<{ id: string; depth: number }> = seeds.map((s) => ({ id: s.id, depth: 0 }));\n let spentTokens = 0;\n for (const seed of seeds) {\n visited.set(seed.id, 0);\n spentTokens += nodeTokenCost(graph, seed.id);\n }\n\n while (frontier.length > 0 && visited.size < budget && spentTokens < tokenBudget) {\n const current = options.dfs ? (frontier.pop() as { id: string; depth: number }) : (frontier.shift() as { id: string; depth: number });\n if (current.depth >= maxDepth) continue;\n\n const neighbors = [...graph.neighbors(current.id)].sort((a, b) => a.localeCompare(b));\n for (const neighbor of neighbors) {\n if (visited.has(neighbor) || visited.size >= budget || spentTokens >= tokenBudget) continue;\n visited.set(neighbor, current.depth + 1);\n spentTokens += nodeTokenCost(graph, neighbor);\n frontier.push({ id: neighbor, depth: current.depth + 1 });\n }\n }\n\n const visitedNodes: VisitedNode[] = [...visited.entries()]\n .map(([id, depth]) => {\n const attrs = graph.getNodeAttributes(id);\n return {\n id,\n label: (attrs.label as string | undefined) ?? id,\n sourceFile: (attrs.sourceFile as string | undefined) ?? '',\n sourceLocation: (attrs.sourceLocation as string | undefined) ?? '',\n depth,\n };\n })\n .sort((a, b) => a.depth - b.depth || a.id.localeCompare(b.id));\n\n const edges: TraversalEdge[] = [];\n graph.forEachEdge((_edge, attrs, source, target) => {\n if (visited.has(source) && visited.has(target)) {\n edges.push({\n source,\n target,\n relation: String(attrs.relation),\n confidence: String(attrs.confidence),\n });\n }\n });\n edges.sort(\n (a, b) => a.source.localeCompare(b.source) || a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation),\n );\n\n return enforceTokenBudget({ seeds, visited: visitedNodes, edges }, tokenBudget);\n}\n\n/**\n * The traversal-time cost estimate can't see how densely connected the\n * visited neighborhood is — a hub-heavy subgraph induces far more edge\n * lines than nodes. Enforce the budget on the *actual* result: drop the\n * deepest/last nodes (and the edges that touched them) until the\n * serialized size fits. Seeds are never dropped.\n */\nfunction enforceTokenBudget(result: QueryResult, tokenBudget: number): QueryResult {\n const cost = (value: unknown): number => Math.ceil(JSON.stringify(value).length / 4);\n\n const visited = [...result.visited];\n let edges = [...result.edges];\n let total = cost(result.seeds) + visited.reduce((s, n) => s + cost(n), 0) + edges.reduce((s, e) => s + cost(e), 0);\n\n const seedIds = new Set(result.seeds.map((s) => s.id));\n // visited is sorted by (depth, id) — pop from the end so the deepest,\n // least-central context goes first and the result stays deterministic.\n while (total > tokenBudget && visited.length > 0) {\n const last = visited[visited.length - 1] as VisitedNode;\n if (seedIds.has(last.id)) break;\n visited.pop();\n total -= cost(last);\n const remaining: TraversalEdge[] = [];\n for (const edge of edges) {\n if (edge.source === last.id || edge.target === last.id) {\n total -= cost(edge);\n } else {\n remaining.push(edge);\n }\n }\n edges = remaining;\n }\n\n return { seeds: result.seeds, visited, edges };\n}\n\nexport interface PathResult {\n from: NodeMatch;\n to: NodeMatch;\n found: boolean;\n path: string[];\n edges: TraversalEdge[];\n}\n\n/** Shortest path between the nodes that best match `fromQuery` and `toQuery` (undirected BFS — connectivity, not call direction). */\nexport function shortestPath(graph: Graph, fromQuery: string, toQuery: string): PathResult | null {\n const from = resolveNode(graph, fromQuery);\n const to = resolveNode(graph, toQuery);\n if (!from || !to) return null;\n\n if (from.id === to.id) {\n return { from, to, found: true, path: [from.id], edges: [] };\n }\n\n const predecessor = new Map<string, string>();\n const visited = new Set<string>([from.id]);\n const queue: string[] = [from.id];\n\n while (queue.length > 0) {\n const current = queue.shift() as string;\n if (current === to.id) break;\n const neighbors = [...graph.neighbors(current)].sort((a, b) => a.localeCompare(b));\n for (const neighbor of neighbors) {\n if (visited.has(neighbor)) continue;\n visited.add(neighbor);\n predecessor.set(neighbor, current);\n queue.push(neighbor);\n }\n }\n\n if (!visited.has(to.id)) {\n return { from, to, found: false, path: [], edges: [] };\n }\n\n const path: string[] = [to.id];\n let cursor = to.id;\n while (cursor !== from.id) {\n const prev = predecessor.get(cursor);\n if (!prev) break;\n path.unshift(prev);\n cursor = prev;\n }\n\n const edges: TraversalEdge[] = [];\n for (let i = 0; i < path.length - 1; i++) {\n const a = path[i] as string;\n const b = path[i + 1] as string;\n const key = graph.edges(a, b)[0] ?? graph.edges(b, a)[0];\n if (key) {\n const attrs = graph.getEdgeAttributes(key);\n edges.push({ source: a, target: b, relation: String(attrs.relation), confidence: String(attrs.confidence) });\n }\n }\n\n return { from, to, found: true, path, edges };\n}\n\nexport interface ExplainResult {\n id: string;\n label: string;\n sourceFile: string;\n sourceLocation: string;\n communityLabel?: string;\n outgoing: TraversalEdge[];\n incoming: TraversalEdge[];\n}\n\n/** Plain-language-ready explanation of the node that best matches `query`. */\nexport function explainNode(graph: Graph, query: string): ExplainResult | null {\n const match = resolveNode(graph, query);\n if (!match) return null;\n\n const attrs = graph.getNodeAttributes(match.id);\n const outgoing: TraversalEdge[] = [];\n const incoming: TraversalEdge[] = [];\n\n graph.forEachOutEdge(match.id, (_edge, edgeAttrs, source, target) => {\n outgoing.push({ source, target, relation: String(edgeAttrs.relation), confidence: String(edgeAttrs.confidence) });\n });\n graph.forEachInEdge(match.id, (_edge, edgeAttrs, source, target) => {\n incoming.push({ source, target, relation: String(edgeAttrs.relation), confidence: String(edgeAttrs.confidence) });\n });\n\n outgoing.sort((a, b) => a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation));\n incoming.sort((a, b) => a.source.localeCompare(b.source) || a.relation.localeCompare(b.relation));\n\n return {\n id: match.id,\n label: match.label,\n sourceFile: (attrs.sourceFile as string | undefined) ?? '',\n sourceLocation: (attrs.sourceLocation as string | undefined) ?? '',\n communityLabel: attrs.communityLabel as string | undefined,\n outgoing,\n incoming,\n };\n}\n","import type Graph from 'graphology';\nimport { resolveNode, type NodeMatch } from './query.js';\nimport type { Confidence, Relation } from './types.js';\n\n/**\n * Reverse impact analysis — \"what breaks if I change X\". Walks *incoming*\n * dependency edges (who calls / imports / inherits from the target)\n * transitively, so depth 1 is the direct blast radius and deeper levels are\n * ripple effects. Like everything in query.ts this is lexical + structural,\n * fully offline and deterministic.\n */\n\n/**\n * Relations where `source --rel--> target` means \"source depends on target\",\n * i.e. changing the target can break the source. `contains`/`method` are\n * included because changing an entity plausibly affects its container file\n * or class signature consumers see.\n */\nconst DEPENDENCY_RELATIONS: ReadonlySet<Relation> = new Set([\n 'calls',\n 'imports',\n 'imports_from',\n 'inherits',\n 'implements',\n 'mixes_in',\n 'embeds',\n 'references',\n 're_exports',\n 'method',\n 'contains',\n] satisfies Relation[]);\n\nexport interface AffectedNode {\n id: string;\n label: string;\n sourceFile: string;\n sourceLocation: string;\n /** 1 = depends on the target directly, 2 = one step removed, ... */\n depth: number;\n /** The dependency edge that pulled this node in (this node -> something already affected). */\n via: {\n relation: Relation;\n confidence: Confidence;\n /** The already-affected node this one depends on. */\n dependsOn: string;\n };\n}\n\nexport interface ImpactResult {\n target: NodeMatch;\n affected: AffectedNode[];\n /** How many affected nodes there are per confidence tier of the edge that pulled each one in. */\n byConfidence: Record<Confidence, number>;\n maxDepth: number;\n truncated: boolean;\n}\n\nexport interface ImpactOptions {\n /** How many reverse hops to follow (default 3). */\n maxDepth?: number;\n /** Hard cap on affected nodes reported (default 200). */\n limit?: number;\n}\n\nconst DEFAULT_IMPACT_DEPTH = 3;\nconst DEFAULT_IMPACT_LIMIT = 200;\n\nconst CONFIDENCE_RANK: Record<Confidence, number> = { EXTRACTED: 3, INFERRED: 2, AMBIGUOUS: 1 };\n\n/**\n * Resolve `nodeQuery` to its best-matching node, then reverse-BFS over\n * incoming dependency edges. Returns null when nothing in the graph matches\n * the query at all (same contract as explainNode()).\n */\nexport function affectedBy(graph: Graph, nodeQuery: string, options: ImpactOptions = {}): ImpactResult | null {\n const target = resolveNode(graph, nodeQuery);\n if (!target) return null;\n\n const maxDepth = options.maxDepth ?? DEFAULT_IMPACT_DEPTH;\n const limit = options.limit ?? DEFAULT_IMPACT_LIMIT;\n\n const affected: AffectedNode[] = [];\n const visited = new Set<string>([target.id]);\n let frontier: string[] = [target.id];\n let truncated = false;\n\n for (let depth = 1; depth <= maxDepth && frontier.length > 0 && !truncated; depth++) {\n // Collect every dependent of the current frontier before descending, so\n // each node's reported depth is its *shortest* reverse distance.\n const nextFrontier = new Map<string, AffectedNode>();\n\n for (const current of [...frontier].sort((a, b) => a.localeCompare(b))) {\n graph.forEachInEdge(current, (_edge, edgeAttrs, source) => {\n if (visited.has(source)) return;\n const relation = edgeAttrs.relation as Relation;\n if (!DEPENDENCY_RELATIONS.has(relation)) return;\n\n const confidence = edgeAttrs.confidence as Confidence;\n const existing = nextFrontier.get(source);\n // Same node reachable via several edges this round: keep the\n // strongest-confidence one, mirroring buildGraph()'s merge rule.\n if (existing && CONFIDENCE_RANK[existing.via.confidence] >= CONFIDENCE_RANK[confidence]) return;\n\n const attrs = graph.getNodeAttributes(source);\n nextFrontier.set(source, {\n id: source,\n label: (attrs.label as string | undefined) ?? source,\n sourceFile: (attrs.sourceFile as string | undefined) ?? '',\n sourceLocation: (attrs.sourceLocation as string | undefined) ?? '',\n depth,\n via: { relation, confidence, dependsOn: current },\n });\n });\n }\n\n const roundNodes = [...nextFrontier.values()].sort((a, b) => a.id.localeCompare(b.id));\n for (const node of roundNodes) {\n if (affected.length >= limit) {\n truncated = true;\n break;\n }\n visited.add(node.id);\n affected.push(node);\n }\n frontier = roundNodes.filter((n) => visited.has(n.id)).map((n) => n.id);\n }\n\n const byConfidence: Record<Confidence, number> = { EXTRACTED: 0, INFERRED: 0, AMBIGUOUS: 0 };\n for (const node of affected) byConfidence[node.via.confidence] += 1;\n\n return { target, affected, byConfidence, maxDepth, truncated };\n}\n","import type Graph from 'graphology';\nimport { scoreNodes } from './query.js';\n\n/**\n * `graphify context` — the working-set pack. Instead of returning node\n * names for the agent to chase (query -> then read whole files anyway),\n * this fuses the two steps: the graph knows every entity's file and line,\n * so rank the nodes relevant to the task, read just the relevant line\n * ranges, and pack the actual code into a token budget. One call returns\n * the code an agent needs to start a task.\n */\n\nexport interface ContextSnippet {\n nodeId: string;\n label: string;\n file: string;\n startLine: number;\n endLine: number;\n code: string;\n /** Why this snippet is in the pack (lexical match / neighbor-of relation). */\n reason: string;\n score: number;\n}\n\nexport interface ContextPack {\n task: string;\n snippets: ContextSnippet[];\n /** Approximate tokens used out of the budget. */\n tokens: number;\n tokenBudget: number;\n /** Ranked nodes that didn't fit the budget — the agent can pull them explicitly. */\n overflow: Array<{ nodeId: string; file: string }>;\n}\n\nexport interface ContextOptions {\n /** Approximate token cap for the pack (default 4000). */\n tokenBudget?: number;\n maxSeeds?: number;\n /** Cap on snippet length in lines (default 60). */\n maxSnippetLines?: number;\n}\n\nexport type FileReader = (path: string) => Promise<string>;\n\nconst DEFAULT_CONTEXT_BUDGET = 4000;\nconst DEFAULT_MAX_SEEDS = 8;\nconst DEFAULT_MAX_SNIPPET_LINES = 60;\n/** A neighbor inherits this fraction of the score of the node that pulled it in. */\nconst NEIGHBOR_DECAY = 0.4;\n\nconst tokensOf = (text: string): number => Math.ceil(text.length / 4);\n\nfunction lineNumberOf(sourceLocation: string): number | null {\n const match = /^L(\\d+)$/.exec(sourceLocation);\n return match ? Number(match[1]) : null;\n}\n\nfunction isReadableFile(sourceFile: string): boolean {\n return sourceFile !== '' && !sourceFile.startsWith('<') && !sourceFile.includes('://');\n}\n\ninterface RankedNode {\n id: string;\n score: number;\n reason: string;\n}\n\n/**\n * Rank nodes for the task: lexical seeds first (their match score), then\n * their graph neighbors at a decayed score, labeled with the relation that\n * connects them. Deterministic (score desc, id asc).\n */\nexport function rankForTask(graph: Graph, task: string, maxSeeds = DEFAULT_MAX_SEEDS): RankedNode[] {\n const seeds = scoreNodes(graph, task).slice(0, maxSeeds);\n const ranked = new Map<string, RankedNode>();\n for (const seed of seeds) {\n ranked.set(seed.id, { id: seed.id, score: seed.score, reason: 'matches the task' });\n }\n\n for (const seed of seeds) {\n graph.forEachEdge(seed.id, (_edge, attrs, source, target) => {\n const neighbor = source === seed.id ? target : source;\n if (ranked.has(neighbor)) return;\n const relation = String(attrs.relation);\n const direction = source === seed.id ? `${relation} ->` : `<- ${relation}`;\n ranked.set(neighbor, {\n id: neighbor,\n score: seed.score * NEIGHBOR_DECAY,\n reason: `${direction} ${seed.label}`,\n });\n });\n }\n\n return [...ranked.values()].sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n}\n\n/**\n * Extract the snippet for a node: from its declaration line to just before\n * the next known entity in the same file (capped), so snippets align with\n * real code block boundaries without needing a parser here.\n */\nfunction snippetRange(\n startLine: number,\n fileLineCount: number,\n entityStartsInFile: number[],\n maxLines: number,\n): { start: number; end: number } {\n const nextStart = entityStartsInFile.find((l) => l > startLine);\n const hardEnd = nextStart !== undefined ? nextStart - 1 : fileLineCount;\n return { start: startLine, end: Math.min(hardEnd, startLine + maxLines - 1) };\n}\n\nexport async function buildContextPack(\n graph: Graph,\n task: string,\n readFile: FileReader,\n options: ContextOptions = {},\n): Promise<ContextPack> {\n const tokenBudget = options.tokenBudget ?? DEFAULT_CONTEXT_BUDGET;\n const maxSnippetLines = options.maxSnippetLines ?? DEFAULT_MAX_SNIPPET_LINES;\n const ranked = rankForTask(graph, task, options.maxSeeds);\n\n // Every known entity start line per file — used to end snippets at the\n // next declaration instead of an arbitrary window.\n const entityStarts = new Map<string, number[]>();\n graph.forEachNode((_id, attrs) => {\n const file = attrs.sourceFile as string | undefined;\n const line = lineNumberOf((attrs.sourceLocation as string | undefined) ?? '');\n if (file && line !== null) {\n const starts = entityStarts.get(file) ?? [];\n starts.push(line);\n entityStarts.set(file, starts);\n }\n });\n for (const starts of entityStarts.values()) starts.sort((a, b) => a - b);\n\n const fileCache = new Map<string, string[] | null>();\n const readLines = async (file: string): Promise<string[] | null> => {\n const cached = fileCache.get(file);\n if (cached !== undefined) return cached;\n let lines: string[] | null;\n try {\n lines = (await readFile(file)).split('\\n');\n } catch {\n lines = null;\n }\n fileCache.set(file, lines);\n return lines;\n };\n\n const snippets: ContextSnippet[] = [];\n const overflow: Array<{ nodeId: string; file: string }> = [];\n const coveredRanges = new Map<string, Array<{ start: number; end: number }>>();\n let tokens = 0;\n\n for (const node of ranked) {\n const attrs = graph.getNodeAttributes(node.id);\n const file = (attrs.sourceFile as string | undefined) ?? '';\n const startLine = lineNumberOf((attrs.sourceLocation as string | undefined) ?? '');\n if (!isReadableFile(file) || startLine === null) continue;\n\n const lines = await readLines(file);\n if (lines === null) continue;\n\n const { start, end } = snippetRange(startLine, lines.length, entityStarts.get(file) ?? [], maxSnippetLines);\n\n // Skip if an already-packed snippet from the same file covers this range.\n const covered = (coveredRanges.get(file) ?? []).some((r) => start >= r.start && end <= r.end);\n if (covered) continue;\n\n const code = lines.slice(start - 1, end).join('\\n');\n const cost = tokensOf(code) + 15; // header overhead\n if (tokens + cost > tokenBudget) {\n overflow.push({ nodeId: node.id, file: `${file}:L${startLine}` });\n continue;\n }\n\n tokens += cost;\n snippets.push({\n nodeId: node.id,\n label: (attrs.label as string | undefined) ?? node.id,\n file,\n startLine: start,\n endLine: end,\n code,\n reason: node.reason,\n score: node.score,\n });\n const ranges = coveredRanges.get(file) ?? [];\n ranges.push({ start, end });\n coveredRanges.set(file, ranges);\n }\n\n return { task, snippets, tokens, tokenBudget, overflow };\n}\n\n/** Render a pack as agent-ready markdown. */\nexport function renderContextPack(pack: ContextPack): string {\n const lines: string[] = [\n `# Context pack: ${pack.task}`,\n '',\n `_~${pack.tokens} of ${pack.tokenBudget} token budget, ${pack.snippets.length} snippet(s)._`,\n '',\n ];\n\n if (pack.snippets.length === 0) {\n lines.push('No matching code found — try different keywords.');\n return lines.join('\\n');\n }\n\n for (const snippet of pack.snippets) {\n lines.push(`## ${snippet.label} — \\`${snippet.file}:L${snippet.startLine}-L${snippet.endLine}\\``);\n lines.push(`_${snippet.reason}_`);\n lines.push('```');\n lines.push(snippet.code);\n lines.push('```');\n lines.push('');\n }\n\n if (pack.overflow.length > 0) {\n lines.push(`## Didn't fit the budget (${pack.overflow.length})`);\n for (const item of pack.overflow.slice(0, 15)) {\n lines.push(`- ${item.nodeId} (${item.file})`);\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","import type Graph from 'graphology';\nimport { affectedBy } from './impact.js';\nimport { resolveNode } from './query.js';\n\n/**\n * `graphify tests` — structural test selection. Coverage tools need\n * instrumentation and a full test run to know what covers what; the graph\n * already knows, statically: a test file imports/calls the code it\n * exercises, so the test files inside a change's reverse blast radius are\n * exactly the ones worth running. Cross-language, no instrumentation.\n */\n\n/** Test-file naming conventions across the supported languages. */\nconst TEST_FILE_PATTERNS: RegExp[] = [\n /(^|\\/)tests?\\//, // tests/ or test/ directory\n /(^|\\/)__tests__\\//,\n /(^|\\/)spec\\//,\n /\\.test\\.[cm]?[jt]sx?$/,\n /\\.spec\\.[cm]?[jt]sx?$/,\n /(^|\\/)test_[^/]+\\.py$/,\n /_test\\.py$/,\n /_test\\.go$/,\n /Tests?\\.(java|cs)$/,\n /_spec\\.rb$/,\n /_test\\.rb$/,\n];\n\nexport function isTestFile(path: string): boolean {\n return TEST_FILE_PATTERNS.some((p) => p.test(path));\n}\n\nexport interface TestSelection {\n /** What the selection was computed for (resolved node id, or the changed files). */\n target: string;\n /** Unique test files, most directly affected first. */\n testFiles: Array<{ file: string; depth: number; via: string }>;\n /** How many non-test nodes were in the blast radius (context for confidence). */\n affectedNodeCount: number;\n}\n\nconst TEST_REACH_DEPTH = 4;\nconst TEST_REACH_LIMIT = 2000;\n\nfunction selectionFromImpact(\n graph: Graph,\n targetIds: string[],\n targetLabel: string,\n): TestSelection {\n const best = new Map<string, { depth: number; via: string }>();\n let affectedNodeCount = 0;\n\n for (const id of targetIds) {\n const impact = affectedBy(graph, id, { maxDepth: TEST_REACH_DEPTH, limit: TEST_REACH_LIMIT });\n if (!impact) continue;\n affectedNodeCount += impact.affected.length;\n for (const node of impact.affected) {\n if (!isTestFile(node.sourceFile)) continue;\n const existing = best.get(node.sourceFile);\n if (!existing || node.depth < existing.depth) {\n best.set(node.sourceFile, { depth: node.depth, via: node.via.dependsOn });\n }\n }\n // The target might itself be inside a test file's blast radius via the\n // file node too — affectedBy already walks contains edges, so imports\n // from test files reach here.\n }\n\n const testFiles = [...best.entries()]\n .map(([file, info]) => ({ file, depth: info.depth, via: info.via }))\n .sort((a, b) => a.depth - b.depth || a.file.localeCompare(b.file));\n\n return { target: targetLabel, testFiles, affectedNodeCount };\n}\n\n/** Test files reachable (reverse) from the node best matching `nodeQuery`. Null if nothing matches. */\nexport function testsForNode(graph: Graph, nodeQuery: string): TestSelection | null {\n const match = resolveNode(graph, nodeQuery);\n if (!match) return null;\n return selectionFromImpact(graph, [match.id], match.id);\n}\n\n/**\n * Test files reachable from any of the given changed files (as reported by\n * `git diff --name-only`). Changed test files select themselves. Unknown\n * files (not in the graph) are skipped.\n */\nexport function testsForChangedFiles(graph: Graph, changedFiles: string[]): TestSelection {\n const fileIds: string[] = [];\n const selfSelected = new Map<string, { depth: number; via: string }>();\n\n for (const file of changedFiles) {\n if (isTestFile(file)) {\n selfSelected.set(file, { depth: 0, via: '(changed directly)' });\n continue;\n }\n if (graph.hasNode(file)) fileIds.push(file);\n }\n\n const selection = selectionFromImpact(graph, fileIds, changedFiles.join(', '));\n for (const [file, info] of selfSelected) {\n if (!selection.testFiles.some((t) => t.file === file)) {\n selection.testFiles.push({ file, depth: info.depth, via: info.via });\n }\n }\n selection.testFiles.sort((a, b) => a.depth - b.depth || a.file.localeCompare(b.file));\n return selection;\n}\n"],"mappings":";;;;;AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,OAAO,WAAW;AASlB,eAAsB,UAAU,SAAsB,UAAK,QAAQ,IAAI,GAAG,cAAc,GAAmB;AACzG,QAAM,WAAW,kBAAkB,cAAc,MAAM;AACvD,QAAM,MAAM,MAAS,YAAS,UAAU,OAAO;AAC/C,QAAM,OAAgB,KAAK,MAAM,GAAG;AACpC,SAAO,MAAM,KAAK,IAAwC;AAC5D;;;ACPA,IAAM,YAAY,oBAAI,IAAI;AAAA,EACxB;AAAA,EAAK;AAAA,EAAM;AAAA,EAAO;AAAA,EAAM;AAAA,EAAO;AAAA,EAAO;AAAA,EAAQ;AAAA,EAAM;AAAA,EAAQ;AAAA,EAAO;AAAA,EACnE;AAAA,EAAQ;AAAA,EAAS;AAAA,EAAQ;AAAA,EAAO;AAAA,EAAO;AAAA,EAAS;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAClE;AAAA,EAAO;AAAA,EAAO;AAAA,EAAM;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAM;AAAA,EAAQ;AACpD,CAAC;AAGD,SAAS,eAAe,MAAsB;AAC5C,SAAO,KACJ,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,yBAAyB,OAAO;AAC7C;AAEA,SAAS,SAAS,MAAwB;AACxC,SAAO,eAAe,IAAI,EACvB,YAAY,EACZ,MAAM,YAAY,EAClB,OAAO,CAAC,UAAU,MAAM,SAAS,KAAK,CAAC,UAAU,IAAI,KAAK,CAAC;AAChE;AAQA,SAAS,YAAY,MAAwB;AAC3C,SAAO,eAAe,IAAI,EACvB,YAAY,EACZ,MAAM,YAAY,EAClB,OAAO,CAAC,UAAU,MAAM,SAAS,CAAC;AACvC;AAGA,IAA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