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
//! Prompt dispatch functions.
//!
//! Contains the main dispatcher functions for routing to appropriate prompt generators
//! based on role and action, as well as prompt replay functionality for checkpoint resume.

use super::generate_resume_note;
use super::prompt_config::PromptConfig;
use super::prompt_scope_key::PromptScopeKey;
use super::types::{Action, Role};
use super::ContextLevel;
use super::TemplateContext;
use super::{
    prompt_developer_iteration_with_context, prompt_fix_with_context, prompt_plan_with_context,
};
use crate::prompts::PromptHistoryEntry;

/// Generate a prompt for any agent type.
///
/// This is the main dispatcher function that routes to the appropriate
/// prompt generator based on role and action.
///
/// The config parameter allows providing:
/// - Language-specific review guidance when the project stack has been detected
/// - PROMPT.md content for planning prompts
/// - PROMPT.md and PLAN.md content for developer iteration prompts
///
/// # Arguments
///
/// * `role` - The agent role (Developer, Reviewer, etc.)
/// * `action` - The action to perform (Plan, Iterate, Fix, etc.)
/// * `context` - The context level (minimal or normal)
/// * `template_context` - Template context for user template overrides
/// * `config` - Prompt configuration with content variables
/// * `workspace` - Workspace for resolving absolute paths
pub fn prompt_for_agent(
    role: Role,
    action: Action,
    context: ContextLevel,
    template_context: &TemplateContext,
    config: PromptConfig,
    workspace: &dyn crate::workspace::Workspace,
) -> String {
    let resume_note = if let Some(resume_ctx) = &config.resume_context {
        generate_resume_note(resume_ctx)
    } else if config.is_resume {
        // Fallback when no rich ResumeContext is available (uses simpler note)
        "\nNOTE: This session is resuming from a previous run. Previous progress is preserved in git history.\n\n".to_string()
    } else {
        String::new()
    };

    let base_prompt = match (role, action) {
        (_, Action::Plan) => prompt_plan_with_context(
            template_context,
            config.prompt_md_content.as_deref(),
            workspace,
        ),
        (Role::Developer | Role::Reviewer, Action::Iterate) => {
            let (prompt_content, plan_content) = config
                .prompt_and_plan
                .unwrap_or((String::new(), String::new()));
            prompt_developer_iteration_with_context(
                template_context,
                config.iteration.unwrap_or(1),
                config.total_iterations.unwrap_or(1),
                context,
                &prompt_content,
                &plan_content,
            )
        }
        (_, Action::Fix) => {
            let (prompt_content, plan_content, issues_content) = config
                .prompt_plan_and_issues
                .unwrap_or((String::new(), String::new(), String::new()));
            prompt_fix_with_context(
                template_context,
                &prompt_content,
                &plan_content,
                &issues_content,
                workspace,
            )
        }
    };

    // Prepend resume note if applicable
    if config.is_resume {
        format!("{resume_note}{base_prompt}")
    } else {
        base_prompt
    }
}

/// Get a stored prompt from history or generate a new one.
///
/// This function implements prompt replay for hardened resume functionality.
/// When resuming from a checkpoint, it checks if a prompt was already used
/// and returns the stored prompt for deterministic behavior. Otherwise, it
/// generates a new prompt using the provided generator function.
///
/// The lookup key is derived from `scope_key.to_string()`.
///
/// Backward-compatibility notes:
/// - Planning/Development/Review/Fix/ConflictResolution keys preserve the legacy
///   `format!()` shapes for existing checkpoint `prompt_history` maps.
/// - Commit keys intentionally include the iteration dimension (`..._iter{iter}_...`).
///   Older checkpoints that stored attempt-only commit keys (pre-RFC-007) will
///   regenerate commit prompts on resume rather than replay potentially-stale entries.
///
/// # Content-ID Validation (RFC-007)
///
/// When `current_content_id` is `Some` and the stored entry has a `content_id`
/// that differs, the entry is treated as a cache miss and a fresh prompt is
/// generated. This prevents stale-content replay when the materialized inputs
/// have changed since the prompt was generated.
///
/// If `current_content_id` is `None`, replay proceeds without content-id validation.
/// If `current_content_id` is `Some` but the stored entry has no `content_id`
/// (legacy entries), the entry is treated as a cache miss and a fresh prompt is
/// generated.
///
/// # Arguments
///
/// * `scope_key` - Typed prompt scope key. Its `Display` string is used for
///   the `HashMap` lookup.
/// * `prompt_history` - The reducer-owned prompt history from `PipelineState`
/// * `current_content_id` - Optional content-id of the current materialized inputs.
///   When `Some`, used to validate that stored entry matches current content.
/// * `generator` - Function to generate the prompt if not found in history
///
/// # Returns
///
/// A tuple of (prompt, `was_replayed`) where:
/// - `prompt` is the prompt string (either replayed or newly generated)
/// - `was_replayed` is true if the prompt came from history, false if newly generated
///
/// # Example
///
/// ```ignore
/// let scope_key = PromptScopeKey::for_development(iteration, None, RetryMode::Normal, recovery_epoch);
/// let (prompt, was_replayed) = get_stored_or_generate_prompt(
///     &scope_key,
///     &state.prompt_history,
///     None,
///     || prompt_for_agent(role, action, context, template_context, config),
/// );
/// if was_replayed {
///     logger.info("Using stored prompt from checkpoint for determinism");
/// }
/// ```
pub fn get_stored_or_generate_prompt<F, S: std::hash::BuildHasher>(
    scope_key: &PromptScopeKey,
    prompt_history: &std::collections::HashMap<String, PromptHistoryEntry, S>,
    current_content_id: Option<&str>,
    generator: F,
) -> (String, bool)
where
    F: FnOnce() -> String,
{
    let key = scope_key.to_string();
    if let Some(entry) = prompt_history.get(&key) {
        // Content-id validation (RFC-007): when the caller can compute a content-id for
        // current materialized inputs, only replay when the stored entry has a matching id.
        let content_id_mismatch = current_content_id
            .is_some_and(|current_id| entry.content_id.as_deref() != Some(current_id));

        if content_id_mismatch {
            // Content changed: generate fresh prompt, do not replay stale entry
            (generator(), false)
        } else {
            (entry.content.clone(), true)
        }
    } else {
        (generator(), false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prompts::prompt_scope_key::RetryMode;

    #[test]
    fn test_get_stored_or_generate_prompt_replays_when_available() {
        let scope_key = PromptScopeKey::for_planning(1, RetryMode::Normal, 0);
        let history = [(
            scope_key.to_string(),
            PromptHistoryEntry::from_string("stored prompt".to_string()),
        )]
        .into_iter()
        .collect::<std::collections::HashMap<_, _>>();

        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&scope_key, &history, None, || {
                "generated prompt".to_string()
            });

        assert_eq!(prompt, "stored prompt");
        assert!(was_replayed, "Should have replayed the stored prompt");
    }

    #[test]
    fn test_get_stored_or_generate_prompt_generates_when_not_available() {
        let scope_key = PromptScopeKey::for_development(2, None, RetryMode::Normal, 0);
        let history = std::collections::HashMap::new();

        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&scope_key, &history, None, || {
                "generated prompt".to_string()
            });

        assert_eq!(prompt, "generated prompt");
        assert!(!was_replayed, "Should have generated a new prompt");
    }

    #[test]
    fn test_get_stored_or_generate_prompt_with_empty_history() {
        let scope_key = PromptScopeKey::for_commit(1, 1, RetryMode::Normal, 0);
        let history = std::collections::HashMap::new();

        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&scope_key, &history, None, || {
                "fresh prompt".to_string()
            });

        assert_eq!(prompt, "fresh prompt");
        assert!(
            !was_replayed,
            "Should have generated a new prompt for empty history"
        );
    }

    #[test]
    fn test_key_lookup_uses_display_string() {
        let scope_key = PromptScopeKey::for_commit(2, 1, RetryMode::Xsd { count: 1 }, 0);
        let expected_key = "commit_message_attempt_iter2_1_xsd_retry_1";
        let history = [(
            expected_key.to_string(),
            PromptHistoryEntry::from_string("stored xsd retry prompt".to_string()),
        )]
        .into_iter()
        .collect::<std::collections::HashMap<_, _>>();

        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&scope_key, &history, None, || "new prompt".to_string());

        assert_eq!(prompt, "stored xsd retry prompt");
        assert!(
            was_replayed,
            "Should replay using Display string '{expected_key}' as key"
        );
    }

    #[test]
    fn test_recovery_epoch_does_not_affect_lookup_key() {
        let scope_key_epoch0 = PromptScopeKey::for_planning(1, RetryMode::Normal, 0);
        let scope_key_epoch1 = PromptScopeKey::for_planning(1, RetryMode::Normal, 1);
        let history = [(
            scope_key_epoch0.to_string(),
            PromptHistoryEntry::from_string("stored".to_string()),
        )]
        .into_iter()
        .collect::<std::collections::HashMap<_, _>>();

        // epoch1 should still find the entry stored under epoch0's Display string
        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&scope_key_epoch1, &history, None, || "new".to_string());
        assert_eq!(prompt, "stored");
        assert!(
            was_replayed,
            "Epoch change alone must not bust the history lookup key"
        );
    }

    #[test]
    fn test_content_id_match_replays_prompt() {
        let scope_key = PromptScopeKey::for_planning(1, RetryMode::Normal, 0);
        let history = [(
            scope_key.to_string(),
            PromptHistoryEntry {
                content: "stored prompt".to_string(),
                content_id: Some("abc123".to_string()),
            },
        )]
        .into_iter()
        .collect::<std::collections::HashMap<_, _>>();

        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&scope_key, &history, Some("abc123"), || {
                "generated".to_string()
            });

        assert_eq!(prompt, "stored prompt");
        assert!(was_replayed, "Should replay when content-ids match");
    }

    #[test]
    fn test_content_id_mismatch_generates_fresh_prompt() {
        let scope_key = PromptScopeKey::for_planning(1, RetryMode::Normal, 0);
        let history = [(
            scope_key.to_string(),
            PromptHistoryEntry {
                content: "stale prompt".to_string(),
                content_id: Some("old_hash".to_string()),
            },
        )]
        .into_iter()
        .collect::<std::collections::HashMap<_, _>>();

        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&scope_key, &history, Some("new_hash"), || {
                "fresh prompt".to_string()
            });

        assert_eq!(prompt, "fresh prompt");
        assert!(
            !was_replayed,
            "Should generate fresh prompt when content-ids differ"
        );
    }

    #[test]
    fn test_legacy_entry_without_content_id_is_treated_as_miss_when_current_content_id_is_known() {
        let scope_key = PromptScopeKey::for_planning(1, RetryMode::Normal, 0);
        let history = [(
            scope_key.to_string(),
            PromptHistoryEntry::from_string("legacy prompt".to_string()),
        )]
        .into_iter()
        .collect::<std::collections::HashMap<_, _>>();

        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&scope_key, &history, Some("any_hash"), || {
                "generated".to_string()
            });

        assert_eq!(prompt, "generated");
        assert!(
            !was_replayed,
            "Legacy entries with no stored content_id must not replay when current_content_id is Some"
        );
    }

    #[test]
    fn test_no_current_content_id_replays_without_validation() {
        let scope_key = PromptScopeKey::for_planning(1, RetryMode::Normal, 0);
        let history = [(
            scope_key.to_string(),
            PromptHistoryEntry {
                content: "stored prompt".to_string(),
                content_id: Some("some_hash".to_string()),
            },
        )]
        .into_iter()
        .collect::<std::collections::HashMap<_, _>>();

        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&scope_key, &history, None, || "generated".to_string());

        assert_eq!(prompt, "stored prompt");
        assert!(
            was_replayed,
            "Should replay when current_content_id is None (caller does not validate)"
        );
    }

    /// SC-2: Iteration 2 development prompt is not replayed from iteration 1's history entry.
    ///
    /// Verifies that `get_stored_or_generate_prompt` generates a fresh prompt for iter2
    /// even when iter1's development prompt exists in history (same Normal retry mode).
    #[test]
    fn iteration_2_development_does_not_replay_iteration_1_prompt() {
        let iter1_key = PromptScopeKey::for_development(1, None, RetryMode::Normal, 0);
        let history = [(
            iter1_key.to_string(),
            PromptHistoryEntry::from_string("iter 1 development prompt".to_string()),
        )]
        .into_iter()
        .collect::<std::collections::HashMap<_, _>>();

        let iter2_key = PromptScopeKey::for_development(2, None, RetryMode::Normal, 0);
        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&iter2_key, &history, None, || {
                "iter 2 fresh development prompt".to_string()
            });

        // Assert: iter2 must generate a fresh prompt, not replay iter1's prompt
        assert!(
            !was_replayed,
            "iter2 development must NOT replay iter1 development prompt"
        );
        assert_eq!(
            prompt, "iter 2 fresh development prompt",
            "iter2 development must receive a freshly generated prompt"
        );
    }

    /// Regression test for RFC-007 root cause: commit prompt stale replay across iterations.
    ///
    /// Before the fix, commit keys were `commit_message_attempt_{attempt}` with no iteration
    /// dimension. Attempt resets to 1 on each new commit cycle, so iter2/attempt1 would
    /// collide with iter1/attempt1 and replay the stale first-cycle prompt.
    ///
    /// This test verifies that when iter1/attempt1 exists in history, requesting
    /// iter2/attempt1 does NOT replay it — the iteration dimension produces a different key.
    #[test]
    fn test_iteration_2_commit_does_not_replay_iteration_1_prompt() {
        let iter1_key = PromptScopeKey::for_commit(1, 1, RetryMode::Normal, 0);
        let history = [(
            iter1_key.to_string(),
            PromptHistoryEntry::from_string("iter 1 commit prompt".to_string()),
        )]
        .into_iter()
        .collect::<std::collections::HashMap<_, _>>();

        let iter2_key = PromptScopeKey::for_commit(2, 1, RetryMode::Normal, 0);
        let (prompt, was_replayed) =
            get_stored_or_generate_prompt(&iter2_key, &history, None, || {
                "iter 2 fresh commit prompt".to_string()
            });

        // Assert: iter2 must generate a fresh prompt, not replay iter1's stale prompt
        assert!(
            !was_replayed,
            "iter2/attempt1 must NOT replay iter1/attempt1"
        );
        assert_eq!(
            prompt, "iter 2 fresh commit prompt",
            "iter2 must receive a freshly generated prompt, not iter1's stale content"
        );
    }
}