trust-tasks-rs 0.1.0

Reference Rust library for the Trust Tasks framework — transport-agnostic, JSON-based descriptions of verifiable work between parties.
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
//! Error-response payload for the `trust-task-error/0.1` framework spec.
//!
//! Models the structure defined in SPEC.md §8.2 and §8.3. The set of standard
//! codes is encoded as the [`StandardCode`] enum; task-specific extensions
//! (SPEC.md §8.5) are namespaced strings carried in the [`TrustTaskCode`]
//! `Extended` variant.

use std::error::Error as StdError;
use std::fmt;
use std::str::FromStr;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::{DeserializeFromStr, SerializeDisplay};
use thiserror::Error;

use crate::transport::ConsistencyError;

/// The `payload` of a `trust-task-error/0.1` document, per SPEC.md §8.2.
///
/// Correlation back to the document this error reports on is carried at the
/// framework level by the `threadId` member of the surrounding
/// [`TrustTask`](crate::TrustTask), not here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorPayload {
    /// Short identifier for the failure category.
    pub code: TrustTaskCode,

    /// Human-readable description. Non-normative; intended for logs and
    /// operator UI.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,

    /// Whether the producer MAY retry the original document. Per SPEC.md §8.4,
    /// "retry" means re-sending bit-for-bit; a new document with a fresh `id`
    /// is not a retry.
    pub retryable: bool,

    /// Earliest time at which the producer SHOULD retry. Meaningful only when
    /// [`retryable`](Self::retryable) is `true`.
    #[serde(
        rename = "retryAfter",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub retry_after: Option<DateTime<Utc>>,

    /// Task-specific extension data. The shape is defined by the
    /// originating *Trust Task specification* (SPEC.md §8.5).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub details: Option<Value>,
}

impl ErrorPayload {
    /// Construct a minimal payload for `code`. `retryable` is initialized to
    /// the code's default per the §8.3 table (overridable via
    /// [`with_retryable`](Self::with_retryable)). All other members are absent.
    pub fn new(code: impl Into<TrustTaskCode>) -> Self {
        let code = code.into();
        let retryable = match &code {
            TrustTaskCode::Standard(c) => c.default_retryable(),
            // Per SPEC §8.5, an unrecognized extension code is treated as
            // `task_failed` — which defaults to non-retryable. The producer of
            // the extension MAY override.
            TrustTaskCode::Extended { .. } => false,
        };
        Self {
            code,
            message: None,
            retryable,
            retry_after: None,
            details: None,
        }
    }

    /// Attach a human-readable message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }

    /// Override the `retryable` flag (default is taken from
    /// [`StandardCode::default_retryable`]).
    pub fn with_retryable(mut self, retryable: bool) -> Self {
        self.retryable = retryable;
        self
    }

    /// Attach a `retryAfter` hint. Meaningful only when `retryable` is `true`.
    pub fn with_retry_after(mut self, when: DateTime<Utc>) -> Self {
        self.retry_after = Some(when);
        self
    }

    /// Attach task-specific extension data.
    pub fn with_details(mut self, details: Value) -> Self {
        self.details = Some(details);
        self
    }

    /// Resolve this payload's code to a [`StandardCode`] the consumer is
    /// guaranteed to recognize, applying the SPEC §8.5 fallback:
    /// unrecognized extension codes collapse to [`StandardCode::TaskFailed`].
    ///
    /// Standard codes are returned as-is.
    pub fn effective_code(&self) -> StandardCode {
        match &self.code {
            TrustTaskCode::Standard(c) => *c,
            TrustTaskCode::Extended { .. } => StandardCode::TaskFailed,
        }
    }

    /// Apply the SPEC §8.4 retry-semantics check.
    ///
    /// Returns `true` only when:
    ///   * `retryable` is `true`, AND
    ///   * `retry_after` is either absent or already past `now`.
    ///
    /// A `false` return means the producer **MUST NOT** retry yet (or at all,
    /// when `retryable` is `false`). "Retry" here is the strict bit-for-bit
    /// sense from SPEC §8.4 — issuing a new document with a fresh `id` is
    /// always permitted regardless of this value.
    pub fn should_retry_at(&self, now: DateTime<Utc>) -> bool {
        if !self.retryable {
            return false;
        }
        match self.retry_after {
            None => true,
            Some(t) => t <= now,
        }
    }
}

impl From<StandardCode> for ErrorPayload {
    fn from(code: StandardCode) -> Self {
        Self::new(code)
    }
}

impl From<TrustTaskCode> for ErrorPayload {
    fn from(code: TrustTaskCode) -> Self {
        Self::new(code)
    }
}

impl fmt::Display for ErrorPayload {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.message.as_deref() {
            Some(msg) => write!(f, "{}: {}", self.code, msg),
            None => write!(f, "{}", self.code),
        }
    }
}

impl StdError for ErrorPayload {}

/// An error code — either a framework-standard code (SPEC.md §8.3) or an
/// extension code namespaced by a spec's slug (SPEC.md §8.5).
#[derive(Debug, Clone, PartialEq, Eq, SerializeDisplay, DeserializeFromStr)]
pub enum TrustTaskCode {
    /// One of the framework-defined codes recognized by every conforming
    /// consumer.
    Standard(StandardCode),

    /// A specification-extended code in the form `<slug>:<local>`.
    Extended {
        /// The slug owning this extension, e.g. `"kyc-handoff"` or `"acl/grant"`.
        slug: String,
        /// The local code identifier within the slug's namespace.
        local: String,
    },
}

/// The framework-defined standard error codes (SPEC.md §8.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StandardCode {
    /// The document did not validate against the framework schema or the
    /// task-specific payload schema.
    MalformedRequest,
    /// The consumer does not recognize the `type` URI.
    UnsupportedType,
    /// The `type` URI was recognized but its `MAJOR.MINOR` is not supported.
    UnsupportedVersion,
    /// `expiresAt` was in the past at the time of evaluation.
    Expired,
    /// A `proof` was required and was missing.
    ProofRequired,
    /// A `proof` was present but failed verification.
    ProofInvalid,
    /// The requesting party is not authorized to invoke this task.
    PermissionDenied,
    /// The document's `recipient` does not identify the receiving consumer.
    WrongRecipient,
    /// An in-band `issuer` or `recipient` is inconsistent with the transport-
    /// authenticated identity for the same party.
    IdentityMismatch,
    /// The recipient party attempted the task and could not complete it.
    TaskFailed,
    /// The recipient party is temporarily unable to process the task.
    Unavailable,
    /// The recipient party encountered an unexpected internal failure.
    InternalError,
}

impl StandardCode {
    /// The default `retryable` value an emitter SHOULD use per SPEC.md §8.3,
    /// unless task-specific knowledge dictates otherwise.
    ///
    /// `TaskFailed` is `varies` in the spec; we treat its default as `false`.
    pub fn default_retryable(self) -> bool {
        matches!(
            self,
            StandardCode::Unavailable | StandardCode::InternalError
        )
    }

    /// The wire-form snake_case string for this code.
    pub fn as_str(self) -> &'static str {
        match self {
            StandardCode::MalformedRequest => "malformed_request",
            StandardCode::UnsupportedType => "unsupported_type",
            StandardCode::UnsupportedVersion => "unsupported_version",
            StandardCode::Expired => "expired",
            StandardCode::ProofRequired => "proof_required",
            StandardCode::ProofInvalid => "proof_invalid",
            StandardCode::PermissionDenied => "permission_denied",
            StandardCode::WrongRecipient => "wrong_recipient",
            StandardCode::IdentityMismatch => "identity_mismatch",
            StandardCode::TaskFailed => "task_failed",
            StandardCode::Unavailable => "unavailable",
            StandardCode::InternalError => "internal_error",
        }
    }
}

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

/// Reason a string fails to parse as a [`TrustTaskCode`].
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ParseCodeError {
    /// The code is empty.
    #[error("error code is empty")]
    Empty,
    /// The namespace portion before `:` is not a valid slug.
    #[error("extension code namespace {0:?} is not a valid slug")]
    InvalidNamespace(String),
    /// The local portion after `:` is empty or malformed.
    #[error("extension code local part {0:?} is invalid")]
    InvalidLocal(String),
}

impl FromStr for TrustTaskCode {
    type Err = ParseCodeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Err(ParseCodeError::Empty);
        }
        match s.split_once(':') {
            Some((slug, local)) => {
                validate_slug(slug)
                    .map_err(|_| ParseCodeError::InvalidNamespace(slug.to_string()))?;
                validate_local(local)
                    .map_err(|_| ParseCodeError::InvalidLocal(local.to_string()))?;
                Ok(TrustTaskCode::Extended {
                    slug: slug.to_string(),
                    local: local.to_string(),
                })
            }
            None => Ok(TrustTaskCode::Standard(parse_standard(s)?)),
        }
    }
}

impl fmt::Display for TrustTaskCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TrustTaskCode::Standard(c) => f.write_str(c.as_str()),
            TrustTaskCode::Extended { slug, local } => write!(f, "{slug}:{local}"),
        }
    }
}

impl From<StandardCode> for TrustTaskCode {
    fn from(code: StandardCode) -> Self {
        TrustTaskCode::Standard(code)
    }
}

/// Typed rejection conditions a conforming consumer raises while applying
/// SPEC.md §7.2.
///
/// Each variant carries the context needed to render a meaningful operator
/// message and maps to a single [`StandardCode`] from §8.3. The `From` impl
/// produces an [`ErrorPayload`] with the matching code, retryable default,
/// and a message derived from the variant's fields.
///
/// Use this on the consumer side to turn `?`-propagated errors from
/// `resolve_parties` / `validate_basic` / your own task logic into a
/// well-formed error response.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum RejectReason {
    /// The document did not validate against the framework or payload schema.
    #[error("malformed request: {reason}")]
    MalformedRequest {
        /// Human-readable explanation, surfaced as `message` in the response.
        reason: String,
    },

    /// The consumer does not implement this `type` URI.
    #[error("unsupported type: {type_uri}")]
    UnsupportedType {
        /// The unsupported Type URI as it appeared in the document.
        type_uri: String,
    },

    /// The consumer recognizes the type but not at this `MAJOR.MINOR`.
    #[error("unsupported version: {type_uri}")]
    UnsupportedVersion {
        /// The unsupported Type URI as it appeared in the document.
        type_uri: String,
    },

    /// The document's `expiresAt` was in the past.
    #[error("document expired at {expires_at}")]
    Expired {
        /// The expiry timestamp carried in the rejected document.
        expires_at: DateTime<Utc>,
    },

    /// A `proof` was required by the spec or consumer policy but was missing.
    #[error("proof required but not present")]
    ProofRequired,

    /// A `proof` was present but failed verification.
    #[error("proof verification failed: {reason}")]
    ProofInvalid {
        /// Human-readable explanation, surfaced as `message`.
        reason: String,
    },

    /// The requesting party is not authorized to invoke this task.
    #[error("permission denied: {reason}")]
    PermissionDenied {
        /// Human-readable explanation, surfaced as `message`.
        reason: String,
    },

    /// The document's `recipient` is set but does not identify the consumer.
    #[error("wrong recipient: in-band {in_band:?}, expected {expected:?}")]
    WrongRecipient {
        /// Value carried by the document's `recipient` member.
        in_band: String,
        /// VID of the consumer that received the document.
        expected: String,
    },

    /// An in-band party identity contradicts the transport-derived value.
    #[error(transparent)]
    IdentityMismatch(#[from] ConsistencyError),

    /// The task was attempted but could not be completed.
    #[error("task failed: {reason}")]
    TaskFailed {
        /// Human-readable explanation, surfaced as `message`.
        reason: String,
        /// Optional spec-defined extension data; carried verbatim into
        /// [`ErrorPayload::details`].
        details: Option<Value>,
    },

    /// The consumer is temporarily unable to process the task.
    #[error("temporarily unavailable")]
    Unavailable {
        /// Optional retry-after hint, surfaced as `retryAfter`.
        retry_after: Option<DateTime<Utc>>,
    },

    /// The consumer encountered an unexpected internal failure.
    #[error("internal error: {reason}")]
    InternalError {
        /// Human-readable explanation, surfaced as `message`.
        reason: String,
    },
}

impl RejectReason {
    /// The [`StandardCode`] that corresponds to this rejection.
    pub fn code(&self) -> StandardCode {
        match self {
            RejectReason::MalformedRequest { .. } => StandardCode::MalformedRequest,
            RejectReason::UnsupportedType { .. } => StandardCode::UnsupportedType,
            RejectReason::UnsupportedVersion { .. } => StandardCode::UnsupportedVersion,
            RejectReason::Expired { .. } => StandardCode::Expired,
            RejectReason::ProofRequired => StandardCode::ProofRequired,
            RejectReason::ProofInvalid { .. } => StandardCode::ProofInvalid,
            RejectReason::PermissionDenied { .. } => StandardCode::PermissionDenied,
            RejectReason::WrongRecipient { .. } => StandardCode::WrongRecipient,
            RejectReason::IdentityMismatch(_) => StandardCode::IdentityMismatch,
            RejectReason::TaskFailed { .. } => StandardCode::TaskFailed,
            RejectReason::Unavailable { .. } => StandardCode::Unavailable,
            RejectReason::InternalError { .. } => StandardCode::InternalError,
        }
    }

    /// Message safe to attach to a wire-serialised [`ErrorPayload`].
    ///
    /// SPEC.md §8.1 (final paragraph) and §10.4 require error-response
    /// messages to be free of consumer-side authentication context. The
    /// [`Display`](std::fmt::Display) implementation (and `to_string()`)
    /// is intentionally chatty for *diagnostic* purposes — it names both the
    /// in-band and the transport-authenticated identities under
    /// [`Self::IdentityMismatch`] and the consumer's own VID under
    /// [`Self::WrongRecipient`], which makes log lines actionable but is
    /// exactly the identity oracle a wire-exposed message must not provide.
    ///
    /// Variants whose `Display` is already consumer-side-neutral
    /// (`Expired`, `ProofInvalid`, …) return the same string the `Display`
    /// would. The variants that *do* leak identity return a sanitised
    /// constant.
    pub fn wire_message(&self) -> String {
        match self {
            // Identity-bearing rejections: sanitised constants. The
            // transport-derived and in-band values stay in logs only.
            RejectReason::IdentityMismatch(_) => {
                "in-band identity does not match transport-derived identity".to_string()
            }
            RejectReason::WrongRecipient { .. } => {
                "document recipient does not identify this consumer".to_string()
            }
            // All other variants carry no consumer-side authentication
            // context — their `Display` is safe for the wire.
            other => other.to_string(),
        }
    }
}

impl From<RejectReason> for ErrorPayload {
    fn from(reason: RejectReason) -> Self {
        let code = reason.code();
        let mut payload = ErrorPayload::new(code).with_message(reason.wire_message());
        match reason {
            RejectReason::Unavailable {
                retry_after: Some(when),
            } => {
                payload = payload.with_retry_after(when);
            }
            RejectReason::TaskFailed {
                details: Some(d), ..
            } => {
                payload = payload.with_details(d);
            }
            _ => {}
        }
        payload
    }
}

fn parse_standard(s: &str) -> Result<StandardCode, ParseCodeError> {
    Ok(match s {
        "malformed_request" => StandardCode::MalformedRequest,
        "unsupported_type" => StandardCode::UnsupportedType,
        "unsupported_version" => StandardCode::UnsupportedVersion,
        "expired" => StandardCode::Expired,
        "proof_required" => StandardCode::ProofRequired,
        "proof_invalid" => StandardCode::ProofInvalid,
        "permission_denied" => StandardCode::PermissionDenied,
        "wrong_recipient" => StandardCode::WrongRecipient,
        "identity_mismatch" => StandardCode::IdentityMismatch,
        "task_failed" => StandardCode::TaskFailed,
        "unavailable" => StandardCode::Unavailable,
        "internal_error" => StandardCode::InternalError,
        // A bare token that doesn't match a standard code is treated as a
        // malformed extension (extensions require a colon-namespaced slug).
        other => return Err(ParseCodeError::InvalidLocal(other.to_string())),
    })
}

fn validate_slug(slug: &str) -> Result<(), ()> {
    if slug.is_empty() {
        return Err(());
    }
    for segment in slug.split('/') {
        validate_segment(segment).ok_or(())?;
    }
    Ok(())
}

fn validate_segment(seg: &str) -> Option<()> {
    let mut chars = seg.chars();
    let first = chars.next()?;
    if !first.is_ascii_lowercase() {
        return None;
    }
    let mut prev_hyphen = false;
    for c in chars {
        match c {
            'a'..='z' | '0'..='9' => prev_hyphen = false,
            '-' => {
                if prev_hyphen {
                    return None;
                }
                prev_hyphen = true;
            }
            _ => return None,
        }
    }
    if prev_hyphen {
        return None;
    }
    Some(())
}

fn validate_local(local: &str) -> Result<(), ()> {
    // Per spec.meta.schema.json: ^[a-z][a-z0-9]*(-[a-z0-9]+)*(/[a-z][a-z0-9]*(-[a-z0-9]+)*)*$
    // for the prefix, and the local portion follows the same rule but
    // additionally permits underscores. We use that relaxed local grammar.
    let mut chars = local.chars();
    let first = chars.next().ok_or(())?;
    if !first.is_ascii_lowercase() {
        return Err(());
    }
    for c in chars {
        match c {
            'a'..='z' | '0'..='9' | '_' => {}
            _ => return Err(()),
        }
    }
    Ok(())
}

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

    #[test]
    fn round_trips_standard_codes() {
        for code in [
            StandardCode::MalformedRequest,
            StandardCode::UnsupportedType,
            StandardCode::UnsupportedVersion,
            StandardCode::Expired,
            StandardCode::ProofRequired,
            StandardCode::ProofInvalid,
            StandardCode::PermissionDenied,
            StandardCode::WrongRecipient,
            StandardCode::IdentityMismatch,
            StandardCode::TaskFailed,
            StandardCode::Unavailable,
            StandardCode::InternalError,
        ] {
            let wire = code.as_str();
            let parsed: TrustTaskCode = wire.parse().unwrap();
            assert_eq!(parsed, TrustTaskCode::Standard(code));
            assert_eq!(parsed.to_string(), wire);
        }
    }

    #[test]
    fn parses_extension_code() {
        let parsed: TrustTaskCode = "kyc-handoff:document_revoked".parse().unwrap();
        assert_eq!(
            parsed,
            TrustTaskCode::Extended {
                slug: "kyc-handoff".to_string(),
                local: "document_revoked".to_string(),
            }
        );
        assert_eq!(parsed.to_string(), "kyc-handoff:document_revoked");
    }

    #[test]
    fn parses_hierarchical_extension_code() {
        let parsed: TrustTaskCode = "acl/grant:permission_denied".parse().unwrap();
        assert!(matches!(
            parsed,
            TrustTaskCode::Extended { ref slug, ref local }
            if slug == "acl/grant" && local == "permission_denied"
        ));
    }

    #[test]
    fn rejects_invalid_namespace() {
        let err: ParseCodeError = "Bad:code".parse::<TrustTaskCode>().unwrap_err();
        assert!(matches!(err, ParseCodeError::InvalidNamespace(s) if s == "Bad"));
    }

    #[test]
    fn default_retryable_matches_spec_table() {
        assert!(!StandardCode::MalformedRequest.default_retryable());
        assert!(!StandardCode::Expired.default_retryable());
        assert!(StandardCode::Unavailable.default_retryable());
        assert!(StandardCode::InternalError.default_retryable());
    }

    #[test]
    fn serializes_payload_as_json() {
        let payload = ErrorPayload {
            code: StandardCode::Expired.into(),
            message: Some("expired".to_string()),
            retryable: false,
            retry_after: None,
            details: None,
        };
        let json = serde_json::to_value(&payload).unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "code": "expired",
                "message": "expired",
                "retryable": false
            })
        );
    }

    #[test]
    fn new_payload_takes_default_retryable() {
        let p = ErrorPayload::new(StandardCode::Expired);
        assert!(!p.retryable);
        let p = ErrorPayload::new(StandardCode::Unavailable);
        assert!(p.retryable);
    }

    #[test]
    fn builder_methods_compose() {
        let when: DateTime<Utc> = "2026-05-17T00:00:00Z".parse().unwrap();
        let payload = ErrorPayload::new(StandardCode::Unavailable)
            .with_message("nodes draining")
            .with_retry_after(when)
            .with_details(serde_json::json!({ "drain_eta": "30s" }));

        assert_eq!(payload.message.as_deref(), Some("nodes draining"));
        assert_eq!(payload.retry_after, Some(when));
        assert!(payload.retryable);
        assert!(payload.details.is_some());
    }

    #[test]
    fn effective_code_falls_back_for_extensions() {
        // SPEC §8.5: unrecognized extension codes are treated as task_failed
        // by consumers that don't implement the originating spec.
        let payload = ErrorPayload::new(TrustTaskCode::Extended {
            slug: "kyc-handoff".into(),
            local: "document_revoked".into(),
        });
        assert_eq!(payload.effective_code(), StandardCode::TaskFailed);

        let payload = ErrorPayload::new(StandardCode::Expired);
        assert_eq!(payload.effective_code(), StandardCode::Expired);
    }

    #[test]
    fn should_retry_at_respects_retryable_flag() {
        let now: DateTime<Utc> = "2026-05-17T12:00:00Z".parse().unwrap();
        let p = ErrorPayload::new(StandardCode::Expired);
        assert!(!p.should_retry_at(now));
    }

    #[test]
    fn should_retry_at_waits_for_retry_after() {
        let later: DateTime<Utc> = "2026-05-17T12:00:00Z".parse().unwrap();
        let now: DateTime<Utc> = "2026-05-17T11:59:00Z".parse().unwrap();
        let p = ErrorPayload::new(StandardCode::Unavailable).with_retry_after(later);
        assert!(!p.should_retry_at(now));
        assert!(p.should_retry_at(later));
    }

    #[test]
    fn reject_reason_maps_to_correct_code() {
        let cases: &[(RejectReason, StandardCode)] = &[
            (
                RejectReason::MalformedRequest { reason: "x".into() },
                StandardCode::MalformedRequest,
            ),
            (RejectReason::ProofRequired, StandardCode::ProofRequired),
            (
                RejectReason::Unavailable { retry_after: None },
                StandardCode::Unavailable,
            ),
        ];
        for (reason, expected) in cases {
            assert_eq!(reason.code(), *expected);
        }
    }

    #[test]
    fn reject_reason_into_payload_carries_message_and_details() {
        let payload: ErrorPayload = RejectReason::Expired {
            expires_at: "2026-04-12T09:31:00Z".parse().unwrap(),
        }
        .into();
        assert_eq!(payload.code, StandardCode::Expired.into());
        assert!(payload.message.as_deref().unwrap().contains("2026-04-12"));
        assert!(!payload.retryable);

        let payload: ErrorPayload = RejectReason::TaskFailed {
            reason: "downstream rejected".into(),
            details: Some(serde_json::json!({ "trace": "abc" })),
        }
        .into();
        assert!(payload.details.is_some());
    }

    #[test]
    fn consistency_error_flows_into_reject_reason_via_question_mark() {
        fn go() -> Result<(), RejectReason> {
            Err(ConsistencyError::IssuerMismatch {
                in_band: "did:web:a".into(),
                transport: "did:web:b".into(),
            })?;
            Ok(())
        }
        let err = go().unwrap_err();
        assert_eq!(err.code(), StandardCode::IdentityMismatch);
    }
}