aicodeman 0.2.9 → 0.3.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 (374) hide show
  1. package/README.md +118 -4
  2. package/dist/ai-idle-checker.d.ts.map +1 -1
  3. package/dist/ai-idle-checker.js +3 -2
  4. package/dist/ai-idle-checker.js.map +1 -1
  5. package/dist/ai-plan-checker.d.ts.map +1 -1
  6. package/dist/ai-plan-checker.js +3 -2
  7. package/dist/ai-plan-checker.js.map +1 -1
  8. package/dist/bash-tool-parser.d.ts +2 -3
  9. package/dist/bash-tool-parser.d.ts.map +1 -1
  10. package/dist/bash-tool-parser.js +14 -31
  11. package/dist/bash-tool-parser.js.map +1 -1
  12. package/dist/config/ai-defaults.d.ts +16 -0
  13. package/dist/config/ai-defaults.d.ts.map +1 -0
  14. package/dist/config/ai-defaults.js +16 -0
  15. package/dist/config/ai-defaults.js.map +1 -0
  16. package/dist/config/auth-config.d.ts +19 -0
  17. package/dist/config/auth-config.d.ts.map +1 -0
  18. package/dist/config/auth-config.js +28 -0
  19. package/dist/config/auth-config.js.map +1 -0
  20. package/dist/config/exec-timeout.d.ts +10 -0
  21. package/dist/config/exec-timeout.d.ts.map +1 -0
  22. package/dist/config/exec-timeout.js +10 -0
  23. package/dist/config/exec-timeout.js.map +1 -0
  24. package/dist/config/map-limits.d.ts +4 -0
  25. package/dist/config/map-limits.d.ts.map +1 -1
  26. package/dist/config/map-limits.js +7 -0
  27. package/dist/config/map-limits.js.map +1 -1
  28. package/dist/config/server-timing.d.ts +42 -0
  29. package/dist/config/server-timing.d.ts.map +1 -0
  30. package/dist/config/server-timing.js +57 -0
  31. package/dist/config/server-timing.js.map +1 -0
  32. package/dist/config/team-config.d.ts +16 -0
  33. package/dist/config/team-config.d.ts.map +1 -0
  34. package/dist/config/team-config.js +16 -0
  35. package/dist/config/team-config.js.map +1 -0
  36. package/dist/config/terminal-limits.d.ts +18 -0
  37. package/dist/config/terminal-limits.d.ts.map +1 -0
  38. package/dist/config/terminal-limits.js +18 -0
  39. package/dist/config/terminal-limits.js.map +1 -0
  40. package/dist/config/tunnel-config.d.ts +27 -0
  41. package/dist/config/tunnel-config.d.ts.map +1 -0
  42. package/dist/config/tunnel-config.js +36 -0
  43. package/dist/config/tunnel-config.js.map +1 -0
  44. package/dist/hooks-config.d.ts +21 -6
  45. package/dist/hooks-config.d.ts.map +1 -1
  46. package/dist/hooks-config.js +28 -12
  47. package/dist/hooks-config.js.map +1 -1
  48. package/dist/image-watcher.d.ts +4 -4
  49. package/dist/image-watcher.d.ts.map +1 -1
  50. package/dist/image-watcher.js +17 -30
  51. package/dist/image-watcher.js.map +1 -1
  52. package/dist/index.js +1 -2
  53. package/dist/index.js.map +1 -1
  54. package/dist/plan-orchestrator.d.ts +2 -24
  55. package/dist/plan-orchestrator.d.ts.map +1 -1
  56. package/dist/plan-orchestrator.js.map +1 -1
  57. package/dist/prompts/planner.d.ts +7 -8
  58. package/dist/prompts/planner.d.ts.map +1 -1
  59. package/dist/prompts/planner.js +7 -8
  60. package/dist/prompts/planner.js.map +1 -1
  61. package/dist/prompts/research-agent.d.ts +6 -4
  62. package/dist/prompts/research-agent.d.ts.map +1 -1
  63. package/dist/prompts/research-agent.js +6 -4
  64. package/dist/prompts/research-agent.js.map +1 -1
  65. package/dist/push-store.d.ts +1 -1
  66. package/dist/push-store.d.ts.map +1 -1
  67. package/dist/push-store.js +4 -12
  68. package/dist/push-store.js.map +1 -1
  69. package/dist/ralph-fix-plan-watcher.d.ts +91 -0
  70. package/dist/ralph-fix-plan-watcher.d.ts.map +1 -0
  71. package/dist/ralph-fix-plan-watcher.js +326 -0
  72. package/dist/ralph-fix-plan-watcher.js.map +1 -0
  73. package/dist/ralph-loop.d.ts +14 -4
  74. package/dist/ralph-loop.d.ts.map +1 -1
  75. package/dist/ralph-loop.js +14 -4
  76. package/dist/ralph-loop.js.map +1 -1
  77. package/dist/ralph-plan-tracker.d.ts +201 -0
  78. package/dist/ralph-plan-tracker.d.ts.map +1 -0
  79. package/dist/ralph-plan-tracker.js +325 -0
  80. package/dist/ralph-plan-tracker.js.map +1 -0
  81. package/dist/ralph-stall-detector.d.ts +84 -0
  82. package/dist/ralph-stall-detector.d.ts.map +1 -0
  83. package/dist/ralph-stall-detector.js +139 -0
  84. package/dist/ralph-stall-detector.js.map +1 -0
  85. package/dist/ralph-status-parser.d.ts +141 -0
  86. package/dist/ralph-status-parser.d.ts.map +1 -0
  87. package/dist/ralph-status-parser.js +478 -0
  88. package/dist/ralph-status-parser.js.map +1 -0
  89. package/dist/ralph-tracker.d.ts +218 -692
  90. package/dist/ralph-tracker.d.ts.map +1 -1
  91. package/dist/ralph-tracker.js +389 -1723
  92. package/dist/ralph-tracker.js.map +1 -1
  93. package/dist/respawn-adaptive-timing.d.ts +61 -0
  94. package/dist/respawn-adaptive-timing.d.ts.map +1 -0
  95. package/dist/respawn-adaptive-timing.js +105 -0
  96. package/dist/respawn-adaptive-timing.js.map +1 -0
  97. package/dist/respawn-controller.d.ts +35 -115
  98. package/dist/respawn-controller.d.ts.map +1 -1
  99. package/dist/respawn-controller.js +167 -607
  100. package/dist/respawn-controller.js.map +1 -1
  101. package/dist/respawn-health.d.ts +54 -0
  102. package/dist/respawn-health.d.ts.map +1 -0
  103. package/dist/respawn-health.js +183 -0
  104. package/dist/respawn-health.js.map +1 -0
  105. package/dist/respawn-metrics.d.ts +81 -0
  106. package/dist/respawn-metrics.d.ts.map +1 -0
  107. package/dist/respawn-metrics.js +198 -0
  108. package/dist/respawn-metrics.js.map +1 -0
  109. package/dist/respawn-patterns.d.ts +45 -0
  110. package/dist/respawn-patterns.d.ts.map +1 -0
  111. package/dist/respawn-patterns.js +125 -0
  112. package/dist/respawn-patterns.js.map +1 -0
  113. package/dist/session-auto-ops.d.ts +89 -0
  114. package/dist/session-auto-ops.d.ts.map +1 -0
  115. package/dist/session-auto-ops.js +224 -0
  116. package/dist/session-auto-ops.js.map +1 -0
  117. package/dist/session-cli-builder.d.ts +62 -0
  118. package/dist/session-cli-builder.d.ts.map +1 -0
  119. package/dist/session-cli-builder.js +121 -0
  120. package/dist/session-cli-builder.js.map +1 -0
  121. package/dist/session-manager.d.ts +17 -5
  122. package/dist/session-manager.d.ts.map +1 -1
  123. package/dist/session-manager.js +17 -5
  124. package/dist/session-manager.js.map +1 -1
  125. package/dist/session-task-cache.d.ts +52 -0
  126. package/dist/session-task-cache.d.ts.map +1 -0
  127. package/dist/session-task-cache.js +90 -0
  128. package/dist/session-task-cache.js.map +1 -0
  129. package/dist/session.d.ts +23 -41
  130. package/dist/session.d.ts.map +1 -1
  131. package/dist/session.js +79 -317
  132. package/dist/session.js.map +1 -1
  133. package/dist/state-store.d.ts +19 -9
  134. package/dist/state-store.d.ts.map +1 -1
  135. package/dist/state-store.js +29 -30
  136. package/dist/state-store.js.map +1 -1
  137. package/dist/subagent-watcher.d.ts +26 -7
  138. package/dist/subagent-watcher.d.ts.map +1 -1
  139. package/dist/subagent-watcher.js +47 -64
  140. package/dist/subagent-watcher.js.map +1 -1
  141. package/dist/team-watcher.d.ts.map +1 -1
  142. package/dist/team-watcher.js +2 -5
  143. package/dist/team-watcher.js.map +1 -1
  144. package/dist/tmux-manager.d.ts.map +1 -1
  145. package/dist/tmux-manager.js +1 -2
  146. package/dist/tmux-manager.js.map +1 -1
  147. package/dist/tunnel-manager.d.ts +26 -0
  148. package/dist/tunnel-manager.d.ts.map +1 -1
  149. package/dist/tunnel-manager.js +126 -7
  150. package/dist/tunnel-manager.js.map +1 -1
  151. package/dist/types/api.d.ts +108 -0
  152. package/dist/types/api.d.ts.map +1 -0
  153. package/dist/types/api.js +98 -0
  154. package/dist/types/api.js.map +1 -0
  155. package/dist/types/app-state.d.ts +117 -0
  156. package/dist/types/app-state.d.ts.map +1 -0
  157. package/dist/types/app-state.js +76 -0
  158. package/dist/types/app-state.js.map +1 -0
  159. package/dist/types/common.d.ts +79 -0
  160. package/dist/types/common.d.ts.map +1 -0
  161. package/dist/types/common.js +17 -0
  162. package/dist/types/common.js.map +1 -0
  163. package/dist/types/index.d.ts +66 -0
  164. package/dist/types/index.d.ts.map +1 -0
  165. package/dist/types/index.js +66 -0
  166. package/dist/types/index.js.map +1 -0
  167. package/dist/types/lifecycle.d.ts +28 -0
  168. package/dist/types/lifecycle.d.ts.map +1 -0
  169. package/dist/types/lifecycle.js +16 -0
  170. package/dist/types/lifecycle.js.map +1 -0
  171. package/dist/types/plan.d.ts +45 -0
  172. package/dist/types/plan.d.ts.map +1 -0
  173. package/dist/types/plan.js +18 -0
  174. package/dist/types/plan.js.map +1 -0
  175. package/dist/types/push.d.ts +36 -0
  176. package/dist/types/push.d.ts.map +1 -0
  177. package/dist/types/push.js +18 -0
  178. package/dist/types/push.js.map +1 -0
  179. package/dist/types/ralph.d.ts +262 -0
  180. package/dist/types/ralph.d.ts.map +1 -0
  181. package/dist/types/ralph.js +70 -0
  182. package/dist/types/ralph.js.map +1 -0
  183. package/dist/types/respawn.d.ts +271 -0
  184. package/dist/types/respawn.d.ts.map +1 -0
  185. package/dist/types/respawn.js +26 -0
  186. package/dist/types/respawn.js.map +1 -0
  187. package/dist/types/run-summary.d.ts +96 -0
  188. package/dist/types/run-summary.d.ts.map +1 -0
  189. package/dist/types/run-summary.js +37 -0
  190. package/dist/types/run-summary.js.map +1 -0
  191. package/dist/types/session.d.ts +152 -0
  192. package/dist/types/session.d.ts.map +1 -0
  193. package/dist/types/session.js +27 -0
  194. package/dist/types/session.js.map +1 -0
  195. package/dist/types/task.d.ts +72 -0
  196. package/dist/types/task.d.ts.map +1 -0
  197. package/dist/types/task.js +19 -0
  198. package/dist/types/task.js.map +1 -0
  199. package/dist/types/teams.d.ts +73 -0
  200. package/dist/types/teams.d.ts.map +1 -0
  201. package/dist/types/teams.js +23 -0
  202. package/dist/types/teams.js.map +1 -0
  203. package/dist/types/tools.d.ts +61 -0
  204. package/dist/types/tools.d.ts.map +1 -0
  205. package/dist/types/tools.js +20 -0
  206. package/dist/types/tools.js.map +1 -0
  207. package/dist/types.d.ts +8 -1134
  208. package/dist/types.d.ts.map +1 -1
  209. package/dist/types.js +8 -210
  210. package/dist/types.js.map +1 -1
  211. package/dist/utils/claude-cli-resolver.d.ts.map +1 -1
  212. package/dist/utils/claude-cli-resolver.js +1 -2
  213. package/dist/utils/claude-cli-resolver.js.map +1 -1
  214. package/dist/utils/debouncer.d.ts +111 -0
  215. package/dist/utils/debouncer.d.ts.map +1 -0
  216. package/dist/utils/debouncer.js +162 -0
  217. package/dist/utils/debouncer.js.map +1 -0
  218. package/dist/utils/index.d.ts +3 -2
  219. package/dist/utils/index.d.ts.map +1 -1
  220. package/dist/utils/index.js +3 -2
  221. package/dist/utils/index.js.map +1 -1
  222. package/dist/utils/opencode-cli-resolver.d.ts.map +1 -1
  223. package/dist/utils/opencode-cli-resolver.js +1 -2
  224. package/dist/utils/opencode-cli-resolver.js.map +1 -1
  225. package/dist/utils/string-similarity.d.ts +0 -57
  226. package/dist/utils/string-similarity.d.ts.map +1 -1
  227. package/dist/utils/string-similarity.js +3 -18
  228. package/dist/utils/string-similarity.js.map +1 -1
  229. package/dist/web/middleware/auth.d.ts +31 -0
  230. package/dist/web/middleware/auth.d.ts.map +1 -0
  231. package/dist/web/middleware/auth.js +154 -0
  232. package/dist/web/middleware/auth.js.map +1 -0
  233. package/dist/web/ports/auth-port.d.ts +18 -0
  234. package/dist/web/ports/auth-port.d.ts.map +1 -0
  235. package/dist/web/ports/auth-port.js +6 -0
  236. package/dist/web/ports/auth-port.js.map +1 -0
  237. package/dist/web/ports/config-port.d.ts +28 -0
  238. package/dist/web/ports/config-port.d.ts.map +1 -0
  239. package/dist/web/ports/config-port.js +6 -0
  240. package/dist/web/ports/config-port.js.map +1 -0
  241. package/dist/web/ports/event-port.d.ts +13 -0
  242. package/dist/web/ports/event-port.d.ts.map +1 -0
  243. package/dist/web/ports/event-port.js +6 -0
  244. package/dist/web/ports/event-port.js.map +1 -0
  245. package/dist/web/ports/index.d.ts +14 -0
  246. package/dist/web/ports/index.d.ts.map +1 -0
  247. package/dist/web/ports/index.js +9 -0
  248. package/dist/web/ports/index.js.map +1 -0
  249. package/dist/web/ports/infra-port.d.ts +36 -0
  250. package/dist/web/ports/infra-port.d.ts.map +1 -0
  251. package/dist/web/ports/infra-port.js +6 -0
  252. package/dist/web/ports/infra-port.js.map +1 -0
  253. package/dist/web/ports/respawn-port.d.ts +20 -0
  254. package/dist/web/ports/respawn-port.d.ts.map +1 -0
  255. package/dist/web/ports/respawn-port.js +6 -0
  256. package/dist/web/ports/respawn-port.js.map +1 -0
  257. package/dist/web/ports/session-port.d.ts +15 -0
  258. package/dist/web/ports/session-port.d.ts.map +1 -0
  259. package/dist/web/ports/session-port.js +6 -0
  260. package/dist/web/ports/session-port.js.map +1 -0
  261. package/dist/web/public/api-client.js +82 -0
  262. package/dist/web/public/api-client.js.br +0 -0
  263. package/dist/web/public/api-client.js.gz +0 -0
  264. package/dist/web/public/app.js +117 -201
  265. package/dist/web/public/app.js.br +0 -0
  266. package/dist/web/public/app.js.gz +0 -0
  267. package/dist/web/public/constants.js +365 -0
  268. package/dist/web/public/constants.js.br +0 -0
  269. package/dist/web/public/constants.js.gz +0 -0
  270. package/dist/web/public/index.html +15 -3
  271. package/dist/web/public/index.html.br +0 -0
  272. package/dist/web/public/index.html.gz +0 -0
  273. package/dist/web/public/keyboard-accessory.js +302 -0
  274. package/dist/web/public/keyboard-accessory.js.br +0 -0
  275. package/dist/web/public/keyboard-accessory.js.gz +0 -0
  276. package/dist/web/public/mobile-handlers.js +491 -0
  277. package/dist/web/public/mobile-handlers.js.br +0 -0
  278. package/dist/web/public/mobile-handlers.js.gz +0 -0
  279. package/dist/web/public/mobile.css.gz +0 -0
  280. package/dist/web/public/notification-manager.js +472 -0
  281. package/dist/web/public/notification-manager.js.br +0 -0
  282. package/dist/web/public/notification-manager.js.gz +0 -0
  283. package/dist/web/public/ralph-wizard.js +33 -9
  284. package/dist/web/public/ralph-wizard.js.br +0 -0
  285. package/dist/web/public/ralph-wizard.js.gz +0 -0
  286. package/dist/web/public/styles.css.gz +0 -0
  287. package/dist/web/public/subagent-windows.js +1149 -0
  288. package/dist/web/public/subagent-windows.js.br +0 -0
  289. package/dist/web/public/subagent-windows.js.gz +0 -0
  290. package/dist/web/public/sw.js +15 -0
  291. package/dist/web/public/sw.js.br +0 -0
  292. package/dist/web/public/sw.js.gz +0 -0
  293. package/dist/web/public/upload.html.gz +0 -0
  294. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  295. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  296. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  297. package/dist/web/public/vendor/xterm-zerolag-input.js +4 -0
  298. package/dist/web/public/vendor/xterm-zerolag-input.js.br +0 -0
  299. package/dist/web/public/vendor/xterm-zerolag-input.js.gz +0 -0
  300. package/dist/web/public/vendor/xterm.css.gz +0 -0
  301. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  302. package/dist/web/public/voice-input.js +882 -0
  303. package/dist/web/public/voice-input.js.br +0 -0
  304. package/dist/web/public/voice-input.js.gz +0 -0
  305. package/dist/web/route-helpers.d.ts +38 -0
  306. package/dist/web/route-helpers.d.ts.map +1 -0
  307. package/dist/web/route-helpers.js +144 -0
  308. package/dist/web/route-helpers.js.map +1 -0
  309. package/dist/web/routes/case-routes.d.ts +9 -0
  310. package/dist/web/routes/case-routes.d.ts.map +1 -0
  311. package/dist/web/routes/case-routes.js +426 -0
  312. package/dist/web/routes/case-routes.js.map +1 -0
  313. package/dist/web/routes/file-routes.d.ts +8 -0
  314. package/dist/web/routes/file-routes.d.ts.map +1 -0
  315. package/dist/web/routes/file-routes.js +337 -0
  316. package/dist/web/routes/file-routes.js.map +1 -0
  317. package/dist/web/routes/hook-event-routes.d.ts +9 -0
  318. package/dist/web/routes/hook-event-routes.d.ts.map +1 -0
  319. package/dist/web/routes/hook-event-routes.js +57 -0
  320. package/dist/web/routes/hook-event-routes.js.map +1 -0
  321. package/dist/web/routes/index.d.ts +16 -0
  322. package/dist/web/routes/index.d.ts.map +1 -0
  323. package/dist/web/routes/index.js +16 -0
  324. package/dist/web/routes/index.js.map +1 -0
  325. package/dist/web/routes/mux-routes.d.ts +8 -0
  326. package/dist/web/routes/mux-routes.d.ts.map +1 -0
  327. package/dist/web/routes/mux-routes.js +32 -0
  328. package/dist/web/routes/mux-routes.js.map +1 -0
  329. package/dist/web/routes/plan-routes.d.ts +9 -0
  330. package/dist/web/routes/plan-routes.d.ts.map +1 -0
  331. package/dist/web/routes/plan-routes.js +385 -0
  332. package/dist/web/routes/plan-routes.js.map +1 -0
  333. package/dist/web/routes/push-routes.d.ts +8 -0
  334. package/dist/web/routes/push-routes.d.ts.map +1 -0
  335. package/dist/web/routes/push-routes.js +49 -0
  336. package/dist/web/routes/push-routes.js.map +1 -0
  337. package/dist/web/routes/ralph-routes.d.ts +9 -0
  338. package/dist/web/routes/ralph-routes.d.ts.map +1 -0
  339. package/dist/web/routes/ralph-routes.js +485 -0
  340. package/dist/web/routes/ralph-routes.js.map +1 -0
  341. package/dist/web/routes/respawn-routes.d.ts +8 -0
  342. package/dist/web/routes/respawn-routes.d.ts.map +1 -0
  343. package/dist/web/routes/respawn-routes.js +270 -0
  344. package/dist/web/routes/respawn-routes.js.map +1 -0
  345. package/dist/web/routes/scheduled-routes.d.ts +8 -0
  346. package/dist/web/routes/scheduled-routes.d.ts.map +1 -0
  347. package/dist/web/routes/scheduled-routes.js +51 -0
  348. package/dist/web/routes/scheduled-routes.js.map +1 -0
  349. package/dist/web/routes/session-routes.d.ts +9 -0
  350. package/dist/web/routes/session-routes.d.ts.map +1 -0
  351. package/dist/web/routes/session-routes.js +751 -0
  352. package/dist/web/routes/session-routes.js.map +1 -0
  353. package/dist/web/routes/system-routes.d.ts +9 -0
  354. package/dist/web/routes/system-routes.d.ts.map +1 -0
  355. package/dist/web/routes/system-routes.js +699 -0
  356. package/dist/web/routes/system-routes.js.map +1 -0
  357. package/dist/web/routes/team-routes.d.ts +8 -0
  358. package/dist/web/routes/team-routes.d.ts.map +1 -0
  359. package/dist/web/routes/team-routes.js +14 -0
  360. package/dist/web/routes/team-routes.js.map +1 -0
  361. package/dist/web/schemas.d.ts +43 -3
  362. package/dist/web/schemas.d.ts.map +1 -1
  363. package/dist/web/schemas.js +6 -2
  364. package/dist/web/schemas.js.map +1 -1
  365. package/dist/web/server.d.ts +35 -15
  366. package/dist/web/server.d.ts.map +1 -1
  367. package/dist/web/server.js +563 -3971
  368. package/dist/web/server.js.map +1 -1
  369. package/dist/web/sse-events.d.ts +361 -0
  370. package/dist/web/sse-events.d.ts.map +1 -0
  371. package/dist/web/sse-events.js +396 -0
  372. package/dist/web/sse-events.js.map +1 -0
  373. package/package.json +2 -1
  374. package/scripts/postinstall.js +58 -0
@@ -1,75 +1,46 @@
1
1
  /**
2
- * @fileoverview Ralph Tracker - Detects Ralph Wiggum loops, todos, and completion phrases
2
+ * @fileoverview Ralph Tracker - Detects Ralph Wiggum loops, todos, and completion phrases.
3
3
  *
4
- * This module parses terminal output from Claude Code sessions to detect:
5
- * - Ralph Wiggum loop state (active, completion phrase, iteration count)
6
- * - Todo list items from the TodoWrite tool
4
+ * Parses terminal output from Claude Code sessions to detect:
5
+ * - Ralph loop state (active, completion phrase, iteration count)
6
+ * - Todo items from the TodoWrite tool (with deduplication and expiry)
7
7
  * - Completion phrases signaling loop completion
8
+ * - Circuit breaker state (CLOSED/HALF_OPEN/OPEN)
8
9
  *
9
- * The tracker is DISABLED by default and auto-enables when Ralph-related
10
- * patterns are detected in the output stream, reducing overhead for
11
- * sessions not using autonomous loops.
10
+ * DISABLED by default auto-enables when Ralph-related patterns appear,
11
+ * reducing overhead for non-autonomous sessions.
12
+ *
13
+ * Composed of four sub-modules:
14
+ * - `RalphPlanTracker`: Plan task management, checkpoints, versioning
15
+ * - `RalphFixPlanWatcher`: @fix_plan.md file watching and parsing
16
+ * - `RalphStallDetector`: Iteration stall detection
17
+ * - `RalphStatusParser`: RALPH_STATUS block parsing, circuit breaker
18
+ *
19
+ * Key exports:
20
+ * - `RalphTracker` class — main tracker, extends EventEmitter
21
+ * - `RalphTrackerEvents` interface — typed event map
22
+ * - Re-exports: `EnhancedPlanTask`, `CheckpointReview` from ralph-plan-tracker
23
+ *
24
+ * Key methods: `processData(data)` — feed terminal output, `getState()`,
25
+ * `getTodos()`, `getCompletionHistory()`, `getPlanTasks()`, `reset()`
26
+ *
27
+ * @dependencies types (RalphTrackerState, RalphTodoItem, CircuitBreakerStatus),
28
+ * ralph-plan-tracker, ralph-fix-plan-watcher, ralph-stall-detector, ralph-status-parser,
29
+ * config/buffer-limits, config/map-limits
30
+ * @consumedby session (owns one RalphTracker per session), web/server (SSE events)
31
+ * @emits ralphStateChanged, todoUpdated, completionDetected, statusBlockParsed,
32
+ * circuitBreakerChanged, exitGateMet, planTaskUpdated, planCheckpoint
12
33
  *
13
34
  * @module ralph-tracker
14
35
  */
15
36
  import { EventEmitter } from 'node:events';
16
37
  import { RalphTrackerState, RalphTodoItem, RalphStatusBlock, CircuitBreakerStatus, RalphTodoProgress, CompletionConfidence, PlanTaskStatus, TddPhase } from './types.js';
17
- /**
18
- * Enhanced plan task with verification criteria, dependencies, and execution tracking.
19
- * Supports TDD workflow, failure tracking, and plan versioning.
20
- */
21
- export interface EnhancedPlanTask {
22
- /** Unique identifier (e.g., "P0-001") */
23
- id: string;
24
- /** Task description */
25
- content: string;
26
- /** Criticality level */
27
- priority: 'P0' | 'P1' | 'P2' | null;
28
- /** How to verify completion */
29
- verificationCriteria?: string;
30
- /** Command to run for verification */
31
- testCommand?: string;
32
- /** IDs of tasks that must complete first */
33
- dependencies: string[];
34
- /** Current execution status */
35
- status: PlanTaskStatus;
36
- /** How many times attempted */
37
- attempts: number;
38
- /** Most recent failure reason */
39
- lastError?: string;
40
- /** Timestamp of completion */
41
- completedAt?: number;
42
- /** Plan version this belongs to */
43
- version: number;
44
- /** TDD phase category */
45
- tddPhase?: TddPhase;
46
- /** ID of paired test/impl task */
47
- pairedWith?: string;
48
- /** Estimated complexity */
49
- complexity?: 'low' | 'medium' | 'high';
50
- /** Checklist items for review tasks (tddPhase: 'review') */
51
- reviewChecklist?: string[];
52
- }
53
- /** Checkpoint review data */
54
- export interface CheckpointReview {
55
- iteration: number;
56
- timestamp: number;
57
- summary: {
58
- total: number;
59
- completed: number;
60
- failed: number;
61
- blocked: number;
62
- pending: number;
63
- inProgress: number;
64
- };
65
- stuckTasks: Array<{
66
- id: string;
67
- content: string;
68
- attempts: number;
69
- lastError?: string;
70
- }>;
71
- recommendations: string[];
72
- }
38
+ import { RalphPlanTracker } from './ralph-plan-tracker.js';
39
+ import type { EnhancedPlanTask, CheckpointReview } from './ralph-plan-tracker.js';
40
+ import { RalphFixPlanWatcher } from './ralph-fix-plan-watcher.js';
41
+ import { RalphStallDetector } from './ralph-stall-detector.js';
42
+ import { RalphStatusParser } from './ralph-status-parser.js';
43
+ export type { EnhancedPlanTask, CheckpointReview } from './ralph-plan-tracker.js';
73
44
  /**
74
45
  * Events emitted by RalphTracker
75
46
  * @event loopUpdate - Fired when loop state changes (active, iteration, completion phrase)
@@ -136,6 +107,13 @@ export interface RalphTrackerEvents {
136
107
  * - 2nd occurrence: Emits `completionDetected` event (actual completion)
137
108
  * - If loop already active: Emits immediately on first occurrence
138
109
  *
110
+ * ## Sub-modules
111
+ *
112
+ * - `planTracker` - Plan task management, checkpoints, versioning
113
+ * - `fixPlanWatcher` - @fix_plan.md file watching and parsing
114
+ * - `stallDetector` - Iteration stall detection
115
+ * - `statusParser` - RALPH_STATUS block parsing, circuit breaker
116
+ *
139
117
  * ## Events
140
118
  *
141
119
  * - `loopUpdate` - Loop state changed (status, iteration, phrase)
@@ -154,6 +132,14 @@ export interface RalphTrackerEvents {
154
132
  * ```
155
133
  */
156
134
  export declare class RalphTracker extends EventEmitter {
135
+ /** Plan task management sub-module */
136
+ readonly planTracker: RalphPlanTracker;
137
+ /** @fix_plan.md file watcher sub-module */
138
+ readonly fixPlanWatcher: RalphFixPlanWatcher;
139
+ /** Iteration stall detector sub-module */
140
+ readonly stallDetector: RalphStallDetector;
141
+ /** RALPH_STATUS block parser and circuit breaker sub-module */
142
+ readonly statusParser: RalphStatusParser;
157
143
  /** Current state of the detected loop */
158
144
  private _loopState;
159
145
  /** Map of todo items by ID for O(1) lookup */
@@ -167,14 +153,10 @@ export declare class RalphTracker extends EventEmitter {
167
153
  private _completionPhraseCount;
168
154
  /** Timestamp of last cleanup check for throttling */
169
155
  private _lastCleanupTime;
170
- /** Debounce timer for todoUpdate events */
171
- private _todoUpdateTimer;
172
- /** Debounce timer for loopUpdate events */
173
- private _loopUpdateTimer;
174
- /** Flag indicating pending todoUpdate emission */
175
- private _todoUpdatePending;
176
- /** Flag indicating pending loopUpdate emission */
177
- private _loopUpdatePending;
156
+ /** Debouncer for todoUpdate events */
157
+ private _todoDeb;
158
+ /** Debouncer for loopUpdate events */
159
+ private _loopDeb;
178
160
  /** When true, prevents auto-enable on pattern detection */
179
161
  private _autoEnableDisabled;
180
162
  /** Maps task numbers from "✔ Task #N" format to their content for status updates */
@@ -187,59 +169,6 @@ export declare class RalphTracker extends EventEmitter {
187
169
  private _partialPromiseBuffer;
188
170
  /** Maximum size of partial promise buffer */
189
171
  private static readonly MAX_PARTIAL_PROMISE_SIZE;
190
- /** Circuit breaker state tracking */
191
- private _circuitBreaker;
192
- /** Buffer for RALPH_STATUS block lines */
193
- private _statusBlockBuffer;
194
- /** Flag indicating we're inside a RALPH_STATUS block */
195
- private _inStatusBlock;
196
- /** Last parsed RALPH_STATUS block */
197
- private _lastStatusBlock;
198
- /** Count of completion indicators detected (for dual-condition exit) */
199
- private _completionIndicators;
200
- /** Whether dual-condition exit gate has been met */
201
- private _exitGateMet;
202
- /** Cumulative files modified across all iterations */
203
- private _totalFilesModified;
204
- /** Cumulative tasks completed across all iterations */
205
- private _totalTasksCompleted;
206
- /** Working directory for @fix_plan.md watching */
207
- private _workingDir;
208
- /** File watcher for @fix_plan.md */
209
- private _fixPlanWatcher;
210
- /** Error handler for FSWatcher (stored for cleanup to prevent memory leak) */
211
- private _fixPlanWatcherErrorHandler;
212
- /** Debounce timer for file change events */
213
- private _fixPlanReloadTimer;
214
- /** Path to the @fix_plan.md file being watched */
215
- private _fixPlanPath;
216
- /**
217
- * When @fix_plan.md is active, treat it as the source of truth for todo status.
218
- * This prevents output-based detection from overriding file-based status.
219
- */
220
- private get isFileAuthoritative();
221
- /** Current version of the plan (incremented on changes) */
222
- private _planVersion;
223
- /** History of plan versions for rollback support */
224
- private _planHistory;
225
- /** Enhanced plan tasks with execution tracking */
226
- private _planTasks;
227
- /** Checkpoint intervals (iterations at which to trigger review) */
228
- private _checkpointIterations;
229
- /** Last checkpoint iteration */
230
- private _lastCheckpointIteration;
231
- /** Timestamp when iteration count last changed */
232
- private _lastIterationChangeTime;
233
- /** Last observed iteration count for stall detection */
234
- private _lastObservedIteration;
235
- /** Timer for iteration stall detection */
236
- private _iterationStallTimer;
237
- /** Iteration stall warning threshold (ms) - default 10 minutes */
238
- private _iterationStallWarningMs;
239
- /** Iteration stall critical threshold (ms) - default 20 minutes */
240
- private _iterationStallCriticalMs;
241
- /** Whether stall warning has been emitted */
242
- private _iterationStallWarned;
243
172
  /** Alternate completion phrases (P1-003: multi-phrase support) - Set for O(1) lookup */
244
173
  private _alternateCompletionPhrases;
245
174
  /** History of todo completion times (ms) for averaging */
@@ -250,595 +179,395 @@ export declare class RalphTracker extends EventEmitter {
250
179
  private _todosStartedAt;
251
180
  /** Map of todo ID to timestamp when it started (for duration tracking) */
252
181
  private _todoStartTimes;
182
+ /** Last calculated completion confidence */
183
+ private _lastCompletionConfidence;
184
+ /** Manages periodic cleanup timers (todo expiry) */
185
+ private cleanup;
186
+ /** Confidence threshold for triggering completion (0-100) */
187
+ private static readonly COMPLETION_CONFIDENCE_THRESHOLD;
253
188
  /**
254
189
  * Creates a new RalphTracker instance.
255
190
  * Starts in disabled state until Ralph patterns are detected.
256
191
  */
257
192
  constructor();
258
193
  /**
259
- * Add an alternate completion phrase (P1-003: multi-phrase support).
260
- * Multiple phrases can trigger completion (useful for complex workflows).
261
- * @param phrase - Additional phrase that can trigger completion
194
+ * Forward all sub-module events through RalphTracker
195
+ * so external consumers don't need to know about the split.
262
196
  */
263
- addAlternateCompletionPhrase(phrase: string): void;
197
+ private _wireSubModuleEvents;
264
198
  /**
265
- * Remove an alternate completion phrase.
266
- * @param phrase - Phrase to remove
199
+ * Initialize plan tasks from generated plan items.
267
200
  */
268
- removeAlternateCompletionPhrase(phrase: string): void;
201
+ initializePlanTasks(items: Array<{
202
+ id?: string;
203
+ content: string;
204
+ priority?: 'P0' | 'P1' | 'P2' | null;
205
+ verificationCriteria?: string;
206
+ testCommand?: string;
207
+ dependencies?: string[];
208
+ tddPhase?: TddPhase;
209
+ pairedWith?: string;
210
+ complexity?: 'low' | 'medium' | 'high';
211
+ }>): void;
269
212
  /**
270
- * Check if a phrase matches any valid completion phrase (primary or alternate).
271
- * @param phrase - Phrase to check
272
- * @returns True if phrase matches any valid completion phrase
213
+ * Update a specific plan task's status, attempts, or error.
273
214
  */
274
- isValidCompletionPhrase(phrase: string): boolean;
215
+ updatePlanTask(taskId: string, update: {
216
+ status?: PlanTaskStatus;
217
+ error?: string;
218
+ incrementAttempts?: boolean;
219
+ }): {
220
+ success: boolean;
221
+ task?: EnhancedPlanTask;
222
+ error?: string;
223
+ };
275
224
  /**
276
- * Find which completion phrase (primary or alternate) matches the given phrase.
277
- * @param phrase - Phrase to check
278
- * @returns The matched canonical phrase, or null if no match
225
+ * Add a new task to the plan.
279
226
  */
280
- private findMatchingCompletionPhrase;
227
+ addPlanTask(task: {
228
+ content: string;
229
+ priority?: 'P0' | 'P1' | 'P2';
230
+ verificationCriteria?: string;
231
+ dependencies?: string[];
232
+ insertAfter?: string;
233
+ }): {
234
+ task: EnhancedPlanTask;
235
+ };
281
236
  /**
282
- * Prevent auto-enable from pattern detection.
283
- * Use this when the user has explicitly disabled the Ralph tracker.
237
+ * Get all plan tasks.
284
238
  */
285
- disableAutoEnable(): void;
239
+ getPlanTasks(): EnhancedPlanTask[];
286
240
  /**
287
- * Allow auto-enable from pattern detection.
241
+ * Generate a checkpoint review.
288
242
  */
289
- enableAutoEnable(): void;
243
+ generateCheckpointReview(): CheckpointReview;
290
244
  /**
291
- * Whether auto-enable is disabled.
245
+ * Get plan version history.
292
246
  */
293
- get autoEnableDisabled(): boolean;
247
+ getPlanHistory(): Array<{
248
+ version: number;
249
+ timestamp: number;
250
+ summary: string;
251
+ stats: {
252
+ total: number;
253
+ completed: number;
254
+ failed: number;
255
+ };
256
+ }>;
257
+ /**
258
+ * Rollback to a previous plan version.
259
+ */
260
+ rollbackToVersion(version: number): {
261
+ success: boolean;
262
+ plan?: EnhancedPlanTask[];
263
+ error?: string;
264
+ };
265
+ /**
266
+ * Check if checkpoint review is due.
267
+ */
268
+ isCheckpointDue(): boolean;
269
+ /**
270
+ * Get current plan version.
271
+ */
272
+ get planVersion(): number;
294
273
  /**
295
274
  * Set the working directory and start watching @fix_plan.md.
296
- * Automatically loads existing @fix_plan.md if present.
297
275
  * @param workingDir - The session's working directory
298
276
  */
299
277
  setWorkingDir(workingDir: string): void;
300
278
  /**
301
279
  * Load @fix_plan.md from disk if it exists.
302
- * Called on initialization and when file changes are detected.
303
280
  */
304
281
  loadFixPlanFromDisk(): Promise<number>;
305
282
  /**
306
- * Start watching @fix_plan.md for changes.
307
- * Reloads todos when the file is modified.
283
+ * Stop watching @fix_plan.md.
308
284
  */
309
- private startWatchingFixPlan;
285
+ stopWatchingFixPlan(): void;
310
286
  /**
311
- * Handle @fix_plan.md file change with debouncing.
287
+ * When @fix_plan.md is active, treat it as the source of truth for todo status.
312
288
  */
313
- private handleFixPlanChange;
289
+ get isFileAuthoritative(): boolean;
314
290
  /**
315
- * Stop watching @fix_plan.md.
291
+ * Generate @fix_plan.md content from current todos.
316
292
  */
317
- stopWatchingFixPlan(): void;
293
+ generateFixPlanMarkdown(): string;
294
+ /**
295
+ * Parse @fix_plan.md content and import todos.
296
+ * Replaces current todos with imported ones.
297
+ *
298
+ * @param content - Markdown content from @fix_plan.md
299
+ * @returns Number of todos imported
300
+ */
301
+ importFixPlanMarkdown(content: string): number;
302
+ /**
303
+ * Start iteration stall detection timer.
304
+ */
305
+ startIterationStallDetection(): void;
306
+ /**
307
+ * Stop iteration stall detection timer.
308
+ */
309
+ stopIterationStallDetection(): void;
310
+ /**
311
+ * Get iteration stall metrics for monitoring.
312
+ */
313
+ getIterationStallMetrics(): {
314
+ lastIterationChangeTime: number;
315
+ stallDurationMs: number;
316
+ warningThresholdMs: number;
317
+ criticalThresholdMs: number;
318
+ isWarned: boolean;
319
+ currentIteration: number;
320
+ };
321
+ /**
322
+ * Configure iteration stall thresholds.
323
+ */
324
+ configureIterationStallThresholds(warningMs: number, criticalMs: number): void;
325
+ /**
326
+ * Manually reset circuit breaker to CLOSED state.
327
+ * @fires circuitBreakerUpdate
328
+ */
329
+ resetCircuitBreaker(): void;
330
+ /**
331
+ * Get current circuit breaker status.
332
+ */
333
+ get circuitBreakerStatus(): CircuitBreakerStatus;
334
+ /**
335
+ * Get last parsed RALPH_STATUS block.
336
+ */
337
+ get lastStatusBlock(): RalphStatusBlock | null;
338
+ /**
339
+ * Get cumulative stats from status blocks.
340
+ */
341
+ get cumulativeStats(): {
342
+ filesModified: number;
343
+ tasksCompleted: number;
344
+ completionIndicators: number;
345
+ };
346
+ /**
347
+ * Whether dual-condition exit gate has been met.
348
+ */
349
+ get exitGateMet(): boolean;
350
+ /**
351
+ * Add an alternate completion phrase (P1-003: multi-phrase support).
352
+ */
353
+ addAlternateCompletionPhrase(phrase: string): void;
354
+ /**
355
+ * Remove an alternate completion phrase.
356
+ */
357
+ removeAlternateCompletionPhrase(phrase: string): void;
358
+ /**
359
+ * Check if a phrase matches any valid completion phrase (primary or alternate).
360
+ */
361
+ isValidCompletionPhrase(phrase: string): boolean;
362
+ /**
363
+ * Find which completion phrase (primary or alternate) matches the given phrase.
364
+ */
365
+ private findMatchingCompletionPhrase;
366
+ /**
367
+ * Prevent auto-enable from pattern detection.
368
+ */
369
+ disableAutoEnable(): void;
370
+ /**
371
+ * Allow auto-enable from pattern detection.
372
+ */
373
+ enableAutoEnable(): void;
374
+ /**
375
+ * Whether auto-enable is disabled.
376
+ */
377
+ get autoEnableDisabled(): boolean;
318
378
  /**
319
379
  * Whether the tracker is enabled and actively monitoring output.
320
- * Disabled by default; auto-enables when Ralph patterns detected.
321
- * @returns True if tracker is processing terminal data
322
380
  */
323
381
  get enabled(): boolean;
324
382
  /**
325
383
  * Enable the tracker to start monitoring terminal output.
326
- * Called automatically when Ralph patterns are detected.
327
- * Emits 'enabled' event when transitioning from disabled state.
328
384
  * @fires enabled
329
385
  * @fires loopUpdate
330
386
  */
331
387
  enable(): void;
332
388
  /**
333
389
  * Disable the tracker to stop monitoring terminal output.
334
- * Terminal data will be ignored until re-enabled.
335
390
  * @fires loopUpdate
336
391
  */
337
392
  disable(): void;
338
393
  /**
339
394
  * Soft reset - clears state but keeps enabled status.
340
- * Use when a new task/loop starts within the same session.
341
- *
342
- * Clears:
343
- * - All todo items
344
- * - Completion phrase tracking
345
- * - Loop state (active, iterations)
346
- * - Line buffer
347
- *
348
- * Preserves:
349
- * - Enabled status
350
- *
351
395
  * @fires loopUpdate
352
396
  * @fires todoUpdate
353
397
  */
354
398
  reset(): void;
355
399
  /**
356
400
  * Full reset - clears all state including enabled status.
357
- * Use when session is closed or completely cleared.
358
- * Returns tracker to initial disabled state.
359
401
  * @fires loopUpdate
360
402
  * @fires todoUpdate
361
403
  */
362
404
  fullReset(): void;
363
405
  /**
364
406
  * Clear all debounce timers.
365
- * Called during reset/fullReset to prevent stale emissions.
366
407
  */
367
408
  private clearDebounceTimers;
368
409
  /**
369
410
  * Emit todoUpdate event with debouncing.
370
- * Batches rapid consecutive calls to reduce UI jitter.
371
- * The event fires after EVENT_DEBOUNCE_MS of inactivity.
372
411
  */
373
412
  private emitTodoUpdateDebounced;
374
413
  /**
375
414
  * Emit loopUpdate event with debouncing.
376
- * Batches rapid consecutive calls to reduce UI jitter.
377
- * The event fires after EVENT_DEBOUNCE_MS of inactivity.
378
415
  */
379
416
  private emitLoopUpdateDebounced;
380
417
  /**
381
418
  * Flush all pending debounced events immediately.
382
- * Useful for testing or when immediate state sync is needed.
383
419
  */
384
420
  flushPendingEvents(): void;
385
421
  /**
386
422
  * Get a copy of the current loop state.
387
- * @returns Shallow copy of loop state (safe to modify)
388
- */
389
- /**
390
- * Start iteration stall detection timer.
391
- * Should be called when the loop becomes active.
392
- */
393
- startIterationStallDetection(): void;
394
- /**
395
- * Stop iteration stall detection timer.
396
- */
397
- stopIterationStallDetection(): void;
398
- /**
399
- * Check for iteration stall and emit appropriate events.
400
- */
401
- private checkIterationStall;
402
- /**
403
- * Get iteration stall metrics for monitoring.
404
- */
405
- getIterationStallMetrics(): {
406
- lastIterationChangeTime: number;
407
- stallDurationMs: number;
408
- warningThresholdMs: number;
409
- criticalThresholdMs: number;
410
- isWarned: boolean;
411
- currentIteration: number;
412
- };
413
- /**
414
- * Configure iteration stall thresholds.
415
- * @param warningMs - Warning threshold in milliseconds
416
- * @param criticalMs - Critical threshold in milliseconds
417
423
  */
418
- configureIterationStallThresholds(warningMs: number, criticalMs: number): void;
419
424
  get loopState(): RalphTrackerState;
420
- /** Last calculated completion confidence */
421
- private _lastCompletionConfidence;
422
- /** Confidence threshold for triggering completion (0-100) */
423
- private static readonly COMPLETION_CONFIDENCE_THRESHOLD;
424
425
  /**
425
426
  * Calculate confidence score for a potential completion signal.
426
- *
427
- * Scoring weights:
428
- * - Promise tag with proper format: +30
429
- * - Matches expected phrase: +25
430
- * - All todos complete: +20
431
- * - EXIT_SIGNAL: true: +15
432
- * - Multiple completion indicators (>=2): +10
433
- * - Context appropriate (not in prompt/explanation): +10
434
- * - Loop was explicitly active: +10
435
- *
436
- * @param phrase - The detected phrase to evaluate
437
- * @param context - Optional surrounding context for the phrase
438
- * @returns CompletionConfidence assessment
439
427
  */
440
428
  calculateCompletionConfidence(phrase: string, context?: string): CompletionConfidence;
441
429
  /**
442
430
  * Get all tracked todo items as an array.
443
- * @returns Array of todo items (copy, safe to modify)
444
431
  */
445
432
  get todos(): RalphTodoItem[];
446
433
  /**
447
434
  * Process raw terminal data to detect inner loop patterns.
448
- *
449
- * This is the main entry point for parsing output. Call this with each
450
- * chunk of data from the PTY. The tracker will:
451
- *
452
- * 1. Strip ANSI escape codes
453
- * 2. Auto-enable if disabled and Ralph patterns detected
454
- * 3. Buffer data and process complete lines
455
- * 4. Detect loop status, todos, and completion phrases
456
- * 5. Periodically clean up expired todos
457
- *
458
- * @param data - Raw terminal data (may include ANSI codes)
459
- * @fires loopUpdate - When loop state changes
460
- * @fires todoUpdate - When todos are detected or updated
461
- * @fires completionDetected - When completion phrase found
462
- * @fires enabled - When tracker auto-enables
463
435
  */
464
436
  processTerminalData(data: string): void;
465
437
  /**
466
438
  * Process pre-stripped terminal data (ANSI codes already removed).
467
- * Use this when the caller has already stripped ANSI to avoid redundant regex work.
468
439
  */
469
440
  processCleanData(cleanData: string): void;
470
441
  /**
471
442
  * Check if data contains patterns that should auto-enable the tracker.
472
- *
473
- * The tracker auto-enables when any of these patterns are detected:
474
- * - `/ralph-loop:ralph-loop` command
475
- * - `<promise>PHRASE</promise>` completion tags
476
- * - TodoWrite tool usage indicators
477
- * - Iteration patterns (`Iteration 5/50`, `[5/50]`)
478
- * - Todo checkboxes (`- [ ]`, `- [x]`)
479
- * - Todo indicator icons (`☐`, `◐`, `☒`)
480
- * - Loop start messages (`Loop started at`)
481
- * - All tasks complete announcements
482
- * - Task completion signals
483
- *
484
- * @param data - ANSI-cleaned terminal data
485
- * @returns True if any Ralph-related pattern is detected
486
443
  */
487
444
  private shouldAutoEnable;
488
445
  /**
489
446
  * Process a single line of terminal output.
490
- * Runs all detection methods in sequence.
491
- * @param line - Single line of ANSI-cleaned terminal output
492
447
  */
493
448
  private processLine;
494
449
  /**
495
450
  * Detect "all tasks complete" messages.
496
- *
497
- * When a valid "all complete" message is detected:
498
- * 1. Marks all tracked todos as completed
499
- * 2. Emits completion event if a completion phrase is set
500
- *
501
- * Validation criteria:
502
- * - Line must match ALL_COMPLETE_PATTERN
503
- * - Line must be reasonably short (<100 chars) to avoid matching commentary
504
- * - Must not look like prompt text (no "output:" or `<promise>`)
505
- * - Must have at least one tracked todo
506
- * - If count is mentioned, should roughly match tracked todo count
507
- *
508
- * @param line - Single line to check
509
- * @fires todoUpdate - If any todos marked complete
510
- * @fires completionDetected - If completion phrase was set
511
- * @fires loopUpdate - If loop state changes
512
451
  */
513
452
  private detectAllTasksComplete;
514
453
  /**
515
- * Detect individual task completion signals
516
- * e.g., "Task 8 is done", "marked as completed"
517
- *
518
- * NOTE: This is intentionally conservative to avoid jitter.
519
- * Only marks a todo complete if we can match it by task number.
454
+ * Detect individual task completion signals.
520
455
  */
521
456
  private detectTaskCompletion;
522
457
  /**
523
458
  * Check for multi-line patterns that might span line boundaries.
524
- * Completion phrases can be split across PTY chunks.
525
- *
526
- * Handles cross-chunk promise tags by:
527
- * 1. Checking combined buffer + new data for complete tags
528
- * 2. Detecting partial tags at end of chunk and buffering
529
- * 3. Clearing buffer when complete tag found or buffer gets stale
530
- *
531
- * @param data - The full data chunk (may contain multiple lines)
532
459
  */
533
460
  private checkMultiLinePatterns;
534
461
  /**
535
462
  * Detect completion phrases in a line.
536
- *
537
- * Handles two formats:
538
- * 1. Tagged: `<promise>PHRASE</promise>` - Processed via handleCompletionPhrase
539
- * 2. Bare: Just `PHRASE` - Only if we already know the expected phrase
540
- *
541
- * Bare phrase detection avoids false positives by requiring:
542
- * - The phrase was previously seen in tagged form
543
- * - Line is standalone or ends with the phrase
544
- * - Line doesn't look like prompt context
545
- *
546
- * @param line - Single line to check
547
463
  */
548
464
  private detectCompletionPhrase;
549
465
  /**
550
466
  * Handle a bare completion phrase (without XML tags).
551
- *
552
- * Only fires completion if:
553
- * 1. The phrase was previously seen in tagged form (from prompt)
554
- * 2. This is the first bare occurrence (prevents double-firing)
555
- *
556
- * When triggered:
557
- * - Marks all todos as complete
558
- * - Emits completionDetected event
559
- * - Sets loop to inactive
560
- *
561
- * @param phrase - The completion phrase text
562
- * @fires todoUpdate - If any todos marked complete
563
- * @fires completionDetected - When completion triggered
564
- * @fires loopUpdate - When loop state changes
565
467
  */
566
468
  private handleBareCompletionPhrase;
567
469
  /**
568
- * Handle a detected completion phrase
569
- *
570
- * Uses occurrence-based detection combined with confidence scoring
571
- * to distinguish prompt from actual completion:
572
- * - 1st occurrence: Store as expected phrase (likely in prompt)
573
- * - 2nd occurrence OR high confidence: Emit completionDetected (actual completion)
574
- * - If loop already active: Emit immediately (explicit loop start)
470
+ * Handle a detected completion phrase.
575
471
  */
576
472
  private handleCompletionPhrase;
577
473
  /**
578
474
  * Check if two phrases match with fuzzy tolerance.
579
- * Handles variations in:
580
- * - Case (COMPLETE vs Complete)
581
- * - Whitespace (TASK_DONE vs TASK DONE)
582
- * - Separators (TASK_DONE vs TASK-DONE)
583
- * - Minor typos with Levenshtein distance (COMPLET vs COMPLETE)
584
- *
585
- * @param phrase1 - First phrase to compare
586
- * @param phrase2 - Second phrase to compare
587
- * @param maxDistance - Maximum edit distance for fuzzy match (default: 2)
588
- * @returns True if phrases are fuzzy-equal
589
475
  */
590
476
  private isFuzzyPhraseMatch;
591
477
  /**
592
478
  * Validate a completion phrase and emit warnings if it's risky.
593
- *
594
- * P1-002: Configurable false positive prevention
595
- *
596
- * Checks for:
597
- * - Common/generic phrases (DONE, COMPLETE, etc.)
598
- * - Short phrases (< MIN_RECOMMENDED_PHRASE_LENGTH)
599
- * - Numeric-only phrases
600
- *
601
- * @param phrase - The completion phrase to validate
602
- * @fires phraseValidationWarning - When a risky phrase is detected
603
479
  */
604
480
  private validateCompletionPhrase;
605
481
  /**
606
482
  * Activate the loop if not already active.
607
- *
608
- * Sets loop state to active and initializes counters.
609
- * No-op if loop is already active.
610
- *
611
- * @returns True if loop was activated, false if already active
612
- * @fires loopUpdate - When loop state changes
613
483
  */
614
484
  private activateLoopIfNeeded;
615
485
  /**
616
486
  * Detect loop start and status indicators.
617
- *
618
- * Patterns detected:
619
- * - Ralph loop start commands (`/ralph-loop:ralph-loop`)
620
- * - Loop start messages (`Loop started at`, `Starting Ralph loop`)
621
- * - Max iterations setting (`max-iterations 50`)
622
- * - Iteration progress (`Iteration 5/50`, `[5/50]`)
623
- * - Elapsed time (`Elapsed: 2.5 hours`)
624
- * - Cycle count (`cycle #5`, `respawn cycle #3`)
625
- * - TodoWrite tool usage
626
- *
627
- * @param line - Single line to check
628
- * @fires loopUpdate - When any loop state changes
629
487
  */
630
488
  private detectLoopStatus;
631
489
  /**
632
490
  * Detect todo items in various formats from Claude Code output.
633
- *
634
- * Supported formats:
635
- * - Format 1: Checkbox markdown (`- [ ] Task`, `- [x] Task`)
636
- * - Format 2: Indicator icons (`Todo: ☐ Task`, `Todo: ✓ Task`)
637
- * - Format 3: Status in parentheses (`- Task (pending)`)
638
- * - Format 4: Native TodoWrite (`☐ Task`, `☒ Task`, `◐ Task`)
639
- *
640
- * Uses quick pre-check to skip lines that can't contain todos.
641
- * Excludes tool invocations and Claude commentary patterns.
642
- *
643
- * @param line - Single line to check
644
- * @fires todoUpdate - When any todos are detected or updated
645
491
  */
646
492
  private detectTodoItems;
647
493
  /**
648
494
  * Convert a todo icon character to its corresponding status.
649
- *
650
- * Icon mappings:
651
- * - Completed: `✓`, `✅`, `☒`, `◉`, `●`
652
- * - In Progress: `◐`, `⏳`, `⌛`, `🔄`
653
- * - Pending: `☐`, `○`, and anything else (default)
654
- *
655
- * @param icon - Single character icon
656
- * @returns Corresponding RalphTodoStatus
657
495
  */
658
496
  private iconToStatus;
659
497
  /**
660
498
  * Parse priority from todo content.
661
- * P1-008: Enhanced keyword-based priority inference.
662
- *
663
- * Priority levels:
664
- * - P0 (Critical): Explicit P0, "critical", "blocker", "urgent", "security", "crash", "broken"
665
- * - P1 (High): Explicit P1, "important", "high priority", "bug", "fix", "error", "fail"
666
- * - P2 (Medium): Explicit P2, "nice to have", "low priority", "refactor", "cleanup", "improve"
667
- *
668
- * @param content - Todo content text
669
- * @returns Parsed priority level or null
670
499
  */
671
500
  private parsePriority;
672
501
  /**
673
502
  * Add a new todo item or update an existing one.
674
- *
675
- * Behavior:
676
- * - Content is cleaned (ANSI removed, whitespace collapsed)
677
- * - Content under 5 chars is skipped
678
- * - ID is generated from normalized content (stable hash)
679
- * - Priority is parsed from content (P0/P1/P2, Critical, High Priority, etc.)
680
- * - Existing item: Updates status and timestamp
681
- * - New item: Adds to map, evicts oldest if at MAX_TODOS_PER_SESSION
682
- *
683
- * @param content - Raw todo content text
684
- * @param status - Status to set
685
503
  */
686
504
  private upsertTodo;
687
505
  /**
688
506
  * Normalize todo content for consistent matching.
689
- *
690
- * Normalization steps:
691
- * 1. Collapse multiple whitespace to single space
692
- * 2. Remove special characters (keep alphanumeric + basic punctuation)
693
- * 3. Trim whitespace
694
- * 4. Convert to lowercase
695
- *
696
- * This prevents duplicate todos from terminal rendering artifacts.
697
- *
698
- * @param content - Raw todo content
699
- * @returns Normalized lowercase string
700
507
  */
701
508
  private normalizeTodoContent;
702
509
  /**
703
510
  * Calculate similarity between two strings.
704
- *
705
- * P1-007: Uses a hybrid approach combining:
706
- * 1. Levenshtein-based similarity for edit-distance tolerance
707
- * 2. Bigram (Dice coefficient) for reordering tolerance
708
- * Returns the maximum of both methods.
709
- *
710
- * @param str1 - First string (will be normalized)
711
- * @param str2 - Second string (will be normalized)
712
- * @returns Similarity score from 0.0 (no similarity) to 1.0 (identical)
713
511
  */
714
512
  private calculateSimilarity;
715
513
  /**
716
514
  * Calculate bigram (Dice coefficient) similarity.
717
- * Good for detecting near-duplicates with word reordering.
718
- *
719
- * @param norm1 - First normalized string
720
- * @param norm2 - Second normalized string
721
- * @returns Similarity score from 0.0 to 1.0
722
515
  */
723
516
  private calculateBigramSimilarity;
724
517
  /**
725
518
  * Find an existing todo that is similar to the given content.
726
- * Returns the most similar todo if similarity >= threshold.
727
- *
728
- * Deduplication is intentionally conservative:
729
- * - Short strings (< 30 chars): require 95% similarity (nearly identical)
730
- * - Medium strings (30-60 chars): require 90% similarity
731
- * - Longer strings: use default 85% threshold
732
- *
733
- * This prevents over-aggressive deduplication of brief, numbered items
734
- * like "Task 1", "Task 2" while still catching true duplicates.
735
- *
736
- * @param content - New todo content to check against existing todos
737
- * @returns Similar todo item if found, undefined otherwise
738
519
  */
739
520
  private findSimilarTodo;
740
521
  /**
741
522
  * Estimate complexity of a todo based on content keywords.
742
- * Used for duration estimation.
743
- *
744
- * @param content - Todo content text
745
- * @returns Complexity category
746
523
  */
747
524
  private estimateComplexity;
748
525
  /**
749
526
  * Get estimated duration for a complexity level (ms).
750
- * Based on historical patterns from similar tasks.
751
- *
752
- * @param complexity - Complexity category
753
- * @returns Estimated duration in milliseconds
754
527
  */
755
528
  private getEstimatedDuration;
756
529
  /**
757
530
  * Get average completion time from historical data.
758
- * @returns Average time in ms, or null if no data
759
531
  */
760
532
  private getAverageCompletionTime;
761
533
  /**
762
534
  * Record a todo completion for progress tracking.
763
- * @param todoId - ID of the completed todo
764
535
  */
765
536
  private recordTodoCompletion;
766
537
  /**
767
538
  * Start tracking a todo for duration estimation.
768
- * @param todoId - ID of the todo being started
769
539
  */
770
540
  private startTrackingTodo;
771
541
  /**
772
542
  * Get progress estimation for the todo list.
773
- * P1-009: Provides completion percentage, estimated remaining time,
774
- * and projected completion timestamp.
775
- *
776
- * @returns Progress estimation object
777
543
  */
778
544
  getTodoProgress(): RalphTodoProgress;
779
- /**
780
- * Generate a stable ID from todo content using djb2 hash.
781
- *
782
- * Uses the djb2 hash algorithm for good distribution across strings.
783
- * Content is normalized first to prevent duplicates from terminal artifacts.
784
- *
785
- * @param content - Todo content text
786
- * @returns Stable ID in format `todo-{hash}` (base36 encoded)
787
- */
788
545
  /**
789
546
  * Generate a stable ID from todo content using content hashing.
790
- *
791
- * P1-007: Uses centralized todoContentHash utility for consistency
792
- * with deduplication logic.
793
- *
794
- * @param content - Todo content text
795
- * @returns Unique ID string prefixed with "todo-"
796
547
  */
797
548
  private generateTodoId;
798
549
  /**
799
550
  * Find the todo item with the oldest detectedAt timestamp.
800
- * Used for LRU eviction when at MAX_TODOS_PER_SESSION limit.
801
- * @returns Oldest todo item, or undefined if map is empty
802
551
  */
803
552
  private findOldestTodo;
804
553
  /**
805
554
  * Conditionally run cleanup, throttled to CLEANUP_THROTTLE_MS.
806
- * Prevents cleanup from running on every data chunk (performance).
807
555
  */
808
556
  private maybeCleanupExpiredTodos;
809
557
  /**
810
558
  * Remove todo items older than TODO_EXPIRY_MS.
811
- * Emits todoUpdate if any items were removed.
812
- * @fires todoUpdate - When expired items are removed
813
559
  */
814
560
  private cleanupExpiredTodos;
815
561
  /**
816
562
  * Programmatically start a loop (external API).
817
- *
818
- * Use when starting a loop from outside terminal detection,
819
- * such as from a user action or API call.
820
- *
821
- * Automatically enables the tracker if not already enabled.
822
- *
823
- * @param completionPhrase - Optional phrase that signals completion
824
- * @param maxIterations - Optional maximum iteration count
825
- * @fires enabled - If tracker was disabled
826
- * @fires loopUpdate - When loop state changes
827
563
  */
828
564
  startLoop(completionPhrase?: string, maxIterations?: number): void;
829
565
  /**
830
566
  * Update the maximum iteration count (external API).
831
- *
832
- * @param maxIterations - New max iterations, or null to remove limit
833
- * @fires loopUpdate - When loop state changes
834
567
  */
835
568
  setMaxIterations(maxIterations: number | null): void;
836
569
  /**
837
- * Configure the tracker from external state (e.g. ralph plugin config).
838
- * Only updates fields that are provided, leaving others unchanged.
839
- *
840
- * @param config - Partial configuration to apply
841
- * @fires loopUpdate - When loop state changes
570
+ * Configure the tracker from external state.
842
571
  */
843
572
  configure(config: {
844
573
  enabled?: boolean;
@@ -847,36 +576,18 @@ export declare class RalphTracker extends EventEmitter {
847
576
  }): void;
848
577
  /**
849
578
  * Programmatically stop the loop (external API).
850
- *
851
- * Sets loop to inactive. Does not disable the tracker
852
- * or clear todos - use reset() or clear() for that.
853
- *
854
- * @fires loopUpdate - When loop state changes
855
579
  */
856
580
  stopLoop(): void;
857
581
  /**
858
582
  * Enforce size limit on _taskNumberToContent map.
859
- * Removes lowest task numbers (oldest tasks) when limit exceeded.
860
583
  */
861
584
  private enforceTaskMappingLimit;
862
585
  /**
863
586
  * Clear all state and disable the tracker.
864
- *
865
- * Use when the session is cleared or closed.
866
- * Resets everything to initial disabled state.
867
- *
868
- * @fires loopUpdate - With initial state
869
- * @fires todoUpdate - With empty array
870
587
  */
871
588
  clear(): void;
872
589
  /**
873
590
  * Get aggregated statistics about tracked todos.
874
- *
875
- * @returns Object with counts by status:
876
- * - total: Total number of tracked todos
877
- * - pending: Todos not yet started
878
- * - inProgress: Todos currently in progress
879
- * - completed: Finished todos
880
591
  */
881
592
  getTodoStats(): {
882
593
  total: number;
@@ -886,195 +597,10 @@ export declare class RalphTracker extends EventEmitter {
886
597
  };
887
598
  /**
888
599
  * Restore tracker state from persisted data.
889
- *
890
- * Use after loading state from StateStore. Handles backwards
891
- * compatibility by defaulting missing `enabled` flag to false.
892
- *
893
- * Note: Does not emit events (caller should handle if needed).
894
- *
895
- * @param loopState - Persisted loop state object
896
- * @param todos - Persisted todo items array
897
600
  */
898
601
  restoreState(loopState: RalphTrackerState, todos: RalphTodoItem[]): void;
899
- /**
900
- * Process a line for RALPH_STATUS block detection.
901
- * Buffers lines between ---RALPH_STATUS--- and ---END_RALPH_STATUS---
902
- * then parses the complete block.
903
- *
904
- * @param line - Single line to process (already trimmed)
905
- * @fires statusBlockDetected - When a complete block is parsed
906
- */
907
- private processStatusBlockLine;
908
- /**
909
- * Parse buffered RALPH_STATUS block lines into structured data.
910
- *
911
- * P1-004: Enhanced with schema validation and error recovery
912
- *
913
- * @param lines - Array of lines between block markers
914
- * @fires statusBlockDetected - When parsing succeeds
915
- */
916
- private parseStatusBlock;
917
- /**
918
- * Handle a parsed RALPH_STATUS block.
919
- * Updates circuit breaker, checks exit conditions.
920
- *
921
- * @param block - Parsed status block
922
- * @fires statusBlockDetected - With the block data
923
- * @fires circuitBreakerUpdate - If state changes
924
- * @fires exitGateMet - If dual-condition exit triggered
925
- */
926
- private handleStatusBlock;
927
- /**
928
- * Update circuit breaker state based on iteration results.
929
- *
930
- * @param hasProgress - Whether this iteration made progress
931
- * @param testsStatus - Current test status
932
- * @param status - Overall status from RALPH_STATUS
933
- * @fires circuitBreakerUpdate - If state changes
934
- */
935
- private updateCircuitBreaker;
936
- /**
937
- * Manually reset circuit breaker to CLOSED state.
938
- * Use when user acknowledges the issue is resolved.
939
- *
940
- * @fires circuitBreakerUpdate
941
- */
942
- resetCircuitBreaker(): void;
943
- /**
944
- * Get current circuit breaker status.
945
- */
946
- get circuitBreakerStatus(): CircuitBreakerStatus;
947
- /**
948
- * Get last parsed RALPH_STATUS block.
949
- */
950
- get lastStatusBlock(): RalphStatusBlock | null;
951
- /**
952
- * Get cumulative stats from status blocks.
953
- */
954
- get cumulativeStats(): {
955
- filesModified: number;
956
- tasksCompleted: number;
957
- completionIndicators: number;
958
- };
959
- /**
960
- * Whether dual-condition exit gate has been met.
961
- */
962
- get exitGateMet(): boolean;
963
- /**
964
- * Check line for completion indicators (natural language patterns).
965
- * Used for dual-condition exit gate.
966
- *
967
- * @param line - Line to check
968
- */
969
- private detectCompletionIndicators;
970
- /**
971
- * Generate @fix_plan.md content from current todos.
972
- * Groups todos by priority and status.
973
- *
974
- * @returns Markdown content for @fix_plan.md
975
- */
976
- generateFixPlanMarkdown(): string;
977
- /**
978
- * Parse @fix_plan.md content and import todos.
979
- * Replaces current todos with imported ones.
980
- *
981
- * @param content - Markdown content from @fix_plan.md
982
- * @returns Number of todos imported
983
- */
984
- importFixPlanMarkdown(content: string): number;
985
- /**
986
- * Initialize plan tasks from generated plan items.
987
- * Called when wizard generates a new plan.
988
- */
989
- initializePlanTasks(items: Array<{
990
- id?: string;
991
- content: string;
992
- priority?: 'P0' | 'P1' | 'P2' | null;
993
- verificationCriteria?: string;
994
- testCommand?: string;
995
- dependencies?: string[];
996
- tddPhase?: TddPhase;
997
- pairedWith?: string;
998
- complexity?: 'low' | 'medium' | 'high';
999
- }>): void;
1000
- /**
1001
- * Update a specific plan task's status, attempts, or error.
1002
- */
1003
- updatePlanTask(taskId: string, update: {
1004
- status?: PlanTaskStatus;
1005
- error?: string;
1006
- incrementAttempts?: boolean;
1007
- }): {
1008
- success: boolean;
1009
- task?: EnhancedPlanTask;
1010
- error?: string;
1011
- };
1012
- /**
1013
- * Unblock tasks that were waiting on a completed dependency.
1014
- */
1015
- private _unblockDependentTasks;
1016
- /**
1017
- * Check if current iteration is a checkpoint and emit review if so.
1018
- */
1019
- private _checkForCheckpoint;
1020
- /**
1021
- * Generate a checkpoint review summarizing plan progress and stuck tasks.
1022
- */
1023
- generateCheckpointReview(): CheckpointReview;
1024
- /**
1025
- * Save current plan state to history.
1026
- */
1027
- private _savePlanToHistory;
1028
- /**
1029
- * Get plan version history.
1030
- */
1031
- getPlanHistory(): Array<{
1032
- version: number;
1033
- timestamp: number;
1034
- summary: string;
1035
- stats: {
1036
- total: number;
1037
- completed: number;
1038
- failed: number;
1039
- };
1040
- }>;
1041
- /**
1042
- * Rollback to a previous plan version.
1043
- */
1044
- rollbackToVersion(version: number): {
1045
- success: boolean;
1046
- plan?: EnhancedPlanTask[];
1047
- error?: string;
1048
- };
1049
- /**
1050
- * Add a new task to the plan (for runtime adaptation).
1051
- */
1052
- addPlanTask(task: {
1053
- content: string;
1054
- priority?: 'P0' | 'P1' | 'P2';
1055
- verificationCriteria?: string;
1056
- dependencies?: string[];
1057
- insertAfter?: string;
1058
- }): {
1059
- task: EnhancedPlanTask;
1060
- };
1061
- /**
1062
- * Get all plan tasks.
1063
- */
1064
- getPlanTasks(): EnhancedPlanTask[];
1065
- /**
1066
- * Get current plan version.
1067
- */
1068
- get planVersion(): number;
1069
- /**
1070
- * Check if checkpoint review is due for current iteration.
1071
- */
1072
- isCheckpointDue(): boolean;
1073
602
  /**
1074
603
  * Clean up all resources and release memory.
1075
- *
1076
- * Call this when the session is being destroyed to prevent memory leaks.
1077
- * Stops file watchers, clears all timers, data, and removes event listeners.
1078
604
  */
1079
605
  destroy(): void;
1080
606
  }