@dimassetoid/septum-mcp 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +122 -0
  7. package/src/cli/commands/hook.ts +268 -0
  8. package/src/cli/commands/init.ts +553 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +41 -0
  11. package/src/cli/commands/topology.ts +161 -0
  12. package/src/cli/index.ts +167 -0
  13. package/src/cli/scaffold/harness-config.ts +621 -0
  14. package/src/cli/templates/hooks.ts +75 -0
  15. package/src/cli/templates/rules.ts +50 -0
  16. package/src/cli/templates/skill.ts +51 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +442 -0
  19. package/src/core/boundary/staged-auditor.ts +58 -0
  20. package/src/core/config/loader.ts +122 -0
  21. package/src/core/config/schema.ts +69 -0
  22. package/src/core/database/client.ts +60 -0
  23. package/src/core/database/repositories/dependency.repository.ts +712 -0
  24. package/src/core/database/repositories/domain.repository.ts +330 -0
  25. package/src/core/database/repositories/environment.repository.ts +207 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +508 -0
  29. package/src/core/database/repository.ts +303 -0
  30. package/src/core/database/schema.ts +154 -0
  31. package/src/core/discovery/topology-detector.ts +805 -0
  32. package/src/core/ingestion/hasher.ts +5 -0
  33. package/src/core/ingestion/pipeline.ts +623 -0
  34. package/src/core/parser/behavioral-analyzer.ts +119 -0
  35. package/src/core/parser/boundary-tracker.ts +443 -0
  36. package/src/core/parser/extractors/base.ts +67 -0
  37. package/src/core/parser/extractors/blade.ts +159 -0
  38. package/src/core/parser/extractors/csharp.ts +244 -0
  39. package/src/core/parser/extractors/django-semantic.ts +687 -0
  40. package/src/core/parser/extractors/elysia-semantic.ts +538 -0
  41. package/src/core/parser/extractors/express-semantic.ts +444 -0
  42. package/src/core/parser/extractors/fastapi-semantic.ts +736 -0
  43. package/src/core/parser/extractors/fastify-semantic.ts +774 -0
  44. package/src/core/parser/extractors/flask-semantic.ts +515 -0
  45. package/src/core/parser/extractors/frontend.ts +149 -0
  46. package/src/core/parser/extractors/go-semantic.ts +611 -0
  47. package/src/core/parser/extractors/go.ts +491 -0
  48. package/src/core/parser/extractors/hono-semantic.ts +567 -0
  49. package/src/core/parser/extractors/java.ts +225 -0
  50. package/src/core/parser/extractors/laravel-semantic.ts +1122 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +368 -0
  52. package/src/core/parser/extractors/nestjs-semantic.ts +543 -0
  53. package/src/core/parser/extractors/php.ts +569 -0
  54. package/src/core/parser/extractors/python.ts +498 -0
  55. package/src/core/parser/extractors/registry.ts +78 -0
  56. package/src/core/parser/extractors/ruby.ts +234 -0
  57. package/src/core/parser/extractors/rust.ts +286 -0
  58. package/src/core/parser/extractors/semantic-extractor.interface.ts +22 -0
  59. package/src/core/parser/extractors/symfony-semantic.ts +354 -0
  60. package/src/core/parser/extractors/typescript.ts +826 -0
  61. package/src/core/parser/language-capabilities.ts +71 -0
  62. package/src/core/parser/schema/providers/laravel-migration-provider.ts +216 -0
  63. package/src/core/parser/schema/providers/prisma-schema-provider.ts +90 -0
  64. package/src/core/parser/schema/schema-provider-registry.ts +43 -0
  65. package/src/core/parser/schema/schema-provider.interface.ts +33 -0
  66. package/src/core/parser/tree-sitter.ts +63 -0
  67. package/src/core/parser/wasm-assets.ts +25 -0
  68. package/src/core/parser/wasm-loader.ts +274 -0
  69. package/src/core/resolver/call-graph-tracer.ts +724 -0
  70. package/src/core/resolver/import-resolver.ts +437 -0
  71. package/src/core/resolver/module-resolver.ts +482 -0
  72. package/src/core/resolver/path-resolver.ts +200 -0
  73. package/src/core/resolver/symbol-locator.ts +276 -0
  74. package/src/core/resolver/symbol-reference.ts +53 -0
  75. package/src/core/resolver/vertical-slice-tracer.ts +366 -0
  76. package/src/core/resources/ignore.ts +123 -0
  77. package/src/core/resources/limits.ts +14 -0
  78. package/src/core/resources/source-files.ts +62 -0
  79. package/src/core/resources/work-queue.ts +74 -0
  80. package/src/core/session/session-manager.ts +107 -0
  81. package/src/core/telemetry/telemetry.ts +97 -0
  82. package/src/core/topology/environment-detector.ts +973 -0
  83. package/src/core/topology/types.ts +83 -0
  84. package/src/index.ts +21 -0
  85. package/src/mcp/schemas.ts +1105 -0
  86. package/src/mcp/server.ts +774 -0
  87. package/src/mcp/tools/boundary.ts +17 -0
  88. package/src/mcp/tools/check-boundary.ts +387 -0
  89. package/src/mcp/tools/domain.ts +40 -0
  90. package/src/mcp/tools/feature.ts +67 -0
  91. package/src/mcp/tools/get-domain-catalog.ts +226 -0
  92. package/src/mcp/tools/get-environment-topology.ts +138 -0
  93. package/src/mcp/tools/get-feature-context.ts +224 -0
  94. package/src/mcp/tools/get-symbol-hotspots.ts +54 -0
  95. package/src/mcp/tools/get-symbol-impact.ts +64 -0
  96. package/src/mcp/tools/get-symbol.ts +175 -0
  97. package/src/mcp/tools/locate-symbol.ts +196 -0
  98. package/src/mcp/tools/register-domain.ts +75 -0
  99. package/src/mcp/tools/register-feature.ts +110 -0
  100. package/src/mcp/tools/slice.ts +16 -0
  101. package/src/mcp/tools/symbol.ts +93 -0
  102. package/src/mcp/tools/trace-vertical-slice.ts +80 -0
  103. package/src/mcp/workspace-manager.ts +159 -0
  104. package/src/mcp/workspace-watcher.ts +202 -0
  105. package/src/types/index.ts +456 -0
  106. package/src/types/wasm.d.ts +4 -0
  107. package/src/utils/version-check.ts +209 -0
  108. package/src/version.ts +1 -0
@@ -0,0 +1,5 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export function computeContentHash(content: string): string {
4
+ return createHash("sha256").update(content, "utf8").digest("hex");
5
+ }
@@ -0,0 +1,623 @@
1
+ import { RESOLVER_REVISION } from "../resolver/import-resolver.ts";
2
+ import { shouldIgnoreSourcePath } from "../resources/ignore.ts";
3
+ import { RESOURCE_LIMITS } from "../resources/limits.ts";
4
+ import { readSourceFile, SourceFileLimitError, collectSourceSkips, type SkippedSourceFile, type SourceReadFingerprint } from "../resources/source-files.ts";
5
+ import { existsSync, readdirSync, readFileSync, statSync, lstatSync, realpathSync } from "node:fs";
6
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
7
+ import { isPathContained, resolveWorkspaceRoot } from "../resolver/path-resolver.ts";
8
+ import type { ParsedFileAST } from "../../types/index.ts";
9
+ import type { ValidatedSeptumConfig } from "../config/schema.ts";
10
+ import type { SeptumRepository } from "../database/repository.ts";
11
+ import { detectArchetype } from "../parser/extractors/base.ts";
12
+ import { SemanticSliceExtractorRegistry } from "../parser/extractors/registry.ts";
13
+ import { TopologyDetector } from "../discovery/topology-detector.ts";
14
+ import { PARSER_REVISION } from "../parser/language-capabilities.ts";
15
+ import { ASTParserEngine } from "../parser/tree-sitter.ts";
16
+ import { CallGraphTracer } from "../resolver/call-graph-tracer.ts";
17
+ import { ModuleResolver } from "../resolver/module-resolver.ts";
18
+ import { computeContentHash } from "./hasher.ts";
19
+
20
+ export interface IngestionMetrics {
21
+ domains_processed: number;
22
+ files_scanned: number;
23
+ files_updated: number;
24
+ files_skipped: number;
25
+ symbols_indexed: number;
26
+ dependencies_indexed: number;
27
+ duration_ms: number;
28
+ }
29
+
30
+ export class IngestionPipeline {
31
+ private repo: SeptumRepository;
32
+ private parserEngine: ASTParserEngine;
33
+ private customWorkspaceRoot?: string;
34
+
35
+ constructor(repo: SeptumRepository, workspaceRoot?: string) {
36
+ this.repo = repo;
37
+ this.parserEngine = new ASTParserEngine();
38
+ if (workspaceRoot) {
39
+ this.customWorkspaceRoot = resolve(workspaceRoot);
40
+ }
41
+ }
42
+
43
+ public async run(config: ValidatedSeptumConfig, options: { verifyContent?: boolean; signal?: AbortSignal } = {}): Promise<IngestionMetrics> {
44
+ this.repo.setMeta("workspace_root", this.resolveWorkspaceRoot(config, Object.values(config.domains)[0]?.root ?? "."));
45
+ this.repo.setMeta("resolver_revision", RESOLVER_REVISION);
46
+ this.repo.setMeta("sync_state", "running");
47
+ try {
48
+ let result: IngestionMetrics | undefined;
49
+ for (let attempt = 0; attempt < 2; attempt++) {
50
+ try { result = await this.runSync(config, options); break; }
51
+ catch (error) {
52
+ if (attempt || !(error instanceof Error) || !error.message.startsWith("Source changed during synchronization:")) throw error;
53
+ options.signal?.throwIfAborted();
54
+ }
55
+ }
56
+ this.repo.setMeta("sync_state", "complete");
57
+ this.repo.setMeta("sync_error", "");
58
+ return result!;
59
+ } catch (error) {
60
+ this.repo.setMeta("sync_state", "error");
61
+ this.repo.setMeta("sync_error", String(error));
62
+ throw error;
63
+ }
64
+ }
65
+
66
+ private async runSync(config: ValidatedSeptumConfig, options: { verifyContent?: boolean; signal?: AbortSignal }): Promise<IngestionMetrics> {
67
+ this.ensureParserRevision();
68
+ const startTime = performance.now();
69
+ let filesScanned = 0;
70
+ let filesUpdated = 0;
71
+ let filesSkipped = 0;
72
+ let symbolsIndexed = 0;
73
+ let dependenciesIndexed = 0;
74
+ const unsupportedFiles: string[] = [];
75
+ const skippedFiles: SkippedSourceFile[] = [];
76
+ let removedFiles = 0;
77
+
78
+ let domainNames = Object.keys(config.domains);
79
+ const projectRoot = this.customWorkspaceRoot || resolveWorkspaceRoot();
80
+
81
+ // Auto-discovery mode if no domains explicitly declared in config
82
+ if (domainNames.length === 0) {
83
+ const discovered = this.autoDiscoverDomains(projectRoot);
84
+ for (const [dName, dCfg] of Object.entries(discovered)) {
85
+ config.domains[dName] = {
86
+ root: dCfg.root,
87
+ description: dCfg.description,
88
+ allowed_dependencies: dCfg.allowed_dependencies || [],
89
+ forbidden_dependencies: dCfg.forbidden_dependencies || [],
90
+ archetypes: dCfg.archetypes || {},
91
+ };
92
+ }
93
+ domainNames = Object.keys(config.domains);
94
+ }
95
+ const inventory = this.sourceInventory(projectRoot, config.settings.ignore_patterns, options.signal);
96
+
97
+ const existingFilesMap = new Map<string, import("../../types/index.ts").FileRecord>();
98
+ for (const f of this.repo.getAllFiles()) {
99
+ existingFilesMap.set(f.path, f);
100
+ }
101
+
102
+ for (const domainName of domainNames) {
103
+ const domainCfg = config.domains[domainName];
104
+ const domainId = this.repo.upsertDomain(domainName, domainCfg);
105
+ const workspaceRoot = this.resolveWorkspaceRoot(config, domainCfg.root);
106
+ // SV-02: Enforce workspace containment during ingestion (reject traversal/symlink escape)
107
+ if (!isPathContained(domainCfg.root, workspaceRoot)) {
108
+ throw new Error(`Domain root '${domainCfg.root}' for domain '${domainName}' escapes workspace boundary '${workspaceRoot}'.`);
109
+ }
110
+ const absDomainRoot = resolve(workspaceRoot, domainCfg.root);
111
+
112
+ try {
113
+ const rootStat = statSync(absDomainRoot);
114
+ if (!rootStat.isDirectory()) {
115
+ throw new Error(`Domain root '${domainCfg.root}' is not a directory.`);
116
+ }
117
+ } catch (err: any) {
118
+ if (err?.code === "ENOENT") {
119
+ removedFiles += this.repo.getAllFiles().filter(file => file.domain_id === domainId).length;
120
+ this.repo.files.deleteFilesNotInPaths(domainId, []);
121
+ if (removedFiles) this.repo.setMeta("slices_dirty", "1");
122
+ continue;
123
+ }
124
+ // SV-01: Permission or I/O failure (EACCES, EPERM, EIO). Do NOT prune, propagate error!
125
+ throw new Error(`Failed to access domain root '${domainCfg.root}' for domain '${domainName}': ${err.message || err}`);
126
+ }
127
+
128
+ const childDomainRoots = domainNames
129
+ .filter(name => name !== domainName)
130
+ .map(name => relative(workspaceRoot, resolve(workspaceRoot, config.domains[name].root)).replace(/\\/g, "/"))
131
+ .filter(child => {
132
+ const fromParent = relative(absDomainRoot, resolve(workspaceRoot, child)).replace(/\\/g, "/");
133
+ return fromParent !== "" && fromParent !== ".." && !fromParent.startsWith("../") && !isAbsolute(fromParent);
134
+ });
135
+
136
+ const collectedFiles = this.collectFiles(
137
+ absDomainRoot,
138
+ workspaceRoot,
139
+ config.settings.ignore_patterns,
140
+ childDomainRoots,
141
+ options.signal
142
+ );
143
+ const activeRelPaths = new Set<string>();
144
+
145
+ const pendingMetadataUpdates: Array<{
146
+ id: number;
147
+ mtimeMs: number;
148
+ sizeBytes: number;
149
+ file: import("../../types/index.ts").FileRecord;
150
+ archetype: ReturnType<typeof detectArchetype>;
151
+ }> = [];
152
+
153
+ const pendingUpdates: Array<{
154
+ fullPath: string;
155
+ relPath: string;
156
+ contentHash: string;
157
+ lineCount: number;
158
+ archetype: ReturnType<typeof detectArchetype>;
159
+ mtimeMs: number;
160
+ sizeBytes: number;
161
+ ast: ParsedFileAST;
162
+ }> = [];
163
+
164
+ let batchBytes = 0;
165
+ const commitBatch = () => {
166
+ for (const item of pendingUpdates) {
167
+ let currentHash: string | undefined;
168
+ try { currentHash = existsSync(item.fullPath) ? computeContentHash(readSourceFile(item.fullPath)) : undefined; }
169
+ catch (error: any) {
170
+ if (error?.code !== "ENOENT") throw error;
171
+ }
172
+ if (currentHash !== item.contentHash) {
173
+ throw new Error(`Source changed during synchronization: '${item.relPath}'. Run sync again after the file stops changing.`);
174
+ }
175
+ }
176
+ this.repo.runInTransaction(() => {
177
+ for (const meta of pendingMetadataUpdates) {
178
+ if (meta.file.archetype !== meta.archetype) {
179
+ this.repo.upsertFile(domainId, meta.file.path, meta.archetype, meta.file.content_hash, meta.file.line_count, meta.mtimeMs, meta.sizeBytes);
180
+ this.repo.setMeta("slices_dirty", "1");
181
+ } else this.repo.updateFileMetadataOnly(meta.id, meta.mtimeMs, meta.sizeBytes);
182
+ }
183
+
184
+ if (pendingUpdates.length) this.repo.setMeta("slices_dirty", "1");
185
+ for (const item of pendingUpdates) {
186
+ const fileId = this.repo.upsertFile(
187
+ domainId,
188
+ item.relPath,
189
+ item.archetype,
190
+ item.contentHash,
191
+ item.lineCount,
192
+ item.mtimeMs,
193
+ item.sizeBytes
194
+ );
195
+
196
+ this.repo.replaceFileSymbols(fileId, item.ast.symbols);
197
+ this.repo.replaceFileDependencies(fileId, item.ast.dependencies);
198
+
199
+ symbolsIndexed += item.ast.symbols.length;
200
+ dependenciesIndexed += item.ast.dependencies.length;
201
+ }
202
+
203
+ });
204
+ pendingUpdates.length = 0;
205
+ pendingMetadataUpdates.length = 0;
206
+ batchBytes = 0;
207
+ };
208
+
209
+ for (const { fullPath, relPath } of collectedFiles) {
210
+ options.signal?.throwIfAborted();
211
+ if (pendingMetadataUpdates.length >= RESOURCE_LIMITS.batchFiles) commitBatch();
212
+ filesScanned++;
213
+ if (filesScanned % RESOURCE_LIMITS.batchFiles === 0) { await new Promise<void>(done => setTimeout(done, 0)); options.signal?.throwIfAborted(); }
214
+ activeRelPaths.add(relPath);
215
+
216
+ let stat;
217
+ try {
218
+ stat = statSync(fullPath);
219
+ } catch (error: any) {
220
+ if (error?.code === "ENOENT") continue;
221
+ throw new Error(`Failed to inspect source '${relPath}': ${error?.message || error}`);
222
+ }
223
+
224
+ const mtimeMs = stat.mtimeMs;
225
+ const sizeBytes = stat.size;
226
+ const existingFile = existingFilesMap.get(relPath);
227
+
228
+ // Reuse indexed content only after verifying its hash.
229
+ if (sizeBytes > RESOURCE_LIMITS.sourceBytes) {
230
+ skippedFiles.push({path: relPath, reason: "file_too_large"});
231
+ if (existingFile) removedFiles++;
232
+ this.repo.deleteFileByPath(relPath);
233
+ this.repo.setMeta("slices_dirty", "1");
234
+ continue;
235
+ }
236
+ if (pendingUpdates.length >= RESOURCE_LIMITS.batchFiles || (batchBytes + sizeBytes > RESOURCE_LIMITS.batchBytes && pendingUpdates.length > 0)) { commitBatch(); await new Promise<void>(done => setTimeout(done, 0)); options.signal?.throwIfAborted(); }
237
+ let content: string;
238
+ try { content = readSourceFile(fullPath); }
239
+ catch (error) {
240
+ if (!(error instanceof SourceFileLimitError)) throw error;
241
+ skippedFiles.push({path: relPath, reason: "file_too_large"});
242
+ if (existingFile) removedFiles++;
243
+ this.repo.deleteFileByPath(relPath);
244
+ this.repo.setMeta("slices_dirty", "1");
245
+ continue;
246
+ }
247
+ const currentHash = computeContentHash(content);
248
+
249
+ if (
250
+ existingFile &&
251
+ existingFile.domain_id === domainId &&
252
+ existingFile.content_hash === currentHash
253
+ ) {
254
+ // Content identical despite mtime bump (e.g. touch) - queue metadata update for batch transaction
255
+ pendingMetadataUpdates.push({ id: existingFile.id, mtimeMs, sizeBytes, file: existingFile, archetype: detectArchetype(relPath, domainCfg.archetypes ?? {}) });
256
+ filesSkipped++;
257
+ continue;
258
+ }
259
+
260
+ const lineCount = content.split("\n").length;
261
+ const archetype = detectArchetype(relPath, domainCfg.archetypes ?? {});
262
+ const ast = await this.parserEngine.parseFile(fullPath, content);
263
+ if (ast.status === "unsupported") {
264
+ unsupportedFiles.push(relPath);
265
+ this.repo.deleteFileByPath(relPath);
266
+ this.repo.setMeta("slices_dirty", "1");
267
+ continue;
268
+ }
269
+ if (ast.status === "degraded") throw new Error(`Cannot reliably index '${relPath}': parser is degraded. ${ast.diagnostics?.map(d => `${d.code}: ${d.message}`).join("; ") ?? ""}`);
270
+
271
+ filesUpdated++;
272
+ batchBytes += sizeBytes;
273
+ pendingUpdates.push({
274
+ fullPath,
275
+ relPath,
276
+ contentHash: currentHash,
277
+ lineCount,
278
+ archetype,
279
+ mtimeMs,
280
+ sizeBytes,
281
+ ast,
282
+ });
283
+ }
284
+
285
+ commitBatch();
286
+ this.repo.runInTransaction(() => {
287
+ // State Reconciliation: Prune deleted files from DB using pre-loaded existingFilesMap
288
+ for (const [existingPath, existingRecord] of existingFilesMap.entries()) {
289
+ if (existingRecord.domain_id === domainId && !activeRelPaths.has(existingPath)) {
290
+ removedFiles++;
291
+ this.repo.setMeta("slices_dirty", "1");
292
+ this.repo.deleteFileByPath(existingPath);
293
+ existingFilesMap.delete(existingPath);
294
+ }
295
+ }
296
+ });
297
+ }
298
+
299
+ options.signal?.throwIfAborted();
300
+ const topologyInputs = ["package.json", "composer.json", "nest-cli.json", "go.mod", "artisan", "tsconfig.json"]
301
+ .map(file => { const target = join(projectRoot, file); return existsSync(target) ? readSourceFile(target) : ""; });
302
+ const semanticRevision = computeContentHash(JSON.stringify([config.domains, topologyInputs]));
303
+ // Membership covers newly added semantic files outside registered domains.
304
+ const inventoryRevision = computeContentHash(JSON.stringify(inventory));
305
+ const priorInputs: SourceReadFingerprint[] = JSON.parse(this.repo.getMeta("semantic_inputs") || "[]");
306
+ let semanticInputChanged = false;
307
+ for (let index = 0; index < priorInputs.length; index++) {
308
+ if (index % RESOURCE_LIMITS.batchFiles === 0) { await new Promise<void>(done => setTimeout(done, 0)); options.signal?.throwIfAborted(); }
309
+ const input = priorInputs[index];
310
+ const file = resolve(projectRoot, input.path);
311
+ if (!existsSync(file)) { semanticInputChanged = true; break; }
312
+ const stat = statSync(file);
313
+ if (stat.size !== input.size || stat.mtimeMs !== input.mtime) { semanticInputChanged = true; break; }
314
+ if (!options.verifyContent) continue;
315
+ try { semanticInputChanged = computeContentHash(readSourceFile(file)) !== input.hash; }
316
+ catch (error) { if (error instanceof SourceFileLimitError) semanticInputChanged = input.hash !== "file_too_large"; else throw error; }
317
+ if (semanticInputChanged) break;
318
+ }
319
+ const extractorRevision = "3"; // Bump when extractor or inferred-chain semantics change.
320
+ if (this.repo.getMeta("semantic_extractor_revision") !== extractorRevision || this.repo.getMeta("semantic_inventory") !== inventoryRevision || semanticInputChanged || filesUpdated > 0 || removedFiles > 0 || this.repo.getMeta("slices_dirty") === "1" || this.repo.getMeta("semantic_revision") !== semanticRevision) {
321
+ const extracted = await collectSourceSkips(projectRoot, async () => {
322
+ const detectedTopology = TopologyDetector.detect(projectRoot);
323
+ const semanticSlices = await SemanticSliceExtractorRegistry.extractAllSlices(projectRoot, detectedTopology.framework, undefined, options.signal);
324
+ return semanticSlices.length > 0 ? semanticSlices : new CallGraphTracer(this.repo, projectRoot).traceAllSlices();
325
+ });
326
+ options.signal?.throwIfAborted();
327
+ if (extracted.skipped.length) {
328
+ this.repo.setMeta("skipped_files", JSON.stringify([...skippedFiles,...extracted.skipped]));
329
+ this.repo.setMeta("slices_dirty", "1");
330
+ throw new Error("Semantic extraction incomplete: source read limit exceeded.");
331
+ }
332
+ skippedFiles.push(...extracted.skipped);
333
+ this.repo.runInTransaction(() => {
334
+ this.repo.clearVerticalSlices();
335
+ for (const slice of extracted.value) this.repo.upsertVerticalSlice(slice);
336
+ this.repo.setMeta("slices_dirty", "");
337
+ this.repo.setMeta("semantic_revision", semanticRevision);
338
+ this.repo.setMeta("semantic_extractor_revision", extractorRevision);
339
+ this.repo.setMeta("semantic_inventory", inventoryRevision);
340
+ this.repo.setMeta("semantic_inputs", JSON.stringify(extracted.inputs));
341
+ this.repo.setMeta("semantic_skipped_files", JSON.stringify(extracted.skipped));
342
+ });
343
+ }
344
+
345
+ skippedFiles.push(...JSON.parse(this.repo.getMeta("semantic_skipped_files") || "[]"));
346
+ if (JSON.stringify(inventory) !== JSON.stringify(this.sourceInventory(projectRoot, config.settings.ignore_patterns, options.signal))) {
347
+ throw new Error("Source changed during synchronization: workspace inventory changed. Run sync again after the files stop changing.");
348
+ }
349
+ const durationMs = Math.round(performance.now() - startTime);
350
+
351
+ // Identify uncovered eligible source files outside registered domains
352
+ const indexedPaths = new Set(this.repo.getAllFiles().map((file) => file.path));
353
+ const allWorkspaceFiles = this.collectFiles(projectRoot, projectRoot, config.settings.ignore_patterns, [], options.signal);
354
+ const unsupportedSet = new Set(unsupportedFiles);
355
+ const skippedSet = new Set(skippedFiles.map((file) => file.path));
356
+ const uncoveredFiles = allWorkspaceFiles
357
+ .map((file) => file.relPath)
358
+ .filter((rel) => !indexedPaths.has(rel) && !unsupportedSet.has(rel) && !skippedSet.has(rel));
359
+
360
+ // Update SSOT repo_meta watermark
361
+ this.repo.runInTransaction(() => {
362
+ this.repo.setMeta("last_sync", new Date().toISOString());
363
+ this.repo.setMeta("sync_duration_ms", String(durationMs));
364
+ this.repo.setMeta("files_scanned", String(filesScanned));
365
+ this.repo.setMeta("files_updated", String(filesUpdated));
366
+ this.repo.setMeta("symbols_indexed", String(symbolsIndexed));
367
+ this.repo.setMeta("dependencies_indexed", String(dependenciesIndexed));
368
+ this.repo.setMeta("unsupported_files", JSON.stringify(unsupportedFiles));
369
+ this.repo.setMeta("skipped_files", JSON.stringify([...new Map(skippedFiles.map(file => [file.path, file])).values()]));
370
+ this.repo.setMeta("uncovered_files", JSON.stringify(uncoveredFiles));
371
+ });
372
+
373
+ this.repo.checkpoint();
374
+
375
+ return {
376
+ domains_processed: domainNames.length,
377
+ files_scanned: filesScanned,
378
+ files_updated: filesUpdated,
379
+ files_skipped: filesSkipped,
380
+ symbols_indexed: symbolsIndexed,
381
+ dependencies_indexed: dependenciesIndexed,
382
+ duration_ms: durationMs,
383
+ };
384
+ }
385
+
386
+ public autoDiscoverDomains(projectRoot: string): Record<string, import("../../types/index.ts").DomainConfig> {
387
+ return TopologyDetector.detect(projectRoot).domains;
388
+ }
389
+
390
+ private sourceInventory(root: string, ignorePatterns: string[], signal?: AbortSignal): string[] {
391
+ return this.collectFiles(root, root, ignorePatterns, [], signal).map(({fullPath, relPath}) => {
392
+ const stat = statSync(fullPath);
393
+ let hash: string;
394
+ try { hash = computeContentHash(readSourceFile(fullPath)); }
395
+ catch (error) {
396
+ if (!(error instanceof SourceFileLimitError)) throw error;
397
+ hash = `file_too_large:${stat.size}:${stat.mtimeMs}`;
398
+ }
399
+ return `${relPath}:${hash}`;
400
+ }).sort();
401
+ }
402
+
403
+ private collectFiles(
404
+ dir: string,
405
+ workspaceRoot: string,
406
+ ignorePatterns: string[],
407
+ childDomainRoots: string[] = [],
408
+ signal?: AbortSignal
409
+ ): Array<{ fullPath: string; relPath: string }> {
410
+ const results: Array<{ fullPath: string; relPath: string }> = [];
411
+
412
+ // SV-02: Check if initial dir itself is an escaping symlink
413
+ try {
414
+ const dirLstat = lstatSync(dir);
415
+ if (dirLstat.isSymbolicLink()) {
416
+ const real = realpathSync(dir);
417
+ if (!isPathContained(real, workspaceRoot)) {
418
+ throw new Error(`Directory '${dir}' is a symlink escaping workspace boundary '${workspaceRoot}'.`);
419
+ }
420
+ }
421
+ } catch (err: any) {
422
+ if (err?.code !== "ENOENT") throw err;
423
+ }
424
+
425
+ const walk = (currentDir: string) => {
426
+ signal?.throwIfAborted();
427
+ let entries: string[] = [];
428
+ try {
429
+ entries = readdirSync(currentDir);
430
+ } catch (err: any) {
431
+ // SV-01: Do not swallow permission/IO errors; propagate so pipeline reports incomplete/error
432
+ if (err?.code === "ENOENT") {
433
+ return;
434
+ }
435
+ throw new Error(`Failed to read directory '${currentDir}': ${err.message || err}`);
436
+ }
437
+
438
+ for (const entry of entries) {
439
+ signal?.throwIfAborted();
440
+ const fullPath = join(currentDir, entry);
441
+ const relPath = relative(workspaceRoot, fullPath).replace(/\\/g, "/");
442
+
443
+ if (shouldIgnoreSourcePath(relPath, ignorePatterns)) {
444
+ continue;
445
+ }
446
+
447
+ if (childDomainRoots.some((child) => relPath === child || relPath.startsWith(child + "/"))) {
448
+ continue;
449
+ }
450
+
451
+ try {
452
+ const stat = lstatSync(fullPath);
453
+ if (stat.isSymbolicLink()) {
454
+ try {
455
+ const real = realpathSync(fullPath);
456
+ if (!isPathContained(real, workspaceRoot)) {
457
+ continue;
458
+ }
459
+ const targetStat = statSync(real);
460
+ if (targetStat.isDirectory()) {
461
+ continue;
462
+ } else if (targetStat.isFile() && this.isSourceFile(real)) {
463
+ results.push({ fullPath, relPath });
464
+ }
465
+ } catch {
466
+ continue;
467
+ }
468
+ continue;
469
+ }
470
+
471
+ if (stat.isDirectory()) {
472
+ walk(fullPath);
473
+ } else if (stat.isFile() && this.isSourceFile(fullPath)) {
474
+ results.push({ fullPath, relPath });
475
+ }
476
+ } catch (err: any) {
477
+ if (err?.code === "ENOENT") {
478
+ continue;
479
+ }
480
+ throw new Error(`Failed to stat path '${fullPath}': ${err.message || err}`);
481
+ }
482
+ }
483
+ };
484
+
485
+ walk(dir);
486
+ return results;
487
+ }
488
+
489
+ private resolveWorkspaceRoot(config: ValidatedSeptumConfig, domainRoot: string): string {
490
+ if (this.customWorkspaceRoot) {
491
+ return this.customWorkspaceRoot;
492
+ }
493
+ const settings = config.settings as Record<string, unknown> | undefined;
494
+ if (typeof settings?.workspace_root === "string" && settings.workspace_root.trim()) {
495
+ return resolve(settings.workspace_root);
496
+ }
497
+ if (config.settings.db_path && config.settings.db_path !== ":memory:") {
498
+ const dbDir = dirname(resolve(config.settings.db_path));
499
+ const candidate = basename(dbDir) === ".septum" ? dirname(dbDir) : dbDir;
500
+ const absDomainRoot = isAbsolute(domainRoot) ? domainRoot : resolve(candidate, domainRoot);
501
+ if (absDomainRoot.startsWith(candidate)) {
502
+ return candidate;
503
+ }
504
+ }
505
+ return resolveWorkspaceRoot();
506
+ }
507
+
508
+
509
+ private isSourceFile(path: string): boolean {
510
+ return ASTParserEngine.isSourceFile(path);
511
+ }
512
+
513
+ private ensureParserRevision(): void {
514
+ const revision = PARSER_REVISION;
515
+ if (this.repo.getMeta("parser_revision") === revision) return;
516
+ this.repo.runInTransaction(() => {
517
+ for (const file of this.repo.getAllFiles()) {
518
+ this.repo.upsertFile(file.domain_id, file.path, file.archetype, "", file.line_count, -1, -1);
519
+ }
520
+ this.repo.clearVerticalSlices();
521
+ this.repo.setMeta("parser_revision", revision);
522
+ });
523
+ }
524
+
525
+ /**
526
+ * JIT single-file ingestion: quickly verifies and updates a single file's AST,
527
+ * symbols, and dependencies in SQLite if its mtime or content hash has changed.
528
+ */
529
+ public async ingestFile(targetFilePath: string, config: ValidatedSeptumConfig): Promise<boolean> {
530
+ this.ensureParserRevision();
531
+ const fullPath = resolve(targetFilePath);
532
+ if (!existsSync(fullPath)) return false;
533
+
534
+ let stat;
535
+ try {
536
+ stat = statSync(fullPath);
537
+ if (!stat.isFile() || !this.isSourceFile(fullPath)) return false;
538
+ } catch {
539
+ return false;
540
+ }
541
+
542
+ const mtimeMs = stat.mtimeMs;
543
+ const sizeBytes = stat.size;
544
+
545
+ const projectRoot = this.customWorkspaceRoot || resolveWorkspaceRoot();
546
+ const relPath = relative(projectRoot, fullPath).replace(/\\/g, "/");
547
+
548
+ if (shouldIgnoreSourcePath(relPath, config.settings.ignore_patterns ?? [])) {
549
+ return false;
550
+ }
551
+
552
+ const targetDomainName = new ModuleResolver(projectRoot, this.repo).resolveSourceDomain(fullPath, config);
553
+ const targetDomainCfg = targetDomainName ? config.domains[targetDomainName] : null;
554
+
555
+ if (!targetDomainName || !targetDomainCfg) {
556
+ return false;
557
+ }
558
+
559
+ const domainId = this.repo.upsertDomain(targetDomainName, targetDomainCfg);
560
+ const existingFile = this.repo.getFileByPath(relPath);
561
+
562
+ let content: string;
563
+ try { content = readSourceFile(fullPath); }
564
+ catch (error) {
565
+ if (!(error instanceof SourceFileLimitError)) throw error;
566
+ this.repo.runInTransaction(() => {
567
+ this.repo.deleteFileByPath(relPath);
568
+ this.repo.clearVerticalSlices();
569
+ this.repo.setMeta("slices_dirty", "1");
570
+ const skipped: SkippedSourceFile[] = JSON.parse(this.repo.getMeta("skipped_files") || "[]");
571
+ this.repo.setMeta("skipped_files", JSON.stringify([...skipped.filter(file => file.path !== relPath), {path: relPath, reason: "file_too_large"}]));
572
+ });
573
+ return false;
574
+ }
575
+ const currentHash = computeContentHash(content);
576
+ const archetype = detectArchetype(relPath, targetDomainCfg.archetypes ?? {});
577
+
578
+ // Tier 2: Hash verification
579
+ if (existingFile && existingFile.domain_id === domainId && existingFile.content_hash === currentHash) {
580
+ if (existingFile.archetype !== archetype) {
581
+ this.repo.runInTransaction(() => {
582
+ this.repo.upsertFile(domainId, relPath, archetype, currentHash, existingFile.line_count, mtimeMs, sizeBytes);
583
+ this.repo.setMeta("slices_dirty", "1");
584
+ });
585
+ } else this.repo.updateFileMetadataOnly(existingFile.id, mtimeMs, sizeBytes);
586
+ return false;
587
+ }
588
+
589
+ const lineCount = content.split("\n").length;
590
+ const ast = await this.parserEngine.parseFile(fullPath, content);
591
+ if (ast.status === "unsupported") {
592
+ this.repo.deleteFileByPath(relPath);
593
+ const unsupported = new Set<string>(JSON.parse(this.repo.getMeta("unsupported_files") || "[]"));
594
+ unsupported.add(relPath);
595
+ this.repo.setMeta("unsupported_files", JSON.stringify([...unsupported]));
596
+ return false;
597
+ }
598
+ if (ast.status === "degraded") throw new Error(`Cannot reliably index '${relPath}': parser is degraded. ${ast.diagnostics?.map(d => `${d.code}: ${d.message}`).join("; ") ?? ""}`);
599
+
600
+ this.repo.runInTransaction(() => {
601
+ const fileId = this.repo.upsertFile(
602
+ domainId,
603
+ relPath,
604
+ archetype,
605
+ currentHash,
606
+ lineCount,
607
+ mtimeMs,
608
+ sizeBytes
609
+ );
610
+ this.repo.replaceFileSymbols(fileId, ast.symbols);
611
+ this.repo.replaceFileDependencies(fileId, ast.dependencies);
612
+ this.repo.clearVerticalSlices();
613
+ this.repo.setMeta("slices_dirty", "1");
614
+ const skipped: SkippedSourceFile[] = JSON.parse(this.repo.getMeta("skipped_files") || "[]");
615
+ this.repo.setMeta("skipped_files", JSON.stringify(skipped.filter(file => file.path !== relPath)));
616
+ const unsupported = JSON.parse(this.repo.getMeta("unsupported_files") || "[]") as string[];
617
+ this.repo.setMeta("unsupported_files", JSON.stringify(unsupported.filter(path => path !== relPath)));
618
+ });
619
+
620
+ return true;
621
+ }
622
+ }
623
+