recursive-agent 0.6.0

A minimal, orthogonal, self-improving coding agent kernel in Rust
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
//! Selective rewind for a session's checkpoint chain.
//!
//! Reads `checkpoints.jsonl`, identifies which files this session
//! touched in turns >= the rewind cutoff, detects conflicts where the
//! current workspace state diverges from this session's last known
//! post-snapshot for those files, and asks [`ShadowRepo::restore_paths`]
//! to revert only that file subset.
//!
//! Multi-session safety: because `restore_paths` operates on a path
//! whitelist, files modified by a sibling session are never touched
//! unless they happen to also fall within this session's touched set
//! (in which case the conflict is surfaced and the user must
//! `--force`).

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use crate::checkpoint::{CheckpointId, RestoreStats, ShadowRepo};
use crate::checkpoint_log::{read_log, truncate_to_turn};
use crate::error::{Error, Result};

/// Outcome of a [`rewind`] call when conflicts were detected.
#[derive(Debug, Clone)]
pub struct ConflictReport {
    /// Files that have diverged from this session's last known state.
    pub files: Vec<String>,
}

/// Plan describing what a rewind would do, for a dry-run preview.
#[derive(Debug, Clone)]
pub struct RewindPlan {
    /// Target checkpoint to restore the touched files to.
    pub target: CheckpointId,
    /// Workspace-relative paths in this session's touched set.
    pub touched_paths: Vec<String>,
    /// The last "post" checkpoint this session recorded. Used for
    /// conflict detection.
    pub last_known_post: Option<CheckpointId>,
    /// Turns that will be removed from `checkpoints.jsonl` and from
    /// the conversation transcript on commit.
    pub turns_to_drop: Vec<usize>,
}

/// Compute a [`RewindPlan`] for rewinding `to_turn`.
///
/// `to_turn` is the turn index whose **start** state we want to
/// restore. So `to_turn = 0` undoes everything; `to_turn = 3`
/// preserves turns 0..=2 and undoes 3 and later.
///
/// Returns an error if the log doesn't contain `to_turn` (e.g. the
/// session never reached that turn) or if no `pre` checkpoint was
/// recorded for it.
pub fn plan_rewind(log_path: &Path, to_turn: usize) -> Result<RewindPlan> {
    let recs = read_log(log_path)?;
    if recs.is_empty() {
        return Err(Error::Tool {
            name: "rewind".into(),
            message: "no checkpoints recorded for this session".into(),
        });
    }

    let target_rec = recs
        .iter()
        .find(|r| r.turn == to_turn)
        .ok_or_else(|| Error::Tool {
            name: "rewind".into(),
            message: format!("turn {to_turn} is not in this session's checkpoint log"),
        })?;

    let target = target_rec.pre.clone().ok_or_else(|| Error::Tool {
        name: "rewind".into(),
        message: format!(
            "turn {to_turn} has no pre-snapshot recorded; \
             cannot rewind to its start"
        ),
    })?;

    let mut touched: HashSet<String> = HashSet::new();
    let mut turns_to_drop = Vec::new();
    for r in &recs {
        if r.turn >= to_turn {
            turns_to_drop.push(r.turn);
            for p in &r.touched_files {
                touched.insert(p.clone());
            }
        }
    }
    let mut touched_paths: Vec<String> = touched.into_iter().collect();
    touched_paths.sort();

    let last_known_post = recs.last().map(|r| r.post.clone());

    Ok(RewindPlan {
        target,
        touched_paths,
        last_known_post,
        turns_to_drop,
    })
}

/// Check whether the workspace's current state for the touched files
/// matches the session's last-known post-snapshot. Returns the list
/// of conflicting paths (empty list = safe to proceed).
pub fn detect_conflicts(repo: &ShadowRepo, plan: &RewindPlan) -> Result<Vec<String>> {
    let last = match &plan.last_known_post {
        Some(id) => id,
        None => return Ok(vec![]),
    };
    let mut conflicts = Vec::new();
    for path in &plan.touched_paths {
        let abs = repo.workspace().join(path);
        let current = std::fs::read(&abs).ok();
        let expected = repo.read_file_at(last, path)?;
        if current != expected {
            conflicts.push(path.clone());
        }
    }
    Ok(conflicts)
}

/// Apply a rewind plan: restore files, then truncate the checkpoint
/// log. Transcript truncation is left to the caller because it owns
/// `transcript.jsonl`.
///
/// `force = false` aborts on detected conflicts and returns
/// `Err(Error::Tool { ... })` whose message lists each file. Callers
/// can choose to retry with `force = true`.
pub fn apply_rewind(
    repo: &ShadowRepo,
    log_path: &Path,
    plan: &RewindPlan,
    force: bool,
) -> Result<RewindResult> {
    if !force {
        let conflicts = detect_conflicts(repo, plan)?;
        if !conflicts.is_empty() {
            return Err(Error::Tool {
                name: "rewind".into(),
                message: format!(
                    "rewind blocked by {} conflicting file(s): {}\n\
                     Re-run with --force to overwrite.",
                    conflicts.len(),
                    conflicts.join(", ")
                ),
            });
        }
    }
    let stats = repo.restore_paths(&plan.target, &plan.touched_paths)?;
    truncate_to_turn(
        log_path,
        plan.turns_to_drop.iter().copied().min().unwrap_or(0),
    )?;
    Ok(RewindResult {
        stats,
        dropped_turns: plan.turns_to_drop.clone(),
    })
}

/// Result of a successful rewind.
#[derive(Debug, Clone)]
pub struct RewindResult {
    pub stats: RestoreStats,
    pub dropped_turns: Vec<usize>,
}

/// Convenience: locate `checkpoints.jsonl` for a session given the
/// workspace root and a session id. Mirrors the path layout chosen
/// by `SessionWriter`.
pub fn checkpoint_log_path(workspace: &Path, workspace_slug: &str, session_id: &str) -> PathBuf {
    workspace
        .join(".recursive")
        .join("sessions")
        .join(workspace_slug)
        .join(session_id)
        .join("checkpoints.jsonl")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::checkpoint_log::{CheckpointLogWriter, CheckpointRecord, TouchedVia};
    use std::fs;
    use std::process::Command;
    use tempfile::TempDir;

    fn has_git() -> bool {
        Command::new("git").arg("--version").output().is_ok()
    }

    /// Workspace tempdir + sibling shadow tempdir. The pair is passed
    /// to `ShadowRepo::open_at` so tests don't need the global env
    /// lock and can run in parallel. `dir.path()` returns the
    /// workspace; `shadow_dir(&dir)` returns the shadow path.
    struct ShadowWs {
        workspace: TempDir,
        shadow: TempDir,
    }

    impl ShadowWs {
        fn path(&self) -> &Path {
            self.workspace.path()
        }
        fn open_repo(&self) -> Result<ShadowRepo> {
            ShadowRepo::open_at(self.path(), self.shadow.path().join("shadow-git"))
        }
    }

    fn shadow_ws() -> ShadowWs {
        ShadowWs {
            workspace: tempfile::tempdir().expect("workspace tempdir"),
            shadow: tempfile::tempdir().expect("shadow tempdir"),
        }
    }

    fn write_log(path: &Path, records: &[CheckpointRecord]) {
        let w = CheckpointLogWriter::open(path).unwrap();
        for r in records {
            w.append(r).unwrap();
        }
    }

    fn rec(turn: usize, pre: Option<&str>, post: &str, touched: &[&str]) -> CheckpointRecord {
        CheckpointRecord {
            turn,
            pre: pre.map(|s| CheckpointId(s.to_string())),
            post: CheckpointId(post.to_string()),
            touched_files: touched.iter().map(|s| s.to_string()).collect(),
            touched_via: TouchedVia::Structured,
            started_at: 0,
            finished_at: 0,
        }
    }

    #[test]
    fn plan_rewind_collects_touched_files_across_dropped_turns() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("c.jsonl");
        write_log(
            &log,
            &[
                rec(0, Some("p0"), "q0", &["a.txt"]),
                rec(1, Some("q0"), "q1", &["b.txt"]),
                rec(2, Some("q1"), "q2", &["c.txt"]),
            ],
        );
        let plan = plan_rewind(&log, 1).unwrap();
        assert_eq!(plan.target.0, "q0");
        assert_eq!(plan.touched_paths, vec!["b.txt", "c.txt"]);
        assert_eq!(plan.turns_to_drop, vec![1, 2]);
        assert_eq!(
            plan.last_known_post.as_ref().map(|c| c.0.as_str()),
            Some("q2")
        );
    }

    #[test]
    fn plan_rewind_to_zero_drops_all() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("c.jsonl");
        write_log(
            &log,
            &[
                rec(0, Some("p0"), "q0", &["a.txt"]),
                rec(1, Some("q0"), "q1", &["b.txt"]),
            ],
        );
        let plan = plan_rewind(&log, 0).unwrap();
        assert_eq!(plan.turns_to_drop, vec![0, 1]);
    }

    #[test]
    fn plan_rewind_errors_on_unknown_turn() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("c.jsonl");
        write_log(&log, &[rec(0, Some("p0"), "q0", &[])]);
        assert!(plan_rewind(&log, 5).is_err());
    }

    #[test]
    fn detect_conflicts_flags_externally_modified_file() {
        if !has_git() {
            return;
        }
        let dir = shadow_ws();
        fs::write(dir.path().join("a.txt"), "v0").unwrap();
        let repo = dir.open_repo().unwrap();
        let pre = repo.snapshot_for_session("s", "pre").unwrap();
        fs::write(dir.path().join("a.txt"), "v1").unwrap();
        let post = repo.snapshot_for_session("s", "post").unwrap();

        // Simulate "external" change after this session's last snapshot.
        fs::write(dir.path().join("a.txt"), "v2-from-someone-else").unwrap();

        let plan = RewindPlan {
            target: pre.clone(),
            touched_paths: vec!["a.txt".into()],
            last_known_post: Some(post),
            turns_to_drop: vec![0],
        };
        let conflicts = detect_conflicts(&repo, &plan).unwrap();
        assert_eq!(conflicts, vec!["a.txt".to_string()]);
    }

    #[test]
    fn apply_rewind_restores_and_truncates_log() {
        if !has_git() {
            return;
        }
        let dir = shadow_ws();
        let log = dir.path().join("c.jsonl");
        let target_path = dir.path().join("file.txt");
        fs::write(&target_path, "before").unwrap();
        let repo = dir.open_repo().unwrap();
        let pre = repo.snapshot_for_session("s", "t0 pre").unwrap();
        fs::write(&target_path, "after").unwrap();
        let post = repo.snapshot_for_session("s", "t0 post").unwrap();

        write_log(
            &log,
            &[CheckpointRecord {
                turn: 0,
                pre: Some(pre.clone()),
                post: post.clone(),
                touched_files: vec!["file.txt".into()],
                touched_via: TouchedVia::Structured,
                started_at: 0,
                finished_at: 0,
            }],
        );

        let plan = plan_rewind(&log, 0).unwrap();
        let result = apply_rewind(&repo, &log, &plan, false).unwrap();
        assert_eq!(result.stats.restored, 1);
        assert_eq!(fs::read_to_string(&target_path).unwrap(), "before");
        assert!(read_log(&log).unwrap().is_empty());
    }

    #[test]
    fn apply_rewind_blocks_on_conflict_without_force() {
        if !has_git() {
            return;
        }
        let dir = shadow_ws();
        let log = dir.path().join("c.jsonl");
        let f = dir.path().join("file.txt");
        fs::write(&f, "v0").unwrap();
        let repo = dir.open_repo().unwrap();
        let pre = repo.snapshot_for_session("s", "pre").unwrap();
        fs::write(&f, "v1").unwrap();
        let post = repo.snapshot_for_session("s", "post").unwrap();

        write_log(
            &log,
            &[CheckpointRecord {
                turn: 0,
                pre: Some(pre.clone()),
                post: post.clone(),
                touched_files: vec!["file.txt".into()],
                touched_via: TouchedVia::Structured,
                started_at: 0,
                finished_at: 0,
            }],
        );

        // External edit between session's last snapshot and rewind.
        fs::write(&f, "external-edit").unwrap();

        let plan = plan_rewind(&log, 0).unwrap();
        let err = apply_rewind(&repo, &log, &plan, false).unwrap_err();
        assert!(err.to_string().contains("conflict"));
    }

    #[test]
    fn apply_rewind_force_overrides_conflict() {
        if !has_git() {
            return;
        }
        let dir = shadow_ws();
        let log = dir.path().join("c.jsonl");
        let f = dir.path().join("file.txt");
        fs::write(&f, "v0").unwrap();
        let repo = dir.open_repo().unwrap();
        let pre = repo.snapshot_for_session("s", "pre").unwrap();
        fs::write(&f, "v1").unwrap();
        let post = repo.snapshot_for_session("s", "post").unwrap();

        write_log(
            &log,
            &[CheckpointRecord {
                turn: 0,
                pre: Some(pre.clone()),
                post: post.clone(),
                touched_files: vec!["file.txt".into()],
                touched_via: TouchedVia::Structured,
                started_at: 0,
                finished_at: 0,
            }],
        );

        fs::write(&f, "external").unwrap();
        let plan = plan_rewind(&log, 0).unwrap();
        let _ = apply_rewind(&repo, &log, &plan, true).unwrap();
        assert_eq!(fs::read_to_string(&f).unwrap(), "v0");
    }

    #[test]
    fn rewind_does_not_touch_sibling_session_files() {
        if !has_git() {
            return;
        }
        let dir = shadow_ws();
        let log_a = dir.path().join("a.jsonl");
        let mine = dir.path().join("mine.txt");
        let theirs = dir.path().join("theirs.txt");
        fs::write(&mine, "mine-v0").unwrap();
        fs::write(&theirs, "theirs-v0").unwrap();
        let repo = dir.open_repo().unwrap();

        let pre_a = repo.snapshot_for_session("a", "pre").unwrap();
        // A modifies its own file.
        fs::write(&mine, "mine-v1").unwrap();
        let post_a = repo.snapshot_for_session("a", "post").unwrap();

        // B (sibling) modifies its own file *after* A took its post-snapshot.
        fs::write(&theirs, "theirs-v1").unwrap();

        write_log(
            &log_a,
            &[CheckpointRecord {
                turn: 0,
                pre: Some(pre_a.clone()),
                post: post_a.clone(),
                touched_files: vec!["mine.txt".into()],
                touched_via: TouchedVia::Structured,
                started_at: 0,
                finished_at: 0,
            }],
        );

        let plan = plan_rewind(&log_a, 0).unwrap();
        let _ = apply_rewind(&repo, &log_a, &plan, false).unwrap();

        assert_eq!(fs::read_to_string(&mine).unwrap(), "mine-v0");
        assert_eq!(
            fs::read_to_string(&theirs).unwrap(),
            "theirs-v1",
            "sibling session's file must not be touched"
        );
    }
}