@dimassetoid/septum-mcp 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +46 -28
  2. package/package.json +4 -4
  3. package/src/cli/commands/check.ts +27 -16
  4. package/src/cli/commands/hook.ts +38 -101
  5. package/src/cli/commands/init.ts +26 -9
  6. package/src/cli/commands/sync.ts +4 -6
  7. package/src/cli/hook-payload.ts +43 -0
  8. package/src/cli/index.ts +9 -52
  9. package/src/cli/scaffold/harness-config.ts +48 -8
  10. package/src/cli/templates/hooks.ts +49 -14
  11. package/src/cli/templates/rules.ts +34 -49
  12. package/src/cli/templates/skill.ts +39 -35
  13. package/src/core/boundary/evaluator.ts +67 -83
  14. package/src/core/boundary/staged-auditor.ts +102 -40
  15. package/src/core/config/domain-ownership.ts +45 -0
  16. package/src/core/config/loader.ts +81 -29
  17. package/src/core/config/schema.ts +0 -10
  18. package/src/core/database/repositories/dependency.repository.ts +169 -148
  19. package/src/core/database/repositories/domain.repository.ts +46 -3
  20. package/src/core/database/repositories/symbol.repository.ts +226 -87
  21. package/src/core/database/repository.ts +73 -18
  22. package/src/core/database/schema.ts +2 -33
  23. package/src/core/discovery/navigation.ts +105 -0
  24. package/src/core/discovery/topology-detector.ts +60 -2
  25. package/src/core/ingestion/pipeline.ts +96 -129
  26. package/src/core/parser/behavioral-analyzer.ts +26 -22
  27. package/src/core/parser/boundary-tracker.ts +15 -0
  28. package/src/core/parser/extractors/base.ts +7 -3
  29. package/src/core/parser/extractors/csharp.ts +7 -3
  30. package/src/core/parser/extractors/django-semantic.ts +4 -36
  31. package/src/core/parser/extractors/elysia-semantic.ts +3 -24
  32. package/src/core/parser/extractors/express-semantic.ts +3 -18
  33. package/src/core/parser/extractors/fastapi-semantic.ts +19 -53
  34. package/src/core/parser/extractors/fastify-semantic.ts +3 -18
  35. package/src/core/parser/extractors/flask-semantic.ts +22 -55
  36. package/src/core/parser/extractors/go-semantic.ts +92 -33
  37. package/src/core/parser/extractors/hono-semantic.ts +3 -24
  38. package/src/core/parser/extractors/java.ts +5 -3
  39. package/src/core/parser/extractors/laravel-semantic.ts +44 -16
  40. package/src/core/parser/extractors/mcp-cli-semantic.ts +6 -7
  41. package/src/core/parser/extractors/nestjs-semantic.ts +3 -19
  42. package/src/core/parser/extractors/php.ts +16 -0
  43. package/src/core/parser/extractors/python.ts +9 -4
  44. package/src/core/parser/extractors/registry.ts +26 -5
  45. package/src/core/parser/extractors/ruby.ts +8 -5
  46. package/src/core/parser/extractors/rust.ts +31 -13
  47. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  48. package/src/core/parser/extractors/symfony-semantic.ts +4 -37
  49. package/src/core/parser/extractors/typescript.ts +14 -1
  50. package/src/core/parser/implementation-fingerprint.ts +97 -0
  51. package/src/core/parser/language-capabilities.ts +23 -7
  52. package/src/core/parser/schema/providers/laravel-migration-provider.ts +73 -50
  53. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  54. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  55. package/src/core/parser/semantic-revision.ts +3 -0
  56. package/src/core/parser/static-string.ts +51 -0
  57. package/src/core/resolver/call-graph-tracer.ts +337 -28
  58. package/src/core/resolver/import-resolver.ts +107 -179
  59. package/src/core/resolver/interpretation-inputs.ts +7 -0
  60. package/src/core/resolver/languages/go.ts +103 -0
  61. package/src/core/resolver/languages/managed.ts +200 -0
  62. package/src/core/resolver/languages/python.ts +115 -0
  63. package/src/core/resolver/languages/ruby.ts +40 -0
  64. package/src/core/resolver/languages/rust.ts +127 -0
  65. package/src/core/resolver/languages/shared.ts +71 -0
  66. package/src/core/resolver/module-resolver.ts +8 -4
  67. package/src/core/resolver/slice-catalog.ts +79 -0
  68. package/src/core/resolver/slice-format.ts +9 -0
  69. package/src/core/resolver/symbol-impact.ts +381 -0
  70. package/src/core/resolver/vertical-slice-tracer.ts +93 -115
  71. package/src/core/resources/ignore.ts +22 -1
  72. package/src/core/resources/source-files.ts +143 -20
  73. package/src/core/resources/source-inventory.ts +55 -0
  74. package/src/core/retrieval/context-page.ts +109 -0
  75. package/src/core/retrieval/context.ts +320 -0
  76. package/src/core/retrieval/resolution-warnings.ts +21 -0
  77. package/src/core/retrieval/symbol-evidence.ts +97 -0
  78. package/src/core/retrieval/typescript-references.ts +262 -0
  79. package/src/core/telemetry/telemetry.ts +54 -9
  80. package/src/index.ts +0 -3
  81. package/src/mcp/schemas.ts +61 -420
  82. package/src/mcp/server.ts +116 -290
  83. package/src/mcp/tools/boundary.ts +2 -2
  84. package/src/mcp/tools/check-boundary.ts +55 -60
  85. package/src/mcp/tools/get-domain-catalog.ts +32 -219
  86. package/src/mcp/tools/get-symbol-impact.ts +45 -5
  87. package/src/mcp/tools/get-symbol.ts +227 -3
  88. package/src/mcp/tools/locate-symbol.ts +54 -14
  89. package/src/mcp/tools/{domain.ts → map.ts} +4 -18
  90. package/src/mcp/tools/register-domain.ts +41 -3
  91. package/src/mcp/tools/symbol.ts +23 -21
  92. package/src/mcp/tools/trace-vertical-slice.ts +36 -10
  93. package/src/mcp/workspace-manager.ts +15 -4
  94. package/src/mcp/workspace-watcher.ts +8 -8
  95. package/src/types/index.ts +35 -53
  96. package/src/cli/commands/topology.ts +0 -161
  97. package/src/core/database/repositories/environment.repository.ts +0 -207
  98. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  99. package/src/core/session/session-manager.ts +0 -107
  100. package/src/core/topology/environment-detector.ts +0 -973
  101. package/src/core/topology/types.ts +0 -83
  102. package/src/mcp/tools/feature.ts +0 -67
  103. package/src/mcp/tools/get-environment-topology.ts +0 -138
  104. package/src/mcp/tools/get-feature-context.ts +0 -224
  105. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  106. package/src/mcp/tools/register-feature.ts +0 -110
@@ -0,0 +1,105 @@
1
+ import type { SeptumRepository } from "../database/repository.ts";
2
+ import type { NavigationQuery } from "../../types/index.ts";
3
+
4
+ export const NAVIGATION_SCHEMA = "navigation/v1";
5
+
6
+ /** Navigation selects indexed structure; declaration inspection belongs to symbol. */
7
+ export function buildNavigation(repo: SeptumRepository, args: NavigationQuery, root: string) {
8
+ const domains = repo.getAllDomains();
9
+ const requested = args.domain ?? args.name;
10
+ const domain = domains.find(domain => domain.name.toLowerCase() === requested?.toLowerCase());
11
+ if (requested && !domain) return {
12
+ schema: NAVIGATION_SCHEMA, status: "not_found", domain: requested,
13
+ found: false, message: `Domain '${requested}' not found in Septum catalog.`,
14
+ suggestions: domains.map(domain => domain.name),
15
+ suggested_action: { tool: "septum_map", params: { action: "catalog" } },
16
+ available_domains: domains.map(domain => domain.name),
17
+ next: [{ tool: "septum_map", args: { action: "catalog" } }],
18
+ };
19
+ const files = repo.getNavigationFiles();
20
+ const byPath = new Map(files.map(file => [file.path, file]));
21
+ const domainCounts = new Map<string, number>();
22
+ for (const file of files) domainCounts.set(file.domain, (domainCounts.get(file.domain) ?? 0) + 1);
23
+ const filter = args.file_filter?.replace(/\\/g, "/").toLowerCase();
24
+ const matching = files.filter(file => (!domain || file.domain === domain.name) &&
25
+ (!filter || file.path.toLowerCase().includes(filter)) &&
26
+ (!(args.archetype_filter ?? args.archetype) || file.archetype === (args.archetype_filter ?? args.archetype)));
27
+ const paths = new Set(matching.map(file => file.path));
28
+ const relationships = repo.getImportRelationships(root);
29
+ const degree = new Map<string, number>();
30
+ const edges = new Map<string, { from: string; to: string; relation: "imports"; count: number }>();
31
+ const unresolved: Array<{ file: string; target: string; reason: string }> = [];
32
+ const workspace = !domain && !filter && !args.archetype_filter && !args.archetype;
33
+ for (const edge of relationships) {
34
+ const source = edge.source.file;
35
+ const targets = [...new Set(edge.resolution.targets.flatMap(target => target.files))];
36
+ const relevant = paths.has(source) || targets.some(target => paths.has(target));
37
+ if (!relevant) continue;
38
+ if (edge.freshness !== "current" || !["resolved", "external"].includes(edge.resolution.status) || edge.resolution.coverage === "conditional" || edge.index_coverage === "partial") {
39
+ unresolved.push({ file: source, target: edge.resolution.source.target,
40
+ reason: edge.freshness !== "current" ? `source_${edge.freshness}` : edge.index_coverage === "partial" ? "target_not_fully_indexed" : edge.resolution.reason });
41
+ }
42
+ if (edge.freshness !== "current" || edge.resolution.status !== "resolved") continue;
43
+ for (const target of targets) {
44
+ degree.set(source, (degree.get(source) ?? 0) + 1);
45
+ degree.set(target, (degree.get(target) ?? 0) + 1);
46
+ const from = workspace ? byPath.get(source)?.domain : source;
47
+ const to = workspace ? byPath.get(target)?.domain : target;
48
+ if (!from || !to || workspace && from === to) continue;
49
+ const key = JSON.stringify([from, to]);
50
+ const prior = edges.get(key);
51
+ if (prior) prior.count++;
52
+ else edges.set(key, { from, to, relation: "imports", count: 1 });
53
+ }
54
+ }
55
+ const entries = repo.getNavigationEntrypoints().filter(entry => entry.file && paths.has(entry.file));
56
+ const entryFiles = new Set(entries.map(entry => entry.file));
57
+ matching.sort((a, b) => Number(entryFiles.has(b.path)) - Number(entryFiles.has(a.path)) ||
58
+ (degree.get(b.path) ?? 0) - (degree.get(a.path) ?? 0) || a.path.localeCompare(b.path));
59
+ const offset = args.file_offset ?? 0;
60
+ const limit = args.file_limit ?? (args.detail_level === "full" ? 100 : 40);
61
+ const selected = workspace ? [] : matching.slice(offset, offset + limit);
62
+ const selectedPaths = new Set(selected.map(file => file.path));
63
+ const allEdges = [...edges.values()].sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to));
64
+ const relevantEdges = workspace ? allEdges : allEdges.filter(edge => selectedPaths.has(edge.from) || selectedPaths.has(edge.to));
65
+ const compactDomainOnly = Boolean(domain && !filter && !(args.archetype_filter ?? args.archetype) && args.detail_level !== "full");
66
+ const filteredEdges = compactDomainOnly
67
+ ? relevantEdges.filter(edge => byPath.get(edge.from)?.domain !== byPath.get(edge.to)?.domain)
68
+ : relevantEdges;
69
+ const dependencies = filteredEdges.slice(0, 100);
70
+ const entrypoints = entries.filter(entry => workspace || selectedPaths.has(entry.file!)).slice(0, 20);
71
+ const sync = repo.getMeta("sync_state") ?? "unindexed";
72
+ const dirty = repo.getMeta("slices_dirty") === "1";
73
+ const end = offset + selected.length;
74
+ const diagnostics = {
75
+ unresolved_imports: unresolved.length,
76
+ unsupported_files: (JSON.parse(repo.getMeta("unsupported_files") || "[]") as string[]).filter(path => !domain || path.startsWith(domain.root_path.replace(/\/$/, "") + "/")).length,
77
+ skipped_files: (JSON.parse(repo.getMeta("skipped_files") || "[]") as Array<{ path: string }>).filter(file => !domain || file.path.startsWith(domain.root_path.replace(/\/$/, "") + "/")).length,
78
+ };
79
+ return {
80
+ schema: NAVIGATION_SCHEMA,
81
+ status: requested || filter ? matching.length ? "success" : "not_found" : domains.length ? "success" : "NOT_INDEXED",
82
+ scope: { level: workspace ? "workspace" : filter ? "file" : "domain", ...(domain ? { domain: domain.name } : {}), ...(filter ? { file_filter: args.file_filter } : {}) },
83
+ domains: (workspace ? domains : domain ? [domain] : []).map(domain => ({ name: domain.name, root: domain.root_path,
84
+ file_count: domainCounts.get(domain.name) ?? 0,
85
+ allowed_dependencies: JSON.parse(domain.allowed_deps_json || "[]") as string[],
86
+ forbidden_dependencies: JSON.parse(domain.forbidden_deps_json || "[]") as string[],
87
+ })),
88
+ files: selected,
89
+ dependencies,
90
+ entrypoints: entrypoints.map(entry => ({ ...entry, evidence: "static_catalog", runtime_verified: false })),
91
+ health: { index: sync, sync_needed: dirty, coverage: "partial", ...diagnostics,
92
+ reasons: [...new Set(unresolved.map(item => item.reason))].sort().slice(0, 10) },
93
+ index_status: { sync_state: sync, sync_needed: dirty },
94
+ accounting: { matching_files: matching.length, returned_files: selected.length,
95
+ omitted_files: workspace ? 0 : Math.max(0, matching.length - selected.length),
96
+ total_dependencies: allEdges.length, returned_dependencies: dependencies.length, omitted_dependencies: allEdges.length - dependencies.length,
97
+ total_entrypoints: entries.length, omitted_entrypoints: entries.length - entrypoints.length },
98
+ ...(!workspace && end < matching.length ? { pagination: { next_file_offset: end, file_offset: offset } } : {}),
99
+ ...(args.include_evidence ? { diagnostics: unresolved.slice(0, 5), diagnostics_omitted: Math.max(0, unresolved.length - 5) } : {}),
100
+ next: entrypoints[0] ? [{ tool: "septum_slice", args: { query: `${entrypoints[0].method} ${entrypoints[0].target}`, controller_file: entrypoints[0].file } }]
101
+ : selected[0]?.anchor ? [{ tool: "septum_symbol", args: { action: "locate", query: selected[0].anchor, file_path: selected[0].path } }]
102
+ : [{ tool: "septum_map", args: { action: "catalog", ...(domains[0] ? { domain: domains[0].name } : {}) } }],
103
+ relationship_limits: "Dependencies are imports, not calls or execution order. Entrypoints come from the static catalog and may be inferred. Unindexed targets remain uncertain.",
104
+ };
105
+ }
@@ -3,6 +3,7 @@ import * as path from "node:path";
3
3
  import type { DomainConfig } from "../../types/index.ts";
4
4
  import type { SeptumRepository } from "../database/repository.ts";
5
5
  import { DEFAULT_IGNORED_DIRECTORIES, isIgnoredDirectory } from "../resources/ignore.ts";
6
+ import { assertUniqueDomainRoots, domainNameKey, domainRootIdentity } from "../config/domain-ownership.ts";
6
7
 
7
8
  export type ProjectType =
8
9
  | "monorepo"
@@ -547,16 +548,73 @@ export class TopologyDetector {
547
548
  projectRoot: string = process.cwd(),
548
549
  forceResetPolicies: boolean = false
549
550
  ): Record<string, DomainConfig> {
551
+ assertUniqueDomainRoots(Object.fromEntries(repo.getAllDomains().map(domain => [domain.name, { root: domain.root_path }])), projectRoot);
550
552
  const topology = this.detect(projectRoot);
551
553
 
552
554
  for (const [name, config] of Object.entries(topology.domains)) {
553
555
  const existing = repo.domains.getDomainByName(name);
554
556
  if (!existing || forceResetPolicies) {
555
- repo.upsertDomain(name, config);
557
+ const identity = domainRootIdentity(config.root, projectRoot);
558
+ const owner = repo.getAllDomains().find(domain => domainRootIdentity(domain.root_path, projectRoot) === identity && domainNameKey(domain.name) !== domainNameKey(name));
559
+ // Inference must not create an alias for an explicitly registered owner.
560
+ if (owner && !existing) continue;
561
+ repo.domains.upsertDomain(name, config, projectRoot);
556
562
  }
557
563
  }
558
564
 
559
- // Persist Macro Metadata SSOT
565
+ if (forceResetPolicies) {
566
+ repo.domains.pruneDomainsNotIn(Object.keys(topology.domains));
567
+ }
568
+
569
+ return this.persistMacroMetadata(repo, topology);
570
+ }
571
+
572
+ /**
573
+ * Synchronize explicit domains from septum.config.json as the SSOT without
574
+ * writing auto-discovered domains, while still updating macro metadata and
575
+ * reporting any detected framework sub-domains shadowed by coarse roots.
576
+ */
577
+ public static syncExplicitConfigDomains(
578
+ repo: SeptumRepository,
579
+ projectRoot: string,
580
+ explicitDomains: Record<string, DomainConfig>
581
+ ): {
582
+ domains: Record<string, DomainConfig>;
583
+ shadowedSubdomains: Array<{ explicitDomain: string; explicitRoot: string; detectedNames: string[] }>;
584
+ } {
585
+ assertUniqueDomainRoots(explicitDomains, projectRoot);
586
+ for (const [name, config] of Object.entries(explicitDomains)) {
587
+ repo.domains.upsertDomain(name, config, projectRoot);
588
+ }
589
+ repo.domains.pruneDomainsNotIn(Object.keys(explicitDomains));
590
+
591
+ const topology = this.detect(projectRoot);
592
+ const domains = this.persistMacroMetadata(repo, topology);
593
+
594
+ const shadowedSubdomains: Array<{ explicitDomain: string; explicitRoot: string; detectedNames: string[] }> = [];
595
+ for (const [explicitDomain, explicitCfg] of Object.entries(explicitDomains)) {
596
+ const parentAbs = path.resolve(projectRoot, explicitCfg.root);
597
+ const detectedNames: string[] = [];
598
+ for (const [detectedName, detectedCfg] of Object.entries(topology.domains)) {
599
+ if (domainNameKey(detectedName) === domainNameKey(explicitDomain)) continue;
600
+ const childAbs = path.resolve(projectRoot, detectedCfg.root);
601
+ const rel = path.relative(parentAbs, childAbs);
602
+ if (rel !== "" && rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel)) {
603
+ detectedNames.push(detectedName);
604
+ }
605
+ }
606
+ if (detectedNames.length > 0) {
607
+ shadowedSubdomains.push({ explicitDomain, explicitRoot: explicitCfg.root, detectedNames });
608
+ }
609
+ }
610
+
611
+ return { domains, shadowedSubdomains };
612
+ }
613
+
614
+ private static persistMacroMetadata(
615
+ repo: SeptumRepository,
616
+ topology: DiscoveredProjectTopology
617
+ ): Record<string, DomainConfig> {
560
618
  repo.setMeta("project_type", topology.projectType);
561
619
  repo.setMeta("architecture_style", topology.architectureStyle);
562
620
  repo.setMeta("framework", topology.framework);
@@ -1,21 +1,25 @@
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";
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 } 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
12
  import type { 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";
19
23
 
20
24
  export interface IngestionMetrics {
21
25
  domains_processed: number;
@@ -24,10 +28,15 @@ export interface IngestionMetrics {
24
28
  files_skipped: number;
25
29
  symbols_indexed: number;
26
30
  dependencies_indexed: number;
31
+ /** Indexed-file parse attempts across this sync, including recovered retries; excludes semantic extraction. */
32
+ parser_invocations: number;
27
33
  duration_ms: number;
28
34
  }
29
35
 
30
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 }>();
31
40
  private repo: SeptumRepository;
32
41
  private parserEngine: ASTParserEngine;
33
42
  private customWorkspaceRoot?: string;
@@ -40,14 +49,16 @@ export class IngestionPipeline {
40
49
  }
41
50
  }
42
51
 
43
- public async run(config: ValidatedSeptumConfig, options: { verifyContent?: boolean; signal?: AbortSignal } = {}): Promise<IngestionMetrics> {
52
+ public async run(config: ValidatedSeptumConfig, options: { verifyContent?: boolean; rebuild?: boolean; signal?: AbortSignal } = {}): Promise<IngestionMetrics> {
44
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));
45
55
  this.repo.setMeta("resolver_revision", RESOLVER_REVISION);
46
56
  this.repo.setMeta("sync_state", "running");
57
+ const work = { parserInvocations: 0 };
47
58
  try {
48
59
  let result: IngestionMetrics | undefined;
49
60
  for (let attempt = 0; attempt < 2; attempt++) {
50
- try { result = await this.runSync(config, options); break; }
61
+ try { result = await this.runSync(config, options, work); break; }
51
62
  catch (error) {
52
63
  if (attempt || !(error instanceof Error) || !error.message.startsWith("Source changed during synchronization:")) throw error;
53
64
  options.signal?.throwIfAborted();
@@ -55,16 +66,15 @@ export class IngestionPipeline {
55
66
  }
56
67
  this.repo.setMeta("sync_state", "complete");
57
68
  this.repo.setMeta("sync_error", "");
69
+ this.repo.setMeta("sync_error_code", "");
58
70
  return result!;
59
71
  } catch (error) {
60
- this.repo.setMeta("sync_state", "error");
61
- this.repo.setMeta("sync_error", String(error));
72
+ this.recordSyncFailure(error);
62
73
  throw error;
63
74
  }
64
75
  }
65
76
 
66
- private async runSync(config: ValidatedSeptumConfig, options: { verifyContent?: boolean; signal?: AbortSignal }): Promise<IngestionMetrics> {
67
- this.ensureParserRevision();
77
+ private async runSync(config: ValidatedSeptumConfig, options: { verifyContent?: boolean; rebuild?: boolean; signal?: AbortSignal }, work: { parserInvocations: number }): Promise<IngestionMetrics> {
68
78
  const startTime = performance.now();
69
79
  let filesScanned = 0;
70
80
  let filesUpdated = 0;
@@ -76,11 +86,13 @@ export class IngestionPipeline {
76
86
  let removedFiles = 0;
77
87
 
78
88
  let domainNames = Object.keys(config.domains);
89
+ const hasExplicitDomains = domainNames.length > 0;
79
90
  const projectRoot = this.customWorkspaceRoot || resolveWorkspaceRoot();
80
91
 
81
- // Auto-discovery mode if no domains explicitly declared in config
92
+ // Existing SQLite ownership precedes inference when the caller omits domains.
82
93
  if (domainNames.length === 0) {
83
- const discovered = this.autoDiscoverDomains(projectRoot);
94
+ const discovered = this.repo.getAllDomains().length
95
+ ? ConfigLoader.loadFromRepository(this.repo).domains : this.autoDiscoverDomains(projectRoot);
84
96
  for (const [dName, dCfg] of Object.entries(discovered)) {
85
97
  config.domains[dName] = {
86
98
  root: dCfg.root,
@@ -92,6 +104,15 @@ export class IngestionPipeline {
92
104
  }
93
105
  domainNames = Object.keys(config.domains);
94
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);
95
116
  const inventory = this.sourceInventory(projectRoot, config.settings.ignore_patterns, options.signal);
96
117
 
97
118
  const existingFilesMap = new Map<string, import("../../types/index.ts").FileRecord>();
@@ -225,7 +246,7 @@ export class IngestionPipeline {
225
246
  const sizeBytes = stat.size;
226
247
  const existingFile = existingFilesMap.get(relPath);
227
248
 
228
- // Reuse indexed content only after verifying its hash.
249
+ const archetype = detectArchetype(relPath, domainCfg.archetypes ?? {});
229
250
  if (sizeBytes > RESOURCE_LIMITS.sourceBytes) {
230
251
  skippedFiles.push({path: relPath, reason: "file_too_large"});
231
252
  if (existingFile) removedFiles++;
@@ -233,6 +254,15 @@ export class IngestionPipeline {
233
254
  this.repo.setMeta("slices_dirty", "1");
234
255
  continue;
235
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
+ }
236
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(); }
237
267
  let content: string;
238
268
  try { content = readSourceFile(fullPath); }
@@ -245,6 +275,7 @@ export class IngestionPipeline {
245
275
  continue;
246
276
  }
247
277
  const currentHash = computeContentHash(content);
278
+ this.verifiedFiles.set(relPath, { ctime: stat.ctimeMs, hash: currentHash });
248
279
 
249
280
  if (
250
281
  existingFile &&
@@ -252,13 +283,15 @@ export class IngestionPipeline {
252
283
  existingFile.content_hash === currentHash
253
284
  ) {
254
285
  // 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 ?? {}) });
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
+ }
256
289
  filesSkipped++;
257
290
  continue;
258
291
  }
259
292
 
260
293
  const lineCount = content.split("\n").length;
261
- const archetype = detectArchetype(relPath, domainCfg.archetypes ?? {});
294
+ work.parserInvocations++;
262
295
  const ast = await this.parserEngine.parseFile(fullPath, content);
263
296
  if (ast.status === "unsupported") {
264
297
  unsupportedFiles.push(relPath);
@@ -303,8 +336,8 @@ export class IngestionPipeline {
303
336
  // Membership covers newly added semantic files outside registered domains.
304
337
  const inventoryRevision = computeContentHash(JSON.stringify(inventory));
305
338
  const priorInputs: SourceReadFingerprint[] = JSON.parse(this.repo.getMeta("semantic_inputs") || "[]");
306
- let semanticInputChanged = false;
307
- for (let index = 0; index < priorInputs.length; index++) {
339
+ let semanticInputChanged = !sourceObservationsCurrent(projectRoot, JSON.parse(this.repo.getMeta("semantic_observations") || '{"paths":[],"directories":[]}'));
340
+ for (let index = 0; index < priorInputs.length && !semanticInputChanged; index++) {
308
341
  if (index % RESOURCE_LIMITS.batchFiles === 0) { await new Promise<void>(done => setTimeout(done, 0)); options.signal?.throwIfAborted(); }
309
342
  const input = priorInputs[index];
310
343
  const file = resolve(projectRoot, input.path);
@@ -316,29 +349,11 @@ export class IngestionPipeline {
316
349
  catch (error) { if (error instanceof SourceFileLimitError) semanticInputChanged = input.hash !== "file_too_large"; else throw error; }
317
350
  if (semanticInputChanged) break;
318
351
  }
319
- const extractorRevision = "3"; // Bump when extractor or inferred-chain semantics change.
352
+ const extractorRevision = SEMANTIC_FINGERPRINT;
320
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) {
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));
354
+ await rebuildSliceCatalog(this.repo, projectRoot, {
355
+ ignorePatterns: config.settings.ignore_patterns, signal: options.signal,
356
+ semanticRevision, inventoryRevision,
342
357
  });
343
358
  }
344
359
 
@@ -350,6 +365,7 @@ export class IngestionPipeline {
350
365
 
351
366
  // Identify uncovered eligible source files outside registered domains
352
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);
353
369
  const allWorkspaceFiles = this.collectFiles(projectRoot, projectRoot, config.settings.ignore_patterns, [], options.signal);
354
370
  const unsupportedSet = new Set(unsupportedFiles);
355
371
  const skippedSet = new Set(skippedFiles.map((file) => file.path));
@@ -379,6 +395,7 @@ export class IngestionPipeline {
379
395
  files_skipped: filesSkipped,
380
396
  symbols_indexed: symbolsIndexed,
381
397
  dependencies_indexed: dependenciesIndexed,
398
+ parser_invocations: work.parserInvocations,
382
399
  duration_ms: durationMs,
383
400
  };
384
401
  }
@@ -390,13 +407,9 @@ export class IngestionPipeline {
390
407
  private sourceInventory(root: string, ignorePatterns: string[], signal?: AbortSignal): string[] {
391
408
  return this.collectFiles(root, root, ignorePatterns, [], signal).map(({fullPath, relPath}) => {
392
409
  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}`;
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}`;
400
413
  }).sort();
401
414
  }
402
415
 
@@ -407,83 +420,8 @@ export class IngestionPipeline {
407
420
  childDomainRoots: string[] = [],
408
421
  signal?: AbortSignal
409
422
  ): 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;
423
+ return scanSourceFiles(workspaceRoot, { directory: dir, ignorePatterns, excludeRoots: childDomainRoots, signal })
424
+ .files.map(fullPath => ({ fullPath, relPath: relative(workspaceRoot, fullPath).replace(/\\/g, "/") }));
487
425
  }
488
426
 
489
427
  private resolveWorkspaceRoot(config: ValidatedSeptumConfig, domainRoot: string): string {
@@ -510,14 +448,29 @@ export class IngestionPipeline {
510
448
  return ASTParserEngine.isSourceFile(path);
511
449
  }
512
450
 
513
- private ensureParserRevision(): void {
514
- const revision = PARSER_REVISION;
515
- if (this.repo.getMeta("parser_revision") === revision) return;
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;
516
468
  this.repo.runInTransaction(() => {
517
469
  for (const file of this.repo.getAllFiles()) {
518
470
  this.repo.upsertFile(file.domain_id, file.path, file.archetype, "", file.line_count, -1, -1);
519
471
  }
520
472
  this.repo.clearVerticalSlices();
473
+ this.repo.setMeta("slices_dirty", "1");
521
474
  this.repo.setMeta("parser_revision", revision);
522
475
  });
523
476
  }
@@ -527,7 +480,9 @@ export class IngestionPipeline {
527
480
  * symbols, and dependencies in SQLite if its mtime or content hash has changed.
528
481
  */
529
482
  public async ingestFile(targetFilePath: string, config: ValidatedSeptumConfig): Promise<boolean> {
530
- this.ensureParserRevision();
483
+ try { this.assertDomainOwnership(config, this.customWorkspaceRoot || resolveWorkspaceRoot()); }
484
+ catch (error) { this.recordSyncFailure(error); throw error; }
485
+ this.ensureParserFingerprint();
531
486
  const fullPath = resolve(targetFilePath);
532
487
  if (!existsSync(fullPath)) return false;
533
488
 
@@ -582,7 +537,9 @@ export class IngestionPipeline {
582
537
  this.repo.upsertFile(domainId, relPath, archetype, currentHash, existingFile.line_count, mtimeMs, sizeBytes);
583
538
  this.repo.setMeta("slices_dirty", "1");
584
539
  });
585
- } else this.repo.updateFileMetadataOnly(existingFile.id, mtimeMs, sizeBytes);
540
+ } else if (existingFile.mtime_ms !== mtimeMs || existingFile.size_bytes !== sizeBytes) {
541
+ this.repo.updateFileMetadataOnly(existingFile.id, mtimeMs, sizeBytes);
542
+ }
586
543
  return false;
587
544
  }
588
545
 
@@ -597,6 +554,16 @@ export class IngestionPipeline {
597
554
  }
598
555
  if (ast.status === "degraded") throw new Error(`Cannot reliably index '${relPath}': parser is degraded. ${ast.diagnostics?.map(d => `${d.code}: ${d.message}`).join("; ") ?? ""}`);
599
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
+
600
567
  this.repo.runInTransaction(() => {
601
568
  const fileId = this.repo.upsertFile(
602
569
  domainId,