-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsession.rs
More file actions
2166 lines (2044 loc) · 75.6 KB
/
Copy pathsession.rs
File metadata and controls
2166 lines (2044 loc) · 75.6 KB
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Session persistence: append-only JSONL of conversation messages, prefixed
// by a schema-version header line so future shape changes can migrate old
// files instead of silently misreading them. On init, if the session file
// exists it's loaded and replayed; each finalized message is appended (and
// fsync'd) so a crash mid-task loses at most the in-flight turn.
use crate::message::Message;
use serde_json::Value;
use std::fs::OpenOptions;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
/// Bump when the on-disk message shape changes. load() validates the header.
pub const SESSION_VERSION: u32 = 2;
fn header_line() -> String {
format!("{{\"_session_version\": {}}}", SESSION_VERSION)
}
fn ensure_header(path: &Path) {
// Create the file with a header if it doesn't exist yet.
if path.exists() {
return;
}
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(mut f) = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path)
{
let _ = writeln!(f, "{}", header_line());
let _ = f.flush();
let _ = f.sync_all();
}
}
/// Migrate an existing session file's version header if needed.
/// Does **not** create a missing file. Unused `/new` and launch paths must
/// not leave a header-only journal; the first `append` creates the file.
pub fn ensure(path: &Path) {
if path.exists() {
migrate_header(path);
}
}
/// True for a conversation journal (`<stamp>.jsonl`), not sidecar JSONL
/// (`*.checkpoints.jsonl`, `*.intercom.jsonl`).
pub fn is_session_file(path: &Path) -> bool {
let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
return false;
};
let Some(stem) = name.strip_suffix(".jsonl") else {
return false;
};
!stem.is_empty() && !stem.contains('.')
}
/// True when the journal has at least one conversation message.
pub fn has_messages(path: &Path) -> bool {
describe(path).messages > 0
}
fn migrate_header(path: &Path) {
let Ok(content) = std::fs::read_to_string(path) else {
return;
};
let Some((first, rest)) = content.split_once('\n') else {
return;
};
let Ok(header) = serde_json::from_str::<Value>(first) else {
return;
};
let Some(version) = header.get("_session_version").and_then(Value::as_u64) else {
return;
};
if version as u32 >= SESSION_VERSION {
return;
}
let migrated = format!("{}\n{}", header_line(), rest);
let _ = crate::fsutil::atomic_write_str(path, &migrated);
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunState {
Started,
Completed,
Cancelled,
Failed,
Interrupted,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RunRecord {
pub session_id: String,
pub run_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent_run_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_call_id: Option<String>,
pub state: RunState,
pub timestamp_ms: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ParentDelivery {
pub parent_run_id: String,
pub run_id: String,
pub artifact_path: PathBuf,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct CompactionRecord {
pub id: String,
#[serde(default, rename = "parentId")]
pub parent_id: Option<String>,
#[serde(default)]
pub root: Option<String>,
#[serde(default)]
pub summary: String,
#[serde(default)]
pub artifacts: Vec<String>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AbandonedBranch {
pub from: String,
pub to: String,
pub summary: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct SessionEntry {
pub id: String,
#[serde(default, rename = "parentId")]
pub parent_id: Option<String>,
/// Branch markers carry no transcript message. The next real append becomes
/// their child, so branching never injects synthetic content into context.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<Message>,
}
fn next_compaction_id() -> String {
use rand::Rng;
format!("compaction-{:016x}", rand::thread_rng().gen::<u64>())
}
fn next_entry_id() -> String {
use rand::Rng;
format!("entry-{:016x}", rand::thread_rng().gen::<u64>())
}
fn leaf_path(path: &Path) -> PathBuf {
path.with_extension("leaf.json")
}
fn read_active_leaf(path: &Path) -> Result<Option<String>, String> {
let sidecar = leaf_path(path);
let raw = match std::fs::read_to_string(&sidecar) {
Ok(raw) => raw,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(format!("read active leaf {}: {error}", sidecar.display())),
};
let value: Value = serde_json::from_str(&raw)
.map_err(|error| format!("malformed active leaf {}: {error}", sidecar.display()))?;
let leaf = value
.get("leaf")
.and_then(Value::as_str)
.filter(|id| !id.trim().is_empty())
.ok_or_else(|| {
format!(
"malformed active leaf {}: missing leaf id",
sidecar.display()
)
})?;
Ok(Some(leaf.to_string()))
}
pub fn active_leaf(path: &Path) -> Option<String> {
read_active_leaf(path).ok().flatten()
}
fn set_active_leaf(path: &Path, id: &str) -> Result<(), String> {
crate::fsutil::atomic_write_str(
&leaf_path(path),
&serde_json::json!({"leaf":id}).to_string(),
)
.map_err(|e| format!("write active leaf: {e}"))
}
#[derive(Debug, Default)]
pub struct LoadReport {
pub messages: Vec<Message>,
pub warnings: Vec<String>,
pub unfinished_runs: Vec<RunRecord>,
pub parent_deliveries: Vec<ParentDelivery>,
pub entries: Vec<SessionEntry>,
pub compactions: Vec<CompactionRecord>,
pub abandoned_branches: Vec<AbandonedBranch>,
}
fn tree_metadata(
entries: &[SessionEntry],
leaf: Option<&str>,
) -> Result<(Vec<String>, Vec<String>), String> {
let mut by_id = std::collections::HashMap::new();
for entry in entries {
if entry.id.trim().is_empty() {
return Err("session tree contains an empty entry id".into());
}
if by_id.insert(entry.id.as_str(), entry).is_some() {
return Err(format!(
"session tree contains duplicate entry id {}",
entry.id
));
}
}
for entry in entries {
if let Some(parent) = entry.parent_id.as_deref() {
if parent == entry.id {
return Err(format!("session entry {} points to itself", entry.id));
}
if !by_id.contains_key(parent) {
return Err(format!(
"session entry {} points to missing parent {}",
entry.id, parent
));
}
}
}
let Some(leaf) = leaf else {
return Ok((Vec::new(), Vec::new()));
};
if !by_id.contains_key(leaf) {
return Err(format!("active session leaf {leaf} is unknown"));
}
let mut ancestry = Vec::new();
let mut cursor = Some(leaf);
let mut seen = std::collections::HashSet::new();
while let Some(id) = cursor {
if !seen.insert(id) {
return Err("session tree contains a parent cycle".into());
}
ancestry.push(id.to_string());
cursor = by_id.get(id).and_then(|entry| entry.parent_id.as_deref());
}
ancestry.reverse();
let parent = by_id.get(leaf).and_then(|entry| entry.parent_id.as_deref());
let siblings = entries
.iter()
.filter(|entry| entry.parent_id.as_deref() == parent && entry.id != leaf)
.map(|entry| entry.id.clone())
.collect();
Ok((ancestry, siblings))
}
pub fn session_tree(path: &Path) -> Value {
let report = match load_report(path) {
Ok(report) => report,
Err(error) => {
return serde_json::json!({"leaf": Value::Null, "entries": [], "compactions": [], "abandonedBranches": [], "ancestry": [], "siblings": [], "warning": error})
}
};
let leaf = match read_active_leaf(path) {
Ok(leaf) => leaf.or_else(|| report.entries.last().map(|entry| entry.id.clone())),
Err(error) => {
return serde_json::json!({"leaf": Value::Null, "entries": report.entries, "compactions": report.compactions, "abandonedBranches": report.abandoned_branches, "ancestry": [], "siblings": [], "warning": error})
}
};
match tree_metadata(&report.entries, leaf.as_deref()) {
Ok((ancestry, siblings)) => serde_json::json!({
"leaf": leaf,
"entries": report.entries,
"compactions": report.compactions,
"abandonedBranches": report.abandoned_branches,
"ancestry": ancestry,
"siblings": siblings,
}),
Err(error) => {
serde_json::json!({"leaf": Value::Null, "entries": report.entries, "compactions": report.compactions, "abandonedBranches": report.abandoned_branches, "ancestry": [], "siblings": [], "warning": error})
}
}
}
/// Visible history for TUI/web, each message tagged with its session entry id
/// so "edit from here" can call `session_branch` with a real `entry-*` id.
pub fn history_messages(path: Option<&Path>, messages: &[Message]) -> Vec<Value> {
let ids = path.and_then(entry_ids_for_visible).unwrap_or_default();
messages
.iter()
.filter(|m| !m.is_system())
.enumerate()
.map(|(i, message)| {
let mut value = Value::from(message);
if let Some(id) = ids.get(i) {
if let Some(obj) = value.as_object_mut() {
obj.insert("entry_id".into(), serde_json::json!(id));
}
}
value
})
.collect()
}
fn entry_ids_for_visible(path: &Path) -> Option<Vec<String>> {
let report = load_report(path).ok()?;
let leaf = active_leaf(path).or_else(|| report.entries.last().map(|entry| entry.id.clone()))?;
let by_id: std::collections::HashMap<&str, &SessionEntry> = report
.entries
.iter()
.map(|entry| (entry.id.as_str(), entry))
.collect();
let mut chain = Vec::new();
let mut cursor = Some(leaf.as_str());
let mut guard = 0usize;
while let Some(id) = cursor {
guard += 1;
if guard > 10_000 {
break;
}
let Some(entry) = by_id.get(id) else {
break;
};
if entry
.message
.as_ref()
.is_some_and(|message| !message.is_system())
{
chain.push(entry.id.clone());
}
cursor = entry.parent_id.as_deref();
}
chain.reverse();
Some(chain)
}
pub fn create_branch(path: &Path, entry_id: &str) -> Result<String, String> {
let report = load_report(path)?;
tree_metadata(&report.entries, Some(entry_id))?;
if let Some(from) = active_leaf(path).filter(|from| from != entry_id) {
let by_id: std::collections::HashMap<&str, &SessionEntry> = report
.entries
.iter()
.map(|entry| (entry.id.as_str(), entry))
.collect();
let mut cursor = Some(from.as_str());
let mut abandoned = Vec::new();
while let Some(id) = cursor {
if id == entry_id {
break;
}
let Some(entry) = by_id.get(id) else { break };
if let Some(text) = entry.message.as_ref().and_then(Message::content_text) {
abandoned.push(text.to_string());
}
cursor = entry.parent_id.as_deref();
}
if !abandoned.is_empty() {
abandoned.reverse();
let mut summary = abandoned.join(" | ");
const MAX_BRANCH_SUMMARY_CHARS: usize = 512;
if summary.chars().count() > MAX_BRANCH_SUMMARY_CHARS {
summary = summary.chars().take(MAX_BRANCH_SUMMARY_CHARS - 1).collect();
summary.push('…');
}
append_branch_summary(path, &from, entry_id, &summary)?;
}
}
let _lock = crate::fsutil::FileLock::acquire(&path.with_extension("lock"))
.map_err(|e| format!("lock session branch: {e}"))?;
ensure_record_boundary(path);
let id = next_entry_id();
let entry = SessionEntry {
id: id.clone(),
parent_id: Some(entry_id.to_string()),
message: None,
};
let mut file = OpenOptions::new()
.append(true)
.open(path)
.map_err(|e| format!("open session branch: {e}"))?;
writeln!(file, "{}", serde_json::json!({"_entry": entry}))
.map_err(|e| format!("append session branch: {e}"))?;
file.sync_all()
.map_err(|e| format!("sync session branch: {e}"))?;
set_active_leaf(path, &id)?;
Ok(id)
}
pub fn append_run_state(
path: &Path,
session_id: &str,
run_id: &str,
state: RunState,
detail: Option<&str>,
) {
append_activity_state(path, session_id, run_id, "run", None, None, state, detail);
}
/// Append a lifecycle record for foreground or child activity. New optional
/// identity fields are backward-compatible with v2 journals and let recovery
/// distinguish an interrupted tool, subagent, or goal without ever restarting it.
#[allow(clippy::too_many_arguments)]
pub fn append_activity_state(
path: &Path,
session_id: &str,
run_id: &str,
kind: &str,
parent_run_id: Option<&str>,
tool_call_id: Option<&str>,
state: RunState,
detail: Option<&str>,
) {
ensure_header(path);
// Same lock as append/rewrite so run-state lines cannot interleave
// with message entries (CORE_REVIEW).
let Ok(_lock) = crate::fsutil::FileLock::acquire(&path.with_extension("lock")) else {
eprintln!(
"[session] activity_state lock failed for {}",
path.display()
);
return;
};
ensure_record_boundary(path);
let record = RunRecord {
session_id: session_id.to_string(),
run_id: run_id.to_string(),
kind: Some(kind.to_string()),
parent_run_id: parent_run_id.map(str::to_string),
tool_call_id: tool_call_id.map(str::to_string),
state,
timestamp_ms: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64,
detail: detail.map(str::to_string),
};
let Ok(mut file) = OpenOptions::new().append(true).open(path) else {
return;
};
let line = serde_json::json!({"_run": record});
let _ = writeln!(file, "{line}");
let _ = file.flush();
}
pub fn append(path: &Path, msg: &Message) {
ensure_header(path);
let Ok(_lock) = crate::fsutil::FileLock::acquire(&path.with_extension("lock")) else {
eprintln!(
"[session] append lock failed for {}; message not persisted",
path.display()
);
return;
};
ensure_record_boundary(path);
let id = next_entry_id();
let entry = SessionEntry {
id: id.clone(),
parent_id: active_leaf(path),
message: Some(msg.clone()),
};
let Ok(mut file) = OpenOptions::new().append(true).open(path) else {
eprintln!(
"[session] append open failed for {}; message not persisted",
path.display()
);
return;
};
let line = serde_json::json!({"_entry": entry});
if writeln!(file, "{line}").is_err() || file.flush().is_err() {
eprintln!(
"[session] append write failed for {}; message not persisted",
path.display()
);
return;
}
let _ = file.sync_all();
let _ = set_active_leaf(path, &id);
}
fn ensure_record_boundary(path: &Path) {
use std::io::{Read, Seek, SeekFrom};
let Ok(mut file) = OpenOptions::new().read(true).append(true).open(path) else {
return;
};
let Ok(length) = file.metadata().map(|metadata| metadata.len()) else {
return;
};
if length == 0 || file.seek(SeekFrom::End(-1)).is_err() {
return;
}
let mut last = [0_u8; 1];
if file.read_exact(&mut last).is_ok() && last[0] != b'\n' {
let _ = file.write_all(b"\n");
let _ = file.flush();
}
}
#[cfg(test)]
fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
pub fn artifact_path(session_path: &Path, run_id: &str) -> PathBuf {
use sha2::{Digest, Sha256};
let digest = Sha256::digest(run_id.as_bytes());
let hash = digest[..12]
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
session_path
.parent()
.unwrap_or_else(|| Path::new("."))
.join("artifacts")
.join(format!("job-{hash}.json"))
}
#[cfg(test)]
pub fn write_job_artifact(
session_path: &Path,
run_id: &str,
parent_run_id: Option<&str>,
state: &str,
summary: &str,
) -> Result<PathBuf, String> {
let now = now_ms();
write_job_artifact_record(
session_path,
run_id,
parent_run_id,
run_id,
state,
now,
now,
(state == "failed").then_some(summary),
summary,
)
}
/// Persist the complete durable job record. The artifact is session-owned and
/// its own path is recorded as the result reference so restart can inspect it.
pub fn write_job_artifact_record(
session_path: &Path,
run_id: &str,
parent_run_id: Option<&str>,
task_identity: &str,
state: &str,
started_at: u64,
ended_at: u64,
error: Option<&str>,
summary: &str,
) -> Result<PathBuf, String> {
let path = artifact_path(session_path, run_id);
std::fs::create_dir_all(path.parent().unwrap())
.map_err(|e| format!("create artifact dir: {e}"))?;
let body = serde_json::json!({
"run_id": run_id,
"parent_run_id": parent_run_id,
"task_identity": task_identity,
"state": state,
"started_at": started_at,
"ended_at": ended_at,
"error": error,
"summary": summary,
"result_ref": path.display().to_string(),
});
crate::fsutil::atomic_write_str(&path, &(body.to_string() + "\n"))
.map_err(|e| format!("write job artifact: {e}"))?;
Ok(path)
}
pub fn read_job_artifact(session_path: &Path, run_id: &str) -> Option<Value> {
std::fs::read_to_string(artifact_path(session_path, run_id))
.ok()
.and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
.filter(|value| value.get("run_id").and_then(Value::as_str) == Some(run_id))
}
fn artifact_reference_run_id(reference: &str) -> Option<&str> {
let value = reference.strip_prefix("artifact://")?;
let filename = value.rsplit('/').next().unwrap_or(value);
filename.strip_suffix(".json").or(Some(filename))
}
pub fn artifact_run_ids_referenced_by_messages(
messages: &[Message],
) -> std::collections::HashSet<String> {
let mut retained = std::collections::HashSet::new();
for message in messages {
let Some(content) = message.content_text() else {
continue;
};
for value in content
.match_indices("artifact://")
.map(|(offset, _)| &content[offset..])
{
let reference = value.split_whitespace().next().unwrap_or(value);
if let Some(id) = artifact_reference_run_id(reference) {
retained.insert(id.to_string());
}
}
}
retained
}
pub fn shake_artifacts(
session_path: &Path,
keep_run_ids: &std::collections::HashSet<String>,
) -> Result<usize, String> {
let Some(dir) = session_path.parent().map(|parent| parent.join("artifacts")) else {
return Ok(0);
};
let Ok(entries) = std::fs::read_dir(&dir) else {
return Ok(0);
};
let mut retained = keep_run_ids.clone();
if let Ok(report) = load_report(session_path) {
retained.extend(
report
.parent_deliveries
.into_iter()
.map(|delivery| delivery.run_id),
);
for compaction in report.compactions {
for reference in compaction.artifacts {
if let Some(id) = artifact_reference_run_id(&reference) {
retained.insert(id.to_string());
}
}
}
}
let mut removed = 0;
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
continue;
}
let keep = std::fs::read_to_string(&path)
.ok()
.and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
.and_then(|value| {
value
.get("run_id")
.and_then(Value::as_str)
.map(str::to_string)
})
.is_some_and(|id| retained.contains(&id));
if !keep && std::fs::remove_file(&path).is_ok() {
removed += 1;
}
}
Ok(removed)
}
pub fn append_parent_delivery(
session_path: &Path,
parent_run_id: &str,
run_id: &str,
artifact: &Path,
) -> Result<(), String> {
ensure_header(session_path);
let _lock = crate::fsutil::FileLock::acquire(&session_path.with_extension("lock"))
.map_err(|e| e.to_string())?;
let existing = std::fs::read_to_string(session_path).unwrap_or_default();
if existing
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.any(|value| {
let Some(delivery) = value.get("_parent_delivery") else {
return false;
};
delivery.get("run_id").and_then(Value::as_str) == Some(run_id)
&& delivery.get("parent_run_id").and_then(Value::as_str) == Some(parent_run_id)
})
{
return Ok(());
}
ensure_record_boundary(session_path);
let mut file = OpenOptions::new()
.append(true)
.open(session_path)
.map_err(|e| e.to_string())?;
writeln!(file, "{}", serde_json::json!({"_parent_delivery":{"parent_run_id":parent_run_id,"run_id":run_id,"artifact_path":artifact}})).map_err(|e| e.to_string())?;
file.sync_all().map_err(|e| e.to_string())
}
pub fn append_compaction(
path: &Path,
messages: &[Message],
summary: &str,
artifacts: &[String],
) -> Result<(), String> {
ensure_header(path);
let _lock = crate::fsutil::FileLock::acquire(&path.with_extension("lock"))
.map_err(|e| format!("lock compaction journal: {e}"))?;
ensure_record_boundary(path);
let parent_id = active_leaf(path);
let record = CompactionRecord {
id: next_compaction_id(),
parent_id: parent_id.clone(),
root: parent_id,
summary: summary.to_string(),
artifacts: artifacts.to_vec(),
};
let mut file = OpenOptions::new()
.append(true)
.open(path)
.map_err(|e| format!("open compaction journal: {e}"))?;
let line = serde_json::json!({"_compaction": {
"id": record.id,
"parentId": record.parent_id,
"root": record.root,
"summary": record.summary,
"artifacts": record.artifacts,
"messages": messages,
}});
writeln!(file, "{line}").map_err(|e| format!("append compaction journal: {e}"))?;
file.sync_all()
.map_err(|e| format!("sync compaction journal: {e}"))
}
fn append_branch_summary(path: &Path, from: &str, to: &str, summary: &str) -> Result<(), String> {
let _lock = crate::fsutil::FileLock::acquire(&path.with_extension("lock"))
.map_err(|e| format!("lock branch journal: {e}"))?;
ensure_record_boundary(path);
let mut file = OpenOptions::new()
.append(true)
.open(path)
.map_err(|e| format!("open branch journal: {e}"))?;
writeln!(
file,
"{}",
serde_json::json!({"_abandoned_branch": {"from": from, "to": to, "summary": summary}})
)
.map_err(|e| format!("append branch journal: {e}"))?;
file.sync_all()
.map_err(|e| format!("sync branch journal: {e}"))
}
/// fsync the session file so finalized turns survive a crash. Call at turn
/// end (and on abort paths that have already appended results).
pub fn sync(path: &Path) {
if let Ok(f) = OpenOptions::new().append(true).open(path) {
let _ = f.sync_all();
}
if let Some(parent) = path.parent() {
fsync_dir(parent);
}
}
/// Load all messages from a session file. Skips the version header and any
/// unparseable lines. Returns `Ok(Vec)` for a missing file (nothing to resume)
/// or a current-version file. Returns `Err(human_message)` when the file's
/// header version is NEWER than `SESSION_VERSION` — refusing to silently
/// misread/drop a session on upgrade (the caller surfaces the error to the
/// user instead of quietly starting blank).
pub fn load(path: &Path) -> Result<Vec<Message>, String> {
load_report(path).map(|report| report.messages)
}
/// Load readable conversation records and return explicit recovery details.
/// Malformed records do not erase valid history; an incomplete final line is
/// treated as a crash-truncated append, while malformed interior lines are
/// counted separately. Started runs without a terminal record are returned so
/// startup can persist an `interrupted` terminal state without rerunning work.
pub fn load_report(path: &Path) -> Result<LoadReport, String> {
let Ok(content) = std::fs::read_to_string(path) else {
return Ok(LoadReport::default());
};
let nonempty: Vec<(usize, &str)> = content
.lines()
.enumerate()
.filter(|(_, line)| !line.trim().is_empty())
.collect();
let mut lines = nonempty.iter();
// First non-empty line must be the version header. If it's absent or a
// future version, bail with a clear error rather than guess.
let first = lines.next().map(|(_, line)| *line).unwrap_or("");
let mut report = LoadReport::default();
let mut run_states = std::collections::HashMap::<String, RunRecord>::new();
let mut first_is_message = false;
if let Ok(v) = serde_json::from_str::<Value>(first) {
if let Some(ver) = v.get("_session_version").and_then(|x| x.as_u64()) {
if ver as u32 > SESSION_VERSION {
return Err(format!(
"session file {} is version {ver}, newer than supported ({SESSION_VERSION}); not loaded to avoid corrupting it. Delete the file (or migrate it) to continue.",
path.display()
));
}
if (ver as u32) < SESSION_VERSION {
report.warnings.push(format!(
"session schema v{ver} loaded through compatibility mode; it will migrate to v{SESSION_VERSION} before the next append"
));
}
} else {
first_is_message = true;
report.warnings.push(
"legacy session without a version header loaded in compatibility mode".into(),
);
}
} else if !first.is_empty() {
first_is_message = true;
}
let records: Vec<(usize, &str)> = if first_is_message {
nonempty.clone()
} else {
nonempty.into_iter().skip(1).collect()
};
let last_line = records.last().map(|(line, _)| *line);
let final_line_terminated = content.ends_with('\n');
let mut compaction_root: Option<String> = None;
let mut malformed = Vec::new();
for (line_number, line) in records {
let line_number = line_number + 1;
let value = match serde_json::from_str::<Value>(line) {
Ok(value) => value,
Err(_) => {
if Some(line_number - 1) == last_line && !final_line_terminated {
report.warnings.push(format!(
"recovered session after ignoring a truncated final record at line {line_number}"
));
} else {
malformed.push(line_number);
}
continue;
}
};
if let Some(run) = value.get("_run") {
match serde_json::from_value::<RunRecord>(run.clone()) {
Ok(record) => {
run_states.insert(record.run_id.clone(), record);
}
Err(_) => malformed.push(line_number),
}
continue;
}
if let Some(compaction) = value.get("_compaction") {
if let Ok(record) = serde_json::from_value::<CompactionRecord>(compaction.clone()) {
report.compactions.push(record);
}
report.messages.clear();
compaction_root = compaction
.get("root")
.and_then(Value::as_str)
.map(str::to_string);
if let Some(messages) = compaction.get("messages").and_then(Value::as_array) {
for message in messages {
if let Ok(mut parsed) = serde_json::from_value::<Message>(message.clone()) {
parsed.normalize_embedded_thinking();
report.messages.push(parsed);
}
}
}
continue;
}
if let Some(entry) = value.get("_entry") {
match serde_json::from_value::<SessionEntry>(entry.clone()) {
Ok(mut entry) => {
if let Some(message) = &mut entry.message {
message.normalize_embedded_thinking();
}
report.entries.push(entry);
}
Err(_) => malformed.push(line_number),
}
continue;
}
if let Some(delivery) = value.get("_parent_delivery") {
match serde_json::from_value::<ParentDelivery>(delivery.clone()) {
Ok(record) => report.parent_deliveries.push(record),
Err(_) => malformed.push(line_number),
}
continue;
}
match serde_json::from_value::<Message>(value) {
Ok(mut message) => {
message.normalize_embedded_thinking();
report.messages.push(message);
}
Err(_) => malformed.push(line_number),
}
}
if !malformed.is_empty() {
report.warnings.push(format!(
"ignored {} malformed session record(s) at line(s) {}",
malformed.len(),
malformed
.iter()
.map(usize::to_string)
.collect::<Vec<_>>()
.join(", ")
));
}
if !report.entries.is_empty() {
let selected_leaf = match read_active_leaf(path) {
Ok(leaf) => leaf,
Err(error) => {
report.warnings.push(error);
None
}
};
if let Err(error) = tree_metadata(&report.entries, selected_leaf.as_deref()) {
report.warnings.push(error);
}
let by_id: std::collections::HashMap<String, SessionEntry> = report
.entries
.iter()
.cloned()
.map(|entry| (entry.id.clone(), entry))
.collect();
let mut cursor =
selected_leaf.or_else(|| report.entries.last().map(|entry| entry.id.clone()));
let mut ancestry = Vec::new();
let mut seen = std::collections::HashSet::new();
while let Some(id) = cursor {
if compaction_root.as_deref() == Some(id.as_str()) || !seen.insert(id.clone()) {
break;
}
let Some(entry) = by_id.get(&id) else {
break;
};
if let Some(message) = &entry.message {
ancestry.push(message.clone());
}
cursor = entry.parent_id.clone();
}
ancestry.reverse();
report.messages.extend(ancestry);
}
report.unfinished_runs = run_states
.into_values()
.filter(|record| record.state == RunState::Started)
.collect();
Ok(report)
}
/// Sidecar path for per-session "always" approval escalations (tool kinds the
/// user said "always" to). Stored beside the session file so it travels with
/// the project and survives restart — previously these were in-memory only,
/// so a restart silently un-gated kinds the user had approved.
fn escalations_path(session_path: &Path) -> PathBuf {
let mut p = session_path.as_os_str().to_os_string();
p.push(".escalations");
PathBuf::from(p)
}
/// Load persisted escalated approval kinds (empty set if absent/unreadable).
pub fn load_escalations(session_path: &Path) -> std::collections::HashSet<String> {
let p = escalations_path(session_path);
let Ok(content) = std::fs::read_to_string(&p) else {
return std::collections::HashSet::new();
};
serde_json::from_str::<Vec<String>>(&content)
.map(|v| v.into_iter().collect())
.unwrap_or_default()
}
/// Best-effort directory fsync after an atomic rename. POSIX does not guarantee
/// a rename survives a power-loss crash unless the parent directory is also
/// fsync'd, so after each temp→target rename we fsync the parent dir. Ignored on
/// platforms where a directory cannot be opened as a file (Windows) — `File::open`
/// on a directory simply fails there and the `if let Ok` skips it.
fn fsync_dir(path: &Path) {
if let Ok(f) = std::fs::File::open(path) {
let _ = f.sync_all();
}
}
/// Persist the current set of escalated approval kinds atomically (temp +
/// fsync + rename) so a crash never truncates it.
pub fn save_escalations(session_path: &Path, kinds: &std::collections::HashSet<String>) {
let p = escalations_path(session_path);
if let Some(parent) = p.parent() {
let _ = std::fs::create_dir_all(parent);
}
let tmp = crate::fsutil::unique_tmp(&p);
let Ok(mut f) = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(&tmp)
else {
return;
};
let list: Vec<&String> = kinds.iter().collect();
let _ = writeln!(f, "{}", serde_json::to_string(&list).unwrap_or_default());
let _ = f.flush();
let _ = f.sync_all();
drop(f); // release before rename (Windows)
let _ = std::fs::rename(&tmp, &p);
if let Some(parent) = p.parent() {