@dimassetoid/septum-mcp 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +122 -0
  7. package/src/cli/commands/hook.ts +268 -0
  8. package/src/cli/commands/init.ts +553 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +41 -0
  11. package/src/cli/commands/topology.ts +161 -0
  12. package/src/cli/index.ts +167 -0
  13. package/src/cli/scaffold/harness-config.ts +621 -0
  14. package/src/cli/templates/hooks.ts +75 -0
  15. package/src/cli/templates/rules.ts +50 -0
  16. package/src/cli/templates/skill.ts +51 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +442 -0
  19. package/src/core/boundary/staged-auditor.ts +58 -0
  20. package/src/core/config/loader.ts +122 -0
  21. package/src/core/config/schema.ts +69 -0
  22. package/src/core/database/client.ts +60 -0
  23. package/src/core/database/repositories/dependency.repository.ts +712 -0
  24. package/src/core/database/repositories/domain.repository.ts +330 -0
  25. package/src/core/database/repositories/environment.repository.ts +207 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +508 -0
  29. package/src/core/database/repository.ts +303 -0
  30. package/src/core/database/schema.ts +154 -0
  31. package/src/core/discovery/topology-detector.ts +805 -0
  32. package/src/core/ingestion/hasher.ts +5 -0
  33. package/src/core/ingestion/pipeline.ts +623 -0
  34. package/src/core/parser/behavioral-analyzer.ts +119 -0
  35. package/src/core/parser/boundary-tracker.ts +443 -0
  36. package/src/core/parser/extractors/base.ts +67 -0
  37. package/src/core/parser/extractors/blade.ts +159 -0
  38. package/src/core/parser/extractors/csharp.ts +244 -0
  39. package/src/core/parser/extractors/django-semantic.ts +687 -0
  40. package/src/core/parser/extractors/elysia-semantic.ts +538 -0
  41. package/src/core/parser/extractors/express-semantic.ts +444 -0
  42. package/src/core/parser/extractors/fastapi-semantic.ts +736 -0
  43. package/src/core/parser/extractors/fastify-semantic.ts +774 -0
  44. package/src/core/parser/extractors/flask-semantic.ts +515 -0
  45. package/src/core/parser/extractors/frontend.ts +149 -0
  46. package/src/core/parser/extractors/go-semantic.ts +611 -0
  47. package/src/core/parser/extractors/go.ts +491 -0
  48. package/src/core/parser/extractors/hono-semantic.ts +567 -0
  49. package/src/core/parser/extractors/java.ts +225 -0
  50. package/src/core/parser/extractors/laravel-semantic.ts +1122 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +368 -0
  52. package/src/core/parser/extractors/nestjs-semantic.ts +543 -0
  53. package/src/core/parser/extractors/php.ts +569 -0
  54. package/src/core/parser/extractors/python.ts +498 -0
  55. package/src/core/parser/extractors/registry.ts +78 -0
  56. package/src/core/parser/extractors/ruby.ts +234 -0
  57. package/src/core/parser/extractors/rust.ts +286 -0
  58. package/src/core/parser/extractors/semantic-extractor.interface.ts +22 -0
  59. package/src/core/parser/extractors/symfony-semantic.ts +354 -0
  60. package/src/core/parser/extractors/typescript.ts +826 -0
  61. package/src/core/parser/language-capabilities.ts +71 -0
  62. package/src/core/parser/schema/providers/laravel-migration-provider.ts +216 -0
  63. package/src/core/parser/schema/providers/prisma-schema-provider.ts +90 -0
  64. package/src/core/parser/schema/schema-provider-registry.ts +43 -0
  65. package/src/core/parser/schema/schema-provider.interface.ts +33 -0
  66. package/src/core/parser/tree-sitter.ts +63 -0
  67. package/src/core/parser/wasm-assets.ts +25 -0
  68. package/src/core/parser/wasm-loader.ts +274 -0
  69. package/src/core/resolver/call-graph-tracer.ts +724 -0
  70. package/src/core/resolver/import-resolver.ts +437 -0
  71. package/src/core/resolver/module-resolver.ts +482 -0
  72. package/src/core/resolver/path-resolver.ts +200 -0
  73. package/src/core/resolver/symbol-locator.ts +276 -0
  74. package/src/core/resolver/symbol-reference.ts +53 -0
  75. package/src/core/resolver/vertical-slice-tracer.ts +366 -0
  76. package/src/core/resources/ignore.ts +123 -0
  77. package/src/core/resources/limits.ts +14 -0
  78. package/src/core/resources/source-files.ts +62 -0
  79. package/src/core/resources/work-queue.ts +74 -0
  80. package/src/core/session/session-manager.ts +107 -0
  81. package/src/core/telemetry/telemetry.ts +97 -0
  82. package/src/core/topology/environment-detector.ts +973 -0
  83. package/src/core/topology/types.ts +83 -0
  84. package/src/index.ts +21 -0
  85. package/src/mcp/schemas.ts +1105 -0
  86. package/src/mcp/server.ts +774 -0
  87. package/src/mcp/tools/boundary.ts +17 -0
  88. package/src/mcp/tools/check-boundary.ts +387 -0
  89. package/src/mcp/tools/domain.ts +40 -0
  90. package/src/mcp/tools/feature.ts +67 -0
  91. package/src/mcp/tools/get-domain-catalog.ts +226 -0
  92. package/src/mcp/tools/get-environment-topology.ts +138 -0
  93. package/src/mcp/tools/get-feature-context.ts +224 -0
  94. package/src/mcp/tools/get-symbol-hotspots.ts +54 -0
  95. package/src/mcp/tools/get-symbol-impact.ts +64 -0
  96. package/src/mcp/tools/get-symbol.ts +175 -0
  97. package/src/mcp/tools/locate-symbol.ts +196 -0
  98. package/src/mcp/tools/register-domain.ts +75 -0
  99. package/src/mcp/tools/register-feature.ts +110 -0
  100. package/src/mcp/tools/slice.ts +16 -0
  101. package/src/mcp/tools/symbol.ts +93 -0
  102. package/src/mcp/tools/trace-vertical-slice.ts +80 -0
  103. package/src/mcp/workspace-manager.ts +159 -0
  104. package/src/mcp/workspace-watcher.ts +202 -0
  105. package/src/types/index.ts +456 -0
  106. package/src/types/wasm.d.ts +4 -0
  107. package/src/utils/version-check.ts +209 -0
  108. package/src/version.ts +1 -0
@@ -0,0 +1,621 @@
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
+ codexHooksConfig.hooks = (typeof codexHooksConfig.hooks === "object" && codexHooksConfig.hooks !== null && !Array.isArray(codexHooksConfig.hooks))
254
+ ? codexHooksConfig.hooks
255
+ : {};
256
+ const preToolUse = Array.isArray(codexHooksConfig.hooks.PreToolUse) ? codexHooksConfig.hooks.PreToolUse : [];
257
+
258
+ const hasSeptumHook = preToolUse.some((h: any) => {
259
+ if (Array.isArray(h?.hooks)) {
260
+ return h.hooks.some((hk: any) => typeof hk?.command === "string" && hk.command.includes("septum-pre-write"));
261
+ }
262
+ return typeof h?.command === "string" && h.command.includes("septum-pre-write");
263
+ });
264
+ const canonicalHook = {
265
+ matcher: "Write|Edit|Bash",
266
+ hooks: [
267
+ {
268
+ type: "command",
269
+ command:
270
+ "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'",
271
+ },
272
+ ],
273
+ };
274
+ if (!hasSeptumHook) {
275
+ preToolUse.push(canonicalHook);
276
+ codexHooksConfig.hooks.PreToolUse = preToolUse;
277
+ writeJsonFile(codexHooksPath, codexHooksConfig);
278
+ console.log(" ✓ Configured Codex CLI lifecycle boundary guard: '.codex/hooks.json'.");
279
+ } else if (force) {
280
+ const cleanedHooks: any[] = [];
281
+ for (const h of preToolUse) {
282
+ if (Array.isArray(h?.hooks)) {
283
+ const remaining = h.hooks.filter((hk: any) =>
284
+ !(typeof hk?.command === "string" && hk.command.includes("septum-pre-write"))
285
+ );
286
+ if (remaining.length > 0) cleanedHooks.push({ ...h, hooks: remaining });
287
+ } else if (typeof h?.command === "string" && h.command.includes("septum-pre-write")) {
288
+ // Dedicated single command hook, omit
289
+ } else if (!JSON.stringify(h).includes("septum-pre-write")) {
290
+ cleanedHooks.push(h);
291
+ }
292
+ }
293
+ cleanedHooks.push(canonicalHook);
294
+ codexHooksConfig.hooks.PreToolUse = cleanedHooks;
295
+ writeJsonFile(codexHooksPath, codexHooksConfig);
296
+ console.log(" ✓ Force-regenerated Codex CLI lifecycle boundary guard: '.codex/hooks.json' (--force).");
297
+ }
298
+ configured.push(".codex/hooks.json");
299
+ }
300
+
301
+ return configured.length > 0 ? configured.join(" & ") : null;
302
+ }
303
+
304
+ case "opencode": {
305
+ const configured: string[] = [];
306
+
307
+ // 1. Skills and Hook scripts in opencode/ (rules omitted as Opencode does not support rules/)
308
+ scaffoldHarnessCustomizations("opencode", cwd, force, outErrors, { includeRules: false });
309
+ configured.push("opencode/ (skills, hooks)");
310
+
311
+ // 2. MCP config in opencode.json (project root)
312
+ const configPath = path.join(cwd, "opencode.json");
313
+ const result = readJsonConfigFile(configPath);
314
+ if (result.status === "malformed") {
315
+ console.error(` ✕ Error: Malformed JSON in 'opencode.json': ${result.error}. Preserving existing file without modification.`);
316
+ if (outErrors) outErrors.push(`Malformed JSON in 'opencode.json': ${result.error}`);
317
+ } else {
318
+ const existing = result.status === "valid" ? result.data : {};
319
+ const mcp = (typeof existing.mcp === "object" && existing.mcp !== null && !Array.isArray(existing.mcp))
320
+ ? existing.mcp
321
+ : {};
322
+ if (!mcp.septum || force) {
323
+ mcp.septum = {
324
+ type: "local",
325
+ command: ["septum", "serve"],
326
+ };
327
+ existing.mcp = mcp;
328
+ writeJsonFile(configPath, existing);
329
+ console.log(" ✓ Configured Opencode MCP server in 'opencode.json'.");
330
+ }
331
+ configured.push("opencode.json");
332
+ }
333
+
334
+ return configured.join(" & ");
335
+ }
336
+
337
+ case "agents": {
338
+ const configured: string[] = [];
339
+
340
+ // 1. Skills and Hook scripts in .agents/ + AGENTS.md root guidance (rules omitted as standard uses AGENTS.md)
341
+ scaffoldHarnessCustomizations(".agents", cwd, force, outErrors, { rootDoc: "AGENTS.md", includeRules: false });
342
+ configured.push(".agents/ (skills, hooks)");
343
+
344
+ // 2. MCP config in .agents/mcp.json
345
+ const agentsDir = path.join(cwd, ".agents");
346
+ const mcpPath = path.join(agentsDir, "mcp.json");
347
+ const mcpResult = readJsonConfigFile(mcpPath);
348
+ if (mcpResult.status === "malformed") {
349
+ console.error(` ✕ Error: Malformed JSON in '.agents/mcp.json': ${mcpResult.error}. Preserving existing file without modification.`);
350
+ if (outErrors) outErrors.push(`Malformed JSON in '.agents/mcp.json': ${mcpResult.error}`);
351
+ } else {
352
+ const existing = mcpResult.status === "valid" ? mcpResult.data : {};
353
+ const servers = (typeof existing.mcpServers === "object" && existing.mcpServers !== null && !Array.isArray(existing.mcpServers))
354
+ ? existing.mcpServers
355
+ : {};
356
+ if (!servers.septum || force) {
357
+ servers.septum = {
358
+ command: "septum",
359
+ args: ["serve"],
360
+ };
361
+ existing.mcpServers = servers;
362
+ writeJsonFile(mcpPath, existing);
363
+ console.log(" ✓ Configured .agents MCP server in '.agents/mcp.json'.");
364
+ }
365
+ configured.push(".agents/mcp.json");
366
+ }
367
+
368
+ return configured.join(" & ");
369
+ }
370
+
371
+ default:
372
+ return null;
373
+ }
374
+ }
375
+
376
+ export function scaffoldHarnessCustomizations(
377
+ harnessDirName: string,
378
+ cwd: string = process.cwd(),
379
+ force: boolean = false,
380
+ outErrors?: string[],
381
+ options?: { rootDoc?: string; includeRules?: boolean }
382
+ ): void {
383
+ const targetDir = path.join(cwd, harnessDirName);
384
+ if (!fs.existsSync(targetDir)) {
385
+ fs.mkdirSync(targetDir, { recursive: true });
386
+ }
387
+
388
+ // 1. Skill: <harnessDir>/skills/septum-map/SKILL.md
389
+ const skillDir = path.join(targetDir, "skills", "septum-map");
390
+ if (!fs.existsSync(skillDir)) {
391
+ fs.mkdirSync(skillDir, { recursive: true });
392
+ }
393
+ const skillPath = path.join(skillDir, "SKILL.md");
394
+ if (!fs.existsSync(skillPath)) {
395
+ fs.writeFileSync(skillPath, SEPTUM_MAP_SKILL_TEMPLATE, "utf-8");
396
+ console.log(` ✓ Deployed AI Agent skill: '${harnessDirName}/skills/septum-map/SKILL.md'.`);
397
+ } else {
398
+ const existing = fs.readFileSync(skillPath, "utf-8");
399
+ if (existing === SEPTUM_MAP_SKILL_TEMPLATE) {
400
+ // Unchanged
401
+ } else if (force) {
402
+ fs.writeFileSync(skillPath, SEPTUM_MAP_SKILL_TEMPLATE, "utf-8");
403
+ console.log(` ✓ Updated AI Agent skill: '${harnessDirName}/skills/septum-map/SKILL.md' (--force).`);
404
+ } else {
405
+ console.log(` ✓ Preserved existing customized AI Agent skill: '${harnessDirName}/skills/septum-map/SKILL.md'.`);
406
+ }
407
+ }
408
+
409
+ // 2. Rule: <harnessDir>/rules/septum-boundary.md (Only supported natively by Gemini/Antigravity)
410
+ if (options?.includeRules) {
411
+ const rulesDir = path.join(targetDir, "rules");
412
+ if (!fs.existsSync(rulesDir)) {
413
+ fs.mkdirSync(rulesDir, { recursive: true });
414
+ }
415
+ const rulePath = path.join(rulesDir, "septum-boundary.md");
416
+ if (!fs.existsSync(rulePath)) {
417
+ fs.writeFileSync(rulePath, SEPTUM_RULES_TEMPLATE, "utf-8");
418
+ console.log(` ✓ Deployed AI Agent boundary rules: '${harnessDirName}/rules/septum-boundary.md'.`);
419
+ } else {
420
+ const existing = fs.readFileSync(rulePath, "utf-8");
421
+ if (existing === SEPTUM_RULES_TEMPLATE) {
422
+ // Unchanged
423
+ } else if (force) {
424
+ fs.writeFileSync(rulePath, SEPTUM_RULES_TEMPLATE, "utf-8");
425
+ console.log(` ✓ Updated AI Agent boundary rules: '${harnessDirName}/rules/septum-boundary.md' (--force).`);
426
+ } else {
427
+ console.log(` ✓ Preserved existing customized AI Agent boundary rules: '${harnessDirName}/rules/septum-boundary.md'.`);
428
+ }
429
+ }
430
+ }
431
+
432
+ // Optional root document (CLAUDE.md or AGENTS.md)
433
+ if (options?.rootDoc) {
434
+ const rootDocPath = path.join(cwd, options.rootDoc);
435
+ if (!fs.existsSync(rootDocPath)) {
436
+ fs.writeFileSync(rootDocPath, `# ${options.rootDoc} Guidelines\n\n${SEPTUM_RULES_TEMPLATE}\n`, "utf-8");
437
+ console.log(` ✓ Created onboarding instructions: '${options.rootDoc}'.`);
438
+ } else if (force) {
439
+ const existing = fs.readFileSync(rootDocPath, "utf-8");
440
+ if (!existing.includes("septum_domain")) {
441
+ fs.writeFileSync(rootDocPath, existing.trimEnd() + "\n\n" + SEPTUM_RULES_TEMPLATE + "\n", "utf-8");
442
+ console.log(` ✓ Appended Septum boundary rules to '${options.rootDoc}' (--force).`);
443
+ }
444
+ }
445
+ }
446
+
447
+ // 3. Shared Hook Scripts: <harnessDir>/hooks/septum-pre-write.sh & septum-post-write.sh
448
+ ensureHarnessHookScripts(harnessDirName, cwd, force);
449
+ console.log(` ✓ Deployed lifecycle hook scripts in '${harnessDirName}/hooks/'.`);
450
+
451
+ // 4. Hooks Config: <harnessDir>/hooks.json
452
+ deployHarnessHooksJson(harnessDirName, cwd, force, outErrors);
453
+ }
454
+
455
+ export function deployHarnessHooksJson(
456
+ harnessDirName: string,
457
+ cwd: string = process.cwd(),
458
+ force: boolean = false,
459
+ outErrors?: string[]
460
+ ): void {
461
+ const targetDir = path.join(cwd, harnessDirName);
462
+ const hooksJsonPath = path.join(targetDir, "hooks.json");
463
+ const hooksResult = readJsonConfigFile(hooksJsonPath);
464
+ if (hooksResult.status === "malformed") {
465
+ console.error(` ✕ Error: Malformed JSON in '${harnessDirName}/hooks.json': ${hooksResult.error}. Preserving existing file without modification.`);
466
+ if (outErrors) outErrors.push(`Malformed JSON in '${harnessDirName}/hooks.json': ${hooksResult.error}`);
467
+ return;
468
+ }
469
+
470
+ const existingHooks = hooksResult.status === "valid" ? hooksResult.data : {};
471
+ const mergedHooks: Record<string, any> = { ...existingHooks };
472
+
473
+ for (const [namespace, events] of Object.entries(SEPTUM_HOOKS_CONFIG)) {
474
+ if (!mergedHooks[namespace] || typeof mergedHooks[namespace] !== "object") {
475
+ mergedHooks[namespace] = { ...events };
476
+ continue;
477
+ }
478
+
479
+ const targetNs = { ...mergedHooks[namespace] };
480
+ const hasAnyHookArray = Array.isArray(targetNs.PreToolUse) || Array.isArray(targetNs.PostToolUse);
481
+
482
+ if (!force && !hasAnyHookArray && targetNs.user_override) {
483
+ continue;
484
+ }
485
+
486
+ for (const [eventName, templateEntries] of Object.entries(events as Record<string, any[]>)) {
487
+ const existingEntries = Array.isArray(targetNs[eventName]) ? [...targetNs[eventName]] : [];
488
+ const isSeptumCommand = (cmd: unknown) =>
489
+ typeof cmd === "string" && (cmd.includes("septum-pre-write") || cmd.includes("septum-post-write"));
490
+
491
+ if (!force) {
492
+ const hasManagedHook = existingEntries.some((entry: any) => {
493
+ if (Array.isArray(entry?.hooks)) {
494
+ return entry.hooks.some((h: any) => isSeptumCommand(h?.command));
495
+ }
496
+ return isSeptumCommand(entry?.command);
497
+ });
498
+ if (!hasManagedHook) {
499
+ existingEntries.push(...templateEntries);
500
+ }
501
+ } else {
502
+ const cleanedEntries: any[] = [];
503
+ for (const entry of existingEntries) {
504
+ if (Array.isArray(entry?.hooks)) {
505
+ const userHooks = entry.hooks.filter((h: any) => !isSeptumCommand(h?.command));
506
+ if (userHooks.length > 0) {
507
+ cleanedEntries.push({ ...entry, hooks: userHooks });
508
+ }
509
+ } else if (isSeptumCommand(entry?.command)) {
510
+ // Dedicated entry, omit
511
+ } else if (!JSON.stringify(entry).includes("septum-pre-write") && !JSON.stringify(entry).includes("septum-post-write")) {
512
+ cleanedEntries.push(entry);
513
+ }
514
+ }
515
+ cleanedEntries.push(...templateEntries);
516
+ targetNs[eventName] = cleanedEntries;
517
+ continue;
518
+ }
519
+ targetNs[eventName] = existingEntries;
520
+ }
521
+ mergedHooks[namespace] = targetNs;
522
+ }
523
+
524
+ writeJsonFile(hooksJsonPath, mergedHooks);
525
+ console.log(` ✓ Configured AI Agent lifecycle hooks: '${harnessDirName}/hooks.json'.`);
526
+ }
527
+
528
+ export function ensureHarnessHookScripts(
529
+ harnessDirName: string,
530
+ cwd: string = process.cwd(),
531
+ force: boolean = false
532
+ ): { preWrite: string; postWrite: string } {
533
+ const hooksDir = path.join(cwd, harnessDirName, "hooks");
534
+ if (!fs.existsSync(hooksDir)) {
535
+ fs.mkdirSync(hooksDir, { recursive: true });
536
+ }
537
+
538
+ const preWriteHook = path.join(hooksDir, "septum-pre-write.sh");
539
+ if (!fs.existsSync(preWriteHook) || force) {
540
+ fs.writeFileSync(preWriteHook, SEPTUM_PRE_WRITE_SCRIPT, "utf-8");
541
+ }
542
+ try {
543
+ const stat = fs.statSync(preWriteHook);
544
+ if ((stat.mode & 0o111) === 0 || force) {
545
+ fs.chmodSync(preWriteHook, 0o755);
546
+ }
547
+ } catch (err: unknown) {
548
+ const message = err instanceof Error ? err.message : String(err);
549
+ console.warn(` Notice: Could not set executable permission on '${preWriteHook}': ${message}`);
550
+ }
551
+
552
+ const postWriteHook = path.join(hooksDir, "septum-post-write.sh");
553
+ if (!fs.existsSync(postWriteHook) || force) {
554
+ fs.writeFileSync(postWriteHook, SEPTUM_POST_WRITE_SCRIPT, "utf-8");
555
+ }
556
+ try {
557
+ const stat = fs.statSync(postWriteHook);
558
+ if ((stat.mode & 0o111) === 0 || force) {
559
+ fs.chmodSync(postWriteHook, 0o755);
560
+ }
561
+ } catch (err: unknown) {
562
+ const message = err instanceof Error ? err.message : String(err);
563
+ console.warn(` Notice: Could not set executable permission on '${postWriteHook}': ${message}`);
564
+ }
565
+
566
+ return { preWrite: preWriteHook, postWrite: postWriteHook };
567
+ }
568
+
569
+ // Backward-compatibility wrapper for Antigravity (.gemini)
570
+ export function ensureSharedHookScripts(cwd: string, force: boolean = false): { preWrite: string; postWrite: string } {
571
+ return ensureHarnessHookScripts(".gemini", cwd, force);
572
+ }
573
+
574
+ // Backward-compatibility wrapper for Antigravity (.gemini)
575
+ export function scaffoldAgentCustomizations(cwd: string, force: boolean = false, outErrors?: string[]): void {
576
+ scaffoldHarnessCustomizations(".gemini", cwd, force, outErrors, { includeRules: true });
577
+ }
578
+
579
+ export function appendTomlMcpServer(
580
+ tomlPath: string,
581
+ serverName: string,
582
+ command: string,
583
+ args: string[],
584
+ force: boolean = false
585
+ ): void {
586
+ let existingContent = "";
587
+ if (fs.existsSync(tomlPath)) {
588
+ existingContent = fs.readFileSync(tomlPath, "utf-8");
589
+ }
590
+
591
+ const tableHeader = `[mcp_servers.${serverName}]`;
592
+ const formattedArgs = JSON.stringify(args);
593
+ const block = `\n${tableHeader}\ncommand = "${command}"\nargs = ${formattedArgs}\n`;
594
+
595
+ const mcpServersKeyPattern = `(?:"mcp_servers"|'mcp_servers'|mcp_servers)`;
596
+ const serverKeyPattern = `(?:"${serverName}"|'${serverName}'|${serverName})`;
597
+ const activeTableHeaderRegex = new RegExp(
598
+ `^[ \\t]*\\[[ \\t]*${mcpServersKeyPattern}[ \\t]*\\.[ \\t]*${serverKeyPattern}[ \\t]*\\][ \\t]*(?:#.*)?$`,
599
+ "m"
600
+ );
601
+ const hasActiveTable = activeTableHeaderRegex.test(existingContent);
602
+
603
+ if (hasActiveTable) {
604
+ if (force) {
605
+ const sectionRegex = new RegExp(
606
+ `(?:^|\\n)[ \\t]*\\[[ \\t]*${mcpServersKeyPattern}[ \\t]*\\.[ \\t]*${serverKeyPattern}[ \\t]*\\][ \\t]*(?:#.*)?\\r?\\n[\\s\\S]*?(?=\\r?\\n[ \\t]*\\[|$)`
607
+ );
608
+ if (sectionRegex.test(existingContent)) {
609
+ const updated = existingContent.replace(
610
+ sectionRegex,
611
+ `\n${tableHeader}\ncommand = "${command}"\nargs = ${formattedArgs}\n`
612
+ );
613
+ fs.writeFileSync(tomlPath, updated.trimStart(), "utf-8");
614
+ return;
615
+ }
616
+ }
617
+ return;
618
+ }
619
+
620
+ fs.writeFileSync(tomlPath, (existingContent.trim() ? existingContent.trim() + "\n" : "") + block, "utf-8");
621
+ }