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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Starting commit tracking for incremental diff generation.
//!
//! This module manages the starting commit reference that enables incremental
//! diffs for reviewers while keeping agents isolated from git history.
//!
//! # Overview
//!
//! When a Ralph pipeline starts, the current HEAD commit is saved as the
//! "starting commit" in `.agent/start_commit`. This reference is used to:
//!
//! 1. Generate incremental diffs for reviewers (changes since pipeline start)
//! 2. Keep agents unaware of git history (no git context in prompts)
//! 3. Enable proper review of accumulated changes across iterations
//!
//! The starting commit file persists across pipeline runs unless explicitly
//! reset by the user via the `--reset-start-commit` CLI command.

use std::path::Path;

use crate::common::domain_types::GitOid;
use crate::workspace::{Workspace, WorkspaceFs};

mod iot {
    pub type Result<T> = std::io::Result<T>;
    pub type Error = std::io::Error;
    pub type ErrorKind = std::io::ErrorKind;
}

// Boundary module for libgit2 revwalk operations.
include!("start_commit/io.rs");

/// Path to the starting commit file.
///
/// Stored in `.agent/start_commit`, this file contains the OID (SHA) of the
/// commit that was HEAD when the pipeline started.
const START_COMMIT_FILE: &str = ".agent/start_commit";

/// Sentinel value written to `.agent/start_commit` when the repository has no commits yet.
///
/// This enables incremental diffs to work in a single run that starts on an unborn HEAD
/// by treating the starting point as the empty tree.
const EMPTY_REPO_SENTINEL: &str = "__EMPTY_REPO__";

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StartPoint {
    /// A concrete commit OID to diff from.
    Commit(GitOid),
    /// An empty repository baseline (diff from the empty tree).
    EmptyRepo,
}

/// Get the current HEAD commit OID.
///
/// Returns the full SHA-1 hash of the current HEAD commit.
///
/// # Errors
///
/// Returns an error if:
/// - Not in a git repository
/// - HEAD cannot be resolved (e.g., unborn branch)
/// - HEAD is not a commit (e.g., symbolic ref to tag)
///
/// **Note:** This function uses the current working directory to discover the repo.
pub fn get_current_head_oid() -> iot::Result<String> {
    let repo = git2::Repository::discover(".").map_err(|e| to_io_error(&e))?;
    get_current_head_oid_impl(&repo)
}

/// Get the current HEAD commit OID for an explicit repository root.
///
/// This avoids accidentally discovering a different repository when the process
/// current working directory is not inside `repo_root`.
///
/// # Errors
///
/// Returns an error if the repository cannot be opened or HEAD cannot be resolved.
pub fn get_current_head_oid_at(repo_root: &Path) -> iot::Result<String> {
    let repo = git2::Repository::open(repo_root).map_err(|e| to_io_error(&e))?;
    get_current_head_oid_impl(&repo)
}

/// Implementation of `get_current_head_oid`.
fn get_current_head_oid_impl(repo: &git2::Repository) -> iot::Result<String> {
    let head = repo.head().map_err(|e| {
        // Handle UnbornBranch error consistently with git_diff()
        // This provides a clearer error message for empty repositories
        if e.code() == git2::ErrorCode::UnbornBranch {
            iot::Error::new(iot::ErrorKind::NotFound, "No commits yet (unborn branch)")
        } else {
            to_io_error(&e)
        }
    })?;

    // Get the commit OID
    let head_commit = head.peel_to_commit().map_err(|e| to_io_error(&e))?;

    Ok(head_commit.id().to_string())
}

fn get_current_start_point(repo: &git2::Repository) -> iot::Result<StartPoint> {
    let head = repo.head();
    let start_point = match head {
        Ok(head) => {
            let head_commit = head.peel_to_commit().map_err(|e| to_io_error(&e))?;
            StartPoint::Commit(git2_oid_to_git_oid(head_commit.id())?)
        }
        Err(ref e) if e.code() == git2::ErrorCode::UnbornBranch => StartPoint::EmptyRepo,
        Err(e) => return Err(to_io_error(&e)),
    };
    Ok(start_point)
}

/// Save the current HEAD commit as the starting commit.
///
/// Writes the current HEAD OID to `.agent/start_commit` only if it doesn't
/// already exist. This ensures the `start_commit` persists across pipeline runs
/// and is only reset when explicitly requested via `--reset-start-commit`.
///
/// # Errors
///
/// Returns an error if:
/// - The current HEAD cannot be determined
/// - The `.agent` directory cannot be created
/// - The file cannot be written
///
pub fn save_start_commit() -> iot::Result<()> {
    let repo = git2::Repository::discover(".").map_err(|e| to_io_error(&e))?;
    let repo_root = repo
        .workdir()
        .ok_or_else(|| iot::Error::new(iot::ErrorKind::NotFound, "No workdir for repository"))?;
    save_start_commit_impl(&repo, repo_root)
}

/// Implementation of `save_start_commit`.
fn save_start_commit_impl(repo: &git2::Repository, repo_root: &Path) -> iot::Result<()> {
    // If a start commit exists and is valid, preserve it across runs.
    // If it exists but is invalid/corrupt, automatically repair it.
    if load_start_point_impl(repo, repo_root).is_ok() {
        return Ok(());
    }

    write_start_point(repo_root, get_current_start_point(repo)?)
}

fn write_start_commit_with_oid(repo_root: &Path, oid: &str) -> iot::Result<()> {
    let workspace = WorkspaceFs::new(repo_root.to_path_buf());
    workspace.write(Path::new(START_COMMIT_FILE), oid)
}

fn write_start_point(repo_root: &Path, start_point: StartPoint) -> iot::Result<()> {
    let content = match start_point {
        StartPoint::Commit(oid) => oid.to_string(),
        StartPoint::EmptyRepo => EMPTY_REPO_SENTINEL.to_string(),
    };
    let workspace = WorkspaceFs::new(repo_root.to_path_buf());
    workspace.write(Path::new(START_COMMIT_FILE), &content)
}

/// Write start point to file using workspace abstraction.
///
/// This is the workspace-aware version that should be used in pipeline code
/// where a workspace is available.
fn write_start_point_with_workspace(
    workspace: &dyn Workspace,
    start_point: StartPoint,
) -> iot::Result<()> {
    let path = Path::new(START_COMMIT_FILE);
    let content = match start_point {
        StartPoint::Commit(oid) => oid.to_string(),
        StartPoint::EmptyRepo => EMPTY_REPO_SENTINEL.to_string(),
    };
    workspace.write(path, &content)
}

/// Load start point from file using workspace abstraction.
///
/// This version reads the file content via workspace but still validates
/// the commit exists using the provided repository.
///
/// This is the workspace-aware version for pipeline code where git operations
/// are needed for validation.
///
/// # Errors
///
/// Returns error if the operation fails.
pub fn load_start_point_with_workspace(
    workspace: &dyn Workspace,
    repo: &git2::Repository,
) -> iot::Result<StartPoint> {
    let path = Path::new(START_COMMIT_FILE);
    let content = workspace.read(path)?;
    let raw = content.trim();

    if raw.is_empty() {
        return Err(iot::Error::new(
            iot::ErrorKind::InvalidData,
            "Starting commit file is empty. Run 'ralph --reset-start-commit' to fix.",
        ));
    }

    if raw == EMPTY_REPO_SENTINEL {
        return Ok(StartPoint::EmptyRepo);
    }

    let git_oid = parse_git_oid(raw)?;
    let oid = git_oid_to_git2_oid(&git_oid)?;

    // Ensure the commit still exists in this repository.
    repo.find_commit(oid).map_err(|e| {
        let err_msg = e.message();
        if err_msg.contains("not found") || err_msg.contains("invalid") {
            iot::Error::new(
                iot::ErrorKind::NotFound,
                format!(
                    "Start commit '{raw}' no longer exists (history rewritten). \
                     Run 'ralph --reset-start-commit' to fix."
                ),
            )
        } else {
            to_io_error(&e)
        }
    })?;

    Ok(StartPoint::Commit(git_oid))
}

/// Save start commit using workspace abstraction.
///
/// This is the workspace-aware version for pipeline code where a workspace
/// is available. If a valid start commit already exists, it is preserved.
///
/// # Errors
///
/// Returns error if the operation fails.
pub fn save_start_commit_with_workspace(
    workspace: &dyn Workspace,
    repo: &git2::Repository,
) -> iot::Result<()> {
    // If a start commit exists and is valid, preserve it across runs.
    if load_start_point_with_workspace(workspace, repo).is_ok() {
        return Ok(());
    }

    write_start_point_with_workspace(workspace, get_current_start_point(repo)?)
}

/// Load the starting commit OID from the file.
///
/// Reads the `.agent/start_commit` file and returns the stored OID.
///
/// # Errors
///
/// Returns an error if:
/// - The file does not exist
/// - The file cannot be read
/// - The file content is invalid
///
pub fn load_start_point() -> iot::Result<StartPoint> {
    let repo = git2::Repository::discover(".").map_err(|e| {
        iot::Error::new(
            iot::ErrorKind::NotFound,
            format!("Git repository error: {e}. Run 'ralph --reset-start-commit' to fix."),
        )
    })?;
    let repo_root = repo
        .workdir()
        .ok_or_else(|| iot::Error::new(iot::ErrorKind::NotFound, "No workdir for repository"))?;
    load_start_point_impl(&repo, repo_root)
}

/// Implementation of `load_start_point`.
fn load_start_point_impl(repo: &git2::Repository, repo_root: &Path) -> iot::Result<StartPoint> {
    let workspace = WorkspaceFs::new(repo_root.to_path_buf());
    load_start_point_with_workspace(&workspace, repo)
}

/// Result of resetting the start commit.
#[derive(Debug, Clone)]
pub struct ResetStartCommitResult {
    /// The OID that `start_commit` was set to.
    pub oid: String,
    /// The default branch used for merge-base calculation (if applicable).
    pub default_branch: Option<String>,
    /// Whether we fell back to HEAD (when on main/master branch).
    pub fell_back_to_head: bool,
}

/// Reset the starting commit to merge-base with the default branch.
///
/// This is a CLI command that updates `.agent/start_commit` to the merge-base
/// between HEAD and the default branch (main/master). This provides a better
/// baseline for feature branch workflows, showing only changes since branching.
///
/// If the current branch is main/master itself, falls back to current HEAD.
///
/// # Errors
///
/// Returns an error if:
/// - The current HEAD cannot be determined
/// - The default branch cannot be found
/// - No common ancestor exists between HEAD and the default branch
/// - The file cannot be written
///
pub fn reset_start_commit() -> iot::Result<ResetStartCommitResult> {
    let repo = git2::Repository::discover(".").map_err(|e| to_io_error(&e))?;
    let repo_root = repo
        .workdir()
        .ok_or_else(|| iot::Error::new(iot::ErrorKind::NotFound, "No workdir for repository"))?;
    reset_start_commit_impl(&repo, repo_root)
}

/// Implementation of `reset_start_commit`.
fn reset_start_commit_impl(
    repo: &git2::Repository,
    repo_root: &Path,
) -> iot::Result<ResetStartCommitResult> {
    // Get current HEAD
    let head = repo.head().map_err(|e| {
        if e.code() == git2::ErrorCode::UnbornBranch {
            iot::Error::new(iot::ErrorKind::NotFound, "No commits yet (unborn branch)")
        } else {
            to_io_error(&e)
        }
    })?;
    let head_commit = head.peel_to_commit().map_err(|e| to_io_error(&e))?;

    // Check if we're on main/master - if so, fall back to HEAD
    let current_branch = head.shorthand().unwrap_or("HEAD");
    if current_branch == "main" || current_branch == "master" {
        let oid = head_commit.id().to_string();
        write_start_commit_with_oid(repo_root, &oid)?;
        return Ok(ResetStartCommitResult {
            oid,
            default_branch: None,
            fell_back_to_head: true,
        });
    }

    // Get the default branch
    let default_branch = super::branch::get_default_branch_at(repo_root)?;

    // Find the default branch commit
    let default_ref = format!("refs/heads/{default_branch}");
    let default_commit = if let Ok(reference) = repo.find_reference(&default_ref) {
        reference.peel_to_commit().map_err(|e| to_io_error(&e))?
    } else {
        // Try origin/<default_branch> as fallback
        let origin_ref = format!("refs/remotes/origin/{default_branch}");
        match repo.find_reference(&origin_ref) {
            Ok(reference) => reference.peel_to_commit().map_err(|e| to_io_error(&e))?,
            Err(_) => {
                return Err(iot::Error::new(
                    iot::ErrorKind::NotFound,
                    format!(
                        "Default branch '{default_branch}' not found locally or in origin. \
                         Make sure the branch exists."
                    ),
                ));
            }
        }
    };

    // Calculate merge-base
    let merge_base = repo
        .merge_base(head_commit.id(), default_commit.id())
        .map_err(|e| {
            if e.code() == git2::ErrorCode::NotFound {
                iot::Error::new(
                    iot::ErrorKind::NotFound,
                    format!(
                        "No common ancestor between current branch and '{default_branch}' (unrelated branches)"
                    ),
                )
            } else {
                to_io_error(&e)
            }
        })?;

    let oid = merge_base.to_string();
    write_start_commit_with_oid(repo_root, &oid)?;

    Ok(ResetStartCommitResult {
        oid,
        default_branch: Some(default_branch),
        fell_back_to_head: false,
    })
}

/// Start commit summary for display.
///
/// Contains information about the start commit for user display.
#[derive(Debug, Clone)]
pub struct StartCommitSummary {
    /// The start commit OID (short form, or None if not set).
    pub start_oid: Option<GitOid>,
    /// Number of commits since start commit.
    pub commits_since: usize,
    /// Whether the start commit is stale (>10 commits behind).
    pub is_stale: bool,
}

impl StartCommitSummary {
    /// Format a compact version for inline display.
    pub fn format_compact(&self) -> String {
        self.start_oid.as_ref().map_or_else(
            || "Start: not set".to_string(),
            |oid| {
                let oid_str = oid.as_str();
                let short_oid = &oid_str[..8.min(oid_str.len())];
                if self.is_stale {
                    format!(
                        "Start: {} (+{} commits, STALE)",
                        short_oid, self.commits_since
                    )
                } else if self.commits_since > 0 {
                    format!("Start: {} (+{} commits)", short_oid, self.commits_since)
                } else {
                    format!("Start: {short_oid}")
                }
            },
        )
    }
}

/// Get a summary of the start commit state for display.
///
/// Returns a `StartCommitSummary` containing information about the current
/// start commit, commits since start, and staleness status.
///
///
/// # Errors
///
/// Returns error if the operation fails.
pub fn get_start_commit_summary() -> iot::Result<StartCommitSummary> {
    let repo = git2::Repository::discover(".").map_err(|e| to_io_error(&e))?;
    let repo_root = repo
        .workdir()
        .ok_or_else(|| iot::Error::new(iot::ErrorKind::NotFound, "No workdir for repository"))?;
    get_start_commit_summary_impl(&repo, repo_root)
}

/// Implementation of `get_start_commit_summary`.
fn get_start_commit_summary_impl(
    repo: &git2::Repository,
    repo_root: &Path,
) -> iot::Result<StartCommitSummary> {
    let start_point = load_start_point_impl(repo, repo_root)?;
    let start_oid = match start_point {
        StartPoint::Commit(oid) => Some(oid),
        StartPoint::EmptyRepo => None,
    };

    let (commits_since, is_stale) = if let Some(ref oid) = start_oid {
        // Get HEAD commit
        let head_oid = get_current_head_oid_impl(repo)?;
        let head_commit = repo
            .find_commit(git2::Oid::from_str(&head_oid).map_err(|_| {
                iot::Error::new(iot::ErrorKind::InvalidData, "Invalid HEAD OID format")
            })?)
            .map_err(|e| to_io_error(&e))?;

        let start_commit_oid = git_oid_to_git2_oid(oid)?;

        let start_commit = repo
            .find_commit(start_commit_oid)
            .map_err(|e| to_io_error(&e))?;

        // Count commits between start and HEAD
        let count = revwalk_count_commits_since(repo, head_commit.id(), start_commit.id(), 1000)?;

        let is_stale = count > 10;
        (count, is_stale)
    } else {
        (0, false)
    };

    Ok(StartCommitSummary {
        start_oid,
        commits_since,
        is_stale,
    })
}

pub(crate) fn git2_oid_to_git_oid(oid: git2::Oid) -> iot::Result<GitOid> {
    let text = oid.to_string();
    GitOid::try_from_str(&text).map_err(|err| {
        iot::Error::new(
            iot::ErrorKind::InvalidData,
            format!("Invalid git2 OID from git: {text} ({err})"),
        )
    })
}

pub fn git_oid_to_git2_oid(oid: &GitOid) -> iot::Result<git2::Oid> {
    git2::Oid::from_str(oid.as_str()).map_err(|_| {
        iot::Error::new(
            iot::ErrorKind::InvalidData,
            format!("Stored start commit '{oid}' is not valid for git2"),
        )
    })
}

pub(crate) fn parse_git_oid(raw: &str) -> iot::Result<GitOid> {
    GitOid::try_from_str(raw).map_err(|_| {
        iot::Error::new(
            iot::ErrorKind::InvalidData,
            format!(
                "Invalid OID format in {START_COMMIT_FILE}: '{raw}'. Run 'ralph --reset-start-commit' to fix."
            ),
        )
    })
}

/// Convert git2 error to `iot::Error`.
fn to_io_error(err: &git2::Error) -> iot::Error {
    iot::Error::other(err.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::domain_types::GitOid;

    #[test]
    fn test_start_commit_file_path_defined() {
        assert_eq!(START_COMMIT_FILE, ".agent/start_commit");
    }

    #[test]
    fn test_get_current_head_oid_returns_result() {
        // We're in a git repo with commits, so HEAD OID should always resolve.
        let result = get_current_head_oid();
        assert!(
            result.is_ok(),
            "get_current_head_oid failed in a git repo: {:?}",
            result.err()
        );
    }

    #[test]
    fn start_point_commit_holds_git_oid() {
        let oid_text = "0123456789abcdef0123456789abcdef01234567";
        let git_oid = match GitOid::try_from_str(oid_text) {
            Ok(oid) => oid,
            Err(err) => panic!("Failed to parse valid OID: {err}"),
        };

        let start_point = StartPoint::Commit(git_oid.clone());

        if let StartPoint::Commit(stored) = start_point {
            assert_eq!(stored, git_oid);
        } else {
            panic!("StartPoint::Commit did not store the GitOid variant");
        }
    }
}