multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
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
//! Catalog maintenance commands: `doctor`, `stats`, `failures`, and `trace`.
//!
//! These commands read the run ledger and the durable store. They change
//! nothing except reconciling the ledger with the store: a run the ledger
//! still holds as unfinished is updated from the store's current state, or
//! marked lost when the store no longer has its execution.

use std::collections::BTreeMap;

use multicast::output::CommandResult;
use multicast_codemode::{
    ExecutionEvent, ExecutionState, ExecutionStatus, LogEntryState, Snippet, normalize_code,
    sanitize_namespace,
};
use serde_json::{Value, json};

use super::ledger::{self, Ledger, Run};
use super::{Resolved, State, check_schema, error, not_found, ok, referenced_methods, warn_ledger};

/// Consecutive failures of the current version that make a workflow failing.
const FAILING_STREAK: usize = 3;

/// Default number of days without a run before a workflow is stale.
const DEFAULT_STALE_DAYS: u64 = 30;

/// Runs listed by `stats NAME`.
const RECENT_RUNS: usize = 10;

/// Characters of an argument or result shown before truncation.
const VALUE_PREVIEW: usize = 160;

/// Console lines shown by `trace` without `--full`.
const CONSOLE_TAIL: usize = 20;

const DAY_MS: u64 = 86_400_000;

/// How much a finding matters.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Severity {
    /// The catalog is broken: a workflow cannot succeed as it stands.
    Error,
    /// Something needs a decision or a follow-up.
    Warning,
    /// Informational; shown only with `--all`.
    Notice,
}

impl Severity {
    fn name(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warning => "warning",
            Self::Notice => "notice",
        }
    }
}

/// One doctor finding.
struct Finding {
    severity: Severity,
    workflow: String,
    check: &'static str,
    message: String,
    hint: String,
    execution_id: Option<String>,
}

impl Finding {
    fn to_json(&self) -> Value {
        let mut value = json!({
            "severity": self.severity.name(),
            "workflow": self.workflow,
            "check": self.check,
            "message": self.message,
            "hint": self.hint,
        });
        if let Some(id) = &self.execution_id {
            value["executionId"] = Value::String(id.clone());
        }
        value
    }
}

/// Formats Unix milliseconds as an RFC 3339 UTC timestamp.
pub(crate) fn timestamp(ms: u64) -> String {
    let seconds = ms / 1000;
    let days = (seconds / 86_400) as i64;
    let time = seconds % 86_400;
    // Civil date from days since 1970-01-01 (proleptic Gregorian calendar).
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let day_of_era = z - era * 146_097;
    let year_of_era =
        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let month_index = (5 * day_of_year + 2) / 153;
    let day = day_of_year - (153 * month_index + 2) / 5 + 1;
    let month = if month_index < 10 {
        month_index + 3
    } else {
        month_index - 9
    };
    let year = year_of_era + era * 400 + i64::from(month <= 2);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
        time / 3600,
        time % 3600 / 60,
        time % 60
    )
}

fn optional_timestamp(ms: Option<u64>) -> Value {
    ms.map_or(Value::Null, |ms| Value::String(timestamp(ms)))
}

fn now_ms() -> u64 {
    web_time::SystemTime::now()
        .duration_since(web_time::UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_millis() as u64)
}

/// Whether a store error means the execution does not exist.
fn is_missing(message: &str) -> bool {
    message.ends_with("not found")
}

/// Previews a value: small values verbatim, large ones truncated as text.
fn preview(value: &Value, full: bool) -> Value {
    if full {
        return value.clone();
    }
    let text = value.to_string();
    if text.chars().count() <= VALUE_PREVIEW {
        return value.clone();
    }
    let shown: String = text.chars().take(VALUE_PREVIEW).collect();
    let remaining = text.len() - shown.len();
    Value::String(format!("{shown}… ({remaining} more bytes)"))
}

/// Number of newest terminal runs of `version` that failed in a row.
///
/// Only completed and failed runs count; rejected, cancelled, rolled back,
/// and lost runs say nothing about whether the program works.
fn failure_streak<'a>(runs: &'a [Run], version: &str) -> (usize, Option<&'a Run>) {
    let mut streak = 0;
    let mut latest = None;
    for run in runs.iter().filter(|run| run.version == version) {
        match run.status.as_str() {
            "error" => {
                streak += 1;
                latest.get_or_insert(run);
            }
            "completed" => break,
            _ => {}
        }
    }
    (streak, latest)
}

fn ledger_or_error(state: &State) -> Result<&Ledger, Box<CommandResult>> {
    state.ledger().ok_or_else(|| {
        Box::new(error(
            "WORKFLOW_LEDGER_UNAVAILABLE",
            "The workflow run ledger could not be opened",
        ))
    })
}

impl State {
    /// Brings unfinished ledger runs up to date with the store.
    ///
    /// Returns the runs that remain unfinished with their store state, and the
    /// runs found lost.
    async fn reconcile(
        &self,
        ledger: &Ledger,
    ) -> Result<(Vec<(Run, ExecutionState)>, Vec<Run>), String> {
        let service = self.service().await?;
        let mut open = Vec::new();
        let mut lost = Vec::new();
        for run in ledger.unfinished()? {
            match service.execution(run.execution_id.clone()).await {
                Ok(execution) => {
                    warn_ledger(ledger.record(&execution, execution.updated_at));
                    if matches!(
                        execution.status,
                        ExecutionStatus::Running | ExecutionStatus::Paused
                    ) {
                        open.push((run, execution));
                    }
                }
                Err(message) if is_missing(&message) => {
                    warn_ledger(ledger.mark_lost(&run.execution_id, now_ms()));
                    lost.push(run);
                }
                Err(message) => return Err(message),
            }
        }
        Ok((open, lost))
    }

    /// `workflows doctor`: findings that need action, most severe first.
    pub(crate) async fn doctor(&self, options: &Value) -> Result<CommandResult, String> {
        let ledger = match ledger_or_error(self) {
            Ok(ledger) => ledger,
            Err(result) => return Ok(*result),
        };
        let all = options.get("all").and_then(Value::as_bool).unwrap_or(false);
        let stale_days = options
            .get("stale_days")
            .and_then(Value::as_f64)
            .map_or(DEFAULT_STALE_DAYS, |days| days.max(0.0) as u64);
        let now = now_ms();
        let mut findings = Vec::new();

        let (open, lost) = self.reconcile(ledger).await?;
        for (run, execution) in open {
            let id = run.execution_id.clone();
            if execution.status == ExecutionStatus::Running {
                findings.push(Finding {
                    severity: Severity::Warning,
                    workflow: run.workflow,
                    check: "interrupted",
                    message: format!(
                        "Run {id} stopped while running, started {}",
                        timestamp(run.started_at)
                    ),
                    hint: format!("workflows resume {id}, or workflows cancel {id} to drop it"),
                    execution_id: Some(id),
                });
            } else {
                let actions: Vec<String> = execution
                    .log
                    .iter()
                    .filter(|entry| {
                        entry.state == LogEntryState::Pending && entry.requires_approval
                    })
                    .map(|entry| {
                        format!("{}.{} (seq {})", entry.connector, entry.method, entry.seq)
                    })
                    .collect();
                if actions.is_empty() {
                    findings.push(Finding {
                        severity: Severity::Warning,
                        workflow: run.workflow,
                        check: "recovery-required",
                        message: format!("Run {id} has an uncertain call outcome; reconcile it with the host before resuming"),
                        hint: format!("workflows resume {id}, or workflows cancel {id} to drop it"),
                        execution_id: Some(id),
                    });
                    continue;
                }
                findings.push(Finding {
                    severity: Severity::Warning,
                    workflow: run.workflow,
                    check: "awaiting-decision",
                    message: format!(
                        "Run {id} is waiting for approval of {}, since {}",
                        actions.join(", "),
                        timestamp(execution.updated_at)
                    ),
                    hint: format!("workflows approve {id}  or  workflows reject {id}"),
                    execution_id: Some(id),
                });
            }
        }
        for run in lost {
            let id = run.execution_id.clone();
            findings.push(Finding {
                severity: Severity::Notice,
                check: "lost",
                message: format!(
                    "Run {id} never finished and its execution is no longer in the store"
                ),
                hint: format!("workflows run {}", run.workflow),
                workflow: run.workflow,
                execution_id: Some(id),
            });
        }

        let snippets = self.service().await?.snippets().await?;
        findings.extend(self.saved_findings(&snippets));
        findings.extend(self.archetype_findings().await?);

        let mut checked = 0;
        for workflow in self.catalog_workflows().await? {
            checked += 1;
            findings.extend(self.health_findings(ledger, &workflow, now, stale_days)?);
        }

        findings.sort_by(|left, right| {
            (left.severity, &left.workflow, left.check).cmp(&(
                right.severity,
                &right.workflow,
                right.check,
            ))
        });
        let errors = count(&findings, Severity::Error);
        let warnings = count(&findings, Severity::Warning);
        let notices = count(&findings, Severity::Notice);
        let shown: Vec<Value> = findings
            .iter()
            .filter(|finding| all || finding.severity != Severity::Notice)
            .map(Finding::to_json)
            .collect();
        let healthy = errors == 0 && warnings == 0;
        Ok(CommandResult::Ok {
            data: json!({
                "healthy": healthy,
                "workflows": checked,
                "errors": errors,
                "warnings": warnings,
                "notices": notices,
                "findings": shown,
            }),
            cta: None,
            exit_code: (!healthy).then_some(1),
        })
    }

    /// Drift checks for saved archetypes against the current CLI and workflows.
    async fn archetype_findings(&self) -> Result<Vec<Finding>, String> {
        let mut findings = Vec::new();
        for archetype in self.archetype_store()?.list()? {
            let name = archetype.name.clone();
            if self.archetypes.contains_key(&name) {
                findings.push(Finding {
                    severity: Severity::Warning,
                    workflow: name.clone(),
                    check: "archetype-shadowed",
                    message: format!(
                        "Saved archetype '{name}' never activates: a shipped archetype has the same name"
                    ),
                    hint: format!("archetypes delete {name}"),
                    execution_id: None,
                });
                continue;
            }
            let missing = self.missing_scope(&archetype).await?;
            if !missing.is_empty() {
                findings.push(Finding {
                    severity: Severity::Error,
                    workflow: name.clone(),
                    check: "archetype-missing-scope",
                    message: format!(
                        "Saved archetype '{name}' scopes {}, which this CLI no longer has",
                        missing.join(", ")
                    ),
                    hint: format!(
                        "archetypes show {name}, then save a corrected scope or archetypes delete {name}"
                    ),
                    execution_id: None,
                });
            }
        }
        Ok(findings)
    }

    /// Drift checks for saved workflows against the current CLI.
    fn saved_findings(&self, snippets: &[Snippet]) -> Vec<Finding> {
        let namespace = sanitize_namespace(self.catalog.name());
        let mut findings = Vec::new();
        let mut programs: BTreeMap<String, Vec<String>> = BTreeMap::new();
        for snippet in snippets {
            let name = snippet.name.clone();
            if self.shipped.contains_key(&name) {
                findings.push(Finding {
                    severity: Severity::Warning,
                    workflow: name.clone(),
                    check: "shadowed",
                    message: format!(
                        "Saved workflow '{name}' never runs: a shipped workflow has the same name"
                    ),
                    hint: format!("workflows delete {name}"),
                    execution_id: None,
                });
                continue;
            }
            let mut missing: Vec<String> = referenced_methods(&snippet.code, &namespace)
                .into_iter()
                .filter(|method| self.catalog.get(method).is_none())
                .map(|method| format!("{namespace}.{method}"))
                .collect();
            missing.dedup();
            if !missing.is_empty() {
                findings.push(Finding {
                    severity: Severity::Error,
                    workflow: name.clone(),
                    check: "missing-command",
                    message: format!(
                        "Saved workflow '{name}' calls {}, which this CLI no longer has",
                        missing.join(", ")
                    ),
                    hint: format!(
                        "workflows show {name}, then save a corrected program or workflows delete {name}"
                    ),
                    execution_id: None,
                });
            }
            if let Some(schema) = &snippet.input_schema
                && let Err(errors) = check_schema(schema)
            {
                findings.push(Finding {
                    severity: Severity::Error,
                    workflow: name.clone(),
                    check: "unsupported-schema",
                    message: format!(
                        "Saved workflow '{name}' has an input schema this CLI cannot check: {}",
                        errors.join("; ")
                    ),
                    hint: format!("save '{name}' again with a supported input schema"),
                    execution_id: None,
                });
            }
            programs
                .entry(normalize_code(&snippet.code).trim().to_string())
                .or_default()
                .push(name);
        }
        for names in programs.into_values().filter(|names| names.len() > 1) {
            for name in &names {
                let others: Vec<&str> = names
                    .iter()
                    .filter(|other| *other != name)
                    .map(String::as_str)
                    .collect();
                findings.push(Finding {
                    severity: Severity::Notice,
                    workflow: name.clone(),
                    check: "duplicate",
                    message: format!(
                        "Saved workflow '{name}' has the same program as {}",
                        others.join(", ")
                    ),
                    hint: "keep one and workflows delete the others".to_string(),
                    execution_id: None,
                });
            }
        }
        findings
    }

    /// Run-history checks for one workflow's current version.
    fn health_findings(
        &self,
        ledger: &Ledger,
        workflow: &Resolved,
        now: u64,
        stale_days: u64,
    ) -> Result<Vec<Finding>, String> {
        let name = &workflow.name;
        let version = workflow.version();
        let totals = ledger.totals(name)?;
        let mut findings = Vec::new();
        let Some(last_run) = totals.iter().map(|totals| totals.last_run).max() else {
            findings.push(Finding {
                severity: Severity::Notice,
                workflow: name.clone(),
                check: "never-run",
                message: format!("Workflow '{name}' has never run"),
                hint: format!("workflows run {name}"),
                execution_id: None,
            });
            return Ok(findings);
        };
        let runs = ledger.recent(name, ledger::RUNS_PER_WORKFLOW)?;
        let (streak, latest) = failure_streak(&runs, &version);
        if let Some(latest) = latest {
            let cause = latest
                .fingerprint
                .as_deref()
                .and_then(|fingerprint| {
                    ledger
                        .failures(Some(name))
                        .ok()?
                        .into_iter()
                        .find(|group| group.fingerprint == fingerprint)
                })
                .map(|group| format!("{}: {}", group.step, group.shape))
                .unwrap_or_default();
            let failing = streak >= FAILING_STREAK;
            findings.push(Finding {
                severity: if failing {
                    Severity::Error
                } else {
                    Severity::Warning
                },
                workflow: name.clone(),
                check: if failing { "failing" } else { "failed" },
                message: format!(
                    "The last {streak} run{} of '{name}' version {version} failed; latest cause {cause}",
                    if streak == 1 { "" } else { "s" }
                ),
                hint: format!(
                    "workflows failures {name}  and  workflows trace {}",
                    latest.execution_id
                ),
                execution_id: Some(latest.execution_id.clone()),
            });
        }
        if now.saturating_sub(last_run) > stale_days.saturating_mul(DAY_MS) {
            findings.push(Finding {
                severity: Severity::Notice,
                workflow: name.clone(),
                check: "stale",
                message: format!("Workflow '{name}' last ran {}", timestamp(last_run)),
                hint: format!(
                    "workflows run {name}  or, if saved and unused, workflows delete {name}"
                ),
                execution_id: None,
            });
        }
        Ok(findings)
    }

    /// `workflows stats [NAME]`.
    pub(crate) async fn stats(&self, name: Option<&str>) -> Result<CommandResult, String> {
        let ledger = match ledger_or_error(self) {
            Ok(ledger) => ledger,
            Err(result) => return Ok(*result),
        };
        let workflows = match name {
            Some(name) => match self.resolve(name).await? {
                Some(workflow) => vec![workflow],
                None => return Ok(not_found(name)),
            },
            None => self.catalog_workflows().await?,
        };
        let mut rows = Vec::new();
        for workflow in &workflows {
            let version = workflow.version();
            let totals = ledger.totals(&workflow.name)?;
            let current = totals
                .iter()
                .find(|totals| totals.version == version)
                .cloned()
                .unwrap_or_default();
            let decided = current.completed + current.failed;
            let mut row = json!({
                "name": workflow.name,
                "origin": workflow.origin,
                "version": version,
                "runs": current.started,
                "completed": current.completed,
                "failed": current.failed,
                "rejected": current.rejected,
                "cancelled": current.cancelled,
                "rolledBack": current.rolled_back,
                "lost": current.lost,
                "successRate": (decided > 0).then(|| current.completed as f64 / decided as f64),
                "earlierVersionRuns": totals
                    .iter()
                    .filter(|totals| totals.version != version)
                    .map(|totals| totals.started)
                    .sum::<u64>(),
                "firstRun": optional_timestamp(totals.iter().map(|t| t.first_run).min()),
                "lastRun": optional_timestamp(totals.iter().map(|t| t.last_run).max()),
                "lastSuccess": optional_timestamp(totals.iter().filter_map(|t| t.last_success).max()),
                "lastFailure": optional_timestamp(totals.iter().filter_map(|t| t.last_failure).max()),
            });
            if name.is_some() {
                row["recent"] = ledger
                    .recent(&workflow.name, RECENT_RUNS)?
                    .iter()
                    .map(|run| {
                        json!({
                            "executionId": run.execution_id,
                            "version": run.version,
                            "status": run.status,
                            "startedAt": timestamp(run.started_at),
                            "durationMs": run.ended_at.map(|end| end.saturating_sub(run.started_at)),
                            "failure": run.fingerprint,
                        })
                    })
                    .collect();
            }
            rows.push(row);
        }
        Ok(ok(Value::Array(rows)))
    }

    /// `workflows failures [NAME]`.
    pub(crate) async fn failures(
        &self,
        name: Option<&str>,
        all: bool,
    ) -> Result<CommandResult, String> {
        let ledger = match ledger_or_error(self) {
            Ok(ledger) => ledger,
            Err(result) => return Ok(*result),
        };
        let mut last_success = BTreeMap::new();
        let mut groups = Vec::new();
        let mut resolved = 0;
        for group in ledger.failures(name)? {
            let success = match last_success.get(&group.workflow) {
                Some(success) => *success,
                None => {
                    let success = ledger
                        .totals(&group.workflow)?
                        .iter()
                        .filter_map(|totals| totals.last_success)
                        .max();
                    last_success.insert(group.workflow.clone(), success);
                    success
                }
            };
            let active = success.is_none_or(|success| group.last_seen > success);
            if !active {
                resolved += 1;
                if !all {
                    continue;
                }
            }
            groups.push(json!({
                "workflow": group.workflow,
                "cause": group.fingerprint,
                "active": active,
                "count": group.count,
                "step": group.step,
                "message": group.shape,
                "sample": group.sample,
                "firstSeen": timestamp(group.first_seen),
                "lastSeen": timestamp(group.last_seen),
                "version": group.last_version,
                "lastExecution": group.last_execution,
                "hint": format!("workflows trace {}", group.last_execution),
            }));
        }
        Ok(ok(json!({
            "causes": groups,
            "resolvedHidden": if all { 0 } else { resolved },
        })))
    }

    /// `workflows trace EXECUTION_ID`.
    pub(crate) async fn trace(&self, id: &str, full: bool) -> Result<CommandResult, String> {
        let run = self
            .ledger()
            .and_then(|ledger| ledger.run(id).ok().flatten());
        let execution = match self.service().await?.execution(id.to_string()).await {
            Ok(execution) => execution,
            Err(message) if is_missing(&message) => {
                return Ok(match run {
                    Some(run) => ok(json!({
                        "executionId": id,
                        "workflow": run.workflow,
                        "version": run.version,
                        "traceId": run.trace_id,
                        "spanId": run.span_id,
                        "status": run.status,
                        "startedAt": timestamp(run.started_at),
                        "failure": run.fingerprint,
                        "detail": "The store no longer holds this execution; only its ledger record remains",
                    })),
                    None => error(
                        "EXECUTION_NOT_FOUND",
                        format!("No workflow execution '{id}'"),
                    ),
                });
            }
            Err(message) => return Err(message),
        };
        self.record(&execution);
        Ok(ok(trace_view(&execution, run.as_ref(), full)))
    }
}

fn count(findings: &[Finding], severity: Severity) -> usize {
    findings
        .iter()
        .filter(|finding| finding.severity == severity)
        .count()
}

/// Renders one execution for `trace`.
fn trace_view(execution: &ExecutionState, run: Option<&Run>, full: bool) -> Value {
    let steps: Vec<Value> = execution
        .log
        .iter()
        .map(|entry| {
            json!({
                "seq": entry.seq,
                "call": format!("{}.{}", entry.connector, entry.method),
                "state": log_state_name(entry.state),
                "needsApproval": entry.requires_approval,
                "arguments": preview(&entry.arguments, full),
                "result": entry.result.as_ref().map(|result| preview(result, full)),
            })
        })
        .collect();
    let failed_at = (execution.status == ExecutionStatus::Error).then(|| {
        match execution
            .log
            .iter()
            .rev()
            .find(|entry| entry.state == LogEntryState::Executing)
        {
            Some(entry) => json!({
                "seq": entry.seq,
                "call": format!("{}.{}", entry.connector, entry.method),
            }),
            None => json!({
                "call": "program",
                "afterSeq": execution
                    .log
                    .iter()
                    .filter(|entry| entry.state == LogEntryState::Applied)
                    .map(|entry| entry.seq)
                    .max(),
            }),
        }
    });
    let console_skipped = if full {
        0
    } else {
        execution.logs.len().saturating_sub(CONSOLE_TAIL)
    };
    let timeline: Vec<Value> = execution
        .events
        .iter()
        .filter_map(|event| match event {
            ExecutionEvent::Status { status, at } => Some(json!({
                "status": ledger::status_name(*status),
                "afterMs": at.saturating_sub(execution.created_at),
            })),
            _ => None,
        })
        .collect();
    json!({
        "executionId": execution.id,
        "trace": execution.trace,
        "workflow": run.map(|run| run.workflow.clone()),
        "version": run.map(|run| run.version.clone()),
        "status": ledger::status_name(execution.status),
        "createdAt": timestamp(execution.created_at),
        "durationMs": execution.updated_at.saturating_sub(execution.created_at),
        "steps": steps,
        "failedAt": failed_at,
        "error": execution.error.as_deref().map(|raw| {
            if full { raw.to_string() } else { ledger::readable_error(raw) }
        }),
        "console": execution.logs[console_skipped..],
        "consoleSkipped": console_skipped,
        "timeline": timeline,
    })
}

fn log_state_name(state: LogEntryState) -> &'static str {
    match state {
        LogEntryState::Pending => "pending",
        LogEntryState::Executing => "executing",
        LogEntryState::Applied => "applied",
        LogEntryState::Reverted => "reverted",
    }
}

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

    #[test]
    fn formats_utc_timestamps() {
        assert_eq!(timestamp(0), "1970-01-01T00:00:00Z");
        assert_eq!(timestamp(951_782_400_000), "2000-02-29T00:00:00Z");
        assert_eq!(timestamp(1_709_251_199_999), "2024-02-29T23:59:59Z");
        assert_eq!(timestamp(4_102_444_800_000), "2100-01-01T00:00:00Z");
    }

    #[test]
    fn previews_truncate_only_large_values() {
        let small = json!({"a": 1});
        assert_eq!(preview(&small, false), small);
        let large = json!("x".repeat(400));
        let shown = preview(&large, false);
        let text = shown.as_str().unwrap();
        assert!(text.ends_with("(242 more bytes)"), "{text}");
        assert_eq!(preview(&large, true), large);
    }

    fn run(version: &str, status: &str) -> Run {
        Run {
            execution_id: format!("{version}-{status}"),
            workflow: "w".into(),
            version: version.into(),
            started_at: 0,
            ended_at: None,
            status: status.into(),
            fingerprint: None,
            trace_id: None,
            span_id: None,
        }
    }

    #[test]
    fn failure_streaks_ignore_decisions_and_other_versions() {
        let runs = [
            run("v2", "error"),
            run("v2", "rejected"),
            run("v1", "completed"),
            run("v2", "error"),
            run("v2", "completed"),
            run("v2", "error"),
        ];
        let (streak, latest) = failure_streak(&runs, "v2");
        assert_eq!(streak, 2);
        assert_eq!(latest.unwrap().execution_id, "v2-error");
        assert_eq!(failure_streak(&runs, "v1").0, 0);
    }
}