@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,486 @@
1
+ import { ImportResolver } from "./import-resolver.ts";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import type { ValidatedSeptumConfig } from "../config/schema.ts";
5
+ import type { SeptumRepository } from "../database/repository.ts";
6
+ import { assertUniqueDomainRoots } from "../config/domain-ownership.ts";
7
+
8
+ export interface PathAliasRule {
9
+ prefix: string;
10
+ targets: string[];
11
+ }
12
+
13
+ export interface Psr4Rule {
14
+ prefix: string;
15
+ baseDir: string;
16
+ }
17
+
18
+ export class ModuleResolver {
19
+ private projectRoot: string;
20
+ private repo?: SeptumRepository;
21
+ private tsPaths: PathAliasRule[] = [];
22
+ private tsBaseUrl: string = ".";
23
+ private psr4Rules: Psr4Rule[] = [];
24
+ private configsLoaded = false;
25
+ private fileDomainCache?: Map<string, string>;
26
+ private symbolDomainCache?: Map<string, string>;
27
+ private packageNameCache?: Map<string, string | null>;
28
+
29
+ constructor(projectRoot: string = process.cwd(), repo?: SeptumRepository) {
30
+ this.projectRoot = path.resolve(projectRoot);
31
+ this.repo = repo;
32
+ }
33
+
34
+ public resolveImport(target: string, sourceFile: string, statement?: string) {
35
+ return new ImportResolver(this.projectRoot, this.repo?.getAllDomains?.().map(domain => domain.root_path) ?? []).resolve(target, sourceFile, statement);
36
+ }
37
+
38
+ public setRepository(repo: SeptumRepository): void {
39
+ this.repo = repo;
40
+ this.fileDomainCache = undefined;
41
+ this.symbolDomainCache = undefined;
42
+ }
43
+
44
+ public getProjectRoot(): string {
45
+ return this.projectRoot;
46
+ }
47
+
48
+ /**
49
+ * Lazily loads project configuration files (tsconfig.json, composer.json)
50
+ */
51
+ public ensureConfigLoaded(): void {
52
+ if (this.configsLoaded) return;
53
+ this.loadTsConfig();
54
+ this.loadComposerJson();
55
+ this.configsLoaded = true;
56
+ }
57
+
58
+ private ensureRepoCachesLoaded(): void {
59
+ if (!this.repo) return;
60
+ if (this.fileDomainCache && this.symbolDomainCache) return;
61
+
62
+ this.fileDomainCache = new Map<string, string>();
63
+ this.symbolDomainCache = new Map<string, string>();
64
+
65
+ if (
66
+ typeof this.repo.getAllDomains === "function" &&
67
+ typeof this.repo.getAllFiles === "function"
68
+ ) {
69
+ const domains = this.repo.getAllDomains();
70
+ const domainById = new Map<number, string>();
71
+ for (const d of domains) {
72
+ domainById.set(d.id, d.name);
73
+ }
74
+
75
+ const files = this.repo.getAllFiles();
76
+ const domainByFilePath = new Map<string, string>();
77
+ for (const f of files) {
78
+ const domName = domainById.get(f.domain_id);
79
+ if (domName) {
80
+ this.fileDomainCache.set(f.path, domName);
81
+ const norm = f.path.replace(/\\/g, "/");
82
+ this.fileDomainCache.set(norm, domName);
83
+ domainByFilePath.set(f.path, domName);
84
+ }
85
+ }
86
+
87
+ if (typeof this.repo.getAllSymbolsWithFiles === "function") {
88
+ const symbols = this.repo.getAllSymbolsWithFiles();
89
+ for (const s of symbols) {
90
+ const domName = domainByFilePath.get(s.file_path) ?? this.fileDomainCache.get(s.file_path);
91
+ if (domName && !this.symbolDomainCache.has(s.name)) {
92
+ this.symbolDomainCache.set(s.name, domName);
93
+ }
94
+ }
95
+ }
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Resolves the domain that owns the given source file.
101
+ */
102
+ public resolveSourceDomain(
103
+ filePath: string,
104
+ config: ValidatedSeptumConfig
105
+ ): string | null {
106
+ assertUniqueDomainRoots(config.domains, this.projectRoot);
107
+ return this.matchDomainByPath(filePath, config);
108
+ }
109
+
110
+ /**
111
+ * Deterministically resolves an imported module/target to its target domain.
112
+ */
113
+ public resolveTargetDomain(
114
+ targetStatement: string,
115
+ sourceFilePath: string | undefined,
116
+ config: ValidatedSeptumConfig,
117
+ statement?: string
118
+ ): string | null {
119
+ assertUniqueDomainRoots(config.domains, this.projectRoot);
120
+ if (sourceFilePath && (fs.existsSync(path.resolve(this.projectRoot,sourceFilePath)) || this.repo?.getMeta?.("workspace_root"))) {
121
+ const resolution = this.resolveImport(targetStatement,sourceFilePath,statement);
122
+ if (resolution.status !== "resolved" || resolution.coverage === "conditional") return null;
123
+ const domains = [...new Set(resolution.targets.flatMap(target => target.files.map(file => this.matchDomainByPath(file,config))).filter((d): d is string => !!d))];
124
+ return domains.length === 1 ? domains[0]! : null;
125
+ }
126
+ // Legacy index-only/path-policy callers have no physical source evidence.
127
+ this.ensureConfigLoaded();
128
+
129
+ const normalizedTarget = targetStatement.trim().replace(/^['"]|['"]$/g, "");
130
+ if (!normalizedTarget) return null;
131
+
132
+ // 1. Relative imports: ./ or ../ or Python dot relative . or ..
133
+ if (normalizedTarget.startsWith("./") || normalizedTarget.startsWith("../")) {
134
+ if (sourceFilePath) {
135
+ const sourceAbs = this.toAbsolutePath(sourceFilePath);
136
+ const sourceDir = path.dirname(sourceAbs);
137
+ const resolvedCandidate = path.resolve(sourceDir, normalizedTarget);
138
+ const domainFromPath = this.matchDomainByPath(resolvedCandidate, config);
139
+ if (domainFromPath) return domainFromPath;
140
+ }
141
+ } else if (normalizedTarget.startsWith(".")) {
142
+ // Python style relative import (e.g. .service, ..billing.service)
143
+ if (sourceFilePath) {
144
+ const sourceAbs = this.toAbsolutePath(sourceFilePath);
145
+ const sourceDir = path.dirname(sourceAbs);
146
+ const dotMatch = /^\.+/.exec(normalizedTarget);
147
+ if (dotMatch) {
148
+ const dotCount = dotMatch[0].length;
149
+ const remainder = normalizedTarget.slice(dotCount).replace(/\./g, path.sep);
150
+ const upSteps = "../".repeat(Math.max(0, dotCount - 1));
151
+ const resolvedCandidate = path.resolve(sourceDir, upSteps, remainder);
152
+ const domainFromPath = this.matchDomainByPath(resolvedCandidate, config);
153
+ if (domainFromPath) return domainFromPath;
154
+ }
155
+ }
156
+ }
157
+
158
+ // 2. Workspace Package Name Resolution (e.g. @repo/shared-types, @repo/design-system)
159
+ const domainFromPackage = this.matchDomainByPackageName(normalizedTarget, config);
160
+ if (domainFromPackage) return domainFromPackage;
161
+
162
+ // 3. Python Absolute Dot-notation: domains.billing.service or app.domains.billing
163
+ if (normalizedTarget.includes(".") && !normalizedTarget.includes("/")) {
164
+ const asPath = normalizedTarget.replace(/\./g, path.sep);
165
+ const candidatePath = path.resolve(this.projectRoot, asPath);
166
+ const domainFromPython = this.matchDomainByPath(candidatePath, config);
167
+ if (domainFromPython) return domainFromPython;
168
+ }
169
+
170
+ // 3. TypeScript Path Aliases (tsconfig.json paths)
171
+ const tsResolved = this.resolveTsPathAlias(normalizedTarget);
172
+ if (tsResolved) {
173
+ const domainFromTs = this.matchDomainByPath(tsResolved, config);
174
+ if (domainFromTs) return domainFromTs;
175
+ }
176
+
177
+ // 4. PHP PSR-4 Namespaces (composer.json autoload)
178
+ const phpResolved = this.resolvePsr4Namespace(normalizedTarget);
179
+ if (phpResolved) {
180
+ const domainFromPhp = this.matchDomainByPath(phpResolved, config);
181
+ if (domainFromPhp) return domainFromPhp;
182
+ }
183
+
184
+ // 4. Database-driven direct file & symbol lookup (pre-cached in memory to eliminate N+1)
185
+ if (this.repo) {
186
+ this.ensureRepoCachesLoaded();
187
+ const normKey = normalizedTarget.replace(/\\/g, "/");
188
+ const cachedFileDomain =
189
+ this.fileDomainCache?.get(normalizedTarget) ?? this.fileDomainCache?.get(normKey);
190
+ if (cachedFileDomain !== undefined) {
191
+ if (cachedFileDomain) return cachedFileDomain;
192
+ } else if (typeof this.repo.getFileWithDomain === "function") {
193
+ const fileRecord = this.repo.getFileWithDomain(normalizedTarget);
194
+ const domName = fileRecord?.domain_name ?? "";
195
+ this.fileDomainCache?.set(normalizedTarget, domName);
196
+ this.fileDomainCache?.set(normKey, domName);
197
+ if (domName) return domName;
198
+ }
199
+
200
+ // 5. Database-driven symbol lookup
201
+ const symbolName = this.extractSymbolName(normalizedTarget);
202
+ if (symbolName) {
203
+ const cachedSymDomain = this.symbolDomainCache?.get(symbolName);
204
+ if (cachedSymDomain !== undefined) {
205
+ if (cachedSymDomain) return cachedSymDomain;
206
+ } else if (typeof this.repo.findSymbolWithDomain === "function") {
207
+ const symbolRecord = this.repo.findSymbolWithDomain(symbolName);
208
+ const domName = symbolRecord?.domain_name ?? "";
209
+ this.symbolDomainCache?.set(symbolName, domName);
210
+ if (domName) return domName;
211
+ }
212
+ }
213
+ }
214
+
215
+ // 6. Root path segment matching (fallback for explicit domain root references)
216
+ // Only apply if the target explicitly references a domain root or is a path within the workspace
217
+ const normalizedSlash = normalizedTarget.replace(/\\/g, "/").toLowerCase();
218
+ const isBarePackage =
219
+ !normalizedTarget.startsWith(".") &&
220
+ !normalizedTarget.startsWith("/") &&
221
+ !normalizedTarget.includes(path.sep) &&
222
+ !normalizedTarget.includes("/");
223
+
224
+ if (!isBarePackage) {
225
+ for (const [domainName, domainCfg] of Object.entries(config.domains)) {
226
+ const domainRootSlash = domainCfg.root.replace(/\\/g, "/").replace(/^\.\//, "").toLowerCase();
227
+
228
+ if (
229
+ normalizedSlash === domainRootSlash ||
230
+ normalizedSlash.startsWith(`${domainRootSlash}/`) ||
231
+ normalizedSlash.includes(`/${domainRootSlash}/`)
232
+ ) {
233
+ return domainName;
234
+ }
235
+
236
+ const candidateAbs = path.resolve(this.projectRoot, normalizedTarget);
237
+ const domainAbsRoot = this.toAbsolutePath(domainCfg.root);
238
+ if (this.isSubPathOrSame(candidateAbs, domainAbsRoot) && fs.existsSync(candidateAbs)) {
239
+ return domainName;
240
+ }
241
+ }
242
+ }
243
+
244
+ return null;
245
+ }
246
+
247
+ private matchDomainByPath(targetPath: string, config: ValidatedSeptumConfig): string | null {
248
+ const absTargetPath = this.toAbsolutePath(targetPath);
249
+
250
+ const sortedDomains = Object.entries(config.domains)
251
+ .map(([domainName, domainCfg]) => ({
252
+ domainName,
253
+ domainCfg,
254
+ absRoot: this.toAbsolutePath(domainCfg.root),
255
+ }))
256
+ .sort((a, b) => b.absRoot.length - a.absRoot.length);
257
+
258
+ for (const { domainName, absRoot } of sortedDomains) {
259
+ if (this.isSubPathOrSame(absTargetPath, absRoot)) {
260
+ return domainName;
261
+ }
262
+ }
263
+
264
+ return null;
265
+ }
266
+
267
+ private matchDomainByPackageName(target: string, config: ValidatedSeptumConfig): string | null {
268
+ if (!this.packageNameCache) {
269
+ this.packageNameCache = new Map<string, string | null>();
270
+ }
271
+
272
+ for (const [domainName, domainCfg] of Object.entries(config.domains)) {
273
+ const pkgJsonPath = path.resolve(this.projectRoot, domainCfg.root, "package.json");
274
+ const cached = this.packageNameCache.get(pkgJsonPath);
275
+ let pkgName: string | null = cached ?? null;
276
+ if (cached === undefined) {
277
+ if (fs.existsSync(pkgJsonPath)) {
278
+ try {
279
+ const raw = fs.readFileSync(pkgJsonPath, "utf8");
280
+ const pkg = JSON.parse(raw);
281
+ if (pkg.name && typeof pkg.name === "string") {
282
+ pkgName = pkg.name;
283
+ }
284
+ } catch {
285
+ // Ignore unreadable or invalid package.json
286
+ }
287
+ }
288
+ this.packageNameCache.set(pkgJsonPath, pkgName);
289
+ }
290
+
291
+ if (pkgName && (target === pkgName || target.startsWith(`${pkgName}/`))) {
292
+ return domainName;
293
+ }
294
+ }
295
+ return null;
296
+ }
297
+
298
+ public toCanonicalPath(filePath: string): string {
299
+ let resolved = path.isAbsolute(filePath)
300
+ ? path.normalize(filePath)
301
+ : path.resolve(this.projectRoot, filePath);
302
+
303
+ if (process.platform === "win32") {
304
+ // Normalize drive letter to uppercase (e.g. c:\ -> C:\)
305
+ resolved = resolved.replace(/^[a-zA-Z]:/, (m) => m.toUpperCase());
306
+ }
307
+ return resolved;
308
+ }
309
+
310
+ private isSubPathOrSame(targetPath: string, rootPath: string): boolean {
311
+ const canonicalTarget = this.toCanonicalPath(targetPath);
312
+ const canonicalRoot = this.toCanonicalPath(rootPath);
313
+
314
+ if (process.platform === "win32") {
315
+ const lowerTarget = canonicalTarget.toLowerCase();
316
+ const lowerRoot = canonicalRoot.toLowerCase();
317
+ if (lowerTarget === lowerRoot) return true;
318
+ const rootWithSep = lowerRoot.endsWith(path.sep)
319
+ ? lowerRoot
320
+ : lowerRoot + path.sep;
321
+ return lowerTarget.startsWith(rootWithSep);
322
+ }
323
+
324
+ if (canonicalTarget === canonicalRoot) return true;
325
+ const rootWithSep = canonicalRoot.endsWith(path.sep)
326
+ ? canonicalRoot
327
+ : canonicalRoot + path.sep;
328
+
329
+ return canonicalTarget.startsWith(rootWithSep);
330
+ }
331
+
332
+ private toAbsolutePath(filePath: string): string {
333
+ return this.toCanonicalPath(filePath);
334
+ }
335
+
336
+ private extractSymbolName(target: string): string | null {
337
+ // PHP namespace or TS qualified name: Foo\Bar\Baz or Foo/Bar/Baz or bare Baz
338
+ const cleaned = target.replace(/\\/g, "/");
339
+ const parts = cleaned.split("/").filter(Boolean);
340
+ const lastPart = parts[parts.length - 1];
341
+ if (lastPart && /^[A-Z][a-zA-Z0-9_]*$/.test(lastPart)) {
342
+ return lastPart;
343
+ }
344
+ return null;
345
+ }
346
+
347
+ public fileExistsOnDisk(targetPath: string): boolean {
348
+ if (fs.existsSync(targetPath)) {
349
+ try {
350
+ const stat = fs.statSync(targetPath);
351
+ if (stat.isFile()) return true;
352
+ if (stat.isDirectory()) {
353
+ const indexExtensions = [".ts", ".tsx", ".js", ".jsx", ".d.ts"];
354
+ for (const ext of indexExtensions) {
355
+ if (fs.existsSync(path.join(targetPath, `index${ext}`))) {
356
+ return true;
357
+ }
358
+ }
359
+ }
360
+ } catch {
361
+ return false;
362
+ }
363
+ }
364
+
365
+ const extensions = [".ts", ".tsx", ".js", ".jsx", ".d.ts", ".json"];
366
+ for (const ext of extensions) {
367
+ if (fs.existsSync(targetPath + ext)) {
368
+ return true;
369
+ }
370
+ }
371
+
372
+ const indexExtensions = [".ts", ".tsx", ".js", ".jsx", ".d.ts"];
373
+ for (const ext of indexExtensions) {
374
+ if (fs.existsSync(path.join(targetPath, `index${ext}`))) {
375
+ return true;
376
+ }
377
+ }
378
+
379
+ return false;
380
+ }
381
+
382
+ private resolveTsPathAlias(target: string): string | null {
383
+ for (const rule of this.tsPaths) {
384
+ if (rule.prefix.endsWith("*")) {
385
+ const basePrefix = rule.prefix.slice(0, -1);
386
+ if (target.startsWith(basePrefix)) {
387
+ const suffix = target.slice(basePrefix.length);
388
+ for (const targetPattern of rule.targets) {
389
+ const candidate = targetPattern.replace("*", suffix);
390
+ const baseDir = path.resolve(this.projectRoot, this.tsBaseUrl);
391
+ const resolved = path.resolve(baseDir, candidate);
392
+ if (this.fileExistsOnDisk(resolved)) {
393
+ return resolved;
394
+ }
395
+ }
396
+ }
397
+ } else if (target === rule.prefix) {
398
+ for (const targetPattern of rule.targets) {
399
+ const baseDir = path.resolve(this.projectRoot, this.tsBaseUrl);
400
+ const resolved = path.resolve(baseDir, targetPattern);
401
+ if (this.fileExistsOnDisk(resolved)) {
402
+ return resolved;
403
+ }
404
+ }
405
+ }
406
+ }
407
+ return null;
408
+ }
409
+
410
+ private resolvePsr4Namespace(target: string): string | null {
411
+ // PHP PSR-4: App\Domain\Billing\Service -> app/Domain/Billing/Service.php
412
+ const normalizedTarget = target.replace(/\//g, "\\");
413
+
414
+ for (const rule of this.psr4Rules) {
415
+ if (normalizedTarget.startsWith(rule.prefix)) {
416
+ const subNamespace = normalizedTarget.slice(rule.prefix.length);
417
+ const subPath = subNamespace.replace(/\\/g, path.sep);
418
+ const resolved = path.resolve(this.projectRoot, rule.baseDir, subPath);
419
+ if (!resolved.endsWith(".php") && !resolved.endsWith(".inc")) {
420
+ const withPhp = `${resolved}.php`;
421
+ if (fs.existsSync(withPhp)) {
422
+ return withPhp;
423
+ }
424
+ }
425
+ return resolved;
426
+ }
427
+ }
428
+ return null;
429
+ }
430
+
431
+ private loadTsConfig(): void {
432
+ const tsconfigPath = path.join(this.projectRoot, "tsconfig.json");
433
+ if (!fs.existsSync(tsconfigPath)) return;
434
+
435
+ try {
436
+ const raw = fs.readFileSync(tsconfigPath, "utf-8");
437
+ // Strip comments (simple JSON with comments regex)
438
+ const cleanJson = raw.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
439
+ const parsed = JSON.parse(cleanJson);
440
+ const compilerOptions = parsed.compilerOptions ?? {};
441
+
442
+ this.tsBaseUrl = compilerOptions.baseUrl ?? ".";
443
+
444
+ if (compilerOptions.paths && typeof compilerOptions.paths === "object") {
445
+ for (const [key, val] of Object.entries(compilerOptions.paths)) {
446
+ const targets = Array.isArray(val) ? (val as string[]) : [String(val)];
447
+ this.tsPaths.push({
448
+ prefix: key,
449
+ targets,
450
+ });
451
+ }
452
+ }
453
+ } catch {
454
+ // Graceful fallback if tsconfig is malformed
455
+ }
456
+ }
457
+
458
+ private loadComposerJson(): void {
459
+ const composerPath = path.join(this.projectRoot, "composer.json");
460
+ if (!fs.existsSync(composerPath)) return;
461
+
462
+ try {
463
+ const raw = fs.readFileSync(composerPath, "utf-8");
464
+ const parsed = JSON.parse(raw);
465
+
466
+ const extractPsr4 = (section: Record<string, unknown> | undefined) => {
467
+ if (section && typeof section["psr-4"] === "object" && section["psr-4"] !== null) {
468
+ for (const [ns, dir] of Object.entries(section["psr-4"] as Record<string, string>)) {
469
+ this.psr4Rules.push({
470
+ prefix: ns,
471
+ baseDir: String(dir),
472
+ });
473
+ }
474
+ }
475
+ };
476
+
477
+ extractPsr4(parsed.autoload);
478
+ extractPsr4(parsed["autoload-dev"]);
479
+
480
+ // Sort longest-prefix-first to prevent short prefixes from shadowing specific ones
481
+ this.psr4Rules.sort((a, b) => b.prefix.length - a.prefix.length);
482
+ } catch {
483
+ // Graceful fallback if composer.json is malformed
484
+ }
485
+ }
486
+ }
@@ -0,0 +1,200 @@
1
+ import { existsSync, statSync, realpathSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, normalize, relative, resolve } from "node:path";
3
+
4
+ export const PROJECT_ROOT_MARKERS = [
5
+ "package.json",
6
+ "composer.json",
7
+ "go.mod",
8
+ "pyproject.toml",
9
+ "Cargo.toml",
10
+ ".git",
11
+ ".septum",
12
+ "pnpm-workspace.yaml",
13
+ "lerna.json",
14
+ "tsconfig.json",
15
+ "jsconfig.json",
16
+ ];
17
+
18
+ let lastKnownProjectRoot: string | undefined;
19
+
20
+ /**
21
+ * Normalizes and canonicalizes a path for cross-platform consistency.
22
+ * On Windows, uppercases drive letters (e.g. "c:\" -> "C:\") to eliminate map lookup misses.
23
+ */
24
+ export function canonicalizePath(targetPath: string): string {
25
+ if (!targetPath || typeof targetPath !== "string") {
26
+ return targetPath;
27
+ }
28
+ let abs = normalize(resolve(targetPath));
29
+ try { if (existsSync(abs)) abs = realpathSync(abs); } catch { /* Keep lexical paths for missing or inaccessible files. */ }
30
+ if (process.platform === "win32") {
31
+ abs = abs.replace(/^[a-zA-Z]:/, (m) => m.toUpperCase());
32
+ }
33
+ return abs;
34
+ }
35
+
36
+ export function setLastKnownProjectRoot(root: string): void {
37
+ if (root && typeof root === "string") {
38
+ lastKnownProjectRoot = canonicalizePath(root);
39
+ }
40
+ }
41
+
42
+ export function getLastKnownProjectRoot(): string | undefined {
43
+ return lastKnownProjectRoot;
44
+ }
45
+
46
+ export function clearLastKnownProjectRoot(): void {
47
+ lastKnownProjectRoot = undefined;
48
+ }
49
+
50
+ /**
51
+ * Checks whether a given directory is an MCP host / IDE installation directory
52
+ * (e.g. Antigravity Electron install directory) rather than a user project codebase.
53
+ */
54
+ export function isAppHostDirectory(dirPath: string): boolean {
55
+ try {
56
+ const norm = dirPath.toLowerCase().replace(/\\/g, "/");
57
+ if (norm.includes("/antigravity") || norm.includes("/appdata/local/programs/antigravity")) {
58
+ // Check if it has Electron app runtime signatures
59
+ if (
60
+ existsSync(join(dirPath, "resources", "app.asar")) ||
61
+ existsSync(join(dirPath, "resources", "app.asar.unpacked")) ||
62
+ existsSync(join(dirPath, "locales"))
63
+ ) {
64
+ return true;
65
+ }
66
+ }
67
+ } catch {
68
+ // Ignore error
69
+ }
70
+ return false;
71
+ }
72
+
73
+ /**
74
+ * Discovers the project root directory by walking up looking for marker files.
75
+ */
76
+ export function findProjectRoot(fromPath: string): string {
77
+ try {
78
+ let dir = resolve(fromPath);
79
+
80
+ if (existsSync(dir)) {
81
+ const stat = statSync(dir);
82
+ if (!stat.isDirectory()) {
83
+ dir = dirname(dir);
84
+ }
85
+ } else {
86
+ dir = dirname(dir);
87
+ }
88
+
89
+ let current = dir;
90
+ while (true) {
91
+ // Don't treat an app host directory as a project root
92
+ if (!isAppHostDirectory(current)) {
93
+ for (const marker of PROJECT_ROOT_MARKERS) {
94
+ if (existsSync(join(current, marker))) {
95
+ return canonicalizePath(current);
96
+ }
97
+ }
98
+ }
99
+
100
+ const parent = dirname(current);
101
+ if (parent === current) break;
102
+ current = parent;
103
+ }
104
+ } catch {
105
+ // Filesystem traversal error fallback
106
+ }
107
+
108
+ return canonicalizePath(existsSync(fromPath) && statSync(fromPath).isDirectory() ? fromPath : dirname(resolve(fromPath)));
109
+ }
110
+
111
+ /**
112
+ * Ergonomically resolves the active workspace root:
113
+ * 1. Explicit pathHint (if provided and valid).
114
+ * 2. SEPTUM_WORKSPACE_ROOT environment variable.
115
+ * 3. lastKnownProjectRoot (if cached from earlier tool calls).
116
+ * 4. findProjectRoot from process.cwd() (if not an app host directory).
117
+ */
118
+ export function resolveWorkspaceRoot(pathHint?: string): string {
119
+ if (pathHint && typeof pathHint === "string" && pathHint.trim()) {
120
+ const trimmed = pathHint.trim().replace(/^['"]|['"]$/g, "");
121
+ const absHint = resolve(trimmed);
122
+ const candidate = existsSync(absHint) && statSync(absHint).isDirectory() ? canonicalizePath(absHint) : findProjectRoot(trimmed);
123
+ if (candidate && existsSync(candidate) && !isAppHostDirectory(candidate)) {
124
+ setLastKnownProjectRoot(candidate);
125
+ return candidate;
126
+ }
127
+ }
128
+
129
+ const envRoot = process.env.SEPTUM_WORKSPACE_ROOT || process.env.WORKSPACE_ROOT;
130
+ if (envRoot && existsSync(envRoot) && !isAppHostDirectory(envRoot)) {
131
+ const candidate = canonicalizePath(envRoot);
132
+ setLastKnownProjectRoot(candidate);
133
+ return candidate;
134
+ }
135
+
136
+ if (lastKnownProjectRoot && existsSync(lastKnownProjectRoot)) {
137
+ return lastKnownProjectRoot;
138
+ }
139
+
140
+ const cwd = process.cwd();
141
+ if (!isAppHostDirectory(cwd)) {
142
+ const candidate = findProjectRoot(cwd);
143
+ setLastKnownProjectRoot(candidate);
144
+ return candidate;
145
+ }
146
+
147
+ // Fallback if inside app host directory: keep looking in lastKnown or return cwd
148
+ return canonicalizePath(cwd);
149
+ }
150
+
151
+ /**
152
+ * Verifies that candidatePath is strictly contained within workspaceRoot.
153
+ * Resolves symlinks (realpath) if the path exists, and checks ancestor realpath if not yet created.
154
+ */
155
+ export function isPathContained(candidatePath: string, workspaceRoot: string): boolean {
156
+ if (!candidatePath || !workspaceRoot) return false;
157
+ try {
158
+ const canonicalWorkspace = canonicalizePath(workspaceRoot);
159
+ const resolvedTarget = isAbsolute(candidatePath) ? normalize(candidatePath) : resolve(canonicalWorkspace, candidatePath);
160
+
161
+ // Lexical containment
162
+ const relLexical = relative(canonicalWorkspace, resolvedTarget).replace(/\\/g, "/");
163
+ if (relLexical === ".." || relLexical.startsWith("../") || isAbsolute(relLexical)) {
164
+ return false;
165
+ }
166
+
167
+ // Realpath / symlink containment
168
+ if (existsSync(resolvedTarget)) {
169
+ const realTarget = realpathSync(resolvedTarget);
170
+ const relReal = relative(canonicalWorkspace, realTarget).replace(/\\/g, "/");
171
+ if (relReal === ".." || relReal.startsWith("../") || isAbsolute(relReal)) {
172
+ return false;
173
+ }
174
+ } else {
175
+ let cur = dirname(resolvedTarget);
176
+ while (!existsSync(cur)) {
177
+ const parent = dirname(cur);
178
+ if (parent === cur) break;
179
+ cur = parent;
180
+ }
181
+ if (existsSync(cur)) {
182
+ const realCur = realpathSync(cur);
183
+ const relCur = relative(canonicalWorkspace, realCur).replace(/\\/g, "/");
184
+ if (relCur === ".." || relCur.startsWith("../") || isAbsolute(relCur)) {
185
+ return false;
186
+ }
187
+ }
188
+ }
189
+
190
+ return true;
191
+ } catch {
192
+ return false;
193
+ }
194
+ }
195
+
196
+ export function assertPathContained(candidatePath: string, workspaceRoot: string, contextDescription = "Path"): void {
197
+ if (!isPathContained(candidatePath, workspaceRoot)) {
198
+ throw new Error(`${contextDescription} '${candidatePath}' escapes workspace boundary '${workspaceRoot}'.`);
199
+ }
200
+ }