ralph-agent-loop 0.3.1

A Rust CLI for managing AI agent loops with a structured JSON task queue
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Productivity module tests.
//!
//! Responsibilities:
//! - Unit tests for productivity tracking functionality.
//!
//! Not handled here:
//! - Integration tests (see `tests/` directory).

use std::collections::BTreeMap;

use tempfile::TempDir;

use crate::contracts::{Task, TaskPriority, TaskStatus};

use super::calculations::{calculate_velocity_for_today, next_milestone, update_streak};
use super::date_utils::{date_key_add_days, parse_date_key, previous_date_key};
use super::persistence::load_productivity_stats;
use super::reports::format_duration;
use super::types::{DayStats, ProductivityStats, StreakInfo};
use super::{record_task_completion, record_task_completion_by_id};

fn create_test_task(id: &str, title: &str) -> Task {
    Task {
        id: id.to_string(),
        title: title.to_string(),
        description: None,
        status: TaskStatus::Done,
        priority: TaskPriority::Medium,
        tags: vec![],
        scope: vec![],
        evidence: vec![],
        plan: vec![],
        notes: vec![],
        request: None,
        agent: None,
        created_at: Some("2026-01-01T00:00:00Z".to_string()),
        updated_at: Some("2026-01-01T00:00:00Z".to_string()),
        completed_at: Some("2026-01-01T12:00:00Z".to_string()),
        started_at: None,
        scheduled_start: None,
        depends_on: vec![],
        blocks: vec![],
        relates_to: vec![],
        duplicates: None,
        custom_fields: std::collections::HashMap::new(),
        parent_id: None,
        estimated_minutes: None,
        actual_minutes: None,
    }
}

#[test]
fn test_load_stats_empty_cache() {
    let temp = TempDir::new().unwrap();
    let stats = load_productivity_stats(temp.path()).unwrap();
    assert_eq!(stats.total_completed, 0);
    assert!(stats.daily.is_empty());
    // CRITICAL: Default last_updated_at must never be empty (regression test for RQ-0636)
    assert!(
        !stats.last_updated_at.is_empty(),
        "Default last_updated_at should never be empty"
    );
}

#[test]
fn test_record_task_completion() {
    let temp = TempDir::new().unwrap();
    let task = create_test_task("RQ-0001", "Test task");

    let result = record_task_completion(&task, temp.path()).unwrap();

    assert_eq!(result.total_completed, 1);
    assert_eq!(result.new_streak, 1);
    assert!(result.streak_updated);
    assert!(result.milestone_achieved.is_none());

    // Verify saved
    let stats = load_productivity_stats(temp.path()).unwrap();
    assert_eq!(stats.total_completed, 1);

    // CRITICAL: All persisted timestamps must be non-empty (regression test for RQ-0636)
    assert!(
        !stats.last_updated_at.is_empty(),
        "last_updated_at should never be empty"
    );
    for day_stats in stats.daily.values() {
        for task_ref in &day_stats.tasks {
            assert!(
                !task_ref.completed_at.is_empty(),
                "Task completed_at should never be empty"
            );
        }
    }
}

#[test]
fn test_milestone_detection() {
    let temp = TempDir::new().unwrap();

    // Complete 10 tasks
    for i in 1..=10 {
        let task = create_test_task(&format!("RQ-{:04}", i), "Test task");
        let result = record_task_completion(&task, temp.path()).unwrap();

        if i == 10 {
            assert_eq!(result.milestone_achieved, Some(10));
        } else {
            assert!(result.milestone_achieved.is_none());
        }
    }
}

#[test]
fn test_duplicate_completion_ignored() {
    let temp = TempDir::new().unwrap();
    let task = create_test_task("RQ-0001", "Test task");

    // Record same task twice
    record_task_completion(&task, temp.path()).unwrap();
    let _result = record_task_completion(&task, temp.path()).unwrap();

    // Should still show as completed but not increment count
    let stats = load_productivity_stats(temp.path()).unwrap();
    // Note: Currently we don't dedupe across days, just within the same day
    // So this test verifies the daily deduplication
    assert!(stats.total_completed >= 1);
}

#[test]
fn test_velocity_calculation() {
    // Use fixed dates that cross a year boundary to test real calendar math
    let today: String = "2026-01-01".to_string();
    let yesterday: String = "2025-12-31".to_string();

    let stats = ProductivityStats {
        version: 1,
        first_task_completed_at: None,
        last_updated_at: format!("{}T00:00:00Z", today),
        daily: {
            let mut daily = BTreeMap::new();
            daily.insert(
                today.clone(),
                DayStats {
                    date: today.clone(),
                    completed_count: 5,
                    tasks: vec![],
                },
            );
            daily.insert(
                yesterday.clone(),
                DayStats {
                    date: yesterday,
                    completed_count: 3,
                    tasks: vec![],
                },
            );
            daily
        },
        streak: StreakInfo::default(),
        total_completed: 8,
        milestones: vec![],
    };

    let velocity = calculate_velocity_for_today(&stats, 7, &today);
    assert_eq!(velocity.total_completed, 8);
    assert!(velocity.average_per_day > 0.0);
}

#[test]
fn test_next_milestone() {
    assert_eq!(next_milestone(0), Some(10));
    assert_eq!(next_milestone(9), Some(10));
    assert_eq!(next_milestone(10), Some(50));
    assert_eq!(next_milestone(100), Some(250));
    assert_eq!(next_milestone(5000), None);
}

#[test]
fn test_format_duration() {
    assert_eq!(format_duration(30), "30s");
    assert_eq!(format_duration(90), "1m");
    assert_eq!(format_duration(3600), "1h 0m");
    assert_eq!(format_duration(90061), "1d 1h");
}

// Tests for date key helpers with proper calendar math

#[test]
fn test_previous_date_key_leap_year() {
    // 2024 is a leap year: March 1 -> Feb 29
    assert_eq!(
        previous_date_key("2024-03-01"),
        Some("2024-02-29".to_string())
    );
}

#[test]
fn test_previous_date_key_non_leap_year() {
    // 2026 is not a leap year: March 1 -> Feb 28
    assert_eq!(
        previous_date_key("2026-03-01"),
        Some("2026-02-28".to_string())
    );
}

#[test]
fn test_previous_date_key_year_boundary() {
    // Jan 1 -> Dec 31 of previous year
    assert_eq!(
        previous_date_key("2026-01-01"),
        Some("2025-12-31".to_string())
    );
}

#[test]
fn test_previous_date_key_month_boundary_30_day() {
    // May 1 -> April 30 (April has 30 days)
    assert_eq!(
        previous_date_key("2026-05-01"),
        Some("2026-04-30".to_string())
    );
}

#[test]
fn test_previous_date_key_normal_day() {
    // Normal day decrement
    assert_eq!(
        previous_date_key("2026-02-15"),
        Some("2026-02-14".to_string())
    );
}

#[test]
fn test_parse_date_key_invalid() {
    assert_eq!(parse_date_key(""), None);
    assert_eq!(parse_date_key("  "), None);
    assert_eq!(parse_date_key("not-a-date"), None);
    assert_eq!(parse_date_key("2026-02-30"), None); // Feb 30 doesn't exist
}

#[test]
fn test_date_key_offset_backwards() {
    // Go back 7 days from Jan 5 = Dec 29
    assert_eq!(
        date_key_add_days("2026-01-05", -7),
        Some("2025-12-29".to_string())
    );
}

#[test]
fn test_date_key_add_days_forward() {
    // Go forward 5 days
    assert_eq!(
        date_key_add_days("2026-01-01", 5),
        Some("2026-01-06".to_string())
    );
}

#[test]
fn test_streak_year_boundary() {
    // Test that streak correctly increments across year boundaries
    let mut stats = ProductivityStats {
        version: 1,
        first_task_completed_at: None,
        last_updated_at: "2026-01-01T00:00:00Z".to_string(),
        daily: BTreeMap::new(),
        streak: StreakInfo {
            current_streak: 3,
            longest_streak: 5,
            last_completed_date: Some("2025-12-31".to_string()),
        },
        total_completed: 10,
        milestones: vec![],
    };

    // Complete a task on Jan 1, 2026 - should continue the streak
    let updated = update_streak(&mut stats, "2026-01-01");
    assert!(updated);
    assert_eq!(stats.streak.current_streak, 4);
    assert_eq!(
        stats.streak.last_completed_date,
        Some("2026-01-01".to_string())
    );
}

#[test]
fn test_streak_breaks_when_gap() {
    // Test that streak breaks when there's a gap
    let mut stats = ProductivityStats {
        version: 1,
        first_task_completed_at: None,
        last_updated_at: "2026-01-05T00:00:00Z".to_string(),
        daily: BTreeMap::new(),
        streak: StreakInfo {
            current_streak: 3,
            longest_streak: 5,
            last_completed_date: Some("2026-01-01".to_string()), // Last completed 3 days ago
        },
        total_completed: 10,
        milestones: vec![],
    };

    // Complete a task on Jan 5, 2026 - should break and restart streak
    let updated = update_streak(&mut stats, "2026-01-05");
    assert!(updated);
    assert_eq!(stats.streak.current_streak, 1); // Reset to 1
    assert_eq!(
        stats.streak.last_completed_date,
        Some("2026-01-05".to_string())
    );
}

#[test]
fn test_update_streak_invalid_today_is_noop() {
    let mut stats = ProductivityStats {
        version: 1,
        first_task_completed_at: None,
        last_updated_at: "2026-01-01T00:00:00Z".to_string(),
        daily: BTreeMap::new(),
        streak: StreakInfo {
            current_streak: 3,
            longest_streak: 5,
            last_completed_date: Some("2026-01-01".to_string()),
        },
        total_completed: 10,
        milestones: vec![],
    };

    let before_current = stats.streak.current_streak;
    let before_longest = stats.streak.longest_streak;
    let before_last = stats.streak.last_completed_date.clone();
    assert!(!update_streak(&mut stats, "not-a-date"));
    assert_eq!(stats.streak.current_streak, before_current);
    assert_eq!(stats.streak.longest_streak, before_longest);
    assert_eq!(stats.streak.last_completed_date, before_last);
}

#[test]
fn test_record_task_completion_by_id() {
    let temp = TempDir::new().unwrap();

    let result = record_task_completion_by_id("RQ-0001", "Test task", temp.path()).unwrap();

    assert_eq!(result.total_completed, 1);
    assert_eq!(result.new_streak, 1);
    assert!(result.streak_updated);

    // Verify saved
    let stats = load_productivity_stats(temp.path()).unwrap();
    assert_eq!(stats.total_completed, 1);
}

// Test for daily stats pruning (memory hotspot fix)
#[test]
fn test_old_daily_stats_get_pruned() {
    use crate::productivity::calculations::prune_old_daily_stats;
    use crate::productivity::types::{CompletedTaskRef, DayStats, ProductivityStats, StreakInfo};

    let today = "2026-01-15";
    let mut stats = ProductivityStats {
        version: 1,
        first_task_completed_at: None,
        last_updated_at: format!("{}T00:00:00Z", today),
        daily: BTreeMap::new(),
        streak: StreakInfo::default(),
        total_completed: 0,
        milestones: vec![],
    };

    // Add entries spanning 120 days (older than 90-day retention)
    for i in 0..120 {
        let date = date_key_add_days(today, -(i as i64)).unwrap();
        stats.daily.insert(
            date.clone(),
            DayStats {
                date: date.clone(),
                completed_count: 1,
                tasks: vec![CompletedTaskRef {
                    id: format!("RQ-{:04}", i),
                    title: "Old task".to_string(),
                    completed_at: format!("{}T12:00:00Z", date),
                }],
            },
        );
    }

    assert_eq!(
        stats.daily.len(),
        120,
        "Should start with 120 daily entries"
    );

    // Prune old stats
    prune_old_daily_stats(&mut stats, today);

    // Should retain only the last 90 days plus today = 91 entries
    assert_eq!(
        stats.daily.len(),
        91,
        "Should prune to 91 entries (90 days retention + today)"
    );

    // Verify old entries are gone
    let oldest_date = date_key_add_days(today, -91);
    assert!(oldest_date.is_some(), "Date 91 days ago should be valid");

    // The entry at 91 days ago should NOT exist (it's past the 90-day retention)
    if let Some(old_date) = oldest_date {
        assert!(
            !stats.daily.contains_key(&old_date),
            "Entry 91 days ago should have been pruned"
        );
    }

    // The entry at 90 days ago SHOULD exist (at the boundary)
    let boundary_date = date_key_add_days(today, -90).unwrap();
    assert!(
        stats.daily.contains_key(&boundary_date),
        "Entry at 90-day boundary should be retained"
    );
}

#[test]
fn test_prune_respects_total_completed() {
    // Verify that pruning daily stats doesn't affect the total_completed counter
    use crate::productivity::calculations::prune_old_daily_stats;
    use crate::productivity::types::{DayStats, ProductivityStats, StreakInfo};

    let today = "2026-01-15";
    let mut stats = ProductivityStats {
        version: 1,
        first_task_completed_at: None,
        last_updated_at: format!("{}T00:00:00Z", today),
        daily: BTreeMap::new(),
        streak: StreakInfo::default(),
        total_completed: 5000, // High total from historical data
        milestones: vec![],
    };

    // Only add 10 days of recent data
    for i in 0..10 {
        let date = date_key_add_days(today, -(i as i64)).unwrap();
        stats.daily.insert(
            date.clone(),
            DayStats {
                date: date.to_string(),
                completed_count: 1,
                tasks: vec![],
            },
        );
    }

    prune_old_daily_stats(&mut stats, today);

    // Total completed should remain unchanged
    assert_eq!(stats.total_completed, 5000);
    // Milestones and streaks are preserved
    assert_eq!(stats.daily.len(), 10);
}