@dimassetoid/septum-mcp 0.2.1 → 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 (106) hide show
  1. package/README.md +46 -28
  2. package/package.json +4 -4
  3. package/src/cli/commands/check.ts +27 -16
  4. package/src/cli/commands/hook.ts +38 -101
  5. package/src/cli/commands/init.ts +26 -9
  6. package/src/cli/commands/sync.ts +4 -6
  7. package/src/cli/hook-payload.ts +43 -0
  8. package/src/cli/index.ts +9 -52
  9. package/src/cli/scaffold/harness-config.ts +48 -8
  10. package/src/cli/templates/hooks.ts +49 -14
  11. package/src/cli/templates/rules.ts +34 -49
  12. package/src/cli/templates/skill.ts +39 -35
  13. package/src/core/boundary/evaluator.ts +67 -83
  14. package/src/core/boundary/staged-auditor.ts +102 -40
  15. package/src/core/config/domain-ownership.ts +45 -0
  16. package/src/core/config/loader.ts +81 -29
  17. package/src/core/config/schema.ts +0 -10
  18. package/src/core/database/repositories/dependency.repository.ts +169 -148
  19. package/src/core/database/repositories/domain.repository.ts +46 -3
  20. package/src/core/database/repositories/symbol.repository.ts +226 -87
  21. package/src/core/database/repository.ts +73 -18
  22. package/src/core/database/schema.ts +2 -33
  23. package/src/core/discovery/navigation.ts +105 -0
  24. package/src/core/discovery/topology-detector.ts +60 -2
  25. package/src/core/ingestion/pipeline.ts +96 -129
  26. package/src/core/parser/behavioral-analyzer.ts +26 -22
  27. package/src/core/parser/boundary-tracker.ts +15 -0
  28. package/src/core/parser/extractors/base.ts +7 -3
  29. package/src/core/parser/extractors/csharp.ts +7 -3
  30. package/src/core/parser/extractors/django-semantic.ts +4 -36
  31. package/src/core/parser/extractors/elysia-semantic.ts +3 -24
  32. package/src/core/parser/extractors/express-semantic.ts +3 -18
  33. package/src/core/parser/extractors/fastapi-semantic.ts +19 -53
  34. package/src/core/parser/extractors/fastify-semantic.ts +3 -18
  35. package/src/core/parser/extractors/flask-semantic.ts +22 -55
  36. package/src/core/parser/extractors/go-semantic.ts +92 -33
  37. package/src/core/parser/extractors/hono-semantic.ts +3 -24
  38. package/src/core/parser/extractors/java.ts +5 -3
  39. package/src/core/parser/extractors/laravel-semantic.ts +44 -16
  40. package/src/core/parser/extractors/mcp-cli-semantic.ts +6 -7
  41. package/src/core/parser/extractors/nestjs-semantic.ts +3 -19
  42. package/src/core/parser/extractors/php.ts +16 -0
  43. package/src/core/parser/extractors/python.ts +9 -4
  44. package/src/core/parser/extractors/registry.ts +26 -5
  45. package/src/core/parser/extractors/ruby.ts +8 -5
  46. package/src/core/parser/extractors/rust.ts +31 -13
  47. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  48. package/src/core/parser/extractors/symfony-semantic.ts +4 -37
  49. package/src/core/parser/extractors/typescript.ts +14 -1
  50. package/src/core/parser/implementation-fingerprint.ts +97 -0
  51. package/src/core/parser/language-capabilities.ts +23 -7
  52. package/src/core/parser/schema/providers/laravel-migration-provider.ts +73 -50
  53. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  54. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  55. package/src/core/parser/semantic-revision.ts +3 -0
  56. package/src/core/parser/static-string.ts +51 -0
  57. package/src/core/resolver/call-graph-tracer.ts +337 -28
  58. package/src/core/resolver/import-resolver.ts +107 -179
  59. package/src/core/resolver/interpretation-inputs.ts +7 -0
  60. package/src/core/resolver/languages/go.ts +103 -0
  61. package/src/core/resolver/languages/managed.ts +200 -0
  62. package/src/core/resolver/languages/python.ts +115 -0
  63. package/src/core/resolver/languages/ruby.ts +40 -0
  64. package/src/core/resolver/languages/rust.ts +127 -0
  65. package/src/core/resolver/languages/shared.ts +71 -0
  66. package/src/core/resolver/module-resolver.ts +8 -4
  67. package/src/core/resolver/slice-catalog.ts +79 -0
  68. package/src/core/resolver/slice-format.ts +9 -0
  69. package/src/core/resolver/symbol-impact.ts +381 -0
  70. package/src/core/resolver/vertical-slice-tracer.ts +93 -115
  71. package/src/core/resources/ignore.ts +22 -1
  72. package/src/core/resources/source-files.ts +143 -20
  73. package/src/core/resources/source-inventory.ts +55 -0
  74. package/src/core/retrieval/context-page.ts +109 -0
  75. package/src/core/retrieval/context.ts +320 -0
  76. package/src/core/retrieval/resolution-warnings.ts +21 -0
  77. package/src/core/retrieval/symbol-evidence.ts +97 -0
  78. package/src/core/retrieval/typescript-references.ts +262 -0
  79. package/src/core/telemetry/telemetry.ts +54 -9
  80. package/src/index.ts +0 -3
  81. package/src/mcp/schemas.ts +61 -420
  82. package/src/mcp/server.ts +116 -290
  83. package/src/mcp/tools/boundary.ts +2 -2
  84. package/src/mcp/tools/check-boundary.ts +55 -60
  85. package/src/mcp/tools/get-domain-catalog.ts +32 -219
  86. package/src/mcp/tools/get-symbol-impact.ts +45 -5
  87. package/src/mcp/tools/get-symbol.ts +227 -3
  88. package/src/mcp/tools/locate-symbol.ts +54 -14
  89. package/src/mcp/tools/{domain.ts → map.ts} +4 -18
  90. package/src/mcp/tools/register-domain.ts +41 -3
  91. package/src/mcp/tools/symbol.ts +23 -21
  92. package/src/mcp/tools/trace-vertical-slice.ts +36 -10
  93. package/src/mcp/workspace-manager.ts +15 -4
  94. package/src/mcp/workspace-watcher.ts +8 -8
  95. package/src/types/index.ts +35 -53
  96. package/src/cli/commands/topology.ts +0 -161
  97. package/src/core/database/repositories/environment.repository.ts +0 -207
  98. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  99. package/src/core/session/session-manager.ts +0 -107
  100. package/src/core/topology/environment-detector.ts +0 -973
  101. package/src/core/topology/types.ts +0 -83
  102. package/src/mcp/tools/feature.ts +0 -67
  103. package/src/mcp/tools/get-environment-topology.ts +0 -138
  104. package/src/mcp/tools/get-feature-context.ts +0 -224
  105. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  106. package/src/mcp/tools/register-feature.ts +0 -110
@@ -1,10 +1,12 @@
1
1
  import { posix, relative, resolve, isAbsolute } from "node:path";
2
+ import { existsSync } from "node:fs";
2
3
  import type { BoundaryViolation } from "../../types/index.ts";
3
4
  import type { ValidatedSeptumConfig } from "../config/schema.ts";
4
5
  import { ConfigLoader } from "../config/loader.ts";
5
6
  import type { SeptumRepository } from "../database/repository.ts";
6
7
  import { ModuleResolver } from "../resolver/module-resolver.ts";
7
8
  import { matchesSimpleGlob } from "../parser/extractors/base.ts";
9
+ import { assertUniqueDomainRoots } from "../config/domain-ownership.ts";
8
10
 
9
11
  export class BoundaryEvaluator {
10
12
  private repo: SeptumRepository;
@@ -19,10 +21,13 @@ export class BoundaryEvaluator {
19
21
  return this.resolver;
20
22
  }
21
23
 
24
+ public withResolver(resolver: ModuleResolver): BoundaryEvaluator {
25
+ return new BoundaryEvaluator(this.repo, resolver);
26
+ }
27
+
22
28
  public evaluate(
23
29
  filePath: string,
24
30
  proposedImports: string[] = [],
25
- featureKey?: string,
26
31
  config?: ValidatedSeptumConfig
27
32
  ): BoundaryViolation[] {
28
33
  let activeConfig = config;
@@ -33,27 +38,49 @@ export class BoundaryEvaluator {
33
38
  ? fromRepo
34
39
  : ConfigLoader.loadFromDatabaseOrDefaults();
35
40
  }
41
+ assertUniqueDomainRoots(activeConfig.domains, this.resolver.getProjectRoot());
36
42
  const violations: BoundaryViolation[] = [];
37
43
 
38
- if (featureKey) {
39
- violations.push(...this.checkFeatureTouchpoints(featureKey, filePath, activeConfig));
40
- }
41
-
42
44
  if (proposedImports.length > 0) {
43
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
+ }
44
67
  }
45
68
 
46
69
  return violations;
47
70
  }
48
71
 
49
72
  public auditCodebase(config: ValidatedSeptumConfig): BoundaryViolation[] {
73
+ assertUniqueDomainRoots(config.domains, this.resolver.getProjectRoot());
50
74
  const violations: BoundaryViolation[] = [];
51
75
  const allDependencies = this.repo.getAllDependenciesWithDomains();
52
76
 
53
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)));
54
81
  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);
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);
57
84
  if (!targetDomain || targetDomain === dep.source_domain) {
58
85
  continue;
59
86
  }
@@ -94,7 +121,7 @@ export class BoundaryEvaluator {
94
121
  }
95
122
  }
96
123
 
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;
124
+ const currentDependencies = evidence ? allDependencies.filter(dep => current.has(key(dep.source_file, dep.line_number, dep.target))) : allDependencies;
98
125
  violations.push(...this.detectCircularDependencies(config, currentDependencies));
99
126
 
100
127
  return violations;
@@ -112,6 +139,7 @@ export class BoundaryEvaluator {
112
139
  }>,
113
140
  relevantFiles?: ReadonlySet<string>
114
141
  ): BoundaryViolation[] {
142
+ assertUniqueDomainRoots(config.domains, this.resolver.getProjectRoot());
115
143
  const violations: BoundaryViolation[] = [];
116
144
  let allDependencies = preloadedDeps ?? this.repo.getAllDependenciesWithDomains();
117
145
  if (!preloadedDeps && this.repo.getMeta?.("workspace_root")) {
@@ -142,9 +170,9 @@ export class BoundaryEvaluator {
142
170
  registerKnownFile(d.source_file);
143
171
  }
144
172
 
145
- const resolveTargetFile = (sourceFile: string, rawTarget: string): string | null => {
146
- if (this.repo.getMeta?.("workspace_root")) {
147
- const result = this.resolver.resolveImport(rawTarget,sourceFile);
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);
148
176
  const files = result.targets.flatMap(target => target.files);
149
177
  return result.status === "resolved" && result.coverage !== "conditional" && files.length === 1 ? files[0]! : null;
150
178
  }
@@ -183,16 +211,27 @@ export class BoundaryEvaluator {
183
211
  const fileGraph = new Map<string, Map<string, EdgeMeta>>();
184
212
  const domainGraph = new Map<string, Map<string, EdgeMeta>>();
185
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
+
186
219
  for (const dep of allDependencies) {
187
220
  if (this.repo.getMeta?.("workspace_root")) {
188
- const result = this.resolver.resolveImport(dep.target,dep.source_file);
221
+ const result = this.resolver.resolveImport(dep.target,dep.source_file,dep.statement);
189
222
  if (result.status !== "resolved" || result.coverage === "conditional") continue;
190
223
  } else if (dep.is_external) continue;
191
224
 
192
- const targetDomain = this.resolveTargetDomain(dep.target, config, dep.source_file);
225
+ const targetDomain = this.resolveTargetDomain(dep.target, config, dep.source_file, dep.statement);
193
226
 
194
- // 1. Domain-to-domain edge
195
- if (targetDomain && targetDomain !== dep.source_domain) {
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
+ ) {
196
235
  let outMap = domainGraph.get(dep.source_domain);
197
236
  if (!outMap) {
198
237
  outMap = new Map();
@@ -211,8 +250,12 @@ export class BoundaryEvaluator {
211
250
  outMap.get(targetDomain)!.files.add(dep.source_file);
212
251
  }
213
252
 
214
- // 2. File-to-file edge
215
- const targetFile = resolveTargetFile(dep.source_file, dep.target);
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);
216
259
  if (targetFile && targetFile !== dep.source_file) {
217
260
  let outMap = fileGraph.get(dep.source_file);
218
261
  if (!outMap) {
@@ -309,7 +352,8 @@ export class BoundaryEvaluator {
309
352
  public checkProposedChanges(
310
353
  sourceFilePath: string,
311
354
  proposedImports: string[],
312
- config: ValidatedSeptumConfig
355
+ config: ValidatedSeptumConfig,
356
+ importStatements?: string[]
313
357
  ): BoundaryViolation[] {
314
358
  const violations: BoundaryViolation[] = [];
315
359
  const sourceDomain = this.resolveSourceDomain(sourceFilePath, config);
@@ -335,8 +379,8 @@ export class BoundaryEvaluator {
335
379
  const forbidden = sourceDomainConfig.forbidden_dependencies ?? [];
336
380
  const allowed = sourceDomainConfig.allowed_dependencies ?? [];
337
381
 
338
- for (const statement of proposedImports) {
339
- const targetDomain = this.resolveTargetDomain(statement, config, sourceFilePath);
382
+ for (const [index, statement] of proposedImports.entries()) {
383
+ const targetDomain = this.resolveTargetDomain(statement, config, sourceFilePath, importStatements?.[index]);
340
384
  if (!targetDomain || targetDomain === sourceDomain) {
341
385
  continue;
342
386
  }
@@ -374,69 +418,9 @@ export class BoundaryEvaluator {
374
418
  public resolveTargetDomain(
375
419
  targetStatement: string,
376
420
  config: ValidatedSeptumConfig,
377
- sourceFilePath?: string
421
+ sourceFilePath?: string,
422
+ statement?: string
378
423
  ): 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;
424
+ return this.resolver.resolveTargetDomain(targetStatement, sourceFilePath, config, statement);
441
425
  }
442
426
  }
@@ -1,58 +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";
1
5
  import { RESOURCE_LIMITS } from "../resources/limits.ts";
2
6
  import { execFileSync } from "node:child_process";
3
- import { resolve, relative, sep } from "node:path";
7
+ import { resolve, relative, join, dirname } from "node:path";
4
8
  import type { ImportResolution, BoundaryViolation } from "../../types/index.ts";
5
9
  import type { ValidatedSeptumConfig } from "../config/schema.ts";
6
10
  import { ASTParserEngine } from "../parser/tree-sitter.ts";
7
11
  import type { SeptumRepository } from "../database/repository.ts";
8
- import type { BoundaryEvaluator } from "./evaluator.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";
9
15
 
10
16
  export async function auditStagedFiles(
11
17
  evaluator: BoundaryEvaluator,
12
18
  config: ValidatedSeptumConfig,
13
19
  workspaceRoot: string,
14
- featureKey?: string,
15
20
  repo?: SeptumRepository
16
21
  ): Promise<{ files: string[]; violations: BoundaryViolation[]; resolution_issues: ImportResolution[] }> {
17
22
  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}.`);
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;
43
72
  }
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);
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);
50
114
  }
51
- violations.push(...found);
52
115
  }
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 };
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 }); }
58
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
+ }
@@ -1,44 +1,99 @@
1
- import { existsSync } from "node:fs";
2
- import { isAbsolute, join } from "node:path";
1
+ import { closeSync, existsSync, lstatSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { isAbsolute, join, resolve } from "node:path";
3
3
  import { Database } from "bun:sqlite";
4
- import type { ValidatedSeptumConfig } from "./schema.ts";
5
- import { TopologyDetector } from "../discovery/topology-detector.ts";
4
+ import { SeptumConfigSchema, type ValidatedSeptumConfig } from "./schema.ts";
6
5
  import { SeptumDatabase } from "../database/client.ts";
7
6
  import { SeptumRepository } from "../database/repository.ts";
8
- import { resolveWorkspaceRoot, isAppHostDirectory } from "../resolver/path-resolver.ts";
7
+ import { resolveWorkspaceRoot } from "../resolver/path-resolver.ts";
8
+ import type { DomainConfig } from "../../types/index.ts";
9
+
10
+ export function resolveDatabasePath(root: string, dbPath = ".septum/septum.db"): string {
11
+ return dbPath === ":memory:" || isAbsolute(dbPath) ? dbPath : resolve(root, dbPath);
12
+ }
9
13
 
10
14
  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
+ /** Read configuration without initializing or modifying workspace state. */
15
16
  public static load(
16
17
  dbPath?: string,
17
18
  projectRoot?: string
18
19
  ): ValidatedSeptumConfig {
19
20
  const root = resolveWorkspaceRoot(projectRoot);
20
- const resolvedDbPath = dbPath
21
- ? (isAbsolute(dbPath) ? dbPath : join(root, dbPath))
22
- : join(root, ".septum", "septum.db");
21
+ const configFilePath = join(root, "septum.config.json");
22
+ if (existsSync(configFilePath)) {
23
+ const diskConfig = ConfigLoader.loadFromDisk(configFilePath);
24
+ if (dbPath) diskConfig.settings.db_path = dbPath;
25
+ return diskConfig;
26
+ }
27
+ return ConfigLoader.loadFromDatabaseOrDefaults(resolveDatabasePath(root, dbPath));
28
+ }
23
29
 
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
+ /** The file owns policy when present; retain unknown user fields on updates. */
31
+ public static writeDomain(root: string, name: string, domain: DomainConfig, expected: string): void {
32
+ const file = join(root, "septum.config.json");
33
+ const lock = `${file}.lock`;
34
+ const fd = openSync(lock, "wx");
35
+ const temporary = `${file}.${process.pid}.tmp`;
36
+ try {
37
+ if (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink()) throw new Error("Policy file must be a regular file.");
38
+ if (readFileSync(file, "utf8") !== expected) throw new Error("Policy changed during registration; reload and retry.");
39
+ const raw = JSON.parse(expected);
40
+ const domains = { ...raw.domains };
41
+ const key = Object.keys(domains).find(key => key.toLowerCase() === name.toLowerCase()) ?? name;
42
+ domains[key] = { ...domains[key], ...domain };
43
+ const updated = { ...raw, domains };
44
+ SeptumConfigSchema.parse(updated);
45
+ writeFileSync(temporary, JSON.stringify(updated, null, 2) + "\n", { flag: "wx", mode: lstatSync(file).mode & 0o777 });
46
+ if (readFileSync(file, "utf8") !== expected) throw new Error("Policy changed during registration; reload and retry.");
47
+ renameSync(temporary, file);
48
+ } finally {
49
+ closeSync(fd);
50
+ rmSync(temporary, { force: true });
51
+ rmSync(lock, { force: true });
30
52
  }
53
+ }
31
54
 
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();
55
+ public static loadFromDisk(filePath: string): ValidatedSeptumConfig {
56
+ try {
57
+ const raw = readFileSync(filePath, "utf-8");
58
+ const parsed = JSON.parse(raw);
59
+ const defaults = ConfigLoader.getDefaultConfig();
60
+ const merged = {
61
+ ...defaults,
62
+ ...parsed,
63
+ settings: {
64
+ ...defaults.settings,
65
+ ...(parsed.settings || {}),
66
+ },
67
+ domains: parsed.domains || {},
68
+ };
69
+ return SeptumConfigSchema.parse(merged);
70
+ } catch (err: any) {
71
+ throw new Error(`Failed to load configuration from '${filePath}': ${err.message || err}`);
39
72
  }
73
+ }
40
74
 
41
- return ConfigLoader.loadFromDatabaseOrDefaults(resolvedDbPath);
75
+ public static syncDiskConfigToDatabase(
76
+ dbPath: string,
77
+ diskConfig: ValidatedSeptumConfig,
78
+ workspaceRoot?: string
79
+ ): void {
80
+ if (!existsSync(dbPath)) return;
81
+ const septumDb = new SeptumDatabase(dbPath);
82
+ const repo = new SeptumRepository(septumDb.raw);
83
+ try {
84
+ repo.runInTransaction(() => {
85
+ repo.setMeta("settings_json", JSON.stringify(diskConfig.settings));
86
+ if (diskConfig.domains && Object.keys(diskConfig.domains).length > 0) {
87
+ const domainNames = Object.keys(diskConfig.domains);
88
+ for (const [name, domain] of Object.entries(diskConfig.domains)) {
89
+ repo.upsertDomain(name, domain, workspaceRoot);
90
+ }
91
+ repo.pruneDomainsNotIn(domainNames);
92
+ }
93
+ });
94
+ } finally {
95
+ septumDb.close();
96
+ }
42
97
  }
43
98
 
44
99
  public static getDefaultConfig(): ValidatedSeptumConfig {
@@ -66,7 +121,6 @@ export class ConfigLoader {
66
121
  ],
67
122
  },
68
123
  domains: {},
69
- features: {},
70
124
  };
71
125
  }
72
126
 
@@ -85,8 +139,6 @@ export class ConfigLoader {
85
139
  }
86
140
 
87
141
  if (typeof repo?.getMeta === "function") {
88
- const features = repo.getMeta("features_json");
89
- if (features) config.features = JSON.parse(features);
90
142
  const settings = repo.getMeta("settings_json");
91
143
  if (settings) Object.assign(config.settings, JSON.parse(settings));
92
144
  }
@@ -8,15 +8,6 @@ export const DomainConfigSchema = z.object({
8
8
  archetypes: z.record(z.string()).optional().default({}),
9
9
  });
10
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
11
  export const SeptumConfigSchema = z.object({
21
12
  version: z.string().default("1.0"),
22
13
  settings: z
@@ -63,7 +54,6 @@ export const SeptumConfigSchema = z.object({
63
54
  ],
64
55
  }),
65
56
  domains: z.record(DomainConfigSchema).default({}),
66
- features: z.record(FeatureConfigSchema).optional().default({}),
67
57
  });
68
58
 
69
59
  export type ValidatedSeptumConfig = z.infer<typeof SeptumConfigSchema>;