@dimassetoid/septum-mcp 0.2.1 → 0.5.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 (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -2,11 +2,11 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { handleSyncCommand } from "./sync.ts";
5
+ import { createSyncProgressReporter } from "./sync-progress.ts";
5
6
  import { TopologyDetector } from "../../core/discovery/topology-detector.ts";
6
- import { EnvironmentDetector } from "../../core/topology/environment-detector.ts";
7
7
  import { SeptumDatabase } from "../../core/database/client.ts";
8
8
  import { SeptumRepository } from "../../core/database/repository.ts";
9
- import { ConfigLoader } from "../../core/config/loader.ts";
9
+ import { ConfigLoader, resolveDatabasePath } from "../../core/config/loader.ts";
10
10
  import { resolveWorkspaceRoot } from "../../core/resolver/path-resolver.ts";
11
11
 
12
12
  import { promptSelectHarnesses } from "../ui/prompts.ts";
@@ -18,23 +18,41 @@ export async function handleInitCommand(force: boolean = false): Promise<void> {
18
18
  if (!fs.existsSync(septumDir)) {
19
19
  fs.mkdirSync(septumDir, { recursive: true });
20
20
  }
21
- const dbPath = path.join(workspaceRoot, ".septum", "septum.db");
21
+ const policyFile = path.join(workspaceRoot, "septum.config.json");
22
+ const diskConfig = fs.existsSync(policyFile) ? ConfigLoader.loadFromDisk(policyFile) : undefined;
23
+ const dbPath = resolveDatabasePath(workspaceRoot, diskConfig?.settings.db_path);
22
24
 
23
25
  console.log("\n\x1b[36m◆\x1b[0m \x1b[1mSeptum Architecture Guard & SSOT Initializer\x1b[0m\n\x1b[36m│\x1b[0m");
24
26
  console.log(`\x1b[36m│\x1b[0m Workspace: ${workspaceRoot}`);
25
27
 
26
- // 1. Auto-discover project topology and persist to SQLite SSOT
28
+ // 1. Auto-discover project topology (or sync explicit septum.config.json domains) and persist to SQLite SSOT
27
29
  console.log("\x1b[36m◇\x1b[0m Analyzing codebase topology, modular boundaries, and deployment infrastructure...");
28
30
  const db = new SeptumDatabase(dbPath);
29
31
  try {
30
32
  const repo = new SeptumRepository(db.raw);
31
- const domains = TopologyDetector.discoverAndPersist(repo, workspaceRoot);
32
- EnvironmentDetector.detect(workspaceRoot, repo);
33
+ const hasExplicitDomains = Boolean(diskConfig && Object.keys(diskConfig.domains).length > 0);
34
+ let domains: Record<string, import("../../types/index.ts").DomainConfig>;
35
+ let shadowedSubdomains: Array<{ explicitDomain: string; explicitRoot: string; detectedNames: string[] }> = [];
36
+ if (hasExplicitDomains) {
37
+ const synced = TopologyDetector.syncExplicitConfigDomains(repo, workspaceRoot, diskConfig!.domains);
38
+ domains = synced.domains;
39
+ shadowedSubdomains = synced.shadowedSubdomains;
40
+ console.log("\x1b[36m│\x1b[0m \x1b[33mℹ\x1b[0m Using explicit domains from septum.config.json (skipping topology auto-discovery).");
41
+ } else {
42
+ domains = TopologyDetector.discoverAndPersist(repo, workspaceRoot, force);
43
+ }
33
44
  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:`);
45
+ console.log(`\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m ${hasExplicitDomains ? "Synchronized" : "Discovered and registered"} ${domainNames.length} domain(s) in SQLite SSOT:`);
35
46
  for (const name of domainNames) {
36
47
  console.log(`\x1b[36m│\x1b[0m - \x1b[1m${name}\x1b[0m: root -> '${domains[name].root}'`);
37
48
  }
49
+ for (const shadow of shadowedSubdomains) {
50
+ const preview = shadow.detectedNames.slice(0, 6).join(", ");
51
+ const suffix = shadow.detectedNames.length > 6 ? `, +${shadow.detectedNames.length - 6} more` : "";
52
+ console.log(
53
+ `\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.`
54
+ );
55
+ }
38
56
  const scanned = JSON.parse(repo.getMeta("scanned_folders") || "[]");
39
57
  const ignored = JSON.parse(repo.getMeta("ignored_folders") || "[]");
40
58
  if (scanned.length > 0) {
@@ -74,8 +92,16 @@ export async function handleInitCommand(force: boolean = false): Promise<void> {
74
92
 
75
93
  // 4. Run initial codebase ingestion
76
94
  console.log("\x1b[36m◇\x1b[0m Indexing codebase AST (Tree-Sitter) to build symbol table & dependency graph...");
95
+ const progressReporter = createSyncProgressReporter({ prefix: "\x1b[36m│\x1b[0m " });
77
96
  try {
78
- await handleSyncCommand({ workspaceRoot, dbPath });
97
+ await handleSyncCommand({
98
+ workspaceRoot,
99
+ dbPath,
100
+ rebuild: true,
101
+ quiet: true,
102
+ onProgress: progressReporter.onProgress,
103
+ });
104
+ progressReporter.cleanup();
79
105
  console.log("\x1b[36m│\x1b[0m \x1b[32m✓\x1b[0m AST indexing completed successfully.");
80
106
  console.log("\x1b[36m│\x1b[0m");
81
107
 
@@ -116,7 +142,7 @@ export async function handleInitCommand(force: boolean = false): Promise<void> {
116
142
  }
117
143
  process.exitCode = 1;
118
144
  } else {
119
- console.log("\x1b[32m└ ✓ Septum successfully initialized with complete index coverage!\x1b[0m");
145
+ console.log("\x1b[32m└ ✓ Septum initialization and configured source synchronization completed.\x1b[0m");
120
146
  }
121
147
 
122
148
  if (hasPartialCoverage && harnessErrors.length > 0) {
@@ -0,0 +1,33 @@
1
+ import { realpathSync, statSync } from "node:fs";
2
+ import { summarizeToolCalls } from "../../core/telemetry/summary.ts";
3
+
4
+ export function handleStatsCommand(workspace: string, json: boolean): void {
5
+ const root = realpathSync(workspace);
6
+ if (!statSync(root).isDirectory()) throw new Error("Stats requires a workspace directory.");
7
+ const summary = summarizeToolCalls(root);
8
+ if (json) {
9
+ console.log(JSON.stringify(summary, null, 2));
10
+ return;
11
+ }
12
+
13
+ console.log(`Septum tool calls in ${root}`);
14
+ console.log(`${summary.calls} calls, ${summary.errors} errors (latest ${summary.sample_limit} tool events from septum.log and septum.log.1)`);
15
+ if (!summary.calls) return;
16
+ console.log(`Range: ${summary.first_timestamp ?? "unknown"} to ${summary.last_timestamp ?? "unknown"}`);
17
+ console.log(`Duration p50/p95: ${summary.duration_ms.p50}/${summary.duration_ms.p95} ms`);
18
+ if (summary.response_bytes.samples) {
19
+ console.log(`Response size p50/p95: ${summary.response_bytes.p50}/${summary.response_bytes.p95} bytes (${summary.response_bytes.samples} samples)`);
20
+ }
21
+ for (const [name, tool] of Object.entries(summary.tools)) {
22
+ console.log(` ${name}: ${tool.calls} calls, ${tool.errors} errors`);
23
+ for (const [action, counts] of Object.entries(tool.actions)) {
24
+ console.log(` ${action}: ${counts.calls} calls, ${counts.errors} errors`);
25
+ }
26
+ }
27
+ if (summary.recent_errors.length) {
28
+ console.log("Recent errors:");
29
+ for (const error of summary.recent_errors) {
30
+ console.log(` ${error.timestamp ?? "unknown"} ${error.tool} ${error.stage ?? "-"} ${error.code ?? "-"} ${error.trace_id ?? "-"}`);
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,71 @@
1
+ import type { IngestionProgressEvent } from "../../core/ingestion/pipeline.ts";
2
+
3
+ export interface SyncProgressReporterOptions {
4
+ /** Optional line prefix (e.g. `init` tree rail). */
5
+ prefix?: string;
6
+ /** Override TTY detection (useful in unit tests). */
7
+ isTty?: boolean;
8
+ /** Override stdout.write for inline TTY updates. */
9
+ write?: (chunk: string) => void;
10
+ /** Override console.log for completed phase lines. */
11
+ log?: (line: string) => void;
12
+ }
13
+
14
+ export interface SyncProgressReporter {
15
+ onProgress: (event: IngestionProgressEvent) => void;
16
+ cleanup: () => void;
17
+ }
18
+
19
+ /**
20
+ * Creates a shared CLI progress reporter for ingestion phases (`scanning`,
21
+ * `parsing`, `resolving`, `linking`) used by both `septum init` and `septum sync`.
22
+ */
23
+ export function createSyncProgressReporter(options: SyncProgressReporterOptions = {}): SyncProgressReporter {
24
+ const prefix = options.prefix ?? "";
25
+ const isTty = options.isTty ?? Boolean(process.stdout.isTTY);
26
+ const write = options.write ?? ((chunk: string) => process.stdout.write(chunk));
27
+ const log = options.log ?? ((line: string) => console.log(line));
28
+ let activeProgressLine = false;
29
+
30
+ const cleanup = () => {
31
+ if (activeProgressLine) {
32
+ write("\r\x1b[K");
33
+ activeProgressLine = false;
34
+ }
35
+ };
36
+
37
+ const onProgress = (event: IngestionProgressEvent) => {
38
+ if (event.phase === "scanning") {
39
+ if (event.status === "start" && isTty) {
40
+ write(`\r${prefix}\x1b[36m◆\x1b[0m Scanning files...\x1b[K`);
41
+ activeProgressLine = true;
42
+ } else if (event.status === "done") {
43
+ cleanup();
44
+ log(`${prefix}\x1b[36m◆\x1b[0m Scanning files — ${event.total.toLocaleString()} found`);
45
+ }
46
+ } else if (event.phase === "parsing") {
47
+ if (event.status === "progress" && isTty) {
48
+ write(
49
+ `\r${prefix}\x1b[36m◆\x1b[0m Parsing code — ${event.processed.toLocaleString()}/${event.total.toLocaleString()}\x1b[K`
50
+ );
51
+ activeProgressLine = true;
52
+ } else if (event.status === "done") {
53
+ cleanup();
54
+ log(`${prefix}\x1b[36m◆\x1b[0m Parsing code — done`);
55
+ }
56
+ } else if (event.phase === "resolving" && event.status === "done") {
57
+ cleanup();
58
+ log(`${prefix}\x1b[36m◆\x1b[0m Resolving refs & domains — done`);
59
+ } else if (event.phase === "linking") {
60
+ if (event.status === "start" && isTty) {
61
+ write(`\r${prefix}\x1b[36m◆\x1b[0m Linking entrypoints & slices...\x1b[K`);
62
+ activeProgressLine = true;
63
+ } else if (event.status === "done") {
64
+ cleanup();
65
+ log(`${prefix}\x1b[36m◆\x1b[0m Linking entrypoints & slices — done (${event.slices.toLocaleString()} slices)`);
66
+ }
67
+ }
68
+ };
69
+
70
+ return { onProgress, cleanup };
71
+ }
@@ -1,39 +1,65 @@
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
- import { IngestionPipeline } from "../../core/ingestion/pipeline.ts";
4
+ import { IngestionPipeline, type IngestionProgressEvent } from "../../core/ingestion/pipeline.ts";
6
5
  import { resolveWorkspaceRoot } from "../../core/resolver/path-resolver.ts";
6
+ import { createSyncProgressReporter } from "./sync-progress.ts";
7
7
 
8
8
  export interface SyncCommandOptions {
9
9
  json?: boolean;
10
+ quiet?: boolean;
10
11
  workspaceRoot?: string;
11
12
  dbPath?: string;
13
+ rebuild?: boolean;
14
+ onProgress?: (info: IngestionProgressEvent) => void;
12
15
  }
13
16
 
14
17
  export async function handleSyncCommand(options: SyncCommandOptions = {}): Promise<void> {
15
18
  const root = resolveWorkspaceRoot(options.workspaceRoot || process.cwd());
16
19
  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 resolvedDbPath = resolveDatabasePath(root, options.dbPath ?? config.settings.db_path);
20
21
  const db = new SeptumDatabase(resolvedDbPath);
21
22
  try {
22
23
  const repo = new SeptumRepository(db.raw);
23
24
  const pipeline = new IngestionPipeline(repo, root);
24
25
 
25
- const metrics = await pipeline.run(config);
26
+ const reporter =
27
+ !options.json && !options.quiet && !options.onProgress
28
+ ? createSyncProgressReporter()
29
+ : undefined;
30
+
31
+ let metrics;
32
+ try {
33
+ metrics = await pipeline.run(config, {
34
+ rebuild: options.rebuild,
35
+ onProgress: options.onProgress ?? reporter?.onProgress,
36
+ });
37
+ } finally {
38
+ reporter?.cleanup();
39
+ }
26
40
 
27
41
  if (options.json) {
28
42
  console.log(JSON.stringify(metrics, null, 2));
29
- } else {
43
+ } else if (!options.quiet) {
44
+ const sliceCount = repo.countVerticalSlices();
30
45
  console.log(
31
46
  `[Septum Sync] Ingested in ${metrics.duration_ms.toFixed(0)}ms: ` +
32
47
  `${metrics.files_updated} updated/added, ` +
33
48
  `${metrics.files_skipped} unchanged, ` +
34
49
  `${metrics.symbols_indexed} symbols, ` +
35
- `${metrics.dependencies_indexed} deps.`
50
+ `${metrics.dependencies_indexed} deps, ` +
51
+ `${sliceCount} slices.`
36
52
  );
53
+ const unsupportedFiles = JSON.parse(repo.getMeta("unsupported_files") || "[]") as unknown[];
54
+ const skippedFiles = JSON.parse(repo.getMeta("skipped_files") || "[]") as unknown[];
55
+ const uncoveredFiles = JSON.parse(repo.getMeta("uncovered_files") || "[]") as unknown[];
56
+ if (unsupportedFiles.length > 0 || skippedFiles.length > 0 || uncoveredFiles.length > 0) {
57
+ const parts: string[] = [];
58
+ if (uncoveredFiles.length > 0) parts.push(`${uncoveredFiles.length} uncovered`);
59
+ if (skippedFiles.length > 0) parts.push(`${skippedFiles.length} skipped`);
60
+ if (unsupportedFiles.length > 0) parts.push(`${unsupportedFiles.length} unsupported`);
61
+ console.log(`[Septum Sync] Coverage: partial (${parts.join(", ")}).`);
62
+ }
37
63
  }
38
64
  } finally {
39
65
  db.close();
@@ -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
+ }
package/src/cli/index.ts CHANGED
@@ -1,12 +1,5 @@
1
1
  import { parseArgs } from "node:util";
2
- import { SessionManager } from "../core/session/session-manager.ts";
3
2
  import { SEPTUM_VERSION, checkRuntimeVersion, formatUpdateNotice, type RuntimeVersionMeta } from "../utils/version-check.ts";
4
- import { handleCheckCommand } from "./commands/check.ts";
5
- import { handleHookCommand } from "./commands/hook.ts";
6
- import { handleInitCommand } from "./commands/init.ts";
7
- import { handleTopologyCommand } from "./commands/topology.ts";
8
- import { handleServeCommand } from "./commands/serve.ts";
9
- import { handleSyncCommand } from "./commands/sync.ts";
10
3
 
11
4
  export async function runCLI(argv: string[]): Promise<void> {
12
5
  let parsed;
@@ -20,7 +13,6 @@ export async function runCLI(argv: string[]): Promise<void> {
20
13
  json: { type: "boolean" },
21
14
  strict: { type: "boolean" },
22
15
  staged: { type: "boolean" },
23
- feature: { type: "string" },
24
16
  },
25
17
  allowPositionals: true,
26
18
  strict: false,
@@ -53,65 +45,42 @@ export async function runCLI(argv: string[]): Promise<void> {
53
45
  try {
54
46
  switch (command) {
55
47
  case "init": {
48
+ const { handleInitCommand } = await import("./commands/init.ts");
56
49
  const force = Boolean(flags.force);
57
50
  await handleInitCommand(force);
58
51
  break;
59
52
  }
60
53
 
61
54
  case "sync": {
55
+ const { handleSyncCommand } = await import("./commands/sync.ts");
62
56
  const json = Boolean(flags.json);
63
57
  await handleSyncCommand({ json });
64
58
  break;
65
59
  }
66
60
 
67
61
  case "check": {
62
+ const { handleCheckCommand } = await import("./commands/check.ts");
68
63
  const strict = Boolean(flags.strict);
69
64
  const staged = Boolean(flags.staged);
70
- const feature = typeof flags.feature === "string" ? flags.feature : undefined;
71
65
  const json = Boolean(flags.json);
72
- await handleCheckCommand({ strict, staged, feature, json });
66
+ await handleCheckCommand({ strict, staged, json });
73
67
  break;
74
68
  }
75
69
 
76
- case "serve": {
77
- await handleServeCommand();
78
- break;
79
- }
80
-
81
- case "topology":
82
- case "env": {
83
- await handleTopologyCommand(positionals[1], positionals[2], positionals[3], positionals[4], positionals[5]);
70
+ case "stats": {
71
+ const { handleStatsCommand } = await import("./commands/stats.ts");
72
+ handleStatsCommand(positionals[1] ?? process.cwd(), Boolean(flags.json));
84
73
  break;
85
74
  }
86
75
 
87
- case "feature": {
88
- const sub = positionals[1];
89
- if (sub === "clear") {
90
- const cleared = SessionManager.clearActiveSession(process.cwd(), undefined, Boolean(flags.force));
91
- if (cleared) {
92
- console.log("✓ Active feature session successfully cleared.");
93
- } else {
94
- console.log("ℹ No active feature session found.");
95
- }
96
- } else if (sub === "status" || !sub) {
97
- const current = SessionManager.getActiveSession(process.cwd());
98
- if (current) {
99
- console.log(`\nActive Feature Session:`);
100
- console.log(`▶ Feature Key : ${current.feature_key}`);
101
- console.log(`▶ Domain : ${current.domain}`);
102
- console.log(`▶ Locked At : ${current.locked_at}`);
103
- console.log(`▶ Touchpoints : ${current.touchpoints.join(", ")}\n`);
104
- } else {
105
- console.log("ℹ No active feature session. All domain files accessible according to boundary rules.");
106
- }
107
- } else {
108
- console.error(`Unknown feature subcommand: '${sub}'. Use 'status' or 'clear'.`);
109
- process.exit(1);
110
- }
76
+ case "serve": {
77
+ const { handleServeCommand } = await import("./commands/serve.ts");
78
+ await handleServeCommand();
111
79
  break;
112
80
  }
113
81
 
114
82
  case "hook": {
83
+ const { handleHookCommand } = await import("./commands/hook.ts");
115
84
  await handleHookCommand(argv.slice(2));
116
85
  break;
117
86
  }
@@ -132,7 +101,7 @@ export async function runCLI(argv: string[]): Promise<void> {
132
101
  function printHelp(versionMeta?: RuntimeVersionMeta): void {
133
102
  const notice = versionMeta ? formatUpdateNotice(versionMeta) : null;
134
103
  console.log(`
135
- Septum — Deterministic Bounded-Context & Structural File Catalog
104
+ Septum — Deterministic Bounded-Context & Architecture Guard
136
105
  Version: v${SEPTUM_VERSION}${notice ? `\n\n${notice}` : ""}
137
106
 
138
107
  USAGE:
@@ -142,23 +111,18 @@ USAGE:
142
111
  COMMANDS:
143
112
  Core Lifecycle & Indexing:
144
113
  init Initialize configuration, gitignore, pre-commit hook, and catalog
145
- Flags: -f, --force (regenerate Septum-owned hooks & harness artifacts; preserves DB, domain policies, and user hooks)
114
+ Flags: -f, --force (regenerate Septum-owned hooks & harness artifacts)
146
115
  sync Codebase AST synchronization and catalog update (full or incremental)
147
116
  Flags: --json
148
117
 
149
118
  Boundary & Enforcement:
150
119
  check Audit codebase for cross-domain boundary violations
151
- Flags: --strict, --staged, --feature <name>, --json
152
- feature [status|clear] View or release active feature context session lock
153
- Flags: --force (explicit recovery of another owner's session)
120
+ Flags: --strict, --staged, --json
154
121
  hook [subhook] Internal pre-tool guardrail hook (e.g. pre-write)
155
122
 
156
- Environment & Topology:
157
- topology, env [action] Inspect 6-layer environment topology & distributed nodes
158
- Subcommands: resolve <layer> <platform>, add-node, remove-node, clear
159
-
160
123
  Daemon & Protocol:
161
124
  serve Start Model Context Protocol (MCP) server over stdio
125
+ stats [workspace] Summarize recent MCP tool logs (supports --json)
162
126
 
163
127
  GLOBAL FLAGS:
164
128
  -h, --help Show this help message
@@ -250,9 +250,36 @@ export function configureHarness(
250
250
  if (outErrors) outErrors.push(`Malformed JSON in '.codex/hooks.json': ${hooksResult.error}`);
251
251
  } else {
252
252
  const codexHooksConfig = hooksResult.status === "valid" ? hooksResult.data : { hooks: {} };
253
+ const originalHooks = JSON.stringify(codexHooksConfig);
253
254
  codexHooksConfig.hooks = (typeof codexHooksConfig.hooks === "object" && codexHooksConfig.hooks !== null && !Array.isArray(codexHooksConfig.hooks))
254
255
  ? codexHooksConfig.hooks
255
256
  : {};
257
+ const legacy = codexHooksConfig["septum-boundary-guard"];
258
+ if (legacy && typeof legacy === "object" && !Array.isArray(legacy)) {
259
+ const unknownKeys = Object.keys(legacy).filter(key => !["PreToolUse", "PostToolUse"].includes(key));
260
+ if (unknownKeys.length) {
261
+ const message = `Cannot migrate unknown legacy Codex hook fields: ${unknownKeys.join(", ")}. Preserving hooks.json.`;
262
+ console.error(` ✕ ${message}`);
263
+ outErrors?.push(message);
264
+ return configured.join(" & ");
265
+ }
266
+ for (const event of ["PreToolUse", "PostToolUse"]) {
267
+ if (Array.isArray(legacy[event])) {
268
+ codexHooksConfig.hooks[event] = [...(codexHooksConfig.hooks[event] ?? []), ...legacy[event]];
269
+ }
270
+ }
271
+ delete codexHooksConfig["septum-boundary-guard"];
272
+ }
273
+ for (const entries of Object.values(codexHooksConfig.hooks) as any[]) {
274
+ if (!Array.isArray(entries)) continue;
275
+ for (let i = 0; i < entries.length; i++) {
276
+ const entry = entries[i];
277
+ if (entry?.type === "command" && typeof entry.command === "string" && !entry.hooks) {
278
+ const { matcher, ...handler } = entry;
279
+ entries[i] = { ...(matcher !== undefined ? { matcher } : {}), hooks: [handler] };
280
+ }
281
+ }
282
+ }
256
283
  const preToolUse = Array.isArray(codexHooksConfig.hooks.PreToolUse) ? codexHooksConfig.hooks.PreToolUse : [];
257
284
 
258
285
  const hasSeptumHook = preToolUse.some((h: any) => {
@@ -276,7 +303,7 @@ export function configureHarness(
276
303
  codexHooksConfig.hooks.PreToolUse = preToolUse;
277
304
  writeJsonFile(codexHooksPath, codexHooksConfig);
278
305
  console.log(" ✓ Configured Codex CLI lifecycle boundary guard: '.codex/hooks.json'.");
279
- } else if (force) {
306
+ } else if (force || legacy) {
280
307
  const cleanedHooks: any[] = [];
281
308
  for (const h of preToolUse) {
282
309
  if (Array.isArray(h?.hooks)) {
@@ -293,8 +320,9 @@ export function configureHarness(
293
320
  cleanedHooks.push(canonicalHook);
294
321
  codexHooksConfig.hooks.PreToolUse = cleanedHooks;
295
322
  writeJsonFile(codexHooksPath, codexHooksConfig);
296
- console.log(" ✓ Force-regenerated Codex CLI lifecycle boundary guard: '.codex/hooks.json' (--force).");
323
+ console.log(" ✓ Regenerated Codex CLI lifecycle boundary guard: '.codex/hooks.json'.");
297
324
  }
325
+ if (JSON.stringify(codexHooksConfig) !== originalHooks) writeJsonFile(codexHooksPath, codexHooksConfig);
298
326
  configured.push(".codex/hooks.json");
299
327
  }
300
328
 
@@ -385,24 +413,34 @@ export function scaffoldHarnessCustomizations(
385
413
  fs.mkdirSync(targetDir, { recursive: true });
386
414
  }
387
415
 
388
- // 1. Skill: <harnessDir>/skills/septum-map/SKILL.md
389
- const skillDir = path.join(targetDir, "skills", "septum-map");
416
+ // 1. Skill: <harnessDir>/skills/use-septum/SKILL.md
417
+ // Clean up legacy skill folder if present
418
+ const legacySkillDir = path.join(targetDir, "skills", "septum-map");
419
+ if (fs.existsSync(legacySkillDir)) {
420
+ try {
421
+ fs.rmSync(legacySkillDir, { recursive: true, force: true });
422
+ } catch {
423
+ // Best-effort cleanup
424
+ }
425
+ }
426
+
427
+ const skillDir = path.join(targetDir, "skills", "use-septum");
390
428
  if (!fs.existsSync(skillDir)) {
391
429
  fs.mkdirSync(skillDir, { recursive: true });
392
430
  }
393
431
  const skillPath = path.join(skillDir, "SKILL.md");
394
432
  if (!fs.existsSync(skillPath)) {
395
433
  fs.writeFileSync(skillPath, SEPTUM_MAP_SKILL_TEMPLATE, "utf-8");
396
- console.log(` ✓ Deployed AI Agent skill: '${harnessDirName}/skills/septum-map/SKILL.md'.`);
434
+ console.log(` ✓ Deployed AI Agent skill: '${harnessDirName}/skills/use-septum/SKILL.md'.`);
397
435
  } else {
398
436
  const existing = fs.readFileSync(skillPath, "utf-8");
399
437
  if (existing === SEPTUM_MAP_SKILL_TEMPLATE) {
400
438
  // Unchanged
401
439
  } else if (force) {
402
440
  fs.writeFileSync(skillPath, SEPTUM_MAP_SKILL_TEMPLATE, "utf-8");
403
- console.log(` ✓ Updated AI Agent skill: '${harnessDirName}/skills/septum-map/SKILL.md' (--force).`);
441
+ console.log(` ✓ Updated AI Agent skill: '${harnessDirName}/skills/use-septum/SKILL.md' (--force).`);
404
442
  } else {
405
- console.log(` ✓ Preserved existing customized AI Agent skill: '${harnessDirName}/skills/septum-map/SKILL.md'.`);
443
+ console.log(` ✓ Preserved existing customized AI Agent skill: '${harnessDirName}/skills/use-septum/SKILL.md'.`);
406
444
  }
407
445
  }
408
446
 
@@ -437,7 +475,7 @@ export function scaffoldHarnessCustomizations(
437
475
  console.log(` ✓ Created onboarding instructions: '${options.rootDoc}'.`);
438
476
  } else if (force) {
439
477
  const existing = fs.readFileSync(rootDocPath, "utf-8");
440
- if (!existing.includes("septum_domain")) {
478
+ if (!existing.includes("septum_map")) {
441
479
  fs.writeFileSync(rootDocPath, existing.trimEnd() + "\n\n" + SEPTUM_RULES_TEMPLATE + "\n", "utf-8");
442
480
  console.log(` ✓ Appended Septum boundary rules to '${options.rootDoc}' (--force).`);
443
481
  }
@@ -458,6 +496,8 @@ export function deployHarnessHooksJson(
458
496
  force: boolean = false,
459
497
  outErrors?: string[]
460
498
  ): void {
499
+ // Codex uses the strict event schema installed by configureHarness, without a namespace wrapper.
500
+ if (harnessDirName === ".codex") return;
461
501
  const targetDir = path.join(cwd, harnessDirName);
462
502
  const hooksJsonPath = path.join(targetDir, "hooks.json");
463
503
  const hooksResult = readJsonConfigFile(hooksJsonPath);