agent-enderun 1.10.4 → 1.11.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 (210) hide show
  1. package/README.md +34 -45
  2. package/dist/framework-mcp/tests/tools/quality/check_lint.test.js +1 -1
  3. package/dist/framework-mcp/tests/tools/quality/check_lint.test.js.map +1 -1
  4. package/dist/src/cli/adapters/core.d.ts +1 -1
  5. package/dist/src/cli/adapters/core.js +0 -1
  6. package/dist/src/cli/adapters/core.js.map +1 -1
  7. package/dist/src/cli/adapters/index.d.ts +1 -0
  8. package/dist/src/cli/adapters/index.js +1 -0
  9. package/dist/src/cli/adapters/index.js.map +1 -1
  10. package/dist/src/cli/adapters/scaffold.d.ts +1 -1
  11. package/dist/src/cli/adapters/scaffold.js +13 -7
  12. package/dist/src/cli/adapters/scaffold.js.map +1 -1
  13. package/dist/src/cli/commands/init/scaffold-core.d.ts +5 -2
  14. package/dist/src/cli/commands/init/scaffold-core.js +28 -6
  15. package/dist/src/cli/commands/init/scaffold-core.js.map +1 -1
  16. package/dist/src/cli/commands/init.js +31 -4
  17. package/dist/src/cli/commands/init.js.map +1 -1
  18. package/dist/src/cli/commands/orchestrate.d.ts +9 -7
  19. package/dist/src/cli/commands/orchestrate.js +40 -4
  20. package/dist/src/cli/commands/orchestrate.js.map +1 -1
  21. package/dist/src/cli/commands/plan.d.ts +3 -1
  22. package/dist/src/cli/commands/plan.js +79 -22
  23. package/dist/src/cli/commands/plan.js.map +1 -1
  24. package/dist/src/cli/index.js +11 -15
  25. package/dist/src/cli/index.js.map +1 -1
  26. package/dist/src/cli/utils/compliance.js +0 -1
  27. package/dist/src/cli/utils/compliance.js.map +1 -1
  28. package/dist/src/cli/utils/config-schema.d.ts +7 -7
  29. package/dist/src/cli/utils/pkg.d.ts +19 -0
  30. package/dist/src/cli/utils/pkg.js +29 -5
  31. package/dist/src/cli/utils/pkg.js.map +1 -1
  32. package/dist/src/modules/adapters/definitions.js +1 -1
  33. package/dist/src/modules/adapters/definitions.js.map +1 -1
  34. package/dist/src/modules/adapters/shared.js +7 -4
  35. package/dist/src/modules/adapters/shared.js.map +1 -1
  36. package/dist/src/modules/agents/definitions.d.ts +1 -1
  37. package/dist/src/modules/agents/definitions.js +129 -69
  38. package/dist/src/modules/agents/definitions.js.map +1 -1
  39. package/dist/src/modules/agents/registry/analyst.js +5 -1
  40. package/dist/src/modules/agents/registry/analyst.js.map +1 -1
  41. package/dist/src/modules/agents/registry/backend.js +5 -4
  42. package/dist/src/modules/agents/registry/backend.js.map +1 -1
  43. package/dist/src/modules/agents/registry/database.js +2 -1
  44. package/dist/src/modules/agents/registry/database.js.map +1 -1
  45. package/dist/src/modules/agents/registry/devops.js +2 -0
  46. package/dist/src/modules/agents/registry/devops.js.map +1 -1
  47. package/dist/src/modules/agents/registry/explorer.js +1 -0
  48. package/dist/src/modules/agents/registry/explorer.js.map +1 -1
  49. package/dist/src/modules/agents/registry/git.js +3 -1
  50. package/dist/src/modules/agents/registry/git.js.map +1 -1
  51. package/dist/src/modules/agents/registry/manager.js +8 -2
  52. package/dist/src/modules/agents/registry/manager.js.map +1 -1
  53. package/dist/src/modules/agents/registry/native.js +5 -1
  54. package/dist/src/modules/agents/registry/native.js.map +1 -1
  55. package/dist/src/modules/agents/registry/security.js +1 -0
  56. package/dist/src/modules/agents/registry/security.js.map +1 -1
  57. package/dist/src/shared/constants.d.ts +1 -1
  58. package/dist/src/shared/constants.js +10 -9
  59. package/dist/src/shared/constants.js.map +1 -1
  60. package/dist/tests/approve.test.js +4 -9
  61. package/dist/tests/approve.test.js.map +1 -1
  62. package/dist/tests/integration/agent_flow.test.js +2 -2
  63. package/dist/tests/integration/agent_flow.test.js.map +1 -1
  64. package/dist/tests/orchestrate.test.js +2 -7
  65. package/dist/tests/orchestrate.test.js.map +1 -1
  66. package/framework-mcp/dist/constants.js +64 -0
  67. package/framework-mcp/dist/index.js +109 -0
  68. package/framework-mcp/dist/tools/control_plane/locking.js +64 -0
  69. package/framework-mcp/dist/tools/control_plane/registry.js +34 -0
  70. package/framework-mcp/dist/tools/dashboard/start_dashboard.js +29 -0
  71. package/framework-mcp/dist/tools/definitions.js +300 -0
  72. package/framework-mcp/dist/tools/file_system/batch_surgical_edit.js +59 -0
  73. package/framework-mcp/dist/tools/file_system/patch_file.js +25 -0
  74. package/framework-mcp/dist/tools/file_system/read_file.js +51 -0
  75. package/framework-mcp/dist/tools/file_system/replace_text.js +43 -0
  76. package/framework-mcp/dist/tools/file_system/write_file.js +38 -0
  77. package/framework-mcp/dist/tools/framework/audit_deps.js +41 -0
  78. package/framework-mcp/dist/tools/framework/get_status.js +5 -0
  79. package/framework-mcp/dist/tools/framework/orchestrate.js +5 -0
  80. package/framework-mcp/dist/tools/framework/run_tests.js +25 -0
  81. package/framework-mcp/dist/tools/framework/update_contract_hash.js +5 -0
  82. package/framework-mcp/dist/tools/framework/update_memory.js +8 -0
  83. package/framework-mcp/dist/tools/index.js +62 -0
  84. package/framework-mcp/dist/tools/memory/get_insights.js +34 -0
  85. package/framework-mcp/dist/tools/memory/read_memory.js +28 -0
  86. package/framework-mcp/dist/tools/messaging/log_action.js +22 -0
  87. package/framework-mcp/dist/tools/messaging/send_message.js +87 -0
  88. package/framework-mcp/dist/tools/observability/check_ports.js +26 -0
  89. package/framework-mcp/dist/tools/observability/get_health.js +19 -0
  90. package/framework-mcp/dist/tools/quality/check_lint.js +28 -0
  91. package/framework-mcp/dist/tools/search/get_gaps.js +48 -0
  92. package/framework-mcp/dist/tools/search/get_map.js +43 -0
  93. package/framework-mcp/dist/tools/search/grep_search.js +76 -0
  94. package/framework-mcp/dist/tools/search/list_dir.js +28 -0
  95. package/framework-mcp/dist/tools/shell/run_command.js +46 -0
  96. package/framework-mcp/dist/tools/types.js +1 -0
  97. package/framework-mcp/dist/utils/cli.js +20 -0
  98. package/framework-mcp/dist/utils/compliance.js +29 -0
  99. package/framework-mcp/dist/utils/fs.js +44 -0
  100. package/framework-mcp/dist/utils/metrics.js +56 -0
  101. package/framework-mcp/dist/utils/security.js +60 -0
  102. package/framework-mcp/package.json +19 -0
  103. package/framework-mcp/src/constants.ts +78 -0
  104. package/framework-mcp/src/declarations.d.ts +17 -0
  105. package/framework-mcp/src/index.ts +132 -0
  106. package/framework-mcp/src/tools/control_plane/locking.ts +71 -0
  107. package/framework-mcp/src/tools/control_plane/registry.ts +38 -0
  108. package/framework-mcp/src/tools/dashboard/start_dashboard.ts +33 -0
  109. package/framework-mcp/src/tools/definitions.ts +302 -0
  110. package/framework-mcp/src/tools/file_system/batch_surgical_edit.ts +79 -0
  111. package/framework-mcp/src/tools/file_system/patch_file.ts +33 -0
  112. package/framework-mcp/src/tools/file_system/read_file.ts +58 -0
  113. package/framework-mcp/src/tools/file_system/replace_text.ts +52 -0
  114. package/framework-mcp/src/tools/file_system/write_file.ts +45 -0
  115. package/framework-mcp/src/tools/framework/audit_deps.ts +49 -0
  116. package/framework-mcp/src/tools/framework/get_status.ts +7 -0
  117. package/framework-mcp/src/tools/framework/orchestrate.ts +7 -0
  118. package/framework-mcp/src/tools/framework/run_tests.ts +28 -0
  119. package/framework-mcp/src/tools/framework/update_contract_hash.ts +7 -0
  120. package/framework-mcp/src/tools/framework/update_memory.ts +10 -0
  121. package/framework-mcp/src/tools/index.ts +66 -0
  122. package/framework-mcp/src/tools/memory/get_insights.ts +41 -0
  123. package/framework-mcp/src/tools/memory/read_memory.ts +31 -0
  124. package/framework-mcp/src/tools/messaging/log_action.ts +28 -0
  125. package/framework-mcp/src/tools/messaging/send_message.ts +89 -0
  126. package/framework-mcp/src/tools/observability/check_ports.ts +30 -0
  127. package/framework-mcp/src/tools/observability/get_health.ts +24 -0
  128. package/framework-mcp/src/tools/quality/check_lint.ts +33 -0
  129. package/framework-mcp/src/tools/search/get_gaps.ts +54 -0
  130. package/framework-mcp/src/tools/search/get_map.ts +48 -0
  131. package/framework-mcp/src/tools/search/grep_search.ts +76 -0
  132. package/framework-mcp/src/tools/search/list_dir.ts +34 -0
  133. package/framework-mcp/src/tools/shell/run_command.ts +56 -0
  134. package/framework-mcp/src/tools/types.ts +89 -0
  135. package/framework-mcp/src/utils/cli.ts +20 -0
  136. package/framework-mcp/src/utils/compliance.ts +37 -0
  137. package/framework-mcp/src/utils/fs.ts +45 -0
  138. package/framework-mcp/src/utils/metrics.ts +73 -0
  139. package/framework-mcp/src/utils/security.ts +66 -0
  140. package/framework-mcp/tests/tools/file_system/file_system_tools.test.ts +212 -0
  141. package/framework-mcp/tests/tools/messaging/send_message.test.ts +136 -0
  142. package/framework-mcp/tests/tools/quality/check_lint.test.ts +46 -0
  143. package/framework-mcp/tests/tools/shell/run_command.test.ts +55 -0
  144. package/framework-mcp/tsconfig.json +14 -0
  145. package/package.json +5 -3
  146. package/src/cli/adapters/core.ts +2 -3
  147. package/src/cli/adapters/index.ts +1 -0
  148. package/src/cli/adapters/scaffold.ts +20 -7
  149. package/src/cli/commands/init/scaffold-core.ts +45 -6
  150. package/src/cli/commands/init.ts +31 -2
  151. package/src/cli/commands/orchestrate.ts +41 -4
  152. package/src/cli/commands/plan.ts +89 -23
  153. package/src/cli/index.ts +14 -19
  154. package/src/cli/utils/compliance.ts +8 -9
  155. package/src/cli/utils/pkg.ts +42 -13
  156. package/src/modules/adapters/definitions.ts +1 -1
  157. package/src/modules/adapters/shared.ts +7 -4
  158. package/src/modules/agents/definitions.ts +140 -73
  159. package/src/modules/agents/registry/analyst.ts +5 -1
  160. package/src/modules/agents/registry/backend.ts +5 -4
  161. package/src/modules/agents/registry/database.ts +2 -1
  162. package/src/modules/agents/registry/devops.ts +2 -0
  163. package/src/modules/agents/registry/explorer.ts +1 -0
  164. package/src/modules/agents/registry/git.ts +3 -1
  165. package/src/modules/agents/registry/manager.ts +8 -2
  166. package/src/modules/agents/registry/native.ts +5 -1
  167. package/src/modules/agents/registry/security.ts +1 -0
  168. package/src/shared/constants.ts +14 -13
  169. package/templates/prompts/bug-fix-recipe.md +20 -0
  170. package/templates/prompts/contract-design-recipe.md +21 -0
  171. package/templates/prompts/db-management-recipe.md +25 -0
  172. package/templates/prompts/deployment-recipe.md +23 -0
  173. package/templates/prompts/new-feature-recipe.md +19 -0
  174. package/templates/prompts/performance-optimization-recipe.md +23 -0
  175. package/templates/prompts/pull-request-template.md +21 -0
  176. package/templates/prompts/refactoring-recipe.md +21 -0
  177. package/templates/prompts/security-audit-recipe.md +20 -0
  178. package/templates/standards/architecture-standards.md +23 -0
  179. package/templates/standards/auth-standards.md +125 -0
  180. package/templates/standards/crud-governance.md +21 -0
  181. package/templates/standards/deployment-standards.md +21 -0
  182. package/templates/standards/frontend-standards.md +37 -0
  183. package/templates/standards/github-actions-standards.md +43 -0
  184. package/templates/standards/i18n-standards.md +17 -0
  185. package/templates/standards/kysely-standards.md +47 -0
  186. package/templates/standards/llm-governance.md +15 -0
  187. package/templates/standards/logging-and-secrets.md +34 -0
  188. package/templates/standards/mobile-standards.md +23 -0
  189. package/templates/standards/observability-standards.md +15 -0
  190. package/templates/standards/performance-standards.md +15 -0
  191. package/templates/standards/pino-standards.md +46 -0
  192. package/templates/standards/playwright-standards.md +54 -0
  193. package/templates/standards/quality-standards.md +31 -0
  194. package/templates/standards/react-query-standards.md +72 -0
  195. package/templates/standards/react-router-standards.md +62 -0
  196. package/templates/standards/security-audit-standards.md +16 -0
  197. package/templates/standards/security-standards.md +21 -0
  198. package/templates/standards/swagger-standards.md +50 -0
  199. package/templates/standards/tailwind-standards.md +20 -0
  200. package/templates/standards/testing-standards.md +31 -0
  201. package/templates/standards/typeorm-standards.md +49 -0
  202. package/templates/standards/vitest-standards.md +110 -0
  203. package/src/cli/commands/app.ts +0 -56
  204. package/src/cli/utils/app-backend.ts +0 -257
  205. package/src/cli/utils/app-docs.ts +0 -83
  206. package/src/cli/utils/app-frontend.ts +0 -263
  207. package/src/cli/utils/app-inferrer.ts +0 -63
  208. package/src/cli/utils/app-mobile.ts +0 -113
  209. package/src/cli/utils/app-types.ts +0 -248
  210. package/src/cli/utils/app.ts +0 -6
@@ -0,0 +1,5 @@
1
+ import { safeExec } from "../../utils/cli.js";
2
+ export function handleUpdateContractHash(projectRoot, args) {
3
+ const output = safeExec("npx", ["agent-enderun", "update-contract"], projectRoot, args.timeout);
4
+ return { content: [{ type: "text", text: output }] };
5
+ }
@@ -0,0 +1,8 @@
1
+ import { safeExec } from "../../utils/cli.js";
2
+ export function handleUpdateProjectMemory(projectRoot, args) {
3
+ const section = args.section;
4
+ const content = args.content;
5
+ // Using execFileSync with array args prevents command injection
6
+ safeExec("npx", ["agent-enderun", "update_project_memory", section, content], projectRoot);
7
+ return { content: [{ type: "text", text: `✅ Section ${section} updated.` }] };
8
+ }
@@ -0,0 +1,62 @@
1
+ import { TOOLS } from "./definitions.js";
2
+ import { handleReadFile } from "./file_system/read_file.js";
3
+ import { handleWriteFile } from "./file_system/write_file.js";
4
+ import { handleReplaceText } from "./file_system/replace_text.js";
5
+ import { handleBatchSurgicalEdit } from "./file_system/batch_surgical_edit.js";
6
+ import { handlePatchFile } from "./file_system/patch_file.js";
7
+ import { handleGrepSearch } from "./search/grep_search.js";
8
+ import { handleListDir } from "./search/list_dir.js";
9
+ import { handleGetProjectGaps } from "./search/get_gaps.js";
10
+ import { handleGetProjectMap } from "./search/get_map.js";
11
+ import { handleGetFrameworkStatus } from "./framework/get_status.js";
12
+ import { handleUpdateProjectMemory } from "./framework/update_memory.js";
13
+ import { handleAuditDependencies } from "./framework/audit_deps.js";
14
+ import { handleRunTests } from "./framework/run_tests.js";
15
+ import { handleGetSystemHealth } from "./observability/get_health.js";
16
+ import { handleCheckPorts } from "./observability/check_ports.js";
17
+ import { handleStartDashboard } from "./dashboard/start_dashboard.js";
18
+ import { handleOrchestrateLoop } from "./framework/orchestrate.js";
19
+ import { handleUpdateContractHash } from "./framework/update_contract_hash.js";
20
+ import { handleReadProjectMemory } from "./memory/read_memory.js";
21
+ import { handleGetMemoryInsights } from "./memory/get_insights.js";
22
+ import { handleSendAgentMessage } from "./messaging/send_message.js";
23
+ import { handleLogAgentAction } from "./messaging/log_action.js";
24
+ import { handleAcquireLock, handleReleaseLock } from "./control_plane/locking.js";
25
+ import { handleRegisterAgent } from "./control_plane/registry.js";
26
+ import { handleRunCommand } from "./shell/run_command.js";
27
+ import { handleCheckLint } from "./quality/check_lint.js";
28
+ // Map of tool names to their handler functions
29
+ const bind = (fn) => {
30
+ return (root, args) => fn(root, args);
31
+ };
32
+ export const toolHandlers = {
33
+ read_file: bind(handleReadFile),
34
+ view_file: bind(handleReadFile), // Alias
35
+ list_dir: bind(handleListDir),
36
+ grep_search: bind(handleGrepSearch),
37
+ get_project_map: bind(handleGetProjectMap),
38
+ get_project_gaps: bind(handleGetProjectGaps),
39
+ write_file: bind(handleWriteFile),
40
+ replace_text: bind(handleReplaceText),
41
+ batch_surgical_edit: bind(handleBatchSurgicalEdit),
42
+ patch_file: bind(handlePatchFile),
43
+ get_framework_status: bind(handleGetFrameworkStatus),
44
+ read_project_memory: bind(handleReadProjectMemory),
45
+ get_memory_insights: bind(handleGetMemoryInsights),
46
+ update_project_memory: bind(handleUpdateProjectMemory),
47
+ audit_dependencies: bind(handleAuditDependencies),
48
+ run_tests: bind(handleRunTests),
49
+ get_system_health: bind(handleGetSystemHealth),
50
+ check_active_ports: bind(handleCheckPorts),
51
+ start_dashboard: bind(handleStartDashboard),
52
+ orchestrate_loop: bind(handleOrchestrateLoop),
53
+ send_agent_message: bind(handleSendAgentMessage),
54
+ log_agent_action: bind(handleLogAgentAction),
55
+ update_contract_hash: bind(handleUpdateContractHash),
56
+ acquire_lock: bind(handleAcquireLock),
57
+ release_lock: bind(handleReleaseLock),
58
+ register_agent: bind(handleRegisterAgent),
59
+ run_shell_command: bind(handleRunCommand),
60
+ check_lint: bind(handleCheckLint),
61
+ };
62
+ export { TOOLS };
@@ -0,0 +1,34 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { resolveFrameworkDir } from "../../utils/security.js";
4
+ /**
5
+ * Extracts key insights from the project memory to minimize token usage.
6
+ * Returns only the active phase, trace, and the last 5 decisions/tasks.
7
+ */
8
+ export function handleGetMemoryInsights(projectRoot, _args) {
9
+ try {
10
+ const frameworkDir = resolveFrameworkDir(projectRoot);
11
+ const memoryPath = path.join(projectRoot, frameworkDir, "memory/PROJECT_MEMORY.md");
12
+ if (!fs.existsSync(memoryPath)) {
13
+ return { content: [{ type: "text", text: "New project: No history available." }] };
14
+ }
15
+ const content = fs.readFileSync(memoryPath, "utf8");
16
+ const lines = content.split("\n");
17
+ const activePhase = lines.find(l => l.includes("Active Phase:"))?.split(":")[1]?.trim() || "Unknown";
18
+ const activeTrace = lines.find(l => l.includes("Active Trace:"))?.split(":")[1]?.trim() || "None";
19
+ // Find the last 5 history items (heuristic)
20
+ const historyStartIndex = lines.findIndex(l => l.includes("## History"));
21
+ let recentHistory = "No history found.";
22
+ if (historyStartIndex !== -1) {
23
+ recentHistory = lines.slice(historyStartIndex + 1, historyStartIndex + 15)
24
+ .filter(l => l.trim().startsWith("-"))
25
+ .slice(-5)
26
+ .join("\n");
27
+ }
28
+ const insights = `🧠 **Memory Insights**\n- **Phase:** ${activePhase}\n- **Trace:** ${activeTrace}\n\n**Recent Actions:**\n${recentHistory}`;
29
+ return { content: [{ type: "text", text: insights }] };
30
+ }
31
+ catch (e) {
32
+ return { isError: true, content: [{ type: "text", text: `Failed to extract insights: ${String(e)}` }] };
33
+ }
34
+ }
@@ -0,0 +1,28 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { resolveFrameworkDir } from "../../utils/security.js";
4
+ /**
5
+ * Reads the project's central memory (PROJECT_MEMORY.md).
6
+ * This is the "brain" of the project.
7
+ */
8
+ export function handleReadProjectMemory(projectRoot, _args) {
9
+ try {
10
+ const frameworkDir = resolveFrameworkDir(projectRoot);
11
+ const memoryPath = path.join(projectRoot, frameworkDir, "memory/PROJECT_MEMORY.md");
12
+ if (!fs.existsSync(memoryPath)) {
13
+ return {
14
+ content: [{ type: "text", text: "ℹ️ Project memory file not found. It might be a new project." }]
15
+ };
16
+ }
17
+ const content = fs.readFileSync(memoryPath, "utf8");
18
+ return {
19
+ content: [{ type: "text", text: content }]
20
+ };
21
+ }
22
+ catch (e) {
23
+ return {
24
+ isError: true,
25
+ content: [{ type: "text", text: `Failed to read project memory: ${String(e)}` }]
26
+ };
27
+ }
28
+ }
@@ -0,0 +1,22 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { resolveFrameworkDir } from "../../utils/security.js";
4
+ export function handleLogAgentAction(projectRoot, args) {
5
+ const { agent, action, traceId, status, summary } = args;
6
+ const findings = args.findings ? args.findings.split(",").map(f => f.trim()) : [];
7
+ const frameworkDir = resolveFrameworkDir(projectRoot);
8
+ const agentName = agent.replace("@", "");
9
+ const logPath = path.join(projectRoot, frameworkDir, "logs", `${agentName}.json`);
10
+ const logEntry = {
11
+ timestamp: new Date().toISOString(),
12
+ agent,
13
+ action,
14
+ requestId: traceId,
15
+ status,
16
+ summary,
17
+ findings
18
+ };
19
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
20
+ fs.appendFileSync(logPath, JSON.stringify(logEntry) + "\n");
21
+ return { content: [{ type: "text", text: `✅ Action logged for ${agent} to ${path.join(frameworkDir, "logs", `${agentName}.json`)}` }] };
22
+ }
@@ -0,0 +1,87 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { resolveFrameworkDir } from "../../utils/security.js";
4
+ import { Metrics } from "../../utils/metrics.js";
5
+ export async function handleSendAgentMessage(projectRoot, args) {
6
+ const { to, category, content, traceId } = args;
7
+ const from = args.from || "@mcp";
8
+ if (!to || !category || !content || !traceId) {
9
+ const err = "Missing required messaging arguments (to, category, content, or traceId).";
10
+ Metrics.logError(projectRoot, from, "send_agent_message", err);
11
+ return { isError: true, content: [{ type: "text", text: `❌ ${err}` }] };
12
+ }
13
+ const frameworkDir = resolveFrameworkDir(projectRoot);
14
+ const messagesDir = path.join(projectRoot, frameworkDir, "messages");
15
+ const agentName = to.replace("@", "");
16
+ const messagePath = path.join(messagesDir, `${agentName}.json`);
17
+ const lockPath = path.join(messagesDir, `${agentName}.lock`);
18
+ // Hermes Lock Protocol: Retry 3 times with 500ms delay
19
+ let retries = 3;
20
+ let acquired = false;
21
+ while (retries > 0) {
22
+ try {
23
+ if (fs.existsSync(lockPath)) {
24
+ try {
25
+ const stats = fs.statSync(lockPath);
26
+ if (Date.now() - stats.mtimeMs > 5000) {
27
+ fs.unlinkSync(lockPath);
28
+ }
29
+ }
30
+ catch {
31
+ // ignore if concurrently unlinked
32
+ }
33
+ }
34
+ fs.mkdirSync(messagesDir, { recursive: true });
35
+ fs.writeFileSync(lockPath, `Locked by ${from} at ${new Date().toISOString()}`, { flag: "wx" });
36
+ acquired = true;
37
+ break;
38
+ }
39
+ catch (err) {
40
+ const error = err;
41
+ if (error.code === "EEXIST") {
42
+ retries--;
43
+ if (retries > 0) {
44
+ await new Promise((resolve) => setTimeout(resolve, 500));
45
+ }
46
+ }
47
+ else {
48
+ return { content: [{ type: "text", text: `❌ Unexpected lock acquisition error: ${error.message || String(err)}` }], isError: true };
49
+ }
50
+ }
51
+ }
52
+ if (!acquired) {
53
+ const err = `Could not send message to ${to}: Hermes lock is busy.`;
54
+ Metrics.logError(projectRoot, from, "send_agent_message", err);
55
+ return { content: [{ type: "text", text: `❌ ${err}` }], isError: true };
56
+ }
57
+ try {
58
+ const defaultPriority = (category === "ALERT" || category === "ACTION") ? "HIGH" : "NORMAL";
59
+ const message = {
60
+ timestamp: new Date().toISOString(),
61
+ from,
62
+ to,
63
+ category,
64
+ traceId,
65
+ content,
66
+ priority: args.priority || defaultPriority,
67
+ status: "PENDING"
68
+ };
69
+ fs.appendFileSync(messagePath, JSON.stringify(message) + "\n");
70
+ return { content: [{ type: "text", text: `✅ Message sent to ${to} (from: ${from})` }] };
71
+ }
72
+ catch (e) {
73
+ const err = `Failed to write message: ${String(e)}`;
74
+ Metrics.logError(projectRoot, from, "send_agent_message", err);
75
+ return { isError: true, content: [{ type: "text", text: `❌ ${err}` }] };
76
+ }
77
+ finally {
78
+ if (acquired && fs.existsSync(lockPath)) {
79
+ try {
80
+ fs.unlinkSync(lockPath);
81
+ }
82
+ catch {
83
+ // ignore
84
+ }
85
+ }
86
+ }
87
+ }
@@ -0,0 +1,26 @@
1
+ import { execSync } from "child_process";
2
+ /**
3
+ * Checks for active network ports and their status.
4
+ */
5
+ export function handleCheckPorts(projectRoot, args) {
6
+ const filter = args.filter || ""; // Optional filter (e.g., ":3000")
7
+ try {
8
+ // Using 'lsof -i -P -n' to list open files and network connections
9
+ // Note: may require permissions or behave differently on non-Unix systems
10
+ const command = process.platform === "win32"
11
+ ? `netstat -ano | findstr LISTENING ${filter ? `| findstr ${filter}` : ""}`
12
+ : `lsof -i -P -n | grep LISTEN ${filter ? `| grep ${filter}` : ""}`;
13
+ const output = execSync(command, { encoding: "utf8" });
14
+ return {
15
+ content: [{
16
+ type: "text",
17
+ text: `📡 **Active Listening Ports:**\n\n${output || "No active listening ports found matching filter."}`
18
+ }]
19
+ };
20
+ }
21
+ catch (_e) {
22
+ return {
23
+ content: [{ type: "text", text: "ℹ️ No active ports found or command failed (this is normal if nothing is listening)." }]
24
+ };
25
+ }
26
+ }
@@ -0,0 +1,19 @@
1
+ import os from "os";
2
+ /**
3
+ * Retrieves system health metrics including CPU load and memory usage.
4
+ */
5
+ export function handleGetSystemHealth(_projectRoot, _args) {
6
+ const totalMem = os.totalmem();
7
+ const freeMem = os.freemem();
8
+ const usedMem = totalMem - freeMem;
9
+ const memUsagePercent = ((usedMem / totalMem) * 100).toFixed(2);
10
+ const loadAvg = os.loadavg(); // [1, 5, 15] minute averages
11
+ const healthReport = `🖥️ **System Health Report**
12
+ - **Memory:** ${memUsagePercent}% used (${(usedMem / 1024 / 1024 / 1024).toFixed(2)} GB / ${(totalMem / 1024 / 1024 / 1024).toFixed(2)} GB)
13
+ - **CPU Load (1m, 5m, 15m):** ${loadAvg.map(l => l.toFixed(2)).join(", ")}
14
+ - **Platform:** ${os.platform()} (${os.release()})
15
+ - **Uptime:** ${(os.uptime() / 3600).toFixed(2)} hours`;
16
+ return {
17
+ content: [{ type: "text", text: healthReport }]
18
+ };
19
+ }
@@ -0,0 +1,28 @@
1
+ import { exec } from "child_process";
2
+ import { Metrics } from "../../utils/metrics.js";
3
+ const LINT_COMMAND = "npm run lint";
4
+ const TIMEOUT = 60000; // 60 seconds
5
+ /**
6
+ * Handles running the project's linter.
7
+ */
8
+ export function handleCheckLint(projectRoot, _args) {
9
+ return new Promise((resolve) => {
10
+ exec(LINT_COMMAND, { cwd: projectRoot, timeout: TIMEOUT }, (error, stdout, stderr) => {
11
+ const output = stdout + stderr;
12
+ const tokens = Metrics.estimateTokens(output);
13
+ if (error) {
14
+ const err = `Linting failed: ${error.message}`;
15
+ Metrics.logError(projectRoot, "@mcp", "check_lint", err);
16
+ resolve({
17
+ isError: true,
18
+ content: [{ type: "text", text: `❌ Lint Errors Found:\n\n${output}` }]
19
+ });
20
+ return;
21
+ }
22
+ Metrics.logUsage(projectRoot, "@mcp", "check_lint", tokens);
23
+ resolve({
24
+ content: [{ type: "text", text: `✅ Lint check passed successfully:\n\n${output}` }]
25
+ });
26
+ });
27
+ });
28
+ }
@@ -0,0 +1,48 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { safePath } from "../../utils/security.js";
4
+ /**
5
+ * Scans the codebase for TODOs, FIXMEs, and empty function bodies.
6
+ * Helps identify what's left and where the agent might have skipped logic.
7
+ */
8
+ export function handleGetProjectGaps(projectRoot, args) {
9
+ const srcDir = safePath(projectRoot, args.path || "src");
10
+ const results = [];
11
+ const walk = (dir) => {
12
+ if (!fs.existsSync(dir))
13
+ return;
14
+ const files = fs.readdirSync(dir);
15
+ for (const file of files) {
16
+ const fullPath = path.join(dir, file);
17
+ const relativePath = path.relative(projectRoot, fullPath);
18
+ if (fs.statSync(fullPath).isDirectory()) {
19
+ if (file !== "node_modules" && file !== "dist" && !file.startsWith(".")) {
20
+ walk(fullPath);
21
+ }
22
+ }
23
+ else if (file.endsWith(".ts") || file.endsWith(".tsx")) {
24
+ const content = fs.readFileSync(fullPath, "utf8");
25
+ const lines = content.split("\n");
26
+ lines.forEach((line, index) => {
27
+ // 1. Scan for markers
28
+ if (line.includes("TODO") || line.includes("FIXME") || line.includes("!!!")) {
29
+ results.push(`[${relativePath}:${index + 1}] Marker found: ${line.trim()}`);
30
+ }
31
+ // 2. Scan for empty function placeholders (heuristic)
32
+ if (line.includes("throw new Error(\"Not implemented") || line.includes("// ... rest of code")) {
33
+ results.push(`[${relativePath}:${index + 1}] Gap found: ${line.trim()}`);
34
+ }
35
+ });
36
+ }
37
+ }
38
+ };
39
+ walk(srcDir);
40
+ return {
41
+ content: [{
42
+ type: "text",
43
+ text: results.length > 0
44
+ ? `Found ${results.length} gaps/todos:\n\n${results.join("\n")}`
45
+ : "✅ No major gaps or TODOs found in the scanned directory."
46
+ }]
47
+ };
48
+ }
@@ -0,0 +1,43 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ /**
4
+ * Generates a tree-view map of the project structure.
5
+ * Helps agents visualize the entire project layout quickly.
6
+ */
7
+ export function handleGetProjectMap(projectRoot, args) {
8
+ const maxDepth = args.maxDepth || 3;
9
+ const includeFiles = args.includeFiles !== false;
10
+ const buildTree = (dir, depth) => {
11
+ if (depth > maxDepth)
12
+ return [];
13
+ const results = [];
14
+ const files = fs.readdirSync(dir);
15
+ files.forEach(file => {
16
+ if (file === "node_modules" || file === ".git" || file === "dist" || file.startsWith("."))
17
+ return;
18
+ const fullPath = path.join(dir, file);
19
+ const stat = fs.statSync(fullPath);
20
+ const indent = " ".repeat(depth);
21
+ if (stat.isDirectory()) {
22
+ results.push(`${indent}📁 ${file}/`);
23
+ results.push(...buildTree(fullPath, depth + 1));
24
+ }
25
+ else if (includeFiles) {
26
+ results.push(`${indent}📄 ${file}`);
27
+ }
28
+ });
29
+ return results;
30
+ };
31
+ try {
32
+ const tree = buildTree(projectRoot, 0);
33
+ return {
34
+ content: [{
35
+ type: "text",
36
+ text: `🗺️ **Project Map (Depth: ${maxDepth})**\n\n${tree.join("\n")}`
37
+ }]
38
+ };
39
+ }
40
+ catch (e) {
41
+ return { isError: true, content: [{ type: "text", text: `Failed to map project: ${String(e)}` }] };
42
+ }
43
+ }
@@ -0,0 +1,76 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { Metrics } from "../../utils/metrics.js";
4
+ /**
5
+ * Searches for a regex pattern within files in the project.
6
+ */
7
+ export function handleGrepSearch(projectRoot, args) {
8
+ const pattern = args.pattern;
9
+ const includePattern = args.includePattern || ""; // e.g., ".ts"
10
+ const excludePattern = args.excludePattern || "node_modules";
11
+ if (!pattern) {
12
+ const err = "Search pattern is required.";
13
+ Metrics.logError(projectRoot, "@mcp", "grep_search", err);
14
+ return { isError: true, content: [{ type: "text", text: `❌ ${err}` }] };
15
+ }
16
+ const results = [];
17
+ let regex;
18
+ try {
19
+ regex = new RegExp(pattern, "g");
20
+ }
21
+ catch (e) {
22
+ const err = `Invalid regex pattern: ${String(e)}`;
23
+ Metrics.logError(projectRoot, "@mcp", "grep_search", err);
24
+ return { isError: true, content: [{ type: "text", text: `❌ ${err}` }] };
25
+ }
26
+ const walk = (dir) => {
27
+ if (results.length > 100)
28
+ return;
29
+ try {
30
+ const files = fs.readdirSync(dir);
31
+ for (const file of files) {
32
+ if (results.length > 100)
33
+ return;
34
+ const filePath = path.join(dir, file);
35
+ if (excludePattern && filePath.includes(excludePattern)) {
36
+ continue;
37
+ }
38
+ const stat = fs.statSync(filePath);
39
+ if (stat.isDirectory()) {
40
+ walk(filePath);
41
+ }
42
+ else if (stat.isFile()) {
43
+ if (includePattern && !filePath.endsWith(includePattern)) {
44
+ continue;
45
+ }
46
+ const content = fs.readFileSync(filePath, "utf8");
47
+ // Create a new regex object for each line to avoid state issues with /g
48
+ if (new RegExp(pattern).test(content)) {
49
+ if (results.length < 100) {
50
+ results.push(filePath);
51
+ }
52
+ }
53
+ }
54
+ }
55
+ }
56
+ catch (e) {
57
+ // Ignore directories that cannot be read
58
+ }
59
+ };
60
+ try {
61
+ walk(projectRoot);
62
+ }
63
+ catch (e) {
64
+ const err = `Search failed: ${String(e)}`;
65
+ Metrics.logError(projectRoot, "@mcp", "grep_search", err);
66
+ return { isError: true, content: [{ type: "text", text: `❌ ${err}` }] };
67
+ }
68
+ return {
69
+ content: [{
70
+ type: "text",
71
+ text: results.length > 0
72
+ ? `Found ${results.length} matches:\n\n${results.join("\n")}`
73
+ : "No matches found."
74
+ }]
75
+ };
76
+ }
@@ -0,0 +1,28 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { safePath } from "../../utils/security.js";
4
+ /**
5
+ * Lists the contents of a directory.
6
+ */
7
+ export function handleListDir(projectRoot, args) {
8
+ const dirPath = safePath(projectRoot, args.path || ".");
9
+ if (!fs.existsSync(dirPath)) {
10
+ throw new Error(`Directory not found: ${args.path}`);
11
+ }
12
+ const stats = fs.statSync(dirPath);
13
+ if (!stats.isDirectory()) {
14
+ throw new Error(`Path is not a directory: ${args.path}`);
15
+ }
16
+ const files = fs.readdirSync(dirPath);
17
+ const results = files.map(file => {
18
+ const fullPath = path.join(dirPath, file);
19
+ const isDir = fs.statSync(fullPath).isDirectory();
20
+ return `${isDir ? "[DIR] " : " "}${file}`;
21
+ });
22
+ return {
23
+ content: [{
24
+ type: "text",
25
+ text: `Directory listing for ${args.path || "."}:\n\n${results.join("\n")}`
26
+ }]
27
+ };
28
+ }
@@ -0,0 +1,46 @@
1
+ import { exec } from "child_process";
2
+ import { Metrics } from "../../utils/metrics.js";
3
+ const COMMAND_ALLOW_LIST = [
4
+ "npm test",
5
+ "npm run lint",
6
+ "git status",
7
+ "git diff",
8
+ "npx vitest run", // From the audit, this is the test command
9
+ "npm run build", // From the audit
10
+ ];
11
+ const TIMEOUT = 30000; // 30 seconds
12
+ export function handleRunCommand(projectRoot, args) {
13
+ const command = args.command;
14
+ const isAllowed = COMMAND_ALLOW_LIST.some(allowedCmd => command.startsWith(allowedCmd));
15
+ if (!isAllowed) {
16
+ const errorMsg = `Command not allowed: "${command}". Only commands starting with the following are allowed: ${COMMAND_ALLOW_LIST.join(", ")}`;
17
+ Metrics.logError(projectRoot, "@mcp", `run_shell_command: ${command} (denied)`, errorMsg);
18
+ return Promise.resolve({
19
+ content: [{ type: "text", text: `ERROR: ${errorMsg}` }],
20
+ isError: true,
21
+ });
22
+ }
23
+ return new Promise((resolve) => {
24
+ exec(command, { cwd: projectRoot, timeout: TIMEOUT }, (error, stdout, stderr) => {
25
+ const output = stdout + stderr;
26
+ const tokens = Metrics.estimateTokens(output);
27
+ Metrics.logUsage(projectRoot, "@mcp", `run_shell_command: ${command}`, tokens);
28
+ if (error) {
29
+ const errorMsg = `Command failed with exit code ${error.code}: ${error.message}.`;
30
+ Metrics.logError(projectRoot, "@mcp", `run_shell_command: ${command}`, errorMsg);
31
+ resolve({
32
+ content: [{ type: "text", text: `ERROR: ${errorMsg}. Output: ${output}` }],
33
+ isError: true,
34
+ });
35
+ return;
36
+ }
37
+ // Truncate long outputs
38
+ const MAX_OUTPUT_LENGTH = 5000;
39
+ let truncatedOutput = output;
40
+ if (output.length > MAX_OUTPUT_LENGTH) {
41
+ truncatedOutput = output.substring(0, MAX_OUTPUT_LENGTH) + "... [TRUNCATED] ..."; // Simplified
42
+ }
43
+ resolve({ content: [{ type: "text", text: truncatedOutput }] });
44
+ });
45
+ });
46
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ import { execFileSync } from "child_process";
2
+ /**
3
+ * Executes a CLI command safely using execFileSync (no shell injection risk).
4
+ * Captures stderr gracefully to prevent stream crashes.
5
+ */
6
+ export function safeExec(command, args, cwd, timeout) {
7
+ try {
8
+ return execFileSync(command, args, {
9
+ cwd,
10
+ encoding: "utf8",
11
+ timeout: timeout || 30000,
12
+ maxBuffer: 1024 * 1024,
13
+ stdio: ["pipe", "pipe", "pipe"],
14
+ });
15
+ }
16
+ catch (error) {
17
+ const err = error;
18
+ throw new Error(err.stderr || err.message || "Command execution failed", { cause: error });
19
+ }
20
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Enterprise Compliance Guardrail
3
+ * Checks content against corporate standards before allowing file mutations.
4
+ */
5
+ export function verifyCorporateCompliance(content, filePath) {
6
+ // 1. Zero Console Policy
7
+ if (content.includes("console.log(") || content.includes("console.warn(") || content.includes("console.error(")) {
8
+ if (!filePath.includes("logger.ts") && !filePath.includes("check.ts") && !filePath.includes("cli.ts")) {
9
+ throw new Error("❌ Corporate Compliance Breach: 'console.log/warn/error' usage is forbidden. " +
10
+ "Use the 'logger' system from '@/shared/logger' instead.");
11
+ }
12
+ }
13
+ // 2. No Explicit Any Policy
14
+ const anyRegex = /[:<]\s*any\b|\bas\s+any\b/g;
15
+ if (anyRegex.test(content)) {
16
+ if (!filePath.includes("definitions.ts") && !filePath.includes("types.ts")) {
17
+ throw new Error("❌ Corporate Compliance Breach: 'any' type is forbidden. " +
18
+ "Use 'unknown', 'generics', or proper interfaces for type safety.");
19
+ }
20
+ }
21
+ // 3. Hardcoded Secrets Guard (Simple heuristic)
22
+ const secretKeywords = [/API_KEY\s*=\s*['"][^'"]+['"]/i, /SECRET\s*=\s*['"][^'"]+['"]/i, /PASSWORD\s*=\s*['"][^'"]+['"]/i];
23
+ for (const regex of secretKeywords) {
24
+ if (regex.test(content) && !filePath.endsWith(".env.example")) {
25
+ throw new Error("❌ Corporate Compliance Breach: Hardcoded secrets detected. " +
26
+ "All sensitive data must be managed via '.env' files.");
27
+ }
28
+ }
29
+ }