@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.
Files changed (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -1,21 +1,32 @@
1
+ import { scanSourceFiles, type SourceInventory } from "../resources/source-inventory.ts";
2
+ import { rebuildSliceCatalog } from "../resolver/slice-catalog.ts";
3
+ import { SEMANTIC_FINGERPRINT } from "../parser/semantic-revision.ts";
1
4
  import { RESOLVER_REVISION } from "../resolver/import-resolver.ts";
5
+ import { sourceObservationsCurrent } from "../resources/source-files.ts";
2
6
  import { shouldIgnoreSourcePath } from "../resources/ignore.ts";
3
7
  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";
8
+ import { readSourceFile, SourceFileLimitError, type SkippedSourceFile, type SourceReadFingerprint } from "../resources/source-files.ts";
9
+ import { existsSync, statSync, type Stats } from "node:fs";
6
10
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
7
11
  import { isPathContained, resolveWorkspaceRoot } from "../resolver/path-resolver.ts";
8
- import type { ParsedFileAST } from "../../types/index.ts";
12
+ import type { ArchetypeKind, ParsedFileAST } from "../../types/index.ts";
9
13
  import type { ValidatedSeptumConfig } from "../config/schema.ts";
10
14
  import type { SeptumRepository } from "../database/repository.ts";
11
15
  import { detectArchetype } from "../parser/extractors/base.ts";
12
- import { SemanticSliceExtractorRegistry } from "../parser/extractors/registry.ts";
13
16
  import { TopologyDetector } from "../discovery/topology-detector.ts";
14
- import { PARSER_REVISION } from "../parser/language-capabilities.ts";
17
+ import { PARSER_FINGERPRINT } from "../parser/language-capabilities.ts";
15
18
  import { ASTParserEngine } from "../parser/tree-sitter.ts";
16
- import { CallGraphTracer } from "../resolver/call-graph-tracer.ts";
17
19
  import { ModuleResolver } from "../resolver/module-resolver.ts";
18
20
  import { computeContentHash } from "./hasher.ts";
21
+ import { assertUniqueDomainRoots, domainNameKey, DomainRootConflictError } from "../config/domain-ownership.ts";
22
+ import { ConfigLoader } from "../config/loader.ts";
23
+ import { SeptumTelemetry } from "../telemetry/telemetry.ts";
24
+
25
+ export type IngestionProgressEvent =
26
+ | { phase: "scanning"; status: "start" | "done"; total: number }
27
+ | { phase: "parsing"; status: "progress" | "done"; processed: number; total: number }
28
+ | { phase: "resolving"; status: "done"; symbols: number; dependencies: number }
29
+ | { phase: "linking"; status: "start" | "done"; slices: number };
19
30
 
20
31
  export interface IngestionMetrics {
21
32
  domains_processed: number;
@@ -24,10 +35,21 @@ export interface IngestionMetrics {
24
35
  files_skipped: number;
25
36
  symbols_indexed: number;
26
37
  dependencies_indexed: number;
38
+ /** Indexed-file parse attempts across this sync, including recovered retries; excludes semantic extraction. */
39
+ parser_invocations: number;
27
40
  duration_ms: number;
41
+ stage_timings_ms?: {
42
+ scan_ms: number;
43
+ parse_ms: number;
44
+ commit_ms: number;
45
+ slice_ms: number;
46
+ };
28
47
  }
29
48
 
30
49
  export class IngestionPipeline {
50
+ // Only trust metadata already content-verified by this pipeline instance.
51
+ // ctime catches edits which deliberately preserve size and mtime.
52
+ private verifiedFiles = new Map<string, { ctime: number; hash: string }>();
31
53
  private repo: SeptumRepository;
32
54
  private parserEngine: ASTParserEngine;
33
55
  private customWorkspaceRoot?: string;
@@ -40,14 +62,25 @@ export class IngestionPipeline {
40
62
  }
41
63
  }
42
64
 
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 ?? "."));
65
+ public async run(
66
+ config: ValidatedSeptumConfig,
67
+ options: {
68
+ verifyContent?: boolean;
69
+ rebuild?: boolean;
70
+ signal?: AbortSignal;
71
+ onProgress?: (info: IngestionProgressEvent) => void;
72
+ } = {}
73
+ ): Promise<IngestionMetrics> {
74
+ const workspaceRoot = this.resolveWorkspaceRoot(config, Object.values(config.domains)[0]?.root ?? ".");
75
+ this.repo.setMeta("workspace_root", workspaceRoot);
76
+ this.repo.setMeta("settings_json", JSON.stringify(config.settings));
45
77
  this.repo.setMeta("resolver_revision", RESOLVER_REVISION);
46
78
  this.repo.setMeta("sync_state", "running");
79
+ const work = { parserInvocations: 0 };
47
80
  try {
48
81
  let result: IngestionMetrics | undefined;
49
82
  for (let attempt = 0; attempt < 2; attempt++) {
50
- try { result = await this.runSync(config, options); break; }
83
+ try { result = await this.runSync(config, options, work); break; }
51
84
  catch (error) {
52
85
  if (attempt || !(error instanceof Error) || !error.message.startsWith("Source changed during synchronization:")) throw error;
53
86
  options.signal?.throwIfAborted();
@@ -55,17 +88,59 @@ export class IngestionPipeline {
55
88
  }
56
89
  this.repo.setMeta("sync_state", "complete");
57
90
  this.repo.setMeta("sync_error", "");
91
+ this.repo.setMeta("sync_error_code", "");
92
+ SeptumTelemetry.recordSystemEvent({
93
+ level: "INFO",
94
+ component: "ingestion",
95
+ event: "ingestion_completed",
96
+ fields: {
97
+ state_previous: "running",
98
+ state_current: "complete",
99
+ files_scanned: result!.files_scanned,
100
+ files_updated: result!.files_updated,
101
+ files_skipped: result!.files_skipped,
102
+ parser_invocations: result!.parser_invocations,
103
+ duration_ms: result!.duration_ms,
104
+ ...(result!.stage_timings_ms ?? {}),
105
+ },
106
+ workspaceRoot,
107
+ emitStderr: false,
108
+ });
58
109
  return result!;
59
110
  } catch (error) {
60
- this.repo.setMeta("sync_state", "error");
61
- this.repo.setMeta("sync_error", String(error));
111
+ this.recordSyncFailure(error);
112
+ SeptumTelemetry.recordSystemEvent({
113
+ level: "ERROR",
114
+ component: "ingestion",
115
+ event: "ingestion_failed",
116
+ fields: {
117
+ state_previous: "running",
118
+ state_current: "error",
119
+ error_code: error instanceof DomainRootConflictError ? error.code : undefined,
120
+ message: (error instanceof Error ? error.message : String(error)).slice(0, 256),
121
+ },
122
+ workspaceRoot,
123
+ emitStderr: false,
124
+ });
62
125
  throw error;
63
126
  }
64
127
  }
65
128
 
66
- private async runSync(config: ValidatedSeptumConfig, options: { verifyContent?: boolean; signal?: AbortSignal }): Promise<IngestionMetrics> {
67
- this.ensureParserRevision();
129
+ private async runSync(
130
+ config: ValidatedSeptumConfig,
131
+ options: {
132
+ verifyContent?: boolean;
133
+ rebuild?: boolean;
134
+ signal?: AbortSignal;
135
+ onProgress?: (info: IngestionProgressEvent) => void;
136
+ },
137
+ work: { parserInvocations: number }
138
+ ): Promise<IngestionMetrics> {
68
139
  const startTime = performance.now();
140
+ let scanMs = 0;
141
+ let parseMs = 0;
142
+ let commitMs = 0;
143
+ let sliceMs = 0;
69
144
  let filesScanned = 0;
70
145
  let filesUpdated = 0;
71
146
  let filesSkipped = 0;
@@ -73,14 +148,17 @@ export class IngestionPipeline {
73
148
  let dependenciesIndexed = 0;
74
149
  const unsupportedFiles: string[] = [];
75
150
  const skippedFiles: SkippedSourceFile[] = [];
151
+ const ingestedFullPaths = new Set<string>();
76
152
  let removedFiles = 0;
77
153
 
78
154
  let domainNames = Object.keys(config.domains);
155
+ const hasExplicitDomains = domainNames.length > 0;
79
156
  const projectRoot = this.customWorkspaceRoot || resolveWorkspaceRoot();
80
157
 
81
- // Auto-discovery mode if no domains explicitly declared in config
158
+ // Existing SQLite ownership precedes inference when the caller omits domains.
82
159
  if (domainNames.length === 0) {
83
- const discovered = this.autoDiscoverDomains(projectRoot);
160
+ const discovered = this.repo.getAllDomains().length
161
+ ? ConfigLoader.loadFromRepository(this.repo).domains : this.autoDiscoverDomains(projectRoot);
84
162
  for (const [dName, dCfg] of Object.entries(discovered)) {
85
163
  config.domains[dName] = {
86
164
  root: dCfg.root,
@@ -92,13 +170,73 @@ export class IngestionPipeline {
92
170
  }
93
171
  domainNames = Object.keys(config.domains);
94
172
  }
95
- const inventory = this.sourceInventory(projectRoot, config.settings.ignore_patterns, options.signal);
173
+ this.assertDomainOwnership(config, projectRoot);
174
+ if (hasExplicitDomains) {
175
+ const pruned = this.repo.pruneDomainsNotIn(domainNames);
176
+ if (pruned.prunedDomains > 0) {
177
+ removedFiles += pruned.removedFiles;
178
+ this.repo.setMeta("slices_dirty", "1");
179
+ }
180
+ }
181
+ this.ensureParserFingerprint(options.rebuild);
182
+ options.onProgress?.({ phase: "scanning", status: "start", total: 0 });
183
+ const scanStart = performance.now();
184
+ const initialScan = scanSourceFiles(projectRoot, { ignorePatterns: config.settings.ignore_patterns, signal: options.signal });
185
+ const initialStats = new Map<string, Stats>();
186
+ const initialEntries: Array<{ fullPath: string; relPath: string }> = [];
187
+ const inventory = initialScan.files.map(fullPath => {
188
+ const relPath = relative(projectRoot, fullPath).replace(/\\/g, "/");
189
+ const stat = statSync(fullPath);
190
+ initialStats.set(fullPath, stat);
191
+ initialEntries.push({ fullPath, relPath });
192
+ return `${relPath}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.ino}`;
193
+ }).sort();
194
+ scanMs += performance.now() - scanStart;
195
+ const totalEstimatedFiles = initialEntries.length;
196
+ options.onProgress?.({ phase: "scanning", status: "done", total: totalEstimatedFiles });
197
+ const batchFilesLimit = options.rebuild && totalEstimatedFiles >= 500 ? 250 : RESOURCE_LIMITS.batchFiles;
198
+ const batchBytesLimit = options.rebuild && totalEstimatedFiles >= 500 ? 4 * 1024 * 1024 : RESOURCE_LIMITS.batchBytes;
96
199
 
97
200
  const existingFilesMap = new Map<string, import("../../types/index.ts").FileRecord>();
98
201
  for (const f of this.repo.getAllFiles()) {
99
202
  existingFilesMap.set(f.path, f);
100
203
  }
101
204
 
205
+ // Single-pass O(F * depth) longest-prefix domain partitioning for projectRoot domains
206
+ const prefixToDomain = new Map<string, string>();
207
+ for (const domainName of domainNames) {
208
+ const domainCfg = config.domains[domainName];
209
+ const wsRoot = this.resolveWorkspaceRoot(config, domainCfg.root);
210
+ if (wsRoot !== projectRoot || !isPathContained(domainCfg.root, wsRoot)) continue;
211
+ const relPrefix = relative(wsRoot, resolve(wsRoot, domainCfg.root)).replace(/\\/g, "/");
212
+ prefixToDomain.set(relPrefix, domainName);
213
+ }
214
+ const entriesByDomain = new Map<string, Array<{ fullPath: string; relPath: string }>>();
215
+ for (const entry of initialEntries) {
216
+ let owner: string | undefined = prefixToDomain.get(entry.relPath);
217
+ if (!owner) {
218
+ let dir = entry.relPath;
219
+ while (true) {
220
+ const slash = dir.lastIndexOf("/");
221
+ if (slash === -1) {
222
+ owner = prefixToDomain.get("");
223
+ break;
224
+ }
225
+ dir = dir.slice(0, slash);
226
+ owner = prefixToDomain.get(dir);
227
+ if (owner) break;
228
+ }
229
+ }
230
+ if (owner) {
231
+ let bucket = entriesByDomain.get(owner);
232
+ if (!bucket) {
233
+ bucket = [];
234
+ entriesByDomain.set(owner, bucket);
235
+ }
236
+ bucket.push(entry);
237
+ }
238
+ }
239
+
102
240
  for (const domainName of domainNames) {
103
241
  const domainCfg = config.domains[domainName];
104
242
  const domainId = this.repo.upsertDomain(domainName, domainCfg);
@@ -125,21 +263,21 @@ export class IngestionPipeline {
125
263
  throw new Error(`Failed to access domain root '${domainCfg.root}' for domain '${domainName}': ${err.message || err}`);
126
264
  }
127
265
 
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
- );
266
+ const collectedFiles = workspaceRoot === projectRoot
267
+ ? (entriesByDomain.get(domainName) ?? [])
268
+ : this.collectFiles(
269
+ absDomainRoot,
270
+ workspaceRoot,
271
+ config.settings.ignore_patterns,
272
+ domainNames
273
+ .filter(name => name !== domainName)
274
+ .map(name => relative(workspaceRoot, resolve(workspaceRoot, config.domains[name].root)).replace(/\\/g, "/"))
275
+ .filter(child => {
276
+ const fromParent = relative(absDomainRoot, resolve(workspaceRoot, child)).replace(/\\/g, "/");
277
+ return fromParent !== "" && fromParent !== ".." && !fromParent.startsWith("../") && !isAbsolute(fromParent);
278
+ }),
279
+ options.signal
280
+ );
143
281
  const activeRelPaths = new Set<string>();
144
282
 
145
283
  const pendingMetadataUpdates: Array<{
@@ -157,22 +295,39 @@ export class IngestionPipeline {
157
295
  lineCount: number;
158
296
  archetype: ReturnType<typeof detectArchetype>;
159
297
  mtimeMs: number;
298
+ ctimeMs: number;
160
299
  sizeBytes: number;
300
+ ino: number;
161
301
  ast: ParsedFileAST;
162
302
  }> = [];
163
303
 
164
304
  let batchBytes = 0;
165
305
  const commitBatch = () => {
166
306
  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;
307
+ let changed = false;
308
+ try {
309
+ const s = statSync(item.fullPath);
310
+ if (s.size !== item.sizeBytes || s.mtimeMs !== item.mtimeMs || s.ctimeMs !== item.ctimeMs || s.ino !== item.ino) {
311
+ changed = true;
312
+ }
313
+ } catch (error: any) {
314
+ if (error?.code === "ENOENT") {
315
+ throw new Error(`Source changed during synchronization: '${item.relPath}'. Run sync again after the file stops changing.`);
316
+ }
317
+ throw error;
171
318
  }
172
- if (currentHash !== item.contentHash) {
173
- throw new Error(`Source changed during synchronization: '${item.relPath}'. Run sync again after the file stops changing.`);
319
+ if (changed) {
320
+ let currentHash: string | undefined;
321
+ try { currentHash = existsSync(item.fullPath) ? computeContentHash(readSourceFile(item.fullPath)) : undefined; }
322
+ catch (error: any) {
323
+ if (error?.code !== "ENOENT") throw error;
324
+ }
325
+ if (currentHash !== item.contentHash) {
326
+ throw new Error(`Source changed during synchronization: '${item.relPath}'. Run sync again after the file stops changing.`);
327
+ }
174
328
  }
175
329
  }
330
+ const commitStart = performance.now();
176
331
  this.repo.runInTransaction(() => {
177
332
  for (const meta of pendingMetadataUpdates) {
178
333
  if (meta.file.archetype !== meta.archetype) {
@@ -181,26 +336,18 @@ export class IngestionPipeline {
181
336
  } else this.repo.updateFileMetadataOnly(meta.id, meta.mtimeMs, meta.sizeBytes);
182
337
  }
183
338
 
184
- if (pendingUpdates.length) this.repo.setMeta("slices_dirty", "1");
185
339
  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);
340
+ this.publishParsedFile(domainId, item, false);
198
341
 
199
342
  symbolsIndexed += item.ast.symbols.length;
200
343
  dependenciesIndexed += item.ast.dependencies.length;
201
344
  }
345
+ if (pendingUpdates.length > 0) {
346
+ this.repo.setMeta("slices_dirty", "1");
347
+ }
202
348
 
203
349
  });
350
+ commitMs += performance.now() - commitStart;
204
351
  pendingUpdates.length = 0;
205
352
  pendingMetadataUpdates.length = 0;
206
353
  batchBytes = 0;
@@ -208,24 +355,30 @@ export class IngestionPipeline {
208
355
 
209
356
  for (const { fullPath, relPath } of collectedFiles) {
210
357
  options.signal?.throwIfAborted();
211
- if (pendingMetadataUpdates.length >= RESOURCE_LIMITS.batchFiles) commitBatch();
358
+ if (pendingMetadataUpdates.length >= batchFilesLimit) commitBatch();
212
359
  filesScanned++;
213
- if (filesScanned % RESOURCE_LIMITS.batchFiles === 0) { await new Promise<void>(done => setTimeout(done, 0)); options.signal?.throwIfAborted(); }
360
+ if (filesScanned % RESOURCE_LIMITS.batchFiles === 0) {
361
+ options.onProgress?.({ phase: "parsing", status: "progress", processed: filesScanned, total: totalEstimatedFiles });
362
+ await new Promise<void>(done => setTimeout(done, 0));
363
+ options.signal?.throwIfAborted();
364
+ }
214
365
  activeRelPaths.add(relPath);
215
366
 
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}`);
367
+ let stat = initialStats.get(fullPath);
368
+ if (!stat) {
369
+ try {
370
+ stat = statSync(fullPath);
371
+ } catch (error: any) {
372
+ if (error?.code === "ENOENT") continue;
373
+ throw new Error(`Failed to inspect source '${relPath}': ${error?.message || error}`);
374
+ }
222
375
  }
223
376
 
224
377
  const mtimeMs = stat.mtimeMs;
225
378
  const sizeBytes = stat.size;
226
379
  const existingFile = existingFilesMap.get(relPath);
227
380
 
228
- // Reuse indexed content only after verifying its hash.
381
+ const archetype = detectArchetype(relPath, domainCfg.archetypes ?? {});
229
382
  if (sizeBytes > RESOURCE_LIMITS.sourceBytes) {
230
383
  skippedFiles.push({path: relPath, reason: "file_too_large"});
231
384
  if (existingFile) removedFiles++;
@@ -233,7 +386,16 @@ export class IngestionPipeline {
233
386
  this.repo.setMeta("slices_dirty", "1");
234
387
  continue;
235
388
  }
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(); }
389
+ // Fast sync trusts metadata; explicit verification and rebuilds read bytes.
390
+ if (!options.verifyContent && !options.rebuild && existingFile &&
391
+ existingFile.domain_id === domainId && existingFile.mtime_ms === mtimeMs &&
392
+ existingFile.size_bytes === sizeBytes && existingFile.archetype === archetype &&
393
+ this.verifiedFiles.get(relPath)?.ctime === stat.ctimeMs &&
394
+ this.verifiedFiles.get(relPath)?.hash === existingFile.content_hash) {
395
+ filesSkipped++;
396
+ continue;
397
+ }
398
+ if (pendingUpdates.length >= batchFilesLimit || (batchBytes + sizeBytes > batchBytesLimit && pendingUpdates.length > 0)) { commitBatch(); await new Promise<void>(done => setTimeout(done, 0)); options.signal?.throwIfAborted(); }
237
399
  let content: string;
238
400
  try { content = readSourceFile(fullPath); }
239
401
  catch (error) {
@@ -245,6 +407,7 @@ export class IngestionPipeline {
245
407
  continue;
246
408
  }
247
409
  const currentHash = computeContentHash(content);
410
+ this.verifiedFiles.set(relPath, { ctime: stat.ctimeMs, hash: currentHash });
248
411
 
249
412
  if (
250
413
  existingFile &&
@@ -252,21 +415,39 @@ export class IngestionPipeline {
252
415
  existingFile.content_hash === currentHash
253
416
  ) {
254
417
  // 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 ?? {}) });
418
+ if (existingFile.mtime_ms !== mtimeMs || existingFile.size_bytes !== sizeBytes || existingFile.archetype !== archetype) {
419
+ pendingMetadataUpdates.push({ id: existingFile.id, mtimeMs, sizeBytes, file: existingFile, archetype });
420
+ }
256
421
  filesSkipped++;
257
422
  continue;
258
423
  }
259
424
 
260
425
  const lineCount = content.split("\n").length;
261
- const archetype = detectArchetype(relPath, domainCfg.archetypes ?? {});
426
+ ingestedFullPaths.add(fullPath);
427
+ work.parserInvocations++;
428
+ const parseStart = performance.now();
262
429
  const ast = await this.parserEngine.parseFile(fullPath, content);
263
- if (ast.status === "unsupported") {
430
+ parseMs += performance.now() - parseStart;
431
+ if (ast.status === "unsupported" || ast.status === "degraded") {
264
432
  unsupportedFiles.push(relPath);
433
+ if (existingFile) removedFiles++;
265
434
  this.repo.deleteFileByPath(relPath);
266
435
  this.repo.setMeta("slices_dirty", "1");
436
+ if (ast.status === "degraded") {
437
+ SeptumTelemetry.recordSystemEvent({
438
+ level: "WARN",
439
+ component: "ingestion",
440
+ event: "parser_degraded_isolated",
441
+ fields: {
442
+ file: relPath,
443
+ diagnostics: ast.diagnostics?.map(d => `${d.code}: ${d.message}`).join("; ").slice(0, 200),
444
+ },
445
+ workspaceRoot: projectRoot,
446
+ emitStderr: false,
447
+ });
448
+ }
267
449
  continue;
268
450
  }
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
451
 
271
452
  filesUpdated++;
272
453
  batchBytes += sizeBytes;
@@ -277,7 +458,9 @@ export class IngestionPipeline {
277
458
  lineCount,
278
459
  archetype,
279
460
  mtimeMs,
461
+ ctimeMs: stat.ctimeMs,
280
462
  sizeBytes,
463
+ ino: stat.ino,
281
464
  ast,
282
465
  });
283
466
  }
@@ -288,14 +471,16 @@ export class IngestionPipeline {
288
471
  for (const [existingPath, existingRecord] of existingFilesMap.entries()) {
289
472
  if (existingRecord.domain_id === domainId && !activeRelPaths.has(existingPath)) {
290
473
  removedFiles++;
291
- this.repo.setMeta("slices_dirty", "1");
292
- this.repo.deleteFileByPath(existingPath);
474
+ this.removeIndexedFile(existingPath);
293
475
  existingFilesMap.delete(existingPath);
294
476
  }
295
477
  }
296
478
  });
297
479
  }
298
480
 
481
+ options.onProgress?.({ phase: "parsing", status: "done", processed: filesScanned, total: totalEstimatedFiles });
482
+ options.onProgress?.({ phase: "resolving", status: "done", symbols: symbolsIndexed, dependencies: dependenciesIndexed });
483
+
299
484
  options.signal?.throwIfAborted();
300
485
  const topologyInputs = ["package.json", "composer.json", "nest-cli.json", "go.mod", "artisan", "tsconfig.json"]
301
486
  .map(file => { const target = join(projectRoot, file); return existsSync(target) ? readSourceFile(target) : ""; });
@@ -303,8 +488,8 @@ export class IngestionPipeline {
303
488
  // Membership covers newly added semantic files outside registered domains.
304
489
  const inventoryRevision = computeContentHash(JSON.stringify(inventory));
305
490
  const priorInputs: SourceReadFingerprint[] = JSON.parse(this.repo.getMeta("semantic_inputs") || "[]");
306
- let semanticInputChanged = false;
307
- for (let index = 0; index < priorInputs.length; index++) {
491
+ let semanticInputChanged = !sourceObservationsCurrent(projectRoot, JSON.parse(this.repo.getMeta("semantic_observations") || '{"paths":[],"directories":[]}'));
492
+ for (let index = 0; index < priorInputs.length && !semanticInputChanged; index++) {
308
493
  if (index % RESOURCE_LIMITS.batchFiles === 0) { await new Promise<void>(done => setTimeout(done, 0)); options.signal?.throwIfAborted(); }
309
494
  const input = priorInputs[index];
310
495
  const file = resolve(projectRoot, input.path);
@@ -316,45 +501,50 @@ export class IngestionPipeline {
316
501
  catch (error) { if (error instanceof SourceFileLimitError) semanticInputChanged = input.hash !== "file_too_large"; else throw error; }
317
502
  if (semanticInputChanged) break;
318
503
  }
319
- const extractorRevision = "3"; // Bump when extractor or inferred-chain semantics change.
504
+ const extractorRevision = SEMANTIC_FINGERPRINT;
505
+ options.onProgress?.({ phase: "linking", status: "start", slices: 0 });
506
+ const sliceStart = performance.now();
320
507
  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));
508
+ await rebuildSliceCatalog(this.repo, projectRoot, {
509
+ ignorePatterns: config.settings.ignore_patterns, signal: options.signal,
510
+ semanticRevision, inventoryRevision, inventory: initialScan,
342
511
  });
343
512
  }
513
+ sliceMs += performance.now() - sliceStart;
514
+ options.onProgress?.({ phase: "linking", status: "done", slices: this.repo.countVerticalSlices() });
344
515
 
345
516
  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))) {
517
+ const endScan = scanSourceFiles(projectRoot, { ignorePatterns: config.settings.ignore_patterns, signal: options.signal });
518
+ if (endScan.files.length !== initialStats.size || endScan.files.some(fullPath => !initialStats.has(fullPath))) {
347
519
  throw new Error("Source changed during synchronization: workspace inventory changed. Run sync again after the files stop changing.");
348
520
  }
521
+ for (const fullPath of ingestedFullPaths) {
522
+ const initialStat = initialStats.get(fullPath);
523
+ if (!initialStat) continue;
524
+ let endStat: Stats;
525
+ try {
526
+ endStat = statSync(fullPath);
527
+ } catch {
528
+ throw new Error("Source changed during synchronization: workspace inventory changed. Run sync again after the files stop changing.");
529
+ }
530
+ if (
531
+ endStat.size !== initialStat.size ||
532
+ endStat.mtimeMs !== initialStat.mtimeMs ||
533
+ endStat.ctimeMs !== initialStat.ctimeMs ||
534
+ endStat.ino !== initialStat.ino
535
+ ) {
536
+ throw new Error("Source changed during synchronization: workspace inventory changed. Run sync again after the files stop changing.");
537
+ }
538
+ }
349
539
  const durationMs = Math.round(performance.now() - startTime);
350
540
 
351
541
  // Identify uncovered eligible source files outside registered domains
352
542
  const indexedPaths = new Set(this.repo.getAllFiles().map((file) => file.path));
353
- const allWorkspaceFiles = this.collectFiles(projectRoot, projectRoot, config.settings.ignore_patterns, [], options.signal);
543
+ for (const path of this.verifiedFiles.keys()) if (!indexedPaths.has(path)) this.verifiedFiles.delete(path);
354
544
  const unsupportedSet = new Set(unsupportedFiles);
355
545
  const skippedSet = new Set(skippedFiles.map((file) => file.path));
356
- const uncoveredFiles = allWorkspaceFiles
357
- .map((file) => file.relPath)
546
+ const uncoveredFiles = initialEntries
547
+ .map((entry) => entry.relPath)
358
548
  .filter((rel) => !indexedPaths.has(rel) && !unsupportedSet.has(rel) && !skippedSet.has(rel));
359
549
 
360
550
  // Update SSOT repo_meta watermark
@@ -379,7 +569,14 @@ export class IngestionPipeline {
379
569
  files_skipped: filesSkipped,
380
570
  symbols_indexed: symbolsIndexed,
381
571
  dependencies_indexed: dependenciesIndexed,
572
+ parser_invocations: work.parserInvocations,
382
573
  duration_ms: durationMs,
574
+ stage_timings_ms: {
575
+ scan_ms: Math.round(scanMs),
576
+ parse_ms: Math.round(parseMs),
577
+ commit_ms: Math.round(commitMs),
578
+ slice_ms: Math.round(sliceMs),
579
+ },
383
580
  };
384
581
  }
385
582
 
@@ -390,13 +587,9 @@ export class IngestionPipeline {
390
587
  private sourceInventory(root: string, ignorePatterns: string[], signal?: AbortSignal): string[] {
391
588
  return this.collectFiles(root, root, ignorePatterns, [], signal).map(({fullPath, relPath}) => {
392
589
  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}`;
590
+ // Guard membership and concurrent writes without rereading every source.
591
+ // Content checks belong to indexed files and semantic-input verification.
592
+ return `${relPath}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.ino}`;
400
593
  }).sort();
401
594
  }
402
595
 
@@ -407,83 +600,8 @@ export class IngestionPipeline {
407
600
  childDomainRoots: string[] = [],
408
601
  signal?: AbortSignal
409
602
  ): 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;
603
+ return scanSourceFiles(workspaceRoot, { directory: dir, ignorePatterns, excludeRoots: childDomainRoots, signal })
604
+ .files.map(fullPath => ({ fullPath, relPath: relative(workspaceRoot, fullPath).replace(/\\/g, "/") }));
487
605
  }
488
606
 
489
607
  private resolveWorkspaceRoot(config: ValidatedSeptumConfig, domainRoot: string): string {
@@ -510,14 +628,29 @@ export class IngestionPipeline {
510
628
  return ASTParserEngine.isSourceFile(path);
511
629
  }
512
630
 
513
- private ensureParserRevision(): void {
514
- const revision = PARSER_REVISION;
515
- if (this.repo.getMeta("parser_revision") === revision) return;
631
+ public assertDomainOwnership(config: ValidatedSeptumConfig, projectRoot: string): void {
632
+ const proposedNames = new Set(Object.keys(config.domains).map(domainNameKey));
633
+ const retained = Object.fromEntries(this.repo.getAllDomains()
634
+ .filter(domain => !proposedNames.has(domainNameKey(domain.name)))
635
+ .map(domain => [domain.name, { root: domain.root_path }]));
636
+ assertUniqueDomainRoots({ ...retained, ...config.domains }, projectRoot);
637
+ }
638
+
639
+ private recordSyncFailure(error: unknown): void {
640
+ this.repo.setMeta("sync_state", "error");
641
+ this.repo.setMeta("sync_error", String(error));
642
+ this.repo.setMeta("sync_error_code", error instanceof DomainRootConflictError ? error.code : "");
643
+ }
644
+
645
+ private ensureParserFingerprint(rebuild = false): void {
646
+ const revision = PARSER_FINGERPRINT;
647
+ if (!rebuild && this.repo.getMeta("parser_revision") === revision) return;
516
648
  this.repo.runInTransaction(() => {
517
649
  for (const file of this.repo.getAllFiles()) {
518
650
  this.repo.upsertFile(file.domain_id, file.path, file.archetype, "", file.line_count, -1, -1);
519
651
  }
520
652
  this.repo.clearVerticalSlices();
653
+ this.repo.setMeta("slices_dirty", "1");
521
654
  this.repo.setMeta("parser_revision", revision);
522
655
  });
523
656
  }
@@ -526,8 +659,53 @@ export class IngestionPipeline {
526
659
  * JIT single-file ingestion: quickly verifies and updates a single file's AST,
527
660
  * symbols, and dependencies in SQLite if its mtime or content hash has changed.
528
661
  */
662
+ /** Apply inside the caller's transaction after checking the source hash. */
663
+ private publishParsedFile(domainId: number, file: {
664
+ relPath: string;
665
+ archetype: ArchetypeKind;
666
+ contentHash: string;
667
+ lineCount: number;
668
+ mtimeMs: number;
669
+ sizeBytes: number;
670
+ ast: ParsedFileAST;
671
+ }, markSlicesDirty = true): void {
672
+ const { relPath, archetype, contentHash, lineCount, mtimeMs, sizeBytes, ast } = file;
673
+ const fileId = this.repo.upsertFile(domainId, relPath, archetype, contentHash, lineCount, mtimeMs, sizeBytes);
674
+ this.repo.replaceFileSymbols(fileId, ast.symbols);
675
+ this.repo.replaceFileDependencies(fileId, ast.dependencies);
676
+ if (markSlicesDirty) this.repo.setMeta("slices_dirty", "1");
677
+ }
678
+
679
+ private removeIndexedFile(path: string): void {
680
+ this.repo.deleteFileByPath(path);
681
+ this.repo.setMeta("slices_dirty", "1");
682
+ }
683
+
684
+ private updateFileDiagnostics(path: string, reason?: "file_too_large" | "unsupported"): void {
685
+ const skipped: SkippedSourceFile[] = JSON.parse(this.repo.getMeta("skipped_files") || "[]");
686
+ const unsupported: string[] = JSON.parse(this.repo.getMeta("unsupported_files") || "[]");
687
+ this.repo.setMeta("skipped_files", JSON.stringify([
688
+ ...skipped.filter(file => file.path !== path),
689
+ ...(reason === "file_too_large" ? [{ path, reason }] : []),
690
+ ]));
691
+ this.repo.setMeta("unsupported_files", JSON.stringify([
692
+ ...unsupported.filter(file => file !== path),
693
+ ...(reason === "unsupported" ? [path] : []),
694
+ ]));
695
+ }
696
+
697
+ public removeFile(path: string, reason?: "file_too_large" | "unsupported"): void {
698
+ this.repo.runInTransaction(() => {
699
+ this.removeIndexedFile(path);
700
+ this.repo.clearVerticalSlices();
701
+ this.updateFileDiagnostics(path, reason);
702
+ });
703
+ }
704
+
529
705
  public async ingestFile(targetFilePath: string, config: ValidatedSeptumConfig): Promise<boolean> {
530
- this.ensureParserRevision();
706
+ try { this.assertDomainOwnership(config, this.customWorkspaceRoot || resolveWorkspaceRoot()); }
707
+ catch (error) { this.recordSyncFailure(error); throw error; }
708
+ this.ensureParserFingerprint();
531
709
  const fullPath = resolve(targetFilePath);
532
710
  if (!existsSync(fullPath)) return false;
533
711
 
@@ -563,13 +741,7 @@ export class IngestionPipeline {
563
741
  try { content = readSourceFile(fullPath); }
564
742
  catch (error) {
565
743
  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
- });
744
+ this.removeFile(relPath, "file_too_large");
573
745
  return false;
574
746
  }
575
747
  const currentHash = computeContentHash(content);
@@ -582,39 +754,33 @@ export class IngestionPipeline {
582
754
  this.repo.upsertFile(domainId, relPath, archetype, currentHash, existingFile.line_count, mtimeMs, sizeBytes);
583
755
  this.repo.setMeta("slices_dirty", "1");
584
756
  });
585
- } else this.repo.updateFileMetadataOnly(existingFile.id, mtimeMs, sizeBytes);
757
+ } else if (existingFile.mtime_ms !== mtimeMs || existingFile.size_bytes !== sizeBytes) {
758
+ this.repo.updateFileMetadataOnly(existingFile.id, mtimeMs, sizeBytes);
759
+ }
586
760
  return false;
587
761
  }
588
762
 
589
763
  const lineCount = content.split("\n").length;
590
764
  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]));
765
+ if (ast.status === "unsupported" || ast.status === "degraded") {
766
+ this.removeFile(relPath, "unsupported");
596
767
  return false;
597
768
  }
598
- if (ast.status === "degraded") throw new Error(`Cannot reliably index '${relPath}': parser is degraded. ${ast.diagnostics?.map(d => `${d.code}: ${d.message}`).join("; ") ?? ""}`);
769
+
770
+ let latestHash: string | undefined;
771
+ try { latestHash = computeContentHash(readSourceFile(fullPath)); }
772
+ catch { /* A vanished, unreadable or oversized source must not publish the parsed version. */ }
773
+ if (latestHash !== currentHash) {
774
+ const message = `Source changed during synchronization: '${relPath}' changed during single-file parsing. Run sync against stable inputs.`;
775
+ this.repo.setMeta("sync_state", "error");
776
+ this.repo.setMeta("sync_error", message);
777
+ throw new Error(message);
778
+ }
599
779
 
600
780
  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);
781
+ this.publishParsedFile(domainId, { relPath, archetype, contentHash: currentHash, lineCount, mtimeMs, sizeBytes, ast });
612
782
  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)));
783
+ this.updateFileDiagnostics(relPath);
618
784
  });
619
785
 
620
786
  return true;