apoc 0.9.1

Agentic process control for LLMs
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
//! Unified recording timeline and deterministic causal analysis.

use std::cmp::Ordering;
use std::collections::{BTreeSet, HashSet};

use base64::Engine as _;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::{DebuggerArtifact, DebuggerManager, DebuggerRecording, now_ms};
use crate::history::invocation_scope;
use crate::model::{CausalEvent, InvocationQuery, InvocationRecord};

const TIMELINE_DEFAULT_LIMIT: usize = 100;
const TIMELINE_MAX_LIMIT: usize = 500;
const CONTEXT_MARGIN_MS: u64 = 5 * 60 * 1_000;

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTimelineItem {
    pub id: String,
    pub at: u64,
    pub kind: String,
    pub label: String,
    pub ref_id: Option<String>,
    #[serde(default)]
    pub details: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTimeline {
    pub recording_id: String,
    pub session_id: String,
    pub items: Vec<DebuggerTimelineItem>,
    pub report: DebuggerArtifact,
    pub generated_at: u64,
    pub truncated: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWhyCause {
    pub item: DebuggerTimelineItem,
    pub score: f64,
    pub in_stack: bool,
    pub ms_before: u64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWhyContext {
    pub mark: Option<DebuggerTimelineItem>,
    pub prompt: Option<DebuggerTimelineItem>,
    pub commit: Option<DebuggerTimelineItem>,
    #[serde(default)]
    pub edit: Option<DebuggerTimelineItem>,
    pub diff: Option<DebuggerTimelineItem>,
    pub execution: Option<DebuggerTimelineItem>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWhy {
    pub recording_id: String,
    pub session_id: String,
    pub target: DebuggerTimelineItem,
    pub causes: Vec<DebuggerWhyCause>,
    pub context: DebuggerWhyContext,
    pub answer: String,
    pub limitations: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct DebuggerRecordingCorrelation {
    pub session_id: String,
    pub kind: String,
    pub reference: String,
    pub path: Option<String>,
    pub at: Option<u64>,
    pub actor: String,
    pub causation_id: String,
}

impl DebuggerManager {
    pub fn recording_correlate(
        &self,
        correlation: DebuggerRecordingCorrelation,
    ) -> Result<CausalEvent, String> {
        let DebuggerRecordingCorrelation {
            session_id,
            kind,
            reference,
            path,
            at,
            actor,
            causation_id,
        } = correlation;
        let recording = self
            .recording_status(&session_id)?
            .ok_or_else(|| format!("Debugger session \"{session_id}\" has no recording"))?;
        let (event_kind, subject, details) = match kind.as_str() {
            "edit" => {
                let path = path
                    .filter(|path| !path.is_empty())
                    .ok_or_else(|| "Recording edit correlation requires path".to_string())?;
                (
                    "debugger.recording.edit",
                    path.clone(),
                    json!({"path":path,"reference":reference}),
                )
            }
            "commit" => {
                if reference.is_empty() {
                    return Err("Recording commit correlation requires reference".to_string());
                }
                (
                    "debugger.recording.commit",
                    reference.clone(),
                    json!({"commit":reference}),
                )
            }
            other => {
                return Err(format!(
                    "Unknown recording correlation kind \"{other}\"; expected edit or commit"
                ));
            }
        };
        self.store.append_causal_event(CausalEvent {
            sequence: 0,
            id: uuid::Uuid::now_v7().to_string(),
            at: at.unwrap_or_else(now_ms),
            kind: event_kind.to_string(),
            subject,
            actor,
            correlation_id: session_id.clone(),
            causation_id: Some(causation_id),
            execution_id: recording.execution_id,
            session_id: Some(session_id),
            payload_id: None,
            details,
        })
    }

    pub fn recording_timeline(
        &self,
        session_id: &str,
        cwd: Option<&str>,
        limit: usize,
    ) -> Result<DebuggerTimeline, String> {
        let recording = self
            .recording_status(session_id)?
            .ok_or_else(|| format!("Debugger session \"{session_id}\" has no recording"))?;
        let requested_limit = if limit == 0 {
            TIMELINE_DEFAULT_LIMIT
        } else {
            limit.min(TIMELINE_MAX_LIMIT)
        };
        let (mut items, source_truncated) = self.recording_timeline_items(&recording, cwd)?;
        let total = items.len();
        if total > requested_limit {
            let mut protected = items
                .iter()
                .filter(|item| {
                    matches!(item.kind.as_str(), "mark" | "error" | "exception" | "diff")
                })
                .cloned()
                .collect::<Vec<_>>();
            let mut protected_kinds = protected
                .iter()
                .map(|item| item.kind.clone())
                .collect::<HashSet<_>>();
            for item in items.iter().rev() {
                if protected_kinds.insert(item.kind.clone()) {
                    protected.push(item.clone());
                }
            }
            items.drain(..total - requested_limit);
            let retained = items
                .iter()
                .map(|item| item.id.clone())
                .collect::<HashSet<_>>();
            items.extend(
                protected
                    .into_iter()
                    .filter(|item| !retained.contains(&item.id)),
            );
            items.sort_by(|left, right| {
                left.at
                    .cmp(&right.at)
                    .then_with(|| timeline_order(&left.kind).cmp(&timeline_order(&right.kind)))
                    .then_with(|| left.id.cmp(&right.id))
            });
        }
        let generated_at = now_ms();
        let html = render_timeline_report(&recording, &items, generated_at, total);
        let report = self.store.put_debugger_artifact(
            session_id,
            recording.execution_id.as_deref(),
            "debugger_timeline_report",
            "text/html",
            html.as_bytes(),
        )?;
        Ok(DebuggerTimeline {
            recording_id: recording.id,
            session_id: session_id.to_string(),
            items,
            report,
            generated_at,
            truncated: source_truncated || total > requested_limit,
        })
    }

    pub fn recording_why(
        &self,
        session_id: &str,
        cwd: Option<&str>,
        substring: Option<&str>,
        window_ms: u64,
    ) -> Result<DebuggerWhy, String> {
        let recording = self
            .recording_status(session_id)?
            .ok_or_else(|| format!("Debugger session \"{session_id}\" has no recording"))?;
        let (items, _) = self.recording_timeline_items(&recording, cwd)?;
        let needle = substring.map(str::to_lowercase);
        let errors = items
            .iter()
            .filter(|item| item.kind == "error" || item.kind == "exception")
            .filter(|item| {
                needle.as_ref().is_none_or(|needle| {
                    item.label.to_lowercase().contains(needle)
                        || item.details.to_string().to_lowercase().contains(needle)
                })
            })
            .collect::<Vec<_>>();
        let latest = errors.last().ok_or_else(|| match substring {
            Some(value) => format!("No recorded error matches \"{value}\""),
            None => "No errors or exceptions are present in the recording".to_string(),
        })?;
        let target = errors
            .iter()
            .find(|item| item.label == latest.label && item.kind == latest.kind)
            .copied()
            .unwrap_or(latest);
        let target = (*target).clone();
        let window_ms = if window_ms == 0 {
            CONTEXT_MARGIN_MS
        } else {
            window_ms
        };
        let lower = target.at.saturating_sub(window_ms);
        let stack = target
            .details
            .get("stack")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_lowercase();
        let mut causes = items
            .iter()
            .filter(|item| item.at <= target.at && item.at >= lower)
            .filter(|item| matches!(item.kind.as_str(), "edit" | "diff" | "execution" | "causal"))
            .map(|item| rank_cause(item, &stack, target.at, window_ms))
            .collect::<Vec<_>>();
        causes.sort_by(|left, right| {
            right
                .score
                .partial_cmp(&left.score)
                .unwrap_or(Ordering::Equal)
                .then_with(|| right.item.at.cmp(&left.item.at))
                .then_with(|| left.item.id.cmp(&right.item.id))
        });
        causes.truncate(8);
        let context = DebuggerWhyContext {
            mark: latest_item(&items, "mark", target.at),
            prompt: latest_item(&items, "prompt", target.at),
            commit: latest_item(&items, "commit", target.at),
            edit: latest_item(&items, "edit", target.at),
            diff: latest_item(&items, "diff", target.at),
            execution: latest_item(&items, "execution", target.at),
        };
        let answer = build_why_answer(&target, causes.first(), &context);
        let mut limitations = Vec::new();
        if !items.iter().any(|item| item.kind == "edit") {
            limitations.push(
                "No file path was present in sanitized invocation input, so file-level edit blame is unavailable."
                    .to_string(),
            );
        }
        if context.commit.is_none() {
            limitations.push(
                "No commit identity was present in invocation workspace evidence before the error."
                    .to_string(),
            );
        }
        if causes.is_empty() {
            limitations.push(
                "No edit, diff, execution, or causal event was recorded inside the lookback window."
                    .to_string(),
            );
        }
        Ok(DebuggerWhy {
            recording_id: recording.id,
            session_id: session_id.to_string(),
            target,
            causes,
            context,
            answer,
            limitations,
        })
    }

    fn recording_timeline_items(
        &self,
        recording: &DebuggerRecording,
        cwd: Option<&str>,
    ) -> Result<(Vec<DebuggerTimelineItem>, bool), String> {
        let since = recording.started_at.saturating_sub(CONTEXT_MARGIN_MS);
        let until = recording
            .stopped_at
            .unwrap_or_else(now_ms)
            .saturating_add(CONTEXT_MARGIN_MS);
        let captures = self.store.debugger_captures(&recording.id)?;
        let marks = self.store.debugger_marks(&recording.id)?;
        let afters = self.store.debugger_afters(&recording.id)?;
        let events = self
            .store
            .debugger_events(&recording.session_id, 0, 1_000)?;
        let scope = cwd.map(|cwd| invocation_scope(Some(cwd)));
        let mut invocation_query = InvocationQuery {
            limit: TIMELINE_MAX_LIMIT,
            scope_kind: scope.as_ref().map(|scope| scope.kind),
            scope_key: scope.as_ref().and_then(|scope| scope.key.clone()),
            since_ms: Some(since),
            until_ms: Some(until),
            ..InvocationQuery::default()
        };
        let mut invocations = Vec::new();
        let mut invocation_source_truncated = false;
        for _ in 0..4 {
            let page = self.store.timeline_invocations(&invocation_query)?;
            invocations.extend(page.invocations);
            let Some(cursor) = page.next_cursor else {
                invocation_source_truncated = false;
                break;
            };
            invocation_query.cursor = Some(cursor);
            invocation_source_truncated = true;
        }
        let execution_ids = invocations
            .iter()
            .filter_map(|invocation| invocation.execution_id.clone())
            .collect::<HashSet<_>>();
        let causal_rows = self.store.causal_events_between(since, until, 1_000)?;
        let causal_source_truncated = causal_rows.len() >= 1_000;
        let causal = causal_rows
            .into_iter()
            .filter(|event| {
                event.session_id.as_deref() == Some(recording.session_id.as_str())
                    || event.execution_id.as_ref().is_some_and(|id| {
                        execution_ids.contains(id) || recording.execution_id.as_ref() == Some(id)
                    })
            })
            .collect::<Vec<_>>();

        let mut items = Vec::new();
        let mut seen_console = HashSet::new();
        let mut seen_exceptions = HashSet::new();
        let mut seen_network = HashSet::new();
        for capture in &captures {
            items.push(DebuggerTimelineItem {
                id: format!("capture:{}", capture.id),
                at: capture.at,
                kind: "capture".to_string(),
                label: format!("{}: {}", capture.reason, capture.url),
                ref_id: Some(capture.id.clone()),
                details: json!({
                    "sequence":capture.sequence,
                    "reason":capture.reason,
                    "url":capture.url,
                    "scroll_y":capture.scroll_y,
                    "artifact":capture.screenshot.artifact,
                    "warnings":capture.state.warnings
                }),
            });
            for entry in &capture.state.console {
                if entry.kind != "error" && entry.kind != "assert" {
                    continue;
                }
                let key = format!("{}:{}", entry.kind, entry.id);
                if seen_console.insert(key.clone()) {
                    items.push(DebuggerTimelineItem {
                        id: format!("console:{key}"),
                        at: epoch_ms(entry.at, capture.at),
                        kind: "error".to_string(),
                        label: entry.text.clone(),
                        ref_id: Some(capture.id.clone()),
                        details: json!({"console_id":entry.id,"stack":entry.stack.join(" ")}),
                    });
                }
            }
            for entry in &capture.state.exceptions {
                let key = format!("{}:{}", entry.kind, entry.id);
                if seen_exceptions.insert(key.clone()) {
                    items.push(DebuggerTimelineItem {
                        id: format!("exception:{key}"),
                        at: epoch_ms(entry.at, capture.at),
                        kind: "exception".to_string(),
                        label: entry.text.clone(),
                        ref_id: Some(capture.id.clone()),
                        details: json!({
                            "exception_id":entry.id,
                            "kind":entry.kind,
                            "file":entry.file,
                            "line":entry.line,
                            "stack":format!("{}:{}", entry.file, entry.line),
                            "uncaught":entry.uncaught
                        }),
                    });
                }
            }
            for request in &capture.state.network {
                if request.error.is_none() && request.status.is_none_or(|status| status < 400) {
                    continue;
                }
                if seen_network.insert(request.id.clone()) {
                    items.push(DebuggerTimelineItem {
                        id: format!("network:{}", request.id),
                        at: capture.at,
                        kind: "network_failure".to_string(),
                        label: format!("{} {}", request.method, request.url),
                        ref_id: Some(request.id.clone()),
                        details: json!({"status":request.status,"error":request.error}),
                    });
                }
            }
        }
        for mark in marks {
            items.push(DebuggerTimelineItem {
                id: format!("mark:{}", mark.id),
                at: mark.at,
                kind: "mark".to_string(),
                label: mark.name,
                ref_id: Some(mark.capture_id),
                details: Value::Null,
            });
        }
        for after in afters {
            items.push(DebuggerTimelineItem {
                id: format!("after:{}", after.id),
                at: after.at,
                kind: "diff".to_string(),
                label: format!("{:.3}% pixels changed", after.diff_percent),
                ref_id: Some(after.id),
                details: json!({
                    "before_capture_id":after.before_capture_id,
                    "after_capture_id":after.after_capture_id,
                    "diff_pixels":after.diff_pixels,
                    "region":after.region,
                    "report":after.report
                }),
            });
        }
        let debugger_events_source_truncated = events.len() >= 1_000;
        for event in events
            .into_iter()
            .filter(|event| event.at >= since && event.at <= until)
        {
            items.push(DebuggerTimelineItem {
                id: format!("debugger_event:{}", event.id),
                at: event.at,
                kind: "debugger_event".to_string(),
                label: event.kind,
                ref_id: event.execution_id,
                details: event.details,
            });
        }
        for event in causal {
            let item_kind = causal_item_kind(&event.kind, &event.details);
            let path = (item_kind == "edit")
                .then(|| named_strings(&event.details, "path").into_iter().next())
                .flatten();
            let ref_id = if item_kind == "commit" {
                named_strings(&event.details, "commit").into_iter().next()
            } else {
                event.execution_id.clone().or(event.payload_id.clone())
            };
            items.push(DebuggerTimelineItem {
                id: format!("causal:{}", event.id),
                at: event.at,
                kind: item_kind.to_string(),
                label: format!("{}: {}", event.kind, event.subject),
                ref_id,
                details: json!({
                    "actor":event.actor,
                    "correlation_id":event.correlation_id,
                    "causation_id":event.causation_id,
                    "path":path,
                    "data":event.details
                }),
            });
        }
        append_invocation_items(&mut items, &invocations);
        items.sort_by(|left, right| {
            left.at
                .cmp(&right.at)
                .then_with(|| timeline_order(&left.kind).cmp(&timeline_order(&right.kind)))
                .then_with(|| left.id.cmp(&right.id))
        });
        Ok((
            items,
            invocation_source_truncated
                || causal_source_truncated
                || debugger_events_source_truncated
                || captures.len() >= 1_000,
        ))
    }
}

fn append_invocation_items(
    items: &mut Vec<DebuggerTimelineItem>,
    invocations: &[InvocationRecord],
) {
    let mut commits = BTreeSet::new();
    let mut diffs = BTreeSet::new();
    for invocation in invocations {
        if let Some(purpose) = invocation.purpose.as_ref() {
            items.push(DebuggerTimelineItem {
                id: format!("prompt:{}", invocation.id),
                at: invocation.started_at,
                kind: "prompt".to_string(),
                label: purpose.clone(),
                ref_id: Some(invocation.id.clone()),
                details: json!({"command_path":invocation.command_path,"actor":invocation.actor}),
            });
        }
        if let Some(execution_id) = invocation.execution_id.as_ref() {
            items.push(DebuggerTimelineItem {
                id: format!("execution:{}:{}", execution_id, invocation.id),
                at: invocation.started_at,
                kind: "execution".to_string(),
                label: invocation.command_path.clone(),
                ref_id: Some(execution_id.clone()),
                details: json!({
                    "invocation_id":invocation.id,
                    "status":invocation.status,
                    "exit_code":invocation.exit_code,
                    "error_code":invocation.error_code,
                    "error":invocation.error
                }),
            });
        }
        for commit in named_strings(&invocation.normalized_input, "commit") {
            if !commit.is_empty() && commits.insert(commit.clone()) {
                items.push(DebuggerTimelineItem {
                    id: format!("commit:{}", commit),
                    at: invocation.started_at,
                    kind: "commit".to_string(),
                    label: short_value(&commit),
                    ref_id: Some(commit),
                    details: json!({"invocation_id":invocation.id}),
                });
            }
        }
        for digest in named_strings(&invocation.normalized_input, "dirty_digest") {
            if !digest.is_empty() && diffs.insert(digest.clone()) {
                items.push(DebuggerTimelineItem {
                    id: format!("workspace_diff:{}", digest),
                    at: invocation.started_at,
                    kind: "diff".to_string(),
                    label: format!("workspace {}", short_value(&digest)),
                    ref_id: Some(digest),
                    details: json!({"invocation_id":invocation.id,"command_path":invocation.command_path}),
                });
            }
        }
    }
}

fn rank_cause(
    item: &DebuggerTimelineItem,
    stack: &str,
    target_at: u64,
    window_ms: u64,
) -> DebuggerWhyCause {
    let ms_before = target_at.saturating_sub(item.at);
    let recency = 1.0 - ms_before as f64 / window_ms.max(1) as f64;
    let path = item
        .details
        .get("path")
        .and_then(Value::as_str)
        .unwrap_or(&item.label);
    let basename = path
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(path)
        .to_lowercase();
    let in_stack = !stack.is_empty() && !basename.is_empty() && stack.contains(&basename);
    DebuggerWhyCause {
        item: item.clone(),
        score: recency + if in_stack { 1.0 } else { 0.0 },
        in_stack,
        ms_before,
    }
}

fn latest_item(
    items: &[DebuggerTimelineItem],
    kind: &str,
    at: u64,
) -> Option<DebuggerTimelineItem> {
    items
        .iter()
        .rev()
        .find(|item| item.kind == kind && item.at <= at)
        .cloned()
}

fn build_why_answer(
    target: &DebuggerTimelineItem,
    cause: Option<&DebuggerWhyCause>,
    context: &DebuggerWhyContext,
) -> String {
    let head = format!(
        "\"{}\" first appeared at {}",
        truncate(&target.label, 80),
        target.at
    );
    let Some(cause) = cause else {
        return format!("{head}; no recorded cause was found in the lookback window");
    };
    let mut answer = format!(
        "{head}, {} after {} {}",
        format_duration(cause.ms_before),
        cause.item.kind,
        truncate(&cause.item.label, 80)
    );
    if cause.in_stack {
        answer.push_str("; its file appears in the stack");
    }
    if let Some(mark) = context.mark.as_ref() {
        answer.push_str(&format!(" (mark: {})", truncate(&mark.label, 40)));
    }
    if let Some(edit) = context.edit.as_ref() {
        answer.push_str(&format!(" (edit: {})", truncate(&edit.label, 40)));
    }
    answer
}

fn render_timeline_report(
    recording: &DebuggerRecording,
    items: &[DebuggerTimelineItem],
    generated_at: u64,
    total: usize,
) -> String {
    let cards = items
        .iter()
        .map(|item| {
            let image = if item.kind == "capture" {
                item.details
                    .pointer("/artifact/path")
                    .and_then(Value::as_str)
                    .and_then(|path| std::fs::read(path).ok())
                    .map(|bytes| {
                        let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
                        format!("<img alt=\"Recorded browser capture\" src=\"data:image/png;base64,{encoded}\">")
                    })
                    .unwrap_or_default()
            } else {
                String::new()
            };
            format!(
                "<article class=\"{}\"><div class=\"kind\">{}</div><h2>{}</h2><time>{}</time>{}<pre>{}</pre></article>",
                html_escape(&item.kind),
                html_escape(&item.kind),
                html_escape(&item.label),
                item.at,
                image,
                html_escape(&serde_json::to_string_pretty(&item.details).unwrap_or_default())
            )
        })
        .collect::<Vec<_>>()
        .join("\n");
    format!(
        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>apoc debugger timeline</title><style>body{{margin:0;background:#0b0d10;color:#e8edf2;font:14px ui-monospace,monospace}}header{{position:sticky;top:0;background:#11151bcc;padding:20px;backdrop-filter:blur(12px);z-index:1}}main{{display:flex;gap:16px;overflow:auto;padding:20px;align-items:flex-start}}article{{width:360px;min-width:360px;background:#151a21;border:1px solid #303946;border-radius:12px;padding:14px}}article.capture{{width:520px;min-width:520px}}img{{display:block;width:100%;height:auto;border-radius:8px;margin:12px 0}}h1,h2{{margin:0 0 8px}}h2{{font-size:15px;overflow-wrap:anywhere}}.kind{{color:#7dd3fc;text-transform:uppercase;font-size:11px;letter-spacing:.08em}}time{{color:#94a3b8}}pre{{white-space:pre-wrap;overflow-wrap:anywhere;color:#bac6d3}}</style></head><body><header><h1>apoc debugger timeline</h1><div>recording {} · showing {} of {} items · generated {}</div></header><main>{}</main></body></html>",
        html_escape(&recording.id),
        items.len(),
        total,
        generated_at,
        cards
    )
}

fn epoch_ms(value: f64, fallback: u64) -> u64 {
    if !value.is_finite() || value <= 0.0 {
        return fallback;
    }
    if value >= 1_000_000_000_000.0 {
        value as u64
    } else if value >= 1_000_000_000.0 {
        (value * 1_000.0) as u64
    } else {
        fallback
    }
}

fn named_strings(value: &Value, name: &str) -> Vec<String> {
    let mut output = Vec::new();
    collect_named_strings(value, name, &mut output);
    output
}

fn collect_named_strings(value: &Value, name: &str, output: &mut Vec<String>) {
    match value {
        Value::Object(values) => {
            for (key, value) in values {
                if key == name
                    && let Some(value) = value.as_str()
                {
                    output.push(value.to_string());
                }
                collect_named_strings(value, name, output);
            }
        }
        Value::Array(values) => {
            for value in values {
                collect_named_strings(value, name, output);
            }
        }
        _ => {}
    }
}

fn causal_item_kind<'a>(kind: &'a str, details: &Value) -> &'a str {
    let kind_lower = kind.to_lowercase();
    let has_path = named_strings(details, "path")
        .into_iter()
        .any(|path| !path.is_empty());
    if kind_lower.contains("commit")
        && named_strings(details, "commit")
            .into_iter()
            .any(|commit| !commit.is_empty())
    {
        "commit"
    } else if has_path
        && ["edit", "write", "patch", "mutation"]
            .iter()
            .any(|marker| kind_lower.contains(marker))
    {
        "edit"
    } else {
        "causal"
    }
}

fn timeline_order(kind: &str) -> u8 {
    match kind {
        "mark" => 0,
        "prompt" | "commit" | "edit" => 1,
        "execution" | "causal" | "debugger_event" => 2,
        "capture" => 3,
        "error" | "exception" | "network_failure" => 4,
        "diff" => 5,
        _ => 6,
    }
}

fn short_value(value: &str) -> String {
    value.chars().take(12).collect()
}

fn format_duration(milliseconds: u64) -> String {
    if milliseconds < 1_000 {
        format!("{milliseconds}ms")
    } else {
        format!("{:.1}s", milliseconds as f64 / 1_000.0)
    }
}

fn truncate(value: &str, max: usize) -> String {
    if value.chars().count() <= max {
        value.to_string()
    } else {
        let mut value = value
            .chars()
            .take(max.saturating_sub(1))
            .collect::<String>();
        value.push('…');
        value
    }
}

fn html_escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ranks_a_recent_stack_file_above_a_newer_unrelated_edit() {
        let stack_edit = DebuggerTimelineItem {
            id: "edit:cart".to_string(),
            at: 1_000,
            kind: "edit".to_string(),
            label: "src/Cart.tsx".to_string(),
            ref_id: None,
            details: json!({"path":"src/Cart.tsx"}),
        };
        let unrelated = DebuggerTimelineItem {
            id: "edit:css".to_string(),
            at: 1_900,
            kind: "edit".to_string(),
            label: "src/site.css".to_string(),
            ref_id: None,
            details: json!({"path":"src/site.css"}),
        };
        let stack = rank_cause(&stack_edit, "at cart.tsx:12", 2_000, 5_000);
        let unrelated = rank_cause(&unrelated, "at cart.tsx:12", 2_000, 5_000);
        assert!(stack.in_stack);
        assert!(stack.score > unrelated.score);
    }

    #[test]
    fn normalizes_epoch_and_monotonic_debugger_times_truthfully() {
        assert_eq!(epoch_ms(1_700_000_000_000.0, 7), 1_700_000_000_000);
        assert_eq!(epoch_ms(1_700_000_000.0, 7), 1_700_000_000_000);
        assert_eq!(epoch_ms(123.0, 7), 7);
    }
}