vela-protocol 0.911.0

Core library for the Vela scientific knowledge protocol: replayable frontier state, signed canonical events, and proof packets.
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
//! Ed25519 signing for the event log — the trust infrastructure layer.
//!
//! The signed EVENT log is the sole signing authority: a registered human
//! actor's events carry a verifiable signature, and `verify_event_signature`
//! checks them against the registered pubkey. The legacy per-finding signature
//! lane (the v0.37 multi-sig `SignedEnvelope` / threshold machinery) was retired
//! — `SignedEnvelope` and `Project.signatures` survive only so historical
//! frontiers that still carry envelopes deserialize and replay unchanged. They
//! are vestigial data (hash-neutral): nothing creates, verifies, or gates on
//! them.

use std::path::Path;

use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};

/// A signed envelope wrapping a finding's cryptographic signature.
///
/// Vestigial: retained so historical `Project.signatures` deserialize. The
/// finding-signature lane is retired; no code path produces or verifies these.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SignedEnvelope {
    pub finding_id: String,
    /// Hex-encoded Ed25519 signature (128 hex chars = 64 bytes).
    pub signature: String,
    /// Hex-encoded public key of the signer (64 hex chars = 32 bytes).
    pub public_key: String,
    /// ISO 8601 timestamp of when the signature was produced.
    pub signed_at: String,
    /// Algorithm identifier (always "ed25519").
    pub algorithm: String,
}

/// Phase M (v0.4): registered actor identity. Maps a stable `actor.id`
/// to an Ed25519 public key, established at a specific timestamp.
///
/// Once an actor is registered in a frontier, any canonical event
/// whose `actor.id` matches must carry a verifiable signature under
/// `--strict`. Frontiers without registered actors retain the legacy
/// "placeholder reviewer" rejection from v0.3 only.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ActorRecord {
    /// Stable, namespaced identifier (e.g. "reviewer:human-reviewer").
    pub id: String,
    /// Hex-encoded Ed25519 public key (64 hex chars = 32 bytes).
    pub public_key: String,
    /// Algorithm identifier (always "ed25519").
    #[serde(default = "default_algorithm")]
    pub algorithm: String,
    /// ISO 8601 timestamp of when the actor was registered.
    pub created_at: String,
    /// Historical actor-tier metadata retained only so immutable records
    /// continue to decode. Current constructors emit `None`; this field grants
    /// no write or decision authority.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tier: Option<String>,
    /// v0.43: Optional ORCID identifier for cross-system identity.
    /// Format: `0000-0000-0000-000X` (16 digits in 4 groups, final
    /// character optionally `X` per ISO 7064). When set, the actor's
    /// identity can be cross-referenced through the public ORCID
    /// directory at `https://orcid.org/<orcid>`. The substrate stores
    /// the pointer; it does not verify the ORCID exists online (that
    /// is L4 work). Pre-v0.43 actors load with `None` and behave
    /// exactly as before.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub orcid: Option<String>,
    /// v0.51: Read-side access clearance. `None` (default) means
    /// public-only access. `Some(Restricted)` permits reading
    /// `Public` and `Restricted` tiered objects; `Some(Classified)`
    /// permits all. Unlike the historical `tier` field above, this is active
    /// read-side policy; it never grants write or decision authority.
    /// Pre-v0.51 actors load with `None` and behave
    /// exactly as before — the field is purely additive.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access_clearance: Option<crate::access_tier::AccessTier>,
    /// v0.127: revocation timestamp. When set, the actor's key is
    /// considered compromised or retired as of that moment.
    /// Signatures on events with `timestamp < revoked_at` remain
    /// valid (the key was trusted when the event was signed); new
    /// signatures on events with `timestamp >= revoked_at` are
    /// rejected by `verify_event_signature`. Pre-v0.127 actors load
    /// with `None` and verify exactly as before.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revoked_at: Option<String>,
    /// v0.127: free-form reason for revocation (e.g. "key
    /// compromised 2026-05-10", "rotated to reviewer:human-reviewer-v2").
    /// Display-only; the substrate does not parse this field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revoked_reason: Option<String>,
}

impl ActorRecord {
    /// v0.127: true iff the actor's key is revoked relative to an
    /// event timestamp. An event signed before `revoked_at` remains
    /// valid (the substrate does not retroactively invalidate
    /// historical signatures); an event signed at-or-after the
    /// revocation is rejected. Both timestamps are parsed as RFC 3339
    /// instants so equivalent offsets compare correctly. Invalid
    /// timestamps fail closed and are treated as revoked.
    pub fn is_revoked_at(&self, event_timestamp: &str) -> bool {
        let Ok(event_time) = chrono::DateTime::parse_from_rfc3339(event_timestamp) else {
            return true;
        };
        let Some(revoked_at) = self.revoked_at.as_deref() else {
            return false;
        };
        let Ok(revoked_time) = chrono::DateTime::parse_from_rfc3339(revoked_at) else {
            return true;
        };
        event_time >= revoked_time
    }
}

/// v0.43: Validate an ORCID identifier's structural shape. ORCID IDs
/// are 16 digits in 4 groups of 4 separated by hyphens, with the
/// final character optionally being `X` (the ISO 7064 check digit).
/// Accepts bare form `0000-0001-2345-6789`, the URL form
/// `https://orcid.org/0000-...`, or the prefixed form `orcid:0000-...`
/// and returns the bare form.
pub fn validate_orcid(s: &str) -> Result<String, String> {
    let trimmed = s.trim();
    let bare = trimmed
        .strip_prefix("https://orcid.org/")
        .or_else(|| trimmed.strip_prefix("http://orcid.org/"))
        .or_else(|| trimmed.strip_prefix("orcid:"))
        .unwrap_or(trimmed);
    if bare.len() != 19 {
        return Err(format!(
            "ORCID must be 19 chars (0000-0000-0000-000X), got {}",
            bare.len()
        ));
    }
    let mut groups = bare.split('-');
    for i in 0..4 {
        let g = groups
            .next()
            .ok_or_else(|| format!("ORCID missing group {} of 4", i + 1))?;
        if g.len() != 4 {
            return Err(format!(
                "ORCID group {} must be 4 chars, got {}",
                i + 1,
                g.len()
            ));
        }
        for (j, c) in g.chars().enumerate() {
            let allow_x = i == 3 && j == 3;
            if !c.is_ascii_digit() && !(allow_x && c == 'X') {
                return Err(format!(
                    "ORCID character '{c}' at group {} pos {} not a digit (or X check digit)",
                    i + 1,
                    j + 1
                ));
            }
        }
    }
    if groups.next().is_some() {
        return Err("ORCID has too many hyphenated groups".to_string());
    }
    Ok(bare.to_string())
}

fn default_algorithm() -> String {
    "ed25519".to_string()
}

// ── Key generation ───────────────────────────────────────────────────

/// Generate an Ed25519 keypair. Writes the private key to `output_dir/private.key`
/// and the public key to `output_dir/public.key`. Both are hex-encoded.
pub fn generate_keypair(output_dir: &Path) -> Result<String, String> {
    use rand::rngs::OsRng;

    std::fs::create_dir_all(output_dir)
        .map_err(|e| format!("Failed to create output directory: {e}"))?;

    let signing_key = SigningKey::generate(&mut OsRng);
    let verifying_key = signing_key.verifying_key();

    let private_hex = hex::encode(signing_key.to_bytes());
    let public_hex = hex::encode(verifying_key.to_bytes());

    let private_path = output_dir.join("private.key");
    let public_path = output_dir.join("public.key");

    std::fs::write(&private_path, &private_hex)
        .map_err(|e| format!("Failed to write private key: {e}"))?;
    // The private key is a plaintext seed; make it owner-read-only so a
    // stray backup or shared machine cannot leak the signing authority.
    // Best-effort and Unix-only (Windows ACLs are a separate concern).
    harden_key_permissions(&private_path);
    std::fs::write(&public_path, &public_hex)
        .map_err(|e| format!("Failed to write public key: {e}"))?;

    Ok(public_hex)
}

/// Set 0600 on a private-key file where the platform supports it. Best
/// effort: a failure to tighten permissions must not fail key generation,
/// but the common case (Unix) gets a private key that is not world- or
/// group-readable.
pub fn harden_key_permissions(path: &Path) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = std::fs::metadata(path) {
            let mut perms = meta.permissions();
            perms.set_mode(0o600);
            let _ = std::fs::set_permissions(path, perms);
        }
    }
    #[cfg(not(unix))]
    {
        let _ = path;
    }
}

// ── Signing and verification ─────────────────────────────────────────

/// Parse a hex-encoded Ed25519 signing key (64 hex chars = the 32-byte seed).
/// The inline form of [`load_signing_key_from_path`], for callers that hold the
/// key as a string rather than a file — e.g. a deployment secret delivered as
/// an environment variable (Fly/Heroku/K8s), where there is no key file to
/// point a path at.
pub fn signing_key_from_hex(hex_str: &str) -> Result<SigningKey, String> {
    let bytes =
        hex::decode(hex_str.trim()).map_err(|e| format!("Invalid hex in private key: {e}"))?;
    let key_bytes: [u8; 32] = bytes
        .try_into()
        .map_err(|_| "Private key must be exactly 32 bytes".to_string())?;
    Ok(SigningKey::from_bytes(&key_bytes))
}

/// Load a signing key from a hex-encoded file.
fn load_signing_key(path: &Path) -> Result<SigningKey, String> {
    let hex_str =
        std::fs::read_to_string(path).map_err(|e| format!("Failed to read private key: {e}"))?;
    signing_key_from_hex(&hex_str)
}

/// v0.49.3: public key-loading and primitive-signing helpers so the
/// hub (and any other downstream binary) can sign small JSON payloads
/// — e.g., the `/.well-known/vela` manifest — without needing direct
/// access to the ed25519_dalek dep or to the SigningKey type.

/// Load a hex-encoded Ed25519 signing key from disk.
///
/// Same on-disk format `vela sign generate-keypair` writes.
pub fn load_signing_key_from_path(path: &Path) -> Result<SigningKey, String> {
    load_signing_key(path)
}

/// Sign arbitrary bytes with the given key. Returns the 64-byte
/// signature.
pub fn sign_bytes(signing_key: &SigningKey, bytes: &[u8]) -> [u8; 64] {
    signing_key.sign(bytes).to_bytes()
}

/// Hex-encoded Ed25519 public key (64 chars) for the given signing key.
pub fn pubkey_hex(signing_key: &SigningKey) -> String {
    hex::encode(signing_key.verifying_key().to_bytes())
}

/// Parse a verifying key from a hex string.
fn parse_verifying_key(hex_str: &str) -> Result<VerifyingKey, String> {
    let bytes = hex::decode(hex_str).map_err(|e| format!("Invalid hex in public key: {e}"))?;
    let key_bytes: [u8; 32] = bytes
        .try_into()
        .map_err(|_| "Public key must be exactly 32 bytes".to_string())?;
    VerifyingKey::from_bytes(&key_bytes).map_err(|e| format!("Invalid public key: {e}"))
}

// ── Event signing (Phase M, v0.4) ────────────────────────────────────

/// Compute the canonical signing bytes for a `StateEvent`. The `signature`
/// field is excluded from the preimage (you can't sign over your own
/// signature). The same canonical-JSON rule that derives `vev_…` is reused.
///
/// A second implementation must produce byte-identical signing bytes
/// for the same event content; the verification rule depends on it.
pub fn event_signing_bytes(
    event: &crate::events::StateEvent,
    version: crate::signing_input::SigVersion,
) -> Result<Vec<u8>, String> {
    use serde_json::json;
    let preimage = json!({
        "schema": event.schema,
        "id": event.id,
        "kind": event.kind,
        "target": event.target,
        "actor": event.actor,
        "timestamp": event.timestamp,
        "reason": event.reason,
        "before_hash": event.before_hash,
        "after_hash": event.after_hash,
        "payload": event.payload,
        "caveats": event.caveats,
    });
    let body = crate::canonical::to_canonical_bytes(&preimage)?;
    Ok(crate::signing_input::signing_input(
        version,
        crate::signing_input::payload_type::EVENT,
        &body,
    ))
}

/// Sign a canonical event with an Ed25519 private key, returning a signature
/// suitable for `event.signature`. New signatures are v1 (DSSE/PAE), carried as
/// a `v1:` prefix on the signature string so historical bare-hex signatures read
/// as v0. The prefix is not part of the event id or the (content-only)
/// event_log_hash, so the flip is transparent to addressing.
pub fn sign_event(
    event: &crate::events::StateEvent,
    signing_key: &SigningKey,
) -> Result<String, String> {
    let bytes = event_signing_bytes(event, crate::signing_input::SigVersion::V1)?;
    let signature = signing_key.sign(&bytes);
    Ok(format!("v1:{}", hex::encode(signature.to_bytes())))
}

/// Verify that `event.signature` is a valid Ed25519 signature over the canonical
/// signing bytes of `event`, produced by the holder of `expected_pubkey_hex`.
/// The signing-input version is read from the signature's `v1:` prefix (a bare
/// hex signature is historical v0); the framing is then fixed, so flipping the
/// prefix changes the bytes and fails verification (fail-closed).
pub fn verify_event_signature(
    event: &crate::events::StateEvent,
    expected_pubkey_hex: &str,
) -> Result<bool, String> {
    use crate::signing_input::SigVersion;
    let raw = event
        .signature
        .as_deref()
        .ok_or_else(|| format!("event {} has no signature field", event.id))?;
    let (version, signature_hex) = match raw.strip_prefix("v1:") {
        Some(hex) => (SigVersion::V1, hex),
        None => (SigVersion::V0, raw),
    };
    let verifying_key = parse_verifying_key(expected_pubkey_hex)?;
    let sig_bytes =
        hex::decode(signature_hex).map_err(|e| format!("invalid signature hex: {e}"))?;
    let signature = ed25519_dalek::Signature::from_bytes(
        &sig_bytes
            .try_into()
            .map_err(|_| "Signature must be 64 bytes")?,
    );
    let bytes = event_signing_bytes(event, version)?;
    Ok(verifying_key.verify(&bytes, &signature).is_ok())
}

// ── Proposal signing (Phase Q-w, v0.5) ───────────────────────────────

/// Compute the canonical signing bytes for a `StateProposal`. The
/// `signature` (held externally on the wire) is excluded from the
/// preimage. Same canonical-JSON discipline as `event_signing_bytes`.
///
/// The proposal `id` is included, which deterministically pins the
/// content (since `vpr_…` is content-addressed under Phase P).
pub fn proposal_signing_bytes(
    proposal: &crate::proposals::StateProposal,
) -> Result<Vec<u8>, String> {
    use serde_json::json;
    let preimage = json!({
        "schema": proposal.schema,
        "id": proposal.id,
        "kind": proposal.kind,
        "target": proposal.target,
        "actor": proposal.actor,
        "created_at": proposal.created_at,
        "reason": proposal.reason,
        "payload": proposal.payload,
        "source_refs": proposal.source_refs,
        "caveats": proposal.caveats,
    });
    let body = crate::canonical::to_canonical_bytes(&preimage)?;
    Ok(crate::signing_input::signing_input(
        crate::signing_input::SigVersion::V0,
        crate::signing_input::payload_type::PROPOSAL,
        &body,
    ))
}

/// Sign a proposal with an Ed25519 private key, returning a hex-encoded
/// signature suitable for transport on a write API.
pub fn sign_proposal(
    proposal: &crate::proposals::StateProposal,
    signing_key: &SigningKey,
) -> Result<String, String> {
    let bytes = proposal_signing_bytes(proposal)?;
    Ok(hex::encode(signing_key.sign(&bytes).to_bytes()))
}

/// Verify a hex-encoded Ed25519 signature against the canonical signing
/// bytes of `proposal`, using `expected_pubkey_hex` as the verifying key.
pub fn verify_proposal_signature(
    proposal: &crate::proposals::StateProposal,
    signature_hex: &str,
    expected_pubkey_hex: &str,
) -> Result<bool, String> {
    let verifying_key = parse_verifying_key(expected_pubkey_hex)?;
    let sig_bytes =
        hex::decode(signature_hex).map_err(|e| format!("invalid signature hex: {e}"))?;
    let signature = ed25519_dalek::Signature::from_bytes(
        &sig_bytes
            .try_into()
            .map_err(|_| "Signature must be 64 bytes")?,
    );
    let bytes = proposal_signing_bytes(proposal)?;
    Ok(verifying_key.verify(&bytes, &signature).is_ok())
}

/// Generic signature verifier for action-on-canonical-bytes: verify
/// `signature_hex` is a valid Ed25519 signature over `signing_bytes`,
/// produced by the holder of `expected_pubkey_hex`. Used by write
/// actions that don't sign over a full proposal/event struct (e.g.,
/// accept/reject decisions).
pub fn verify_action_signature(
    signing_bytes: &[u8],
    signature_hex: &str,
    expected_pubkey_hex: &str,
) -> Result<bool, String> {
    let verifying_key = parse_verifying_key(expected_pubkey_hex)?;
    let sig_bytes =
        hex::decode(signature_hex).map_err(|e| format!("invalid signature hex: {e}"))?;
    let signature = ed25519_dalek::Signature::from_bytes(
        &sig_bytes
            .try_into()
            .map_err(|_| "Signature must be 64 bytes")?,
    );
    Ok(verifying_key.verify(signing_bytes, &signature).is_ok())
}

// ── Tests ────────────────────────────────────────────────────────────

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

    fn test_keypair() -> SigningKey {
        use rand::rngs::OsRng;
        SigningKey::generate(&mut OsRng)
    }

    fn actor_with_revocation(revoked_at: Option<&str>) -> ActorRecord {
        ActorRecord {
            id: "reviewer:test".to_string(),
            public_key: "00".repeat(32),
            algorithm: "ed25519".to_string(),
            created_at: "2026-05-01T00:00:00Z".to_string(),
            tier: None,
            orcid: None,
            access_clearance: None,
            revoked_at: revoked_at.map(ToString::to_string),
            revoked_reason: None,
        }
    }

    #[test]
    fn actor_revocation_compares_rfc3339_instants_across_offsets() {
        let actor = actor_with_revocation(Some("2026-05-28T20:00:00-04:00"));

        assert!(actor.is_revoked_at("2026-05-29T00:00:00Z"));
        assert!(!actor.is_revoked_at("2026-05-28T23:59:59Z"));
    }

    #[test]
    fn actor_revocation_fails_closed_on_invalid_timestamps() {
        let actor = actor_with_revocation(Some("not-a-timestamp"));
        assert!(actor.is_revoked_at("2026-05-29T00:00:00Z"));

        let active_actor = actor_with_revocation(None);
        assert!(active_actor.is_revoked_at("not-a-timestamp"));
    }

    #[cfg(unix)]
    #[test]
    fn generated_private_key_is_owner_only() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        generate_keypair(dir.path()).unwrap();
        let mode = std::fs::metadata(dir.path().join("private.key"))
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o600, "private key must be owner-read/write only");
    }

    /// The deposit-endpoint signing contract: a deposit client (e.g. a producer
    /// posting to the hub's append endpoint)
    /// signs `to_vec(json!({action, vfr_id, parent_event_log_hash, batch}))`
    /// with the owner key; the hub rebuilds that preimage from the parsed wire
    /// body and checks it with `verify_action_signature`. This asserts the two
    /// sides agree — including the JSON round-trip the batch takes over the
    /// wire — so a correctly-signed client request is accepted, and a tampered
    /// one is not.
    #[test]
    fn append_deposit_signature_roundtrips_client_to_server() {
        use ed25519_dalek::Signer;
        use serde_json::json;

        let key = test_keypair();
        let pubkey_hex = hex::encode(key.verifying_key().to_bytes());

        // Client side: build the batch value, then the preimage, then sign.
        let batch = json!([
            {"object_kind": "event_only", "event": {"id": "vev_1", "kind": "finding.asserted"}}
        ]);
        let preimage = json!({
            "action": "append",
            "vfr_id": "vfr_demo",
            "parent_event_log_hash": "sha256:abc",
            "batch": batch,
        });
        let client_bytes = serde_json::to_vec(&preimage).unwrap();
        let sig_hex = hex::encode(key.sign(&client_bytes).to_bytes());

        // Server side: the batch arrives as parsed JSON; rebuild the preimage
        // from it (the round-trip the wire imposes) and verify.
        let parsed_batch: serde_json::Value =
            serde_json::from_slice(&serde_json::to_vec(&batch).unwrap()).unwrap();
        let server_preimage = json!({
            "action": "append",
            "vfr_id": "vfr_demo",
            "parent_event_log_hash": "sha256:abc",
            "batch": parsed_batch,
        });
        let server_bytes = serde_json::to_vec(&server_preimage).unwrap();

        assert_eq!(
            client_bytes, server_bytes,
            "preimage bytes must match across the wire"
        );
        assert!(
            verify_action_signature(&server_bytes, &sig_hex, &pubkey_hex).unwrap(),
            "the client's signature must verify on the server side"
        );
        // A tampered parent hash must NOT verify.
        let tampered = json!({
            "action": "append", "vfr_id": "vfr_demo",
            "parent_event_log_hash": "sha256:DIFFERENT", "batch": parsed_batch,
        });
        assert!(
            !verify_action_signature(
                &serde_json::to_vec(&tampered).unwrap(),
                &sig_hex,
                &pubkey_hex
            )
            .unwrap(),
            "a tampered preimage must be rejected"
        );
    }

    #[test]
    fn keygen_produces_valid_files() {
        let dir = std::env::temp_dir().join("vela_test_keygen");
        let _ = std::fs::remove_dir_all(&dir);

        let pubkey = generate_keypair(&dir).unwrap();
        assert_eq!(pubkey.len(), 64); // 32 bytes hex-encoded

        let private_hex = std::fs::read_to_string(dir.join("private.key")).unwrap();
        let public_hex = std::fs::read_to_string(dir.join("public.key")).unwrap();
        assert_eq!(private_hex.len(), 64);
        assert_eq!(public_hex, pubkey);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn registered_actor_signed_event_roundtrip() {
        // Phase M: a registered actor's event must sign-and-verify
        // against its registered pubkey via `event_signing_bytes`. This
        // is the load-bearing claim for the v0.4 strict-mode gate.
        use crate::events::{
            EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget, compute_event_id,
        };

        let key = test_keypair();
        let pubkey_hex = hex::encode(key.verifying_key().to_bytes());

        let mut event = StateEvent {
            schema: EVENT_SCHEMA.to_string(),
            id: String::new(),
            kind: "finding.reviewed".into(),
            target: StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test".to_string(),
            },
            actor: StateActor {
                id: "reviewer:registered".to_string(),
                r#type: "human".to_string(),
            },
            timestamp: "2026-04-25T00:00:00Z".to_string(),
            reason: "phase-m round-trip test".to_string(),
            before_hash: NULL_HASH.to_string(),
            after_hash: "sha256:abc".to_string(),
            payload: serde_json::json!({"status": "accepted", "proposal_id": "vpr_test"}),
            caveats: vec![],
            signature: None,
        };
        event.id = compute_event_id(&event);
        event.signature = Some(sign_event(&event, &key).unwrap());

        // Verifies against the registered pubkey.
        assert!(verify_event_signature(&event, &pubkey_hex).unwrap());

        // Tampering with the reason invalidates the signature.
        let mut tampered = event.clone();
        tampered.reason = "different reason".to_string();
        assert!(!verify_event_signature(&tampered, &pubkey_hex).unwrap());
    }

    #[test]
    fn v0_and_v1_event_signatures_both_verify() {
        // The migration seam (M8): a new signature is v1 (v1:-prefixed) and a
        // historical signature is v0 (bare hex). Both must verify so the flip
        // never strands a historical event, and a downgrade (claiming a v1
        // signature is v0) must fail closed.
        use crate::events::{
            EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget, compute_event_id,
        };
        use crate::signing_input::SigVersion;

        let key = test_keypair();
        let pubkey = hex::encode(key.verifying_key().to_bytes());
        let mut event = StateEvent {
            schema: EVENT_SCHEMA.to_string(),
            id: String::new(),
            kind: "finding.reviewed".into(),
            target: StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test".to_string(),
            },
            actor: StateActor {
                id: "reviewer:registered".to_string(),
                r#type: "human".to_string(),
            },
            timestamp: "2026-06-30T00:00:00Z".to_string(),
            reason: "v0/v1 dual-verify".to_string(),
            before_hash: NULL_HASH.to_string(),
            after_hash: "sha256:abc".to_string(),
            payload: serde_json::json!({"status": "accepted", "proposal_id": "vpr_test"}),
            caveats: vec![],
            signature: None,
        };
        event.id = compute_event_id(&event);

        // New default: sign_event emits a v1: signature, and it verifies.
        event.signature = Some(sign_event(&event, &key).unwrap());
        assert!(event.signature.as_deref().unwrap().starts_with("v1:"));
        assert!(verify_event_signature(&event, &pubkey).unwrap());

        // Historical v0: a bare-hex signature over the v0 framing still verifies.
        let v0_bytes = event_signing_bytes(&event, SigVersion::V0).unwrap();
        let mut v0_event = event.clone();
        v0_event.signature = Some(hex::encode(key.sign(&v0_bytes).to_bytes()));
        assert!(verify_event_signature(&v0_event, &pubkey).unwrap());

        // Downgrade attempt: strip the v1: prefix so it claims v0. The framing
        // then differs from what was signed, so it must fail closed.
        let mut downgraded = event.clone();
        let bare = event
            .signature
            .as_deref()
            .unwrap()
            .strip_prefix("v1:")
            .unwrap()
            .to_string();
        downgraded.signature = Some(bare);
        assert!(!verify_event_signature(&downgraded, &pubkey).unwrap());
    }

    #[test]
    fn provenance_co_author_confers_no_signing_authority() {
        // The co-authorship block names a non-human assistant (agent:claude)
        // inside the SIGNED payload. The structural guarantee: the signature is
        // verified only against actor.id's key, never against any provenance
        // name. An AI named as a co-author can therefore never stand in as the
        // signer, so no model is ever in the trust path even when it is recorded
        // as having drafted the work.
        use crate::events::{
            EVENT_SCHEMA, NULL_HASH, StateActor, StateEvent, StateTarget, compute_event_id,
        };
        use crate::provenance::{MachineContribution, Provenance};

        let human_key = test_keypair();
        let human_pubkey = hex::encode(human_key.verifying_key().to_bytes());
        let agent_key = test_keypair();
        let agent_pubkey = hex::encode(agent_key.verifying_key().to_bytes());

        let mut payload = serde_json::json!({"status": "accepted", "proposal_id": "vpr_test"});
        crate::provenance::attach_to_payload(
            &mut payload,
            &Provenance {
                machine_contributions: vec![MachineContribution {
                    id: "agent:claude".to_string(),
                    class: "agent".to_string(),
                    role: "drafted".to_string(),
                    tool: "claude-code".to_string(),
                    generated_by: "model: claude-opus-4-8".to_string(),
                    authority: "none".to_string(),
                }],
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(
            payload["provenance"]["machine_contributions"][0]["id"],
            "agent:claude"
        );

        let mut event = StateEvent {
            schema: EVENT_SCHEMA.to_string(),
            id: String::new(),
            kind: "review.accepted".into(),
            target: StateTarget {
                r#type: "proposal".to_string(),
                id: "vpr_test".to_string(),
            },
            actor: StateActor {
                id: "reviewer:will-blair".to_string(),
                r#type: "human".to_string(),
            },
            timestamp: "2026-06-30T00:00:00Z".to_string(),
            reason: "co-authored accept".to_string(),
            before_hash: NULL_HASH.to_string(),
            after_hash: "sha256:abc".to_string(),
            payload,
            caveats: vec![],
            signature: None,
        };
        event.id = compute_event_id(&event);
        event.signature = Some(sign_event(&event, &human_key).unwrap());

        // The accountable human's key verifies the co-authored event.
        assert!(verify_event_signature(&event, &human_pubkey).unwrap());
        // The co-author's own key does NOT verify it: being named in provenance
        // grants zero signing authority.
        assert!(!verify_event_signature(&event, &agent_pubkey).unwrap());
        // The block is signed-over, so tampering with the co-author name breaks
        // the human's signature (the attribution is tamper-evident).
        let mut tampered = event.clone();
        tampered.payload["provenance"]["machine_contributions"][0]["id"] =
            serde_json::json!("agent:someone-else");
        assert!(!verify_event_signature(&tampered, &human_pubkey).unwrap());
    }

    // ── v0.43 ORCID validation ───────────────────────────────────────

    #[test]
    fn validate_orcid_accepts_canonical_form() {
        assert_eq!(
            validate_orcid("0000-0001-2345-6789").unwrap(),
            "0000-0001-2345-6789"
        );
    }

    #[test]
    fn validate_orcid_accepts_check_digit_x() {
        assert_eq!(
            validate_orcid("0000-0001-5109-393X").unwrap(),
            "0000-0001-5109-393X"
        );
    }

    #[test]
    fn validate_orcid_strips_url_prefix() {
        assert_eq!(
            validate_orcid("https://orcid.org/0000-0001-2345-6789").unwrap(),
            "0000-0001-2345-6789"
        );
    }

    #[test]
    fn validate_orcid_strips_orcid_prefix() {
        assert_eq!(
            validate_orcid("orcid:0000-0001-2345-6789").unwrap(),
            "0000-0001-2345-6789"
        );
    }

    #[test]
    fn validate_orcid_rejects_short() {
        assert!(validate_orcid("0000-0001").is_err());
    }

    #[test]
    fn validate_orcid_rejects_letters_in_non_check_position() {
        assert!(validate_orcid("0000-A001-2345-6789").is_err());
    }

    #[test]
    fn validate_orcid_rejects_x_in_first_three_groups() {
        assert!(validate_orcid("000X-0001-2345-6789").is_err());
    }

    #[test]
    fn validate_orcid_rejects_extra_groups() {
        assert!(validate_orcid("0000-0001-2345-6789-9999").is_err());
    }
}