@dimassetoid/septum-mcp 0.2.1 → 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 (106) hide show
  1. package/README.md +46 -28
  2. package/package.json +4 -4
  3. package/src/cli/commands/check.ts +27 -16
  4. package/src/cli/commands/hook.ts +38 -101
  5. package/src/cli/commands/init.ts +26 -9
  6. package/src/cli/commands/sync.ts +4 -6
  7. package/src/cli/hook-payload.ts +43 -0
  8. package/src/cli/index.ts +9 -52
  9. package/src/cli/scaffold/harness-config.ts +48 -8
  10. package/src/cli/templates/hooks.ts +49 -14
  11. package/src/cli/templates/rules.ts +34 -49
  12. package/src/cli/templates/skill.ts +39 -35
  13. package/src/core/boundary/evaluator.ts +67 -83
  14. package/src/core/boundary/staged-auditor.ts +102 -40
  15. package/src/core/config/domain-ownership.ts +45 -0
  16. package/src/core/config/loader.ts +81 -29
  17. package/src/core/config/schema.ts +0 -10
  18. package/src/core/database/repositories/dependency.repository.ts +169 -148
  19. package/src/core/database/repositories/domain.repository.ts +46 -3
  20. package/src/core/database/repositories/symbol.repository.ts +226 -87
  21. package/src/core/database/repository.ts +73 -18
  22. package/src/core/database/schema.ts +2 -33
  23. package/src/core/discovery/navigation.ts +105 -0
  24. package/src/core/discovery/topology-detector.ts +60 -2
  25. package/src/core/ingestion/pipeline.ts +96 -129
  26. package/src/core/parser/behavioral-analyzer.ts +26 -22
  27. package/src/core/parser/boundary-tracker.ts +15 -0
  28. package/src/core/parser/extractors/base.ts +7 -3
  29. package/src/core/parser/extractors/csharp.ts +7 -3
  30. package/src/core/parser/extractors/django-semantic.ts +4 -36
  31. package/src/core/parser/extractors/elysia-semantic.ts +3 -24
  32. package/src/core/parser/extractors/express-semantic.ts +3 -18
  33. package/src/core/parser/extractors/fastapi-semantic.ts +19 -53
  34. package/src/core/parser/extractors/fastify-semantic.ts +3 -18
  35. package/src/core/parser/extractors/flask-semantic.ts +22 -55
  36. package/src/core/parser/extractors/go-semantic.ts +92 -33
  37. package/src/core/parser/extractors/hono-semantic.ts +3 -24
  38. package/src/core/parser/extractors/java.ts +5 -3
  39. package/src/core/parser/extractors/laravel-semantic.ts +44 -16
  40. package/src/core/parser/extractors/mcp-cli-semantic.ts +6 -7
  41. package/src/core/parser/extractors/nestjs-semantic.ts +3 -19
  42. package/src/core/parser/extractors/php.ts +16 -0
  43. package/src/core/parser/extractors/python.ts +9 -4
  44. package/src/core/parser/extractors/registry.ts +26 -5
  45. package/src/core/parser/extractors/ruby.ts +8 -5
  46. package/src/core/parser/extractors/rust.ts +31 -13
  47. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  48. package/src/core/parser/extractors/symfony-semantic.ts +4 -37
  49. package/src/core/parser/extractors/typescript.ts +14 -1
  50. package/src/core/parser/implementation-fingerprint.ts +97 -0
  51. package/src/core/parser/language-capabilities.ts +23 -7
  52. package/src/core/parser/schema/providers/laravel-migration-provider.ts +73 -50
  53. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  54. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  55. package/src/core/parser/semantic-revision.ts +3 -0
  56. package/src/core/parser/static-string.ts +51 -0
  57. package/src/core/resolver/call-graph-tracer.ts +337 -28
  58. package/src/core/resolver/import-resolver.ts +107 -179
  59. package/src/core/resolver/interpretation-inputs.ts +7 -0
  60. package/src/core/resolver/languages/go.ts +103 -0
  61. package/src/core/resolver/languages/managed.ts +200 -0
  62. package/src/core/resolver/languages/python.ts +115 -0
  63. package/src/core/resolver/languages/ruby.ts +40 -0
  64. package/src/core/resolver/languages/rust.ts +127 -0
  65. package/src/core/resolver/languages/shared.ts +71 -0
  66. package/src/core/resolver/module-resolver.ts +8 -4
  67. package/src/core/resolver/slice-catalog.ts +79 -0
  68. package/src/core/resolver/slice-format.ts +9 -0
  69. package/src/core/resolver/symbol-impact.ts +381 -0
  70. package/src/core/resolver/vertical-slice-tracer.ts +93 -115
  71. package/src/core/resources/ignore.ts +22 -1
  72. package/src/core/resources/source-files.ts +143 -20
  73. package/src/core/resources/source-inventory.ts +55 -0
  74. package/src/core/retrieval/context-page.ts +109 -0
  75. package/src/core/retrieval/context.ts +320 -0
  76. package/src/core/retrieval/resolution-warnings.ts +21 -0
  77. package/src/core/retrieval/symbol-evidence.ts +97 -0
  78. package/src/core/retrieval/typescript-references.ts +262 -0
  79. package/src/core/telemetry/telemetry.ts +54 -9
  80. package/src/index.ts +0 -3
  81. package/src/mcp/schemas.ts +61 -420
  82. package/src/mcp/server.ts +116 -290
  83. package/src/mcp/tools/boundary.ts +2 -2
  84. package/src/mcp/tools/check-boundary.ts +55 -60
  85. package/src/mcp/tools/get-domain-catalog.ts +32 -219
  86. package/src/mcp/tools/get-symbol-impact.ts +45 -5
  87. package/src/mcp/tools/get-symbol.ts +227 -3
  88. package/src/mcp/tools/locate-symbol.ts +54 -14
  89. package/src/mcp/tools/{domain.ts → map.ts} +4 -18
  90. package/src/mcp/tools/register-domain.ts +41 -3
  91. package/src/mcp/tools/symbol.ts +23 -21
  92. package/src/mcp/tools/trace-vertical-slice.ts +36 -10
  93. package/src/mcp/workspace-manager.ts +15 -4
  94. package/src/mcp/workspace-watcher.ts +8 -8
  95. package/src/types/index.ts +35 -53
  96. package/src/cli/commands/topology.ts +0 -161
  97. package/src/core/database/repositories/environment.repository.ts +0 -207
  98. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  99. package/src/core/session/session-manager.ts +0 -107
  100. package/src/core/topology/environment-detector.ts +0 -973
  101. package/src/core/topology/types.ts +0 -83
  102. package/src/mcp/tools/feature.ts +0 -67
  103. package/src/mcp/tools/get-environment-topology.ts +0 -138
  104. package/src/mcp/tools/get-feature-context.ts +0 -224
  105. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  106. package/src/mcp/tools/register-feature.ts +0 -110
package/README.md CHANGED
@@ -2,21 +2,23 @@
2
2
 
3
3
  > **Architecture boundary guard and codebase intelligence for AI coding agents.**
4
4
 
5
- [![Version: 0.2.1](https://img.shields.io/badge/Version-0.2.1-blue)](package.json)
5
+ [![Version: 0.3.0](https://img.shields.io/badge/Version-0.3.0-blue)](package.json)
6
6
  [![Runtime: Bun](https://img.shields.io/badge/Runtime-Bun-black?logo=bun)](https://bun.sh)
7
7
  [![Protocol: Model Context Protocol](https://img.shields.io/badge/Protocol-MCP-green)](https://modelcontextprotocol.io/)
8
8
  [![Database: SQLite WAL](https://img.shields.io/badge/Database-SQLite%20(bun:sqlite)-003B57?logo=sqlite)](https://sqlite.org/)
9
9
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue)](LICENSE)
10
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.
11
+ Septum provides architecture maps, declaration context, and boundary checks for AI coding agents before and after edits. It indexes source in a local SQLite database and evaluates configured domain dependency rules. Results describe detected relationships and analysis limits; application behavior still requires application verification.
12
+
13
+ Start with the [implemented feature documentation](docs/feature/README.md), which describes the reviewed source checkout, tool behavior and known limits. Installed binaries and running MCP processes can use a different revision.
12
14
 
13
15
  ---
14
16
 
15
17
  ## Installation
16
18
 
17
- ### Option 1: Standalone Binary (Recommended)
19
+ ### Option 1: Standalone Binary
18
20
 
19
- No need to install Bun, Node.js, or package managers. Download and install the prebuilt binary:
21
+ The standalone executable bundles its runtime. The installation scripts select a release executable for the platform:
20
22
 
21
23
  **Linux & macOS:**
22
24
  ```bash
@@ -38,32 +40,39 @@ If you already use [Bun](https://bun.sh):
38
40
  bun add -g @dimassetoid/septum-mcp
39
41
  ```
40
42
 
41
- > **Zero-Install:** You can also run commands directly using `bunx @dimassetoid/septum-mcp <command>`.
43
+ You can invoke the package with `bunx @dimassetoid/septum-mcp <command>`.
42
44
 
43
45
  ---
44
46
 
45
47
  ## Quick Start
46
48
 
47
- ### 1. Initialize in Any Project
49
+ ### 1. Initialize a Workspace
48
50
 
49
51
  Run `septum init` from the workspace directory you want Septum to manage:
50
52
 
51
53
  ```bash
52
54
  septum init
53
- # or zero-install via bunx:
54
- bunx septum init
55
+ # or via bunx:
56
+ bunx @dimassetoid/septum-mcp init
55
57
  ```
56
58
 
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:
59
+ Initialization:
60
+
61
+ 1. **Infers Project Structure:** Uses supported manifests and directory layouts to propose domains and dependency policies.
62
+ 2. **Indexes Supported Source:** Stores extracted declarations, imports and static entrypoints in the configured database; the default is `.septum/septum.db`.
63
+ 3. **Scaffolds Selected Agent Configurations:** Writes MCP configuration, skills and hook artifacts for supported environments:
61
64
  - **Antigravity** (`.gemini/`)
62
65
  - **Claude Code** (`.claude/`, `.mcp.json`, `CLAUDE.md`)
63
66
  - **Codex** (`.codex/`)
64
67
  - **Opencode** (`opencode/`, `opencode.json`)
65
68
  - **.agents Standard** (`.agents/`, `AGENTS.md`)
66
69
 
70
+ Semantic adapters cover selected patterns in Laravel, Symfony, MCP/CLI, NestJS, Express, Fastify, Hono, Elysia, FastAPI, Django, Flask and Go. Their applicability and extraction results depend on repository syntax and configuration.
71
+
72
+ Import resolution includes supported Python manifests/lockfiles, Go workspaces/replacements, Rust Cargo/modules, Ruby literal requires/gems, Java source projects and C# namespaces/project references. See [import resolution](docs/feature/import-resolution.md) for supported cases and unresolved boundaries.
73
+
74
+ Detection and scaffolding do not certify every framework pattern or active client hook. See the [feature specifications and architecture contracts](docs/feature/README.md) for full scope and technical details.
75
+
67
76
  ### 2. Manual MCP Client Configuration (Optional)
68
77
 
69
78
  If your MCP client is not configured via `septum init`, add Septum to your MCP configuration (`.mcp.json` or `claude_desktop_config.json`):
@@ -78,7 +87,7 @@ If your MCP client is not configured via `septum init`, add Septum to your MCP c
78
87
  }
79
88
  }
80
89
  ```
81
- *(Or use `"command": "bunx", "args": ["septum", "serve"]` if running without global installation).*
90
+ *(Or use `"command": "bunx", "args": ["@dimassetoid/septum-mcp", "serve"]` when invoking the package through Bun).*
82
91
 
83
92
  ---
84
93
 
@@ -86,12 +95,10 @@ If your MCP client is not configured via `septum init`, add Septum to your MCP c
86
95
 
87
96
  | Command | Description |
88
97
  |---|---|
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 |
98
+ | `septum init [--force]` | Scaffold agent integrations and build initial symbol catalog. `--force` regenerates Septum-managed configs while preserving existing database and user git hooks |
90
99
  | `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 |
100
+ | `septum check [--strict] [--staged] [--json]` | Verify boundary rules and detect cross-domain or circular dependency violations |
101
+ | `septum hook pre-write` | Reconstruct supported candidate edits from stdin and evaluate their imports; interception depends on the client and hook configuration |
95
102
  | `septum serve` | Start stdio Model Context Protocol (MCP) server |
96
103
 
97
104
  ---
@@ -100,22 +107,33 @@ If your MCP client is not configured via `septum init`, add Septum to your MCP c
100
107
 
101
108
  All tools provide structured schemas via the Model Context Protocol:
102
109
 
103
- - **Domain & Architecture Overview (`septum_domain`):**
104
- - `action: "catalog"`: High-level architecture map and module dependencies (`detail_level: "compact" | "full"`).
110
+ - **Domain Map & Discovery (`septum_map`):**
111
+ - `action: "catalog"`: Navigation map (`navigation/v1`): domain/file import paths, static entrypoints, health and targeted next steps. `full` expands navigation; inspect signatures and source with `septum_symbol`.
105
112
  - `action: "register"`: Register or update domain boundaries with allowed and forbidden dependencies.
106
- - `action: "topology"`: Inspect deployment environment and infrastructure services.
107
113
  - **Symbol Inspection & Impact Analysis (`septum_symbol`):**
108
114
  - `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.
115
+ - `action: "context"` (accepts `action: "inspect"` as alias): Retrieve declaration implementation and supporting declarations (deep TypeScript context retrieval within `budget_bytes`, or bounded polyglot source inspection).
116
+ - `action: "impact"`: Inspect static dependent/caller hints. Imports are reported separately and do not prove executed calls or a complete runtime blast radius.
112
117
  - **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.
118
+ - Navigate static context across application layers from supported entrypoints (`query`, `controller_file`, `max_depth`). Each node shows its relationship evidence or `unknown`.
114
119
  - **Dependency & Boundary Validator (`septum_boundary`):**
115
120
  - 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.
121
+ - Check staged files in the Git index before commit (`scope: "staged"`).
122
+ - Audit circular dependencies and boundary violations for a specific domain (`scope: "domain"`) or the entire codebase (`scope: "all"`).
123
+
124
+ ---
125
+
126
+ ## Select context before editing
127
+
128
+ Locate a declaration, select its returned `symbol_ref` when names are ambiguous, then request context:
129
+
130
+ ```json
131
+ {"action":"context","query":"submit","file_path":"src/submit.ts","budget_bytes":65536}
132
+ ```
133
+
134
+ Send these arguments to `septum_symbol` with an explicit `workspace_path` when needed. Context v4 supports `.ts/.mts/.cts` and selects supporting declarations through bounded local/import bindings. Set `context_mode: "deep"` explicitly for this policy, or `context_mode: "source"` for bounded source inspection. Omission preserves legacy automatic selection; responses identify the selected mode. TSX and complete business dependency closure are outside the deep-context policy.
135
+
136
+ Read evidence scope, freshness and omissions before editing. Context inspection returns source/contracts; lookup and server freshness guards can synchronize the local index. Use impact for potential consumers and application checks for behavior. Budget, paging, source identity and recovery semantics have one owner: the [symbol context contract](docs/feature/symbol-context-contract.md). Per-action requirements are in [septum_symbol](docs/feature/septum-symbol.md).
119
137
 
120
138
  ---
121
139
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dimassetoid/septum-mcp",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Deterministic Bounded-Context, Structural File Catalog & Anti-Poisoning Partition for AI Agents",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -32,7 +32,8 @@
32
32
  "web-tree-sitter": "^0.24.0",
33
33
  "yaml": "^2.7.0",
34
34
  "zod": "^3.24.2",
35
- "tree-sitter-wasms": "^0.1.13"
35
+ "tree-sitter-wasms": "^0.1.13",
36
+ "typescript": "^5.7.3"
36
37
  },
37
38
  "license": "MIT",
38
39
  "repository": {
@@ -66,7 +67,6 @@
66
67
  ],
67
68
  "devDependencies": {
68
69
  "@types/bun": "latest",
69
- "@types/node": "^22.13.4",
70
- "typescript": "^5.7.3"
70
+ "@types/node": "^22.13.4"
71
71
  }
72
72
  }
@@ -1,5 +1,5 @@
1
1
  import { BoundaryEvaluator } from "../../core/boundary/evaluator.ts";
2
- import { ConfigLoader } from "../../core/config/loader.ts";
2
+ import { ConfigLoader, resolveDatabasePath } from "../../core/config/loader.ts";
3
3
  import { SeptumDatabase } from "../../core/database/client.ts";
4
4
  import { SeptumRepository } from "../../core/database/repository.ts";
5
5
  import type { BoundaryViolation } from "../../types/index.ts";
@@ -7,12 +7,11 @@ import { IngestionPipeline } from "../../core/ingestion/pipeline.ts";
7
7
  import { auditStagedFiles } from "../../core/boundary/staged-auditor.ts";
8
8
  import { resolveWorkspaceRoot } from "../../core/resolver/path-resolver.ts";
9
9
  import { ModuleResolver } from "../../core/resolver/module-resolver.ts";
10
- import { join, isAbsolute } from "node:path";
11
10
 
12
11
  export interface CheckCommandOptions {
13
12
  strict?: boolean;
14
13
  staged?: boolean;
15
- feature?: string;
14
+ domain?: string;
16
15
  json?: boolean;
17
16
  }
18
17
 
@@ -33,7 +32,7 @@ export async function handleCheckCommand(
33
32
  const workspaceRoot = resolveWorkspaceRoot(process.cwd());
34
33
  const config = ConfigLoader.load(undefined, workspaceRoot);
35
34
  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));
35
+ const db = new SeptumDatabase(resolveDatabasePath(workspaceRoot, config.settings.db_path));
37
36
  const repo = new SeptumRepository(db.raw);
38
37
  const evaluator = new BoundaryEvaluator(repo, new ModuleResolver(workspaceRoot, repo));
39
38
 
@@ -58,7 +57,7 @@ export async function handleCheckCommand(
58
57
  }
59
58
 
60
59
  if (options.staged) {
61
- const staged = await auditStagedFiles(evaluator, config, workspaceRoot, options.feature, repo);
60
+ const staged = await auditStagedFiles(evaluator, config, workspaceRoot, repo);
62
61
  violations = staged.violations;
63
62
  if (staged.resolution_issues.length && violations.length === 0) {
64
63
  console.warn(options.json ? JSON.stringify({ status: "unknown", resolution_issues: staged.resolution_issues }) : "Staged import resolution is incomplete; approval is unknown.");
@@ -100,21 +99,33 @@ export async function handleCheckCommand(
100
99
  return;
101
100
  }
102
101
 
103
- console.error(`\n[Septum Boundary Violation] Found ${violations.length} boundary violation(s):\n`);
102
+ const isStrict = options.strict || config.settings.enforcement === "strict";
104
103
 
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
- }
104
+ if (isStrict) {
105
+ console.error(`\n[Septum Boundary Violation] Found ${violations.length} boundary violation(s) [STRICT MODE - BLOCKED]:\n`);
112
106
 
107
+ for (const v of violations) {
108
+ console.error(` ✕ [${v.rule.toUpperCase()}] at ${v.file}:${v.line}`);
109
+ console.error(` Source Domain: ${v.source_domain}`);
110
+ console.error(` Target Domain: ${v.target_domain}`);
111
+ console.error(` Import Target: ${v.imported_target}`);
112
+ console.error(` Message: ${v.message}\n`);
113
+ }
113
114
 
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.");
115
+ console.error("[Septum Failure] Process terminated with exit code 1 due to boundary violations in strict mode.");
117
116
  process.exitCode = 1;
117
+ } else {
118
+ console.warn(`\n[Septum Boundary Advisory] Found ${violations.length} boundary advisory item(s) (enforcement: warn - non-blocking):\n`);
119
+
120
+ for (const v of violations) {
121
+ console.warn(` • [${v.rule.toUpperCase()}] at ${v.file}:${v.line}`);
122
+ console.warn(` Source Domain: ${v.source_domain}`);
123
+ console.warn(` Target Domain: ${v.target_domain}`);
124
+ console.warn(` Import Target: ${v.imported_target}`);
125
+ console.warn(` Message: ${v.message}\n`);
126
+ }
127
+
128
+ console.warn("[Septum Advisory Notice] Staged changes allowed (exit code 0). To block commits on boundary violations, configure 'enforcement: \"strict\"' in septum settings or pass '--strict'.\n");
118
129
  }
119
130
  } finally {
120
131
  db.close();
@@ -1,11 +1,14 @@
1
+ import { normalizeHookEdit } from "../hook-payload.ts";
2
+ import { assertPathContained } from "../../core/resolver/path-resolver.ts";
3
+ import { readSourceFile } from "../../core/resources/source-files.ts";
1
4
  import * as fs from "node:fs";
2
5
  import * as path from "node:path";
3
6
  import { BoundaryEvaluator } from "../../core/boundary/evaluator.ts";
4
- import { ConfigLoader } from "../../core/config/loader.ts";
7
+ import { ConfigLoader, resolveDatabasePath } from "../../core/config/loader.ts";
5
8
  import { SeptumDatabase } from "../../core/database/client.ts";
6
9
  import { SeptumRepository } from "../../core/database/repository.ts";
7
10
  import { ASTParserEngine } from "../../core/parser/tree-sitter.ts";
8
- import { SessionManager } from "../../core/session/session-manager.ts";
11
+ import { ModuleResolver } from "../../core/resolver/module-resolver.ts";
9
12
 
10
13
  interface ToolCallInfo {
11
14
  name?: string;
@@ -20,20 +23,27 @@ export interface ToolPayload {
20
23
  file_path?: string;
21
24
  filePath?: string;
22
25
  path?: string;
26
+ Path?: string;
23
27
  ReplacementContent?: string;
24
28
  CodeContent?: string;
25
29
  new_string?: string;
26
30
  content?: string;
31
+ Content?: string;
32
+ Replacement?: string;
27
33
  ReplacementChunks?: Array<{ ReplacementContent?: string }>;
28
- feature_key?: string;
29
34
  };
30
35
  arguments?: Record<string, unknown>;
31
36
  TargetFile?: string;
32
37
  file_path?: string;
33
38
  filePath?: string;
34
39
  path?: string;
40
+ Path?: string;
35
41
  ReplacementContent?: string;
36
42
  CodeContent?: string;
43
+ new_string?: string;
44
+ content?: string;
45
+ Content?: string;
46
+ Replacement?: string;
37
47
  }
38
48
 
39
49
  let configuredExitCode = 1;
@@ -80,8 +90,10 @@ function blockHook(db: SeptumDatabase | null, reason: string): never {
80
90
  }
81
91
 
82
92
  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");
93
+ const callerRoot = process.cwd();
94
+ const workspaceRoot = path.resolve(process.env.SEPTUM_HOOK_ROOT || callerRoot);
95
+ const config = ConfigLoader.load(undefined, workspaceRoot);
96
+ const dbPath = resolveDatabasePath(workspaceRoot, config.settings.db_path);
85
97
  if (!fs.existsSync(dbPath)) {
86
98
  process.exit(0);
87
99
  }
@@ -100,107 +112,31 @@ async function runPreWriteHook(): Promise<void> {
100
112
  process.exit(0);
101
113
  }
102
114
 
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) {
115
+ let edit;
116
+ try {
117
+ edit = normalizeHookEdit(payload, target => {
118
+ const file = path.resolve(callerRoot, target);
119
+ assertPathContained(file, workspaceRoot, "Hook source");
120
+ return readSourceFile(file);
121
+ });
122
+ if (edit) assertPathContained(path.resolve(callerRoot, edit.target), workspaceRoot, "Hook target");
123
+ } catch (error) { blockHook(null, error instanceof Error ? error.message : String(error)); }
124
+ if (!edit) {
125
+ process.stdout.write(JSON.stringify({ decision: "allow", coverage: "unknown", reason: "Unsupported hook payload; no source candidate was evaluated." }) + "\n");
123
126
  process.exit(0);
124
127
  }
128
+ const targetFile = path.relative(workspaceRoot, path.resolve(callerRoot, edit.target)).replace(/\\/g, "/");
129
+ const content = edit.content;
125
130
 
126
- const config = ConfigLoader.load();
127
- const db = new SeptumDatabase(config.settings.db_path);
131
+ const db = new SeptumDatabase(dbPath);
128
132
  const repo = new SeptumRepository(db.raw);
129
- const evaluator = new BoundaryEvaluator(repo);
133
+ const evaluator = new BoundaryEvaluator(repo, new ModuleResolver(workspaceRoot, repo));
130
134
 
131
135
  try {
132
136
  const sourceDomain = evaluator.resolveSourceDomain(targetFile, config);
133
137
 
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
138
+ // Real-time AST Import Interception:
202
139
  // Extract imports from proposed content and check for boundary leaks
203
- // -------------------------------------------------------------
204
140
  if (content && sourceDomain) {
205
141
  const astEngine = new ASTParserEngine();
206
142
  const parsed = await astEngine.parseFile(targetFile, content);
@@ -212,14 +148,15 @@ async function runPreWriteHook(): Promise<void> {
212
148
  const boundaryViolations = evaluator.checkProposedChanges(
213
149
  targetFile,
214
150
  proposedImports,
215
- config
151
+ config,
152
+ parsed.dependencies.map(d => d.statement)
216
153
  );
217
154
 
218
155
  if (boundaryViolations.length > 0) {
219
156
  const v = boundaryViolations[0];
220
157
  blockHook(
221
158
  db,
222
- `\n[SEPTUM GATE 2 VIOLATION - Forbidden Cross-Domain Import]\n` +
159
+ `\n[SEPTUM BOUNDARY VIOLATION - Forbidden Cross-Domain Import]\n` +
223
160
  `✕ Operation blocked: Proposed code imports forbidden domain '${v.target_domain}' from '${v.source_domain}'.\n` +
224
161
  `▶ OFFENDING IMPORT: ${v.imported_target}\n` +
225
162
  `▶ RULE: ${v.rule}\n` +
@@ -233,7 +170,7 @@ async function runPreWriteHook(): Promise<void> {
233
170
 
234
171
  // If running in Antigravity or standard JSON IPC mode, emit allow decision
235
172
  try {
236
- process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
173
+ process.stdout.write(JSON.stringify({ decision: "allow", coverage: edit.coverage, evaluated: sourceDomain ? "proposed_imports" : "unmapped_domain" }) + "\n");
237
174
  } catch {
238
175
  // ignore
239
176
  }
@@ -242,7 +179,7 @@ async function runPreWriteHook(): Promise<void> {
242
179
  db.close();
243
180
  const message = err instanceof Error ? err.message : String(err);
244
181
  console.error(`\x1b[31m[Septum Hook Error]\x1b[0m ${message}`);
245
- process.exit(1);
182
+ process.exit(configuredExitCode);
246
183
  }
247
184
  }
248
185
 
@@ -3,10 +3,9 @@ import * as path from "node:path";
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { handleSyncCommand } from "./sync.ts";
5
5
  import { TopologyDetector } from "../../core/discovery/topology-detector.ts";
6
- import { EnvironmentDetector } from "../../core/topology/environment-detector.ts";
7
6
  import { SeptumDatabase } from "../../core/database/client.ts";
8
7
  import { SeptumRepository } from "../../core/database/repository.ts";
9
- import { ConfigLoader } from "../../core/config/loader.ts";
8
+ import { ConfigLoader, resolveDatabasePath } from "../../core/config/loader.ts";
10
9
  import { resolveWorkspaceRoot } from "../../core/resolver/path-resolver.ts";
11
10
 
12
11
  import { promptSelectHarnesses } from "../ui/prompts.ts";
@@ -18,23 +17,41 @@ export async function handleInitCommand(force: boolean = false): Promise<void> {
18
17
  if (!fs.existsSync(septumDir)) {
19
18
  fs.mkdirSync(septumDir, { recursive: true });
20
19
  }
21
- const dbPath = path.join(workspaceRoot, ".septum", "septum.db");
20
+ const policyFile = path.join(workspaceRoot, "septum.config.json");
21
+ const diskConfig = fs.existsSync(policyFile) ? ConfigLoader.loadFromDisk(policyFile) : undefined;
22
+ const dbPath = resolveDatabasePath(workspaceRoot, diskConfig?.settings.db_path);
22
23
 
23
24
  console.log("\n\x1b[36m◆\x1b[0m \x1b[1mSeptum Architecture Guard & SSOT Initializer\x1b[0m\n\x1b[36m│\x1b[0m");
24
25
  console.log(`\x1b[36m│\x1b[0m Workspace: ${workspaceRoot}`);
25
26
 
26
- // 1. Auto-discover project topology and persist to SQLite SSOT
27
+ // 1. Auto-discover project topology (or sync explicit septum.config.json domains) and persist to SQLite SSOT
27
28
  console.log("\x1b[36m◇\x1b[0m Analyzing codebase topology, modular boundaries, and deployment infrastructure...");
28
29
  const db = new SeptumDatabase(dbPath);
29
30
  try {
30
31
  const repo = new SeptumRepository(db.raw);
31
- const domains = TopologyDetector.discoverAndPersist(repo, workspaceRoot);
32
- EnvironmentDetector.detect(workspaceRoot, repo);
32
+ const hasExplicitDomains = Boolean(diskConfig && Object.keys(diskConfig.domains).length > 0);
33
+ let domains: Record<string, import("../../types/index.ts").DomainConfig>;
34
+ let shadowedSubdomains: Array<{ explicitDomain: string; explicitRoot: string; detectedNames: string[] }> = [];
35
+ if (hasExplicitDomains) {
36
+ const synced = TopologyDetector.syncExplicitConfigDomains(repo, workspaceRoot, diskConfig!.domains);
37
+ domains = synced.domains;
38
+ shadowedSubdomains = synced.shadowedSubdomains;
39
+ console.log("\x1b[36m│\x1b[0m \x1b[33mℹ\x1b[0m Using explicit domains from septum.config.json (skipping topology auto-discovery).");
40
+ } else {
41
+ domains = TopologyDetector.discoverAndPersist(repo, workspaceRoot, force);
42
+ }
33
43
  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:`);
44
+ console.log(`\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m ${hasExplicitDomains ? "Synchronized" : "Discovered and registered"} ${domainNames.length} domain(s) in SQLite SSOT:`);
35
45
  for (const name of domainNames) {
36
46
  console.log(`\x1b[36m│\x1b[0m - \x1b[1m${name}\x1b[0m: root -> '${domains[name].root}'`);
37
47
  }
48
+ for (const shadow of shadowedSubdomains) {
49
+ const preview = shadow.detectedNames.slice(0, 6).join(", ");
50
+ const suffix = shadow.detectedNames.length > 6 ? `, +${shadow.detectedNames.length - 6} more` : "";
51
+ console.log(
52
+ `\x1b[36m│\x1b[0m \x1b[33m⚠\x1b[0m Explicit domain '${shadow.explicitDomain}' (root: '${shadow.explicitRoot}') covers ${shadow.detectedNames.length} detected sub-domain(s) (${preview}${suffix}). Remove '${shadow.explicitDomain}' or clear 'domains' in septum.config.json to use auto-discovered layers.`
53
+ );
54
+ }
38
55
  const scanned = JSON.parse(repo.getMeta("scanned_folders") || "[]");
39
56
  const ignored = JSON.parse(repo.getMeta("ignored_folders") || "[]");
40
57
  if (scanned.length > 0) {
@@ -75,7 +92,7 @@ export async function handleInitCommand(force: boolean = false): Promise<void> {
75
92
  // 4. Run initial codebase ingestion
76
93
  console.log("\x1b[36m◇\x1b[0m Indexing codebase AST (Tree-Sitter) to build symbol table & dependency graph...");
77
94
  try {
78
- await handleSyncCommand({ workspaceRoot, dbPath });
95
+ await handleSyncCommand({ workspaceRoot, dbPath, rebuild: true });
79
96
  console.log("\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m AST indexing completed successfully.");
80
97
  console.log("\x1b[36m│\x1b[0m");
81
98
 
@@ -116,7 +133,7 @@ export async function handleInitCommand(force: boolean = false): Promise<void> {
116
133
  }
117
134
  process.exitCode = 1;
118
135
  } else {
119
- console.log("\x1b[32m└ ✓ Septum successfully initialized with complete index coverage!\x1b[0m");
136
+ console.log("\x1b[32m└ ✓ Septum initialization and configured source synchronization completed.\x1b[0m");
120
137
  }
121
138
 
122
139
  if (hasPartialCoverage && harnessErrors.length > 0) {
@@ -1,5 +1,4 @@
1
- import * as path from "node:path";
2
- import { ConfigLoader } from "../../core/config/loader.ts";
1
+ import { ConfigLoader, resolveDatabasePath } from "../../core/config/loader.ts";
3
2
  import { SeptumDatabase } from "../../core/database/client.ts";
4
3
  import { SeptumRepository } from "../../core/database/repository.ts";
5
4
  import { IngestionPipeline } from "../../core/ingestion/pipeline.ts";
@@ -9,20 +8,19 @@ export interface SyncCommandOptions {
9
8
  json?: boolean;
10
9
  workspaceRoot?: string;
11
10
  dbPath?: string;
11
+ rebuild?: boolean;
12
12
  }
13
13
 
14
14
  export async function handleSyncCommand(options: SyncCommandOptions = {}): Promise<void> {
15
15
  const root = resolveWorkspaceRoot(options.workspaceRoot || process.cwd());
16
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));
17
+ const resolvedDbPath = resolveDatabasePath(root, options.dbPath ?? config.settings.db_path);
20
18
  const db = new SeptumDatabase(resolvedDbPath);
21
19
  try {
22
20
  const repo = new SeptumRepository(db.raw);
23
21
  const pipeline = new IngestionPipeline(repo, root);
24
22
 
25
- const metrics = await pipeline.run(config);
23
+ const metrics = await pipeline.run(config, { rebuild: options.rebuild });
26
24
 
27
25
  if (options.json) {
28
26
  console.log(JSON.stringify(metrics, null, 2));
@@ -0,0 +1,43 @@
1
+ export interface HookEdit {
2
+ target: string;
3
+ content: string;
4
+ coverage: "complete_candidate" | "replacement_fragment";
5
+ }
6
+ function record(value: unknown): Record<string, unknown> {
7
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
8
+ }
9
+ function firstString(input: Record<string, unknown>, keys: string[]): string | undefined {
10
+ for (const key of keys) if (typeof input[key] === "string") return input[key] as string;
11
+ }
12
+ function replace(source: string, old: string, replacement: string, all = false): string {
13
+ if (!old || !source.includes(old)) throw new Error("Hook edit does not match current source; refresh the file before editing.");
14
+ if (!all && source.indexOf(old) !== source.lastIndexOf(old)) throw new Error("Hook edit is ambiguous; provide a unique old_string or replace_all.");
15
+ return all ? source.split(old).join(replacement) : source.replace(old, () => replacement);
16
+ }
17
+
18
+ /** Normalize supported harness payloads; reconstruct replacements before parsing imports. */
19
+ export function normalizeHookEdit(payload: unknown, readCurrent: (target: string) => string): HookEdit | undefined {
20
+ const outer = record(payload);
21
+ const input = record(outer.tool_input ?? outer.arguments ?? record(outer.toolCall).args ?? outer);
22
+ const target = firstString(input, ["TargetFile", "file_path", "filePath", "path", "Path"]) ?? firstString(outer, ["TargetFile", "file_path", "filePath", "path", "Path"]);
23
+ if (!target) return;
24
+ const full = firstString(input, ["CodeContent", "content", "Content"]) ?? firstString(outer, ["CodeContent", "content", "Content"]);
25
+ if (full !== undefined) return { target, content: full, coverage: "complete_candidate" };
26
+ const edits = Array.isArray(input.edits) ? input.edits : Array.isArray(input.ReplacementChunks) ? input.ReplacementChunks : undefined;
27
+ if (edits) {
28
+ let content = readCurrent(target);
29
+ for (const value of edits) {
30
+ const edit = record(value);
31
+ const old = firstString(edit, ["old_string", "TargetContent"]);
32
+ const next = firstString(edit, ["new_string", "ReplacementContent"]);
33
+ if (old === undefined || next === undefined) return { target, content: edits.map(value => firstString(record(value), ["new_string", "ReplacementContent"]) ?? "").join("\n"), coverage: "replacement_fragment" };
34
+ content = replace(content, old, next, edit.replace_all === true);
35
+ }
36
+ return { target, content, coverage: "complete_candidate" };
37
+ }
38
+ const replacement = firstString(input, ["ReplacementContent", "new_string", "Replacement"]) ?? firstString(outer, ["ReplacementContent", "new_string", "Replacement"]);
39
+ if (replacement === undefined) return;
40
+ const old = firstString(input, ["old_string", "TargetContent"]) ?? firstString(outer, ["old_string", "TargetContent"]);
41
+ return { target, content: old === undefined ? replacement : replace(readCurrent(target), old, replacement, input.replace_all === true),
42
+ coverage: old === undefined ? "replacement_fragment" : "complete_candidate" };
43
+ }