polyc-crypto 2026.8.1

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
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
//! `ask_question` (`#1660`) signed-answer canonical, verification, and the
//! per-question correlation-token contract.
//!
//! A **sibling to the HITL approval flow's `approval_response` machinery in
//! [`crate::approval`], not a reuse of it** — see issue #1660 and its parent
//! PRD #1659. The trust shape is identical (THIN signing: an edge sends an
//! *unsigned* answer intent, the control plane resolves and signs
//! server-side, the harness re-verifies before trusting the answer) but the
//! signed canonical is its own, with its own field set and its own key names
//! (`question_call_id`/`question_index`, not `request_id`/`tool_name`), so an
//! approval signature can never verify as a question answer and vice versa.
//! The [`ApprovalSigner`] role intentionally covers this human-decision
//! answer family as well as tool approvals. Session, turn-read, web-session
//! grants, and journal roots use different roles.

use std::collections::HashSet;

use serde::Serialize;
use serde_json::Value;

use crate::approval::ApprovalSigner;
use crate::signed::{Envelope, canonical_bytes};
use crate::verify;

/// The signed `state` value for a question a human explicitly answered by
/// picking an option.
pub const ANSWERED_STATE: &str = "answered";
/// The signed `state` value for a question a human explicitly declined to
/// choose ("use your own judgment") — distinct from [`ANSWERED_STATE`] so the
/// agent never mistakes a decline for a real answer.
pub const DECLINED_STATE: &str = "declined";
/// The signed `state` value for a question nobody answered before its idle
/// window elapsed.
///
/// The control plane auto-resolved it to the recommended option (or the
/// first option if none was marked recommended). Signed and unforgeable, so
/// the agent is told this was an assumption, not a genuine human answer.
pub const AUTO_RESOLVED_STATE: &str = "auto_resolved";

/// TTL for a minted answer token (`#1660`).
///
/// Mirrors [`crate::approval::RESOLVE_TOKEN_TTL_MS`]'s reasoning: generous
/// enough that a human has time to see and answer the question card (which
/// can sit in a chat thread for hours or days), short enough that a token
/// captured off a stale card cannot answer the question indefinitely.
pub const ANSWER_TOKEN_TTL_MS: u64 = 24 * 60 * 60 * 1000;

/// The single source for the signed `question_response` canonical JSON. Both
/// the signing path ([`answer_payload`]) and the verifying paths
/// ([`verify_signed_answer`], [`verify_wire_answer`]) route through this so
/// the covered field set/order cannot drift. Adding/renaming/reordering here
/// is a signed-contract change.
///
/// Deliberately uses `question_call_id`/`question_index` rather than the
/// approval canonical's `request_id`/`tool_name` key names: even though both
/// canonicals are JSON objects an attacker might try to splice together, no
/// approval signature can ever verify against this shape (the signed BYTES
/// differ) and no answer signature can ever verify as an approval.
///
/// `question_args_json` is the `ask_question` call's full raw arguments (every
/// question in the call, not just this one) — the audit binding a verifier
/// matches against [`VerifiedQuestionAnswer::binds_question`], mirroring how
/// the approval canonical binds `args_json`. `conversation_id` and `nonce`
/// make the answer a single-use, conversation-bound capability, exactly like
/// `#370`'s approval-response token.
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
fn answer_canonical(
    call_id: &str,
    index: u32,
    question_args_json: &str,
    state: &str,
    selected_index: Option<u32>,
    selected_label: &str,
    answered_by: &str,
    conversation_id: &str,
    nonce: &str,
) -> Vec<u8> {
    canonical_bytes(&answer_fields(
        call_id,
        index,
        question_args_json,
        state,
        selected_index,
        selected_label,
        answered_by,
        conversation_id,
        nonce,
    ))
}

/// The signed `question_response` field set, in its frozen order.
///
/// Declaration order IS the signed contract — see [`canonical_bytes`] and ADR
/// 0009. `selected_index` is serialized as an explicit `null` for a decline
/// rather than skipped, which is what the `json!` object this replaced emitted
/// and therefore what every already-signed `question_response` in a
/// deployment's log covers.
#[derive(Serialize)]
struct AnswerCanonical<'a> {
    question_call_id: &'a str,
    question_index: u32,
    question_args_json: &'a str,
    state: &'a str,
    selected_index: Option<u32>,
    selected_label: &'a str,
    answered_by: &'a str,
    conversation_id: &'a str,
    nonce: &'a str,
}

/// The answer body both [`answer_canonical`] and [`answer_payload`] build, so
/// the signed field list exists once rather than in two hand-maintained copies
/// (`#1845`).
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
const fn answer_fields<'a>(
    call_id: &'a str,
    index: u32,
    question_args_json: &'a str,
    state: &'a str,
    selected_index: Option<u32>,
    selected_label: &'a str,
    answered_by: &'a str,
    conversation_id: &'a str,
    nonce: &'a str,
) -> AnswerCanonical<'a> {
    AnswerCanonical {
        question_call_id: call_id,
        question_index: index,
        question_args_json,
        state,
        selected_index,
        selected_label,
        answered_by,
        conversation_id,
        nonce,
    }
}

/// JSON payload for a `question_response` event.
///
/// The signature commits to the canonical (unsigned) JSON form: the question
/// identity (`call_id`, `index`, `question_args_json`), the resolution
/// (`state`/`selected_index`/`selected_label`), who resolved it
/// (`answered_by`, empty for [`AUTO_RESOLVED_STATE`]), and the
/// conversation/nonce binding. `signed_by`/`signature_hex` are populated
/// *after* the signer runs and are NOT covered by the signature.
///
/// Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
pub fn answer_payload(
    call_id: &str,
    index: u32,
    question_args_json: &str,
    state: &str,
    selected_index: Option<u32>,
    selected_label: &str,
    answered_by: &str,
    conversation_id: &str,
    nonce: &str,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        answer_fields(
            call_id,
            index,
            question_args_json,
            state,
            selected_index,
            selected_label,
            answered_by,
            conversation_id,
            nonce,
        ),
        signer.as_signer(),
    )
}

/// A verified, decoded `question_response` payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedQuestionAnswer {
    /// The `ask_question` tool-call id this answer resolves.
    pub call_id: String,
    /// This answer's question index within its call's `questions` array.
    pub index: u32,
    /// The bound raw `ask_question` call arguments (every question in the
    /// call) — the audit binding [`Self::binds_question`] matches
    /// byte-for-byte.
    pub question_args_json: String,
    /// One of [`ANSWERED_STATE`], [`DECLINED_STATE`], or
    /// [`AUTO_RESOLVED_STATE`].
    pub state: String,
    /// The chosen option's index, when `state == ANSWERED_STATE` or
    /// `AUTO_RESOLVED_STATE`. `None` for a decline.
    pub selected_index: Option<u32>,
    /// The chosen option's label, mirrored alongside the index so a consumer
    /// never has to re-resolve it against the (possibly since-compacted)
    /// original question payload.
    pub selected_label: String,
    /// Who answered — empty for [`AUTO_RESOLVED_STATE`] (nobody did).
    pub answered_by: String,
    /// The conversation this answer was signed for, covered by the
    /// signature so a token signed for one conversation cannot be replayed
    /// into another.
    pub conversation_id: String,
    /// Per-answer unique value, covered by the signature. A consumer
    /// records it on use so the answer cannot be re-applied once spent
    /// (single-use, mirrors `#370`).
    pub nonce: String,
    /// The verified signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
    /// Hex-encoded ed25519 public key of the signer — the same bytes as
    /// [`Self::signer_public_key`], kept alongside it in the wire-ready
    /// encoding so a consumer forwarding this answer onward (the control
    /// plane's outstanding-answer collector, to the harness) never
    /// re-derives the hex itself. Mirrors
    /// `polyc_crypto::approval::DecodedResponse::signer_pk_hex`.
    pub signer_pk_hex: String,
    /// Hex-encoded ed25519 signature over the canonical answer tuple —
    /// forwarded onward so the harness can independently re-verify (THIN
    /// signing) rather than trust the control plane's own verification.
    /// Mirrors `polyc_crypto::approval::DecodedResponse::signature_hex`.
    pub signature_hex: String,
}

impl VerifiedQuestionAnswer {
    /// Whether this verified answer is bound to the EXACT question
    /// `(call_id, index, question_args_json)` — the args-binding a resume
    /// path must check before applying the answer, mirroring
    /// [`crate::approval::VerifiedResponse::authorizes_call`].
    #[must_use]
    pub fn binds_question(&self, call_id: &str, index: u32, question_args_json: &str) -> bool {
        self.call_id == call_id
            && self.index == index
            && self.question_args_json == question_args_json
    }
}

/// Verify a persisted `question_response` payload.
///
/// Returns `Some(record)` if the signature checks out against the embedded
/// public key (the caller is responsible for trusting that public key — see
/// [`verify_signed_answer_pinned`]). Returns `None` if the payload is
/// malformed, the hex fields don't decode, or the signature doesn't verify.
#[must_use]
pub fn verify_signed_answer(payload: &[u8]) -> Option<VerifiedQuestionAnswer> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    let call_id = v.get("question_call_id")?.as_str()?.to_owned();
    let index = u32::try_from(v.get("question_index")?.as_u64()?).ok()?;
    let question_args_json = v.get("question_args_json")?.as_str()?.to_owned();
    let state = v.get("state")?.as_str()?.to_owned();
    let selected_index = match v.get("selected_index") {
        Some(Value::Null) | None => None,
        Some(x) => Some(u32::try_from(x.as_u64()?).ok()?),
    };
    let selected_label = v.get("selected_label")?.as_str()?.to_owned();
    let answered_by = v.get("answered_by")?.as_str()?.to_owned();
    let conversation_id = v.get("conversation_id")?.as_str()?.to_owned();
    let nonce = v.get("nonce")?.as_str()?.to_owned();
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;

    let canonical = answer_canonical(
        &call_id,
        index,
        &question_args_json,
        &state,
        selected_index,
        &selected_label,
        &answered_by,
        &conversation_id,
        &nonce,
    );
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedQuestionAnswer {
            call_id,
            index,
            question_args_json,
            state,
            selected_index,
            selected_label,
            answered_by,
            conversation_id,
            nonce,
            signer_pk_hex: crate::hex::lower(&pk),
            signature_hex: crate::hex::lower(&sig),
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// Verify a persisted `question_response` payload against a **trusted-signer
/// allow-list**.
///
/// Mirrors [`crate::approval::verify_signed_response_pinned`]: without this
/// gate an attacker could sign a well-formed answer with their own key,
/// embed it, and have it honored. Returns `None` (fail closed) on a
/// malformed payload, an untrusted signer, or a bad signature.
#[must_use]
pub fn verify_signed_answer_pinned(
    payload: &[u8],
    trusted_signers: &[Vec<u8>],
) -> Option<VerifiedQuestionAnswer> {
    let verified = verify_signed_answer(payload)?;
    if !trusted_signers
        .iter()
        .any(|k| k.as_slice() == verified.signer_public_key)
    {
        return None;
    }
    Some(verified)
}

/// Verify a persisted `question_response` as a SINGLE-USE, conversation-bound
/// capability (invariant I3/I7), gated on a trusted-signer allow-list.
///
/// Returns the verified answer only when ALL hold: the embedded signer is
/// trusted; the signature verifies; the signed `conversation_id` equals
/// `conversation_id`; the signed `nonce` is non-empty AND not already in
/// `consumed`. The caller MUST record the returned nonce into its `consumed`
/// set before honoring the answer, so a second presentation is rejected.
#[must_use]
pub fn verify_answer_capability<S: std::hash::BuildHasher>(
    payload: &[u8],
    conversation_id: &str,
    consumed: &HashSet<String, S>,
    trusted_signers: &[Vec<u8>],
) -> Option<VerifiedQuestionAnswer> {
    let verified = verify_signed_answer_pinned(payload, trusted_signers)?;
    if verified.conversation_id != conversation_id {
        return None;
    }
    if verified.nonce.is_empty() || consumed.contains(&verified.nonce) {
        return None;
    }
    Some(verified)
}

/// Verify a wire-form `question_response`, binding the answer to its full
/// signed identity.
///
/// Used by the harness when it receives an answer over the wire and must
/// confirm provenance AND identity before feeding it back into the turn as
/// the `ask_question` call's result — the trust boundary this exists for:
/// silent acceptance would let a compromised control plane forge a user's
/// answer. Returns `true` only if `signer_pk_hex + signature_hex` validates
/// against the canonical.
#[must_use]
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field of the canonical contract
pub fn verify_wire_answer(
    call_id: &str,
    index: u32,
    question_args_json: &str,
    state: &str,
    selected_index: Option<u32>,
    selected_label: &str,
    answered_by: &str,
    conversation_id: &str,
    nonce: &str,
    signer_pk_hex: &str,
    signature_hex: &str,
) -> bool {
    let Some(pk) = crate::hex::decode(signer_pk_hex) else {
        return false;
    };
    let Some(sig) = crate::hex::decode(signature_hex) else {
        return false;
    };
    let canonical = answer_canonical(
        call_id,
        index,
        question_args_json,
        state,
        selected_index,
        selected_label,
        answered_by,
        conversation_id,
        nonce,
    );
    verify(&pk, &canonical, &sig)
}

// ── Per-question correlation token ──────────────────────────────────────────

/// The canonical (signature-covered) form of an answer token (`#1660`).
///
/// Deliberately uses the SAME `question_call_id`/`question_index` key names
/// [`answer_canonical`] uses, but a DIFFERENT key set than
/// [`crate::approval`]'s `resolve_token_canonical` (`request_id` vs
/// `question_call_id`) — an approval resolve token must never verify as an
/// answer token and vice versa; [`verify_answer_token`]'s own test pins this
/// cross-domain rejection.
fn answer_token_canonical(
    call_id: &str,
    index: u32,
    conversation_id: &str,
    minted_at_ms: u64,
) -> Vec<u8> {
    canonical_bytes(&AnswerTokenCanonical {
        question_call_id: call_id,
        question_index: index,
        conversation_id,
        minted_at_ms,
    })
}

/// The signed answer-token field set, in its frozen order. See ADR 0009.
#[derive(Serialize)]
struct AnswerTokenCanonical<'a> {
    question_call_id: &'a str,
    question_index: u32,
    conversation_id: &'a str,
    minted_at_ms: u64,
}

/// A minted answer token: the canonical body plus its signature.
///
/// The token carries no `signed_by` — it is verified against the control
/// plane's own key, supplied by the caller of [`verify_answer_token`], never
/// one carried on the token itself. Mirrors
/// `polyc_crypto::approval::mint_resolve_token`'s shape, so
/// [`crate::signed::Envelope`] (which always writes both provenance fields)
/// does not apply here.
#[derive(Serialize)]
struct AnswerToken<'a> {
    #[serde(flatten)]
    body: AnswerTokenCanonical<'a>,
    signature_hex: String,
}

/// Mint a short-lived, signed answer token scoped to one pending question.
///
/// Scoped to `(call_id, index, conversation_id)` — the correlation-token
/// contract every downstream edge slice (#1661-#1664) consumes unchanged.
/// Mirrors [`crate::approval::mint_resolve_token`]'s shape and
/// unforgeability argument: opaque to, and unforgeable by, anything
/// downstream of the mint point. `minted_at_ms` is the caller's wall clock
/// at mint time; pass a real timestamp in production, an injected one in
/// tests.
///
/// Returns the token as a lowercase-hex opaque string, safe to carry on any
/// wire surface (a button value, a proto field) alongside `call_id`/`index`.
#[must_use]
pub fn mint_answer_token(
    call_id: &str,
    index: u32,
    conversation_id: &str,
    minted_at_ms: u64,
    signer: &ApprovalSigner,
) -> String {
    // Built once and reused for both the signature and the envelope. Writing the
    // field list a second time here would be a second hand-maintained copy of a
    // signed field set — the drift this module's `answer_fields` exists to stop.
    let body = AnswerTokenCanonical {
        question_call_id: call_id,
        question_index: index,
        conversation_id,
        minted_at_ms,
    };
    let signature = signer.sign(&canonical_bytes(&body));
    let full = AnswerToken {
        body,
        signature_hex: crate::hex::lower(&signature),
    };
    crate::hex::lower(&canonical_bytes(&full))
}

/// Verify an answer token minted by [`mint_answer_token`] against the
/// `(call_id, index, conversation_id)` a `Respond` call presents it for.
///
/// Returns `true` only when ALL hold: the token decodes; its embedded
/// signature verifies against `signer`'s public key; its bound identity
/// equals the ones supplied; and `now_ms - minted_at_ms` is within
/// [`ANSWER_TOKEN_TTL_MS`] (a token minted in the future, by clock skew
/// beyond the TTL, also fails — fail closed rather than trust an
/// out-of-bounds clock). Fails closed on any malformed field.
#[must_use]
pub fn verify_answer_token(
    token: &str,
    call_id: &str,
    index: u32,
    conversation_id: &str,
    now_ms: u64,
    signer: &ApprovalSigner,
) -> bool {
    let Some(bytes) = crate::hex::decode(token) else {
        return false;
    };
    let Ok(v) = serde_json::from_slice::<Value>(&bytes) else {
        return false;
    };
    let (
        Some(bound_call_id),
        Some(bound_index),
        Some(bound_conversation_id),
        Some(minted_at_ms),
        Some(signature_hex),
    ) = (
        v.get("question_call_id").and_then(Value::as_str),
        v.get("question_index").and_then(Value::as_u64),
        v.get("conversation_id").and_then(Value::as_str),
        v.get("minted_at_ms").and_then(Value::as_u64),
        v.get("signature_hex").and_then(Value::as_str),
    )
    else {
        return false;
    };
    let Ok(bound_index) = u32::try_from(bound_index) else {
        return false;
    };
    if bound_call_id != call_id || bound_index != index || bound_conversation_id != conversation_id
    {
        return false;
    }
    let elapsed = now_ms.abs_diff(minted_at_ms);
    if elapsed > ANSWER_TOKEN_TTL_MS {
        return false;
    }
    let Some(sig) = crate::hex::decode(signature_hex) else {
        return false;
    };
    let canonical = answer_token_canonical(
        bound_call_id,
        bound_index,
        bound_conversation_id,
        minted_at_ms,
    );
    verify(&signer.public_key_bytes(), &canonical, &sig)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    fn valid_answer_payload(signer: &ApprovalSigner) -> Vec<u8> {
        answer_payload(
            "call-1",
            0,
            r#"{"questions":[]}"#,
            ANSWERED_STATE,
            Some(1),
            "Production",
            "slack:T1:U9",
            "conv-A",
            "nonce-A",
            signer,
        )
        .0
    }

    #[test]
    fn signed_answer_round_trips() {
        let signer = ApprovalSigner::from_seed(1);
        let payload = valid_answer_payload(&signer);
        let verified = verify_signed_answer(&payload).expect("signature verifies");
        assert_eq!(verified.call_id, "call-1");
        assert_eq!(verified.index, 0);
        assert_eq!(verified.state, ANSWERED_STATE);
        assert_eq!(verified.selected_index, Some(1));
        assert_eq!(verified.selected_label, "Production");
        assert_eq!(verified.answered_by, "slack:T1:U9");
        assert!(verified.binds_question("call-1", 0, r#"{"questions":[]}"#));
        assert!(!verified.binds_question("call-2", 0, r#"{"questions":[]}"#));
    }

    /// `#1660` Step 7: the decoded record carries the RAW signer/signature
    /// hex alongside the verified fields — not just `signer_public_key`
    /// bytes — so a consumer (the control plane's outstanding-answer
    /// collector) can re-forward the exact signed bytes to the harness for
    /// its own independent re-verification (THIN signing), mirroring
    /// `polyc_crypto::approval::DecodedResponse::{signer_pk_hex,
    /// signature_hex}`.
    #[test]
    fn verified_answer_carries_raw_signer_and_signature_hex() {
        let signer = ApprovalSigner::from_seed(1);
        let payload = valid_answer_payload(&signer);
        let verified = verify_signed_answer(&payload).expect("signature verifies");
        assert_eq!(
            verified.signer_pk_hex,
            crate::hex::lower(&signer.public_key_bytes())
        );
        assert!(!verified.signature_hex.is_empty());
        // The hex must actually verify against the canonical this payload
        // signs — not just be non-empty — so re-derive the signature bytes
        // and check them against `verify` directly.
        let sig_bytes = crate::hex::decode(&verified.signature_hex).expect("valid hex");
        let canonical = answer_canonical(
            &verified.call_id,
            verified.index,
            &verified.question_args_json,
            &verified.state,
            verified.selected_index,
            &verified.selected_label,
            &verified.answered_by,
            &verified.conversation_id,
            &verified.nonce,
        );
        assert!(verify(&signer.public_key_bytes(), &canonical, &sig_bytes));
    }

    #[test]
    fn declined_and_auto_resolved_states_round_trip_with_no_selection_or_answerer() {
        let signer = ApprovalSigner::from_seed(1);
        let (payload, ..) = answer_payload(
            "call-1",
            0,
            "{}",
            DECLINED_STATE,
            None,
            "",
            "slack:T1:U9",
            "conv-A",
            "nonce-B",
            &signer,
        );
        let v = verify_signed_answer(&payload).expect("verifies");
        assert_eq!(v.state, DECLINED_STATE);
        assert_eq!(v.selected_index, None);

        let (payload, ..) = answer_payload(
            "call-1",
            0,
            "{}",
            AUTO_RESOLVED_STATE,
            Some(0),
            "Staging",
            "",
            "conv-A",
            "nonce-C",
            &signer,
        );
        let v = verify_signed_answer(&payload).expect("verifies");
        assert_eq!(v.state, AUTO_RESOLVED_STATE);
        assert_eq!(
            v.answered_by, "",
            "nobody answered an auto-resolved question"
        );
    }

    /// Invariant I3: every signed field is covered — tampering with any one
    /// (the state, the selection, who answered, the conversation, or the
    /// nonce) must fail verification.
    #[test]
    fn tampered_state_or_selection_fails_verification() {
        let signer = ApprovalSigner::from_seed(1);
        let payload = valid_answer_payload(&signer);
        let mut v: Value = serde_json::from_slice(&payload).unwrap();
        for (field, val) in [
            ("state", Value::String(DECLINED_STATE.to_owned())),
            ("selected_index", Value::Number(2.into())),
            ("selected_label", Value::String("Staging".into())),
            ("answered_by", Value::String("slack:T1:U0".into())),
            ("conversation_id", Value::String("conv-B".into())),
            ("nonce", Value::String("nonce-Z".into())),
            ("question_call_id", Value::String("call-2".into())),
            ("question_index", Value::Number(1.into())),
        ] {
            let mut tampered = v.clone();
            tampered[field] = val;
            let bytes = serde_json::to_vec(&tampered).unwrap();
            assert!(
                verify_signed_answer(&bytes).is_none(),
                "tampering `{field}` must invalidate the signature"
            );
        }
        // Sanity: the untampered payload still verifies.
        assert!(verify_signed_answer(&serde_json::to_vec(&v.take()).unwrap()).is_some());
    }

    /// Invariant I3: a signature from a signer outside the trusted allow-list
    /// authorizes nothing, even though it is internally self-consistent.
    #[test]
    fn answer_from_non_allowlisted_signer_is_rejected() {
        let trusted = ApprovalSigner::from_seed(1);
        let attacker = ApprovalSigner::from_seed(666);
        let payload = valid_answer_payload(&attacker);
        assert!(
            verify_signed_answer_pinned(&payload, &[trusted.public_key_bytes()]).is_none(),
            "an untrusted signer's answer must never verify"
        );
        assert!(
            verify_signed_answer_pinned(&payload, &[attacker.public_key_bytes()]).is_some(),
            "sanity: the attacker's own key does verify its own signature"
        );
    }

    /// Invariant I3/`#370`-style replay guard: a token signed for one
    /// conversation must be rejected when presented for another, even though
    /// every other field is byte-identical.
    #[test]
    fn answer_rejected_across_conversations() {
        let signer = ApprovalSigner::from_seed(1);
        let payload = valid_answer_payload(&signer);
        let consumed = HashSet::new();
        assert!(
            verify_answer_capability(&payload, "conv-A", &consumed, &[signer.public_key_bytes()])
                .is_some()
        );
        assert!(
            verify_answer_capability(&payload, "conv-B", &consumed, &[signer.public_key_bytes()])
                .is_none(),
            "an answer signed for conv-A must be rejected when presented for conv-B"
        );
    }

    /// Invariant I2/I7: a single-use answer is rejected on a second
    /// presentation, mirroring `capability_is_single_use` for approvals.
    #[test]
    fn question_answer_capability_is_single_use() {
        let signer = ApprovalSigner::from_seed(1);
        let payload = valid_answer_payload(&signer);
        let mut consumed = HashSet::new();
        let v =
            verify_answer_capability(&payload, "conv-A", &consumed, &[signer.public_key_bytes()])
                .expect("first use honored");
        assert_eq!(v.nonce, "nonce-A");
        consumed.insert(v.nonce.clone());
        assert!(
            verify_answer_capability(&payload, "conv-A", &consumed, &[signer.public_key_bytes()])
                .is_none(),
            "a spent answer must be rejected on re-presentation"
        );
    }

    /// Cross-domain canonical separation: an approval's own signed
    /// `approval_response`/`resolve_token` bytes must never verify as a
    /// question answer/token, and vice versa — the two canonicals use
    /// different key names specifically so this can never accidentally work.
    #[test]
    fn approval_payloads_never_verify_as_question_answers() {
        let signer = ApprovalSigner::from_seed(1);
        let (approval_payload, ..) = crate::approval::response_payload(
            "call-1",
            "ask_question",
            r#"{"questions":[]}"#,
            "",
            true,
            false,
            &[],
            "slack:T1:U9",
            "",
            "",
            "",
            "",
            "conv-A",
            "nonce-A",
            &signer,
        );
        assert!(
            verify_signed_answer(&approval_payload).is_none(),
            "an approval_response payload must never decode+verify as a question_response"
        );

        let resolve_token = crate::approval::mint_resolve_token("call-1", "conv-A", 1_000, &signer);
        assert!(
            !verify_answer_token(&resolve_token, "call-1", 0, "conv-A", 1_000, &signer),
            "an approval resolve_token must never verify as an answer token"
        );
    }

    /// `polyc_proto::tool_display::question_answered_text` duplicates
    /// `ANSWERED_STATE`/`DECLINED_STATE`/`AUTO_RESOLVED_STATE` as local
    /// string literals (`polyc-proto` can't depend on `polyc-crypto` for the
    /// real consts — see that function's own doc for the layer reason).
    /// `polyc-crypto` depends on `polyc-proto`, so this crate is the one
    /// that CAN cross-check them: feed this crate's own real consts in and
    /// confirm each produces its OWN distinct sentence shape, not the
    /// declined-shaped fallback every unrecognized string renders as.
    #[test]
    fn proto_question_answered_text_recognizes_this_crates_real_state_consts() {
        let answered = polyc_proto::question_answered_text(
            "Deploy target",
            ANSWERED_STATE,
            "@ada",
            "Production",
        );
        assert!(
            answered.contains("@ada answered"),
            "ANSWERED_STATE must render as a real answer, not the declined fallback: {answered}"
        );

        let auto_resolved = polyc_proto::question_answered_text(
            "Deploy target",
            AUTO_RESOLVED_STATE,
            "",
            "Production",
        );
        assert!(
            auto_resolved.contains("Nobody answered"),
            "AUTO_RESOLVED_STATE must render as an assumption, not the declined fallback: {auto_resolved}"
        );

        let declined =
            polyc_proto::question_answered_text("Deploy target", DECLINED_STATE, "@ada", "");
        assert!(
            declined.contains("@ada declined"),
            "DECLINED_STATE must render as a real decline: {declined}"
        );
    }
}

#[cfg(test)]
mod answer_token_tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use super::*;

    #[test]
    fn answer_token_verifies_for_its_own_question() {
        let signer = ApprovalSigner::from_seed(11);
        let token = mint_answer_token("call-1", 0, "conv-A", 1_000, &signer);
        assert!(verify_answer_token(
            &token, "call-1", 0, "conv-A", 1_000, &signer
        ));
    }

    #[test]
    fn answer_token_rejects_a_different_question_index() {
        let signer = ApprovalSigner::from_seed(11);
        let token = mint_answer_token("call-1", 0, "conv-A", 1_000, &signer);
        assert!(!verify_answer_token(
            &token, "call-1", 1, "conv-A", 1_000, &signer
        ));
    }

    #[test]
    fn answer_token_rejects_a_different_call_id() {
        let signer = ApprovalSigner::from_seed(11);
        let token = mint_answer_token("call-1", 0, "conv-A", 1_000, &signer);
        assert!(!verify_answer_token(
            &token, "call-2", 0, "conv-A", 1_000, &signer
        ));
    }

    #[test]
    fn answer_token_rejects_a_different_conversation() {
        let signer = ApprovalSigner::from_seed(11);
        let token = mint_answer_token("call-1", 0, "conv-A", 1_000, &signer);
        assert!(!verify_answer_token(
            &token, "call-1", 0, "conv-B", 1_000, &signer
        ));
    }

    #[test]
    fn answer_token_rejects_wrong_signer() {
        let signer = ApprovalSigner::from_seed(11);
        let other = ApprovalSigner::from_seed(12);
        let token = mint_answer_token("call-1", 0, "conv-A", 1_000, &signer);
        assert!(!verify_answer_token(
            &token, "call-1", 0, "conv-A", 1_000, &other
        ));
    }

    #[test]
    fn answer_token_rejects_after_ttl_elapses() {
        let signer = ApprovalSigner::from_seed(11);
        let token = mint_answer_token("call-1", 0, "conv-A", 0, &signer);
        assert!(verify_answer_token(
            &token,
            "call-1",
            0,
            "conv-A",
            ANSWER_TOKEN_TTL_MS,
            &signer
        ));
        assert!(!verify_answer_token(
            &token,
            "call-1",
            0,
            "conv-A",
            ANSWER_TOKEN_TTL_MS + 1,
            &signer
        ));
    }

    #[test]
    fn answer_token_rejects_garbage() {
        let signer = ApprovalSigner::from_seed(11);
        assert!(!verify_answer_token(
            "not-hex", "call-1", 0, "conv-A", 0, &signer
        ));
        assert!(!verify_answer_token("", "call-1", 0, "conv-A", 0, &signer));
    }
}

#[cfg(test)]
mod canonical_freeze {
    //! Every signed canonical in this module, frozen as literal bytes (`#1845`).
    //!
    //! These are the bytes a deployment has already signed and has sitting in
    //! its log. They are checked in, never regenerated: regenerating one is the
    //! defect this module exists to catch, because a canonical whose bytes move
    //! invalidates every signature ever minted over the old ones.
    //!
    //! The reason they can be single literals at all is the conversion `#1845`
    //! made, following `#1842`. Before it, each canonical was a
    //! [`serde_json::Value`], whose object is a `BTreeMap` (keys sorted) by
    //! default and an `IndexMap` (insertion order) whenever anything in the
    //! build graph enables `serde_json/preserve_order` — so the same payload
    //! signed by two binaries with different dependency sets produced different
    //! bytes and different signatures. Every literal below is the
    //! insertion-order form, which is what a control-plane binary (where
    //! `preserve_order` is unified in) has always signed. Run this module under
    //! either selection and every literal holds:
    //!
    //! ```text
    //! cargo nextest run -p polyc-crypto                    # no preserve_order
    //! cargo nextest run -p polyc-crypto -p polyc-payments  # preserve_order on
    //! ```
    //!
    //! See ADR 0009 for the decision these literals enforce.
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;

    /// Assert a canonical's bytes are exactly the frozen literal.
    fn frozen(label: &str, got: &[u8], want: &str) {
        assert_eq!(
            String::from_utf8(got.to_vec()).unwrap(),
            want,
            "{label}: canonical bytes moved — every signature over the old bytes is now unverifiable"
        );
    }

    const QUESTION_ARGS: &str =
        r#"{"questions":[{"prompt":"Ship it?","options":["Hold","Yes, proceed"]}]}"#;
    const MINTED_AT_MS: u64 = 1_750_000_000_000;

    #[test]
    fn answered_canonical_and_payload_are_frozen() {
        frozen(
            "answer_canonical (answered)",
            &answer_canonical(
                "call-1",
                0,
                QUESTION_ARGS,
                ANSWERED_STATE,
                Some(1),
                "Yes, proceed",
                "persona:alice",
                "conv-1",
                "nonce-answer",
            ),
            ANSWERED_CANONICAL,
        );
        let (full, sig, _) = answer_payload(
            "call-1",
            0,
            QUESTION_ARGS,
            ANSWERED_STATE,
            Some(1),
            "Yes, proceed",
            "persona:alice",
            "conv-1",
            "nonce-answer",
            &ApprovalSigner::from_seed(99),
        );
        frozen("answer_payload (answered)", &full, ANSWERED_PAYLOAD);
        assert_eq!(crate::hex::lower(&sig), ANSWERED_SIG);
    }

    // A decline signs `selected_index` as an explicit `null`, not an omitted
    // key — the shape the `json!` object this replaced emitted, and therefore
    // what every already-signed decline in a deployment's log covers.
    #[test]
    fn declined_canonical_and_payload_are_frozen() {
        frozen(
            "answer_canonical (declined)",
            &answer_canonical(
                "call-1",
                0,
                QUESTION_ARGS,
                DECLINED_STATE,
                None,
                "",
                "persona:alice",
                "conv-1",
                "nonce-answer",
            ),
            DECLINED_CANONICAL,
        );
        let (full, sig, _) = answer_payload(
            "call-1",
            0,
            QUESTION_ARGS,
            DECLINED_STATE,
            None,
            "",
            "persona:alice",
            "conv-1",
            "nonce-answer",
            &ApprovalSigner::from_seed(99),
        );
        frozen("answer_payload (declined)", &full, DECLINED_PAYLOAD);
        assert_eq!(crate::hex::lower(&sig), DECLINED_SIG);
    }

    #[test]
    fn answer_token_is_frozen() {
        frozen(
            "answer_token_canonical",
            &answer_token_canonical("call-1", 0, "conv-1", MINTED_AT_MS),
            TOKEN_CANONICAL,
        );
        assert_eq!(
            mint_answer_token(
                "call-1",
                0,
                "conv-1",
                MINTED_AT_MS,
                &ApprovalSigner::from_seed(99)
            ),
            TOKEN_MINTED,
            "a minted answer token's bytes are frozen — a token is hex of the whole object"
        );
    }

    const ANSWERED_CANONICAL: &str = r#"{"question_call_id":"call-1","question_index":0,"question_args_json":"{\"questions\":[{\"prompt\":\"Ship it?\",\"options\":[\"Hold\",\"Yes, proceed\"]}]}","state":"answered","selected_index":1,"selected_label":"Yes, proceed","answered_by":"persona:alice","conversation_id":"conv-1","nonce":"nonce-answer"}"#;
    const ANSWERED_PAYLOAD: &str = r#"{"question_call_id":"call-1","question_index":0,"question_args_json":"{\"questions\":[{\"prompt\":\"Ship it?\",\"options\":[\"Hold\",\"Yes, proceed\"]}]}","state":"answered","selected_index":1,"selected_label":"Yes, proceed","answered_by":"persona:alice","conversation_id":"conv-1","nonce":"nonce-answer","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"e7b877065d853887c0188eff5fb971a9d8e531e2c36e3ffa8d02dc5da2b3cb17a8dc140bfb1d6b4c6c6529d0b4890851516d03b1d633d96b1496d6713b08a705"}"#;
    const ANSWERED_SIG: &str = "e7b877065d853887c0188eff5fb971a9d8e531e2c36e3ffa8d02dc5da2b3cb17a8dc140bfb1d6b4c6c6529d0b4890851516d03b1d633d96b1496d6713b08a705";
    const DECLINED_CANONICAL: &str = r#"{"question_call_id":"call-1","question_index":0,"question_args_json":"{\"questions\":[{\"prompt\":\"Ship it?\",\"options\":[\"Hold\",\"Yes, proceed\"]}]}","state":"declined","selected_index":null,"selected_label":"","answered_by":"persona:alice","conversation_id":"conv-1","nonce":"nonce-answer"}"#;
    const DECLINED_PAYLOAD: &str = r#"{"question_call_id":"call-1","question_index":0,"question_args_json":"{\"questions\":[{\"prompt\":\"Ship it?\",\"options\":[\"Hold\",\"Yes, proceed\"]}]}","state":"declined","selected_index":null,"selected_label":"","answered_by":"persona:alice","conversation_id":"conv-1","nonce":"nonce-answer","signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"5961a4cc427c84674a0a60b0f51552143b511751c2295705dbd323e062b504858de0f2209e67bb0c7a6826e80ec9831c2864c9f910cf7b4e137656da273fa30d"}"#;
    const DECLINED_SIG: &str = "5961a4cc427c84674a0a60b0f51552143b511751c2295705dbd323e062b504858de0f2209e67bb0c7a6826e80ec9831c2864c9f910cf7b4e137656da273fa30d";
    const TOKEN_CANONICAL: &str = r#"{"question_call_id":"call-1","question_index":0,"conversation_id":"conv-1","minted_at_ms":1750000000000}"#;
    const TOKEN_MINTED: &str = "7b227175657374696f6e5f63616c6c5f6964223a2263616c6c2d31222c227175657374696f6e5f696e646578223a302c22636f6e766572736174696f6e5f6964223a22636f6e762d31222c226d696e7465645f61745f6d73223a313735303030303030303030302c227369676e61747572655f686578223a223337633731353962313761313236643935323466313766616636323766623565396461626133313535616638316163666539313966633634363833653634626530333833386539363033383165313931366533643033626437333338653830353762636636326565313365643166353639363866616366323034373936643065227d";
}