@dimassetoid/septum-mcp 0.3.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +38 -55
  2. package/package.json +7 -5
  3. package/src/cli/commands/check.ts +14 -10
  4. package/src/cli/commands/hook.ts +41 -6
  5. package/src/cli/commands/init.ts +10 -1
  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 +32 -4
  9. package/src/cli/index.ts +7 -0
  10. package/src/cli/templates/hooks.ts +3 -14
  11. package/src/cli/templates/skill.ts +17 -10
  12. package/src/core/boundary/audit.ts +383 -0
  13. package/src/core/boundary/evaluator.ts +251 -114
  14. package/src/core/boundary/staged-auditor.ts +147 -55
  15. package/src/core/config/domain-ownership.ts +6 -4
  16. package/src/core/config/domain-registration.ts +141 -0
  17. package/src/core/config/loader.ts +1 -25
  18. package/src/core/config/schema.ts +24 -36
  19. package/src/core/database/client.ts +2 -0
  20. package/src/core/database/repositories/dependency.repository.ts +334 -572
  21. package/src/core/database/repositories/domain.repository.ts +2 -1
  22. package/src/core/database/repositories/file.repository.ts +10 -0
  23. package/src/core/database/repositories/symbol.repository.ts +97 -398
  24. package/src/core/database/repository.ts +68 -9
  25. package/src/core/database/schema.ts +26 -0
  26. package/src/core/discovery/declarative-routes.ts +69 -0
  27. package/src/core/discovery/framework-detector.ts +149 -0
  28. package/src/core/discovery/navigation.ts +222 -58
  29. package/src/core/discovery/topology-detector.ts +93 -168
  30. package/src/core/errors.ts +19 -0
  31. package/src/core/ingestion/pipeline.ts +287 -88
  32. package/src/core/parser/extractors/base.ts +11 -3
  33. package/src/core/parser/extractors/csharp.ts +2 -2
  34. package/src/core/parser/extractors/django-routing.ts +163 -0
  35. package/src/core/parser/extractors/django-semantic.ts +397 -481
  36. package/src/core/parser/extractors/elysia-semantic.ts +172 -475
  37. package/src/core/parser/extractors/express-semantic.ts +195 -383
  38. package/src/core/parser/extractors/fastapi-semantic.ts +178 -361
  39. package/src/core/parser/extractors/fastify-semantic.ts +216 -717
  40. package/src/core/parser/extractors/flask-semantic.ts +89 -352
  41. package/src/core/parser/extractors/go-routing.ts +344 -0
  42. package/src/core/parser/extractors/go-semantic.ts +205 -562
  43. package/src/core/parser/extractors/go.ts +6 -3
  44. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  45. package/src/core/parser/extractors/hono-semantic.ts +132 -509
  46. package/src/core/parser/extractors/java.ts +2 -2
  47. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  48. package/src/core/parser/extractors/laravel-semantic.ts +143 -335
  49. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  50. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +82 -333
  52. package/src/core/parser/extractors/nestjs-semantic.ts +238 -494
  53. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  54. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  55. package/src/core/parser/extractors/php.ts +1 -1
  56. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  57. package/src/core/parser/extractors/python.ts +5 -9
  58. package/src/core/parser/extractors/registry.ts +2 -0
  59. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  60. package/src/core/parser/extractors/ruby.ts +2 -2
  61. package/src/core/parser/extractors/rust.ts +4 -4
  62. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  63. package/src/core/parser/extractors/symfony-semantic.ts +72 -226
  64. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  65. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  66. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  67. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  68. package/src/core/parser/extractors/typescript.ts +23 -216
  69. package/src/core/parser/language-capabilities.ts +1 -1
  70. package/src/core/parser/schema/providers/laravel-migration-provider.ts +4 -1
  71. package/src/core/parser/wasm-loader.ts +6 -2
  72. package/src/core/resolver/ast-method-tracer.ts +230 -0
  73. package/src/core/resolver/call-graph-helpers.ts +72 -0
  74. package/src/core/resolver/call-graph-tracer.ts +169 -414
  75. package/src/core/resolver/dependency-analysis.ts +593 -0
  76. package/src/core/resolver/import-candidates.ts +120 -0
  77. package/src/core/resolver/import-evidence.ts +88 -0
  78. package/src/core/resolver/import-resolver.ts +60 -7
  79. package/src/core/resolver/interpretation-inputs.ts +60 -2
  80. package/src/core/resolver/languages/python.ts +31 -13
  81. package/src/core/resolver/languages/shared.ts +4 -1
  82. package/src/core/resolver/module-resolver.ts +10 -3
  83. package/src/core/resolver/path-resolver.ts +6 -3
  84. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  85. package/src/core/resolver/slice-catalog.ts +21 -6
  86. package/src/core/resolver/slice-format.ts +13 -0
  87. package/src/core/resolver/slice-selection.ts +237 -0
  88. package/src/core/resolver/symbol-impact.ts +104 -8
  89. package/src/core/resolver/symbol-locator.ts +82 -15
  90. package/src/core/resolver/vertical-slice-tracer.ts +31 -230
  91. package/src/core/resources/ignore.ts +0 -1
  92. package/src/core/resources/limits.ts +2 -1
  93. package/src/core/resources/work-queue.ts +167 -4
  94. package/src/core/retrieval/context-page.ts +11 -4
  95. package/src/core/retrieval/context.ts +363 -226
  96. package/src/{mcp/tools/get-symbol.ts → core/retrieval/source-context.ts} +145 -96
  97. package/src/core/retrieval/symbol-details.ts +453 -0
  98. package/src/core/retrieval/symbol-evidence.ts +3 -3
  99. package/src/core/retrieval/typescript-references.ts +38 -7
  100. package/src/core/retrieval/universal-context.ts +182 -0
  101. package/src/core/telemetry/summary.ts +114 -0
  102. package/src/core/telemetry/telemetry.ts +192 -49
  103. package/src/mcp/formatters/compact-text.ts +439 -0
  104. package/src/mcp/resources-and-prompts.ts +255 -0
  105. package/src/mcp/schemas/boundary.ts +145 -0
  106. package/src/mcp/schemas/map.ts +250 -0
  107. package/src/mcp/schemas/shared.ts +52 -0
  108. package/src/mcp/schemas/slice.ts +60 -0
  109. package/src/mcp/schemas/symbol.ts +268 -0
  110. package/src/mcp/schemas.ts +5 -746
  111. package/src/mcp/server.ts +269 -429
  112. package/src/mcp/tool-catalog.ts +331 -0
  113. package/src/mcp/tools/boundary.ts +68 -3
  114. package/src/mcp/tools/map.ts +104 -4
  115. package/src/mcp/tools/slice.ts +101 -3
  116. package/src/mcp/tools/symbol.ts +469 -17
  117. package/src/mcp/ui/app-client.ts +899 -0
  118. package/src/mcp/ui/app.html +478 -0
  119. package/src/mcp/workflow-playbooks.ts +181 -0
  120. package/src/mcp/workspace-boundary.ts +50 -0
  121. package/src/mcp/workspace-manager.ts +88 -15
  122. package/src/mcp/workspace-watcher.ts +30 -11
  123. package/src/types/index.ts +12 -0
  124. package/src/mcp/tools/check-boundary.ts +0 -382
  125. package/src/mcp/tools/get-domain-catalog.ts +0 -39
  126. package/src/mcp/tools/get-symbol-impact.ts +0 -104
  127. package/src/mcp/tools/locate-symbol.ts +0 -236
  128. package/src/mcp/tools/register-domain.ts +0 -113
  129. package/src/mcp/tools/trace-vertical-slice.ts +0 -106
@@ -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
+ }
@@ -7,12 +7,14 @@ 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
15
  import { DomainRootConflictError } from '../core/config/domain-ownership.ts';
16
+ import { WorkspaceBusyError } from '../core/errors.ts';
17
+ import { SeptumTelemetry } from '../core/telemetry/telemetry.ts';
16
18
 
17
19
  export function resolveServerWorkspace(options: {workspacePath?: string; filePath?: string; fallbackRoot?: string; knownRoots?: string[]; initial?: boolean; cwd?: string} = {}): string {
18
20
  const cwd = options.cwd || process.cwd();
@@ -45,7 +47,6 @@ export function resolveServerWorkspace(options: {workspacePath?: string; filePat
45
47
  }
46
48
  }
47
49
 
48
- setLastKnownProjectRoot(root);
49
50
  return root;
50
51
  }
51
52
 
@@ -68,23 +69,34 @@ export interface WorkspaceContext {
68
69
  pipeline: IngestionPipeline;
69
70
  ready: Promise<void>;
70
71
  watcher: WorkspaceWatcher;
72
+ queue: ReadWriteWorkQueue;
71
73
  }
72
74
  interface Entry { context: WorkspaceContext; leases: number; lastUsed: number; initializing: boolean; abort: AbortController; disposal?: Promise<void> }
73
75
  export interface WorkspaceLease { context: WorkspaceContext; release(): void }
74
76
 
75
77
  export class WorkspaceManager {
76
78
  private contexts = new Map<string, Entry>();
77
- private queue = new SerialWorkQueue();
78
79
  private budget = new WatchBudget();
79
80
  private disposals = new Set<Promise<void>>();
80
81
  private closed = false;
82
+ private activeRequests = 0;
81
83
  private closing: Promise<void> | null = null;
82
84
  private idleTimer: ReturnType<typeof setInterval>;
83
85
  initialRoot?: string;
84
86
  lastRoot?: string;
85
87
  get activeRoots(): string[] { return [...this.contexts.keys()]; }
86
88
  constructor(private readonly now: () => number = Date.now) {
87
- 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);
88
100
  this.idleTimer.unref();
89
101
  }
90
102
  get size(): number { return this.contexts.size; }
@@ -92,6 +104,62 @@ export class WorkspaceManager {
92
104
  get syncDurationMs(): number { return Math.max(0, ...[...this.contexts.values()].map(entry => Number(entry.context.repo.getMeta("sync_duration_ms") || 0))); }
93
105
  get pendingPaths(): number { return [...this.contexts.values()].reduce((n, entry) => n + entry.context.watcher.pendingCount, 0); }
94
106
 
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
+
95
163
  acquire(rawRoot: string, options: { deferDiscovery?: boolean } = {}): WorkspaceLease {
96
164
  if (this.closed) throw new Error('Septum server is shutting down');
97
165
  const root = realpathSync(rawRoot);
@@ -109,7 +177,8 @@ export class WorkspaceManager {
109
177
  const pipeline = new IngestionPipeline(repo, root);
110
178
  const evaluator = new BoundaryEvaluator(repo, new ModuleResolver(root, repo));
111
179
  const abort = new AbortController();
112
- const ready = this.queue.run(async () => {
180
+ const queue = new ReadWriteWorkQueue();
181
+ const ready = queue.runWrite(async () => {
113
182
  abort.signal.throwIfAborted();
114
183
  // An explicit first registration chooses ownership before discovery.
115
184
  if (options.deferDiscovery && Object.keys(config.domains).length === 0 && repo.getAllDomains().length === 0) return;
@@ -120,8 +189,8 @@ export class WorkspaceManager {
120
189
  if (!(error instanceof DomainRootConflictError)) throw error;
121
190
  }
122
191
  });
123
- const watcher = new WorkspaceWatcher(root, repo, pipeline, ready, this.queue, this.budget, () => ConfigLoader.load(undefined, root));
124
- entry = {context:{root,config,db,repo,evaluator,pipeline,ready,watcher},leases:0,lastUsed:this.now(),initializing:true,abort};
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};
125
194
  this.contexts.set(root, entry);
126
195
  const initialized = entry;
127
196
  void ready.then(() => { initialized.initializing = false; }, () => { initialized.initializing = false; this.dispose(initialized); });
@@ -141,10 +210,18 @@ export class WorkspaceManager {
141
210
  const stop = entry.context.watcher.close();
142
211
  // Eviction of an idle context closes its database before admitting another.
143
212
  if (idle) entry.context.db.close();
144
- 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(); } });
145
214
  entry.disposal = disposal;
146
215
  this.disposals.add(disposal);
147
- 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
+ );
148
225
  return disposal;
149
226
  }
150
227
 
@@ -153,15 +230,11 @@ export class WorkspaceManager {
153
230
  await Promise.all(expired.map(entry => this.dispose(entry)));
154
231
  }
155
232
 
156
- runTool<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
157
- return this.queue.run(() => { if (this.closed) throw new Error("Septum server is shutting down"); return work(); }, signal);
158
- }
159
-
160
233
  close(): Promise<void> {
161
234
  if (this.closing) return this.closing;
162
235
  this.closed = true; clearInterval(this.idleTimer);
163
236
  const pending = [...this.contexts.values()].map(entry => this.dispose(entry));
164
- this.closing = Promise.allSettled([...pending, ...this.disposals, this.queue.drain()]).then(results => {
237
+ this.closing = Promise.allSettled([...pending, ...this.disposals]).then(results => {
165
238
  const failed = results.find(result => result.status === 'rejected');
166
239
  if (failed?.status === 'rejected') throw failed.reason;
167
240
  });
@@ -1,13 +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';
7
8
  import { isResolutionInput } from '../core/resolver/interpretation-inputs.ts';
9
+ import { rebuildSliceCatalog } from '../core/resolver/slice-catalog.ts';
8
10
  import { shouldIgnoreSourcePath } from '../core/resources/ignore.ts';
9
11
  import { RESOURCE_LIMITS } from '../core/resources/limits.ts';
10
- import { SerialWorkQueue } from '../core/resources/work-queue.ts';
12
+ import type { WorkQueue } from '../core/resources/work-queue.ts';
11
13
 
12
14
  export class WatchBudget {
13
15
  count = 0;
@@ -22,6 +24,7 @@ export class WorkspaceWatcher {
22
24
  private timer: ReturnType<typeof setTimeout> | null = null;
23
25
  private poll: ReturnType<typeof setInterval> | null = null;
24
26
  private flushing: Promise<void> | null = null;
27
+ private auditReconciliation?: Promise<void>;
25
28
  private closed = false;
26
29
  private reconcile = false;
27
30
  private lastVerify = 0;
@@ -35,7 +38,7 @@ export class WorkspaceWatcher {
35
38
  private readonly repo: SeptumRepository,
36
39
  private readonly pipeline: IngestionPipeline,
37
40
  private readonly ready: Promise<void>,
38
- private readonly queue: SerialWorkQueue,
41
+ private readonly queue: WorkQueue,
39
42
  private readonly budget: WatchBudget,
40
43
  private readonly loadConfig: () => ValidatedSeptumConfig,
41
44
  ) {
@@ -63,7 +66,13 @@ export class WorkspaceWatcher {
63
66
  this.clearWatches();
64
67
  this.mode = 'polling';
65
68
  this.repo.setMeta('watcher_mode', 'polling');
66
- 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
+ });
67
76
  }
68
77
 
69
78
  private registerDirectories(): void {
@@ -133,6 +142,15 @@ export class WorkspaceWatcher {
133
142
  this.timer = setTimeout(() => { this.timer = null; void this.flush(false).catch(error => this.recordError(error)); }, RESOURCE_LIMITS.debounceMs);
134
143
  }
135
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
+
136
154
  async flush(forceVerify = true, signal?: AbortSignal): Promise<void> {
137
155
  if (this.closed) return;
138
156
  // Let already-ready FS notifications arrive before inspecting pending work.
@@ -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; }
@@ -15,6 +15,11 @@ export type ArchetypeKind =
15
15
  | "route"
16
16
  | "util"
17
17
  | "view"
18
+ | "config"
19
+ | "parser"
20
+ | "resolver"
21
+ | "pipeline"
22
+ | "server"
18
23
  | "unknown";
19
24
 
20
25
  export type SymbolKind =
@@ -58,6 +63,7 @@ export interface CheckBoundaryArgs {
58
63
  proposed_imports?: string[];
59
64
  scope?: "file" | "all" | "staged" | "domain";
60
65
  domain?: string;
66
+ format?: "json" | "text";
61
67
  workspace_path?: string;
62
68
  }
63
69
 
@@ -200,6 +206,7 @@ export interface BoundaryViolation {
200
206
  imported_target: string;
201
207
  rule: BoundaryViolationRule;
202
208
  message: string;
209
+ pre_existing?: boolean;
203
210
  }
204
211
 
205
212
  export interface FileConnectionsSummary {
@@ -265,6 +272,8 @@ export interface NavigationEntrypoint {
265
272
 
266
273
  export interface ExecutionChainNode {
267
274
  relationship?: { kind: "imports" | "declares" | "member_of" | "calls" | "route_binding" | "schema_binding"; derivation: "source" | "inferred"; source?: { file: string; line: number; statement?: string }; reason: string };
275
+ parent_symbol?: string;
276
+ depth?: number;
268
277
 
269
278
  stage:
270
279
  | "ingress"
@@ -361,7 +370,9 @@ export interface GetSymbolArgs {
361
370
  include_source?: boolean;
362
371
  source_start_line?: number;
363
372
  source_line_limit?: number;
373
+ budget_bytes?: number;
364
374
  semantic_depth?: number;
375
+ format?: "json" | "text";
365
376
  workspace_path?: string;
366
377
  }
367
378
 
@@ -412,6 +423,7 @@ export interface GetSymbolImpactArgs {
412
423
  query?: string;
413
424
  file_path?: string;
414
425
  symbol_ref?: SymbolReference;
426
+ format?: "json" | "text";
415
427
  workspace_path?: string;
416
428
  }
417
429