zebflow 0.10.10

Reactive web automation platform โ€” pipelines, templates, and real-time collaboration in a single binary.
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
//! Bounded invocation-log capture, independent of execution payload ownership.
//!
//! A borrowed tree is serialized through a sampling/redaction view into a capped
//! buffer. No complete payload clone is made. Secret markers are discovered in
//! the **whole** tree first, including omitted array elements: a secret declared
//! there may also occur in a retained value. That scan is linear in input size;
//! sampling reduces copying/serialization, not the cost of discovering secrets.
//!
//! Byte budgets cover captured config/input/output JSON across a node or run.
//! Fixed omission markers and trace bookkeeping (IDs, timings, error messages)
//! are outside these budgets. They are not a cap on the entire database record.
//! Exhausting a budget replaces that capture with a typed marker and consumes
//! the attempted allowance. Execution values are never truncated or modified.

use std::collections::HashSet;
use std::io::{self, Write};

use serde::ser::{SerializeMap, SerializeSeq};
use serde::{Deserialize, Serialize, Serializer};
use serde_json::{Value, json};

use crate::pipeline::nodes::NodeExecutionOutput;

pub mod preview_snapshot;

#[cfg(test)]
mod tests;

/// How much of a payload a run records.
///
/// A pipeline on a device has no room for run history; a pipeline being
/// debugged wants all of it. Contract: `kinds/invocation-record` ยง Capture
/// Level. Rule 3 holds underneath every level โ€” a credential's value is never
/// shown, whatever this is set to.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CaptureLevel {
    /// Node id, kind, pins, timing, status, error code. No payloads at all,
    /// and none of the work of producing them.
    None,
    /// `None`, plus the payloads of nodes that failed. The default: it costs
    /// what `None` costs on disk for a run that succeeds, and a run that fails
    /// is the one anybody opens.
    #[default]
    OnError,
    /// Every node's config, input and output, subject to the byte budgets.
    Full,
}

/// Optional capture overrides. Missing fields inherit the project setting,
/// then the built-in default. Retention count/age are configured separately.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TraceCaptureSettings {
    /// How much of each payload is recorded. Default: `on-error`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub level: Option<CaptureLevel>,
    /// First N elements of every logged array; 0 disables array sampling only.
    /// Default: 6. Strings, depth, and byte budgets still apply with 0.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub array_sample_count: Option<u32>,
    /// Maximum Unicode characters retained per string. Default: 8192.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_string_chars: Option<u32>,
    /// Maximum container depth, with the payload root at depth 0. Default: 8.
    /// An additional encoded-depth ceiling of 112 accounts for sample wrappers
    /// and reserves room for trace/API envelopes under JSON's parser limit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_depth: Option<u32>,
    /// Captured config/input/output bytes per node execution. Default: 65536.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_node_bytes: Option<u32>,
    /// Captured data bytes per invocation. Child function runs currently have
    /// independent budgets. Default: 1048576. Does not change log retention.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_run_bytes: Option<u32>,
}

/// Fully resolved capture policy, snapshotted once at invocation start.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct TraceCaptureLimits {
    /// See [`CaptureLevel`].
    pub level: CaptureLevel,
    /// See [`TraceCaptureSettings::array_sample_count`].
    pub array_sample_count: u32,
    /// See [`TraceCaptureSettings::max_string_chars`].
    pub max_string_chars: u32,
    /// See [`TraceCaptureSettings::max_depth`].
    pub max_depth: u32,
    /// See [`TraceCaptureSettings::max_node_bytes`].
    pub max_node_bytes: u32,
    /// See [`TraceCaptureSettings::max_run_bytes`].
    pub max_run_bytes: u32,
}

impl TraceCaptureSettings {
    /// Validate configured limits at API/contract boundaries. Only array
    /// sampling accepts zero; finite limits prevent accidental unlimited logs.
    pub fn validate(&self) -> Result<(), String> {
        for (name, value, min, max) in [
            ("array_sample_count", self.array_sample_count, 0, 1_000_000),
            ("max_string_chars", self.max_string_chars, 1, 1_048_576),
            ("max_depth", self.max_depth, 1, 64),
            ("max_node_bytes", self.max_node_bytes, 256, 16_777_216),
            ("max_run_bytes", self.max_run_bytes, 256, 67_108_864),
        ] {
            if value.is_some_and(|value| value < min || value > max) {
                return Err(format!(
                    "trace_capture.{name} must be between {min} and {max}"
                ));
            }
        }
        Ok(())
    }

    /// Resolve each field independently: pipeline override โ†’ project โ†’ default.
    /// In particular, `Some(0)` is a real array override, never inheritance.
    pub fn resolve(&self, overrides: Option<&Self>) -> TraceCaptureLimits {
        let empty = Self::default();
        let over = overrides.unwrap_or(&empty);
        TraceCaptureLimits {
            level: over.level.or(self.level).unwrap_or_default(),
            array_sample_count: over
                .array_sample_count
                .or(self.array_sample_count)
                .unwrap_or(6),
            max_string_chars: over
                .max_string_chars
                .or(self.max_string_chars)
                .unwrap_or(8192),
            max_depth: over.max_depth.or(self.max_depth).unwrap_or(8),
            max_node_bytes: over.max_node_bytes.or(self.max_node_bytes).unwrap_or(65536),
            max_run_bytes: over.max_run_bytes.or(self.max_run_bytes).unwrap_or(1048576),
        }
    }
}

/// Per-invocation budget. Start a fresh node allowance with [`Self::begin_node`].
pub(crate) struct TraceCapture {
    limits: TraceCaptureLimits,
    run_left: usize,
    node_left: usize,
    /// Values this project has taken out of the credential store. Masked in
    /// every payload at every level โ€” `kinds/invocation-record` rule 3. Held
    /// here, owned, so `Secrets` can borrow them alongside the markers it
    /// discovers in the payload itself.
    confidential: Vec<String>,
}

impl TraceCapture {
    pub(crate) fn new(limits: TraceCaptureLimits) -> Self {
        Self {
            run_left: limits.max_run_bytes as usize,
            node_left: 0,
            limits,
            confidential: Vec::new(),
        }
    }

    /// Values that must never appear, whatever the level says.
    pub(crate) fn with_confidential(mut self, values: Vec<String>) -> Self {
        // Longest first, so a secret that contains another is masked whole
        // rather than leaving its tail visible.
        let mut values = values;
        values.sort_by(|a, b| b.len().cmp(&a.len()));
        self.confidential = values;
        self
    }

    pub(crate) fn begin_node(&mut self) {
        self.node_left = self.limits.max_node_bytes as usize;
    }

    /// Does this level record payloads for a node that *succeeded*?
    ///
    /// `OnError` answers no, which is what makes the default cost nothing on
    /// disk for an ordinary run.
    pub(crate) fn records_successful_payloads(&self) -> bool {
        matches!(self.limits.level, CaptureLevel::Full)
    }

    /// Does this level ever record payloads?
    ///
    /// `None` answers no, and the caller skips the serialization entirely โ€”
    /// not capturing is cheaper than capturing and discarding, which is the
    /// whole point on a device.
    pub(crate) fn records_any_payload(&self) -> bool {
        !matches!(self.limits.level, CaptureLevel::None)
    }

    /// Does this node's input or output go into the record?
    ///
    /// The level decides, with one exception: a node that declares a canvas
    /// preview for that payload (`config.preview.in` / `.out`) has asked to
    /// see it, so `on-error` records it even for a node that succeeded โ€”
    /// otherwise the preview would read "no run yet" forever at the default
    /// level. `None` still records nothing: an operator chose that for a
    /// device, and a preview does not overrule them. The byte budgets are
    /// untouched either way; a preview widens nothing.
    pub(crate) fn records_payload_for(&self, success: bool, wanted_by_preview: bool) -> bool {
        if !success {
            return self.records_any_payload();
        }
        self.records_successful_payloads() || (wanted_by_preview && self.records_any_payload())
    }

    /// Capture one borrowed payload, preserving private-marker and exception
    /// semantics. Serialization stops immediately when the byte buffer is full.
    pub(crate) fn capture(&mut self, value: &Value) -> Value {
        self.capture_mode(value, false)
    }

    /// Capture resolved config using the existing config secret-key policy;
    /// editor-only `ui` properties are omitted at every level.
    pub(crate) fn config(&mut self, value: &Value) -> Option<Value> {
        if value.is_null() || value.as_object().is_some_and(|v| v.is_empty()) {
            return None;
        }
        Some(self.capture_mode(value, true))
    }

    fn capture_mode(&mut self, value: &Value, config: bool) -> Value {
        if self.node_left.min(self.run_left) == 0 {
            return byte_marker();
        }
        // Moved out for the duration: `Secrets` borrows these alongside the
        // payload's own markers, and `encode` needs `&mut self`.
        let confidential = std::mem::take(&mut self.confidential);
        let mut secrets = Secrets::discover(value);
        // Rule 3: a credential's value is hidden at every level, and it is not
        // among the payload's markers because no node put it there.
        for value in &confidential {
            secrets.tokens.push(value.as_str());
        }
        let limits = self.limits;
        let captured = self.encode(&View {
            value,
            secrets: &secrets,
            limits: &limits,
            depth: 0,
            wire_depth: 0,
            path: Vec::new(),
            masked: false,
            excepted: false,
            config,
        });
        drop(secrets);
        self.confidential = confidential;
        captured
    }

    /// Treat multiple node emissions as one logged array. Avoid constructing a
    /// second owned array containing all execution payloads just to sample it.
    pub(crate) fn outputs(&mut self, outputs: &[NodeExecutionOutput]) -> Value {
        if outputs.len() == 1 {
            return self.capture(&outputs[0].payload);
        }
        if self.node_left.min(self.run_left) == 0 {
            return byte_marker();
        }
        let limits = self.limits;
        self.encode(&Emissions { outputs, limits })
    }

    fn encode(&mut self, value: &impl Serialize) -> Value {
        let allowance = self.node_left.min(self.run_left);
        let mut buffer = CappedBuffer {
            bytes: Vec::new(),
            limit: allowance,
        };
        let result = serde_json::to_writer(&mut buffer, value);
        let charged = if result.is_ok() {
            buffer.bytes.len()
        } else {
            allowance
        };
        self.node_left -= charged;
        self.run_left -= charged;
        if result.is_err() {
            return byte_marker();
        }
        serde_json::from_slice(&buffer.bytes).unwrap_or_else(|_| byte_marker())
    }
}

fn byte_marker() -> Value {
    json!({"__zf_trace_summary": "bytes", "reason": "capture budget exhausted"})
}

struct CappedBuffer {
    bytes: Vec<u8>,
    limit: usize,
}

impl Write for CappedBuffer {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if bytes.len() > self.limit.saturating_sub(self.bytes.len()) {
            return Err(io::Error::other("trace capture byte budget"));
        }
        self.bytes.extend_from_slice(bytes);
        Ok(bytes.len())
    }
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn private_key(key: &str) -> bool {
    matches!(
        key,
        "__zf_private_redact" | "__zf_private_trace_redact" | "__zf_private_redact_except_paths"
    )
}

/// Borrowed traversal frames avoid allocating an iterator box for every row.
enum ScanFrame<'a> {
    One(Option<&'a Value>),
    Array(std::slice::Iter<'a, Value>),
    Object(serde_json::map::Iter<'a>),
}
impl<'a> ScanFrame<'a> {
    fn next(&mut self) -> Option<&'a Value> {
        match self {
            Self::One(item) => item.take(),
            Self::Array(items) => items.next(),
            Self::Object(items) => items
                .find(|(key, _)| !private_key(key))
                .map(|(_, item)| item),
        }
    }
}

struct Secrets<'a> {
    tokens: Vec<&'a str>,
    exceptions: Vec<Vec<&'a str>>,
}

impl<'a> Secrets<'a> {
    fn discover(value: &'a Value) -> Self {
        let mut result = Self {
            tokens: Vec::new(),
            exceptions: Vec::new(),
        };
        if let Some(paths) = value
            .get("__zf_private_redact_except_paths")
            .and_then(Value::as_array)
        {
            for path in paths {
                let parts: Vec<_> = match path {
                    Value::String(path) => path
                        .split('.')
                        .map(str::trim)
                        .filter(|s| !s.is_empty())
                        .collect(),
                    Value::Array(path) => path
                        .iter()
                        .filter_map(Value::as_str)
                        .map(str::trim)
                        .filter(|s| !s.is_empty())
                        .collect(),
                    _ => Vec::new(),
                };
                if !parts.is_empty() {
                    result.exceptions.push(parts);
                }
            }
        }
        let mut seen = HashSet::new();
        // Iterator stack is O(depth), not O(array length); omitted data is
        // scanned without allocating a parallel list of references to it.
        let mut stack = vec![ScanFrame::One(Some(value))];
        while let Some(iter) = stack.last_mut() {
            let Some(item) = iter.next() else {
                stack.pop();
                continue;
            };
            match item {
                Value::Object(map) => {
                    for key in ["__zf_private_trace_redact", "__zf_private_redact"] {
                        if let Some(items) = map.get(key).and_then(Value::as_array) {
                            for token in items
                                .iter()
                                .filter_map(Value::as_str)
                                .map(str::trim)
                                .filter(|s| !s.is_empty())
                            {
                                if seen.insert(token) {
                                    result.tokens.push(token);
                                }
                            }
                        }
                    }
                    stack.push(ScanFrame::Object(map.iter()));
                }
                Value::Array(items) => stack.push(ScanFrame::Array(items.iter())),
                _ => {}
            }
        }
        result
    }
}

struct View<'a> {
    value: &'a Value,
    secrets: &'a Secrets<'a>,
    limits: &'a TraceCaptureLimits,
    depth: u32,
    wire_depth: u32,
    path: Vec<&'a str>,
    masked: bool,
    excepted: bool,
    config: bool,
}

impl View<'_> {
    fn child<'a>(&'a self, value: &'a Value, key: Option<&'a str>) -> View<'a> {
        let mut path = self.path.clone();
        if let Some(key) = key {
            path.push(key);
        }
        let excepted = self.excepted || (!self.config && self.secrets.exceptions.contains(&path));
        let sensitive = key.is_some_and(|key| {
            if self.config {
                crate::pipeline::engines::basic::is_sensitive_trace_config_key(key)
            } else {
                crate::pipeline::nodes::basic::trigger::webhook::is_sensitive_payload_key(key)
            }
        });
        View {
            value,
            secrets: self.secrets,
            limits: self.limits,
            depth: self.depth + 1,
            // A sampled array adds a summary object around its preview array.
            wire_depth: self.wire_depth
                + if self
                    .value
                    .as_array()
                    .is_some_and(|items| sample_count(items.len(), self.limits) < items.len())
                {
                    2
                } else {
                    1
                },
            path,
            masked: self.masked || (!excepted && sensitive),
            excepted,
            config: self.config,
        }
    }
}

impl Serialize for View<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if self.masked
            && (self.config
                || !matches!(
                    self.value,
                    Value::Null | Value::Bool(_) | Value::Array(_) | Value::Object(_)
                ))
        {
            return serializer.serialize_str(REDACTED);
        }
        match self.value {
            Value::Array(items) => {
                if self.depth >= self.limits.max_depth || self.wire_depth >= 112 {
                    return json!({"__zf_trace_summary":"array","len":items.len(),"reason":"depth"}).serialize(serializer);
                }
                let count = sample_count(items.len(), self.limits);
                if count < items.len() {
                    let mut map = serializer.serialize_map(Some(4))?;
                    map.serialize_entry("__zf_trace_summary", "array")?;
                    map.serialize_entry("len", &items.len())?;
                    map.serialize_entry("omitted", &(items.len() - count))?;
                    map.serialize_entry(
                        "preview",
                        &Preview {
                            parent: self,
                            items: &items[..count],
                        },
                    )?;
                    map.end()
                } else {
                    Preview {
                        parent: self,
                        items,
                    }
                    .serialize(serializer)
                }
            }
            Value::Object(map) => {
                if self.depth >= self.limits.max_depth || self.wire_depth >= 112 {
                    return json!({"__zf_trace_summary":"object","keys":map.len(),"reason":"depth"}).serialize(serializer);
                }
                let mut out = serializer.serialize_map(None)?;
                for (key, value) in map {
                    // `ui` and `preview` are canvas presentation the engine never
                    // reads; a trace of the run has no use for either.
                    if private_key(key) || (self.config && (key == "ui" || key == "preview")) {
                        continue;
                    }
                    out.serialize_entry(key, &self.child(value, Some(key)))?;
                }
                out.end()
            }
            Value::String(text) => {
                let chars = text.chars().count();
                let cap = self.limits.max_string_chars as usize;
                let (preview, truncated) = redacted_preview(
                    text,
                    if self.excepted {
                        &[]
                    } else {
                        &self.secrets.tokens
                    },
                    cap,
                );
                if truncated {
                    json!({"__zf_trace_summary":"string","chars":chars,"preview":preview})
                        .serialize(serializer)
                } else {
                    serializer.serialize_str(&preview)
                }
            }
            value => value.serialize(serializer),
        }
    }
}

/// What a masked value reads as, everywhere.
pub(crate) const REDACTED: &str = "โ€ขโ€ขโ€ขโ€ขโ€ขโ€ข";

/// Replace the value at every declared path with the redaction marker.
///
/// Rule 3 by position. Operates on a clone destined for the record โ€” the value
/// the next node receives is never touched, because a level shapes the record
/// and never the run.
///
/// JSON Pointer with one extension: `*` matches a single object member or array
/// element. No recursive descent, filters or expressions โ€” an unknown-depth
/// response is protected by masking its containing subtree, which is simpler to
/// reason about than searching for guessed names at unknown depth. A path that
/// matches nothing is silently fine; shapes differ between API versions and a
/// missing optional field is not an error.
pub fn mask_secret_paths(value: &Value, paths: &[String]) -> Value {
    let mut out = value.clone();
    for path in paths {
        let segments: Vec<&str> = path
            .trim_start_matches('/')
            .split('/')
            .filter(|s| !s.is_empty())
            .collect();
        if !segments.is_empty() {
            mask_at(&mut out, &segments);
        }
    }
    out
}

fn mask_at(value: &mut Value, segments: &[&str]) {
    let Some((head, rest)) = segments.split_first() else {
        *value = Value::String(REDACTED.to_string());
        return;
    };
    match value {
        Value::Object(map) => {
            if *head == "*" {
                for child in map.values_mut() {
                    mask_at(child, rest);
                }
            } else if let Some(child) = map.get_mut(*head) {
                mask_at(child, rest);
            }
        }
        Value::Array(items) => {
            if *head == "*" {
                for child in items.iter_mut() {
                    mask_at(child, rest);
                }
            } else if let Ok(index) = head.parse::<usize>() {
                if let Some(child) = items.get_mut(index) {
                    mask_at(child, rest);
                }
            }
        }
        _ => {}
    }
}

/// Capture one payload at given limits with given confidential values.
/// Test-only door onto the real capture path.
#[doc(hidden)]
pub fn capture_for_test(
    limits: TraceCaptureLimits,
    confidential: Vec<String>,
    value: &Value,
) -> Value {
    let mut capture = TraceCapture::new(limits).with_confidential(confidential);
    capture.begin_node();
    capture.capture(value)
}

/// Redact declared literal secrets throughout an execution string using the
/// same overlap policy as trace previews. No capture limit applies: unrelated
/// text is retained in full. Empty tokens are ignored, as in the node contract.
pub(crate) fn redact_literal_secrets(text: &str, tokens: &[String]) -> String {
    let tokens: Vec<_> = tokens
        .iter()
        .map(String::as_str)
        .filter(|token| !token.is_empty())
        .collect();
    redacted_preview(text, &tokens, usize::MAX).0
}

/// Walk the original string so truncation can never expose the prefix of a
/// secret cut by the preview boundary. Retain at most `cap` output characters;
/// token matches consume borrowed input without copying the token or its tail.
/// Overlapping occurrences form one masked range, independently of token order:
/// declaring `abc` and `bcdef` masks all of `abcdef`, including the shared tail.
fn redacted_preview(text: &str, tokens: &[&str], cap: usize) -> (String, bool) {
    if tokens.is_empty() {
        let end = text
            .char_indices()
            .nth(cap)
            .map(|(i, _)| i)
            .unwrap_or(text.len());
        return (text[..end].to_owned(), end < text.len());
    }
    let mut output = String::with_capacity(text.len().min(cap));
    let mut rest = text;
    let mut written = 0;
    while !rest.is_empty() && written < cap {
        if let Some(token) = tokens
            .iter()
            .filter(|token| rest.starts_with(**token))
            .max_by_key(|token| token.len())
        {
            rest = &rest[overlapping_secret_end(rest, tokens, token.len())..];
            let mask_chars = (cap - written).min(6);
            for _ in 0..mask_chars {
                output.push('โ€ข');
            }
            written += mask_chars;
        } else {
            let ch = rest.chars().next().expect("nonempty string");
            output.push(ch);
            written += 1;
            rest = &rest[ch.len_utf8()..];
        }
    }
    (output, !rest.is_empty())
}

/// Extend a known secret prefix through the union of overlapping occurrences.
/// Only matches crossing the current boundary can extend it, so each search
/// borrows at most a two-token-width window. Searching from its end skips
/// redundant interior matches in long repeated secrets without allocating an
/// occurrence list. Adjacent occurrences remain separate masks.
fn overlapping_secret_end(text: &str, tokens: &[&str], mut end: usize) -> usize {
    loop {
        let previous = end;
        for token in tokens {
            // A one-byte token cannot overlap and extend another byte range.
            if token.len() <= 1 {
                continue;
            }
            let mut start = end.saturating_sub(token.len() - 1);
            while !text.is_char_boundary(start) {
                start += 1;
            }
            let mut limit = end.saturating_add(token.len() - 1).min(text.len());
            while !text.is_char_boundary(limit) {
                limit -= 1;
            }
            if let Some(offset) = text[start..limit].rfind(token) {
                end = end.max(start + offset + token.len());
            }
        }
        if end == previous || end == text.len() {
            return end;
        }
    }
}

fn sample_count(len: usize, limits: &TraceCaptureLimits) -> usize {
    if limits.array_sample_count == 0 {
        len
    } else {
        len.min(limits.array_sample_count as usize)
    }
}

struct Preview<'a> {
    parent: &'a View<'a>,
    items: &'a [Value],
}
impl Serialize for Preview<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.items.len()))?;
        for item in self.items {
            seq.serialize_element(&self.parent.child(item, None))?;
        }
        seq.end()
    }
}

struct Emissions<'a> {
    outputs: &'a [NodeExecutionOutput],
    limits: TraceCaptureLimits,
}
impl Serialize for Emissions<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(2))?;
        map.serialize_entry("count", &self.outputs.len())?;
        map.serialize_entry("emissions", &EmissionArray(self))?;
        map.end()
    }
}

struct EmissionArray<'a>(&'a Emissions<'a>);
impl Serialize for EmissionArray<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let count = sample_count(self.0.outputs.len(), &self.0.limits);
        if count == self.0.outputs.len() {
            return EmissionItems(self.0, count).serialize(serializer);
        }
        let mut map = serializer.serialize_map(Some(4))?;
        map.serialize_entry("__zf_trace_summary", "array")?;
        map.serialize_entry("len", &self.0.outputs.len())?;
        map.serialize_entry("omitted", &(self.0.outputs.len() - count))?;
        map.serialize_entry("preview", &EmissionItems(self.0, count))?;
        map.end()
    }
}

struct EmissionItems<'a>(&'a Emissions<'a>, usize);
impl Serialize for EmissionItems<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.1))?;
        for out in &self.0.outputs[..self.1] {
            let secrets = Secrets::discover(&out.payload);
            seq.serialize_element(&View {
                value: &out.payload,
                secrets: &secrets,
                limits: &self.0.limits,
                depth: 0,
                wire_depth: 0,
                path: Vec::new(),
                masked: false,
                excepted: false,
                config: false,
            })?;
        }
        seq.end()
    }
}