@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
@@ -0,0 +1,181 @@
1
+ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
2
+
3
+ function normalizeTrimmedArg(value: string | undefined): string | undefined {
4
+ const trimmed = typeof value === "string" ? value.trim() : "";
5
+ return trimmed || undefined;
6
+ }
7
+
8
+ function userTextMessage(description: string, lines: string[]) {
9
+ return {
10
+ description,
11
+ messages: [
12
+ {
13
+ role: "user" as const,
14
+ content: {
15
+ type: "text" as const,
16
+ text: lines.join("\n"),
17
+ },
18
+ },
19
+ ],
20
+ };
21
+ }
22
+
23
+ const PLAYBOOKS = [
24
+ {
25
+ name: "open-apps",
26
+ description: "Open the Septum Architecture UI and report workspace coverage or partial-index gaps with next steps.",
27
+ arguments: [
28
+ {
29
+ name: "workspace_path",
30
+ description: "Optional explicit workspace root path.",
31
+ required: false,
32
+ },
33
+ ],
34
+ render(args: Record<string, string | undefined>) {
35
+ const workspacePath = normalizeTrimmedArg(args.workspace_path);
36
+ const mapArgs = JSON.stringify({
37
+ action: "catalog",
38
+ detail_level: "compact",
39
+ ...(workspacePath ? { workspace_path: workspacePath } : {}),
40
+ });
41
+ return userTextMessage("Open Septum Architecture UI and inspect workspace coverage.", [
42
+ "Open the Septum Architecture UI and inspect workspace coverage:",
43
+ `1. Call \`septum_map\` with \`${mapArgs}\` to open the Septum Architecture UI and load domain topology and index health.`,
44
+ "2. Check `status` and `health` (`index`, `coverage`, `sync_needed`, `unsupported_files`, `skipped_files`, `unresolved_imports`, `reasons`). Read `septum://apps` if the client supports MCP resources for partial-file samples.",
45
+ "3. If `status` is `NOT_INDEXED` or `coverage` is `partial`, list the uncovered files or conditions and give concrete next steps (`septum init`, `septum sync`, `septum_map(action='register')`, or `ignore_patterns` / alias fixes).",
46
+ ]);
47
+ },
48
+ },
49
+ {
50
+ name: "audit-coupling",
51
+ description: "Find circular dependencies, forbidden imports, and high-coupling domains, ranked by remediation priority.",
52
+ arguments: [
53
+ {
54
+ name: "domain",
55
+ description: "Optional domain name to focus the audit.",
56
+ required: false,
57
+ },
58
+ {
59
+ name: "workspace_path",
60
+ description: "Optional explicit workspace root path.",
61
+ required: false,
62
+ },
63
+ ],
64
+ render(args: Record<string, string | undefined>) {
65
+ const domain = normalizeTrimmedArg(args.domain);
66
+ const workspacePath = normalizeTrimmedArg(args.workspace_path);
67
+ const target = { ...(domain && { domain }), ...(workspacePath && { workspace_path: workspacePath }) };
68
+ const mapArgs = JSON.stringify({ action: "catalog", detail_level: "compact", ...target });
69
+ const boundaryArgs = JSON.stringify({ scope: domain ? "domain" : "all", ...target });
70
+ return userTextMessage("Prioritized coupling and boundary audit.", [
71
+ "Audit the codebase for coupling, circular dependencies, and boundary violations:",
72
+ `1. Call \`septum_map\` with \`${mapArgs}\` to inspect domain sizes, cross-domain import counts, and unresolved imports.`,
73
+ `2. Call \`septum_boundary\` with \`${boundaryArgs}\` to list all circular dependencies and forbidden imports.`,
74
+ "3. Rank fixes by priority: (1) break circular dependencies, (2) resolve forbidden cross-domain imports with exact `file:line`, and (3) flag high fan-out domains or missing coverage.",
75
+ ]);
76
+ },
77
+ },
78
+ {
79
+ name: "check-staged",
80
+ description: "Check staged git changes for domain boundary and circular dependency violations before committing.",
81
+ arguments: [
82
+ {
83
+ name: "workspace_path",
84
+ description: "Optional explicit workspace root path.",
85
+ required: false,
86
+ },
87
+ ],
88
+ render(args: Record<string, string | undefined>) {
89
+ const workspacePath = normalizeTrimmedArg(args.workspace_path);
90
+ const boundaryArgs = JSON.stringify({
91
+ scope: "staged",
92
+ ...(workspacePath ? { workspace_path: workspacePath } : {}),
93
+ });
94
+ return userTextMessage("Check staged git changes against domain boundaries.", [
95
+ "Verify staged git changes before committing:",
96
+ `1. Call \`septum_boundary\` with \`${boundaryArgs}\`.`,
97
+ "2. If `status` is `rejected`, list each violation with `file:line`, `rule`, and import direction, then propose concrete refactors to satisfy the boundary.",
98
+ "3. If `status` is `approved`, confirm staged changes introduce no boundary or circular-dependency violations (and note any partial-coverage caveats).",
99
+ ]);
100
+ },
101
+ },
102
+ {
103
+ name: "plan-refactor",
104
+ description: "Map blast radius and domain rules before moving or splitting a module or symbol.",
105
+ arguments: [
106
+ {
107
+ name: "target",
108
+ description: "Optional target symbol name or file path to refactor (uses active conversation context if omitted).",
109
+ required: false,
110
+ },
111
+ {
112
+ name: "workspace_path",
113
+ description: "Optional explicit workspace root path.",
114
+ required: false,
115
+ },
116
+ ],
117
+ render(args: Record<string, string | undefined>) {
118
+ const target = normalizeTrimmedArg(args.target);
119
+ const workspacePath = normalizeTrimmedArg(args.workspace_path);
120
+ const wsPart = workspacePath ? `, workspace_path: ${JSON.stringify(workspacePath)}` : "";
121
+ const targetStep = target
122
+ ? `1. Call \`septum_symbol\` with \`{ action: "impact", query: ${JSON.stringify(target)}${wsPart} }\` to map static callers and import dependents.`
123
+ : `1. Identify the target symbol or file from conversation context (ask the user if unclear), then call \`septum_symbol\` with \`{ action: "impact", query: "<target>"${wsPart} }\`.`;
124
+ const mapArgs = JSON.stringify({
125
+ action: "catalog",
126
+ detail_level: "compact",
127
+ ...(workspacePath ? { workspace_path: workspacePath } : {}),
128
+ });
129
+ return userTextMessage("Blast-radius and domain-safe refactor plan.", [
130
+ "Build a domain-compliant refactoring plan:",
131
+ targetStep,
132
+ `2. Call \`septum_map\` with \`${mapArgs}\` to check source and target domain \`allowed_dependencies\` and \`forbidden_dependencies\`.`,
133
+ "3. Outline a leaf-to-core migration order and note any `septum_boundary(scope='file')` checks needed before moving imports.",
134
+ ]);
135
+ },
136
+ },
137
+ {
138
+ name: "trace-feature",
139
+ description: "Trace an HTTP, GraphQL, job, or CLI entrypoint through handlers, services, and repositories.",
140
+ arguments: [
141
+ {
142
+ name: "query",
143
+ description: "Optional route URI, controller action, or CLI command (discovers entrypoints via septum_map if omitted).",
144
+ required: false,
145
+ },
146
+ {
147
+ name: "workspace_path",
148
+ description: "Optional explicit workspace root path.",
149
+ required: false,
150
+ },
151
+ ],
152
+ render(args: Record<string, string | undefined>) {
153
+ const query = normalizeTrimmedArg(args.query);
154
+ const workspacePath = normalizeTrimmedArg(args.workspace_path);
155
+ const wsArgs = workspacePath ? { workspace_path: workspacePath } : {};
156
+ const sliceArgs = query
157
+ ? JSON.stringify({ query, max_depth: 5, ...wsArgs })
158
+ : null;
159
+ const mapArgs = JSON.stringify({ action: "catalog", detail_level: "compact", ...wsArgs });
160
+ return userTextMessage("Trace feature execution slice.", [
161
+ "Trace the end-to-end static execution flow of the feature:",
162
+ sliceArgs
163
+ ? `1. Call \`septum_slice\` with \`${sliceArgs}\` to open the Slice view and inspect the static chain.`
164
+ : `1. Call \`septum_map\` with \`${mapArgs}\` to list static entrypoints, pick the relevant route or command from context (or ask the user), then call \`septum_slice\`.`,
165
+ "2. Summarize each stage (entrypoint -> handler/controller -> service -> repository/job) with `file:line`, flagging skipped layers, direct DB access from controllers, or unresolved hops.",
166
+ ]);
167
+ },
168
+ },
169
+ ] as const;
170
+
171
+ export const SEPTUM_PROMPTS = PLAYBOOKS.map(({ name, description, arguments: args }) => ({ name, description, arguments: args }));
172
+
173
+ export function listSeptumPrompts() {
174
+ return { prompts: [...SEPTUM_PROMPTS] };
175
+ }
176
+
177
+ export function getSeptumPrompt(name: string, args: Record<string, string | undefined> = {}) {
178
+ const playbook = PLAYBOOKS.find(entry => entry.name === name);
179
+ if (!playbook) throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: '${name}'`);
180
+ return playbook.render(args);
181
+ }
@@ -0,0 +1,50 @@
1
+ import { evaluateBoundary } from "../core/boundary/audit.ts";
2
+ import { waitForSharedWork } from "../core/resources/work-queue.ts";
3
+ import type { BoundaryToolArgs } from "./schemas.ts";
4
+ import { renderBoundaryAudit } from "./tools/boundary.ts";
5
+ import type { WorkspaceContext, WorkspaceManager } from "./workspace-manager.ts";
6
+
7
+ export async function runWorkspaceBoundary(
8
+ manager: WorkspaceManager,
9
+ context: WorkspaceContext,
10
+ args: BoundaryToolArgs,
11
+ options: { signal?: AbortSignal; onSync?: () => void; onAudit?: () => void; onRetry?: () => void } = {},
12
+ ) {
13
+ const { signal } = options;
14
+ const audit = (syncProgress?: () => void, auditProgress?: () => void) => manager.runInWorkspace(context, async ctx => {
15
+ auditProgress?.();
16
+ return evaluateBoundary(ctx.evaluator, ctx.config, args, ctx.repo, ctx.root);
17
+ }, { signal, onSync: syncProgress });
18
+
19
+ const format = args.format ?? "text";
20
+ const first = await audit(options.onSync, options.onAudit);
21
+ if (!("stale_files" in first.payload) || !first.payload.stale_files.length) {
22
+ return renderBoundaryAudit(first, args.max_bytes, format);
23
+ }
24
+
25
+ // The first audit has released the serial lane. The watcher uses that lane
26
+ // for reconciliation and owns the shared work independently of this request.
27
+ options.onRetry?.();
28
+ try {
29
+ signal?.throwIfAborted();
30
+ await waitForSharedWork(context.watcher.reconcileForAudit(), signal);
31
+ const retried = await audit();
32
+ signal?.throwIfAborted();
33
+ return renderBoundaryAudit(retried, args.max_bytes, format);
34
+ } catch {
35
+ if (signal?.aborted && !(signal.reason instanceof Error && signal.reason.name === "TimeoutError")) {
36
+ signal.throwIfAborted();
37
+ }
38
+ const timedOut = signal?.aborted;
39
+ // Keep any violations already proved by the available evidence.
40
+ return renderBoundaryAudit({
41
+ kind: "incomplete_evidence",
42
+ payload: {
43
+ ...first.payload,
44
+ message: timedOut
45
+ ? "Boundary audit deadline expired during index reconciliation or retry. The available evidence is incomplete."
46
+ : "Boundary audit could not reconcile the index and complete the retry. The available evidence is incomplete. See workspace health for details.",
47
+ },
48
+ }, args.max_bytes, format);
49
+ }
50
+ }
@@ -1,17 +1,20 @@
1
1
  import { existsSync, realpathSync, statSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, isAbsolute, join, resolve } from 'node:path';
4
- import { ConfigLoader } from '../core/config/loader.ts';
4
+ import { ConfigLoader, resolveDatabasePath } from '../core/config/loader.ts';
5
5
  import type { ValidatedSeptumConfig } from '../core/config/schema.ts';
6
6
  import { SeptumDatabase } from '../core/database/client.ts';
7
7
  import { SeptumRepository } from '../core/database/repository.ts';
8
8
  import { BoundaryEvaluator } from '../core/boundary/evaluator.ts';
9
9
  import { ModuleResolver } from '../core/resolver/module-resolver.ts';
10
- import { findProjectRoot, isAppHostDirectory, isPathContained, PROJECT_ROOT_MARKERS, setLastKnownProjectRoot } from '../core/resolver/path-resolver.ts';
10
+ import { findProjectRoot, isAppHostDirectory, isPathContained, PROJECT_ROOT_MARKERS } from '../core/resolver/path-resolver.ts';
11
11
  import { IngestionPipeline } from '../core/ingestion/pipeline.ts';
12
12
  import { RESOURCE_LIMITS } from '../core/resources/limits.ts';
13
- import { SerialWorkQueue } from '../core/resources/work-queue.ts';
13
+ import { ReadWriteWorkQueue, waitForSharedWork } from '../core/resources/work-queue.ts';
14
14
  import { WatchBudget, WorkspaceWatcher } from './workspace-watcher.ts';
15
+ import { DomainRootConflictError } from '../core/config/domain-ownership.ts';
16
+ import { WorkspaceBusyError } from '../core/errors.ts';
17
+ import { SeptumTelemetry } from '../core/telemetry/telemetry.ts';
15
18
 
16
19
  export function resolveServerWorkspace(options: {workspacePath?: string; filePath?: string; fallbackRoot?: string; knownRoots?: string[]; initial?: boolean; cwd?: string} = {}): string {
17
20
  const cwd = options.cwd || process.cwd();
@@ -44,7 +47,6 @@ export function resolveServerWorkspace(options: {workspacePath?: string; filePat
44
47
  }
45
48
  }
46
49
 
47
- setLastKnownProjectRoot(root);
48
50
  return root;
49
51
  }
50
52
 
@@ -67,23 +69,34 @@ export interface WorkspaceContext {
67
69
  pipeline: IngestionPipeline;
68
70
  ready: Promise<void>;
69
71
  watcher: WorkspaceWatcher;
72
+ queue: ReadWriteWorkQueue;
70
73
  }
71
74
  interface Entry { context: WorkspaceContext; leases: number; lastUsed: number; initializing: boolean; abort: AbortController; disposal?: Promise<void> }
72
75
  export interface WorkspaceLease { context: WorkspaceContext; release(): void }
73
76
 
74
77
  export class WorkspaceManager {
75
78
  private contexts = new Map<string, Entry>();
76
- private queue = new SerialWorkQueue();
77
79
  private budget = new WatchBudget();
78
80
  private disposals = new Set<Promise<void>>();
79
81
  private closed = false;
82
+ private activeRequests = 0;
80
83
  private closing: Promise<void> | null = null;
81
84
  private idleTimer: ReturnType<typeof setInterval>;
82
85
  initialRoot?: string;
83
86
  lastRoot?: string;
84
87
  get activeRoots(): string[] { return [...this.contexts.keys()]; }
85
88
  constructor(private readonly now: () => number = Date.now) {
86
- this.idleTimer = setInterval(() => { void this.expireIdle().catch(error => console.error(`[Septum Cleanup Warning] ${String(error)}`)); }, 60_000);
89
+ this.idleTimer = setInterval(() => {
90
+ void this.expireIdle().catch(error =>
91
+ SeptumTelemetry.recordSystemEvent({
92
+ level: 'WARN',
93
+ component: 'workspace_manager',
94
+ event: 'idle_expiration_failed',
95
+ fields: { message: String(error).slice(0, 256) },
96
+ workspaceRoot: this.lastRoot ?? this.initialRoot ?? null,
97
+ })
98
+ );
99
+ }, 60_000);
87
100
  this.idleTimer.unref();
88
101
  }
89
102
  get size(): number { return this.contexts.size; }
@@ -91,7 +104,63 @@ export class WorkspaceManager {
91
104
  get syncDurationMs(): number { return Math.max(0, ...[...this.contexts.values()].map(entry => Number(entry.context.repo.getMeta("sync_duration_ms") || 0))); }
92
105
  get pendingPaths(): number { return [...this.contexts.values()].reduce((n, entry) => n + entry.context.watcher.pendingCount, 0); }
93
106
 
94
- acquire(rawRoot: string): WorkspaceLease {
107
+ /** Inspect an active context synchronously without renewing or creating it. */
108
+ peek(root: string): WorkspaceContext | undefined {
109
+ return this.contexts.get(root)?.context;
110
+ }
111
+
112
+ async runInWorkspace<T>(
113
+ ctx: WorkspaceContext,
114
+ work: (prepared: WorkspaceContext) => Promise<T>,
115
+ {
116
+ signal,
117
+ isDomainRegistration = false,
118
+ mode = "read",
119
+ onSync,
120
+ }: { signal?: AbortSignal; isDomainRegistration?: boolean; mode?: "read" | "write"; onSync?: () => void } = {},
121
+ ): Promise<T> {
122
+ signal?.throwIfAborted();
123
+ if (this.closed) throw new Error("Septum server is shutting down");
124
+ if (this.activeRequests >= RESOURCE_LIMITS.maxQueuePending) {
125
+ throw new WorkspaceBusyError(`Server is busy: workspace request limit (${RESOURCE_LIMITS.maxQueuePending}) exceeded.`);
126
+ }
127
+ this.activeRequests++;
128
+ try {
129
+ await waitForSharedWork(ctx.ready, signal);
130
+ signal?.throwIfAborted();
131
+ const registrationBeforeDiscovery =
132
+ isDomainRegistration && Object.keys(ctx.config.domains).length === 0 && ctx.repo.getAllDomains().length === 0;
133
+ try {
134
+ if (!registrationBeforeDiscovery) {
135
+ onSync?.();
136
+ await waitForSharedWork(ctx.watcher.flush(false), signal);
137
+ }
138
+ } catch (error) {
139
+ signal?.throwIfAborted();
140
+ if (!isDomainRegistration || !(error instanceof DomainRootConflictError)) throw error;
141
+ }
142
+ // Flush can enqueue work on the same lane. Reload and use policy only after
143
+ // admission, so another queued request cannot change the policy mid-call.
144
+ const runQueued = mode === "write" || isDomainRegistration
145
+ ? ctx.queue.runWrite.bind(ctx.queue)
146
+ : ctx.queue.runRead.bind(ctx.queue);
147
+ return await runQueued(async () => {
148
+ if (this.closed) throw new Error("Septum server is shutting down");
149
+ const syncError = ctx.repo.getMeta("sync_error");
150
+ if (syncError && !(isDomainRegistration && ctx.repo.getMeta("sync_error_code") === "DOMAIN_ROOT_CONFLICT")) {
151
+ throw new Error(`Workspace index synchronization failed: ${syncError}`);
152
+ }
153
+ ctx.config = ConfigLoader.load(undefined, ctx.root);
154
+ if (!isDomainRegistration) ctx.pipeline.assertDomainOwnership(ctx.config, ctx.root);
155
+ ctx.evaluator.getResolver().setRepository(ctx.repo);
156
+ return work(ctx);
157
+ }, signal);
158
+ } finally {
159
+ this.activeRequests--;
160
+ }
161
+ }
162
+
163
+ acquire(rawRoot: string, options: { deferDiscovery?: boolean } = {}): WorkspaceLease {
95
164
  if (this.closed) throw new Error('Septum server is shutting down');
96
165
  const root = realpathSync(rawRoot);
97
166
  let entry = this.contexts.get(root);
@@ -102,15 +171,26 @@ export class WorkspaceManager {
102
171
  this.dispose(idle);
103
172
  }
104
173
  const config = ConfigLoader.load(undefined, root);
105
- const db = new SeptumDatabase(resolve(root, config.settings.db_path || '.septum/septum.db'));
174
+ const db = new SeptumDatabase(resolveDatabasePath(root, config.settings.db_path));
106
175
  try {
107
176
  const repo = new SeptumRepository(db.raw);
108
177
  const pipeline = new IngestionPipeline(repo, root);
109
178
  const evaluator = new BoundaryEvaluator(repo, new ModuleResolver(root, repo));
110
179
  const abort = new AbortController();
111
- const ready = this.queue.run(async () => { abort.signal.throwIfAborted(); await pipeline.run(config, {verifyContent:true,signal:abort.signal}); });
112
- const watcher = new WorkspaceWatcher(root, repo, pipeline, ready, this.queue, this.budget, () => ConfigLoader.load(undefined, root));
113
- entry = {context:{root,config,db,repo,evaluator,pipeline,ready,watcher},leases:0,lastUsed:this.now(),initializing:true,abort};
180
+ const queue = new ReadWriteWorkQueue();
181
+ const ready = queue.runWrite(async () => {
182
+ abort.signal.throwIfAborted();
183
+ // An explicit first registration chooses ownership before discovery.
184
+ if (options.deferDiscovery && Object.keys(config.domains).length === 0 && repo.getAllDomains().length === 0) return;
185
+ try { await pipeline.run(config, {verifyContent:true,signal:abort.signal}); }
186
+ catch (error) {
187
+ // Keep a conflicting legacy workspace open for explicit domain repair.
188
+ // Its index remains in error and cannot serve normal tool requests.
189
+ if (!(error instanceof DomainRootConflictError)) throw error;
190
+ }
191
+ });
192
+ const watcher = new WorkspaceWatcher(root, repo, pipeline, ready, queue, this.budget, () => ConfigLoader.load(undefined, root));
193
+ entry = {context:{root,config,db,repo,evaluator,pipeline,ready,watcher,queue},leases:0,lastUsed:this.now(),initializing:true,abort};
114
194
  this.contexts.set(root, entry);
115
195
  const initialized = entry;
116
196
  void ready.then(() => { initialized.initializing = false; }, () => { initialized.initializing = false; this.dispose(initialized); });
@@ -130,10 +210,18 @@ export class WorkspaceManager {
130
210
  const stop = entry.context.watcher.close();
131
211
  // Eviction of an idle context closes its database before admitting another.
132
212
  if (idle) entry.context.db.close();
133
- const disposal = stop.then(async () => { if (!idle) { await this.queue.drain(); entry.context.db.close(); } });
213
+ const disposal = stop.then(async () => { if (!idle) { await entry.context.queue.drain(); entry.context.db.close(); } });
134
214
  entry.disposal = disposal;
135
215
  this.disposals.add(disposal);
136
- void disposal.finally(() => this.disposals.delete(disposal)).catch(error => console.error(`[Septum Cleanup Warning] ${String(error)}`));
216
+ void disposal.finally(() => this.disposals.delete(disposal)).catch(error =>
217
+ SeptumTelemetry.recordSystemEvent({
218
+ level: 'WARN',
219
+ component: 'workspace_manager',
220
+ event: 'workspace_disposal_failed',
221
+ fields: { message: String(error).slice(0, 256) },
222
+ workspaceRoot: entry.context.root,
223
+ })
224
+ );
137
225
  return disposal;
138
226
  }
139
227
 
@@ -142,15 +230,11 @@ export class WorkspaceManager {
142
230
  await Promise.all(expired.map(entry => this.dispose(entry)));
143
231
  }
144
232
 
145
- runTool<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
146
- return this.queue.run(() => { if (this.closed) throw new Error("Septum server is shutting down"); return work(); }, signal);
147
- }
148
-
149
233
  close(): Promise<void> {
150
234
  if (this.closing) return this.closing;
151
235
  this.closed = true; clearInterval(this.idleTimer);
152
236
  const pending = [...this.contexts.values()].map(entry => this.dispose(entry));
153
- this.closing = Promise.allSettled([...pending, ...this.disposals, this.queue.drain()]).then(results => {
237
+ this.closing = Promise.allSettled([...pending, ...this.disposals]).then(results => {
154
238
  const failed = results.find(result => result.status === 'rejected');
155
239
  if (failed?.status === 'rejected') throw failed.reason;
156
240
  });
@@ -1,12 +1,15 @@
1
1
  import { existsSync, lstatSync, readdirSync, watch, type FSWatcher } from 'node:fs';
2
2
  import { join, relative, resolve, isAbsolute } from 'node:path';
3
3
  import type { ValidatedSeptumConfig } from '../core/config/schema.ts';
4
+ import { SeptumTelemetry } from '../core/telemetry/telemetry.ts';
4
5
  import type { SeptumRepository } from '../core/database/repository.ts';
5
6
  import type { IngestionPipeline } from '../core/ingestion/pipeline.ts';
6
7
  import { ASTParserEngine } from '../core/parser/tree-sitter.ts';
8
+ import { isResolutionInput } from '../core/resolver/interpretation-inputs.ts';
9
+ import { rebuildSliceCatalog } from '../core/resolver/slice-catalog.ts';
7
10
  import { shouldIgnoreSourcePath } from '../core/resources/ignore.ts';
8
11
  import { RESOURCE_LIMITS } from '../core/resources/limits.ts';
9
- import { SerialWorkQueue } from '../core/resources/work-queue.ts';
12
+ import type { WorkQueue } from '../core/resources/work-queue.ts';
10
13
 
11
14
  export class WatchBudget {
12
15
  count = 0;
@@ -21,6 +24,7 @@ export class WorkspaceWatcher {
21
24
  private timer: ReturnType<typeof setTimeout> | null = null;
22
25
  private poll: ReturnType<typeof setInterval> | null = null;
23
26
  private flushing: Promise<void> | null = null;
27
+ private auditReconciliation?: Promise<void>;
24
28
  private closed = false;
25
29
  private reconcile = false;
26
30
  private lastVerify = 0;
@@ -34,7 +38,7 @@ export class WorkspaceWatcher {
34
38
  private readonly repo: SeptumRepository,
35
39
  private readonly pipeline: IngestionPipeline,
36
40
  private readonly ready: Promise<void>,
37
- private readonly queue: SerialWorkQueue,
41
+ private readonly queue: WorkQueue,
38
42
  private readonly budget: WatchBudget,
39
43
  private readonly loadConfig: () => ValidatedSeptumConfig,
40
44
  ) {
@@ -62,7 +66,13 @@ export class WorkspaceWatcher {
62
66
  this.clearWatches();
63
67
  this.mode = 'polling';
64
68
  this.repo.setMeta('watcher_mode', 'polling');
65
- console.error(`[Septum Watcher Warning] Using bounded polling: ${String(error)}`);
69
+ SeptumTelemetry.recordSystemEvent({
70
+ level: 'WARN',
71
+ component: 'watcher',
72
+ event: 'watcher_polling_fallback',
73
+ fields: { message: String(error).slice(0, 256) },
74
+ workspaceRoot: this.root,
75
+ });
66
76
  }
67
77
 
68
78
  private registerDirectories(): void {
@@ -71,9 +81,6 @@ export class WorkspaceWatcher {
71
81
  this.config = config;
72
82
  const seen = new Set<string>();
73
83
  const stack = [this.root];
74
- const domainRoots = Object.values(config.domains || {})
75
- .map(d => relative(this.root, resolve(this.root, d.root)).replace(/\\/g, '/').replace(/^\/|\/$/g, ''))
76
- .filter(dr => dr !== '.' && dr !== '');
77
84
  try {
78
85
  while (stack.length) {
79
86
  const dir = stack.pop()!;
@@ -99,10 +106,8 @@ export class WorkspaceWatcher {
99
106
  const childDir = join(dir, entry.name);
100
107
  const childRel = relative(this.root, childDir).replace(/\\/g, '/');
101
108
  if (shouldIgnoreSourcePath(childRel, config.settings.ignore_patterns)) continue;
102
- if (domainRoots.length > 0) {
103
- const isRelevant = domainRoots.some(dr => childRel === dr || childRel.startsWith(dr + '/') || dr.startsWith(childRel + '/'));
104
- if (!isRelevant) continue;
105
- }
109
+ // Semantic inputs may live outside registered domain roots.
110
+ // The shared watch budget still bounds this workspace inventory.
106
111
  stack.push(childDir);
107
112
  }
108
113
  }
@@ -122,7 +127,7 @@ export class WorkspaceWatcher {
122
127
  if (isAbsolute(rel) || rel === '..' || rel.startsWith('../') || shouldIgnoreSourcePath(norm, this.config.settings.ignore_patterns)) return;
123
128
  let directory = this.watches.has(target);
124
129
  try { directory ||= lstatSync(target).isDirectory(); } catch { /* deletion */ }
125
- if (directory || /(^|\/)(package\.json|composer\.json|nest-cli\.json|go\.mod|tsconfig\.json|artisan)$/.test(norm)) {
130
+ if (directory || isResolutionInput(norm)) {
126
131
  this.reconcile = true;
127
132
  this.pending.clear();
128
133
  } else if (ASTParserEngine.isSourceFile(norm)) {
@@ -137,7 +142,20 @@ export class WorkspaceWatcher {
137
142
  this.timer = setTimeout(() => { this.timer = null; void this.flush(false).catch(error => this.recordError(error)); }, RESOURCE_LIMITS.debounceMs);
138
143
  }
139
144
 
145
+ reconcileForAudit(): Promise<void> {
146
+ if (!this.auditReconciliation) {
147
+ this.auditReconciliation = this.flush(true).finally(() => {
148
+ this.auditReconciliation = undefined;
149
+ });
150
+ }
151
+ return this.auditReconciliation;
152
+ }
153
+
140
154
  async flush(forceVerify = true, signal?: AbortSignal): Promise<void> {
155
+ if (this.closed) return;
156
+ // Let already-ready FS notifications arrive before inspecting pending work.
157
+ // MCP requests and native watcher events can be queued in the same turn.
158
+ await new Promise<void>(done => setImmediate(done));
141
159
  if (this.closed) return;
142
160
  signal?.throwIfAborted();
143
161
  if (this.timer) { clearTimeout(this.timer); this.timer = null; }
@@ -172,16 +190,17 @@ export class WorkspaceWatcher {
172
190
  this.abort.signal.throwIfAborted();
173
191
  const target = resolve(this.root, filename);
174
192
  if (existsSync(target)) await this.pipeline.ingestFile(target, config);
175
- else this.repo.runInTransaction(() => {
176
- this.repo.deleteFileByPath(filename); this.repo.clearVerticalSlices(); this.repo.setMeta('slices_dirty', '1');
177
- const unsupported: string[] = JSON.parse(this.repo.getMeta('unsupported_files') || '[]');
178
- this.repo.setMeta('unsupported_files', JSON.stringify(unsupported.filter(path => path !== filename)));
179
- const skipped: {path: string; reason: string}[] = JSON.parse(this.repo.getMeta('skipped_files') || '[]');
180
- this.repo.setMeta('skipped_files', JSON.stringify(skipped.filter(file => file.path !== filename)));
181
- });
193
+ else this.pipeline.removeFile(filename);
182
194
  }
183
195
  }
184
- if (sourceEvents || this.repo.getMeta('slices_dirty') === '1') await this.pipeline.run(config, {signal: this.abort.signal});
196
+ if (this.repo.getMeta('slices_dirty') === '1') {
197
+ await rebuildSliceCatalog(this.repo, this.root, {
198
+ ignorePatterns: config.settings.ignore_patterns,
199
+ signal: this.abort.signal,
200
+ });
201
+ } else if (sourceEvents) {
202
+ await this.pipeline.run(config, {signal: this.abort.signal});
203
+ }
185
204
  }, signal);
186
205
  try { await this.flushing; }
187
206
  finally { this.flushing = null; }