ultron-kernel-apis 1.0.0

Host operations behind the thin Python kernel APIs: code skills and the skill catalog, memory, hints, images
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
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
//! `ctx.*` (port of the request side of `ultron/context-control.ts`) and the context-edit semantics it relies on
//! (`applyContextEdits` / `contextEditsOf` of `packages/agent/src/harness/session/context.ts`).
//!
//! The model edits what it sees, never the durable transcript: every change is an entry appended to the calling
//! lane's conversation branch (a `context_edit` custom entry for forget/summarize, its own custom entries for pins
//! and notes), and only that branch sees it. Guard rails: the current user message, a tool call still waiting for
//! its result, and pinned items are never edited; entries before the newest compaction are out of reach. A summary
//! moves tool calls and their results together. Entries appended while a turn runs are not on the branch until the
//! turn's next boundary; this module keeps them as pending so later reads in the same cell already see them.
//!
//! The branch itself lives in the session/harness: [`ContextBranches`] is what this module reads and appends.
//! Entries are the TS `Entry` JSON (`{id, parentId, seq, timestamp, type, ...}`).

use crate::util::{Clock, system_clock};
use crate::{ApiModule, Request};
use serde_json::{Map, Value, json};
use session_journal::context::{
    Applied, CONTEXT_EDIT_CUSTOM_TYPE, CONTEXT_OMITTED_CUSTOM_TYPE, apply_context_edits_marked, content_call_ids,
    context_edits_of,
};
use std::collections::HashSet;
use std::sync::{Arc, Mutex};

pub const COMPACTION_TRIM_ENV: &str = "ULTRON_COMPACTION_TRIM";

pub const CONTEXT_NOTE_CUSTOM_TYPE: &str = "ultron:context-note";
pub const CONTEXT_PIN_CUSTOM_TYPE: &str = "ultron:context-pin";
/// Custom message type of a note in the model's context.
pub const CONTEXT_NOTE_MESSAGE_TYPE: &str = "ultron-note";

/// `CONTEXT_ENTRY_PROJECTORS[CONTEXT_NOTE_CUSTOM_TYPE]`: a note is a custom message at its place in the branch
/// ("Note (ctx.note): ..."); a note without text projects nothing.
pub fn project_note(entry: &Value) -> Vec<Value> {
    match entry["data"].get("text").and_then(Value::as_str) {
        Some(text) if !text.is_empty() => vec![json!({"role": "custom", "customType": CONTEXT_NOTE_MESSAGE_TYPE,
            "content": format!("Note (ctx.note): {text}"), "display": true, "timestamp": entry["timestamp"]})],
        _ => Vec::new(),
    }
}

const HISTORY_DEFAULT: i64 = 20;
const HISTORY_MAX: i64 = 200;
const PREVIEW_CHARS: usize = 160;
const NOTE_MAX_CHARS: usize = 4000;
const SUMMARY_MAX_CHARS: usize = 8000;
const REASON_MAX_CHARS: usize = 500;
const COLLAPSE_HEAD_CHARS: usize = 200;
const COLLAPSE_MAX_TASKS: usize = 8;
const TRIM_HEAD_CHARS: usize = 4096;
const TRIM_TAIL_CHARS: usize = 1024;
const STATE_LIST_MAX: usize = 20;
const KINDS: &[&str] = &["user", "assistant", "tool", "custom", "note", "summary", "compaction"];

/// The conversation branches of the session's lanes, as the harness keeps them.
pub trait ContextBranches: Send + Sync {
    /// The lane's committed branch, oldest first.
    fn entries(&self, lane: &str) -> Result<Vec<Value>, String>;
    /// Appends a custom entry (at once, or at the running turn's next boundary); returns its id.
    fn append_custom(&self, lane: &str, custom_type: &str, data: &Value) -> Result<String, String>;
    /// Id of the branch's newest committed entry.
    fn tip_id(&self, lane: &str) -> Result<Option<String>, String>;
}

/// Readable text of a message, for previews and kept items (`messageText`).
pub fn message_text(message: &Value) -> String {
    match message.get("content") {
        Some(Value::String(text)) => return text.clone(),
        Some(Value::Array(parts)) => {
            let texts: Vec<String> = parts
                .iter()
                .map(|part| {
                    if !part.is_object() {
                        return String::new();
                    }
                    match part["type"].as_str() {
                        Some("text") => part["text"].as_str().unwrap_or_default().to_string(),
                        Some("thinking") => part["thinking"].as_str().unwrap_or_default().to_string(),
                        Some("toolCall") => {
                            let name = match &part["name"] {
                                Value::String(name) => name.clone(),
                                Value::Null if part.get("name").is_none() => "undefined".into(),
                                other => jsrt::json::stringify(other),
                            };
                            let arguments = match part.get("arguments") {
                                Some(value) if !value.is_null() => jsrt::json::stringify(value),
                                _ => "{}".into(),
                            };
                            format!("{name}({})", jsrt::utf16::head(&arguments, 2000))
                        }
                        Some("image") => "[image]".into(),
                        _ => String::new(),
                    }
                })
                .filter(|text| !text.is_empty())
                .collect();
            return texts.join("\n");
        }
        _ => {}
    }
    for key in ["summary", "output"] {
        if let Some(Value::String(text)) = message.get(key) {
            return text.clone();
        }
    }
    String::new()
}

/// `oneLine`: whitespace runs collapsed to one space, trimmed, cut to `max` UTF-16 units with an ellipsis.
fn one_line(text: &str, max: usize) -> String {
    let flat = jsrt::string::flatten(text);
    let flat = flat.as_str();
    if jsrt::utf16::len(flat) > max {
        format!("{}…", jsrt::utf16::head(flat, max - 1))
    } else {
        flat.to_string()
    }
}

fn note_text(entry: &Value) -> String {
    if entry["type"] == "custom"
        && let Some(text) = entry["data"].get("text").and_then(Value::as_str)
    {
        return text.to_string();
    }
    String::new()
}

fn entry_bytes(entry: &Value) -> usize {
    match entry["type"].as_str() {
        Some("message") => {
            let message = &entry["message"];
            match message.get("content") {
                Some(content) if !content.is_null() => jsrt::json::stringify(content).len(),
                _ => jsrt::json::stringify(&Value::String(message_text(message))).len(),
            }
        }
        Some("compaction" | "branch_summary") => entry["summary"].as_str().map_or(0, str::len),
        Some("custom") if entry["customType"] == CONTEXT_NOTE_CUSTOM_TYPE => note_text(entry).len(),
        _ => 0,
    }
}

fn kind_of(entry: &Value) -> Option<&'static str> {
    match entry["type"].as_str()? {
        "message" => Some(match entry["message"]["role"].as_str() {
            Some("user") => "user",
            Some("assistant") => "assistant",
            Some("toolResult") => "tool",
            _ => "custom",
        }),
        "compaction" => Some("compaction"),
        "branch_summary" => Some("summary"),
        "custom" if entry["customType"] == CONTEXT_NOTE_CUSTOM_TYPE => Some("note"),
        _ => None,
    }
}

fn entry_text(entry: &Value) -> String {
    match entry["type"].as_str() {
        Some("message") => message_text(&entry["message"]),
        Some("compaction" | "branch_summary") => entry["summary"].as_str().unwrap_or_default().to_string(),
        _ => note_text(entry),
    }
}

fn tool_call_ids(message: &Value) -> Vec<String> {
    if message["role"] != "assistant" {
        return Vec::new();
    }
    content_call_ids(&message["content"])
}

fn is_uuid(value: &str) -> bool {
    let bytes = value.as_bytes();
    bytes.len() == 36
        && bytes.iter().enumerate().all(|(index, b)| match index {
            8 | 13 | 18 | 23 => *b == b'-',
            _ => b.is_ascii_hexdigit(),
        })
}

/// A finished task as it stands in the root's context after collapse on return.
#[derive(Debug, Clone, PartialEq)]
pub struct TaskLine {
    pub id: String,
    pub definition: String,
    pub key: String,
    pub status: String,
    pub cost: Option<f64>,
}

/// `taskLine`: one line that stands for a finished task.
pub fn task_line(task: &TaskLine) -> String {
    let key = if is_uuid(&task.key) {
        String::new()
    } else {
        format!(" key={}", task.key)
    };
    let cost = match task.cost {
        None => "cost=?".to_string(),
        Some(cost) => format!("cost=${cost:.4}"),
    };
    format!(
        "↳ task {} {}{key} {} {cost} · full result: await agents.result(\"{}\")",
        task.id, task.definition, task.status, task.id
    )
}

/// `collapsedCellText`: the collapsed form of a cell output that returned finished tasks.
pub fn collapsed_cell_text(entry_id: &str, original: &str, tasks: &[TaskLine]) -> String {
    let mut lines = vec![
        format!(
            "[collapsed on return: this cell output was {} bytes; ctx.get(\"{entry_id}\") shows it]",
            original.len()
        ),
        one_line(original, COLLAPSE_HEAD_CHARS),
    ];
    lines.extend(tasks.iter().take(COLLAPSE_MAX_TASKS).map(task_line));
    if tasks.len() > COLLAPSE_MAX_TASKS {
        lines.push(format!("↳ +{} more finished tasks", tasks.len() - COLLAPSE_MAX_TASKS));
    }
    lines.join("\n")
}

/// `trimmedResultText`: head and tail of a tool result trimmed before compaction (UTF-16 offsets).
pub fn trimmed_result_text(entry_id: &str, original: &str) -> String {
    let units = jsrt::utf16::len(original);
    let cut = units as i64 - TRIM_HEAD_CHARS as i64 - TRIM_TAIL_CHARS as i64;
    let head = jsrt::utf16::head(original, TRIM_HEAD_CHARS);
    let tail_start = jsrt::utf16::head(original, units.saturating_sub(TRIM_TAIL_CHARS)).len();
    format!(
        "{head}\n[... {cut} characters trimmed before compaction; ctx.get(\"{entry_id}\") shows them ...]\n{}",
        &original[tail_start..]
    )
}

#[derive(Debug, Clone)]
struct EditInfo {
    replacement: Option<Value>,
    source: String,
    reason: Option<String>,
}

/// A consistent read of one lane's branch plus this module's entries still pending behind a running turn.
struct BranchView {
    path: Vec<Value>,
    compaction_index: Option<usize>,
    /// Where the window (the entries after the last compaction) starts in `path`.
    window_start: usize,
    applied: Vec<Applied>,
    /// Edit per target, in first-edit order (a later edit of the same target replaces it in place).
    edits: Vec<(String, EditInfo)>,
    /// Pinned ids, in pin order.
    pins: Vec<String>,
    protected: HashSet<String>,
}

impl BranchView {
    fn window(&self) -> &[Value] {
        &self.path[self.window_start..]
    }
    fn by_id(&self, id: &str) -> Option<&Value> {
        self.window().iter().find(|entry| entry["id"] == id)
    }
    fn applied(&self, id: &str) -> Option<&Applied> {
        self.applied.iter().find(|applied| applied.entry["id"] == id)
    }
    fn edit(&self, id: &str) -> Option<&EditInfo> {
        self.edits.iter().find(|(target, _)| target == id).map(|(_, info)| info)
    }
    fn pinned(&self, id: &str) -> bool {
        self.pins.iter().any(|pin| pin == id)
    }
}

fn is_omitted(entry: &Value) -> bool {
    entry["type"] == "custom" && entry["customType"] == CONTEXT_OMITTED_CUSTOM_TYPE
}

fn id_list(value: Option<&Value>) -> Result<Vec<String>, String> {
    let items = value
        .and_then(Value::as_array)
        .filter(|items| !items.is_empty())
        .ok_or("ids must be a nonempty list of item ids")?;
    let ids = items
        .iter()
        .map(|id| jsrt::payload::nonempty_string(Some(id), "id"))
        .collect::<Result<Vec<_>, _>>()?;
    if ids.len() > HISTORY_MAX as usize {
        return Err(format!("at most {HISTORY_MAX} ids per edit"));
    }
    let mut seen = HashSet::new();
    Ok(ids.into_iter().filter(|id| seen.insert(id.clone())).collect())
}

/// Collapse-on-return bookkeeping and the lanes this module serves.
#[derive(Default)]
struct Tracking {
    /// Root cell running now (tool call id).
    current_cell: Option<String>,
    /// Finished root-level tasks waiting for a cell to be attributed to.
    unattributed: Vec<TaskLine>,
    /// Cells (tool call ids, oldest first) whose output returned finished tasks and is not collapsed yet.
    cells: Vec<(String, Vec<TaskLine>)>,
    /// Per lane: tokens freed by trims since its newest assistant message (whose usage predates them).
    trimmed: Vec<(String, String, i64)>,
    /// Lanes that used ctx, and the root: only these carry notes and pins across compaction.
    lanes: HashSet<String>,
}

pub struct ContextControl {
    branches: Arc<dyn ContextBranches>,
    clock: Clock,
    trim: bool,
    /// (lane, entry) appended by this module that the branch does not show yet.
    pending: Mutex<Vec<(String, Value)>>,
    tracking: Mutex<Tracking>,
    /// The last `ctx.state` answer and the main branch it was read from (its tip and the ids pending on it): the TUI
    /// asks every few seconds, and reading the branch copies all of it.
    state_cache: Mutex<Option<(StateKey, Value)>>,
}

type StateKey = (Option<String>, Vec<String>);

impl ContextControl {
    pub fn new(branches: Arc<dyn ContextBranches>) -> Self {
        let tracking = Tracking {
            lanes: HashSet::from([kernel::ROOT_LANE.to_string()]),
            ..Tracking::default()
        };
        Self {
            branches,
            clock: system_clock(),
            trim: true,
            pending: Mutex::new(Vec::new()),
            tracking: Mutex::new(tracking),
            state_cache: Mutex::new(None),
        }
    }

    /// Trim old tool results before a threshold compaction (default on; `ULTRON_COMPACTION_TRIM=off` turns it off).
    pub fn with_trim(mut self, trim: bool) -> Self {
        self.trim = trim;
        self
    }

    fn known(&self, lane: &str) {
        jsrt::sync::lock(&self.tracking).lanes.insert(lane.to_string());
    }

    fn append(&self, lane: &str, custom_type: &str, data: Value) -> Result<String, String> {
        let id = self.branches.append_custom(lane, custom_type, &data)?;
        // While a turn runs the entry waits for the next boundary; later reads in this cell must already see it.
        if self.branches.tip_id(lane)?.as_deref() != Some(id.as_str()) {
            jsrt::sync::lock(&self.pending).push((
                lane.to_string(),
                json!({"id": id, "parentId": null, "seq": jsrt::number::MAX_SAFE_INTEGER, "timestamp": (self.clock)(),
                    "type": "custom", "customType": custom_type, "data": data}),
            ));
        }
        Ok(id)
    }

    fn view(&self, lane: &str) -> Result<BranchView, String> {
        let committed = self.branches.entries(lane)?;
        let committed_ids: HashSet<&str> = committed.iter().filter_map(|entry| entry["id"].as_str()).collect();
        let mut pending = jsrt::sync::lock(&self.pending);
        pending.retain(|(_, entry)| !entry["id"].as_str().is_some_and(|id| committed_ids.contains(id)));
        let mut path = committed;
        path.extend(
            pending
                .iter()
                .filter(|(owner, _)| owner == lane)
                .map(|(_, entry)| entry.clone()),
        );
        drop(pending);
        let compaction_index = path.iter().rposition(|entry| entry["type"] == "compaction");
        let window_start = compaction_index.map_or(0, |index| index + 1);
        let window = &path[window_start..];
        let applied = apply_context_edits_marked(window);
        let mut edits: Vec<(String, EditInfo)> = Vec::new();
        for entry in window {
            let data = if entry["type"] == "custom" && entry["data"].is_object() {
                &entry["data"]
            } else {
                &Value::Null
            };
            for edit in context_edits_of(entry) {
                let info = EditInfo {
                    replacement: edit.replacement,
                    source: data["source"].as_str().unwrap_or("unknown").to_string(),
                    reason: data["reason"].as_str().map(str::to_string),
                };
                match edits.iter_mut().find(|(target, _)| *target == edit.target_id) {
                    Some(slot) => slot.1 = info,
                    None => edits.push((edit.target_id, info)),
                }
            }
        }
        let mut pins: Vec<String> = Vec::new();
        for entry in &path {
            if entry["type"] != "custom" || entry["customType"] != CONTEXT_PIN_CUSTOM_TYPE || !entry["data"].is_object()
            {
                continue;
            }
            let Some(target) = entry["data"]["targetId"].as_str() else {
                continue;
            };
            pins.retain(|pin| pin != target);
            if entry["data"]["pinned"] != false {
                pins.push(target.to_string());
            }
        }
        // The current user message, and a tool call still waiting for its result, are never edited.
        let mut protected = HashSet::new();
        if let Some(user) = window
            .iter()
            .rev()
            .find(|entry| entry["type"] == "message" && entry["message"]["role"] == "user")
        {
            protected.insert(user["id"].as_str().unwrap_or_default().to_string());
        }
        let results: HashSet<&str> = window
            .iter()
            .filter(|entry| entry["type"] == "message" && entry["message"]["role"] == "toolResult")
            .filter_map(|entry| entry["message"]["toolCallId"].as_str())
            .collect();
        for entry in window {
            if entry["type"] == "message"
                && tool_call_ids(&entry["message"])
                    .iter()
                    .any(|id| !results.contains(id.as_str()))
            {
                protected.insert(entry["id"].as_str().unwrap_or_default().to_string());
            }
        }
        Ok(BranchView {
            path,
            compaction_index,
            window_start,
            applied,
            edits,
            pins,
            protected,
        })
    }

    fn item(view: &BranchView, entry: &Value) -> Option<Value> {
        let kind = kind_of(entry)?;
        let id = entry["id"].as_str().unwrap_or_default();
        let visible = view.applied(id);
        let omitted = visible.is_some_and(|applied| is_omitted(&applied.entry));
        let own = view.edit(id);
        let mut state = "visible";
        if own.is_some() || omitted || visible.is_none_or(|applied| applied.changed) {
            state = match own {
                Some(own) if own.source == "collapse" => "collapsed",
                Some(own) if own.source == "ctx.summarize" => "summarized",
                _ if omitted || own.is_some_and(|own| own.replacement.is_none()) => "forgotten",
                _ => "replaced",
            };
        }
        let mut item = Map::new();
        item.insert("id".into(), entry["id"].clone());
        item.insert("kind".into(), kind.into());
        if entry["type"] == "message"
            && entry["message"]["role"] == "toolResult"
            && let Some(tool) = entry["message"].get("toolName")
        {
            item.insert("tool".into(), tool.clone());
        }
        let bytes = match visible {
            Some(applied) if !omitted => entry_bytes(&applied.entry),
            _ => 0,
        };
        item.insert("bytes".into(), bytes.into());
        item.insert("original_bytes".into(), entry_bytes(entry).into());
        item.insert("preview".into(), one_line(&entry_text(entry), PREVIEW_CHARS).into());
        item.insert("state".into(), state.into());
        item.insert("pinned".into(), view.pinned(id).into());
        item.insert("protected".into(), view.protected.contains(id).into());
        item.insert("at".into(), entry["timestamp"].clone());
        Some(Value::Object(item))
    }

    fn visible_bytes(view: &BranchView) -> usize {
        view.applied
            .iter()
            .filter(|applied| !is_omitted(&applied.entry))
            .map(|applied| entry_bytes(&applied.entry))
            .sum()
    }

    /// Refuses the whole request when any id is unknown, outside the context, protected, or pinned.
    fn guard(view: &BranchView, ids: &[String]) -> Result<(), String> {
        let mut problems = Vec::new();
        for id in ids {
            match view.by_id(id) {
                None => problems.push(format!(
                    "{id} is not in the model's context on this branch (unknown, or before the last compaction)"
                )),
                Some(entry) if matches!(kind_of(entry), None | Some("compaction" | "summary")) => {
                    problems.push(format!(
                        "{id} is a {} entry and cannot be edited",
                        entry["type"].as_str().unwrap_or("undefined")
                    ))
                }
                Some(_) if view.protected.contains(id) => {
                    problems.push(format!("{id} belongs to the current user turn and cannot be edited"))
                }
                Some(_) if view.pinned(id) => problems.push(format!("{id} is pinned (ctx.unpin it first)")),
                Some(_) => {}
            }
        }
        if problems.is_empty() {
            Ok(())
        } else {
            Err(format!("Context edit refused: {}", problems.join("; ")))
        }
    }

    /// Tool calls and their results move together in a summarized span.
    fn closure(view: &BranchView, ids: &[String]) -> Vec<String> {
        let mut out: Vec<String> = ids.to_vec();
        let add = |out: &mut Vec<String>, id: &str| {
            if !out.iter().any(|known| known == id) {
                out.push(id.to_string());
            }
        };
        let mut call_owner: Vec<(String, String)> = Vec::new();
        let mut results_of: Vec<(String, Vec<String>)> = Vec::new();
        for entry in view.window() {
            if entry["type"] != "message" {
                continue;
            }
            let id = entry["id"].as_str().unwrap_or_default().to_string();
            for call in tool_call_ids(&entry["message"]) {
                match call_owner.iter_mut().find(|(known, _)| *known == call) {
                    Some(slot) => slot.1 = id.clone(),
                    None => call_owner.push((call, id.clone())),
                }
            }
            if entry["message"]["role"] == "toolResult" {
                let call = entry["message"]["toolCallId"].as_str().unwrap_or_default();
                if let Some((_, owner)) = call_owner.iter().find(|(known, _)| known == call) {
                    match results_of.iter_mut().find(|(known, _)| known == owner) {
                        Some(slot) => slot.1.push(id.clone()),
                        None => results_of.push((owner.clone(), vec![id.clone()])),
                    }
                }
            }
        }
        for id in ids {
            let Some(entry) = view.by_id(id) else { continue };
            if entry["type"] == "message" && entry["message"]["role"] == "toolResult" {
                let call = entry["message"]["toolCallId"].as_str().unwrap_or_default();
                if let Some((_, owner)) = call_owner.iter().find(|(known, _)| known == call) {
                    add(&mut out, owner);
                }
            }
        }
        for id in out.clone() {
            if let Some((_, results)) = results_of.iter().find(|(owner, _)| *owner == id) {
                for result in results {
                    add(&mut out, result);
                }
            }
        }
        out
    }

    /// Forgotten, pinned and noted items of the root branch (`ctx.state`, the `/rlm` panel).
    pub fn state(&self) -> Result<Value, String> {
        let pending_ids = jsrt::sync::lock(&self.pending)
            .iter()
            .filter(|(lane, _)| lane == kernel::ROOT_LANE)
            .map(|(_, entry)| entry["id"].as_str().unwrap_or_default().to_string())
            .collect();
        let key = (self.branches.tip_id(kernel::ROOT_LANE)?, pending_ids);
        if let Some((cached, state)) = &*jsrt::sync::lock(&self.state_cache)
            && *cached == key
        {
            return Ok(state.clone());
        }
        let state = self.read_state()?;
        *jsrt::sync::lock(&self.state_cache) = Some((key, state.clone()));
        Ok(state)
    }

    fn read_state(&self) -> Result<Value, String> {
        let view = self.view(kernel::ROOT_LANE)?;
        let item = |id: &str| match view.by_id(id) {
            Some(entry) => json!({"id": id, "kind": kind_of(entry).unwrap_or("custom"),
                "preview": one_line(&entry_text(entry), 80)}),
            None => json!({"id": id}),
        };
        let edited: Vec<&(String, EditInfo)> = view.edits.iter().filter(|(id, _)| view.by_id(id).is_some()).collect();
        let forgotten: Vec<Value> = edited
            .iter()
            .filter(|(_, info)| info.source != "collapse" && info.source != "trim")
            .map(|(id, info)| {
                let mut value = item(id);
                value["source"] = info.source.clone().into();
                if let Some(reason) = &info.reason {
                    value["reason"] = reason.clone().into();
                }
                value
            })
            .collect();
        let last = |items: Vec<Value>| -> Vec<Value> {
            let skip = items.len().saturating_sub(STATE_LIST_MAX);
            items.into_iter().skip(skip).collect()
        };
        let pinned: Vec<Value> = view.pins.iter().map(|id| item(id)).collect();
        let notes = view
            .path
            .iter()
            .filter(|entry| entry["type"] == "custom" && entry["customType"] == CONTEXT_NOTE_CUSTOM_TYPE)
            .count();
        Ok(json!({
            "forgotten": last(forgotten.clone()),
            "forgottenCount": forgotten.len(),
            "collapsedCount": edited.len() - forgotten.len(),
            "pinned": last(pinned),
            "pinnedCount": view.pins.len(),
            "notes": notes,
        }))
    }

    pub fn handle_request(&self, kind: &str, payload: &Map<String, Value>, lane: &str) -> Result<Value, String> {
        if kind == "ctx.state" {
            jsrt::payload::fields(payload, &[])?;
            return self.state();
        }
        self.known(lane);
        let view = self.view(lane)?;
        match kind {
            "ctx.history" => {
                kernel::ops::fields("ctx.history", payload)?;
                let limit = match payload.get("limit") {
                    None => HISTORY_DEFAULT,
                    Some(value) => jsrt::number::safe_integer(value)
                        .filter(|limit| (1..=HISTORY_MAX).contains(limit))
                        .ok_or_else(|| format!("limit must be an integer between 1 and {HISTORY_MAX}"))?,
                };
                let kinds: Option<HashSet<&str>> = match payload.get("kinds") {
                    None | Some(Value::Null) => None,
                    Some(Value::Array(items))
                        if items.iter().all(|k| k.as_str().is_some_and(|k| KINDS.contains(&k))) =>
                    {
                        Some(items.iter().filter_map(Value::as_str).collect())
                    }
                    Some(_) => return Err(format!("kinds must be a list of: {}", KINDS.join(", "))),
                };
                let items: Vec<Value> = view
                    .window()
                    .iter()
                    .filter_map(|entry| Self::item(&view, entry))
                    .filter(|item| {
                        kinds
                            .as_ref()
                            .is_none_or(|kinds| kinds.contains(item["kind"].as_str().unwrap_or("")))
                    })
                    .collect();
                let visible: u64 = items.iter().filter_map(|item| item["bytes"].as_u64()).sum();
                let shown: Vec<Value> = items[items.len().saturating_sub(limit as usize)..].to_vec();
                Ok(json!({"items": shown, "total": items.len(), "visible_bytes": visible,
                    "compacted": view.compaction_index.is_some()}))
            }
            "ctx.get" => {
                kernel::ops::fields("ctx.get", payload)?;
                let id = jsrt::payload::nonempty_string(payload.get("id"), "id")?;
                let entry = view.by_id(&id);
                let item = entry.and_then(|entry| Self::item(&view, entry));
                let (Some(entry), Some(mut item)) = (entry, item) else {
                    return Err(format!("Unknown context item: {id}"));
                };
                item["text"] = entry_text(entry).into();
                if entry["type"] == "message" {
                    item["message"] = entry["message"].clone();
                }
                item["visible_text"] = match view.applied(&id) {
                    Some(applied) if item["state"] != "forgotten" => entry_text(&applied.entry).into(),
                    _ => Value::Null,
                };
                Ok(item)
            }
            "ctx.forget" => {
                kernel::ops::fields("ctx.forget", payload)?;
                let ids = id_list(payload.get("ids"))?;
                let reason = jsrt::utf16::head(
                    &jsrt::payload::nonempty_string(payload.get("reason"), "reason")?,
                    REASON_MAX_CHARS,
                )
                .to_string();
                Self::guard(&view, &ids)?;
                let fresh: Vec<String> = ids
                    .iter()
                    .filter(|id| view.edit(id).is_none_or(|info| info.replacement.is_some()))
                    .cloned()
                    .collect();
                let before = Self::visible_bytes(&view);
                if fresh.is_empty() {
                    return Ok(json!({"forgotten": [], "already": ids, "edit_id": null, "freed_bytes": 0}));
                }
                let edits: Vec<Value> = fresh
                    .iter()
                    .map(|id| json!({"targetId": id, "replacement": null}))
                    .collect();
                let edit_id = self.append(
                    lane,
                    CONTEXT_EDIT_CUSTOM_TYPE,
                    json!({"edits": edits, "source": "ctx.forget", "reason": reason}),
                )?;
                let after = Self::visible_bytes(&self.view(lane)?);
                let already: Vec<&String> = ids.iter().filter(|id| !fresh.contains(id)).collect();
                Ok(json!({"forgotten": fresh, "already": already, "edit_id": edit_id,
                    "freed_bytes": before.saturating_sub(after)}))
            }
            "ctx.summarize" => {
                kernel::ops::fields("ctx.summarize", payload)?;
                let text = jsrt::payload::nonempty_string(payload.get("text"), "text")?;
                if jsrt::utf16::len(&text) > SUMMARY_MAX_CHARS {
                    return Err(format!("text exceeds {SUMMARY_MAX_CHARS} characters"));
                }
                let mut ids = Self::closure(&view, &id_list(payload.get("ids"))?);
                Self::guard(&view, &ids)?;
                let order = |id: &String| view.window().iter().position(|entry| entry["id"] == id.as_str());
                ids.sort_by_key(order);
                let first = ids[0].clone();
                let plural = if ids.len() == 1 { "" } else { "s" };
                let mut edits = vec![json!({"targetId": first, "replacement": {
                    "content": format!("[Summary of {} earlier item{plural} (ctx.summarize)]\n{text}", ids.len())}})];
                edits.extend(ids[1..].iter().map(|id| json!({"targetId": id, "replacement": null})));
                let before = Self::visible_bytes(&view);
                let edit_id = self.append(
                    lane,
                    CONTEXT_EDIT_CUSTOM_TYPE,
                    json!({"edits": edits, "source": "ctx.summarize"}),
                )?;
                let after = Self::visible_bytes(&self.view(lane)?);
                Ok(json!({"summarized": ids, "summary_id": first, "edit_id": edit_id,
                    "freed_bytes": before.saturating_sub(after)}))
            }
            "ctx.pin" | "ctx.unpin" => {
                kernel::ops::fields(kind, payload)?;
                let id = jsrt::payload::nonempty_string(payload.get("id"), "id")?;
                if !view.by_id(&id).is_some_and(|entry| kind_of(entry).is_some()) {
                    return Err(format!("Unknown context item: {id}"));
                }
                let pin = kind == "ctx.pin";
                if view.pinned(&id) == pin {
                    return Ok(json!({"id": id, "pinned": pin, "changed": false}));
                }
                self.append(lane, CONTEXT_PIN_CUSTOM_TYPE, json!({"targetId": id, "pinned": pin}))?;
                Ok(json!({"id": id, "pinned": pin, "changed": true}))
            }
            "ctx.note" => {
                kernel::ops::fields("ctx.note", payload)?;
                let text = jsrt::payload::nonempty_string(payload.get("text"), "text")?;
                if jsrt::utf16::len(&text) > NOTE_MAX_CHARS {
                    return Err(format!("note exceeds {NOTE_MAX_CHARS} characters"));
                }
                Ok(json!({"id": self.append(lane, CONTEXT_NOTE_CUSTOM_TYPE, json!({"text": text}))?}))
            }
            _ => Err(kernel::ops::not_wired(kind)),
        }
    }
}

impl ApiModule for ContextControl {
    fn prefixes(&self) -> &[&str] {
        &["ctx."]
    }

    fn handle(&self, request: &Request<'_>) -> Result<Value, String> {
        self.handle_request(request.kind, request.payload, request.lane)
    }
}

const COLLAPSE_MIN_BYTES: usize = 600;
const MAX_PENDING_CELLS: usize = 64;
const TRIM_MIN_CHARS: usize = 8192;
const TRIM_TARGET: f64 = 0.9;
const KEPT_ITEM_CHARS: usize = 4000;
const KEPT_TOTAL_CHARS: i64 = 16000;
pub const CONTEXT_KEPT_MESSAGE_TYPE: &str = "ultron-context-kept";

impl ContextControl {
    /// Harness `tool_start`: a root `rlm` cell starts; finished tasks not yet attributed belong to it.
    pub fn tool_start(&self, lane: &str, tool_name: &str, tool_call_id: &str) {
        if lane != kernel::ROOT_LANE || tool_name != "rlm" {
            return;
        }
        let mut tracking = jsrt::sync::lock(&self.tracking);
        tracking.current_cell = Some(tool_call_id.to_string());
        if !tracking.unattributed.is_empty() {
            let lines = std::mem::take(&mut tracking.unattributed);
            set_cell(&mut tracking.cells, tool_call_id, lines);
        }
    }

    pub fn tool_end(&self, lane: &str, tool_call_id: &str) {
        let mut tracking = jsrt::sync::lock(&self.tracking);
        if lane == kernel::ROOT_LANE && tracking.current_cell.as_deref() == Some(tool_call_id) {
            tracking.current_cell = None;
        }
    }

    /// Harness `message_end`: once the root model answered after a cell's output, collapse it.
    pub fn message_end(&self, lane: &str, role: &str) -> Result<(), String> {
        if lane == kernel::ROOT_LANE && role == "assistant" && !jsrt::sync::lock(&self.tracking).cells.is_empty() {
            self.collapse()?;
        }
        Ok(())
    }

    pub fn run_end(&self, lane: &str) -> Result<(), String> {
        if lane == kernel::ROOT_LANE && !jsrt::sync::lock(&self.tracking).cells.is_empty() {
            self.collapse()?;
        }
        Ok(())
    }

    /// A task's terminal result is durable (`NativeTask` JSON). Root-level tasks are attributed to the root cell
    /// that returns them.
    pub fn task_ended(&self, task: &Value, cost: Option<f64>) {
        if task.get("parentId").is_some() {
            return;
        }
        let text = |key: &str| task[key].as_str().unwrap_or_default().to_string();
        let status = task["result"]["status"]
            .as_str()
            .map_or_else(|| text("state"), str::to_string);
        let line = TaskLine {
            id: text("id"),
            definition: text("definition"),
            key: text("key"),
            status,
            cost,
        };
        let mut tracking = jsrt::sync::lock(&self.tracking);
        match tracking.current_cell.clone() {
            Some(cell) => {
                let mut lines = tracking
                    .cells
                    .iter()
                    .find(|(id, _)| *id == cell)
                    .map(|(_, lines)| lines.clone())
                    .unwrap_or_default();
                lines.push(line);
                set_cell(&mut tracking.cells, &cell, lines);
            }
            None => {
                tracking.unattributed.push(line);
                if tracking.unattributed.len() > MAX_PENDING_CELLS {
                    tracking.unattributed.remove(0);
                }
            }
        }
        while tracking.cells.len() > MAX_PENDING_CELLS {
            tracking.cells.remove(0);
        }
    }

    /// Harness `entry_added`: drops a pending copy of the entry; for a context edit, the event observers receive.
    pub fn entry_added(&self, lane: &str, entry: &Value) -> Option<Value> {
        if entry["type"] != "custom" {
            return None;
        }
        jsrt::sync::lock(&self.pending).retain(|(_, pending)| pending["id"] != entry["id"]);
        if entry["customType"] != CONTEXT_EDIT_CUSTOM_TYPE {
            return None;
        }
        let data = if entry["data"].is_object() {
            &entry["data"]
        } else {
            &Value::Null
        };
        let mut event = Map::new();
        event.insert("lane".into(), lane.into());
        event.insert("editId".into(), entry["id"].clone());
        event.insert("source".into(), data["source"].as_str().unwrap_or("unknown").into());
        if let Some(reason) = data["reason"].as_str() {
            event.insert("reason".into(), reason.into());
        }
        let edits: Vec<Value> = context_edits_of(entry)
            .into_iter()
            .map(|edit| {
                let action = if edit.replacement.is_none() { "omit" } else { "replace" };
                json!({"targetId": edit.target_id, "action": action})
            })
            .collect();
        event.insert("edits".into(), edits.into());
        if let Some(tasks) = data["tasks"].as_array() {
            let tasks: Vec<Value> = tasks
                .iter()
                .map(|task| match task {
                    Value::String(text) => Value::String(text.clone()),
                    other => Value::String(jsrt::json::stringify(other)),
                })
                .collect();
            event.insert("tasks".into(), tasks.into());
        }
        Some(Value::Object(event))
    }

    /// Collapse cell outputs the model has already answered after.
    fn collapse(&self) -> Result<(), String> {
        if jsrt::sync::lock(&self.tracking).cells.is_empty() {
            return Ok(());
        }
        let view = self.view(kernel::ROOT_LANE)?;
        let mut edits = Vec::new();
        let mut tasks = Vec::new();
        let mut answered_after = false;
        for entry in view.window().iter().rev() {
            if entry["type"] != "message" {
                continue;
            }
            let message = &entry["message"];
            if message["role"] == "assistant" {
                answered_after = true;
                continue;
            }
            if message["role"] != "toolResult" || !answered_after {
                continue;
            }
            let call = message["toolCallId"].as_str().unwrap_or_default();
            let lines = {
                let mut tracking = jsrt::sync::lock(&self.tracking);
                let Some(index) = tracking.cells.iter().position(|(id, _)| id == call) else {
                    continue;
                };
                tracking.cells.remove(index).1
            };
            let id = entry["id"].as_str().unwrap_or_default();
            if view.pinned(id) || view.edit(id).is_some() {
                continue;
            }
            let original = message_text(message);
            if original.len() <= COLLAPSE_MIN_BYTES {
                continue;
            }
            let content = collapsed_cell_text(id, &original, &lines);
            if jsrt::utf16::len(&content) >= jsrt::utf16::len(&original) {
                continue;
            }
            edits.push(json!({"targetId": id, "replacement": {"content": content}}));
            tasks.extend(lines.into_iter().map(|line| line.id));
        }
        if edits.is_empty() {
            return Ok(());
        }
        edits.reverse();
        self.append(
            kernel::ROOT_LANE,
            CONTEXT_EDIT_CUSTOM_TYPE,
            json!({"edits": edits, "source": "collapse", "reason": "task results returned", "tasks": tasks}),
        )?;
        Ok(())
    }

    /// Harness `before_compaction`: for a threshold compaction, trims tool results the model answered after when
    /// that brings the estimate under 90% of the threshold; true declines the compaction.
    pub fn before_compaction(
        &self,
        lane: &str,
        reason: &str,
        tokens_before: i64,
        context_window: Option<i64>,
        reserve_tokens: i64,
    ) -> Result<bool, String> {
        if !self.trim || reason != "threshold" {
            return Ok(false);
        }
        self.known(lane);
        let Some(window) = context_window else {
            return Ok(false);
        };
        self.trim_instead(lane, tokens_before, window - reserve_tokens)
    }

    fn trim_instead(&self, lane: &str, tokens: i64, threshold: i64) -> Result<bool, String> {
        let view = self.view(lane)?;
        let target = threshold as f64 * TRIM_TARGET;
        let last_assistant = view
            .window()
            .iter()
            .rev()
            .find(|entry| entry["type"] == "message" && entry["message"]["role"] == "assistant")
            .and_then(|entry| entry["id"].as_str().map(str::to_string));
        let credit = jsrt::sync::lock(&self.tracking)
            .trimmed
            .iter()
            .find(|(name, assistant, _)| name == lane && Some(assistant) == last_assistant.as_ref())
            .map_or(0, |(_, _, saved)| *saved);
        if (tokens - credit) as f64 <= target {
            return Ok(true);
        }
        let mut edits = Vec::new();
        let mut saved = 0i64;
        let mut answered_after = false;
        for entry in view.window().iter().rev() {
            if entry["type"] != "message" {
                continue;
            }
            let message = &entry["message"];
            if message["role"] == "assistant" {
                answered_after = true;
                continue;
            }
            if message["role"] != "toolResult" || !answered_after {
                continue;
            }
            let id = entry["id"].as_str().unwrap_or_default();
            if view.pinned(id) || view.edit(id).is_some() || view.protected.contains(id) {
                continue;
            }
            // Text only: an image's cost is not in its characters.
            if !message["content"]
                .as_array()
                .is_some_and(|parts| parts.iter().all(|part| part["type"] == "text"))
            {
                continue;
            }
            let original = message_text(message);
            if jsrt::utf16::len(&original) <= TRIM_MIN_CHARS {
                continue;
            }
            let content = trimmed_result_text(id, &original);
            saved += (jsrt::utf16::len(&original) as i64 - jsrt::utf16::len(&content) as i64).div_euclid(4);
            edits.push(json!({"targetId": id, "replacement": {"content": content}}));
        }
        let Some(last_assistant) = last_assistant else {
            return Ok(false);
        };
        if edits.is_empty() || (tokens - credit - saved) as f64 > target {
            return Ok(false);
        }
        edits.reverse();
        self.append(
            lane,
            CONTEXT_EDIT_CUSTOM_TYPE,
            json!({"edits": edits, "source": "trim", "reason": "trimmed old tool results instead of compacting"}),
        )?;
        let mut tracking = jsrt::sync::lock(&self.tracking);
        tracking.trimmed.retain(|(name, _, _)| name != lane);
        tracking
            .trimmed
            .push((lane.to_string(), last_assistant, credit + saved));
        Ok(true)
    }

    /// Notes and pinned items that the newest compaction cut off, as one bounded text block.
    pub fn kept_across_compaction(&self, lane: &str) -> Result<Option<String>, String> {
        let view = self.view(lane)?;
        let Some(index) = view.compaction_index else {
            return Ok(None);
        };
        let retained: HashSet<String> = view.path[index]["retainedTail"]
            .as_array()
            .map(|tail| tail.iter().map(jsrt::json::stringify).collect())
            .unwrap_or_default();
        let before = &view.path[..index];
        let omitted: HashSet<String> = before
            .iter()
            .flat_map(context_edits_of)
            .filter(|edit| edit.replacement.is_none())
            .map(|edit| edit.target_id)
            .collect();
        let mut lines: Vec<String> = Vec::new();
        let mut budget = KEPT_TOTAL_CHARS;
        let mut add = |line: String| {
            if budget <= 0 {
                return;
            }
            let bounded = if jsrt::utf16::len(&line) as i64 > budget {
                format!("{}…", jsrt::utf16::head(&line, budget as usize - 1))
            } else {
                line
            };
            budget -= jsrt::utf16::len(&bounded) as i64;
            lines.push(bounded);
        };
        for entry in before {
            let id = entry["id"].as_str().unwrap_or_default();
            if entry["type"] == "custom" && entry["customType"] == CONTEXT_NOTE_CUSTOM_TYPE && !omitted.contains(id) {
                add(format!("- note {id}: {}", note_text(entry)));
            } else if view.pinned(id)
                && entry["type"] == "message"
                && !retained.contains(&jsrt::json::stringify(&entry["message"]))
            {
                let text = message_text(&entry["message"]);
                let text = if jsrt::utf16::len(&text) > KEPT_ITEM_CHARS {
                    format!("{}…", jsrt::utf16::head(&text, KEPT_ITEM_CHARS - 1))
                } else {
                    text
                };
                add(format!(
                    "- pinned {id} ({}): {text}",
                    entry["message"]["role"].as_str().unwrap_or("undefined")
                ));
            }
        }
        if lines.is_empty() {
            return Ok(None);
        }
        Ok(Some(format!(
            "Notes and pinned items kept across compaction (ctx.note / ctx.pin):\n{}",
            lines.join("\n")
        )))
    }

    /// Harness `transform_context`: after a compaction summary, shows again the notes and pinned items it cut off
    /// (only for lanes that used ctx, and the root). `None` leaves the messages unchanged.
    pub fn transform_context(&self, lane: &str, messages: &[Value]) -> Result<Option<Vec<Value>>, String> {
        let Some(index) = messages
            .iter()
            .position(|message| message["role"] == "compactionSummary")
        else {
            return Ok(None);
        };
        if !jsrt::sync::lock(&self.tracking).lanes.contains(lane) {
            return Ok(None);
        }
        let Some(kept) = self.kept_across_compaction(lane)? else {
            return Ok(None);
        };
        let mut out = messages.to_vec();
        out.insert(
            index + 1,
            json!({"role": "custom", "customType": CONTEXT_KEPT_MESSAGE_TYPE, "content": kept, "display": false,
                "timestamp": (self.clock)()}),
        );
        Ok(Some(out))
    }
}

/// Sets a cell's task lines, keeping its place in the insertion order (a JS Map).
fn set_cell(cells: &mut Vec<(String, Vec<TaskLine>)>, id: &str, lines: Vec<TaskLine>) {
    match cells.iter_mut().find(|(known, _)| known == id) {
        Some(slot) => slot.1 = lines,
        None => cells.push((id.to_string(), lines)),
    }
}