@dimassetoid/septum-mcp 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -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 +122 -0
  7. package/src/cli/commands/hook.ts +268 -0
  8. package/src/cli/commands/init.ts +553 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +41 -0
  11. package/src/cli/commands/topology.ts +161 -0
  12. package/src/cli/index.ts +167 -0
  13. package/src/cli/scaffold/harness-config.ts +621 -0
  14. package/src/cli/templates/hooks.ts +75 -0
  15. package/src/cli/templates/rules.ts +50 -0
  16. package/src/cli/templates/skill.ts +51 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +442 -0
  19. package/src/core/boundary/staged-auditor.ts +58 -0
  20. package/src/core/config/loader.ts +122 -0
  21. package/src/core/config/schema.ts +69 -0
  22. package/src/core/database/client.ts +60 -0
  23. package/src/core/database/repositories/dependency.repository.ts +712 -0
  24. package/src/core/database/repositories/domain.repository.ts +330 -0
  25. package/src/core/database/repositories/environment.repository.ts +207 -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 +508 -0
  29. package/src/core/database/repository.ts +303 -0
  30. package/src/core/database/schema.ts +154 -0
  31. package/src/core/discovery/topology-detector.ts +805 -0
  32. package/src/core/ingestion/hasher.ts +5 -0
  33. package/src/core/ingestion/pipeline.ts +623 -0
  34. package/src/core/parser/behavioral-analyzer.ts +119 -0
  35. package/src/core/parser/boundary-tracker.ts +443 -0
  36. package/src/core/parser/extractors/base.ts +67 -0
  37. package/src/core/parser/extractors/blade.ts +159 -0
  38. package/src/core/parser/extractors/csharp.ts +244 -0
  39. package/src/core/parser/extractors/django-semantic.ts +687 -0
  40. package/src/core/parser/extractors/elysia-semantic.ts +538 -0
  41. package/src/core/parser/extractors/express-semantic.ts +444 -0
  42. package/src/core/parser/extractors/fastapi-semantic.ts +736 -0
  43. package/src/core/parser/extractors/fastify-semantic.ts +774 -0
  44. package/src/core/parser/extractors/flask-semantic.ts +515 -0
  45. package/src/core/parser/extractors/frontend.ts +149 -0
  46. package/src/core/parser/extractors/go-semantic.ts +611 -0
  47. package/src/core/parser/extractors/go.ts +491 -0
  48. package/src/core/parser/extractors/hono-semantic.ts +567 -0
  49. package/src/core/parser/extractors/java.ts +225 -0
  50. package/src/core/parser/extractors/laravel-semantic.ts +1122 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +368 -0
  52. package/src/core/parser/extractors/nestjs-semantic.ts +543 -0
  53. package/src/core/parser/extractors/php.ts +569 -0
  54. package/src/core/parser/extractors/python.ts +498 -0
  55. package/src/core/parser/extractors/registry.ts +78 -0
  56. package/src/core/parser/extractors/ruby.ts +234 -0
  57. package/src/core/parser/extractors/rust.ts +286 -0
  58. package/src/core/parser/extractors/semantic-extractor.interface.ts +22 -0
  59. package/src/core/parser/extractors/symfony-semantic.ts +354 -0
  60. package/src/core/parser/extractors/typescript.ts +826 -0
  61. package/src/core/parser/language-capabilities.ts +71 -0
  62. package/src/core/parser/schema/providers/laravel-migration-provider.ts +216 -0
  63. package/src/core/parser/schema/providers/prisma-schema-provider.ts +90 -0
  64. package/src/core/parser/schema/schema-provider-registry.ts +43 -0
  65. package/src/core/parser/schema/schema-provider.interface.ts +33 -0
  66. package/src/core/parser/tree-sitter.ts +63 -0
  67. package/src/core/parser/wasm-assets.ts +25 -0
  68. package/src/core/parser/wasm-loader.ts +274 -0
  69. package/src/core/resolver/call-graph-tracer.ts +724 -0
  70. package/src/core/resolver/import-resolver.ts +437 -0
  71. package/src/core/resolver/module-resolver.ts +482 -0
  72. package/src/core/resolver/path-resolver.ts +200 -0
  73. package/src/core/resolver/symbol-locator.ts +276 -0
  74. package/src/core/resolver/symbol-reference.ts +53 -0
  75. package/src/core/resolver/vertical-slice-tracer.ts +366 -0
  76. package/src/core/resources/ignore.ts +123 -0
  77. package/src/core/resources/limits.ts +14 -0
  78. package/src/core/resources/source-files.ts +62 -0
  79. package/src/core/resources/work-queue.ts +74 -0
  80. package/src/core/session/session-manager.ts +107 -0
  81. package/src/core/telemetry/telemetry.ts +97 -0
  82. package/src/core/topology/environment-detector.ts +973 -0
  83. package/src/core/topology/types.ts +83 -0
  84. package/src/index.ts +21 -0
  85. package/src/mcp/schemas.ts +1105 -0
  86. package/src/mcp/server.ts +774 -0
  87. package/src/mcp/tools/boundary.ts +17 -0
  88. package/src/mcp/tools/check-boundary.ts +387 -0
  89. package/src/mcp/tools/domain.ts +40 -0
  90. package/src/mcp/tools/feature.ts +67 -0
  91. package/src/mcp/tools/get-domain-catalog.ts +226 -0
  92. package/src/mcp/tools/get-environment-topology.ts +138 -0
  93. package/src/mcp/tools/get-feature-context.ts +224 -0
  94. package/src/mcp/tools/get-symbol-hotspots.ts +54 -0
  95. package/src/mcp/tools/get-symbol-impact.ts +64 -0
  96. package/src/mcp/tools/get-symbol.ts +175 -0
  97. package/src/mcp/tools/locate-symbol.ts +196 -0
  98. package/src/mcp/tools/register-domain.ts +75 -0
  99. package/src/mcp/tools/register-feature.ts +110 -0
  100. package/src/mcp/tools/slice.ts +16 -0
  101. package/src/mcp/tools/symbol.ts +93 -0
  102. package/src/mcp/tools/trace-vertical-slice.ts +80 -0
  103. package/src/mcp/workspace-manager.ts +159 -0
  104. package/src/mcp/workspace-watcher.ts +202 -0
  105. package/src/types/index.ts +456 -0
  106. package/src/types/wasm.d.ts +4 -0
  107. package/src/utils/version-check.ts +209 -0
  108. package/src/version.ts +1 -0
@@ -0,0 +1,437 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { builtinModules } from "node:module";
4
+ import { computeContentHash } from "../ingestion/hasher.ts";
5
+ import { readSourceFile } from "../resources/source-files.ts";
6
+ import type { ImportResolution, ResolutionTarget } from "../../types/index.ts";
7
+
8
+ export const RESOLVER_REVISION = "3";
9
+ const GO_STDLIB = new Set("archive bufio builtin bytes cmp compress container context crypto database debug embed encoding errors expvar flag fmt go hash html image index io iter log maps math mime net os path plugin reflect regexp runtime slices sort strconv strings structs sync syscall testing text time unicode unique unsafe".split(" "));
10
+
11
+ const PYTHON_STDLIB = new Set("abc argparse array ast asyncio atexit base64 bdb binascii bisect builtins bz2 calendar cgi cgitb chunk cmath cmd code codecs codeop collections colorsys compileall concurrent configparser contextlib contextvars copy copyreg cProfile crypt csv ctypes curses dataclasses datetime dbm decimal difflib dis distutils doctest email encodings ensurepip enum errno faulthandler fcntl filecmp fileinput fnmatch fractions ftplib functools gc getopt getpass gettext glob graphlib gzip hashlib heapq hmac html http idlelib imaplib imghdr imp importlib inspect io ipaddress itertools json keyword lib2to3 linecache locale logging lzma mailbox mailcap marshal math mimetypes mmap modulefinder msilib msvcrt multiprocessing netrc nntplib numbers operator optparse os ossaudiodev pathlib pdb pickle pickletools pipes pkgutil platform plistlib poplib posix posixpath pprint profile pstats pty pwd py_compile pyclbr pydoc queue quopri random re readline reprlib resource rlcompleter runpy sched secrets select selectors shelve shlex shutil signal site smtpd smtplib sndhdr socket socketserver spwd sqlite3 ssl stat statistics string stringprep struct subprocess sunau symbol symtable sys sysconfig syslog tabnanny tarfile telnetlib tempfile termios test textwrap threading time timeit tkinter token tokenize tomllib trace traceback tracemalloc tty turtle turtledemo types typing unicodedata unittest urllib uu uuid venv warnings wave weakref webbrowser winreg winsound wsgiref xdrlib xml xmlrpc zipapp zipfile zipimport zlib zoneinfo".split(" "));
12
+
13
+ const PYTHON_DIST_TO_MODULE_MAP: Record<string, string[]> = {
14
+ pillow: ["pil"],
15
+ pyyaml: ["yaml"],
16
+ python_dotenv: ["dotenv"],
17
+ scikit_learn: ["sklearn"],
18
+ beautifulsoup4: ["bs4"],
19
+ opencv_python: ["cv2"],
20
+ protobuf: ["google"],
21
+ typing_extensions: ["typing_extensions"],
22
+ };
23
+
24
+ const PHP_STDLIB = new Set([
25
+ "stdClass", "Exception", "ErrorException", "Error", "TypeError", "ValueError", "ArgumentCountError",
26
+ "ArithmeticError", "DivisionByZeroError", "ParseError", "AssertionError", "DateTime", "DateTimeImmutable",
27
+ "DateTimeZone", "DateInterval", "DatePeriod", "PDO", "PDOStatement", "PDOException", "Closure", "Generator",
28
+ "Fiber", "Throwable", "Stringable", "Countable", "Iterator", "IteratorAggregate", "Traversable", "ArrayAccess",
29
+ "Serializable", "SplFileInfo", "SplFileObject", "SplFixedArray", "SplDoublyLinkedList", "SplQueue", "SplStack",
30
+ "SplHeap", "SplMinHeap", "SplMaxHeap", "SplPriorityQueue", "SplObserver", "SplSubject", "Reflection",
31
+ "ReflectionClass", "ReflectionMethod", "ReflectionFunction", "ReflectionProperty", "ReflectionParameter",
32
+ "ReflectionType", "ReflectionNamedType", "ReflectionUnionType", "ReflectionIntersectionType", "ReflectionAttribute",
33
+ "ReflectionEnum", "ReflectionEnumUnitCase", "ReflectionEnumBackedCase", "JsonException", "DomainException",
34
+ "InvalidArgumentException", "LengthException", "LogicException", "OutOfBoundsException", "OutOfRangeException",
35
+ "OverflowException", "RangeException", "RuntimeException", "UnderflowException", "UnexpectedValueException",
36
+ "BadFunctionCallException", "BadMethodCallException", "Attribute"
37
+ ]);
38
+
39
+ /** Static, workspace-contained resolution. No manifest scripts, downloads or retained cache. */
40
+ export class ImportResolver {
41
+ private root: string;
42
+ constructor(root: string, private packageRoots: string[] = []) { this.root = path.resolve(root); }
43
+
44
+ public resolve(target: string, sourceFile: string): ImportResolution {
45
+ const manifests: Record<string, string> = {};
46
+ const result: ImportResolution = {
47
+ status: "unresolved", targets: [], reason: "target_not_found", coverage: "partial",
48
+ resolver_revision: RESOLVER_REVISION, config_revision: "", source: { file: sourceFile, target },
49
+ };
50
+ const finish = (status: ImportResolution["status"], reason: string, targets: ResolutionTarget[] = []) => ({
51
+ ...result, status, reason, targets,
52
+ config_revision: computeContentHash(JSON.stringify({ root: this.root, revision: RESOLVER_REVISION, manifests })),
53
+ });
54
+ const read = (file: string): string | undefined => {
55
+ this.assertContained(file);
56
+ if (!fs.existsSync(file)) { manifests[path.relative(this.root, file)] = "missing"; return undefined; }
57
+ const text = readSourceFile(file); manifests[path.relative(this.root, file)] = computeContentHash(text); return text;
58
+ };
59
+ const json = (file: string): any => {
60
+ const raw = read(file); if (raw === undefined) return {};
61
+ const clean = raw.replace(/"(?:\\.|[^"\\])*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, token => token.startsWith('"') ? token : " ")
62
+ .replace(/"(?:\\.|[^"\\])*"|,\s*[}\]]/g, token => token.startsWith('"') ? token : token.slice(1));
63
+ const parsed = JSON.parse(clean);
64
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("malformed_manifest");
65
+ return parsed;
66
+ };
67
+ const filesAt = (base: string, extensions: string[]): string[] => {
68
+ this.assertContained(base);
69
+ const extraCandidates: string[] = [];
70
+ if (base.endsWith(".js")) {
71
+ const stripped = base.slice(0, -3);
72
+ extraCandidates.push(stripped + ".ts", stripped + ".tsx", stripped + ".d.ts", path.join(stripped, "index.ts"));
73
+ } else if (base.endsWith(".mjs")) {
74
+ const stripped = base.slice(0, -4);
75
+ extraCandidates.push(stripped + ".mts", stripped + ".d.mts");
76
+ } else if (base.endsWith(".cjs")) {
77
+ const stripped = base.slice(0, -4);
78
+ extraCandidates.push(stripped + ".cts", stripped + ".d.cts");
79
+ } else if (base.endsWith(".jsx")) {
80
+ const stripped = base.slice(0, -4);
81
+ extraCandidates.push(stripped + ".tsx");
82
+ }
83
+ const candidates = [base, ...extraCandidates, ...extensions.map(ext => base + ext), ...extensions.map(ext => path.join(base, "index" + ext))];
84
+ return [...new Set(candidates.filter(file => {
85
+ this.assertContained(file);
86
+ return fs.existsSync(file) && fs.statSync(file).isFile();
87
+ }).map(file => path.relative(this.root, file).replace(/\\/g, "/")))];
88
+ };
89
+ const resolvedFiles = (files: string[], reason: string) => {
90
+ const unique = [...new Set(files)].sort();
91
+ return finish(unique.length === 1 ? "resolved" : unique.length > 1 ? "ambiguous" : "unresolved", reason,
92
+ unique.map(file => ({ kind: "file", files: [file] })));
93
+ };
94
+ try {
95
+ if (target.startsWith("dynamic:")) return finish("unresolved", "dynamic_target");
96
+ const source = path.resolve(this.root, sourceFile); this.assertContained(source);
97
+ const ext = path.extname(source).toLowerCase();
98
+ if (ext === ".go") {
99
+ let dir = path.dirname(source), modDir: string | undefined, mod = "";
100
+ while (true) {
101
+ if (read(path.join(dir, "go.work")) !== undefined) return finish("unsupported", "go_work_not_supported");
102
+ const text = read(path.join(dir, "go.mod"));
103
+ if (text !== undefined && !modDir) { modDir = dir; mod = text; }
104
+ if (dir === this.root) break;
105
+ dir = path.dirname(dir);
106
+ }
107
+ if (!modDir) return finish("unsupported", "go_mod_missing");
108
+ if (/^\s*replace\b/m.test(mod)) return finish("unsupported", "go_replace_not_supported");
109
+ const moduleName = mod.match(/^\s*module\s+([^\s]+)\s*$/m)?.[1]?.replace(/^"|"$/g, "");
110
+ if (!moduleName) return finish("unsupported", "malformed_go_mod");
111
+ if (target === moduleName || target.startsWith(moduleName + "/")) {
112
+ const packageDir = path.resolve(modDir, target.slice(moduleName.length).replace(/^\//, "")); this.assertContained(packageDir);
113
+ let parent = packageDir;
114
+ while (parent !== modDir) {
115
+ if (!parent.startsWith(modDir + path.sep)) return finish("unsupported", "outside_module");
116
+ if (read(path.join(parent, "go.mod")) !== undefined) return finish("unsupported", "nested_go_mod");
117
+ parent = path.dirname(parent);
118
+ }
119
+ if (!fs.existsSync(packageDir) || !fs.statSync(packageDir).isDirectory()) return finish("unresolved", "go_package_missing");
120
+ const names = fs.readdirSync(packageDir).filter(name => name.endsWith(".go") && !name.endsWith("_test.go")).sort();
121
+ const packageFiles: string[] = [];
122
+ for (const name of names) {
123
+ const file = path.join(packageDir, name); this.assertContained(file);
124
+ const content = readSourceFile(file);
125
+ if (/^\s*\/\/\s*(?:go:build|\+build)\b/m.test(content) || /_(?:linux|windows|darwin|freebsd|amd64|arm64|386|arm)\.go$/.test(name)) result.coverage = "conditional";
126
+ packageFiles.push(path.relative(this.root, file).replace(/\\/g, "/"));
127
+ }
128
+ return packageFiles.length ? finish("resolved", "go_module_package", [{ kind: "package", files: packageFiles }]) : finish("unresolved", "go_package_empty");
129
+ }
130
+ if (GO_STDLIB.has(target.split("/")[0]!)) return finish("external", "go_standard_library");
131
+ const requirements = [...mod.matchAll(/^\s*(?:require\s+)?([A-Za-z0-9._~/-]+)\s+v[^\s]+/gm)].map(m => m[1]!);
132
+ if (requirements.some(name => target === name || target.startsWith(name + "/"))) return finish("external", "go_required_module");
133
+ return finish("unresolved", "go_module_not_declared");
134
+ }
135
+ if (ext === ".php") {
136
+ const normTarget = target.replace(/^\\/, "");
137
+ if (
138
+ PHP_STDLIB.has(normTarget) ||
139
+ normTarget.startsWith("Attribute") ||
140
+ normTarget.startsWith("ReturnTypeWillChange")
141
+ ) {
142
+ return finish("external", "php_standard_library");
143
+ }
144
+
145
+ const composer = json(path.join(this.root, "composer.json"));
146
+ const rules = { ...(composer.autoload?.["psr-4"] ?? {}), ...(composer["autoload-dev"]?.["psr-4"] ?? {}) };
147
+ const matches = Object.keys(rules)
148
+ .filter((prefix) => normTarget.startsWith(prefix.replace(/^\\/, "")))
149
+ .sort((a, b) => b.length - a.length);
150
+
151
+ if (matches.length > 0) {
152
+ const prefix = matches[0]!;
153
+ const cleanPrefix = prefix.replace(/^\\/, "");
154
+ const dirs = Array.isArray(rules[prefix]) ? rules[prefix] : [rules[prefix]];
155
+ if (!dirs.every((d: unknown) => typeof d === "string")) return finish("unsupported", "malformed_psr4");
156
+
157
+ const relativePath = normTarget.slice(cleanPrefix.length).replace(/\\/g, "/");
158
+ const candidateFiles: string[] = [];
159
+ for (const dir of dirs) {
160
+ const absBase = path.resolve(this.root, dir, relativePath);
161
+ this.assertContained(absBase);
162
+ candidateFiles.push(...filesAt(absBase, [".php"]));
163
+ }
164
+
165
+ if (candidateFiles.length === 0) {
166
+ return finish("unresolved", "file_not_found");
167
+ }
168
+ return resolvedFiles(candidateFiles, "composer_psr4");
169
+ }
170
+
171
+ // Check declared composer dependencies
172
+ const requirements = { ...(composer.require ?? {}), ...(composer["require-dev"] ?? {}) };
173
+ const topNamespace = normTarget.split("\\")[0]!.toLowerCase();
174
+ for (const reqPackage of Object.keys(requirements)) {
175
+ const [vendor, pkg] = reqPackage.toLowerCase().split("/");
176
+ if (
177
+ vendor === topNamespace ||
178
+ pkg === topNamespace ||
179
+ (vendor === "laravel" && topNamespace === "illuminate") ||
180
+ (vendor === "symfony" && topNamespace === "symfony") ||
181
+ (vendor === "guzzlehttp" && topNamespace === "guzzlehttp")
182
+ ) {
183
+ return finish("external", "composer_required_package");
184
+ }
185
+ }
186
+
187
+ if (
188
+ normTarget.startsWith("Illuminate\\") ||
189
+ normTarget.startsWith("Symfony\\") ||
190
+ normTarget.startsWith("Psr\\") ||
191
+ normTarget.startsWith("Composer\\")
192
+ ) {
193
+ return finish("external", "php_framework_namespace");
194
+ }
195
+
196
+ return finish("unresolved", "php_namespace_not_mapped");
197
+ }
198
+ if (ext === ".py") {
199
+ if (target.startsWith(".")) {
200
+ const dotsMatch = target.match(/^\.+/);
201
+ const dotCount = dotsMatch ? dotsMatch[0].length : 0;
202
+ const remainder = target.slice(dotCount);
203
+ let baseDir = path.dirname(source);
204
+ for (let i = 1; i < dotCount; i++) {
205
+ baseDir = path.dirname(baseDir);
206
+ }
207
+ this.assertContained(baseDir);
208
+ const fsSubpath = remainder ? remainder.split(".").join(path.sep) : "";
209
+ const targetDirOrFile = fsSubpath ? path.resolve(baseDir, fsSubpath) : baseDir;
210
+ this.assertContained(targetDirOrFile);
211
+
212
+ const candidates: string[] = [];
213
+ if (fsSubpath) {
214
+ const pyFile = targetDirOrFile + ".py";
215
+ if (fs.existsSync(pyFile) && fs.statSync(pyFile).isFile()) {
216
+ candidates.push(path.relative(this.root, pyFile).replace(/\\/g, "/"));
217
+ }
218
+ }
219
+ const initFile = path.join(targetDirOrFile, "__init__.py");
220
+ if (fs.existsSync(initFile) && fs.statSync(initFile).isFile()) {
221
+ candidates.push(path.relative(this.root, initFile).replace(/\\/g, "/"));
222
+ }
223
+ return resolvedFiles(candidates, "python_relative_module");
224
+ }
225
+
226
+ const parts = target.split(".");
227
+ const topPackage = parts[0]!;
228
+ const fsSubpath = parts.join(path.sep);
229
+
230
+ const searchRoots: string[] = [];
231
+ const srcDir = path.resolve(this.root, "src");
232
+ if (fs.existsSync(srcDir) && fs.statSync(srcDir).isDirectory()) {
233
+ searchRoots.push(srcDir);
234
+ }
235
+ searchRoots.push(this.root);
236
+ const callerDir = path.dirname(source);
237
+ if (callerDir !== this.root && callerDir !== srcDir) {
238
+ searchRoots.push(callerDir);
239
+ }
240
+ for (const pkgRoot of this.packageRoots) {
241
+ const abs = path.resolve(this.root, pkgRoot);
242
+ if (!searchRoots.includes(abs) && fs.existsSync(abs)) {
243
+ searchRoots.push(abs);
244
+ }
245
+ }
246
+
247
+ const localCandidates: string[] = [];
248
+ for (const sRoot of searchRoots) {
249
+ const candidateFile = path.resolve(sRoot, fsSubpath + ".py");
250
+ if (candidateFile.startsWith(this.root + path.sep) && fs.existsSync(candidateFile) && fs.statSync(candidateFile).isFile()) {
251
+ localCandidates.push(path.relative(this.root, candidateFile).replace(/\\/g, "/"));
252
+ }
253
+ const candidateInit = path.resolve(sRoot, fsSubpath, "__init__.py");
254
+ if (candidateInit.startsWith(this.root + path.sep) && fs.existsSync(candidateInit) && fs.statSync(candidateInit).isFile()) {
255
+ localCandidates.push(path.relative(this.root, candidateInit).replace(/\\/g, "/"));
256
+ }
257
+ }
258
+
259
+ const unique = [...new Set(localCandidates)].sort();
260
+ if (unique.length > 0) {
261
+ return finish(
262
+ unique.length === 1 ? "resolved" : "ambiguous",
263
+ unique.length === 1 ? "python_local_module" : "multiple_python_candidates",
264
+ unique.map(file => ({ kind: "file", files: [file] }))
265
+ );
266
+ }
267
+
268
+ if (PYTHON_STDLIB.has(topPackage)) {
269
+ return finish("external", "python_standard_library");
270
+ }
271
+
272
+ const declaredPackages = new Set<string>();
273
+ const reqText = read(path.join(this.root, "requirements.txt"));
274
+ if (reqText) {
275
+ for (const rawLine of reqText.split(/\r?\n/)) {
276
+ const line = rawLine.replace(/#.*$/, "").trim();
277
+ if (!line || line.startsWith("-")) continue;
278
+ const match = line.match(/^([A-Za-z0-9_.-]+)/);
279
+ if (match) declaredPackages.add(match[1].toLowerCase().replace(/[-_.]/g, "_"));
280
+ }
281
+ }
282
+ const pyprojectText = read(path.join(this.root, "pyproject.toml"));
283
+ if (pyprojectText) {
284
+ for (const rawLine of pyprojectText.split(/\r?\n/)) {
285
+ const line = rawLine.replace(/#.*$/, "").trim();
286
+ const matchArray = line.match(/^["']([A-Za-z0-9_.-]+)(?:[><=~!^;].*)?["']/);
287
+ if (matchArray) {
288
+ declaredPackages.add(matchArray[1].toLowerCase().replace(/[-_.]/g, "_"));
289
+ continue;
290
+ }
291
+ const matchKey = line.match(/^([A-Za-z0-9_.-]+)\s*=\s*(?:\{|"[^"]*"|'[^']*'|\d)/);
292
+ if (matchKey && !["python", "version", "name", "description"].includes(matchKey[1].toLowerCase())) {
293
+ declaredPackages.add(matchKey[1].toLowerCase().replace(/[-_.]/g, "_"));
294
+ }
295
+ }
296
+ }
297
+ const pipfileText = read(path.join(this.root, "Pipfile"));
298
+ if (pipfileText) {
299
+ for (const rawLine of pipfileText.split(/\r?\n/)) {
300
+ const line = rawLine.replace(/#.*$/, "").trim();
301
+ const match = line.match(/^([A-Za-z0-9_.-]+)\s*=/);
302
+ if (match) declaredPackages.add(match[1].toLowerCase().replace(/[-_.]/g, "_"));
303
+ }
304
+ }
305
+
306
+ const normalizedTop = topPackage.toLowerCase().replace(/[-_.]/g, "_");
307
+ const isDeclared = declaredPackages.has(normalizedTop) ||
308
+ Object.entries(PYTHON_DIST_TO_MODULE_MAP).some(([dist, mods]) => declaredPackages.has(dist) && mods.includes(normalizedTop));
309
+
310
+ if (isDeclared) {
311
+ return finish("external", "python_manifest_dependency");
312
+ }
313
+
314
+ return finish("unresolved", "python_module_not_declared");
315
+ }
316
+ if (!/\.(?:[cm]?[jt]sx?|vue|astro|svelte)$/.test(ext)) return finish("unsupported", "language_resolver_unavailable");
317
+ const extensions = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".d.ts", ".json"];
318
+ if (target.startsWith(".") || path.isAbsolute(target)) return resolvedFiles(filesAt(path.resolve(path.dirname(source), target), extensions), "relative_path");
319
+ if (builtinModules.includes(target) || target.startsWith("node:") && builtinModules.includes(target.slice(5)) || target === "bun" || target.startsWith("bun:")) return finish("external", "runtime_builtin");
320
+ for (let dir = path.dirname(source); dir.startsWith(this.root + path.sep); dir = path.dirname(dir)) {
321
+ if (fs.existsSync(path.join(dir, "tsconfig.json"))) return finish("unsupported", "nested_tsconfig_project_selection_unknown");
322
+ }
323
+ const loadTsConfig = (configPath: string, visited = new Set<string>()): any => {
324
+ if (visited.has(configPath)) throw new Error("circular_tsconfig_extends");
325
+ visited.add(configPath);
326
+ const cfg = json(configPath);
327
+ let options: any = {};
328
+ const extendsList = cfg.extends === undefined ? [] : Array.isArray(cfg.extends) ? cfg.extends : [cfg.extends];
329
+ for (const extRef of extendsList) {
330
+ if (typeof extRef !== "string") throw new Error("malformed_tsconfig_extends");
331
+ const base = extRef.startsWith(".") || path.isAbsolute(extRef)
332
+ ? path.resolve(path.dirname(configPath), extRef)
333
+ : path.resolve(this.root, "node_modules", extRef);
334
+ this.assertContained(base);
335
+ let parentPath = base.endsWith(".json") ? base : base + ".json";
336
+ if (!fs.existsSync(parentPath) && fs.existsSync(base) && fs.statSync(base).isDirectory()) {
337
+ const pkg = json(path.join(base, "package.json"));
338
+ parentPath = path.resolve(base, typeof pkg.tsconfig === "string" ? pkg.tsconfig : "tsconfig.json");
339
+ }
340
+ this.assertContained(parentPath);
341
+ if (!fs.existsSync(parentPath)) throw new Error("tsconfig_extends_not_found");
342
+ options = { ...options, ...loadTsConfig(parentPath, visited) };
343
+ }
344
+ const own = cfg.compilerOptions ?? {};
345
+ if (typeof own !== "object" || Array.isArray(own)) throw new Error("malformed_tsconfig_options");
346
+ options = { ...options, ...own };
347
+ if (Object.hasOwn(own, "baseUrl")) {
348
+ if (typeof own.baseUrl !== "string") throw new Error("malformed_tsconfig_baseurl");
349
+ options.baseUrl = path.resolve(path.dirname(configPath), own.baseUrl);
350
+ }
351
+ if (Object.hasOwn(own, "paths")) options.pathsBase = path.dirname(configPath);
352
+ visited.delete(configPath);
353
+ return options;
354
+ };
355
+
356
+ const options = loadTsConfig(path.join(this.root, "tsconfig.json"));
357
+ const aliases = options.paths ?? {};
358
+ if (typeof aliases !== "object" || Array.isArray(aliases)) return finish("unsupported", "malformed_ts_paths");
359
+ const matching = Object.keys(aliases).filter(key => {
360
+ const star = key.indexOf("*");
361
+ return star < 0 ? target === key : key.indexOf("*", star + 1) < 0 && target.startsWith(key.slice(0, star)) && target.endsWith(key.slice(star + 1)) && target.length >= key.length - 1;
362
+ }).sort((a,b) => (b.includes("*") ? b.indexOf("*") : Number.MAX_SAFE_INTEGER) - (a.includes("*") ? a.indexOf("*") : Number.MAX_SAFE_INTEGER));
363
+ if (matching.length) {
364
+ const key = matching[0]!; const values = aliases[key];
365
+ if (!Array.isArray(values) || !values.every(v=>typeof v === "string")) return finish("unsupported", "malformed_ts_paths");
366
+ for (const value of values as string[]) {
367
+ const star = key.indexOf("*");
368
+ const matched = star < 0 ? "" : target.slice(star, target.length - (key.length - star - 1));
369
+ const files = filesAt(path.resolve(options.baseUrl ?? options.pathsBase ?? this.root, value.replace("*", matched)), extensions);
370
+ if (files.length) return resolvedFiles(files, "tsconfig_paths");
371
+ }
372
+ }
373
+ if (options.baseUrl && !matching.length) {
374
+ const baseFiles = filesAt(path.resolve(options.baseUrl, target), extensions);
375
+ if (baseFiles.length) return resolvedFiles(baseFiles, "tsconfig_baseurl");
376
+ }
377
+ if (!options.baseUrl && !matching.length) {
378
+ const local = target.startsWith("@/") ? target.replace(/^@\//,"src/") : target;
379
+ const localFiles = filesAt(path.resolve(this.root,local),extensions);
380
+ if (localFiles.length) return resolvedFiles(localFiles,"workspace_path");
381
+ }
382
+ const pkg = json(path.join(this.root,"package.json"));
383
+ const workspacePatterns = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? [];
384
+ const roots = [...this.packageRoots];
385
+ for (const pattern of workspacePatterns) {
386
+ if (typeof pattern !== "string") return finish("unsupported","malformed_workspace_pattern");
387
+ if (pattern.endsWith("/*")) {
388
+ const parent = path.resolve(this.root,pattern.slice(0,-2)); this.assertContained(parent);
389
+ if (fs.existsSync(parent)) roots.push(...fs.readdirSync(parent,{withFileTypes:true}).filter(entry=>entry.isDirectory()).map(entry=>path.relative(this.root,path.join(parent,entry.name))));
390
+ } else if (!pattern.includes("*")) roots.push(pattern);
391
+ else return finish("unsupported","workspace_glob_not_supported");
392
+ }
393
+ const workspaceFiles: string[] = [];
394
+ for (const directory of [...new Set(roots)]) {
395
+ const workspace = json(path.resolve(this.root,directory,"package.json"));
396
+ if (typeof workspace.name !== "string" || !(target === workspace.name || target.startsWith(workspace.name + "/"))) continue;
397
+ const subpath = target.slice(workspace.name.length).replace(/^\//, "");
398
+ let resolvedEntry: string | undefined;
399
+
400
+ if (!subpath) {
401
+ const exported = typeof workspace.exports === "string" ? workspace.exports : workspace.exports?.["."];
402
+ if (typeof exported === "string") {
403
+ resolvedEntry = exported;
404
+ } else if (exported && typeof exported === "object") {
405
+ resolvedEntry = exported.import || exported.default || exported.require || exported.types;
406
+ if (typeof resolvedEntry !== "string") return finish("unsupported", "conditional_package_exports");
407
+ }
408
+ } else if (workspace.exports && typeof workspace.exports === "object") {
409
+ const subExport = workspace.exports["./" + subpath] ?? workspace.exports["./" + subpath + ".js"];
410
+ if (typeof subExport === "string") {
411
+ resolvedEntry = subExport;
412
+ } else if (subExport && typeof subExport === "object") {
413
+ resolvedEntry = subExport.import || subExport.default || subExport.require || subExport.types;
414
+ }
415
+ }
416
+
417
+ const entry = resolvedEntry || subpath || workspace.module || workspace.main || "index";
418
+ if (typeof entry !== "string") return finish("unsupported","package_entry_not_literal");
419
+ workspaceFiles.push(...filesAt(path.resolve(this.root,directory,entry),extensions));
420
+ }
421
+ if (workspaceFiles.length) return resolvedFiles(workspaceFiles,"workspace_package");
422
+ const name = target.startsWith("@") ? target.split("/").slice(0,2).join("/") : target.split("/")[0]!;
423
+ if ([pkg.dependencies,pkg.devDependencies,pkg.peerDependencies,pkg.optionalDependencies].some(deps => deps && Object.hasOwn(deps,name))) return finish("external","package_manifest_dependency");
424
+ return finish("unresolved", "package_not_declared");
425
+ } catch (error) {
426
+ return finish("unsupported", error instanceof Error && error.message.includes("outside_workspace") ? "outside_workspace" : `manifest_or_source_error: ${error instanceof Error ? error.message : String(error)}`);
427
+ }
428
+ }
429
+
430
+ private assertContained(file: string): void {
431
+ const contained = (candidate: string, root: string) => candidate === root || candidate.startsWith(root + path.sep);
432
+ if (!contained(path.resolve(file), this.root)) throw new Error("outside_workspace");
433
+ let existing = file;
434
+ while (!fs.existsSync(existing) && existing !== this.root) existing = path.dirname(existing);
435
+ if (fs.existsSync(existing) && !contained(fs.realpathSync(existing), fs.realpathSync(this.root))) throw new Error("outside_workspace");
436
+ }
437
+ }