aicodeman 0.2.8

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 (246) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +403 -0
  3. package/dist/ai-checker-base.d.ts +175 -0
  4. package/dist/ai-checker-base.d.ts.map +1 -0
  5. package/dist/ai-checker-base.js +424 -0
  6. package/dist/ai-checker-base.js.map +1 -0
  7. package/dist/ai-idle-checker.d.ts +53 -0
  8. package/dist/ai-idle-checker.d.ts.map +1 -0
  9. package/dist/ai-idle-checker.js +141 -0
  10. package/dist/ai-idle-checker.js.map +1 -0
  11. package/dist/ai-plan-checker.d.ts +52 -0
  12. package/dist/ai-plan-checker.d.ts.map +1 -0
  13. package/dist/ai-plan-checker.js +103 -0
  14. package/dist/ai-plan-checker.js.map +1 -0
  15. package/dist/bash-tool-parser.d.ts +191 -0
  16. package/dist/bash-tool-parser.d.ts.map +1 -0
  17. package/dist/bash-tool-parser.js +598 -0
  18. package/dist/bash-tool-parser.js.map +1 -0
  19. package/dist/cli.d.ts +12 -0
  20. package/dist/cli.d.ts.map +1 -0
  21. package/dist/cli.js +460 -0
  22. package/dist/cli.js.map +1 -0
  23. package/dist/config/buffer-limits.d.ts +59 -0
  24. package/dist/config/buffer-limits.d.ts.map +1 -0
  25. package/dist/config/buffer-limits.js +74 -0
  26. package/dist/config/buffer-limits.js.map +1 -0
  27. package/dist/config/map-limits.d.ts +40 -0
  28. package/dist/config/map-limits.d.ts.map +1 -0
  29. package/dist/config/map-limits.js +52 -0
  30. package/dist/config/map-limits.js.map +1 -0
  31. package/dist/file-stream-manager.d.ts +148 -0
  32. package/dist/file-stream-manager.d.ts.map +1 -0
  33. package/dist/file-stream-manager.js +351 -0
  34. package/dist/file-stream-manager.js.map +1 -0
  35. package/dist/hooks-config.d.ts +31 -0
  36. package/dist/hooks-config.d.ts.map +1 -0
  37. package/dist/hooks-config.js +115 -0
  38. package/dist/hooks-config.js.map +1 -0
  39. package/dist/image-watcher.d.ts +86 -0
  40. package/dist/image-watcher.d.ts.map +1 -0
  41. package/dist/image-watcher.js +275 -0
  42. package/dist/image-watcher.js.map +1 -0
  43. package/dist/index.d.ts +11 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +54 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/mux-factory.d.ts +13 -0
  48. package/dist/mux-factory.d.ts.map +1 -0
  49. package/dist/mux-factory.js +19 -0
  50. package/dist/mux-factory.js.map +1 -0
  51. package/dist/mux-interface.d.ts +145 -0
  52. package/dist/mux-interface.d.ts.map +1 -0
  53. package/dist/mux-interface.js +9 -0
  54. package/dist/mux-interface.js.map +1 -0
  55. package/dist/plan-orchestrator.d.ts +123 -0
  56. package/dist/plan-orchestrator.d.ts.map +1 -0
  57. package/dist/plan-orchestrator.js +500 -0
  58. package/dist/plan-orchestrator.js.map +1 -0
  59. package/dist/prompts/index.d.ts +9 -0
  60. package/dist/prompts/index.d.ts.map +1 -0
  61. package/dist/prompts/index.js +9 -0
  62. package/dist/prompts/index.js.map +1 -0
  63. package/dist/prompts/planner.d.ts +14 -0
  64. package/dist/prompts/planner.d.ts.map +1 -0
  65. package/dist/prompts/planner.js +83 -0
  66. package/dist/prompts/planner.js.map +1 -0
  67. package/dist/prompts/research-agent.d.ts +10 -0
  68. package/dist/prompts/research-agent.d.ts.map +1 -0
  69. package/dist/prompts/research-agent.js +143 -0
  70. package/dist/prompts/research-agent.js.map +1 -0
  71. package/dist/push-store.d.ts +41 -0
  72. package/dist/push-store.d.ts.map +1 -0
  73. package/dist/push-store.js +168 -0
  74. package/dist/push-store.js.map +1 -0
  75. package/dist/ralph-config.d.ts +67 -0
  76. package/dist/ralph-config.d.ts.map +1 -0
  77. package/dist/ralph-config.js +134 -0
  78. package/dist/ralph-config.js.map +1 -0
  79. package/dist/ralph-loop.d.ts +124 -0
  80. package/dist/ralph-loop.d.ts.map +1 -0
  81. package/dist/ralph-loop.js +418 -0
  82. package/dist/ralph-loop.js.map +1 -0
  83. package/dist/ralph-tracker.d.ts +1081 -0
  84. package/dist/ralph-tracker.d.ts.map +1 -0
  85. package/dist/ralph-tracker.js +3343 -0
  86. package/dist/ralph-tracker.js.map +1 -0
  87. package/dist/respawn-controller.d.ts +1182 -0
  88. package/dist/respawn-controller.d.ts.map +1 -0
  89. package/dist/respawn-controller.js +2754 -0
  90. package/dist/respawn-controller.js.map +1 -0
  91. package/dist/run-summary.d.ts +123 -0
  92. package/dist/run-summary.d.ts.map +1 -0
  93. package/dist/run-summary.js +325 -0
  94. package/dist/run-summary.js.map +1 -0
  95. package/dist/session-lifecycle-log.d.ts +36 -0
  96. package/dist/session-lifecycle-log.d.ts.map +1 -0
  97. package/dist/session-lifecycle-log.js +101 -0
  98. package/dist/session-lifecycle-log.js.map +1 -0
  99. package/dist/session-manager.d.ts +97 -0
  100. package/dist/session-manager.d.ts.map +1 -0
  101. package/dist/session-manager.js +224 -0
  102. package/dist/session-manager.js.map +1 -0
  103. package/dist/session.d.ts +686 -0
  104. package/dist/session.d.ts.map +1 -0
  105. package/dist/session.js +2025 -0
  106. package/dist/session.js.map +1 -0
  107. package/dist/state-store.d.ts +189 -0
  108. package/dist/state-store.d.ts.map +1 -0
  109. package/dist/state-store.js +730 -0
  110. package/dist/state-store.js.map +1 -0
  111. package/dist/subagent-watcher.d.ts +345 -0
  112. package/dist/subagent-watcher.d.ts.map +1 -0
  113. package/dist/subagent-watcher.js +1469 -0
  114. package/dist/subagent-watcher.js.map +1 -0
  115. package/dist/task-queue.d.ts +108 -0
  116. package/dist/task-queue.d.ts.map +1 -0
  117. package/dist/task-queue.js +235 -0
  118. package/dist/task-queue.js.map +1 -0
  119. package/dist/task-tracker.d.ts +306 -0
  120. package/dist/task-tracker.d.ts.map +1 -0
  121. package/dist/task-tracker.js +488 -0
  122. package/dist/task-tracker.js.map +1 -0
  123. package/dist/task.d.ts +73 -0
  124. package/dist/task.d.ts.map +1 -0
  125. package/dist/task.js +177 -0
  126. package/dist/task.js.map +1 -0
  127. package/dist/team-watcher.d.ts +53 -0
  128. package/dist/team-watcher.d.ts.map +1 -0
  129. package/dist/team-watcher.js +313 -0
  130. package/dist/team-watcher.js.map +1 -0
  131. package/dist/templates/case-template.md +461 -0
  132. package/dist/templates/claude-md.d.ts +26 -0
  133. package/dist/templates/claude-md.d.ts.map +1 -0
  134. package/dist/templates/claude-md.js +74 -0
  135. package/dist/templates/claude-md.js.map +1 -0
  136. package/dist/tmux-manager.d.ts +181 -0
  137. package/dist/tmux-manager.d.ts.map +1 -0
  138. package/dist/tmux-manager.js +1405 -0
  139. package/dist/tmux-manager.js.map +1 -0
  140. package/dist/transcript-watcher.d.ts +110 -0
  141. package/dist/transcript-watcher.d.ts.map +1 -0
  142. package/dist/transcript-watcher.js +338 -0
  143. package/dist/transcript-watcher.js.map +1 -0
  144. package/dist/tunnel-manager.d.ts +54 -0
  145. package/dist/tunnel-manager.d.ts.map +1 -0
  146. package/dist/tunnel-manager.js +251 -0
  147. package/dist/tunnel-manager.js.map +1 -0
  148. package/dist/types.d.ts +1139 -0
  149. package/dist/types.d.ts.map +1 -0
  150. package/dist/types.js +215 -0
  151. package/dist/types.js.map +1 -0
  152. package/dist/utils/buffer-accumulator.d.ts +111 -0
  153. package/dist/utils/buffer-accumulator.d.ts.map +1 -0
  154. package/dist/utils/buffer-accumulator.js +172 -0
  155. package/dist/utils/buffer-accumulator.js.map +1 -0
  156. package/dist/utils/claude-cli-resolver.d.ts +26 -0
  157. package/dist/utils/claude-cli-resolver.d.ts.map +1 -0
  158. package/dist/utils/claude-cli-resolver.js +78 -0
  159. package/dist/utils/claude-cli-resolver.js.map +1 -0
  160. package/dist/utils/cleanup-manager.d.ts +165 -0
  161. package/dist/utils/cleanup-manager.d.ts.map +1 -0
  162. package/dist/utils/cleanup-manager.js +274 -0
  163. package/dist/utils/cleanup-manager.js.map +1 -0
  164. package/dist/utils/index.d.ts +19 -0
  165. package/dist/utils/index.d.ts.map +1 -0
  166. package/dist/utils/index.js +19 -0
  167. package/dist/utils/index.js.map +1 -0
  168. package/dist/utils/lru-map.d.ts +140 -0
  169. package/dist/utils/lru-map.d.ts.map +1 -0
  170. package/dist/utils/lru-map.js +234 -0
  171. package/dist/utils/lru-map.js.map +1 -0
  172. package/dist/utils/nice-wrapper.d.ts +13 -0
  173. package/dist/utils/nice-wrapper.d.ts.map +1 -0
  174. package/dist/utils/nice-wrapper.js +17 -0
  175. package/dist/utils/nice-wrapper.js.map +1 -0
  176. package/dist/utils/opencode-cli-resolver.d.ts +21 -0
  177. package/dist/utils/opencode-cli-resolver.d.ts.map +1 -0
  178. package/dist/utils/opencode-cli-resolver.js +67 -0
  179. package/dist/utils/opencode-cli-resolver.js.map +1 -0
  180. package/dist/utils/regex-patterns.d.ts +64 -0
  181. package/dist/utils/regex-patterns.d.ts.map +1 -0
  182. package/dist/utils/regex-patterns.js +74 -0
  183. package/dist/utils/regex-patterns.js.map +1 -0
  184. package/dist/utils/stale-expiration-map.d.ts +159 -0
  185. package/dist/utils/stale-expiration-map.d.ts.map +1 -0
  186. package/dist/utils/stale-expiration-map.js +277 -0
  187. package/dist/utils/stale-expiration-map.js.map +1 -0
  188. package/dist/utils/string-similarity.d.ts +108 -0
  189. package/dist/utils/string-similarity.d.ts.map +1 -0
  190. package/dist/utils/string-similarity.js +189 -0
  191. package/dist/utils/string-similarity.js.map +1 -0
  192. package/dist/utils/token-validation.d.ts +39 -0
  193. package/dist/utils/token-validation.d.ts.map +1 -0
  194. package/dist/utils/token-validation.js +59 -0
  195. package/dist/utils/token-validation.js.map +1 -0
  196. package/dist/utils/type-safety.d.ts +33 -0
  197. package/dist/utils/type-safety.d.ts.map +1 -0
  198. package/dist/utils/type-safety.js +35 -0
  199. package/dist/utils/type-safety.js.map +1 -0
  200. package/dist/web/public/app.js +491 -0
  201. package/dist/web/public/app.js.br +0 -0
  202. package/dist/web/public/app.js.gz +0 -0
  203. package/dist/web/public/index.html +1675 -0
  204. package/dist/web/public/index.html.br +0 -0
  205. package/dist/web/public/index.html.gz +0 -0
  206. package/dist/web/public/manifest.json +8 -0
  207. package/dist/web/public/mobile.css +1 -0
  208. package/dist/web/public/mobile.css.br +0 -0
  209. package/dist/web/public/mobile.css.gz +0 -0
  210. package/dist/web/public/ralph-wizard.js +1037 -0
  211. package/dist/web/public/ralph-wizard.js.br +0 -0
  212. package/dist/web/public/ralph-wizard.js.gz +0 -0
  213. package/dist/web/public/styles.css +1 -0
  214. package/dist/web/public/styles.css.br +0 -0
  215. package/dist/web/public/styles.css.gz +0 -0
  216. package/dist/web/public/sw.js +67 -0
  217. package/dist/web/public/sw.js.br +0 -0
  218. package/dist/web/public/sw.js.gz +0 -0
  219. package/dist/web/public/upload.html +155 -0
  220. package/dist/web/public/upload.html.br +0 -0
  221. package/dist/web/public/upload.html.gz +0 -0
  222. package/dist/web/public/vendor/xterm-addon-fit.min.js +1 -0
  223. package/dist/web/public/vendor/xterm-addon-fit.min.js.br +0 -0
  224. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  225. package/dist/web/public/vendor/xterm-addon-unicode11.min.js +1 -0
  226. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.br +0 -0
  227. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  228. package/dist/web/public/vendor/xterm-addon-webgl.min.js +2 -0
  229. package/dist/web/public/vendor/xterm-addon-webgl.min.js.br +0 -0
  230. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  231. package/dist/web/public/vendor/xterm.css +209 -0
  232. package/dist/web/public/vendor/xterm.css.br +0 -0
  233. package/dist/web/public/vendor/xterm.css.gz +0 -0
  234. package/dist/web/public/vendor/xterm.min.js +9 -0
  235. package/dist/web/public/vendor/xterm.min.js.br +0 -0
  236. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  237. package/dist/web/schemas.d.ts +479 -0
  238. package/dist/web/schemas.d.ts.map +1 -0
  239. package/dist/web/schemas.js +448 -0
  240. package/dist/web/schemas.js.map +1 -0
  241. package/dist/web/server.d.ts +207 -0
  242. package/dist/web/server.d.ts.map +1 -0
  243. package/dist/web/server.js +5784 -0
  244. package/dist/web/server.js.map +1 -0
  245. package/package.json +110 -0
  246. package/scripts/postinstall.js +390 -0
@@ -0,0 +1,1081 @@
1
+ /**
2
+ * @fileoverview Ralph Tracker - Detects Ralph Wiggum loops, todos, and completion phrases
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
7
+ * - Completion phrases signaling loop completion
8
+ *
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.
12
+ *
13
+ * @module ralph-tracker
14
+ */
15
+ import { EventEmitter } from 'node:events';
16
+ 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
+ }
73
+ /**
74
+ * Events emitted by RalphTracker
75
+ * @event loopUpdate - Fired when loop state changes (active, iteration, completion phrase)
76
+ * @event todoUpdate - Fired when todo list changes (items added, status changed)
77
+ * @event completionDetected - Fired when completion phrase is detected (task complete)
78
+ * @event enabled - Fired when tracker auto-enables due to Ralph pattern detection
79
+ * @event statusBlockDetected - Fired when a RALPH_STATUS block is parsed
80
+ * @event circuitBreakerUpdate - Fired when circuit breaker state changes
81
+ * @event exitGateMet - Fired when dual-condition exit gate is met
82
+ */
83
+ export interface RalphTrackerEvents {
84
+ /** Emitted when loop state changes */
85
+ loopUpdate: (state: RalphTrackerState) => void;
86
+ /** Emitted when todo list is modified */
87
+ todoUpdate: (todos: RalphTodoItem[]) => void;
88
+ /** Emitted when completion phrase detected (loop finished) */
89
+ completionDetected: (phrase: string) => void;
90
+ /** Emitted when tracker auto-enables from disabled state */
91
+ enabled: () => void;
92
+ /** Emitted when a RALPH_STATUS block is parsed */
93
+ statusBlockDetected: (block: RalphStatusBlock) => void;
94
+ /** Emitted when circuit breaker state changes */
95
+ circuitBreakerUpdate: (status: CircuitBreakerStatus) => void;
96
+ /** Emitted when dual-condition exit gate is met (completion indicators >= 2 AND EXIT_SIGNAL: true) */
97
+ exitGateMet: (data: {
98
+ completionIndicators: number;
99
+ exitSignal: boolean;
100
+ }) => void;
101
+ /** Emitted when iteration count hasn't changed for an extended period (stall warning) */
102
+ iterationStallWarning: (data: {
103
+ iteration: number;
104
+ stallDurationMs: number;
105
+ }) => void;
106
+ /** Emitted when iteration count hasn't changed for critical period (stall critical) */
107
+ iterationStallCritical: (data: {
108
+ iteration: number;
109
+ stallDurationMs: number;
110
+ }) => void;
111
+ /** Emitted when a common/risky completion phrase is detected (P1-002) */
112
+ phraseValidationWarning: (data: {
113
+ phrase: string;
114
+ reason: 'common' | 'short' | 'numeric';
115
+ suggestedPhrase: string;
116
+ }) => void;
117
+ }
118
+ /**
119
+ * RalphTracker - Parses terminal output to detect Ralph Wiggum loops and todos
120
+ *
121
+ * This class monitors Claude Code session output to detect:
122
+ * 1. **Ralph Wiggum loop state** - Active loops, completion phrases, iteration counts
123
+ * 2. **Todo list items** - From TodoWrite tool in various formats
124
+ * 3. **Completion signals** - `<promise>PHRASE</promise>` tags
125
+ *
126
+ * ## Lifecycle
127
+ *
128
+ * The tracker is **DISABLED by default** and auto-enables when Ralph-related
129
+ * patterns are detected (e.g., /ralph-loop:ralph-loop, <promise>, todos).
130
+ * This reduces overhead for sessions not using autonomous loops.
131
+ *
132
+ * ## Completion Detection
133
+ *
134
+ * Uses occurrence-based detection to distinguish prompt from actual completion:
135
+ * - 1st occurrence of `<promise>X</promise>`: Stored as expected phrase (likely in prompt)
136
+ * - 2nd occurrence: Emits `completionDetected` event (actual completion)
137
+ * - If loop already active: Emits immediately on first occurrence
138
+ *
139
+ * ## Events
140
+ *
141
+ * - `loopUpdate` - Loop state changed (status, iteration, phrase)
142
+ * - `todoUpdate` - Todo list modified (add, status change)
143
+ * - `completionDetected` - Loop completion phrase detected
144
+ * - `enabled` - Tracker auto-enabled from disabled state
145
+ *
146
+ * @extends EventEmitter
147
+ * @example
148
+ * ```typescript
149
+ * const tracker = new RalphTracker();
150
+ * tracker.on('completionDetected', (phrase) => {
151
+ * console.log('Loop completed with phrase:', phrase);
152
+ * });
153
+ * tracker.processTerminalData(ptyOutput);
154
+ * ```
155
+ */
156
+ export declare class RalphTracker extends EventEmitter {
157
+ /** Current state of the detected loop */
158
+ private _loopState;
159
+ /** Map of todo items by ID for O(1) lookup */
160
+ private _todos;
161
+ /** Buffer for incomplete lines from terminal data */
162
+ private _lineBuffer;
163
+ /**
164
+ * Tracks occurrences of completion phrases.
165
+ * Used to distinguish prompt echo (1st) from actual completion (2nd+).
166
+ */
167
+ private _completionPhraseCount;
168
+ /** Timestamp of last cleanup check for throttling */
169
+ 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;
178
+ /** When true, prevents auto-enable on pattern detection */
179
+ private _autoEnableDisabled;
180
+ /** Maps task numbers from "✔ Task #N" format to their content for status updates */
181
+ private _taskNumberToContent;
182
+ /**
183
+ * Buffer for partial promise tags split across PTY chunks.
184
+ * Holds content after '<promise>' when closing tag hasn't arrived yet.
185
+ * Max 256 chars to prevent unbounded growth from malformed tags.
186
+ */
187
+ private _partialPromiseBuffer;
188
+ /** Maximum size of partial promise buffer */
189
+ 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
+ /** Alternate completion phrases (P1-003: multi-phrase support) - Set for O(1) lookup */
244
+ private _alternateCompletionPhrases;
245
+ /** History of todo completion times (ms) for averaging */
246
+ private _completionTimes;
247
+ /** Maximum number of completion times to track */
248
+ private static readonly MAX_COMPLETION_TIMES;
249
+ /** Timestamp when todos started being tracked for this session */
250
+ private _todosStartedAt;
251
+ /** Map of todo ID to timestamp when it started (for duration tracking) */
252
+ private _todoStartTimes;
253
+ /**
254
+ * Creates a new RalphTracker instance.
255
+ * Starts in disabled state until Ralph patterns are detected.
256
+ */
257
+ constructor();
258
+ /**
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
262
+ */
263
+ addAlternateCompletionPhrase(phrase: string): void;
264
+ /**
265
+ * Remove an alternate completion phrase.
266
+ * @param phrase - Phrase to remove
267
+ */
268
+ removeAlternateCompletionPhrase(phrase: string): void;
269
+ /**
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
273
+ */
274
+ isValidCompletionPhrase(phrase: string): boolean;
275
+ /**
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
279
+ */
280
+ private findMatchingCompletionPhrase;
281
+ /**
282
+ * Prevent auto-enable from pattern detection.
283
+ * Use this when the user has explicitly disabled the Ralph tracker.
284
+ */
285
+ disableAutoEnable(): void;
286
+ /**
287
+ * Allow auto-enable from pattern detection.
288
+ */
289
+ enableAutoEnable(): void;
290
+ /**
291
+ * Whether auto-enable is disabled.
292
+ */
293
+ get autoEnableDisabled(): boolean;
294
+ /**
295
+ * Set the working directory and start watching @fix_plan.md.
296
+ * Automatically loads existing @fix_plan.md if present.
297
+ * @param workingDir - The session's working directory
298
+ */
299
+ setWorkingDir(workingDir: string): void;
300
+ /**
301
+ * Load @fix_plan.md from disk if it exists.
302
+ * Called on initialization and when file changes are detected.
303
+ */
304
+ loadFixPlanFromDisk(): Promise<number>;
305
+ /**
306
+ * Start watching @fix_plan.md for changes.
307
+ * Reloads todos when the file is modified.
308
+ */
309
+ private startWatchingFixPlan;
310
+ /**
311
+ * Handle @fix_plan.md file change with debouncing.
312
+ */
313
+ private handleFixPlanChange;
314
+ /**
315
+ * Stop watching @fix_plan.md.
316
+ */
317
+ stopWatchingFixPlan(): void;
318
+ /**
319
+ * 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
+ */
323
+ get enabled(): boolean;
324
+ /**
325
+ * 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
+ * @fires enabled
329
+ * @fires loopUpdate
330
+ */
331
+ enable(): void;
332
+ /**
333
+ * Disable the tracker to stop monitoring terminal output.
334
+ * Terminal data will be ignored until re-enabled.
335
+ * @fires loopUpdate
336
+ */
337
+ disable(): void;
338
+ /**
339
+ * 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
+ * @fires loopUpdate
352
+ * @fires todoUpdate
353
+ */
354
+ reset(): void;
355
+ /**
356
+ * 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
+ * @fires loopUpdate
360
+ * @fires todoUpdate
361
+ */
362
+ fullReset(): void;
363
+ /**
364
+ * Clear all debounce timers.
365
+ * Called during reset/fullReset to prevent stale emissions.
366
+ */
367
+ private clearDebounceTimers;
368
+ /**
369
+ * 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
+ */
373
+ private emitTodoUpdateDebounced;
374
+ /**
375
+ * 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
+ */
379
+ private emitLoopUpdateDebounced;
380
+ /**
381
+ * Flush all pending debounced events immediately.
382
+ * Useful for testing or when immediate state sync is needed.
383
+ */
384
+ flushPendingEvents(): void;
385
+ /**
386
+ * 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
+ */
418
+ configureIterationStallThresholds(warningMs: number, criticalMs: number): void;
419
+ 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
+ * 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
+ */
440
+ calculateCompletionConfidence(phrase: string, context?: string): CompletionConfidence;
441
+ /**
442
+ * Get all tracked todo items as an array.
443
+ * @returns Array of todo items (copy, safe to modify)
444
+ */
445
+ get todos(): RalphTodoItem[];
446
+ /**
447
+ * 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
+ */
464
+ processTerminalData(data: string): void;
465
+ /**
466
+ * 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
+ */
469
+ processCleanData(cleanData: string): void;
470
+ /**
471
+ * 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
+ */
487
+ private shouldAutoEnable;
488
+ /**
489
+ * 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
+ */
493
+ private processLine;
494
+ /**
495
+ * 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
+ */
513
+ private detectAllTasksComplete;
514
+ /**
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.
520
+ */
521
+ private detectTaskCompletion;
522
+ /**
523
+ * 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
+ */
533
+ private checkMultiLinePatterns;
534
+ /**
535
+ * 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
+ */
548
+ private detectCompletionPhrase;
549
+ /**
550
+ * 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
+ */
566
+ private handleBareCompletionPhrase;
567
+ /**
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)
575
+ */
576
+ private handleCompletionPhrase;
577
+ /**
578
+ * 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
+ */
590
+ private isFuzzyPhraseMatch;
591
+ /**
592
+ * 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
+ */
604
+ private validateCompletionPhrase;
605
+ /**
606
+ * 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
+ */
614
+ private activateLoopIfNeeded;
615
+ /**
616
+ * 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
+ */
630
+ private detectLoopStatus;
631
+ /**
632
+ * 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
+ */
646
+ private detectTodoItems;
647
+ /**
648
+ * 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
+ */
658
+ private iconToStatus;
659
+ /**
660
+ * 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
+ */
671
+ private parsePriority;
672
+ /**
673
+ * 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
+ */
686
+ private upsertTodo;
687
+ /**
688
+ * 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
+ */
701
+ private normalizeTodoContent;
702
+ /**
703
+ * 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
+ */
714
+ private calculateSimilarity;
715
+ /**
716
+ * 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
+ */
723
+ private calculateBigramSimilarity;
724
+ /**
725
+ * 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
+ */
739
+ private findSimilarTodo;
740
+ /**
741
+ * 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
+ */
747
+ private estimateComplexity;
748
+ /**
749
+ * 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
+ */
755
+ private getEstimatedDuration;
756
+ /**
757
+ * Get average completion time from historical data.
758
+ * @returns Average time in ms, or null if no data
759
+ */
760
+ private getAverageCompletionTime;
761
+ /**
762
+ * Record a todo completion for progress tracking.
763
+ * @param todoId - ID of the completed todo
764
+ */
765
+ private recordTodoCompletion;
766
+ /**
767
+ * Start tracking a todo for duration estimation.
768
+ * @param todoId - ID of the todo being started
769
+ */
770
+ private startTrackingTodo;
771
+ /**
772
+ * 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
+ */
778
+ 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
+ /**
789
+ * 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
+ */
797
+ private generateTodoId;
798
+ /**
799
+ * 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
+ */
803
+ private findOldestTodo;
804
+ /**
805
+ * Conditionally run cleanup, throttled to CLEANUP_THROTTLE_MS.
806
+ * Prevents cleanup from running on every data chunk (performance).
807
+ */
808
+ private maybeCleanupExpiredTodos;
809
+ /**
810
+ * 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
+ */
814
+ private cleanupExpiredTodos;
815
+ /**
816
+ * 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
+ */
828
+ startLoop(completionPhrase?: string, maxIterations?: number): void;
829
+ /**
830
+ * 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
+ */
835
+ setMaxIterations(maxIterations: number | null): void;
836
+ /**
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
842
+ */
843
+ configure(config: {
844
+ enabled?: boolean;
845
+ completionPhrase?: string;
846
+ maxIterations?: number;
847
+ }): void;
848
+ /**
849
+ * 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
+ */
856
+ stopLoop(): void;
857
+ /**
858
+ * Enforce size limit on _taskNumberToContent map.
859
+ * Removes lowest task numbers (oldest tasks) when limit exceeded.
860
+ */
861
+ private enforceTaskMappingLimit;
862
+ /**
863
+ * 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
+ */
871
+ clear(): void;
872
+ /**
873
+ * 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
+ */
881
+ getTodoStats(): {
882
+ total: number;
883
+ pending: number;
884
+ inProgress: number;
885
+ completed: number;
886
+ };
887
+ /**
888
+ * 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
+ */
898
+ 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
+ /**
1074
+ * 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
+ */
1079
+ destroy(): void;
1080
+ }
1081
+ //# sourceMappingURL=ralph-tracker.d.ts.map