onerig-core 0.2.4

Core library of onerig: run state machine, lane policy and harness adapters.
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
//! Chat session persistence on disk (design sections 5 and 8):
//! `<repo>/.onerig/sessions/<session id>/transcript.jsonl`, `lock`, and `raw-<n>.log`.

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

use serde::{Deserialize, Serialize};

use crate::store::{
    Lock, LockError, Phase, RunDir, StoreError, append_jsonl, create_sub_dir, open_dir, read_jsonl,
    sorted_entries,
};
use crate::turn::{ChatMessage, Proposal};

/// `<repo>/.onerig/sessions`.
pub fn sessions_root(repo: &Path) -> PathBuf {
    repo.join(".onerig").join("sessions")
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionDir {
    path: PathBuf,
}

impl SessionDir {
    pub fn create(repo: &Path, session_id: &str) -> Result<SessionDir, StoreError> {
        let path = create_sub_dir(&sessions_root(repo), session_id)?;
        Ok(SessionDir { path })
    }

    pub fn open(repo: &Path, session_id: &str) -> Result<SessionDir, StoreError> {
        let path = open_dir(sessions_root(repo).join(session_id), session_id)?;
        Ok(SessionDir { path })
    }

    pub fn latest(repo: &Path) -> Result<Option<String>, StoreError> {
        let ids = sorted_entries(&sessions_root(repo))?;
        Ok(ids
            .into_iter()
            .find(|id| sessions_root(repo).join(id).is_dir()))
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn lock(&self) -> Result<Lock, LockError> {
        Lock::acquire_file(self.path.join("lock"))
    }

    pub fn raw_log_path(&self, seq: u64) -> PathBuf {
        self.path.join(format!("raw-{seq}.log"))
    }

    /// Scans `raw-*.log` files in the session directory and returns the next sequence number.
    pub fn next_raw_log_seq(&self) -> u64 {
        let max = std::fs::read_dir(&self.path)
            .into_iter()
            .flatten()
            .filter_map(Result::ok)
            .filter_map(|e| e.file_name().into_string().ok())
            .filter_map(|name| {
                name.strip_prefix("raw-")?
                    .strip_suffix(".log")?
                    .parse::<u64>()
                    .ok()
            })
            .max();
        max.map_or(1, |n| n + 1)
    }

    pub fn append(&self, record: &TranscriptRecord) -> Result<(), StoreError> {
        append_jsonl(&self.transcript_path(), record)
    }

    pub fn read_transcript(&self) -> Result<Vec<TranscriptRecord>, StoreError> {
        read_jsonl(&self.transcript_path())
    }

    fn transcript_path(&self) -> PathBuf {
        self.path.join("transcript.jsonl")
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TranscriptRecord {
    pub ts: u64,
    #[serde(flatten)]
    pub entry: TranscriptEntry,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TranscriptEntry {
    Owner {
        text: String,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        btw: bool,
    },
    Planner {
        text: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        plan: Option<Proposal>,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        btw: bool,
    },
    Run {
        run: String,
        #[serde(default)]
        from_owner: bool,
    },
    System {
        text: String,
    },
}

/// Extracts owner and planner messages from transcript records in chronological order.
pub fn messages(records: &[TranscriptRecord]) -> Vec<ChatMessage> {
    records
        .iter()
        .filter_map(|record| match &record.entry {
            TranscriptEntry::Owner { text, .. } => Some(ChatMessage {
                from_owner: true,
                text: text.clone(),
            }),
            TranscriptEntry::Planner { text, .. } => Some(ChatMessage {
                from_owner: false,
                text: text.clone(),
            }),
            TranscriptEntry::Run { .. } | TranscriptEntry::System { .. } => None,
        })
        .collect()
}

/// Reconstructs the current unapproved waiting plan from transcript records.
pub fn waiting_plan(records: &[TranscriptRecord]) -> Option<Proposal> {
    let mut waiting = None;
    for record in records {
        match &record.entry {
            TranscriptEntry::Planner {
                plan: Some(proposal),
                btw: false,
                ..
            } => waiting = Some(proposal.clone()),
            TranscriptEntry::Run {
                from_owner: false, ..
            } => waiting = None,
            _ => {}
        }
    }
    waiting
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionRuns {
    pub latest_done_branch: Option<String>,
    pub planner_cwd: PathBuf,
    pub latest_resumable: Option<String>,
}

/// Inspects the runs listed in `records` to find the latest done base and resumable run.
pub fn session_runs(repo: &Path, records: &[TranscriptRecord]) -> SessionRuns {
    let mut result = SessionRuns {
        latest_done_branch: None,
        planner_cwd: repo.to_path_buf(),
        latest_resumable: None,
    };
    for record in records {
        let TranscriptEntry::Run { run, .. } = &record.entry else {
            continue;
        };
        let Ok(state) = RunDir::open(repo, run).and_then(|d| d.read_state()) else {
            continue;
        };
        if state.phase == Phase::Done {
            result.latest_done_branch = Some(state.branch);
            result.planner_cwd = if state.worktree.is_dir() {
                state.worktree
            } else {
                repo.to_path_buf()
            };
        } else if state.phase != Phase::Failed {
            result.latest_resumable = Some(run.clone());
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plan::{Plan, Task};
    use crate::store::{LaneMark, STATE_VERSION, State};
    use serde_json::json;
    use std::collections::BTreeMap;

    fn proposal(goal: &str) -> Proposal {
        Proposal {
            goal: goal.into(),
            plan: Plan {
                tasks: vec![Task {
                    id: "t1".into(),
                    title: "Task 1".into(),
                    instructions: "Do it.".into(),
                    acceptance: vec!["Done".into()],
                    lane: None,
                    from_owner: false,
                }],
            },
        }
    }

    #[test]
    fn transcript_records_match_documented_json_and_round_trip() {
        let records = [
            TranscriptRecord {
                ts: 1,
                entry: TranscriptEntry::Owner {
                    text: "add retries".into(),
                    btw: false,
                },
            },
            TranscriptRecord {
                ts: 2,
                entry: TranscriptEntry::Planner {
                    text: "Two tasks".into(),
                    plan: Some(proposal("Add retries")),
                    btw: false,
                },
            },
            TranscriptRecord {
                ts: 3,
                entry: TranscriptEntry::Run {
                    run: "r1".into(),
                    from_owner: false,
                },
            },
            TranscriptRecord {
                ts: 4,
                entry: TranscriptEntry::System {
                    text: "paused".into(),
                },
            },
        ];

        assert_eq!(
            serde_json::to_value(&records[0]).unwrap(),
            json!({"ts": 1, "kind": "owner", "text": "add retries"})
        );
        assert_eq!(
            serde_json::to_value(&records[2]).unwrap(),
            json!({"ts": 3, "kind": "run", "run": "r1", "from_owner": false})
        );

        let repo = tempfile::tempdir().unwrap();
        let dir = SessionDir::create(repo.path(), "s1").unwrap();
        for rec in &records {
            dir.append(rec).unwrap();
        }
        assert_eq!(dir.read_transcript().unwrap(), records);
    }

    #[test]
    fn session_dir_handles_latest_lock_and_raw_log_sequence() {
        let repo = tempfile::tempdir().unwrap();
        assert_eq!(SessionDir::latest(repo.path()).unwrap(), None);

        let s1 = SessionDir::create(repo.path(), "20261125-090000-0001").unwrap();
        let s2 = SessionDir::create(repo.path(), "20261125-100000-0002").unwrap();
        assert_eq!(
            SessionDir::latest(repo.path()).unwrap().as_deref(),
            Some("20261125-100000-0002")
        );
        assert_eq!(
            SessionDir::open(repo.path(), "20261125-090000-0001").unwrap(),
            s1
        );

        let _lock = s2.lock().unwrap();
        assert!(matches!(s2.lock(), Err(LockError::Held { .. })));

        assert_eq!(s2.next_raw_log_seq(), 1);
        std::fs::write(s2.raw_log_path(1), "a").unwrap();
        std::fs::write(s2.raw_log_path(4), "b").unwrap();
        assert_eq!(s2.next_raw_log_seq(), 5);
    }

    #[test]
    fn messages_waiting_plan_and_session_runs_derive_state_from_transcript() {
        let repo = tempfile::tempdir().unwrap();
        let wt = repo.path().join("wt-done");
        std::fs::create_dir(&wt).unwrap();
        let make_state = |id: &str, phase: Phase, worktree: PathBuf| State {
            v: STATE_VERSION,
            run_id: id.into(),
            goal: "g".into(),
            updated_at: 1,
            repo: repo.path().to_path_buf(),
            worktree,
            branch: format!("onerig/{id}"),
            phase,
            paused: None,
            task_index: None,
            task_base: None,
            attempt: None,
            attempts_used: 0,
            lane: None,
            unknown_streak: 0,
            skipped: vec![],
            last_end: None,
            approved: false,
            issues: vec![],
            last_output_tail: String::new(),
            job_seq: 0,
            lanes: BTreeMap::<String, LaneMark>::new(),
        };
        RunDir::create(repo.path(), "r1")
            .unwrap()
            .write_state(&make_state("r1", Phase::Done, wt.clone()))
            .unwrap();
        RunDir::create(repo.path(), "r2")
            .unwrap()
            .write_state(&make_state(
                "r2",
                Phase::Paused,
                repo.path().join("missing"),
            ))
            .unwrap();

        let recs = [
            TranscriptRecord {
                ts: 1,
                entry: TranscriptEntry::Owner {
                    text: "q".into(),
                    btw: false,
                },
            },
            TranscriptRecord {
                ts: 2,
                entry: TranscriptEntry::Planner {
                    text: "p1".into(),
                    plan: Some(proposal("G1")),
                    btw: false,
                },
            },
            TranscriptRecord {
                ts: 3,
                entry: TranscriptEntry::Run {
                    run: "r1".into(),
                    from_owner: true,
                },
            },
            TranscriptRecord {
                ts: 4,
                entry: TranscriptEntry::Planner {
                    text: "answer only".into(),
                    plan: None,
                    btw: false,
                },
            },
        ];

        assert_eq!(
            messages(&recs),
            [
                ChatMessage {
                    from_owner: true,
                    text: "q".into()
                },
                ChatMessage {
                    from_owner: false,
                    text: "p1".into()
                },
                ChatMessage {
                    from_owner: false,
                    text: "answer only".into()
                },
            ]
        );
        assert_eq!(waiting_plan(&recs), Some(proposal("G1")));

        let started = [
            recs[1].clone(),
            TranscriptRecord {
                ts: 5,
                entry: TranscriptEntry::Run {
                    run: "r2".into(),
                    from_owner: false,
                },
            },
        ];
        assert_eq!(waiting_plan(&started), None);

        let all_runs = [
            TranscriptRecord {
                ts: 3,
                entry: TranscriptEntry::Run {
                    run: "r1".into(),
                    from_owner: false,
                },
            },
            TranscriptRecord {
                ts: 5,
                entry: TranscriptEntry::Run {
                    run: "r2".into(),
                    from_owner: false,
                },
            },
        ];
        let runs = session_runs(repo.path(), &all_runs);
        assert_eq!(runs.latest_done_branch.as_deref(), Some("onerig/r1"));
        assert_eq!(runs.planner_cwd, wt);
        assert_eq!(runs.latest_resumable.as_deref(), Some("r2"));
    }
}