aex-core 2.0.0-beta.1

Core types, traits, and errors for Agent Exchange Protocol (AEX).
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
//! Wire format **v2** — namespace-agnostic, AEX-branded prefix.
//!
//! This module is the v2 counterpart of [`crate::wire`]. The only semantic
//! changes versus v1 are:
//!
//! 1. **Prefix is brand-neutral**: every canonical message starts with
//!    `aex-<msg>:v2` instead of `spize-<msg>:v1`. The wire format no longer
//!    embeds a vendor name in cryptographically signed bytes.
//! 2. **Tighter clock skew window**: 60 seconds (down from 300s in v1).
//!    Aligns with JWT/OAuth2 RFC 7519 §4.1.4 norms — see ADR-0044.
//!    AgentId values inside the payload are expected to be W3C DID URIs
//!    (`did:method:specific-id[#fragment]`), but legacy `spize:` strings
//!    are still accepted at parse-time for the v1→v2 grace window.
//!
//! The byte-level shape (line-based, LF terminator, no trailing LF,
//! ASCII-only fields) is **identical** to v1. Existing signers/verifiers
//! that operate on raw bytes need only swap the bytes-producing function.
//!
//! See [`crate::wire`] for the v1 canonical formats kept stable for the
//! 30-day sunset grace defined in ADR-0036.

use crate::{Error, Result};

/// Wire protocol version produced by this module.
pub const PROTOCOL_VERSION_V2: &str = "v2";

/// Maximum acceptable clock skew between client and server for v2 messages,
/// in seconds. Tighter than v1's 300s; see ADR-0044.
pub const MAX_CLOCK_SKEW_SECS_V2: i64 = 60;

/// Minimum nonce length (hex chars). 32 chars = 128 bits of entropy.
/// Unchanged from v1 — entropy budget is the same regardless of prefix.
pub const MIN_NONCE_LEN: usize = 32;

/// Maximum nonce length (hex chars). Prevents pathological inputs.
pub const MAX_NONCE_LEN: usize = 128;

/// Check if `issued_at` is within the v2 allowed skew relative to `now`.
/// Overflow-safe under all `i64` inputs.
pub fn is_within_clock_skew_v2(now_unix: i64, issued_at_unix: i64) -> bool {
    let diff = (now_unix as i128).saturating_sub(issued_at_unix as i128);
    diff.unsigned_abs() <= MAX_CLOCK_SKEW_SECS_V2 as u128
}

/// Produce the canonical bytes a client signs to register an agent (v2).
///
/// Format:
/// ```text
/// aex-register:v2
/// pub={public_key_hex}
/// org={org}
/// name={name}
/// nonce={nonce}
/// ts={issued_at_unix}
/// ```
///
/// All inputs must be ASCII. Returns an error if any field contains
/// characters that could create canonicalization ambiguity (newlines,
/// NULs, non-ASCII).
pub fn registration_challenge_bytes_v2(
    public_key_hex: &str,
    org: &str,
    name: &str,
    nonce: &str,
    issued_at_unix: i64,
) -> Result<Vec<u8>> {
    validate_ascii_line(public_key_hex, "public_key_hex")?;
    validate_ascii_line(org, "org")?;
    validate_ascii_line(name, "name")?;
    validate_nonce(nonce)?;

    let msg = format!(
        "aex-register:{version}\npub={pub}\norg={org}\nname={name}\nnonce={nonce}\nts={ts}",
        version = PROTOCOL_VERSION_V2,
        pub = public_key_hex,
        org = org,
        name = name,
        nonce = nonce,
        ts = issued_at_unix,
    );
    Ok(msg.into_bytes())
}

/// Canonical bytes signed by the **sender** when initiating a transfer (v2).
///
/// Format:
/// ```text
/// aex-transfer-intent:v2
/// sender={sender_agent_id}
/// recipient={recipient}
/// size={size_bytes}
/// mime={declared_mime_or_empty}
/// filename={filename_or_empty}
/// nonce={nonce}
/// ts={issued_at_unix}
/// ```
///
/// `sender_agent_id` and `recipient` are expected to be either W3C DID
/// URIs (`did:method:id[#fragment]`) or legacy `spize:` ids during the
/// dual-wire grace window.
pub fn transfer_intent_bytes_v2(
    sender_agent_id: &str,
    recipient: &str,
    size_bytes: u64,
    declared_mime: &str,
    filename: &str,
    nonce: &str,
    issued_at_unix: i64,
) -> Result<Vec<u8>> {
    validate_ascii_line(sender_agent_id, "sender_agent_id")?;
    validate_ascii_line(recipient, "recipient")?;
    validate_ascii_line_opt(declared_mime, "declared_mime")?;
    validate_ascii_line_opt(filename, "filename")?;
    validate_nonce(nonce)?;

    let msg = format!(
        "aex-transfer-intent:{version}\nsender={sender}\nrecipient={recipient}\nsize={size}\nmime={mime}\nfilename={filename}\nnonce={nonce}\nts={ts}",
        version = PROTOCOL_VERSION_V2,
        sender = sender_agent_id,
        recipient = recipient,
        size = size_bytes,
        mime = declared_mime,
        filename = filename,
        nonce = nonce,
        ts = issued_at_unix,
    );
    Ok(msg.into_bytes())
}

/// Canonical bytes signed by the control plane when issuing a data-plane
/// ticket (v2). Semantically identical to v1; only the prefix changes.
///
/// ```text
/// aex-data-ticket:v2
/// transfer={transfer_id}
/// recipient={recipient_agent_id}
/// data_plane={data_plane_url}
/// expires={expires_unix}
/// nonce={nonce}
/// ```
pub fn data_ticket_bytes_v2(
    transfer_id: &str,
    recipient_agent_id: &str,
    data_plane_url: &str,
    expires_unix: i64,
    nonce: &str,
) -> Result<Vec<u8>> {
    validate_ascii_line(transfer_id, "transfer_id")?;
    validate_ascii_line(recipient_agent_id, "recipient_agent_id")?;
    validate_ascii_line(data_plane_url, "data_plane_url")?;
    validate_nonce(nonce)?;

    let msg = format!(
        "aex-data-ticket:{version}\ntransfer={tx}\nrecipient={rec}\ndata_plane={dp}\nexpires={exp}\nnonce={nonce}",
        version = PROTOCOL_VERSION_V2,
        tx = transfer_id,
        rec = recipient_agent_id,
        dp = data_plane_url,
        exp = expires_unix,
        nonce = nonce,
    );
    Ok(msg.into_bytes())
}

/// Canonical bytes signed by an agent's current key when requesting a
/// key rotation (v2). Mirrors the v1 protocol defined in ADR-0024.
///
/// ```text
/// aex-rotate-key:v2
/// agent={agent_id}
/// old_pub={current_public_key_hex}
/// new_pub={new_public_key_hex}
/// nonce={nonce}
/// ts={issued_at_unix}
/// ```
pub fn rotate_key_challenge_bytes_v2(
    agent_id: &str,
    old_public_key_hex: &str,
    new_public_key_hex: &str,
    nonce: &str,
    issued_at_unix: i64,
) -> Result<Vec<u8>> {
    validate_ascii_line(agent_id, "agent_id")?;
    validate_ascii_line(old_public_key_hex, "old_public_key_hex")?;
    validate_ascii_line(new_public_key_hex, "new_public_key_hex")?;
    validate_nonce(nonce)?;

    if old_public_key_hex == new_public_key_hex {
        return Err(Error::Internal(
            "old_public_key_hex and new_public_key_hex must differ".into(),
        ));
    }

    let msg = format!(
        "aex-rotate-key:{version}\nagent={agent}\nold_pub={old}\nnew_pub={new}\nnonce={nonce}\nts={ts}",
        version = PROTOCOL_VERSION_V2,
        agent = agent_id,
        old = old_public_key_hex,
        new = new_public_key_hex,
        nonce = nonce,
        ts = issued_at_unix,
    );
    Ok(msg.into_bytes())
}

/// Canonical bytes signed by the **recipient** when requesting a blob or
/// acknowledging delivery (v2).
pub fn transfer_receipt_bytes_v2(
    recipient_agent_id: &str,
    transfer_id: &str,
    action: &str,
    nonce: &str,
    issued_at_unix: i64,
) -> Result<Vec<u8>> {
    validate_ascii_line(recipient_agent_id, "recipient_agent_id")?;
    validate_ascii_line(transfer_id, "transfer_id")?;
    validate_ascii_line(action, "action")?;
    validate_nonce(nonce)?;

    if !matches!(action, "download" | "ack" | "inbox" | "request_ticket") {
        return Err(Error::Internal(format!(
            "action must be 'download', 'ack', 'inbox' or 'request_ticket', got {}",
            action
        )));
    }

    let msg = format!(
        "aex-transfer-receipt:{version}\nrecipient={rec}\ntransfer={tx}\naction={act}\nnonce={nonce}\nts={ts}",
        version = PROTOCOL_VERSION_V2,
        rec = recipient_agent_id,
        tx = transfer_id,
        act = action,
        nonce = nonce,
        ts = issued_at_unix,
    );
    Ok(msg.into_bytes())
}

/// Canonical bytes for an `aex-decision-request:v2` message.
///
/// Signed by the **recipient** and returned to the sender when an
/// inbound transfer cannot be answered synchronously — typically
/// because a deferred decider (human, secondary AI, policy engine,
/// or consensus) needs time to evaluate the request. The protocol
/// takes no position on who the decider is.
///
/// Format:
/// ```text
/// aex-decision-request:v2
/// recipient={recipient_agent_id}
/// transfer={transfer_id}
/// decision={decision_id}
/// eta_secs={eta_seconds}
/// nonce={nonce}
/// ts={issued_at_unix}
/// ```
///
/// `eta_seconds` is a non-negative integer hint for how long the
/// sender should expect to wait. `0` means "as soon as practical";
/// negative values are rejected.
///
/// Reference: ADR-0049.
pub fn decision_request_bytes_v2(
    recipient_agent_id: &str,
    transfer_id: &str,
    decision_id: &str,
    eta_seconds: u64,
    nonce: &str,
    issued_at_unix: i64,
) -> Result<Vec<u8>> {
    validate_ascii_line(recipient_agent_id, "recipient_agent_id")?;
    validate_ascii_line(transfer_id, "transfer_id")?;
    validate_ascii_line(decision_id, "decision_id")?;
    validate_nonce(nonce)?;

    let msg = format!(
        "aex-decision-request:{version}\nrecipient={rec}\ntransfer={tx}\ndecision={dec}\neta_secs={eta}\nnonce={nonce}\nts={ts}",
        version = PROTOCOL_VERSION_V2,
        rec = recipient_agent_id,
        tx = transfer_id,
        dec = decision_id,
        eta = eta_seconds,
        nonce = nonce,
        ts = issued_at_unix,
    );
    Ok(msg.into_bytes())
}

/// Canonical bytes for an `aex-decision-response:v2` message.
///
/// Signed by the **recipient** and sent to the sender once the
/// deferred decision has been taken. Carries the outcome and an
/// optional human-readable reason. Once a response is delivered for
/// a given `decision_id`, the decision is final — changing one's
/// mind requires a new transfer.
///
/// Format:
/// ```text
/// aex-decision-response:v2
/// recipient={recipient_agent_id}
/// transfer={transfer_id}
/// decision={decision_id}
/// outcome={accepted|rejected}
/// reason={reason_or_empty}
/// nonce={nonce}
/// ts={issued_at_unix}
/// ```
///
/// `outcome` is exactly one of `accepted` or `rejected`. `reason`
/// is optional (empty allowed). The verifier-side MUST persist
/// this message in the audit chain as a
/// [`SignedDecisionReceipt`](`crate`) event so the decision is
/// non-repudiable.
///
/// Reference: ADR-0049.
pub fn decision_response_bytes_v2(
    recipient_agent_id: &str,
    transfer_id: &str,
    decision_id: &str,
    outcome: &str,
    reason: &str,
    nonce: &str,
    issued_at_unix: i64,
) -> Result<Vec<u8>> {
    validate_ascii_line(recipient_agent_id, "recipient_agent_id")?;
    validate_ascii_line(transfer_id, "transfer_id")?;
    validate_ascii_line(decision_id, "decision_id")?;
    validate_ascii_line(outcome, "outcome")?;
    validate_ascii_line_opt(reason, "reason")?;
    validate_nonce(nonce)?;

    if !matches!(outcome, "accepted" | "rejected") {
        return Err(Error::Internal(format!(
            "outcome must be 'accepted' or 'rejected', got {}",
            outcome
        )));
    }

    let msg = format!(
        "aex-decision-response:{version}\nrecipient={rec}\ntransfer={tx}\ndecision={dec}\noutcome={out}\nreason={reason}\nnonce={nonce}\nts={ts}",
        version = PROTOCOL_VERSION_V2,
        rec = recipient_agent_id,
        tx = transfer_id,
        dec = decision_id,
        out = outcome,
        reason = reason,
        nonce = nonce,
        ts = issued_at_unix,
    );
    Ok(msg.into_bytes())
}

// ── shared validators (duplicate of wire.rs internals; intentional to
// keep v1 untouched and v2 self-contained) ──────────────────────────

fn validate_ascii_line(s: &str, field: &str) -> Result<()> {
    if s.is_empty() {
        return Err(Error::Internal(format!("{} is empty", field)));
    }
    for (i, c) in s.chars().enumerate() {
        if !c.is_ascii() || c == '\n' || c == '\r' || c == '\0' {
            return Err(Error::Internal(format!(
                "{} has invalid char at {}: {:?}",
                field, i, c
            )));
        }
    }
    Ok(())
}

fn validate_ascii_line_opt(s: &str, field: &str) -> Result<()> {
    if s.is_empty() {
        return Ok(());
    }
    validate_ascii_line(s, field)
}

fn validate_nonce(nonce: &str) -> Result<()> {
    if nonce.len() < MIN_NONCE_LEN || nonce.len() > MAX_NONCE_LEN {
        return Err(Error::Internal(format!(
            "nonce length {} outside [{}, {}]",
            nonce.len(),
            MIN_NONCE_LEN,
            MAX_NONCE_LEN
        )));
    }
    if !nonce.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(Error::Internal("nonce must be hex".into()));
    }
    Ok(())
}

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

    const NONCE: &str = "0123456789abcdef0123456789abcdef";

    #[test]
    fn v2_register_canonical_bytes_stable() {
        let bytes =
            registration_challenge_bytes_v2("aabbcc", "acme", "alice", NONCE, 1_700_000_000)
                .unwrap();
        let expected = "aex-register:v2\npub=aabbcc\norg=acme\nname=alice\nnonce=0123456789abcdef0123456789abcdef\nts=1700000000";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn v2_transfer_intent_uses_did_uri() {
        let bytes = transfer_intent_bytes_v2(
            "did:web:acme.com#agent-vendite",
            "did:web:beta-corp.com#acquisti",
            12345,
            "application/pdf",
            "invoice.pdf",
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        let expected = "aex-transfer-intent:v2\nsender=did:web:acme.com#agent-vendite\nrecipient=did:web:beta-corp.com#acquisti\nsize=12345\nmime=application/pdf\nfilename=invoice.pdf\nnonce=0123456789abcdef0123456789abcdef\nts=1700000000";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn v2_transfer_intent_with_legacy_spize_id() {
        // During grace window, v2 wire still accepts legacy `spize:` ids.
        let bytes = transfer_intent_bytes_v2(
            "spize:acme/alice:aabbcc",
            "did:ethr:0x14a34:0xabc",
            100,
            "",
            "",
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.starts_with("aex-transfer-intent:v2\n"));
        assert!(s.contains("sender=spize:acme/alice:aabbcc\n"));
        assert!(s.contains("recipient=did:ethr:0x14a34:0xabc\n"));
    }

    #[test]
    fn v2_data_ticket_stable() {
        let bytes = data_ticket_bytes_v2(
            "tx_abc123",
            "did:web:acme.com#bob",
            "https://data.acme.com",
            1_700_000_100,
            NONCE,
        )
        .unwrap();
        let expected = "aex-data-ticket:v2\ntransfer=tx_abc123\nrecipient=did:web:acme.com#bob\ndata_plane=https://data.acme.com\nexpires=1700000100\nnonce=0123456789abcdef0123456789abcdef";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn v2_rotate_key_stable() {
        let old = "1".repeat(64);
        let new = "2".repeat(64);
        let bytes = rotate_key_challenge_bytes_v2(
            "did:spize:acme/alice#aabbcc",
            &old,
            &new,
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.starts_with("aex-rotate-key:v2\n"));
        assert!(s.contains("agent=did:spize:acme/alice#aabbcc\n"));
    }

    #[test]
    fn v2_receipt_stable() {
        let bytes = transfer_receipt_bytes_v2(
            "did:web:beta-corp.com#acquisti",
            "tx_abc123",
            "ack",
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        let expected = "aex-transfer-receipt:v2\nrecipient=did:web:beta-corp.com#acquisti\ntransfer=tx_abc123\naction=ack\nnonce=0123456789abcdef0123456789abcdef\nts=1700000000";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn v2_clock_skew_60s_window() {
        let now = 1_700_000_000_i64;
        assert!(is_within_clock_skew_v2(now, now));
        assert!(is_within_clock_skew_v2(now, now - 60));
        assert!(is_within_clock_skew_v2(now, now + 60));
        assert!(!is_within_clock_skew_v2(now, now - 61));
        assert!(!is_within_clock_skew_v2(now, now + 61));
    }

    #[test]
    fn v2_clock_skew_extreme_inputs_do_not_panic() {
        let now = 1_700_000_000_i64;
        assert!(!is_within_clock_skew_v2(now, i64::MIN));
        assert!(!is_within_clock_skew_v2(now, i64::MAX));
        assert!(!is_within_clock_skew_v2(i64::MAX, i64::MIN));
    }

    #[test]
    fn v2_newline_in_field_rejected() {
        let err = registration_challenge_bytes_v2("aa", "ac\nme", "alice", NONCE, 100).unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn v2_non_ascii_field_rejected() {
        let err = registration_challenge_bytes_v2("aa", "acmè", "alice", NONCE, 100).unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn v2_short_nonce_rejected() {
        let err =
            registration_challenge_bytes_v2("aa", "acme", "alice", "deadbeef", 100).unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn v2_non_hex_nonce_rejected() {
        let err = registration_challenge_bytes_v2("aa", "acme", "alice", &"z".repeat(32), 100)
            .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn v2_rotate_key_rejects_same_old_and_new() {
        let same = "a".repeat(64);
        let err = rotate_key_challenge_bytes_v2(
            "did:spize:acme/alice#aabbcc",
            &same,
            &same,
            NONCE,
            1_700_000_000,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn v2_receipt_rejects_bad_action() {
        let err =
            transfer_receipt_bytes_v2("did:web:beta-corp.com#bob", "tx_abc", "overwrite", NONCE, 1)
                .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn v2_data_ticket_rejects_newline_url() {
        let err = data_ticket_bytes_v2(
            "tx_abc",
            "did:web:acme.com#bob",
            "https://evil.test\nspoof",
            1,
            NONCE,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn v2_decision_request_stable() {
        let bytes = decision_request_bytes_v2(
            "did:web:acme.com#agent-vendite",
            "tx_abc123",
            "dec_0001",
            86_400,
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        let expected = "aex-decision-request:v2\nrecipient=did:web:acme.com#agent-vendite\ntransfer=tx_abc123\ndecision=dec_0001\neta_secs=86400\nnonce=0123456789abcdef0123456789abcdef\nts=1700000000";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn v2_decision_response_accepted_stable() {
        let bytes = decision_response_bytes_v2(
            "did:web:acme.com#agent-vendite",
            "tx_abc123",
            "dec_0001",
            "accepted",
            "",
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        let expected = "aex-decision-response:v2\nrecipient=did:web:acme.com#agent-vendite\ntransfer=tx_abc123\ndecision=dec_0001\noutcome=accepted\nreason=\nnonce=0123456789abcdef0123456789abcdef\nts=1700000000";
        assert_eq!(bytes, expected.as_bytes());
    }

    #[test]
    fn v2_decision_response_rejected_with_reason_stable() {
        let bytes = decision_response_bytes_v2(
            "did:web:acme.com#agent-vendite",
            "tx_abc123",
            "dec_0001",
            "rejected",
            "operator declined: budget exceeded",
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.starts_with("aex-decision-response:v2\n"));
        assert!(s.contains("outcome=rejected\n"));
        assert!(s.contains("reason=operator declined: budget exceeded\n"));
    }

    #[test]
    fn v2_decision_response_rejects_bad_outcome() {
        let err = decision_response_bytes_v2(
            "did:web:acme.com#agent-vendite",
            "tx_abc123",
            "dec_0001",
            "maybe",
            "",
            NONCE,
            1_700_000_000,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn v2_decision_request_rejects_newline_in_fields() {
        let err = decision_request_bytes_v2(
            "did:web:acme.com#agent-vendite",
            "tx_abc\n123",
            "dec_0001",
            60,
            NONCE,
            1_700_000_000,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Internal(_)));
    }

    #[test]
    fn v2_decision_messages_distinguish_request_from_response() {
        // Two messages with the same business fields must produce
        // distinct bytes — the prefix differs (request vs response),
        // so signatures bound to one cannot replay as the other.
        let req = decision_request_bytes_v2(
            "did:web:acme.com#x",
            "tx_1",
            "dec_1",
            60,
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        let resp = decision_response_bytes_v2(
            "did:web:acme.com#x",
            "tx_1",
            "dec_1",
            "accepted",
            "",
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        assert_ne!(req, resp);
        assert!(std::str::from_utf8(&req)
            .unwrap()
            .starts_with("aex-decision-request:v2\n"));
        assert!(std::str::from_utf8(&resp)
            .unwrap()
            .starts_with("aex-decision-response:v2\n"));
    }

    #[test]
    fn v2_prefix_differs_from_v1_for_identical_inputs() {
        // Critical invariant: v1 and v2 bytes for the same logical message
        // are NEVER equal — they encode different wire versions and any
        // signature verifier must distinguish them.
        let v1 = crate::wire::registration_challenge_bytes(
            "aabbcc",
            "acme",
            "alice",
            NONCE,
            1_700_000_000,
        )
        .unwrap();
        let v2 = registration_challenge_bytes_v2("aabbcc", "acme", "alice", NONCE, 1_700_000_000)
            .unwrap();
        assert_ne!(v1, v2);
        // Specifically: v1 starts with "spize-", v2 with "aex-".
        assert!(std::str::from_utf8(&v1).unwrap().starts_with("spize-"));
        assert!(std::str::from_utf8(&v2).unwrap().starts_with("aex-"));
    }
}