Skip to main content

onerig_core/
session.rs

1//! Chat session persistence on disk (design sections 5 and 8):
2//! `<repo>/.onerig/sessions/<session id>/transcript.jsonl`, `lock`, and `raw-<n>.log`.
3
4use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7
8use crate::store::{
9    Lock, LockError, Phase, RunDir, StoreError, append_jsonl, create_sub_dir, open_dir, read_jsonl,
10    sorted_entries,
11};
12use crate::turn::{ChatMessage, Proposal};
13
14/// `<repo>/.onerig/sessions`.
15pub fn sessions_root(repo: &Path) -> PathBuf {
16    repo.join(".onerig").join("sessions")
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct SessionDir {
21    path: PathBuf,
22}
23
24impl SessionDir {
25    pub fn create(repo: &Path, session_id: &str) -> Result<SessionDir, StoreError> {
26        let path = create_sub_dir(&sessions_root(repo), session_id)?;
27        Ok(SessionDir { path })
28    }
29
30    pub fn open(repo: &Path, session_id: &str) -> Result<SessionDir, StoreError> {
31        let path = open_dir(sessions_root(repo).join(session_id), session_id)?;
32        Ok(SessionDir { path })
33    }
34
35    pub fn latest(repo: &Path) -> Result<Option<String>, StoreError> {
36        let ids = sorted_entries(&sessions_root(repo))?;
37        Ok(ids
38            .into_iter()
39            .find(|id| sessions_root(repo).join(id).is_dir()))
40    }
41
42    pub fn path(&self) -> &Path {
43        &self.path
44    }
45
46    pub fn lock(&self) -> Result<Lock, LockError> {
47        Lock::acquire_file(self.path.join("lock"))
48    }
49
50    pub fn raw_log_path(&self, seq: u64) -> PathBuf {
51        self.path.join(format!("raw-{seq}.log"))
52    }
53
54    /// Scans `raw-*.log` files in the session directory and returns the next sequence number.
55    pub fn next_raw_log_seq(&self) -> u64 {
56        let max = std::fs::read_dir(&self.path)
57            .into_iter()
58            .flatten()
59            .filter_map(Result::ok)
60            .filter_map(|e| e.file_name().into_string().ok())
61            .filter_map(|name| {
62                name.strip_prefix("raw-")?
63                    .strip_suffix(".log")?
64                    .parse::<u64>()
65                    .ok()
66            })
67            .max();
68        max.map_or(1, |n| n + 1)
69    }
70
71    pub fn append(&self, record: &TranscriptRecord) -> Result<(), StoreError> {
72        append_jsonl(&self.transcript_path(), record)
73    }
74
75    pub fn read_transcript(&self) -> Result<Vec<TranscriptRecord>, StoreError> {
76        read_jsonl(&self.transcript_path())
77    }
78
79    fn transcript_path(&self) -> PathBuf {
80        self.path.join("transcript.jsonl")
81    }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85pub struct TranscriptRecord {
86    pub ts: u64,
87    #[serde(flatten)]
88    pub entry: TranscriptEntry,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(tag = "kind", rename_all = "snake_case")]
93pub enum TranscriptEntry {
94    Owner {
95        text: String,
96        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
97        btw: bool,
98    },
99    Planner {
100        text: String,
101        #[serde(default, skip_serializing_if = "Option::is_none")]
102        plan: Option<Proposal>,
103        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
104        btw: bool,
105    },
106    Run {
107        run: String,
108        #[serde(default)]
109        from_owner: bool,
110    },
111    System {
112        text: String,
113    },
114}
115
116/// Extracts owner and planner messages from transcript records in chronological order.
117pub fn messages(records: &[TranscriptRecord]) -> Vec<ChatMessage> {
118    records
119        .iter()
120        .filter_map(|record| match &record.entry {
121            TranscriptEntry::Owner { text, .. } => Some(ChatMessage {
122                from_owner: true,
123                text: text.clone(),
124            }),
125            TranscriptEntry::Planner { text, .. } => Some(ChatMessage {
126                from_owner: false,
127                text: text.clone(),
128            }),
129            TranscriptEntry::Run { .. } | TranscriptEntry::System { .. } => None,
130        })
131        .collect()
132}
133
134/// Reconstructs the current unapproved waiting plan from transcript records.
135pub fn waiting_plan(records: &[TranscriptRecord]) -> Option<Proposal> {
136    let mut waiting = None;
137    for record in records {
138        match &record.entry {
139            TranscriptEntry::Planner {
140                plan: Some(proposal),
141                btw: false,
142                ..
143            } => waiting = Some(proposal.clone()),
144            TranscriptEntry::Run {
145                from_owner: false, ..
146            } => waiting = None,
147            _ => {}
148        }
149    }
150    waiting
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct SessionRuns {
155    pub latest_done_branch: Option<String>,
156    pub planner_cwd: PathBuf,
157    pub latest_resumable: Option<String>,
158}
159
160/// Inspects the runs listed in `records` to find the latest done base and resumable run.
161pub fn session_runs(repo: &Path, records: &[TranscriptRecord]) -> SessionRuns {
162    let mut result = SessionRuns {
163        latest_done_branch: None,
164        planner_cwd: repo.to_path_buf(),
165        latest_resumable: None,
166    };
167    for record in records {
168        let TranscriptEntry::Run { run, .. } = &record.entry else {
169            continue;
170        };
171        let Ok(state) = RunDir::open(repo, run).and_then(|d| d.read_state()) else {
172            continue;
173        };
174        if state.phase == Phase::Done {
175            result.latest_done_branch = Some(state.branch);
176            result.planner_cwd = if state.worktree.is_dir() {
177                state.worktree
178            } else {
179                repo.to_path_buf()
180            };
181        } else if state.phase != Phase::Failed {
182            result.latest_resumable = Some(run.clone());
183        }
184    }
185    result
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use crate::plan::{Plan, Task};
192    use crate::store::{LaneMark, STATE_VERSION, State};
193    use serde_json::json;
194    use std::collections::BTreeMap;
195
196    fn proposal(goal: &str) -> Proposal {
197        Proposal {
198            goal: goal.into(),
199            plan: Plan {
200                tasks: vec![Task {
201                    id: "t1".into(),
202                    title: "Task 1".into(),
203                    instructions: "Do it.".into(),
204                    acceptance: vec!["Done".into()],
205                    lane: None,
206                    from_owner: false,
207                }],
208            },
209        }
210    }
211
212    #[test]
213    fn transcript_records_match_documented_json_and_round_trip() {
214        let records = [
215            TranscriptRecord {
216                ts: 1,
217                entry: TranscriptEntry::Owner {
218                    text: "add retries".into(),
219                    btw: false,
220                },
221            },
222            TranscriptRecord {
223                ts: 2,
224                entry: TranscriptEntry::Planner {
225                    text: "Two tasks".into(),
226                    plan: Some(proposal("Add retries")),
227                    btw: false,
228                },
229            },
230            TranscriptRecord {
231                ts: 3,
232                entry: TranscriptEntry::Run {
233                    run: "r1".into(),
234                    from_owner: false,
235                },
236            },
237            TranscriptRecord {
238                ts: 4,
239                entry: TranscriptEntry::System {
240                    text: "paused".into(),
241                },
242            },
243        ];
244
245        assert_eq!(
246            serde_json::to_value(&records[0]).unwrap(),
247            json!({"ts": 1, "kind": "owner", "text": "add retries"})
248        );
249        assert_eq!(
250            serde_json::to_value(&records[2]).unwrap(),
251            json!({"ts": 3, "kind": "run", "run": "r1", "from_owner": false})
252        );
253
254        let repo = tempfile::tempdir().unwrap();
255        let dir = SessionDir::create(repo.path(), "s1").unwrap();
256        for rec in &records {
257            dir.append(rec).unwrap();
258        }
259        assert_eq!(dir.read_transcript().unwrap(), records);
260    }
261
262    #[test]
263    fn session_dir_handles_latest_lock_and_raw_log_sequence() {
264        let repo = tempfile::tempdir().unwrap();
265        assert_eq!(SessionDir::latest(repo.path()).unwrap(), None);
266
267        let s1 = SessionDir::create(repo.path(), "20261125-090000-0001").unwrap();
268        let s2 = SessionDir::create(repo.path(), "20261125-100000-0002").unwrap();
269        assert_eq!(
270            SessionDir::latest(repo.path()).unwrap().as_deref(),
271            Some("20261125-100000-0002")
272        );
273        assert_eq!(
274            SessionDir::open(repo.path(), "20261125-090000-0001").unwrap(),
275            s1
276        );
277
278        let _lock = s2.lock().unwrap();
279        assert!(matches!(s2.lock(), Err(LockError::Held { .. })));
280
281        assert_eq!(s2.next_raw_log_seq(), 1);
282        std::fs::write(s2.raw_log_path(1), "a").unwrap();
283        std::fs::write(s2.raw_log_path(4), "b").unwrap();
284        assert_eq!(s2.next_raw_log_seq(), 5);
285    }
286
287    #[test]
288    fn messages_waiting_plan_and_session_runs_derive_state_from_transcript() {
289        let repo = tempfile::tempdir().unwrap();
290        let wt = repo.path().join("wt-done");
291        std::fs::create_dir(&wt).unwrap();
292        let make_state = |id: &str, phase: Phase, worktree: PathBuf| State {
293            v: STATE_VERSION,
294            run_id: id.into(),
295            goal: "g".into(),
296            updated_at: 1,
297            repo: repo.path().to_path_buf(),
298            worktree,
299            branch: format!("onerig/{id}"),
300            phase,
301            paused: None,
302            task_index: None,
303            task_base: None,
304            attempt: None,
305            attempts_used: 0,
306            lane: None,
307            unknown_streak: 0,
308            skipped: vec![],
309            last_end: None,
310            approved: false,
311            issues: vec![],
312            last_output_tail: String::new(),
313            job_seq: 0,
314            lanes: BTreeMap::<String, LaneMark>::new(),
315        };
316        RunDir::create(repo.path(), "r1")
317            .unwrap()
318            .write_state(&make_state("r1", Phase::Done, wt.clone()))
319            .unwrap();
320        RunDir::create(repo.path(), "r2")
321            .unwrap()
322            .write_state(&make_state(
323                "r2",
324                Phase::Paused,
325                repo.path().join("missing"),
326            ))
327            .unwrap();
328
329        let recs = [
330            TranscriptRecord {
331                ts: 1,
332                entry: TranscriptEntry::Owner {
333                    text: "q".into(),
334                    btw: false,
335                },
336            },
337            TranscriptRecord {
338                ts: 2,
339                entry: TranscriptEntry::Planner {
340                    text: "p1".into(),
341                    plan: Some(proposal("G1")),
342                    btw: false,
343                },
344            },
345            TranscriptRecord {
346                ts: 3,
347                entry: TranscriptEntry::Run {
348                    run: "r1".into(),
349                    from_owner: true,
350                },
351            },
352            TranscriptRecord {
353                ts: 4,
354                entry: TranscriptEntry::Planner {
355                    text: "answer only".into(),
356                    plan: None,
357                    btw: false,
358                },
359            },
360        ];
361
362        assert_eq!(
363            messages(&recs),
364            [
365                ChatMessage {
366                    from_owner: true,
367                    text: "q".into()
368                },
369                ChatMessage {
370                    from_owner: false,
371                    text: "p1".into()
372                },
373                ChatMessage {
374                    from_owner: false,
375                    text: "answer only".into()
376                },
377            ]
378        );
379        assert_eq!(waiting_plan(&recs), Some(proposal("G1")));
380
381        let started = [
382            recs[1].clone(),
383            TranscriptRecord {
384                ts: 5,
385                entry: TranscriptEntry::Run {
386                    run: "r2".into(),
387                    from_owner: false,
388                },
389            },
390        ];
391        assert_eq!(waiting_plan(&started), None);
392
393        let all_runs = [
394            TranscriptRecord {
395                ts: 3,
396                entry: TranscriptEntry::Run {
397                    run: "r1".into(),
398                    from_owner: false,
399                },
400            },
401            TranscriptRecord {
402                ts: 5,
403                entry: TranscriptEntry::Run {
404                    run: "r2".into(),
405                    from_owner: false,
406                },
407            },
408        ];
409        let runs = session_runs(repo.path(), &all_runs);
410        assert_eq!(runs.latest_done_branch.as_deref(), Some("onerig/r1"));
411        assert_eq!(runs.planner_cwd, wt);
412        assert_eq!(runs.latest_resumable.as_deref(), Some("r2"));
413    }
414}