coreason-runtime 0.1.0

Kinetic Plane execution engine for the CoReason Tripartite Cybernetic Manifold
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
// Copyright (c) 2026 CoReason, Inc.
// All rights reserved.

//! Merkle DAG WORM (Write-Once Read-Many) Commit Ledger (#323).
//!
//! Replaces `coreason_runtime/execution_plane/worm_ledger.py`.
//!
//! Implements a tamper-evident cryptographic log compliant with SEC Rule 17a-4/204-2.
//! State transitions are Merkle-chained using SHA-256, forming an append-only DAG
//! where each entry references the hash of the prior entry. Any out-of-band mutation
//! is programmatically detectable by re-verifying the chain.
//!
//! Zero Waste: Delegates SHA-256 hashing to the `sha2` crate (MIT/Apache-2.0).
//! We only write the domain-specific Merkle chaining and ledger management logic.

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::sync::{Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};

// ─── Error Types ──────────────────────────────────────────────────────

/// Raised when tamper-evident Merkle chain verification fails.
///
/// This indicates an out-of-band database mutation or replay attack
/// that violates SEC Rule 17a-4/204-2 WORM storage compliance.
#[derive(Debug, Clone)]
pub struct MerkleChainViolationError {
    pub message: String,
}

impl std::fmt::Display for MerkleChainViolationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MerkleChainViolation: {}", self.message)
    }
}

impl std::error::Error for MerkleChainViolationError {}

// ─── Canonicalization & Hashing ───────────────────────────────────────

/// Produce a deterministic canonical representation of a JSON state value.
///
/// Zero Waste: Delegates to `olpc-cjson::CanonicalFormatter` (RFC 8785 Canonical JSON).
/// Guarantees sorted keys and deterministic output for identical inputs.
pub fn canonicalize_state(state: &serde_json::Value) -> String {
    let mut buf = Vec::new();
    let mut serializer =
        serde_json::Serializer::with_formatter(&mut buf, olpc_cjson::CanonicalFormatter::new());
    serde::Serialize::serialize(state, &mut serializer).unwrap();
    String::from_utf8(buf).unwrap_or_default()
}

/// Compute the Merkle chain hash: SHA-256(prior_hash || ":" || canonical_state).
///
/// This creates an unbroken chain where each hash depends on all prior
/// state transitions, making any retroactive modification detectable.
///
/// Zero Waste: Delegates to `sha2::Sha256`.
pub fn compute_merkle_hash(canonical_state: &str, prior_hash: &str) -> String {
    let combined = format!("{}:{}", prior_hash, canonical_state);
    let mut hasher = Sha256::new();
    hasher.update(combined.as_bytes());
    format!("{:x}", hasher.finalize())
}

// ─── Ledger Entry ─────────────────────────────────────────────────────

/// A single entry in the WORM commit ledger.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LedgerEntry {
    /// Monotonically increasing integer.
    pub sequence_id: u64,
    /// The Temporal workflow that produced this state transition.
    pub workflow_id: String,
    /// SHA-256(prior_hash || canonical_state).
    pub merkle_hash: String,
    /// The merkle_hash of the previous entry (genesis = "0" * 64).
    pub prior_hash: String,
    /// The serialized state delta.
    pub canonical_state: String,
    /// Unix epoch timestamp of the commit.
    pub timestamp: f64,
}

// ─── WORM Commit Ledger ───────────────────────────────────────────────

/// The genesis hash: 64 zero characters (null SHA-256).
const GENESIS_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000";

/// Append-only commit ledger for tamper-evident state tracking.
///
/// Each commit entry contains:
/// - `sequence_id`: Monotonically increasing integer
/// - `workflow_id`: The Temporal workflow that produced this state transition
/// - `merkle_hash`: SHA-256(prior_hash || canonical_state)
/// - `prior_hash`: The merkle_hash of the previous entry (genesis = "0" * 64)
/// - `canonical_state`: The serialized state delta
/// - `timestamp`: Unix epoch of the commit
pub struct WORMCommitLedger {
    last_hash: String,
    sequence_id: u64,
    entries: Vec<LedgerEntry>,
}

impl WORMCommitLedger {
    /// Create a new empty WORM commit ledger.
    pub fn new() -> Self {
        Self {
            last_hash: GENESIS_HASH.to_string(),
            sequence_id: 0,
            entries: Vec::new(),
        }
    }

    /// Append a new state transition to the WORM ledger.
    ///
    /// Returns the new merkle_hash for the entry.
    pub fn append(&mut self, workflow_id: &str, state_delta: &serde_json::Value) -> String {
        let canonical = canonicalize_state(state_delta);
        let new_hash = compute_merkle_hash(&canonical, &self.last_hash);

        self.sequence_id += 1;
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs_f64();

        let entry = LedgerEntry {
            sequence_id: self.sequence_id,
            workflow_id: workflow_id.to_string(),
            merkle_hash: new_hash.clone(),
            prior_hash: self.last_hash.clone(),
            canonical_state: canonical,
            timestamp: now,
        };

        self.entries.push(entry);
        self.last_hash = new_hash.clone();
        new_hash
    }

    /// Verify the integrity of the entire Merkle chain.
    ///
    /// Returns `Ok(true)` if the chain is valid.
    /// Returns `Err(MerkleChainViolationError)` if any entry has been tampered with.
    pub fn verify_chain(&self) -> Result<bool, MerkleChainViolationError> {
        let mut expected_prior = GENESIS_HASH.to_string();

        for entry in &self.entries {
            let expected_hash = compute_merkle_hash(&entry.canonical_state, &expected_prior);

            if entry.merkle_hash != expected_hash {
                return Err(MerkleChainViolationError {
                    message: format!(
                        "Tamper detected at sequence {}: expected hash {}... but found {}... \
                         This violates SEC Rule 17a-4/204-2 WORM storage compliance.",
                        entry.sequence_id,
                        &expected_hash[..16],
                        &entry.merkle_hash[..16],
                    ),
                });
            }

            if entry.prior_hash != expected_prior {
                return Err(MerkleChainViolationError {
                    message: format!(
                        "Chain break at sequence {}: prior_hash {}... does not match expected {}...",
                        entry.sequence_id,
                        &entry.prior_hash[..16],
                        &expected_prior[..16],
                    ),
                });
            }

            expected_prior = entry.merkle_hash.clone();
        }

        Ok(true)
    }

    /// Return the hash of the most recent commit.
    pub fn last_hash(&self) -> &str {
        &self.last_hash
    }

    /// Return the number of commits in the ledger.
    pub fn len(&self) -> u64 {
        self.sequence_id
    }

    /// Return true if the ledger has no commits.
    pub fn is_empty(&self) -> bool {
        self.sequence_id == 0
    }

    /// Retrieve all entries from the ledger, ordered by sequence_id.
    pub fn entries(&self) -> &[LedgerEntry] {
        &self.entries
    }

    /// Query entries by time range (inclusive bounds).
    ///
    /// Returns all entries with `start_time <= timestamp <= end_time`.
    pub fn query_by_time_range(&self, start_time: f64, end_time: f64) -> Vec<&LedgerEntry> {
        self.entries
            .iter()
            .filter(|e| e.timestamp >= start_time && e.timestamp <= end_time)
            .collect()
    }

    /// Query a single entry by its sequence_id.
    ///
    /// Returns `None` if no entry with the given ID exists.
    pub fn query_by_id(&self, sequence_id: u64) -> Option<&LedgerEntry> {
        self.entries.iter().find(|e| e.sequence_id == sequence_id)
    }

    /// Serialize the entire ledger to a JSON value.
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "last_hash": self.last_hash,
            "sequence_id": self.sequence_id,
            "entries": self.entries,
        })
    }
}

impl Default for WORMCommitLedger {
    fn default() -> Self {
        Self::new()
    }
}

// ─── Thread-Safe Singleton ────────────────────────────────────────────

/// Get or create the singleton WORM commit ledger instance.
///
/// Thread-safe via `OnceLock` + `Mutex`.
pub fn get_worm_ledger() -> &'static Mutex<WORMCommitLedger> {
    static INSTANCE: OnceLock<Mutex<WORMCommitLedger>> = OnceLock::new();
    INSTANCE.get_or_init(|| Mutex::new(WORMCommitLedger::new()))
}

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

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

    #[test]
    fn test_genesis_state() {
        let ledger = WORMCommitLedger::new();
        assert_eq!(ledger.last_hash(), GENESIS_HASH);
        assert_eq!(ledger.len(), 0);
        assert!(ledger.is_empty());
    }

    #[test]
    fn test_append_single_entry() {
        let mut ledger = WORMCommitLedger::new();
        let state = serde_json::json!({"action": "deploy", "version": "1.0"});
        let hash = ledger.append("wf-001", &state);

        assert_ne!(hash, GENESIS_HASH);
        assert_eq!(ledger.len(), 1);
        assert!(!ledger.is_empty());
        assert_eq!(ledger.last_hash(), hash);
    }

    #[test]
    fn test_append_multiple_entries_chain() {
        let mut ledger = WORMCommitLedger::new();
        let h1 = ledger.append("wf-001", &serde_json::json!({"step": 1}));
        let h2 = ledger.append("wf-001", &serde_json::json!({"step": 2}));
        let h3 = ledger.append("wf-002", &serde_json::json!({"step": 3}));

        assert_eq!(ledger.len(), 3);
        // Each hash is different
        assert_ne!(h1, h2);
        assert_ne!(h2, h3);
        // Chain links are correct
        assert_eq!(ledger.entries()[0].prior_hash, GENESIS_HASH);
        assert_eq!(ledger.entries()[1].prior_hash, h1);
        assert_eq!(ledger.entries()[2].prior_hash, h2);
    }

    #[test]
    fn test_verify_chain_valid() {
        let mut ledger = WORMCommitLedger::new();
        ledger.append("wf-001", &serde_json::json!({"a": 1}));
        ledger.append("wf-001", &serde_json::json!({"b": 2}));
        ledger.append("wf-002", &serde_json::json!({"c": 3}));

        assert!(ledger.verify_chain().is_ok());
    }

    #[test]
    fn test_verify_chain_detects_tamper() {
        let mut ledger = WORMCommitLedger::new();
        ledger.append("wf-001", &serde_json::json!({"a": 1}));
        ledger.append("wf-001", &serde_json::json!({"b": 2}));

        // Tamper with the first entry's canonical_state
        ledger.entries[0].canonical_state = "{\"tampered\":true}".to_string();

        let result = ledger.verify_chain();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("Tamper detected at sequence 1"));
    }

    #[test]
    fn test_verify_chain_detects_prior_hash_break() {
        let mut ledger = WORMCommitLedger::new();
        ledger.append("wf-001", &serde_json::json!({"a": 1}));
        ledger.append("wf-001", &serde_json::json!({"b": 2}));

        // Break the chain link
        ledger.entries[1].prior_hash =
            "bad_hash_0000000000000000000000000000000000000000000000000000".to_string();
        // Also fix the merkle_hash to match the tampered prior_hash so we hit the prior_hash check
        let canonical = &ledger.entries[1].canonical_state;
        ledger.entries[1].merkle_hash =
            compute_merkle_hash(canonical, &ledger.entries[1].prior_hash);

        let result = ledger.verify_chain();
        assert!(result.is_err());
    }

    #[test]
    fn test_verify_empty_chain() {
        let ledger = WORMCommitLedger::new();
        assert!(ledger.verify_chain().is_ok());
    }

    #[test]
    fn test_canonicalize_state_deterministic() {
        // Keys in different insertion order should produce identical canonical form
        let a = serde_json::json!({"z": 1, "a": 2, "m": 3});
        let b = serde_json::json!({"a": 2, "m": 3, "z": 1});
        assert_eq!(canonicalize_state(&a), canonicalize_state(&b));
    }

    #[test]
    fn test_canonicalize_nested_objects() {
        let state = serde_json::json!({"outer": {"b": 2, "a": 1}});
        let canonical = canonicalize_state(&state);
        // "a" should come before "b" in the output
        let a_pos = canonical.find("\"a\"").unwrap();
        let b_pos = canonical.find("\"b\"").unwrap();
        assert!(a_pos < b_pos);
    }

    #[test]
    fn test_compute_merkle_hash_deterministic() {
        let h1 = compute_merkle_hash("test_state", GENESIS_HASH);
        let h2 = compute_merkle_hash("test_state", GENESIS_HASH);
        assert_eq!(h1, h2);
        assert_eq!(h1.len(), 64); // SHA-256 hex digest length
    }

    #[test]
    fn test_compute_merkle_hash_different_inputs() {
        let h1 = compute_merkle_hash("state_a", GENESIS_HASH);
        let h2 = compute_merkle_hash("state_b", GENESIS_HASH);
        assert_ne!(h1, h2);
    }

    #[test]
    fn test_query_by_id() {
        let mut ledger = WORMCommitLedger::new();
        ledger.append("wf-001", &serde_json::json!({"x": 1}));
        ledger.append("wf-002", &serde_json::json!({"x": 2}));

        let entry = ledger.query_by_id(1).unwrap();
        assert_eq!(entry.workflow_id, "wf-001");

        let entry2 = ledger.query_by_id(2).unwrap();
        assert_eq!(entry2.workflow_id, "wf-002");

        assert!(ledger.query_by_id(999).is_none());
    }

    #[test]
    fn test_query_by_time_range() {
        let mut ledger = WORMCommitLedger::new();
        ledger.append("wf-001", &serde_json::json!({"x": 1}));

        // All entries should fall within a wide time range
        let all = ledger.query_by_time_range(0.0, f64::MAX);
        assert_eq!(all.len(), 1);

        // No entries in the distant past
        let none = ledger.query_by_time_range(0.0, 1.0);
        assert!(none.is_empty());
    }

    #[test]
    fn test_to_json() {
        let mut ledger = WORMCommitLedger::new();
        ledger.append("wf-001", &serde_json::json!({"action": "test"}));

        let json = ledger.to_json();
        assert!(json["last_hash"].is_string());
        assert_eq!(json["sequence_id"], 1);
        assert!(json["entries"].is_array());
        assert_eq!(json["entries"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn test_singleton_ledger() {
        let ledger = get_worm_ledger();
        let mut guard = ledger.lock().unwrap();
        let initial_len = guard.len();
        guard.append("singleton-test", &serde_json::json!({"singleton": true}));
        assert_eq!(guard.len(), initial_len + 1);
    }
}