index-core 1.0.0

Core document model and semantic types for Index.
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
//! Telemetry-free diagnostic records.

use std::fmt::{Display, Formatter};

use crate::auth::Redactor;
use crate::{DocumentQuality, DocumentQualityCategory, IndexDocument, IndexNode};

/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    /// Informational diagnostic.
    Info,
    /// Warning diagnostic.
    Warning,
    /// Error diagnostic.
    Error,
}

impl Display for DiagnosticSeverity {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Info => f.write_str("info"),
            Self::Warning => f.write_str("warning"),
            Self::Error => f.write_str("error"),
        }
    }
}

/// Telemetry policy for Index diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TelemetryPolicy {
    /// Diagnostics stay local and are never transmitted by core crates.
    LocalOnly,
}

/// Boundary that produced or observed a diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSource {
    /// Local file or stdin input.
    LocalInput,
    /// Network fetch boundary.
    Network,
    /// HTML parser boundary.
    Parser,
    /// Readability extraction boundary.
    Readability,
    /// Generic transformer fallback.
    GenericTransformer,
    /// Site adapter boundary.
    Adapter,
    /// Headless fallback boundary.
    Headless,
    /// Extraction and serialization boundary.
    Extraction,
    /// Renderer or terminal layout boundary.
    Renderer,
    /// Local knowledge shelf boundary.
    Shelf,
}

impl DiagnosticSource {
    /// Returns a stable source name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::LocalInput => "local-input",
            Self::Network => "network",
            Self::Parser => "parser",
            Self::Readability => "readability",
            Self::GenericTransformer => "generic-transformer",
            Self::Adapter => "adapter",
            Self::Headless => "headless",
            Self::Extraction => "extraction",
            Self::Renderer => "renderer",
            Self::Shelf => "shelf",
        }
    }
}

impl Display for DiagnosticSource {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Transformation confidence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticConfidence {
    /// No useful content was extracted.
    Failed,
    /// Some content exists, but the result is likely incomplete.
    Low,
    /// The output is usable but may need a fallback or fixture.
    Medium,
}

impl DiagnosticConfidence {
    /// Returns a stable confidence label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Failed => "failed",
            Self::Low => "low",
            Self::Medium => "medium",
        }
    }
}

impl Display for DiagnosticConfidence {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Suggested next action for a failed or low-confidence page.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticAction {
    /// Retry the operation.
    Retry,
    /// Try a headless snapshot fallback.
    TryHeadless,
    /// Extract links or structured output for inspection.
    Extract,
    /// Create a local redacted capture artifact.
    Capture,
    /// Repair the current reader view locally.
    Repair,
    /// Add or improve a fixture.
    AddFixture,
    /// Search the local knowledge shelf.
    ShelfSearch,
}

impl DiagnosticAction {
    /// Returns user-facing action text.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Retry => "retry the request",
            Self::TryHeadless => "try headless fallback",
            Self::Extract => "extract links or JSON for inspection",
            Self::Capture => "capture a local redacted fixture",
            Self::Repair => "repair the reader view locally",
            Self::AddFixture => "add or improve a fixture",
            Self::ShelfSearch => "search the local knowledge shelf",
        }
    }

    /// Returns an exact command or command pattern the user can run locally.
    #[must_use]
    pub const fn command(self) -> &'static str {
        match self {
            Self::Retry => ":open <url>",
            Self::TryHeadless => "index --headless <url>",
            Self::Extract => ":extract links",
            Self::Capture => ":capture preview",
            Self::Repair => ":repair promote <region-id>",
            Self::AddFixture => "index capture --validate <artifact-file>",
            Self::ShelfSearch => "index shelf search <query>",
        }
    }
}

impl Display for DiagnosticAction {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.label())
    }
}

impl TelemetryPolicy {
    /// Returns whether the policy permits automatic network transmission.
    #[must_use]
    pub const fn allows_network_transmission(self) -> bool {
        match self {
            Self::LocalOnly => false,
        }
    }
}

/// Likely cause for a failed or low-confidence page.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FailureCause {
    /// Network fetch or DNS/transport failed.
    NetworkUnavailable,
    /// Local parsing failed or produced an unusable structure.
    ParseFailed,
    /// A timeout stopped a fetch or rendering attempt.
    Timeout,
    /// No useful page content was available.
    EmptyContent,
    /// Index did not understand the static page shape.
    UnsupportedPageShape,
    /// Extraction or serialization failed.
    ExtractionFailed,
    /// Renderer layout or terminal output failed.
    RendererFailed,
    /// Local shelf storage or search failed.
    ShelfUnavailable,
    /// A document exists but Index has low confidence in its completeness.
    LowConfidence,
    /// A security or origin policy rejected the operation.
    BlockedByPolicy,
    /// A site adapter declined or failed and generic fallback was used.
    AdapterMismatch,
    /// The cause was not specific enough to classify.
    Unknown,
}

impl FailureCause {
    /// Returns the stable cause name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NetworkUnavailable => "network-unavailable",
            Self::ParseFailed => "parse-failed",
            Self::Timeout => "timeout",
            Self::EmptyContent => "empty-content",
            Self::UnsupportedPageShape => "unsupported-page-shape",
            Self::ExtractionFailed => "extraction-failed",
            Self::RendererFailed => "renderer-failed",
            Self::ShelfUnavailable => "shelf-unavailable",
            Self::LowConfidence => "low-confidence",
            Self::BlockedByPolicy => "blocked-by-policy",
            Self::AdapterMismatch => "adapter-mismatch",
            Self::Unknown => "unknown",
        }
    }

    /// Returns concise user-facing cause text.
    #[must_use]
    pub const fn explanation(self) -> &'static str {
        match self {
            Self::NetworkUnavailable => "Index could not retrieve the requested page.",
            Self::ParseFailed => "Index could not parse the supplied content into a safe document.",
            Self::Timeout => "The operation took longer than the configured budget.",
            Self::EmptyContent => "The page did not expose readable semantic content.",
            Self::UnsupportedPageShape => {
                "The static transformer could not map this page shape confidently."
            }
            Self::ExtractionFailed => {
                "Index could not serialize the document into the requested extraction format."
            }
            Self::RendererFailed => {
                "Index could not lay out the document for the current terminal view."
            }
            Self::ShelfUnavailable => {
                "Index could not read, write, or search the local knowledge shelf."
            }
            Self::LowConfidence => "Index produced a partial document and needs review or repair.",
            Self::BlockedByPolicy => {
                "A security, origin, sandbox, or URL policy rejected the page."
            }
            Self::AdapterMismatch => {
                "A site-specific adapter did not match confidently, so fallback behavior was used."
            }
            Self::Unknown => "Index could not classify the failure precisely.",
        }
    }

    /// Classifies a failure from its boundary and reason.
    #[must_use]
    pub fn classify(source: DiagnosticSource, reason: &str) -> Self {
        let reason = reason.to_ascii_lowercase();
        if reason.contains("timeout") || reason.contains("timed out") {
            Self::Timeout
        } else if reason.contains("schema")
            || reason.contains("json")
            || reason.contains("markdown")
            || reason.contains("extract")
        {
            Self::ExtractionFailed
        } else if reason.contains("render")
            || reason.contains("layout")
            || reason.contains("terminal")
            || reason.contains("viewport")
        {
            Self::RendererFailed
        } else if reason.contains("shelf")
            || reason.contains("saved record")
            || reason.contains("offline record")
        {
            Self::ShelfUnavailable
        } else if reason.contains("low confidence") || reason.contains("partial document") {
            Self::LowConfidence
        } else if reason.contains("parse") || reason.contains("malformed") {
            Self::ParseFailed
        } else if reason.contains("denied")
            || reason.contains("blocked")
            || reason.contains("unsafe")
            || reason.contains("policy")
        {
            Self::BlockedByPolicy
        } else if reason.contains("empty")
            || reason.contains("no readable")
            || reason.contains("missing readable")
            || reason.contains("did not contain readable")
        {
            Self::EmptyContent
        } else {
            match source {
                DiagnosticSource::Network => Self::NetworkUnavailable,
                DiagnosticSource::Adapter => Self::AdapterMismatch,
                DiagnosticSource::Parser => Self::ParseFailed,
                DiagnosticSource::GenericTransformer | DiagnosticSource::Readability => {
                    Self::UnsupportedPageShape
                }
                DiagnosticSource::Headless => Self::Unknown,
                DiagnosticSource::Extraction => Self::ExtractionFailed,
                DiagnosticSource::Renderer => Self::RendererFailed,
                DiagnosticSource::Shelf => Self::ShelfUnavailable,
                DiagnosticSource::LocalInput => Self::Unknown,
            }
        }
    }
}

impl Display for FailureCause {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Structured diagnostic field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticField {
    /// Field key.
    pub key: String,
    /// Field value.
    pub value: String,
}

impl DiagnosticField {
    /// Creates a diagnostic field.
    #[must_use]
    pub fn new(key: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            value: value.into(),
        }
    }
}

/// Local diagnostic record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticRecord {
    /// Diagnostic severity.
    pub severity: DiagnosticSeverity,
    /// Stable diagnostic code.
    pub code: String,
    /// Human-readable message.
    pub message: String,
    /// Structured details.
    pub fields: Vec<DiagnosticField>,
}

impl DiagnosticRecord {
    /// Creates a diagnostic record.
    #[must_use]
    pub fn new(
        severity: DiagnosticSeverity,
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            severity,
            code: code.into(),
            message: message.into(),
            fields: Vec::new(),
        }
    }

    /// Appends one structured field.
    #[must_use]
    pub fn with_field(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.fields.push(DiagnosticField::new(key, value));
        self
    }

    /// Returns a redacted copy suitable for logs or support reports.
    #[must_use]
    pub fn redacted(&self, redactor: &Redactor) -> Self {
        Self {
            severity: self.severity,
            code: self.code.clone(),
            message: redactor.redact(&self.message),
            fields: self
                .fields
                .iter()
                .map(|field| DiagnosticField::new(&field.key, redactor.redact(&field.value)))
                .collect(),
        }
    }

    /// Formats the diagnostic as deterministic local text.
    #[must_use]
    pub fn to_local_text(&self) -> String {
        let mut lines = vec![format!(
            "{}[{}]: {}",
            self.severity, self.code, self.message
        )];
        for field in &self.fields {
            lines.push(format!("{}={}", field.key, field.value));
        }
        lines.join("\n")
    }
}

/// Actionable diagnostic document for failed or low-confidence pages.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FailureDiagnostic {
    /// Diagnostic title.
    pub title: String,
    /// Boundary that produced the diagnostic.
    pub source: DiagnosticSource,
    /// Confidence level.
    pub confidence: DiagnosticConfidence,
    /// Short user-facing reason.
    pub reason: String,
    /// Likely cause classification.
    pub cause: FailureCause,
    /// Fallback that was attempted or selected.
    pub fallback: Option<String>,
    /// Steps or boundaries Index tried before failing.
    pub tried: Vec<String>,
    /// Suggested next actions.
    pub actions: Vec<DiagnosticAction>,
    /// Exact suggested commands.
    pub commands: Vec<String>,
    /// Structured diagnostic records.
    pub records: Vec<DiagnosticRecord>,
}

impl FailureDiagnostic {
    /// Creates an actionable diagnostic.
    #[must_use]
    pub fn new(
        title: impl Into<String>,
        source: DiagnosticSource,
        confidence: DiagnosticConfidence,
        reason: impl Into<String>,
    ) -> Self {
        let reason = reason.into();
        let cause = FailureCause::classify(source, &reason);
        Self {
            title: title.into(),
            source,
            confidence,
            reason,
            cause,
            fallback: None,
            tried: vec![source.as_str().to_owned()],
            actions: Vec::new(),
            commands: Vec::new(),
            records: Vec::new(),
        }
    }

    /// Overrides the likely cause classification.
    #[must_use]
    pub fn with_likely_cause(mut self, cause: FailureCause) -> Self {
        self.cause = cause;
        self
    }

    /// Adds fallback information.
    #[must_use]
    pub fn with_fallback(mut self, fallback: impl Into<String>) -> Self {
        self.fallback = Some(fallback.into());
        self
    }

    /// Adds a deterministic "what Index tried" entry.
    #[must_use]
    pub fn with_tried(mut self, tried: impl Into<String>) -> Self {
        self.tried.push(tried.into());
        self
    }

    /// Adds suggested next actions.
    #[must_use]
    pub fn with_actions(mut self, actions: impl IntoIterator<Item = DiagnosticAction>) -> Self {
        self.actions.extend(actions);
        self
    }

    /// Adds one exact suggested command.
    #[must_use]
    pub fn with_command(mut self, command: impl Into<String>) -> Self {
        self.commands.push(command.into());
        self
    }

    /// Adds one structured diagnostic record.
    #[must_use]
    pub fn with_record(mut self, record: DiagnosticRecord) -> Self {
        self.records.push(record);
        self
    }

    /// Returns a redacted copy suitable for logs and fixture submissions.
    #[must_use]
    pub fn redacted(&self, redactor: &Redactor) -> Self {
        Self {
            title: redactor.redact(&self.title),
            source: self.source,
            confidence: self.confidence,
            reason: redactor.redact(&self.reason),
            cause: self.cause,
            fallback: self.fallback.as_ref().map(|value| redactor.redact(value)),
            tried: self
                .tried
                .iter()
                .map(|value| redactor.redact(value))
                .collect(),
            actions: self.actions.clone(),
            commands: self
                .commands
                .iter()
                .map(|value| redactor.redact(value))
                .collect(),
            records: self
                .records
                .iter()
                .map(|record| record.redacted(redactor))
                .collect(),
        }
    }

    /// Formats deterministic local diagnostic text.
    #[must_use]
    pub fn to_local_text(&self) -> String {
        let mut lines = vec![
            format!("title={}", self.title),
            format!("source={}", self.source),
            format!("confidence={}", self.confidence),
            format!("reason={}", self.reason),
            format!("cause={}", self.cause),
        ];
        if let Some(fallback) = &self.fallback {
            lines.push(format!("fallback={fallback}"));
        }
        for tried in &self.tried {
            lines.push(format!("tried={tried}"));
        }
        for action in &self.actions {
            lines.push(format!("action={action}"));
        }
        for command in self.suggested_commands() {
            lines.push(format!("command={command}"));
        }
        for record in &self.records {
            lines.push(record.to_local_text());
        }
        lines.join("\n")
    }

    /// Returns exact suggested commands.
    #[must_use]
    pub fn suggested_commands(&self) -> Vec<String> {
        if !self.commands.is_empty() {
            return self.commands.clone();
        }
        self.actions
            .iter()
            .map(|action| action.command().to_owned())
            .collect()
    }

    /// Converts the diagnostic into an Index document.
    #[must_use]
    pub fn into_document(self) -> IndexDocument {
        let commands = self.suggested_commands();
        let mut document = IndexDocument::titled(self.title.clone());
        document.metadata.quality = Some(DocumentQuality::new(
            DocumentQualityCategory::Failed,
            0,
            [
                format!("source: {}", self.source),
                format!("confidence: {}", self.confidence),
                format!("cause: {}", self.cause),
                self.reason.clone(),
            ],
        ));
        document.push(IndexNode::Heading {
            level: 1,
            text: self.title.clone(),
        });
        document.push(IndexNode::Error(self.reason.clone()));
        document.push(IndexNode::Heading {
            level: 2,
            text: "What Index tried".to_owned(),
        });
        let mut tried = vec![
            format!("source: {}", self.source),
            format!("confidence: {}", self.confidence),
        ];
        tried.extend(self.tried.clone());
        if let Some(fallback) = self.fallback {
            tried.push(format!("fallback path: {fallback}"));
        }
        document.push(IndexNode::List {
            ordered: false,
            items: tried,
        });
        document.push(IndexNode::Heading {
            level: 2,
            text: "Likely cause".to_owned(),
        });
        document.push(IndexNode::Paragraph(format!(
            "{}: {}",
            self.cause,
            self.cause.explanation()
        )));
        if !commands.is_empty() {
            document.push(IndexNode::Heading {
                level: 2,
                text: "Suggested commands".to_owned(),
            });
            document.push(IndexNode::CodeBlock {
                language: Some("sh".to_owned()),
                code: commands.join("\n"),
            });
        }
        if !self.actions.is_empty() {
            document.push(IndexNode::Heading {
                level: 2,
                text: "Suggested actions".to_owned(),
            });
            document.push(IndexNode::List {
                ordered: false,
                items: self
                    .actions
                    .into_iter()
                    .map(|action| action.label().to_owned())
                    .collect(),
            });
        }
        if !self.records.is_empty() {
            document.push(IndexNode::Heading {
                level: 2,
                text: "Diagnostics".to_owned(),
            });
            for record in self.records {
                document.push(IndexNode::Paragraph(record.to_local_text()));
            }
        }
        document
    }
}

#[cfg(test)]
mod tests {
    use super::{
        DiagnosticAction, DiagnosticConfidence, DiagnosticRecord, DiagnosticSeverity,
        DiagnosticSource, FailureCause, FailureDiagnostic, TelemetryPolicy,
    };
    use crate::Redactor;

    #[test]
    fn telemetry_policy_disallows_automatic_network_transmission() {
        assert!(!TelemetryPolicy::LocalOnly.allows_network_transmission());
    }

    #[test]
    fn diagnostic_record_formats_stable_local_text() {
        let record = DiagnosticRecord::new(
            DiagnosticSeverity::Warning,
            "INDEX-WARN",
            "content was truncated",
        )
        .with_field("url", "https://example.test")
        .with_field("bytes", "1024");

        assert_eq!(
            record.to_local_text(),
            "warning[INDEX-WARN]: content was truncated\nurl=https://example.test\nbytes=1024"
        );
    }

    #[test]
    fn diagnostic_record_redacts_message_and_fields() {
        let mut redactor = Redactor::new();
        redactor.add_secret("secret-value");
        let record = DiagnosticRecord::new(
            DiagnosticSeverity::Error,
            "INDEX-AUTH",
            "Authorization: Bearer secret-value",
        )
        .with_field("cookie", "Cookie: session=secret-value")
        .with_field("path", "/tmp/index");

        let redacted = record.redacted(&redactor);

        assert!(redacted.to_local_text().contains("[REDACTED]"));
        assert!(!redacted.to_local_text().contains("secret-value"));
        assert!(redacted.to_local_text().contains("path=/tmp/index"));
    }

    #[test]
    fn failure_diagnostic_formats_redacts_and_renders_document() {
        let mut redactor = Redactor::new();
        redactor.add_secret("secret-token");
        let diagnostic = FailureDiagnostic::new(
            "Unsupported page",
            DiagnosticSource::Readability,
            DiagnosticConfidence::Low,
            "could not understand token=secret-token",
        )
        .with_fallback("generic transformer")
        .with_tried("readability extraction")
        .with_command(":capture save unsupported.capture")
        .with_actions([
            DiagnosticAction::TryHeadless,
            DiagnosticAction::Extract,
            DiagnosticAction::Capture,
            DiagnosticAction::AddFixture,
        ])
        .with_record(
            DiagnosticRecord::new(
                DiagnosticSeverity::Warning,
                "INDEX-LOW-CONFIDENCE",
                "private token secret-token",
            )
            .with_field("url", "https://example.test/?token=secret-token"),
        );

        let local_text = diagnostic.to_local_text();
        assert!(local_text.contains("source=readability"));
        assert!(local_text.contains("confidence=low"));
        assert!(local_text.contains("cause=unsupported-page-shape"));
        assert!(local_text.contains("tried=readability extraction"));
        assert!(local_text.contains("action=try headless fallback"));
        assert!(local_text.contains("command=:capture save unsupported.capture"));

        let redacted = diagnostic.redacted(&redactor);
        assert!(!redacted.to_local_text().contains("secret-token"));
        assert!(redacted.to_local_text().contains("[REDACTED]"));

        let document = redacted.into_document();
        assert_eq!(document.title, "Unsupported page");
        assert!(!document.is_empty());
    }

    #[test]
    fn failure_cause_classification_is_stable() {
        assert_eq!(
            FailureCause::classify(DiagnosticSource::Network, "dns failed"),
            FailureCause::NetworkUnavailable
        );
        assert_eq!(
            FailureCause::classify(DiagnosticSource::Headless, "timed out after 1000ms"),
            FailureCause::Timeout
        );
        assert_eq!(
            FailureCause::classify(DiagnosticSource::LocalInput, "unsafe scheme denied"),
            FailureCause::BlockedByPolicy
        );
        assert_eq!(
            FailureCause::classify(DiagnosticSource::GenericTransformer, "no readable content"),
            FailureCause::EmptyContent
        );
        assert_eq!(
            FailureCause::classify(DiagnosticSource::Adapter, "uncertain detection"),
            FailureCause::AdapterMismatch
        );
        assert_eq!(
            FailureCause::classify(DiagnosticSource::Parser, "malformed HTML parse failed"),
            FailureCause::ParseFailed
        );
        assert_eq!(
            FailureCause::classify(DiagnosticSource::Extraction, "JSON schema failure"),
            FailureCause::ExtractionFailed
        );
        assert_eq!(
            FailureCause::classify(DiagnosticSource::Renderer, "terminal layout overflow"),
            FailureCause::RendererFailed
        );
        assert_eq!(
            FailureCause::classify(DiagnosticSource::Shelf, "shelf index missing"),
            FailureCause::ShelfUnavailable
        );
        assert_eq!(
            FailureCause::classify(
                DiagnosticSource::Readability,
                "low confidence partial document"
            ),
            FailureCause::LowConfidence
        );
    }

    #[test]
    fn failure_document_contains_commands_and_capture_action() {
        let document = FailureDiagnostic::new(
            "Failed",
            DiagnosticSource::Network,
            DiagnosticConfidence::Failed,
            "could not fetch",
        )
        .with_actions([DiagnosticAction::Retry, DiagnosticAction::Capture])
        .into_document();
        let rendered = format!("{:?}", document.nodes);

        assert!(rendered.contains("What Index tried"));
        assert!(rendered.contains("Likely cause"));
        assert!(rendered.contains("Suggested commands"));
        assert!(rendered.contains(":capture preview"));
    }

    #[test]
    fn failure_documents_cover_major_boundaries_with_exact_commands() {
        for (source, reason, command, cause) in [
            (
                DiagnosticSource::Parser,
                "malformed parse input",
                ":capture preview",
                FailureCause::ParseFailed,
            ),
            (
                DiagnosticSource::Network,
                "dns failed",
                ":open <url>",
                FailureCause::NetworkUnavailable,
            ),
            (
                DiagnosticSource::GenericTransformer,
                "unsupported page shape",
                ":repair promote <region-id>",
                FailureCause::UnsupportedPageShape,
            ),
            (
                DiagnosticSource::Extraction,
                "JSON schema failure",
                ":extract links",
                FailureCause::ExtractionFailed,
            ),
            (
                DiagnosticSource::Renderer,
                "terminal layout overflow",
                ":repair promote <region-id>",
                FailureCause::RendererFailed,
            ),
            (
                DiagnosticSource::Shelf,
                "shelf index missing",
                "index shelf search <query>",
                FailureCause::ShelfUnavailable,
            ),
        ] {
            let document = FailureDiagnostic::new(
                "Boundary failed",
                source,
                DiagnosticConfidence::Failed,
                reason,
            )
            .with_actions([
                DiagnosticAction::Retry,
                DiagnosticAction::Extract,
                DiagnosticAction::Capture,
                DiagnosticAction::Repair,
                DiagnosticAction::ShelfSearch,
            ])
            .into_document();
            let rendered = format!("{:?}", document.nodes);

            assert!(
                rendered.contains(command),
                "{source} missing command {command}"
            );
            assert!(
                rendered.contains(cause.as_str()),
                "{source} missing cause {cause}"
            );
            assert!(document.metadata.quality.as_ref().is_some_and(|quality| {
                quality.category == crate::DocumentQualityCategory::Failed
            }));
        }
    }

    #[test]
    fn diagnostic_enum_names_are_stable() {
        assert_eq!(DiagnosticSource::LocalInput.as_str(), "local-input");
        assert_eq!(DiagnosticSource::Network.to_string(), "network");
        assert_eq!(DiagnosticSource::Parser.to_string(), "parser");
        assert_eq!(
            DiagnosticSource::GenericTransformer.to_string(),
            "generic-transformer"
        );
        assert_eq!(DiagnosticSource::Adapter.to_string(), "adapter");
        assert_eq!(DiagnosticSource::Headless.to_string(), "headless");
        assert_eq!(DiagnosticSource::Extraction.to_string(), "extraction");
        assert_eq!(DiagnosticSource::Renderer.to_string(), "renderer");
        assert_eq!(DiagnosticSource::Shelf.to_string(), "shelf");
        assert_eq!(DiagnosticConfidence::Failed.as_str(), "failed");
        assert_eq!(DiagnosticConfidence::Medium.to_string(), "medium");
        assert_eq!(DiagnosticAction::Retry.to_string(), "retry the request");
        assert_eq!(
            DiagnosticAction::Repair.command(),
            ":repair promote <region-id>"
        );
        assert_eq!(FailureCause::Timeout.to_string(), "timeout");
        assert_eq!(
            FailureCause::ShelfUnavailable.to_string(),
            "shelf-unavailable"
        );
    }
}