@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,863 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { DomainConfig } from "../../types/index.ts";
4
+ import type { SeptumRepository } from "../database/repository.ts";
5
+ import { DEFAULT_IGNORED_DIRECTORIES, isIgnoredDirectory } from "../resources/ignore.ts";
6
+ import { assertUniqueDomainRoots, domainNameKey, domainRootIdentity } from "../config/domain-ownership.ts";
7
+
8
+ export type ProjectType =
9
+ | "monorepo"
10
+ | "fullstack"
11
+ | "backend"
12
+ | "frontend"
13
+ | "cli-mcp"
14
+ | "generic";
15
+
16
+ export type ArchitectureStyle =
17
+ | "modular-ddd"
18
+ | "layered-monolith"
19
+ | "clean-architecture"
20
+ | "monorepo-workspaces"
21
+ | "cli-adapter"
22
+ | "generic";
23
+
24
+ export interface DiscoveredProjectTopology {
25
+ framework: string;
26
+ language: "typescript" | "javascript" | "php" | "python" | "go" | "generic";
27
+ projectType: ProjectType;
28
+ architectureStyle: ArchitectureStyle;
29
+ domains: Record<string, DomainConfig>;
30
+ scanned_folders: string[];
31
+ ignored_folders: string[];
32
+ }
33
+
34
+ export class TopologyDetector {
35
+ private static readonly IGNORED_DIRS = new Set([
36
+ ...DEFAULT_IGNORED_DIRECTORIES,
37
+ "tests",
38
+ "test",
39
+ "scripts",
40
+ "locales",
41
+ "resources",
42
+ "public",
43
+ "assets",
44
+ "static",
45
+ ]);
46
+
47
+ private static readonly SOURCE_EXTENSIONS = new Set([
48
+ ".ts",
49
+ ".js",
50
+ ".tsx",
51
+ ".jsx",
52
+ ".php",
53
+ ".py",
54
+ ".go",
55
+ ".rs",
56
+ ".vue",
57
+ ]);
58
+
59
+ /**
60
+ * Reads compilerOptions.paths from tsconfig.json or jsconfig.json.
61
+ */
62
+ public static readTsConfigPaths(projectRoot: string): Record<string, string[]> {
63
+ for (const file of ["tsconfig.json", "jsconfig.json"]) {
64
+ const fullPath = path.join(projectRoot, file);
65
+ if (fs.existsSync(fullPath)) {
66
+ try {
67
+ const raw = fs.readFileSync(fullPath, "utf-8");
68
+ const stripped = raw.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
69
+ const parsed = JSON.parse(stripped);
70
+ if (parsed.compilerOptions?.paths) {
71
+ return parsed.compilerOptions.paths;
72
+ }
73
+ } catch {
74
+ // Ignore tsconfig parse error
75
+ }
76
+ }
77
+ }
78
+ return {};
79
+ }
80
+
81
+ /**
82
+ * Checks whether a directory recursively contains any source code files.
83
+ */
84
+ private static hasSourceFiles(dir: string): boolean {
85
+ try {
86
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
87
+ for (const entry of entries) {
88
+ if (isIgnoredDirectory(entry.name) || this.IGNORED_DIRS.has(entry.name)) continue;
89
+ const full = path.join(dir, entry.name);
90
+ if (entry.isFile()) {
91
+ const ext = path.extname(entry.name).toLowerCase();
92
+ if (this.SOURCE_EXTENSIONS.has(ext)) return true;
93
+ } else if (entry.isDirectory()) {
94
+ if (this.hasSourceFiles(full)) return true;
95
+ }
96
+ }
97
+ } catch {
98
+ // Ignore read errors
99
+ }
100
+ return false;
101
+ }
102
+
103
+ /**
104
+ * Checks whether a directory contains any direct source code files at its root level.
105
+ */
106
+ public static hasDirectSourceFiles(dir: string): boolean {
107
+ try {
108
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
109
+ for (const entry of entries) {
110
+ if (entry.isFile() && !entry.name.startsWith(".")) {
111
+ const ext = path.extname(entry.name).toLowerCase();
112
+ if (this.SOURCE_EXTENSIONS.has(ext)) return true;
113
+ }
114
+ }
115
+ } catch {
116
+ // Ignore read errors
117
+ }
118
+ return false;
119
+ }
120
+
121
+ /**
122
+ * Detects project topology, classifies project type & architecture style, and maps domains.
123
+ */
124
+ public static detect(projectRoot: string = process.cwd()): DiscoveredProjectTopology {
125
+ const language = this.detectLanguage(projectRoot);
126
+ const framework = this.detectFramework(projectRoot, language);
127
+ const isMonorepo = this.detectMonorepo(projectRoot);
128
+
129
+ const domains: Record<string, DomainConfig> = {};
130
+ let architectureStyle: ArchitectureStyle = "generic";
131
+
132
+ // 1. Monorepo Workspaces (apps/*, packages/*, modules/*, libs/*)
133
+ if (isMonorepo) {
134
+ architectureStyle = "monorepo-workspaces";
135
+ const workspaceDirs = ["apps", "packages", "modules", "libs"];
136
+ interface WorkspaceCandidate {
137
+ parent: string;
138
+ sub: string;
139
+ relRoot: string;
140
+ }
141
+ const candidates: WorkspaceCandidate[] = [];
142
+
143
+ for (const parent of workspaceDirs) {
144
+ const fullParent = path.join(projectRoot, parent);
145
+ if (fs.existsSync(fullParent) && fs.statSync(fullParent).isDirectory()) {
146
+ const subs = this.getSubdirectories(fullParent);
147
+ for (const sub of subs) {
148
+ candidates.push({ parent, sub, relRoot: path.join(parent, sub) });
149
+ }
150
+ }
151
+ }
152
+
153
+ // Detect collisions across workspace subdirectories
154
+ const nameCounts = new Map<string, number>();
155
+ for (const c of candidates) {
156
+ const lower = c.sub.toLowerCase();
157
+ nameCounts.set(lower, (nameCounts.get(lower) || 0) + 1);
158
+ }
159
+
160
+ const appDomains: string[] = [];
161
+ const packageDomains: string[] = [];
162
+ const items: Array<{ domainName: string; parent: string; sub: string; relRoot: string }> = [];
163
+
164
+ for (const c of candidates) {
165
+ const lower = c.sub.toLowerCase();
166
+ let domainName = (nameCounts.get(lower) || 0) > 1
167
+ ? `${c.parent}-${lower}`
168
+ : lower;
169
+
170
+ let uniqueName = domainName;
171
+ let counter = 2;
172
+ while (items.some((it) => it.domainName === uniqueName)) {
173
+ uniqueName = `${domainName}-${counter++}`;
174
+ }
175
+
176
+ if (c.parent === "apps") {
177
+ appDomains.push(uniqueName);
178
+ } else {
179
+ packageDomains.push(uniqueName);
180
+ }
181
+ items.push({ domainName: uniqueName, parent: c.parent, sub: c.sub, relRoot: c.relRoot });
182
+ }
183
+
184
+ for (const item of items) {
185
+ domains[item.domainName] = {
186
+ root: item.relRoot,
187
+ description: `Monorepo ${item.parent} package: ${item.sub}`,
188
+ allowed_dependencies: item.parent === "apps" ? packageDomains : [],
189
+ forbidden_dependencies: item.parent !== "apps" ? appDomains : [],
190
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, item.relRoot)),
191
+ };
192
+ }
193
+ }
194
+
195
+ // 2. Modular DDD (app/Domain, src/modules, src/domains, domains/*, etc.)
196
+ if (Object.keys(domains).length === 0) {
197
+ const modularCandidates = [
198
+ { prefix: "domain", dir: path.join(projectRoot, "app", "Domain") },
199
+ { prefix: "domain", dir: path.join(projectRoot, "app", "Domains") },
200
+ { prefix: "domain", dir: path.join(projectRoot, "app", "domain") },
201
+ { prefix: "domain", dir: path.join(projectRoot, "app", "domains") },
202
+ { prefix: "module", dir: path.join(projectRoot, "app", "modules") },
203
+ { prefix: "feature", dir: path.join(projectRoot, "app", "features") },
204
+ { prefix: "domain", dir: path.join(projectRoot, "src", "domains") },
205
+ { prefix: "domain", dir: path.join(projectRoot, "src", "domain") },
206
+ { prefix: "feature", dir: path.join(projectRoot, "src", "features") },
207
+ { prefix: "module", dir: path.join(projectRoot, "src", "modules") },
208
+ { prefix: "domain", dir: path.join(projectRoot, "domains") },
209
+ { prefix: "domain", dir: path.join(projectRoot, "domain") },
210
+ { prefix: "module", dir: path.join(projectRoot, "modules") },
211
+ { prefix: "feature", dir: path.join(projectRoot, "features") },
212
+ ];
213
+
214
+ for (const cand of modularCandidates) {
215
+ if (fs.existsSync(cand.dir) && fs.statSync(cand.dir).isDirectory()) {
216
+ const subdirs = this.getSubdirectories(cand.dir).filter((s) =>
217
+ this.hasSourceFiles(path.join(cand.dir, s))
218
+ );
219
+ if (subdirs.length > 0) {
220
+ architectureStyle = "modular-ddd";
221
+ for (const sub of subdirs) {
222
+ const relRoot = path.relative(projectRoot, path.join(cand.dir, sub));
223
+ domains[sub.toLowerCase()] = {
224
+ root: relRoot,
225
+ description: `Modular ${cand.prefix} domain: ${sub}`,
226
+ allowed_dependencies: ["shared", "common", "root"],
227
+ forbidden_dependencies: [],
228
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, relRoot)),
229
+ };
230
+ }
231
+
232
+ // Check if parent container (e.g. src/ or app/) has direct entrypoint files
233
+ const parentContainer = path.dirname(cand.dir);
234
+ if (parentContainer !== projectRoot && this.hasDirectSourceFiles(parentContainer)) {
235
+ const relParent = path.relative(projectRoot, parentContainer);
236
+ domains["root"] = {
237
+ root: relParent,
238
+ description: `Root entrypoint and shared bootstrap layer in ${relParent}`,
239
+ allowed_dependencies: Object.keys(domains),
240
+ forbidden_dependencies: [],
241
+ archetypes: this.inferDefaultArchetypes(parentContainer),
242
+ };
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }
248
+
249
+ // 3. Layered Monolith / Clean Architecture in standard code directories (src, app, lib)
250
+ if (Object.keys(domains).length === 0) {
251
+ for (const standardDirName of ["src", "app", "lib"]) {
252
+ const standardDir = path.join(projectRoot, standardDirName);
253
+ if (fs.existsSync(standardDir) && fs.statSync(standardDir).isDirectory()) {
254
+ const subdirs = this.getSubdirectories(standardDir).filter((s) =>
255
+ this.hasSourceFiles(path.join(standardDir, s))
256
+ );
257
+ const hasDirectFiles = this.hasDirectSourceFiles(standardDir);
258
+
259
+ if (subdirs.length > 0) {
260
+ architectureStyle =
261
+ framework === "mcp-server" || framework === "cli"
262
+ ? "cli-adapter"
263
+ : "layered-monolith";
264
+
265
+ const sharedKernelNames = new Set(["types", "shared", "common", "contracts"]);
266
+ const coreNames = new Set(["core", "domain", "services", "usecase", "internal"]);
267
+ const adapterNames = new Set([
268
+ "cli",
269
+ "mcp",
270
+ "api",
271
+ "controllers",
272
+ "routes",
273
+ "handlers",
274
+ "delivery",
275
+ ]);
276
+
277
+ for (const sub of subdirs) {
278
+ const relRoot = path.join(standardDirName, sub);
279
+ const name = sub.toLowerCase();
280
+ let allowed: string[] = [];
281
+ let forbidden: string[] = [];
282
+
283
+ if (sharedKernelNames.has(name)) {
284
+ allowed = [];
285
+ forbidden = Array.from(adapterNames)
286
+ .concat(Array.from(coreNames))
287
+ .filter((n) => subdirs.map((s) => s.toLowerCase()).includes(n));
288
+ } else if (coreNames.has(name)) {
289
+ allowed = subdirs
290
+ .map((s) => s.toLowerCase())
291
+ .filter((s) => sharedKernelNames.has(s));
292
+ forbidden = subdirs
293
+ .map((s) => s.toLowerCase())
294
+ .filter((s) => adapterNames.has(s));
295
+ } else {
296
+ // Adapters
297
+ allowed = subdirs
298
+ .map((s) => s.toLowerCase())
299
+ .filter((s) => sharedKernelNames.has(s) || coreNames.has(s));
300
+ forbidden = [];
301
+ }
302
+
303
+ domains[name] = {
304
+ root: relRoot,
305
+ description: `${sub} layer`,
306
+ allowed_dependencies: [...new Set(allowed)],
307
+ forbidden_dependencies: forbidden,
308
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, relRoot)),
309
+ };
310
+ }
311
+
312
+ // Register root domain if direct source files exist in the standard folder
313
+ if (hasDirectFiles) {
314
+ domains["root"] = {
315
+ root: standardDirName,
316
+ description: `Root entrypoint and shared bootstrap layer in ${standardDirName}`,
317
+ allowed_dependencies: subdirs.map((s) => s.toLowerCase()),
318
+ forbidden_dependencies: [],
319
+ archetypes: this.inferDefaultArchetypes(standardDir),
320
+ };
321
+ }
322
+ break;
323
+ } else if (hasDirectFiles) {
324
+ // Flat source folder with multi-nested code files
325
+ architectureStyle = "layered-monolith";
326
+ domains["app"] = {
327
+ root: standardDirName,
328
+ description: `Primary application domain in ${standardDirName}`,
329
+ allowed_dependencies: [],
330
+ forbidden_dependencies: [],
331
+ archetypes: this.inferDefaultArchetypes(standardDir),
332
+ };
333
+ break;
334
+ }
335
+ }
336
+ }
337
+ }
338
+
339
+ // 4. Framework-specific structural patterns (Laravel, Go)
340
+ if (Object.keys(domains).length === 0) {
341
+ if (language === "php" || framework.includes("laravel") || fs.existsSync(path.join(projectRoot, "artisan"))) {
342
+ const appDir = path.join(projectRoot, "app");
343
+ if (fs.existsSync(appDir)) {
344
+ architectureStyle = "layered-monolith";
345
+ const subdirs = this.getSubdirectories(appDir).filter((s) =>
346
+ this.hasSourceFiles(path.join(appDir, s))
347
+ );
348
+ if (subdirs.length > 0) {
349
+ for (const sub of subdirs) {
350
+ domains[sub.toLowerCase()] = {
351
+ root: path.join("app", sub),
352
+ description: `Laravel layer: ${sub}`,
353
+ allowed_dependencies: [],
354
+ forbidden_dependencies: [],
355
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, "app", sub)),
356
+ };
357
+ }
358
+ if (this.hasDirectSourceFiles(appDir)) {
359
+ domains["root"] = {
360
+ root: "app",
361
+ description: "Laravel application root",
362
+ allowed_dependencies: subdirs.map((s) => s.toLowerCase()),
363
+ forbidden_dependencies: [],
364
+ archetypes: this.inferDefaultArchetypes(appDir),
365
+ };
366
+ }
367
+ } else {
368
+ domains["app"] = {
369
+ root: "app",
370
+ description: "Core Laravel Application (auto-discovered)",
371
+ allowed_dependencies: [],
372
+ forbidden_dependencies: [],
373
+ archetypes: {
374
+ controller: "app/Http/Controllers/**",
375
+ service: "app/Services/**",
376
+ model: "app/Models/**",
377
+ repository: "app/Repositories/**",
378
+ },
379
+ };
380
+ }
381
+ }
382
+
383
+ const routesDir = path.join(projectRoot, "routes");
384
+ if (fs.existsSync(routesDir)) {
385
+ domains["routes"] = {
386
+ root: "routes",
387
+ description: "Laravel HTTP Route Definitions (auto-discovered)",
388
+ allowed_dependencies: [],
389
+ forbidden_dependencies: [],
390
+ archetypes: {
391
+ route: "routes/**/*.php",
392
+ },
393
+ };
394
+ }
395
+
396
+ const databaseDir = path.join(projectRoot, "database");
397
+ if (fs.existsSync(databaseDir)) {
398
+ domains["database"] = {
399
+ root: "database",
400
+ description: "Laravel Migrations and Database Schemas (auto-discovered)",
401
+ allowed_dependencies: [],
402
+ forbidden_dependencies: [],
403
+ archetypes: {
404
+ migration: "database/migrations/**/*.php",
405
+ },
406
+ };
407
+ }
408
+
409
+ const viewsDir = path.join(projectRoot, "resources", "views");
410
+ if (fs.existsSync(viewsDir)) {
411
+ domains["views"] = {
412
+ root: "resources/views",
413
+ description: "Laravel Blade Templates and UI Views (auto-discovered)",
414
+ allowed_dependencies: [],
415
+ forbidden_dependencies: [],
416
+ archetypes: {
417
+ view: "resources/views/**/*.blade.php",
418
+ },
419
+ };
420
+ }
421
+ } else if (language === "go" || fs.existsSync(path.join(projectRoot, "go.mod"))) {
422
+ architectureStyle = "clean-architecture";
423
+ const pkgDir = path.join(projectRoot, "pkg");
424
+ if (fs.existsSync(pkgDir) && this.hasSourceFiles(pkgDir)) {
425
+ domains["pkg"] = {
426
+ root: "pkg",
427
+ description: "Go public library pkg",
428
+ allowed_dependencies: [],
429
+ forbidden_dependencies: ["internal", "cmd"],
430
+ archetypes: this.inferDefaultArchetypes(pkgDir),
431
+ };
432
+ }
433
+
434
+ const internalDir = path.join(projectRoot, "internal");
435
+ if (fs.existsSync(internalDir)) {
436
+ const internalSubs = this.getSubdirectories(internalDir).filter((s) =>
437
+ this.hasSourceFiles(path.join(internalDir, s))
438
+ );
439
+ if (internalSubs.length > 0) {
440
+ for (const sub of internalSubs) {
441
+ domains[sub.toLowerCase()] = {
442
+ root: path.join("internal", sub),
443
+ description: `Internal ${sub} domain`,
444
+ allowed_dependencies: domains["pkg"] ? ["pkg"] : [],
445
+ forbidden_dependencies: ["cmd"],
446
+ archetypes: this.inferDefaultArchetypes(path.join(internalDir, sub)),
447
+ };
448
+ }
449
+ } else if (this.hasSourceFiles(internalDir)) {
450
+ domains["internal"] = {
451
+ root: "internal",
452
+ description: "Go internal layer",
453
+ allowed_dependencies: domains["pkg"] ? ["pkg"] : [],
454
+ forbidden_dependencies: ["cmd"],
455
+ archetypes: this.inferDefaultArchetypes(internalDir),
456
+ };
457
+ }
458
+ }
459
+
460
+ const cmdDir = path.join(projectRoot, "cmd");
461
+ if (fs.existsSync(cmdDir)) {
462
+ const cmdSubs = this.getSubdirectories(cmdDir).filter((s) =>
463
+ this.hasSourceFiles(path.join(cmdDir, s))
464
+ );
465
+ if (cmdSubs.length > 0) {
466
+ for (const sub of cmdSubs) {
467
+ domains[`cmd-${sub.toLowerCase()}`] = {
468
+ root: path.join("cmd", sub),
469
+ description: `Go entrypoint: ${sub}`,
470
+ allowed_dependencies: Object.keys(domains),
471
+ forbidden_dependencies: [],
472
+ archetypes: this.inferDefaultArchetypes(path.join(cmdDir, sub)),
473
+ };
474
+ }
475
+ } else if (this.hasSourceFiles(cmdDir)) {
476
+ domains["cmd"] = {
477
+ root: "cmd",
478
+ description: "Go entrypoint cmd",
479
+ allowed_dependencies: Object.keys(domains),
480
+ forbidden_dependencies: [],
481
+ archetypes: this.inferDefaultArchetypes(cmdDir),
482
+ };
483
+ }
484
+ }
485
+ }
486
+ }
487
+
488
+ // 5. Fallback: Top-level directories that contain source code
489
+ if (Object.keys(domains).length === 0) {
490
+ const topDirs = this.getSubdirectories(projectRoot).filter((d) =>
491
+ this.hasSourceFiles(path.join(projectRoot, d))
492
+ );
493
+ for (const d of topDirs) {
494
+ domains[d.toLowerCase()] = {
495
+ root: d,
496
+ description: `Top-level domain: ${d}`,
497
+ allowed_dependencies: [],
498
+ forbidden_dependencies: [],
499
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, d)),
500
+ };
501
+ }
502
+ if (this.hasDirectSourceFiles(projectRoot)) {
503
+ domains["root"] = {
504
+ root: ".",
505
+ description: "Top-level root domain",
506
+ allowed_dependencies: Object.keys(domains),
507
+ forbidden_dependencies: [],
508
+ archetypes: this.inferDefaultArchetypes(projectRoot),
509
+ };
510
+ }
511
+ }
512
+
513
+ const projectType = this.detectProjectType(projectRoot, framework, language, isMonorepo);
514
+
515
+ const scanned_folders = Array.from(new Set(Object.values(domains).map((d) => d.root))).sort();
516
+
517
+ const ignored_folders: string[] = [];
518
+ try {
519
+ const entries = fs.readdirSync(projectRoot, { withFileTypes: true });
520
+ for (const entry of entries) {
521
+ if (entry.isDirectory()) {
522
+ if (isIgnoredDirectory(entry.name) || this.IGNORED_DIRS.has(entry.name)) {
523
+ ignored_folders.push(entry.name);
524
+ }
525
+ }
526
+ }
527
+ } catch {}
528
+ ignored_folders.sort();
529
+
530
+ return {
531
+ framework,
532
+ language,
533
+ projectType,
534
+ architectureStyle,
535
+ domains,
536
+ scanned_folders,
537
+ ignored_folders,
538
+ };
539
+ }
540
+
541
+ /**
542
+ * Discovers project topology and persists domains and macro metadata directly into SQLite SSOT.
543
+ * If a domain is already registered, its existing root and policy are preserved on repeat init,
544
+ * while new domains discovered from the codebase are added.
545
+ */
546
+ public static discoverAndPersist(
547
+ repo: SeptumRepository,
548
+ projectRoot: string = process.cwd(),
549
+ forceResetPolicies: boolean = false
550
+ ): Record<string, DomainConfig> {
551
+ assertUniqueDomainRoots(Object.fromEntries(repo.getAllDomains().map(domain => [domain.name, { root: domain.root_path }])), projectRoot);
552
+ const topology = this.detect(projectRoot);
553
+
554
+ for (const [name, config] of Object.entries(topology.domains)) {
555
+ const existing = repo.domains.getDomainByName(name);
556
+ if (!existing || forceResetPolicies) {
557
+ const identity = domainRootIdentity(config.root, projectRoot);
558
+ const owner = repo.getAllDomains().find(domain => domainRootIdentity(domain.root_path, projectRoot) === identity && domainNameKey(domain.name) !== domainNameKey(name));
559
+ // Inference must not create an alias for an explicitly registered owner.
560
+ if (owner && !existing) continue;
561
+ repo.domains.upsertDomain(name, config, projectRoot);
562
+ }
563
+ }
564
+
565
+ if (forceResetPolicies) {
566
+ repo.domains.pruneDomainsNotIn(Object.keys(topology.domains));
567
+ }
568
+
569
+ return this.persistMacroMetadata(repo, topology);
570
+ }
571
+
572
+ /**
573
+ * Synchronize explicit domains from septum.config.json as the SSOT without
574
+ * writing auto-discovered domains, while still updating macro metadata and
575
+ * reporting any detected framework sub-domains shadowed by coarse roots.
576
+ */
577
+ public static syncExplicitConfigDomains(
578
+ repo: SeptumRepository,
579
+ projectRoot: string,
580
+ explicitDomains: Record<string, DomainConfig>
581
+ ): {
582
+ domains: Record<string, DomainConfig>;
583
+ shadowedSubdomains: Array<{ explicitDomain: string; explicitRoot: string; detectedNames: string[] }>;
584
+ } {
585
+ assertUniqueDomainRoots(explicitDomains, projectRoot);
586
+ for (const [name, config] of Object.entries(explicitDomains)) {
587
+ repo.domains.upsertDomain(name, config, projectRoot);
588
+ }
589
+ repo.domains.pruneDomainsNotIn(Object.keys(explicitDomains));
590
+
591
+ const topology = this.detect(projectRoot);
592
+ const domains = this.persistMacroMetadata(repo, topology);
593
+
594
+ const shadowedSubdomains: Array<{ explicitDomain: string; explicitRoot: string; detectedNames: string[] }> = [];
595
+ for (const [explicitDomain, explicitCfg] of Object.entries(explicitDomains)) {
596
+ const parentAbs = path.resolve(projectRoot, explicitCfg.root);
597
+ const detectedNames: string[] = [];
598
+ for (const [detectedName, detectedCfg] of Object.entries(topology.domains)) {
599
+ if (domainNameKey(detectedName) === domainNameKey(explicitDomain)) continue;
600
+ const childAbs = path.resolve(projectRoot, detectedCfg.root);
601
+ const rel = path.relative(parentAbs, childAbs);
602
+ if (rel !== "" && rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel)) {
603
+ detectedNames.push(detectedName);
604
+ }
605
+ }
606
+ if (detectedNames.length > 0) {
607
+ shadowedSubdomains.push({ explicitDomain, explicitRoot: explicitCfg.root, detectedNames });
608
+ }
609
+ }
610
+
611
+ return { domains, shadowedSubdomains };
612
+ }
613
+
614
+ private static persistMacroMetadata(
615
+ repo: SeptumRepository,
616
+ topology: DiscoveredProjectTopology
617
+ ): Record<string, DomainConfig> {
618
+ repo.setMeta("project_type", topology.projectType);
619
+ repo.setMeta("architecture_style", topology.architectureStyle);
620
+ repo.setMeta("framework", topology.framework);
621
+ repo.setMeta("language", topology.language);
622
+ repo.setMeta("scanned_folders", JSON.stringify(topology.scanned_folders));
623
+ repo.setMeta("ignored_folders", JSON.stringify(topology.ignored_folders));
624
+
625
+ const allRecords = repo.domains.getAllDomains();
626
+ repo.setMeta(
627
+ "macro_summary",
628
+ JSON.stringify({
629
+ projectType: topology.projectType,
630
+ framework: topology.framework,
631
+ architectureStyle: topology.architectureStyle,
632
+ domainsCount: allRecords.length,
633
+ domains: allRecords.map((r) => r.name),
634
+ scannedFolders: topology.scanned_folders,
635
+ ignoredFolders: topology.ignored_folders,
636
+ })
637
+ );
638
+
639
+ const result: Record<string, DomainConfig> = {};
640
+ for (const record of allRecords) {
641
+ result[record.name] = {
642
+ root: record.root_path,
643
+ allowed_dependencies: JSON.parse(record.allowed_deps_json || "[]"),
644
+ forbidden_dependencies: JSON.parse(record.forbidden_deps_json || "[]"),
645
+ archetypes: JSON.parse(record.archetypes_json || "{}"),
646
+ };
647
+ }
648
+
649
+ return result;
650
+ }
651
+
652
+ private static detectMonorepo(projectRoot: string): boolean {
653
+ if (
654
+ fs.existsSync(path.join(projectRoot, "pnpm-workspace.yaml")) ||
655
+ fs.existsSync(path.join(projectRoot, "lerna.json")) ||
656
+ fs.existsSync(path.join(projectRoot, "turbo.json")) ||
657
+ fs.existsSync(path.join(projectRoot, "nx.json"))
658
+ ) {
659
+ return true;
660
+ }
661
+
662
+ const hasApps = fs.existsSync(path.join(projectRoot, "apps"));
663
+ const hasPackages = fs.existsSync(path.join(projectRoot, "packages"));
664
+ const hasLibs = fs.existsSync(path.join(projectRoot, "libs"));
665
+ if (hasApps && (hasPackages || hasLibs)) return true;
666
+
667
+ const pkgPath = path.join(projectRoot, "package.json");
668
+ if (fs.existsSync(pkgPath)) {
669
+ try {
670
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
671
+ if (pkg.workspaces && Array.isArray(pkg.workspaces) && pkg.workspaces.length > 0) {
672
+ return true;
673
+ }
674
+ } catch (err: unknown) {
675
+ const msg = err instanceof Error ? err.message : String(err);
676
+ console.warn(`[Septum Topology] Could not parse ${pkgPath}: ${msg}`);
677
+ }
678
+ }
679
+
680
+ return false;
681
+ }
682
+
683
+ private static detectProjectType(
684
+ projectRoot: string,
685
+ framework: string,
686
+ language: string,
687
+ isMonorepo: boolean
688
+ ): ProjectType {
689
+ if (isMonorepo) return "monorepo";
690
+
691
+ if (framework === "mcp-server" || framework === "cli") return "cli-mcp";
692
+
693
+ if (framework === "nextjs" || framework === "nuxt" || framework === "astro") {
694
+ return "fullstack";
695
+ }
696
+
697
+ if (framework.includes("laravel")) {
698
+ const hasJs = fs.existsSync(path.join(projectRoot, "resources/js"));
699
+ const hasViews = fs.existsSync(path.join(projectRoot, "resources/views"));
700
+ return hasJs || hasViews ? "fullstack" : "backend";
701
+ }
702
+
703
+ if (framework === "vue" || framework === "react") {
704
+ return "frontend";
705
+ }
706
+
707
+ if (
708
+ framework === "nestjs" ||
709
+ framework === "express" ||
710
+ framework === "fastify" ||
711
+ language === "go" ||
712
+ language === "python" ||
713
+ language === "php"
714
+ ) {
715
+ return "backend";
716
+ }
717
+
718
+ return "generic";
719
+ }
720
+
721
+ private static inferDefaultArchetypes(fullDir: string): Record<string, string> {
722
+ const archetypes: Record<string, string> = {};
723
+ if (!fs.existsSync(fullDir)) return archetypes;
724
+
725
+ try {
726
+ const items = fs.readdirSync(fullDir, { withFileTypes: true });
727
+ for (const it of items) {
728
+ if (it.isDirectory() && !it.name.startsWith(".")) {
729
+ const name = it.name.toLowerCase();
730
+ archetypes[name] = `${it.name}/**`;
731
+ }
732
+ }
733
+ if (Object.keys(archetypes).length === 0) {
734
+ archetypes["source"] = "**/*.*";
735
+ }
736
+ } catch {}
737
+
738
+ return archetypes;
739
+ }
740
+
741
+ private static detectLanguage(projectRoot: string): DiscoveredProjectTopology["language"] {
742
+ if (
743
+ fs.existsSync(path.join(projectRoot, "composer.json")) ||
744
+ fs.existsSync(path.join(projectRoot, "artisan"))
745
+ ) {
746
+ return "php";
747
+ }
748
+ if (fs.existsSync(path.join(projectRoot, "go.mod"))) return "go";
749
+ if (
750
+ fs.existsSync(path.join(projectRoot, "pyproject.toml")) ||
751
+ fs.existsSync(path.join(projectRoot, "requirements.txt"))
752
+ ) {
753
+ return "python";
754
+ }
755
+ if (
756
+ fs.existsSync(path.join(projectRoot, "tsconfig.json")) ||
757
+ fs.existsSync(path.join(projectRoot, "package.json"))
758
+ ) {
759
+ return "typescript";
760
+ }
761
+ return "generic";
762
+ }
763
+
764
+ private static detectFramework(
765
+ projectRoot: string,
766
+ language: DiscoveredProjectTopology["language"]
767
+ ): string {
768
+ if (language === "php") {
769
+ if (fs.existsSync(path.join(projectRoot, "artisan"))) return "laravel";
770
+ if (
771
+ fs.existsSync(path.join(projectRoot, "bin/console")) ||
772
+ fs.existsSync(path.join(projectRoot, "symfony.lock"))
773
+ ) {
774
+ return "symfony";
775
+ }
776
+ const composerJson = path.join(projectRoot, "composer.json");
777
+ if (fs.existsSync(composerJson)) {
778
+ try {
779
+ const composer = JSON.parse(fs.readFileSync(composerJson, "utf-8"));
780
+ const reqs = { ...(composer.require ?? {}), ...(composer["require-dev"] ?? {}) };
781
+ if (reqs["symfony/framework-bundle"] || reqs["symfony/symfony"]) {
782
+ return "symfony";
783
+ }
784
+ } catch {}
785
+ }
786
+ return "generic-php";
787
+ }
788
+ if (language === "typescript" || language === "javascript") {
789
+ const pkgJson = path.join(projectRoot, "package.json");
790
+ try {
791
+ if (fs.existsSync(pkgJson)) {
792
+ const pkg = JSON.parse(fs.readFileSync(pkgJson, "utf-8"));
793
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
794
+ if (allDeps.next) return "nextjs";
795
+ if (allDeps.nuxt) return "nuxt";
796
+ if (allDeps.astro) return "astro";
797
+ if (allDeps.vue) return "vue";
798
+ if (allDeps["@nestjs/core"]) return "nestjs";
799
+ if (allDeps.express) return "express";
800
+ if (allDeps.fastify) return "fastify";
801
+ if (allDeps.hono) return "hono";
802
+ if (allDeps.elysia) return "elysia";
803
+ if (allDeps["@modelcontextprotocol/sdk"]) return "mcp-server";
804
+ }
805
+ } catch (err: unknown) {
806
+ const msg = err instanceof Error ? err.message : String(err);
807
+ console.warn(`[Septum Topology] Failed to inspect dependencies in ${pkgJson}: ${msg}`);
808
+ }
809
+ return "generic-node";
810
+ }
811
+ if (language === "python") {
812
+ if (
813
+ fs.existsSync(path.join(projectRoot, "manage.py")) ||
814
+ fs.existsSync(path.join(projectRoot, "wsgi.py")) ||
815
+ fs.existsSync(path.join(projectRoot, "asgi.py"))
816
+ ) {
817
+ return "django";
818
+ }
819
+ const readSafe = (p: string) => {
820
+ try {
821
+ return fs.existsSync(p) ? fs.readFileSync(p, "utf-8").toLowerCase() : "";
822
+ } catch {
823
+ return "";
824
+ }
825
+ };
826
+ const deps =
827
+ readSafe(path.join(projectRoot, "requirements.txt")) +
828
+ " " +
829
+ readSafe(path.join(projectRoot, "pyproject.toml")) +
830
+ " " +
831
+ readSafe(path.join(projectRoot, "Pipfile"));
832
+ if (deps.includes("fastapi")) return "fastapi";
833
+ if (deps.includes("django")) return "django";
834
+ if (deps.includes("flask")) return "flask";
835
+ return "generic-python";
836
+ }
837
+ if (language === "go") {
838
+ const goModPath = path.join(projectRoot, "go.mod");
839
+ if (fs.existsSync(goModPath)) {
840
+ try {
841
+ const modContent = fs.readFileSync(goModPath, "utf-8").toLowerCase();
842
+ if (modContent.includes("github.com/gin-gonic/gin")) return "gin";
843
+ if (modContent.includes("github.com/labstack/echo")) return "echo";
844
+ if (modContent.includes("github.com/go-chi/chi")) return "chi";
845
+ if (modContent.includes("github.com/gofiber/fiber")) return "fiber";
846
+ } catch {}
847
+ }
848
+ return "generic-go";
849
+ }
850
+ return "generic";
851
+ }
852
+
853
+ private static getSubdirectories(dir: string): string[] {
854
+ try {
855
+ return fs
856
+ .readdirSync(dir, { withFileTypes: true })
857
+ .filter((e) => e.isDirectory() && !isIgnoredDirectory(e.name) && !this.IGNORED_DIRS.has(e.name))
858
+ .map((e) => e.name);
859
+ } catch {
860
+ return [];
861
+ }
862
+ }
863
+ }