ralph-workflow 0.7.18

PROMPT-driven multi-agent orchestrator for git repos
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Typed prompt scope key for replay identity.
//!
//! RFC-007 Short-term corrective action #1 and #5: Replace ad-hoc `format!()` string keys
//! with a typed `PromptScopeKey` struct that makes missing identity dimensions impossible
//! at compile time.
//!
//! # Design
//!
//! Each prompt key has a phase-specific set of identity dimensions:
//! - **Planning**: iteration + `retry_mode`
//! - **Development**: iteration + optional continuation + `retry_mode`
//! - **Commit**: iteration + attempt + `retry_mode`
//! - **Review**: pass + `retry_mode`
//! - **Fix**: pass + `retry_mode`
//!
//! `recovery_epoch` is carried for auditing/future isolation but is NOT included
//! in the `Display` string to preserve checkpoint backward-compatibility.
//! Level-3/4 recovery increments `recovery_epoch` and clears `PipelineState.prompt_history`
//! atomically. This is the safety mechanism that prevents stale prompt replay across
//! epoch boundaries, even if iteration counters are reset or reused.
//!
//! # Backward Compatibility
//!
//! The `Display` implementation produces strings identical to the `format!()` calls
//! it replaces. Existing checkpoint `prompt_history` maps remain compatible.

use std::fmt;

/// The pipeline phase that a prompt belongs to.
///
/// Used as a discriminant in `PromptScopeKey` to ensure callers construct
/// keys with the correct phase-specific constructor.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PromptPhase {
    /// Planning phase (iteration-scoped).
    Planning,
    /// Development phase (iteration-scoped, optional continuation).
    Development,
    /// Commit message phase (iteration + attempt-scoped).
    Commit,
    /// Review phase (pass-scoped).
    Review,
    /// Fix phase (pass-scoped).
    Fix,
    /// Rebase conflict resolution phase (rebase-phase-name-scoped).
    ///
    /// `phase` is the lowercase rebase phase name (e.g., "planning", "development")
    /// derived from git rebase context, not the main pipeline phase.
    ConflictResolution {
        /// The rebase phase name (lowercase).
        phase: String,
    },
}

/// The retry mode for a prompt invocation.
///
/// Included in the scope key to distinguish fresh prompts from retry variants.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RetryMode {
    /// Normal (first attempt or continuation) — no retry suffix.
    Normal,
    /// Same-agent retry — appends `_same_agent_retry_{count}` suffix.
    SameAgent {
        /// Retry count (1-based).
        count: u32,
    },
    /// XSD validation retry — appends `_xsd_retry_{count}` suffix.
    Xsd {
        /// Retry count (1-based).
        count: u32,
    },
}

/// Typed prompt scope key.
///
/// Uniquely identifies a prompt for replay from checkpoint history.
/// Constructed via phase-specific factory methods to enforce required dimensions.
///
/// # Backward Compatibility
///
/// `Display` output exactly matches the `format!()` strings previously used in handlers.
/// The `recovery_epoch` field is NOT part of `Display` — it is a future-proofing hook
/// and an audit dimension only.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PromptScopeKey {
    /// Pipeline phase this prompt belongs to.
    phase: PromptPhase,
    /// Development iteration (0-based). Used by Planning, Development, Commit phases.
    iteration: u32,
    /// Review/fix pass number (0-based). Used by Review and Fix phases.
    pass: Option<u32>,
    /// Commit attempt number within the iteration. Used by Commit phase.
    attempt: Option<u32>,
    /// Continuation attempt within a development iteration. Used by Development phase.
    continuation: Option<u32>,
    /// Retry mode for this invocation.
    retry_mode: RetryMode,
    /// Recovery epoch counter — number of epoch-resetting recoveries (level-3/4) that have
    /// occurred. NOT included in `Display` but carried for auditing and future isolation.
    recovery_epoch: u32,
}

impl PromptScopeKey {
    /// Construct a key for the Planning phase.
    #[must_use]
    pub const fn for_planning(iteration: u32, retry_mode: RetryMode, recovery_epoch: u32) -> Self {
        Self {
            phase: PromptPhase::Planning,
            iteration,
            pass: None,
            attempt: None,
            continuation: None,
            retry_mode,
            recovery_epoch,
        }
    }

    /// Construct a key for the Development phase.
    ///
    /// Set `continuation` to `Some(attempt)` for continuation mode,
    /// or `None` for normal and retry modes.
    #[must_use]
    pub const fn for_development(
        iteration: u32,
        continuation: Option<u32>,
        retry_mode: RetryMode,
        recovery_epoch: u32,
    ) -> Self {
        Self {
            phase: PromptPhase::Development,
            iteration,
            pass: None,
            attempt: None,
            continuation,
            retry_mode,
            recovery_epoch,
        }
    }

    /// Construct a key for the Commit phase.
    #[must_use]
    pub const fn for_commit(
        iteration: u32,
        attempt: u32,
        retry_mode: RetryMode,
        recovery_epoch: u32,
    ) -> Self {
        Self {
            phase: PromptPhase::Commit,
            iteration,
            pass: None,
            attempt: Some(attempt),
            continuation: None,
            retry_mode,
            recovery_epoch,
        }
    }

    /// Construct a key for the Review phase.
    #[must_use]
    pub const fn for_review(pass: u32, retry_mode: RetryMode, recovery_epoch: u32) -> Self {
        Self {
            phase: PromptPhase::Review,
            iteration: 0,
            pass: Some(pass),
            attempt: None,
            continuation: None,
            retry_mode,
            recovery_epoch,
        }
    }

    /// Construct a key for the Fix phase.
    #[must_use]
    pub const fn for_fix(pass: u32, retry_mode: RetryMode, recovery_epoch: u32) -> Self {
        Self {
            phase: PromptPhase::Fix,
            iteration: 0,
            pass: Some(pass),
            attempt: None,
            continuation: None,
            retry_mode,
            recovery_epoch,
        }
    }

    /// Construct a key for a rebase conflict resolution prompt.
    ///
    /// The `phase` argument is the rebase phase name (lowercase), e.g. `"planning"`
    /// or `"development"`, derived from the git rebase context. It is NOT a main
    /// pipeline phase — it identifies which rebase phase triggered the conflict.
    ///
    /// `recovery_epoch` is carried for auditing but the rebase handler owns epoch
    /// semantics via `PromptCaptured` events. Pass `0` from effectful helpers.
    ///
    /// The `Display` output (`"{phase}_conflict_resolution"`) is byte-identical to
    /// the former `format!("{}_conflict_resolution", phase.to_lowercase())` calls,
    /// preserving backward-compatibility with existing checkpoint `prompt_history` maps.
    #[must_use]
    pub fn for_conflict_resolution(phase: &str, recovery_epoch: u32) -> Self {
        Self {
            phase: PromptPhase::ConflictResolution {
                phase: phase.to_lowercase(),
            },
            iteration: 0,
            pass: None,
            attempt: None,
            continuation: None,
            retry_mode: RetryMode::Normal,
            recovery_epoch,
        }
    }
}

/// Display implementation producing strings largely backward-compatible with existing checkpoint data.
///
/// Output format per phase:
/// - Planning: `planning_{iter}[_{retry_suffix}]`
/// - Development: `development_{iter}[_continuation_{n}][_{retry_suffix}]`
/// - Commit: `commit_message_attempt_iter{iter}_{attempt}[_{retry_suffix}]` (NOTE: includes iteration; this intentionally differs from pre-RFC-007 attempt-only commit keys)
/// - Review: `review_{pass}[_{retry_suffix}]`
/// - Fix: `fix_{pass}[_{retry_suffix}]`
///
/// Retry suffixes:
/// - `SameAgent { count }` → `_same_agent_retry_{count}`
/// - `Xsd { count }` → `_xsd_retry_{count}`
///
/// NOTE: `recovery_epoch` is intentionally excluded from Display to preserve
/// backward-compatibility with existing checkpoint `prompt_history` entries.
impl fmt::Display for PromptScopeKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let base = match &self.phase {
            PromptPhase::Planning => format!("planning_{}", self.iteration),
            PromptPhase::Development => self.continuation.map_or_else(
                || format!("development_{}", self.iteration),
                |c| format!("development_{}_continuation_{}", self.iteration, c),
            ),
            PromptPhase::Commit => format!(
                "commit_message_attempt_iter{}_{}",
                self.iteration,
                self.attempt.unwrap_or(1)
            ),
            PromptPhase::Review => format!("review_{}", self.pass.unwrap_or(1)),
            PromptPhase::Fix => format!("fix_{}", self.pass.unwrap_or(1)),
            PromptPhase::ConflictResolution { phase } => {
                format!("{phase}_conflict_resolution")
            }
        };
        match &self.retry_mode {
            RetryMode::Normal => write!(f, "{base}"),
            RetryMode::SameAgent { count } => write!(f, "{base}_same_agent_retry_{count}"),
            RetryMode::Xsd { count } => write!(f, "{base}_xsd_retry_{count}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // =========================================================================
    // Planning phase key tests
    // =========================================================================

    #[test]
    fn planning_normal_key_matches_legacy_format() {
        let key = PromptScopeKey::for_planning(0, RetryMode::Normal, 0);
        assert_eq!(key.to_string(), "planning_0");
    }

    #[test]
    fn planning_normal_key_iteration_2() {
        let key = PromptScopeKey::for_planning(2, RetryMode::Normal, 0);
        assert_eq!(key.to_string(), "planning_2");
    }

    #[test]
    fn planning_same_agent_retry_key_matches_legacy_format() {
        let key = PromptScopeKey::for_planning(0, RetryMode::SameAgent { count: 2 }, 0);
        assert_eq!(key.to_string(), "planning_0_same_agent_retry_2");
    }

    // =========================================================================
    // Development phase key tests
    // =========================================================================

    #[test]
    fn development_normal_key_matches_legacy_format() {
        let key = PromptScopeKey::for_development(0, None, RetryMode::Normal, 0);
        assert_eq!(key.to_string(), "development_0");
    }

    #[test]
    fn development_continuation_key_matches_legacy_format() {
        let key = PromptScopeKey::for_development(0, Some(3), RetryMode::Normal, 0);
        assert_eq!(key.to_string(), "development_0_continuation_3");
    }

    #[test]
    fn development_same_agent_retry_key_matches_legacy_format() {
        let key = PromptScopeKey::for_development(2, None, RetryMode::SameAgent { count: 1 }, 0);
        assert_eq!(key.to_string(), "development_2_same_agent_retry_1");
    }

    // =========================================================================
    // Commit phase key tests
    // =========================================================================

    #[test]
    fn commit_normal_key_matches_legacy_format() {
        let key = PromptScopeKey::for_commit(0, 1, RetryMode::Normal, 0);
        assert_eq!(key.to_string(), "commit_message_attempt_iter0_1");
    }

    #[test]
    fn commit_same_agent_retry_key_matches_legacy_format() {
        let key = PromptScopeKey::for_commit(0, 1, RetryMode::SameAgent { count: 1 }, 0);
        assert_eq!(
            key.to_string(),
            "commit_message_attempt_iter0_1_same_agent_retry_1"
        );
    }

    #[test]
    fn commit_xsd_retry_key_matches_legacy_format() {
        let key = PromptScopeKey::for_commit(0, 1, RetryMode::Xsd { count: 1 }, 0);
        assert_eq!(
            key.to_string(),
            "commit_message_attempt_iter0_1_xsd_retry_1"
        );
    }

    // =========================================================================
    // Review phase key tests
    // =========================================================================

    #[test]
    fn review_normal_key_matches_legacy_format() {
        let key = PromptScopeKey::for_review(0, RetryMode::Normal, 0);
        assert_eq!(key.to_string(), "review_0");
    }

    #[test]
    fn review_xsd_retry_key_matches_legacy_format() {
        // invalid_output_attempts is the XSD retry count for review
        let key = PromptScopeKey::for_review(1, RetryMode::Xsd { count: 3 }, 0);
        assert_eq!(key.to_string(), "review_1_xsd_retry_3");
    }

    #[test]
    fn review_same_agent_retry_key_matches_legacy_format() {
        let key = PromptScopeKey::for_review(1, RetryMode::SameAgent { count: 2 }, 0);
        assert_eq!(key.to_string(), "review_1_same_agent_retry_2");
    }

    // =========================================================================
    // Fix phase key tests
    // =========================================================================

    #[test]
    fn fix_normal_key_matches_legacy_format() {
        let key = PromptScopeKey::for_fix(1, RetryMode::Normal, 0);
        assert_eq!(key.to_string(), "fix_1");
    }

    #[test]
    fn fix_same_agent_retry_key_matches_legacy_format() {
        let key = PromptScopeKey::for_fix(1, RetryMode::SameAgent { count: 1 }, 0);
        assert_eq!(key.to_string(), "fix_1_same_agent_retry_1");
    }

    #[test]
    fn fix_xsd_retry_key_matches_legacy_format() {
        let key = PromptScopeKey::for_fix(1, RetryMode::Xsd { count: 2 }, 0);
        assert_eq!(key.to_string(), "fix_1_xsd_retry_2");
    }

    // =========================================================================
    // recovery_epoch isolation tests
    // =========================================================================

    #[test]
    fn recovery_epoch_not_in_display_string() {
        // Two keys with same phase/iteration/retry but different epochs
        // must produce the same Display string (epoch not in key string)
        let key_epoch_0 = PromptScopeKey::for_planning(1, RetryMode::Normal, 0);
        let key_epoch_1 = PromptScopeKey::for_planning(1, RetryMode::Normal, 1);
        assert_eq!(
            key_epoch_0.to_string(),
            key_epoch_1.to_string(),
            "recovery_epoch must not affect Display string for checkpoint compat"
        );
    }

    #[test]
    fn keys_are_unique_across_phases() {
        let planning = PromptScopeKey::for_planning(1, RetryMode::Normal, 0).to_string();
        let development =
            PromptScopeKey::for_development(1, None, RetryMode::Normal, 0).to_string();
        let commit = PromptScopeKey::for_commit(1, 1, RetryMode::Normal, 0).to_string();
        let review = PromptScopeKey::for_review(1, RetryMode::Normal, 0).to_string();
        let fix = PromptScopeKey::for_fix(1, RetryMode::Normal, 0).to_string();

        let all = [&planning, &development, &commit, &review, &fix];
        assert!(all.iter().enumerate().all(|(i, k1)| {
            all.iter()
                .enumerate()
                .filter(|(j, _)| i != *j)
                .all(|(_, k2)| k1 != k2)
        }));
    }

    #[test]
    fn keys_are_unique_across_retry_modes() {
        let normal = PromptScopeKey::for_planning(1, RetryMode::Normal, 0).to_string();
        let same_agent =
            PromptScopeKey::for_planning(1, RetryMode::SameAgent { count: 1 }, 0).to_string();
        assert_ne!(normal, same_agent);
    }

    #[test]
    fn keys_are_unique_across_iterations() {
        let iter1 = PromptScopeKey::for_planning(1, RetryMode::Normal, 0).to_string();
        let iter2 = PromptScopeKey::for_planning(2, RetryMode::Normal, 0).to_string();
        assert_ne!(iter1, iter2);
    }

    /// SC-2: Development phase keys are unique across iterations.
    ///
    /// Ensures that iteration 2's development prompt key cannot collide with
    /// iteration 1's key, so a checkpoint from cycle 1 cannot be replayed in cycle 2.
    #[test]
    fn development_keys_are_unique_across_iterations() {
        let iter1 = PromptScopeKey::for_development(1, None, RetryMode::Normal, 0).to_string();
        let iter2 = PromptScopeKey::for_development(2, None, RetryMode::Normal, 0).to_string();
        assert_ne!(
            iter1, iter2,
            "Development keys must differ across iterations to prevent stale replay. \
             iter1='{iter1}', iter2='{iter2}'"
        );
    }

    /// Regression test for the root cause of the stale prompt replay bug (RFC-007).
    ///
    /// The bug: commit attempt numbers reset to 1 on each new commit cycle. Before
    /// the fix, keys were `commit_message_attempt_1` (attempt-only), so iter2/attempt1
    /// would collide with iter1/attempt1 and replay the stale first-cycle prompt.
    ///
    /// After the fix, keys include the iteration dimension:
    /// `commit_message_attempt_iter1_1` != `commit_message_attempt_iter2_1`.
    #[test]
    fn commit_keys_are_unique_across_iterations_same_attempt() {
        // Both use attempt=1 (attempt resets to 1 on each new commit cycle — the bug scenario)
        let iter1_attempt1 = PromptScopeKey::for_commit(1, 1, RetryMode::Normal, 0).to_string();
        let iter2_attempt1 = PromptScopeKey::for_commit(2, 1, RetryMode::Normal, 0).to_string();
        assert_ne!(
            iter1_attempt1, iter2_attempt1,
            "Commit keys must differ across iterations even when attempt number is the same. \
             iter1/attempt1 = '{iter1_attempt1}', iter2/attempt1 = '{iter2_attempt1}'"
        );
    }

    // =========================================================================
    // ConflictResolution phase key tests
    // =========================================================================

    #[test]
    fn test_conflict_resolution_key_format_matches_legacy_raw_string() {
        // Verifies byte-identical output to the former:
        //   format!("{}_conflict_resolution", "planning".to_lowercase())
        let key = PromptScopeKey::for_conflict_resolution("planning", 0);
        assert_eq!(key.to_string(), "planning_conflict_resolution");
    }

    #[test]
    fn test_conflict_resolution_key_for_different_phases() {
        assert_eq!(
            PromptScopeKey::for_conflict_resolution("development", 0).to_string(),
            "development_conflict_resolution"
        );
        assert_eq!(
            PromptScopeKey::for_conflict_resolution("RebaseOnly", 0).to_string(),
            "rebaseonly_conflict_resolution"
        );
    }

    #[test]
    fn test_conflict_resolution_key_lowercases_phase() {
        let upper = PromptScopeKey::for_conflict_resolution("PLANNING", 0).to_string();
        let lower = PromptScopeKey::for_conflict_resolution("planning", 0).to_string();
        assert_eq!(upper, lower);
    }

    #[test]
    fn test_conflict_resolution_key_recovery_epoch_not_in_display() {
        let key_epoch0 = PromptScopeKey::for_conflict_resolution("planning", 0);
        let key_epoch1 = PromptScopeKey::for_conflict_resolution("planning", 1);
        assert_eq!(
            key_epoch0.to_string(),
            key_epoch1.to_string(),
            "recovery_epoch must not affect Display string for checkpoint compat"
        );
    }

    #[test]
    fn test_conflict_resolution_key_is_unique_from_pipeline_phase_keys() {
        let conflict_key = PromptScopeKey::for_conflict_resolution("planning", 0).to_string();
        let planning_key = PromptScopeKey::for_planning(1, RetryMode::Normal, 0).to_string();
        let development_key =
            PromptScopeKey::for_development(1, None, RetryMode::Normal, 0).to_string();
        // Conflict key contains "_conflict_resolution" suffix, which pipeline keys do not.
        assert_ne!(conflict_key, planning_key);
        assert_ne!(conflict_key, development_key);
        assert!(conflict_key.ends_with("_conflict_resolution"));
    }
}