ultron-compaction 1.0.2

Context compaction and branch summarization of packages/coding-agent/src/core/compaction: token estimation, cut points, summary requests
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! Context compaction and branch summarization, ported from
//! `packages/coding-agent/src/core/compaction/` (`compaction.ts`, `branch-summarization.ts`, `utils.ts`).
//!
//! Session entries and agent messages are JSON values in the session file format (see `session-file`), so custom
//! roles (`bashExecution`, `custom`, `branchSummary`, `compactionSummary`) and unknown fields pass through untouched.
//! Summaries are produced by a caller-supplied async model call that receives a [`SummaryRequest`] built from
//! `ai` types and returns the provider's [`AssistantMessage`]; this crate does no I/O.

mod branch;
mod bug_summary;

use std::collections::HashSet;

use ai::transcript::{ContextUsageEstimate, normalize_context};
use ai::{
    AssistantContent, AssistantMessage, Context, Message, Model, StopReason, TextContent, TranscriptContext, Usage,
    UserContent, UserMessage, UserMessageContent,
};
use indexmap::IndexSet;
use jsrt::utf16;
use protocol::custom_types;
use serde_json::Value;
use session_file::{Leaf, ProjectedEntry, SessionProjection, build_session_projection, current_system_message, js};
use session_journal::context::convert_to_llm;

pub use branch::{
    BranchPreparation, BranchSummary, BranchSummaryError, BranchSummaryOptions, collect_entries_for_branch_summary,
    generate_branch_summary, prepare_branch_entries,
};
pub use bug_summary::{bug_summary_request, bug_summary_text};

// ============================================================================
// Shared utilities (utils.ts)
// ============================================================================

fn str_of<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
    value.get(key).and_then(Value::as_str)
}

fn role(message: &Value) -> Option<&str> {
    str_of(message, "role")
}

fn entry_type(entry: &Value) -> Option<&str> {
    str_of(entry, "type")
}

/// `contentText(content, separator)`: a string as is, else the text blocks joined.
fn content_text(content: Option<&Value>, separator: &str) -> String {
    match content {
        Some(Value::String(text)) => text.clone(),
        Some(Value::Array(blocks)) => blocks
            .iter()
            .filter(|b| str_of(b, "type") == Some("text"))
            .map(|b| js::join_string(b.get("text")))
            .collect::<Vec<_>>()
            .join(separator),
        _ => String::new(),
    }
}

/// Files touched by `read`, `write` and `edit` tool calls, in first-seen order.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FileOperations {
    pub read: IndexSet<String>,
    pub written: IndexSet<String>,
    pub edited: IndexSet<String>,
}

/// `extractFileOpsFromMessage`: records the `path` argument of assistant `read`/`write`/`edit` tool calls.
pub fn extract_file_ops_from_message(message: &Value, ops: &mut FileOperations) {
    if role(message) != Some("assistant") {
        return;
    }
    let Some(blocks) = message.get("content").and_then(Value::as_array) else {
        return;
    };
    for block in blocks {
        if str_of(block, "type") != Some("toolCall") || block.get("name").is_none() {
            continue;
        }
        let Some(path) = block.get("arguments").and_then(|args| str_of(args, "path")) else {
            continue;
        };
        if path.is_empty() {
            continue;
        }
        let set = match str_of(block, "name") {
            Some("read") => &mut ops.read,
            Some("write") => &mut ops.written,
            Some("edit") => &mut ops.edited,
            _ => continue,
        };
        set.insert(path.to_string());
    }
}

/// `computeFileLists`: `(read-only files, modified files)`, each sorted.
pub fn compute_file_lists(ops: &FileOperations) -> (Vec<String>, Vec<String>) {
    let modified: IndexSet<&String> = ops.edited.iter().chain(&ops.written).collect();
    let mut read_files: Vec<String> = ops.read.iter().filter(|f| !modified.contains(f)).cloned().collect();
    let mut modified_files: Vec<String> = modified.into_iter().cloned().collect();
    utf16::sort(&mut read_files);
    utf16::sort(&mut modified_files);
    (read_files, modified_files)
}

/// `formatFileOperations`: the `<read-files>`/`<modified-files>` sections appended to a summary.
pub fn format_file_operations(read_files: &[String], modified_files: &[String]) -> String {
    let mut sections = Vec::new();
    if !read_files.is_empty() {
        sections.push(format!("<read-files>\n{}\n</read-files>", read_files.join("\n")));
    }
    if !modified_files.is_empty() {
        sections.push(format!(
            "<modified-files>\n{}\n</modified-files>",
            modified_files.join("\n")
        ));
    }
    if sections.is_empty() {
        return String::new();
    }
    format!("\n\n{}", sections.join("\n\n"))
}

const TOOL_RESULT_MAX_CHARS: usize = 2000;

fn truncate_for_summary(text: &str, max_chars: usize) -> String {
    let len = utf16::len(text);
    if len <= max_chars {
        return text.to_string();
    }
    format!(
        "{}\n\n[... {} more characters truncated]",
        utf16::head(text, max_chars),
        len - max_chars
    )
}

/// `serializeConversation`: LLM messages (see [`convert_to_llm`]) as `[Role]: ...` text, so the summarizer reads the
/// transcript instead of continuing it. Tool results are cut to 2000 characters.
pub fn serialize_conversation(messages: &[Value]) -> String {
    let mut parts = Vec::new();
    for message in messages {
        match role(message) {
            Some("user") => {
                let content = content_text(message.get("content"), "");
                if !content.is_empty() {
                    parts.push(format!("[User]: {content}"));
                }
            }
            Some("assistant") => {
                let blocks = message
                    .get("content")
                    .and_then(Value::as_array)
                    .map_or(&[][..], Vec::as_slice);
                let mut thinking = Vec::new();
                let mut calls = Vec::new();
                for block in blocks {
                    match str_of(block, "type") {
                        Some("thinking") => thinking.push(js::join_string(block.get("thinking"))),
                        Some("toolCall") => {
                            let args = match block.get("arguments") {
                                Some(Value::Object(map)) => jsrt::json::object_entries(map)
                                    .into_iter()
                                    .map(|(k, v)| format!("{k}={}", jsrt::json::stringify(v)))
                                    .collect::<Vec<_>>()
                                    .join(", "),
                                _ => String::new(),
                            };
                            calls.push(format!("{}({args})", js::join_string(block.get("name"))));
                        }
                        _ => {}
                    }
                }
                if !thinking.is_empty() {
                    parts.push(format!("[Assistant thinking]: {}", thinking.join("\n")));
                }
                if blocks.iter().any(|b| str_of(b, "type") == Some("text")) {
                    parts.push(format!("[Assistant]: {}", content_text(message.get("content"), "\n")));
                }
                if !calls.is_empty() {
                    parts.push(format!("[Assistant tool calls]: {}", calls.join("; ")));
                }
            }
            Some("toolResult") => {
                let content = content_text(message.get("content"), "");
                if !content.is_empty() {
                    parts.push(format!(
                        "[Tool result]: {}",
                        truncate_for_summary(&content, TOOL_RESULT_MAX_CHARS)
                    ));
                }
            }
            _ => {}
        }
    }
    parts.join("\n\n")
}

/// [`convert_to_llm`] for a summary's conversation (Rust-only): recalled long-term memory and the active refinements
/// are left out. They came from memory and the ledger; a summary that repeated them would be kept or proposed again
/// as if the session had learned them.
pub fn convert_for_summary(messages: &[Value]) -> Vec<Value> {
    let recalled = |m: &Value| {
        role(m) == Some("custom")
            && matches!(
                m.get("customType").and_then(Value::as_str),
                Some(custom_types::RECALLED_MEMORY | custom_types::REFINEMENTS)
            )
    };
    if !messages.iter().any(recalled) {
        return convert_to_llm(messages);
    }
    let kept: Vec<Value> = messages.iter().filter(|m| !recalled(m)).cloned().collect();
    convert_to_llm(&kept)
}

const SUMMARIZATION_SYSTEM_PROMPT: &str = "You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.

Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CompactionSettings {
    pub enabled: bool,
    pub reserve_tokens: u64,
    pub keep_recent_tokens: u64,
}

impl Default for CompactionSettings {
    fn default() -> Self {
        CompactionSettings {
            enabled: true,
            reserve_tokens: 16384,
            keep_recent_tokens: 20000,
        }
    }
}

fn number(value: &Value, key: &str) -> u64 {
    value.get(key).and_then(Value::as_f64).map_or(0, |n| n as u64)
}

/// `calculateContextTokens`: `totalTokens`, else the sum of input, output and cache tokens.
pub fn calculate_context_tokens(usage: &Value) -> u64 {
    match number(usage, "totalTokens") {
        0 => {
            number(usage, "input") + number(usage, "output") + number(usage, "cacheRead") + number(usage, "cacheWrite")
        }
        total => total,
    }
}

/// Usage of an assistant message that completed and reported a non-zero count.
fn assistant_usage(message: &Value) -> Option<&Value> {
    if role(message) != Some("assistant") || matches!(str_of(message, "stopReason"), Some("aborted" | "error")) {
        return None;
    }
    message
        .get("usage")
        .filter(|u| jsrt::value::truthy(Some(u)) && calculate_context_tokens(u) > 0)
}

const ESTIMATED_IMAGE_CHARS: usize = 4800;

fn text_and_image_chars(content: Option<&Value>) -> usize {
    match content {
        Some(Value::String(text)) => utf16::len(text),
        Some(Value::Array(blocks)) => blocks
            .iter()
            .map(|block| match str_of(block, "type") {
                Some("text") => str_of(block, "text").map_or(0, utf16::len),
                Some("image") => ESTIMATED_IMAGE_CHARS,
                _ => 0,
            })
            .sum(),
        _ => 0,
    }
}

/// `estimateTokens`: characters / 4, rounded up (an overestimate); images count 4800 characters.
pub fn estimate_tokens(message: &Value) -> u64 {
    let len = |key: &str| str_of(message, key).map_or(0, utf16::len);
    let chars = match role(message) {
        Some("system") => {
            let sections: usize = match message.get("sections") {
                Some(Value::Object(map)) => map.values().filter_map(Value::as_str).map(utf16::len).sum(),
                _ => 0,
            };
            let tools = message
                .get("toolsAdded")
                .filter(|t| jsrt::value::truthy(Some(t)))
                .map_or(0, |t| utf16::len(&jsrt::json::stringify(t)));
            text_and_image_chars(message.get("content")) + sections + tools
        }
        Some("user" | "custom" | "toolResult") => text_and_image_chars(message.get("content")),
        Some("assistant") => message
            .get("content")
            .and_then(Value::as_array)
            .map_or(&[][..], Vec::as_slice)
            .iter()
            .map(|block| match str_of(block, "type") {
                Some("text") => str_of(block, "text").map_or(0, utf16::len),
                Some("thinking") => str_of(block, "thinking").map_or(0, utf16::len),
                Some("toolCall") => {
                    str_of(block, "name").map_or(0, utf16::len)
                        + block
                            .get("arguments")
                            .map_or(0, |a| utf16::len(&jsrt::json::stringify(a)))
                }
                _ => 0,
            })
            .sum(),
        Some("bashExecution") => len("command") + len("output"),
        Some("branchSummary" | "compactionSummary") => len("summary"),
        _ => 0,
    };
    chars.div_ceil(4) as u64
}

/// `estimateContextTokens`: the newest valid assistant usage plus estimates for the messages after it.
pub fn estimate_context_tokens(messages: &[Value]) -> ContextUsageEstimate {
    let last = messages
        .iter()
        .enumerate()
        .rev()
        .find_map(|(i, m)| assistant_usage(m).map(|u| (calculate_context_tokens(u), i)));
    match last {
        None => {
            let tokens = messages.iter().map(estimate_tokens).sum();
            ContextUsageEstimate {
                tokens,
                usage_tokens: 0,
                trailing_tokens: tokens,
                last_usage_index: None,
            }
        }
        Some((usage_tokens, index)) => {
            let trailing_tokens: u64 = messages[index + 1..].iter().map(estimate_tokens).sum();
            ContextUsageEstimate {
                tokens: usage_tokens + trailing_tokens,
                usage_tokens,
                trailing_tokens,
                last_usage_index: Some(index),
            }
        }
    }
}

/// `estimateProjectedContextTokens`: like [`estimate_context_tokens`], but usage recorded before the latest context
/// edit or compaction on the branch is stale, so then every projected message is estimated instead.
pub fn estimate_projected_context_tokens(
    projection: &SessionProjection<'_>,
    branch_entries: &[Value],
) -> ContextUsageEstimate {
    let estimate = estimate_context_tokens(&projection.messages);
    if let Some(last_usage) = estimate.last_usage_index {
        let mut start = 0;
        let mut usage_entry_id = None;
        for entry in &projection.entries {
            let next = start + entry.messages.len();
            if last_usage < next {
                usage_entry_id = entry.source.get("id").filter(|id| jsrt::value::truthy(Some(id)));
                break;
            }
            start = next;
        }
        let usage_entry_index =
            usage_entry_id.and_then(|id| branch_entries.iter().position(|e| e.get("id") == Some(id)));
        let invalidating = branch_entries
            .iter()
            .rposition(|e| matches!(entry_type(e), Some("context_edit" | "compaction")));
        if usage_entry_index.is_some_and(|u| invalidating.is_none_or(|i| u > i)) {
            return estimate;
        }
    }
    let system = current_system_message(&projection.messages).map_or(0, |m| estimate_tokens(&m));
    let tokens = system
        + projection
            .messages
            .iter()
            .filter(|m| role(m) != Some("system"))
            .map(estimate_tokens)
            .sum::<u64>();
    ContextUsageEstimate {
        tokens,
        usage_tokens: 0,
        trailing_tokens: tokens,
        last_usage_index: None,
    }
}

/// `shouldCompact`: whether the context leaves less than `reserve_tokens` of the window.
pub fn should_compact(context_tokens: u64, context_window: u64, settings: &CompactionSettings) -> bool {
    settings.enabled && i128::from(context_tokens) > i128::from(context_window) - i128::from(settings.reserve_tokens)
}

fn is_cut_point_message(message: &Value) -> bool {
    matches!(
        role(message),
        Some("user" | "assistant" | "bashExecution" | "custom" | "branchSummary" | "compactionSummary")
    )
}

fn is_turn_start_message(message: &Value) -> bool {
    matches!(
        role(message),
        Some("user" | "bashExecution" | "custom" | "branchSummary" | "compactionSummary")
    )
}

fn is_turn_start_entry(entry: &Value) -> bool {
    entry_type(entry) != Some("compaction") && session_file::entry_messages(entry).iter().any(is_turn_start_message)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CutPoint {
    /// Index of the first entry to keep.
    pub first_kept_entry_index: usize,
    /// The entry that starts the turn being split, when the cut is mid-turn.
    pub turn_start_index: Option<usize>,
    pub is_split_turn: bool,
}

/// `findTurnStartIndex`: the nearest entry at or before `entry_index` (not before `start_index`) that starts a turn.
pub fn find_turn_start_index(entries: &[Value], entry_index: usize, start_index: usize) -> Option<usize> {
    (start_index..=entry_index)
        .rev()
        .find(|&i| is_turn_start_entry(&entries[i]))
}

/// Walks back from `end` summing `tokens(i)`; once `keep` is reached, cuts at the nearest cut point at or after it.
fn budget_cut(
    cut_points: &[usize],
    start: usize,
    end: usize,
    keep: u64,
    tokens: impl Fn(usize) -> u64,
) -> (usize, bool) {
    let mut accumulated = 0;
    for i in (start..end).rev() {
        let message_tokens = tokens(i);
        if message_tokens == 0 {
            continue;
        }
        accumulated += message_tokens;
        if accumulated >= keep {
            let cut = cut_points
                .iter()
                .copied()
                .find(|&c| c >= i)
                .unwrap_or(cut_points[cut_points.len() - 1]);
            return (cut, true);
        }
    }
    (cut_points[0], false)
}

/// `findCutPoint`: the first entry to keep so that roughly `keep_recent_tokens` of recent context survive. Cuts only
/// at user-like or assistant messages, never at tool results.
pub fn find_cut_point(entries: &[Value], start_index: usize, end_index: usize, keep_recent_tokens: u64) -> CutPoint {
    let cut_points: Vec<usize> = (start_index..end_index)
        .filter(|&i| {
            entry_type(&entries[i]) != Some("compaction")
                && session_file::entry_messages(&entries[i])
                    .iter()
                    .any(is_cut_point_message)
        })
        .collect();
    if cut_points.is_empty() {
        return CutPoint {
            first_kept_entry_index: start_index,
            turn_start_index: None,
            is_split_turn: false,
        };
    }
    let (mut cut, _) = budget_cut(&cut_points, start_index, end_index, keep_recent_tokens, |i| {
        session_file::entry_messages(&entries[i])
            .iter()
            .map(estimate_tokens)
            .sum()
    });
    while cut > start_index {
        let previous = &entries[cut - 1];
        if entry_type(previous) == Some("compaction") || !session_file::entry_messages(previous).is_empty() {
            break;
        }
        cut -= 1;
    }
    let starts_turn = is_turn_start_entry(&entries[cut]);
    let turn_start_index = if starts_turn {
        None
    } else {
        find_turn_start_index(entries, cut, start_index)
    };
    CutPoint {
        first_kept_entry_index: cut,
        turn_start_index,
        is_split_turn: !starts_turn && turn_start_index.is_some(),
    }
}

fn source_type<'a>(entry: &ProjectedEntry<'a>) -> Option<&'a str> {
    entry_type(entry.source)
}

fn is_projected_turn_start(entry: &ProjectedEntry<'_>) -> bool {
    source_type(entry) != Some("compaction") && entry.messages.iter().any(is_turn_start_message)
}

/// `findProjectedCutPoint`: [`find_cut_point`] over context-edited entries.
fn find_projected_cut_point(entries: &[ProjectedEntry<'_>], start: usize, end: usize, keep: u64) -> CutPoint {
    let cut_points: Vec<usize> = (start..end)
        .filter(|&i| {
            source_type(&entries[i]) != Some("compaction") && entries[i].messages.iter().any(is_cut_point_message)
        })
        .collect();
    if cut_points.is_empty() {
        return CutPoint {
            first_kept_entry_index: start,
            turn_start_index: None,
            is_split_turn: false,
        };
    }
    let (mut cut, exceeded) = budget_cut(&cut_points, start, end, keep, |i| {
        entries[i].messages.iter().map(estimate_tokens).sum()
    });

    // A recovery attempt and its omission edits are context-invisible after the last visible input. Advance only for
    // a closed suffix containing an omitted assistant attempt; arbitrary metadata must not move the cut past input.
    let suffix = entries.get(cut + 1..end).unwrap_or_default();
    let visible = |e: &ProjectedEntry<'_>| {
        source_type(e) != Some("context_edit") && !session_file::entry_messages(e.source).is_empty()
    };
    let omitted = |e: &ProjectedEntry<'_>| visible(e) && e.messages.is_empty();
    let omitted_ids: HashSet<String> = suffix
        .iter()
        .filter(|e| omitted(e))
        .map(|e| id_key(e.source.get("id")))
        .collect();
    let external_replacement = suffix.iter().any(|e| {
        source_type(e) == Some("context_edit")
            && e.source.get("replacement") != Some(&Value::Null)
            && !omitted_ids.contains(&id_key(e.source.get("targetId")))
    });
    let recovery_suffix = exceeded
        && !external_replacement
        && suffix.iter().any(|e| {
            source_type(e) == Some("message")
                && e.source.get("message").and_then(role) == Some("assistant")
                && omitted(e)
        })
        && suffix
            .iter()
            .all(|e| source_type(e) != Some("compaction") && (!visible(e) || omitted(e)));
    if recovery_suffix {
        cut += 1;
    }

    while cut > start {
        let previous = &entries[cut - 1];
        if source_type(previous) == Some("compaction") || !previous.messages.is_empty() {
            break;
        }
        cut -= 1;
    }
    let starts_turn = is_projected_turn_start(&entries[cut]);
    let turn_start_index = if starts_turn {
        None
    } else {
        (start..=cut).rev().find(|&i| is_projected_turn_start(&entries[i]))
    };
    CutPoint {
        first_kept_entry_index: cut,
        turn_start_index,
        is_split_turn: !starts_turn && turn_start_index.is_some(),
    }
}

/// JavaScript `Set`/`Map` key for an id: `undefined` is distinct from every string.
fn id_key(value: Option<&Value>) -> String {
    value.map_or_else(|| "undefined".to_string(), jsrt::json::stringify)
}

/// `CompactionPreparation`: what [`compact`] summarizes and keeps.
#[derive(Clone, Debug, PartialEq)]
pub struct CompactionPreparation {
    pub first_kept_entry_id: String,
    /// Messages summarized and dropped.
    pub messages_to_summarize: Vec<Value>,
    /// The start of a split turn, summarized separately.
    pub turn_prefix_messages: Vec<Value>,
    pub is_split_turn: bool,
    pub tokens_before: u64,
    /// The previous compaction's summary, for an iterative update.
    pub previous_summary: Option<String>,
    pub file_ops: FileOperations,
    pub settings: CompactionSettings,
}

/// Messages an entry contributes to a summary: none for compactions, and never system messages (prompt state).
fn summary_messages(entries: &[ProjectedEntry<'_>]) -> Vec<Value> {
    entries
        .iter()
        .filter(|e| source_type(e) != Some("compaction"))
        .flat_map(|e| e.messages.iter().filter(|m| role(m) != Some("system")).cloned())
        .collect()
}

/// Adds the read/modified lists a pi-generated (not extension) summary entry recorded in `details`.
fn add_recorded_files(entry: &Value, ops: &mut FileOperations) {
    if jsrt::value::truthy(entry.get("fromHook")) {
        return;
    }
    let Some(details) = entry.get("details").filter(|d| jsrt::value::truthy(Some(d))) else {
        return;
    };
    let files = |key: &str| {
        details
            .get(key)
            .and_then(Value::as_array)
            .map_or(&[][..], Vec::as_slice)
            .iter()
            .filter_map(Value::as_str)
            .map(str::to_string)
    };
    ops.read.extend(files("readFiles"));
    ops.edited.extend(files("modifiedFiles"));
}

/// `prepareCompaction`: picks the cut on the session path and collects what to summarize. `None` when the path
/// ends in a compaction or nothing would be summarized.
pub fn prepare_compaction(path_entries: &[Value], settings: CompactionSettings) -> Option<CompactionPreparation> {
    if path_entries.last().is_some_and(|e| entry_type(e) == Some("compaction")) {
        return None;
    }
    let projection = build_session_projection(path_entries, Leaf::Last);
    let entries = &projection.entries;
    // The newest compaction is projected first; older ones in its kept range contribute nothing.
    let prev_compaction = entries
        .iter()
        .position(|e| source_type(e) == Some("compaction") && !e.messages.is_empty());
    let previous_summary = prev_compaction
        .and_then(|i| str_of(entries[i].source, "summary"))
        .map(str::to_string);
    let boundary_start = prev_compaction.map_or(0, |i| i + 1);
    let tokens_before = estimate_projected_context_tokens(&projection, path_entries).tokens;
    let cut = find_projected_cut_point(entries, boundary_start, entries.len(), settings.keep_recent_tokens);

    let first_kept_entry_id = entries
        .get(cut.first_kept_entry_index)
        .and_then(|e| str_of(e.source, "id"))
        .filter(|id| !id.is_empty())?
        .to_string();
    let history_end = match cut.turn_start_index {
        Some(turn_start) if cut.is_split_turn => turn_start,
        _ => cut.first_kept_entry_index,
    };
    let messages_to_summarize = summary_messages(entries.get(boundary_start..history_end).unwrap_or_default());
    let turn_prefix_messages = match cut.turn_start_index {
        Some(turn_start) if cut.is_split_turn => summary_messages(&entries[turn_start..cut.first_kept_entry_index]),
        _ => Vec::new(),
    };
    if messages_to_summarize.is_empty() && turn_prefix_messages.is_empty() {
        return None;
    }

    let mut file_ops = FileOperations::default();
    if let Some(i) = prev_compaction {
        add_recorded_files(entries[i].source, &mut file_ops);
    }
    for message in messages_to_summarize.iter().chain(&turn_prefix_messages) {
        extract_file_ops_from_message(message, &mut file_ops);
    }
    Some(CompactionPreparation {
        first_kept_entry_id,
        messages_to_summarize,
        turn_prefix_messages,
        is_split_turn: cut.is_split_turn,
        tokens_before,
        previous_summary,
        file_ops,
        settings,
    })
}

const SUMMARIZATION_PROMPT: &str = "The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.

Use this EXACT format:

## Goal
[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]

## Constraints & Preferences
- [Any constraints, preferences, or requirements mentioned by user]
- [Or \"(none)\" if none were mentioned]

## Progress
### Done
- [x] [Completed tasks/changes]

### In Progress
- [ ] [Current work]

### Blocked
- [Issues preventing progress, if any]

## Key Decisions
- **[Decision]**: [Brief rationale]

## Next Steps
1. [Ordered list of what should happen next]

## Critical Context
- [Any data, examples, or references needed to continue]
- [Or \"(none)\" if not applicable]

Keep each section concise. Preserve exact file paths, function names, and error messages.";

const UPDATE_SUMMARIZATION_PROMPT: &str = "The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.

Update the existing structured summary with new information. RULES:
- PRESERVE all existing information from the previous summary
- ADD new progress, decisions, and context from the new messages
- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed
- UPDATE \"Next Steps\" based on what was accomplished
- PRESERVE exact file paths, function names, and error messages
- If something is no longer relevant, you may remove it

Use this EXACT format:

## Goal
[Preserve existing goals, add new ones if the task expanded]

## Constraints & Preferences
- [Preserve existing, add new ones discovered]

## Progress
### Done
- [x] [Include previously done items AND newly completed items]

### In Progress
- [ ] [Current work - update based on progress]

### Blocked
- [Current blockers - remove if resolved]

## Key Decisions
- **[Decision]**: [Brief rationale] (preserve all previous, add new)

## Next Steps
1. [Update based on current state]

## Critical Context
- [Preserve important context, add new if needed]

Keep each section concise. Preserve exact file paths, function names, and error messages.";

const TURN_PREFIX_SUMMARIZATION_PROMPT: &str = "The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.

Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be placed before the later messages so the conversation can continue with the necessary context.

## Original Request
[What did the user ask for?]

## Progress So Far
- [Key decisions and work completed in these messages]

## Context Needed to Continue
- [Information from these messages needed to understand the later work]

Only summarize information explicitly present above. Do not infer or recreate later messages.";

/// One summarization call. The caller adds its credentials, headers and abort signal, always sends it with
/// `cacheRetention: "none"` (one-off summaries must not write the cache), and mints a fresh routing session id when
/// `session_id` is `None`.
#[derive(Clone, Debug, PartialEq)]
pub struct SummaryRequest {
    pub context: TranscriptContext,
    pub max_tokens: u64,
    /// The thinking level, for reasoning models when one other than `off` was requested.
    pub reasoning: Option<String>,
    pub session_id: Option<String>,
}

/// The summarization transcript: the summarizer system prompt and one user message holding `prompt`.
pub(crate) fn summary_context(prompt: String, now_ms: i64) -> TranscriptContext {
    normalize_context(&Context {
        system_prompt: Some(SUMMARIZATION_SYSTEM_PROMPT.to_string()),
        messages: vec![Message::User(UserMessage {
            content: UserMessageContent::Blocks(vec![UserContent::Text(TextContent {
                text: prompt,
                text_signature: None,
            })]),
            timestamp: now_ms,
        })],
        tools: None,
    })
}

/// `min(floor(fraction * reserve), model.maxTokens || Infinity)`.
fn summary_max_tokens(fraction: f64, reserve_tokens: u64, model: &Model) -> u64 {
    let budget = (fraction * reserve_tokens as f64).floor() as u64;
    if model.max_tokens > 0 {
        budget.min(model.max_tokens)
    } else {
        budget
    }
}

/// `getSummarizationFailure`: why a response must not become a checkpoint (an error, or a length stop that left
/// the summary incomplete).
pub(crate) fn summarization_failure(response: &AssistantMessage, label: &str) -> Option<String> {
    match response.stop_reason {
        StopReason::Error => Some(format!(
            "{label} failed: {}",
            response
                .error_message
                .as_deref()
                .filter(|m| !m.is_empty())
                .unwrap_or("Unknown error")
        )),
        StopReason::Length => Some(format!(
            "{label} failed: generation hit the token cap and the summary is incomplete"
        )),
        _ => None,
    }
}

fn has_tool_call(response: &AssistantMessage) -> bool {
    response
        .content
        .iter()
        .any(|b| matches!(b, AssistantContent::ToolCall(_)))
}

/// `contentText` of a response: its text blocks joined by newlines.
fn response_text(response: &AssistantMessage) -> String {
    response
        .content
        .iter()
        .filter_map(|b| match b {
            AssistantContent::Text(t) => Some(t.text.as_str()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Settings of one compaction run (`compact`'s model, focus, thinking level and routing session).
#[derive(Clone, Copy, Debug)]
pub struct CompactOptions<'a> {
    pub model: &'a Model,
    /// Extra focus appended to the summary prompt.
    pub custom_instructions: Option<&'a str>,
    pub thinking_level: Option<&'a str>,
    /// Routing session id forwarded to the provider (without enabling prompt caching).
    pub session_id: Option<&'a str>,
    /// `Date.now()` for the request's user message.
    pub now_ms: i64,
}

impl CompactOptions<'_> {
    fn request(&self, prompt: String, max_tokens: u64) -> SummaryRequest {
        let reasoning = self
            .thinking_level
            .filter(|level| self.model.reasoning && !level.is_empty() && *level != "off")
            .map(str::to_string);
        SummaryRequest {
            context: summary_context(prompt, self.now_ms),
            max_tokens,
            reasoning,
            session_id: self.session_id.map(str::to_string),
        }
    }
}

/// `generateSummaryWithUsage`: the history summary request (an update when `previous_summary` is set).
pub fn history_summary_request(
    messages: &[Value],
    reserve_tokens: u64,
    previous_summary: Option<&str>,
    options: &CompactOptions<'_>,
) -> SummaryRequest {
    let previous = previous_summary.filter(|s| !s.is_empty());
    let mut instructions = if previous.is_some() {
        UPDATE_SUMMARIZATION_PROMPT
    } else {
        SUMMARIZATION_PROMPT
    }
    .to_string();
    if let Some(focus) = options.custom_instructions.filter(|s| !s.is_empty()) {
        instructions = format!("{instructions}\n\nAdditional focus: {focus}");
    }
    let conversation = serialize_conversation(&convert_for_summary(messages));
    let mut prompt = format!("<conversation>\n{conversation}\n</conversation>\n\n");
    if let Some(previous) = previous {
        prompt.push_str(&format!("<previous-summary>\n{previous}\n</previous-summary>\n\n"));
    }
    prompt.push_str(&instructions);
    options.request(prompt, summary_max_tokens(0.8, reserve_tokens, options.model))
}

/// `generateTurnPrefixSummary`'s request: a checkpoint of the start of a split turn, with half the budget.
pub fn turn_prefix_request(messages: &[Value], reserve_tokens: u64, options: &CompactOptions<'_>) -> SummaryRequest {
    let conversation = serialize_conversation(&convert_for_summary(messages));
    let prompt = format!("# Conversation\n{conversation}\n\n# Instructions\n{TURN_PREFIX_SUMMARIZATION_PROMPT}");
    turn_prefix_request_of(prompt, reserve_tokens, options)
}

/// A turn prefix summary request asking `prompt`: the summary request's shape (system prompt, reasoning, session)
/// with half the reserve as its budget.
pub fn turn_prefix_request_of(prompt: String, reserve_tokens: u64, options: &CompactOptions<'_>) -> SummaryRequest {
    options.request(prompt, summary_max_tokens(0.5, reserve_tokens, options.model))
}

/// The history summary a split turn uses when nothing before the turn was summarized.
pub const NO_PRIOR_HISTORY: &str = "No prior history.";

/// The summary of a split turn: the history's summary, then the turn prefix's.
pub fn split_turn_summary(history: &str, prefix: &str) -> String {
    format!("{history}\n\n---\n\n**Turn Context (split turn):**\n\n{prefix}")
}

/// `CompactionResult`; `details` holds the file lists.
#[derive(Clone, Debug, PartialEq)]
pub struct CompactionResult {
    pub summary: String,
    pub first_kept_entry_id: String,
    pub tokens_before: u64,
    pub usage: Usage,
    pub read_files: Vec<String>,
    pub modified_files: Vec<String>,
}

impl CompactionResult {
    /// The compaction entry it makes (Pi's `CompactionEntry` fields, written by Ultron itself: `fromHook` false),
    /// keeping `retained_tail` after the summary and recording the summary's `usage`.
    pub fn entry(&self, retained_tail: Vec<Value>, usage: Value) -> serde_json::Map<String, Value> {
        let mut entry = serde_json::Map::new();
        entry.insert("type".into(), "compaction".into());
        entry.insert("summary".into(), self.summary.clone().into());
        entry.insert("retainedTail".into(), Value::Array(retained_tail));
        entry.insert("tokensBefore".into(), self.tokens_before.into());
        entry.insert(
            "details".into(),
            serde_json::json!({"readFiles": self.read_files, "modifiedFiles": self.modified_files}),
        );
        entry.insert("usage".into(), usage);
        entry.insert("fromHook".into(), false.into());
        entry
    }
}

fn combine_usage(first: &Usage, second: &Usage) -> Usage {
    let optional =
        |a: Option<u64>, b: Option<u64>| (a.is_some() || b.is_some()).then(|| a.unwrap_or(0) + b.unwrap_or(0));
    Usage {
        input: first.input + second.input,
        output: first.output + second.output,
        cache_read: first.cache_read + second.cache_read,
        cache_write: first.cache_write + second.cache_write,
        cache_write_1h: optional(first.cache_write_1h, second.cache_write_1h),
        reasoning: optional(first.reasoning, second.reasoning),
        total_tokens: first.total_tokens + second.total_tokens,
        cost: ai::Cost {
            input: first.cost.input + second.cost.input,
            output: first.cost.output + second.cost.output,
            cache_read: first.cost.cache_read + second.cost.cache_read,
            cache_write: first.cost.cache_write + second.cost.cache_write,
            total: first.cost.total + second.cost.total,
        },
    }
}

/// Why a request gave no summary: the error text is upstream's thrown message, and `too_long` says the model refused
/// the request as longer than its window (Rust-only).
struct SummaryFailure {
    message: String,
    too_long: bool,
}

/// Sends one request and checks the response.
async fn summarize(
    request: SummaryRequest,
    label: &str,
    call: &mut impl AsyncFnMut(SummaryRequest) -> AssistantMessage,
) -> Result<(String, Usage), SummaryFailure> {
    let response = call(request).await;
    if let Some(message) = summarization_failure(&response, label) {
        return Err(SummaryFailure {
            message,
            too_long: ai::overflow::is_context_overflow(&response),
        });
    }
    if has_tool_call(&response) {
        return Err(SummaryFailure {
            message: format!("{label} attempted to call a tool"),
            too_long: false,
        });
    }
    Ok((response_text(&response), response.usage))
}

/// Where to cut two or more `messages` in half by estimated size, with a message on each side.
fn halfway(messages: &[Value]) -> usize {
    let total: u64 = messages.iter().map(estimate_tokens).sum();
    let mut seen = 0;
    let half = messages.iter().position(|message| {
        seen += estimate_tokens(message);
        seen * 2 >= total
    });
    half.map_or(1, |index| index + 1).clamp(1, messages.len() - 1)
}

/// Summarizes `parts` in order, each updating the summary of what came before it (first `previous`). Rust-only: a
/// part the model refuses as too long is cut in half and each half is tried in its place. The summary goes to the
/// lane's current model, which after a model switch may count a history as more tokens than its window holds, and
/// no estimate made here predicts a provider's count. One message that is too long alone fails with the
/// provider's error.
async fn summarize_parts(
    parts: Vec<&[Value]>,
    mut previous: Option<String>,
    label: &str,
    reserve_tokens: u64,
    options: &CompactOptions<'_>,
    call: &mut impl AsyncFnMut(SummaryRequest) -> AssistantMessage,
) -> Result<(String, Usage), String> {
    let mut pending: Vec<&[Value]> = parts.into_iter().rev().collect();
    let mut usage: Option<Usage> = None;
    while let Some(part) = pending.pop() {
        let request = history_summary_request(part, reserve_tokens, previous.as_deref(), options);
        match summarize(request, label, call).await {
            Ok((text, used)) => {
                usage = Some(usage.map_or(used.clone(), |sum| combine_usage(&sum, &used)));
                previous = Some(text);
            }
            Err(failure) if failure.too_long && part.len() > 1 => {
                let (first, rest) = part.split_at(halfway(part));
                pending.extend([rest, first]);
            }
            Err(failure) => return Err(failure.message),
        }
    }
    Ok((previous.unwrap_or_default(), usage.unwrap_or_default()))
}

/// `compact`: summarizes a prepared compaction through `call` (history, then the split turn's prefix when cutting
/// mid-turn) and appends the file lists.
pub async fn compact(
    preparation: &CompactionPreparation,
    options: &CompactOptions<'_>,
    mut call: impl AsyncFnMut(SummaryRequest) -> AssistantMessage,
) -> Result<CompactionResult, String> {
    let prep = preparation;
    let reserve = prep.settings.reserve_tokens;
    let split = prep.is_split_turn && !prep.turn_prefix_messages.is_empty();
    let mut previous = prep.previous_summary.clone();
    let mut usage = None;
    if !split || !prep.messages_to_summarize.is_empty() {
        let history = vec![&prep.messages_to_summarize[..]];
        let (text, used) = summarize_parts(history, previous, "Summarization", reserve, options, &mut call).await?;
        (previous, usage) = (Some(text), Some(used));
    }
    let plus = |used: Usage| usage.as_ref().map_or(used.clone(), |sum| combine_usage(sum, &used));
    let (mut summary, usage) = if split {
        const LABEL: &str = "Turn prefix summarization";
        let prefix = &prep.turn_prefix_messages[..];
        let request = turn_prefix_request(prefix, reserve, options);
        match summarize(request, LABEL, &mut call).await {
            Ok((prefix_text, used)) => {
                let history = previous.unwrap_or_else(|| NO_PRIOR_HISTORY.to_string());
                (split_turn_summary(&history, &prefix_text), plus(used))
            }
            // A prefix too long for the model is summarized as more history, in halves.
            Err(failure) if failure.too_long && prefix.len() > 1 => {
                let (first, rest) = prefix.split_at(halfway(prefix));
                let (text, used) =
                    summarize_parts(vec![first, rest], previous, LABEL, reserve, options, &mut call).await?;
                (text, plus(used))
            }
            Err(failure) => return Err(failure.message),
        }
    } else {
        (previous.unwrap_or_default(), usage.unwrap_or_default())
    };
    let (read_files, modified_files) = compute_file_lists(&prep.file_ops);
    summary.push_str(&format_file_operations(&read_files, &modified_files));
    Ok(CompactionResult {
        summary,
        first_kept_entry_id: prep.first_kept_entry_id.clone(),
        tokens_before: prep.tokens_before,
        usage,
        read_files,
        modified_files,
    })
}