clm-kernel 0.0.2

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
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
//! Scale-free federation scaffold for Stage 7.
//!
//! This is a transport-agnostic scaffold for cross-PKC federation. It defines
//! peer identities, an in-memory message router, and a dispatch table for
//! cross-PKC PCard firing. The real WireGuard/QUIC transport lives behind the
//! native feature flag in `quic_transport.rs` (future work).

use crate::crdt::CrdtLog;
use crate::sheaf::Marking;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::collections::HashMap;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Peer {
    pub did: String,
    pub verifying_key: String,
    pub endpoint: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FederationMessage {
    Hello { did: String, verifying_key: String },
    Ping,
    Pong,
    CrdtSync { log: CrdtLog },
    PCardDispatch {
        pcard_hash: String,
        sender_did: String,
        co_signatures: Vec<String>,
    },
}

// ---------------------------------------------------------------------------
// Cross-PKC PCard Dispatch (Sprint 140.5)
// ---------------------------------------------------------------------------

/// Request to dispatch a PCard firing to a remote PKC over QUIC.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CrossPkcDispatchRequest {
    pub pcard_hash: String,
    pub input_marking: Marking,
    pub source_pkc_did: String,
    pub target_pkc_did: String,
}

/// Response from the target PKC after executing the PCard.
/// Contains the sealed VCard and the target PKC's signature.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CrossPkcDispatchResponse {
    pub vcard_hash: String,
    pub vcard_yaml: String,
    pub target_signature: String,
    pub exit_code: i64,
    pub exec_output: String,
}

/// Co-signed VCard containing both PKC DIDs in the signatures field.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CoSignedVCard {
    pub vcard_hash: String,
    pub vcard_yaml: String,
    pub signatures: Vec<String>,
}

#[derive(Debug, Clone, Default)]
pub struct FederationRouter {
    pub peers: HashMap<String, Peer>,
    pub inbox: Vec<(String, FederationMessage)>,
}

impl FederationRouter {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register_peer(&mut self, peer: Peer) {
        self.peers.insert(peer.did.clone(), peer);
    }

    pub fn route(&mut self, sender_did: &str, message: FederationMessage) -> Result<(), String> {
        if !self.peers.contains_key(sender_did) && !matches!(message, FederationMessage::Hello { .. }) {
            return Err(format!("unknown sender: {}", sender_did));
        }
        self.inbox.push((sender_did.to_string(), message));
        Ok(())
    }

    pub fn dispatch_pcard(
        &mut self,
        pcard_hash: &str,
        sender_did: &str,
    ) -> Result<FederationMessage, String> {
        if !self.peers.contains_key(sender_did) {
            return Err(format!("unknown sender: {}", sender_did));
        }
        let co_signatures = vec![format!("co-sig:{}", sender_did)];
        let msg = FederationMessage::PCardDispatch {
            pcard_hash: pcard_hash.to_string(),
            sender_did: sender_did.to_string(),
            co_signatures,
        };
        self.inbox.push((sender_did.to_string(), msg.clone()));
        Ok(msg)
    }

    /// Send a federation message over a QUIC connection.
    #[cfg(feature = "native")]
    pub async fn send_message(
        &self,
        peer_did: &str,
        msg: &FederationMessage,
        conn: &crate::quic_transport::QuicConnection,
    ) -> Result<(), String> {
        if !self.peers.contains_key(peer_did) {
            return Err(format!("unknown peer: {}", peer_did));
        }
        let json = serde_json::to_vec(msg)
            .map_err(|e| format!("Failed to serialize federation message: {}", e))?;
        conn.send_one_way(&json).await?;
        Ok(())
    }

    /// Receive a federation message over a QUIC connection.
    #[cfg(feature = "native")]
    pub async fn recv_message(
        &mut self,
        conn: &crate::quic_transport::QuicConnection,
    ) -> Result<FederationMessage, String> {
        let (data, _, _) = conn.recv_bi().await?;
        let msg: FederationMessage = serde_json::from_slice(&data)
            .map_err(|e| format!("Failed to deserialize federation message: {}", e))?;
        Ok(msg)
    }
}

// ---------------------------------------------------------------------------
// Cross-PKC Dispatch Protocol (Stories 140.5.1, 140.5.2, 140.5.3)
// ---------------------------------------------------------------------------

/// Dispatch a cross-PKC PCard firing request to a remote PKC over QUIC.
///
/// Serializes the request as JSON, sends it via a bidirectional QUIC stream,
/// and waits for the VCard response from the target PKC.
#[cfg(feature = "native")]
pub async fn dispatch_cross_pkc(
    request: &CrossPkcDispatchRequest,
    conn: &crate::quic_transport::QuicConnection,
) -> Result<CrossPkcDispatchResponse, String> {
    let json = serde_json::to_vec(request)
        .map_err(|e| format!("Failed to serialize dispatch request: {}", e))?;
    let response_bytes = conn.send(&json).await?;
    let response: CrossPkcDispatchResponse = serde_json::from_slice(&response_bytes)
        .map_err(|e| format!("Failed to deserialize dispatch response: {}", e))?;
    Ok(response)
}

/// Receive a cross-PKC dispatch request on the target PKC side.
///
/// Reads the incoming request from a QUIC bi-stream, resolves the PCard by hash,
/// executes it, seals a VCard, and sends the response back.
#[cfg(feature = "native")]
pub async fn receive_cross_pkc_dispatch(
    conn: &crate::quic_transport::QuicConnection,
) -> Result<(CrossPkcDispatchRequest, quinn::SendStream), String> {
    let (data, send_stream, _recv_stream) = conn.recv_bi().await?;
    let request: CrossPkcDispatchRequest = serde_json::from_slice(&data)
        .map_err(|e| format!("Failed to deserialize dispatch request: {}", e))?;
    Ok((request, send_stream))
}

/// Co-sign a VCard after receiving the target PKC's response.
///
/// The source PKC adds its counter-signature to the VCard. The final
/// `CoSignedVCard` contains both PKC DIDs in the `signatures` field.
pub fn co_sign_vcard(
    response: &CrossPkcDispatchResponse,
    source_pkc_did: &str,
    target_pkc_did: &str,
) -> CoSignedVCard {
    let signatures = vec![
        format!("sig:{}", target_pkc_did),
        format!("sig:{}", source_pkc_did),
    ];
    CoSignedVCard {
        vcard_hash: response.vcard_hash.clone(),
        vcard_yaml: response.vcard_yaml.clone(),
        signatures,
    }
}

thread_local! {
    static ROUTER: RefCell<FederationRouter> = RefCell::new(FederationRouter::new());
}

pub fn init_federation() {
    ROUTER.with(|r| *r.borrow_mut() = FederationRouter::new());
}

pub fn register_peer(peer: Peer) {
    ROUTER.with(|r| r.borrow_mut().register_peer(peer));
}

pub fn dispatch_pcard(pcard_hash: &str, sender_did: &str) -> Result<FederationMessage, String> {
    ROUTER.with(|r| r.borrow_mut().dispatch_pcard(pcard_hash, sender_did))
}

pub fn take_inbox() -> Vec<(String, FederationMessage)> {
    ROUTER.with(|r| std::mem::take(&mut r.borrow_mut().inbox))
}

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

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_peer_registration() {
        init_federation();
        let peer = Peer {
            did: "did:key:alice".to_string(),
            verifying_key: "vk-alice".to_string(),
            endpoint: "localhost:9000".to_string(),
        };
        register_peer(peer.clone());
        ROUTER.with(|r| {
            assert_eq!(r.borrow().peers.get("did:key:alice"), Some(&peer));
        });
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_dispatch_pcard_creates_co_signed_message() {
        init_federation();
        let peer = Peer {
            did: "did:key:bob".to_string(),
            verifying_key: "vk-bob".to_string(),
            endpoint: "localhost:9001".to_string(),
        };
        register_peer(peer);
        let msg = dispatch_pcard("sha256:pcard1", "did:key:bob").unwrap();
        match msg {
            FederationMessage::PCardDispatch { pcard_hash, sender_did, co_signatures } => {
                assert_eq!(pcard_hash, "sha256:pcard1");
                assert_eq!(sender_did, "did:key:bob");
                assert_eq!(co_signatures, vec!["co-sig:did:key:bob"]);
            }
            _ => panic!("expected PCardDispatch"),
        }
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_unknown_sender_rejected() {
        init_federation();
        assert!(dispatch_pcard("sha256:pcard1", "did:key:unknown").is_err());
    }

    #[cfg(feature = "native")]
    #[tokio::test]
    async fn test_federation_message_quic_round_trip() {
        use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};

        let cert = generate_self_signed_cert("federation-test").unwrap();
        let server = QuicEndpoint::new_server(0, &cert).unwrap();
        let server_addr = server.local_addr().unwrap();

        let server_handle = tokio::spawn(async move {
            let conn = server.accept().await.unwrap();
            let (data, send_stream, _) = conn.recv_bi().await.unwrap();

            // Echo the message back
            conn.respond(send_stream, &data).await.unwrap();
            let _ = conn.conn.closed().await;
        });

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        let client = QuicEndpoint::new_client().unwrap();
        let conn = client.connect(&server_addr.to_string(), "federation-test").await.unwrap();

        let mut router = FederationRouter::new();
        router.register_peer(Peer {
            did: "did:key:alice".to_string(),
            verifying_key: "vk-alice".to_string(),
            endpoint: server_addr.to_string(),
        });

        // Use send (bi-stream) so server can recv_bi
        let msg = FederationMessage::Ping;
        let json = serde_json::to_vec(&msg).unwrap();
        let _response = conn.send(&json).await.unwrap();

        server_handle.await.unwrap();
        client.close();
    }

    #[cfg(feature = "native")]
    #[tokio::test]
    async fn test_cross_pkc_dispatch_round_trip() {
        use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};
        use std::time::Instant;

        let cert = generate_self_signed_cert("cross-pkc-test").unwrap();
        let server = QuicEndpoint::new_server(0, &cert).unwrap();
        let server_addr = server.local_addr().unwrap();

        let server_handle = tokio::spawn(async move {
            let conn = server.accept().await.unwrap();

            // Receive the dispatch request
            let (request, send_stream) = receive_cross_pkc_dispatch(&conn).await.unwrap();
            assert_eq!(request.pcard_hash, "sha256:test-pcard");
            assert_eq!(request.source_pkc_did, "did:pkc:source");
            assert_eq!(request.target_pkc_did, "did:pkc:target");

            // Simulate PCard execution and seal a VCard
            let vcard_yaml = format!(
                "vcard_token:\n  gate_type: \"dispatch\"\n  result: \"pass\"\n  pcard_hash: \"{}\"\n  timestamp: \"{}\"",
                request.pcard_hash,
                chrono::Utc::now().to_rfc3339()
            );
            let vcard_hash = crate::fs_utils::compute_sha256_hex(vcard_yaml.as_bytes());

            let response = CrossPkcDispatchResponse {
                vcard_hash: crate::hash::prefixed(&vcard_hash),
                vcard_yaml,
                target_signature: "sig:did:pkc:target".to_string(),
                exit_code: 0,
                exec_output: "OK".to_string(),
            };

            // Send response back on the bi-stream
            let response_json = serde_json::to_vec(&response).unwrap();
            conn.respond(send_stream, &response_json).await.unwrap();
            let _ = conn.conn.closed().await;
        });

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        let client = QuicEndpoint::new_client().unwrap();
        let conn = client.connect(&server_addr.to_string(), "cross-pkc-test").await.unwrap();

        let request = CrossPkcDispatchRequest {
            pcard_hash: "sha256:test-pcard".to_string(),
            input_marking: Marking::new(),
            source_pkc_did: "did:pkc:source".to_string(),
            target_pkc_did: "did:pkc:target".to_string(),
        };

        let start = Instant::now();
        let response = dispatch_cross_pkc(&request, &conn).await.unwrap();
        let elapsed = start.elapsed();

        assert_eq!(response.exit_code, 0);
        assert_eq!(response.exec_output, "OK");
        assert!(response.vcard_hash.starts_with("blake3:") || response.vcard_hash.starts_with("sha256:"));
        assert!(response.target_signature.contains("did:pkc:target"));

        // Latency should be well under 500ms on loopback
        assert!(elapsed.as_millis() < 5000, "latency {}ms exceeds 5000ms budget", elapsed.as_millis());

        server_handle.await.unwrap();
        client.close();
    }

    #[cfg_attr(not(target_arch = "wasm32"), test)]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    fn test_vcard_co_signing_contains_both_dids() {
        let response = CrossPkcDispatchResponse {
            vcard_hash: "sha256:vcard-1".to_string(),
            vcard_yaml: "vcard_token: ...".to_string(),
            target_signature: "sig:did:pkc:target".to_string(),
            exit_code: 0,
            exec_output: "OK".to_string(),
        };

        let co_signed = co_sign_vcard(&response, "did:pkc:source", "did:pkc:target");
        assert_eq!(co_signed.signatures.len(), 2);
        assert!(co_signed.signatures.contains(&"sig:did:pkc:target".to_string()));
        assert!(co_signed.signatures.contains(&"sig:did:pkc:source".to_string()));
    }

    #[cfg(feature = "native")]
    #[tokio::test]
    async fn test_cross_pkc_dispatch_timeout_on_unreachable_target() {
        use crate::quic_transport::{QuicEndpoint, generate_self_signed_cert};

        let cert = generate_self_signed_cert("timeout-test").unwrap();
        // Bind server but close it immediately to simulate unreachable target
        let server = QuicEndpoint::new_server(0, &cert).unwrap();
        let server_addr = server.local_addr().unwrap();
        drop(server);

        let client = QuicEndpoint::new_client().unwrap();
        // This should fail since the server is gone
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            client.connect(&server_addr.to_string(), "timeout-test"),
        ).await;

        assert!(result.is_err() || result.unwrap().is_err(), "expected timeout or connection error");
        client.close();
    }
}