@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,426 @@
1
+ import { posix, relative, resolve, isAbsolute } from "node:path";
2
+ import { existsSync } from "node:fs";
3
+ import type { BoundaryViolation } from "../../types/index.ts";
4
+ import type { ValidatedSeptumConfig } from "../config/schema.ts";
5
+ import { ConfigLoader } from "../config/loader.ts";
6
+ import type { SeptumRepository } from "../database/repository.ts";
7
+ import { ModuleResolver } from "../resolver/module-resolver.ts";
8
+ import { matchesSimpleGlob } from "../parser/extractors/base.ts";
9
+ import { assertUniqueDomainRoots } from "../config/domain-ownership.ts";
10
+
11
+ export class BoundaryEvaluator {
12
+ private repo: SeptumRepository;
13
+ private resolver: ModuleResolver;
14
+
15
+ constructor(repo: SeptumRepository, resolver?: ModuleResolver) {
16
+ this.repo = repo;
17
+ this.resolver = resolver ?? new ModuleResolver(process.cwd(), repo);
18
+ }
19
+
20
+ public getResolver(): ModuleResolver {
21
+ return this.resolver;
22
+ }
23
+
24
+ public withResolver(resolver: ModuleResolver): BoundaryEvaluator {
25
+ return new BoundaryEvaluator(this.repo, resolver);
26
+ }
27
+
28
+ public evaluate(
29
+ filePath: string,
30
+ proposedImports: string[] = [],
31
+ config?: ValidatedSeptumConfig
32
+ ): BoundaryViolation[] {
33
+ let activeConfig = config;
34
+ if (!activeConfig) {
35
+ const fromRepo = ConfigLoader.loadFromRepository(this.repo);
36
+ activeConfig =
37
+ Object.keys(fromRepo.domains).length > 0
38
+ ? fromRepo
39
+ : ConfigLoader.loadFromDatabaseOrDefaults();
40
+ }
41
+ assertUniqueDomainRoots(activeConfig.domains, this.resolver.getProjectRoot());
42
+ const violations: BoundaryViolation[] = [];
43
+
44
+ if (proposedImports.length > 0) {
45
+ violations.push(...this.checkProposedChanges(filePath, proposedImports, activeConfig));
46
+ const sourceDomain = this.resolveSourceDomain(filePath, activeConfig);
47
+ if (sourceDomain && typeof this.repo.getAllDependenciesWithDomains === "function") {
48
+ const existingDeps = this.repo.getAllDependenciesWithDomains().filter(
49
+ (dep) => dep.source_file !== filePath
50
+ );
51
+ const proposedDeps = proposedImports.map((statement) => ({
52
+ source_file: filePath,
53
+ source_domain: sourceDomain,
54
+ line_number: 1,
55
+ target: statement,
56
+ statement,
57
+ is_external: false,
58
+ }));
59
+ violations.push(
60
+ ...this.detectCircularDependencies(
61
+ activeConfig,
62
+ [...existingDeps, ...proposedDeps],
63
+ new Set([filePath])
64
+ )
65
+ );
66
+ }
67
+ }
68
+
69
+ return violations;
70
+ }
71
+
72
+ public auditCodebase(config: ValidatedSeptumConfig): BoundaryViolation[] {
73
+ assertUniqueDomainRoots(config.domains, this.resolver.getProjectRoot());
74
+ const violations: BoundaryViolation[] = [];
75
+ const allDependencies = this.repo.getAllDependenciesWithDomains();
76
+
77
+ const evidence = this.repo.getMeta?.("workspace_root") ? this.repo.getImportRelationships(this.resolver.getProjectRoot()) : undefined;
78
+ const key = (file: string, line: number, target: string) => JSON.stringify([file, line, target]);
79
+ const current = new Set(evidence?.filter(edge => edge.freshness === "current").map(edge => key(edge.source.file, edge.source.line, edge.resolution.source.target)));
80
+ const resolved = new Set(evidence?.filter(edge => edge.freshness === "current" && edge.resolution.status === "resolved" && edge.resolution.coverage !== "conditional").map(edge => key(edge.source.file, edge.source.line, edge.resolution.source.target)));
81
+ for (const dep of allDependencies) {
82
+ if (evidence && !resolved.has(key(dep.source_file, dep.line_number, dep.target))) continue;
83
+ const targetDomain = this.resolveTargetDomain(dep.target, config, dep.source_file, dep.statement);
84
+ if (!targetDomain || targetDomain === dep.source_domain) {
85
+ continue;
86
+ }
87
+
88
+ const sourceDomainConfig = config.domains[dep.source_domain];
89
+ if (!sourceDomainConfig) {
90
+ continue;
91
+ }
92
+
93
+ const forbidden = sourceDomainConfig.forbidden_dependencies ?? [];
94
+ const allowed = sourceDomainConfig.allowed_dependencies ?? [];
95
+
96
+ // 1. Explicit forbidden check
97
+ if (forbidden.includes(targetDomain)) {
98
+ violations.push({
99
+ file: dep.source_file,
100
+ line: dep.line_number,
101
+ source_domain: dep.source_domain,
102
+ target_domain: targetDomain,
103
+ imported_target: dep.target,
104
+ rule: "forbidden_dependency",
105
+ message: `Forbidden cross-domain dependency detected: '${dep.source_domain}' is strictly prohibited from importing domain '${targetDomain}'.`,
106
+ });
107
+ continue;
108
+ }
109
+
110
+ // 2. Strict enforcement allowed check
111
+ if (config.settings.enforcement === "strict" && !allowed.includes(targetDomain)) {
112
+ violations.push({
113
+ file: dep.source_file,
114
+ line: dep.line_number,
115
+ source_domain: dep.source_domain,
116
+ target_domain: targetDomain,
117
+ imported_target: dep.target,
118
+ rule: "disallowed_dependency",
119
+ message: `Disallowed dependency: '${targetDomain}' is not declared in allowed_dependencies for domain '${dep.source_domain}'.`,
120
+ });
121
+ }
122
+ }
123
+
124
+ const currentDependencies = evidence ? allDependencies.filter(dep => current.has(key(dep.source_file, dep.line_number, dep.target))) : allDependencies;
125
+ violations.push(...this.detectCircularDependencies(config, currentDependencies));
126
+
127
+ return violations;
128
+ }
129
+
130
+ public detectCircularDependencies(
131
+ config: ValidatedSeptumConfig,
132
+ preloadedDeps?: Array<{
133
+ source_file: string;
134
+ source_domain: string;
135
+ line_number: number;
136
+ target: string;
137
+ statement: string;
138
+ is_external: boolean;
139
+ }>,
140
+ relevantFiles?: ReadonlySet<string>
141
+ ): BoundaryViolation[] {
142
+ assertUniqueDomainRoots(config.domains, this.resolver.getProjectRoot());
143
+ const violations: BoundaryViolation[] = [];
144
+ let allDependencies = preloadedDeps ?? this.repo.getAllDependenciesWithDomains();
145
+ if (!preloadedDeps && this.repo.getMeta?.("workspace_root")) {
146
+ const current = this.repo.getImportRelationships(this.resolver.getProjectRoot());
147
+ allDependencies = allDependencies.filter(dep => current.some(edge => edge.source.file === dep.source_file && edge.source.line === dep.line_number && edge.freshness === "current"));
148
+ }
149
+
150
+ // Prepare file lookup maps for internal file-to-file resolution
151
+ const fileByNormPath = new Map<string, string>();
152
+ const fileByNoExtPath = new Map<string, string>();
153
+
154
+ const registerKnownFile = (rawPath: string) => {
155
+ const norm = rawPath.replace(/\\/g, "/").replace(/^\.\//, "");
156
+ fileByNormPath.set(norm.toLowerCase(), rawPath);
157
+ const noExt = norm.replace(/\.[^/.]+$/, "").toLowerCase();
158
+ fileByNoExtPath.set(noExt, rawPath);
159
+ if (noExt.endsWith("/index")) {
160
+ fileByNoExtPath.set(noExt.slice(0, -"/index".length), rawPath);
161
+ }
162
+ };
163
+
164
+ if (typeof this.repo.getAllFiles === "function") {
165
+ for (const f of this.repo.getAllFiles()) {
166
+ registerKnownFile(f.path);
167
+ }
168
+ }
169
+ for (const d of allDependencies) {
170
+ registerKnownFile(d.source_file);
171
+ }
172
+
173
+ const resolveTargetFile = (sourceFile: string, rawTarget: string, statement?: string): string | null => {
174
+ if (this.repo.getMeta?.("workspace_root") || existsSync(resolve(this.resolver.getProjectRoot(), sourceFile))) {
175
+ const result = this.resolver.resolveImport(rawTarget,sourceFile,statement);
176
+ const files = result.targets.flatMap(target => target.files);
177
+ return result.status === "resolved" && result.coverage !== "conditional" && files.length === 1 ? files[0]! : null;
178
+ }
179
+ const cleaned = rawTarget.trim().replace(/^['"]|['"]$/g, "").replace(/\\/g, "/");
180
+ if (!cleaned) return null;
181
+
182
+ if (cleaned.startsWith(".")) {
183
+ const srcDir = posix.dirname(sourceFile.replace(/\\/g, "/"));
184
+ const joined = posix.normalize(posix.join(srcDir, cleaned)).replace(/^\.\//, "");
185
+ const lowerJoined = joined.toLowerCase();
186
+ const exact =
187
+ fileByNormPath.get(lowerJoined) ??
188
+ fileByNoExtPath.get(lowerJoined.replace(/\.[^/.]+$/, ""));
189
+ if (exact) return exact;
190
+ }
191
+
192
+ const aliasClean = cleaned.replace(/^@\//, "src/").replace(/^\.\//, "");
193
+ const lowerAlias = aliasClean.toLowerCase();
194
+ const byAlias =
195
+ fileByNormPath.get(lowerAlias) ??
196
+ fileByNoExtPath.get(lowerAlias.replace(/\.[^/.]+$/, ""));
197
+ if (byAlias) return byAlias;
198
+
199
+ return null;
200
+ };
201
+
202
+ type EdgeMeta = {
203
+ files: Set<string>;
204
+ file: string;
205
+ line: number;
206
+ source_domain: string;
207
+ target_domain: string;
208
+ target: string;
209
+ };
210
+
211
+ const fileGraph = new Map<string, Map<string, EdgeMeta>>();
212
+ const domainGraph = new Map<string, Map<string, EdgeMeta>>();
213
+
214
+ const isTypeOnlyImport = (statement?: string): boolean => {
215
+ if (!statement) return false;
216
+ return /^\s*(?:import|export)\s+type\b/.test(statement.trim());
217
+ };
218
+
219
+ for (const dep of allDependencies) {
220
+ if (this.repo.getMeta?.("workspace_root")) {
221
+ const result = this.resolver.resolveImport(dep.target,dep.source_file,dep.statement);
222
+ if (result.status !== "resolved" || result.coverage === "conditional") continue;
223
+ } else if (dep.is_external) continue;
224
+
225
+ const targetDomain = this.resolveTargetDomain(dep.target, config, dep.source_file, dep.statement);
226
+
227
+ // 1. Domain-to-domain edge (exclude virtual/top-level aggregator "root" domain and type-only imports)
228
+ if (
229
+ targetDomain &&
230
+ targetDomain !== dep.source_domain &&
231
+ dep.source_domain !== "root" &&
232
+ targetDomain !== "root" &&
233
+ !isTypeOnlyImport(dep.statement)
234
+ ) {
235
+ let outMap = domainGraph.get(dep.source_domain);
236
+ if (!outMap) {
237
+ outMap = new Map();
238
+ domainGraph.set(dep.source_domain, outMap);
239
+ }
240
+ if (!outMap.has(targetDomain)) {
241
+ outMap.set(targetDomain, {
242
+ files: new Set([dep.source_file]),
243
+ file: dep.source_file,
244
+ line: dep.line_number,
245
+ source_domain: dep.source_domain,
246
+ target_domain: targetDomain,
247
+ target: dep.target,
248
+ });
249
+ }
250
+ outMap.get(targetDomain)!.files.add(dep.source_file);
251
+ }
252
+
253
+ // 2. File-to-file edge (type-only imports are erased at compile time and do not create runtime cycles)
254
+ if (isTypeOnlyImport(dep.statement)) {
255
+ continue;
256
+ }
257
+
258
+ const targetFile = resolveTargetFile(dep.source_file, dep.target, dep.statement);
259
+ if (targetFile && targetFile !== dep.source_file) {
260
+ let outMap = fileGraph.get(dep.source_file);
261
+ if (!outMap) {
262
+ outMap = new Map();
263
+ fileGraph.set(dep.source_file, outMap);
264
+ }
265
+ if (!outMap.has(targetFile)) {
266
+ outMap.set(targetFile, {
267
+ files: new Set([dep.source_file]),
268
+ file: dep.source_file,
269
+ line: dep.line_number,
270
+ source_domain: dep.source_domain,
271
+ target_domain: targetDomain ?? dep.source_domain,
272
+ target: dep.target,
273
+ });
274
+ }
275
+ }
276
+ }
277
+
278
+ const findCycles = (
279
+ graph: Map<string, Map<string, EdgeMeta>>,
280
+ kindLabel: "file" | "domain"
281
+ ) => {
282
+ const visited = new Set<string>();
283
+ const inStack = new Set<string>();
284
+ const stack: string[] = [];
285
+ const reportedCycles = new Set<string>();
286
+
287
+ const canonicalizeCycle = (nodes: string[]): string => {
288
+ if (nodes.length === 0) return "";
289
+ let minIdx = 0;
290
+ for (let i = 1; i < nodes.length; i++) {
291
+ if (nodes[i] < nodes[minIdx]) minIdx = i;
292
+ }
293
+ const rotated = [...nodes.slice(minIdx), ...nodes.slice(0, minIdx)];
294
+ return rotated.join("->");
295
+ };
296
+
297
+ const dfs = (node: string) => {
298
+ visited.add(node);
299
+ inStack.add(node);
300
+ stack.push(node);
301
+
302
+ const neighbors = graph.get(node);
303
+ if (neighbors) {
304
+ for (const [nextNode, edgeMeta] of neighbors.entries()) {
305
+ if (!visited.has(nextNode)) {
306
+ dfs(nextNode);
307
+ } else if (inStack.has(nextNode)) {
308
+ const cycleStartIndex = stack.indexOf(nextNode);
309
+ if (cycleStartIndex !== -1) {
310
+ const cycleNodes = stack.slice(cycleStartIndex);
311
+ const sig = canonicalizeCycle(cycleNodes);
312
+ const cycleEdges = cycleNodes.map((source, index) => graph.get(source)?.get(cycleNodes[(index + 1) % cycleNodes.length]));
313
+ if (relevantFiles && !cycleEdges.some(edge => edge && [...edge.files].some(file => relevantFiles.has(file)))) continue;
314
+ if (!reportedCycles.has(sig)) {
315
+ reportedCycles.add(sig);
316
+ const firstNode = cycleNodes[0];
317
+ const secondNode = cycleNodes[1] ?? nextNode;
318
+ const firstEdge = graph.get(firstNode)?.get(secondNode) ?? edgeMeta;
319
+ const cycleDisplay = [...cycleNodes, cycleNodes[0]].join(" -> ");
320
+ violations.push({
321
+ file: firstEdge.file,
322
+ line: firstEdge.line,
323
+ source_domain: firstEdge.source_domain,
324
+ target_domain: firstEdge.target_domain,
325
+ imported_target: firstEdge.target,
326
+ rule: "circular_dependency",
327
+ message: `Circular ${kindLabel} dependency detected: ${cycleDisplay}.`,
328
+ });
329
+ }
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ stack.pop();
336
+ inStack.delete(node);
337
+ };
338
+
339
+ for (const startNode of graph.keys()) {
340
+ if (!visited.has(startNode)) {
341
+ dfs(startNode);
342
+ }
343
+ }
344
+ };
345
+
346
+ findCycles(fileGraph, "file");
347
+ findCycles(domainGraph, "domain");
348
+
349
+ return violations;
350
+ }
351
+
352
+ public checkProposedChanges(
353
+ sourceFilePath: string,
354
+ proposedImports: string[],
355
+ config: ValidatedSeptumConfig,
356
+ importStatements?: string[]
357
+ ): BoundaryViolation[] {
358
+ const violations: BoundaryViolation[] = [];
359
+ const sourceDomain = this.resolveSourceDomain(sourceFilePath, config);
360
+
361
+ if (!sourceDomain) {
362
+ violations.push({
363
+ file: sourceFilePath,
364
+ line: 1,
365
+ source_domain: "unmapped",
366
+ target_domain: "unknown",
367
+ imported_target: "",
368
+ rule: "unmapped_domain",
369
+ message: `File '${sourceFilePath}' does not belong to any declared bounded context. Boundary integrity cannot be enforced.`,
370
+ });
371
+ return violations;
372
+ }
373
+
374
+ const sourceDomainConfig = config.domains[sourceDomain];
375
+ if (!sourceDomainConfig) {
376
+ return violations;
377
+ }
378
+
379
+ const forbidden = sourceDomainConfig.forbidden_dependencies ?? [];
380
+ const allowed = sourceDomainConfig.allowed_dependencies ?? [];
381
+
382
+ for (const [index, statement] of proposedImports.entries()) {
383
+ const targetDomain = this.resolveTargetDomain(statement, config, sourceFilePath, importStatements?.[index]);
384
+ if (!targetDomain || targetDomain === sourceDomain) {
385
+ continue;
386
+ }
387
+
388
+ if (forbidden.includes(targetDomain)) {
389
+ violations.push({
390
+ file: sourceFilePath,
391
+ line: 1,
392
+ source_domain: sourceDomain,
393
+ target_domain: targetDomain,
394
+ imported_target: statement,
395
+ rule: "forbidden_dependency",
396
+ message: `Illegal import blocked: Domain '${sourceDomain}' is strictly forbidden from importing domain '${targetDomain}'.`,
397
+ });
398
+ } else if (config.settings.enforcement === "strict" && !allowed.includes(targetDomain)) {
399
+ violations.push({
400
+ file: sourceFilePath,
401
+ line: 1,
402
+ source_domain: sourceDomain,
403
+ target_domain: targetDomain,
404
+ imported_target: statement,
405
+ rule: "disallowed_dependency",
406
+ message: `Unlisted domain dependency: '${targetDomain}' must be explicitly added to allowed_dependencies before domain '${sourceDomain}' can import it.`,
407
+ });
408
+ }
409
+ }
410
+
411
+ return violations;
412
+ }
413
+
414
+ public resolveSourceDomain(filePath: string, config: ValidatedSeptumConfig): string | null {
415
+ return this.resolver.resolveSourceDomain(filePath, config);
416
+ }
417
+
418
+ public resolveTargetDomain(
419
+ targetStatement: string,
420
+ config: ValidatedSeptumConfig,
421
+ sourceFilePath?: string,
422
+ statement?: string
423
+ ): string | null {
424
+ return this.resolver.resolveTargetDomain(targetStatement, sourceFilePath, config, statement);
425
+ }
426
+ }
@@ -0,0 +1,120 @@
1
+ import { mkdtempSync, mkdirSync, rmSync, openSync, closeSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { ModuleResolver } from "../resolver/module-resolver.ts";
4
+ import type { BoundaryEvaluator } from "./evaluator.ts";
5
+ import { RESOURCE_LIMITS } from "../resources/limits.ts";
6
+ import { execFileSync } from "node:child_process";
7
+ import { resolve, relative, join, dirname } from "node:path";
8
+ import type { ImportResolution, BoundaryViolation } from "../../types/index.ts";
9
+ import type { ValidatedSeptumConfig } from "../config/schema.ts";
10
+ import { ASTParserEngine } from "../parser/tree-sitter.ts";
11
+ import type { SeptumRepository } from "../database/repository.ts";
12
+ import { computeContentHash } from "../ingestion/hasher.ts";
13
+ import { PARSER_FINGERPRINT } from "../parser/language-capabilities.ts";
14
+ import { isResolutionInput } from "../resolver/interpretation-inputs.ts";
15
+
16
+ export async function auditStagedFiles(
17
+ evaluator: BoundaryEvaluator,
18
+ config: ValidatedSeptumConfig,
19
+ workspaceRoot: string,
20
+ repo?: SeptumRepository
21
+ ): Promise<{ files: string[]; violations: BoundaryViolation[]; resolution_issues: ImportResolution[] }> {
22
+ const gitRoot = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: workspaceRoot, encoding: "utf8" }).trim();
23
+ // Freeze the index as a Git tree. Every source/config/target is read from this tree.
24
+ const tree = execFileSync("git", ["write-tree"], { cwd: gitRoot, encoding: "utf8", timeout: 5000 }).trim();
25
+ const scratch = mkdtempSync(join(tmpdir(), "septum-staged-"));
26
+ const snapshot = join(scratch, "tree");
27
+ try {
28
+ mkdirSync(snapshot);
29
+ const entries = execFileSync("git", ["ls-tree", "-r", "-l", "-z", tree], { cwd: gitRoot, encoding: "utf8", maxBuffer: 10 * 1024 * 1024 }).split("\0").filter(Boolean);
30
+ if (entries.length > 20000) throw new Error("Staged view exceeds file-count limit (20000).");
31
+ let totalBytes = 0;
32
+ const indexedPaths: string[] = [];
33
+ const blobs: Array<{ oid: string; file: string; size: number }> = [];
34
+ for (const entry of entries) {
35
+ const match = /^(\d+) blob ([a-f0-9]+)\s+(\d+)\t([\s\S]+)$/.exec(entry);
36
+ if (!match || !["100644", "100755"].includes(match[1]!)) throw new Error("Cannot certify staged view containing symlinks or submodules.");
37
+ const [, , oid, sizeText, file] = match;
38
+ // Only source and interpretation inputs need bytes in the parser snapshot.
39
+ // Keep the complete path inventory so omitted assets cannot masquerade as source.
40
+ indexedPaths.push(file!);
41
+ const needed = ASTParserEngine.isSourceFile(file!) || isResolutionInput(file!);
42
+ if (!needed) continue;
43
+ const size = Number(sizeText);
44
+ totalBytes += size;
45
+ if (size > RESOURCE_LIMITS.sourceBytes || totalBytes > 128 * 1024 * 1024) throw new Error("Staged view exceeds resource limits.");
46
+ const destination = resolve(snapshot, file!);
47
+ if (!destination.startsWith(snapshot + "/")) throw new Error("Invalid staged path.");
48
+ blobs.push({ oid: oid!, file: file!, size });
49
+ }
50
+ // One raw-blob process, spooled to disk to bound JS memory. checkout-index
51
+ // applies smudge/EOL/encoding filters; archive applies export attributes.
52
+ // Neither is a faithful raw index snapshot for parsing and resolution.
53
+ const batchPath = join(scratch, "blobs");
54
+ const fd = openSync(batchPath, "w");
55
+ try {
56
+ execFileSync("git", ["cat-file", "--batch"], { cwd: gitRoot, timeout: 30000,
57
+ input: blobs.map(blob => blob.oid + "\n").join(""), stdio: ["pipe", fd, "pipe"] });
58
+ } finally { closeSync(fd); }
59
+ const batch = Bun.file(batchPath);
60
+ let offset = 0;
61
+ for (const { oid, file, size } of blobs) {
62
+ const header = `${oid} blob ${size}\n`;
63
+ const length = header.length + size + 1;
64
+ const record = Buffer.from(await batch.slice(offset, offset + length).arrayBuffer());
65
+ if (record.length !== length || record.subarray(0, header.length).toString() !== header || record[length - 1] !== 10) {
66
+ throw new Error("Invalid staged blob batch.");
67
+ }
68
+ const destination = resolve(snapshot, file);
69
+ mkdirSync(dirname(destination), { recursive: true });
70
+ writeFileSync(destination, record.subarray(header.length, length - 1));
71
+ offset += length;
72
+ }
73
+ const rawPrefix = relative(gitRoot, workspaceRoot).replace(/\\/g, "/");
74
+ const prefix = rawPrefix === "." ? "" : rawPrefix;
75
+ const inside = (file: string) => !prefix || file === prefix || file.startsWith(prefix + "/");
76
+ const hasHead = (() => { try { execFileSync("git", ["rev-parse", "--verify", "HEAD"], { cwd: gitRoot, stdio: "ignore" }); return true; } catch { return false; } })();
77
+ const emptyTree = execFileSync("git", ["hash-object", "-t", "tree", "--stdin"], { cwd: gitRoot, input: "", encoding: "utf8" }).trim();
78
+ const stagedPaths = (filter: string) => execFileSync("git", ["diff-tree", "--root", "--no-commit-id", "-r", "--name-only", `--diff-filter=${filter}`, "-z", hasHead ? "HEAD" : emptyTree, tree], {
79
+ cwd: gitRoot, encoding: "utf-8", timeout: 5000, maxBuffer: 10 * 1024 * 1024,
80
+ }).split("\0").filter(Boolean).map(f => f.replace(/\\/g, "/")).filter(inside);
81
+ const files = stagedPaths("ACMR").map(file => (prefix ? relative(prefix, file) : file).replace(/\\/g, "/"));
82
+ const deleted = stagedPaths("D").map(file => (prefix ? relative(prefix, file) : file).replace(/\\/g, "/"));
83
+ const snapshotRoot = join(snapshot, prefix);
84
+ evaluator = evaluator.withResolver(new ModuleResolver(snapshotRoot));
85
+ const violations: BoundaryViolation[] = [];
86
+ const resolutionIssues: ImportResolution[] = [];
87
+ const stagedDependencies: ReturnType<SeptumRepository["getAllDependenciesWithDomains"]> = [];
88
+ const parser = new ASTParserEngine();
89
+ const interpretationChanged = [...files, ...deleted].some(isResolutionInput);
90
+ const changed = new Set(files);
91
+ const sourceFiles = indexedPaths.filter(inside).map(file => (prefix ? relative(prefix, file) : file).replace(/\\/g, "/"));
92
+ for (const file of sourceFiles) {
93
+ if (!ASTParserEngine.isSourceFile(file) || !evaluator.resolveSourceDomain(file, config)) continue;
94
+ const content = await Bun.file(resolve(snapshotRoot, file)).text();
95
+ const existing = repo?.getFileByPath(file);
96
+ const reusable = !changed.has(file) && !interpretationChanged &&
97
+ repo?.getMeta("sync_state") === "complete" && repo.getMeta("parser_revision") === PARSER_FINGERPRINT &&
98
+ existing?.content_hash === computeContentHash(content);
99
+ const dependencies = reusable ? repo!.getDependenciesByFileId(existing!.id) : await (async () => {
100
+ const parsed = await parser.parseFile(resolve(snapshotRoot, file), content);
101
+ if (parsed.status === "unsupported" || parsed.status === "degraded") {
102
+ throw new Error(`Cannot reliably parse staged file '${file}': ${parsed.status}.`);
103
+ }
104
+ return parsed.dependencies;
105
+ })();
106
+ for (const dependency of dependencies) {
107
+ 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 });
108
+ const found = evaluator.checkProposedChanges(file, [dependency.target], config, [dependency.statement]).map(violation => ({ ...violation, line: dependency.line_number }));
109
+ const resolution = evaluator.getResolver().resolveImport(dependency.target,file,dependency.statement);
110
+ if (found.length === 0 && (!["resolved","external"].includes(resolution.status) || resolution.coverage === "conditional")) {
111
+ resolutionIssues.push(resolution);
112
+ }
113
+ if (changed.has(file) || interpretationChanged) violations.push(...found);
114
+ }
115
+ }
116
+ const staged = new Set([...files, ...deleted]);
117
+ violations.push(...evaluator.detectCircularDependencies(config, stagedDependencies, interpretationChanged ? new Set(sourceFiles) : staged));
118
+ return { files: Array.from(staged), violations, resolution_issues: resolutionIssues };
119
+ } finally { rmSync(scratch, { recursive: true, force: true }); }
120
+ }
@@ -0,0 +1,45 @@
1
+ import { lstatSync, realpathSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+
4
+ // SQLite's built-in NOCASE/LOWER folds ASCII, not all Unicode case pairs.
5
+ export function domainNameKey(name: string): string {
6
+ return name.replace(/[A-Z]/g, letter => letter.toLowerCase());
7
+ }
8
+
9
+ export class DomainRootConflictError extends Error {
10
+ readonly code = "DOMAIN_ROOT_CONFLICT";
11
+ constructor(readonly owner: string, readonly contender: string, readonly root: string) {
12
+ super(`Domain root conflict: '${owner}' and '${contender}' both own '${root}'. Update the existing domain by name, or move one domain to a distinct root. Nested roots are allowed; no domains were merged or deleted.`);
13
+ this.name = "DomainRootConflictError";
14
+ }
15
+ }
16
+
17
+ /** Resolve existing ancestors too, so symlink aliases of future directories collide. */
18
+ export function domainRootIdentity(root: string, workspaceRoot: string): string {
19
+ let current = resolve(workspaceRoot, root);
20
+ const missing: string[] = [];
21
+ while (true) {
22
+ try { return join(realpathSync(current), ...missing); }
23
+ catch (error) {
24
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
25
+ try {
26
+ if (lstatSync(current).isSymbolicLink()) throw new Error(`Cannot resolve domain root '${root}': broken symbolic link '${current}'. Repair the link before assigning ownership.`);
27
+ } catch (statError) {
28
+ if ((statError as NodeJS.ErrnoException).code !== "ENOENT") throw statError;
29
+ }
30
+ const parent = dirname(current);
31
+ if (parent === current) throw error;
32
+ missing.unshift(basename(current)); current = parent;
33
+ }
34
+ }
35
+ }
36
+
37
+ export function assertUniqueDomainRoots(domains: Record<string, { root: string }>, workspaceRoot: string): void {
38
+ const owners = new Map<string, string>();
39
+ for (const [name, config] of Object.entries(domains).sort(([a], [b]) => a.localeCompare(b))) {
40
+ const identity = domainRootIdentity(config.root, workspaceRoot);
41
+ const owner = owners.get(identity);
42
+ if (owner && domainNameKey(owner) !== domainNameKey(name)) throw new DomainRootConflictError(owner, name, identity);
43
+ owners.set(identity, name);
44
+ }
45
+ }