@fabersep/atlas 0.0.0-stage → 0.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.
Files changed (155) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/LICENSE +202 -0
  3. package/README.md +175 -2
  4. package/dist/packs/csharp/calls.d.ts +4 -0
  5. package/dist/packs/csharp/calls.js +167 -0
  6. package/dist/packs/csharp/declarations.d.ts +4 -0
  7. package/dist/packs/csharp/declarations.js +142 -0
  8. package/dist/packs/csharp/pack.d.ts +2 -0
  9. package/dist/packs/csharp/pack.js +39 -0
  10. package/dist/packs/csharp/resolve.d.ts +2 -0
  11. package/dist/packs/csharp/resolve.js +35 -0
  12. package/dist/packs/csharp/signals.d.ts +7 -0
  13. package/dist/packs/csharp/signals.js +143 -0
  14. package/dist/packs/dart/calls.d.ts +4 -0
  15. package/dist/packs/dart/calls.js +130 -0
  16. package/dist/packs/dart/declarations.d.ts +11 -0
  17. package/dist/packs/dart/declarations.js +79 -0
  18. package/dist/packs/dart/members.d.ts +4 -0
  19. package/dist/packs/dart/members.js +62 -0
  20. package/dist/packs/dart/pack.d.ts +2 -0
  21. package/dist/packs/dart/pack.js +37 -0
  22. package/dist/packs/dart/resolve.d.ts +2 -0
  23. package/dist/packs/dart/resolve.js +32 -0
  24. package/dist/packs/index.d.ts +3 -0
  25. package/dist/packs/index.js +8 -0
  26. package/dist/packs/json/pack.d.ts +2 -0
  27. package/dist/packs/json/pack.js +27 -0
  28. package/dist/packs/msbuild/pack.d.ts +2 -0
  29. package/dist/packs/msbuild/pack.js +75 -0
  30. package/dist/packs/msbuild/xml.d.ts +16 -0
  31. package/dist/packs/msbuild/xml.js +123 -0
  32. package/dist/packs/typescript/calls.d.ts +4 -0
  33. package/dist/packs/typescript/calls.js +208 -0
  34. package/dist/packs/typescript/declarations.d.ts +9 -0
  35. package/dist/packs/typescript/declarations.js +74 -0
  36. package/dist/packs/typescript/members.d.ts +4 -0
  37. package/dist/packs/typescript/members.js +92 -0
  38. package/dist/packs/typescript/pack.d.ts +2 -0
  39. package/dist/packs/typescript/pack.js +53 -0
  40. package/dist/packs/typescript/resolve.d.ts +2 -0
  41. package/dist/packs/typescript/resolve.js +68 -0
  42. package/dist/packs/typescript/signals.d.ts +7 -0
  43. package/dist/packs/typescript/signals.js +310 -0
  44. package/dist/packs/yaml/pack.d.ts +2 -0
  45. package/dist/packs/yaml/pack.js +35 -0
  46. package/dist/src/cli.d.ts +2 -0
  47. package/dist/src/cli.js +477 -0
  48. package/dist/src/context/pre-grep.d.ts +15 -0
  49. package/dist/src/context/pre-grep.js +79 -0
  50. package/dist/src/context/pre-invoke.d.ts +20 -0
  51. package/dist/src/context/pre-invoke.js +127 -0
  52. package/dist/src/context/pre-prompt.d.ts +16 -0
  53. package/dist/src/context/pre-prompt.js +66 -0
  54. package/dist/src/context/session.d.ts +17 -0
  55. package/dist/src/context/session.js +57 -0
  56. package/dist/src/graph/build.d.ts +17 -0
  57. package/dist/src/graph/build.js +41 -0
  58. package/dist/src/graph/metrics.d.ts +12 -0
  59. package/dist/src/graph/metrics.js +75 -0
  60. package/dist/src/graph/topology.d.ts +5 -0
  61. package/dist/src/graph/topology.js +54 -0
  62. package/dist/src/health/compare.d.ts +2 -0
  63. package/dist/src/health/compare.js +38 -0
  64. package/dist/src/health/duplicates.d.ts +11 -0
  65. package/dist/src/health/duplicates.js +66 -0
  66. package/dist/src/health/health.d.ts +12 -0
  67. package/dist/src/health/health.js +94 -0
  68. package/dist/src/health/types.d.ts +101 -0
  69. package/dist/src/health/types.js +5 -0
  70. package/dist/src/index.d.ts +25 -0
  71. package/dist/src/index.js +22 -0
  72. package/dist/src/init/init.d.ts +104 -0
  73. package/dist/src/init/init.js +499 -0
  74. package/dist/src/init/scout.d.ts +45 -0
  75. package/dist/src/init/scout.js +217 -0
  76. package/dist/src/jsonc.d.ts +5 -0
  77. package/dist/src/jsonc.js +34 -0
  78. package/dist/src/mcp/server.d.ts +398 -0
  79. package/dist/src/mcp/server.js +543 -0
  80. package/dist/src/metrics/doctor.d.ts +15 -0
  81. package/dist/src/metrics/doctor.js +125 -0
  82. package/dist/src/metrics/log.d.ts +43 -0
  83. package/dist/src/metrics/log.js +101 -0
  84. package/dist/src/metrics/stats.d.ts +43 -0
  85. package/dist/src/metrics/stats.js +172 -0
  86. package/dist/src/model.d.ts +178 -0
  87. package/dist/src/model.js +2 -0
  88. package/dist/src/outputs.d.ts +16 -0
  89. package/dist/src/outputs.js +48 -0
  90. package/dist/src/packs/calls.d.ts +9 -0
  91. package/dist/src/packs/calls.js +119 -0
  92. package/dist/src/packs/dataShape.d.ts +6 -0
  93. package/dist/src/packs/dataShape.js +54 -0
  94. package/dist/src/packs/pack.d.ts +51 -0
  95. package/dist/src/packs/pack.js +3 -0
  96. package/dist/src/packs/packFiles.d.ts +5 -0
  97. package/dist/src/packs/packFiles.js +12 -0
  98. package/dist/src/packs/symbols.d.ts +39 -0
  99. package/dist/src/packs/symbols.js +98 -0
  100. package/dist/src/packs/treeSitter.d.ts +8 -0
  101. package/dist/src/packs/treeSitter.js +107 -0
  102. package/dist/src/queries/flow.d.ts +42 -0
  103. package/dist/src/queries/flow.js +398 -0
  104. package/dist/src/queries/investigate.d.ts +43 -0
  105. package/dist/src/queries/investigate.js +216 -0
  106. package/dist/src/queries/map.d.ts +28 -0
  107. package/dist/src/queries/map.js +102 -0
  108. package/dist/src/queries/neighborhood.d.ts +35 -0
  109. package/dist/src/queries/neighborhood.js +60 -0
  110. package/dist/src/queries/search.d.ts +37 -0
  111. package/dist/src/queries/search.js +279 -0
  112. package/dist/src/scan/audit.d.ts +2 -0
  113. package/dist/src/scan/audit.js +41 -0
  114. package/dist/src/scan/records.d.ts +12 -0
  115. package/dist/src/scan/records.js +42 -0
  116. package/dist/src/scan/resolveImports.d.ts +3 -0
  117. package/dist/src/scan/resolveImports.js +47 -0
  118. package/dist/src/scan/roles.d.ts +5 -0
  119. package/dist/src/scan/roles.js +87 -0
  120. package/dist/src/scan/scan.d.ts +24 -0
  121. package/dist/src/scan/scan.js +72 -0
  122. package/dist/src/text/briefs.d.ts +13 -0
  123. package/dist/src/text/briefs.js +43 -0
  124. package/dist/src/text/collapse.d.ts +10 -0
  125. package/dist/src/text/collapse.js +58 -0
  126. package/dist/src/text/declarations.d.ts +12 -0
  127. package/dist/src/text/declarations.js +120 -0
  128. package/dist/src/text/structure.d.ts +2 -0
  129. package/dist/src/text/structure.js +15 -0
  130. package/dist/src/text/tree.d.ts +20 -0
  131. package/dist/src/text/tree.js +49 -0
  132. package/dist/src/tokens.d.ts +4 -0
  133. package/dist/src/tokens.js +9 -0
  134. package/dist/src/version.d.ts +10 -0
  135. package/dist/src/version.js +11 -0
  136. package/dist/src/walk/ignoreRules.d.ts +17 -0
  137. package/dist/src/walk/ignoreRules.js +72 -0
  138. package/dist/src/walk/walk.d.ts +11 -0
  139. package/dist/src/walk/walk.js +29 -0
  140. package/grammars/LICENSE-tree-sitter-dart +20 -0
  141. package/grammars/README.md +11 -0
  142. package/grammars/tree-sitter-dart.wasm +0 -0
  143. package/package.json +68 -4
  144. package/packs/csharp/README.md +9 -0
  145. package/packs/csharp/imports.scm +3 -0
  146. package/packs/csharp/symbols.scm +17 -0
  147. package/packs/dart/imports.scm +5 -0
  148. package/packs/dart/symbols.scm +13 -0
  149. package/packs/msbuild/README.md +11 -0
  150. package/packs/typescript/exports.scm +16 -0
  151. package/packs/typescript/imports.scm +9 -0
  152. package/packs/typescript/symbols.scm +19 -0
  153. package/schema/ast_code_map.schema.json +144 -0
  154. package/schema/schema-lock.json +7 -0
  155. package/schema/topology.schema.json +87 -0
@@ -0,0 +1,398 @@
1
+ import { cleanTypeName, fieldTypeMap } from '../packs/calls.js';
2
+ import { CONTAINER_KINDS, FUNCTION_KINDS } from '../packs/symbols.js';
3
+ import { isTestFile } from './map.js';
4
+ export class UnknownSymbolError extends Error {
5
+ }
6
+ function normKey(key) {
7
+ const parts = key.split('.');
8
+ // Strip PascalCase/UPPER enum prefixes (e.g. `JobName.SendReceipt` -> `SendReceipt`),
9
+ // but preserve lowercase dot-namespaced event keys (e.g. `users.suspend` vs `documents.suspend`).
10
+ const target = parts.length > 1 && /^[A-Z]/.test(parts[0]) ? parts[parts.length - 1] : key;
11
+ return target.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
12
+ }
13
+ function simpleType(ref) {
14
+ return ref.replace(/<.*$/s, '').split('.').pop().trim();
15
+ }
16
+ const MEDIATR_HANDLER_RX = /^I(?:Request|Notification)Handler<\s*([^,>\s]+)/;
17
+ class FlowGraph {
18
+ callables = new Map();
19
+ virtuals = new Map();
20
+ containersByName = new Map();
21
+ containersByFileAndName = new Map();
22
+ functionsByName = new Map();
23
+ implsByInterface = new Map();
24
+ eventHandlers = new Map();
25
+ jobHandlers = new Map();
26
+ mediatrHandlers = new Map();
27
+ outgoing = new Map();
28
+ incoming = new Map();
29
+ constructor(map, includeTests) {
30
+ const files = includeTests ? map.files : map.files.filter((f) => !isTestFile(f.path));
31
+ // 1. Index all containers, callables, implements, and virtual handler entrypoints
32
+ for (const record of files) {
33
+ for (const sym of record.symbols) {
34
+ if (CONTAINER_KINDS.has(sym.kind)) {
35
+ this.indexContainer(record, sym);
36
+ }
37
+ else if (FUNCTION_KINDS.has(sym.kind)) {
38
+ this.indexCallable(record, sym, undefined);
39
+ }
40
+ }
41
+ }
42
+ // 2. Index interface implementations and MediatR handlers
43
+ for (const list of this.containersByName.values()) {
44
+ for (const c of list) {
45
+ for (const iface of c.symbol.implements ?? []) {
46
+ const base = simpleType(iface);
47
+ const arr = this.implsByInterface.get(base) ?? [];
48
+ arr.push(c);
49
+ this.implsByInterface.set(base, arr);
50
+ const mediatr = MEDIATR_HANDLER_RX.exec(iface.trim());
51
+ if (mediatr) {
52
+ const cmd = simpleType(mediatr[1]);
53
+ const handle = (c.symbol.members ?? []).find((m) => FUNCTION_KINDS.has(m.kind) && (m.name === 'Handle' || m.name === 'HandleAsync'));
54
+ if (handle) {
55
+ const entry = this.callables.get(`${c.file}#${c.name}.${handle.name}`);
56
+ if (entry) {
57
+ const key = normKey(cmd);
58
+ const handlers = this.mediatrHandlers.get(key) ?? [];
59
+ handlers.push(entry);
60
+ this.mediatrHandlers.set(key, handlers);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+ }
67
+ // 3. Resolve all call sites and implements edges
68
+ for (const entry of this.callables.values()) {
69
+ for (const call of entry.symbol.calls ?? []) {
70
+ this.resolveCallSite(entry, call);
71
+ }
72
+ }
73
+ }
74
+ indexContainer(record, sym) {
75
+ const entry = {
76
+ id: `${record.path}#${sym.name}`,
77
+ name: sym.name,
78
+ file: record.path,
79
+ symbol: sym,
80
+ record,
81
+ fields: fieldTypeMap(sym),
82
+ };
83
+ const list = this.containersByName.get(sym.name) ?? [];
84
+ list.push(entry);
85
+ this.containersByName.set(sym.name, list);
86
+ this.containersByFileAndName.set(`${record.path}#${sym.name}`, entry);
87
+ for (const m of sym.members ?? []) {
88
+ if (FUNCTION_KINDS.has(m.kind))
89
+ this.indexCallable(record, m, sym.name);
90
+ else if (CONTAINER_KINDS.has(m.kind))
91
+ this.indexContainer(record, m);
92
+ }
93
+ }
94
+ indexCallable(record, sym, owner) {
95
+ const label = owner ? `${owner}.${sym.name}` : sym.name;
96
+ const id = `${record.path}#${label}`;
97
+ const entry = { id, label, file: record.path, line: sym.lineStart, owner, symbol: sym, record };
98
+ this.callables.set(id, entry);
99
+ if (!owner) {
100
+ const list = this.functionsByName.get(sym.name) ?? [];
101
+ list.push(entry);
102
+ this.functionsByName.set(sym.name, list);
103
+ }
104
+ for (const ep of sym.entrypoints ?? []) {
105
+ if (ep.startsWith('event:')) {
106
+ const key = normKey(ep.slice('event:'.length));
107
+ const list = this.eventHandlers.get(key) ?? [];
108
+ list.push(entry);
109
+ this.eventHandlers.set(key, list);
110
+ }
111
+ else if (ep.startsWith('job:')) {
112
+ const key = normKey(ep.slice('job:'.length));
113
+ const list = this.jobHandlers.get(key) ?? [];
114
+ list.push(entry);
115
+ this.jobHandlers.set(key, list);
116
+ }
117
+ }
118
+ }
119
+ addEdge(edge) {
120
+ const out = this.outgoing.get(edge.from) ?? [];
121
+ if (!out.some((e) => e.to === edge.to && e.kind === edge.kind)) {
122
+ out.push(edge);
123
+ this.outgoing.set(edge.from, out);
124
+ }
125
+ const inc = this.incoming.get(edge.to) ?? [];
126
+ if (!inc.some((e) => e.from === edge.from && e.kind === edge.kind)) {
127
+ inc.push(edge);
128
+ this.incoming.set(edge.to, inc);
129
+ }
130
+ }
131
+ ensureVirtual(id, label, boundary) {
132
+ if (!this.virtuals.has(id))
133
+ this.virtuals.set(id, { id, label, ...(boundary ? { boundary } : {}) });
134
+ return id;
135
+ }
136
+ /** Looks up a field's type on `container` or any ancestor class along its `extends` chain. */
137
+ resolveFieldType(container, fieldName, visited = new Set()) {
138
+ if (!container || visited.has(container.id))
139
+ return undefined;
140
+ visited.add(container.id);
141
+ const local = container.fields.get(fieldName);
142
+ if (local)
143
+ return local;
144
+ for (const ext of container.symbol.extends ?? []) {
145
+ const parent = this.findContainer(container.record, simpleType(ext));
146
+ const inherited = this.resolveFieldType(parent, fieldName, visited);
147
+ if (inherited)
148
+ return inherited;
149
+ }
150
+ return undefined;
151
+ }
152
+ /** Finds a container by name, preferring files directly imported by `fromRecord`. */
153
+ findContainer(fromRecord, name) {
154
+ const sameFile = this.containersByFileAndName.get(`${fromRecord.path}#${name}`);
155
+ if (sameFile)
156
+ return sameFile;
157
+ const importedTargets = new Set(fromRecord.imports.filter((i) => i.kind === 'file' && i.target).map((i) => i.target));
158
+ const candidates = this.containersByName.get(name);
159
+ if (!candidates?.length)
160
+ return undefined;
161
+ const imported = candidates.find((c) => importedTargets.has(c.file));
162
+ return imported ?? candidates[0];
163
+ }
164
+ /** Finds a method on a container or its `extends` chain. */
165
+ findMethodOnContainer(container, methodName, visited = new Set()) {
166
+ if (visited.has(container.id))
167
+ return undefined;
168
+ visited.add(container.id);
169
+ const direct = this.callables.get(`${container.file}#${container.name}.${methodName}`);
170
+ if (direct)
171
+ return direct;
172
+ for (const ext of container.symbol.extends ?? []) {
173
+ const parent = this.findContainer(container.record, simpleType(ext));
174
+ if (parent) {
175
+ const inherited = this.findMethodOnContainer(parent, methodName, visited);
176
+ if (inherited)
177
+ return inherited;
178
+ }
179
+ }
180
+ return undefined;
181
+ }
182
+ resolveCallSite(from, call) {
183
+ // 1. Virtual async/indirect bridges: events, jobs, MediatR
184
+ if (call.kind === 'emits' && call.targetKey) {
185
+ const vid = this.ensureVirtual(`event:${normKey(call.targetKey)}`, `event:${call.targetKey}`);
186
+ this.addEdge({ from: from.id, to: vid, kind: 'emits', callLine: call.line });
187
+ for (const h of this.eventHandlers.get(normKey(call.targetKey)) ?? []) {
188
+ this.addEdge({ from: vid, to: h.id, kind: 'handles' });
189
+ }
190
+ return;
191
+ }
192
+ if (call.kind === 'queues' && call.targetKey) {
193
+ const vid = this.ensureVirtual(`job:${normKey(call.targetKey)}`, `job:${call.targetKey}`, 'queue');
194
+ this.addEdge({ from: from.id, to: vid, kind: 'queues', callLine: call.line, boundary: 'queue' });
195
+ for (const h of this.jobHandlers.get(normKey(call.targetKey)) ?? []) {
196
+ this.addEdge({ from: vid, to: h.id, kind: 'handles' });
197
+ }
198
+ return;
199
+ }
200
+ if (call.kind === 'sends' && call.targetKey) {
201
+ const vid = this.ensureVirtual(`mediatr:${normKey(call.targetKey)}`, `mediatr:${call.targetKey}`);
202
+ this.addEdge({ from: from.id, to: vid, kind: 'sends', callLine: call.line });
203
+ for (const h of this.mediatrHandlers.get(normKey(call.targetKey)) ?? []) {
204
+ this.addEdge({ from: vid, to: h.id, kind: 'handles' });
205
+ }
206
+ return;
207
+ }
208
+ // 2. Direct member call: resolve receiverType (local, inherited field, or static class name)
209
+ if (call.receiver) {
210
+ const ownerContainer = from.owner ? this.containersByFileAndName.get(`${from.file}#${from.owner}`) : undefined;
211
+ let receiverType = call.receiverType;
212
+ if (!receiverType) {
213
+ if (call.receiver === 'this')
214
+ receiverType = from.owner;
215
+ else
216
+ receiverType = this.resolveFieldType(ownerContainer, call.receiver) ?? cleanTypeName(call.receiver);
217
+ }
218
+ if (receiverType) {
219
+ const targetContainer = this.findContainer(from.record, receiverType);
220
+ if (targetContainer) {
221
+ const targetMethod = this.findMethodOnContainer(targetContainer, call.method);
222
+ if (targetMethod && targetMethod.id !== from.id) {
223
+ this.addEdge({ from: from.id, to: targetMethod.id, kind: 'calls', callLine: call.line, boundary: call.boundary });
224
+ // Follow `implements` edges when calling an interface method
225
+ if (targetContainer.symbol.kind === 'interface') {
226
+ for (const impl of this.implsByInterface.get(targetContainer.name) ?? []) {
227
+ const implMethod = this.findMethodOnContainer(impl, call.method);
228
+ if (implMethod && implMethod.id !== targetMethod.id) {
229
+ this.addEdge({ from: targetMethod.id, to: implMethod.id, kind: 'impl' });
230
+ }
231
+ }
232
+ }
233
+ return;
234
+ }
235
+ }
236
+ }
237
+ // Unresolved call that crosses an external boundary ([db], [http], [queue], [fs])
238
+ if (call.boundary) {
239
+ const vid = this.ensureVirtual(`ext:${call.boundary}:${call.callee}`, `${call.callee}()`, call.boundary);
240
+ this.addEdge({ from: from.id, to: vid, kind: 'calls', callLine: call.line, boundary: call.boundary });
241
+ }
242
+ return;
243
+ }
244
+ // 3. Bare function call: same file -> imported files -> unique match in CodeMap
245
+ const sameFileFn = this.callables.get(`${from.file}#${call.method}`);
246
+ if (sameFileFn && sameFileFn.id !== from.id) {
247
+ this.addEdge({ from: from.id, to: sameFileFn.id, kind: 'calls', callLine: call.line, boundary: call.boundary });
248
+ return;
249
+ }
250
+ const importedTargets = new Set(from.record.imports.filter((i) => i.kind === 'file' && i.target).map((i) => i.target));
251
+ const fns = this.functionsByName.get(call.method);
252
+ if (fns?.length) {
253
+ const imported = fns.find((f) => importedTargets.has(f.file));
254
+ const target = imported ?? (fns.length === 1 ? fns[0] : undefined);
255
+ if (target && target.id !== from.id) {
256
+ this.addEdge({ from: from.id, to: target.id, kind: 'calls', callLine: call.line, boundary: call.boundary });
257
+ return;
258
+ }
259
+ }
260
+ if (call.boundary) {
261
+ const vid = this.ensureVirtual(`ext:${call.boundary}:${call.callee}`, `${call.callee}()`, call.boundary);
262
+ this.addEdge({ from: from.id, to: vid, kind: 'calls', callLine: call.line, boundary: call.boundary });
263
+ }
264
+ }
265
+ /** Matches a user-supplied symbol query (`Class.method`, `file#Class.method`, `event:X`, `job:X`, `Class`, `fn`). */
266
+ resolveQuery(raw) {
267
+ const q = raw.trim();
268
+ if (q.startsWith('event:')) {
269
+ const key = `event:${normKey(q.slice('event:'.length))}`;
270
+ if (this.virtuals.has(key))
271
+ return [key];
272
+ const handlers = this.eventHandlers.get(normKey(q.slice('event:'.length)));
273
+ if (handlers?.length)
274
+ return handlers.map((h) => h.id);
275
+ }
276
+ if (q.startsWith('job:')) {
277
+ const key = `job:${normKey(q.slice('job:'.length))}`;
278
+ if (this.virtuals.has(key))
279
+ return [key];
280
+ const handlers = this.jobHandlers.get(normKey(q.slice('job:'.length)));
281
+ if (handlers?.length)
282
+ return handlers.map((h) => h.id);
283
+ }
284
+ // Exact id: `path#Symbol` or `path:Symbol`
285
+ const normalizedId = q.includes('#') ? q : q.includes(':') ? q.replace(':', '#') : undefined;
286
+ if (normalizedId && this.callables.has(normalizedId))
287
+ return [normalizedId];
288
+ // Exact `Class.method` or `functionName`
289
+ const exactLabel = [...this.callables.values()].filter((c) => c.label === q);
290
+ if (exactLabel.length)
291
+ return exactLabel.map((c) => c.id);
292
+ // Ends with `#Class.method` or `/file.ts#Class.method`
293
+ if (normalizedId) {
294
+ const suffix = [...this.callables.values()].filter((c) => c.id.endsWith(normalizedId));
295
+ if (suffix.length)
296
+ return suffix.map((c) => c.id);
297
+ }
298
+ // Match by bare method name or class name
299
+ const byClass = [...this.callables.values()].filter((c) => c.owner === q && c.symbol.visibility !== 'private');
300
+ if (byClass.length)
301
+ return byClass.map((c) => c.id);
302
+ const byMethod = [...this.callables.values()].filter((c) => c.symbol.name === q);
303
+ if (byMethod.length)
304
+ return byMethod.map((c) => c.id);
305
+ throw new UnknownSymbolError(`Symbol not found in code map: ${raw}`);
306
+ }
307
+ buildTree(nodeId, direction, depth, pathVisited, edge) {
308
+ const callable = this.callables.get(nodeId);
309
+ const virtual = this.virtuals.get(nodeId);
310
+ const base = callable
311
+ ? {
312
+ id: callable.id,
313
+ label: callable.label,
314
+ file: callable.file,
315
+ line: callable.line,
316
+ ...(callable.symbol.entrypoints?.length ? { entrypoints: callable.symbol.entrypoints } : {}),
317
+ ...(callable.symbol.throws?.length ? { throws: callable.symbol.throws } : {}),
318
+ ...(edge?.boundary ? { boundary: edge.boundary } : {}),
319
+ ...(edge ? { edgeKind: edge.kind, ...(edge.callLine ? { callLine: edge.callLine } : {}) } : {}),
320
+ children: [],
321
+ }
322
+ : {
323
+ id: nodeId,
324
+ label: virtual?.label ?? nodeId,
325
+ virtual: true,
326
+ ...(virtual?.boundary || edge?.boundary ? { boundary: virtual?.boundary ?? edge?.boundary } : {}),
327
+ ...(edge ? { edgeKind: edge.kind, ...(edge.callLine ? { callLine: edge.callLine } : {}) } : {}),
328
+ children: [],
329
+ };
330
+ if (pathVisited.has(nodeId)) {
331
+ base.cycle = true;
332
+ return base;
333
+ }
334
+ if (depth <= 0)
335
+ return base;
336
+ const nextVisited = new Set(pathVisited);
337
+ nextVisited.add(nodeId);
338
+ const edges = direction === 'downstream' ? (this.outgoing.get(nodeId) ?? []) : (this.incoming.get(nodeId) ?? []);
339
+ for (const e of edges) {
340
+ const nextId = direction === 'downstream' ? e.to : e.from;
341
+ base.children.push(this.buildTree(nextId, direction, depth - 1, nextVisited, e));
342
+ }
343
+ return base;
344
+ }
345
+ }
346
+ /** Downstream execution flow from `<symbol>` up to `depth` hops. */
347
+ export function flow(map, symbolQuery, options = {}) {
348
+ const depth = options.depth ?? 4;
349
+ const graph = new FlowGraph(map, options.includeTests === true);
350
+ const rootIds = graph.resolveQuery(symbolQuery);
351
+ const roots = rootIds.map((id) => graph.buildTree(id, 'downstream', depth, new Set()));
352
+ return { query: symbolQuery, direction: 'downstream', depth, roots };
353
+ }
354
+ /** Upstream impact (callers and entrypoints reaching `<symbol>`) up to `depth` hops. */
355
+ export function impact(map, symbolQuery, options = {}) {
356
+ const depth = options.depth ?? 4;
357
+ const graph = new FlowGraph(map, options.includeTests === true);
358
+ const rootIds = graph.resolveQuery(symbolQuery);
359
+ const roots = rootIds.map((id) => graph.buildTree(id, 'upstream', depth, new Set()));
360
+ return { query: symbolQuery, direction: 'upstream', depth, roots };
361
+ }
362
+ function formatNodeMeta(node) {
363
+ const parts = [];
364
+ if (node.file && node.line)
365
+ parts.push(`(${node.file}:${node.line})`);
366
+ if (node.entrypoints?.length) {
367
+ const eps = node.entrypoints.length <= 5
368
+ ? node.entrypoints.join(', ')
369
+ : `${node.entrypoints.slice(0, 4).join(', ')}, +${node.entrypoints.length - 4} more`;
370
+ parts.push(`[${eps}]`);
371
+ }
372
+ if (node.throws?.length)
373
+ parts.push(`[throws: ${node.throws.join(', ')}]`);
374
+ if (node.boundary)
375
+ parts.push(`[${node.boundary}]`);
376
+ if (node.cycle)
377
+ parts.push('(cycle)');
378
+ return parts.length ? ` ${parts.join(' ')}` : '';
379
+ }
380
+ function renderFlowNode(node, direction, indent, lines) {
381
+ const arrow = node.edgeKind
382
+ ? direction === 'downstream'
383
+ ? `──${node.edgeKind}──▶ `
384
+ : `◀──${node.edgeKind}── `
385
+ : '';
386
+ lines.push(`${indent}${arrow}${node.label}${formatNodeMeta(node)}`);
387
+ for (const child of node.children) {
388
+ renderFlowNode(child, direction, `${indent} `, lines);
389
+ }
390
+ }
391
+ /** Renders a `flow` or `impact` result as a compact indented tree with `file:line` addresses and edge kinds. */
392
+ export function renderFlow(result) {
393
+ const lines = [];
394
+ for (const root of result.roots) {
395
+ renderFlowNode(root, result.direction, '', lines);
396
+ }
397
+ return lines.join('\n');
398
+ }
@@ -0,0 +1,43 @@
1
+ import type { CodeMap } from '../model.js';
2
+ import { type SearchResult } from './search.js';
3
+ /**
4
+ * One-call deterministic context pack (`investigate`, Feature 03 FR-02).
5
+ * Combines structural search hits, non-trivial flow/impact chains, token-budgeted
6
+ * line-numbered source excerpts, and related test file pointers in a single call.
7
+ */
8
+ export interface InvestigateOptions {
9
+ /** Token budget for the full rendered pack (default: 3000, clamped to 400..16000). */
10
+ budget?: number;
11
+ /** Optional subfolder prefix to restrict search. */
12
+ folder?: string;
13
+ /** Maximum number of search hits to consider (default: 8, clamped to 1..20). */
14
+ limit?: number;
15
+ /** Maximum flow/impact traversal depth (default: 2, clamped to 1..5). */
16
+ depth?: number;
17
+ /** Include test/spec files in search and chains (default: false). */
18
+ includeTests?: boolean;
19
+ }
20
+ export interface InvestigateChain {
21
+ symbol: string;
22
+ flowText?: string;
23
+ impactText?: string;
24
+ }
25
+ export interface InvestigateExcerpt {
26
+ file: string;
27
+ label: string;
28
+ lineStart: number;
29
+ lineEnd: number;
30
+ truncated: boolean;
31
+ code: string;
32
+ }
33
+ export interface InvestigateResult {
34
+ query: string;
35
+ budget: number;
36
+ estimatedTokens: number;
37
+ search: SearchResult;
38
+ chains: InvestigateChain[];
39
+ excerpts: InvestigateExcerpt[];
40
+ relatedTests: string[];
41
+ }
42
+ export declare function investigate(map: CodeMap, root: string, query: string, options?: InvestigateOptions): InvestigateResult;
43
+ export declare function renderInvestigate(result: InvestigateResult): string;
@@ -0,0 +1,216 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { estimateTokens } from '../tokens.js';
4
+ import { flow, impact, renderFlow } from './flow.js';
5
+ import { isTestFile } from './map.js';
6
+ import { renderSearch, search } from './search.js';
7
+ const CALLABLE_KINDS = new Set(['function', 'method', 'constructor', 'getter', 'setter']);
8
+ const MAX_EXCERPT_LINES = 60;
9
+ function hasEdges(res) {
10
+ return res.roots.some((r) => r.children.length > 0);
11
+ }
12
+ function chainQueryForHit(hit) {
13
+ if (CALLABLE_KINDS.has(hit.kind))
14
+ return `${hit.file}#${hit.label}`;
15
+ if (hit.kind === 'class')
16
+ return hit.label;
17
+ return undefined;
18
+ }
19
+ function findRelatedTests(map, hits, maxTests = 6) {
20
+ const matchedFiles = new Set(hits.map((h) => h.file));
21
+ const stems = new Set();
22
+ for (const file of matchedFiles) {
23
+ const base = path.posix.basename(file).replace(/\.[^.]+$/, '').toLowerCase();
24
+ if (base.length >= 4 && base !== 'index')
25
+ stems.add(base);
26
+ }
27
+ const scored = [];
28
+ for (const record of map.files) {
29
+ if (!isTestFile(record.path))
30
+ continue;
31
+ let score = 0;
32
+ for (const imp of record.imports) {
33
+ if (imp.kind === 'file' && imp.target && matchedFiles.has(imp.target)) {
34
+ score += 3;
35
+ }
36
+ }
37
+ const lower = record.path.toLowerCase();
38
+ for (const stem of stems) {
39
+ if (lower.includes(stem))
40
+ score += 1;
41
+ }
42
+ if (score > 0)
43
+ scored.push({ path: record.path, score });
44
+ }
45
+ scored.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
46
+ return scored.slice(0, maxTests).map((s) => s.path);
47
+ }
48
+ function overlaps(ranges, start, end) {
49
+ return ranges.some(([s, e]) => start <= e && end >= s);
50
+ }
51
+ function readExcerpt(root, hit, maxLines, fileCache) {
52
+ let lines = fileCache.get(hit.file);
53
+ if (lines === undefined) {
54
+ const abs = path.join(root, hit.file);
55
+ try {
56
+ lines = fs.readFileSync(abs, 'utf8').split(/\r?\n/);
57
+ }
58
+ catch {
59
+ lines = null;
60
+ }
61
+ fileCache.set(hit.file, lines);
62
+ }
63
+ if (!lines || lines.length === 0)
64
+ return undefined;
65
+ const start = Math.max(1, hit.lineStart);
66
+ const rawEnd = hit.kind === 'file' ? Math.min(lines.length, start + 24) : Math.min(lines.length, Math.max(start, hit.lineEnd));
67
+ const totalLines = rawEnd - start + 1;
68
+ const end = totalLines > maxLines ? start + maxLines - 1 : rawEnd;
69
+ const truncated = end < rawEnd;
70
+ const formatted = [];
71
+ for (let ln = start; ln <= end; ln++) {
72
+ formatted.push(`${ln}: ${lines[ln - 1] ?? ''}`);
73
+ }
74
+ if (truncated) {
75
+ formatted.push(`... (${rawEnd - end} more lines)`);
76
+ }
77
+ return {
78
+ file: hit.file,
79
+ label: hit.label,
80
+ lineStart: start,
81
+ lineEnd: end,
82
+ truncated,
83
+ code: formatted.join('\n'),
84
+ };
85
+ }
86
+ export function investigate(map, root, query, options = {}) {
87
+ const budget = Math.max(400, Math.min(options.budget ?? 3000, 16000));
88
+ const limit = Math.max(1, Math.min(options.limit ?? 8, 20));
89
+ const depth = Math.max(1, Math.min(options.depth ?? 2, 5));
90
+ const includeTests = options.includeTests === true;
91
+ const searchResult = search(map, query, { folder: options.folder, limit, includeTests });
92
+ if (searchResult.hits.length === 0) {
93
+ const empty = {
94
+ query,
95
+ budget,
96
+ estimatedTokens: 0,
97
+ search: searchResult,
98
+ chains: [],
99
+ excerpts: [],
100
+ relatedTests: [],
101
+ };
102
+ empty.estimatedTokens = estimateTokens(renderInvestigate(empty));
103
+ return empty;
104
+ }
105
+ let usedTokens = estimateTokens(renderSearch(searchResult)) + 40;
106
+ const relatedTests = findRelatedTests(map, searchResult.hits);
107
+ if (relatedTests.length) {
108
+ usedTokens += estimateTokens(relatedTests.join('\n')) + 20;
109
+ }
110
+ // 1. Flow / impact chains for up to top 3 distinct callable symbols (within ~35% of budget)
111
+ const chains = [];
112
+ const chainBudget = Math.max(250, Math.floor(budget * 0.35));
113
+ let chainTokens = 0;
114
+ const seenChainKeys = new Set();
115
+ for (const hit of searchResult.hits) {
116
+ if (chains.length >= 3 || chainTokens >= chainBudget)
117
+ break;
118
+ const symQuery = chainQueryForHit(hit);
119
+ if (!symQuery || seenChainKeys.has(symQuery))
120
+ continue;
121
+ seenChainKeys.add(symQuery);
122
+ let flowText;
123
+ let impactText;
124
+ try {
125
+ const f = flow(map, symQuery, { depth, includeTests });
126
+ if (hasEdges(f))
127
+ flowText = renderFlow(f);
128
+ }
129
+ catch {
130
+ // Not in flow graph
131
+ }
132
+ try {
133
+ const imp = impact(map, symQuery, { depth, includeTests });
134
+ if (hasEdges(imp))
135
+ impactText = renderFlow(imp);
136
+ }
137
+ catch {
138
+ // Not in flow graph
139
+ }
140
+ if (!flowText && !impactText)
141
+ continue;
142
+ const cost = estimateTokens((flowText ?? '') + (impactText ?? '')) + 24;
143
+ if (chainTokens + cost > chainBudget && chains.length > 0)
144
+ break;
145
+ if (usedTokens + cost > budget)
146
+ break;
147
+ chains.push({ symbol: hit.label, ...(flowText ? { flowText } : {}), ...(impactText ? { impactText } : {}) });
148
+ chainTokens += cost;
149
+ usedTokens += cost;
150
+ }
151
+ // 2. Line-numbered source excerpts within remaining token budget
152
+ const excerpts = [];
153
+ const covered = new Map();
154
+ const fileCache = new Map();
155
+ for (const hit of searchResult.hits) {
156
+ const remaining = budget - usedTokens;
157
+ if (remaining < 80)
158
+ break;
159
+ const ranges = covered.get(hit.file) ?? [];
160
+ const hitEnd = hit.kind === 'file' ? hit.lineStart + 24 : Math.max(hit.lineStart, hit.lineEnd);
161
+ if (overlaps(ranges, hit.lineStart, hitEnd))
162
+ continue;
163
+ const maxLines = Math.min(MAX_EXCERPT_LINES, Math.max(8, Math.floor(remaining / 12)));
164
+ const excerpt = readExcerpt(root, hit, maxLines, fileCache);
165
+ if (!excerpt)
166
+ continue;
167
+ const cost = estimateTokens(excerpt.code) + 20;
168
+ if (usedTokens + cost > budget && excerpts.length > 0)
169
+ continue;
170
+ excerpts.push(excerpt);
171
+ ranges.push([excerpt.lineStart, excerpt.lineEnd]);
172
+ covered.set(hit.file, ranges);
173
+ usedTokens += cost;
174
+ }
175
+ const result = {
176
+ query,
177
+ budget,
178
+ estimatedTokens: 0,
179
+ search: searchResult,
180
+ chains,
181
+ excerpts,
182
+ relatedTests,
183
+ };
184
+ result.estimatedTokens = estimateTokens(renderInvestigate(result));
185
+ return result;
186
+ }
187
+ export function renderInvestigate(result) {
188
+ if (result.search.hits.length === 0) {
189
+ return `No structural matches for "${result.query}". Try broader keywords, map(zoom=0), or Grep/Read for literal text.`;
190
+ }
191
+ const sections = [
192
+ `## Matches\n${renderSearch(result.search)}`,
193
+ ];
194
+ if (result.chains.length > 0) {
195
+ const chainLines = ['## Chains'];
196
+ for (const c of result.chains) {
197
+ if (c.flowText)
198
+ chainLines.push(`### Flow: ${c.symbol}\n${c.flowText}`);
199
+ if (c.impactText)
200
+ chainLines.push(`### Impact: ${c.symbol}\n${c.impactText}`);
201
+ }
202
+ sections.push(chainLines.join('\n\n'));
203
+ }
204
+ if (result.excerpts.length > 0) {
205
+ const exLines = ['## Code Excerpts'];
206
+ for (const ex of result.excerpts) {
207
+ exLines.push(`### ${ex.label} (${ex.file}:${ex.lineStart}-${ex.lineEnd})\n\`\`\`\n${ex.code}\n\`\`\``);
208
+ }
209
+ sections.push(exLines.join('\n\n'));
210
+ }
211
+ if (result.relatedTests.length > 0) {
212
+ sections.push(`## Related Tests\n${result.relatedTests.map((t) => `- ${t}`).join('\n')}`);
213
+ }
214
+ const body = sections.join('\n\n');
215
+ return `${body}\n\n(investigate pack: ~${estimateTokens(body)}/${result.budget} tokens)`;
216
+ }
@@ -0,0 +1,28 @@
1
+ import type { CodeMap } from '../model.js';
2
+ /**
3
+ * The repo map text of a scanned folder, one of its subfolders, or one file, read from the stored code map (CIN-07).
4
+ * Supports layered zoom levels:
5
+ * - zoom 0: folders/modules with file counts and dominant roles
6
+ * - zoom 1: files + top-level declarations only (no method lists), excluding test files by default
7
+ * - zoom 2: full method-level compact map (default)
8
+ */
9
+ export type ZoomLevel = 0 | 1 | 2;
10
+ export interface MapOptions {
11
+ /** A subfolder or a file of the scanned folder; the whole folder when absent. */
12
+ folder?: string;
13
+ /** Include fields and getters in the one-line summaries (zoom 2). */
14
+ fields?: boolean;
15
+ /** Print every public declaration under its file (the TopologyFULL text) instead of a one-line summary. */
16
+ full?: boolean;
17
+ /** Folder levels to print below the root. */
18
+ depth?: number;
19
+ /** Print the folders only. */
20
+ foldersOnly?: boolean;
21
+ /** Layered zoom level: 0 (modules), 1 (files + top-level symbols), 2 (method-level compact map, default). */
22
+ zoom?: ZoomLevel;
23
+ /** Include test files in zoom 0 and zoom 1 maps (excluded by default). */
24
+ includeTests?: boolean;
25
+ }
26
+ /** Whether a project-relative path looks like a test or spec file. */
27
+ export declare function isTestFile(filePath: string): boolean;
28
+ export declare function renderMap(map: CodeMap, options?: MapOptions): string;