@dimassetoid/septum-mcp 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +133 -0
  7. package/src/cli/commands/hook.ts +205 -0
  8. package/src/cli/commands/init.ts +570 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +39 -0
  11. package/src/cli/hook-payload.ts +43 -0
  12. package/src/cli/index.ts +124 -0
  13. package/src/cli/scaffold/harness-config.ts +661 -0
  14. package/src/cli/templates/hooks.ts +110 -0
  15. package/src/cli/templates/rules.ts +35 -0
  16. package/src/cli/templates/skill.ts +55 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +426 -0
  19. package/src/core/boundary/staged-auditor.ts +120 -0
  20. package/src/core/config/domain-ownership.ts +45 -0
  21. package/src/core/config/loader.ts +174 -0
  22. package/src/core/config/schema.ts +59 -0
  23. package/src/core/database/client.ts +60 -0
  24. package/src/core/database/repositories/dependency.repository.ts +733 -0
  25. package/src/core/database/repositories/domain.repository.ts +373 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +647 -0
  29. package/src/core/database/repository.ts +358 -0
  30. package/src/core/database/schema.ts +123 -0
  31. package/src/core/discovery/navigation.ts +105 -0
  32. package/src/core/discovery/topology-detector.ts +863 -0
  33. package/src/core/ingestion/hasher.ts +5 -0
  34. package/src/core/ingestion/pipeline.ts +590 -0
  35. package/src/core/parser/behavioral-analyzer.ts +123 -0
  36. package/src/core/parser/boundary-tracker.ts +458 -0
  37. package/src/core/parser/extractors/base.ts +71 -0
  38. package/src/core/parser/extractors/blade.ts +159 -0
  39. package/src/core/parser/extractors/csharp.ts +248 -0
  40. package/src/core/parser/extractors/django-semantic.ts +655 -0
  41. package/src/core/parser/extractors/elysia-semantic.ts +517 -0
  42. package/src/core/parser/extractors/express-semantic.ts +429 -0
  43. package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
  44. package/src/core/parser/extractors/fastify-semantic.ts +759 -0
  45. package/src/core/parser/extractors/flask-semantic.ts +482 -0
  46. package/src/core/parser/extractors/frontend.ts +149 -0
  47. package/src/core/parser/extractors/go-semantic.ts +670 -0
  48. package/src/core/parser/extractors/go.ts +491 -0
  49. package/src/core/parser/extractors/hono-semantic.ts +546 -0
  50. package/src/core/parser/extractors/java.ts +227 -0
  51. package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
  52. package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
  53. package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
  54. package/src/core/parser/extractors/php.ts +585 -0
  55. package/src/core/parser/extractors/python.ts +503 -0
  56. package/src/core/parser/extractors/registry.ts +99 -0
  57. package/src/core/parser/extractors/ruby.ts +237 -0
  58. package/src/core/parser/extractors/rust.ts +304 -0
  59. package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
  60. package/src/core/parser/extractors/symfony-semantic.ts +321 -0
  61. package/src/core/parser/extractors/typescript.ts +839 -0
  62. package/src/core/parser/implementation-fingerprint.ts +97 -0
  63. package/src/core/parser/language-capabilities.ts +87 -0
  64. package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
  65. package/src/core/parser/schema/schema-provider-registry.ts +41 -0
  66. package/src/core/parser/schema/schema-provider.interface.ts +34 -0
  67. package/src/core/parser/semantic-revision.ts +3 -0
  68. package/src/core/parser/static-string.ts +51 -0
  69. package/src/core/parser/tree-sitter.ts +63 -0
  70. package/src/core/parser/wasm-assets.ts +25 -0
  71. package/src/core/parser/wasm-loader.ts +274 -0
  72. package/src/core/resolver/call-graph-tracer.ts +1033 -0
  73. package/src/core/resolver/import-resolver.ts +365 -0
  74. package/src/core/resolver/interpretation-inputs.ts +7 -0
  75. package/src/core/resolver/languages/go.ts +103 -0
  76. package/src/core/resolver/languages/managed.ts +200 -0
  77. package/src/core/resolver/languages/python.ts +115 -0
  78. package/src/core/resolver/languages/ruby.ts +40 -0
  79. package/src/core/resolver/languages/rust.ts +127 -0
  80. package/src/core/resolver/languages/shared.ts +71 -0
  81. package/src/core/resolver/module-resolver.ts +486 -0
  82. package/src/core/resolver/path-resolver.ts +200 -0
  83. package/src/core/resolver/slice-catalog.ts +79 -0
  84. package/src/core/resolver/slice-format.ts +9 -0
  85. package/src/core/resolver/symbol-impact.ts +381 -0
  86. package/src/core/resolver/symbol-locator.ts +276 -0
  87. package/src/core/resolver/symbol-reference.ts +53 -0
  88. package/src/core/resolver/vertical-slice-tracer.ts +344 -0
  89. package/src/core/resources/ignore.ts +144 -0
  90. package/src/core/resources/limits.ts +14 -0
  91. package/src/core/resources/source-files.ts +185 -0
  92. package/src/core/resources/source-inventory.ts +55 -0
  93. package/src/core/resources/work-queue.ts +74 -0
  94. package/src/core/retrieval/context-page.ts +109 -0
  95. package/src/core/retrieval/context.ts +320 -0
  96. package/src/core/retrieval/resolution-warnings.ts +21 -0
  97. package/src/core/retrieval/symbol-evidence.ts +97 -0
  98. package/src/core/retrieval/typescript-references.ts +262 -0
  99. package/src/core/telemetry/telemetry.ts +142 -0
  100. package/src/index.ts +18 -0
  101. package/src/mcp/schemas.ts +746 -0
  102. package/src/mcp/server.ts +600 -0
  103. package/src/mcp/tools/boundary.ts +17 -0
  104. package/src/mcp/tools/check-boundary.ts +382 -0
  105. package/src/mcp/tools/get-domain-catalog.ts +39 -0
  106. package/src/mcp/tools/get-symbol-impact.ts +104 -0
  107. package/src/mcp/tools/get-symbol.ts +399 -0
  108. package/src/mcp/tools/locate-symbol.ts +236 -0
  109. package/src/mcp/tools/map.ts +26 -0
  110. package/src/mcp/tools/register-domain.ts +113 -0
  111. package/src/mcp/tools/slice.ts +16 -0
  112. package/src/mcp/tools/symbol.ts +95 -0
  113. package/src/mcp/tools/trace-vertical-slice.ts +106 -0
  114. package/src/mcp/workspace-manager.ts +170 -0
  115. package/src/mcp/workspace-watcher.ts +202 -0
  116. package/src/types/index.ts +438 -0
  117. package/src/types/wasm.d.ts +4 -0
  118. package/src/utils/version-check.ts +209 -0
  119. package/src/version.ts +1 -0
@@ -0,0 +1,113 @@
1
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
+ import type { SeptumRepository } from "../../core/database/repository.ts";
3
+ import { IngestionPipeline, type IngestionMetrics } from "../../core/ingestion/pipeline.ts";
4
+ import { assertPathContained } from "../../core/resolver/path-resolver.ts";
5
+ import { assertUniqueDomainRoots, domainNameKey, domainRootIdentity } from "../../core/config/domain-ownership.ts";
6
+ import type { RegisterDomainArgs } from "../schemas.ts";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { ConfigLoader } from "../../core/config/loader.ts";
10
+ import { SeptumConfigSchema } from "../../core/config/schema.ts";
11
+
12
+ export type { RegisterDomainArgs } from "../schemas.ts";
13
+
14
+ export async function handleRegisterDomain(
15
+ repo: SeptumRepository,
16
+ config: ValidatedSeptumConfig,
17
+ args: Partial<RegisterDomainArgs>,
18
+ workspaceRoot: string = process.cwd(),
19
+ signal?: AbortSignal
20
+ ) {
21
+ signal?.throwIfAborted();
22
+ const domainName = (args.domain || args.name || "").trim();
23
+ if (!domainName || !args.root) {
24
+ throw new Error("Missing required arguments: 'domain' (or 'name') and 'root' are required.");
25
+ }
26
+
27
+ // SV-02: Enforce workspace containment (reject traversal/absolute/symlink escape)
28
+ assertPathContained(args.root, workspaceRoot, "Domain root");
29
+ signal?.throwIfAborted();
30
+
31
+ const domainConfig = {
32
+ root: args.root,
33
+ description: args.description || `Domain: ${domainName}`,
34
+ allowed_dependencies: args.allowed_dependencies,
35
+ forbidden_dependencies: args.forbidden_dependencies,
36
+ archetypes: args.archetypes,
37
+ };
38
+
39
+ const proposed = domainRootIdentity(args.root, workspaceRoot);
40
+ const claims = Object.fromEntries(Object.entries(config.domains).filter(([name, claim]) =>
41
+ domainNameKey(name) !== domainNameKey(domainName) && domainRootIdentity(claim.root, workspaceRoot) === proposed));
42
+ assertUniqueDomainRoots({ ...claims, [domainName]: domainConfig }, workspaceRoot);
43
+
44
+ const policyFile = join(workspaceRoot, "septum.config.json");
45
+ const policySource = existsSync(policyFile) ? readFileSync(policyFile, "utf8") : undefined;
46
+ if (policySource !== undefined) {
47
+ const policy = SeptumConfigSchema.parse(JSON.parse(policySource));
48
+ const existing = Object.entries(policy.domains).find(([name]) => domainNameKey(name) === domainNameKey(domainName))?.[1];
49
+ domainConfig.allowed_dependencies ??= existing?.allowed_dependencies ?? [];
50
+ domainConfig.forbidden_dependencies ??= existing?.forbidden_dependencies ?? [];
51
+ domainConfig.archetypes ??= existing?.archetypes ?? {};
52
+ domainConfig.description = args.description ?? existing?.description ?? domainConfig.description;
53
+ const claims = Object.fromEntries(Object.entries(policy.domains).filter(([name, claim]) =>
54
+ domainNameKey(name) !== domainNameKey(domainName) && domainRootIdentity(claim.root, workspaceRoot) === proposed));
55
+ assertUniqueDomainRoots({ ...claims, [domainName]: domainConfig }, workspaceRoot);
56
+ }
57
+ const domainId = repo.runInTransaction(() => {
58
+ const id = repo.domains.upsertDomain(domainName, domainConfig, workspaceRoot);
59
+ const stored = repo.domains.getDomainByName(domainName)!;
60
+ if (policySource !== undefined) ConfigLoader.writeDomain(workspaceRoot, stored.name, {
61
+ ...domainConfig,
62
+ allowed_dependencies: JSON.parse(stored.allowed_deps_json),
63
+ forbidden_dependencies: JSON.parse(stored.forbidden_deps_json),
64
+ archetypes: JSON.parse(stored.archetypes_json),
65
+ }, policySource);
66
+ return id;
67
+ }, true);
68
+ const stored = repo.domains.getDomainByName(domainName);
69
+ const canonicalName = stored?.name || domainName;
70
+ const finalConfig = {
71
+ root: stored?.root_path || domainConfig.root,
72
+ description: domainConfig.description,
73
+ allowed_dependencies: stored ? JSON.parse(stored.allowed_deps_json || "[]") : (domainConfig.allowed_dependencies || []),
74
+ forbidden_dependencies: stored ? JSON.parse(stored.forbidden_deps_json || "[]") : (domainConfig.forbidden_dependencies || []),
75
+ archetypes: stored ? JSON.parse(stored.archetypes_json || "{}") : (domainConfig.archetypes || {}),
76
+ };
77
+
78
+ config.domains[canonicalName] = finalConfig;
79
+
80
+ let ingestionMetrics: IngestionMetrics | null = null;
81
+ if (args.ingest_now) {
82
+ const pipeline = new IngestionPipeline(repo, workspaceRoot);
83
+ ingestionMetrics = await pipeline.run(config, { signal });
84
+ }
85
+
86
+ return {
87
+ content: [
88
+ {
89
+ type: "text" as const,
90
+ text: JSON.stringify(
91
+ {
92
+ status: "success",
93
+ policy_owner: policySource === undefined ? "database" : "file",
94
+ message: `Domain '${canonicalName}' successfully registered in ${policySource === undefined ? "SQLite" : "septum.config.json"}.${
95
+ args.ingest_now ? " Initial ingestion completed." : ""
96
+ }`,
97
+ domain_id: domainId,
98
+ domain: canonicalName,
99
+ name: canonicalName,
100
+ config: finalConfig,
101
+ ...(repo.getMeta("sync_error_code") === "DOMAIN_ROOT_CONFLICT" ? {
102
+ index_status: { sync_state: "error", code: "DOMAIN_ROOT_CONFLICT" },
103
+ next: ["Resolve any remaining duplicate roots, then sync before using indexed facts. Registration success only records this policy change."],
104
+ } : {}),
105
+ ...(ingestionMetrics ? { ingestion_metrics: ingestionMetrics } : {}),
106
+ },
107
+ null,
108
+ 2
109
+ ),
110
+ },
111
+ ],
112
+ };
113
+ }
@@ -0,0 +1,16 @@
1
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
+ import type { SeptumRepository } from "../../core/database/repository.ts";
3
+ import type { SliceToolArgs } from "../schemas.ts";
4
+ import { handleTraceVerticalSlice } from "./trace-vertical-slice.ts";
5
+
6
+ export type { SliceToolArgs };
7
+
8
+ export function handleSliceTool(
9
+ repo: SeptumRepository,
10
+ config: ValidatedSeptumConfig,
11
+ args: SliceToolArgs,
12
+ workspaceRoot?: string,
13
+ signal?: AbortSignal
14
+ ) {
15
+ return handleTraceVerticalSlice(repo, config, args, workspaceRoot, signal);
16
+ }
@@ -0,0 +1,95 @@
1
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
+ import type { SeptumRepository } from "../../core/database/repository.ts";
3
+ import type { IngestionPipeline } from "../../core/ingestion/pipeline.ts";
4
+ import type { SymbolToolArgs } from "../schemas.ts";
5
+ import { handleLocateSymbol } from "./locate-symbol.ts";
6
+ import { handleGetSymbol } from "./get-symbol.ts";
7
+ import { handleGetSymbolImpact } from "./get-symbol-impact.ts";
8
+ import { retrieveContext } from "../../core/retrieval/context.ts";
9
+ import { symbolWorkspace } from "../../core/retrieval/symbol-evidence.ts";
10
+
11
+ export type { SymbolToolArgs };
12
+
13
+ export async function handleSymbolTool(
14
+ repo: SeptumRepository,
15
+ config: ValidatedSeptumConfig,
16
+ args: SymbolToolArgs,
17
+ pipeline?: IngestionPipeline,
18
+ workspaceRoot?: string,
19
+ signal?: AbortSignal
20
+ ) {
21
+ const action = args.action || "locate";
22
+
23
+ switch (action) {
24
+ case "context":
25
+ case "inspect": {
26
+ const symbol = args.symbol_ref?.name || args.symbol || args.query || "";
27
+ const candidates = repo.findSymbolsByName(symbol, {
28
+ domain: args.domain, filePath: args.file_path, reference: args.symbol_ref,
29
+ });
30
+ const targetPath = candidates.length === 1 ? candidates[0]!.file_path : args.symbol_ref?.file_path || args.file_path;
31
+ const bounded = args.context_mode === "source" || args.include_source !== undefined || args.source_start_line !== undefined || args.source_line_limit !== undefined;
32
+ if (args.context_mode === "deep" || !bounded && (!targetPath || /\.(?:ts|mts|cts)$/.test(targetPath))) {
33
+ return retrieveContext(repo, config, args, symbolWorkspace(repo, workspaceRoot || args.workspace_path), signal);
34
+ }
35
+ if (args.continuation !== undefined || args.budget_bytes !== undefined) {
36
+ return { content: [{ type: "text" as const, text: JSON.stringify({
37
+ status: "invalid_context_options",
38
+ message: "budget_bytes and continuation apply to deep TypeScript context. For bounded source use source_start_line and source_line_limit.",
39
+ }) }] };
40
+ }
41
+ return handleGetSymbol(
42
+ repo,
43
+ config,
44
+ {
45
+ symbol,
46
+ query: symbol,
47
+ domain: args.domain,
48
+ file_path: args.file_path,
49
+ symbol_ref: args.symbol_ref,
50
+ include_dependencies: args.include_dependencies,
51
+ include_source: args.include_source ?? true,
52
+ source_start_line: args.source_start_line,
53
+ source_line_limit: args.source_line_limit,
54
+ semantic_depth: args.semantic_depth,
55
+ workspace_path: args.workspace_path,
56
+ },
57
+ workspaceRoot
58
+ );
59
+ }
60
+
61
+ case "impact": {
62
+ const symbol = args.symbol || args.query || args.symbol_ref?.name || "";
63
+ return handleGetSymbolImpact(
64
+ repo,
65
+ config,
66
+ {
67
+ symbol,
68
+ query: symbol,
69
+ domain: args.domain,
70
+ file_path: args.file_path,
71
+ symbol_ref: args.symbol_ref,
72
+ workspace_path: args.workspace_path,
73
+ },
74
+ workspaceRoot
75
+ );
76
+ }
77
+
78
+ case "locate":
79
+ default:
80
+ return await handleLocateSymbol(
81
+ repo,
82
+ config,
83
+ {
84
+ query: args.query || args.symbol || "",
85
+ domain: args.domain,
86
+ file_path: args.file_path,
87
+ symbol_ref: args.symbol_ref,
88
+ limit: args.limit ?? 10,
89
+ workspace_path: args.workspace_path,
90
+ },
91
+ pipeline,
92
+ workspaceRoot
93
+ );
94
+ }
95
+ }
@@ -0,0 +1,106 @@
1
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
+ import type { SeptumRepository } from "../../core/database/repository.ts";
3
+ import { VerticalSliceTracer } from "../../core/resolver/vertical-slice-tracer.ts";
4
+ import type { VerticalSliceTraceResponse } from "../../types/index.ts";
5
+ import type { TraceVerticalSliceArgs } from "../schemas.ts";
6
+ import { formatSliceNode, SLICE_RELATIONSHIP_LIMITS } from "../../core/resolver/slice-format.ts";
7
+
8
+ export type { TraceVerticalSliceArgs } from "../schemas.ts";
9
+
10
+ export function handleTraceVerticalSlice(
11
+ repo: SeptumRepository,
12
+ config: ValidatedSeptumConfig,
13
+ args: Partial<TraceVerticalSliceArgs> & { route?: string },
14
+ workspaceRoot?: string,
15
+ signal?: AbortSignal
16
+ ) {
17
+ const query = (
18
+ args.query ||
19
+ args.symbol ||
20
+ args.route ||
21
+ ""
22
+ ).toString().trim();
23
+
24
+ if (!query) {
25
+ throw new Error(
26
+ "Missing required argument: 'query' (e.g. 'POST /orders/{id}/status', 'OrderController@updateStatus', or task intent 'Ubah status order di dashboard')"
27
+ );
28
+ }
29
+
30
+ const root =
31
+ workspaceRoot ||
32
+ args.workspace_path ||
33
+ ((config.settings as Record<string, unknown>)?.workspace_root as string) ||
34
+ process.cwd();
35
+ const maxDepth = Math.min(Math.max(Math.trunc(Number(args.max_depth ?? 5)), 1), 8);
36
+ const tracer = new VerticalSliceTracer(repo, root, config.settings.ignore_patterns, false);
37
+ return tracer.traceAsync(query, maxDepth, signal, args.controller_file).then((result: VerticalSliceTraceResponse) => {
38
+ const chain = result.chain || result.slice || [];
39
+
40
+ let summary = "";
41
+ if (result.found && chain.length > 0) {
42
+ summary = chain.map(formatSliceNode).join("\n");
43
+ } else if (result.found && result.entrypoint) {
44
+ summary = `[ENTRYPOINT] ${result.entrypoint.method} ${result.entrypoint.uri}; catalog handler ${result.entrypoint.controller}@${result.entrypoint.action} [unknown; unknown]`;
45
+ } else if (result.diagnostics?.length) {
46
+ summary = ` [UNKNOWN] ${result.message || `No matching slice in the available static catalog for '${query}'.`}`.trim();
47
+ } else {
48
+ summary = `[NOT FOUND] No matching slice in the available static catalog for '${query}'; this does not prove the route is absent at runtime.`;
49
+ }
50
+ if (result.diagnostics?.includes("ambiguous_target")) {
51
+ summary = `[AMBIGUOUS] ${result.message}`;
52
+ } else if (result.diagnostics?.length && result.found) {
53
+ summary = `[UNKNOWN: ${result.diagnostics.join(", ")}]\n${summary}`;
54
+ }
55
+
56
+ const nextHints = result.next ?? [
57
+ result.found && result.entrypoint?.action && result.entrypoint?.file
58
+ ? `Use septum_symbol(action='context', query='${result.entrypoint.action}', file_path='${result.entrypoint.file}') to inspect handler source/contracts; read the selected mode, freshness and omissions.`
59
+ : result.found
60
+ ? "Inspect the selected implementation and unresolved relationships before planning edits."
61
+ : "Refine the query or synchronize the workspace; no match does not prove runtime absence.",
62
+ ];
63
+
64
+ const payload = {
65
+ status: result.diagnostics?.includes("ambiguous_target") ? "ambiguous" : result.diagnostics?.length ? "unknown" : result.found ? "success" : "not_found",
66
+ coverage: result.coverage,
67
+ diagnostics: result.diagnostics,
68
+ next: nextHints,
69
+ controller_file_filter: args.controller_file ?? null,
70
+ query,
71
+ found: result.found,
72
+ confidence: result.confidence,
73
+ confidence_scope: "query_to_catalog_target_only",
74
+ relationship_limits: SLICE_RELATIONSHIP_LIMITS,
75
+ execution_order: "not_established",
76
+ branch_scope: "Static relationships can span mutually exclusive handler actions; this is not one executed branch.",
77
+ is_exact_match: result.is_exact_match,
78
+ architecture_style: result.architecture_style,
79
+ max_depth_applied: result.max_depth_applied ?? maxDepth,
80
+ entrypoint: result.entrypoint || null,
81
+ chain,
82
+ alternatives: result.alternatives || [],
83
+ candidate_count: result.candidate_count,
84
+ alternatives_omitted: result.alternatives_omitted,
85
+ summary,
86
+ message: result.message || summary,
87
+ };
88
+
89
+ return {
90
+ content: [
91
+ {
92
+ type: "text" as const,
93
+ text: JSON.stringify(payload),
94
+ },
95
+ ],
96
+ metadata: {
97
+ status: payload.status,
98
+ found: payload.found,
99
+ confidence: payload.confidence,
100
+ query: payload.query,
101
+ chain_length: payload.chain.length,
102
+ },
103
+ };
104
+ });
105
+ }
106
+
@@ -0,0 +1,170 @@
1
+ import { existsSync, realpathSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { ConfigLoader, resolveDatabasePath } from '../core/config/loader.ts';
5
+ import type { ValidatedSeptumConfig } from '../core/config/schema.ts';
6
+ import { SeptumDatabase } from '../core/database/client.ts';
7
+ import { SeptumRepository } from '../core/database/repository.ts';
8
+ import { BoundaryEvaluator } from '../core/boundary/evaluator.ts';
9
+ import { ModuleResolver } from '../core/resolver/module-resolver.ts';
10
+ import { findProjectRoot, isAppHostDirectory, isPathContained, PROJECT_ROOT_MARKERS, setLastKnownProjectRoot } from '../core/resolver/path-resolver.ts';
11
+ import { IngestionPipeline } from '../core/ingestion/pipeline.ts';
12
+ import { RESOURCE_LIMITS } from '../core/resources/limits.ts';
13
+ import { SerialWorkQueue } from '../core/resources/work-queue.ts';
14
+ import { WatchBudget, WorkspaceWatcher } from './workspace-watcher.ts';
15
+ import { DomainRootConflictError } from '../core/config/domain-ownership.ts';
16
+
17
+ export function resolveServerWorkspace(options: {workspacePath?: string; filePath?: string; fallbackRoot?: string; knownRoots?: string[]; initial?: boolean; cwd?: string} = {}): string {
18
+ const cwd = options.cwd || process.cwd();
19
+ const explicit = options.workspacePath || (!options.filePath ? process.env.SEPTUM_WORKSPACE_ROOT || process.env.WORKSPACE_ROOT : undefined);
20
+ let root: string;
21
+ if (explicit) {
22
+ root = resolve(cwd, explicit);
23
+ } else if (options.filePath && (isAbsolute(options.filePath) || /[\\/]/.test(options.filePath))) {
24
+ const absTarget = resolve(options.fallbackRoot || cwd, options.filePath);
25
+ // SV-04: Prefer known/registered workspace roots that already contain this file before falling back to nested markers
26
+ const containingKnown = options.knownRoots?.find(known => isPathContained(absTarget, known));
27
+ if (containingKnown && isWorkspaceInitialized(containingKnown)) {
28
+ root = containingKnown;
29
+ } else {
30
+ root = findProjectRoot(absTarget);
31
+ }
32
+ } else if (options.fallbackRoot) {
33
+ root = options.fallbackRoot;
34
+ } else {
35
+ if (!PROJECT_ROOT_MARKERS.some(marker => existsSync(join(cwd, marker)))) throw new Error('No project marker in CWD. Set SEPTUM_WORKSPACE_ROOT to an explicit workspace directory.');
36
+ root = cwd;
37
+ }
38
+ root = realpathSync(root);
39
+ if (!statSync(root).isDirectory() || root === dirname(root) || root === realpathSync(homedir()) || isAppHostDirectory(root)) throw new Error(`Unsafe Septum serve workspace: ${root}`);
40
+
41
+ // SV-04: Validate file-workspace consistency when both are present
42
+ if (options.workspacePath && options.filePath && isAbsolute(options.filePath)) {
43
+ if (!isPathContained(options.filePath, root)) {
44
+ throw new Error(`File '${options.filePath}' does not belong to workspace '${root}'.`);
45
+ }
46
+ }
47
+
48
+ setLastKnownProjectRoot(root);
49
+ return root;
50
+ }
51
+
52
+ export function isWorkspaceInitialized(root: string): boolean {
53
+ try {
54
+ // SV-03: Pure .septum directory without config or db is uninitialized
55
+ return existsSync(join(root, "septum.config.json")) ||
56
+ existsSync(join(root, ".septum", "septum.db"));
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ export interface WorkspaceContext {
63
+ root: string;
64
+ config: ValidatedSeptumConfig;
65
+ db: SeptumDatabase;
66
+ repo: SeptumRepository;
67
+ evaluator: BoundaryEvaluator;
68
+ pipeline: IngestionPipeline;
69
+ ready: Promise<void>;
70
+ watcher: WorkspaceWatcher;
71
+ }
72
+ interface Entry { context: WorkspaceContext; leases: number; lastUsed: number; initializing: boolean; abort: AbortController; disposal?: Promise<void> }
73
+ export interface WorkspaceLease { context: WorkspaceContext; release(): void }
74
+
75
+ export class WorkspaceManager {
76
+ private contexts = new Map<string, Entry>();
77
+ private queue = new SerialWorkQueue();
78
+ private budget = new WatchBudget();
79
+ private disposals = new Set<Promise<void>>();
80
+ private closed = false;
81
+ private closing: Promise<void> | null = null;
82
+ private idleTimer: ReturnType<typeof setInterval>;
83
+ initialRoot?: string;
84
+ lastRoot?: string;
85
+ get activeRoots(): string[] { return [...this.contexts.keys()]; }
86
+ 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);
88
+ this.idleTimer.unref();
89
+ }
90
+ get size(): number { return this.contexts.size; }
91
+ get watchCount(): number { return this.budget.count; }
92
+ get syncDurationMs(): number { return Math.max(0, ...[...this.contexts.values()].map(entry => Number(entry.context.repo.getMeta("sync_duration_ms") || 0))); }
93
+ get pendingPaths(): number { return [...this.contexts.values()].reduce((n, entry) => n + entry.context.watcher.pendingCount, 0); }
94
+
95
+ acquire(rawRoot: string, options: { deferDiscovery?: boolean } = {}): WorkspaceLease {
96
+ if (this.closed) throw new Error('Septum server is shutting down');
97
+ const root = realpathSync(rawRoot);
98
+ let entry = this.contexts.get(root);
99
+ if (!entry) {
100
+ if (this.contexts.size >= RESOURCE_LIMITS.workspaces) {
101
+ const idle = [...this.contexts.values()].filter(value => !value.leases && !value.initializing && !value.context.watcher.isBusy).sort((a,b) => a.lastUsed - b.lastUsed)[0];
102
+ if (!idle) throw new Error('Workspace resource limit reached: all workspace slots are busy. Retry after active requests finish.');
103
+ this.dispose(idle);
104
+ }
105
+ const config = ConfigLoader.load(undefined, root);
106
+ const db = new SeptumDatabase(resolveDatabasePath(root, config.settings.db_path));
107
+ try {
108
+ const repo = new SeptumRepository(db.raw);
109
+ const pipeline = new IngestionPipeline(repo, root);
110
+ const evaluator = new BoundaryEvaluator(repo, new ModuleResolver(root, repo));
111
+ const abort = new AbortController();
112
+ const ready = this.queue.run(async () => {
113
+ abort.signal.throwIfAborted();
114
+ // An explicit first registration chooses ownership before discovery.
115
+ if (options.deferDiscovery && Object.keys(config.domains).length === 0 && repo.getAllDomains().length === 0) return;
116
+ try { await pipeline.run(config, {verifyContent:true,signal:abort.signal}); }
117
+ catch (error) {
118
+ // Keep a conflicting legacy workspace open for explicit domain repair.
119
+ // Its index remains in error and cannot serve normal tool requests.
120
+ if (!(error instanceof DomainRootConflictError)) throw error;
121
+ }
122
+ });
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};
125
+ this.contexts.set(root, entry);
126
+ const initialized = entry;
127
+ void ready.then(() => { initialized.initializing = false; }, () => { initialized.initializing = false; this.dispose(initialized); });
128
+ } catch (error) { db.close(); throw error; }
129
+ }
130
+ this.lastRoot = root;
131
+ entry.leases++; entry.lastUsed = this.now();
132
+ const leased = entry; let released = false;
133
+ return {context: entry.context, release: () => { if (!released) { released=true; leased.leases--; leased.lastUsed=this.now(); } }};
134
+ }
135
+
136
+ private dispose(entry: Entry): Promise<void> {
137
+ if (entry.disposal) return entry.disposal;
138
+ if (this.contexts.get(entry.context.root) === entry) this.contexts.delete(entry.context.root);
139
+ entry.abort.abort();
140
+ const idle = !entry.leases && !entry.initializing && !entry.context.watcher.isBusy;
141
+ const stop = entry.context.watcher.close();
142
+ // Eviction of an idle context closes its database before admitting another.
143
+ if (idle) entry.context.db.close();
144
+ const disposal = stop.then(async () => { if (!idle) { await this.queue.drain(); entry.context.db.close(); } });
145
+ entry.disposal = disposal;
146
+ this.disposals.add(disposal);
147
+ void disposal.finally(() => this.disposals.delete(disposal)).catch(error => console.error(`[Septum Cleanup Warning] ${String(error)}`));
148
+ return disposal;
149
+ }
150
+
151
+ async expireIdle(): Promise<void> {
152
+ const expired = [...this.contexts.values()].filter(entry => !entry.leases && !entry.initializing && !entry.context.watcher.isBusy && this.now() - entry.lastUsed >= RESOURCE_LIMITS.workspaceIdleMs);
153
+ await Promise.all(expired.map(entry => this.dispose(entry)));
154
+ }
155
+
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
+ close(): Promise<void> {
161
+ if (this.closing) return this.closing;
162
+ this.closed = true; clearInterval(this.idleTimer);
163
+ const pending = [...this.contexts.values()].map(entry => this.dispose(entry));
164
+ this.closing = Promise.allSettled([...pending, ...this.disposals, this.queue.drain()]).then(results => {
165
+ const failed = results.find(result => result.status === 'rejected');
166
+ if (failed?.status === 'rejected') throw failed.reason;
167
+ });
168
+ return this.closing;
169
+ }
170
+ }