@dimassetoid/septum-mcp 0.2.1 → 0.5.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.
- package/README.md +46 -45
- package/package.json +8 -6
- package/src/cli/commands/check.ts +41 -26
- package/src/cli/commands/hook.ts +77 -105
- package/src/cli/commands/init.ts +35 -9
- package/src/cli/commands/stats.ts +33 -0
- package/src/cli/commands/sync-progress.ts +71 -0
- package/src/cli/commands/sync.ts +35 -9
- package/src/cli/hook-payload.ts +43 -0
- package/src/cli/index.ts +15 -51
- package/src/cli/scaffold/harness-config.ts +48 -8
- package/src/cli/templates/hooks.ts +51 -27
- package/src/cli/templates/rules.ts +34 -49
- package/src/cli/templates/skill.ts +46 -35
- package/src/core/boundary/audit.ts +383 -0
- package/src/core/boundary/evaluator.ts +299 -178
- package/src/core/boundary/staged-auditor.ts +188 -34
- package/src/core/config/domain-ownership.ts +47 -0
- package/src/core/config/domain-registration.ts +141 -0
- package/src/core/config/loader.ts +82 -54
- package/src/core/config/schema.ts +24 -46
- package/src/core/database/client.ts +2 -0
- package/src/core/database/repositories/dependency.repository.ts +326 -543
- package/src/core/database/repositories/domain.repository.ts +48 -4
- package/src/core/database/repositories/file.repository.ts +10 -0
- package/src/core/database/repositories/symbol.repository.ts +97 -259
- package/src/core/database/repository.ts +138 -24
- package/src/core/database/schema.ts +28 -33
- package/src/core/discovery/declarative-routes.ts +69 -0
- package/src/core/discovery/framework-detector.ts +149 -0
- package/src/core/discovery/navigation.ts +269 -0
- package/src/core/discovery/topology-detector.ts +153 -170
- package/src/core/errors.ts +19 -0
- package/src/core/ingestion/pipeline.ts +378 -212
- package/src/core/parser/behavioral-analyzer.ts +26 -22
- package/src/core/parser/boundary-tracker.ts +15 -0
- package/src/core/parser/extractors/base.ts +16 -4
- package/src/core/parser/extractors/csharp.ts +9 -5
- package/src/core/parser/extractors/django-routing.ts +163 -0
- package/src/core/parser/extractors/django-semantic.ts +400 -516
- package/src/core/parser/extractors/elysia-semantic.ts +172 -496
- package/src/core/parser/extractors/express-semantic.ts +195 -398
- package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
- package/src/core/parser/extractors/fastify-semantic.ts +216 -732
- package/src/core/parser/extractors/flask-semantic.ts +92 -388
- package/src/core/parser/extractors/go-routing.ts +344 -0
- package/src/core/parser/extractors/go-semantic.ts +210 -508
- package/src/core/parser/extractors/go.ts +6 -3
- package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
- package/src/core/parser/extractors/hono-semantic.ts +132 -530
- package/src/core/parser/extractors/java.ts +7 -5
- package/src/core/parser/extractors/laravel-routing.ts +263 -0
- package/src/core/parser/extractors/laravel-semantic.ts +169 -333
- package/src/core/parser/extractors/manifest-helpers.ts +64 -0
- package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
- package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
- package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
- package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
- package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
- package/src/core/parser/extractors/php.ts +17 -1
- package/src/core/parser/extractors/python-route-ast.ts +249 -0
- package/src/core/parser/extractors/python.ts +9 -8
- package/src/core/parser/extractors/registry.ts +28 -5
- package/src/core/parser/extractors/route-prefixes.ts +43 -0
- package/src/core/parser/extractors/ruby.ts +10 -7
- package/src/core/parser/extractors/rust.ts +35 -17
- package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
- package/src/core/parser/extractors/symfony-routing.ts +114 -0
- package/src/core/parser/extractors/symfony-semantic.ts +75 -262
- package/src/core/parser/extractors/typescript-bindings.ts +333 -0
- package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
- package/src/core/parser/extractors/typescript-fallback.ts +207 -0
- package/src/core/parser/extractors/typescript-route-context.ts +58 -0
- package/src/core/parser/extractors/typescript.ts +36 -216
- package/src/core/parser/implementation-fingerprint.ts +97 -0
- package/src/core/parser/language-capabilities.ts +23 -7
- package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
- package/src/core/parser/schema/schema-provider-registry.ts +1 -3
- package/src/core/parser/schema/schema-provider.interface.ts +2 -1
- package/src/core/parser/semantic-revision.ts +3 -0
- package/src/core/parser/static-string.ts +51 -0
- package/src/core/parser/wasm-loader.ts +6 -2
- package/src/core/resolver/ast-method-tracer.ts +230 -0
- package/src/core/resolver/call-graph-helpers.ts +72 -0
- package/src/core/resolver/call-graph-tracer.ts +375 -311
- package/src/core/resolver/dependency-analysis.ts +593 -0
- package/src/core/resolver/import-candidates.ts +120 -0
- package/src/core/resolver/import-evidence.ts +88 -0
- package/src/core/resolver/import-resolver.ts +162 -181
- package/src/core/resolver/interpretation-inputs.ts +65 -0
- package/src/core/resolver/languages/go.ts +103 -0
- package/src/core/resolver/languages/managed.ts +200 -0
- package/src/core/resolver/languages/python.ts +133 -0
- package/src/core/resolver/languages/ruby.ts +40 -0
- package/src/core/resolver/languages/rust.ts +127 -0
- package/src/core/resolver/languages/shared.ts +74 -0
- package/src/core/resolver/module-resolver.ts +18 -7
- package/src/core/resolver/path-resolver.ts +6 -3
- package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
- package/src/core/resolver/slice-catalog.ts +94 -0
- package/src/core/resolver/slice-format.ts +22 -0
- package/src/core/resolver/slice-selection.ts +237 -0
- package/src/core/resolver/symbol-impact.ts +477 -0
- package/src/core/resolver/symbol-locator.ts +82 -15
- package/src/core/resolver/vertical-slice-tracer.ts +57 -278
- package/src/core/resources/ignore.ts +21 -1
- package/src/core/resources/limits.ts +2 -1
- package/src/core/resources/source-files.ts +143 -20
- package/src/core/resources/source-inventory.ts +55 -0
- package/src/core/resources/work-queue.ts +167 -4
- package/src/core/retrieval/context-page.ts +116 -0
- package/src/core/retrieval/context.ts +457 -0
- package/src/core/retrieval/resolution-warnings.ts +21 -0
- package/src/core/retrieval/source-context.ts +448 -0
- package/src/core/retrieval/symbol-details.ts +453 -0
- package/src/core/retrieval/symbol-evidence.ts +97 -0
- package/src/core/retrieval/typescript-references.ts +293 -0
- package/src/core/retrieval/universal-context.ts +182 -0
- package/src/core/telemetry/summary.ts +114 -0
- package/src/core/telemetry/telemetry.ts +225 -37
- package/src/index.ts +0 -3
- package/src/mcp/formatters/compact-text.ts +439 -0
- package/src/mcp/resources-and-prompts.ts +253 -0
- package/src/mcp/schemas/boundary.ts +145 -0
- package/src/mcp/schemas/map.ts +250 -0
- package/src/mcp/schemas/shared.ts +52 -0
- package/src/mcp/schemas/slice.ts +60 -0
- package/src/mcp/schemas/symbol.ts +268 -0
- package/src/mcp/schemas.ts +5 -1105
- package/src/mcp/server.ts +263 -597
- package/src/mcp/tool-catalog.ts +331 -0
- package/src/mcp/tools/boundary.ts +69 -4
- package/src/mcp/tools/map.ts +126 -0
- package/src/mcp/tools/slice.ts +101 -3
- package/src/mcp/tools/symbol.ts +480 -26
- package/src/mcp/ui/app-client.ts +899 -0
- package/src/mcp/ui/app.html +478 -0
- package/src/mcp/workflow-playbooks.ts +181 -0
- package/src/mcp/workspace-boundary.ts +50 -0
- package/src/mcp/workspace-manager.ts +102 -18
- package/src/mcp/workspace-watcher.ts +38 -19
- package/src/types/index.ts +47 -53
- package/src/cli/commands/topology.ts +0 -161
- package/src/core/database/repositories/environment.repository.ts +0 -207
- package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
- package/src/core/session/session-manager.ts +0 -107
- package/src/core/topology/environment-detector.ts +0 -973
- package/src/core/topology/types.ts +0 -83
- package/src/mcp/tools/check-boundary.ts +0 -387
- package/src/mcp/tools/domain.ts +0 -40
- package/src/mcp/tools/feature.ts +0 -67
- package/src/mcp/tools/get-domain-catalog.ts +0 -226
- package/src/mcp/tools/get-environment-topology.ts +0 -138
- package/src/mcp/tools/get-feature-context.ts +0 -224
- package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
- package/src/mcp/tools/get-symbol-impact.ts +0 -64
- package/src/mcp/tools/get-symbol.ts +0 -175
- package/src/mcp/tools/locate-symbol.ts +0 -196
- package/src/mcp/tools/register-domain.ts +0 -75
- package/src/mcp/tools/register-feature.ts +0 -110
- package/src/mcp/tools/trace-vertical-slice.ts +0 -80
|
@@ -1,58 +1,212 @@
|
|
|
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,
|
|
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
|
|
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
|
-
): Promise<{
|
|
21
|
+
): Promise<{
|
|
22
|
+
files: string[];
|
|
23
|
+
violations: BoundaryViolation[];
|
|
24
|
+
resolution_issues: ImportResolution[];
|
|
25
|
+
background_resolution_issues_count: number;
|
|
26
|
+
}> {
|
|
17
27
|
const gitRoot = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: workspaceRoot, encoding: "utf8" }).trim();
|
|
28
|
+
// Freeze the index as a Git tree. Every source/config/target is read from this tree.
|
|
29
|
+
const tree = execFileSync("git", ["write-tree"], { cwd: gitRoot, encoding: "utf8", timeout: 5000 }).trim();
|
|
18
30
|
const rawPrefix = relative(gitRoot, workspaceRoot).replace(/\\/g, "/");
|
|
19
31
|
const prefix = rawPrefix === "." ? "" : rawPrefix;
|
|
20
32
|
const inside = (file: string) => !prefix || file === prefix || file.startsWith(prefix + "/");
|
|
21
|
-
const
|
|
33
|
+
const hasHead = (() => { try { execFileSync("git", ["rev-parse", "--verify", "HEAD"], { cwd: gitRoot, stdio: "ignore" }); return true; } catch { return false; } })();
|
|
34
|
+
const emptyTree = execFileSync("git", ["hash-object", "-t", "tree", "--stdin"], { cwd: gitRoot, input: "", encoding: "utf8" }).trim();
|
|
35
|
+
const stagedPaths = (filter: string) => execFileSync("git", ["diff-tree", "--root", "--no-commit-id", "-r", "--name-only", `--diff-filter=${filter}`, "-z", hasHead ? "HEAD" : emptyTree, tree], {
|
|
22
36
|
cwd: gitRoot, encoding: "utf-8", timeout: 5000, maxBuffer: 10 * 1024 * 1024,
|
|
23
37
|
}).split("\0").filter(Boolean).map(f => f.replace(/\\/g, "/")).filter(inside);
|
|
24
38
|
const files = stagedPaths("ACMR").map(file => (prefix ? relative(prefix, file) : file).replace(/\\/g, "/"));
|
|
25
39
|
const deleted = stagedPaths("D").map(file => (prefix ? relative(prefix, file) : file).replace(/\\/g, "/"));
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
if (files.length === 0 && deleted.length === 0) {
|
|
41
|
+
return { files: [], violations: [], resolution_issues: [], background_resolution_issues_count: 0 };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const scratch = mkdtempSync(join(tmpdir(), "septum-staged-"));
|
|
45
|
+
const snapshot = join(scratch, "tree");
|
|
46
|
+
try {
|
|
47
|
+
mkdirSync(snapshot);
|
|
48
|
+
const entries = execFileSync("git", ["ls-tree", "-r", "-l", "-z", tree], { cwd: gitRoot, encoding: "utf8", maxBuffer: 10 * 1024 * 1024 }).split("\0").filter(Boolean);
|
|
49
|
+
if (entries.length > 20000) throw new Error("Staged view exceeds file-count limit (20000).");
|
|
50
|
+
let totalBytes = 0;
|
|
51
|
+
const indexedPaths: string[] = [];
|
|
52
|
+
const blobs: Array<{ oid: string; file: string; size: number }> = [];
|
|
53
|
+
for (const entry of entries) {
|
|
54
|
+
const match = /^(\d+) (?:blob|commit) ([a-f0-9]+)\s+(\d+|-)\t([\s\S]+)$/.exec(entry);
|
|
55
|
+
if (!match) continue;
|
|
56
|
+
const [, mode, oid, sizeText, file] = match;
|
|
57
|
+
// Only source and interpretation inputs need bytes in the parser snapshot.
|
|
58
|
+
// Keep the complete path inventory so omitted assets cannot masquerade as source.
|
|
59
|
+
indexedPaths.push(file!);
|
|
60
|
+
const needed = ASTParserEngine.isSourceFile(file!) || isResolutionInput(file!);
|
|
61
|
+
if (!needed) continue;
|
|
62
|
+
if (!["100644", "100755"].includes(mode!)) throw new Error("Cannot certify staged view containing symlinks or submodules.");
|
|
63
|
+
const size = Number(sizeText);
|
|
64
|
+
totalBytes += size;
|
|
65
|
+
if (size > RESOURCE_LIMITS.sourceBytes || totalBytes > 128 * 1024 * 1024) throw new Error("Staged view exceeds resource limits.");
|
|
66
|
+
const destination = resolve(snapshot, file!);
|
|
67
|
+
if (!destination.startsWith(snapshot + "/")) throw new Error("Invalid staged path.");
|
|
68
|
+
blobs.push({ oid: oid!, file: file!, size });
|
|
43
69
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
70
|
+
const parser = new ASTParserEngine();
|
|
71
|
+
const interpretationChanged = [...files, ...deleted].some(isResolutionInput);
|
|
72
|
+
const changed = new Set(files);
|
|
73
|
+
const canUseFastPath =
|
|
74
|
+
!interpretationChanged &&
|
|
75
|
+
repo?.getMeta("sync_state") === "complete" &&
|
|
76
|
+
repo.getMeta("parser_revision") === PARSER_FINGERPRINT;
|
|
77
|
+
|
|
78
|
+
const indexedFileSet = canUseFastPath
|
|
79
|
+
? new Set(repo!.getAllFiles().map(f => f.path))
|
|
80
|
+
: undefined;
|
|
81
|
+
const unstagedModified = canUseFastPath
|
|
82
|
+
? new Set(
|
|
83
|
+
execFileSync("git", ["diff-files", "--name-only", "-z"], {
|
|
84
|
+
cwd: gitRoot,
|
|
85
|
+
encoding: "utf8",
|
|
86
|
+
timeout: 5000,
|
|
87
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
88
|
+
})
|
|
89
|
+
.split("\0")
|
|
90
|
+
.filter(Boolean)
|
|
91
|
+
.map(f => f.replace(/\\/g, "/"))
|
|
92
|
+
.filter(inside)
|
|
93
|
+
.map(f => (prefix ? relative(prefix, f) : f).replace(/\\/g, "/"))
|
|
94
|
+
)
|
|
95
|
+
: undefined;
|
|
96
|
+
|
|
97
|
+
const blobsToFetch: Array<{ oid: string; file: string; size: number }> = [];
|
|
98
|
+
const placeholderFiles: string[] = [];
|
|
99
|
+
for (const blob of blobs) {
|
|
100
|
+
const relFile = (prefix ? relative(prefix, blob.file) : blob.file).replace(/\\/g, "/");
|
|
101
|
+
const needsBytes =
|
|
102
|
+
!canUseFastPath ||
|
|
103
|
+
changed.has(relFile) ||
|
|
104
|
+
isResolutionInput(blob.file) ||
|
|
105
|
+
isResolutionInput(relFile) ||
|
|
106
|
+
!indexedFileSet!.has(relFile) ||
|
|
107
|
+
unstagedModified!.has(relFile);
|
|
108
|
+
if (needsBytes) {
|
|
109
|
+
blobsToFetch.push(blob);
|
|
110
|
+
} else {
|
|
111
|
+
placeholderFiles.push(blob.file);
|
|
50
112
|
}
|
|
51
|
-
violations.push(...found);
|
|
52
113
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
114
|
+
|
|
115
|
+
for (const file of placeholderFiles) {
|
|
116
|
+
const destination = resolve(snapshot, file);
|
|
117
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
118
|
+
closeSync(openSync(destination, "w"));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (blobsToFetch.length > 0) {
|
|
122
|
+
// One raw-blob process, spooled to disk to bound JS memory. checkout-index
|
|
123
|
+
// applies smudge/EOL/encoding filters; archive applies export attributes.
|
|
124
|
+
// Neither is a faithful raw index snapshot for parsing and resolution.
|
|
125
|
+
const batchPath = join(scratch, "blobs");
|
|
126
|
+
const fd = openSync(batchPath, "w");
|
|
127
|
+
try {
|
|
128
|
+
execFileSync("git", ["cat-file", "--batch"], { cwd: gitRoot, timeout: 30000,
|
|
129
|
+
input: blobsToFetch.map(blob => blob.oid + "\n").join(""), stdio: ["pipe", fd, "pipe"] });
|
|
130
|
+
} finally { closeSync(fd); }
|
|
131
|
+
const batch = Bun.file(batchPath);
|
|
132
|
+
let offset = 0;
|
|
133
|
+
for (const { oid, file, size } of blobsToFetch) {
|
|
134
|
+
const header = `${oid} blob ${size}\n`;
|
|
135
|
+
const length = header.length + size + 1;
|
|
136
|
+
const record = Buffer.from(await batch.slice(offset, offset + length).arrayBuffer());
|
|
137
|
+
if (record.length !== length || record.subarray(0, header.length).toString() !== header || record[length - 1] !== 10) {
|
|
138
|
+
throw new Error("Invalid staged blob batch.");
|
|
139
|
+
}
|
|
140
|
+
const destination = resolve(snapshot, file);
|
|
141
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
142
|
+
writeFileSync(destination, record.subarray(header.length, length - 1));
|
|
143
|
+
offset += length;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const snapshotRoot = join(snapshot, prefix);
|
|
147
|
+
evaluator = evaluator.withResolver(new ModuleResolver(snapshotRoot));
|
|
148
|
+
const violations: BoundaryViolation[] = [];
|
|
149
|
+
const resolutionIssues: ImportResolution[] = [];
|
|
150
|
+
let backgroundResolutionIssuesCount = 0;
|
|
151
|
+
const stagedDependencies: ReturnType<SeptumRepository["getAllDependenciesWithDomains"]> = [];
|
|
152
|
+
const sourceFiles = indexedPaths.filter(inside).map(file => (prefix ? relative(prefix, file) : file).replace(/\\/g, "/"));
|
|
153
|
+
const repoDepsByFile = canUseFastPath
|
|
154
|
+
? (() => {
|
|
155
|
+
const map = new Map<string, ReturnType<SeptumRepository["getAllDependenciesWithDomains"]>>();
|
|
156
|
+
for (const dep of repo!.getAllDependenciesWithDomains()) {
|
|
157
|
+
const list = map.get(dep.source_file) ?? [];
|
|
158
|
+
list.push(dep);
|
|
159
|
+
map.set(dep.source_file, list);
|
|
160
|
+
}
|
|
161
|
+
return map;
|
|
162
|
+
})()
|
|
163
|
+
: undefined;
|
|
164
|
+
|
|
165
|
+
for (const file of sourceFiles) {
|
|
166
|
+
const sourceDomain = evaluator.resolveSourceDomain(file, config);
|
|
167
|
+
if (!ASTParserEngine.isSourceFile(file) || !sourceDomain) continue;
|
|
168
|
+
let dependencies: Array<{ target: string; statement: string; line_number: number; is_external: boolean }>;
|
|
169
|
+
if (canUseFastPath && !changed.has(file) && indexedFileSet!.has(file) && !unstagedModified!.has(file)) {
|
|
170
|
+
dependencies = repoDepsByFile!.get(file) ?? [];
|
|
171
|
+
} else {
|
|
172
|
+
const content = await Bun.file(resolve(snapshotRoot, file)).text();
|
|
173
|
+
const existing = repo?.getFileByPath(file);
|
|
174
|
+
const reusable = !changed.has(file) && !interpretationChanged &&
|
|
175
|
+
repo?.getMeta("sync_state") === "complete" && repo.getMeta("parser_revision") === PARSER_FINGERPRINT &&
|
|
176
|
+
existing?.content_hash === computeContentHash(content);
|
|
177
|
+
dependencies = reusable ? repo!.getDependenciesByFileId(existing!.id) : await (async () => {
|
|
178
|
+
const parsed = await parser.parseFile(resolve(snapshotRoot, file), content);
|
|
179
|
+
if (parsed.status === "unsupported" || parsed.status === "degraded") {
|
|
180
|
+
throw new Error(`Cannot reliably parse staged file '${file}': ${parsed.status}.`);
|
|
181
|
+
}
|
|
182
|
+
return parsed.dependencies;
|
|
183
|
+
})();
|
|
184
|
+
}
|
|
185
|
+
for (const dependency of dependencies) {
|
|
186
|
+
stagedDependencies.push({ source_file: file, source_domain: sourceDomain, target: dependency.target, statement: dependency.statement, line_number: dependency.line_number, is_external: dependency.is_external });
|
|
187
|
+
const isRelevantFile = changed.has(file) || interpretationChanged;
|
|
188
|
+
const resolution = evaluator.getResolver().resolveImport(dependency.target, file, dependency.statement);
|
|
189
|
+
const needsViolationCheck = isRelevantFile || !["resolved", "external"].includes(resolution.status) || resolution.coverage === "conditional";
|
|
190
|
+
const found = needsViolationCheck
|
|
191
|
+
? evaluator.checkProposedChanges(file, [dependency.target], config, [dependency.statement]).map(violation => ({ ...violation, line: dependency.line_number }))
|
|
192
|
+
: [];
|
|
193
|
+
if (found.length === 0 && (!["resolved","external"].includes(resolution.status) || resolution.coverage === "conditional")) {
|
|
194
|
+
if (isRelevantFile) {
|
|
195
|
+
resolutionIssues.push(resolution);
|
|
196
|
+
} else {
|
|
197
|
+
backgroundResolutionIssuesCount++;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (isRelevantFile) violations.push(...found);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const staged = new Set([...files, ...deleted]);
|
|
204
|
+
violations.push(...evaluator.detectCircularDependencies(config, stagedDependencies, interpretationChanged ? new Set(sourceFiles) : staged));
|
|
205
|
+
return {
|
|
206
|
+
files: Array.from(staged),
|
|
207
|
+
violations,
|
|
208
|
+
resolution_issues: resolutionIssues,
|
|
209
|
+
background_resolution_issues_count: backgroundResolutionIssuesCount,
|
|
210
|
+
};
|
|
211
|
+
} finally { rmSync(scratch, { recursive: true, force: true }); }
|
|
58
212
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { SeptumError } from "../errors.ts";
|
|
4
|
+
|
|
5
|
+
// SQLite's built-in NOCASE/LOWER folds ASCII, not all Unicode case pairs.
|
|
6
|
+
export function domainNameKey(name: string): string {
|
|
7
|
+
return name.replace(/[A-Z]/g, letter => letter.toLowerCase());
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class DomainRootConflictError extends SeptumError {
|
|
11
|
+
constructor(readonly owner: string, readonly contender: string, readonly root: string) {
|
|
12
|
+
super(
|
|
13
|
+
"DOMAIN_ROOT_CONFLICT",
|
|
14
|
+
`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.`
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Resolve existing ancestors too, so symlink aliases of future directories collide. */
|
|
20
|
+
export function domainRootIdentity(root: string, workspaceRoot: string): string {
|
|
21
|
+
let current = resolve(workspaceRoot, root);
|
|
22
|
+
const missing: string[] = [];
|
|
23
|
+
while (true) {
|
|
24
|
+
try { return join(realpathSync(current), ...missing); }
|
|
25
|
+
catch (error) {
|
|
26
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
27
|
+
try {
|
|
28
|
+
if (lstatSync(current).isSymbolicLink()) throw new Error(`Cannot resolve domain root '${root}': broken symbolic link '${current}'. Repair the link before assigning ownership.`);
|
|
29
|
+
} catch (statError) {
|
|
30
|
+
if ((statError as NodeJS.ErrnoException).code !== "ENOENT") throw statError;
|
|
31
|
+
}
|
|
32
|
+
const parent = dirname(current);
|
|
33
|
+
if (parent === current) throw error;
|
|
34
|
+
missing.unshift(basename(current)); current = parent;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function assertUniqueDomainRoots(domains: Record<string, { root: string }>, workspaceRoot: string): void {
|
|
40
|
+
const owners = new Map<string, string>();
|
|
41
|
+
for (const [name, config] of Object.entries(domains).sort(([a], [b]) => a.localeCompare(b))) {
|
|
42
|
+
const identity = domainRootIdentity(config.root, workspaceRoot);
|
|
43
|
+
const owner = owners.get(identity);
|
|
44
|
+
if (owner && domainNameKey(owner) !== domainNameKey(name)) throw new DomainRootConflictError(owner, name, identity);
|
|
45
|
+
owners.set(identity, name);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import type { SeptumRepository } from "../database/repository.ts";
|
|
4
|
+
import { IngestionPipeline, type IngestionMetrics } from "../ingestion/pipeline.ts";
|
|
5
|
+
import { assertPathContained } from "../resolver/path-resolver.ts";
|
|
6
|
+
import { assertUniqueDomainRoots, domainNameKey, domainRootIdentity } from "./domain-ownership.ts";
|
|
7
|
+
import { ConfigLoader } from "./loader.ts";
|
|
8
|
+
import { SeptumConfigSchema, type ValidatedSeptumConfig } from "./schema.ts";
|
|
9
|
+
import type { DomainConfig } from "../../types/index.ts";
|
|
10
|
+
|
|
11
|
+
export interface DomainRegistrationInput {
|
|
12
|
+
domain?: string;
|
|
13
|
+
name?: string;
|
|
14
|
+
root?: string;
|
|
15
|
+
description?: string;
|
|
16
|
+
allowed_dependencies?: string[];
|
|
17
|
+
forbidden_dependencies?: string[];
|
|
18
|
+
archetypes?: Record<string, string>;
|
|
19
|
+
ingest_now?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface DomainRegistrationResult {
|
|
23
|
+
policyOwner: "database" | "file";
|
|
24
|
+
domainId: number;
|
|
25
|
+
domain: string;
|
|
26
|
+
config: ValidatedSeptumConfig["domains"][string];
|
|
27
|
+
ingestionMetrics: IngestionMetrics | null;
|
|
28
|
+
conflictPending: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function registerDomainPolicy(
|
|
32
|
+
repo: SeptumRepository,
|
|
33
|
+
config: ValidatedSeptumConfig,
|
|
34
|
+
args: DomainRegistrationInput,
|
|
35
|
+
workspaceRoot: string = process.cwd(),
|
|
36
|
+
signal?: AbortSignal
|
|
37
|
+
): Promise<DomainRegistrationResult> {
|
|
38
|
+
signal?.throwIfAborted();
|
|
39
|
+
const domainName = (args.domain || args.name || "").trim();
|
|
40
|
+
if (!domainName || !args.root) {
|
|
41
|
+
throw new Error("Missing required arguments: 'domain' (or 'name') and 'root' are required.");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// SV-02: Enforce workspace containment (reject traversal/absolute/symlink escape)
|
|
45
|
+
assertPathContained(args.root, workspaceRoot, "Domain root");
|
|
46
|
+
const absDomainRoot = resolve(workspaceRoot, args.root);
|
|
47
|
+
try {
|
|
48
|
+
const rootStat = statSync(absDomainRoot);
|
|
49
|
+
if (!rootStat.isDirectory()) {
|
|
50
|
+
throw new Error(`Domain root '${args.root}' is not a directory.`);
|
|
51
|
+
}
|
|
52
|
+
} catch (err: any) {
|
|
53
|
+
if (err?.code !== "ENOENT") {
|
|
54
|
+
if (err instanceof Error && err.message.endsWith("is not a directory.")) throw err;
|
|
55
|
+
throw new Error(`Failed to access domain root '${args.root}' for domain '${domainName}': ${err?.message || err}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
signal?.throwIfAborted();
|
|
59
|
+
|
|
60
|
+
const domainConfig: DomainConfig = {
|
|
61
|
+
root: args.root,
|
|
62
|
+
description: args.description || `Domain: ${domainName}`,
|
|
63
|
+
allowed_dependencies: args.allowed_dependencies,
|
|
64
|
+
forbidden_dependencies: args.forbidden_dependencies,
|
|
65
|
+
archetypes: args.archetypes,
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const proposed = domainRootIdentity(args.root, workspaceRoot);
|
|
69
|
+
const memoryClaims = Object.fromEntries(
|
|
70
|
+
Object.entries(config.domains).filter(
|
|
71
|
+
([name, claim]) => domainNameKey(name) !== domainNameKey(domainName) && domainRootIdentity(claim.root, workspaceRoot) === proposed
|
|
72
|
+
)
|
|
73
|
+
);
|
|
74
|
+
assertUniqueDomainRoots({ ...memoryClaims, [domainName]: domainConfig }, workspaceRoot);
|
|
75
|
+
|
|
76
|
+
const policyFile = join(workspaceRoot, "septum.config.json");
|
|
77
|
+
const policySource = existsSync(policyFile) ? readFileSync(policyFile, "utf8") : undefined;
|
|
78
|
+
if (policySource !== undefined) {
|
|
79
|
+
const policy = SeptumConfigSchema.parse(JSON.parse(policySource));
|
|
80
|
+
const existing = Object.entries(policy.domains).find(([name]) => domainNameKey(name) === domainNameKey(domainName))?.[1];
|
|
81
|
+
domainConfig.allowed_dependencies ??= existing?.allowed_dependencies ?? [];
|
|
82
|
+
domainConfig.forbidden_dependencies ??= existing?.forbidden_dependencies ?? [];
|
|
83
|
+
domainConfig.archetypes ??= existing?.archetypes ?? {};
|
|
84
|
+
domainConfig.description = args.description ?? existing?.description ?? domainConfig.description;
|
|
85
|
+
const diskClaims = Object.fromEntries(
|
|
86
|
+
Object.entries(policy.domains).filter(
|
|
87
|
+
([name, claim]) => domainNameKey(name) !== domainNameKey(domainName) && domainRootIdentity(claim.root, workspaceRoot) === proposed
|
|
88
|
+
)
|
|
89
|
+
);
|
|
90
|
+
assertUniqueDomainRoots({ ...diskClaims, [domainName]: domainConfig }, workspaceRoot);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const domainId = repo.runInTransaction(() => {
|
|
94
|
+
const id = repo.domains.upsertDomain(domainName, domainConfig, workspaceRoot);
|
|
95
|
+
const stored = repo.domains.getDomainByName(domainName)!;
|
|
96
|
+
if (policySource !== undefined) {
|
|
97
|
+
ConfigLoader.writeDomain(
|
|
98
|
+
workspaceRoot,
|
|
99
|
+
stored.name,
|
|
100
|
+
{
|
|
101
|
+
...domainConfig,
|
|
102
|
+
allowed_dependencies: JSON.parse(stored.allowed_deps_json),
|
|
103
|
+
forbidden_dependencies: JSON.parse(stored.forbidden_deps_json),
|
|
104
|
+
archetypes: JSON.parse(stored.archetypes_json),
|
|
105
|
+
},
|
|
106
|
+
policySource
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
repo.rebindFilesToDomain(stored.root_path || domainConfig.root, id);
|
|
110
|
+
return id;
|
|
111
|
+
}, true);
|
|
112
|
+
|
|
113
|
+
const stored = repo.domains.getDomainByName(domainName);
|
|
114
|
+
const canonicalName = stored?.name || domainName;
|
|
115
|
+
const finalConfig: ValidatedSeptumConfig["domains"][string] = {
|
|
116
|
+
root: stored?.root_path || domainConfig.root,
|
|
117
|
+
description: domainConfig.description,
|
|
118
|
+
allowed_dependencies: stored ? JSON.parse(stored.allowed_deps_json || "[]") : (domainConfig.allowed_dependencies || []),
|
|
119
|
+
forbidden_dependencies: stored ? JSON.parse(stored.forbidden_deps_json || "[]") : (domainConfig.forbidden_dependencies || []),
|
|
120
|
+
archetypes: stored ? JSON.parse(stored.archetypes_json || "{}") : (domainConfig.archetypes || {}),
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
let ingestionMetrics: IngestionMetrics | null = null;
|
|
124
|
+
if (args.ingest_now) {
|
|
125
|
+
const nextConfig: ValidatedSeptumConfig = {
|
|
126
|
+
...config,
|
|
127
|
+
domains: { ...config.domains, [canonicalName]: finalConfig },
|
|
128
|
+
};
|
|
129
|
+
const pipeline = new IngestionPipeline(repo, workspaceRoot);
|
|
130
|
+
ingestionMetrics = await pipeline.run(nextConfig, { signal });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
policyOwner: policySource === undefined ? "database" : "file",
|
|
135
|
+
domainId,
|
|
136
|
+
domain: canonicalName,
|
|
137
|
+
config: finalConfig,
|
|
138
|
+
ingestionMetrics,
|
|
139
|
+
conflictPending: repo.getMeta("sync_error_code") === "DOMAIN_ROOT_CONFLICT",
|
|
140
|
+
};
|
|
141
|
+
}
|
|
@@ -1,73 +1,103 @@
|
|
|
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
|
|
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
|
|
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
|
|
21
|
-
|
|
22
|
-
|
|
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
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
const
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
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 {
|
|
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
|
-
};
|
|
100
|
+
return SeptumConfigSchema.parse({});
|
|
71
101
|
}
|
|
72
102
|
|
|
73
103
|
public static loadFromRepository(repo: SeptumRepository): ValidatedSeptumConfig {
|
|
@@ -85,8 +115,6 @@ export class ConfigLoader {
|
|
|
85
115
|
}
|
|
86
116
|
|
|
87
117
|
if (typeof repo?.getMeta === "function") {
|
|
88
|
-
const features = repo.getMeta("features_json");
|
|
89
|
-
if (features) config.features = JSON.parse(features);
|
|
90
118
|
const settings = repo.getMeta("settings_json");
|
|
91
119
|
if (settings) Object.assign(config.settings, JSON.parse(settings));
|
|
92
120
|
}
|