@dimassetoid/septum-mcp 0.3.0 → 0.5.0

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 (129) hide show
  1. package/README.md +38 -55
  2. package/package.json +7 -5
  3. package/src/cli/commands/check.ts +14 -10
  4. package/src/cli/commands/hook.ts +41 -6
  5. package/src/cli/commands/init.ts +10 -1
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +32 -4
  9. package/src/cli/index.ts +7 -0
  10. package/src/cli/templates/hooks.ts +3 -14
  11. package/src/cli/templates/skill.ts +17 -10
  12. package/src/core/boundary/audit.ts +383 -0
  13. package/src/core/boundary/evaluator.ts +251 -114
  14. package/src/core/boundary/staged-auditor.ts +147 -55
  15. package/src/core/config/domain-ownership.ts +6 -4
  16. package/src/core/config/domain-registration.ts +141 -0
  17. package/src/core/config/loader.ts +1 -25
  18. package/src/core/config/schema.ts +24 -36
  19. package/src/core/database/client.ts +2 -0
  20. package/src/core/database/repositories/dependency.repository.ts +334 -572
  21. package/src/core/database/repositories/domain.repository.ts +2 -1
  22. package/src/core/database/repositories/file.repository.ts +10 -0
  23. package/src/core/database/repositories/symbol.repository.ts +97 -398
  24. package/src/core/database/repository.ts +68 -9
  25. package/src/core/database/schema.ts +26 -0
  26. package/src/core/discovery/declarative-routes.ts +69 -0
  27. package/src/core/discovery/framework-detector.ts +149 -0
  28. package/src/core/discovery/navigation.ts +222 -58
  29. package/src/core/discovery/topology-detector.ts +93 -168
  30. package/src/core/errors.ts +19 -0
  31. package/src/core/ingestion/pipeline.ts +287 -88
  32. package/src/core/parser/extractors/base.ts +11 -3
  33. package/src/core/parser/extractors/csharp.ts +2 -2
  34. package/src/core/parser/extractors/django-routing.ts +163 -0
  35. package/src/core/parser/extractors/django-semantic.ts +397 -481
  36. package/src/core/parser/extractors/elysia-semantic.ts +172 -475
  37. package/src/core/parser/extractors/express-semantic.ts +195 -383
  38. package/src/core/parser/extractors/fastapi-semantic.ts +178 -361
  39. package/src/core/parser/extractors/fastify-semantic.ts +216 -717
  40. package/src/core/parser/extractors/flask-semantic.ts +89 -352
  41. package/src/core/parser/extractors/go-routing.ts +344 -0
  42. package/src/core/parser/extractors/go-semantic.ts +205 -562
  43. package/src/core/parser/extractors/go.ts +6 -3
  44. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  45. package/src/core/parser/extractors/hono-semantic.ts +132 -509
  46. package/src/core/parser/extractors/java.ts +2 -2
  47. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  48. package/src/core/parser/extractors/laravel-semantic.ts +143 -335
  49. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  50. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +82 -333
  52. package/src/core/parser/extractors/nestjs-semantic.ts +238 -494
  53. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  54. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  55. package/src/core/parser/extractors/php.ts +1 -1
  56. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  57. package/src/core/parser/extractors/python.ts +5 -9
  58. package/src/core/parser/extractors/registry.ts +2 -0
  59. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  60. package/src/core/parser/extractors/ruby.ts +2 -2
  61. package/src/core/parser/extractors/rust.ts +4 -4
  62. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  63. package/src/core/parser/extractors/symfony-semantic.ts +72 -226
  64. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  65. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  66. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  67. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  68. package/src/core/parser/extractors/typescript.ts +23 -216
  69. package/src/core/parser/language-capabilities.ts +1 -1
  70. package/src/core/parser/schema/providers/laravel-migration-provider.ts +4 -1
  71. package/src/core/parser/wasm-loader.ts +6 -2
  72. package/src/core/resolver/ast-method-tracer.ts +230 -0
  73. package/src/core/resolver/call-graph-helpers.ts +72 -0
  74. package/src/core/resolver/call-graph-tracer.ts +169 -414
  75. package/src/core/resolver/dependency-analysis.ts +593 -0
  76. package/src/core/resolver/import-candidates.ts +120 -0
  77. package/src/core/resolver/import-evidence.ts +88 -0
  78. package/src/core/resolver/import-resolver.ts +60 -7
  79. package/src/core/resolver/interpretation-inputs.ts +60 -2
  80. package/src/core/resolver/languages/python.ts +31 -13
  81. package/src/core/resolver/languages/shared.ts +4 -1
  82. package/src/core/resolver/module-resolver.ts +10 -3
  83. package/src/core/resolver/path-resolver.ts +6 -3
  84. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  85. package/src/core/resolver/slice-catalog.ts +21 -6
  86. package/src/core/resolver/slice-format.ts +13 -0
  87. package/src/core/resolver/slice-selection.ts +237 -0
  88. package/src/core/resolver/symbol-impact.ts +104 -8
  89. package/src/core/resolver/symbol-locator.ts +82 -15
  90. package/src/core/resolver/vertical-slice-tracer.ts +31 -230
  91. package/src/core/resources/ignore.ts +0 -1
  92. package/src/core/resources/limits.ts +2 -1
  93. package/src/core/resources/work-queue.ts +167 -4
  94. package/src/core/retrieval/context-page.ts +11 -4
  95. package/src/core/retrieval/context.ts +363 -226
  96. package/src/{mcp/tools/get-symbol.ts → core/retrieval/source-context.ts} +145 -96
  97. package/src/core/retrieval/symbol-details.ts +453 -0
  98. package/src/core/retrieval/symbol-evidence.ts +3 -3
  99. package/src/core/retrieval/typescript-references.ts +38 -7
  100. package/src/core/retrieval/universal-context.ts +182 -0
  101. package/src/core/telemetry/summary.ts +114 -0
  102. package/src/core/telemetry/telemetry.ts +192 -49
  103. package/src/mcp/formatters/compact-text.ts +439 -0
  104. package/src/mcp/resources-and-prompts.ts +253 -0
  105. package/src/mcp/schemas/boundary.ts +145 -0
  106. package/src/mcp/schemas/map.ts +250 -0
  107. package/src/mcp/schemas/shared.ts +52 -0
  108. package/src/mcp/schemas/slice.ts +60 -0
  109. package/src/mcp/schemas/symbol.ts +268 -0
  110. package/src/mcp/schemas.ts +5 -746
  111. package/src/mcp/server.ts +269 -429
  112. package/src/mcp/tool-catalog.ts +331 -0
  113. package/src/mcp/tools/boundary.ts +68 -3
  114. package/src/mcp/tools/map.ts +104 -4
  115. package/src/mcp/tools/slice.ts +101 -3
  116. package/src/mcp/tools/symbol.ts +469 -17
  117. package/src/mcp/ui/app-client.ts +899 -0
  118. package/src/mcp/ui/app.html +478 -0
  119. package/src/mcp/workflow-playbooks.ts +181 -0
  120. package/src/mcp/workspace-boundary.ts +50 -0
  121. package/src/mcp/workspace-manager.ts +88 -15
  122. package/src/mcp/workspace-watcher.ts +30 -11
  123. package/src/types/index.ts +12 -0
  124. package/src/mcp/tools/check-boundary.ts +0 -382
  125. package/src/mcp/tools/get-domain-catalog.ts +0 -39
  126. package/src/mcp/tools/get-symbol-impact.ts +0 -104
  127. package/src/mcp/tools/locate-symbol.ts +0 -236
  128. package/src/mcp/tools/register-domain.ts +0 -113
  129. package/src/mcp/tools/trace-vertical-slice.ts +0 -106
@@ -12,8 +12,10 @@ import {
12
12
  calculateControlFlowNesting,
13
13
  findBraceBlockEnd,
14
14
  } from "../boundary-tracker.ts";
15
- import { calculateAstControlFlowNesting, getNodeHeader, parseSourceWithTreeSitter } from "../wasm-loader.ts";
15
+ import { getNodeHeader, calculateAstControlFlowNesting, parseSourceWithTreeSitter } from "../wasm-loader.ts";
16
16
  import type { CodeExtractor } from "./base.ts";
17
+ import { extractWithTypeScriptCompiler } from "./typescript-compiler-fallback.ts";
18
+ import { extractTypeScriptFallback } from "./typescript-fallback.ts";
17
19
 
18
20
  const TS_CONTROL_FLOW_NODES = new Set([
19
21
  "if_statement",
@@ -47,6 +49,15 @@ export class TypeScriptExtractor implements CodeExtractor {
47
49
  () => this.extractFallback(content)
48
50
  );
49
51
 
52
+ if (treeSitterResult && treeSitterResult.status !== "degraded") {
53
+ return treeSitterResult;
54
+ }
55
+
56
+ const compilerAst = extractWithTypeScriptCompiler(filePath, content);
57
+ if (compilerAst) {
58
+ return compilerAst;
59
+ }
60
+
50
61
  if (treeSitterResult) {
51
62
  return treeSitterResult;
52
63
  }
@@ -55,209 +66,7 @@ export class TypeScriptExtractor implements CodeExtractor {
55
66
  }
56
67
 
57
68
  private extractFallback(content: string): ParsedFileAST {
58
- const symbols: ExtractedSymbol[] = [];
59
- const dependencies: ExtractedDependency[] = [];
60
-
61
- const rawLines = content.split("\n");
62
- const cleanContent = blankCommentsAndStrings(content);
63
- const cleanLines = cleanContent.split("\n");
64
-
65
- const importRegex =
66
- /^\s*(?:(?:import|export)\s+(?:type\s+)?(?:([\w*\s{},]+)\s+from\s+)?['"]([^'"]+)['"]|(?:const|let|var)\s+([\w\s{},:$]+)\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)|require\s*\(\s*['"]([^'"]+)['"]\s*\))/;
67
-
68
- for (let i = 0; i < rawLines.length; i++) {
69
- if (!cleanLines[i]?.trim()) continue;
70
- const line = rawLines[i];
71
- const match = importRegex.exec(line);
72
- if (match) {
73
- const target = match[2] || match[4] || match[5];
74
- const clause = match[1] || match[3] || "";
75
- if (target) {
76
- const importedSymbols = clause
77
- .replace(/[{}*]/g, " ")
78
- .split(/,|\bas\b/)
79
- .map((s) => s.trim())
80
- .filter((s) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s) && s !== "type");
81
- const isExternal = !target.startsWith(".") && !target.startsWith("/");
82
- dependencies.push({
83
- target,
84
- statement: line.trim(),
85
- line_number: i + 1,
86
- is_external: isExternal,
87
- ...(importedSymbols.length > 0 ? { imported_symbols: Array.from(new Set(importedSymbols)) } : {}),
88
- });
89
- }
90
- }
91
- }
92
-
93
- // 2. Extract Symbols using cleanLines + brace depth tracking
94
- let currentClass: string | null = null;
95
- let currentClassDepth = 0;
96
- let braceDepth = 0;
97
-
98
- for (let i = 0; i < cleanLines.length; i++) {
99
- const cleanTrimmed = cleanLines[i].trim();
100
- const rawTrimmed = rawLines[i].trim();
101
- const lineNum = i + 1;
102
-
103
- if (currentClass && braceDepth < currentClassDepth) {
104
- currentClass = null;
105
- currentClassDepth = 0;
106
- }
107
-
108
- if (cleanTrimmed && braceDepth === 0) {
109
- const classMatch =
110
- /^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?\b(class|interface)\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/.exec(
111
- cleanTrimmed
112
- );
113
- if (classMatch) {
114
- currentClass = classMatch[2];
115
- currentClassDepth = braceDepth + 1;
116
- const endLine = findBraceBlockEnd(cleanLines, i);
117
- symbols.push({
118
- name: classMatch[2],
119
- kind: classMatch[1] as "class" | "interface",
120
- signature: rawTrimmed.replace(/\{$/, "").trim(),
121
- visibility: "public",
122
- line_start: lineNum,
123
- line_end: endLine,
124
- line_count: Math.max(1, endLine - lineNum + 1),
125
- });
126
- } else {
127
- const typeMatch = /^(?:export\s+)?\btype\s+([A-Za-z_$][A-Za-z0-9_$]*)\b\s*=/.exec(cleanTrimmed);
128
- if (typeMatch) {
129
- const endLine = cleanTrimmed.endsWith(";") ? lineNum : findBraceBlockEnd(cleanLines, i);
130
- symbols.push({
131
- name: typeMatch[1],
132
- kind: "type",
133
- signature: rawTrimmed.replace(/;$/, "").trim(),
134
- visibility: "public",
135
- line_start: lineNum,
136
- line_end: endLine,
137
- line_count: Math.max(1, endLine - lineNum + 1),
138
- });
139
- }
140
-
141
- const enumMatch = /^(?:export\s+)?(?:const\s+)?\benum\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/.exec(cleanTrimmed);
142
- if (enumMatch) {
143
- const endLine = findBraceBlockEnd(cleanLines, i);
144
- symbols.push({
145
- name: enumMatch[1],
146
- kind: "enum",
147
- signature: rawTrimmed.replace(/\{$/, "").trim(),
148
- visibility: "public",
149
- line_start: lineNum,
150
- line_end: endLine,
151
- line_count: Math.max(1, endLine - lineNum + 1),
152
- });
153
- }
154
-
155
- const fnMatch =
156
- /^(?:export\s+)?(?:default\s+)?(?:async\s+)?\bfunction\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)(?:\s*:\s*([^;{]+))?/.exec(
157
- cleanTrimmed
158
- );
159
- if (fnMatch) {
160
- const name = fnMatch[1];
161
- const params = fnMatch[2];
162
- const retType = fnMatch[3] ? `: ${fnMatch[3].trim()}` : "";
163
- const endLine = findBraceBlockEnd(cleanLines, i);
164
- const nestingDepth = calculateControlFlowNesting(rawLines, i, endLine - 1);
165
- symbols.push({
166
- name,
167
- kind: "function",
168
- signature: `${name}(${params})${retType}`,
169
- visibility: "public",
170
- line_start: lineNum,
171
- line_end: endLine,
172
- line_count: Math.max(1, endLine - lineNum + 1),
173
- nesting_depth: nestingDepth,
174
- });
175
- }
176
-
177
- const varMatch =
178
- /^(?:export\s+)?\b(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*([^=;]+))?\s*=\s*(.*)$/.exec(
179
- cleanTrimmed
180
- );
181
- if (varMatch) {
182
- const declKind = varMatch[1];
183
- const varName = varMatch[2];
184
- const typeStr = varMatch[3] ? `: ${varMatch[3].trim()}` : "";
185
- const rhs = varMatch[4].trim();
186
- const isArrowOrFn = /^(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$][A-Za-z0-9_$]*)\s*=>|^function\b/.test(rhs);
187
- symbols.push({
188
- name: varName,
189
- kind: isArrowOrFn ? "function" : declKind === "const" ? "constant" : "variable",
190
- signature: `${declKind} ${varName}${typeStr}`,
191
- visibility: cleanTrimmed.startsWith("export ") ? "public" : "private",
192
- line_start: lineNum,
193
- line_end: lineNum,
194
- line_count: 1,
195
- });
196
- }
197
- }
198
- } else if (cleanTrimmed && currentClass && braceDepth === currentClassDepth) {
199
- const methodMatch =
200
- /^(?:(public|protected|private)\s+)?(?:static\s+)?(?:readonly\s+)?(?:async\s+)?\b([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)(?:\s*:\s*([^;{]+))?/.exec(
201
- cleanTrimmed
202
- );
203
- if (
204
- methodMatch &&
205
- !["if", "for", "while", "switch", "catch", "function", "return"].includes(methodMatch[2])
206
- ) {
207
- const vis = (methodMatch[1] as Visibility) || "public";
208
- const name = methodMatch[2];
209
- const params = methodMatch[3];
210
- const retType = methodMatch[4] ? `: ${methodMatch[4].trim()}` : "";
211
- const endLine = findBraceBlockEnd(cleanLines, i);
212
- const nestingDepth = calculateControlFlowNesting(rawLines, i, endLine - 1);
213
- symbols.push({
214
- name: `${currentClass}::${name}`,
215
- kind: "method",
216
- signature: `${vis} ${name}(${params})${retType}`,
217
- visibility: vis,
218
- line_start: lineNum,
219
- line_end: endLine,
220
- line_count: Math.max(1, endLine - lineNum + 1),
221
- nesting_depth: nestingDepth,
222
- });
223
- } else {
224
- const propMatch =
225
- /^(?:(public|protected|private)\s+)?(?:static\s+)?(?:readonly\s+)?\b([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:\?|\!)?\s*(?::\s*([^;={]+))?(?:\s*=[^;]+)?;\s*$/.exec(
226
- cleanTrimmed
227
- );
228
- if (
229
- propMatch &&
230
- !["return", "const", "let", "var", "throw", "import", "export", "continue", "break"].includes(
231
- propMatch[2]
232
- )
233
- ) {
234
- const vis = (propMatch[1] as Visibility) || "public";
235
- const propName = propMatch[2];
236
- const typeStr = propMatch[3] ? `: ${propMatch[3].trim()}` : "";
237
- symbols.push({
238
- name: `${currentClass}::${propName}`,
239
- kind: "property",
240
- signature: `${vis} ${propName}${typeStr}`,
241
- visibility: vis,
242
- line_start: lineNum,
243
- line_end: lineNum,
244
- line_count: 1,
245
- });
246
- }
247
- }
248
- }
249
-
250
- for (const ch of cleanLines[i]) {
251
- if (ch === "{") braceDepth++;
252
- else if (ch === "}") braceDepth = Math.max(0, braceDepth - 1);
253
- }
254
- if (currentClass && braceDepth < currentClassDepth) {
255
- currentClass = null;
256
- currentClassDepth = 0;
257
- }
258
- }
259
-
260
- return { symbols, dependencies };
69
+ return extractTypeScriptFallback(content);
261
70
  }
262
71
 
263
72
  private extractFromAst(rootNode: Parser.SyntaxNode, content: string): ParsedFileAST {
@@ -267,7 +76,11 @@ export class TypeScriptExtractor implements CodeExtractor {
267
76
 
268
77
  const stripQuotes = (raw: string): string => raw.replace(/^['"`]|['"`]$/g, "");
269
78
 
270
- const walkDependencies = (node: Parser.SyntaxNode): void => {
79
+ const depNodeTypes = /\b(?:require|import)\s*\(/.test(content)
80
+ ? ["import_statement", "export_statement", "call_expression"]
81
+ : ["import_statement", "export_statement"];
82
+
83
+ for (const node of rootNode.descendantsOfType(depNodeTypes)) {
271
84
  if (node.type === "import_statement") {
272
85
  const sourceNode =
273
86
  node.childForFieldName("source") ??
@@ -286,7 +99,7 @@ export class TypeScriptExtractor implements CodeExtractor {
286
99
  });
287
100
  }
288
101
  }
289
- return;
102
+ continue;
290
103
  }
291
104
 
292
105
  if (node.type === "export_statement") {
@@ -306,8 +119,8 @@ export class TypeScriptExtractor implements CodeExtractor {
306
119
  ...(importedSymbols.length > 0 ? { imported_symbols: importedSymbols } : {}),
307
120
  });
308
121
  }
309
- return;
310
122
  }
123
+ continue;
311
124
  }
312
125
 
313
126
  if (node.type === "call_expression") {
@@ -334,13 +147,7 @@ export class TypeScriptExtractor implements CodeExtractor {
334
147
  }
335
148
  }
336
149
  }
337
-
338
- for (const child of node.namedChildren) {
339
- walkDependencies(child);
340
- }
341
- };
342
-
343
- walkDependencies(rootNode);
150
+ }
344
151
 
345
152
  const processTopLevelNode = (stmtNode: Parser.SyntaxNode, isExported: boolean, outerStartRow?: number): void => {
346
153
  const startRow = outerStartRow ?? stmtNode.startPosition.row;
@@ -415,7 +222,7 @@ export class TypeScriptExtractor implements CodeExtractor {
415
222
  symbols.push({
416
223
  name: className,
417
224
  kind,
418
- signature: getNodeHeader(stmtNode),
225
+ signature: getNodeHeader(stmtNode, content),
419
226
  visibility: "public",
420
227
  line_start: lineStart,
421
228
  line_end: lineEnd,
@@ -442,7 +249,7 @@ export class TypeScriptExtractor implements CodeExtractor {
442
249
  symbols.push({
443
250
  name: nameNode.text,
444
251
  kind: stmtNode.type === "enum_declaration" ? "enum" : "type",
445
- signature: getNodeHeader(stmtNode),
252
+ signature: getNodeHeader(stmtNode, content),
446
253
  visibility: "public",
447
254
  line_start: lineStart,
448
255
  line_end: lineEnd,
@@ -45,7 +45,7 @@ export function getOperationCapabilities(filePath: string) {
45
45
  declarations,
46
46
  import_resolution: language && ["typescript", "javascript", "php", "python", "go", "rust", "java", "csharp", "ruby", "frontend"].includes(language.id) ? "partial" : "unsupported",
47
47
  source_context: declarations,
48
- deep_context: /\.(?:ts|mts|cts)$/.test(filePath) ? "bounded_references" : "unsupported",
48
+ deep_context: /\.(?:ts|mts|cts|tsx)$/.test(filePath) ? "bounded_references" : "unsupported",
49
49
  caller_analysis: language?.extractor ? "lexical_heuristic" : "unsupported",
50
50
  runtime_dispatch: "unverified",
51
51
  limits: language?.limits ?? "No registered language extractor.",
@@ -2,6 +2,7 @@ import { blankCommentsAndStrings } from "../../boundary-tracker.ts";
2
2
  import { readOptionalSourceFile } from "../../../resources/source-files.ts";
3
3
  import * as fs from "node:fs";
4
4
  import * as path from "node:path";
5
+ import { warnIfUnexpectedParserError } from "../../extractors/manifest-helpers.ts";
5
6
  import type {
6
7
  SchemaFieldSummary,
7
8
  SchemaMetadata,
@@ -78,7 +79,9 @@ export class LaravelMigrationSchemaProvider implements StackSchemaProvider {
78
79
  if (/protected\s+\$table\s*=/.test(mask.slice(tableMatch.index, tableMatch.index + tableMatch[0].length))) return tableMatch[1]!;
79
80
  }
80
81
  if (/protected\s+\$table\s*=/.test(mask)) return "";
81
- } catch {}
82
+ } catch (err: unknown) {
83
+ warnIfUnexpectedParserError(`Failed to read entity file ${fullEntityPath}`, err);
84
+ }
82
85
  }
83
86
  }
84
87
 
@@ -233,9 +233,13 @@ export async function parseSourceWithTreeSitter(
233
233
  };
234
234
  }
235
235
 
236
- export function getNodeHeader(node: Parser.SyntaxNode): string {
236
+ export function getNodeHeader(node: Parser.SyntaxNode, content?: string): string {
237
237
  const body = node.childForFieldName("body");
238
238
  const end = body ?? node.children.findLast(child => child.type === "end");
239
+ if (content !== undefined) {
240
+ const endOffset = end ? end.startIndex : node.endIndex;
241
+ return content.slice(node.startIndex, endOffset).trim().replace(/;$/, "");
242
+ }
239
243
  return (end ? node.text.slice(0, end.startIndex - node.startIndex) : node.text)
240
244
  .trim().replace(/;$/, "");
241
245
  }
@@ -264,7 +268,7 @@ export function calculateAstControlFlowNesting(
264
268
  }
265
269
  }
266
270
 
267
- for (const child of node.namedChildren) {
271
+ for (let child = node.firstNamedChild; child; child = child.nextNamedSibling) {
268
272
  walk(child, nextDepth, false);
269
273
  }
270
274
  }
@@ -0,0 +1,230 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import ts from "typescript";
4
+ import type { ExecutionChainNode, FileRecord, SymbolRecord } from "../../types/index.ts";
5
+ import { bindContextFile } from "../retrieval/typescript-references.ts";
6
+
7
+ export type BoundUnit = ReturnType<typeof bindContextFile>;
8
+ export type TracerDependency = { target: string; statement: string; line_number: number; is_external: boolean };
9
+
10
+ export interface AstMethodTracerContext {
11
+ projectRoot: string;
12
+ maxChainNodes: number;
13
+ hasWorkspaceRoot: boolean;
14
+ fileSymbols: (fileId: number) => SymbolRecord[];
15
+ fileDependencies: (fileId: number) => TracerDependency[];
16
+ resolveImportTargets: (fromPath: string, moduleSpec: string) => FileRecord[];
17
+ resolveImportToFile: (fromPath: string, moduleSpec: string) => FileRecord | undefined;
18
+ resolveExecutableSymbol: (symbols: SymbolRecord[], preferredNames: string[]) => SymbolRecord | undefined;
19
+ isExecutableSymbol: (symbol: SymbolRecord) => boolean;
20
+ detectStage: (filePath: string, archetype: string) => string;
21
+ }
22
+
23
+ /** Locate the narrowest AST node covering a symbol's indexed line span. */
24
+ export function findAstNodeForSymbol(unit: BoundUnit, sym: SymbolRecord): ts.Node | undefined {
25
+ let best: ts.Node | undefined;
26
+ const visit = (node: ts.Node) => {
27
+ const sLine = unit.source.getLineAndCharacterOfPosition(node.getStart()).line + 1;
28
+ const eLine = unit.source.getLineAndCharacterOfPosition(node.end).line + 1;
29
+ if (sLine <= sym.line_start && eLine >= sym.line_end) {
30
+ if (ts.isFunctionLike(node) || ts.isVariableDeclaration(node) || ts.isClassDeclaration(node)) {
31
+ best = node;
32
+ }
33
+ ts.forEachChild(node, visit);
34
+ }
35
+ };
36
+ ts.forEachChild(unit.source, visit);
37
+ return best ?? unit.declaration(sym.line_start, sym.line_end);
38
+ }
39
+
40
+ /** Collect non-type-only AST import declarations and their referenced symbol names. */
41
+ export function collectActiveAstImports(importDecl: ts.ImportDeclaration, importedNames: Set<string>): string[] {
42
+ if (importDecl.importClause?.isTypeOnly) return [];
43
+ const named = importDecl.importClause?.namedBindings;
44
+ return [...importedNames].filter((name) => {
45
+ if (named && ts.isNamedImports(named)) {
46
+ const el = named.elements.find((e) => (e.propertyName ?? e.name).text === name);
47
+ if (el?.isTypeOnly) return false;
48
+ }
49
+ return name !== "*";
50
+ });
51
+ }
52
+
53
+ function resolveAstTargetSymbol(
54
+ ctx: AstMethodTracerContext,
55
+ resolvedFile: FileRecord,
56
+ symName: string,
57
+ loadBound: (filePath: string) => BoundUnit | null
58
+ ): SymbolRecord | undefined {
59
+ const fileSymbols = ctx.fileSymbols(resolvedFile.id);
60
+ const direct = ctx.resolveExecutableSymbol(fileSymbols, [symName]);
61
+ if (direct || !/\.[cm]?[jt]sx?$/i.test(resolvedFile.path)) return direct;
62
+
63
+ const targetUnit = loadBound(resolvedFile.path);
64
+ const exportedNode = targetUnit?.exported(symName);
65
+ if (!targetUnit || !exportedNode) return undefined;
66
+
67
+ const sLine = targetUnit.source.getLineAndCharacterOfPosition(exportedNode.getStart()).line + 1;
68
+ const eLine = targetUnit.source.getLineAndCharacterOfPosition(exportedNode.end).line + 1;
69
+ return fileSymbols.find((s) => s.line_start >= sLine && s.line_end <= eLine && ctx.isExecutableSymbol(s));
70
+ }
71
+
72
+ /**
73
+ * AST-verified BFS traversal for TypeScript/JavaScript methods.
74
+ * Expands same-file local helper calls without consuming import hop budget,
75
+ * and follows bound imported callees/references up to effectiveMaxDepth.
76
+ */
77
+ export function traverseAstMethodGraph(
78
+ ctx: AstMethodTracerContext,
79
+ startFile: FileRecord,
80
+ startSymbol: SymbolRecord,
81
+ chain: ExecutionChainNode[],
82
+ effectiveMaxDepth: number
83
+ ): void {
84
+ const boundCache = new Map<string, BoundUnit | null>();
85
+ const loadBound = (filePath: string): BoundUnit | null => {
86
+ if (boundCache.has(filePath)) return boundCache.get(filePath)!;
87
+ const fullPath = resolve(ctx.projectRoot, filePath);
88
+ const source = existsSync(fullPath) ? readFileSync(fullPath, "utf-8") : "";
89
+ const unit = source ? bindContextFile(filePath, source) : null;
90
+ boundCache.set(filePath, unit);
91
+ return unit;
92
+ };
93
+
94
+ const visitedNodes = new Set<string>([`${startFile.path}:${startSymbol.name}:${startSymbol.line_start}`]);
95
+ const queue: Array<{ file: FileRecord; symbol: SymbolRecord; depth: number; visualDepth: number }> = [
96
+ { file: startFile, symbol: startSymbol, depth: 1, visualDepth: 1 },
97
+ ];
98
+
99
+ while (queue.length > 0 && chain.length < ctx.maxChainNodes) {
100
+ const current = queue.shift()!;
101
+ if (current.depth > effectiveMaxDepth || !/\.[cm]?[jt]sx?$/i.test(current.file.path)) continue;
102
+
103
+ const unit = loadBound(current.file.path);
104
+ const declNode = unit ? findAstNodeForSymbol(unit, current.symbol) : undefined;
105
+ if (!unit || !declNode) continue;
106
+
107
+ const refs = unit.references(declNode);
108
+ // Bridge same-file local helper calls (e.g. thin entrypoint wrappers delegating to local functions).
109
+ const currentSymbols = ctx.fileSymbols(current.file.id);
110
+ for (const localNode of refs.locals) {
111
+ if (chain.length >= ctx.maxChainNodes) break;
112
+ const isLocalCall = refs.calls.some((c) => c.target === localNode);
113
+ if (!isLocalCall) continue;
114
+ const localStart = unit.source.getLineAndCharacterOfPosition(localNode.getStart()).line + 1;
115
+ const localEnd = unit.source.getLineAndCharacterOfPosition(localNode.end).line + 1;
116
+ const localSymbol = currentSymbols.find(
117
+ (s) =>
118
+ ctx.isExecutableSymbol(s) &&
119
+ (s.line_start === localStart || (s.line_start >= localStart && s.line_end <= localEnd))
120
+ );
121
+ if (!localSymbol) continue;
122
+ const localVisitKey = `${current.file.path}:${localSymbol.name}:${localSymbol.line_start}`;
123
+ if (!chain.some((c) => c.file === current.file.path && c.symbol === localSymbol.name)) {
124
+ const stage = ctx.detectStage(current.file.path, current.file.archetype);
125
+ chain.push({
126
+ stage,
127
+ symbol: localSymbol.name,
128
+ parent_symbol: current.symbol.name,
129
+ depth: current.visualDepth,
130
+ file: current.file.path,
131
+ line: localSymbol.line_start || 1,
132
+ description: `${stage.toUpperCase()} (AST local call): ${localSymbol.name}`,
133
+ relationship: {
134
+ kind: "calls",
135
+ derivation: "source",
136
+ source: { file: current.file.path, line: current.symbol.line_start || 1 },
137
+ reason: "ast_local_call_site",
138
+ },
139
+ });
140
+ }
141
+ if (!visitedNodes.has(localVisitKey)) {
142
+ visitedNodes.add(localVisitKey);
143
+ queue.push({ file: current.file, symbol: localSymbol, depth: current.depth, visualDepth: current.visualDepth + 1 });
144
+ }
145
+ }
146
+
147
+ const importEntries = new Map<ts.ImportDeclaration, Set<string>>(refs.imports);
148
+ if (ts.isMethodDeclaration(declNode) && ts.isClassDeclaration(declNode.parent)) {
149
+ const usedProps = new Set<string>();
150
+ const walkProps = (n: ts.Node) => {
151
+ if (ts.isPropertyAccessExpression(n) && n.expression.kind === ts.SyntaxKind.ThisKeyword) {
152
+ usedProps.add(n.name.text);
153
+ }
154
+ ts.forEachChild(n, walkProps);
155
+ };
156
+ walkProps(declNode);
157
+ if (usedProps.size > 0) {
158
+ for (const member of declNode.parent.members) {
159
+ const propNames = ts.isPropertyDeclaration(member) && ts.isIdentifier(member.name)
160
+ ? [{ name: member.name.text, typeNode: member.type }]
161
+ : ts.isConstructorDeclaration(member)
162
+ ? member.parameters.filter(p => ts.isIdentifier(p.name)).map(p => ({ name: (p.name as ts.Identifier).text, typeNode: p.type }))
163
+ : [];
164
+ for (const p of propNames) {
165
+ if (!usedProps.has(p.name) || !p.typeNode) continue;
166
+ const typeRefs = unit.references(p.typeNode);
167
+ for (const [imp, names] of typeRefs.imports) {
168
+ const existing = importEntries.get(imp) ?? new Set<string>();
169
+ for (const name of names) existing.add(name);
170
+ importEntries.set(imp, existing);
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+
177
+ const deps = ctx.fileDependencies(current.file.id);
178
+
179
+ for (const [importDecl, importedNames] of importEntries) {
180
+ if (chain.length >= ctx.maxChainNodes) break;
181
+ const activeNames = collectActiveAstImports(importDecl, importedNames);
182
+ const moduleSpec = ts.isStringLiteral(importDecl.moduleSpecifier) ? importDecl.moduleSpecifier.text : "";
183
+ if (activeNames.length === 0 || !moduleSpec) continue;
184
+
185
+ const importLine = unit.source.getLineAndCharacterOfPosition(importDecl.getStart()).line + 1;
186
+ const dep = deps.find((d) => d.target === moduleSpec || d.line_number === importLine);
187
+ if (dep?.is_external) continue;
188
+
189
+ const resolvedFiles = ctx.hasWorkspaceRoot
190
+ ? ctx.resolveImportTargets(current.file.path, moduleSpec)
191
+ : [ctx.resolveImportToFile(current.file.path, moduleSpec)].filter((f): f is FileRecord => !!f);
192
+
193
+ for (const resolvedFile of resolvedFiles) {
194
+ for (const symName of activeNames) {
195
+ if (chain.length >= ctx.maxChainNodes) break;
196
+ const mainSymbol = resolveAstTargetSymbol(ctx, resolvedFile, symName, loadBound);
197
+ if (!mainSymbol) continue;
198
+
199
+ const isCall = !refs.escapes.has(importDecl) &&
200
+ refs.calls.some((c) => c.target === importDecl && (!c.name || c.name === symName));
201
+ const stage = ctx.detectStage(resolvedFile.path, resolvedFile.archetype);
202
+
203
+ if (!chain.some((c) => c.file === resolvedFile.path && c.symbol === mainSymbol.name)) {
204
+ chain.push({
205
+ stage,
206
+ symbol: mainSymbol.name,
207
+ parent_symbol: current.symbol.name,
208
+ depth: current.visualDepth,
209
+ file: resolvedFile.path,
210
+ line: mainSymbol.line_start || 1,
211
+ description: `${stage.toUpperCase()} (${isCall ? "AST call" : "AST import"}): ${mainSymbol.name}`,
212
+ relationship: {
213
+ kind: isCall ? "calls" : "imports",
214
+ derivation: "source",
215
+ source: { file: current.file.path, line: importLine, statement: dep?.statement ?? importDecl.getText(unit.source) },
216
+ reason: isCall ? "ast_call_site" : "ast_referenced_import",
217
+ },
218
+ });
219
+ }
220
+
221
+ const visitKey = `${resolvedFile.path}:${mainSymbol.name}:${mainSymbol.line_start}`;
222
+ if (!visitedNodes.has(visitKey) && current.depth < effectiveMaxDepth) {
223
+ visitedNodes.add(visitKey);
224
+ queue.push({ file: resolvedFile, symbol: mainSymbol, depth: current.depth + 1, visualDepth: current.visualDepth + 1 });
225
+ }
226
+ }
227
+ }
228
+ }
229
+ }
230
+ }
@@ -0,0 +1,72 @@
1
+ export function extractImportedSymbolNames(statement: string): string[] {
2
+ if (!statement) return [];
3
+ const names = new Set<string>();
4
+ const braceMatch = statement.match(/\{([^}]+)\}/);
5
+ if (braceMatch) {
6
+ for (const spec of braceMatch[1].split(",")) {
7
+ const cleaned = spec.trim().replace(/^type\s+/, "");
8
+ const parts = cleaned.split(/\s+as\s+/);
9
+ for (const p of parts) {
10
+ const id = p.trim();
11
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(id)) names.add(id);
12
+ }
13
+ }
14
+ }
15
+ const defaultMatch = statement.match(/^\s*import\s+(?:type\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s+from\b/);
16
+ if (defaultMatch) names.add(defaultMatch[1]);
17
+ const pyMatch = statement.match(/\bfrom\s+[^\s]+\s+import\s+([^;(\n]+)/);
18
+ if (pyMatch) {
19
+ for (const spec of pyMatch[1].split(",")) {
20
+ const parts = spec.trim().split(/\s+as\s+/);
21
+ const id = (parts[0] || "").trim();
22
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(id)) names.add(id);
23
+ }
24
+ }
25
+ const phpMatch = statement.match(/^\s*use\s+(?:function\s+|const\s+)?[A-Za-z0-9_\\]+\\([A-Za-z0-9_]+)/);
26
+ if (phpMatch) names.add(phpMatch[1]);
27
+ return Array.from(names);
28
+ }
29
+
30
+ /**
31
+ * Detect generic pipeline stage from file path and archetype.
32
+ */
33
+ export function detectPipelineStage(filePath: string, archetype: string): string {
34
+ const norm = filePath.toLowerCase();
35
+
36
+ if (
37
+ archetype === "validation" ||
38
+ archetype === "dto" ||
39
+ /validation|middleware|dto|request|schema/i.test(norm)
40
+ ) {
41
+ return "validation";
42
+ }
43
+
44
+ if (archetype === "controller" || /controller|handler/i.test(norm)) {
45
+ return "controller";
46
+ }
47
+
48
+ if (
49
+ archetype === "service" ||
50
+ archetype === "use_case" ||
51
+ /use-?cases?|interactor|application|workflow/i.test(norm)
52
+ ) {
53
+ return "use_case";
54
+ }
55
+
56
+ if (
57
+ archetype === "model" ||
58
+ archetype === "entity" ||
59
+ /domain|entities|entity|aggregate/i.test(norm)
60
+ ) {
61
+ return "entity";
62
+ }
63
+
64
+ if (
65
+ archetype === "repository" ||
66
+ /repositories|repository|database|persistence|egress|adapter/i.test(norm)
67
+ ) {
68
+ return "repository";
69
+ }
70
+
71
+ return "service";
72
+ }