@dimassetoid/septum-mcp 0.0.0-stage → 0.3.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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +133 -0
  7. package/src/cli/commands/hook.ts +205 -0
  8. package/src/cli/commands/init.ts +570 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +39 -0
  11. package/src/cli/hook-payload.ts +43 -0
  12. package/src/cli/index.ts +124 -0
  13. package/src/cli/scaffold/harness-config.ts +661 -0
  14. package/src/cli/templates/hooks.ts +110 -0
  15. package/src/cli/templates/rules.ts +35 -0
  16. package/src/cli/templates/skill.ts +55 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +426 -0
  19. package/src/core/boundary/staged-auditor.ts +120 -0
  20. package/src/core/config/domain-ownership.ts +45 -0
  21. package/src/core/config/loader.ts +174 -0
  22. package/src/core/config/schema.ts +59 -0
  23. package/src/core/database/client.ts +60 -0
  24. package/src/core/database/repositories/dependency.repository.ts +733 -0
  25. package/src/core/database/repositories/domain.repository.ts +373 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +647 -0
  29. package/src/core/database/repository.ts +358 -0
  30. package/src/core/database/schema.ts +123 -0
  31. package/src/core/discovery/navigation.ts +105 -0
  32. package/src/core/discovery/topology-detector.ts +863 -0
  33. package/src/core/ingestion/hasher.ts +5 -0
  34. package/src/core/ingestion/pipeline.ts +590 -0
  35. package/src/core/parser/behavioral-analyzer.ts +123 -0
  36. package/src/core/parser/boundary-tracker.ts +458 -0
  37. package/src/core/parser/extractors/base.ts +71 -0
  38. package/src/core/parser/extractors/blade.ts +159 -0
  39. package/src/core/parser/extractors/csharp.ts +248 -0
  40. package/src/core/parser/extractors/django-semantic.ts +655 -0
  41. package/src/core/parser/extractors/elysia-semantic.ts +517 -0
  42. package/src/core/parser/extractors/express-semantic.ts +429 -0
  43. package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
  44. package/src/core/parser/extractors/fastify-semantic.ts +759 -0
  45. package/src/core/parser/extractors/flask-semantic.ts +482 -0
  46. package/src/core/parser/extractors/frontend.ts +149 -0
  47. package/src/core/parser/extractors/go-semantic.ts +670 -0
  48. package/src/core/parser/extractors/go.ts +491 -0
  49. package/src/core/parser/extractors/hono-semantic.ts +546 -0
  50. package/src/core/parser/extractors/java.ts +227 -0
  51. package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
  52. package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
  53. package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
  54. package/src/core/parser/extractors/php.ts +585 -0
  55. package/src/core/parser/extractors/python.ts +503 -0
  56. package/src/core/parser/extractors/registry.ts +99 -0
  57. package/src/core/parser/extractors/ruby.ts +237 -0
  58. package/src/core/parser/extractors/rust.ts +304 -0
  59. package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
  60. package/src/core/parser/extractors/symfony-semantic.ts +321 -0
  61. package/src/core/parser/extractors/typescript.ts +839 -0
  62. package/src/core/parser/implementation-fingerprint.ts +97 -0
  63. package/src/core/parser/language-capabilities.ts +87 -0
  64. package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
  65. package/src/core/parser/schema/schema-provider-registry.ts +41 -0
  66. package/src/core/parser/schema/schema-provider.interface.ts +34 -0
  67. package/src/core/parser/semantic-revision.ts +3 -0
  68. package/src/core/parser/static-string.ts +51 -0
  69. package/src/core/parser/tree-sitter.ts +63 -0
  70. package/src/core/parser/wasm-assets.ts +25 -0
  71. package/src/core/parser/wasm-loader.ts +274 -0
  72. package/src/core/resolver/call-graph-tracer.ts +1033 -0
  73. package/src/core/resolver/import-resolver.ts +365 -0
  74. package/src/core/resolver/interpretation-inputs.ts +7 -0
  75. package/src/core/resolver/languages/go.ts +103 -0
  76. package/src/core/resolver/languages/managed.ts +200 -0
  77. package/src/core/resolver/languages/python.ts +115 -0
  78. package/src/core/resolver/languages/ruby.ts +40 -0
  79. package/src/core/resolver/languages/rust.ts +127 -0
  80. package/src/core/resolver/languages/shared.ts +71 -0
  81. package/src/core/resolver/module-resolver.ts +486 -0
  82. package/src/core/resolver/path-resolver.ts +200 -0
  83. package/src/core/resolver/slice-catalog.ts +79 -0
  84. package/src/core/resolver/slice-format.ts +9 -0
  85. package/src/core/resolver/symbol-impact.ts +381 -0
  86. package/src/core/resolver/symbol-locator.ts +276 -0
  87. package/src/core/resolver/symbol-reference.ts +53 -0
  88. package/src/core/resolver/vertical-slice-tracer.ts +344 -0
  89. package/src/core/resources/ignore.ts +144 -0
  90. package/src/core/resources/limits.ts +14 -0
  91. package/src/core/resources/source-files.ts +185 -0
  92. package/src/core/resources/source-inventory.ts +55 -0
  93. package/src/core/resources/work-queue.ts +74 -0
  94. package/src/core/retrieval/context-page.ts +109 -0
  95. package/src/core/retrieval/context.ts +320 -0
  96. package/src/core/retrieval/resolution-warnings.ts +21 -0
  97. package/src/core/retrieval/symbol-evidence.ts +97 -0
  98. package/src/core/retrieval/typescript-references.ts +262 -0
  99. package/src/core/telemetry/telemetry.ts +142 -0
  100. package/src/index.ts +18 -0
  101. package/src/mcp/schemas.ts +746 -0
  102. package/src/mcp/server.ts +600 -0
  103. package/src/mcp/tools/boundary.ts +17 -0
  104. package/src/mcp/tools/check-boundary.ts +382 -0
  105. package/src/mcp/tools/get-domain-catalog.ts +39 -0
  106. package/src/mcp/tools/get-symbol-impact.ts +104 -0
  107. package/src/mcp/tools/get-symbol.ts +399 -0
  108. package/src/mcp/tools/locate-symbol.ts +236 -0
  109. package/src/mcp/tools/map.ts +26 -0
  110. package/src/mcp/tools/register-domain.ts +113 -0
  111. package/src/mcp/tools/slice.ts +16 -0
  112. package/src/mcp/tools/symbol.ts +95 -0
  113. package/src/mcp/tools/trace-vertical-slice.ts +106 -0
  114. package/src/mcp/workspace-manager.ts +170 -0
  115. package/src/mcp/workspace-watcher.ts +202 -0
  116. package/src/types/index.ts +438 -0
  117. package/src/types/wasm.d.ts +4 -0
  118. package/src/utils/version-check.ts +209 -0
  119. package/src/version.ts +1 -0
@@ -0,0 +1,97 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
3
+ import { dirname, join, relative, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { WASM_ASSETS } from "./wasm-assets.ts";
6
+
7
+ /** Content identity, independent of checkout paths, mtimes and release counters. */
8
+ export function fingerprintImplementation(options: {
9
+ sourceRoot?: string;
10
+ executablePath?: string;
11
+ assets?: Record<string, string>;
12
+ }): string {
13
+ const hash = createHash("sha256");
14
+ const chunk = Buffer.allocUnsafe(256 * 1024);
15
+ const addFile = (label: string, file: string): void => {
16
+ const expectedSize = statSync(file).size;
17
+ hash.update(JSON.stringify([label, expectedSize]));
18
+ // Bound memory while hashing standalone executables, which include the Bun runtime.
19
+ const fd = openSync(file, "r");
20
+ try {
21
+ let total = 0;
22
+ for (;;) {
23
+ const size = readSync(fd, chunk, 0, chunk.length, null);
24
+ if (!size) break;
25
+ hash.update(chunk.subarray(0, size));
26
+ total += size;
27
+ }
28
+ if (total !== expectedSize) throw new Error(`Implementation changed while fingerprinting '${label}'. Restart Septum.`);
29
+ } finally { closeSync(fd); }
30
+ hash.update("\0");
31
+ };
32
+ if (options.executablePath) {
33
+ addFile("executable", options.executablePath);
34
+ } else if (options.sourceRoot) {
35
+ const root = resolve(options.sourceRoot);
36
+ const ancestors = new Set<string>();
37
+ const visit = (directory: string, base = root, prefix = ""): void => {
38
+ const identity = realpathSync(directory);
39
+ if (ancestors.has(identity)) throw new Error(`Implementation directory cycle at '${directory}'.`);
40
+ ancestors.add(identity);
41
+ try {
42
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
43
+ const file = join(directory, entry.name);
44
+ const info = entry.isSymbolicLink() ? statSync(file) : entry;
45
+ if (info.isDirectory()) visit(file, base, prefix);
46
+ else if (info.isFile()) addFile([prefix, relative(base, file).replace(/\\/g, "/")].filter(Boolean).join("/"), file);
47
+ }
48
+ } finally { ancestors.delete(identity); }
49
+ };
50
+ visit(join(root, "src"));
51
+ visit(join(root, "bin"));
52
+ for (const name of ["package.json", "bun.lock", "bun.lockb"]) {
53
+ const file = join(root, name);
54
+ if (existsSync(file)) addFile(name, file);
55
+ }
56
+ // Include installed bytes: local dependency patches can change analysis
57
+ // without changing a package manifest or lockfile.
58
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
59
+ for (const name of Object.keys(manifest.dependencies ?? {}).sort()) {
60
+ let directory = root;
61
+ while (!existsSync(join(directory, "node_modules", name, "package.json"))) {
62
+ const parent = dirname(directory);
63
+ if (parent === directory) throw new Error(`Cannot fingerprint installed dependency '${name}'.`);
64
+ directory = parent;
65
+ }
66
+ const packageRoot = join(directory, "node_modules", name);
67
+ visit(packageRoot, packageRoot, `dependency:${name}`);
68
+ }
69
+ } else {
70
+ throw new Error("Implementation fingerprint requires sourceRoot or executablePath.");
71
+ }
72
+ for (const [name, file] of Object.entries(options.assets ?? {}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
73
+ // Embedded WASM paths support readFileSync in compiled Bun executables.
74
+ hash.update(JSON.stringify(["asset", name]));
75
+ hash.update(readFileSync(file));
76
+ hash.update("\0");
77
+ }
78
+ hash.update(JSON.stringify(["runtime", Bun.version, process.platform, process.arch]));
79
+ return `sha256:${hash.digest("hex")}`;
80
+ }
81
+
82
+ const standalone = typeof Bun.isStandaloneExecutable === "boolean"
83
+ ? Bun.isStandaloneExecutable : Bun.embeddedFiles.length > 0;
84
+ const assets = Object.fromEntries(Object.entries(WASM_ASSETS).map(([name, embedded]) => {
85
+ const override = process.env.SEPTUM_WASM_DIR;
86
+ const candidates = override ? [join(override, name), join(override, "out", name), embedded] : [embedded];
87
+ return [name, candidates.find(file => existsSync(file)) ?? embedded];
88
+ }));
89
+
90
+ // One identity per loaded process. A daemon must restart to load changed implementation code.
91
+ export const ANALYSIS_FINGERPRINT = fingerprintImplementation(standalone ? {
92
+ executablePath: process.platform === "linux" ? "/proc/self/exe" : process.execPath,
93
+ assets,
94
+ } : {
95
+ sourceRoot: resolve(dirname(fileURLToPath(import.meta.url)), "../../.."),
96
+ assets,
97
+ });
@@ -0,0 +1,87 @@
1
+ import * as path from "node:path";
2
+ import grammarPackage from "tree-sitter-wasms/package.json";
3
+ import { ANALYSIS_FINGERPRINT } from "./implementation-fingerprint.ts";
4
+
5
+ export const PARSER_FINGERPRINT = ANALYSIS_FINGERPRINT;
6
+
7
+ type LanguageDefinition = {
8
+ id: string;
9
+ extensions: string[];
10
+ aliases: string[];
11
+ extractor: string | null;
12
+ method: "tree-sitter" | "template-scanner" | "embedded-script" | "unsupported";
13
+ grammar?: string;
14
+ grammarOverrides?: Record<string, string>;
15
+ limits: string;
16
+ };
17
+
18
+ export const LANGUAGE_CAPABILITIES: readonly LanguageDefinition[] = [
19
+ { id: "blade", extensions: [".blade.php"], aliases: [], extractor: "blade", method: "template-scanner", limits: "Literal directives/components only; no PHP or template syntax validation." },
20
+ { id: "typescript", extensions: [".ts", ".tsx", ".mts", ".cts"], aliases: ["ts", "tsx"], extractor: "typescript", method: "tree-sitter", grammar: "typescript", grammarOverrides: { ".tsx": "tsx", tsx: "tsx" }, limits: "Selected declarations/imports; no type checking or complete module resolution." },
21
+ { id: "javascript", extensions: [".js", ".jsx", ".mjs", ".cjs"], aliases: ["js", "jsx"], extractor: "typescript", method: "tree-sitter", grammar: "javascript", limits: "Selected declarations/imports; dynamic targets and module conditions are incomplete." },
22
+ { id: "php", extensions: [".php"], aliases: [], extractor: "php", method: "tree-sitter", grammar: "php", limits: "Selected declarations/imports; partial PSR-4/domain resolution, no runtime reflection." },
23
+ { id: "python", extensions: [".py"], aliases: ["py"], extractor: "python", method: "tree-sitter", grammar: "python", limits: "Selected declarations/imports; package resolution and dynamic attributes incomplete." },
24
+ { id: "go", extensions: [".go"], aliases: ["golang"], extractor: "go", method: "tree-sitter", grammar: "go", limits: "Selected declarations/imports; no complete module/package or receiver resolution." },
25
+ { id: "rust", extensions: [".rs"], aliases: ["rs"], extractor: "rust", method: "tree-sitter", grammar: "rust", limits: "Literal Cargo/module/path dependency resolution; cfg remains conditional, no macro expansion or trait dispatch proof." },
26
+ { id: "java", extensions: [".java"], aliases: [], extractor: "java", method: "tree-sitter", grammar: "java", limits: "Local source types/packages and literal Maven/Gradle project roots; no complete binary classpath or build execution." },
27
+ { id: "csharp", extensions: [".cs"], aliases: ["cs", "c_sharp"], extractor: "csharp", method: "tree-sitter", grammar: "c_sharp", limits: "Local namespaces/types and literal project references; conditional MSBuild inputs remain uncertain, no assembly namespace inference from package names." },
28
+ { id: "ruby", extensions: [".rb"], aliases: ["rb"], extractor: "ruby", method: "tree-sitter", grammar: "ruby", limits: "Literal require_relative, conventional lib roots and declared gems; no dynamic load-path, Zeitwerk configuration or metaprogramming execution." },
29
+ { id: "frontend", extensions: [".vue", ".astro", ".svelte"], aliases: [], extractor: "frontend", method: "embedded-script", limits: "Scans script/frontmatter as TypeScript; no whole-template AST validation." },
30
+ { id: "kotlin", extensions: [".kt"], aliases: [], extractor: null, method: "unsupported", limits: "Recognized for unsupported-file diagnostics; no registered grammar or extractor." },
31
+ { id: "scala", extensions: [".scala"], aliases: [], extractor: null, method: "unsupported", limits: "Recognized only; no registered grammar or extractor." },
32
+ { id: "zig", extensions: [".zig"], aliases: [], extractor: null, method: "unsupported", limits: "Recognized only; no registered grammar or extractor." },
33
+ ];
34
+
35
+ export function getLanguageCapability(filePath: string): LanguageDefinition | undefined {
36
+ const lower = filePath.toLowerCase();
37
+ return LANGUAGE_CAPABILITIES.find(language => language.extensions.some(ext => lower.endsWith(ext)));
38
+ }
39
+
40
+ export function getOperationCapabilities(filePath: string) {
41
+ const language = getLanguageCapability(filePath);
42
+ const declarations = language?.extractor ? "partial" : "unsupported";
43
+ return {
44
+ language: language?.id ?? "unknown",
45
+ declarations,
46
+ import_resolution: language && ["typescript", "javascript", "php", "python", "go", "rust", "java", "csharp", "ruby", "frontend"].includes(language.id) ? "partial" : "unsupported",
47
+ source_context: declarations,
48
+ deep_context: /\.(?:ts|mts|cts)$/.test(filePath) ? "bounded_references" : "unsupported",
49
+ caller_analysis: language?.extractor ? "lexical_heuristic" : "unsupported",
50
+ runtime_dispatch: "unverified",
51
+ limits: language?.limits ?? "No registered language extractor.",
52
+ };
53
+ }
54
+
55
+ export function grammarFileForKey(keyOrPath: string): string | null {
56
+ const key = keyOrPath.trim().toLowerCase();
57
+ if (key.endsWith(".wasm")) return key;
58
+ const language = LANGUAGE_CAPABILITIES.find(l => l.id === key || l.aliases.includes(key))
59
+ ?? getLanguageCapability(key);
60
+ if (!language?.grammar) return null;
61
+ const grammar = language.grammarOverrides?.[key] ?? language.grammarOverrides?.[path.extname(key)] ?? language.grammar;
62
+ return `tree-sitter-${grammar}.wasm`;
63
+ }
64
+
65
+ export function getParserCapabilities(full: boolean) {
66
+ const common = {
67
+ parser_revision: PARSER_FINGERPRINT,
68
+ grammar_package: `${grammarPackage.name}@${grammarPackage.version}`,
69
+ coverage: "partial",
70
+ status_contract: "parsed = parser/scanner completed; degraded = recovery/fallback; unsupported = no extractor. None implies complete extraction or runtime correctness.",
71
+ };
72
+ return full ? {
73
+ ...common,
74
+ languages: LANGUAGE_CAPABILITIES.map(l => ({
75
+ id: l.id, extensions: l.extensions, extractor: l.extractor, method: l.method,
76
+ coverage: l.extractor ? "partial" : "none",
77
+ grammars: [...new Set(l.extensions.map(grammarFileForKey).filter(Boolean))],
78
+ limits: l.limits,
79
+ operations: getOperationCapabilities(`source${l.extensions[0]}`),
80
+ evidence: l.method === "tree-sitter" ? "tests/unit/language-capabilities.test.ts; tests/unit/parser-recovery.test.ts" : "tests/unit/language-capabilities.test.ts",
81
+ })),
82
+ } : {
83
+ ...common,
84
+ languages: Object.fromEntries(LANGUAGE_CAPABILITIES.map(l => [l.id, l.method])),
85
+ detail_hint: "Use detail_level='full' for extensions, grammar assets and per-language limits.",
86
+ };
87
+ }
@@ -0,0 +1,239 @@
1
+ import { blankCommentsAndStrings } from "../../boundary-tracker.ts";
2
+ import { readOptionalSourceFile } from "../../../resources/source-files.ts";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import type {
6
+ SchemaFieldSummary,
7
+ SchemaMetadata,
8
+ StackSchemaProvider,
9
+ } from "../schema-provider.interface.ts";
10
+
11
+ export class LaravelMigrationSchemaProvider implements StackSchemaProvider {
12
+ public readonly id = "laravel-migration";
13
+ public readonly name = "Laravel Migration Schema Provider";
14
+
15
+ public canHandle(projectRoot: string): boolean {
16
+ const migrationsDir = path.join(projectRoot, "database", "migrations");
17
+ return fs.existsSync(migrationsDir) || fs.existsSync(path.join(projectRoot, "artisan"));
18
+ }
19
+
20
+ public resolveEntitySchema(
21
+ projectRoot: string,
22
+ entitySymbol: string,
23
+ entityFilePath?: string
24
+ ): SchemaMetadata | null {
25
+ const migrationsDir = path.join(projectRoot, "database", "migrations");
26
+ if (!fs.existsSync(migrationsDir)) return null;
27
+
28
+ const tableName = this.resolveTableName(projectRoot, entitySymbol, entityFilePath);
29
+ if (!tableName) return null;
30
+
31
+ const migrationFiles = this.findMigrationFiles(migrationsDir);
32
+ if (migrationFiles.length === 0) return null;
33
+
34
+ const fieldsMap = new Map<string, SchemaFieldSummary>();
35
+ let primarySourceFile: string | undefined;
36
+
37
+ for (const migFile of migrationFiles) {
38
+ const fullPath = path.join(migrationsDir, migFile);
39
+ try {
40
+ const content = readOptionalSourceFile(fullPath, "utf-8");
41
+ const before = JSON.stringify([...fieldsMap]);
42
+ if (!this.extractColumnsFromMigration(content, tableName, fieldsMap)) return null;
43
+ if (JSON.stringify([...fieldsMap]) !== before) primarySourceFile = migFile;
44
+ } catch {
45
+ // An unreadable migration can change the summary; do not certify older fields.
46
+ return null;
47
+ }
48
+ }
49
+
50
+ if (fieldsMap.size === 0 || !primarySourceFile) return null;
51
+
52
+ const relSourceFile = path.relative(projectRoot, path.join(migrationsDir, primarySourceFile));
53
+
54
+ return {
55
+ entityName: entitySymbol,
56
+ tableName,
57
+ schemaSourceFile: relSourceFile,
58
+ fields: Array.from(fieldsMap.values()),
59
+ interpretation: "static_migration_summary",
60
+ };
61
+ }
62
+
63
+ private resolveTableName(
64
+ projectRoot: string,
65
+ entitySymbol: string,
66
+ entityFilePath?: string
67
+ ): string {
68
+ // 1. Check if model file defines explicit protected $table = '...';
69
+ if (entityFilePath) {
70
+ const fullEntityPath = path.isAbsolute(entityFilePath)
71
+ ? entityFilePath
72
+ : path.join(projectRoot, entityFilePath);
73
+ if (fs.existsSync(fullEntityPath)) {
74
+ try {
75
+ const content = readOptionalSourceFile(fullEntityPath, "utf-8");
76
+ const mask = blankCommentsAndStrings(content);
77
+ for (const tableMatch of content.matchAll(/protected\s+\$table\s*=\s*['"]([^'"]+)['"]/g)) {
78
+ if (/protected\s+\$table\s*=/.test(mask.slice(tableMatch.index, tableMatch.index + tableMatch[0].length))) return tableMatch[1]!;
79
+ }
80
+ if (/protected\s+\$table\s*=/.test(mask)) return "";
81
+ } catch {}
82
+ }
83
+ }
84
+
85
+ // 2. Derive snake_case plural from entity name (e.g. OrderItem -> order_items)
86
+ return this.pluralize(this.toSnakeCase(entitySymbol));
87
+ }
88
+
89
+ private toSnakeCase(str: string): string {
90
+ return str
91
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
92
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
93
+ .toLowerCase();
94
+ }
95
+
96
+ private pluralize(snake: string): string {
97
+ if (snake.endsWith("y") && !/[aeiou]y$/i.test(snake)) {
98
+ return `${snake.slice(0, -1)}ies`;
99
+ }
100
+ if (/(?:s|x|z|ch|sh)$/i.test(snake)) {
101
+ return `${snake}es`;
102
+ }
103
+ return `${snake}s`;
104
+ }
105
+
106
+ private findMigrationFiles(migrationsDir: string): string[] {
107
+ return fs.readdirSync(migrationsDir).filter(file => file.endsWith(".php")).sort();
108
+ }
109
+
110
+ private extractColumnsFromMigration(
111
+ content: string,
112
+ tableName: string,
113
+ fieldsMap: Map<string, SchemaFieldSummary>
114
+ ): boolean {
115
+ const mask = blankCommentsAndStrings(content, { hashComments: true });
116
+ const blockEnd = (start: number) => {
117
+ let depth = 0;
118
+ for (let i = start; i < mask.length; i++) {
119
+ if (mask[i] === "{") depth++;
120
+ if (mask[i] === "}" && --depth === 0) return i;
121
+ }
122
+ return mask.length;
123
+ };
124
+ const up = /function\s+up\s*\([^)]*\)[^{]*\{/.exec(mask);
125
+ if (!up && /function\s+down\s*\(/.test(mask)) return true;
126
+ const start = up ? up.index + up[0].length : 0;
127
+ const end = up ? blockEnd(start - 1) : mask.length;
128
+ const operations = /Schema::(create|table|dropIfExists|drop|rename)\s*\(/g;
129
+ operations.lastIndex = start;
130
+ let operation: RegExpExecArray | null;
131
+ const bodies: string[] = [];
132
+ while ((operation = operations.exec(mask)) && operation.index < end) {
133
+ const argsStart = operations.lastIndex;
134
+ const literal = /^\s*['"]([^'"]+)['"]/.exec(content.slice(argsStart));
135
+ if (!literal) return false; // Dynamic table names cannot yield a reliable static summary.
136
+ if (operation[1] === "rename") {
137
+ const names = /^\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/.exec(content.slice(argsStart));
138
+ if (!names || names[1] === tableName || names[2] === tableName) return false;
139
+ }
140
+ if (literal[1] !== tableName) continue;
141
+ const kind = operation[1];
142
+ if (["drop", "dropIfExists", "rename"].includes(kind!)) {
143
+ bodies.push("__reset__");
144
+ continue;
145
+ }
146
+ const open = mask.indexOf("{", argsStart);
147
+ const close = open >= 0 ? blockEnd(open) : -1;
148
+ if (open < 0 || close >= end) return false;
149
+ if (kind === "create") bodies.push("__reset__");
150
+ const bodyMask = mask.slice(open + 1, close);
151
+ const body = content.slice(open + 1, close);
152
+ // Copy executable statements only; quoted/comment decoys cannot provide a table call.
153
+ for (const statement of bodyMask.matchAll(/\$table->[^;]+;/g)) {
154
+ bodies.push(body.slice(statement.index!, statement.index! + statement[0].length));
155
+ }
156
+ operations.lastIndex = close + 1;
157
+ }
158
+ for (const rawLine of bodies) {
159
+ const line = rawLine.trim();
160
+ if (line === "__reset__") { fieldsMap.clear(); continue; }
161
+ const drop = /\$table->dropColumn\s*\(\s*['"]([^'"]+)['"]/.exec(line);
162
+ if (drop) { fieldsMap.delete(drop[1]!); continue; }
163
+ const rename = /\$table->renameColumn\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/.exec(line);
164
+ if (rename) {
165
+ const field = fieldsMap.get(rename[1]!);
166
+ fieldsMap.delete(rename[1]!);
167
+ if (field) fieldsMap.set(rename[2]!, { ...field, name: rename[2]! });
168
+ continue;
169
+ }
170
+ if (/\$table->(?:dropColumn|renameColumn)\s*\(/.test(line)) return false;
171
+ if (!line.includes("$table->")) continue;
172
+
173
+ // Special shorthand: $table->id();
174
+ if (/\$table->id\s*\(\s*\)/.test(line)) {
175
+ fieldsMap.set("id", { name: "id", type: "id", isPrimary: true });
176
+ continue;
177
+ }
178
+
179
+ // Special shorthand: $table->id('custom_id');
180
+ const customIdMatch = /\$table->id\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(line);
181
+ if (customIdMatch) {
182
+ fieldsMap.set(customIdMatch[1], { name: customIdMatch[1], type: "id", isPrimary: true });
183
+ continue;
184
+ }
185
+
186
+ // Special shorthand: $table->timestamps();
187
+ if (/\$table->timestamps\s*\(/.test(line)) {
188
+ if (!fieldsMap.has("created_at")) {
189
+ fieldsMap.set("created_at", { name: "created_at", type: "timestamp", nullable: true });
190
+ }
191
+ if (!fieldsMap.has("updated_at")) {
192
+ fieldsMap.set("updated_at", { name: "updated_at", type: "timestamp", nullable: true });
193
+ }
194
+ continue;
195
+ }
196
+
197
+ // Special shorthand: $table->softDeletes();
198
+ if (/\$table->softDeletes\s*\(/.test(line)) {
199
+ if (!fieldsMap.has("deleted_at")) {
200
+ fieldsMap.set("deleted_at", { name: "deleted_at", type: "timestamp", nullable: true });
201
+ }
202
+ continue;
203
+ }
204
+
205
+ // Special shorthand: $table->rememberToken();
206
+ if (/\$table->rememberToken\s*\(/.test(line)) {
207
+ if (!fieldsMap.has("remember_token")) {
208
+ fieldsMap.set("remember_token", { name: "remember_token", type: "string", nullable: true });
209
+ }
210
+ continue;
211
+ }
212
+
213
+ // Standard column definitions: $table->type('column_name', ...)
214
+ const colMatch = /\$table->([a-zA-Z0-9_]+)\s*\(\s*['"]([^'"]+)['"]/.exec(line);
215
+ if (colMatch) {
216
+ const type = colMatch[1];
217
+ const name = colMatch[2];
218
+
219
+ // Skip non-column fluent methods like foreign, dropColumn, index, primary
220
+ if (["index", "unique", "primary", "foreign", "dropColumn", "dropForeign"].includes(type)) {
221
+ continue;
222
+ }
223
+
224
+ const nullable = line.includes("->nullable()");
225
+ const isPrimary = type === "increments" || type === "bigIncrements" || line.includes("->primary()");
226
+ const isForeign = type.startsWith("foreign") || name.endsWith("_id");
227
+
228
+ fieldsMap.set(name, {
229
+ name,
230
+ type,
231
+ nullable: nullable || undefined,
232
+ isPrimary: isPrimary || undefined,
233
+ isForeign: isForeign || undefined,
234
+ });
235
+ }
236
+ }
237
+ return true;
238
+ }
239
+ }
@@ -0,0 +1,41 @@
1
+ import type {
2
+ SchemaMetadata,
3
+ StackSchemaProvider,
4
+ } from "./schema-provider.interface.ts";
5
+ import { LaravelMigrationSchemaProvider } from "./providers/laravel-migration-provider.ts";
6
+
7
+ export class SchemaProviderRegistry {
8
+ private static providers: StackSchemaProvider[] = [
9
+ new LaravelMigrationSchemaProvider(),
10
+ ];
11
+
12
+ /**
13
+ * Registers a custom schema provider.
14
+ */
15
+ public static register(provider: StackSchemaProvider): void {
16
+ this.providers.unshift(provider);
17
+ }
18
+
19
+ /**
20
+ * Resolves physical schema metadata across all registered providers.
21
+ */
22
+ public static resolveSchema(
23
+ projectRoot: string,
24
+ entitySymbol: string,
25
+ entityFilePath?: string
26
+ ): SchemaMetadata | null {
27
+ for (const provider of this.providers) {
28
+ if (provider.canHandle(projectRoot)) {
29
+ try {
30
+ const res = provider.resolveEntitySchema(projectRoot, entitySymbol, entityFilePath);
31
+ if (res) {
32
+ return res;
33
+ }
34
+ } catch {
35
+ // Graceful fallback
36
+ }
37
+ }
38
+ }
39
+ return null;
40
+ }
41
+ }
@@ -0,0 +1,34 @@
1
+ export interface SchemaFieldSummary {
2
+ name: string;
3
+ type: string;
4
+ nullable?: boolean;
5
+ isPrimary?: boolean;
6
+ isForeign?: boolean;
7
+ }
8
+
9
+ export interface SchemaMetadata {
10
+ interpretation?: "static_migration_summary";
11
+ entityName: string;
12
+ tableName: string;
13
+ schemaSourceFile: string;
14
+ fields: SchemaFieldSummary[];
15
+ }
16
+
17
+ export interface StackSchemaProvider {
18
+ readonly id: string;
19
+ readonly name: string;
20
+
21
+ /**
22
+ * Determines if this schema provider can handle the project.
23
+ */
24
+ canHandle(projectRoot: string): boolean;
25
+
26
+ /**
27
+ * Resolves physical schema metadata (table name, source file, fields) for a given entity symbol.
28
+ */
29
+ resolveEntitySchema(
30
+ projectRoot: string,
31
+ entitySymbol: string,
32
+ entityFilePath?: string
33
+ ): SchemaMetadata | null;
34
+ }
@@ -0,0 +1,3 @@
1
+ import { ANALYSIS_FINGERPRINT } from "./implementation-fingerprint.ts";
2
+
3
+ export const SEMANTIC_FINGERPRINT = ANALYSIS_FINGERPRINT;
@@ -0,0 +1,51 @@
1
+ import type Parser from "web-tree-sitter";
2
+
3
+ // Decode literal values without executing source. Unsupported evaluation stays unresolved.
4
+ export function readPythonStaticString(node: Parser.SyntaxNode | null | undefined): string | undefined {
5
+ if (!node) return undefined;
6
+ if (node.type === "concatenated_string") {
7
+ let value = "";
8
+ for (const child of node.namedChildren) {
9
+ if (child.type === "comment") continue;
10
+ const part = readPythonStaticString(child);
11
+ if (part === undefined) return undefined;
12
+ value += part;
13
+ }
14
+ return value;
15
+ }
16
+ if (node.type !== "string") return undefined;
17
+ const match = /^([rRuU]*)("""|'''|"|')([\s\S]*)\2$/.exec(node.text);
18
+ if (!match || node.namedChildren.some(child => child.type === "interpolation")) return undefined;
19
+ const body = match[3];
20
+ if (match[1].toLowerCase().includes("r")) return body;
21
+
22
+ let value = "";
23
+ const escapes: Record<string, string> = { "\\": "\\", "'": "'", '"': '"', a: "\x07", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v" };
24
+ for (let i = 0; i < body.length; i++) {
25
+ if (body[i] !== "\\") { value += body[i]; continue; }
26
+ const escaped = body[++i];
27
+ if (escaped === undefined) return undefined;
28
+ if (escaped === "\n") continue;
29
+ if (escaped === "\r" && body[i + 1] === "\n") { i++; continue; }
30
+ if (escapes[escaped] !== undefined) { value += escapes[escaped]; continue; }
31
+ if (/[0-7]/.test(escaped)) {
32
+ const octal = body.slice(i).match(/^[0-7]{1,3}/)![0];
33
+ value += String.fromCodePoint(parseInt(octal, 8));
34
+ i += octal.length - 1;
35
+ continue;
36
+ }
37
+ const digits = escaped === "x" ? 2 : escaped === "u" ? 4 : escaped === "U" ? 8 : 0;
38
+ if (digits) {
39
+ const hex = body.slice(i + 1, i + 1 + digits);
40
+ if (hex.length !== digits || !/^[0-9a-f]+$/i.test(hex)) return undefined;
41
+ const point = parseInt(hex, 16);
42
+ if (point > 0x10ffff || point >= 0xd800 && point <= 0xdfff) return undefined;
43
+ value += String.fromCodePoint(point);
44
+ i += digits;
45
+ continue;
46
+ }
47
+ if (escaped === "N") return undefined; // Unicode names require a Unicode database.
48
+ value += `\\${escaped}`;
49
+ }
50
+ return value;
51
+ }
@@ -0,0 +1,63 @@
1
+ import type { ParsedFileAST } from "../../types/index.ts";
2
+ import type { CodeExtractor } from "./extractors/base.ts";
3
+ import { BladeExtractor } from "./extractors/blade.ts";
4
+ import { FrontendExtractor } from "./extractors/frontend.ts";
5
+ import { GoExtractor } from "./extractors/go.ts";
6
+ import { PHPExtractor } from "./extractors/php.ts";
7
+ import { PythonExtractor } from "./extractors/python.ts";
8
+ import { TypeScriptExtractor } from "./extractors/typescript.ts";
9
+ import { RustExtractor } from "./extractors/rust.ts";
10
+ import { JavaExtractor } from "./extractors/java.ts";
11
+ import { CSharpExtractor } from "./extractors/csharp.ts";
12
+ import { RubyExtractor } from "./extractors/ruby.ts";
13
+
14
+ import { getLanguageCapability } from "./language-capabilities.ts";
15
+
16
+ export class ASTParserEngine {
17
+ public static isSourceFile(filePath: string): boolean {
18
+ return getLanguageCapability(filePath) !== undefined;
19
+ }
20
+ private extractors: CodeExtractor[];
21
+
22
+ constructor() {
23
+ this.extractors = [
24
+ new BladeExtractor(),
25
+ new FrontendExtractor(),
26
+ new TypeScriptExtractor(),
27
+ new PHPExtractor(),
28
+ new PythonExtractor(),
29
+ new GoExtractor(),
30
+ new RustExtractor(),
31
+ new JavaExtractor(),
32
+ new CSharpExtractor(),
33
+ new RubyExtractor(),
34
+ ];
35
+ }
36
+
37
+ public async parseFile(filePath: string, content: string): Promise<ParsedFileAST> {
38
+ for (const extractor of this.extractors) {
39
+ if (extractor.canHandle(filePath)) {
40
+ const result = await extractor.extract(filePath, content);
41
+ const capability = getLanguageCapability(filePath);
42
+ return {
43
+ status: "parsed", ...result,
44
+ extraction: result.extraction ?? { method: capability?.method ?? "fallback", coverage: "partial" },
45
+ diagnostics: result.diagnostics ?? [],
46
+ };
47
+ }
48
+ }
49
+
50
+ // Default fallback extractor for unknown file types
51
+ return {
52
+ status: "unsupported",
53
+ extraction: { method: "unsupported", coverage: "none" },
54
+ diagnostics: [{ code: "extractor_unavailable", message: `No extractor registered for '${filePath}'.` }],
55
+ symbols: [],
56
+ dependencies: [],
57
+ };
58
+ }
59
+
60
+ public registerExtractor(extractor: CodeExtractor): void {
61
+ this.extractors.unshift(extractor);
62
+ }
63
+ }
@@ -0,0 +1,25 @@
1
+ import runtime from "web-tree-sitter/tree-sitter.wasm" with { type: "file" };
2
+ import typescript from "tree-sitter-wasms/out/tree-sitter-typescript.wasm" with { type: "file" };
3
+ import tsx from "tree-sitter-wasms/out/tree-sitter-tsx.wasm" with { type: "file" };
4
+ import javascript from "tree-sitter-wasms/out/tree-sitter-javascript.wasm" with { type: "file" };
5
+ import php from "tree-sitter-wasms/out/tree-sitter-php.wasm" with { type: "file" };
6
+ import python from "tree-sitter-wasms/out/tree-sitter-python.wasm" with { type: "file" };
7
+ import go from "tree-sitter-wasms/out/tree-sitter-go.wasm" with { type: "file" };
8
+ import rust from "tree-sitter-wasms/out/tree-sitter-rust.wasm" with { type: "file" };
9
+ import java from "tree-sitter-wasms/out/tree-sitter-java.wasm" with { type: "file" };
10
+ import csharp from "tree-sitter-wasms/out/tree-sitter-c_sharp.wasm" with { type: "file" };
11
+ import ruby from "tree-sitter-wasms/out/tree-sitter-ruby.wasm" with { type: "file" };
12
+
13
+ export const WASM_ASSETS: Record<string, string> = {
14
+ "tree-sitter.wasm": runtime,
15
+ "tree-sitter-typescript.wasm": typescript,
16
+ "tree-sitter-tsx.wasm": tsx,
17
+ "tree-sitter-javascript.wasm": javascript,
18
+ "tree-sitter-php.wasm": php,
19
+ "tree-sitter-python.wasm": python,
20
+ "tree-sitter-go.wasm": go,
21
+ "tree-sitter-rust.wasm": rust,
22
+ "tree-sitter-java.wasm": java,
23
+ "tree-sitter-c_sharp.wasm": csharp,
24
+ "tree-sitter-ruby.wasm": ruby,
25
+ };