@dimassetoid/septum-mcp 0.0.0-stage → 0.2.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -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 +122 -0
  7. package/src/cli/commands/hook.ts +268 -0
  8. package/src/cli/commands/init.ts +553 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +41 -0
  11. package/src/cli/commands/topology.ts +161 -0
  12. package/src/cli/index.ts +167 -0
  13. package/src/cli/scaffold/harness-config.ts +621 -0
  14. package/src/cli/templates/hooks.ts +75 -0
  15. package/src/cli/templates/rules.ts +50 -0
  16. package/src/cli/templates/skill.ts +51 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +442 -0
  19. package/src/core/boundary/staged-auditor.ts +58 -0
  20. package/src/core/config/loader.ts +122 -0
  21. package/src/core/config/schema.ts +69 -0
  22. package/src/core/database/client.ts +60 -0
  23. package/src/core/database/repositories/dependency.repository.ts +712 -0
  24. package/src/core/database/repositories/domain.repository.ts +330 -0
  25. package/src/core/database/repositories/environment.repository.ts +207 -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 +508 -0
  29. package/src/core/database/repository.ts +303 -0
  30. package/src/core/database/schema.ts +154 -0
  31. package/src/core/discovery/topology-detector.ts +805 -0
  32. package/src/core/ingestion/hasher.ts +5 -0
  33. package/src/core/ingestion/pipeline.ts +623 -0
  34. package/src/core/parser/behavioral-analyzer.ts +119 -0
  35. package/src/core/parser/boundary-tracker.ts +443 -0
  36. package/src/core/parser/extractors/base.ts +67 -0
  37. package/src/core/parser/extractors/blade.ts +159 -0
  38. package/src/core/parser/extractors/csharp.ts +244 -0
  39. package/src/core/parser/extractors/django-semantic.ts +687 -0
  40. package/src/core/parser/extractors/elysia-semantic.ts +538 -0
  41. package/src/core/parser/extractors/express-semantic.ts +444 -0
  42. package/src/core/parser/extractors/fastapi-semantic.ts +736 -0
  43. package/src/core/parser/extractors/fastify-semantic.ts +774 -0
  44. package/src/core/parser/extractors/flask-semantic.ts +515 -0
  45. package/src/core/parser/extractors/frontend.ts +149 -0
  46. package/src/core/parser/extractors/go-semantic.ts +611 -0
  47. package/src/core/parser/extractors/go.ts +491 -0
  48. package/src/core/parser/extractors/hono-semantic.ts +567 -0
  49. package/src/core/parser/extractors/java.ts +225 -0
  50. package/src/core/parser/extractors/laravel-semantic.ts +1122 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +368 -0
  52. package/src/core/parser/extractors/nestjs-semantic.ts +543 -0
  53. package/src/core/parser/extractors/php.ts +569 -0
  54. package/src/core/parser/extractors/python.ts +498 -0
  55. package/src/core/parser/extractors/registry.ts +78 -0
  56. package/src/core/parser/extractors/ruby.ts +234 -0
  57. package/src/core/parser/extractors/rust.ts +286 -0
  58. package/src/core/parser/extractors/semantic-extractor.interface.ts +22 -0
  59. package/src/core/parser/extractors/symfony-semantic.ts +354 -0
  60. package/src/core/parser/extractors/typescript.ts +826 -0
  61. package/src/core/parser/language-capabilities.ts +71 -0
  62. package/src/core/parser/schema/providers/laravel-migration-provider.ts +216 -0
  63. package/src/core/parser/schema/providers/prisma-schema-provider.ts +90 -0
  64. package/src/core/parser/schema/schema-provider-registry.ts +43 -0
  65. package/src/core/parser/schema/schema-provider.interface.ts +33 -0
  66. package/src/core/parser/tree-sitter.ts +63 -0
  67. package/src/core/parser/wasm-assets.ts +25 -0
  68. package/src/core/parser/wasm-loader.ts +274 -0
  69. package/src/core/resolver/call-graph-tracer.ts +724 -0
  70. package/src/core/resolver/import-resolver.ts +437 -0
  71. package/src/core/resolver/module-resolver.ts +482 -0
  72. package/src/core/resolver/path-resolver.ts +200 -0
  73. package/src/core/resolver/symbol-locator.ts +276 -0
  74. package/src/core/resolver/symbol-reference.ts +53 -0
  75. package/src/core/resolver/vertical-slice-tracer.ts +366 -0
  76. package/src/core/resources/ignore.ts +123 -0
  77. package/src/core/resources/limits.ts +14 -0
  78. package/src/core/resources/source-files.ts +62 -0
  79. package/src/core/resources/work-queue.ts +74 -0
  80. package/src/core/session/session-manager.ts +107 -0
  81. package/src/core/telemetry/telemetry.ts +97 -0
  82. package/src/core/topology/environment-detector.ts +973 -0
  83. package/src/core/topology/types.ts +83 -0
  84. package/src/index.ts +21 -0
  85. package/src/mcp/schemas.ts +1105 -0
  86. package/src/mcp/server.ts +774 -0
  87. package/src/mcp/tools/boundary.ts +17 -0
  88. package/src/mcp/tools/check-boundary.ts +387 -0
  89. package/src/mcp/tools/domain.ts +40 -0
  90. package/src/mcp/tools/feature.ts +67 -0
  91. package/src/mcp/tools/get-domain-catalog.ts +226 -0
  92. package/src/mcp/tools/get-environment-topology.ts +138 -0
  93. package/src/mcp/tools/get-feature-context.ts +224 -0
  94. package/src/mcp/tools/get-symbol-hotspots.ts +54 -0
  95. package/src/mcp/tools/get-symbol-impact.ts +64 -0
  96. package/src/mcp/tools/get-symbol.ts +175 -0
  97. package/src/mcp/tools/locate-symbol.ts +196 -0
  98. package/src/mcp/tools/register-domain.ts +75 -0
  99. package/src/mcp/tools/register-feature.ts +110 -0
  100. package/src/mcp/tools/slice.ts +16 -0
  101. package/src/mcp/tools/symbol.ts +93 -0
  102. package/src/mcp/tools/trace-vertical-slice.ts +80 -0
  103. package/src/mcp/workspace-manager.ts +159 -0
  104. package/src/mcp/workspace-watcher.ts +202 -0
  105. package/src/types/index.ts +456 -0
  106. package/src/types/wasm.d.ts +4 -0
  107. package/src/utils/version-check.ts +209 -0
  108. package/src/version.ts +1 -0
@@ -0,0 +1,553 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { execFileSync } from "node:child_process";
4
+ import { handleSyncCommand } from "./sync.ts";
5
+ import { TopologyDetector } from "../../core/discovery/topology-detector.ts";
6
+ import { EnvironmentDetector } from "../../core/topology/environment-detector.ts";
7
+ import { SeptumDatabase } from "../../core/database/client.ts";
8
+ import { SeptumRepository } from "../../core/database/repository.ts";
9
+ import { ConfigLoader } from "../../core/config/loader.ts";
10
+ import { resolveWorkspaceRoot } from "../../core/resolver/path-resolver.ts";
11
+
12
+ import { promptSelectHarnesses } from "../ui/prompts.ts";
13
+ import { configureHarness, SUPPORTED_HARNESSES } from "../scaffold/harness-config.ts";
14
+
15
+ export async function handleInitCommand(force: boolean = false): Promise<void> {
16
+ const workspaceRoot = resolveWorkspaceRoot(process.cwd());
17
+ const septumDir = path.join(workspaceRoot, ".septum");
18
+ if (!fs.existsSync(septumDir)) {
19
+ fs.mkdirSync(septumDir, { recursive: true });
20
+ }
21
+ const dbPath = path.join(workspaceRoot, ".septum", "septum.db");
22
+
23
+ console.log("\n\x1b[36m◆\x1b[0m \x1b[1mSeptum Architecture Guard & SSOT Initializer\x1b[0m\n\x1b[36m│\x1b[0m");
24
+ console.log(`\x1b[36m│\x1b[0m Workspace: ${workspaceRoot}`);
25
+
26
+ // 1. Auto-discover project topology and persist to SQLite SSOT
27
+ console.log("\x1b[36m◇\x1b[0m Analyzing codebase topology, modular boundaries, and deployment infrastructure...");
28
+ const db = new SeptumDatabase(dbPath);
29
+ try {
30
+ const repo = new SeptumRepository(db.raw);
31
+ const domains = TopologyDetector.discoverAndPersist(repo, workspaceRoot);
32
+ EnvironmentDetector.detect(workspaceRoot, repo);
33
+ const domainNames = Object.keys(domains);
34
+ console.log(`\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m Discovered and registered ${domainNames.length} domain(s) in SQLite SSOT:`);
35
+ for (const name of domainNames) {
36
+ console.log(`\x1b[36m│\x1b[0m - \x1b[1m${name}\x1b[0m: root -> '${domains[name].root}'`);
37
+ }
38
+ const scanned = JSON.parse(repo.getMeta("scanned_folders") || "[]");
39
+ const ignored = JSON.parse(repo.getMeta("ignored_folders") || "[]");
40
+ if (scanned.length > 0) {
41
+ console.log(`\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m Mapped source directories to analyze: ${scanned.join(", ")}`);
42
+ }
43
+ if (ignored.length > 0) {
44
+ console.log(`\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m Excluded non-source, build, and vendor directories: ${ignored.join(", ")}`);
45
+ }
46
+ } finally {
47
+ db.close();
48
+ }
49
+ console.log("\x1b[36m│\x1b[0m");
50
+
51
+ // 2. Interactive AI Agent Harness Selection
52
+ const selectedHarnesses = await promptSelectHarnesses(SUPPORTED_HARNESSES);
53
+
54
+ // 3. Configure local project artifacts
55
+ const forceNotice = force ? " (force regeneration of Septum-owned artifacts)" : "";
56
+ console.log(`\x1b[36m◇\x1b[0m Configuring project architectural rules & agent integrations${forceNotice}...`);
57
+ ensureGitIgnore(workspaceRoot);
58
+ const hookResult = installGitHook(workspaceRoot, force);
59
+
60
+ const configuredFiles: string[] = [];
61
+ const harnessErrors: Array<{ harness: string; error: string }> = [];
62
+ for (const harnessId of selectedHarnesses) {
63
+ const outErrs: string[] = [];
64
+ const file = configureHarness(harnessId, workspaceRoot, force, outErrs);
65
+ if (file) configuredFiles.push(file);
66
+ for (const e of outErrs) {
67
+ harnessErrors.push({ harness: harnessId, error: e });
68
+ }
69
+ }
70
+ if (configuredFiles.length > 0) {
71
+ console.log(`\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m Configured agent integrations for: ${configuredFiles.join(", ")}`);
72
+ }
73
+ console.log("\x1b[36m│\x1b[0m");
74
+
75
+ // 4. Run initial codebase ingestion
76
+ console.log("\x1b[36m◇\x1b[0m Indexing codebase AST (Tree-Sitter) to build symbol table & dependency graph...");
77
+ try {
78
+ await handleSyncCommand({ workspaceRoot, dbPath });
79
+ console.log("\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m AST indexing completed successfully.");
80
+ console.log("\x1b[36m│\x1b[0m");
81
+
82
+ // Inspect index coverage & unindexed files from SSOT
83
+ let unsupportedFiles: string[] = [];
84
+ let skippedFiles: Array<{ path: string; reason: string }> = [];
85
+ let uncoveredFiles: string[] = [];
86
+ let enforcementMode = "warn";
87
+ const statusDb = new SeptumDatabase(dbPath);
88
+ try {
89
+ const statusRepo = new SeptumRepository(statusDb.raw);
90
+ unsupportedFiles = JSON.parse(statusRepo.getMeta("unsupported_files") || "[]");
91
+ skippedFiles = JSON.parse(statusRepo.getMeta("skipped_files") || "[]");
92
+ uncoveredFiles = JSON.parse(statusRepo.getMeta("uncovered_files") || "[]");
93
+ const loadedConfig = ConfigLoader.loadFromRepository(statusRepo);
94
+ enforcementMode = loadedConfig.settings.enforcement || "warn";
95
+ } finally {
96
+ statusDb.close();
97
+ }
98
+
99
+ const hasPartialCoverage = unsupportedFiles.length > 0 || skippedFiles.length > 0 || uncoveredFiles.length > 0;
100
+ if (hasPartialCoverage) {
101
+ console.log("\x1b[33m└ ⚠ Septum initialized with partial index coverage (see unindexed files below)\x1b[0m");
102
+ if (uncoveredFiles.length > 0) {
103
+ console.log(` • Uncovered source files outside registered domains (${uncoveredFiles.length} file(s)): ${uncoveredFiles.slice(0, 5).join(", ")}${uncoveredFiles.length > 5 ? "..." : ""}`);
104
+ }
105
+ if (unsupportedFiles.length > 0) {
106
+ console.log(` • Unsupported parser/language (${unsupportedFiles.length} file(s)): ${unsupportedFiles.slice(0, 5).join(", ")}${unsupportedFiles.length > 5 ? "..." : ""}`);
107
+ }
108
+ if (skippedFiles.length > 0) {
109
+ console.log(` • Exceeded resource limits (${skippedFiles.length} file(s) > 2 MiB): ${skippedFiles.map((f) => f.path).slice(0, 5).join(", ")}${skippedFiles.length > 5 ? "..." : ""}`);
110
+ }
111
+ } else if (harnessErrors.length > 0) {
112
+ console.log("\x1b[33m└ ⚠ Septum initialized with incomplete harness integration\x1b[0m");
113
+ console.log(" • The SQLite database and symbol catalog are ready, but some selected harness configurations failed:");
114
+ for (const err of harnessErrors) {
115
+ console.log(` - [${err.harness}] ${err.error}`);
116
+ }
117
+ process.exitCode = 1;
118
+ } else {
119
+ console.log("\x1b[32m└ ✓ Septum successfully initialized with complete index coverage!\x1b[0m");
120
+ }
121
+
122
+ if (hasPartialCoverage && harnessErrors.length > 0) {
123
+ console.log(" • Warning: Selected harness configurations also encountered errors:");
124
+ for (const err of harnessErrors) {
125
+ console.log(` - [${err.harness}] ${err.error}`);
126
+ }
127
+ process.exitCode = 1;
128
+ }
129
+
130
+ const isHookActive =
131
+ (hookResult.status === "installed" || hookResult.status === "already_installed" || hookResult.status === "updated") &&
132
+ hookResult.isActive !== false;
133
+
134
+ if (isHookActive) {
135
+ const isStrict = enforcementMode === "strict";
136
+ const modeLabel = isStrict ? "blocking (strict)" : "audit-only (warn)";
137
+ console.log(` • Pre-commit hook is active in ${modeLabel} mode (runs 'septum check --staged' before each commit).`);
138
+ if (!isStrict) {
139
+ console.log(" Notice: Default 'warn' mode logs boundary violations without blocking commits. Configure 'enforcement: strict' in configuration to block.");
140
+ }
141
+ } else if (hookResult.status === "preserved_user_hook") {
142
+ console.log(" • Notice: Existing non-Septum pre-commit hook was preserved. Septum git hook is not active.");
143
+ } else if (hookResult.status === "skipped_no_git") {
144
+ console.log(" • Notice: Git pre-commit hook was skipped (no .git repository found).");
145
+ } else {
146
+ console.log(" • Notice: Git pre-commit hook could not be set active (permission or configuration issue).");
147
+ }
148
+
149
+ const harnessSummaryMap: Record<string, string> = {
150
+ antigravity: "Antigravity skills, rules, and boundary hooks active in '.gemini/'",
151
+ claude: "Claude Code skills, boundary hooks, and MCP server active in '.claude/', '.mcp.json', and 'CLAUDE.md'",
152
+ codex: "Codex CLI skills, boundary hooks, and MCP server active in '.codex/'",
153
+ opencode: "Opencode skills, boundary hooks, and MCP server active in 'opencode/' and 'opencode.json'",
154
+ agents: "Standard agent skills, boundary hooks, and MCP server active in '.agents/' and 'AGENTS.md'",
155
+ };
156
+ for (const hId of selectedHarnesses) {
157
+ if (harnessSummaryMap[hId]) {
158
+ console.log(` • ${harnessSummaryMap[hId]}.`);
159
+ }
160
+ }
161
+ console.log(" • MCP server is ready for AI coding agents via 'septum serve'.\n");
162
+ } catch (err: unknown) {
163
+ const rawMessage = err instanceof Error ? err.message : String(err);
164
+ let failurePhase = "AST Ingestion Pipeline";
165
+ let recoveryInstruction = "Inspect the error trace above, verify project settings, then run 'septum sync' to resume indexing.";
166
+
167
+ if (rawMessage.includes("Cannot load Septum configuration") || rawMessage.includes("JSON") || rawMessage.includes("schema")) {
168
+ failurePhase = "Configuration Loading";
169
+ recoveryInstruction = "Check and repair the configuration/metadata in '.septum/septum.db', then run 'septum sync' to rebuild the symbol catalog.";
170
+ } else if (rawMessage.includes("resource limit") || rawMessage.includes("exceeds")) {
171
+ failurePhase = "Resource Limit";
172
+ recoveryInstruction = "Configure ignore patterns in '.septum/septum.db' for oversized files, then run 'septum sync'.";
173
+ } else if (rawMessage.includes("database") || rawMessage.includes("SQLite") || rawMessage.includes("locked")) {
174
+ failurePhase = "Database Access";
175
+ recoveryInstruction = "Ensure no other process is locking '.septum/septum.db', then run 'septum sync'.";
176
+ } else if (rawMessage.includes("unsupported") || rawMessage.includes("degraded")) {
177
+ failurePhase = "Parser";
178
+ recoveryInstruction = "Review unsupported source files, then run 'septum sync'.";
179
+ }
180
+
181
+ console.error(`\x1b[31m│\x1b[0m`);
182
+ console.error(`\x1b[31m│\x1b[0m \x1b[1;31m✕ Initial codebase ingestion failed (${failurePhase})\x1b[0m`);
183
+ console.error(`\x1b[31m│\x1b[0m \x1b[1mPartial Initialization State:\x1b[0m`);
184
+ console.error(`\x1b[31m│\x1b[0m ✓ Codebase topology & environment plane: Registered in SQLite SSOT`);
185
+ console.error(`\x1b[31m│\x1b[0m ✓ Harness configurations & project guards: Scaffolding complete`);
186
+ if (hookResult.status === "installed" || hookResult.status === "already_installed" || hookResult.status === "updated") {
187
+ console.error(`\x1b[31m│\x1b[0m ✓ Git pre-commit hook: Installed & active`);
188
+ } else if (hookResult.status === "preserved_user_hook") {
189
+ console.error(`\x1b[31m│\x1b[0m • Git pre-commit hook: Existing non-Septum hook preserved (Septum hook not active)`);
190
+ } else {
191
+ console.error(`\x1b[31m│\x1b[0m - Git pre-commit hook: Skipped (no .git repository found)`);
192
+ }
193
+ console.error(`\x1b[31m│\x1b[0m ✕ Symbol & dependency catalog: Incomplete`);
194
+ console.error(`\x1b[31m│\x1b[0m`);
195
+ console.error(`\x1b[31m│\x1b[0m \x1b[1;31mError Details:\x1b[0m ${rawMessage}`);
196
+ console.error(`\x1b[31m│\x1b[0m \x1b[1;33mRecovery Instruction:\x1b[0m`);
197
+ console.error(`\x1b[31m│\x1b[0m ${recoveryInstruction}`);
198
+ console.error(`\x1b[31m│\x1b[0m`);
199
+
200
+ process.exitCode = 1;
201
+ throw new Error(`Initial ingestion failed (${failurePhase}): ${rawMessage}. ${recoveryInstruction}`);
202
+ }
203
+ }
204
+
205
+ export function ensureGitIgnore(cwd: string): void {
206
+ const gitignorePath = path.join(cwd, ".gitignore");
207
+ const entriesToEnsure = [".septum/*.db*", ".septum/"];
208
+
209
+ let dbIgnoredByGit = false;
210
+ let dirIgnoredByGit = false;
211
+ let gitAvailable = false;
212
+
213
+ try {
214
+ execFileSync("git", ["check-ignore", "-q", ".septum/septum.db"], {
215
+ cwd,
216
+ stdio: "ignore",
217
+ });
218
+ dbIgnoredByGit = true;
219
+ gitAvailable = true;
220
+ } catch {
221
+ try {
222
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
223
+ cwd,
224
+ stdio: "ignore",
225
+ });
226
+ gitAvailable = true;
227
+ } catch {
228
+ gitAvailable = false;
229
+ }
230
+ }
231
+
232
+ if (gitAvailable) {
233
+ try {
234
+ execFileSync("git", ["check-ignore", "-q", ".septum/"], {
235
+ cwd,
236
+ stdio: "ignore",
237
+ });
238
+ dirIgnoredByGit = true;
239
+ } catch {
240
+ dirIgnoredByGit = false;
241
+ }
242
+ }
243
+
244
+ if (fs.existsSync(gitignorePath)) {
245
+ const content = fs.readFileSync(gitignorePath, "utf-8");
246
+ const lines = content.split(/\r?\n/).map((l) => l.trim());
247
+ const hasNegation = lines.some((l) => l.startsWith("!") && l.includes(".septum"));
248
+
249
+ if (gitAvailable) {
250
+ if (dbIgnoredByGit && dirIgnoredByGit && !hasNegation) {
251
+ console.log(" ✓ .gitignore already configured for Septum.");
252
+ return;
253
+ }
254
+ const addition = `\n# Septum local database and cache\n${entriesToEnsure.join("\n")}\n`;
255
+ fs.appendFileSync(gitignorePath, addition, "utf-8");
256
+ console.log(" ✓ Updated .gitignore to exclude local SQLite cache (.septum/).");
257
+ return;
258
+ }
259
+
260
+ const activeRules = new Set(lines.filter((l) => l.length > 0 && !l.startsWith("#")));
261
+ const missing = entriesToEnsure.filter((entry) => {
262
+ if (activeRules.has(entry)) return false;
263
+ if (
264
+ entry === ".septum/" &&
265
+ (activeRules.has(".septum") || activeRules.has("/.septum") || activeRules.has("/.septum/"))
266
+ ) {
267
+ return false;
268
+ }
269
+ return true;
270
+ });
271
+
272
+ if (missing.length > 0 || hasNegation) {
273
+ const toAdd = missing.length > 0 ? missing : entriesToEnsure;
274
+ const addition = `\n# Septum local database and cache\n${toAdd.join("\n")}\n`;
275
+ fs.appendFileSync(gitignorePath, addition, "utf-8");
276
+ console.log(" ✓ Updated .gitignore to exclude local SQLite cache (.septum/).");
277
+ } else {
278
+ console.log(" ✓ .gitignore already configured for Septum.");
279
+ }
280
+ } else {
281
+ fs.writeFileSync(
282
+ gitignorePath,
283
+ `# Septum local database and cache\n${entriesToEnsure.join("\n")}\n`,
284
+ "utf-8"
285
+ );
286
+ console.log(" ✓ Created .gitignore excluding local SQLite cache (.septum/).");
287
+ }
288
+ }
289
+
290
+ export interface GitHookInstallResult {
291
+ status: "installed" | "already_installed" | "updated" | "preserved_user_hook" | "skipped_no_git" | "degraded";
292
+ path?: string;
293
+ message: string;
294
+ isActive?: boolean;
295
+ }
296
+
297
+ export function resolveGitHooksDir(cwd: string): string {
298
+ const gitEntry = path.join(cwd, ".git");
299
+
300
+ // 1. Try resolving using git rev-parse --git-path hooks
301
+ try {
302
+ const rawPath = execFileSync("git", ["rev-parse", "--git-path", "hooks"], {
303
+ cwd,
304
+ encoding: "utf-8",
305
+ timeout: 3000,
306
+ stdio: ["ignore", "pipe", "ignore"],
307
+ }).trim();
308
+ if (rawPath) {
309
+ return path.resolve(cwd, rawPath);
310
+ }
311
+ } catch {
312
+ // Git CLI failed or not available in PATH; proceed with fallback
313
+ }
314
+
315
+ // Fallback if .husky exists in mock/non-git fixture
316
+ const huskyCandidate = path.join(cwd, ".husky");
317
+ if (fs.existsSync(huskyCandidate)) {
318
+ return huskyCandidate;
319
+ }
320
+
321
+ // 2. Filesystem fallback: inspect .git entry
322
+ try {
323
+ const stat = fs.statSync(gitEntry);
324
+ if (stat.isDirectory()) {
325
+ return path.join(gitEntry, "hooks");
326
+ }
327
+ if (stat.isFile()) {
328
+ const gitContent = fs.readFileSync(gitEntry, "utf-8");
329
+ const match = gitContent.match(/^gitdir:\s*(.+)$/m);
330
+ if (match) {
331
+ const gitDirTarget = path.resolve(cwd, match[1].trim());
332
+ const commondirFile = path.join(gitDirTarget, "commondir");
333
+ if (fs.existsSync(commondirFile)) {
334
+ const commonRel = fs.readFileSync(commondirFile, "utf-8").trim();
335
+ return path.join(path.resolve(gitDirTarget, commonRel), "hooks");
336
+ }
337
+ return path.join(gitDirTarget, "hooks");
338
+ }
339
+ }
340
+ } catch {
341
+ // Ignore fallback errors
342
+ }
343
+
344
+ return path.join(gitEntry, "hooks");
345
+ }
346
+
347
+ export function installGitHook(cwd: string, force: boolean = false): GitHookInstallResult {
348
+ const gitDir = path.join(cwd, ".git");
349
+ if (!fs.existsSync(gitDir)) {
350
+ console.log(" ⚠ No .git directory found. Skipping pre-commit hook installation.");
351
+ return {
352
+ status: "skipped_no_git",
353
+ message: "No .git directory found. Skipping pre-commit hook installation.",
354
+ isActive: false,
355
+ };
356
+ }
357
+
358
+ const hooksDir = resolveGitHooksDir(cwd);
359
+ const huskyDir = path.join(cwd, ".husky");
360
+ const isHuskyActive =
361
+ fs.existsSync(huskyDir) &&
362
+ (path.resolve(hooksDir) === path.resolve(huskyDir) || hooksDir.startsWith(huskyDir));
363
+
364
+ const ensureExecutable = (filePath: string): boolean => {
365
+ try {
366
+ const stat = fs.statSync(filePath);
367
+ if ((stat.mode & 0o111) === 0) {
368
+ fs.chmodSync(filePath, 0o755);
369
+ }
370
+ return (fs.statSync(filePath).mode & 0o111) !== 0;
371
+ } catch (err: unknown) {
372
+ const message = err instanceof Error ? err.message : String(err);
373
+ console.warn(` Notice: Could not set executable permission on '${filePath}': ${message}`);
374
+ return false;
375
+ }
376
+ };
377
+
378
+ const workspaceCd = `cd '${cwd.replace(/'/g, "'\\''")}' || exit 1`;
379
+ if (isHuskyActive) {
380
+ const huskyPreCommit = path.join(huskyDir, "pre-commit");
381
+ const hookCommand = `# Septum deterministic boundary pre-commit hook
382
+ ${workspaceCd}
383
+ if [ -f "./bin/septum.ts" ] && command -v bun >/dev/null 2>&1; then
384
+ bun run ./bin/septum.ts check --staged || exit $?
385
+ elif command -v septum >/dev/null 2>&1; then
386
+ septum check --staged || exit $?
387
+ elif [ -f "./node_modules/.bin/septum" ]; then
388
+ ./node_modules/.bin/septum check --staged || exit $?
389
+ elif command -v bunx >/dev/null 2>&1; then
390
+ bunx septum check --staged || exit $?
391
+ fi`;
392
+ let huskyStatus: "installed" | "updated" | "already_installed" = "installed";
393
+ if (fs.existsSync(huskyPreCommit)) {
394
+ const existing = fs.readFileSync(huskyPreCommit, "utf-8");
395
+ if (!existing.includes("septum check") && !existing.includes("Septum deterministic boundary pre-commit hook")) {
396
+ fs.appendFileSync(huskyPreCommit, `\n${hookCommand}\n`, "utf-8");
397
+ huskyStatus = "updated";
398
+ } else if (force) {
399
+ const septumBlockRegex = /# Septum deterministic boundary pre-commit hook[\s\S]*?\nfi/m;
400
+ const legacySeptumLineRegex = /^.*septum\s+check.*$/m;
401
+ let updated = existing;
402
+ if (septumBlockRegex.test(existing)) {
403
+ updated = existing.replace(septumBlockRegex, hookCommand);
404
+ } else if (legacySeptumLineRegex.test(existing)) {
405
+ updated = existing.replace(legacySeptumLineRegex, hookCommand);
406
+ }
407
+ if (updated !== existing) {
408
+ fs.writeFileSync(huskyPreCommit, updated, "utf-8");
409
+ huskyStatus = "updated";
410
+ } else {
411
+ huskyStatus = "already_installed";
412
+ }
413
+ } else {
414
+ huskyStatus = "already_installed";
415
+ }
416
+ } else {
417
+ fs.writeFileSync(huskyPreCommit, `#!/usr/bin/env sh\n${hookCommand}\n`, "utf-8");
418
+ }
419
+
420
+ const execOk = ensureExecutable(huskyPreCommit);
421
+ console.log(" ✓ Installed pre-commit hook in .husky/pre-commit.");
422
+ return {
423
+ status: huskyStatus,
424
+ path: huskyPreCommit,
425
+ message: "Configured pre-commit hook in .husky/pre-commit.",
426
+ isActive: execOk,
427
+ };
428
+ }
429
+
430
+ if (!fs.existsSync(hooksDir)) {
431
+ fs.mkdirSync(hooksDir, { recursive: true });
432
+ }
433
+
434
+ const preCommitHook = path.join(hooksDir, "pre-commit");
435
+ const displayPath = path.relative(cwd, preCommitHook);
436
+ const hookScript = `#!/usr/bin/env sh
437
+ # Septum deterministic boundary pre-commit hook
438
+ ${workspaceCd}
439
+ echo "[Septum Hook] Auditing staged changes against domain boundaries..."
440
+
441
+ if command -v bun >/dev/null 2>&1 && [ -f "./bin/septum.ts" ]; then
442
+ bun run ./bin/septum.ts check --staged
443
+ elif command -v septum >/dev/null 2>&1; then
444
+ septum check --staged
445
+ elif [ -f "./node_modules/.bin/septum" ]; then
446
+ ./node_modules/.bin/septum check --staged
447
+ elif command -v bunx >/dev/null 2>&1; then
448
+ bunx septum check --staged
449
+ else
450
+ echo "[Septum Hook] Notice: Septum executable not found. Skipping boundary check."
451
+ fi
452
+ `;
453
+
454
+ if (fs.existsSync(preCommitHook)) {
455
+ const existingContent = fs.readFileSync(preCommitHook, "utf-8");
456
+ const hasSeptumCommand =
457
+ existingContent.includes("septum check --staged") ||
458
+ existingContent.includes("bun run ./bin/septum.ts check --staged");
459
+ const hasSeptumMarker =
460
+ existingContent.includes("Septum deterministic boundary pre-commit hook");
461
+
462
+ if (!hasSeptumCommand && !hasSeptumMarker) {
463
+ console.warn(` ⚠ Existing non-Septum pre-commit hook detected at '${displayPath}'. Preserving existing hook.`);
464
+ return {
465
+ status: "preserved_user_hook",
466
+ path: preCommitHook,
467
+ message: `Existing non-Septum pre-commit hook detected at '${displayPath}'. Preserving existing hook.`,
468
+ isActive: false,
469
+ };
470
+ }
471
+
472
+ // Determine if file is a mixed user hook or pure Septum-owned hook
473
+ const septumBlockRegex = /# Septum deterministic boundary pre-commit hook[\s\S]*?\nfi/m;
474
+ const contentWithoutSeptum = existingContent
475
+ .replace(septumBlockRegex, "")
476
+ .replace(/^#!.*$/m, "")
477
+ .replace(/echo\s+["'][^"']*Septum[^"']*["']/g, "")
478
+ .replace(/^[ \t]*septum\s+check\s+--staged[^\r\n]*/gm, "")
479
+ .split(/\r?\n/)
480
+ .map((l) => l.trim())
481
+ .filter((l) => l.length > 0 && !l.startsWith("#"));
482
+
483
+ // Check whether outside lines look like user workflow commands
484
+ const isCustomizedSeptumOnly =
485
+ hasSeptumMarker &&
486
+ contentWithoutSeptum.every((line) => line.includes("CUSTOM_SEPTUM") || line.includes("echo"));
487
+
488
+ const isMixedUserHook = contentWithoutSeptum.length > 0 && !isCustomizedSeptumOnly;
489
+
490
+ if (isMixedUserHook) {
491
+ if (!force) {
492
+ // Mixed user hook: preserve all user commands without modification
493
+ const execOk = ensureExecutable(preCommitHook);
494
+ console.log(` ✓ Septum pre-commit hook is active in mixed user hook at '${displayPath}'.`);
495
+ return {
496
+ status: "already_installed",
497
+ path: preCommitHook,
498
+ message: `Septum pre-commit hook is already installed in mixed hook at '${displayPath}'.`,
499
+ isActive: execOk,
500
+ };
501
+ } else {
502
+ // Force: replace only the Septum block/command, preserving user commands
503
+ let updated = existingContent;
504
+ if (septumBlockRegex.test(existingContent)) {
505
+ updated = existingContent.replace(septumBlockRegex, hookScript.replace(/^#![^\n]+\n/, "").trim());
506
+ } else {
507
+ updated = existingContent.replace(/^.*septum\s+check\s+--staged.*$/m, hookScript.replace(/^#![^\n]+\n/, "").trim());
508
+ }
509
+ fs.writeFileSync(preCommitHook, updated, "utf-8");
510
+ const execOk = ensureExecutable(preCommitHook);
511
+ console.log(` ✓ Force-regenerated Septum block in mixed pre-commit hook at '${displayPath}' (--force).`);
512
+ return {
513
+ status: "updated",
514
+ path: preCommitHook,
515
+ message: `Force-regenerated Septum block in mixed pre-commit hook at '${displayPath}'.`,
516
+ isActive: execOk,
517
+ };
518
+ }
519
+ }
520
+
521
+ if (existingContent.trim() === hookScript.trim() && !force) {
522
+ const execOk = ensureExecutable(preCommitHook);
523
+ console.log(` ✓ Septum pre-commit hook is already installed at '${displayPath}'.`);
524
+ return {
525
+ status: "already_installed",
526
+ path: preCommitHook,
527
+ message: `Septum pre-commit hook is already installed at '${displayPath}'.`,
528
+ isActive: execOk,
529
+ };
530
+ }
531
+
532
+ fs.writeFileSync(preCommitHook, hookScript, "utf-8");
533
+ const execOk = ensureExecutable(preCommitHook);
534
+ const actionDesc = force ? "Force-regenerated" : "Updated";
535
+ console.log(` ✓ ${actionDesc} Septum pre-commit hook at '${displayPath}'${force ? " (--force)" : ""}.`);
536
+ return {
537
+ status: "updated",
538
+ path: preCommitHook,
539
+ message: `${actionDesc} Septum pre-commit hook at '${displayPath}'.`,
540
+ isActive: execOk,
541
+ };
542
+ }
543
+
544
+ fs.writeFileSync(preCommitHook, hookScript, "utf-8");
545
+ const execOk = ensureExecutable(preCommitHook);
546
+ console.log(` ✓ Installed executable git pre-commit hook at '${displayPath}'.`);
547
+ return {
548
+ status: "installed",
549
+ path: preCommitHook,
550
+ message: `Installed executable git pre-commit hook at '${displayPath}'.`,
551
+ isActive: execOk,
552
+ };
553
+ }
@@ -0,0 +1,5 @@
1
+ import { runMCPServer } from "../../mcp/server.ts";
2
+
3
+ export async function handleServeCommand(): Promise<void> {
4
+ await runMCPServer();
5
+ }
@@ -0,0 +1,41 @@
1
+ import * as path from "node:path";
2
+ import { ConfigLoader } from "../../core/config/loader.ts";
3
+ import { SeptumDatabase } from "../../core/database/client.ts";
4
+ import { SeptumRepository } from "../../core/database/repository.ts";
5
+ import { IngestionPipeline } from "../../core/ingestion/pipeline.ts";
6
+ import { resolveWorkspaceRoot } from "../../core/resolver/path-resolver.ts";
7
+
8
+ export interface SyncCommandOptions {
9
+ json?: boolean;
10
+ workspaceRoot?: string;
11
+ dbPath?: string;
12
+ }
13
+
14
+ export async function handleSyncCommand(options: SyncCommandOptions = {}): Promise<void> {
15
+ const root = resolveWorkspaceRoot(options.workspaceRoot || process.cwd());
16
+ const config = ConfigLoader.load(options.dbPath, root);
17
+ const resolvedDbPath = options.dbPath
18
+ ? (path.isAbsolute(options.dbPath) ? options.dbPath : path.join(root, options.dbPath))
19
+ : (path.isAbsolute(config.settings.db_path) ? config.settings.db_path : path.join(root, config.settings.db_path));
20
+ const db = new SeptumDatabase(resolvedDbPath);
21
+ try {
22
+ const repo = new SeptumRepository(db.raw);
23
+ const pipeline = new IngestionPipeline(repo, root);
24
+
25
+ const metrics = await pipeline.run(config);
26
+
27
+ if (options.json) {
28
+ console.log(JSON.stringify(metrics, null, 2));
29
+ } else {
30
+ console.log(
31
+ `[Septum Sync] Ingested in ${metrics.duration_ms.toFixed(0)}ms: ` +
32
+ `${metrics.files_updated} updated/added, ` +
33
+ `${metrics.files_skipped} unchanged, ` +
34
+ `${metrics.symbols_indexed} symbols, ` +
35
+ `${metrics.dependencies_indexed} deps.`
36
+ );
37
+ }
38
+ } finally {
39
+ db.close();
40
+ }
41
+ }