@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/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,36 @@ 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
70
  case "serve": {
71
+ const { handleServeCommand } = await import("./commands/serve.ts");
77
72
  await handleServeCommand();
78
73
  break;
79
74
  }
80
75
 
81
- case "topology":
82
- case "env": {
83
- await handleTopologyCommand(positionals[1], positionals[2], positionals[3], positionals[4], positionals[5]);
84
- break;
85
- }
86
-
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
- }
111
- break;
112
- }
113
-
114
76
  case "hook": {
77
+ const { handleHookCommand } = await import("./commands/hook.ts");
115
78
  await handleHookCommand(argv.slice(2));
116
79
  break;
117
80
  }
@@ -132,7 +95,7 @@ export async function runCLI(argv: string[]): Promise<void> {
132
95
  function printHelp(versionMeta?: RuntimeVersionMeta): void {
133
96
  const notice = versionMeta ? formatUpdateNotice(versionMeta) : null;
134
97
  console.log(`
135
- Septum — Deterministic Bounded-Context & Structural File Catalog
98
+ Septum — Deterministic Bounded-Context & Architecture Guard
136
99
  Version: v${SEPTUM_VERSION}${notice ? `\n\n${notice}` : ""}
137
100
 
138
101
  USAGE:
@@ -142,21 +105,15 @@ USAGE:
142
105
  COMMANDS:
143
106
  Core Lifecycle & Indexing:
144
107
  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)
108
+ Flags: -f, --force (regenerate Septum-owned hooks & harness artifacts)
146
109
  sync Codebase AST synchronization and catalog update (full or incremental)
147
110
  Flags: --json
148
111
 
149
112
  Boundary & Enforcement:
150
113
  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)
114
+ Flags: --strict, --staged, --json
154
115
  hook [subhook] Internal pre-tool guardrail hook (e.g. pre-write)
155
116
 
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
117
  Daemon & Protocol:
161
118
  serve Start Model Context Protocol (MCP) server over stdio
162
119
 
@@ -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);
@@ -2,7 +2,7 @@ export const SEPTUM_HOOKS_CONFIG = {
2
2
  "septum-boundary-guard": {
3
3
  "PreToolUse": [
4
4
  {
5
- "matcher": "write_to_file|replace_file_content|multi_replace_file_content|Write|Edit|MultiEdit",
5
+ "matcher": "write_file|edit_file|write_to_file|replace_file_content|multi_replace_file_content|Write|Edit|MultiEdit|NotebookEdit",
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",
@@ -14,7 +14,7 @@ export const SEPTUM_HOOKS_CONFIG = {
14
14
  ],
15
15
  "PostToolUse": [
16
16
  {
17
- "matcher": "write_to_file|replace_file_content|multi_replace_file_content|Write|Edit|MultiEdit",
17
+ "matcher": "write_file|edit_file|write_to_file|replace_file_content|multi_replace_file_content|Write|Edit|MultiEdit|NotebookEdit",
18
18
  "hooks": [
19
19
  {
20
20
  "type": "command",
@@ -28,15 +28,17 @@ export const SEPTUM_HOOKS_CONFIG = {
28
28
  };
29
29
 
30
30
  export const SEPTUM_PRE_WRITE_SCRIPT = `#!/usr/bin/env sh
31
- # Septum 3-Gate Boundary Guard Pre-Write Hook
32
- # Intercepts write_to_file and replace_file_content before disk mutation
31
+ # Septum candidate import policy hook
32
+ # Passes supported edit payloads to the CLI before the client writes them
33
33
 
34
34
  ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd -P)"
35
35
  if [ ! -f "$ROOT_DIR/.septum/septum.db" ]; then
36
36
  exit 0
37
37
  fi
38
38
 
39
- # Delegate directly to Septum's active 3-gate hook engine
39
+ export SEPTUM_HOOK_ROOT="$ROOT_DIR"
40
+
41
+ # Invoke the available Septum CLI hook command
40
42
  if command -v bun >/dev/null 2>&1 && [ -f "$ROOT_DIR/bin/septum.ts" ]; then
41
43
  exec bun run "$ROOT_DIR/bin/septum.ts" hook pre-write "$@"
42
44
  elif command -v septum >/dev/null 2>&1; then
@@ -59,17 +61,50 @@ if [ ! -f "$ROOT_DIR/.septum/septum.db" ]; then
59
61
  exit 0
60
62
  fi
61
63
 
62
- # Trigger background incremental sync
63
- if command -v bun >/dev/null 2>&1 && [ -f "$ROOT_DIR/bin/septum.ts" ]; then
64
- bun run "$ROOT_DIR/bin/septum.ts" sync >/dev/null 2>&1 &
65
- elif command -v septum >/dev/null 2>&1; then
66
- septum sync >/dev/null 2>&1 &
67
- elif [ -f "$ROOT_DIR/node_modules/.bin/septum" ]; then
68
- "$ROOT_DIR/node_modules/.bin/septum" sync >/dev/null 2>&1 &
69
- elif command -v bunx >/dev/null 2>&1; then
70
- bunx septum sync >/dev/null 2>&1 &
64
+ # Sync always belongs to the workspace containing this generated wrapper.
65
+ cd "$ROOT_DIR" || exit 1
66
+
67
+ LOCK_DIR="$ROOT_DIR/.septum/sync.lock"
68
+ PENDING_FILE="$ROOT_DIR/.septum/sync.pending"
69
+
70
+ # Mark workspace as needing sync so an active lock holder coalesces burst edits
71
+ : > "$PENDING_FILE" 2>/dev/null || true
72
+
73
+ # Recover stale lock if holder PID is no longer alive
74
+ if [ -d "$LOCK_DIR" ] && [ -f "$LOCK_DIR/pid" ]; then
75
+ LOCK_PID="$(cat "$LOCK_DIR/pid" 2>/dev/null)"
76
+ if [ -n "$LOCK_PID" ] && ! kill -0 "$LOCK_PID" 2>/dev/null; then
77
+ rm -rf "$LOCK_DIR" 2>/dev/null || true
78
+ fi
79
+ fi
80
+
81
+ # Non-blocking lock acquisition: if another background sync is active, exit 0
82
+ if ! mkdir "$LOCK_DIR" 2>/dev/null; then
83
+ exit 0
71
84
  fi
72
85
 
86
+ run_septum_sync() {
87
+ if command -v bun >/dev/null 2>&1 && [ -f "$ROOT_DIR/bin/septum.ts" ]; then
88
+ bun run "$ROOT_DIR/bin/septum.ts" sync >/dev/null 2>&1
89
+ elif command -v septum >/dev/null 2>&1; then
90
+ septum sync >/dev/null 2>&1
91
+ elif [ -f "$ROOT_DIR/node_modules/.bin/septum" ]; then
92
+ "$ROOT_DIR/node_modules/.bin/septum" sync >/dev/null 2>&1
93
+ elif command -v bunx >/dev/null 2>&1; then
94
+ bunx septum sync >/dev/null 2>&1
95
+ fi
96
+ }
97
+
98
+ # Trigger coalesced background incremental sync
99
+ (
100
+ trap 'rm -rf "$LOCK_DIR" 2>/dev/null || true' EXIT INT TERM
101
+ while [ -f "$PENDING_FILE" ]; do
102
+ rm -f "$PENDING_FILE" 2>/dev/null || true
103
+ run_septum_sync
104
+ done
105
+ ) >/dev/null 2>&1 &
106
+ echo "$!" > "$LOCK_DIR/pid" 2>/dev/null || true
107
+
73
108
  exit 0
74
109
  `;
75
110
 
@@ -1,50 +1,35 @@
1
- export const SEPTUM_RULES_TEMPLATE = `# Software Architecture, Modular Boundaries & Symbol Reuse Guidelines
2
-
3
- > **Core Principle:** This codebase enforces modular architecture and the DRY (Don't Repeat Yourself) principle. An embedded database (\`.septum/septum.db\`) maintains the Single Source of Truth (SSOT) for the project symbol table, call graph, and dependency graph. Code modifications must respect module boundaries and reuse existing abstractions.
4
-
5
- ---
6
-
7
- ## 1. Symbol Reuse & Module Discovery (Before Writing New Code)
8
-
9
- Before declaring a new class, interface, function, method, or shared type:
10
- 1. **Inspect Module Catalog & File Dependencies:**
11
- Call \`septum_domain({ action: "catalog", domain: "<domain_name>", detail_level: "compact" })\` (or omit \`domain\` for the top-level architecture overview).
12
- * Review existing declarations (\`class\`, \`interface\`, \`struct\`, \`function\`, \`type\`, \`constant\`, \`variable\`) and their line span.
13
- * Review imported modules (\`connections.imports_from\`) and consumer count (\`connections.imported_by_count\`).
14
- * For complete method signatures of a specific component, call \`septum_symbol({ action: "inspect", query: "<SymbolName>" })\`.
15
- 2. **Search for Existing Utilities and Abstractions:**
16
- Call \`septum_symbol({ action: "locate", query: "<keyword>" })\` to verify whether a utility, service, or helper already exists before implementing duplicate logic.
17
- 3. **Scope Constraints for Features:**
18
- When working within an assigned feature branch or task, call \`septum_feature({ action: "get", feature_key: "<feature_name>" })\`:
19
- * **Respect \`allowed_touchpoints\`:** Restrict modifications strictly to files within the designated module scope.
20
- * **Reuse \`reuse_symbols\`:** Import and extend registered components from \`reuse_symbols\` instead of re-implementing them.
21
-
22
- ---
23
-
24
- ## 2. Impact Analysis & Breaking Change Prevention (Before Refactoring)
25
-
26
- 1. **Analyze Call Graph Dependencies (\`inbound_callers\`):**
27
- Before altering method signatures, changing parameter contracts, or deprecating public symbols, check all dependents:
28
- \`\`\`json
29
- septum_symbol({ "action": "impact", "query": "ClassNameOrFunction" })
30
- \`\`\`
31
- Review all \`inbound_callers\` (direct callers and cross-module named imports) to prevent breaking upstream consumers.
32
- 2. **Trace End-to-End Execution Flow (Vertical Slices):**
33
- Call \`septum_slice({ query: "<route|command|handler>", max_depth: 5 })\` (scale up to \`max_depth: 8\` for asynchronous events, message queues, or layered middleware) to trace call chains from API ingress down to data persistence.
34
-
35
- ---
36
-
37
- ## 3. Dependency Validation & Static Boundary Checks
38
-
39
- 1. **Pre-Validate Proposed Module Imports:**
40
- Before adding new cross-module dependencies, validate whether the dependency direction conforms to the architecture:
41
- \`\`\`json
42
- septum_boundary({
43
- "file_path": "src/modules/order/service.ts",
44
- "proposed_imports": ["../billing/service"],
45
- "feature_key": "optional_feature_key"
46
- })
47
- \`\`\`
48
- 2. **Verify Against Circular Dependencies and Boundary Leaks:**
49
- Run \`septum_boundary({ scope: "staged" })\` or \`septum_boundary({ scope: "all" })\` prior to committing changes. If the check returns \`rejected\` (due to \`forbidden_dependency\`, \`disallowed_dependency\`, \`touchpoint_violation\`, or \`circular_dependency\`), refactor the import hierarchy to preserve clean dependency inversion.
1
+ export const SEPTUM_RULES_TEMPLATE = `# Septum: static code navigation and boundary checks
2
+
3
+ Use Septum to inspect indexed declarations, imports, domains and supported entrypoints. Its SQLite database stores extracted static evidence. Read freshness, coverage, diagnostics and omissions before relying on a result.
4
+
5
+ ## Tool routing
6
+
7
+ | Task | Tool | Result |
8
+ | --- | --- | --- |
9
+ | Find domains and files | \`septum_map({action: "catalog", detail_level: "compact"})\` | Domain/file navigation, directed import relationships, static entrypoints and index health |
10
+ | Inspect a declaration | \`septum_symbol({action: "locate", query: "<name>"})\` | Indexed coordinates, declaration reference, candidates or suggestions |
11
+ | Read implementation and supporting declarations | \`septum_symbol({action: "context", query: "<name>", file_path: "<path>"})\` | Deep TypeScript context or bounded source inspection, according to the selected mode |
12
+ | Inspect potential consumers | \`septum_symbol({action: "impact", query: "<name>"})\` | Import dependents, supported static call sites and inferred caller hints |
13
+ | Inspect an entrypoint | \`septum_slice({query: "<route or handler>", max_depth: 5})\` | Static catalog match and related nodes with relationship evidence |
14
+ | Check proposed imports | \`septum_boundary({scope: "file", file_path: "<path>", proposed_imports: [...]})\` | Proposal decision and diagnostics under configured domain rules |
15
+ | Check the Git index | \`septum_boundary({scope: "staged"})\` | Boundary analysis using frozen staged source and interpretation files |
16
+
17
+ ## Reading and acting on results
18
+
19
+ - Start with map when the relevant domain/file is unknown. Follow \`dependencies\`, \`entrypoints\`, \`health\` and \`next\`. Full detail expands navigation selection; use symbol for declaration bodies.
20
+ - Narrow ambiguous declarations with \`file_path\` or a returned \`symbol_ref\`. A found indexed declaration can still have stale or unavailable source.
21
+ - Choose \`context_mode: "deep"\` for supported TypeScript reference context. Choose \`context_mode: "source"\` for bounded source inspection. On the source path, \`include_source: false\` requests signature/dependency details.
22
+ - Deep-context \`budget_bytes\` controls response serialization. Source-mode line limits are a different contract. A setting is not a guarantee of task completeness.
23
+ - Continue deep context with the returned \`continuation\` and unchanged selection/options. Inspect omission accounting and diagnostics.
24
+ - Before changing a public contract, inspect impact and the relevant consumers. Read \`inbound_callers_complete\` and the limits of \`inbound_callers\`; static caller evidence requires application checks.
25
+ - Proposal approval does not audit existing imports. Use all/domain/staged scopes for their corresponding audits.
26
+ - \`unknown\` is not approval. \`rejected\` reports detected violations such as \`forbidden_dependency\`, \`disallowed_dependency\` or \`circular_dependency\`. \`approved\` concerns only the evaluated static scope.
27
+ - Slice confidence describes query-to-catalog matching. Imports do not prove calls; related nodes do not establish execution order or runtime dispatch.
28
+ - If tools are unavailable or evidence is incomplete, inspect relevant source directly and verify the behavior with appropriate project checks.
29
+
30
+ ## Language and workspace scope
31
+
32
+ Declaration extraction and import resolution have separate language-specific limits. Python, Go, Rust, Ruby, Java and C# resolve supported local/manifest patterns; dynamic configuration, conditional builds, binary classpaths and runtime loading can remain unresolved or unsupported. Set \`workspace_path\` explicitly when selecting among repositories.
33
+
34
+ Generated client hooks need client enablement and a matching tool payload. Their presence does not prove that an edit was intercepted.
50
35
  `;
@@ -1,51 +1,55 @@
1
- export const SEPTUM_MAP_SKILL_TEMPLATE = `---
2
- name: septum-map
3
- description: Framework-agnostic codebase architecture and dependency graph analysis. Use when initializing project boundaries, inspecting the symbol table, validating cross-module imports, or reviewing static analysis check results.
1
+ export const USE_SEPTUM_SKILL_TEMPLATE = `---
2
+ name: use-septum
3
+ description: >-
4
+ Inspect backend declarations, imports, domain boundaries and supported static entrypoints with Septum MCP. Use for code navigation, consumer inspection and proposed/staged import checks; inspect coverage and freshness before using results to plan edits.
4
5
  ---
5
6
 
6
- # \`septum-map\` — Codebase Architecture & Static Analysis
7
+ # use-septum
7
8
 
8
- > **Core Principle:** Static analysis indexes AST declarations and dependency graphs to provide deterministic structural evidence. Treat index data as static structural facts, not full runtime trace validation.
9
+ Septum indexes selected source declarations, imports, domain ownership and static entrypoints. It returns static evidence and diagnostics. It does not run the analyzed application or provide a complete runtime caller graph.
9
10
 
10
- ## Scope
11
+ ## Select the tool
11
12
 
12
- Use this skill to navigate the project architecture, verify module boundaries, locate reusable symbols, trace execution flows, and validate dependency rules. This skill guides architectural compliance; domain business decisions remain governed by project specifications.
13
+ | Need | Request | Read from the result |
14
+ | --- | --- | --- |
15
+ | Workspace/domain/file navigation | \`septum_map\`, \`action: "catalog"\`, \`detail_level: "compact"\`, optional \`domain\`/\`file_filter\` | \`navigation/v1\` files/anchors, directed \`dependencies\`, static \`entrypoints\`, \`health\`, \`accounting\`, \`next\` |
16
+ | Domain policy registration | \`septum_map\`, \`action: "register"\`, \`name\`, \`root\`, dependency lists | Recorded policy, \`policy_owner\` and any ingestion result |
17
+ | Declaration lookup | \`septum_symbol\`, \`action: "locate"\`, \`query\` | Indexed coordinates, \`symbol_ref\`, candidates/suggestions and retrieval freshness |
18
+ | TypeScript reference context | \`septum_symbol\`, \`action: "context"\`, \`context_mode: "deep"\` | Source/contracts, relationships, diagnostics, accounting and continuation |
19
+ | Source/signature inspection | \`septum_symbol\`, \`action: "context"\`, \`context_mode: "source"\` | Source slice or signature/dependency details and source status |
20
+ | Potential consumers | \`septum_symbol\`, \`action: "impact"\` | Import dependents, supported static call sites, legacy caller hints and uncertainty |
21
+ | Supported route/handler/job/CLI/event | \`septum_slice\`, \`query\`, optional \`controller_file\` and \`max_depth\` | Catalog target, related nodes, relationship evidence and diagnostics |
22
+ | Proposed imports | \`septum_boundary\`, \`scope: "file"\`, \`file_path\`, \`proposed_imports\` | Proposal decision and evaluated scope |
23
+ | Existing indexed or staged imports | \`septum_boundary\`, \`scope: "all" / "domain" / "staged"\` | Scoped violations, incomplete resolution and recovery hints |
13
24
 
14
- ## Tool & Command Reference
25
+ ## Context selection
15
26
 
16
- The active MCP schema and \`septum --help\` represent the authoritative interface contracts:
27
+ Deep context supports indexed \`.ts\`, \`.mts\` and \`.cts\` declarations. It follows bounded supported references and can project public type contracts. It does not establish a complete business dependency closure.
17
28
 
18
- | Tool | Capability | Considerations |
19
- |---|---|---|
20
- | \`septum_domain\` | \`catalog\` inspects module architecture (supports \`detail_level: "compact"\`); \`register\` defines domain roots; \`topology\` logs infrastructure layers. | Domain registration mutates database state. Directory structures serve as modular hints. |
21
- | \`septum_symbol\` | \`locate\`, \`inspect\`, \`impact\`, or \`hotspots\` across the project symbol table. | Backed by Tree-Sitter AST parsers. Impact analysis reports static inbound callers across the dependency graph. |
22
- | \`septum_slice\` | Traces end-to-end execution paths from ingress handlers down through services and repositories; \`max_depth\` bounds call graph traversal. | Returns matched call graph chains; confidence metrics reflect static AST resolution depth. |
23
- | \`septum_boundary\` | Validates proposed imports and detects \`circular_dependency\` cycles across scopes (\`file\`, \`staged\`, \`domain\`, \`all\`). | Evaluates allowed/forbidden dependency rules. Status \`approved\` confirms zero policy violations in the checked scope. |
24
- | \`septum_feature\` | \`get\` retrieves active task context; \`lock\` registers task touchpoints; \`release\` clears locks. | Restricts edits to authorized module touchpoints during concurrent development sessions. |
29
+ Use \`budget_bytes\` only for deep context. Do not combine it with \`include_source\`, \`source_start_line\` or \`source_line_limit\`. Those options select bounded source inspection when no explicit mode is supplied. \`inspect\` is an alias for \`context\`.
25
30
 
26
- Common CLI commands: \`septum init\` initializes project configuration and agent hooks; \`septum sync\` updates the AST index; \`septum check\` runs static boundary checks on staged or workspace files.
31
+ Source mode includes target source by default. Use \`include_source: false\` for signature/dependency details. When a source slice is truncated, follow \`next_start_line\`. One-hop delegation expansion is heuristic; inspect the selected dependency before treating it as a callee.
27
32
 
28
- ## Architectural Review Workflow
33
+ For deep-context pages, pass the returned \`continuation\` with unchanged target, workspace, configuration and budget. Restart retrieval on invalid/stale continuation. Capacity omissions are distinct from pagination.
29
34
 
30
- 1. **Verify Project Context:** Ensure working directory is aligned. Check that \`.septum/septum.db\` is present. Pass \`workspace_path\` when operating in multi-root workspaces.
31
- 2. **Inspect Module Inventory:** Query the domain catalog to determine registered modules, AST index status, and file coverage metrics. If files are marked unsupported or skipped, note partial coverage.
32
- 3. **Differentiate Evidence from Assumptions:** Use concrete AST symbols, public exports, and declared configuration as evidence. Never guess interfaces or assume unverified dependencies.
33
- 4. **Identify Reusable Components:** Search existing services, models, and utility classes before introducing new declarations to adhere to the DRY principle.
34
- 5. **Analyze Refactoring Blast Radius:** Check inbound callers (\`septum_symbol impact\`) before modifying public method signatures or removing exported declarations.
35
- 6. **Validate Dependency Boundaries:** Run pre-commit checks (\`septum_boundary\`) to ensure proposed imports avoid circular dependencies and respect architectural layering.
35
+ ## Workflow and evidence limits
36
36
 
37
- ## Interpreting Analysis Results
37
+ 1. Use map when the target domain or file is unknown. Full map detail expands navigation selection, not declaration detail.
38
+ 2. Locate a declaration and resolve ambiguity through \`file_path\` or \`symbol_ref\`. Read freshness before using indexed coordinates.
39
+ 3. Retrieve the relevant source/contracts. Inspect diagnostics and omissions, and read further source when needed.
40
+ 4. Before a public-contract change, inspect impact and relevant consumers. \`inbound_callers_complete: false\` means the caller list is incomplete; risk is advisory.
41
+ 5. Evaluate proposed imports against policy. Proposal approval does not certify existing imports or all possible cycles.
42
+ 6. Check the relevant workspace/domain/staged scope and run application checks for behavior affected by the edit.
38
43
 
39
- - \`approved\`: No architectural violations or circular dependencies detected within the evaluated scope.
40
- - \`rejected\`: A boundary violation (\`forbidden_dependency\`, \`disallowed_dependency\`, or \`circular_dependency\`) occurred. The import hierarchy must be refactored.
41
- - \`unknown\` or partial index status: Indexing is incomplete; review unsupported files before concluding compliance.
42
- - Absence of a symbol: Indicates no match in the current AST index, signaling an opportunity to implement or check naming spelling.
44
+ A slice's exact match applies to its catalog target. Imports do not prove calls; static relationships do not prove execution order or runtime dispatch. Validation/schema/entity nodes are context, not a required executed sequence.
43
45
 
44
- ## Standardized Reporting Format
46
+ Boundary \`approved\` describes the evaluated static scope. \`rejected\` reports known violations, including \`circular_dependency\`. \`unknown\` requires inspecting or recovering missing evidence. Resolve ambiguity by narrowing the request.
45
47
 
46
- When summarizing architectural checks:
47
- - **Scope & Action:** Audited file path or module, tool invoked, and whether database state was modified.
48
- - **Structural Evidence:** Exact symbol declarations, caller counts, or dependency paths identified.
49
- - **Status & Violations:** Clear pass/fail outcome with specific rule violations or circular dependency paths if detected.
50
- - **Recommended Action:** Remediation steps (e.g. dependency inversion, extracting shared interfaces, or reusing existing utilities).
48
+ Language declaration support does not imply equivalent module resolution. Rust/Cargo, Ruby requires, Java source projects and C# namespaces have bounded resolver support; dynamic loaders, macros, conditional builds and missing binary metadata remain limited.
49
+
50
+ Set \`workspace_path\` when selecting among repositories. If the MCP tools are unavailable or insufficient, use direct source inspection and appropriate project verification.
51
+
52
+ Describe the operation and observed result. Do not promise token savings, response speed, memory savings, complete caller discovery or universal language/framework coverage.
51
53
  `;
54
+
55
+ export const SEPTUM_MAP_SKILL_TEMPLATE = USE_SEPTUM_SKILL_TEMPLATE;