septum 0.1.4 → 0.1.6

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 (70) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +105 -105
  3. package/bin/septum.ts +4 -4
  4. package/package.json +63 -63
  5. package/src/cli/commands/check.ts +161 -161
  6. package/src/cli/commands/hook.ts +216 -188
  7. package/src/cli/commands/ingest.ts +29 -29
  8. package/src/cli/commands/init.ts +213 -211
  9. package/src/cli/commands/locate.ts +61 -61
  10. package/src/cli/commands/query.ts +104 -64
  11. package/src/cli/commands/serve.ts +5 -5
  12. package/src/cli/commands/slice.ts +50 -48
  13. package/src/cli/commands/sync.ts +31 -31
  14. package/src/cli/index.ts +220 -210
  15. package/src/cli/templates/hooks.ts +75 -75
  16. package/src/cli/templates/rules.ts +50 -38
  17. package/src/cli/templates/skill.ts +65 -69
  18. package/src/core/boundary/evaluator.ts +429 -210
  19. package/src/core/config/loader.ts +117 -97
  20. package/src/core/config/schema.ts +39 -39
  21. package/src/core/database/client.ts +44 -44
  22. package/src/core/database/repositories/dependency.repository.ts +552 -349
  23. package/src/core/database/repositories/domain.repository.ts +275 -198
  24. package/src/core/database/repositories/file.repository.ts +117 -106
  25. package/src/core/database/repositories/meta.repository.ts +33 -33
  26. package/src/core/database/repositories/symbol.repository.ts +482 -443
  27. package/src/core/database/repository.ts +281 -260
  28. package/src/core/database/schema.ts +154 -153
  29. package/src/core/discovery/topology-detector.ts +486 -486
  30. package/src/core/ingestion/hasher.ts +5 -5
  31. package/src/core/ingestion/pipeline.ts +606 -535
  32. package/src/core/parser/boundary-tracker.ts +433 -288
  33. package/src/core/parser/extractors/base.ts +62 -62
  34. package/src/core/parser/extractors/blade.ts +158 -158
  35. package/src/core/parser/extractors/frontend.ts +147 -194
  36. package/src/core/parser/extractors/go.ts +408 -180
  37. package/src/core/parser/extractors/laravel-semantic.ts +1045 -901
  38. package/src/core/parser/extractors/mcp-cli-semantic.ts +328 -199
  39. package/src/core/parser/extractors/nestjs-semantic.ts +134 -119
  40. package/src/core/parser/extractors/php.ts +415 -153
  41. package/src/core/parser/extractors/python.ts +460 -228
  42. package/src/core/parser/extractors/registry.ts +70 -70
  43. package/src/core/parser/extractors/semantic-extractor.interface.ts +21 -21
  44. package/src/core/parser/extractors/typescript.ts +668 -181
  45. package/src/core/parser/tree-sitter.ts +41 -41
  46. package/src/core/parser/wasm-loader.ts +271 -0
  47. package/src/core/resolver/call-graph-tracer.ts +698 -668
  48. package/src/core/resolver/module-resolver.ts +479 -342
  49. package/src/core/resolver/path-resolver.ts +147 -147
  50. package/src/core/resolver/symbol-locator.ts +543 -543
  51. package/src/core/resolver/vertical-slice-tracer.ts +323 -285
  52. package/src/core/session/session-manager.ts +56 -56
  53. package/src/core/telemetry/telemetry.ts +86 -86
  54. package/src/core/topology/environment-detector.ts +109 -6
  55. package/src/index.ts +21 -21
  56. package/src/mcp/schemas.ts +695 -286
  57. package/src/mcp/server.ts +927 -716
  58. package/src/mcp/tools/check-boundary.ts +307 -152
  59. package/src/mcp/tools/get-domain-catalog.ts +155 -121
  60. package/src/mcp/tools/get-environment-topology.ts +3 -6
  61. package/src/mcp/tools/get-feature-context.ts +227 -116
  62. package/src/mcp/tools/get-symbol-hotspots.ts +54 -59
  63. package/src/mcp/tools/get-symbol-impact.ts +28 -26
  64. package/src/mcp/tools/get-symbol.ts +65 -63
  65. package/src/mcp/tools/locate-symbol.ts +169 -190
  66. package/src/mcp/tools/register-domain.ts +59 -64
  67. package/src/mcp/tools/register-feature.ts +91 -0
  68. package/src/mcp/tools/trace-vertical-slice.ts +74 -48
  69. package/src/types/index.ts +366 -315
  70. package/src/version.ts +3 -3
@@ -1,486 +1,486 @@
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
-
6
- export type ProjectType =
7
- | "monorepo"
8
- | "fullstack"
9
- | "backend"
10
- | "frontend"
11
- | "cli-mcp"
12
- | "generic";
13
-
14
- export type ArchitectureStyle =
15
- | "modular-ddd"
16
- | "layered-monolith"
17
- | "clean-architecture"
18
- | "monorepo-workspaces"
19
- | "cli-adapter"
20
- | "generic";
21
-
22
- export interface DiscoveredProjectTopology {
23
- framework: string;
24
- language: "typescript" | "javascript" | "php" | "python" | "go" | "generic";
25
- projectType: ProjectType;
26
- architectureStyle: ArchitectureStyle;
27
- domains: Record<string, DomainConfig>;
28
- }
29
-
30
- export class TopologyDetector {
31
- private static readonly IGNORED_DIRS = new Set([
32
- "node_modules",
33
- "vendor",
34
- "dist",
35
- "build",
36
- ".git",
37
- ".septum",
38
- ".system_generated",
39
- "tests",
40
- "test",
41
- "coverage",
42
- ".vscode",
43
- ".idea",
44
- ".agents",
45
- "bin",
46
- "locales",
47
- "resources",
48
- "public",
49
- "assets",
50
- "static",
51
- ".output",
52
- ".nuxt",
53
- ".next",
54
- ".turbo",
55
- ".cache",
56
- ]);
57
-
58
- private static readonly SOURCE_EXTENSIONS = new Set([
59
- ".ts",
60
- ".js",
61
- ".tsx",
62
- ".jsx",
63
- ".php",
64
- ".py",
65
- ".go",
66
- ".rs",
67
- ".vue",
68
- ]);
69
-
70
- /**
71
- * Reads compilerOptions.paths from tsconfig.json or jsconfig.json.
72
- */
73
- public static readTsConfigPaths(projectRoot: string): Record<string, string[]> {
74
- for (const file of ["tsconfig.json", "jsconfig.json"]) {
75
- const fullPath = path.join(projectRoot, file);
76
- if (fs.existsSync(fullPath)) {
77
- try {
78
- const raw = fs.readFileSync(fullPath, "utf-8");
79
- const stripped = raw.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
80
- const parsed = JSON.parse(stripped);
81
- if (parsed.compilerOptions?.paths) {
82
- return parsed.compilerOptions.paths;
83
- }
84
- } catch {
85
- // Ignore tsconfig parse error
86
- }
87
- }
88
- }
89
- return {};
90
- }
91
-
92
- /**
93
- * Checks whether a directory recursively contains any source code files.
94
- */
95
- private static hasSourceFiles(dir: string): boolean {
96
- try {
97
- const entries = fs.readdirSync(dir, { withFileTypes: true });
98
- for (const entry of entries) {
99
- if (entry.name.startsWith(".") || this.IGNORED_DIRS.has(entry.name)) continue;
100
- const full = path.join(dir, entry.name);
101
- if (entry.isFile()) {
102
- const ext = path.extname(entry.name).toLowerCase();
103
- if (this.SOURCE_EXTENSIONS.has(ext)) return true;
104
- } else if (entry.isDirectory()) {
105
- if (this.hasSourceFiles(full)) return true;
106
- }
107
- }
108
- } catch {
109
- // Ignore read errors
110
- }
111
- return false;
112
- }
113
-
114
- /**
115
- * Detects project topology, classifies project type & architecture style, and maps domains.
116
- */
117
- public static detect(projectRoot: string = process.cwd()): DiscoveredProjectTopology {
118
- const language = this.detectLanguage(projectRoot);
119
- const framework = this.detectFramework(projectRoot, language);
120
- const isMonorepo = this.detectMonorepo(projectRoot);
121
-
122
- const domains: Record<string, DomainConfig> = {};
123
- let architectureStyle: ArchitectureStyle = "generic";
124
-
125
- // 1. Monorepo Workspaces (apps/*, packages/*)
126
- if (isMonorepo) {
127
- architectureStyle = "monorepo-workspaces";
128
- const workspaceDirs = ["apps", "packages", "modules"];
129
- const appDomains: string[] = [];
130
- const packageDomains: string[] = [];
131
-
132
- for (const parent of workspaceDirs) {
133
- const fullParent = path.join(projectRoot, parent);
134
- if (fs.existsSync(fullParent) && fs.statSync(fullParent).isDirectory()) {
135
- const subs = this.getSubdirectories(fullParent);
136
- for (const sub of subs) {
137
- const relRoot = path.join(parent, sub);
138
- const domainName = sub.toLowerCase();
139
- if (parent === "apps") appDomains.push(domainName);
140
- else packageDomains.push(domainName);
141
-
142
- domains[domainName] = {
143
- root: relRoot,
144
- description: `Monorepo ${parent} package: ${sub}`,
145
- allowed_dependencies: parent === "apps" ? packageDomains : [],
146
- forbidden_dependencies: parent !== "apps" ? appDomains : [],
147
- archetypes: this.inferDefaultArchetypes(path.join(projectRoot, relRoot)),
148
- };
149
- }
150
- }
151
- }
152
- }
153
-
154
- // 2. Modular DDD (app/Domain, src/modules, src/domains, etc.)
155
- if (Object.keys(domains).length === 0) {
156
- const modularCandidates = [
157
- { prefix: "domain", dir: path.join(projectRoot, "app", "Domain") },
158
- { prefix: "domain", dir: path.join(projectRoot, "app", "Domains") },
159
- { prefix: "domain", dir: path.join(projectRoot, "src", "domains") },
160
- { prefix: "feature", dir: path.join(projectRoot, "src", "features") },
161
- { prefix: "module", dir: path.join(projectRoot, "src", "modules") },
162
- ];
163
-
164
- for (const cand of modularCandidates) {
165
- if (fs.existsSync(cand.dir) && fs.statSync(cand.dir).isDirectory()) {
166
- const subdirs = this.getSubdirectories(cand.dir);
167
- if (subdirs.length > 0) {
168
- architectureStyle = "modular-ddd";
169
- for (const sub of subdirs) {
170
- const relRoot = path.relative(projectRoot, path.join(cand.dir, sub));
171
- domains[sub.toLowerCase()] = {
172
- root: relRoot,
173
- description: `Modular ${cand.prefix} domain: ${sub}`,
174
- allowed_dependencies: ["shared", "common"],
175
- forbidden_dependencies: [],
176
- archetypes: this.inferDefaultArchetypes(path.join(projectRoot, relRoot)),
177
- };
178
- }
179
- }
180
- }
181
- }
182
- }
183
-
184
- // 3. Layered Monolith / Clean Architecture in src/
185
- const srcDir = path.join(projectRoot, "src");
186
- if (Object.keys(domains).length === 0 && fs.existsSync(srcDir) && fs.statSync(srcDir).isDirectory()) {
187
- const subdirs = this.getSubdirectories(srcDir);
188
- if (subdirs.length > 0) {
189
- architectureStyle =
190
- framework === "mcp-server" || framework === "cli"
191
- ? "cli-adapter"
192
- : "layered-monolith";
193
-
194
- const sharedKernelNames = new Set(["types", "shared", "common", "contracts"]);
195
- const coreNames = new Set(["core", "domain", "services", "usecase", "internal"]);
196
- const adapterNames = new Set([
197
- "cli",
198
- "mcp",
199
- "api",
200
- "controllers",
201
- "routes",
202
- "handlers",
203
- "delivery",
204
- ]);
205
-
206
- for (const sub of subdirs) {
207
- const relRoot = path.join("src", sub);
208
- const name = sub.toLowerCase();
209
- let allowed: string[] = [];
210
- let forbidden: string[] = [];
211
-
212
- if (sharedKernelNames.has(name)) {
213
- allowed = [];
214
- forbidden = Array.from(adapterNames)
215
- .concat(Array.from(coreNames))
216
- .filter((n) => subdirs.map((s) => s.toLowerCase()).includes(n));
217
- } else if (coreNames.has(name)) {
218
- allowed = subdirs
219
- .map((s) => s.toLowerCase())
220
- .filter((s) => sharedKernelNames.has(s));
221
- forbidden = subdirs
222
- .map((s) => s.toLowerCase())
223
- .filter((s) => adapterNames.has(s));
224
- } else {
225
- // Adapters
226
- allowed = subdirs
227
- .map((s) => s.toLowerCase())
228
- .filter((s) => sharedKernelNames.has(s) || coreNames.has(s));
229
- forbidden = [];
230
- }
231
-
232
- domains[name] = {
233
- root: relRoot,
234
- description: `${sub} layer`,
235
- allowed_dependencies: allowed,
236
- forbidden_dependencies: forbidden,
237
- archetypes: this.inferDefaultArchetypes(path.join(projectRoot, relRoot)),
238
- };
239
- }
240
- }
241
- }
242
-
243
- // 4. Framework-specific structural patterns (Laravel, Go)
244
- if (Object.keys(domains).length === 0) {
245
- if (language === "php" || framework.includes("laravel")) {
246
- const appDir = path.join(projectRoot, "app");
247
- if (fs.existsSync(appDir)) {
248
- architectureStyle = "layered-monolith";
249
- const subdirs = this.getSubdirectories(appDir);
250
- for (const sub of subdirs) {
251
- domains[sub.toLowerCase()] = {
252
- root: path.join("app", sub),
253
- description: `Laravel layer: ${sub}`,
254
- allowed_dependencies: [],
255
- forbidden_dependencies: [],
256
- archetypes: this.inferDefaultArchetypes(path.join(projectRoot, "app", sub)),
257
- };
258
- }
259
- }
260
- } else if (language === "go") {
261
- architectureStyle = "clean-architecture";
262
- for (const goDir of ["cmd", "internal", "pkg"]) {
263
- const full = path.join(projectRoot, goDir);
264
- if (fs.existsSync(full)) {
265
- domains[goDir] = {
266
- root: goDir,
267
- description: `Go layer: ${goDir}`,
268
- allowed_dependencies:
269
- goDir === "cmd"
270
- ? ["internal", "pkg"]
271
- : goDir === "internal"
272
- ? ["pkg"]
273
- : [],
274
- forbidden_dependencies: goDir === "pkg" ? ["internal", "cmd"] : [],
275
- archetypes: this.inferDefaultArchetypes(full),
276
- };
277
- }
278
- }
279
- }
280
- }
281
-
282
- // 5. Fallback: Top-level directories that contain source code
283
- if (Object.keys(domains).length === 0) {
284
- const topDirs = this.getSubdirectories(projectRoot).filter((d) =>
285
- this.hasSourceFiles(path.join(projectRoot, d))
286
- );
287
- for (const d of topDirs) {
288
- domains[d.toLowerCase()] = {
289
- root: d,
290
- description: `Top-level domain: ${d}`,
291
- allowed_dependencies: [],
292
- forbidden_dependencies: [],
293
- archetypes: this.inferDefaultArchetypes(path.join(projectRoot, d)),
294
- };
295
- }
296
- }
297
-
298
- const projectType = this.detectProjectType(projectRoot, framework, language, isMonorepo);
299
-
300
- return {
301
- framework,
302
- language,
303
- projectType,
304
- architectureStyle,
305
- domains,
306
- };
307
- }
308
-
309
- /**
310
- * Discovers project topology and persists domains and macro metadata directly into SQLite SSOT.
311
- */
312
- public static discoverAndPersist(
313
- repo: SeptumRepository,
314
- projectRoot: string = process.cwd()
315
- ): Record<string, DomainConfig> {
316
- const topology = this.detect(projectRoot);
317
-
318
- for (const [name, config] of Object.entries(topology.domains)) {
319
- repo.upsertDomain(name, config);
320
- }
321
-
322
- // Persist Macro Metadata SSOT
323
- repo.setMeta("project_type", topology.projectType);
324
- repo.setMeta("architecture_style", topology.architectureStyle);
325
- repo.setMeta("framework", topology.framework);
326
- repo.setMeta("language", topology.language);
327
- repo.setMeta(
328
- "macro_summary",
329
- JSON.stringify({
330
- projectType: topology.projectType,
331
- framework: topology.framework,
332
- architectureStyle: topology.architectureStyle,
333
- domainsCount: Object.keys(topology.domains).length,
334
- domains: Object.keys(topology.domains),
335
- })
336
- );
337
-
338
- return topology.domains;
339
- }
340
-
341
- private static detectMonorepo(projectRoot: string): boolean {
342
- if (
343
- fs.existsSync(path.join(projectRoot, "pnpm-workspace.yaml")) ||
344
- fs.existsSync(path.join(projectRoot, "lerna.json")) ||
345
- fs.existsSync(path.join(projectRoot, "turbo.json"))
346
- ) {
347
- return true;
348
- }
349
-
350
- const hasApps = fs.existsSync(path.join(projectRoot, "apps"));
351
- const hasPackages = fs.existsSync(path.join(projectRoot, "packages"));
352
- if (hasApps && hasPackages) return true;
353
-
354
- const pkgPath = path.join(projectRoot, "package.json");
355
- if (fs.existsSync(pkgPath)) {
356
- try {
357
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
358
- if (pkg.workspaces && Array.isArray(pkg.workspaces) && pkg.workspaces.length > 0) {
359
- return true;
360
- }
361
- } catch (err: unknown) {
362
- const msg = err instanceof Error ? err.message : String(err);
363
- console.warn(`[Septum Topology] Could not parse ${pkgPath}: ${msg}`);
364
- }
365
- }
366
-
367
- return false;
368
- }
369
-
370
- private static detectProjectType(
371
- projectRoot: string,
372
- framework: string,
373
- language: string,
374
- isMonorepo: boolean
375
- ): ProjectType {
376
- if (isMonorepo) return "monorepo";
377
-
378
- if (framework === "mcp-server" || framework === "cli") return "cli-mcp";
379
-
380
- if (framework === "nextjs" || framework === "nuxt" || framework === "astro") {
381
- return "fullstack";
382
- }
383
-
384
- if (framework.includes("laravel")) {
385
- const hasJs = fs.existsSync(path.join(projectRoot, "resources/js"));
386
- const hasViews = fs.existsSync(path.join(projectRoot, "resources/views"));
387
- return hasJs || hasViews ? "fullstack" : "backend";
388
- }
389
-
390
- if (framework === "vue" || framework === "react") {
391
- return "frontend";
392
- }
393
-
394
- if (
395
- framework === "nestjs" ||
396
- framework === "express" ||
397
- framework === "fastify" ||
398
- language === "go" ||
399
- language === "python" ||
400
- language === "php"
401
- ) {
402
- return "backend";
403
- }
404
-
405
- return "generic";
406
- }
407
-
408
- private static inferDefaultArchetypes(fullDir: string): Record<string, string> {
409
- const archetypes: Record<string, string> = {};
410
- if (!fs.existsSync(fullDir)) return archetypes;
411
-
412
- try {
413
- const items = fs.readdirSync(fullDir, { withFileTypes: true });
414
- for (const it of items) {
415
- if (it.isDirectory() && !it.name.startsWith(".")) {
416
- const name = it.name.toLowerCase();
417
- archetypes[name] = `${it.name}/**`;
418
- }
419
- }
420
- if (Object.keys(archetypes).length === 0) {
421
- archetypes["source"] = "**/*.*";
422
- }
423
- } catch {}
424
-
425
- return archetypes;
426
- }
427
-
428
- private static detectLanguage(projectRoot: string): DiscoveredProjectTopology["language"] {
429
- if (fs.existsSync(path.join(projectRoot, "composer.json"))) return "php";
430
- if (fs.existsSync(path.join(projectRoot, "go.mod"))) return "go";
431
- if (
432
- fs.existsSync(path.join(projectRoot, "pyproject.toml")) ||
433
- fs.existsSync(path.join(projectRoot, "requirements.txt"))
434
- ) {
435
- return "python";
436
- }
437
- if (
438
- fs.existsSync(path.join(projectRoot, "tsconfig.json")) ||
439
- fs.existsSync(path.join(projectRoot, "package.json"))
440
- ) {
441
- return "typescript";
442
- }
443
- return "generic";
444
- }
445
-
446
- private static detectFramework(
447
- projectRoot: string,
448
- language: DiscoveredProjectTopology["language"]
449
- ): string {
450
- if (language === "php") {
451
- if (fs.existsSync(path.join(projectRoot, "artisan"))) return "laravel";
452
- return "generic-php";
453
- }
454
- if (language === "typescript" || language === "javascript") {
455
- const pkgJson = path.join(projectRoot, "package.json");
456
- try {
457
- if (fs.existsSync(pkgJson)) {
458
- const pkg = JSON.parse(fs.readFileSync(pkgJson, "utf-8"));
459
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
460
- if (allDeps.next) return "nextjs";
461
- if (allDeps.nuxt) return "nuxt";
462
- if (allDeps.astro) return "astro";
463
- if (allDeps.vue) return "vue";
464
- if (allDeps["@nestjs/core"]) return "nestjs";
465
- if (allDeps["@modelcontextprotocol/sdk"]) return "mcp-server";
466
- }
467
- } catch (err: unknown) {
468
- const msg = err instanceof Error ? err.message : String(err);
469
- console.warn(`[Septum Topology] Failed to inspect dependencies in ${pkgJson}: ${msg}`);
470
- }
471
- return "generic-node";
472
- }
473
- return "generic";
474
- }
475
-
476
- private static getSubdirectories(dir: string): string[] {
477
- try {
478
- return fs
479
- .readdirSync(dir, { withFileTypes: true })
480
- .filter((e) => e.isDirectory() && !this.IGNORED_DIRS.has(e.name) && !e.name.startsWith("."))
481
- .map((e) => e.name);
482
- } catch {
483
- return [];
484
- }
485
- }
486
- }
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
+
6
+ export type ProjectType =
7
+ | "monorepo"
8
+ | "fullstack"
9
+ | "backend"
10
+ | "frontend"
11
+ | "cli-mcp"
12
+ | "generic";
13
+
14
+ export type ArchitectureStyle =
15
+ | "modular-ddd"
16
+ | "layered-monolith"
17
+ | "clean-architecture"
18
+ | "monorepo-workspaces"
19
+ | "cli-adapter"
20
+ | "generic";
21
+
22
+ export interface DiscoveredProjectTopology {
23
+ framework: string;
24
+ language: "typescript" | "javascript" | "php" | "python" | "go" | "generic";
25
+ projectType: ProjectType;
26
+ architectureStyle: ArchitectureStyle;
27
+ domains: Record<string, DomainConfig>;
28
+ }
29
+
30
+ export class TopologyDetector {
31
+ private static readonly IGNORED_DIRS = new Set([
32
+ "node_modules",
33
+ "vendor",
34
+ "dist",
35
+ "build",
36
+ ".git",
37
+ ".septum",
38
+ ".system_generated",
39
+ "tests",
40
+ "test",
41
+ "coverage",
42
+ ".vscode",
43
+ ".idea",
44
+ ".agents",
45
+ "bin",
46
+ "locales",
47
+ "resources",
48
+ "public",
49
+ "assets",
50
+ "static",
51
+ ".output",
52
+ ".nuxt",
53
+ ".next",
54
+ ".turbo",
55
+ ".cache",
56
+ ]);
57
+
58
+ private static readonly SOURCE_EXTENSIONS = new Set([
59
+ ".ts",
60
+ ".js",
61
+ ".tsx",
62
+ ".jsx",
63
+ ".php",
64
+ ".py",
65
+ ".go",
66
+ ".rs",
67
+ ".vue",
68
+ ]);
69
+
70
+ /**
71
+ * Reads compilerOptions.paths from tsconfig.json or jsconfig.json.
72
+ */
73
+ public static readTsConfigPaths(projectRoot: string): Record<string, string[]> {
74
+ for (const file of ["tsconfig.json", "jsconfig.json"]) {
75
+ const fullPath = path.join(projectRoot, file);
76
+ if (fs.existsSync(fullPath)) {
77
+ try {
78
+ const raw = fs.readFileSync(fullPath, "utf-8");
79
+ const stripped = raw.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
80
+ const parsed = JSON.parse(stripped);
81
+ if (parsed.compilerOptions?.paths) {
82
+ return parsed.compilerOptions.paths;
83
+ }
84
+ } catch {
85
+ // Ignore tsconfig parse error
86
+ }
87
+ }
88
+ }
89
+ return {};
90
+ }
91
+
92
+ /**
93
+ * Checks whether a directory recursively contains any source code files.
94
+ */
95
+ private static hasSourceFiles(dir: string): boolean {
96
+ try {
97
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
98
+ for (const entry of entries) {
99
+ if (entry.name.startsWith(".") || this.IGNORED_DIRS.has(entry.name)) continue;
100
+ const full = path.join(dir, entry.name);
101
+ if (entry.isFile()) {
102
+ const ext = path.extname(entry.name).toLowerCase();
103
+ if (this.SOURCE_EXTENSIONS.has(ext)) return true;
104
+ } else if (entry.isDirectory()) {
105
+ if (this.hasSourceFiles(full)) return true;
106
+ }
107
+ }
108
+ } catch {
109
+ // Ignore read errors
110
+ }
111
+ return false;
112
+ }
113
+
114
+ /**
115
+ * Detects project topology, classifies project type & architecture style, and maps domains.
116
+ */
117
+ public static detect(projectRoot: string = process.cwd()): DiscoveredProjectTopology {
118
+ const language = this.detectLanguage(projectRoot);
119
+ const framework = this.detectFramework(projectRoot, language);
120
+ const isMonorepo = this.detectMonorepo(projectRoot);
121
+
122
+ const domains: Record<string, DomainConfig> = {};
123
+ let architectureStyle: ArchitectureStyle = "generic";
124
+
125
+ // 1. Monorepo Workspaces (apps/*, packages/*)
126
+ if (isMonorepo) {
127
+ architectureStyle = "monorepo-workspaces";
128
+ const workspaceDirs = ["apps", "packages", "modules"];
129
+ const appDomains: string[] = [];
130
+ const packageDomains: string[] = [];
131
+
132
+ for (const parent of workspaceDirs) {
133
+ const fullParent = path.join(projectRoot, parent);
134
+ if (fs.existsSync(fullParent) && fs.statSync(fullParent).isDirectory()) {
135
+ const subs = this.getSubdirectories(fullParent);
136
+ for (const sub of subs) {
137
+ const relRoot = path.join(parent, sub);
138
+ const domainName = sub.toLowerCase();
139
+ if (parent === "apps") appDomains.push(domainName);
140
+ else packageDomains.push(domainName);
141
+
142
+ domains[domainName] = {
143
+ root: relRoot,
144
+ description: `Monorepo ${parent} package: ${sub}`,
145
+ allowed_dependencies: parent === "apps" ? packageDomains : [],
146
+ forbidden_dependencies: parent !== "apps" ? appDomains : [],
147
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, relRoot)),
148
+ };
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+ // 2. Modular DDD (app/Domain, src/modules, src/domains, etc.)
155
+ if (Object.keys(domains).length === 0) {
156
+ const modularCandidates = [
157
+ { prefix: "domain", dir: path.join(projectRoot, "app", "Domain") },
158
+ { prefix: "domain", dir: path.join(projectRoot, "app", "Domains") },
159
+ { prefix: "domain", dir: path.join(projectRoot, "src", "domains") },
160
+ { prefix: "feature", dir: path.join(projectRoot, "src", "features") },
161
+ { prefix: "module", dir: path.join(projectRoot, "src", "modules") },
162
+ ];
163
+
164
+ for (const cand of modularCandidates) {
165
+ if (fs.existsSync(cand.dir) && fs.statSync(cand.dir).isDirectory()) {
166
+ const subdirs = this.getSubdirectories(cand.dir);
167
+ if (subdirs.length > 0) {
168
+ architectureStyle = "modular-ddd";
169
+ for (const sub of subdirs) {
170
+ const relRoot = path.relative(projectRoot, path.join(cand.dir, sub));
171
+ domains[sub.toLowerCase()] = {
172
+ root: relRoot,
173
+ description: `Modular ${cand.prefix} domain: ${sub}`,
174
+ allowed_dependencies: ["shared", "common"],
175
+ forbidden_dependencies: [],
176
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, relRoot)),
177
+ };
178
+ }
179
+ }
180
+ }
181
+ }
182
+ }
183
+
184
+ // 3. Layered Monolith / Clean Architecture in src/
185
+ const srcDir = path.join(projectRoot, "src");
186
+ if (Object.keys(domains).length === 0 && fs.existsSync(srcDir) && fs.statSync(srcDir).isDirectory()) {
187
+ const subdirs = this.getSubdirectories(srcDir);
188
+ if (subdirs.length > 0) {
189
+ architectureStyle =
190
+ framework === "mcp-server" || framework === "cli"
191
+ ? "cli-adapter"
192
+ : "layered-monolith";
193
+
194
+ const sharedKernelNames = new Set(["types", "shared", "common", "contracts"]);
195
+ const coreNames = new Set(["core", "domain", "services", "usecase", "internal"]);
196
+ const adapterNames = new Set([
197
+ "cli",
198
+ "mcp",
199
+ "api",
200
+ "controllers",
201
+ "routes",
202
+ "handlers",
203
+ "delivery",
204
+ ]);
205
+
206
+ for (const sub of subdirs) {
207
+ const relRoot = path.join("src", sub);
208
+ const name = sub.toLowerCase();
209
+ let allowed: string[] = [];
210
+ let forbidden: string[] = [];
211
+
212
+ if (sharedKernelNames.has(name)) {
213
+ allowed = [];
214
+ forbidden = Array.from(adapterNames)
215
+ .concat(Array.from(coreNames))
216
+ .filter((n) => subdirs.map((s) => s.toLowerCase()).includes(n));
217
+ } else if (coreNames.has(name)) {
218
+ allowed = subdirs
219
+ .map((s) => s.toLowerCase())
220
+ .filter((s) => sharedKernelNames.has(s));
221
+ forbidden = subdirs
222
+ .map((s) => s.toLowerCase())
223
+ .filter((s) => adapterNames.has(s));
224
+ } else {
225
+ // Adapters
226
+ allowed = subdirs
227
+ .map((s) => s.toLowerCase())
228
+ .filter((s) => sharedKernelNames.has(s) || coreNames.has(s));
229
+ forbidden = [];
230
+ }
231
+
232
+ domains[name] = {
233
+ root: relRoot,
234
+ description: `${sub} layer`,
235
+ allowed_dependencies: allowed,
236
+ forbidden_dependencies: forbidden,
237
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, relRoot)),
238
+ };
239
+ }
240
+ }
241
+ }
242
+
243
+ // 4. Framework-specific structural patterns (Laravel, Go)
244
+ if (Object.keys(domains).length === 0) {
245
+ if (language === "php" || framework.includes("laravel")) {
246
+ const appDir = path.join(projectRoot, "app");
247
+ if (fs.existsSync(appDir)) {
248
+ architectureStyle = "layered-monolith";
249
+ const subdirs = this.getSubdirectories(appDir);
250
+ for (const sub of subdirs) {
251
+ domains[sub.toLowerCase()] = {
252
+ root: path.join("app", sub),
253
+ description: `Laravel layer: ${sub}`,
254
+ allowed_dependencies: [],
255
+ forbidden_dependencies: [],
256
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, "app", sub)),
257
+ };
258
+ }
259
+ }
260
+ } else if (language === "go") {
261
+ architectureStyle = "clean-architecture";
262
+ for (const goDir of ["cmd", "internal", "pkg"]) {
263
+ const full = path.join(projectRoot, goDir);
264
+ if (fs.existsSync(full)) {
265
+ domains[goDir] = {
266
+ root: goDir,
267
+ description: `Go layer: ${goDir}`,
268
+ allowed_dependencies:
269
+ goDir === "cmd"
270
+ ? ["internal", "pkg"]
271
+ : goDir === "internal"
272
+ ? ["pkg"]
273
+ : [],
274
+ forbidden_dependencies: goDir === "pkg" ? ["internal", "cmd"] : [],
275
+ archetypes: this.inferDefaultArchetypes(full),
276
+ };
277
+ }
278
+ }
279
+ }
280
+ }
281
+
282
+ // 5. Fallback: Top-level directories that contain source code
283
+ if (Object.keys(domains).length === 0) {
284
+ const topDirs = this.getSubdirectories(projectRoot).filter((d) =>
285
+ this.hasSourceFiles(path.join(projectRoot, d))
286
+ );
287
+ for (const d of topDirs) {
288
+ domains[d.toLowerCase()] = {
289
+ root: d,
290
+ description: `Top-level domain: ${d}`,
291
+ allowed_dependencies: [],
292
+ forbidden_dependencies: [],
293
+ archetypes: this.inferDefaultArchetypes(path.join(projectRoot, d)),
294
+ };
295
+ }
296
+ }
297
+
298
+ const projectType = this.detectProjectType(projectRoot, framework, language, isMonorepo);
299
+
300
+ return {
301
+ framework,
302
+ language,
303
+ projectType,
304
+ architectureStyle,
305
+ domains,
306
+ };
307
+ }
308
+
309
+ /**
310
+ * Discovers project topology and persists domains and macro metadata directly into SQLite SSOT.
311
+ */
312
+ public static discoverAndPersist(
313
+ repo: SeptumRepository,
314
+ projectRoot: string = process.cwd()
315
+ ): Record<string, DomainConfig> {
316
+ const topology = this.detect(projectRoot);
317
+
318
+ for (const [name, config] of Object.entries(topology.domains)) {
319
+ repo.upsertDomain(name, config);
320
+ }
321
+
322
+ // Persist Macro Metadata SSOT
323
+ repo.setMeta("project_type", topology.projectType);
324
+ repo.setMeta("architecture_style", topology.architectureStyle);
325
+ repo.setMeta("framework", topology.framework);
326
+ repo.setMeta("language", topology.language);
327
+ repo.setMeta(
328
+ "macro_summary",
329
+ JSON.stringify({
330
+ projectType: topology.projectType,
331
+ framework: topology.framework,
332
+ architectureStyle: topology.architectureStyle,
333
+ domainsCount: Object.keys(topology.domains).length,
334
+ domains: Object.keys(topology.domains),
335
+ })
336
+ );
337
+
338
+ return topology.domains;
339
+ }
340
+
341
+ private static detectMonorepo(projectRoot: string): boolean {
342
+ if (
343
+ fs.existsSync(path.join(projectRoot, "pnpm-workspace.yaml")) ||
344
+ fs.existsSync(path.join(projectRoot, "lerna.json")) ||
345
+ fs.existsSync(path.join(projectRoot, "turbo.json"))
346
+ ) {
347
+ return true;
348
+ }
349
+
350
+ const hasApps = fs.existsSync(path.join(projectRoot, "apps"));
351
+ const hasPackages = fs.existsSync(path.join(projectRoot, "packages"));
352
+ if (hasApps && hasPackages) return true;
353
+
354
+ const pkgPath = path.join(projectRoot, "package.json");
355
+ if (fs.existsSync(pkgPath)) {
356
+ try {
357
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
358
+ if (pkg.workspaces && Array.isArray(pkg.workspaces) && pkg.workspaces.length > 0) {
359
+ return true;
360
+ }
361
+ } catch (err: unknown) {
362
+ const msg = err instanceof Error ? err.message : String(err);
363
+ console.warn(`[Septum Topology] Could not parse ${pkgPath}: ${msg}`);
364
+ }
365
+ }
366
+
367
+ return false;
368
+ }
369
+
370
+ private static detectProjectType(
371
+ projectRoot: string,
372
+ framework: string,
373
+ language: string,
374
+ isMonorepo: boolean
375
+ ): ProjectType {
376
+ if (isMonorepo) return "monorepo";
377
+
378
+ if (framework === "mcp-server" || framework === "cli") return "cli-mcp";
379
+
380
+ if (framework === "nextjs" || framework === "nuxt" || framework === "astro") {
381
+ return "fullstack";
382
+ }
383
+
384
+ if (framework.includes("laravel")) {
385
+ const hasJs = fs.existsSync(path.join(projectRoot, "resources/js"));
386
+ const hasViews = fs.existsSync(path.join(projectRoot, "resources/views"));
387
+ return hasJs || hasViews ? "fullstack" : "backend";
388
+ }
389
+
390
+ if (framework === "vue" || framework === "react") {
391
+ return "frontend";
392
+ }
393
+
394
+ if (
395
+ framework === "nestjs" ||
396
+ framework === "express" ||
397
+ framework === "fastify" ||
398
+ language === "go" ||
399
+ language === "python" ||
400
+ language === "php"
401
+ ) {
402
+ return "backend";
403
+ }
404
+
405
+ return "generic";
406
+ }
407
+
408
+ private static inferDefaultArchetypes(fullDir: string): Record<string, string> {
409
+ const archetypes: Record<string, string> = {};
410
+ if (!fs.existsSync(fullDir)) return archetypes;
411
+
412
+ try {
413
+ const items = fs.readdirSync(fullDir, { withFileTypes: true });
414
+ for (const it of items) {
415
+ if (it.isDirectory() && !it.name.startsWith(".")) {
416
+ const name = it.name.toLowerCase();
417
+ archetypes[name] = `${it.name}/**`;
418
+ }
419
+ }
420
+ if (Object.keys(archetypes).length === 0) {
421
+ archetypes["source"] = "**/*.*";
422
+ }
423
+ } catch {}
424
+
425
+ return archetypes;
426
+ }
427
+
428
+ private static detectLanguage(projectRoot: string): DiscoveredProjectTopology["language"] {
429
+ if (fs.existsSync(path.join(projectRoot, "composer.json"))) return "php";
430
+ if (fs.existsSync(path.join(projectRoot, "go.mod"))) return "go";
431
+ if (
432
+ fs.existsSync(path.join(projectRoot, "pyproject.toml")) ||
433
+ fs.existsSync(path.join(projectRoot, "requirements.txt"))
434
+ ) {
435
+ return "python";
436
+ }
437
+ if (
438
+ fs.existsSync(path.join(projectRoot, "tsconfig.json")) ||
439
+ fs.existsSync(path.join(projectRoot, "package.json"))
440
+ ) {
441
+ return "typescript";
442
+ }
443
+ return "generic";
444
+ }
445
+
446
+ private static detectFramework(
447
+ projectRoot: string,
448
+ language: DiscoveredProjectTopology["language"]
449
+ ): string {
450
+ if (language === "php") {
451
+ if (fs.existsSync(path.join(projectRoot, "artisan"))) return "laravel";
452
+ return "generic-php";
453
+ }
454
+ if (language === "typescript" || language === "javascript") {
455
+ const pkgJson = path.join(projectRoot, "package.json");
456
+ try {
457
+ if (fs.existsSync(pkgJson)) {
458
+ const pkg = JSON.parse(fs.readFileSync(pkgJson, "utf-8"));
459
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
460
+ if (allDeps.next) return "nextjs";
461
+ if (allDeps.nuxt) return "nuxt";
462
+ if (allDeps.astro) return "astro";
463
+ if (allDeps.vue) return "vue";
464
+ if (allDeps["@nestjs/core"]) return "nestjs";
465
+ if (allDeps["@modelcontextprotocol/sdk"]) return "mcp-server";
466
+ }
467
+ } catch (err: unknown) {
468
+ const msg = err instanceof Error ? err.message : String(err);
469
+ console.warn(`[Septum Topology] Failed to inspect dependencies in ${pkgJson}: ${msg}`);
470
+ }
471
+ return "generic-node";
472
+ }
473
+ return "generic";
474
+ }
475
+
476
+ private static getSubdirectories(dir: string): string[] {
477
+ try {
478
+ return fs
479
+ .readdirSync(dir, { withFileTypes: true })
480
+ .filter((e) => e.isDirectory() && !this.IGNORED_DIRS.has(e.name) && !e.name.startsWith("."))
481
+ .map((e) => e.name);
482
+ } catch {
483
+ return [];
484
+ }
485
+ }
486
+ }