@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shironim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,125 @@
1
- # Temporary Holding Version
1
+ # Septum
2
+
3
+ > **Architecture boundary guard and codebase intelligence for AI coding agents.**
4
+
5
+ [![Version: 0.2.1](https://img.shields.io/badge/Version-0.2.1-blue)](package.json)
6
+ [![Runtime: Bun](https://img.shields.io/badge/Runtime-Bun-black?logo=bun)](https://bun.sh)
7
+ [![Protocol: Model Context Protocol](https://img.shields.io/badge/Protocol-MCP-green)](https://modelcontextprotocol.io/)
8
+ [![Database: SQLite WAL](https://img.shields.io/badge/Database-SQLite%20(bun:sqlite)-003B57?logo=sqlite)](https://sqlite.org/)
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue)](LICENSE)
10
+
11
+ Septum helps AI coding agents understand codebase architecture and respect modular boundaries. It parses and indexes your codebase into a local SQLite database (`.septum/septum.db`), validates module dependencies, and prevents unauthorized cross-boundary modifications.
12
+
13
+ ---
14
+
15
+ ## Installation
16
+
17
+ ### Option 1: Standalone Binary (Recommended)
18
+
19
+ No need to install Bun, Node.js, or package managers. Download and install the prebuilt binary:
20
+
21
+ **Linux & macOS:**
22
+ ```bash
23
+ curl -fsSL https://raw.githubusercontent.com/Shironim/septum-mcp/master/install.sh | bash
24
+ ```
25
+
26
+ **Windows (PowerShell):**
27
+ ```powershell
28
+ irm https://raw.githubusercontent.com/Shironim/septum-mcp/master/install.ps1 | iex
29
+ ```
30
+
31
+ > **Manual Downloads:** Precompiled binaries are also available on [GitHub Releases](https://github.com/Shironim/septum-mcp/releases) for `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, and `windows-x64.exe`.
32
+
33
+ ### Option 2: Via Bun
34
+
35
+ If you already use [Bun](https://bun.sh):
36
+
37
+ ```bash
38
+ bun add -g @dimassetoid/septum-mcp
39
+ ```
40
+
41
+ > **Zero-Install:** You can also run commands directly using `bunx @dimassetoid/septum-mcp <command>`.
42
+
43
+ ---
44
+
45
+ ## Quick Start
46
+
47
+ ### 1. Initialize in Any Project
48
+
49
+ Run `septum init` from the workspace directory you want Septum to manage:
50
+
51
+ ```bash
52
+ septum init
53
+ # or zero-install via bunx:
54
+ bunx septum init
55
+ ```
56
+
57
+ Septum automatically:
58
+ 1. **Detects Project Structure:** Identifies module boundaries across Monorepos, Laravel, Next.js, NestJS, Express, Fastify, Hono, Elysia, Django, Flask, FastAPI, and Go.
59
+ 2. **Indexes Codebase AST:** Ingests symbols, interfaces, and dependencies into `.septum/septum.db`.
60
+ 3. **Scaffolds Agent Configurations:** Sets up MCP servers, skills, and pre-write hooks for supported environments:
61
+ - **Antigravity** (`.gemini/`)
62
+ - **Claude Code** (`.claude/`, `.mcp.json`, `CLAUDE.md`)
63
+ - **Codex** (`.codex/`)
64
+ - **Opencode** (`opencode/`, `opencode.json`)
65
+ - **.agents Standard** (`.agents/`, `AGENTS.md`)
66
+
67
+ ### 2. Manual MCP Client Configuration (Optional)
68
+
69
+ If your MCP client is not configured via `septum init`, add Septum to your MCP configuration (`.mcp.json` or `claude_desktop_config.json`):
70
+
71
+ ```json
72
+ {
73
+ "mcpServers": {
74
+ "septum": {
75
+ "command": "septum",
76
+ "args": ["serve"]
77
+ }
78
+ }
79
+ }
80
+ ```
81
+ *(Or use `"command": "bunx", "args": ["septum", "serve"]` if running without global installation).*
82
+
83
+ ---
84
+
85
+ ## CLI Reference
86
+
87
+ | Command | Description |
88
+ |---|---|
89
+ | `septum init [--force]` | Detect project topology, scaffold agent integrations, and build initial symbol catalog. `--force` regenerates Septum-managed configs while preserving existing database and user git hooks |
90
+ | `septum sync [--json]` | Synchronize AST and update symbol catalog into `.septum/septum.db` (full or incremental) |
91
+ | `septum check [--strict] [--staged] [--feature <name>] [--json]` | Verify boundary rules and detect cross-domain or circular dependency violations |
92
+ | `septum feature [status\|clear] [--force]` | View or release active feature editing scope |
93
+ | `septum hook pre-write` | Pre-tool guard hook to validate proposed changes before file edits |
94
+ | `septum topology [subcommand]` | Inspect environment topology and infrastructure services |
95
+ | `septum serve` | Start stdio Model Context Protocol (MCP) server |
96
+
97
+ ---
98
+
99
+ ## MCP Tools
100
+
101
+ All tools provide structured schemas via the Model Context Protocol:
102
+
103
+ - **Domain & Architecture Overview (`septum_domain`):**
104
+ - `action: "catalog"`: High-level architecture map and module dependencies (`detail_level: "compact" | "full"`).
105
+ - `action: "register"`: Register or update domain boundaries with allowed and forbidden dependencies.
106
+ - `action: "topology"`: Inspect deployment environment and infrastructure services.
107
+ - **Symbol Inspection & Impact Analysis (`septum_symbol`):**
108
+ - `action: "locate"`: Search and find symbols across the codebase.
109
+ - `action: "inspect"`: Inspect symbol declarations, signatures, and source snippets.
110
+ - `action: "impact"`: Analyze call graphs, dependents, and refactoring blast radius.
111
+ - `action: "hotspots"`: Identify complex functions based on line count and nesting depth.
112
+ - **Execution Flow Tracer (`septum_slice`):**
113
+ - Trace call chains across application layers (*Route ➔ Controller ➔ Service ➔ Repository ➔ Entity*) from HTTP endpoints, queue jobs, CLI commands, or event handlers.
114
+ - **Dependency & Boundary Validator (`septum_boundary`):**
115
+ - Validate proposed file imports against defined architectural rules (`scope: "file"`).
116
+ - Check staged files (`scope: "staged"`), specific domains (`scope: "domain"`), or the whole codebase (`scope: "all"`) for circular dependencies and boundary violations.
117
+ - **Feature Scope Management (`septum_feature`):**
118
+ - Restrict agent editing scope to designated touchpoint files during feature work to prevent unintended changes.
119
+
120
+ ---
121
+
122
+ ## License
123
+
124
+ [MIT](LICENSE) © shironim
2
125
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
package/bin/septum.ts ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bun
2
+ import { runCLI } from "../src/cli/index.ts";
3
+
4
+ runCLI(process.argv);
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@dimassetoid/septum-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Deterministic Bounded-Context, Structural File Catalog & Anti-Poisoning Partition for AI Agents",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "main": "src/index.ts",
10
+ "bin": {
11
+ "septum-mcp": "./bin/septum.ts",
12
+ "septum": "./bin/septum.ts"
13
+ },
14
+ "engines": {
15
+ "bun": ">=1.1.0"
16
+ },
17
+ "scripts": {
18
+ "start": "bun run bin/septum.ts",
19
+ "serve": "bun run bin/septum.ts serve",
20
+ "ingest": "bun run bin/septum.ts sync",
21
+ "sync": "bun run bin/septum.ts sync",
22
+ "check": "bun run bin/septum.ts check",
23
+ "test": "bun test",
24
+ "build": "bun build ./bin/septum.ts --compile --outfile dist/septum",
25
+ "compile:all": "bun run scripts/compile.ts",
26
+ "typecheck": "tsc --noEmit",
27
+ "test:integration": "python3 tests/integration/mcp-reliability.py",
28
+ "postinstall": "bun run scripts/postinstall.ts || true"
29
+ },
30
+ "dependencies": {
31
+ "@modelcontextprotocol/sdk": "^1.5.0",
32
+ "web-tree-sitter": "^0.24.0",
33
+ "yaml": "^2.7.0",
34
+ "zod": "^3.24.2",
35
+ "tree-sitter-wasms": "^0.1.13"
36
+ },
37
+ "license": "MIT",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/shironim/septum-mcp.git"
41
+ },
42
+ "homepage": "https://github.com/shironim/septum-mcp#readme",
43
+ "bugs": {
44
+ "url": "https://github.com/shironim/septum-mcp/issues"
45
+ },
46
+ "keywords": [
47
+ "mcp",
48
+ "model-context-protocol",
49
+ "bounded-context",
50
+ "architecture",
51
+ "ai-agent",
52
+ "tree-sitter",
53
+ "clean-architecture",
54
+ "domain-driven-design",
55
+ "codebase-catalog",
56
+ "antigravity"
57
+ ],
58
+ "files": [
59
+ "bin",
60
+ "src",
61
+ "scripts/postinstall.ts",
62
+ "dist/*.js",
63
+ "dist/*.d.ts",
64
+ "README.md",
65
+ "LICENSE"
66
+ ],
67
+ "devDependencies": {
68
+ "@types/bun": "latest",
69
+ "@types/node": "^22.13.4",
70
+ "typescript": "^5.7.3"
71
+ }
72
+ }
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env bun
2
+ import { SEPTUM_VERSION } from "../src/version.ts";
3
+
4
+ function printBanner(): void {
5
+ const v = `v${SEPTUM_VERSION}`;
6
+ console.log(`
7
+ \x1b[36m╭─────────────────────────────────────────────────────────────╮\x1b[0m
8
+ \x1b[36m│\x1b[0m \x1b[36m│\x1b[0m
9
+ \x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m \x1b[1mSeptum ${v}\x1b[0m successfully installed! \x1b[36m│\x1b[0m
10
+ \x1b[36m│\x1b[0m \x1b[36m│\x1b[0m
11
+ \x1b[36m│\x1b[0m \x1b[1mNext Steps:\x1b[0m \x1b[36m│\x1b[0m
12
+ \x1b[36m│\x1b[0m 1. Navigate to your project directory: \x1b[36m│\x1b[0m
13
+ \x1b[36m│\x1b[0m \x1b[36m$ cd /path/to/your-project\x1b[0m \x1b[36m│\x1b[0m
14
+ \x1b[36m│\x1b[0m 2. Initialize local guard & configure AI agent harness: \x1b[36m│\x1b[0m
15
+ \x1b[36m│\x1b[0m \x1b[36m$ septum init\x1b[0m \x1b[36m│\x1b[0m
16
+ \x1b[36m│\x1b[0m \x1b[36m│\x1b[0m
17
+ \x1b[36m╰─────────────────────────────────────────────────────────────╯\x1b[0m
18
+ `);
19
+ }
20
+
21
+ try {
22
+ printBanner();
23
+ } catch {
24
+ // Postinstall output failure should never abort installation
25
+ }
@@ -0,0 +1,122 @@
1
+ import { BoundaryEvaluator } from "../../core/boundary/evaluator.ts";
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 type { BoundaryViolation } from "../../types/index.ts";
6
+ import { IngestionPipeline } from "../../core/ingestion/pipeline.ts";
7
+ import { auditStagedFiles } from "../../core/boundary/staged-auditor.ts";
8
+ import { resolveWorkspaceRoot } from "../../core/resolver/path-resolver.ts";
9
+ import { ModuleResolver } from "../../core/resolver/module-resolver.ts";
10
+ import { join, isAbsolute } from "node:path";
11
+
12
+ export interface CheckCommandOptions {
13
+ strict?: boolean;
14
+ staged?: boolean;
15
+ feature?: string;
16
+ json?: boolean;
17
+ }
18
+
19
+ export async function handleCheckCommand(
20
+ optionsOrStrict?: boolean | CheckCommandOptions
21
+ ): Promise<void> {
22
+ const options: CheckCommandOptions =
23
+ typeof optionsOrStrict === "boolean" ? { strict: optionsOrStrict } : optionsOrStrict || {};
24
+
25
+ if (!options.json) {
26
+ console.log(
27
+ options.staged
28
+ ? "[Septum] Auditing git staged files against domain boundaries..."
29
+ : "[Septum] Running codebase boundary integrity check..."
30
+ );
31
+ }
32
+
33
+ const workspaceRoot = resolveWorkspaceRoot(process.cwd());
34
+ const config = ConfigLoader.load(undefined, workspaceRoot);
35
+ if (options.strict) config.settings.enforcement = "strict";
36
+ const db = new SeptumDatabase(isAbsolute(config.settings.db_path) ? config.settings.db_path : join(workspaceRoot, config.settings.db_path));
37
+ const repo = new SeptumRepository(db.raw);
38
+ const evaluator = new BoundaryEvaluator(repo, new ModuleResolver(workspaceRoot, repo));
39
+
40
+ try {
41
+ let violations: BoundaryViolation[] = [];
42
+
43
+ const totalDomains = Object.keys(config.domains).length;
44
+ if (!options.staged && totalDomains === 0) {
45
+ const isStrict = options.strict || config.settings.enforcement === "strict";
46
+ if (options.json) {
47
+ console.log(JSON.stringify({
48
+ status: "not_indexed",
49
+ strict: isStrict,
50
+ violations: [],
51
+ message: "No domains registered in workspace. Run 'septum init' first to discover and register domains.",
52
+ }, null, 2));
53
+ } else {
54
+ console.warn("[Septum Warning] No domains registered in workspace. Run 'septum init' first to discover and register domains.");
55
+ }
56
+ if (isStrict) process.exitCode = 1;
57
+ return;
58
+ }
59
+
60
+ if (options.staged) {
61
+ const staged = await auditStagedFiles(evaluator, config, workspaceRoot, options.feature, repo);
62
+ violations = staged.violations;
63
+ if (staged.resolution_issues.length && violations.length === 0) {
64
+ console.warn(options.json ? JSON.stringify({ status: "unknown", resolution_issues: staged.resolution_issues }) : "Staged import resolution is incomplete; approval is unknown.");
65
+ if (options.strict || config.settings.enforcement === "strict") process.exitCode = 1;
66
+ return;
67
+ }
68
+ } else {
69
+ await new IngestionPipeline(repo, workspaceRoot).run(config, { verifyContent: true });
70
+ const unsupported = JSON.parse(repo.getMeta("unsupported_files") || "[]") as string[];
71
+ if (unsupported.length > 0) {
72
+ throw new Error(`Cannot complete boundary audit: unsupported source files: ${unsupported.join(", ")}`);
73
+ }
74
+ const skipped = JSON.parse(repo.getMeta("skipped_files") || "[]") as {path: string}[];
75
+ if (skipped.length) throw new Error(`Cannot complete boundary audit: files exceed resource limits: ${skipped.map(file => file.path).join(", ")}`);
76
+ violations = evaluator.auditCodebase(config);
77
+ const incomplete = repo.getImportRelationships(workspaceRoot).filter(edge => edge.freshness !== "current" || edge.index_coverage !== "complete" || !["resolved","external"].includes(edge.resolution.status) || edge.resolution.coverage === "conditional");
78
+ if (incomplete.length && violations.length === 0) {
79
+ const strict = options.strict || config.settings.enforcement === "strict";
80
+ const payload = { status: "unknown", relationships: incomplete, message: "Import resolution is incomplete; boundary approval is unknown." };
81
+ console.warn(options.json ? JSON.stringify(payload) : payload.message);
82
+ if (strict) process.exitCode = 1;
83
+ return;
84
+ }
85
+ }
86
+
87
+ if (options.json) {
88
+ const isStrict = options.strict || config.settings.enforcement === "strict";
89
+ console.log(JSON.stringify({
90
+ status: violations.length === 0 ? "clean" : "violations_found",
91
+ strict: isStrict,
92
+ violations,
93
+ }, null, 2));
94
+ if (violations.length > 0 && isStrict) process.exitCode = 1;
95
+ return;
96
+ }
97
+
98
+ if (violations.length === 0) {
99
+ console.log("✓ All domain boundaries are clean. Zero cross-domain leaks detected.");
100
+ return;
101
+ }
102
+
103
+ console.error(`\n[Septum Boundary Violation] Found ${violations.length} boundary violation(s):\n`);
104
+
105
+ for (const v of violations) {
106
+ console.error(` ✕ [${v.rule.toUpperCase()}] at ${v.file}:${v.line}`);
107
+ console.error(` Source Domain: ${v.source_domain}`);
108
+ console.error(` Target Domain: ${v.target_domain}`);
109
+ console.error(` Import Target: ${v.imported_target}`);
110
+ console.error(` Message: ${v.message}\n`);
111
+ }
112
+
113
+
114
+ const isStrict = options.strict || config.settings.enforcement === "strict";
115
+ if (isStrict) {
116
+ console.error("[Septum Failure] Process terminated with exit code 1 due to boundary violations.");
117
+ process.exitCode = 1;
118
+ }
119
+ } finally {
120
+ db.close();
121
+ }
122
+ }
@@ -0,0 +1,268 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { BoundaryEvaluator } from "../../core/boundary/evaluator.ts";
4
+ import { ConfigLoader } from "../../core/config/loader.ts";
5
+ import { SeptumDatabase } from "../../core/database/client.ts";
6
+ import { SeptumRepository } from "../../core/database/repository.ts";
7
+ import { ASTParserEngine } from "../../core/parser/tree-sitter.ts";
8
+ import { SessionManager } from "../../core/session/session-manager.ts";
9
+
10
+ interface ToolCallInfo {
11
+ name?: string;
12
+ args?: Record<string, unknown>;
13
+ }
14
+
15
+ export interface ToolPayload {
16
+ tool_name?: string;
17
+ toolCall?: ToolCallInfo;
18
+ tool_input?: {
19
+ TargetFile?: string;
20
+ file_path?: string;
21
+ filePath?: string;
22
+ path?: string;
23
+ ReplacementContent?: string;
24
+ CodeContent?: string;
25
+ new_string?: string;
26
+ content?: string;
27
+ ReplacementChunks?: Array<{ ReplacementContent?: string }>;
28
+ feature_key?: string;
29
+ };
30
+ arguments?: Record<string, unknown>;
31
+ TargetFile?: string;
32
+ file_path?: string;
33
+ filePath?: string;
34
+ path?: string;
35
+ ReplacementContent?: string;
36
+ CodeContent?: string;
37
+ }
38
+
39
+ let configuredExitCode = 1;
40
+
41
+ export async function handleHookCommand(args: string[]): Promise<void> {
42
+ const subHook = args[1] || "pre-write";
43
+ if (args.includes("--exit-code-2") || args.includes("--claude") || args.includes("--cursor")) {
44
+ configuredExitCode = 2;
45
+ }
46
+
47
+ if (subHook === "pre-write") {
48
+ await runPreWriteHook();
49
+ } else {
50
+ process.exit(0);
51
+ }
52
+ }
53
+
54
+ function blockHook(db: SeptumDatabase | null, reason: string): never {
55
+ if (db) {
56
+ try {
57
+ db.close();
58
+ } catch {
59
+ // ignore
60
+ }
61
+ }
62
+
63
+ // Print readable error to stderr for humans and Claude/Cursor/Codex
64
+ console.error(reason);
65
+
66
+ // Print JSON contract to stdout for Antigravity hook engine
67
+ try {
68
+ process.stdout.write(
69
+ JSON.stringify({
70
+ decision: "deny",
71
+ reason: reason.trim(),
72
+ }) + "\n"
73
+ );
74
+ } catch {
75
+ // ignore
76
+ }
77
+
78
+ // Exit code: 1 by default (Unix standard), or 2 if specified for Claude Code / Cursor hooks
79
+ process.exit(configuredExitCode);
80
+ }
81
+
82
+ async function runPreWriteHook(): Promise<void> {
83
+ // If .septum/septum.db does not exist, pass through
84
+ const dbPath = path.resolve(process.cwd(), ".septum", "septum.db");
85
+ if (!fs.existsSync(dbPath)) {
86
+ process.exit(0);
87
+ }
88
+
89
+ // Read JSON payload from stdin
90
+ const stdinData = await readStdin();
91
+ if (!stdinData.trim()) {
92
+ process.exit(0);
93
+ }
94
+
95
+ let payload: ToolPayload;
96
+ try {
97
+ payload = JSON.parse(stdinData);
98
+ } catch {
99
+ // Non-JSON stdin, pass through
100
+ process.exit(0);
101
+ }
102
+
103
+ const toolInput: Record<string, any> =
104
+ payload.tool_input ||
105
+ payload.arguments ||
106
+ payload.toolCall?.args ||
107
+ (payload as Record<string, any>) ||
108
+ {};
109
+ const targetFile: string | undefined =
110
+ toolInput.TargetFile || toolInput.file_path || toolInput.filePath || toolInput.path;
111
+ const chunkContent = Array.isArray(toolInput.ReplacementChunks)
112
+ ? toolInput.ReplacementChunks.map((c: any) => c?.ReplacementContent || "").join("\n")
113
+ : "";
114
+ const content: string =
115
+ toolInput.ReplacementContent ||
116
+ toolInput.CodeContent ||
117
+ toolInput.new_string ||
118
+ toolInput.content ||
119
+ chunkContent ||
120
+ "";
121
+
122
+ if (!targetFile) {
123
+ process.exit(0);
124
+ }
125
+
126
+ const config = ConfigLoader.load();
127
+ const db = new SeptumDatabase(config.settings.db_path);
128
+ const repo = new SeptumRepository(db.raw);
129
+ const evaluator = new BoundaryEvaluator(repo);
130
+
131
+ try {
132
+ const sourceDomain = evaluator.resolveSourceDomain(targetFile, config);
133
+
134
+ // If file is not inside any domain, allow or check feature scope
135
+ if (sourceDomain) {
136
+ // -------------------------------------------------------------
137
+ // GATE 3: Mandatory Catalog Consultation
138
+ // Verify that the AI has consulted the domain catalog before writing
139
+ // -------------------------------------------------------------
140
+ const accessLogPath = path.resolve(process.cwd(), ".septum/catalog_access.json");
141
+ let hasConsulted = false;
142
+
143
+ if (fs.existsSync(accessLogPath)) {
144
+ try {
145
+ const rawAccess = JSON.parse(fs.readFileSync(accessLogPath, "utf-8"));
146
+ const domainsMap: Record<string, string> = rawAccess.domains || {};
147
+ const lowerSource = sourceDomain.toLowerCase();
148
+ const domainAccessedAt =
149
+ domainsMap[sourceDomain] ||
150
+ domainsMap[lowerSource] ||
151
+ Object.entries(domainsMap).find(([k]) => k.toLowerCase() === lowerSource)?.[1];
152
+ if (domainAccessedAt) {
153
+ hasConsulted = true;
154
+ }
155
+ } catch {
156
+ // ignore parse error
157
+ }
158
+ }
159
+
160
+ if (!hasConsulted) {
161
+ blockHook(
162
+ db,
163
+ `\n[SEPTUM GATE 3 VIOLATION - Mandatory Consultation Required]\n` +
164
+ `✕ Operation blocked: You are attempting to write to domain '${sourceDomain}' (${targetFile}) ` +
165
+ `without inspecting its authoritative symbol & file-connection catalog first.\n` +
166
+ `▶ REQUIRED ACTION: Call tool 'septum_domain({ action: "catalog", domain: "${sourceDomain}", detail_level: "compact" })' ` +
167
+ `or 'septum_feature({ action: "get" })' before writing code.\n`
168
+ );
169
+ }
170
+ }
171
+
172
+ // -------------------------------------------------------------
173
+ // GATE 1: Hard Touchpoint Lock (if features are defined)
174
+ // -------------------------------------------------------------
175
+ const session = SessionManager.getActiveSession(process.cwd());
176
+ const requestedFeatureKey = toolInput.feature_key || process.env.SEPTUM_ACTIVE_FEATURE;
177
+ if (session && requestedFeatureKey && requestedFeatureKey !== session.feature_key) {
178
+ throw new Error(`Requested feature '${requestedFeatureKey}' does not own the active scope '${session.feature_key}'.`);
179
+ }
180
+ const activeFeatureKey = session?.feature_key || requestedFeatureKey;
181
+
182
+ if (activeFeatureKey) {
183
+ const touchpointViolations = evaluator.checkFeatureTouchpoints(
184
+ activeFeatureKey,
185
+ targetFile,
186
+ config
187
+ );
188
+
189
+ if (touchpointViolations.length > 0) {
190
+ blockHook(
191
+ db,
192
+ `\n[SEPTUM GATE 1 VIOLATION - Scope Touchpoint Lock]\n` +
193
+ `✕ Operation blocked: File '${targetFile}' is outside the declared allowed_touchpoints for feature '${activeFeatureKey}'.\n` +
194
+ `▶ REASON: ${touchpointViolations[0].message}\n` +
195
+ `▶ REQUIRED ACTION: Only modify files declared in allowed_touchpoints for this feature.\n`
196
+ );
197
+ }
198
+ }
199
+
200
+ // -------------------------------------------------------------
201
+ // GATE 2: Real-time AST Import Interception
202
+ // Extract imports from proposed content and check for boundary leaks
203
+ // -------------------------------------------------------------
204
+ if (content && sourceDomain) {
205
+ const astEngine = new ASTParserEngine();
206
+ const parsed = await astEngine.parseFile(targetFile, content);
207
+ if (ASTParserEngine.isSourceFile(targetFile) && (parsed.status === "unsupported" || parsed.status === "degraded")) {
208
+ throw new Error(`Cannot reliably check imports in '${targetFile}': parser status is ${parsed.status}.`);
209
+ }
210
+
211
+ const proposedImports = parsed.dependencies.map((d) => d.target);
212
+ const boundaryViolations = evaluator.checkProposedChanges(
213
+ targetFile,
214
+ proposedImports,
215
+ config
216
+ );
217
+
218
+ if (boundaryViolations.length > 0) {
219
+ const v = boundaryViolations[0];
220
+ blockHook(
221
+ db,
222
+ `\n[SEPTUM GATE 2 VIOLATION - Forbidden Cross-Domain Import]\n` +
223
+ `✕ Operation blocked: Proposed code imports forbidden domain '${v.target_domain}' from '${v.source_domain}'.\n` +
224
+ `▶ OFFENDING IMPORT: ${v.imported_target}\n` +
225
+ `▶ RULE: ${v.rule}\n` +
226
+ `▶ MESSAGE: ${v.message}\n` +
227
+ `▶ REQUIRED ACTION: Decouple this dependency. Use an authorized Interface, Event, or Shared Kernel.\n`
228
+ );
229
+ }
230
+ }
231
+
232
+ db.close();
233
+
234
+ // If running in Antigravity or standard JSON IPC mode, emit allow decision
235
+ try {
236
+ process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
237
+ } catch {
238
+ // ignore
239
+ }
240
+ process.exit(0);
241
+ } catch (err) {
242
+ db.close();
243
+ const message = err instanceof Error ? err.message : String(err);
244
+ console.error(`\x1b[31m[Septum Hook Error]\x1b[0m ${message}`);
245
+ process.exit(1);
246
+ }
247
+ }
248
+
249
+ function readStdin(): Promise<string> {
250
+ return new Promise((resolve) => {
251
+ let data = "";
252
+ if (process.stdin.isTTY) {
253
+ resolve("");
254
+ return;
255
+ }
256
+
257
+ process.stdin.setEncoding("utf-8");
258
+ process.stdin.on("data", (chunk) => {
259
+ data += chunk;
260
+ });
261
+ process.stdin.on("end", () => {
262
+ resolve(data);
263
+ });
264
+ process.stdin.on("error", () => {
265
+ resolve("");
266
+ });
267
+ });
268
+ }