agent-first-data 0.39.1

A naming convention that lets AI agents understand your data without being told what it means, plus the afdata CLI and a Rust library for reading Markdown structure and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
mod url;

use self::url::{redact_url_field_value, redact_url_in_str, redact_urls_in_text_with_context};
use crate::document::PathStep;
use serde_json::Value;
use std::collections::HashSet;

// ═══════════════════════════════════════════
// Public API: Output Formatters
// ═══════════════════════════════════════════

/// Which fields a [`Redactor`] scrubs. The default is [`RedactionPolicy::All`].
///
/// The policy selects a *scope* inside a structured value. A command line
/// ([`Redactor::argv`]) and a bare URL string ([`Redactor::url`]) have no
/// `result`/`trace` split to scope to, so on those two paths `TraceOnly`
/// redacts in full like `All`, and only [`RedactionPolicy::Off`] turns
/// redaction off.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RedactionPolicy {
    /// Redact every secret field anywhere in the value (the default).
    #[default]
    All,
    /// Redact only inside the top-level `trace` object.
    TraceOnly,
    /// Do not redact anything.
    Off,
}

impl RedactionPolicy {
    /// Whether this policy redacts an input that carries no scope of its own —
    /// a command line or a single URL string, as opposed to a JSON value with a
    /// `trace` object to narrow to.
    ///
    /// `TraceOnly` narrows *where* redaction applies within a value; it does not
    /// weaken redaction. A standalone argv or URL has no non-`trace` half to
    /// leave alone — and both are diagnostic material by construction, the very
    /// thing `TraceOnly` scrubs — so `TraceOnly` redacts them in full, exactly
    /// like `All`. Only `Off`, the caller explicitly asking for raw output,
    /// disables redaction, and it does so on all three paths alike.
    fn redacts_unscoped_input(self) -> bool {
        !matches!(self, RedactionPolicy::Off)
    }
}

/// Rendering style for plain (logfmt) output only. JSON and YAML are always
/// structure-preserving and ignore this.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlainStyle {
    /// Human-readable AFDATA rendering: strip suffixes and format values.
    #[default]
    Readable,
    /// Schema-preserving rendering: keep keys and values unchanged after redaction.
    Raw,
}

/// Configurable redaction builder for secrets and legacy field names.
///
/// `Redactor` encapsulates redaction policy, custom secret field names, and
/// exact legacy URL field names.
/// Build with [`Redactor::new()`], configure via builder methods, then pass to
/// redaction functions like [`redacted_value`] or [`redact_url_secrets`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Redactor {
    policy: RedactionPolicy,
    secret_names: Vec<String>,
    url_names: Vec<String>,
    reveal_names: Vec<String>,
}

impl Redactor {
    /// Create a new default redactor (full redaction, no custom secret names).
    pub fn new() -> Self {
        Self::default()
    }

    /// Set custom field names to treat as secrets in addition to `_secret` suffixes.
    ///
    /// Matching is exact field-name equality at any nesting level. The same
    /// list also matches URL query-parameter names inside `_url` fields.
    /// Builder style: returns `self`.
    pub fn secret_names<I: IntoIterator<Item = S>, S: Into<String>>(mut self, names: I) -> Self {
        self.secret_names = names.into_iter().map(|s| s.into()).collect();
        self
    }

    /// Set exact legacy field names whose values should receive URL-aware
    /// redaction in addition to `_url`/`_URL` suffixed fields.
    ///
    /// A matching string is handled like an `_url` value. Arrays and nested
    /// collections recursively apply that treatment to every string leaf.
    /// Matching is exact and does not normalize case, whitespace, or spelling.
    #[must_use]
    pub fn url_names<I: IntoIterator<Item = S>, S: Into<String>>(mut self, names: I) -> Self {
        self.url_names = names.into_iter().map(Into::into).collect();
        self
    }

    /// Reveal exactly these structured field names at any depth. Other secrets
    /// remain masked; URL parameters and argv never use this exception.
    #[must_use]
    pub fn reveal_names<I: IntoIterator<Item = S>, S: Into<String>>(mut self, names: I) -> Self {
        self.reveal_names = names.into_iter().map(Into::into).collect();
        self
    }

    /// Set the redaction policy (default: full redaction).
    /// Builder style: returns `self`.
    pub fn policy(mut self, policy: RedactionPolicy) -> Self {
        self.policy = policy;
        self
    }

    /// Redact a JSON value copy using this redactor's policy and secret names.
    ///
    /// Clones `value` first; for a large payload you already own and can
    /// mutate, prefer [`Redactor::redact_in_place`] to avoid the copy.
    pub fn value(&self, value: &Value) -> Value {
        let mut v = value.clone();
        self.redact_in_place(&mut v);
        v
    }

    /// Redact `value` as the node found at `path` inside a larger value: the
    /// result is exactly what that node looks like in [`Redactor::value`] of
    /// the whole.
    ///
    /// Taking a node out of its document drops the names above it, and those
    /// names are what redaction reads. So `path` carries them back: an object
    /// key on it that is secret (by `_secret` suffix or `secret_names`, and not
    /// in `reveal_names`) masks the node whole — to `***`, except that a node
    /// which is itself the secret field and is `null` stays `null`, as it does
    /// in the whole. A key on it that is a URL field (`_url` suffix or
    /// `url_names`) scrubs credentials from every string the node holds. The
    /// policy scopes the same way too: under [`RedactionPolicy::TraceOnly`]
    /// only a path into the top-level `trace` object is redacted.
    ///
    /// `path` is the structural route — [`PathStep::Field`] for each object key,
    /// [`PathStep::Element`] for each array element — as
    /// [`document::locate`](crate::document::locate) returns it. An
    /// identifier that selected an element is not a key on the route, so it
    /// never makes the element secret; the element's own keys still do.
    pub fn value_at(&self, path: &[PathStep], value: &Value) -> Value {
        let mut v = value.clone();
        self.redact_in_place_at(path, &mut v);
        v
    }

    /// [`Redactor::value_at`] without the copy.
    pub fn redact_in_place_at(&self, path: &[PathStep], value: &mut Value) {
        // The empty route is the whole value, which the policy scopes itself.
        if path.is_empty() {
            return self.redact_in_place(value);
        }
        let Some(scope) = self.scope_of(path) else {
            return;
        };
        let context = RedactionContext::from_redactor(self);
        match judge_route(scope, &context) {
            Route::Masked { at_node } => {
                // The null exemption belongs to the secret field itself. A node
                // below one was inside a value the whole render hides.
                if !(at_node && value.is_null()) {
                    *value = Value::String(REDACTED_MARKER.into());
                }
            }
            Route::TooDeep => *value = Value::String(MAX_DEPTH_MARKER.into()),
            Route::Url => redact_url_value_depth(value, &context, scope.len()),
            Route::Plain => redact_secrets_with_context_depth(value, &context, scope.len()),
        }
    }

    /// Whether the node at `path` is secret by name: some object key on the
    /// route is secret and not revealed, within the policy's scope. This is
    /// the gate for a caller about to print the raw node rather than its
    /// redacted form. A URL field on the route does not count: whether its
    /// strings carry a credential is a question about the value, which
    /// [`Redactor::value_at`] answers.
    pub fn is_secret_path(&self, path: &[PathStep]) -> bool {
        let Some(scope) = self.scope_of(path) else {
            return false;
        };
        let context = RedactionContext::from_redactor(self);
        scope.iter().any(|step| match step {
            PathStep::Field(key) => context.is_masked_key(key),
            PathStep::Element => false,
        })
    }

    /// The part of `path` this redactor's policy judges, measured from the
    /// root its walk starts at; `None` when the policy leaves the node alone.
    fn scope_of<'p>(&self, path: &'p [PathStep]) -> Option<&'p [PathStep]> {
        match self.policy {
            RedactionPolicy::All => Some(path),
            // The whole render walks `trace` as its own root, so its route
            // starts below that key.
            RedactionPolicy::TraceOnly => match path.split_first() {
                Some((PathStep::Field(key), rest)) if key == "trace" => Some(rest),
                _ => None,
            },
            RedactionPolicy::Off => None,
        }
    }

    /// Redact secret components of a URL string using this redactor's settings.
    ///
    /// A query parameter is redacted iff its (form-decoded) name ends in
    /// `_secret`/`_SECRET` or matches an exact entry in `secret_names`. A
    /// fragment written in the same `k=v&k=v` shape — how an OAuth implicit-flow
    /// response carries its token — is redacted by that same rule; any other
    /// fragment passes through byte-for-byte. The userinfo password
    /// (`scheme://user:pass@host`) is always redacted as a structural rule.
    /// Only the secret spans are replaced with `***`; every other byte is
    /// preserved. A string that is not a single, whitespace-free,
    /// scheme-prefixed URL (including a URL embedded in surrounding prose) is
    /// returned unchanged.
    ///
    /// A URL is unscoped input: `RedactionPolicy::Off` returns it unchanged,
    /// every other policy redacts it in full.
    pub fn url(&self, url: &str) -> String {
        if !self.policy.redacts_unscoped_input() {
            return url.to_string();
        }
        let context = RedactionContext::from_redactor(self);
        redact_url_in_str(url, &context).unwrap_or_else(|| url.to_string())
    }

    /// Redact complete scheme-prefixed URLs embedded in prose.
    ///
    /// This is deliberately explicit and independent from structured field
    /// redaction. It recognizes URL spans only; it never scans surrounding text
    /// for secret-looking names or values.
    pub fn urls_in_text(&self, text: &str) -> String {
        if !self.policy.redacts_unscoped_input() {
            return text.to_string();
        }
        let context = RedactionContext::from_redactor(self);
        redact_urls_in_text_with_context(text, &context)
    }

    /// Redact `value` in place, using this redactor's policy and secret names.
    ///
    /// The zero-copy counterpart of [`Redactor::value`] — use it on a large
    /// payload you already own to avoid cloning.
    pub fn redact_in_place(&self, value: &mut Value) {
        let context = RedactionContext::from_redactor(self);
        apply_redaction_policy_with_context(value, self.policy, &context);
    }

    /// Redact secret *values* out of a command line, using this redactor's
    /// policy and secret names.
    ///
    /// A long flag whose name is secret by AFDATA naming (`--api-key-secret`,
    /// or an exact `secret_names` entry) has its value replaced by `***`, in
    /// both `--flag=value` and `--flag value` spellings. Everything else is
    /// preserved byte-for-byte.
    ///
    /// Free text is deliberately never scanned: a bare `api_key_secret=sk-live`
    /// positional, or a secret-looking token after a non-secret flag, is left
    /// alone. AFDATA decides sensitivity from the *field name*, and argv is no
    /// exception — rename the flag rather than pattern-matching values. A flag
    /// with no value (end of argv, or followed by another flag) is likewise
    /// left inspectable.
    ///
    /// Only long (`--`) flags are recognized, matching the convention's
    /// long-flags-only rule.
    ///
    /// A command line is unscoped input: `RedactionPolicy::Off` returns `args`
    /// unchanged, every other policy redacts in full.
    pub fn argv<S: AsRef<str>>(&self, args: &[S]) -> Vec<String> {
        if !self.policy.redacts_unscoped_input() {
            return args.iter().map(|arg| arg.as_ref().to_string()).collect();
        }
        let context = RedactionContext::from_redactor(self);
        let mut out = Vec::with_capacity(args.len());
        let mut redact_next = false;
        for arg in args {
            let arg = arg.as_ref();
            if redact_next {
                redact_next = false;
                if !arg.starts_with("--") {
                    out.push(REDACTED_MARKER.to_string());
                    continue;
                }
            }
            if let Some(rest) = arg.strip_prefix("--") {
                if let Some((name, _)) = rest.split_once('=') {
                    if is_secret_flag_name(name, &context) {
                        out.push(format!("--{name}={REDACTED_MARKER}"));
                        continue;
                    }
                } else if is_secret_flag_name(rest, &context) {
                    redact_next = true;
                }
            }
            out.push(arg.to_string());
        }
        out
    }

    /// True when `name` would be treated as a secret field name by this
    /// redactor: an exact `_secret`/`_SECRET` suffix, or an exact match
    /// against a configured `secret_names` entry.
    ///
    /// This judges one name. A value taken out of a document is judged by its
    /// whole route instead — a secret ancestor hides it as surely as a secret
    /// leaf, and an identifier that selected an array element is not a name at
    /// all — so use [`Redactor::is_secret_path`] and [`Redactor::value_at`]
    /// there rather than testing the path's last segment with this.
    pub fn is_secret_name(&self, name: &str) -> bool {
        RedactionContext::from_redactor(self).is_secret_key(name)
    }

    /// True when `name` receives URL-aware structured-field redaction: an
    /// exact `_url`/`_URL` suffix or an exact configured `url_names` entry.
    ///
    /// The counterpart to [`Redactor::is_secret_name`], with the same caveat:
    /// for a value taken out of a document, [`Redactor::value_at`] applies the
    /// URL scrubbing its route calls for.
    pub fn is_url_name(&self, name: &str) -> bool {
        RedactionContext::from_redactor(self).is_url_key(name)
    }
}

impl From<RedactionPolicy> for Redactor {
    fn from(policy: RedactionPolicy) -> Self {
        Self {
            policy,
            secret_names: Vec::new(),
            url_names: Vec::new(),
            reveal_names: Vec::new(),
        }
    }
}

/// Output options combining redaction and rendering style.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct OutputOptions {
    /// Redactor applied before rendering.
    pub redaction: Redactor,
    /// Rendering style for plain output only.
    pub style: PlainStyle,
}

impl From<RedactionPolicy> for OutputOptions {
    fn from(policy: RedactionPolicy) -> Self {
        Self {
            redaction: Redactor::from(policy),
            style: PlainStyle::default(),
        }
    }
}

// ═══════════════════════════════════════════
// Public API: Redaction & Utility
// ═══════════════════════════════════════════

/// Return a JSON value copy with default `_secret` redaction applied.
pub fn redacted_value(value: &Value) -> Value {
    Redactor::new().value(value)
}

/// Redact secret values out of a command line, using default options.
///
/// Returns `args` with the value of every `_secret`-suffixed long flag replaced
/// by `***`, covering both `--flag=value` and `--flag value`. Use
/// [`Redactor::argv`] for custom `secret_names` or a non-default policy.
///
/// Intended for CLIs that record their own invocation — startup diagnostics,
/// audit trails, crash reports — where writing argv verbatim would put a
/// credential in the log.
pub fn redact_argv<S: AsRef<str>>(args: &[S]) -> Vec<String> {
    Redactor::new().argv(args)
}

/// Redact secret components of a single URL string, using default options.
///
/// Returns `url` with its userinfo password and any `_secret`-suffixed query
/// parameter values replaced by `***`.
pub fn redact_url_secrets(url: &str) -> String {
    Redactor::new().url(url)
}

/// Redact complete scheme-prefixed URLs embedded in prose, using default
/// secret-name rules.
///
/// This helper is opt-in. Ordinary structured redaction never scans prose.
pub fn redact_urls_in_text(text: &str) -> String {
    Redactor::new().urls_in_text(text)
}

// ═══════════════════════════════════════════
// Secret Redaction
// ═══════════════════════════════════════════

/// The scalar every redacted span, value, and subtree is replaced with. Also
/// the signal plain rendering reads to tell a hidden field from a live one.
pub(crate) const REDACTED_MARKER: &str = "***";

#[derive(Default)]
pub(crate) struct RedactionContext {
    secret_names: HashSet<String>,
    url_names: HashSet<String>,
    reveal_names: HashSet<String>,
}

impl RedactionContext {
    fn from_redactor(redactor: &Redactor) -> Self {
        let secret_names = redactor.secret_names.iter().cloned().collect();
        let url_names = redactor.url_names.iter().cloned().collect();
        Self {
            secret_names,
            url_names,
            reveal_names: redactor.reveal_names.iter().cloned().collect(),
        }
    }

    fn is_secret_key(&self, key: &str) -> bool {
        key_has_secret_suffix(key) || self.secret_names.contains(key)
    }

    fn is_url_key(&self, key: &str) -> bool {
        key_has_url_suffix(key) || self.url_names.contains(key)
    }

    /// A field whose value the structured walk replaces: secret, and not one
    /// of the names the caller chose to reveal.
    fn is_masked_key(&self, key: &str) -> bool {
        self.is_secret_key(key) && !self.reveal_names.contains(key)
    }
}

/// How the structured walk treats the node at the end of a route, decided by
/// the keys above it exactly as the walk itself decides on its way down.
enum Route {
    /// A masked key is on the route; `at_node` when it is the route's last step.
    Masked { at_node: bool },
    /// The walk's depth bound is reached before the route ends.
    TooDeep,
    /// A URL field is on the route, so the node is walked in URL mode.
    Url,
    /// Nothing above the node changes how it is walked.
    Plain,
}

fn judge_route(route: &[PathStep], context: &RedactionContext) -> Route {
    let mut in_url = false;
    for (depth, step) in route.iter().enumerate() {
        // The step from a node at this depth to its child is taken while the
        // walk is at that node, which it never reaches past the bound.
        if depth >= MAX_DEPTH {
            return Route::TooDeep;
        }
        let PathStep::Field(key) = step else {
            continue;
        };
        // Same order as the walk: a masked key wins over a URL key, and a URL
        // field's subtree stays in URL mode while still masking secret keys.
        if context.is_masked_key(key) {
            return Route::Masked {
                at_node: depth + 1 == route.len(),
            };
        }
        if context.is_url_key(key) {
            in_url = true;
        }
    }
    if in_url { Route::Url } else { Route::Plain }
}

fn key_has_secret_suffix(key: &str) -> bool {
    key.ends_with("_secret") || key.ends_with("_SECRET")
}

fn key_has_url_suffix(key: &str) -> bool {
    key.ends_with("_url") || key.ends_with("_URL")
}

/// Whether a long flag's name is secret, normalizing the kebab-case flag
/// spelling to the snake_case field spelling the convention is defined in.
///
/// Ungated: core argv redaction relies on it.
pub(crate) fn is_secret_flag_name(flag_name: &str, context: &RedactionContext) -> bool {
    let normalized = flag_name.replace('-', "_");
    context.is_secret_key(&normalized) || context.is_secret_key(flag_name)
}

const MAX_DEPTH: usize = 256;
const MAX_DEPTH_MARKER: &str = "<afdata:max-depth>";

fn redact_secrets_with_context(value: &mut Value, context: &RedactionContext) {
    redact_secrets_with_context_depth(value, context, 0);
}

fn redact_secrets_with_context_depth(value: &mut Value, context: &RedactionContext, depth: usize) {
    if depth >= MAX_DEPTH {
        *value = Value::String(MAX_DEPTH_MARKER.into());
        return;
    }
    match value {
        Value::Object(map) => {
            let keys: Vec<String> = map.keys().cloned().collect();
            for key in keys {
                if context.is_masked_key(&key) {
                    // A null secret is an *absent* secret. Masking it would
                    // manufacture the appearance of a configured credential:
                    // readers cannot tell `"***"`-because-set from
                    // `"***"`-because-null, so a tool showing its own config
                    // would report every unset secret as configured. Redaction
                    // hides a value that exists; it does not invent one.
                    if !map.get(&key).is_some_and(Value::is_null) {
                        map.insert(key, Value::String(REDACTED_MARKER.into()));
                    }
                } else if context.is_url_key(&key) {
                    if let Some(v) = map.get_mut(&key) {
                        redact_url_value_depth(v, context, depth + 1);
                    }
                } else if let Some(v) = map.get_mut(&key) {
                    redact_secrets_with_context_depth(v, context, depth + 1);
                }
            }
        }
        Value::Array(arr) => {
            for v in arr {
                redact_secrets_with_context_depth(v, context, depth + 1);
            }
        }
        _ => {}
    }
}

fn redact_url_value_depth(value: &mut Value, context: &RedactionContext, depth: usize) {
    if depth >= MAX_DEPTH {
        *value = Value::String(MAX_DEPTH_MARKER.into());
        return;
    }
    match value {
        Value::String(text) => {
            *text = redact_url_field_value(text, context);
        }
        Value::Array(values) => {
            for value in values {
                redact_url_value_depth(value, context, depth + 1);
            }
        }
        Value::Object(values) => {
            let keys = values.keys().cloned().collect::<Vec<_>>();
            for key in keys {
                if context.is_masked_key(&key) {
                    if !values.get(&key).is_some_and(Value::is_null) {
                        values.insert(key, Value::String(REDACTED_MARKER.into()));
                    }
                } else if let Some(value) = values.get_mut(&key) {
                    redact_url_value_depth(value, context, depth + 1);
                }
            }
        }
        _ => {}
    }
}

/// Redact secret components of a single URL string, returning `Some(redacted)`
/// when `s` is a processable URL, or `None` when it is not (so callers can keep
/// the original). Only secret spans change; all other bytes are preserved.
fn apply_redaction_policy_with_context(
    value: &mut Value,
    redaction_policy: RedactionPolicy,
    context: &RedactionContext,
) {
    match redaction_policy {
        RedactionPolicy::All => redact_secrets_with_context(value, context),
        RedactionPolicy::TraceOnly => {
            if let Value::Object(map) = value
                && let Some(trace) = map.get_mut("trace")
            {
                redact_secrets_with_context(trace, context);
            }
        }
        RedactionPolicy::Off => {}
    }
}

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

    // ── A node out of its document keeps its route ──────────

    fn routed_document() -> Value {
        json!({
            "name": "console",
            "endpoint_url": "https://reviewer:pw@h/?token_secret=t&page=2",
            "mirror_url": [
                "https://u:pw@a/",
                {"nested": "https://u:pw@b/", "key_secret": "k", "plain": "mailto:x@y.z"}
            ],
            "vault_secret": {"inner": {"leaf": "x"}, "list": [1, 2], "gone": null},
            "absent_secret": null,
            "api_token": "configured-name",
            "servers": [
                {"name": "api_secret", "port": 1, "password_secret": "p", "hook_url": "https://u:pw@d/"}
            ],
            "trace": {"session_secret": "s", "callback_url": "https://u:pw@c/", "step": 3},
            "shown_secret": "visible"
        })
    }

    fn compare_nodes(redactor: &Redactor, raw: &Value, shown: &Value, route: &mut Vec<PathStep>) {
        assert_eq!(redactor.value_at(route, raw), *shown, "{route:?}");
        match raw {
            Value::Object(map) => {
                for (key, child) in map {
                    route.push(PathStep::Field(key.clone()));
                    compare_nodes(redactor, child, shown.get(key).unwrap_or(shown), route);
                    route.pop();
                }
            }
            Value::Array(items) => {
                for (index, child) in items.iter().enumerate() {
                    route.push(PathStep::Element);
                    compare_nodes(redactor, child, shown.get(index).unwrap_or(shown), route);
                    route.pop();
                }
            }
            _ => {}
        }
    }

    #[test]
    fn a_routed_node_equals_the_same_node_in_the_redacted_whole() {
        let document = routed_document();
        for policy in [
            RedactionPolicy::All,
            RedactionPolicy::TraceOnly,
            RedactionPolicy::Off,
        ] {
            let redactor = Redactor::new()
                .policy(policy)
                .secret_names(["api_token"])
                .reveal_names(["shown_secret"]);
            let whole = redactor.value(&document);
            compare_nodes(&redactor, &document, &whole, &mut Vec::new());
        }
    }

    #[test]
    fn a_route_carries_secret_ancestors_url_fields_and_absent_secrets() {
        let document = routed_document();
        let redactor = Redactor::new().secret_names(["api_token"]);
        let at = |path: &str| {
            let document = crate::document::Value::from(document.clone());
            let node =
                crate::document::locate(&document, path, crate::document::Addressing::INDEX_ONLY)
                    .unwrap();
            let value = Value::try_from(node.value).unwrap();
            (
                redactor.value_at(&node.steps, &value),
                redactor.is_secret_path(&node.steps),
            )
        };
        let key = |name: &str| PathStep::Field(name.to_string());

        // A child beneath a secret ancestor is hidden, even a null one.
        assert_eq!(at("vault_secret.inner.leaf"), (json!("***"), true));
        assert_eq!(at("vault_secret.list.0"), (json!("***"), true));
        assert_eq!(at("vault_secret.gone"), (json!("***"), true));
        // The secret field itself stays null when it is null.
        assert_eq!(at("absent_secret"), (Value::Null, true));
        // A configured exact name counts like the suffix.
        assert_eq!(at("api_token"), (json!("***"), true));
        // A URL field scrubs the selected string, and each element of a
        // URL collection, without hiding the readable parts.
        assert_eq!(
            at("endpoint_url"),
            (
                json!("https://reviewer:***@h/?token_secret=***&page=2"),
                false
            )
        );
        assert_eq!(at("mirror_url.0"), (json!("https://u:***@a/"), false));
        assert_eq!(
            at("mirror_url.1.nested"),
            (json!("https://u:***@b/"), false)
        );
        // A plain field is itself.
        assert_eq!(at("name"), (json!("console"), false));
        // Revealing a name lifts exactly that name.
        let revealing = Redactor::new().reveal_names(["shown_secret"]);
        assert_eq!(
            revealing.value_at(&[key("shown_secret")], &json!("visible")),
            json!("visible")
        );
        assert!(!revealing.is_secret_path(&[key("shown_secret")]));
    }

    #[test]
    fn an_identifier_that_selects_an_element_is_data_not_a_field_name() {
        use crate::document::{self, Addressing, KeyedList};
        let source = document::Value::from(routed_document());
        let lists = [KeyedList {
            prefix: "servers",
            slug_field: "name",
        }];
        let located =
            document::locate(&source, "servers.api_secret", Addressing::keyed(&lists)).unwrap();
        assert_eq!(
            located.steps,
            vec![PathStep::Field("servers".to_string()), PathStep::Element]
        );
        let redactor = Redactor::new();
        assert!(!redactor.is_secret_path(&located.steps));
        let element = Value::try_from(located.value).unwrap();
        // The element's own keys still count.
        assert_eq!(
            redactor.value_at(&located.steps, &element),
            json!({"name": "api_secret", "port": 1, "password_secret": "***", "hook_url": "https://u:***@d/"})
        );

        let located = document::locate(
            &source,
            "servers.api_secret.password_secret",
            Addressing::keyed(&lists),
        )
        .unwrap();
        assert!(redactor.is_secret_path(&located.steps));
    }

    #[test]
    fn trace_only_judges_a_route_from_inside_trace() {
        let redactor = Redactor::new().policy(RedactionPolicy::TraceOnly);
        let key = |name: &str| PathStep::Field(name.to_string());
        assert!(redactor.is_secret_path(&[key("trace"), key("session_secret")]));
        assert!(!redactor.is_secret_path(&[key("result"), key("session_secret")]));
        assert_eq!(
            redactor.value_at(&[key("trace")], &json!({"session_secret": "s"})),
            json!({"session_secret": "***"})
        );
        assert_eq!(
            redactor.value_at(&[key("result"), key("session_secret")], &json!("s")),
            json!("s")
        );
    }

    #[test]
    fn a_route_past_the_depth_bound_is_cut_like_the_whole() {
        let mut document = json!("leaf");
        for _ in 0..(MAX_DEPTH + 4) {
            document = json!({ "k": document });
        }
        let redactor = Redactor::new();
        let whole = redactor.value(&document);
        compare_nodes(&redactor, &document, &whole, &mut Vec::new());
    }

    // ── URL fragments carry secrets too ──────────

    #[test]
    fn url_fragment_params_redacted_like_query_params() {
        assert_eq!(
            redact_url_secrets("https://h/p?token_secret=QUERYLEAK#token_secret=FRAGLEAK"),
            "https://h/p?token_secret=***#token_secret=***"
        );
    }

    #[test]
    fn url_fragment_params_redacted_without_a_query() {
        // The OAuth implicit-flow shape: the credential exists only after '#'.
        assert_eq!(
            redact_url_secrets("https://h/cb#access_token_secret=abc&state=xyz"),
            "https://h/cb#access_token_secret=***&state=xyz"
        );
    }

    #[test]
    fn url_fragment_without_params_is_preserved() {
        for url in [
            "https://h/p?a=1#section",
            "https://h/p#",
            "https://h/p#a/b?c",
        ] {
            assert_eq!(redact_url_secrets(url), url);
        }
    }

    #[test]
    fn url_fragment_honors_secret_names() {
        let redactor = Redactor::new().secret_names(vec!["token".to_string()]);
        assert_eq!(
            redactor.url("https://h/cb#token=abc&page=2"),
            "https://h/cb#token=***&page=2"
        );
    }

    #[test]
    fn url_names_are_exact_and_recurse_through_collections() {
        let redactor = Redactor::new().secret_names(["token"]).url_names([
            "url",
            "relays",
            "synapse_selector",
        ]);
        let input = json!({
            "url": "https://u:pw@h/?token=one",
            "URL": "https://u:visible@h/?token=two",
            "relays": [
                "wss://relay.example/?token=three",
                {"nested": "https://u:pw@nested.example/"}
            ],
            "synapse_selector": "user:pass@host/db",
            "other": "https://u:visible@h/?token=four"
        });

        assert_eq!(
            redactor.value(&input),
            json!({
                "url": "https://u:***@h/?token=***",
                "URL": "https://u:visible@h/?token=two",
                "relays": [
                    "wss://relay.example/?token=***",
                    {"nested": "https://u:***@nested.example/"}
                ],
                "synapse_selector": "***",
                "other": "https://u:visible@h/?token=four"
            })
        );
        assert!(redactor.is_url_name("url"));
        assert!(!redactor.is_url_name("URL"));
    }

    #[test]
    fn prose_url_redaction_is_explicit_and_preserves_punctuation() {
        let message = "connect (https://u:pw@h/?token_secret=one), then wss://h/?token_secret=two. bare user:pw@h stays";
        assert_eq!(
            redact_urls_in_text(message),
            "connect (https://u:***@h/?token_secret=***), then wss://h/?token_secret=***. bare user:pw@h stays"
        );
        assert_eq!(
            redacted_value(&json!({"message": message})),
            json!({"message": message})
        );
    }

    #[test]
    fn prose_url_redaction_honors_policy_and_secret_names() {
        let text = "see https://h/?token=abc";
        assert_eq!(
            Redactor::new().secret_names(["token"]).urls_in_text(text),
            "see https://h/?token=***"
        );
        assert_eq!(
            Redactor::new()
                .policy(RedactionPolicy::Off)
                .secret_names(["token"])
                .urls_in_text(text),
            text
        );
    }

    // ── One policy meaning across value, argv, url ──────────

    fn scoped_value() -> Value {
        json!({
            "result": {"api_key_secret": "sk-result"},
            "trace": {"api_key_secret": "sk-trace"}
        })
    }

    fn argv() -> Vec<String> {
        vec!["tool".to_string(), "--api-key-secret=sk-live".to_string()]
    }

    #[test]
    fn all_policy_redacts_every_path() {
        let redactor = Redactor::new().policy(RedactionPolicy::All);
        assert_eq!(
            redactor.value(&scoped_value()),
            json!({
                "result": {"api_key_secret": "***"},
                "trace": {"api_key_secret": "***"}
            })
        );
        assert_eq!(redactor.argv(&argv()), vec!["tool", "--api-key-secret=***"]);
        assert_eq!(
            redactor.url("https://u:pw@h/cb?token_secret=abc"),
            "https://u:***@h/cb?token_secret=***"
        );
    }

    #[test]
    fn trace_only_scopes_a_value_but_redacts_argv_and_url_in_full() {
        let redactor = Redactor::new().policy(RedactionPolicy::TraceOnly);
        // Scoped input: only the `trace` half is scrubbed.
        assert_eq!(
            redactor.value(&scoped_value()),
            json!({
                "result": {"api_key_secret": "sk-result"},
                "trace": {"api_key_secret": "***"}
            })
        );
        // Unscoped input: a command line and a bare URL have no non-`trace`
        // half to leave alone, so they are redacted like `All`.
        assert_eq!(redactor.argv(&argv()), vec!["tool", "--api-key-secret=***"]);
        assert_eq!(
            redactor.url("https://u:pw@h/cb?token_secret=abc"),
            "https://u:***@h/cb?token_secret=***"
        );
    }

    #[test]
    fn off_policy_disables_every_path() {
        let redactor = Redactor::new().policy(RedactionPolicy::Off);
        assert_eq!(redactor.value(&scoped_value()), scoped_value());
        assert_eq!(redactor.argv(&argv()), argv());
        assert_eq!(
            redactor.url("https://u:pw@h/cb?token_secret=abc"),
            "https://u:pw@h/cb?token_secret=abc"
        );
    }
}