atabey 0.0.13 → 0.0.14

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 (271) hide show
  1. package/ATABEY.md +1 -1
  2. package/README.md +252 -52
  3. package/dist/framework-mcp/src/index.js +914 -62
  4. package/dist/framework-mcp/src/index.js.map +1 -1
  5. package/dist/framework-mcp/src/tools/compliance/mask_pii.d.ts +17 -0
  6. package/dist/framework-mcp/src/tools/compliance/mask_pii.js +56 -0
  7. package/dist/framework-mcp/src/tools/compliance/mask_pii.js.map +1 -0
  8. package/dist/framework-mcp/src/tools/definitions.js +10 -9
  9. package/dist/framework-mcp/src/tools/definitions.js.map +1 -1
  10. package/dist/framework-mcp/src/tools/framework/run_tests.js +25 -0
  11. package/dist/framework-mcp/src/tools/framework/run_tests.js.map +1 -1
  12. package/dist/framework-mcp/src/tools/index.js +7 -8
  13. package/dist/framework-mcp/src/tools/index.js.map +1 -1
  14. package/dist/framework-mcp/src/tools/messaging/approve_operation.d.ts +22 -0
  15. package/dist/framework-mcp/src/tools/messaging/approve_operation.js +81 -0
  16. package/dist/framework-mcp/src/tools/messaging/approve_operation.js.map +1 -0
  17. package/dist/framework-mcp/src/tools/messaging/ask_human.d.ts +15 -0
  18. package/dist/framework-mcp/src/tools/messaging/ask_human.js +89 -20
  19. package/dist/framework-mcp/src/tools/messaging/ask_human.js.map +1 -1
  20. package/dist/framework-mcp/src/tools/observability/check_ports.js +3 -1
  21. package/dist/framework-mcp/src/tools/observability/check_ports.js.map +1 -1
  22. package/dist/framework-mcp/src/tools/quality/analyze_code_quality.js +13 -64
  23. package/dist/framework-mcp/src/tools/quality/analyze_code_quality.js.map +1 -1
  24. package/dist/framework-mcp/src/tools/schemas.d.ts +48 -53
  25. package/dist/framework-mcp/src/tools/schemas.js +18 -22
  26. package/dist/framework-mcp/src/tools/schemas.js.map +1 -1
  27. package/dist/framework-mcp/src/tools/shell/run_command.js +10 -0
  28. package/dist/framework-mcp/src/tools/shell/run_command.js.map +1 -1
  29. package/dist/framework-mcp/src/tools/types.d.ts +11 -105
  30. package/dist/framework-mcp/src/tools/types.js +1 -0
  31. package/dist/framework-mcp/src/tools/types.js.map +1 -1
  32. package/dist/framework-mcp/src/utils/auth.d.ts +36 -0
  33. package/dist/framework-mcp/src/utils/auth.js +79 -0
  34. package/dist/framework-mcp/src/utils/auth.js.map +1 -0
  35. package/dist/framework-mcp/src/utils/auto-rollback.d.ts +71 -0
  36. package/dist/framework-mcp/src/utils/auto-rollback.js +266 -0
  37. package/dist/framework-mcp/src/utils/auto-rollback.js.map +1 -0
  38. package/dist/framework-mcp/src/utils/compliance.js +12 -4
  39. package/dist/framework-mcp/src/utils/compliance.js.map +1 -1
  40. package/dist/framework-mcp/src/utils/context-optimizer.d.ts +69 -0
  41. package/dist/framework-mcp/src/utils/context-optimizer.js +157 -0
  42. package/dist/framework-mcp/src/utils/context-optimizer.js.map +1 -0
  43. package/dist/framework-mcp/src/utils/discipline.d.ts +68 -0
  44. package/dist/framework-mcp/src/utils/discipline.js +218 -0
  45. package/dist/framework-mcp/src/utils/discipline.js.map +1 -0
  46. package/dist/framework-mcp/src/utils/finops.d.ts +143 -0
  47. package/dist/framework-mcp/src/utils/finops.js +326 -0
  48. package/dist/framework-mcp/src/utils/finops.js.map +1 -0
  49. package/dist/framework-mcp/src/utils/human-in-loop.d.ts +95 -0
  50. package/dist/framework-mcp/src/utils/human-in-loop.js +216 -0
  51. package/dist/framework-mcp/src/utils/human-in-loop.js.map +1 -0
  52. package/dist/framework-mcp/src/utils/license-scanner.d.ts +71 -0
  53. package/dist/framework-mcp/src/utils/license-scanner.js +284 -0
  54. package/dist/framework-mcp/src/utils/license-scanner.js.map +1 -0
  55. package/dist/framework-mcp/src/utils/loop-detector.d.ts +105 -0
  56. package/dist/framework-mcp/src/utils/loop-detector.js +362 -0
  57. package/dist/framework-mcp/src/utils/loop-detector.js.map +1 -0
  58. package/dist/framework-mcp/src/utils/quality.d.ts +19 -0
  59. package/dist/framework-mcp/src/utils/quality.js +124 -0
  60. package/dist/framework-mcp/src/utils/quality.js.map +1 -0
  61. package/dist/framework-mcp/src/utils/rules-engine.d.ts +78 -0
  62. package/dist/framework-mcp/src/utils/rules-engine.js +232 -0
  63. package/dist/framework-mcp/src/utils/rules-engine.js.map +1 -0
  64. package/dist/framework-mcp/src/utils/silent-router.d.ts +47 -0
  65. package/dist/framework-mcp/src/utils/silent-router.js +129 -0
  66. package/dist/framework-mcp/src/utils/silent-router.js.map +1 -0
  67. package/dist/framework-mcp/src/utils/storage.d.ts +1 -0
  68. package/dist/framework-mcp/src/utils/storage.js +2 -2
  69. package/dist/framework-mcp/src/utils/storage.js.map +1 -1
  70. package/dist/framework-mcp/src/utils/telemetry-streamer.d.ts +133 -0
  71. package/dist/framework-mcp/src/utils/telemetry-streamer.js +397 -0
  72. package/dist/framework-mcp/src/utils/telemetry-streamer.js.map +1 -0
  73. package/dist/framework-mcp/tests/tools/file_system/file_system_tools.test.js +2 -2
  74. package/dist/framework-mcp/tests/tools/file_system/file_system_tools.test.js.map +1 -1
  75. package/dist/framework-mcp/tests/tools/framework/run_tests.test.d.ts +1 -0
  76. package/dist/framework-mcp/tests/tools/framework/run_tests.test.js +49 -0
  77. package/dist/framework-mcp/tests/tools/framework/run_tests.test.js.map +1 -0
  78. package/dist/framework-mcp/tests/tools/messaging/send_message.test.js +14 -5
  79. package/dist/framework-mcp/tests/tools/messaging/send_message.test.js.map +1 -1
  80. package/dist/framework-mcp/tests/tools/observability/check_ports.test.d.ts +1 -0
  81. package/dist/framework-mcp/tests/tools/observability/check_ports.test.js +30 -0
  82. package/dist/framework-mcp/tests/tools/observability/check_ports.test.js.map +1 -0
  83. package/dist/framework-mcp/tests/tools/shell/run_command.test.js +7 -0
  84. package/dist/framework-mcp/tests/tools/shell/run_command.test.js.map +1 -1
  85. package/dist/framework-mcp/tests/utils/auto-rollback.test.d.ts +7 -0
  86. package/dist/framework-mcp/tests/utils/auto-rollback.test.js +178 -0
  87. package/dist/framework-mcp/tests/utils/auto-rollback.test.js.map +1 -0
  88. package/dist/framework-mcp/tests/utils/context-optimizer.test.d.ts +1 -0
  89. package/dist/framework-mcp/tests/utils/context-optimizer.test.js +62 -0
  90. package/dist/framework-mcp/tests/utils/context-optimizer.test.js.map +1 -0
  91. package/dist/framework-mcp/tests/utils/finops.test.d.ts +7 -0
  92. package/dist/framework-mcp/tests/utils/finops.test.js +157 -0
  93. package/dist/framework-mcp/tests/utils/finops.test.js.map +1 -0
  94. package/dist/framework-mcp/tests/utils/human-in-loop.test.d.ts +1 -0
  95. package/dist/framework-mcp/tests/utils/human-in-loop.test.js +59 -0
  96. package/dist/framework-mcp/tests/utils/human-in-loop.test.js.map +1 -0
  97. package/dist/framework-mcp/tests/utils/license-scanner.test.d.ts +7 -0
  98. package/dist/framework-mcp/tests/utils/license-scanner.test.js +131 -0
  99. package/dist/framework-mcp/tests/utils/license-scanner.test.js.map +1 -0
  100. package/dist/framework-mcp/tests/utils/loop-detector.test.d.ts +7 -0
  101. package/dist/framework-mcp/tests/utils/loop-detector.test.js +204 -0
  102. package/dist/framework-mcp/tests/utils/loop-detector.test.js.map +1 -0
  103. package/dist/framework-mcp/tests/utils/rules-engine.test.d.ts +1 -0
  104. package/dist/framework-mcp/tests/utils/rules-engine.test.js +106 -0
  105. package/dist/framework-mcp/tests/utils/rules-engine.test.js.map +1 -0
  106. package/dist/framework-mcp/tests/utils/telemetry-streamer.test.d.ts +7 -0
  107. package/dist/framework-mcp/tests/utils/telemetry-streamer.test.js +201 -0
  108. package/dist/framework-mcp/tests/utils/telemetry-streamer.test.js.map +1 -0
  109. package/dist/src/cli/commands/check.js +16 -1
  110. package/dist/src/cli/commands/check.js.map +1 -1
  111. package/dist/src/cli/commands/dashboard.js +188 -164
  112. package/dist/src/cli/commands/dashboard.js.map +1 -1
  113. package/dist/src/cli/commands/gateway.js +2 -2
  114. package/dist/src/cli/commands/gateway.js.map +1 -1
  115. package/dist/src/cli/commands/init/scaffold-core.d.ts +2 -0
  116. package/dist/src/cli/commands/init/scaffold-core.js +16 -1
  117. package/dist/src/cli/commands/init/scaffold-core.js.map +1 -1
  118. package/dist/src/cli/commands/init/scaffold-ops.js +2 -2
  119. package/dist/src/cli/commands/init/scaffold-ops.js.map +1 -1
  120. package/dist/src/cli/commands/init/scaffold-standards.js +13 -1
  121. package/dist/src/cli/commands/init/scaffold-standards.js.map +1 -1
  122. package/dist/src/cli/commands/init.d.ts +4 -0
  123. package/dist/src/cli/commands/init.js +80 -24
  124. package/dist/src/cli/commands/init.js.map +1 -1
  125. package/dist/src/cli/commands/quickstart.d.ts +1 -1
  126. package/dist/src/cli/commands/quickstart.js +12 -24
  127. package/dist/src/cli/commands/quickstart.js.map +1 -1
  128. package/dist/src/cli/index.js +24 -23
  129. package/dist/src/cli/index.js.map +1 -1
  130. package/dist/src/cli/shims.js +7 -7
  131. package/dist/src/cli/utils/pkg.js +2 -3
  132. package/dist/src/cli/utils/pkg.js.map +1 -1
  133. package/dist/src/cli/utils/quality.d.ts +10 -0
  134. package/dist/src/cli/utils/quality.js +10 -0
  135. package/dist/src/cli/utils/quality.js.map +1 -0
  136. package/dist/src/modules/agents/definitions.js +45 -40
  137. package/dist/src/modules/agents/definitions.js.map +1 -1
  138. package/dist/src/modules/agents/registry/manager.js +6 -1
  139. package/dist/src/modules/agents/registry/manager.js.map +1 -1
  140. package/dist/src/modules/engines/agent-executor.d.ts +6 -10
  141. package/dist/src/modules/engines/agent-executor.js +53 -21
  142. package/dist/src/modules/engines/agent-executor.js.map +1 -1
  143. package/dist/src/modules/engines/agent-loop.d.ts +34 -0
  144. package/dist/src/modules/engines/agent-loop.js +102 -0
  145. package/dist/src/modules/engines/agent-loop.js.map +1 -0
  146. package/dist/src/modules/engines/evaluation-engine.js +2 -2
  147. package/dist/src/modules/engines/evaluation-engine.js.map +1 -1
  148. package/dist/src/modules/engines/quality-gate.d.ts +13 -5
  149. package/dist/src/modules/engines/quality-gate.js +39 -31
  150. package/dist/src/modules/engines/quality-gate.js.map +1 -1
  151. package/dist/src/modules/engines/routing-engine.d.ts +5 -3
  152. package/dist/src/modules/engines/routing-engine.js +16 -9
  153. package/dist/src/modules/engines/routing-engine.js.map +1 -1
  154. package/dist/src/modules/gateway/cost-tracker.d.ts +5 -0
  155. package/dist/src/modules/gateway/cost-tracker.js +71 -0
  156. package/dist/src/modules/gateway/cost-tracker.js.map +1 -1
  157. package/dist/src/modules/gateway/gateway.d.ts +4 -0
  158. package/dist/src/modules/gateway/gateway.js +8 -0
  159. package/dist/src/modules/gateway/gateway.js.map +1 -1
  160. package/dist/src/shared/audit.js +3 -2
  161. package/dist/src/shared/audit.js.map +1 -1
  162. package/dist/src/shared/pii.d.ts +41 -9
  163. package/dist/src/shared/pii.js +122 -31
  164. package/dist/src/shared/pii.js.map +1 -1
  165. package/dist/src/shared/storage.d.ts +19 -0
  166. package/dist/src/shared/storage.js +46 -6
  167. package/dist/src/shared/storage.js.map +1 -1
  168. package/dist/tests/embedding.test.d.ts +1 -0
  169. package/dist/tests/embedding.test.js +82 -0
  170. package/dist/tests/embedding.test.js.map +1 -0
  171. package/dist/tests/engines/evaluation-engine.test.d.ts +1 -0
  172. package/dist/tests/engines/evaluation-engine.test.js +71 -0
  173. package/dist/tests/engines/evaluation-engine.test.js.map +1 -0
  174. package/dist/tests/engines/planning-engine.test.d.ts +1 -0
  175. package/dist/tests/engines/planning-engine.test.js +100 -0
  176. package/dist/tests/engines/planning-engine.test.js.map +1 -0
  177. package/dist/tests/engines/quality-gate.test.d.ts +1 -0
  178. package/dist/tests/engines/quality-gate.test.js +59 -0
  179. package/dist/tests/engines/quality-gate.test.js.map +1 -0
  180. package/dist/tests/engines/risk-engine.test.d.ts +1 -0
  181. package/dist/tests/engines/risk-engine.test.js +80 -0
  182. package/dist/tests/engines/risk-engine.test.js.map +1 -0
  183. package/dist/tests/engines/routing-engine.test.d.ts +1 -0
  184. package/dist/tests/engines/routing-engine.test.js +78 -0
  185. package/dist/tests/engines/routing-engine.test.js.map +1 -0
  186. package/dist/tests/integration/hermes_locking.test.js +1 -0
  187. package/dist/tests/integration/hermes_locking.test.js.map +1 -1
  188. package/dist/tests/modules/gateway/cost-tracker.test.js +20 -1
  189. package/dist/tests/modules/gateway/cost-tracker.test.js.map +1 -1
  190. package/dist/tests/shared/lock.test.d.ts +1 -0
  191. package/dist/tests/shared/lock.test.js +95 -0
  192. package/dist/tests/shared/lock.test.js.map +1 -0
  193. package/dist/tests/shared/pii.test.d.ts +1 -0
  194. package/dist/tests/shared/pii.test.js +183 -0
  195. package/dist/tests/shared/pii.test.js.map +1 -0
  196. package/framework-mcp/README.md +307 -35
  197. package/framework-mcp/dist/dashboard/assets/index-B2mYld0c.js +1221 -0
  198. package/framework-mcp/dist/dashboard/index.html +1 -1
  199. package/framework-mcp/dist/framework-mcp/src/index.js +914 -62
  200. package/framework-mcp/dist/framework-mcp/src/tools/compliance/mask_pii.js +55 -0
  201. package/framework-mcp/dist/framework-mcp/src/tools/definitions.js +10 -9
  202. package/framework-mcp/dist/framework-mcp/src/tools/framework/run_tests.js +25 -0
  203. package/framework-mcp/dist/framework-mcp/src/tools/index.js +7 -8
  204. package/framework-mcp/dist/framework-mcp/src/tools/messaging/approve_operation.js +80 -0
  205. package/framework-mcp/dist/framework-mcp/src/tools/messaging/ask_human.js +89 -20
  206. package/framework-mcp/dist/framework-mcp/src/tools/observability/check_ports.js +3 -1
  207. package/framework-mcp/dist/framework-mcp/src/tools/quality/analyze_code_quality.js +13 -64
  208. package/framework-mcp/dist/framework-mcp/src/tools/schemas.js +18 -22
  209. package/framework-mcp/dist/framework-mcp/src/tools/shell/run_command.js +10 -0
  210. package/framework-mcp/dist/framework-mcp/src/tools/types.js +1 -0
  211. package/framework-mcp/dist/framework-mcp/src/utils/auth.js +78 -0
  212. package/framework-mcp/dist/framework-mcp/src/utils/auto-rollback.js +265 -0
  213. package/framework-mcp/dist/framework-mcp/src/utils/compliance.js +12 -4
  214. package/framework-mcp/dist/framework-mcp/src/utils/context-optimizer.js +156 -0
  215. package/framework-mcp/dist/framework-mcp/src/utils/discipline.js +217 -0
  216. package/framework-mcp/dist/framework-mcp/src/utils/finops.js +325 -0
  217. package/framework-mcp/dist/framework-mcp/src/utils/human-in-loop.js +215 -0
  218. package/framework-mcp/dist/framework-mcp/src/utils/license-scanner.js +283 -0
  219. package/framework-mcp/dist/framework-mcp/src/utils/loop-detector.js +361 -0
  220. package/framework-mcp/dist/framework-mcp/src/utils/quality.js +123 -0
  221. package/framework-mcp/dist/framework-mcp/src/utils/rules-engine.js +231 -0
  222. package/framework-mcp/dist/framework-mcp/src/utils/silent-router.js +128 -0
  223. package/framework-mcp/dist/framework-mcp/src/utils/storage.js +2 -2
  224. package/framework-mcp/dist/framework-mcp/src/utils/telemetry-streamer.js +396 -0
  225. package/framework-mcp/dist/src/cli/platforms/core.js +72 -0
  226. package/framework-mcp/dist/src/cli/platforms/index.js +5 -0
  227. package/framework-mcp/dist/src/cli/platforms/paths.js +101 -0
  228. package/framework-mcp/dist/src/cli/platforms/scaffold.js +72 -0
  229. package/framework-mcp/dist/src/cli/platforms/utils.js +75 -0
  230. package/framework-mcp/dist/src/cli/utils/claude.js +57 -0
  231. package/framework-mcp/dist/src/cli/utils/compliance.js +12 -0
  232. package/framework-mcp/dist/src/cli/utils/fs.js +138 -0
  233. package/framework-mcp/dist/src/cli/utils/pkg.js +282 -0
  234. package/framework-mcp/dist/src/cli/utils/quality.js +9 -0
  235. package/framework-mcp/dist/src/modules/agents/definitions.js +563 -0
  236. package/framework-mcp/dist/src/modules/agents/registry/analyst.js +39 -0
  237. package/framework-mcp/dist/src/modules/agents/registry/architect.js +42 -0
  238. package/framework-mcp/dist/src/modules/agents/registry/backend.js +50 -0
  239. package/framework-mcp/dist/src/modules/agents/registry/database.js +45 -0
  240. package/framework-mcp/dist/src/modules/agents/registry/devops.js +45 -0
  241. package/framework-mcp/dist/src/modules/agents/registry/explorer.js +37 -0
  242. package/framework-mcp/dist/src/modules/agents/registry/frontend.js +52 -0
  243. package/framework-mcp/dist/src/modules/agents/registry/git.js +36 -0
  244. package/framework-mcp/dist/src/modules/agents/registry/manager.js +64 -0
  245. package/framework-mcp/dist/src/modules/agents/registry/mobile.js +41 -0
  246. package/framework-mcp/dist/src/modules/agents/registry/native.js +41 -0
  247. package/framework-mcp/dist/src/modules/agents/registry/quality.js +43 -0
  248. package/framework-mcp/dist/src/modules/agents/registry/security.js +42 -0
  249. package/framework-mcp/dist/src/modules/agents/types.js +1 -0
  250. package/framework-mcp/dist/src/modules/engines/quality-gate.js +92 -0
  251. package/framework-mcp/dist/src/modules/engines/risk-engine.js +105 -0
  252. package/framework-mcp/dist/src/modules/engines/routing-engine.js +408 -0
  253. package/framework-mcp/dist/src/modules/engines/types.js +1 -0
  254. package/framework-mcp/dist/src/modules/providers/definitions.js +140 -0
  255. package/framework-mcp/dist/src/modules/providers/registry.js +18 -0
  256. package/framework-mcp/dist/src/modules/providers/shared.js +104 -0
  257. package/framework-mcp/dist/src/modules/providers/types.js +1 -0
  258. package/framework-mcp/dist/src/modules/skills/adapter-skills.js +449 -0
  259. package/framework-mcp/dist/src/modules/skills/definitions.js +70 -0
  260. package/framework-mcp/dist/src/shared/audit.js +220 -0
  261. package/framework-mcp/dist/src/shared/errors.js +68 -0
  262. package/framework-mcp/dist/src/shared/lock.js +159 -0
  263. package/framework-mcp/dist/src/shared/pii.js +122 -31
  264. package/framework-mcp/dist/src/shared/retention.js +170 -0
  265. package/framework-mcp/dist/src/shared/storage.js +46 -6
  266. package/framework-mcp/dist/src/shared/string.js +29 -0
  267. package/framework-mcp/package.json +8 -2
  268. package/mcp.json +11 -6
  269. package/package.json +13 -6
  270. package/templates/full/ATABEY_FULL.md +1 -1
  271. package/framework-mcp/dist/dashboard/assets/index-BAPGLiWE.js +0 -267
@@ -0,0 +1,361 @@
1
+ /**
2
+ * ─── LOOP DETECTOR ─────────────────────────────────────────────────
3
+ *
4
+ * Detects and prevents AI agents from entering infinite loops.
5
+ * Monitors call patterns across time, file paths, and tools.
6
+ *
7
+ * Detection Patterns:
8
+ * 1. **Consecutive Same Tool** – Same tool called N times in a row
9
+ * 2. **File Churn** – Same file written/read repeatedly
10
+ * 3. **Oscillation** – A → B → A → B alternating pattern
11
+ * 4. **Time-based Throttle** – Too many calls in a short window
12
+ * 5. **Semantic Similarity** – Similar arguments repeated (e.g., same error fix loop)
13
+ * 6. **Content Identity** – Same content being written repeatedly
14
+ *
15
+ * Action:
16
+ * - Cooldown: Block agent for N seconds
17
+ * - Escalate: Notify dashboard/human if loop persists
18
+ * - Kill: Force-stop the agent session
19
+ *
20
+ * Environment Variables:
21
+ * MCP_LOOP_MAX_CONSECUTIVE - Max same tool calls (default: 10)
22
+ * MCP_LOOP_MAX_FILE_CHURN - Max writes to same file (default: 5)
23
+ * MCP_LOOP_COOLDOWN_MS - Cooldown duration (default: 30000)
24
+ * MCP_LOOP_OSCILLATION_WINDOW - Oscillation detection window (default: 6)
25
+ */
26
+ import path from "path";
27
+ // ─── Configuration ────────────────────────────────────────────────
28
+ const CONFIG = {
29
+ /** Max consecutive same tool calls before action */
30
+ MAX_CONSECUTIVE: parseInt(process.env.MCP_LOOP_MAX_CONSECUTIVE || "10", 10),
31
+ /** Max writes to the same file before action */
32
+ MAX_FILE_CHURN: parseInt(process.env.MCP_LOOP_MAX_FILE_CHURN || "5", 10),
33
+ /** Max reads of the same file before action */
34
+ MAX_FILE_READ_CHURN: parseInt(process.env.MCP_LOOP_MAX_FILE_READ_CHURN || "10", 10),
35
+ /** Oscillation pattern window (min calls to detect A→B→A→B) */
36
+ OSCILLATION_WINDOW: parseInt(process.env.MCP_LOOP_OSCILLATION_WINDOW || "6", 10),
37
+ /** Cooldown duration in ms */
38
+ COOLDOWN_MS: parseInt(process.env.MCP_LOOP_COOLDOWN_MS || "30000", 10),
39
+ /** Max calls to any tool in sliding window */
40
+ MAX_CALLS_IN_WINDOW: parseInt(process.env.MCP_LOOP_MAX_CALLS_IN_WINDOW || "50", 10),
41
+ /** Sliding window size in ms */
42
+ WINDOW_SIZE_MS: parseInt(process.env.MCP_LOOP_WINDOW_MS || "60000", 10),
43
+ /** Enable/disable loop detector */
44
+ ENABLED: process.env.MCP_LOOP_DETECTION !== "false",
45
+ };
46
+ const agentHistories = new Map();
47
+ // ─── Loop Detector ────────────────────────────────────────────────
48
+ /**
49
+ * Get or create agent history.
50
+ */
51
+ function getOrCreateHistory(agent) {
52
+ if (!agentHistories.has(agent)) {
53
+ agentHistories.set(agent, {
54
+ calls: [],
55
+ consecutiveToolCalls: new Map(),
56
+ fileWriteCount: new Map(),
57
+ fileReadCount: new Map(),
58
+ lastContentHashes: [],
59
+ inCooldown: false,
60
+ cooldownUntil: 0,
61
+ cooldownCount: 0,
62
+ lastAlert: null,
63
+ });
64
+ }
65
+ return agentHistories.get(agent);
66
+ }
67
+ /**
68
+ * Prune old calls from history.
69
+ */
70
+ function pruneOldCalls(history) {
71
+ const cutoff = Date.now() - CONFIG.WINDOW_SIZE_MS;
72
+ history.calls = history.calls.filter(c => c.timestamp > cutoff);
73
+ }
74
+ /**
75
+ * Extract file path from tool args if applicable.
76
+ */
77
+ function extractFilePath(toolName, args) {
78
+ if (["write_file", "read_file", "replace_text", "patch_file", "batch_surgical_edit"].includes(toolName)) {
79
+ return args.path || args.filePath || undefined;
80
+ }
81
+ return undefined;
82
+ }
83
+ /**
84
+ * Compute a simple content hash for identity detection.
85
+ */
86
+ function computeContentHash(args) {
87
+ if (args.content && typeof args.content === "string") {
88
+ // Use first 100 chars as hash (fast, good enough for identity)
89
+ return args.content.substring(0, 100);
90
+ }
91
+ return undefined;
92
+ }
93
+ /**
94
+ * Check for oscillation pattern (A → B → A → B).
95
+ */
96
+ function detectOscillation(history, currentTool) {
97
+ const recent = history.calls.slice(-CONFIG.OSCILLATION_WINDOW);
98
+ if (recent.length < 4)
99
+ return false;
100
+ const recentToolNames = [...recent.map(c => c.toolName), currentTool];
101
+ // Check alternating pattern: tool[0] === tool[2] === tool[4] && tool[1] === tool[3] === tool[5]
102
+ if (recentToolNames.length >= 4) {
103
+ if (recentToolNames[0] === recentToolNames[2] &&
104
+ recentToolNames[1] === recentToolNames[3] &&
105
+ recentToolNames[0] !== recentToolNames[1]) {
106
+ // Check if pattern extends to 6
107
+ if (recentToolNames.length >= 6) {
108
+ return recentToolNames[0] === recentToolNames[4] && recentToolNames[1] === recentToolNames[5];
109
+ }
110
+ return true;
111
+ }
112
+ }
113
+ return false;
114
+ }
115
+ /**
116
+ * Detect if same content is being written repeatedly.
117
+ */
118
+ function detectContentIdentity(history, contentHash) {
119
+ if (!contentHash)
120
+ return false;
121
+ const recentHashes = history.lastContentHashes.slice(-5);
122
+ if (recentHashes.length < 3)
123
+ return false;
124
+ // Check if this hash appears 3+ times in last 5
125
+ const hashCount = recentHashes.filter(h => h === contentHash).length;
126
+ if (contentHash === recentHashes[recentHashes.length - 1]) {
127
+ // Count including current
128
+ return hashCount + 1 >= 3;
129
+ }
130
+ return false;
131
+ }
132
+ /**
133
+ * Record a tool call and check for loop patterns.
134
+ * Returns LoopAlert if a loop pattern is detected, null otherwise.
135
+ */
136
+ export function recordAndCheck(agent, toolName, args) {
137
+ if (!CONFIG.ENABLED)
138
+ return null;
139
+ const history = getOrCreateHistory(agent);
140
+ // Check cooldown
141
+ if (history.inCooldown) {
142
+ if (Date.now() < history.cooldownUntil) {
143
+ return {
144
+ type: "rate_limit",
145
+ severity: "critical",
146
+ agent,
147
+ detail: `Agent "${agent}" is in cooldown for ${Math.ceil((history.cooldownUntil - Date.now()) / 1000)}s. Loop detected earlier.`,
148
+ timestamp: Date.now(),
149
+ cooldownUntil: history.cooldownUntil,
150
+ };
151
+ }
152
+ else {
153
+ history.inCooldown = false;
154
+ }
155
+ }
156
+ const filePath = extractFilePath(toolName, args);
157
+ const contentHash = computeContentHash(args);
158
+ const record = {
159
+ agent,
160
+ toolName,
161
+ args,
162
+ timestamp: Date.now(),
163
+ filePath,
164
+ contentHash,
165
+ };
166
+ // Prune old calls
167
+ pruneOldCalls(history);
168
+ // Check 1: Consecutive same tool
169
+ const currentConsecutive = (history.consecutiveToolCalls.get(toolName) || 0) + 1;
170
+ history.consecutiveToolCalls.set(toolName, currentConsecutive);
171
+ // Reset other tools
172
+ for (const [tool] of history.consecutiveToolCalls) {
173
+ if (tool !== toolName) {
174
+ history.consecutiveToolCalls.set(tool, 0);
175
+ }
176
+ }
177
+ if (currentConsecutive >= CONFIG.MAX_CONSECUTIVE) {
178
+ const alert = {
179
+ type: "consecutive_same_tool",
180
+ severity: "critical",
181
+ agent,
182
+ detail: `Agent "${agent}" called "${toolName}" ${currentConsecutive} times consecutively. Possible infinite loop.`,
183
+ timestamp: Date.now(),
184
+ cooldownUntil: Date.now() + CONFIG.COOLDOWN_MS,
185
+ };
186
+ applyCooldown(history, alert, agent);
187
+ return alert;
188
+ }
189
+ // Check 2: File churn (for write operations)
190
+ if (filePath) {
191
+ if (["write_file", "replace_text", "patch_file", "batch_surgical_edit"].includes(toolName)) {
192
+ const writeCount = (history.fileWriteCount.get(filePath) || 0) + 1;
193
+ history.fileWriteCount.set(filePath, writeCount);
194
+ if (writeCount >= CONFIG.MAX_FILE_CHURN) {
195
+ const alert = {
196
+ type: "file_churn",
197
+ severity: "critical",
198
+ agent,
199
+ detail: `Agent "${agent}" wrote to "${path.relative(process.cwd(), filePath)}" ${writeCount} times. Possible file churn loop.`,
200
+ timestamp: Date.now(),
201
+ cooldownUntil: Date.now() + CONFIG.COOLDOWN_MS,
202
+ };
203
+ applyCooldown(history, alert, agent);
204
+ return alert;
205
+ }
206
+ }
207
+ if (toolName === "read_file") {
208
+ const readCount = (history.fileReadCount.get(filePath) || 0) + 1;
209
+ history.fileReadCount.set(filePath, readCount);
210
+ if (readCount >= CONFIG.MAX_FILE_READ_CHURN) {
211
+ const alert = {
212
+ type: "file_churn",
213
+ severity: "warning",
214
+ agent,
215
+ detail: `Agent "${agent}" read "${path.relative(process.cwd(), filePath)}" ${readCount} times. Possible read loop.`,
216
+ timestamp: Date.now(),
217
+ cooldownUntil: null,
218
+ };
219
+ history.lastAlert = alert;
220
+ return alert;
221
+ }
222
+ }
223
+ }
224
+ // Check 3: Oscillation pattern
225
+ if (detectOscillation(history, toolName)) {
226
+ const alert = {
227
+ type: "oscillation",
228
+ severity: "critical",
229
+ agent,
230
+ detail: `Agent "${agent}" is oscillating between tools. Pattern detected in last ${CONFIG.OSCILLATION_WINDOW} calls.`,
231
+ timestamp: Date.now(),
232
+ cooldownUntil: Date.now() + CONFIG.COOLDOWN_MS,
233
+ };
234
+ applyCooldown(history, alert, agent);
235
+ return alert;
236
+ }
237
+ // Check 4: Rate limit (calls in sliding window)
238
+ if (history.calls.length >= CONFIG.MAX_CALLS_IN_WINDOW) {
239
+ const alert = {
240
+ type: "rate_limit",
241
+ severity: "critical",
242
+ agent,
243
+ detail: `Agent "${agent}" made ${history.calls.length} calls in ${CONFIG.WINDOW_SIZE_MS / 1000}s window. Rate limit exceeded.`,
244
+ timestamp: Date.now(),
245
+ cooldownUntil: Date.now() + CONFIG.COOLDOWN_MS,
246
+ };
247
+ applyCooldown(history, alert, agent);
248
+ return alert;
249
+ }
250
+ // Check 5: Content identity (writing same content)
251
+ if (contentHash && detectContentIdentity(history, contentHash)) {
252
+ const alert = {
253
+ type: "content_identity",
254
+ severity: "critical",
255
+ agent,
256
+ detail: `Agent "${agent}" is writing the same content repeatedly. Possible fix-attempt loop.`,
257
+ timestamp: Date.now(),
258
+ cooldownUntil: Date.now() + CONFIG.COOLDOWN_MS,
259
+ };
260
+ applyCooldown(history, alert, agent);
261
+ return alert;
262
+ }
263
+ // If no detection, record the call
264
+ history.calls.push(record);
265
+ // Track content hashes for identity detection
266
+ if (contentHash) {
267
+ history.lastContentHashes.push(contentHash);
268
+ if (history.lastContentHashes.length > 10) {
269
+ history.lastContentHashes.shift();
270
+ }
271
+ }
272
+ return null;
273
+ }
274
+ /**
275
+ * Apply cooldown to an agent.
276
+ */
277
+ function applyCooldown(history, alert, agent) {
278
+ history.inCooldown = true;
279
+ history.cooldownUntil = alert.cooldownUntil || Date.now() + CONFIG.COOLDOWN_MS;
280
+ history.cooldownCount++;
281
+ history.lastAlert = alert;
282
+ process.stderr.write(`[LOOP DETECT] ${alert.type}: ${alert.detail}\n`);
283
+ }
284
+ /**
285
+ * Check if an agent is currently in cooldown.
286
+ */
287
+ export function isInCooldown(agent) {
288
+ const history = agentHistories.get(agent);
289
+ if (!history || !history.inCooldown) {
290
+ return { inCooldown: false, remainingMs: 0, reason: null };
291
+ }
292
+ const remaining = history.cooldownUntil - Date.now();
293
+ if (remaining <= 0) {
294
+ history.inCooldown = false;
295
+ return { inCooldown: false, remainingMs: 0, reason: null };
296
+ }
297
+ return {
298
+ inCooldown: true,
299
+ remainingMs: remaining,
300
+ reason: history.lastAlert?.detail || null,
301
+ };
302
+ }
303
+ /**
304
+ * Manually clear cooldown for an agent.
305
+ */
306
+ export function clearCooldown(agent) {
307
+ const history = agentHistories.get(agent);
308
+ if (history) {
309
+ history.inCooldown = false;
310
+ history.cooldownUntil = 0;
311
+ history.consecutiveToolCalls.clear();
312
+ return true;
313
+ }
314
+ return false;
315
+ }
316
+ /**
317
+ * Get loop detection stats for an agent.
318
+ */
319
+ export function getLoopStats(agent) {
320
+ const history = agentHistories.get(agent);
321
+ if (!history) {
322
+ return {
323
+ totalCalls: 0,
324
+ recentCalls: 0,
325
+ inCooldown: false,
326
+ cooldownCount: 0,
327
+ consecutiveTools: {},
328
+ fileWrites: {},
329
+ fileReads: {},
330
+ lastAlert: null,
331
+ };
332
+ }
333
+ pruneOldCalls(history);
334
+ return {
335
+ totalCalls: history.calls.length + history.cooldownCount * CONFIG.MAX_CALLS_IN_WINDOW,
336
+ recentCalls: history.calls.length,
337
+ inCooldown: history.inCooldown && Date.now() < history.cooldownUntil,
338
+ cooldownCount: history.cooldownCount,
339
+ consecutiveTools: Object.fromEntries(history.consecutiveToolCalls),
340
+ fileWrites: Object.fromEntries(history.fileWriteCount),
341
+ fileReads: Object.fromEntries(history.fileReadCount),
342
+ lastAlert: history.lastAlert,
343
+ };
344
+ }
345
+ /**
346
+ * Get all agents' loop stats.
347
+ */
348
+ export function getAllLoopStats() {
349
+ const stats = {};
350
+ for (const [agent] of agentHistories) {
351
+ stats[agent] = getLoopStats(agent);
352
+ }
353
+ return stats;
354
+ }
355
+ /**
356
+ * Reset all agent histories.
357
+ */
358
+ export function resetLoopDetection() {
359
+ agentHistories.clear();
360
+ }
361
+ export { CONFIG as LoopDetectorConfig };
@@ -0,0 +1,123 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ /**
4
+ * Shared Code Quality Heuristic Scanner
5
+ * Evaluates functions lengths, nesting depth, and usage of the forbidden 'any' type.
6
+ */
7
+ export function analyzePathQuality(projectRoot, targetPath) {
8
+ const absolutePath = path.resolve(projectRoot, targetPath);
9
+ const files = [];
10
+ function collectFilesSync(dir, exts) {
11
+ if (!fs.existsSync(dir))
12
+ return;
13
+ try {
14
+ const stat = fs.statSync(dir);
15
+ if (stat.isFile()) {
16
+ if (exts.some(ext => dir.endsWith(ext))) {
17
+ files.push(dir);
18
+ }
19
+ return;
20
+ }
21
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
22
+ for (const entry of entries) {
23
+ const fullPath = path.join(dir, entry.name);
24
+ if (entry.isDirectory() && !entry.name.startsWith("node_modules") && !entry.name.startsWith(".")) {
25
+ collectFilesSync(fullPath, exts);
26
+ }
27
+ else if (entry.isFile() && exts.some(ext => entry.name.endsWith(ext))) {
28
+ files.push(fullPath);
29
+ }
30
+ }
31
+ }
32
+ catch {
33
+ // Ignore errors reading files/dirs
34
+ }
35
+ }
36
+ collectFilesSync(absolutePath, [".ts", ".tsx"]);
37
+ const issues = [];
38
+ let longFunctions = 0;
39
+ let deepNesting = 0;
40
+ let anyTypes = 0;
41
+ files.forEach((f) => {
42
+ try {
43
+ const content = fs.readFileSync(f, "utf8");
44
+ const lines = content.split("\n");
45
+ const relativePath = path.relative(projectRoot, f);
46
+ // Check for `any` type
47
+ lines.forEach((line, idx) => {
48
+ if (line.trim().startsWith("//") || line.trim().startsWith("/*"))
49
+ return;
50
+ if (line.match(/\bany\b/) && !line.includes("// eslint-disable") && !line.includes("as any")) {
51
+ anyTypes++;
52
+ issues.push({
53
+ file: relativePath,
54
+ line: idx + 1,
55
+ type: "any-type",
56
+ message: `Line ${idx + 1}: Usage of 'any' type`
57
+ });
58
+ }
59
+ });
60
+ // Check for long functions
61
+ let inFunction = false;
62
+ let funcLines = 0;
63
+ let startLine = 0;
64
+ let funcName = "anonymous";
65
+ for (let i = 0; i < lines.length; i++) {
66
+ const line = lines[i];
67
+ // Detect function/method starts using regex
68
+ const funcMatch = line.match(/(?:public|private|protected|static\s+)?(?:async\s+)?(?:function\s+)?(\w+)\s*\([^)]*\)\s*{/);
69
+ const methodMatch = !funcMatch ? line.match(/^\s*(?:public|private|protected|static\s+)?(\w+)\s*\([^)]*\)\s*{/) : null;
70
+ const arrowMatch = !funcMatch && !methodMatch ? line.match(/(?:const|let|var)?\s*(\w+)?\s*=\s*(?:async\s*)?\([^)]*\)\s*=>\s*{/) : null;
71
+ if (funcMatch || methodMatch || arrowMatch) {
72
+ inFunction = true;
73
+ funcLines = 1;
74
+ startLine = i + 1;
75
+ funcName = (funcMatch?.[1] || methodMatch?.[1] || arrowMatch?.[1] || "anonymous").trim();
76
+ continue;
77
+ }
78
+ if (inFunction) {
79
+ funcLines++;
80
+ if (line.includes("}")) {
81
+ if (funcLines > 50) {
82
+ longFunctions++;
83
+ issues.push({
84
+ file: relativePath,
85
+ line: startLine,
86
+ type: "complexity",
87
+ message: `Function '${funcName}' is ${funcLines} lines long (max: 50)`
88
+ });
89
+ }
90
+ inFunction = false;
91
+ }
92
+ }
93
+ }
94
+ // Check nesting depth
95
+ lines.forEach((line, idx) => {
96
+ const indentMatch = line.match(/^(?:\s{2}){5,}/);
97
+ if (indentMatch && !line.trim().startsWith("//") && !line.trim().startsWith("*")) {
98
+ const depth = Math.floor(indentMatch[0].length / 2);
99
+ if (depth > 4) {
100
+ deepNesting++;
101
+ issues.push({
102
+ file: relativePath,
103
+ line: idx + 1,
104
+ type: "complexity",
105
+ message: `Line ${idx + 1}: Nesting depth ${depth}`
106
+ });
107
+ }
108
+ }
109
+ });
110
+ }
111
+ catch {
112
+ // Ignore files that can't be read
113
+ }
114
+ });
115
+ return {
116
+ totalFiles: files.length,
117
+ totalIssues: issues.length,
118
+ longFunctions,
119
+ deepNesting,
120
+ anyTypes,
121
+ issues
122
+ };
123
+ }