Skip to main content

ralph_workflow/phases/
integrity.rs

1//! PROMPT.md integrity utilities.
2//!
3//! This module provides utilities for ensuring PROMPT.md integrity during pipeline execution.
4
5use crate::workspace::Workspace;
6
7/// Periodically restore PROMPT.md if it was deleted by an agent.
8///
9/// This is a defense-in-depth measure to ensure PROMPT.md is always available
10/// even if an agent accidentally deletes it during pipeline execution.
11///
12/// Uses the workspace abstraction for file operations, enabling testing with
13/// `MemoryWorkspace`.
14///
15/// # Parameters
16/// - `workspace`: The workspace for file operations
17/// - `logger`: The logger to use for output
18/// - `phase`: The phase name (e.g., "development", "review") for logging
19/// - `iteration`: The iteration/cycle number for logging
20pub fn ensure_prompt_integrity(
21    workspace: &dyn Workspace,
22    logger: &crate::logger::Logger,
23    phase: &str,
24    iteration: u32,
25) {
26    // Use validate_prompt_md_with_workspace which handles restore internally
27    let result = crate::files::validate_prompt_md_with_workspace(workspace, false, false);
28
29    // Check the result for warnings about restoration
30    for warning in &result.warnings {
31        if warning.contains("restored from") {
32            logger.warn("[PROMPT_INTEGRITY] PROMPT.md was missing or empty and has been restored from backup");
33            logger.warn(&format!(
34                "[PROMPT_INTEGRITY] Deletion detected during {phase} phase (iteration {iteration})"
35            ));
36            logger.warn("[PROMPT_INTEGRITY] Possible cause: Agent used 'rm' or file write tools on PROMPT.md");
37            logger.success(
38                &warning.replace("PROMPT.md was missing and was automatically ", "PROMPT.md "),
39            );
40            return;
41        }
42    }
43
44    // Check for errors (no backup available)
45    for error in &result.errors {
46        if error.contains("not found") || error.contains("missing") || error.contains("empty") {
47            logger.error(&format!(
48                "[PROMPT_INTEGRITY] Failed to restore PROMPT.md: {error}"
49            ));
50            logger.error(&format!(
51                "[PROMPT_INTEGRITY] Error occurred during {phase} phase (iteration {iteration})"
52            ));
53            logger.error("Pipeline may not function correctly without PROMPT.md");
54            return;
55        }
56    }
57
58    // File exists with content - no action needed
59}