@dimassetoid/septum-mcp 0.0.0-stage → 0.3.0

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