anytype 0.5.0

An ergonomic Anytype API client in rust
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
//! Errors returned by `AnytypeClient`
//!
use std::{fmt, path::PathBuf};

use anytype_rpc::error::{AnytypeGrpcError, BackupError, ViewError};
use snafu::prelude::*;

use crate::resolve::ResolveCandidate;

/// Errors returned by the Anytype crate.
///
/// `Display`, `Debug`, and the standard error source chain intentionally omit
/// every free-form string and typed upstream source that could contain request
/// or document content. Match the public variants and fields when an
/// application explicitly needs raw values; use [`AnytypeError::diagnostic`]
/// for ordinary logs and telemetry. Error text is therefore
/// classification-oriented and is not a stable parsing contract.
#[derive(Snafu)]
#[snafu(visibility(pub))]
pub enum AnytypeError {
    // Http connection or timeout error
    #[snafu(display(
        "HTTP transport error {} path:{}",
        diagnostic_method(method),
        crate::http_client::diagnostic_path(url)
    ))]
    Http {
        method: String,
        /// Original request target retained for programmatic inspection.
        /// Use [`AnytypeError::diagnostic`] before logging it.
        url: String,
        /// Raw transport source retained for explicit programmatic matching.
        /// It is omitted from standard formatting and the error source chain.
        #[snafu(source(false))]
        source: reqwest::Error,
        /// Timeout outcome when the transport source is a caller timeout.
        outcome: Option<crate::http_timeout::TimeoutOutcome>,
        /// Elapsed logical-operation time when measured.
        elapsed: Option<std::time::Duration>,
        /// Physical sends when measured.
        attempts: Option<u32>,
    },

    /// A library logical HTTP deadline expired.
    ///
    /// The server may continue work after the caller receives this error.
    #[snafu(display(
        "HTTP deadline expired class={class} outcome={outcome} {} path:{} elapsed_ms={} attempts={attempts}",
        diagnostic_method(method),
        crate::http_client::diagnostic_path(path),
        elapsed.as_millis()
    ))]
    HttpTimeout {
        /// Expired logical deadline class.
        class: crate::http_timeout::HttpTimeoutClass,
        /// Effect on the logical operation.
        outcome: crate::http_timeout::TimeoutOutcome,
        /// Sanitized HTTP method.
        method: String,
        /// Original target retained for programmatic inspection and sanitized
        /// before formatting.
        path: String,
        /// Elapsed logical operation time.
        elapsed: std::time::Duration,
        /// Number of physical sends before expiration.
        attempts: u32,
    },

    /// A non-timeout transport failure left a mutation outcome indeterminate.
    #[snafu(display(
        "HTTP mutation outcome indeterminate {} path:{} attempts={attempts}",
        diagnostic_method(method),
        crate::http_client::diagnostic_path(path)
    ))]
    HttpMutationIndeterminate {
        /// Sanitized HTTP method.
        method: String,
        /// Original target retained for programmatic inspection and sanitized
        /// before formatting.
        path: String,
        /// Number of physical sends before failure.
        attempts: u32,
        /// Completed ambiguous server status, or `None` for transport failure.
        status: Option<u16>,
    },

    /// Anytype Server responded with error.
    /// This error usually means the request was invalid, or there was an internal server error.
    #[snafu(display(
        "Anytype API error status={code} {} path:{} (upstream payload redacted)",
        diagnostic_method(method),
        crate::http_client::diagnostic_path(url)
    ))]
    ApiError {
        code: u16,
        method: String,
        /// Original request target retained for programmatic inspection.
        /// Use [`AnytypeError::diagnostic`] before logging it.
        url: String,
        /// Bounded upstream response text for explicit programmatic handling.
        ///
        /// This may contain document data or credentials supplied by an
        /// untrusted server. It is deliberately omitted from `Display`,
        /// `Debug`, and [`AnytypeError::diagnostic`].
        message: String,
    },

    /// A buffered HTTP response exceeded its configured byte ceiling.
    ///
    /// The error intentionally contains no response body, URL, request body,
    /// or credential-bearing value, so callers may classify it safely.
    #[snafu(display("HTTP response exceeds the configured {limit}-byte limit"))]
    ResponseTooLarge {
        /// Maximum response bytes permitted for this operation.
        limit: u64,
        /// Server-declared length when one was available.
        declared: Option<u64>,
    },

    /// Allowlisted file response headers exceeded the caller's evidence budget.
    #[snafu(display("file response header evidence exceeds the configured {limit}-byte limit"))]
    FileHeaderEvidenceTooLarge {
        /// Maximum retained allowlisted header bytes for this request.
        limit: u64,
        /// HTTP response status retained without any header or body value.
        status: u16,
    },

    /// An allowlisted file response header was structurally invalid.
    #[snafu(display("invalid file response header {header}: {issue}"))]
    InvalidFileResponseHeader {
        /// HTTP response status retained without the response body.
        status: u16,
        /// Fixed allowlisted header name.
        header: &'static str,
        /// Fixed validation classification such as `duplicate` or `malformed`.
        issue: &'static str,
    },

    /// A chat SSE event exceeded its configured incremental buffer ceiling.
    ///
    /// No event bytes, URL, credentials, or upstream body are retained.
    #[snafu(display("chat SSE event exceeds the configured {limit}-byte limit"))]
    ChatSseEventTooLarge {
        /// Maximum bytes permitted for one buffered event, including delimiter.
        limit: u64,
    },

    /// A chat SSE transport failed after the stream was opened.
    ///
    /// The raw transport error is deliberately discarded because reqwest may
    /// retain a credential- or query-bearing URL in its error source.
    #[snafu(display(
        "chat SSE transport failed at path {}",
        crate::http_client::diagnostic_path(path)
    ))]
    ChatSseTransport {
        /// Path-only diagnostic without authority, query, or fragment.
        path: String,
    },

    /// A REST or gRPC chat message contained an invalid timestamp.
    ///
    /// Raw timestamp values and message identities are omitted so this fixed
    /// classification is safe for diagnostics.
    #[snafu(display("invalid chat message timestamp: {field}"))]
    ChatTimestamp {
        /// Message field whose wire value could not be represented canonically.
        field: crate::chats::ChatTimestampField,
    },

    /// An older-history REST page did not provide complete bounded evidence.
    #[snafu(display("chat history evidence is incomplete: {kind}"))]
    ChatHistoryEvidence {
        /// Closed, payload-free classification of the failed evidence check.
        kind: crate::chats::ChatHistoryEvidenceKind,
    },

    /// A supported chat edit changed content without advancing `modified_at`.
    #[snafu(display("chat edit did not advance the modification timestamp"))]
    ChatEditTimestampNotAdvanced,

    /// Encountered server error on "retryable" request, but all retry attempts failed.
    #[snafu(display("server api request: failed {n} times"))]
    TooManyRetries { n: u32 },

    /// Authorization error.
    ///
    /// The raw message remains available for explicit programmatic matching,
    /// but standard formatting omits it because it may contain request data.
    #[snafu(display("Authentication failed (details redacted)"))]
    Auth { message: String },

    /// Deserialization error. This means we didn't deserialize a server response correctly.
    /// If you see this error, please report it as a bug.
    #[snafu(display(
        "Deserialization error at line {} column {}",
        source.line(),
        source.column()
    ))]
    Deserialization {
        #[snafu(source(false))]
        source: serde_json::Error,
    },

    /// Serialization error. unlikely to occur. If you see this error, please report it as a bug.
    #[snafu(display(
        "Serialization error at line {} column {}",
        source.line(),
        source.column()
    ))]
    Serialization {
        #[snafu(source(false))]
        source: serde_json::Error,
    },

    /// Expected item was not found. Returned for any object get by id,
    /// or property or type lookup by unique key, or tag lookup by property and name.
    #[snafu(display("Requested Anytype item was not found (identity redacted)"))]
    NotFound { obj_type: String, key: String },

    /// A name matched more than one item. Returned by the `resolve_*` helpers
    /// (see the [`resolve`](crate::resolve) module) when a space, type, chat,
    /// or view name is not unique in its scope. Use the id (or, for types,
    /// the `@key` form) to disambiguate.
    #[snafu(display("Anytype item name is ambiguous (identity redacted)"))]
    Ambiguous {
        obj_type: String,
        key: String,
        /// Deterministically ordered, deduplicated alternatives that callers
        /// can present when asking the user to disambiguate.
        candidates: Vec<ResolveCandidate>,
    },

    /// A resolver could not prove a unique or missing result within its hard
    /// upstream scan bound. Retry with an id or an explicit unique key.
    #[snafu(display(
        "Anytype item resolution exceeded the {limit}-item scan limit (identity redacted)"
    ))]
    ResolutionLimitExceeded {
        obj_type: String,
        key: String,
        limit: usize,
    },

    /// Client is not authenticated.
    #[snafu(display("Client is not authenticated. Log in first."))]
    Unauthorized,

    /// Client is authenticated, but user does not have proper authorization
    #[snafu(display("Permission denied: User does not have permission to access the object(s)"))]
    Forbidden,

    /// Too many requests occurred. See the anytype rate limit documentation.
    ///
    /// When the Anytype server responds with HTTP 429, the HTTP client
    /// throttles and retries only replay-safe methods
    /// until the server stops returning errors, or up to `rate_limit_max_retries` times
    /// before giving up and returning this error to the client. The config setting
    /// `rate_limit_max_retries` can be increased to handle arbitrary-sized
    /// bursts, with the result that the app may spend more time waiting.
    /// If `rate_limit_max_retries` is zero, replay-safe requests wait and retry
    /// without a retry-count cap. Non-idempotent mutation requests are never
    /// replayed automatically and instead return their original 429 failure.
    #[snafu(display(
        "Rate limit exceeded (parsed wait_time: {} secs; upstream header redacted)",
        duration.as_secs()
    ))]
    RateLimitExceeded {
        /// Raw bounded header value retained for explicit programmatic use.
        /// It is omitted from all standard diagnostics.
        header: String,
        duration: std::time::Duration,
    },

    /// Validation error: an internal parameter validation check failed.
    ///
    /// The raw message remains available for explicit programmatic matching,
    /// but standard formatting omits it because validation context can contain
    /// request or document data.
    #[snafu(display("Validation error (details redacted)"))]
    Validation { message: String },

    /// A `KeyStore` has not been configured.
    /// This is an `AnytypeError` rather than a `KeyStoreError`, because it is a client configuration error
    #[snafu(display("No configured keystore"))]
    NoKeyStore,

    /// gRPC auth or transport error.
    ///
    /// The typed source remains available for explicit programmatic matching,
    /// but standard formatting and the error source chain omit it because
    /// upstream statuses can contain response or request data.
    #[snafu(display("gRPC error (details redacted)"))]
    Grpc {
        #[snafu(source(false))]
        source: anytype_rpc::error::AnytypeGrpcError,
    },

    /// gRPC auth is unavailable (missing config or account key).
    #[snafu(display("gRPC service unavailable (details redacted)"))]
    GrpcUnavailable { message: String },

    /// Error encountered by the configured `KeyStore`.
    ///
    /// The typed source remains available for explicit programmatic matching,
    /// but standard formatting and the error source chain omit it because it
    /// can contain paths, environment names, or backend error text.
    #[snafu(display("KeyStore error (details redacted)"))]
    KeyStore {
        #[snafu(source(false))]
        source: KeyStoreError,
    },

    /// A function requiring the cache failed because the cache is disabled.
    #[snafu(display("Operation requires cache to be enabled"))]
    CacheDisabled,

    /// A body-block read failed graph validation (see
    /// [`body`](crate::body)): the returned block graph was duplicate,
    /// dangling, shared, cyclic, orphaned, oversized, or malformed. The read
    /// fails whole; a partial tree is never returned.
    ///
    /// `detail` contains only block IDs and structural counts.
    #[snafu(display("Body graph validation failed: {kind} (identity redacted)"))]
    BodyGraph {
        /// Object whose body failed validation.
        object_id: String,
        /// Closed violation classification.
        kind: crate::body::BodyGraphErrorKind,
        /// Bounded ID-and-count-only context for explicit programmatic use.
        detail: String,
    },

    /// A body-block write may have reached the server but its exact final
    /// state could not be proved within finite verification bounds.
    ///
    /// Callers must perform a fresh body read before deciding whether any
    /// retry is safe. Standard formatting redacts object and block identity;
    /// `observed` is the last complete, validated snapshot when one was read.
    #[snafu(display(
        "Body mutation outcome is indeterminate after {attempts} verification attempts in {timeout:?} (identity redacted)"
    ))]
    BodyMutationIndeterminate {
        /// Object whose body may have changed.
        object_id: String,
        /// Requested or server-returned affected block ID, when known.
        block_id: Option<crate::body::BlockId>,
        /// Number of completed fresh verification reads.
        attempts: usize,
        /// Finite mutation/verification timeout.
        timeout: std::time::Duration,
        /// Last complete validated body snapshot, when available.
        observed: Option<Box<crate::body::BodySnapshot>>,
    },

    /// A finite body gRPC lifecycle failed without retaining upstream payloads.
    #[snafu(display("Body RPC lifecycle failed: {kind}"))]
    BodyRpcLifecycle {
        /// Closed lifecycle classification.
        kind: crate::body_rpc::BodyRpcLifecycleErrorKind,
    },

    /// A direct collection-membership read could not establish complete,
    /// identity-bound evidence.
    ///
    /// This variant never represents absence. Callers must treat it as an
    /// indeterminate observation and must not use it to justify retrying a
    /// preceding mutation.
    #[snafu(display("Collection membership evidence is incomplete: {kind}"))]
    CollectionMembershipEvidence {
        /// Closed, payload-free classification of the failed evidence check.
        kind: crate::views::CollectionMembershipEvidenceKind,
    },

    /// A finite type-property classification could not complete its owned
    /// `ObjectShow`/`ObjectClose` lifecycle.
    #[snafu(display("Type property classification failed: {kind}"))]
    TypePropertyClassification {
        /// Closed payload-free lifecycle failure classification.
        kind: crate::types::TypePropertyClassificationErrorKind,
    },

    /// A bounded attached-discussion operation failed without exposing identity
    /// or upstream payload data.
    #[snafu(display("Attached discussion operation failed: {kind}"))]
    AttachedDiscussion {
        /// Closed, payload-free failure classification.
        kind: crate::attached_discussions::AttachedDiscussionErrorKind,
    },

    /// The previous operation could not be confirmed within the expected time interval.
    /// For more information, see the notes about eventual consistency in the project [README](../README.md).
    #[snafu(display(
        "Verify timeout after {attempts} attempts in {timeout:?} (identity and last error redacted)"
    ))]
    VerifyTimeout {
        obj_type: String,
        key: String,
        attempts: usize,
        timeout: std::time::Duration,
        last_error: Option<String>,
    },

    /// Some other error occurred.
    ///
    /// The raw message remains available for explicit programmatic matching,
    /// but standard formatting omits it because callers may have included
    /// request or document data.
    #[snafu(display("Anytype error (details redacted)"))]
    Other { message: String },
}

fn diagnostic_method(method: &str) -> &str {
    if !method.is_empty()
        && method.len() <= 16
        && method
            .bytes()
            .all(|byte| byte.is_ascii_alphabetic() || byte == b'-')
    {
        method
    } else {
        "unknown"
    }
}

/// Structured, secret-safe classification of an [`AnytypeError`].
///
/// This value intentionally excludes upstream response text, headers,
/// credential-bearing URLs, request bodies, document bodies, and underlying
/// error strings. It is safe to pass to ordinary application diagnostics.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AnytypeDiagnostic {
    /// Stable error variant name.
    pub variant: &'static str,
    /// HTTP response status when the variant carries one.
    pub status: Option<u16>,
    /// Validated HTTP method when available.
    pub method: Option<String>,
    /// Bounded path-only request context when available.
    pub path: Option<String>,
    /// Library timeout class when a logical deadline expired.
    pub timeout_class: Option<crate::http_timeout::HttpTimeoutClass>,
    /// Whether the timeout came from caller-configured reqwest transport policy.
    pub transport_timeout: bool,
    /// Timeout or ambiguous-mutation outcome when applicable.
    pub timeout_outcome: Option<crate::http_timeout::TimeoutOutcome>,
    /// Saturating elapsed milliseconds when measured.
    pub elapsed_millis: Option<u64>,
    /// Physical HTTP attempt count when measured.
    pub attempts: Option<u32>,
}

impl fmt::Display for AnytypeDiagnostic {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "variant={}", self.variant)?;
        if let Some(status) = self.status {
            write!(formatter, " status={status}")?;
        }
        if let Some(method) = self.method.as_deref() {
            write!(formatter, " method={method}")?;
        }
        if let Some(path) = self.path.as_deref() {
            write!(formatter, " path={path}")?;
        }
        if let Some(class) = self.timeout_class {
            write!(formatter, " timeout_class={class}")?;
        } else if self.transport_timeout {
            formatter.write_str(" timeout_class=transport")?;
        }
        if let Some(outcome) = self.timeout_outcome {
            write!(formatter, " outcome={outcome}")?;
        }
        if let Some(elapsed_millis) = self.elapsed_millis {
            write!(formatter, " elapsed_ms={elapsed_millis}")?;
        }
        if let Some(attempts) = self.attempts {
            write!(formatter, " attempts={attempts}")?;
        }
        Ok(())
    }
}

impl fmt::Debug for AnytypeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("AnytypeError")
            .field(&self.diagnostic())
            .finish()
    }
}

impl AnytypeError {
    /// Returns structured diagnostic context with all payload-bearing fields
    /// removed and every request target reduced to a bounded path.
    #[must_use]
    pub fn diagnostic(&self) -> AnytypeDiagnostic {
        let (variant, status, method, path) = match self {
            Self::Http { method, url, .. } => (
                "http_transport",
                None,
                Some(diagnostic_method(method).to_owned()),
                Some(crate::http_client::diagnostic_path(url)),
            ),
            Self::HttpTimeout { method, path, .. } => (
                "http_timeout",
                None,
                Some(diagnostic_method(method).to_owned()),
                Some(crate::http_client::diagnostic_path(path)),
            ),
            Self::HttpMutationIndeterminate {
                method,
                path,
                status,
                ..
            } => (
                "http_mutation_indeterminate",
                *status,
                Some(diagnostic_method(method).to_owned()),
                Some(crate::http_client::diagnostic_path(path)),
            ),
            Self::ApiError {
                code, method, url, ..
            } => (
                "api_error",
                Some(*code),
                Some(diagnostic_method(method).to_owned()),
                Some(crate::http_client::diagnostic_path(url)),
            ),
            Self::ResponseTooLarge { .. } => ("response_too_large", None, None, None),
            Self::FileHeaderEvidenceTooLarge { status, .. } => {
                ("file_header_evidence_too_large", Some(*status), None, None)
            }
            Self::InvalidFileResponseHeader { status, .. } => {
                ("invalid_file_response_header", Some(*status), None, None)
            }
            Self::ChatSseEventTooLarge { .. } => ("chat_sse_event_too_large", None, None, None),
            Self::ChatSseTransport { path } => (
                "chat_sse_transport",
                None,
                None,
                Some(crate::http_client::diagnostic_path(path)),
            ),
            Self::ChatTimestamp { .. } => ("chat_timestamp", None, None, None),
            Self::ChatHistoryEvidence { .. } => ("chat_history_evidence", None, None, None),
            Self::ChatEditTimestampNotAdvanced => {
                ("chat_edit_timestamp_not_advanced", None, None, None)
            }
            Self::TooManyRetries { .. } => ("too_many_retries", None, None, None),
            Self::Auth { .. } => ("auth", None, None, None),
            Self::Deserialization { .. } => ("deserialization", None, None, None),
            Self::Serialization { .. } => ("serialization", None, None, None),
            Self::NotFound { .. } => ("not_found", None, None, None),
            Self::Ambiguous { .. } => ("ambiguous", None, None, None),
            Self::ResolutionLimitExceeded { .. } => ("resolution_limit_exceeded", None, None, None),
            Self::Unauthorized => ("unauthorized", Some(401), None, None),
            Self::Forbidden => ("forbidden", Some(403), None, None),
            Self::RateLimitExceeded { .. } => ("rate_limit", Some(429), None, None),
            Self::Validation { .. } => ("validation", None, None, None),
            Self::NoKeyStore => ("no_keystore", None, None, None),
            Self::Grpc { .. } => ("grpc", None, None, None),
            Self::GrpcUnavailable { .. } => ("grpc_unavailable", None, None, None),
            Self::KeyStore { .. } => ("keystore", None, None, None),
            Self::CacheDisabled => ("cache_disabled", None, None, None),
            Self::BodyGraph { .. } => ("body_graph", None, None, None),
            Self::BodyMutationIndeterminate { .. } => {
                ("body_mutation_indeterminate", None, None, None)
            }
            Self::BodyRpcLifecycle { .. } => ("body_rpc_lifecycle", None, None, None),
            Self::CollectionMembershipEvidence { .. } => {
                ("collection_membership_evidence", None, None, None)
            }
            Self::TypePropertyClassification { .. } => {
                ("type_property_classification", None, None, None)
            }
            Self::AttachedDiscussion { .. } => ("attached_discussion", None, None, None),
            Self::VerifyTimeout { .. } => ("verify_timeout", None, None, None),
            Self::Other { .. } => ("other", None, None, None),
        };
        let (timeout_class, timeout_outcome, elapsed_millis, attempts) = match self {
            Self::HttpTimeout {
                class,
                outcome,
                elapsed,
                attempts,
                ..
            } => (
                Some(*class),
                Some(*outcome),
                Some(u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)),
                Some(*attempts),
            ),
            Self::HttpMutationIndeterminate { attempts, .. } => (
                None,
                Some(crate::http_timeout::TimeoutOutcome::MutationIndeterminate),
                None,
                Some(*attempts),
            ),
            Self::Http {
                method,
                source,
                outcome,
                elapsed,
                attempts,
                ..
            } if source.is_timeout() => (
                None,
                outcome.or_else(|| {
                    Some(if matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS") {
                        crate::http_timeout::TimeoutOutcome::ReadAborted
                    } else {
                        crate::http_timeout::TimeoutOutcome::MutationIndeterminate
                    })
                }),
                elapsed.map(|elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)),
                *attempts,
            ),
            _ => (None, None, None, None),
        };
        AnytypeDiagnostic {
            variant,
            status,
            method,
            path,
            timeout_class,
            transport_timeout: matches!(self, Self::Http { source, .. } if source.is_timeout()),
            timeout_outcome,
            elapsed_millis,
            attempts,
        }
    }

    /// Returns whether this failure is structurally classified as authentication.
    ///
    /// This predicate covers the public HTTP/configuration authentication
    /// variants and authentication failures nested below [`Self::Grpc`]. It
    /// deliberately examines only typed variants and gRPC status categories;
    /// it never formats or parses upstream messages, URLs, response bodies, or
    /// credential-bearing values. Callers therefore do not need to depend on
    /// `anytype-rpc` merely to choose secret-safe authentication guidance.
    #[must_use]
    pub fn is_authentication(&self) -> bool {
        match self {
            Self::ApiError {
                code: 401 | 403, ..
            }
            | Self::Auth { .. }
            | Self::Unauthorized
            | Self::Forbidden
            | Self::NoKeyStore
            | Self::KeyStore { .. }
            | Self::GrpcUnavailable { .. } => true,
            Self::Grpc { source } => grpc_error_is_authentication(source),
            Self::Http { .. }
            | Self::HttpTimeout { .. }
            | Self::HttpMutationIndeterminate { .. }
            | Self::ApiError { .. }
            | Self::ResponseTooLarge { .. }
            | Self::FileHeaderEvidenceTooLarge { .. }
            | Self::InvalidFileResponseHeader { .. }
            | Self::ChatSseEventTooLarge { .. }
            | Self::ChatSseTransport { .. }
            | Self::ChatTimestamp { .. }
            | Self::ChatHistoryEvidence { .. }
            | Self::ChatEditTimestampNotAdvanced
            | Self::TooManyRetries { .. }
            | Self::Deserialization { .. }
            | Self::Serialization { .. }
            | Self::NotFound { .. }
            | Self::Ambiguous { .. }
            | Self::ResolutionLimitExceeded { .. }
            | Self::RateLimitExceeded { .. }
            | Self::Validation { .. }
            | Self::CacheDisabled
            | Self::BodyGraph { .. }
            | Self::BodyMutationIndeterminate { .. }
            | Self::BodyRpcLifecycle { .. }
            | Self::CollectionMembershipEvidence { .. }
            | Self::TypePropertyClassification { .. }
            | Self::AttachedDiscussion { .. }
            | Self::VerifyTimeout { .. }
            | Self::Other { .. } => false,
        }
    }

    /// Returns bounded alternatives for an ambiguous resolver lookup.
    ///
    /// The slice contains at most
    /// [`MAX_RESOLVE_CANDIDATES`](crate::resolve::MAX_RESOLVE_CANDIDATES)
    /// entries. Other error variants return `None`.
    #[must_use]
    pub fn resolve_candidates(&self) -> Option<&[ResolveCandidate]> {
        match self {
            Self::Ambiguous { candidates, .. } => Some(candidates),
            _ => None,
        }
    }
}

fn grpc_error_is_authentication(error: &AnytypeGrpcError) -> bool {
    match error {
        AnytypeGrpcError::Auth { .. } => true,
        AnytypeGrpcError::View { source } => match source {
            ViewError::Auth { .. } => true,
            ViewError::Rpc { source } => grpc_status_is_authentication(source),
            ViewError::ApiResponse { .. }
            | ViewError::MissingObjectView
            | ViewError::MissingDataviewBlock { .. }
            | ViewError::MissingView { .. }
            | ViewError::NotSupportedView { .. } => false,
        },
        AnytypeGrpcError::Backup { source } => match source {
            BackupError::BackupRpc { source } => grpc_status_is_authentication(source),
            BackupError::BackupAuth { .. } => true,
            BackupError::BackupApiResponse { .. }
            | BackupError::InvalidOptions { .. }
            | BackupError::SpaceNameLookup { .. }
            | BackupError::MissingExportPath
            | BackupError::BackupIo { .. }
            | BackupError::BackupMove { .. }
            | BackupError::Deadline { .. } => false,
        },
        AnytypeGrpcError::Config { .. }
        | AnytypeGrpcError::Transport { .. }
        | AnytypeGrpcError::TimeoutConfig { .. }
        | AnytypeGrpcError::Deadline { .. }
        | AnytypeGrpcError::ControlBoundary { .. } => false,
    }
}

fn grpc_status_is_authentication(status: &tonic::Status) -> bool {
    matches!(
        status.code(),
        tonic::Code::Unauthenticated | tonic::Code::PermissionDenied
    )
}

/// Errors arising from `KeyStore`
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum KeyStoreError {
    /// Problem accessing the key file
    #[snafu(display("keystore file {path:?} {source}"))]
    File {
        //message: String,
        path: PathBuf,
        source: std::io::Error,
    },

    /// Problem accessing OS keyring
    #[snafu(display("keyring error {source}"))]
    Keyring {
        //service: Option<String>,
        //user: Option<String>,
        source: keyring_core::Error,
    },

    /// Required environment variable undefined
    #[snafu(display("file keystore expects environment variable {var}"))]
    FileEnv {
        var: String,
        source: std::env::VarError,
    },

    #[snafu(display("keystore configuration error"))]
    Config { message: String },

    /// Other error type - can be used by external implementations
    #[snafu(display("keystore {message}"))]
    External { message: String },
}

impl From<keyring_core::Error> for KeyStoreError {
    fn from(source: keyring_core::Error) -> Self {
        Self::Keyring { source }
    }
}

impl From<KeyStoreError> for AnytypeError {
    fn from(source: KeyStoreError) -> Self {
        Self::KeyStore { source }
    }
}

impl From<AnytypeGrpcError> for AnytypeError {
    fn from(source: AnytypeGrpcError) -> Self {
        Self::Grpc { source }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use anytype_rpc::error::{AnytypeGrpcError, AuthError, BackupError, ConfigError, ViewError};

    use super::{AnytypeError, KeyStoreError};
    use crate::resolve::ResolveCandidate;

    const SECRET: &str = "STANDARD_DISPLAY_DOCUMENT_SECRET";

    fn grpc(source: AnytypeGrpcError) -> AnytypeError {
        AnytypeError::Grpc { source }
    }

    #[test]
    fn all_raw_bearing_error_variants_keep_fields_but_redact_standard_diagnostics() {
        let errors = vec![
            AnytypeError::Auth {
                message: SECRET.to_owned(),
            },
            AnytypeError::NotFound {
                obj_type: SECRET.to_owned(),
                key: SECRET.to_owned(),
            },
            AnytypeError::Ambiguous {
                obj_type: SECRET.to_owned(),
                key: SECRET.to_owned(),
                candidates: vec![ResolveCandidate::new(SECRET, SECRET)],
            },
            AnytypeError::ResolutionLimitExceeded {
                obj_type: SECRET.to_owned(),
                key: SECRET.to_owned(),
                limit: 37,
            },
            AnytypeError::Validation {
                message: SECRET.to_owned(),
            },
            AnytypeError::Grpc {
                source: AnytypeGrpcError::Auth {
                    source: AuthError::Api {
                        code: 500,
                        description: SECRET.to_owned(),
                    },
                },
            },
            AnytypeError::GrpcUnavailable {
                message: SECRET.to_owned(),
            },
            AnytypeError::ChatSseTransport {
                path: format!("https://{SECRET}.invalid/safe?token={SECRET}"),
            },
            AnytypeError::KeyStore {
                source: KeyStoreError::External {
                    message: SECRET.to_owned(),
                },
            },
            AnytypeError::VerifyTimeout {
                obj_type: SECRET.to_owned(),
                key: SECRET.to_owned(),
                attempts: 4,
                timeout: Duration::from_secs(2),
                last_error: Some(SECRET.to_owned()),
            },
            AnytypeError::Other {
                message: SECRET.to_owned(),
            },
        ];

        let AnytypeError::Auth { message } = &errors[0] else {
            panic!("raw auth fixture changed variant");
        };
        assert_eq!(
            message, SECRET,
            "raw fields remain programmatically available"
        );

        for error in errors {
            let mut diagnostics = format!("{error} {error:?} {}", error.diagnostic());
            let mut source = std::error::Error::source(&error);
            while let Some(current) = source {
                diagnostics.push_str(&format!(" {current} {current:?}"));
                source = current.source();
            }
            assert!(
                !diagnostics.contains(SECRET),
                "standard diagnostics exposed raw variant data: {diagnostics}"
            );
        }
    }

    #[test]
    fn direct_authentication_categories_do_not_depend_on_error_text() {
        let authentication = [
            AnytypeError::ApiError {
                code: 401,
                method: "SECRET_METHOD".to_owned(),
                url: "https://SECRET.invalid".to_owned(),
                message: "SECRET_RESPONSE".to_owned(),
            },
            AnytypeError::ApiError {
                code: 403,
                method: "SECRET_METHOD".to_owned(),
                url: "https://SECRET.invalid".to_owned(),
                message: "SECRET_RESPONSE".to_owned(),
            },
            AnytypeError::Auth {
                message: "SECRET_TOKEN".to_owned(),
            },
            AnytypeError::Unauthorized,
            AnytypeError::Forbidden,
            AnytypeError::NoKeyStore,
            AnytypeError::KeyStore {
                source: KeyStoreError::Config {
                    message: "SECRET_KEYSTORE".to_owned(),
                },
            },
            AnytypeError::GrpcUnavailable {
                message: "SECRET_ACCOUNT_KEY".to_owned(),
            },
        ];
        assert!(authentication.iter().all(AnytypeError::is_authentication));

        let non_authentication = [
            AnytypeError::ApiError {
                code: 500,
                method: "SECRET_METHOD".to_owned(),
                url: "https://SECRET.invalid".to_owned(),
                message: "SECRET_RESPONSE".to_owned(),
            },
            AnytypeError::Validation {
                message: "SECRET_INPUT".to_owned(),
            },
            AnytypeError::Other {
                message: "SECRET_OTHER".to_owned(),
            },
            AnytypeError::ChatSseEventTooLarge { limit: 1 },
            AnytypeError::ChatSseTransport {
                path: "https://SECRET.invalid/safe?token=SECRET".to_owned(),
            },
        ];
        assert!(
            non_authentication
                .iter()
                .all(|error| !error.is_authentication())
        );
    }

    #[test]
    fn nested_grpc_authentication_is_structural_and_exhaustive() {
        let authentication = [
            grpc(AnytypeGrpcError::Auth {
                source: AuthError::Api {
                    code: 5,
                    description: "SECRET_BAD_TOKEN".to_owned(),
                },
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::Rpc {
                    source: tonic::Status::unauthenticated("SECRET_VIEW_TOKEN"),
                },
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::Rpc {
                    source: tonic::Status::permission_denied("SECRET_VIEW_SCOPE"),
                },
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::Auth {
                    source: AuthError::InvalidMetadata {
                        source: "SECRET\nVIEW_TOKEN"
                            .parse::<tonic::metadata::MetadataValue<tonic::metadata::Ascii>>()
                            .unwrap_err(),
                    },
                },
            }),
            grpc(AnytypeGrpcError::Backup {
                source: BackupError::BackupAuth {
                    source: AuthError::InvalidMetadata {
                        source: "SECRET\nTOKEN"
                            .parse::<tonic::metadata::MetadataValue<tonic::metadata::Ascii>>()
                            .unwrap_err(),
                    },
                },
            }),
            grpc(AnytypeGrpcError::Backup {
                source: BackupError::BackupRpc {
                    source: tonic::Status::unauthenticated("SECRET_BACKUP_TOKEN"),
                },
            }),
        ];
        assert!(authentication.iter().all(AnytypeError::is_authentication));

        let transport = tonic::transport::Endpoint::from_shared(
            "not a valid SECRET_TRANSPORT_ENDPOINT".to_owned(),
        )
        .unwrap_err();
        let non_authentication = [
            grpc(AnytypeGrpcError::Config {
                source: ConfigError::MissingHome,
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::Rpc {
                    source: tonic::Status::internal("SECRET_VIEW_INTERNAL"),
                },
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::ApiResponse {
                    code: 0,
                    description: "SECRET_ZERO_API_CODE".to_owned(),
                },
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::ApiResponse {
                    code: 103,
                    description: "SECRET_UNTYPED_CODE".to_owned(),
                },
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::MissingObjectView,
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::MissingDataviewBlock {
                    view_id: "SECRET_VIEW".to_owned(),
                },
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::MissingView {
                    view_id: "SECRET_VIEW".to_owned(),
                },
            }),
            grpc(AnytypeGrpcError::View {
                source: ViewError::NotSupportedView {
                    view_id: "SECRET_VIEW".to_owned(),
                    actual: 99,
                },
            }),
            grpc(AnytypeGrpcError::Backup {
                source: BackupError::BackupRpc {
                    source: tonic::Status::unavailable("SECRET_BACKUP_UNAVAILABLE"),
                },
            }),
            grpc(AnytypeGrpcError::Backup {
                source: BackupError::BackupApiResponse {
                    code: 103,
                    description: "SECRET_UNTYPED_CODE".to_owned(),
                },
            }),
            grpc(AnytypeGrpcError::Backup {
                source: BackupError::InvalidOptions {
                    message: "SECRET_OPTIONS".to_owned(),
                },
            }),
            grpc(AnytypeGrpcError::Backup {
                source: BackupError::SpaceNameLookup {
                    space_id: "SECRET_SPACE".to_owned(),
                    message: "SECRET_LOOKUP".to_owned(),
                },
            }),
            grpc(AnytypeGrpcError::Backup {
                source: BackupError::MissingExportPath,
            }),
            grpc(AnytypeGrpcError::Backup {
                source: BackupError::BackupIo {
                    path: "SECRET_SOURCE".into(),
                    source: std::io::Error::other("SECRET_IO"),
                },
            }),
            grpc(AnytypeGrpcError::Backup {
                source: BackupError::BackupMove {
                    from: "SECRET_SOURCE".into(),
                    to: "SECRET_TARGET".into(),
                    source: std::io::Error::other("SECRET_MOVE"),
                },
            }),
            grpc(AnytypeGrpcError::Transport { source: transport }),
        ];
        assert!(
            non_authentication
                .iter()
                .all(|error| !error.is_authentication())
        );
    }
}