aph-core 0.1.0

APH (Agent per Human) protocol v0.1 — envelope wire types, mandates, notarization flow state machines, and signing helpers
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
//! Property-based tests + golden vector parse tests for APH domain types.
//!
//! The single `use` statement is permitted (and required) by the
//! `proptest!` macro, which relies on identifiers from `proptest::prelude`
//! being in scope. Outside the proptest macro bodies, every other path is
//! fully qualified per house style.
//!
//! Coverage:
//! - serde round-trip on `NotarizationEnvelope`, `DelegationMandate`,
//!   `CommunicationMandate` (proptest-driven), in both the single-proof and
//!   the §7.1.11 two-element-chain wire forms.
//! - serde round-trip on `AphPartyRole` + `AphOperation` (table-driven).
//! - golden-vector parse for the 7 channel-specific envelopes shipped in
//!   `tests/golden/`.
//! - state-machine walks for `HumanPresentNotarizationFlow` (approved
//!   path) and `HumanNotPresentNotarizationFlow` (delivered path), plus
//!   one negative-transition assertion against `AphError::APH_E002`.

use proptest::prelude::*;

// ============================================================
// Shared constants for the proptest-built minimal envelopes.
// ============================================================

/// Fixed 64-char lowercase hex SHA-256 of empty input (RFC 6234 anchor).
/// Reused across every proptest envelope so the proptest only varies the
/// surrounding string fields.
const FIXED_BODY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

const FIXED_VALID_FROM: &str = "2026-05-21T00:00:00Z";
const FIXED_VALID_UNTIL: &str = "2026-05-22T00:00:00Z";

/// A minimal, fixed `NotaryAttested` envelope for tests that vary only the
/// `proof` member. Declared outside `proptest!` because the macro body is
/// the only place a bare `use` is permitted in this crate; building the
/// fixture here keeps the generated-input tests readable.
fn minimal_envelope() -> crate::envelope::NotarizationEnvelope {
  crate::envelope::NotarizationEnvelope {
    aph_version: std::string::String::from("0.1"),
    context: std::vec![
      std::string::String::from("https://www.w3.org/ns/credentials/v2"),
      std::string::String::from("https://w3id.org/aph/v1"),
    ],
    r#type: std::vec![
      std::string::String::from("VerifiableCredential"),
      std::string::String::from("AgentSendAuthorizationCredential"),
    ],
    id: std::string::String::from("urn:uuid:00000000-0000-4000-8000-000000000001"),
    issuer: std::string::String::from("did:key:zNotary"),
    valid_from: std::string::String::from(FIXED_VALID_FROM),
    valid_until: std::string::String::from(FIXED_VALID_UNTIL),
    credential_subject: crate::envelope::CredentialSubject {
      human_principal: crate::envelope::HumanPrincipalRef {
        id: std::string::String::from("did:key:zHuman"),
        display_name: std::string::String::from("Human"),
      },
      agent: crate::envelope::AgentRef {
        id: std::string::String::from("did:web:agent.squillo.com"),
        agent_card_uri: std::option::Option::None,
        display_name: std::string::String::from("Agent"),
        version: std::string::String::from("1.0"),
      },
      channel: crate::envelope::ChannelDescriptor {
        kind: crate::envelope::ChannelKind::Slack,
        recipient_addressing: serde_json::json!({"opaque": "addressing"}),
        recipient_class: std::option::Option::None,
      },
      communication: crate::envelope::CommunicationDescriptor {
        content_class: crate::envelope::ContentClass::Reply,
        body_sha256: std::string::String::from(FIXED_BODY_SHA256),
        body_size: 1842,
        preview_lines: 3,
        preview: std::string::String::from("preview"),
      },
      policy: crate::envelope::PolicyDescriptor {
        decision: crate::envelope::PolicyDecision::AskEveryTime,
        matched_scope: std::string::String::from("per-channel"),
        delegation_mandate_id: std::option::Option::None,
        act_chain: std::vec::Vec::new(),
        attestation_mode: std::option::Option::None,
        delegation_mandate: std::option::Option::None,
      },
      notarization: crate::envelope::NotarizationMetadata {
        notary_service: crate::envelope::NotaryServiceRef {
          id: std::string::String::from("did:web:notary.squillo.com"),
          name: std::string::String::from("Squillo Notary Service"),
          version: std::string::String::from("0.1.0"),
          attested_digest: std::option::Option::None,
          attestation_uri: std::option::Option::None,
        },
        decision_timestamp: std::string::String::from("2026-05-21T00:00:01Z"),
        decision_latency_ms: 1834,
      },
      apple_aur_acceptance: std::option::Option::None,
      audience: std::option::Option::None,
      act_classification: std::option::Option::None,
    },
    linked_mandate: std::option::Option::None,
    // Pattern A (§7.1.1): absent here means NO `credentialStatus` key on
    // the wire, which is what keeps this fixture byte-identical to the
    // pre-revocation shape its signatures were made over.
    credential_status: std::option::Option::None,
    proof: crate::envelope::EnvelopeProofs::Single(crate::envelope::EnvelopeProof {
      r#type: std::string::String::from("DataIntegrityProof"),
      cryptosuite: std::option::Option::Some(std::string::String::from("eddsa-jcs-2022")),
      verification_method: std::string::String::from("did:key:zNotary#zNotary"),
      created: std::string::String::from("2026-05-21T00:00:01Z"),
      proof_purpose: std::string::String::from("assertionMethod"),
      proof_value: std::string::String::from("zProofValueOpaque"),
      id: std::option::Option::None,
      previous_proof: std::option::Option::None,
    }),
  }
}

// ============================================================
// Proptest round-trip tests.
// ============================================================

proptest! {
  /// Serialize -> parse -> serialize cycle preserves a `NotarizationEnvelope`.
  /// The strategy generates short alpha strings for every text field; channel
  /// addressing is fixed to a Slack-shaped opaque JSON blob (the addressing
  /// field is `serde_json::Value`, so shape is irrelevant to the type).
  #[test]
  // Property test over generated DIDs and ids: round-tripping must hold
  // for arbitrary identifier content, not just the hand-written fixtures.
  // Guards against escaping or length assumptions that happen to work for
  // the sample values but fail on real-world identifiers.
  fn envelope_serde_roundtrip(
    id_tail in "[a-z]{1,20}",
    issuer_tail in "[a-z]{1,20}",
    human_did_tail in "[a-z]{1,20}",
    agent_did_tail in "[a-z]{1,20}",
    display_name in "[a-z]{1,20}",
    agent_display_name in "[a-z]{1,20}",
    agent_version in "[a-z]{1,20}",
    // INVERTED 2026-08-28. These drew `"[a-z]{1,20}"` and the body
    // asserted the envelope PARSED — so the suite carried a green test
    // claiming this implementation accepts channel kinds no published
    // spec defines, `service` among them, which is the exact divergence
    // the closed types were built to end. They now draw MEMBERS, and the
    // refusal of a non-member is pinned separately in
    // `envelope::closed_vocabulary_deserialization_tests`.
    channel_kind in proptest::sample::select(crate::envelope::ChannelKind::ALL.to_vec()),
    content_class in proptest::sample::select(crate::envelope::ContentClass::ALL.to_vec()),
    preview in "[a-z]{1,20}",
    decision in proptest::sample::select(crate::envelope::PolicyDecision::ALL.to_vec()),
    matched_scope in "[a-z]{1,20}",
    notary_name in "[a-z]{1,20}",
    notary_version in "[a-z]{1,20}",
  ) {
    let envelope = crate::envelope::NotarizationEnvelope {
      aph_version: std::string::String::from("0.1"),
      context: std::vec![
        std::string::String::from("https://www.w3.org/ns/credentials/v2"),
        std::string::String::from("https://w3id.org/aph/v1"),
      ],
      r#type: std::vec![
        std::string::String::from("VerifiableCredential"),
        std::string::String::from("AgentSendAuthorizationCredential"),
      ],
      id: std::format!("urn:uuid:{}", id_tail),
      issuer: std::format!("did:key:{}", issuer_tail),
      valid_from: std::string::String::from(FIXED_VALID_FROM),
      valid_until: std::string::String::from(FIXED_VALID_UNTIL),
      credential_subject: crate::envelope::CredentialSubject {
        human_principal: crate::envelope::HumanPrincipalRef {
          id: std::format!("did:key:{}", human_did_tail),
          display_name: display_name.clone(),
        },
        agent: crate::envelope::AgentRef {
          id: std::format!("did:web:{}", agent_did_tail),
          agent_card_uri: std::option::Option::None,
          display_name: agent_display_name.clone(),
          version: agent_version.clone(),
        },
        channel: crate::envelope::ChannelDescriptor {
          kind: channel_kind,
          recipient_addressing: serde_json::json!({"opaque": "addressing"}),
          recipient_class: std::option::Option::None,
        },
        communication: crate::envelope::CommunicationDescriptor {
          content_class: content_class,
          body_sha256: std::string::String::from(FIXED_BODY_SHA256),
          body_size: 1842,
          preview_lines: 3,
          preview: preview.clone(),
        },
        policy: crate::envelope::PolicyDescriptor {
          decision: decision,
          matched_scope: matched_scope.clone(),
          delegation_mandate_id: std::option::Option::None,
          act_chain: std::vec::Vec::new(),
          attestation_mode: std::option::Option::None,
          delegation_mandate: std::option::Option::None,
        },
        notarization: crate::envelope::NotarizationMetadata {
          notary_service: crate::envelope::NotaryServiceRef {
            id: std::string::String::from("did:web:notary.squillo.com"),
            name: notary_name.clone(),
            version: notary_version.clone(),
            attested_digest: std::option::Option::None,
            attestation_uri: std::option::Option::None,
          },
          decision_timestamp: std::string::String::from("2026-05-21T00:00:01Z"),
          decision_latency_ms: 1834,
        },
        apple_aur_acceptance: std::option::Option::None,
        audience: std::option::Option::None,
        act_classification: std::option::Option::None,
      },
      linked_mandate: std::option::Option::None,
      // Pattern A (§7.1.1): absent here means NO `credentialStatus` key on
      // the wire, which is what keeps this fixture byte-identical to the
      // pre-revocation shape its signatures were made over.
      credential_status: std::option::Option::None,
      proof: crate::envelope::EnvelopeProofs::Single(crate::envelope::EnvelopeProof {
        r#type: std::string::String::from("DataIntegrityProof"),
        cryptosuite: std::option::Option::Some(std::string::String::from("eddsa-jcs-2022")),
        verification_method: std::string::String::from(
          "did:key:zVerify#zVerify",
        ),
        created: std::string::String::from("2026-05-21T00:00:01Z"),
        proof_purpose: std::string::String::from("assertionMethod"),
        proof_value: std::string::String::from("zProofValueOpaque"),
        id: std::option::Option::None,
        previous_proof: std::option::Option::None,
      }),
    };

    let json = serde_json::to_string(&envelope).expect("serialize");
    let parsed: crate::envelope::NotarizationEnvelope =
      serde_json::from_str(&json).expect("deserialize");
    prop_assert_eq!(&envelope, &parsed);
  }

  /// A `PrincipalSigned` envelope — the two-element proof chain of §7.1.11 —
  /// round-trips with its linkage and label intact.
  #[test]
  // The untagged `proof` union means the JSON SHAPE is the only
  // discriminator between a lone notary proof and a chain. Sweeping
  // generated proof ids proves the array form is re-read as an array for
  // arbitrary identifier content: were it ever collapsed to an object, the
  // §7.2.1 domain separation between a principal proof and a lone notary
  // proof would silently disappear.
  fn envelope_proof_chain_serde_roundtrip(
    principal_id_tail in "[a-z]{1,20}",
    notary_id_tail in "[a-z]{1,20}",
    human_did_tail in "[a-z]{1,20}",
  ) {
    let human_did = std::format!("did:key:{}", human_did_tail);
    let principal_proof_id = std::format!("urn:uuid:{}", principal_id_tail);
    let mut envelope = minimal_envelope();
    envelope.credential_subject.human_principal.id = human_did.clone();
    envelope.credential_subject.policy.attestation_mode =
      std::option::Option::Some(crate::envelope::AttestationMode::PrincipalSigned);
    envelope.proof = crate::envelope::EnvelopeProofs::Chain(std::vec![
      crate::envelope::EnvelopeProof {
        r#type: std::string::String::from("DataIntegrityProof"),
        cryptosuite: std::option::Option::Some(std::string::String::from("eddsa-jcs-2022")),
        verification_method: std::format!("{}#{}", human_did, human_did_tail),
        created: std::string::String::from("2026-05-21T00:00:02Z"),
        proof_purpose: std::string::String::from("assertionMethod"),
        proof_value: std::string::String::from("z-illustrative-principal-proof"),
        id: std::option::Option::Some(principal_proof_id.clone()),
        previous_proof: std::option::Option::None,
      },
      crate::envelope::EnvelopeProof {
        r#type: std::string::String::from("DataIntegrityProof"),
        cryptosuite: std::option::Option::Some(std::string::String::from("eddsa-jcs-2022")),
        verification_method: std::string::String::from("did:key:zNotary#zNotary"),
        created: std::string::String::from("2026-05-21T00:00:03Z"),
        proof_purpose: std::string::String::from("authentication"),
        proof_value: std::string::String::from("z-illustrative-countersignature"),
        id: std::option::Option::Some(std::format!("urn:uuid:n-{}", notary_id_tail)),
        previous_proof: std::option::Option::Some(principal_proof_id),
      },
    ]);

    let json = serde_json::to_string(&envelope).expect("serialize");
    let parsed: crate::envelope::NotarizationEnvelope =
      serde_json::from_str(&json).expect("deserialize");
    prop_assert_eq!(&envelope, &parsed);
    prop_assert!(parsed.proof.is_chain());
    prop_assert_eq!(
      crate::verification::verify_proof_structure(&parsed).expect("well-formed chain"),
      crate::envelope::AttestationMode::PrincipalSigned
    );
  }

  /// `DelegationMandate` round-trips through serde_json with proptest-generated
  /// principal/agent DIDs, allowed channel kinds, and signature string.
  #[test]
  // Same generated-input sweep for the standing mandate: its fields are
  // signature-covered, so serialization must be stable across arbitrary
  // identifier content rather than only the sample() shape.
  fn delegation_mandate_serde_roundtrip(
    id_tail in "[a-z]{1,20}",
    human_did_tail in "[a-z]{1,20}",
    agent_did_tail in "[a-z]{1,20}",
    // Members, for the same reason the kind/class generators were
    // inverted: an arbitrary string here is no longer representable,
    // and drawing one asserted a grant this build cannot hold.
    channels in proptest::collection::vec(
      proptest::sample::select(crate::envelope::ChannelKind::ALL.to_vec()),
      1..=3,
    ),
    signature in "[a-z]{1,40}",
  ) {
    let mandate = crate::delegation_mandate::DelegationMandate {
      id: std::format!("urn:uuid:{}", id_tail),
      human_principal_did: std::format!("did:key:{}", human_did_tail),
      agent_did: std::format!("did:web:{}", agent_did_tail),
      allowed_channels: channels.clone(),
      allowed_recipient_classes: std::option::Option::None,
      rate_limit_per_hour: std::option::Option::None,
      valid_from: std::string::String::from(FIXED_VALID_FROM),
      valid_until: std::string::String::from(FIXED_VALID_UNTIL),
      principal_signature: std::format!("zprincipal-{}", signature),
      notary_signature: signature.clone(),
    };
    let json = serde_json::to_string(&mandate).expect("serialize");
    let parsed: crate::delegation_mandate::DelegationMandate =
      serde_json::from_str(&json).expect("deserialize");
    prop_assert_eq!(&mandate, &parsed);
  }

  /// `CommunicationMandate` round-trips through serde_json with proptest-generated
  /// channel + content_class + signature fields. `body_sha256` is fixed to the
  /// canonical 64-char lowercase hex SHA-256 of empty input.
  #[test]
  // Same for the per-message mandate, completing property coverage of all
  // three signed wire objects (envelope, delegation, communication).
  fn communication_mandate_serde_roundtrip(
    id_tail in "[a-z]{1,20}",
    human_did_tail in "[a-z]{1,20}",
    agent_did_tail in "[a-z]{1,20}",
    // Inverted for the same reason as the envelope generator above.
    channel_kind in proptest::sample::select(crate::envelope::ChannelKind::ALL.to_vec()),
    content_class in proptest::sample::select(crate::envelope::ContentClass::ALL.to_vec()),
    policy_decision in proptest::sample::select(crate::envelope::PolicyDecision::ALL.to_vec()),
    signature in "[a-z]{1,40}",
  ) {
    let mandate = crate::communication_mandate::CommunicationMandate {
      id: std::format!("urn:uuid:{}", id_tail),
      delegation_mandate_id: std::option::Option::None,
      human_principal_did: std::format!("did:key:{}", human_did_tail),
      agent_did: std::format!("did:web:{}", agent_did_tail),
      channel_kind: channel_kind,
      recipient_addressing: serde_json::json!({"opaque": "addressing"}),
      content_class: content_class,
      body_sha256: std::string::String::from(FIXED_BODY_SHA256),
      body_size: 1842,
      policy_decision: policy_decision,
      issued_at: std::string::String::from(FIXED_VALID_FROM),
      expires_at: std::string::String::from(FIXED_VALID_UNTIL),
      notary_signature: signature.clone(),
    };
    let json = serde_json::to_string(&mandate).expect("serialize");
    let parsed: crate::communication_mandate::CommunicationMandate =
      serde_json::from_str(&json).expect("deserialize");
    prop_assert_eq!(&mandate, &parsed);
  }
}

// ============================================================
// Table-driven role + operation serde round-trip.
// ============================================================

#[test]
fn role_serde_roundtrip() {
  // Cross-module check from outside roles.rs: confirms the enum is
  // round-trippable through the crate's public path, not just via the
  // in-module tests that can see private details.
  for role in crate::roles::AphPartyRole::all() {
    let json = serde_json::to_string(role).expect("role serialize");
    let parsed: crate::roles::AphPartyRole =
      serde_json::from_str(&json).expect("role deserialize");
    std::assert_eq!(*role, parsed);
  }
  for op in crate::roles::AphOperation::all() {
    let json = serde_json::to_string(op).expect("op serialize");
    let parsed: crate::roles::AphOperation =
      serde_json::from_str(&json).expect("op deserialize");
    std::assert_eq!(*op, parsed);
  }
}

// ============================================================
// Golden vector parse tests.
//
// Each test reads a checked-in JSON file via `include_str!` and asserts that
// it deserializes cleanly into `NotarizationEnvelope`. The strict
// `deny_unknown_fields` on every wire struct means a field-name drift
// between golden corpus and Rust types fails these tests.
//
// Path from this file:
//   src/prop_tests.rs -> ../tests/golden/<file>.json
// ============================================================

#[test]
fn golden_slack_reply_parses() {
  // Golden vectors are frozen wire samples: they must keep parsing under
  // deny_unknown_fields forever. This is the regression gate that catches
  // any field rename or removal that would orphan already-signed
  // envelopes. Slack exercises thread addressing (parentTs).
  let raw = std::include_str!("../tests/golden/slack_reply_envelope.json");
  let env: crate::envelope::NotarizationEnvelope =
    serde_json::from_str(raw).expect("slack golden parses");
  std::assert_eq!(env.credential_subject.channel.kind, crate::envelope::ChannelKind::Slack);
}

#[test]
fn golden_email_reply_parses() {
  // Email golden: array-valued addressing (to/cc/bcc) plus inReplyTo —
  // the shape most unlike the chat channels, so it guards against an
  // addressing model that only fits single-recipient platforms.
  let raw = std::include_str!("../tests/golden/email_reply_envelope.json");
  let env: crate::envelope::NotarizationEnvelope =
    serde_json::from_str(raw).expect("email golden parses");
  std::assert_eq!(env.credential_subject.channel.kind, crate::envelope::ChannelKind::Email);
}

#[test]
fn golden_discord_dm_parses() {
  // Discord golden: direct-message addressing, where matchedScope is
  // per-recipient rather than per-channel.
  let raw = std::include_str!("../tests/golden/discord_dm_envelope.json");
  let env: crate::envelope::NotarizationEnvelope =
    serde_json::from_str(raw).expect("discord golden parses");
  std::assert_eq!(env.credential_subject.channel.kind, crate::envelope::ChannelKind::Discord);
}

#[test]
fn golden_teams_channel_parses() {
  // Teams golden: three-part tenant/team/channel addressing, the deepest
  // addressing nesting in the corpus.
  let raw = std::include_str!("../tests/golden/teams_channel_envelope.json");
  let env: crate::envelope::NotarizationEnvelope =
    serde_json::from_str(raw).expect("teams golden parses");
  std::assert_eq!(env.credential_subject.channel.kind, crate::envelope::ChannelKind::Teams);
}

#[test]
fn golden_whatsapp_parses() {
  // WhatsApp golden: E.164 phone addressing — a bare identifier string
  // rather than a workspace/channel pair.
  let raw = std::include_str!("../tests/golden/whatsapp_envelope.json");
  let env: crate::envelope::NotarizationEnvelope =
    serde_json::from_str(raw).expect("whatsapp golden parses");
  std::assert_eq!(env.credential_subject.channel.kind, crate::envelope::ChannelKind::Whatsapp);
}

#[test]
fn golden_google_chat_parses() {
  // Google Chat golden: also pins the snake_case `google_chat` channel
  // kind fixed by the §7.1.5 erratum (early drafts said `googleChat`).
  let raw = std::include_str!("../tests/golden/google_chat_envelope.json");
  let env: crate::envelope::NotarizationEnvelope =
    serde_json::from_str(raw).expect("google_chat golden parses");
  std::assert_eq!(env.credential_subject.channel.kind, crate::envelope::ChannelKind::GoogleChat);
}

#[test]
fn golden_imessage_parses() {
  // iMessage golden: alternative addressing (appleId or phone), the one
  // channel whose recipient key is not fixed.
  let raw = std::include_str!("../tests/golden/imessage_envelope.json");
  let env: crate::envelope::NotarizationEnvelope =
    serde_json::from_str(raw).expect("imessage golden parses");
  std::assert_eq!(env.credential_subject.channel.kind, crate::envelope::ChannelKind::Imessage);
}

// ============================================================
// Flow state machine walk tests.
// ============================================================

#[test]
fn human_present_flow_walks_approved_path() {
  // Cross-module smoke: the flow is driven through its public API from
  // outside its own module, proving the machine is usable as exported
  // rather than only through module-internal helpers.
  let mut flow =
    crate::human_present_flow::HumanPresentNotarizationFlow::new("cm-test");
  std::assert_eq!(
    flow.state(),
    crate::human_present_flow::HumanPresentNotarizationState::Drafted,
  );
  flow
    .transition_to(
      crate::human_present_flow::HumanPresentNotarizationState::PendingDecision,
    )
    .expect("Drafted -> PendingDecision");
  flow
    .transition_to(crate::human_present_flow::HumanPresentNotarizationState::Approved)
    .expect("PendingDecision -> Approved");
  flow
    .transition_to(
      crate::human_present_flow::HumanPresentNotarizationState::MandateIssued,
    )
    .expect("Approved -> MandateIssued");
  flow
    .transition_to(
      crate::human_present_flow::HumanPresentNotarizationState::EnvelopeIssued,
    )
    .expect("MandateIssued -> EnvelopeIssued");
  flow
    .transition_to(crate::human_present_flow::HumanPresentNotarizationState::Delivered)
    .expect("EnvelopeIssued -> Delivered");
  std::assert!(flow.state().is_terminal());
}

#[test]
fn human_not_present_flow_walks_delivered_path() {
  // Same cross-module exercise for the standing-delegation machine, so
  // both flows are proven reachable through the crate's public surface.
  let mut flow =
    crate::human_not_present_flow::HumanNotPresentNotarizationFlow::new("dm-test");
  std::assert_eq!(
    flow.state(),
    crate::human_not_present_flow::HumanNotPresentNotarizationState::Drafted,
  );
  flow
    .transition_to(
      crate::human_not_present_flow::HumanNotPresentNotarizationState::MandateIssued,
    )
    .expect("Drafted -> MandateIssued");
  flow
    .transition_to(
      crate::human_not_present_flow::HumanNotPresentNotarizationState::EnvelopeIssued,
    )
    .expect("MandateIssued -> EnvelopeIssued");
  flow
    .transition_to(
      crate::human_not_present_flow::HumanNotPresentNotarizationState::Delivered,
    )
    .expect("EnvelopeIssued -> Delivered");
  std::assert!(flow.state().is_terminal());
}

#[test]
fn human_present_flow_rejects_skip() {
  // Re-pins the consent-bypass guard from outside the module: skipping
  // PendingDecision must fail through the public API too, since that is
  // the path a real caller would use to try it.
  let mut flow =
    crate::human_present_flow::HumanPresentNotarizationFlow::new("cm-test");
  let result = flow.transition_to(
    crate::human_present_flow::HumanPresentNotarizationState::MandateIssued,
  );
  let err = result.expect_err("Drafted -> MandateIssued must be rejected");
  std::assert_eq!(err.code(), "APH_E002");
}