wm-memory 9.1.8

Local-first persistent memory store with sessions and continuity for AI coding agents.
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
//! Record attestations (Track F Slice A, D5 opening move) — tamper-evident
//! provenance for created memories.
//!
//! Every `memory.create` with a node key available appends one attestation
//! to the `attestations` DBI, keyed `att:{galaxy}:{memory_id}`. The entry
//! binds the memory's content hash to the creating agent and node via an
//! Ed25519 signature — the same algorithm as the Sangha mesh identity and
//! its own HKDF-SHA256 purpose subkey (`wm/record-attestation/v1`) derived
//! from the same canonical 64-hex root (`wm_core::kdf::root_bytes`; S9 §2.1 /
//! Q39 §2), so identity and attestation keys never cross.
//!
//! Payload domain separation: the signed bytes begin with
//! `ATTESTATION_DOMAIN` (`wm-record-attestation/v1`), so a record
//! attestation can never verify as a mesh heartbeat/chat payload or vice
//! versa, even though both subkeys share one root. The 9.1.8 KDF split
//! (S9 §2.1) rules new attestations onto the derived subkey; pre-9.1.8 rows
//! keep verifying against their recorded pubkey, so no re-key of history is
//! needed.
//!
//! Why the sign/verify helper lives here instead of reusing
//! `wm_sangha::crypto`: `wm-memory` must stay free of `wm-sangha` (mesh is
//! a transport over stores, never a store dependency — otherwise future
//! mesh↔store wiring cycles). The scheme is identical (Ed25519 over the
//! domain-prefixed payload, lowercase hex); only the call site differs.
//!
//! Merkle convention for `wm anchor`: [`merkle_root_hex`] uses the same
//! Bitcoin-convention loop as the karma anchor (duplicate-last on odd
//! layers, `sha256(left || right)` upward, `sha256("")` for the empty
//! set), so anchor roots are comparable across subsystems. (Follow-up:
//! factor the shared loop out of `KarmaLedger::compute_merkle_root`.)

use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use wm_core::Galaxy;
use wm_core::kdf::{RECORD_ATTESTATION_INFO, hkdf32};

use crate::memory::MemoryId;

/// Domain prefix for every signed attestation payload. Cross-protocol
/// confusion is impossible by construction: no other WhiteMagic protocol
/// signs bytes beginning with this string.
pub const ATTESTATION_DOMAIN: &str = "wm-record-attestation/v1";

/// Name of the LMDB sub-database holding attestations.
pub const ATTESTATIONS_DB: &str = "attestations";

/// Environment variable carrying the node signing key (hex, 32 bytes) —
/// the same `WM_MESH_KEY` the Sangha mesh uses for peer identity.
pub const ATTESTATION_KEY_ENV: &str = "WM_MESH_KEY";

/// One attestation: a node's signed claim "I created this record with
/// this content hash at this time as this agent".
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RecordAttestation {
    /// Attestation domain (always [`ATTESTATION_DOMAIN`] at v1).
    pub domain: String,
    /// Galaxy db name (e.g. `"codex"`).
    pub galaxy: String,
    /// Memory id (hyphenated UUID string).
    pub memory_id: String,
    /// The memory's `content_hash` at creation time.
    pub record_hash: String,
    /// Attributing agent: dispatch session UUID when inside one,
    /// `user_id` when set, else `"local"`.
    pub agent_id: String,
    /// Unix timestamp (seconds) of the creating dispatch.
    pub timestamp: u64,
    /// Signer public key (lowercase hex) — the node's mesh identity.
    pub public_key_hex: String,
    /// Ed25519 signature over [`attestation_payload`] (lowercase hex).
    pub signature_hex: String,
}

/// Result of checking one memory's attestation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AttestationReport {
    /// An attestation row exists for this memory.
    pub attested: bool,
    /// The signature verifies against the recorded pubkey and payload.
    pub signature_valid: bool,
    /// The attested `record_hash` equals the memory's live `content_hash`
    /// (false after a content update — the revisions chain, not the
    /// attestation, covers updates by design).
    pub matches_head: bool,
    /// The attested memory id is present in its galaxy (false when the
    /// memory was deleted after attestation — the attestation row
    /// survives as evidence of what was claimed).
    pub memory_present: bool,
    /// Human-readable break descriptions; empty when fully valid.
    pub breaks: Vec<String>,
}

/// Canonical signed payload. Pipe-delimited fixed-order fields — no
/// canonical-JSON dependency, byte-stable by construction.
#[must_use]
pub fn attestation_payload(
    galaxy: &str,
    memory_id: &str,
    record_hash: &str,
    agent_id: &str,
    timestamp: u64,
) -> String {
    format!("{ATTESTATION_DOMAIN}|{galaxy}|{memory_id}|{record_hash}|{agent_id}|{timestamp}")
}

/// LMDB key for one memory's attestation: `att:{galaxy}:{memory_id}`.
#[must_use]
pub fn attestation_key(galaxy: Galaxy, id: MemoryId) -> Vec<u8> {
    format!("att:{}:{}", galaxy.db_name(), id).into_bytes()
}

/// Key prefix covering the whole attestation DBI (for full scans).
#[must_use]
pub fn attestation_prefix() -> Vec<u8> {
    b"att:".to_vec()
}

/// SHA-256 of a string, lowercase hex.
#[must_use]
pub fn sha256_hex(s: &str) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let digest = Sha256::digest(s.as_bytes());
    digest.iter().fold(String::with_capacity(64), |mut out, b| {
        out.push(HEX[(b >> 4) as usize] as char);
        out.push(HEX[(b & 0x0f) as usize] as char);
        out
    })
}

/// Decode 64-char hex into 32 bytes.
fn decode_key_hex(hex: &str) -> Option<[u8; 32]> {
    if hex.len() != 64 {
        return None;
    }
    let bytes = hex.as_bytes();
    let mut out = [0u8; 32];
    for (i, chunk) in bytes.chunks_exact(2).enumerate() {
        let hi = hex_val(chunk[0])?;
        let lo = hex_val(chunk[1])?;
        out[i] = (hi << 4) | lo;
    }
    Some(out)
}

const fn hex_val(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// Sign an attestation payload with a 32-byte secret key (hex).
/// Returns `(public_key_hex, signature_hex)`, or `None` on bad key
/// material. Pure function — env handling lives at the call site.
#[must_use]
pub fn sign_attestation(payload: &str, secret_hex: &str) -> Option<(String, String)> {
    let secret = decode_key_hex(secret_hex.trim())?;
    let signing = SigningKey::from_bytes(&secret);
    let sig = signing.sign(payload.as_bytes());
    Some((
        hex_of(&signing.verifying_key().to_bytes()),
        hex_of(&sig.to_bytes()),
    ))
}

/// Derive the record-attestation signing key (hex) from node root material.
///
/// HKDF-SHA256 with `info = "wm/record-attestation/v1"` (S9 §2.1 / Q39 §2)
/// over the **canonical** root: a 64-hex-char `WM_MESH_KEY` decoded to its 32
/// bytes — the same root the mesh identity derives from. Non-canonical
/// material derives no attestation subkey (honest negative at the call site;
/// the mesh identity alone tolerates legacy/test material via
/// [`wm_core::kdf::root_bytes`]). The legacy hex-decoded lineage stays
/// accepted during the one-release migration: each attestation stores its
/// signer pubkey, so old rows verify against their recorded key regardless of
/// lineage.
#[must_use]
pub fn derive_attestation_key_hex(root_hex: &str) -> Option<String> {
    let root = decode_key_hex(root_hex.trim())?;
    Some(hex_of(&hkdf32(&root, RECORD_ATTESTATION_INFO)))
}

/// Sign an attestation payload with the HKDF-derived attestation subkey from
/// root material. Returns `(public_key_hex, signature_hex)`; the lineage of
/// the returned key is `wm/record-attestation/v1`.
#[must_use]
pub fn sign_attestation_from_root(payload: &str, root_hex: &str) -> Option<(String, String)> {
    let key = derive_attestation_key_hex(root_hex)?;
    sign_attestation(payload, &key)
}

fn hex_of(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        out.push(HEX[(b >> 4) as usize] as char);
        out.push(HEX[(b & 0x0f) as usize] as char);
    }
    out
}

/// Verify an attestation's signature against its recorded pubkey.
#[must_use]
pub fn verify_attestation(att: &RecordAttestation) -> bool {
    if att.domain != ATTESTATION_DOMAIN {
        return false;
    }
    let payload = attestation_payload(
        &att.galaxy,
        &att.memory_id,
        &att.record_hash,
        &att.agent_id,
        att.timestamp,
    );
    let (Some(pk_bytes), Some(sig_bytes)) = (
        decode_pubkey(&att.public_key_hex),
        decode_sig(&att.signature_hex),
    ) else {
        return false;
    };
    let Ok(pk) = VerifyingKey::from_bytes(&pk_bytes) else {
        return false;
    };
    let sig = ed25519_dalek::Signature::from_bytes(&sig_bytes);
    pk.verify(payload.as_bytes(), &sig).is_ok()
}

fn decode_pubkey(hex: &str) -> Option<[u8; 32]> {
    decode_key_hex(hex)
}

fn decode_sig(hex: &str) -> Option<[u8; 64]> {
    if hex.len() != 128 {
        return None;
    }
    let bytes = hex.as_bytes();
    let mut out = [0u8; 64];
    for (i, chunk) in bytes.chunks_exact(2).enumerate() {
        out[i] = (hex_val(chunk[0])? << 4) | hex_val(chunk[1])?;
    }
    Some(out)
}

/// Merkle root over leaf-hash strings.
///
/// Same convention as the karma anchor (`KarmaLedger::compute_merkle_root`):
/// duplicate-last on odd layers, `sha256(left || right)` upward, `sha256("")`
/// for the empty set. Leaves must be pre-sorted by the caller for determinism.
#[must_use]
pub fn merkle_root_hex(leaves: &[String]) -> String {
    if leaves.is_empty() {
        return sha256_hex("");
    }
    let mut layer: Vec<String> = leaves.to_vec();
    while layer.len() > 1 {
        if layer.len() % 2 != 0 {
            let last = layer.last().cloned().unwrap_or_default();
            layer.push(last);
        }
        let mut next = Vec::with_capacity(layer.len() / 2);
        for pair in layer.chunks(2) {
            next.push(sha256_hex(&format!("{}{}", pair[0], pair[1])));
        }
        layer = next;
    }
    layer.into_iter().next().unwrap_or_default()
}

/// Anchor leaf input for one attestation: binds the record hash to the
/// attestation signature. `wm anchor` sorts leaves before hashing.
#[must_use]
pub fn anchor_leaf_input(record_hash: &str, signature_hex: &str) -> String {
    sha256_hex(&format!("{record_hash}|{signature_hex}"))
}

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

    const TEST_KEY: &str = "0bd1c44170ca3d916648a983dcdb8583d22f2da5b29fdd5ede4b38e805435577";

    fn test_attestation() -> RecordAttestation {
        let payload = attestation_payload("codex", "mem-1", "hash-1", "ses-1", 1_700_000_000);
        let (pk, sig) = sign_attestation(&payload, TEST_KEY).unwrap();
        RecordAttestation {
            domain: ATTESTATION_DOMAIN.to_string(),
            galaxy: "codex".to_string(),
            memory_id: "mem-1".to_string(),
            record_hash: "hash-1".to_string(),
            agent_id: "ses-1".to_string(),
            timestamp: 1_700_000_000,
            public_key_hex: pk,
            signature_hex: sig,
        }
    }

    #[test]
    fn payload_is_domain_prefixed_and_deterministic() {
        let a = attestation_payload("codex", "m", "h", "a", 1);
        let b = attestation_payload("codex", "m", "h", "a", 1);
        assert_eq!(a, b);
        assert!(a.starts_with("wm-record-attestation/v1|"));
        assert_ne!(a, attestation_payload("codex", "m", "h", "a", 2));
    }

    #[test]
    fn hkdf_attestation_subkey_is_domain_separated_and_verifies() {
        let derived = derive_attestation_key_hex(TEST_KEY).expect("valid root material");
        assert_eq!(derived.len(), 64);
        assert_eq!(derive_attestation_key_hex(TEST_KEY).unwrap(), derived);

        let payload = attestation_payload("codex", "mem-1", "hash-1", "ses-1", 1_700_000_000);
        let (pk, sig) = sign_attestation_from_root(&payload, TEST_KEY).unwrap();
        // Deterministic signing; distinct from the legacy hex-decode lineage.
        assert_eq!(
            sign_attestation_from_root(&payload, TEST_KEY).unwrap(),
            (pk.clone(), sig.clone())
        );
        assert_ne!(pk, sign_attestation(&payload, TEST_KEY).unwrap().0);

        let mut att = test_attestation();
        att.public_key_hex = pk;
        att.signature_hex = sig;
        assert!(
            verify_attestation(&att),
            "a derived-lineage attestation must verify against its recorded pubkey"
        );
    }

    #[test]
    fn attestation_key_follows_the_canonical_root_convention() {
        // 64-hex material is decoded before derivation (S9 §2.1 canonical
        // form) — the raw-ASCII interpretation is NOT the root.
        let canonical = derive_attestation_key_hex(TEST_KEY).unwrap();
        let raw_lineage = hex_of(&hkdf32(TEST_KEY.as_bytes(), RECORD_ATTESTATION_INFO));
        assert_ne!(
            canonical, raw_lineage,
            "64-hex root material must be hex-decoded, not read as ASCII"
        );

        // Attestations require canonical root material: non-hex input is an
        // honest negative (the mesh identity alone tolerates legacy material).
        assert!(derive_attestation_key_hex("short-legacy-test-key").is_none());
    }

    #[test]
    fn sign_and_verify_roundtrip() {
        assert!(verify_attestation(&test_attestation()));
    }

    #[test]
    fn tampered_record_hash_rejected() {
        let mut att = test_attestation();
        att.record_hash = "forged".to_string();
        assert!(!verify_attestation(&att));
    }

    #[test]
    fn wrong_domain_rejected() {
        let mut att = test_attestation();
        att.domain = "mesh-heartbeat".to_string();
        assert!(!verify_attestation(&att));
    }

    #[test]
    fn bad_key_material_returns_none() {
        let payload = attestation_payload("codex", "m", "h", "a", 1);
        assert!(sign_attestation(&payload, "zz").is_none());
        assert!(sign_attestation(&payload, "abcd").is_none());
        assert!(sign_attestation(&payload, "").is_none());
    }

    #[test]
    fn merkle_root_matches_karma_convention() {
        // Empty set: sha256("").
        assert_eq!(
            merkle_root_hex(&[]),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
        // Single leaf: the leaf itself.
        assert_eq!(merkle_root_hex(&["abc".to_string()]), "abc");
        // Two leaves: sha256(a || b).
        assert_eq!(
            merkle_root_hex(&["a".to_string(), "b".to_string()]),
            sha256_hex("ab")
        );
        // Three leaves: duplicate-last, then hash up.
        let three = merkle_root_hex(&["a".to_string(), "b".to_string(), "c".to_string()]);
        let level1 = [sha256_hex("ab"), sha256_hex("cc")];
        assert_eq!(three, sha256_hex(&format!("{}{}", level1[0], level1[1])));
        // Deterministic.
        assert_eq!(
            merkle_root_hex(&["x".to_string(), "y".to_string()]),
            merkle_root_hex(&["x".to_string(), "y".to_string()])
        );
    }

    #[test]
    fn keys_are_structured() {
        let id = MemoryId::nil();
        let key = String::from_utf8(attestation_key(Galaxy::Codex, id)).unwrap();
        assert!(key.starts_with("att:codex:"));
        assert_eq!(String::from_utf8(attestation_prefix()).unwrap(), "att:");
    }
}