@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,442 @@
1
+ import { posix, relative, resolve, isAbsolute } from "node:path";
2
+ import type { BoundaryViolation } from "../../types/index.ts";
3
+ import type { ValidatedSeptumConfig } from "../config/schema.ts";
4
+ import { ConfigLoader } from "../config/loader.ts";
5
+ import type { SeptumRepository } from "../database/repository.ts";
6
+ import { ModuleResolver } from "../resolver/module-resolver.ts";
7
+ import { matchesSimpleGlob } from "../parser/extractors/base.ts";
8
+
9
+ export class BoundaryEvaluator {
10
+ private repo: SeptumRepository;
11
+ private resolver: ModuleResolver;
12
+
13
+ constructor(repo: SeptumRepository, resolver?: ModuleResolver) {
14
+ this.repo = repo;
15
+ this.resolver = resolver ?? new ModuleResolver(process.cwd(), repo);
16
+ }
17
+
18
+ public getResolver(): ModuleResolver {
19
+ return this.resolver;
20
+ }
21
+
22
+ public evaluate(
23
+ filePath: string,
24
+ proposedImports: string[] = [],
25
+ featureKey?: string,
26
+ config?: ValidatedSeptumConfig
27
+ ): BoundaryViolation[] {
28
+ let activeConfig = config;
29
+ if (!activeConfig) {
30
+ const fromRepo = ConfigLoader.loadFromRepository(this.repo);
31
+ activeConfig =
32
+ Object.keys(fromRepo.domains).length > 0
33
+ ? fromRepo
34
+ : ConfigLoader.loadFromDatabaseOrDefaults();
35
+ }
36
+ const violations: BoundaryViolation[] = [];
37
+
38
+ if (featureKey) {
39
+ violations.push(...this.checkFeatureTouchpoints(featureKey, filePath, activeConfig));
40
+ }
41
+
42
+ if (proposedImports.length > 0) {
43
+ violations.push(...this.checkProposedChanges(filePath, proposedImports, activeConfig));
44
+ }
45
+
46
+ return violations;
47
+ }
48
+
49
+ public auditCodebase(config: ValidatedSeptumConfig): BoundaryViolation[] {
50
+ const violations: BoundaryViolation[] = [];
51
+ const allDependencies = this.repo.getAllDependenciesWithDomains();
52
+
53
+ const evidence = this.repo.getMeta?.("workspace_root") ? this.repo.getImportRelationships(this.resolver.getProjectRoot()) : undefined;
54
+ for (const dep of allDependencies) {
55
+ if (evidence && !evidence.some(edge => edge.source.file === dep.source_file && edge.source.line === dep.line_number && edge.freshness === "current" && edge.resolution.status === "resolved" && edge.resolution.coverage !== "conditional")) continue;
56
+ const targetDomain = this.resolveTargetDomain(dep.target, config, dep.source_file);
57
+ if (!targetDomain || targetDomain === dep.source_domain) {
58
+ continue;
59
+ }
60
+
61
+ const sourceDomainConfig = config.domains[dep.source_domain];
62
+ if (!sourceDomainConfig) {
63
+ continue;
64
+ }
65
+
66
+ const forbidden = sourceDomainConfig.forbidden_dependencies ?? [];
67
+ const allowed = sourceDomainConfig.allowed_dependencies ?? [];
68
+
69
+ // 1. Explicit forbidden check
70
+ if (forbidden.includes(targetDomain)) {
71
+ violations.push({
72
+ file: dep.source_file,
73
+ line: dep.line_number,
74
+ source_domain: dep.source_domain,
75
+ target_domain: targetDomain,
76
+ imported_target: dep.target,
77
+ rule: "forbidden_dependency",
78
+ message: `Forbidden cross-domain dependency detected: '${dep.source_domain}' is strictly prohibited from importing domain '${targetDomain}'.`,
79
+ });
80
+ continue;
81
+ }
82
+
83
+ // 2. Strict enforcement allowed check
84
+ if (config.settings.enforcement === "strict" && !allowed.includes(targetDomain)) {
85
+ violations.push({
86
+ file: dep.source_file,
87
+ line: dep.line_number,
88
+ source_domain: dep.source_domain,
89
+ target_domain: targetDomain,
90
+ imported_target: dep.target,
91
+ rule: "disallowed_dependency",
92
+ message: `Disallowed dependency: '${targetDomain}' is not declared in allowed_dependencies for domain '${dep.source_domain}'.`,
93
+ });
94
+ }
95
+ }
96
+
97
+ const currentDependencies = evidence ? allDependencies.filter(dep => evidence.some(edge => edge.source.file === dep.source_file && edge.source.line === dep.line_number && edge.freshness === "current")) : allDependencies;
98
+ violations.push(...this.detectCircularDependencies(config, currentDependencies));
99
+
100
+ return violations;
101
+ }
102
+
103
+ public detectCircularDependencies(
104
+ config: ValidatedSeptumConfig,
105
+ preloadedDeps?: Array<{
106
+ source_file: string;
107
+ source_domain: string;
108
+ line_number: number;
109
+ target: string;
110
+ statement: string;
111
+ is_external: boolean;
112
+ }>,
113
+ relevantFiles?: ReadonlySet<string>
114
+ ): BoundaryViolation[] {
115
+ const violations: BoundaryViolation[] = [];
116
+ let allDependencies = preloadedDeps ?? this.repo.getAllDependenciesWithDomains();
117
+ if (!preloadedDeps && this.repo.getMeta?.("workspace_root")) {
118
+ const current = this.repo.getImportRelationships(this.resolver.getProjectRoot());
119
+ allDependencies = allDependencies.filter(dep => current.some(edge => edge.source.file === dep.source_file && edge.source.line === dep.line_number && edge.freshness === "current"));
120
+ }
121
+
122
+ // Prepare file lookup maps for internal file-to-file resolution
123
+ const fileByNormPath = new Map<string, string>();
124
+ const fileByNoExtPath = new Map<string, string>();
125
+
126
+ const registerKnownFile = (rawPath: string) => {
127
+ const norm = rawPath.replace(/\\/g, "/").replace(/^\.\//, "");
128
+ fileByNormPath.set(norm.toLowerCase(), rawPath);
129
+ const noExt = norm.replace(/\.[^/.]+$/, "").toLowerCase();
130
+ fileByNoExtPath.set(noExt, rawPath);
131
+ if (noExt.endsWith("/index")) {
132
+ fileByNoExtPath.set(noExt.slice(0, -"/index".length), rawPath);
133
+ }
134
+ };
135
+
136
+ if (typeof this.repo.getAllFiles === "function") {
137
+ for (const f of this.repo.getAllFiles()) {
138
+ registerKnownFile(f.path);
139
+ }
140
+ }
141
+ for (const d of allDependencies) {
142
+ registerKnownFile(d.source_file);
143
+ }
144
+
145
+ const resolveTargetFile = (sourceFile: string, rawTarget: string): string | null => {
146
+ if (this.repo.getMeta?.("workspace_root")) {
147
+ const result = this.resolver.resolveImport(rawTarget,sourceFile);
148
+ const files = result.targets.flatMap(target => target.files);
149
+ return result.status === "resolved" && result.coverage !== "conditional" && files.length === 1 ? files[0]! : null;
150
+ }
151
+ const cleaned = rawTarget.trim().replace(/^['"]|['"]$/g, "").replace(/\\/g, "/");
152
+ if (!cleaned) return null;
153
+
154
+ if (cleaned.startsWith(".")) {
155
+ const srcDir = posix.dirname(sourceFile.replace(/\\/g, "/"));
156
+ const joined = posix.normalize(posix.join(srcDir, cleaned)).replace(/^\.\//, "");
157
+ const lowerJoined = joined.toLowerCase();
158
+ const exact =
159
+ fileByNormPath.get(lowerJoined) ??
160
+ fileByNoExtPath.get(lowerJoined.replace(/\.[^/.]+$/, ""));
161
+ if (exact) return exact;
162
+ }
163
+
164
+ const aliasClean = cleaned.replace(/^@\//, "src/").replace(/^\.\//, "");
165
+ const lowerAlias = aliasClean.toLowerCase();
166
+ const byAlias =
167
+ fileByNormPath.get(lowerAlias) ??
168
+ fileByNoExtPath.get(lowerAlias.replace(/\.[^/.]+$/, ""));
169
+ if (byAlias) return byAlias;
170
+
171
+ return null;
172
+ };
173
+
174
+ type EdgeMeta = {
175
+ files: Set<string>;
176
+ file: string;
177
+ line: number;
178
+ source_domain: string;
179
+ target_domain: string;
180
+ target: string;
181
+ };
182
+
183
+ const fileGraph = new Map<string, Map<string, EdgeMeta>>();
184
+ const domainGraph = new Map<string, Map<string, EdgeMeta>>();
185
+
186
+ for (const dep of allDependencies) {
187
+ if (this.repo.getMeta?.("workspace_root")) {
188
+ const result = this.resolver.resolveImport(dep.target,dep.source_file);
189
+ if (result.status !== "resolved" || result.coverage === "conditional") continue;
190
+ } else if (dep.is_external) continue;
191
+
192
+ const targetDomain = this.resolveTargetDomain(dep.target, config, dep.source_file);
193
+
194
+ // 1. Domain-to-domain edge
195
+ if (targetDomain && targetDomain !== dep.source_domain) {
196
+ let outMap = domainGraph.get(dep.source_domain);
197
+ if (!outMap) {
198
+ outMap = new Map();
199
+ domainGraph.set(dep.source_domain, outMap);
200
+ }
201
+ if (!outMap.has(targetDomain)) {
202
+ outMap.set(targetDomain, {
203
+ files: new Set([dep.source_file]),
204
+ file: dep.source_file,
205
+ line: dep.line_number,
206
+ source_domain: dep.source_domain,
207
+ target_domain: targetDomain,
208
+ target: dep.target,
209
+ });
210
+ }
211
+ outMap.get(targetDomain)!.files.add(dep.source_file);
212
+ }
213
+
214
+ // 2. File-to-file edge
215
+ const targetFile = resolveTargetFile(dep.source_file, dep.target);
216
+ if (targetFile && targetFile !== dep.source_file) {
217
+ let outMap = fileGraph.get(dep.source_file);
218
+ if (!outMap) {
219
+ outMap = new Map();
220
+ fileGraph.set(dep.source_file, outMap);
221
+ }
222
+ if (!outMap.has(targetFile)) {
223
+ outMap.set(targetFile, {
224
+ files: new Set([dep.source_file]),
225
+ file: dep.source_file,
226
+ line: dep.line_number,
227
+ source_domain: dep.source_domain,
228
+ target_domain: targetDomain ?? dep.source_domain,
229
+ target: dep.target,
230
+ });
231
+ }
232
+ }
233
+ }
234
+
235
+ const findCycles = (
236
+ graph: Map<string, Map<string, EdgeMeta>>,
237
+ kindLabel: "file" | "domain"
238
+ ) => {
239
+ const visited = new Set<string>();
240
+ const inStack = new Set<string>();
241
+ const stack: string[] = [];
242
+ const reportedCycles = new Set<string>();
243
+
244
+ const canonicalizeCycle = (nodes: string[]): string => {
245
+ if (nodes.length === 0) return "";
246
+ let minIdx = 0;
247
+ for (let i = 1; i < nodes.length; i++) {
248
+ if (nodes[i] < nodes[minIdx]) minIdx = i;
249
+ }
250
+ const rotated = [...nodes.slice(minIdx), ...nodes.slice(0, minIdx)];
251
+ return rotated.join("->");
252
+ };
253
+
254
+ const dfs = (node: string) => {
255
+ visited.add(node);
256
+ inStack.add(node);
257
+ stack.push(node);
258
+
259
+ const neighbors = graph.get(node);
260
+ if (neighbors) {
261
+ for (const [nextNode, edgeMeta] of neighbors.entries()) {
262
+ if (!visited.has(nextNode)) {
263
+ dfs(nextNode);
264
+ } else if (inStack.has(nextNode)) {
265
+ const cycleStartIndex = stack.indexOf(nextNode);
266
+ if (cycleStartIndex !== -1) {
267
+ const cycleNodes = stack.slice(cycleStartIndex);
268
+ const sig = canonicalizeCycle(cycleNodes);
269
+ const cycleEdges = cycleNodes.map((source, index) => graph.get(source)?.get(cycleNodes[(index + 1) % cycleNodes.length]));
270
+ if (relevantFiles && !cycleEdges.some(edge => edge && [...edge.files].some(file => relevantFiles.has(file)))) continue;
271
+ if (!reportedCycles.has(sig)) {
272
+ reportedCycles.add(sig);
273
+ const firstNode = cycleNodes[0];
274
+ const secondNode = cycleNodes[1] ?? nextNode;
275
+ const firstEdge = graph.get(firstNode)?.get(secondNode) ?? edgeMeta;
276
+ const cycleDisplay = [...cycleNodes, cycleNodes[0]].join(" -> ");
277
+ violations.push({
278
+ file: firstEdge.file,
279
+ line: firstEdge.line,
280
+ source_domain: firstEdge.source_domain,
281
+ target_domain: firstEdge.target_domain,
282
+ imported_target: firstEdge.target,
283
+ rule: "circular_dependency",
284
+ message: `Circular ${kindLabel} dependency detected: ${cycleDisplay}.`,
285
+ });
286
+ }
287
+ }
288
+ }
289
+ }
290
+ }
291
+
292
+ stack.pop();
293
+ inStack.delete(node);
294
+ };
295
+
296
+ for (const startNode of graph.keys()) {
297
+ if (!visited.has(startNode)) {
298
+ dfs(startNode);
299
+ }
300
+ }
301
+ };
302
+
303
+ findCycles(fileGraph, "file");
304
+ findCycles(domainGraph, "domain");
305
+
306
+ return violations;
307
+ }
308
+
309
+ public checkProposedChanges(
310
+ sourceFilePath: string,
311
+ proposedImports: string[],
312
+ config: ValidatedSeptumConfig
313
+ ): BoundaryViolation[] {
314
+ const violations: BoundaryViolation[] = [];
315
+ const sourceDomain = this.resolveSourceDomain(sourceFilePath, config);
316
+
317
+ if (!sourceDomain) {
318
+ violations.push({
319
+ file: sourceFilePath,
320
+ line: 1,
321
+ source_domain: "unmapped",
322
+ target_domain: "unknown",
323
+ imported_target: "",
324
+ rule: "unmapped_domain",
325
+ message: `File '${sourceFilePath}' does not belong to any declared bounded context. Boundary integrity cannot be enforced.`,
326
+ });
327
+ return violations;
328
+ }
329
+
330
+ const sourceDomainConfig = config.domains[sourceDomain];
331
+ if (!sourceDomainConfig) {
332
+ return violations;
333
+ }
334
+
335
+ const forbidden = sourceDomainConfig.forbidden_dependencies ?? [];
336
+ const allowed = sourceDomainConfig.allowed_dependencies ?? [];
337
+
338
+ for (const statement of proposedImports) {
339
+ const targetDomain = this.resolveTargetDomain(statement, config, sourceFilePath);
340
+ if (!targetDomain || targetDomain === sourceDomain) {
341
+ continue;
342
+ }
343
+
344
+ if (forbidden.includes(targetDomain)) {
345
+ violations.push({
346
+ file: sourceFilePath,
347
+ line: 1,
348
+ source_domain: sourceDomain,
349
+ target_domain: targetDomain,
350
+ imported_target: statement,
351
+ rule: "forbidden_dependency",
352
+ message: `Illegal import blocked: Domain '${sourceDomain}' is strictly forbidden from importing domain '${targetDomain}'.`,
353
+ });
354
+ } else if (config.settings.enforcement === "strict" && !allowed.includes(targetDomain)) {
355
+ violations.push({
356
+ file: sourceFilePath,
357
+ line: 1,
358
+ source_domain: sourceDomain,
359
+ target_domain: targetDomain,
360
+ imported_target: statement,
361
+ rule: "disallowed_dependency",
362
+ message: `Unlisted domain dependency: '${targetDomain}' must be explicitly added to allowed_dependencies before domain '${sourceDomain}' can import it.`,
363
+ });
364
+ }
365
+ }
366
+
367
+ return violations;
368
+ }
369
+
370
+ public resolveSourceDomain(filePath: string, config: ValidatedSeptumConfig): string | null {
371
+ return this.resolver.resolveSourceDomain(filePath, config);
372
+ }
373
+
374
+ public resolveTargetDomain(
375
+ targetStatement: string,
376
+ config: ValidatedSeptumConfig,
377
+ sourceFilePath?: string
378
+ ): string | null {
379
+ return this.resolver.resolveTargetDomain(targetStatement, sourceFilePath, config);
380
+ }
381
+
382
+ public checkFeatureTouchpoints(
383
+ featureKey: string,
384
+ targetFilePath: string,
385
+ config: ValidatedSeptumConfig
386
+ ): BoundaryViolation[] {
387
+ const violations: BoundaryViolation[] = [];
388
+ const features = config.features ?? {};
389
+ const featureConfig = features[featureKey];
390
+
391
+ if (!featureConfig) {
392
+ violations.push({
393
+ file: targetFilePath,
394
+ line: 1,
395
+ source_domain: "unknown",
396
+ target_domain: "unknown",
397
+ imported_target: targetFilePath,
398
+ rule: "unknown_feature",
399
+ message: `Feature '${featureKey}' is not defined in septum configuration.`,
400
+ });
401
+ return violations;
402
+ }
403
+
404
+ const root = this.resolver.getProjectRoot();
405
+ const normalizedTarget = relative(root, resolve(root, targetFilePath.replace(/\\/g, "/"))).replace(/\\/g, "/");
406
+ const allowedTouchpoints = featureConfig.allowed_touchpoints.map((tp) =>
407
+ isAbsolute(tp) ? relative(root, tp).replace(/\\/g, "/") : posix.normalize(tp.replace(/\\/g, "/"))
408
+ );
409
+
410
+ const domainCfg = config.domains[featureConfig.domain];
411
+ const domainRoot = domainCfg?.root ? domainCfg.root.replace(/\\/g, "/").replace(/^\.\//, "") : "";
412
+
413
+ const matches = (pattern: string): boolean => {
414
+ if (normalizedTarget === pattern) return true;
415
+ if (pattern.endsWith("/**")) {
416
+ return normalizedTarget.startsWith(pattern.slice(0, -3) + "/");
417
+ }
418
+ if (pattern.endsWith("/*")) {
419
+ const prefix = pattern.slice(0, -2) + "/";
420
+ return normalizedTarget.startsWith(prefix) && !normalizedTarget.slice(prefix.length).includes("/");
421
+ }
422
+ return matchesSimpleGlob(normalizedTarget, pattern, false);
423
+ };
424
+ const isAllowed = allowedTouchpoints.some(pattern =>
425
+ matches(pattern) || Boolean(domainRoot && matches(posix.normalize(`${domainRoot}/${pattern}`)))
426
+ );
427
+
428
+ if (!isAllowed) {
429
+ violations.push({
430
+ file: targetFilePath,
431
+ line: 1,
432
+ source_domain: featureConfig.domain,
433
+ target_domain: "unknown",
434
+ imported_target: targetFilePath,
435
+ rule: "touchpoint_violation",
436
+ message: `Scope violation: File '${targetFilePath}' is outside the declared allowed_touchpoints for feature '${featureKey}'. Permitted: [${allowedTouchpoints.join(", ")}].`,
437
+ });
438
+ }
439
+
440
+ return violations;
441
+ }
442
+ }
@@ -0,0 +1,58 @@
1
+ import { RESOURCE_LIMITS } from "../resources/limits.ts";
2
+ import { execFileSync } from "node:child_process";
3
+ import { resolve, relative, sep } from "node:path";
4
+ import type { ImportResolution, BoundaryViolation } from "../../types/index.ts";
5
+ import type { ValidatedSeptumConfig } from "../config/schema.ts";
6
+ import { ASTParserEngine } from "../parser/tree-sitter.ts";
7
+ import type { SeptumRepository } from "../database/repository.ts";
8
+ import type { BoundaryEvaluator } from "./evaluator.ts";
9
+
10
+ export async function auditStagedFiles(
11
+ evaluator: BoundaryEvaluator,
12
+ config: ValidatedSeptumConfig,
13
+ workspaceRoot: string,
14
+ featureKey?: string,
15
+ repo?: SeptumRepository
16
+ ): Promise<{ files: string[]; violations: BoundaryViolation[]; resolution_issues: ImportResolution[] }> {
17
+ const gitRoot = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: workspaceRoot, encoding: "utf8" }).trim();
18
+ const rawPrefix = relative(gitRoot, workspaceRoot).replace(/\\/g, "/");
19
+ const prefix = rawPrefix === "." ? "" : rawPrefix;
20
+ const inside = (file: string) => !prefix || file === prefix || file.startsWith(prefix + "/");
21
+ const stagedPaths = (filter: string) => execFileSync("git", ["diff", "--cached", "--name-only", `--diff-filter=${filter}`, "-z"], {
22
+ cwd: gitRoot, encoding: "utf-8", timeout: 5000, maxBuffer: 10 * 1024 * 1024,
23
+ }).split("\0").filter(Boolean).map(f => f.replace(/\\/g, "/")).filter(inside);
24
+ const files = stagedPaths("ACMR").map(file => (prefix ? relative(prefix, file) : file).replace(/\\/g, "/"));
25
+ const deleted = stagedPaths("D").map(file => (prefix ? relative(prefix, file) : file).replace(/\\/g, "/"));
26
+ const violations: BoundaryViolation[] = [];
27
+ const resolutionIssues: ImportResolution[] = [];
28
+ if (featureKey) for (const file of deleted) violations.push(...evaluator.checkFeatureTouchpoints(featureKey, file, config));
29
+ const stagedDependencies: ReturnType<SeptumRepository["getAllDependenciesWithDomains"]> = [];
30
+ const parser = new ASTParserEngine();
31
+ for (const file of files) {
32
+ if (featureKey) violations.push(...evaluator.checkFeatureTouchpoints(featureKey, file, config));
33
+ if (!ASTParserEngine.isSourceFile(file) || !evaluator.resolveSourceDomain(file, config)) continue;
34
+ const gitFile = prefix ? `${prefix}/${file}` : file;
35
+ const size = Number(execFileSync("git", ["cat-file", "-s", `:${gitFile}`], {cwd:gitRoot,encoding:"utf8",timeout:5000,maxBuffer:1024}));
36
+ if (!Number.isFinite(size) || size > RESOURCE_LIMITS.sourceBytes) throw new Error(`Staged source exceeds resource limit: '${file}'.`);
37
+ const content = execFileSync("git", ["show", `:${gitFile}`], {
38
+ cwd: gitRoot, encoding: "utf-8", timeout: 5000, maxBuffer: RESOURCE_LIMITS.sourceBytes + 1,
39
+ });
40
+ const parsed = await parser.parseFile(resolve(workspaceRoot, file), content);
41
+ if (parsed.status === "unsupported" || parsed.status === "degraded") {
42
+ throw new Error(`Cannot reliably parse staged file '${file}': ${parsed.status}.`);
43
+ }
44
+ for (const dependency of parsed.dependencies) {
45
+ stagedDependencies.push({ source_file: file, source_domain: evaluator.resolveSourceDomain(file, config)!, target: dependency.target, statement: dependency.statement, line_number: dependency.line_number, is_external: dependency.is_external });
46
+ const found = evaluator.checkProposedChanges(file, [dependency.target], config).map(violation => ({ ...violation, line: dependency.line_number }));
47
+ const resolution = evaluator.getResolver().resolveImport(dependency.target,file);
48
+ if (found.length === 0 && (!["resolved","external"].includes(resolution.status) || resolution.coverage === "conditional")) {
49
+ resolutionIssues.push(resolution);
50
+ }
51
+ violations.push(...found);
52
+ }
53
+ }
54
+ const staged = new Set([...files, ...deleted]);
55
+ const baseline = (repo?.getAllDependenciesWithDomains() || []).filter(dependency => !staged.has(dependency.source_file));
56
+ violations.push(...evaluator.detectCircularDependencies(config, [...baseline, ...stagedDependencies], staged));
57
+ return { files: Array.from(staged), violations, resolution_issues: resolutionIssues };
58
+ }
@@ -0,0 +1,122 @@
1
+ import { existsSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { Database } from "bun:sqlite";
4
+ import type { ValidatedSeptumConfig } from "./schema.ts";
5
+ import { TopologyDetector } from "../discovery/topology-detector.ts";
6
+ import { SeptumDatabase } from "../database/client.ts";
7
+ import { SeptumRepository } from "../database/repository.ts";
8
+ import { resolveWorkspaceRoot, isAppHostDirectory } from "../resolver/path-resolver.ts";
9
+
10
+ export class ConfigLoader {
11
+ /**
12
+ * Loads configuration with SQLite as the Single Source of Truth (SSOT).
13
+ * Automatically executes Zero-Config TopologyDetector if the database has no domains.
14
+ */
15
+ public static load(
16
+ dbPath?: string,
17
+ projectRoot?: string
18
+ ): ValidatedSeptumConfig {
19
+ const root = resolveWorkspaceRoot(projectRoot);
20
+ const resolvedDbPath = dbPath
21
+ ? (isAbsolute(dbPath) ? dbPath : join(root, dbPath))
22
+ : join(root, ".septum", "septum.db");
23
+
24
+ // 1. If database exists and has registered domains, load directly from SQLite SSOT
25
+ if (existsSync(resolvedDbPath)) {
26
+ const dbConfig = ConfigLoader.loadFromDatabaseOrDefaults(resolvedDbPath);
27
+ if (Object.keys(dbConfig.domains).length > 0) {
28
+ return dbConfig;
29
+ }
30
+ }
31
+
32
+ // 2. Zero-Config Auto-Discovery: Discover project topology and persist to SQLite
33
+ // Guard against running auto-discovery inside MCP host / IDE installation folders
34
+ if (!isAppHostDirectory(root)) {
35
+ const septumDb = new SeptumDatabase(resolvedDbPath);
36
+ const repo = new SeptumRepository(septumDb.raw);
37
+ TopologyDetector.discoverAndPersist(repo, root);
38
+ septumDb.close();
39
+ }
40
+
41
+ return ConfigLoader.loadFromDatabaseOrDefaults(resolvedDbPath);
42
+ }
43
+
44
+ public static getDefaultConfig(): ValidatedSeptumConfig {
45
+ return {
46
+ version: "1.0",
47
+ settings: {
48
+ enforcement: "warn",
49
+ db_path: ".septum/septum.db",
50
+ ignore_patterns: [
51
+ "node_modules/**",
52
+ "vendor/**",
53
+ "dist/**",
54
+ "build/**",
55
+ "out/**",
56
+ "target/**",
57
+ "coverage/**",
58
+ ".venv/**",
59
+ "venv/**",
60
+ "__pycache__/**",
61
+ "tests/**",
62
+ "scripts/**",
63
+ "bin/**",
64
+ ".git/**",
65
+ ".septum/**",
66
+ ],
67
+ },
68
+ domains: {},
69
+ features: {},
70
+ };
71
+ }
72
+
73
+ public static loadFromRepository(repo: SeptumRepository): ValidatedSeptumConfig {
74
+ const config = ConfigLoader.getDefaultConfig();
75
+ if (repo && typeof repo.getAllDomains === "function") {
76
+ const rows = repo.getAllDomains();
77
+ for (const row of rows) {
78
+ config.domains[row.name] = {
79
+ root: row.root_path,
80
+ allowed_dependencies: JSON.parse(row.allowed_deps_json || "[]"),
81
+ forbidden_dependencies: JSON.parse(row.forbidden_deps_json || "[]"),
82
+ archetypes: JSON.parse(row.archetypes_json || "{}"),
83
+ };
84
+ }
85
+ }
86
+
87
+ if (typeof repo?.getMeta === "function") {
88
+ const features = repo.getMeta("features_json");
89
+ if (features) config.features = JSON.parse(features);
90
+ const settings = repo.getMeta("settings_json");
91
+ if (settings) Object.assign(config.settings, JSON.parse(settings));
92
+ }
93
+ return config;
94
+ }
95
+
96
+ public static loadFromDatabaseOrDefaults(dbPath: string = ".septum/septum.db"): ValidatedSeptumConfig {
97
+ const config = ConfigLoader.getDefaultConfig();
98
+ config.settings.db_path = dbPath;
99
+
100
+ if (existsSync(dbPath)) {
101
+ try {
102
+ const db = new Database(dbPath, { readonly: true });
103
+ const tables = db
104
+ .query<{ name: string }, [string]>(
105
+ "SELECT name FROM sqlite_master WHERE type='table' AND name = ?"
106
+ )
107
+ .get("domains");
108
+
109
+ try {
110
+ if (tables) Object.assign(config, ConfigLoader.loadFromRepository(new SeptumRepository(db)));
111
+ config.settings.db_path = dbPath;
112
+ } finally {
113
+ db.close();
114
+ }
115
+ } catch {
116
+ throw new Error(`Cannot load Septum configuration from '${dbPath}'.`);
117
+ }
118
+ }
119
+
120
+ return config;
121
+ }
122
+ }
@@ -0,0 +1,69 @@
1
+ import { z } from "zod";
2
+
3
+ export const DomainConfigSchema = z.object({
4
+ root: z.string().min(1, "root path cannot be empty"),
5
+ description: z.string().optional(),
6
+ allowed_dependencies: z.array(z.string()).default([]),
7
+ forbidden_dependencies: z.array(z.string()).default([]),
8
+ archetypes: z.record(z.string()).optional().default({}),
9
+ });
10
+
11
+ export const FeatureConfigSchema = z.object({
12
+ domain: z.string().min(1, "domain reference is required"),
13
+ description: z.string().optional(),
14
+ allowed_touchpoints: z.array(z.string()).min(1, "allowed_touchpoints must contain at least one file/path"),
15
+ reuse_symbols: z.array(z.string()).optional().default([]),
16
+ input_contract: z.record(z.unknown()).optional().default({}),
17
+ output_contract: z.record(z.unknown()).optional().default({}),
18
+ });
19
+
20
+ export const SeptumConfigSchema = z.object({
21
+ version: z.string().default("1.0"),
22
+ settings: z
23
+ .object({
24
+ enforcement: z.enum(["strict", "warn"]).default("strict"),
25
+ db_path: z.string().default(".septum/septum.db"),
26
+ ignore_patterns: z
27
+ .array(z.string())
28
+ .default([
29
+ "node_modules/**",
30
+ "vendor/**",
31
+ "dist/**",
32
+ "build/**",
33
+ "out/**",
34
+ "target/**",
35
+ "coverage/**",
36
+ ".venv/**",
37
+ "venv/**",
38
+ "__pycache__/**",
39
+ "tests/**",
40
+ "scripts/**",
41
+ "bin/**",
42
+ ".git/**",
43
+ ]),
44
+ })
45
+ .default({
46
+ enforcement: "strict",
47
+ db_path: ".septum/septum.db",
48
+ ignore_patterns: [
49
+ "node_modules/**",
50
+ "vendor/**",
51
+ "dist/**",
52
+ "build/**",
53
+ "out/**",
54
+ "target/**",
55
+ "coverage/**",
56
+ ".venv/**",
57
+ "venv/**",
58
+ "__pycache__/**",
59
+ "tests/**",
60
+ "scripts/**",
61
+ "bin/**",
62
+ ".git/**",
63
+ ],
64
+ }),
65
+ domains: z.record(DomainConfigSchema).default({}),
66
+ features: z.record(FeatureConfigSchema).optional().default({}),
67
+ });
68
+
69
+ export type ValidatedSeptumConfig = z.infer<typeof SeptumConfigSchema>;