interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-cli / src / checkpoint.rs

1078 lines · 40541 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! File checkpoints and the agent-write ledger (sc#667).
17//!
18//! One shared content-addressed store under `~/basecamp/checkpoints`:
19//!
20//! - `objects/ab/cdef...`: file contents named by their SHA-256, shared by
21//! every session (the same bytes are stored once).
22//! - `snapshots/<id>.json`: one snapshot per directory per turn, taken just
23//! before the agent's first write into that directory in that turn.
24//! - `ledger/<session>.jsonl`: every write the agent's file tools made, with
25//! the content hash before and after, hash-chained line to line.
26//!
27//! A rollback restores only paths in the ledger, and only where the file
28//! still holds what the agent left. A file the operator edited after the
29//! agent is a conflict and is kept; files the operator edited that the agent
30//! never wrote are reported as spared and never touched.
31//!
32//! The pure part (hashing, the chain, the rollback planner) takes values and
33//! returns values, so it can move to Omega (ADR 0024). The store is the edge.
34//!
35//! Prior art: Hermes Agent, Nous Research, MIT licence, commit 5480918
36//! (read 2026-10-18), `tools/checkpoint_manager.py`. Hermes keeps a shared
37//! bare git store; this is our own content-addressed store with the same
38//! shape (shared objects, per-directory per-turn snapshots, agent ledger).
39//! Mechanism re-implemented from reading; no code copied.
40
41use serde::{Deserialize, Serialize};
42use sha2::{Digest, Sha256};
43use std::collections::{BTreeMap, BTreeSet, HashSet};
44use std::fs::{self, File};
45use std::io::{Read, Write};
46use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd};
47use std::os::unix::ffi::OsStrExt;
48use std::path::{Path, PathBuf};
49use std::sync::{Mutex, OnceLock};
50
51pub type Hash = String;
52
53/// Directory snapshot bounds: files bigger than this, or past this count,
54/// are listed as skipped. The written file's own prior content is always
55/// kept, whatever its size.
56pub const SNAPSHOT_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;
57pub const SNAPSHOT_MAX_FILES: usize = 512;
58
59const GENESIS: &str = "genesis";
60
61// ---------------------------------------------------------------------------
62// Pure part
63// ---------------------------------------------------------------------------
64
65pub fn hash_bytes(bytes: &[u8]) -> Hash {
66 hex::encode(Sha256::digest(bytes))
67}
68
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70pub struct Snapshot {
71 pub session: String,
72 pub turn: u64,
73 pub dir: String,
74 /// File name (not path) to content hash, regular files only.
75 pub files: BTreeMap<String, Hash>,
76 pub skipped: Vec<String>,
77}
78
79impl Snapshot {
80 /// Content address of the snapshot itself.
81 pub fn id(&self) -> Hash {
82 hash_bytes(&serde_json::to_vec(self).unwrap_or_default())
83 }
84}
85
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87pub struct LedgerEntry {
88 pub seq: u64,
89 pub turn: u64,
90 pub tool: String,
91 pub path: String,
92 /// `None` = the file did not exist.
93 pub before: Option<Hash>,
94 pub after: Option<Hash>,
95 /// Snapshot of the directory for this turn.
96 pub snapshot: Hash,
97 /// Hash of the previous ledger line, `genesis` for the first.
98 pub prev: Hash,
99}
100
101/// Serialize an entry as one ledger line (without the newline) and return
102/// the hash the next entry must carry as `prev`.
103pub fn ledger_line(entry: &LedgerEntry) -> (String, Hash) {
104 let line = serde_json::to_string(entry).unwrap_or_default();
105 let next = hash_bytes(line.as_bytes());
106 (line, next)
107}
108
109/// Parse and verify a ledger file. A torn last line (crash mid-append) is
110/// dropped; a broken chain anywhere else is refused, so a rollback never runs
111/// on a ledger someone edited. Returns the entries and the next `prev`.
112pub fn read_ledger(text: &str) -> Result<(Vec<LedgerEntry>, Hash), String> {
113 let mut entries = Vec::new();
114 let mut prev = GENESIS.to_string();
115 let lines: Vec<&str> = text.split('\n').collect();
116 // `text` ends with '\n' when the last append finished, so the last piece
117 // is empty; anything else there is a torn line.
118 let complete = lines.len().saturating_sub(1);
119 for (i, line) in lines.iter().take(complete).enumerate() {
120 let entry: LedgerEntry = serde_json::from_str(line)
121 .map_err(|e| format!("ledger line {} is damaged: {}", i + 1, e))?;
122 if entry.prev != prev {
123 return Err(format!("ledger chain broken at line {}", i + 1));
124 }
125 if entry.seq != i as u64 {
126 return Err(format!("ledger sequence broken at line {}", i + 1));
127 }
128 prev = hash_bytes(line.as_bytes());
129 entries.push(entry);
130 }
131 Ok((entries, prev))
132}
133
134#[derive(Debug, Clone, PartialEq)]
135pub enum RollbackStep {
136 /// Put the agent's starting content back (`None` = remove the file the
137 /// agent created).
138 Restore { path: String, to: Option<Hash> },
139 /// The file already holds its starting content.
140 AlreadyThere { path: String },
141 /// Someone changed the file after the agent; it is kept as it is.
142 Conflict {
143 path: String,
144 agent_left: Option<Hash>,
145 found: Option<Hash>,
146 },
147}
148
149/// Plan the rollback of every agent write in turns `>= from_turn`.
150/// `current` holds the present hash of every ledger path (`None` = absent).
151/// A path missing from `current` is treated as absent.
152pub fn plan_rollback(
153 entries: &[LedgerEntry],
154 from_turn: u64,
155 current: &BTreeMap<String, Option<Hash>>,
156) -> Vec<RollbackStep> {
157 let mut by_path: BTreeMap<&str, Vec<&LedgerEntry>> = BTreeMap::new();
158 for e in entries.iter().filter(|e| e.turn >= from_turn) {
159 by_path.entry(e.path.as_str()).or_default().push(e);
160 }
161 let mut steps = Vec::new();
162 for (path, mut writes) in by_path {
163 writes.sort_by_key(|e| e.seq);
164 let start = writes[0].before.clone();
165 let left = writes[writes.len() - 1].after.clone();
166 let found = current.get(path).cloned().flatten();
167 let path = path.to_string();
168 if found == start {
169 steps.push(RollbackStep::AlreadyThere { path });
170 } else if found == left {
171 steps.push(RollbackStep::Restore { path, to: start });
172 } else {
173 steps.push(RollbackStep::Conflict {
174 path,
175 agent_left: left,
176 found,
177 });
178 }
179 }
180 steps
181}
182
183/// Files in the snapshotted directories that changed since the snapshot and
184/// that the agent never wrote: the operator's edits, left alone. `current`
185/// maps full paths in those directories to their present hash.
186pub fn spared_operator_edits(
187 snapshots: &[Snapshot],
188 agent_paths: &BTreeSet<String>,
189 current: &BTreeMap<String, Option<Hash>>,
190) -> Vec<String> {
191 let mut spared = BTreeSet::new();
192 for snap in snapshots {
193 let dir = Path::new(&snap.dir);
194 for (name, hash) in &snap.files {
195 let full = dir.join(name).to_string_lossy().into_owned();
196 if agent_paths.contains(&full) {
197 continue;
198 }
199 if current.get(&full).cloned().flatten().as_ref() != Some(hash) {
200 spared.insert(full);
201 }
202 }
203 for full in current.keys() {
204 let p = Path::new(full);
205 if p.parent() == Some(dir)
206 && !agent_paths.contains(full)
207 && p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
208 !snap.files.contains_key(n) && !snap.skipped.iter().any(|s| s == n)
209 })
210 {
211 spared.insert(full.clone());
212 }
213 }
214 }
215 spared.into_iter().collect()
216}
217
218// ---------------------------------------------------------------------------
219// Edge: the on-disk store
220// ---------------------------------------------------------------------------
221
222pub fn store_root(home: &Path) -> PathBuf {
223 home.join("basecamp/checkpoints")
224}
225
226#[derive(Debug, Clone)]
227pub struct CheckpointStore {
228 root: PathBuf,
229}
230
231impl CheckpointStore {
232 pub fn new(root: PathBuf) -> Self {
233 Self { root }
234 }
235
236 fn object_path(&self, hash: &str) -> PathBuf {
237 let (a, b) = hash.split_at(2.min(hash.len()));
238 self.root.join("objects").join(a).join(b)
239 }
240
241 pub fn put_blob(&self, bytes: &[u8]) -> Result<Hash, String> {
242 let hash = hash_bytes(bytes);
243 let path = self.object_path(&hash);
244 if !path.exists() {
245 write_atomic(&path, bytes)?;
246 }
247 Ok(hash)
248 }
249
250 /// Read a blob and check it still hashes to its name.
251 pub fn get_blob(&self, hash: &str) -> Result<Vec<u8>, String> {
252 let bytes = fs::read(self.object_path(hash))
253 .map_err(|e| format!("checkpoint object {hash} unreadable: {e}"))?;
254 if hash_bytes(&bytes) != hash {
255 return Err(format!("checkpoint object {hash} is damaged"));
256 }
257 Ok(bytes)
258 }
259
260 fn ledger_path(&self, session: &str) -> PathBuf {
261 self.root.join("ledger").join(format!("{session}.jsonl"))
262 }
263
264 pub fn load_ledger(&self, session: &str) -> Result<(Vec<LedgerEntry>, Hash), String> {
265 match fs::read_to_string(self.ledger_path(session)) {
266 Ok(text) => read_ledger(&text),
267 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok((Vec::new(), GENESIS.into())),
268 Err(e) => Err(format!("ledger unreadable: {e}")),
269 }
270 }
271
272 fn append_ledger(&self, session: &str, line: &str) -> Result<(), String> {
273 let path = self.ledger_path(session);
274 if let Some(parent) = path.parent() {
275 fs::create_dir_all(parent).map_err(|e| e.to_string())?;
276 }
277 let mut f = fs::OpenOptions::new()
278 .create(true)
279 .append(true)
280 .open(&path)
281 .map_err(|e| format!("ledger open failed: {e}"))?;
282 f.write_all(format!("{line}\n").as_bytes())
283 .and_then(|_| f.sync_all())
284 .map_err(|e| format!("ledger append failed: {e}"))
285 }
286
287 fn snapshot_path(&self, id: &str) -> PathBuf {
288 self.root.join("snapshots").join(format!("{id}.json"))
289 }
290
291 pub fn load_snapshot(&self, id: &str) -> Result<Snapshot, String> {
292 let bytes = fs::read(self.snapshot_path(id)).map_err(|e| e.to_string())?;
293 let snap: Snapshot = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
294 if snap.id() != id {
295 return Err(format!("snapshot {id} is damaged"));
296 }
297 Ok(snap)
298 }
299
300 /// Snapshot the regular files directly inside `dir`.
301 ///
302 /// The directory's final component is opened `O_NOFOLLOW`, and each child
303 /// is read with `openat(O_NOFOLLOW)`. A symlink where the directory name
304 /// should be refuses the snapshot. A symlink child is omitted, not followed.
305 fn take_snapshot(&self, session: &str, turn: u64, dir: &Path) -> Result<Hash, String> {
306 let mut files = BTreeMap::new();
307 let mut skipped = Vec::new();
308 match open_snapshot_dir(dir) {
309 Ok(dirfd) => {
310 let mut names = snapshot_entries(dirfd.as_raw_fd()).unwrap_or_default();
311 names.sort();
312 for (name, size) in names {
313 if files.len() >= SNAPSHOT_MAX_FILES || size > SNAPSHOT_MAX_FILE_BYTES {
314 skipped.push(name);
315 continue;
316 }
317 match read_snapshot_file(dirfd.as_raw_fd(), &name) {
318 Ok(Some(bytes)) if bytes.len() as u64 <= SNAPSHOT_MAX_FILE_BYTES => {
319 files.insert(name, self.put_blob(&bytes)?);
320 }
321 _ => skipped.push(name),
322 }
323 }
324 }
325 Err(e) if e.raw_os_error() == Some(libc::ELOOP) => {
326 return Err(format!(
327 "cannot snapshot {}: directory entry is a symlink",
328 dir.display()
329 ));
330 }
331 Err(_) => {}
332 }
333 let snap = Snapshot {
334 session: session.to_string(),
335 turn,
336 dir: dir.to_string_lossy().into_owned(),
337 files,
338 skipped,
339 };
340 let id = snap.id();
341 let path = self.snapshot_path(&id);
342 if !path.exists() {
343 write_atomic(&path, &serde_json::to_vec(&snap).unwrap_or_default())?;
344 }
345 Ok(id)
346 }
347
348 /// Plan and apply the rollback of `session`'s agent writes in turns
349 /// `>= from_turn`.
350 pub fn rollback(&self, session: &str, from_turn: u64) -> Result<RollbackReport, String> {
351 let (entries, _) = self.load_ledger(session)?;
352 let agent_paths: BTreeSet<String> = entries
353 .iter()
354 .filter(|e| e.turn >= from_turn)
355 .map(|e| e.path.clone())
356 .collect();
357 let mut current = BTreeMap::new();
358 for p in &agent_paths {
359 current.insert(p.clone(), current_hash(Path::new(p)));
360 }
361 let steps = plan_rollback(&entries, from_turn, &current);
362
363 // Spared files are worked out before anything is restored.
364 let mut snap_ids = BTreeSet::new();
365 for e in entries.iter().filter(|e| e.turn >= from_turn) {
366 snap_ids.insert(e.snapshot.clone());
367 }
368 let mut snapshots = Vec::new();
369 for id in &snap_ids {
370 snapshots.push(self.load_snapshot(id)?);
371 }
372 let mut dir_state = BTreeMap::new();
373 for snap in &snapshots {
374 if let Ok(rd) = fs::read_dir(&snap.dir) {
375 for e in rd.flatten() {
376 if e.file_type().map(|t| t.is_file()).unwrap_or(false) {
377 let p = e.path();
378 dir_state.insert(p.to_string_lossy().into_owned(), current_hash(&p));
379 }
380 }
381 }
382 }
383 let spared = spared_operator_edits(&snapshots, &agent_paths, &dir_state);
384
385 let mut report = RollbackReport {
386 from_turn,
387 spared,
388 ..Default::default()
389 };
390 for step in steps {
391 match step {
392 RollbackStep::Restore { path, to: Some(h) } => {
393 let bytes = self.get_blob(&h)?;
394 write_atomic(Path::new(&path), &bytes)?;
395 report.restored.push(path);
396 }
397 RollbackStep::Restore { path, to: None } => {
398 fs::remove_file(&path).map_err(|e| format!("remove {path}: {e}"))?;
399 report.removed.push(path);
400 }
401 RollbackStep::AlreadyThere { path } => report.unchanged.push(path),
402 RollbackStep::Conflict { path, .. } => report.conflicts.push(path),
403 }
404 }
405 Ok(report)
406 }
407}
408
409#[derive(Debug, Clone, Default, PartialEq)]
410pub struct RollbackReport {
411 pub from_turn: u64,
412 /// Agent-written files put back to their starting content.
413 pub restored: Vec<String>,
414 /// Files the agent created, removed again.
415 pub removed: Vec<String>,
416 /// Agent-written files already at their starting content.
417 pub unchanged: Vec<String>,
418 /// Agent-written files someone changed afterwards: kept as found.
419 pub conflicts: Vec<String>,
420 /// Files in the same directories the operator changed: never touched.
421 pub spared: Vec<String>,
422}
423
424fn current_hash(path: &Path) -> Option<Hash> {
425 fs::read(path).ok().map(|b| hash_bytes(&b))
426}
427
428fn open_snapshot_dir(dir: &Path) -> std::io::Result<OwnedFd> {
429 let c = std::ffi::CString::new(dir.as_os_str().as_bytes())
430 .map_err(|_| std::io::Error::from_raw_os_error(libc::EINVAL))?;
431 // SAFETY: `c` is a valid C string. A non-negative fd is owned here.
432 // `O_NOFOLLOW` refuses a symlink in the final component.
433 let fd = unsafe {
434 libc::open(
435 c.as_ptr(),
436 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
437 )
438 };
439 if fd < 0 {
440 return Err(std::io::Error::last_os_error());
441 }
442 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
443}
444
445/// Regular files directly inside `dirfd`, as `(name, size)`. Symlinks are omitted.
446fn snapshot_entries(dirfd: libc::c_int) -> std::io::Result<Vec<(String, u64)>> {
447 let raw = dup_snapshot_fd(dirfd)?.into_raw_fd();
448 // SAFETY: `raw` is a live fd. fdopendir owns it on success.
449 let dir = unsafe { libc::fdopendir(raw) };
450 if dir.is_null() {
451 let err = std::io::Error::last_os_error();
452 unsafe { libc::close(raw) };
453 return Err(err);
454 }
455 let mut out = Vec::new();
456 let walked = loop {
457 clear_errno();
458 let ent = unsafe { libc::readdir(dir) };
459 if ent.is_null() {
460 // A null readdir is end of directory when errno is still 0.
461 let err = std::io::Error::last_os_error();
462 break match err.raw_os_error() {
463 None | Some(0) => Ok(()),
464 Some(_) => Err(err),
465 };
466 }
467 let name_c = unsafe { std::ffi::CStr::from_ptr((*ent).d_name.as_ptr()) };
468 let name = String::from_utf8_lossy(name_c.to_bytes()).into_owned();
469 if name == "." || name == ".." {
470 continue;
471 }
472 let Ok(c_name) = std::ffi::CString::new(name.as_str()) else {
473 continue;
474 };
475 let mut st = std::mem::MaybeUninit::<libc::stat>::uninit();
476 // SAFETY: `dirfd` is the caller's directory. `c_name` is one component.
477 let rc = unsafe {
478 libc::fstatat(
479 dirfd,
480 c_name.as_ptr(),
481 st.as_mut_ptr(),
482 libc::AT_SYMLINK_NOFOLLOW,
483 )
484 };
485 if rc != 0 {
486 continue;
487 }
488 let st = unsafe { st.assume_init() };
489 if st.st_mode & libc::S_IFMT != libc::S_IFREG {
490 continue;
491 }
492 let size = if st.st_size < 0 { 0 } else { st.st_size as u64 };
493 out.push((name, size));
494 };
495 unsafe { libc::closedir(dir) };
496 walked?;
497 Ok(out)
498}
499
500/// Set the calling thread's errno to 0 so a null `readdir` can be told apart
501/// from a failed one. std has no errno setter, so this names the per-OS libc
502/// accessor; reading errno goes through `std::io::Error::last_os_error`.
503fn clear_errno() {
504 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "redox"))]
505 let p = unsafe { libc::__errno_location() };
506 #[cfg(any(
507 target_vendor = "apple",
508 target_os = "freebsd",
509 target_os = "dragonfly"
510 ))]
511 let p = unsafe { libc::__error() };
512 #[cfg(any(target_os = "android", target_os = "openbsd", target_os = "netbsd"))]
513 let p = unsafe { libc::__errno() };
514 // SAFETY: each accessor returns the calling thread's errno slot.
515 unsafe { *p = 0 };
516}
517
518fn dup_snapshot_fd(fd: libc::c_int) -> std::io::Result<OwnedFd> {
519 let n = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) };
520 if n < 0 {
521 return Err(std::io::Error::last_os_error());
522 }
523 Ok(unsafe { OwnedFd::from_raw_fd(n) })
524}
525
526fn read_snapshot_file(dirfd: libc::c_int, name: &str) -> std::io::Result<Option<Vec<u8>>> {
527 let c = std::ffi::CString::new(name)
528 .map_err(|_| std::io::Error::from_raw_os_error(libc::EINVAL))?;
529 // SAFETY: `dirfd` is a directory and `c` is a single component.
530 let fd = unsafe {
531 libc::openat(
532 dirfd,
533 c.as_ptr(),
534 libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK,
535 )
536 };
537 if fd < 0 {
538 let err = std::io::Error::last_os_error();
539 if err.raw_os_error() == Some(libc::ELOOP) {
540 return Ok(None);
541 }
542 return Err(err);
543 }
544 let mut file = File::from(unsafe { OwnedFd::from_raw_fd(fd) });
545 if !file.metadata()?.file_type().is_file() {
546 return Ok(None);
547 }
548 let mut buf = Vec::new();
549 let mut tmp = [0u8; 8192];
550 loop {
551 let n = file.read(&mut tmp)?;
552 if n == 0 {
553 break;
554 }
555 if buf.len() as u64 + n as u64 > SNAPSHOT_MAX_FILE_BYTES {
556 return Ok(None);
557 }
558 buf.extend_from_slice(&tmp[..n]);
559 }
560 Ok(Some(buf))
561}
562
563fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
564 let parent = path.parent().unwrap_or(Path::new("."));
565 fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
566 let tmp = parent.join(format!(
567 ".{}.aien-tmp-{}",
568 path.file_name().and_then(|n| n.to_str()).unwrap_or("f"),
569 std::process::id()
570 ));
571 let mut f = fs::File::create(&tmp).map_err(|e| format!("create {}: {e}", tmp.display()))?;
572 f.write_all(bytes)
573 .and_then(|_| f.sync_all())
574 .map_err(|e| format!("write {}: {e}", tmp.display()))?;
575 fs::rename(&tmp, path).map_err(|e| format!("rename onto {}: {e}", path.display()))
576}
577
578/// One chat session's view of the store: turn counter, which directories
579/// are already snapshotted this turn, and the ledger chain head.
580#[derive(Debug)]
581pub struct Session {
582 pub store: CheckpointStore,
583 pub id: String,
584 pub turn: u64,
585 /// Record only writes under this directory (`None` = every write).
586 pub scope: Option<PathBuf>,
587 snapshotted: HashSet<(u64, PathBuf)>,
588 turn_snapshots: BTreeMap<PathBuf, Hash>,
589 next_seq: u64,
590 prev: Hash,
591}
592
593/// What `before_write` captured; handed back to `after_write`.
594#[derive(Debug, Clone)]
595pub struct Pending {
596 path: PathBuf,
597 before: Option<Hash>,
598 snapshot: Hash,
599}
600
601impl Session {
602 pub fn open(store: CheckpointStore, id: &str) -> Result<Self, String> {
603 let (entries, prev) = store.load_ledger(id)?;
604 let turn = entries.last().map(|e| e.turn).unwrap_or(0);
605 Ok(Self {
606 store,
607 id: id.to_string(),
608 turn,
609 scope: None,
610 snapshotted: HashSet::new(),
611 turn_snapshots: BTreeMap::new(),
612 next_seq: entries.len() as u64,
613 prev,
614 })
615 }
616
617 pub fn begin_turn(&mut self) -> u64 {
618 self.turn += 1;
619 self.turn_snapshots.clear();
620 self.turn
621 }
622
623 /// Call before an agent write to `path` (absolute). Snapshots the
624 /// directory once this turn and keeps the file's prior content.
625 ///
626 /// Reads `path` by name, so it is test-only. Tool dispatch passes bytes
627 /// from the held descriptor (`before_write_with_bytes`).
628 #[cfg(test)]
629 pub fn before_write(&mut self, path: &Path) -> Result<Pending, String> {
630 let bytes = match fs::read(path) {
631 Ok(bytes) => Some(bytes),
632 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
633 Err(e) => {
634 return Err(format!(
635 "cannot read {} before writing: {e}",
636 path.display()
637 ))
638 }
639 };
640 self.before_write_with_bytes(path, bytes)
641 }
642
643 fn before_write_with_bytes(
644 &mut self,
645 path: &Path,
646 bytes: Option<Vec<u8>>,
647 ) -> Result<Pending, String> {
648 let dir = path.parent().unwrap_or(Path::new("/")).to_path_buf();
649 let key = (self.turn, dir.clone());
650 if !self.snapshotted.contains(&key) {
651 let id = self.store.take_snapshot(&self.id, self.turn, &dir)?;
652 self.snapshotted.insert(key);
653 self.turn_snapshots.insert(dir.clone(), id);
654 }
655 let snapshot = self.turn_snapshots.get(&dir).cloned().unwrap_or_default();
656 let before = match bytes {
657 Some(b) => Some(self.store.put_blob(&b)?),
658 None => None,
659 };
660 Ok(Pending {
661 path: path.to_path_buf(),
662 before,
663 snapshot,
664 })
665 }
666
667 /// Call after the write; appends one ledger line.
668 ///
669 /// Reads the path by name, so it is test-only. Tool dispatch passes bytes
670 /// from the held descriptor (`after_write_with_bytes`).
671 #[cfg(test)]
672 pub fn after_write(&mut self, pending: Pending, tool: &str) -> Result<(), String> {
673 let after_bytes = fs::read(&pending.path).ok();
674 self.after_write_with_bytes(pending, tool, after_bytes)
675 }
676
677 fn after_write_with_bytes(
678 &mut self,
679 pending: Pending,
680 tool: &str,
681 bytes: Option<Vec<u8>>,
682 ) -> Result<(), String> {
683 let after = match bytes {
684 Some(b) => Some(self.store.put_blob(&b)?),
685 None => None,
686 };
687 if after == pending.before {
688 return Ok(());
689 }
690 let entry = LedgerEntry {
691 seq: self.next_seq,
692 turn: self.turn,
693 tool: tool.to_string(),
694 path: pending.path.to_string_lossy().into_owned(),
695 before: pending.before,
696 after,
697 snapshot: pending.snapshot,
698 prev: self.prev.clone(),
699 };
700 let (line, next) = ledger_line(&entry);
701 self.store.append_ledger(&self.id, &line)?;
702 self.next_seq += 1;
703 self.prev = next;
704 Ok(())
705 }
706
707 /// Turns with agent writes, newest last, with their file counts.
708 pub fn turns(&self) -> Result<Vec<(u64, usize)>, String> {
709 let (entries, _) = self.store.load_ledger(&self.id)?;
710 let mut by_turn: BTreeMap<u64, BTreeSet<&str>> = BTreeMap::new();
711 for e in &entries {
712 by_turn.entry(e.turn).or_default().insert(e.path.as_str());
713 }
714 Ok(by_turn.into_iter().map(|(t, p)| (t, p.len())).collect())
715 }
716}
717
718// ---------------------------------------------------------------------------
719// Edge: the process's active session (set by the chat loop)
720// ---------------------------------------------------------------------------
721
722fn active() -> &'static Mutex<Option<Session>> {
723 static ACTIVE: OnceLock<Mutex<Option<Session>>> = OnceLock::new();
724 ACTIVE.get_or_init(|| Mutex::new(None))
725}
726
727/// Start recording agent writes for this session. Without this call (tests,
728/// other entry points) the file tools record nothing.
729pub fn start_session(home: &Path, session_id: &str) -> Result<(), String> {
730 let session = Session::open(CheckpointStore::new(store_root(home)), session_id)?;
731 *active().lock().map_err(|_| "checkpoint lock poisoned")? = Some(session);
732 Ok(())
733}
734
735/// Stop recording (tests and shutdown).
736#[allow(dead_code)]
737pub fn stop_session() {
738 if let Ok(mut guard) = active().lock() {
739 *guard = None;
740 }
741}
742
743/// Start a session that records only writes under `scope`.
744#[allow(dead_code)]
745pub fn start_scoped_session(home: &Path, session_id: &str, scope: PathBuf) -> Result<(), String> {
746 let mut session = Session::open(CheckpointStore::new(store_root(home)), session_id)?;
747 session.scope = Some(scope);
748 *active().lock().map_err(|_| "checkpoint lock poisoned")? = Some(session);
749 Ok(())
750}
751
752pub fn begin_turn() {
753 if let Ok(mut guard) = active().lock() {
754 if let Some(s) = guard.as_mut() {
755 s.begin_turn();
756 }
757 }
758}
759
760pub fn active_ledger_name() -> Option<String> {
761 active().lock().ok()?.as_ref().map(|s| s.id.clone())
762}
763
764/// Run `write` as a recorded agent write of `path`. The target's before and
765/// after bytes come from `read_target` (a descriptor the caller is holding),
766/// never from a fresh pathname read. If the prior content cannot be kept the
767/// write is refused, because it could not be rolled back. If the ledger
768/// append fails after the write, the error is returned beside the result.
769pub fn record_agent_write_with_reader<T>(
770 path: &Path,
771 tool: &str,
772 mut read_target: impl FnMut() -> Result<Option<Vec<u8>>, String>,
773 write: impl FnOnce() -> T,
774) -> Result<(T, Option<String>), String> {
775 let mut guard = active()
776 .lock()
777 .map_err(|_| "checkpoint lock poisoned".to_string())?;
778 let Some(session) = guard
779 .as_mut()
780 .filter(|s| s.scope.as_ref().is_none_or(|d| path.starts_with(d)))
781 else {
782 return Ok((write(), None));
783 };
784 let before_bytes = read_target().map_err(|e| format!("CHECKPOINT REFUSAL: {e}"))?;
785 let pending = session
786 .before_write_with_bytes(path, before_bytes)
787 .map_err(|e| format!("CHECKPOINT REFUSAL: {e}"))?;
788 let out = write();
789 let warn = match read_target() {
790 Ok(bytes) => session.after_write_with_bytes(pending, tool, bytes).err(),
791 Err(e) => Some(e),
792 };
793 Ok((out, warn))
794}
795
796/// The session `session` names, or else the active one.
797fn session_or_active(session: Option<&str>) -> Result<String, String> {
798 match session {
799 Some(s) => Ok(s.to_string()),
800 None => active_ledger_name()
801 .ok_or_else(|| "no active session; name one: /checkpoints <session-id>".to_string()),
802 }
803}
804
805/// Turns (turn number, file writes) of an active session or of `session`.
806/// The session id is deliberately not in the result: callers that print the
807/// turns do not print the id (sc#689, cleartext logging of a session id).
808pub fn list_turns(home: &Path, session: Option<&str>) -> Result<Vec<(u64, usize)>, String> {
809 let id = session_or_active(session)?;
810 let s = Session::open(CheckpointStore::new(store_root(home)), &id)?;
811 s.turns()
812}
813
814/// Roll back `session` (default: the active one) from `turn` (default: its
815/// last turn with agent writes). Returns the report only; see `list_turns`.
816pub fn rollback(
817 home: &Path,
818 turn: Option<u64>,
819 session: Option<&str>,
820) -> Result<RollbackReport, String> {
821 let id = session_or_active(session)?;
822 let turns = list_turns(home, Some(id.as_str()))?;
823 let Some(last) = turns.last().map(|(t, _)| *t) else {
824 return Err(format!("session {id} has no agent writes to roll back"));
825 };
826 let from = turn.unwrap_or(last);
827 let store = CheckpointStore::new(store_root(home));
828 // Hold the active session lock so no agent write lands mid-rollback.
829 let _guard = active().lock();
830 store.rollback(&id, from)
831}
832
833#[cfg(test)]
834mod tests {
835 use super::*;
836
837 #[test]
838 fn snapshot_entries_ignores_a_stale_errno_at_end_of_directory() {
839 let dir = tempfile::tempdir_in("/tmp").unwrap();
840 std::fs::write(dir.path().join("a"), b"12345").unwrap();
841 let fd = open_snapshot_dir(dir.path()).unwrap();
842 // Leave EBADF in errno; successful calls before readdir keep it.
843 assert_eq!(unsafe { libc::close(-1) }, -1);
844 assert_eq!(
845 std::io::Error::last_os_error().raw_os_error(),
846 Some(libc::EBADF)
847 );
848 let got = snapshot_entries(fd.as_raw_fd()).expect("end of directory is not an error");
849 assert_eq!(got, vec![("a".to_string(), 5)]);
850 }
851
852 fn entry(
853 seq: u64,
854 turn: u64,
855 path: &str,
856 before: Option<&str>,
857 after: Option<&str>,
858 ) -> LedgerEntry {
859 LedgerEntry {
860 seq,
861 turn,
862 tool: "write_to_file".into(),
863 path: path.into(),
864 before: before.map(String::from),
865 after: after.map(String::from),
866 snapshot: "s".into(),
867 prev: String::new(),
868 }
869 }
870
871 #[test]
872 fn planner_restores_only_what_still_holds_the_agents_bytes() {
873 let entries = vec![
874 entry(0, 1, "/w/a", Some("a0"), Some("a1")),
875 entry(1, 2, "/w/a", Some("a1"), Some("a2")),
876 entry(2, 2, "/w/new", None, Some("n1")),
877 entry(3, 2, "/w/b", Some("b0"), Some("b1")),
878 entry(4, 2, "/w/c", Some("c0"), Some("c1")),
879 ];
880 let current: BTreeMap<String, Option<Hash>> = [
881 ("/w/a", Some("a2")),
882 ("/w/new", Some("n1")),
883 ("/w/b", Some("operator")), // operator edited after the agent
884 ("/w/c", Some("c0")), // already back
885 ]
886 .into_iter()
887 .map(|(k, v)| (k.to_string(), v.map(String::from)))
888 .collect();
889 let steps = plan_rollback(&entries, 2, &current);
890 assert_eq!(
891 steps,
892 vec![
893 RollbackStep::Restore {
894 path: "/w/a".into(),
895 to: Some("a1".into())
896 },
897 RollbackStep::Conflict {
898 path: "/w/b".into(),
899 agent_left: Some("b1".into()),
900 found: Some("operator".into())
901 },
902 RollbackStep::AlreadyThere {
903 path: "/w/c".into()
904 },
905 RollbackStep::Restore {
906 path: "/w/new".into(),
907 to: None
908 },
909 ]
910 );
911 // From turn 1, /w/a goes back to its turn-1 start.
912 let steps = plan_rollback(&entries, 1, &current);
913 assert_eq!(
914 steps[0],
915 RollbackStep::Restore {
916 path: "/w/a".into(),
917 to: Some("a0".into())
918 }
919 );
920 }
921
922 #[test]
923 fn ledger_chain_detects_edits_and_drops_a_torn_tail() {
924 let mut text = String::new();
925 let mut prev = GENESIS.to_string();
926 for seq in 0..3 {
927 let mut e = entry(seq, 1, "/w/a", Some("x"), Some("y"));
928 e.prev = prev.clone();
929 let (line, next) = ledger_line(&e);
930 text.push_str(&line);
931 text.push('\n');
932 prev = next;
933 }
934 let (entries, head) = read_ledger(&text).unwrap();
935 assert_eq!(entries.len(), 3);
936 assert_eq!(head, prev);
937
938 let torn = format!("{text}{{\"seq\":3,\"tu");
939 assert_eq!(read_ledger(&torn).unwrap().0.len(), 3);
940
941 let edited = text.replacen("\"/w/a\"", "\"/w/z\"", 1);
942 assert!(read_ledger(&edited).is_err());
943 let dropped: String = text.lines().skip(1).map(|l| format!("{l}\n")).collect();
944 assert!(read_ledger(&dropped).is_err());
945 }
946
947 /// Acceptance: after mixed operator and agent edits, a rollback restores
948 /// only the agent's files.
949 #[test]
950 fn rollback_after_mixed_edits_restores_only_the_agents_files() {
951 let tmp = tempfile::tempdir().unwrap();
952 let work = tmp.path().join("work");
953 fs::create_dir_all(&work).unwrap();
954 let store = CheckpointStore::new(tmp.path().join("checkpoints"));
955 let mut s = Session::open(store.clone(), "s1").unwrap();
956
957 let agent_file = work.join("agent.rs");
958 let shared = work.join("shared.rs");
959 let operator_file = work.join("operator.md");
960 let created = work.join("created.txt");
961 fs::write(&agent_file, "agent v0").unwrap();
962 fs::write(&shared, "shared v0").unwrap();
963 fs::write(&operator_file, "operator v0").unwrap();
964
965 // Turn 1: the agent writes two files and creates one.
966 s.begin_turn();
967 for (p, text) in [
968 (&agent_file, "agent v1"),
969 (&shared, "shared v1"),
970 (&created, "new"),
971 ] {
972 let pending = s.before_write(p).unwrap();
973 fs::write(p, text).unwrap();
974 s.after_write(pending, "write_to_file").unwrap();
975 }
976 // The operator edits a file the agent never touched, edits a file the
977 // agent wrote, and adds a new file of their own.
978 fs::write(&operator_file, "operator v1").unwrap();
979 fs::write(&shared, "shared operator fix").unwrap();
980 let operator_new = work.join("operator-new.md");
981 fs::write(&operator_new, "mine").unwrap();
982
983 let report = store.rollback("s1", 1).unwrap();
984 assert_eq!(fs::read_to_string(&agent_file).unwrap(), "agent v0");
985 assert!(!created.exists());
986 assert_eq!(fs::read_to_string(&operator_file).unwrap(), "operator v1");
987 assert_eq!(fs::read_to_string(&shared).unwrap(), "shared operator fix");
988 assert_eq!(fs::read_to_string(&operator_new).unwrap(), "mine");
989 let s = |p: &Path| p.to_string_lossy().into_owned();
990 assert_eq!(report.restored, vec![s(&agent_file)]);
991 assert_eq!(report.removed, vec![s(&created)]);
992 assert_eq!(report.conflicts, vec![s(&shared)]);
993 assert_eq!(report.spared, vec![s(&operator_new), s(&operator_file)]);
994
995 // A second rollback changes nothing.
996 let again = store.rollback("s1", 1).unwrap();
997 assert!(again.restored.is_empty() && again.removed.is_empty());
998 assert_eq!(fs::read_to_string(&operator_file).unwrap(), "operator v1");
999 }
1000
1001 /// Negative control: restoring the whole directory snapshot (what a
1002 /// plain checkpoint does) would destroy the operator's edit; the ledger
1003 /// is what prevents it.
1004 #[test]
1005 fn negative_control_snapshot_alone_would_revert_operator_edits() {
1006 let tmp = tempfile::tempdir().unwrap();
1007 let work = tmp.path().join("work");
1008 fs::create_dir_all(&work).unwrap();
1009 let store = CheckpointStore::new(tmp.path().join("checkpoints"));
1010 let mut s = Session::open(store.clone(), "s2").unwrap();
1011 let agent_file = work.join("a.txt");
1012 let operator_file = work.join("o.txt");
1013 fs::write(&agent_file, "a0").unwrap();
1014 fs::write(&operator_file, "o0").unwrap();
1015 s.begin_turn();
1016 let pending = s.before_write(&agent_file).unwrap();
1017 fs::write(&agent_file, "a1").unwrap();
1018 s.after_write(pending, "write_to_file").unwrap();
1019 fs::write(&operator_file, "o1").unwrap();
1020
1021 let (entries, _) = store.load_ledger("s2").unwrap();
1022 let snap = store.load_snapshot(&entries[0].snapshot).unwrap();
1023 // The snapshot holds the operator file's old content ...
1024 assert_eq!(snap.files.get("o.txt"), Some(&hash_bytes(b"o0")));
1025 // ... but the ledger never names it, so rollback leaves it.
1026 assert!(entries
1027 .iter()
1028 .all(|e| e.path != operator_file.to_string_lossy()));
1029 store.rollback("s2", 1).unwrap();
1030 assert_eq!(fs::read_to_string(&operator_file).unwrap(), "o1");
1031 assert_eq!(fs::read_to_string(&agent_file).unwrap(), "a0");
1032 }
1033
1034 #[test]
1035 fn one_snapshot_per_directory_per_turn_and_shared_objects() {
1036 let tmp = tempfile::tempdir().unwrap();
1037 let work = tmp.path().join("work");
1038 fs::create_dir_all(&work).unwrap();
1039 let store = CheckpointStore::new(tmp.path().join("checkpoints"));
1040 let mut s = Session::open(store.clone(), "s3").unwrap();
1041 s.begin_turn();
1042 for i in 0..3 {
1043 let p = work.join(format!("f{i}"));
1044 let pending = s.before_write(&p).unwrap();
1045 fs::write(&p, "same bytes").unwrap();
1046 s.after_write(pending, "write_to_file").unwrap();
1047 }
1048 let snaps = fs::read_dir(tmp.path().join("checkpoints/snapshots"))
1049 .unwrap()
1050 .count();
1051 assert_eq!(snaps, 1);
1052 s.begin_turn();
1053 let p = work.join("f0");
1054 let pending = s.before_write(&p).unwrap();
1055 fs::write(&p, "turn two").unwrap();
1056 s.after_write(pending, "write_to_file").unwrap();
1057 let snaps = fs::read_dir(tmp.path().join("checkpoints/snapshots"))
1058 .unwrap()
1059 .count();
1060 assert_eq!(snaps, 2);
1061 // "same bytes" is stored once.
1062 assert!(store.get_blob(&hash_bytes(b"same bytes")).is_ok());
1063
1064 // A reopened session continues the chain and the turn count.
1065 let reopened = Session::open(store.clone(), "s3").unwrap();
1066 assert_eq!(reopened.turn, 2);
1067 assert_eq!(reopened.turns().unwrap(), vec![(1, 3), (2, 1)]);
1068 }
1069
1070 #[test]
1071 fn a_damaged_object_stops_the_restore() {
1072 let tmp = tempfile::tempdir().unwrap();
1073 let store = CheckpointStore::new(tmp.path().join("checkpoints"));
1074 let h = store.put_blob(b"good").unwrap();
1075 fs::write(store.object_path(&h), b"evil").unwrap();
1076 assert!(store.get_blob(&h).is_err());
1077 }
1078}