@dimassetoid/septum-mcp 0.0.0-stage → 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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +133 -0
  7. package/src/cli/commands/hook.ts +205 -0
  8. package/src/cli/commands/init.ts +570 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +39 -0
  11. package/src/cli/hook-payload.ts +43 -0
  12. package/src/cli/index.ts +124 -0
  13. package/src/cli/scaffold/harness-config.ts +661 -0
  14. package/src/cli/templates/hooks.ts +110 -0
  15. package/src/cli/templates/rules.ts +35 -0
  16. package/src/cli/templates/skill.ts +55 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +426 -0
  19. package/src/core/boundary/staged-auditor.ts +120 -0
  20. package/src/core/config/domain-ownership.ts +45 -0
  21. package/src/core/config/loader.ts +174 -0
  22. package/src/core/config/schema.ts +59 -0
  23. package/src/core/database/client.ts +60 -0
  24. package/src/core/database/repositories/dependency.repository.ts +733 -0
  25. package/src/core/database/repositories/domain.repository.ts +373 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +647 -0
  29. package/src/core/database/repository.ts +358 -0
  30. package/src/core/database/schema.ts +123 -0
  31. package/src/core/discovery/navigation.ts +105 -0
  32. package/src/core/discovery/topology-detector.ts +863 -0
  33. package/src/core/ingestion/hasher.ts +5 -0
  34. package/src/core/ingestion/pipeline.ts +590 -0
  35. package/src/core/parser/behavioral-analyzer.ts +123 -0
  36. package/src/core/parser/boundary-tracker.ts +458 -0
  37. package/src/core/parser/extractors/base.ts +71 -0
  38. package/src/core/parser/extractors/blade.ts +159 -0
  39. package/src/core/parser/extractors/csharp.ts +248 -0
  40. package/src/core/parser/extractors/django-semantic.ts +655 -0
  41. package/src/core/parser/extractors/elysia-semantic.ts +517 -0
  42. package/src/core/parser/extractors/express-semantic.ts +429 -0
  43. package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
  44. package/src/core/parser/extractors/fastify-semantic.ts +759 -0
  45. package/src/core/parser/extractors/flask-semantic.ts +482 -0
  46. package/src/core/parser/extractors/frontend.ts +149 -0
  47. package/src/core/parser/extractors/go-semantic.ts +670 -0
  48. package/src/core/parser/extractors/go.ts +491 -0
  49. package/src/core/parser/extractors/hono-semantic.ts +546 -0
  50. package/src/core/parser/extractors/java.ts +227 -0
  51. package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
  52. package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
  53. package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
  54. package/src/core/parser/extractors/php.ts +585 -0
  55. package/src/core/parser/extractors/python.ts +503 -0
  56. package/src/core/parser/extractors/registry.ts +99 -0
  57. package/src/core/parser/extractors/ruby.ts +237 -0
  58. package/src/core/parser/extractors/rust.ts +304 -0
  59. package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
  60. package/src/core/parser/extractors/symfony-semantic.ts +321 -0
  61. package/src/core/parser/extractors/typescript.ts +839 -0
  62. package/src/core/parser/implementation-fingerprint.ts +97 -0
  63. package/src/core/parser/language-capabilities.ts +87 -0
  64. package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
  65. package/src/core/parser/schema/schema-provider-registry.ts +41 -0
  66. package/src/core/parser/schema/schema-provider.interface.ts +34 -0
  67. package/src/core/parser/semantic-revision.ts +3 -0
  68. package/src/core/parser/static-string.ts +51 -0
  69. package/src/core/parser/tree-sitter.ts +63 -0
  70. package/src/core/parser/wasm-assets.ts +25 -0
  71. package/src/core/parser/wasm-loader.ts +274 -0
  72. package/src/core/resolver/call-graph-tracer.ts +1033 -0
  73. package/src/core/resolver/import-resolver.ts +365 -0
  74. package/src/core/resolver/interpretation-inputs.ts +7 -0
  75. package/src/core/resolver/languages/go.ts +103 -0
  76. package/src/core/resolver/languages/managed.ts +200 -0
  77. package/src/core/resolver/languages/python.ts +115 -0
  78. package/src/core/resolver/languages/ruby.ts +40 -0
  79. package/src/core/resolver/languages/rust.ts +127 -0
  80. package/src/core/resolver/languages/shared.ts +71 -0
  81. package/src/core/resolver/module-resolver.ts +486 -0
  82. package/src/core/resolver/path-resolver.ts +200 -0
  83. package/src/core/resolver/slice-catalog.ts +79 -0
  84. package/src/core/resolver/slice-format.ts +9 -0
  85. package/src/core/resolver/symbol-impact.ts +381 -0
  86. package/src/core/resolver/symbol-locator.ts +276 -0
  87. package/src/core/resolver/symbol-reference.ts +53 -0
  88. package/src/core/resolver/vertical-slice-tracer.ts +344 -0
  89. package/src/core/resources/ignore.ts +144 -0
  90. package/src/core/resources/limits.ts +14 -0
  91. package/src/core/resources/source-files.ts +185 -0
  92. package/src/core/resources/source-inventory.ts +55 -0
  93. package/src/core/resources/work-queue.ts +74 -0
  94. package/src/core/retrieval/context-page.ts +109 -0
  95. package/src/core/retrieval/context.ts +320 -0
  96. package/src/core/retrieval/resolution-warnings.ts +21 -0
  97. package/src/core/retrieval/symbol-evidence.ts +97 -0
  98. package/src/core/retrieval/typescript-references.ts +262 -0
  99. package/src/core/telemetry/telemetry.ts +142 -0
  100. package/src/index.ts +18 -0
  101. package/src/mcp/schemas.ts +746 -0
  102. package/src/mcp/server.ts +600 -0
  103. package/src/mcp/tools/boundary.ts +17 -0
  104. package/src/mcp/tools/check-boundary.ts +382 -0
  105. package/src/mcp/tools/get-domain-catalog.ts +39 -0
  106. package/src/mcp/tools/get-symbol-impact.ts +104 -0
  107. package/src/mcp/tools/get-symbol.ts +399 -0
  108. package/src/mcp/tools/locate-symbol.ts +236 -0
  109. package/src/mcp/tools/map.ts +26 -0
  110. package/src/mcp/tools/register-domain.ts +113 -0
  111. package/src/mcp/tools/slice.ts +16 -0
  112. package/src/mcp/tools/symbol.ts +95 -0
  113. package/src/mcp/tools/trace-vertical-slice.ts +106 -0
  114. package/src/mcp/workspace-manager.ts +170 -0
  115. package/src/mcp/workspace-watcher.ts +202 -0
  116. package/src/types/index.ts +438 -0
  117. package/src/types/wasm.d.ts +4 -0
  118. package/src/utils/version-check.ts +209 -0
  119. package/src/version.ts +1 -0
@@ -0,0 +1,661 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import {
4
+ SEPTUM_HOOKS_CONFIG,
5
+ SEPTUM_POST_WRITE_SCRIPT,
6
+ SEPTUM_PRE_WRITE_SCRIPT,
7
+ } from "../templates/hooks.ts";
8
+ import { SEPTUM_RULES_TEMPLATE } from "../templates/rules.ts";
9
+ import { SEPTUM_MAP_SKILL_TEMPLATE } from "../templates/skill.ts";
10
+
11
+ export interface HarnessOption {
12
+ id: string;
13
+ name: string;
14
+ targetFile: string;
15
+ description: string;
16
+ selectedByDefault?: boolean;
17
+ }
18
+
19
+ export const SUPPORTED_HARNESSES: HarnessOption[] = [
20
+ {
21
+ id: "antigravity",
22
+ name: "Antigravity",
23
+ targetFile: ".gemini/ (skills, rules, hooks, mcp_config.json)",
24
+ description: "Skills, rules, hooks, and MCP config for Antigravity AI agents",
25
+ selectedByDefault: true,
26
+ },
27
+ {
28
+ id: "claude",
29
+ name: "Claude Code",
30
+ targetFile: ".claude/ (skills, hooks, mcp.json, settings.json) & .mcp.json & CLAUDE.md",
31
+ description: "Skills, hooks, and MCP config for Claude Code",
32
+ selectedByDefault: true,
33
+ },
34
+ {
35
+ id: "codex",
36
+ name: "Codex",
37
+ targetFile: ".codex/ (skills, hooks.json, config.toml)",
38
+ description: "Skills, hooks, and MCP config for OpenAI Codex CLI",
39
+ selectedByDefault: false,
40
+ },
41
+ {
42
+ id: "opencode",
43
+ name: "Opencode",
44
+ targetFile: "opencode/ (skills, hooks) & opencode.json",
45
+ description: "Skills, hooks, and MCP config for Opencode AI harness",
46
+ selectedByDefault: false,
47
+ },
48
+ {
49
+ id: "agents",
50
+ name: ".agents",
51
+ targetFile: ".agents/ (skills, hooks, mcp.json) & AGENTS.md",
52
+ description: "Cross-agent skills, hooks, and MCP config following the .agents standard",
53
+ selectedByDefault: false,
54
+ },
55
+ ];
56
+
57
+ export type ConfigReadResult<T = Record<string, any>> =
58
+ | { status: "missing" }
59
+ | { status: "valid"; data: T }
60
+ | { status: "malformed"; error: string; raw: string };
61
+
62
+ export function readJsonConfigFile<T = Record<string, any>>(filePath: string): ConfigReadResult<T> {
63
+ if (!fs.existsSync(filePath)) return { status: "missing" };
64
+ const raw = fs.readFileSync(filePath, "utf-8");
65
+ try {
66
+ const parsed = JSON.parse(raw);
67
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
68
+ return {
69
+ status: "malformed",
70
+ error: `Expected JSON object root, found ${parsed === null ? "null" : Array.isArray(parsed) ? "array" : typeof parsed}`,
71
+ raw,
72
+ };
73
+ }
74
+ return { status: "valid", data: parsed as T };
75
+ } catch (err: unknown) {
76
+ const message = err instanceof Error ? err.message : String(err);
77
+ return {
78
+ status: "malformed",
79
+ error: `Malformed JSON syntax: ${message}`,
80
+ raw,
81
+ };
82
+ }
83
+ }
84
+
85
+ function writeJsonFile(filePath: string, data: unknown): void {
86
+ const dir = path.dirname(filePath);
87
+ if (!fs.existsSync(dir)) {
88
+ fs.mkdirSync(dir, { recursive: true });
89
+ }
90
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n", "utf-8");
91
+ }
92
+
93
+ export function configureHarness(
94
+ harnessId: string,
95
+ cwd: string = process.cwd(),
96
+ force: boolean = false,
97
+ outErrors?: string[]
98
+ ): string | null {
99
+ switch (harnessId) {
100
+ case "antigravity": {
101
+ // 1. Skill, Rules, and Hook scripts in .gemini/
102
+ scaffoldHarnessCustomizations(".gemini", cwd, force, outErrors, { includeRules: true });
103
+
104
+ // 2. MCP config in .gemini/mcp_config.json
105
+ const geminiDir = path.join(cwd, ".gemini");
106
+ const mcpConfigPath = path.join(geminiDir, "mcp_config.json");
107
+ const result = readJsonConfigFile(mcpConfigPath);
108
+ if (result.status === "malformed") {
109
+ console.error(` ✕ Error: Malformed JSON in '.gemini/mcp_config.json': ${result.error}. Preserving existing file without modification.`);
110
+ if (outErrors) outErrors.push(`Malformed JSON in '.gemini/mcp_config.json': ${result.error}`);
111
+ } else {
112
+ const existing = result.status === "valid" ? result.data : {};
113
+ const servers = (typeof existing.mcpServers === "object" && existing.mcpServers !== null && !Array.isArray(existing.mcpServers))
114
+ ? existing.mcpServers
115
+ : {};
116
+ if (!servers.septum || force) {
117
+ servers.septum = {
118
+ command: "septum",
119
+ args: ["serve"],
120
+ };
121
+ existing.mcpServers = servers;
122
+ writeJsonFile(mcpConfigPath, existing);
123
+ }
124
+ }
125
+ return ".gemini/ (skills, rules, hooks, mcp_config.json)";
126
+ }
127
+
128
+ case "claude": {
129
+ const configured: string[] = [];
130
+
131
+ // 1. Skills and Hook scripts in .claude/ + CLAUDE.md root guidance (rules omitted as Claude Code does not support rules/)
132
+ scaffoldHarnessCustomizations(".claude", cwd, force, outErrors, { rootDoc: "CLAUDE.md", includeRules: false });
133
+
134
+ // 2. MCP config in .claude/mcp.json and .mcp.json (project root)
135
+ const claudeDir = path.join(cwd, ".claude");
136
+ if (!fs.existsSync(claudeDir)) {
137
+ fs.mkdirSync(claudeDir, { recursive: true });
138
+ }
139
+ const claudeMcpPath = path.join(claudeDir, "mcp.json");
140
+ const rootMcpPath = path.join(cwd, ".mcp.json");
141
+
142
+ for (const configPath of [claudeMcpPath, rootMcpPath]) {
143
+ const mcpResult = readJsonConfigFile(configPath);
144
+ if (mcpResult.status === "malformed") {
145
+ const relPath = path.relative(cwd, configPath);
146
+ console.error(` ✕ Error: Malformed JSON in '${relPath}': ${mcpResult.error}. Preserving existing file without modification.`);
147
+ if (outErrors) outErrors.push(`Malformed JSON in '${relPath}': ${mcpResult.error}`);
148
+ } else {
149
+ const existing = mcpResult.status === "valid" ? mcpResult.data : {};
150
+ const servers = (typeof existing.mcpServers === "object" && existing.mcpServers !== null && !Array.isArray(existing.mcpServers))
151
+ ? existing.mcpServers
152
+ : {};
153
+ if (!servers.septum || force) {
154
+ servers.septum = {
155
+ command: "septum",
156
+ args: ["serve"],
157
+ };
158
+ existing.mcpServers = servers;
159
+ writeJsonFile(configPath, existing);
160
+ }
161
+ const relPath = path.relative(cwd, configPath);
162
+ configured.push(relPath);
163
+ }
164
+ }
165
+ console.log(" ✓ Configured Claude Code MCP server in '.claude/mcp.json' & '.mcp.json'.");
166
+
167
+ // 3. Lifecycle hooks in .claude/settings.json
168
+ const claudeSettingsPath = path.join(cwd, ".claude", "settings.json");
169
+ const claudeResult = readJsonConfigFile(claudeSettingsPath);
170
+ if (claudeResult.status === "malformed") {
171
+ console.error(` ✕ Error: Malformed JSON in '.claude/settings.json': ${claudeResult.error}. Preserving existing file without modification.`);
172
+ if (outErrors) outErrors.push(`Malformed JSON in '.claude/settings.json': ${claudeResult.error}`);
173
+ } else {
174
+ const claudeSettings = claudeResult.status === "valid" ? claudeResult.data : {};
175
+ const claudeHooks = (typeof claudeSettings.hooks === "object" && claudeSettings.hooks !== null && !Array.isArray(claudeSettings.hooks))
176
+ ? claudeSettings.hooks
177
+ : {};
178
+ const preToolHooks = Array.isArray(claudeHooks.PreToolUse) ? claudeHooks.PreToolUse : [];
179
+
180
+ const hasSeptumHook = preToolHooks.some((h: any) => {
181
+ if (Array.isArray(h?.hooks)) {
182
+ return h.hooks.some((hk: any) => typeof hk?.command === "string" && hk.command.includes("septum-pre-write"));
183
+ }
184
+ return typeof h?.command === "string" && h.command.includes("septum-pre-write");
185
+ });
186
+ const canonicalHook = {
187
+ matcher: "Write|Edit|NotebookEdit",
188
+ hooks: [
189
+ {
190
+ type: "command",
191
+ command:
192
+ "sh -c 'ROOT=\"$(pwd -P)\"; for d in .claude .gemini .codex opencode .agents; do if [ -f \"$ROOT/$d/hooks/septum-pre-write.sh\" ]; then exec \"$ROOT/$d/hooks/septum-pre-write.sh\" --exit-code-2 \"$@\"; fi; done; exit 0'",
193
+ },
194
+ ],
195
+ };
196
+ if (!hasSeptumHook) {
197
+ preToolHooks.push(canonicalHook);
198
+ claudeHooks.PreToolUse = preToolHooks;
199
+ claudeSettings.hooks = claudeHooks;
200
+ writeJsonFile(claudeSettingsPath, claudeSettings);
201
+ console.log(" ✓ Configured Claude Code lifecycle boundary guard: '.claude/settings.json'.");
202
+ } else if (force) {
203
+ const cleanedHooks: any[] = [];
204
+ for (const h of preToolHooks) {
205
+ if (Array.isArray(h?.hooks)) {
206
+ const userHooks = h.hooks.filter((hk: any) =>
207
+ !(typeof hk?.command === "string" && hk.command.includes("septum-pre-write"))
208
+ );
209
+ if (userHooks.length > 0) {
210
+ cleanedHooks.push({ ...h, hooks: userHooks });
211
+ }
212
+ } else if (typeof h?.command === "string" && h.command.includes("septum-pre-write")) {
213
+ // Dedicated single command hook, omit
214
+ } else if (!JSON.stringify(h).includes("septum-pre-write")) {
215
+ cleanedHooks.push(h);
216
+ }
217
+ }
218
+ cleanedHooks.push(canonicalHook);
219
+ claudeHooks.PreToolUse = cleanedHooks;
220
+ claudeSettings.hooks = claudeHooks;
221
+ writeJsonFile(claudeSettingsPath, claudeSettings);
222
+ console.log(" ✓ Force-regenerated Claude Code lifecycle boundary guard: '.claude/settings.json' (--force).");
223
+ }
224
+ configured.push(".claude/settings.json");
225
+ }
226
+
227
+ return configured.length > 0 ? configured.join(" & ") : null;
228
+ }
229
+
230
+ case "codex": {
231
+ const configured: string[] = [];
232
+
233
+ // 1. Skills and Hook scripts in .codex/ (rules omitted as Codex CLI does not support rules/)
234
+ scaffoldHarnessCustomizations(".codex", cwd, force, outErrors, { includeRules: false });
235
+
236
+ // 2. MCP config in .codex/config.toml
237
+ const codexDir = path.join(cwd, ".codex");
238
+ if (!fs.existsSync(codexDir)) {
239
+ fs.mkdirSync(codexDir, { recursive: true });
240
+ }
241
+ const configTomlPath = path.join(codexDir, "config.toml");
242
+ appendTomlMcpServer(configTomlPath, "septum", "septum", ["serve"], force);
243
+ configured.push(".codex/config.toml");
244
+
245
+ // 3. Lifecycle hooks in .codex/hooks.json
246
+ const codexHooksPath = path.join(codexDir, "hooks.json");
247
+ const hooksResult = readJsonConfigFile(codexHooksPath);
248
+ if (hooksResult.status === "malformed") {
249
+ console.error(` ✕ Error: Malformed JSON in '.codex/hooks.json': ${hooksResult.error}. Preserving existing file without modification.`);
250
+ if (outErrors) outErrors.push(`Malformed JSON in '.codex/hooks.json': ${hooksResult.error}`);
251
+ } else {
252
+ const codexHooksConfig = hooksResult.status === "valid" ? hooksResult.data : { hooks: {} };
253
+ const originalHooks = JSON.stringify(codexHooksConfig);
254
+ codexHooksConfig.hooks = (typeof codexHooksConfig.hooks === "object" && codexHooksConfig.hooks !== null && !Array.isArray(codexHooksConfig.hooks))
255
+ ? codexHooksConfig.hooks
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
+ }
283
+ const preToolUse = Array.isArray(codexHooksConfig.hooks.PreToolUse) ? codexHooksConfig.hooks.PreToolUse : [];
284
+
285
+ const hasSeptumHook = preToolUse.some((h: any) => {
286
+ if (Array.isArray(h?.hooks)) {
287
+ return h.hooks.some((hk: any) => typeof hk?.command === "string" && hk.command.includes("septum-pre-write"));
288
+ }
289
+ return typeof h?.command === "string" && h.command.includes("septum-pre-write");
290
+ });
291
+ const canonicalHook = {
292
+ matcher: "Write|Edit|Bash",
293
+ hooks: [
294
+ {
295
+ type: "command",
296
+ command:
297
+ "sh -c 'ROOT=\"$(pwd -P)\"; for d in .codex .gemini .claude opencode .agents; do if [ -f \"$ROOT/$d/hooks/septum-pre-write.sh\" ]; then exec \"$ROOT/$d/hooks/septum-pre-write.sh\" --exit-code-2 \"$@\"; fi; done; exit 0'",
298
+ },
299
+ ],
300
+ };
301
+ if (!hasSeptumHook) {
302
+ preToolUse.push(canonicalHook);
303
+ codexHooksConfig.hooks.PreToolUse = preToolUse;
304
+ writeJsonFile(codexHooksPath, codexHooksConfig);
305
+ console.log(" ✓ Configured Codex CLI lifecycle boundary guard: '.codex/hooks.json'.");
306
+ } else if (force || legacy) {
307
+ const cleanedHooks: any[] = [];
308
+ for (const h of preToolUse) {
309
+ if (Array.isArray(h?.hooks)) {
310
+ const remaining = h.hooks.filter((hk: any) =>
311
+ !(typeof hk?.command === "string" && hk.command.includes("septum-pre-write"))
312
+ );
313
+ if (remaining.length > 0) cleanedHooks.push({ ...h, hooks: remaining });
314
+ } else if (typeof h?.command === "string" && h.command.includes("septum-pre-write")) {
315
+ // Dedicated single command hook, omit
316
+ } else if (!JSON.stringify(h).includes("septum-pre-write")) {
317
+ cleanedHooks.push(h);
318
+ }
319
+ }
320
+ cleanedHooks.push(canonicalHook);
321
+ codexHooksConfig.hooks.PreToolUse = cleanedHooks;
322
+ writeJsonFile(codexHooksPath, codexHooksConfig);
323
+ console.log(" ✓ Regenerated Codex CLI lifecycle boundary guard: '.codex/hooks.json'.");
324
+ }
325
+ if (JSON.stringify(codexHooksConfig) !== originalHooks) writeJsonFile(codexHooksPath, codexHooksConfig);
326
+ configured.push(".codex/hooks.json");
327
+ }
328
+
329
+ return configured.length > 0 ? configured.join(" & ") : null;
330
+ }
331
+
332
+ case "opencode": {
333
+ const configured: string[] = [];
334
+
335
+ // 1. Skills and Hook scripts in opencode/ (rules omitted as Opencode does not support rules/)
336
+ scaffoldHarnessCustomizations("opencode", cwd, force, outErrors, { includeRules: false });
337
+ configured.push("opencode/ (skills, hooks)");
338
+
339
+ // 2. MCP config in opencode.json (project root)
340
+ const configPath = path.join(cwd, "opencode.json");
341
+ const result = readJsonConfigFile(configPath);
342
+ if (result.status === "malformed") {
343
+ console.error(` ✕ Error: Malformed JSON in 'opencode.json': ${result.error}. Preserving existing file without modification.`);
344
+ if (outErrors) outErrors.push(`Malformed JSON in 'opencode.json': ${result.error}`);
345
+ } else {
346
+ const existing = result.status === "valid" ? result.data : {};
347
+ const mcp = (typeof existing.mcp === "object" && existing.mcp !== null && !Array.isArray(existing.mcp))
348
+ ? existing.mcp
349
+ : {};
350
+ if (!mcp.septum || force) {
351
+ mcp.septum = {
352
+ type: "local",
353
+ command: ["septum", "serve"],
354
+ };
355
+ existing.mcp = mcp;
356
+ writeJsonFile(configPath, existing);
357
+ console.log(" ✓ Configured Opencode MCP server in 'opencode.json'.");
358
+ }
359
+ configured.push("opencode.json");
360
+ }
361
+
362
+ return configured.join(" & ");
363
+ }
364
+
365
+ case "agents": {
366
+ const configured: string[] = [];
367
+
368
+ // 1. Skills and Hook scripts in .agents/ + AGENTS.md root guidance (rules omitted as standard uses AGENTS.md)
369
+ scaffoldHarnessCustomizations(".agents", cwd, force, outErrors, { rootDoc: "AGENTS.md", includeRules: false });
370
+ configured.push(".agents/ (skills, hooks)");
371
+
372
+ // 2. MCP config in .agents/mcp.json
373
+ const agentsDir = path.join(cwd, ".agents");
374
+ const mcpPath = path.join(agentsDir, "mcp.json");
375
+ const mcpResult = readJsonConfigFile(mcpPath);
376
+ if (mcpResult.status === "malformed") {
377
+ console.error(` ✕ Error: Malformed JSON in '.agents/mcp.json': ${mcpResult.error}. Preserving existing file without modification.`);
378
+ if (outErrors) outErrors.push(`Malformed JSON in '.agents/mcp.json': ${mcpResult.error}`);
379
+ } else {
380
+ const existing = mcpResult.status === "valid" ? mcpResult.data : {};
381
+ const servers = (typeof existing.mcpServers === "object" && existing.mcpServers !== null && !Array.isArray(existing.mcpServers))
382
+ ? existing.mcpServers
383
+ : {};
384
+ if (!servers.septum || force) {
385
+ servers.septum = {
386
+ command: "septum",
387
+ args: ["serve"],
388
+ };
389
+ existing.mcpServers = servers;
390
+ writeJsonFile(mcpPath, existing);
391
+ console.log(" ✓ Configured .agents MCP server in '.agents/mcp.json'.");
392
+ }
393
+ configured.push(".agents/mcp.json");
394
+ }
395
+
396
+ return configured.join(" & ");
397
+ }
398
+
399
+ default:
400
+ return null;
401
+ }
402
+ }
403
+
404
+ export function scaffoldHarnessCustomizations(
405
+ harnessDirName: string,
406
+ cwd: string = process.cwd(),
407
+ force: boolean = false,
408
+ outErrors?: string[],
409
+ options?: { rootDoc?: string; includeRules?: boolean }
410
+ ): void {
411
+ const targetDir = path.join(cwd, harnessDirName);
412
+ if (!fs.existsSync(targetDir)) {
413
+ fs.mkdirSync(targetDir, { recursive: true });
414
+ }
415
+
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");
428
+ if (!fs.existsSync(skillDir)) {
429
+ fs.mkdirSync(skillDir, { recursive: true });
430
+ }
431
+ const skillPath = path.join(skillDir, "SKILL.md");
432
+ if (!fs.existsSync(skillPath)) {
433
+ fs.writeFileSync(skillPath, SEPTUM_MAP_SKILL_TEMPLATE, "utf-8");
434
+ console.log(` ✓ Deployed AI Agent skill: '${harnessDirName}/skills/use-septum/SKILL.md'.`);
435
+ } else {
436
+ const existing = fs.readFileSync(skillPath, "utf-8");
437
+ if (existing === SEPTUM_MAP_SKILL_TEMPLATE) {
438
+ // Unchanged
439
+ } else if (force) {
440
+ fs.writeFileSync(skillPath, SEPTUM_MAP_SKILL_TEMPLATE, "utf-8");
441
+ console.log(` ✓ Updated AI Agent skill: '${harnessDirName}/skills/use-septum/SKILL.md' (--force).`);
442
+ } else {
443
+ console.log(` ✓ Preserved existing customized AI Agent skill: '${harnessDirName}/skills/use-septum/SKILL.md'.`);
444
+ }
445
+ }
446
+
447
+ // 2. Rule: <harnessDir>/rules/septum-boundary.md (Only supported natively by Gemini/Antigravity)
448
+ if (options?.includeRules) {
449
+ const rulesDir = path.join(targetDir, "rules");
450
+ if (!fs.existsSync(rulesDir)) {
451
+ fs.mkdirSync(rulesDir, { recursive: true });
452
+ }
453
+ const rulePath = path.join(rulesDir, "septum-boundary.md");
454
+ if (!fs.existsSync(rulePath)) {
455
+ fs.writeFileSync(rulePath, SEPTUM_RULES_TEMPLATE, "utf-8");
456
+ console.log(` ✓ Deployed AI Agent boundary rules: '${harnessDirName}/rules/septum-boundary.md'.`);
457
+ } else {
458
+ const existing = fs.readFileSync(rulePath, "utf-8");
459
+ if (existing === SEPTUM_RULES_TEMPLATE) {
460
+ // Unchanged
461
+ } else if (force) {
462
+ fs.writeFileSync(rulePath, SEPTUM_RULES_TEMPLATE, "utf-8");
463
+ console.log(` ✓ Updated AI Agent boundary rules: '${harnessDirName}/rules/septum-boundary.md' (--force).`);
464
+ } else {
465
+ console.log(` ✓ Preserved existing customized AI Agent boundary rules: '${harnessDirName}/rules/septum-boundary.md'.`);
466
+ }
467
+ }
468
+ }
469
+
470
+ // Optional root document (CLAUDE.md or AGENTS.md)
471
+ if (options?.rootDoc) {
472
+ const rootDocPath = path.join(cwd, options.rootDoc);
473
+ if (!fs.existsSync(rootDocPath)) {
474
+ fs.writeFileSync(rootDocPath, `# ${options.rootDoc} Guidelines\n\n${SEPTUM_RULES_TEMPLATE}\n`, "utf-8");
475
+ console.log(` ✓ Created onboarding instructions: '${options.rootDoc}'.`);
476
+ } else if (force) {
477
+ const existing = fs.readFileSync(rootDocPath, "utf-8");
478
+ if (!existing.includes("septum_map")) {
479
+ fs.writeFileSync(rootDocPath, existing.trimEnd() + "\n\n" + SEPTUM_RULES_TEMPLATE + "\n", "utf-8");
480
+ console.log(` ✓ Appended Septum boundary rules to '${options.rootDoc}' (--force).`);
481
+ }
482
+ }
483
+ }
484
+
485
+ // 3. Shared Hook Scripts: <harnessDir>/hooks/septum-pre-write.sh & septum-post-write.sh
486
+ ensureHarnessHookScripts(harnessDirName, cwd, force);
487
+ console.log(` ✓ Deployed lifecycle hook scripts in '${harnessDirName}/hooks/'.`);
488
+
489
+ // 4. Hooks Config: <harnessDir>/hooks.json
490
+ deployHarnessHooksJson(harnessDirName, cwd, force, outErrors);
491
+ }
492
+
493
+ export function deployHarnessHooksJson(
494
+ harnessDirName: string,
495
+ cwd: string = process.cwd(),
496
+ force: boolean = false,
497
+ outErrors?: string[]
498
+ ): void {
499
+ // Codex uses the strict event schema installed by configureHarness, without a namespace wrapper.
500
+ if (harnessDirName === ".codex") return;
501
+ const targetDir = path.join(cwd, harnessDirName);
502
+ const hooksJsonPath = path.join(targetDir, "hooks.json");
503
+ const hooksResult = readJsonConfigFile(hooksJsonPath);
504
+ if (hooksResult.status === "malformed") {
505
+ console.error(` ✕ Error: Malformed JSON in '${harnessDirName}/hooks.json': ${hooksResult.error}. Preserving existing file without modification.`);
506
+ if (outErrors) outErrors.push(`Malformed JSON in '${harnessDirName}/hooks.json': ${hooksResult.error}`);
507
+ return;
508
+ }
509
+
510
+ const existingHooks = hooksResult.status === "valid" ? hooksResult.data : {};
511
+ const mergedHooks: Record<string, any> = { ...existingHooks };
512
+
513
+ for (const [namespace, events] of Object.entries(SEPTUM_HOOKS_CONFIG)) {
514
+ if (!mergedHooks[namespace] || typeof mergedHooks[namespace] !== "object") {
515
+ mergedHooks[namespace] = { ...events };
516
+ continue;
517
+ }
518
+
519
+ const targetNs = { ...mergedHooks[namespace] };
520
+ const hasAnyHookArray = Array.isArray(targetNs.PreToolUse) || Array.isArray(targetNs.PostToolUse);
521
+
522
+ if (!force && !hasAnyHookArray && targetNs.user_override) {
523
+ continue;
524
+ }
525
+
526
+ for (const [eventName, templateEntries] of Object.entries(events as Record<string, any[]>)) {
527
+ const existingEntries = Array.isArray(targetNs[eventName]) ? [...targetNs[eventName]] : [];
528
+ const isSeptumCommand = (cmd: unknown) =>
529
+ typeof cmd === "string" && (cmd.includes("septum-pre-write") || cmd.includes("septum-post-write"));
530
+
531
+ if (!force) {
532
+ const hasManagedHook = existingEntries.some((entry: any) => {
533
+ if (Array.isArray(entry?.hooks)) {
534
+ return entry.hooks.some((h: any) => isSeptumCommand(h?.command));
535
+ }
536
+ return isSeptumCommand(entry?.command);
537
+ });
538
+ if (!hasManagedHook) {
539
+ existingEntries.push(...templateEntries);
540
+ }
541
+ } else {
542
+ const cleanedEntries: any[] = [];
543
+ for (const entry of existingEntries) {
544
+ if (Array.isArray(entry?.hooks)) {
545
+ const userHooks = entry.hooks.filter((h: any) => !isSeptumCommand(h?.command));
546
+ if (userHooks.length > 0) {
547
+ cleanedEntries.push({ ...entry, hooks: userHooks });
548
+ }
549
+ } else if (isSeptumCommand(entry?.command)) {
550
+ // Dedicated entry, omit
551
+ } else if (!JSON.stringify(entry).includes("septum-pre-write") && !JSON.stringify(entry).includes("septum-post-write")) {
552
+ cleanedEntries.push(entry);
553
+ }
554
+ }
555
+ cleanedEntries.push(...templateEntries);
556
+ targetNs[eventName] = cleanedEntries;
557
+ continue;
558
+ }
559
+ targetNs[eventName] = existingEntries;
560
+ }
561
+ mergedHooks[namespace] = targetNs;
562
+ }
563
+
564
+ writeJsonFile(hooksJsonPath, mergedHooks);
565
+ console.log(` ✓ Configured AI Agent lifecycle hooks: '${harnessDirName}/hooks.json'.`);
566
+ }
567
+
568
+ export function ensureHarnessHookScripts(
569
+ harnessDirName: string,
570
+ cwd: string = process.cwd(),
571
+ force: boolean = false
572
+ ): { preWrite: string; postWrite: string } {
573
+ const hooksDir = path.join(cwd, harnessDirName, "hooks");
574
+ if (!fs.existsSync(hooksDir)) {
575
+ fs.mkdirSync(hooksDir, { recursive: true });
576
+ }
577
+
578
+ const preWriteHook = path.join(hooksDir, "septum-pre-write.sh");
579
+ if (!fs.existsSync(preWriteHook) || force) {
580
+ fs.writeFileSync(preWriteHook, SEPTUM_PRE_WRITE_SCRIPT, "utf-8");
581
+ }
582
+ try {
583
+ const stat = fs.statSync(preWriteHook);
584
+ if ((stat.mode & 0o111) === 0 || force) {
585
+ fs.chmodSync(preWriteHook, 0o755);
586
+ }
587
+ } catch (err: unknown) {
588
+ const message = err instanceof Error ? err.message : String(err);
589
+ console.warn(` Notice: Could not set executable permission on '${preWriteHook}': ${message}`);
590
+ }
591
+
592
+ const postWriteHook = path.join(hooksDir, "septum-post-write.sh");
593
+ if (!fs.existsSync(postWriteHook) || force) {
594
+ fs.writeFileSync(postWriteHook, SEPTUM_POST_WRITE_SCRIPT, "utf-8");
595
+ }
596
+ try {
597
+ const stat = fs.statSync(postWriteHook);
598
+ if ((stat.mode & 0o111) === 0 || force) {
599
+ fs.chmodSync(postWriteHook, 0o755);
600
+ }
601
+ } catch (err: unknown) {
602
+ const message = err instanceof Error ? err.message : String(err);
603
+ console.warn(` Notice: Could not set executable permission on '${postWriteHook}': ${message}`);
604
+ }
605
+
606
+ return { preWrite: preWriteHook, postWrite: postWriteHook };
607
+ }
608
+
609
+ // Backward-compatibility wrapper for Antigravity (.gemini)
610
+ export function ensureSharedHookScripts(cwd: string, force: boolean = false): { preWrite: string; postWrite: string } {
611
+ return ensureHarnessHookScripts(".gemini", cwd, force);
612
+ }
613
+
614
+ // Backward-compatibility wrapper for Antigravity (.gemini)
615
+ export function scaffoldAgentCustomizations(cwd: string, force: boolean = false, outErrors?: string[]): void {
616
+ scaffoldHarnessCustomizations(".gemini", cwd, force, outErrors, { includeRules: true });
617
+ }
618
+
619
+ export function appendTomlMcpServer(
620
+ tomlPath: string,
621
+ serverName: string,
622
+ command: string,
623
+ args: string[],
624
+ force: boolean = false
625
+ ): void {
626
+ let existingContent = "";
627
+ if (fs.existsSync(tomlPath)) {
628
+ existingContent = fs.readFileSync(tomlPath, "utf-8");
629
+ }
630
+
631
+ const tableHeader = `[mcp_servers.${serverName}]`;
632
+ const formattedArgs = JSON.stringify(args);
633
+ const block = `\n${tableHeader}\ncommand = "${command}"\nargs = ${formattedArgs}\n`;
634
+
635
+ const mcpServersKeyPattern = `(?:"mcp_servers"|'mcp_servers'|mcp_servers)`;
636
+ const serverKeyPattern = `(?:"${serverName}"|'${serverName}'|${serverName})`;
637
+ const activeTableHeaderRegex = new RegExp(
638
+ `^[ \\t]*\\[[ \\t]*${mcpServersKeyPattern}[ \\t]*\\.[ \\t]*${serverKeyPattern}[ \\t]*\\][ \\t]*(?:#.*)?$`,
639
+ "m"
640
+ );
641
+ const hasActiveTable = activeTableHeaderRegex.test(existingContent);
642
+
643
+ if (hasActiveTable) {
644
+ if (force) {
645
+ const sectionRegex = new RegExp(
646
+ `(?:^|\\n)[ \\t]*\\[[ \\t]*${mcpServersKeyPattern}[ \\t]*\\.[ \\t]*${serverKeyPattern}[ \\t]*\\][ \\t]*(?:#.*)?\\r?\\n[\\s\\S]*?(?=\\r?\\n[ \\t]*\\[|$)`
647
+ );
648
+ if (sectionRegex.test(existingContent)) {
649
+ const updated = existingContent.replace(
650
+ sectionRegex,
651
+ `\n${tableHeader}\ncommand = "${command}"\nargs = ${formattedArgs}\n`
652
+ );
653
+ fs.writeFileSync(tomlPath, updated.trimStart(), "utf-8");
654
+ return;
655
+ }
656
+ }
657
+ return;
658
+ }
659
+
660
+ fs.writeFileSync(tomlPath, (existingContent.trim() ? existingContent.trim() + "\n" : "") + block, "utf-8");
661
+ }