Skip to main content

agentmux_srv_core/backend/slug_migration/
journal.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The write-ahead journal, `journal.jsonl` in the run's backup folder: one
5//! JSON record per line, appended and synced before the next write it
6//! describes. A step's intent (with its before-image) is recorded before
7//! the step runs and its result after, so a run that stops anywhere resumes
8//! at the first step without a result, and a rollback knows what to undo.
9//!
10//! No record holds a key or a secret: a before-image names a key row, and
11//! the row itself comes back from the backup copy of its database.
12
13use std::io::Write;
14use std::path::{Path, PathBuf};
15
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19use crate::backend::rpc_types::ForkSlugPlan;
20
21pub const JOURNAL_FILE: &str = "journal.jsonl";
22const VERSION: u32 = 1;
23
24/// The steps of ยง4 Phase 2, in the order they run for each agent.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
26pub enum Step {
27    S1,
28    S2,
29    S3,
30    S4,
31    S5,
32    S6,
33    S7,
34    S8,
35}
36
37pub const STEPS: [Step; 8] = [Step::S1, Step::S2, Step::S3, Step::S4, Step::S5, Step::S6, Step::S7, Step::S8];
38
39/// One file the run copied before its first write.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct BackupEntry {
42    pub original: String,
43    /// Relative to the run's folder.
44    pub copy: String,
45    pub sha256: String,
46    pub database: bool,
47}
48
49/// What a file looked like when the run finished, for restore mode.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51pub struct Fingerprint {
52    pub path: String,
53    /// SHA-256 of a file, or of a database's rows (`backup::db_digest`).
54    pub digest: String,
55    /// A file's modification time, ms; 0 for a database, whose file a WAL
56    /// checkpoint touches without changing a row.
57    pub mtime_ms: i64,
58}
59
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61#[serde(tag = "t", rename_all = "snake_case")]
62pub enum Record {
63    Header { version: u32, started_at: i64, retired_at: i64, plan: ForkSlugPlan, backups: Vec<BackupEntry> },
64    Intent { uid: String, step: Step, before: Value },
65    Done { uid: String, step: Step, changes: Vec<String> },
66    Verified { uid: String },
67    Failed { uid: String, error: String },
68    /// Left out of this run with nothing written for it: its new id was
69    /// taken after the plan (another channel created an agent with it).
70    Skipped { uid: String, reason: String },
71    Finished { at: i64, after: Vec<Fingerprint> },
72    Undo { uid: String, step: Step },
73    Undone { uid: String, step: Step, changes: Vec<String> },
74    RolledBack { at: i64, mode: String },
75}
76
77/// An open journal: its records so far, appended to on disk as they come.
78pub struct Journal {
79    pub path: PathBuf,
80    pub records: Vec<Record>,
81}
82
83impl Journal {
84    /// A new journal in `dir`, starting with its header.
85    pub fn create(dir: &Path, started_at: i64, retired_at: i64, plan: ForkSlugPlan, backups: Vec<BackupEntry>) -> Result<Journal, String> {
86        let mut j = Journal { path: dir.join(JOURNAL_FILE), records: Vec::new() };
87        j.append(Record::Header { version: VERSION, started_at, retired_at, plan, backups })?;
88        // The file's directory entry is durable too, not only its bytes.
89        sync_dir(dir);
90        Ok(j)
91    }
92
93    /// The journal at `path`. A last record cut short by a crash (no newline
94    /// after it, or one that doesn't parse) was never acted on, since a record
95    /// is written before what it allows: it is discarded, and the file cut
96    /// back to the end of its last complete line, so the next record starts on
97    /// a line of its own. A complete record missing only its newline is kept.
98    /// Any other line that doesn't parse is an error.
99    pub fn open(path: &Path) -> Result<Journal, String> {
100        Self::load(path, true)
101    }
102
103    /// [`Journal::open`] without the repair: a torn last record is left out
104    /// but the file isn't touched, for a reader that doesn't hold the
105    /// migration lock while a run may be appending (the plan).
106    pub fn read(path: &Path) -> Result<Journal, String> {
107        Self::load(path, false)
108    }
109
110    fn load(path: &Path, repair: bool) -> Result<Journal, String> {
111        let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
112        let mut keep = bytes.len();
113        // The last line, and where it starts.
114        let body = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
115        let start = body.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1);
116        let last = &body[start..];
117        if !last.iter().all(u8::is_ascii_whitespace) && serde_json::from_slice::<Record>(last).is_err() {
118            keep = start;
119            tracing::warn!(journal = %path.display(), discarded = last.len(), "fork slug migration: discarded a torn last journal record");
120        }
121        if repair && keep < bytes.len() {
122            let f = std::fs::OpenOptions::new().write(true).open(path).map_err(|e| format!("{}: {e}", path.display()))?;
123            f.set_len(keep as u64).map_err(|e| format!("{}: {e}", path.display()))?;
124            f.sync_all().map_err(|e| format!("{}: {e}", path.display()))?;
125        }
126        let text = String::from_utf8_lossy(&bytes[..keep]);
127        let mut records = Vec::new();
128        for (i, line) in text.lines().enumerate().filter(|(_, l)| !l.trim().is_empty()) {
129            let record = serde_json::from_str::<Record>(line).map_err(|e| format!("{} line {}: {e}", path.display(), i + 1))?;
130            records.push(record);
131        }
132        match records.first() {
133            Some(Record::Header { version, .. }) if *version <= VERSION => {}
134            _ => return Err(format!("{} has no header this build reads", path.display())),
135        }
136        Ok(Journal { path: path.to_path_buf(), records })
137    }
138
139    pub fn dir(&self) -> PathBuf {
140        self.path.parent().map(Path::to_path_buf).unwrap_or_default()
141    }
142
143    /// Append `record` on a line of its own and sync it to disk before
144    /// returning: the step it allows runs only once it is durable. A file
145    /// that doesn't end in a newline (a record written without one) gets
146    /// one first, so two records never share a line.
147    pub fn append(&mut self, record: Record) -> Result<(), String> {
148        use std::io::{Read, Seek, SeekFrom};
149        let err = |e: std::io::Error| format!("{}: {e}", self.path.display());
150        let mut line = serde_json::to_string(&record).map_err(|e| e.to_string())?;
151        line.push('\n');
152        let mut opts = std::fs::OpenOptions::new();
153        opts.create(true).read(true).append(true);
154        // Owner-only from its creation, like the backup beside it (Unix).
155        #[cfg(unix)]
156        {
157            use std::os::unix::fs::OpenOptionsExt as _;
158            opts.mode(0o600);
159        }
160        let mut f = opts.open(&self.path).map_err(err)?;
161        let len = f.metadata().map_err(err)?.len();
162        if len > 0 {
163            let mut last = [0u8; 1];
164            f.seek(SeekFrom::Start(len - 1)).map_err(err)?;
165            f.read_exact(&mut last).map_err(err)?;
166            if last[0] != b'\n' {
167                line.insert(0, '\n');
168            }
169        }
170        f.write_all(line.as_bytes()).map_err(err)?;
171        f.sync_all().map_err(err)?;
172        self.records.push(record);
173        Ok(())
174    }
175
176    pub fn header(&self) -> (i64, &ForkSlugPlan, &[BackupEntry]) {
177        match &self.records[0] {
178            Record::Header { retired_at, plan, backups, .. } => (*retired_at, plan, backups),
179            _ => unreachable!("open and create both start with a header"),
180        }
181    }
182
183    /// The before-image recorded for `step` of `uid`, if its intent was.
184    pub fn intent(&self, uid: &str, step: Step) -> Option<&Value> {
185        self.records.iter().find_map(|r| match r {
186            Record::Intent { uid: u, step: s, before } if u == uid && *s == step => Some(before),
187            _ => None,
188        })
189    }
190
191    pub fn done(&self, uid: &str, step: Step) -> bool {
192        self.records.iter().any(|r| matches!(r, Record::Done { uid: u, step: s, .. } if u == uid && *s == step))
193    }
194
195    pub fn skipped(&self, uid: &str) -> Option<&str> {
196        self.records.iter().find_map(|r| match r {
197            Record::Skipped { uid: u, reason } if u == uid => Some(reason.as_str()),
198            _ => None,
199        })
200    }
201
202    pub fn verified(&self, uid: &str) -> bool {
203        self.records.iter().any(|r| matches!(r, Record::Verified { uid: u } if u == uid))
204    }
205
206    pub fn undone(&self, uid: &str, step: Step) -> bool {
207        self.records.iter().any(|r| matches!(r, Record::Undone { uid: u, step: s, .. } if u == uid && *s == step))
208    }
209
210    pub fn finished(&self) -> Option<&[Fingerprint]> {
211        self.records.iter().find_map(|r| match r {
212            Record::Finished { after, .. } => Some(after.as_slice()),
213            _ => None,
214        })
215    }
216
217    pub fn rolled_back(&self) -> bool {
218        self.records.iter().any(|r| matches!(r, Record::RolledBack { .. }))
219    }
220
221    /// Every intent, in the order it was recorded.
222    pub fn intents(&self) -> Vec<(String, Step, Value)> {
223        self.records
224            .iter()
225            .filter_map(|r| match r {
226                Record::Intent { uid, step, before } => Some((uid.clone(), *step, before.clone())),
227                _ => None,
228            })
229            .collect()
230    }
231
232    /// The changes each step recorded for `uid`, in order.
233    pub fn changes(&self, uid: &str) -> Vec<String> {
234        self.records
235            .iter()
236            .filter_map(|r| match r {
237                Record::Done { uid: u, step, changes } if u == uid => Some(changes.iter().map(move |c| format!("{step:?}: {c}"))),
238                _ => None,
239            })
240            .flatten()
241            .collect()
242    }
243
244    pub fn last_failure(&self) -> Option<String> {
245        let failed = self.records.iter().rposition(|r| matches!(r, Record::Failed { .. }))?;
246        let later_progress = self.records[failed + 1..].iter().any(|r| matches!(r, Record::Done { .. } | Record::Verified { .. }));
247        match &self.records[failed] {
248            Record::Failed { uid, error } if !later_progress => Some(format!("{uid}: {error}")),
249            _ => None,
250        }
251    }
252}
253
254/// Sync a directory, so a file just created in it survives a power loss.
255/// Windows makes a new directory entry durable with the file itself; there is
256/// no directory handle to sync there.
257#[cfg(unix)]
258fn sync_dir(dir: &Path) {
259    if let Ok(d) = std::fs::File::open(dir) {
260        let _ = d.sync_all();
261    }
262}
263
264#[cfg(not(unix))]
265fn sync_dir(_dir: &Path) {}
266
267/// Every run's journal under `backups`, newest first.
268pub fn journals(backups: &Path) -> Vec<PathBuf> {
269    let Ok(dirs) = std::fs::read_dir(backups) else { return Vec::new() };
270    let mut out: Vec<PathBuf> = dirs
271        .flatten()
272        .filter(|d| d.file_name().to_string_lossy().starts_with("slug-migration-"))
273        .map(|d| d.path().join(JOURNAL_FILE))
274        .filter(|p| p.is_file())
275        .collect();
276    out.sort();
277    out.reverse();
278    out
279}