exocortex-server 0.3.0

The Exocortex node binary: mcp-standalone and backend-node modes over one listener (gRPC + HTTP + SSE) with gossip and lease re-election.
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
//! H11 / §23 #18: the full session-wrapup chain over the wire — a producer
//! submits a batch to the backend node via gRPC, storage commits publish
//! invalidations through the cluster hub, and a sibling client's SSE
//! subscriber observes the memory in its local cache within 500ms.
//! R-T16a: a second sync of the same source with a bumped snapshot_id
//! produces ADDITIONAL assertions, never overwrites.

use std::sync::Arc;

struct McpProcess {
    child: std::process::Child,
    input: std::process::ChildStdin,
    output: std::sync::mpsc::Receiver<Result<String, String>>,
}

fn bounded_lines(
    mut stdout: std::process::ChildStdout,
) -> std::sync::mpsc::Receiver<Result<String, String>> {
    let (sender, output) = std::sync::mpsc::channel();
    std::thread::spawn(move || loop {
        use std::io::Read as _;
        let mut line = Vec::new();
        let result = loop {
            let mut byte = [0_u8; 1];
            match stdout.read(&mut byte) {
                Ok(0) if line.is_empty() => break None,
                Ok(0) => break Some(Err("MCP child closed stdout mid-response".into())),
                Ok(_) if byte[0] == b'\n' => {
                    break Some(
                        String::from_utf8(line)
                            .map_err(|_| "MCP child response was not UTF-8".into()),
                    )
                }
                Ok(_) if line.len() == exocortex_wire::limits::MAX_MCP_REQUEST_BYTES => {
                    break Some(Err("MCP child response exceeded 1 MiB".into()));
                }
                Ok(_) => line.push(byte[0]),
                Err(error) => {
                    break Some(Err(format!("MCP child stdout failed: {error}")));
                }
            }
        };
        let Some(result) = result else {
            break;
        };
        if sender.send(result).is_err() {
            break;
        }
    });
    output
}

impl McpProcess {
    fn spawn(data_dir: &std::path::Path) -> Self {
        use std::process::Stdio;
        let test_exe = std::env::current_exe().unwrap();
        let debug_dir = test_exe.parent().unwrap().parent().unwrap();
        let mut child = std::process::Command::new(debug_dir.join("exocortex-mcp-client"))
            .args([
                "--org",
                "org",
                "--user",
                "e2e",
                "--data-dir",
                data_dir.to_str().unwrap(),
            ])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .spawn()
            .expect("the acceptance gate builds exocortex-mcp-client");
        let output = bounded_lines(child.stdout.take().unwrap());
        Self {
            input: child.stdin.take().unwrap(),
            output,
            child,
        }
    }

    fn send(&mut self, messages: &[serde_json::Value]) {
        use std::io::Write;
        for message in messages {
            writeln!(self.input, "{message}").unwrap();
        }
        self.input.flush().unwrap();
    }

    fn read(&mut self) -> serde_json::Value {
        match self.output.recv_timeout(std::time::Duration::from_secs(10)) {
            Ok(Ok(line)) => serde_json::from_str(&line).unwrap(),
            result => {
                let _ = self.child.kill();
                let _ = self.child.wait();
                panic!("MCP child response failed or timed out: {result:?}");
            }
        }
    }
}

impl Drop for McpProcess {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

use exocortex_kernel::Ontology;
use exocortex_storage::{InMemoryStorage, Storage};
use exocortex_wire::ingest::v1::{
    ingest_service_client::IngestServiceClient, ExternalKey, ExternalSnapshotInfo, IngestBatch,
    MemoryDraft, ProducerIdentity,
};

use exocortex_cache::LocalCache;
use exocortex_client::sync::{run_sse_sync, SseSyncConfig};

const CLUSTER_KEY: [u8; 32] = [7u8; 32];
const PRODUCER_KEY: [u8; 32] = [8u8; 32];
const HARNESS_STARTUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

fn authed<T>(message: T) -> tonic::Request<T> {
    let mut request = tonic::Request::new(message);
    request.metadata_mut().insert(
        "authorization",
        "Bearer test-only-e2e-bearer-token-00000000"
            .parse()
            .unwrap(),
    );
    request
}

async fn boot() -> (
    exocortex_server::backend::BackendNode<InMemoryStorage>,
    Arc<InMemoryStorage>,
    Arc<Ontology>,
    std::net::SocketAddr,
) {
    let onto = Arc::new(Ontology::from_packs(vec![exocortex_pack_dev_v1::pack_def()]).unwrap());
    let storage = Arc::new(InMemoryStorage::new(onto.clone()));
    let node = exocortex_server::backend::run_backend_node(
        storage.clone(),
        onto.clone(),
        exocortex_server::backend::BackendNodeArgs {
            org: "org".into(),
            bind: "127.0.0.1:0".into(),
            transport: exocortex_server::backend::TransportSecurity::PlaintextLoopback,
            node_id: "e2e-node".into(),
            cluster_secret: CLUSTER_KEY,
            principals: Arc::new(
                exocortex_server::principal::PrincipalRegistry::single(
                    "test-only-e2e-bearer-token-00000000".into(),
                    exocortex_ops::operations::ops_vc(
                        "org",
                        "e2e",
                        exocortex_kernel::Visibility::Org,
                    ),
                )
                .unwrap(),
            ),
            gossip_listen: "127.0.0.1:0".parse().unwrap(),
            seed_nodes: vec![],
            redis_url: None,
            quiet_hours: exocortex_dreams::fire::QuietHours::none(),
            admin_source_policies: vec![
                (
                    (
                        "org".into(),
                        "iceberg://warehouse/orders".into(),
                        "external-sync".into(),
                    ),
                    exocortex_ingest::service::AdminSourcePolicy {
                        ceiling: exocortex_kernel::Visibility::Org,
                        kind: exocortex_kernel::ProducerKind::AnalyticsAdapter,
                        signing_key: PRODUCER_KEY,
                    },
                ),
                (
                    (
                        "org".into(),
                        "session://e2e".into(),
                        "session-wrapup".into(),
                    ),
                    exocortex_ingest::service::AdminSourcePolicy {
                        ceiling: exocortex_kernel::Visibility::Org,
                        kind: exocortex_kernel::ProducerKind::CodingAgent,
                        signing_key: PRODUCER_KEY,
                    },
                ),
            ],
        },
    )
    .await
    .unwrap();
    let addr = node.local_addr;
    (node, storage, onto, addr)
}

fn signed(mut b: IngestBatch) -> IngestBatch {
    exocortex_wire::signing::prepare_batch(&PRODUCER_KEY, &mut b);
    b
}

fn ext_batch(fp: [u8; 32], snapshot: &str, key: &str, title: &str) -> IngestBatch {
    signed(IngestBatch {
        org_id: "org".into(),
        source_uri: "iceberg://warehouse/orders".into(),
        producer_id: "external-sync".into(),
        batch_id: format!("b-{snapshot}-{key}"),
        mapping_version: "orders:1.0.0".into(),
        ontology_fingerprint: fp.to_vec(),
        ceiling: 3,
        checksum: String::new(),
        observed_at: None,
        recorded_at: None,
        snapshot: Some(ExternalSnapshotInfo {
            snapshot_id: snapshot.into(),
            schema_hash: [0u8; 32].to_vec(),
            source_flavor: "custom".into(),
        }),
        memories: vec![MemoryDraft {
            draft_key: key.into(),
            id: String::new(),
            memory_type: "General".into(),
            title: title.into(),
            content: "orders row".into(),
            tags: vec![],
            visibility: 3,
            valid_from: None,
            valid_until: None,
            external_key: Some(ExternalKey {
                table_uuid: [9u8; 16].to_vec(),
                logical_pk: key.into(),
                mapping_version: 1,
            }),
        }],
        relationships: vec![],
        producer: Some(ProducerIdentity {
            node_id: "n".into(),
            agent_id: String::new(),
            adapter_id: String::new(),
            hmac_signature: vec![],

            client_metadata: None,
        }),
    })
}

#[tokio::test(flavor = "multi_thread")]
async fn wrapup_chain_grpc_to_sse_to_sibling_client() {
    let (node, storage, onto, addr) = boot().await;
    let keepalive = node;

    // Sibling client: cache + writer over the same storage (visibility of
    // the committed rows), SSE subscriber against the node's HTTP surface.
    let (cache, rx) = LocalCache::new(64 * 1024 * 1024);
    let cache = Arc::new(cache);
    {
        let cache = cache.clone();
        let storage = storage.clone();
        tokio::spawn(async move { cache.run(storage, rx).await });
    }
    let seed = test_mem("seed", 1);
    storage.upsert_memory(&seed).await.unwrap();
    cache
        .reseed_from_storage(&*storage, &"org".into())
        .await
        .unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    let mut cfg = SseSyncConfig::new(format!("http://{addr}"), CLUSTER_KEY, onto.fingerprint.0);
    cfg.backoff = std::time::Duration::from_millis(50);
    // CS1: /v1/changes sits behind the same bearer layer as the op surface.
    cfg.bearer = Some("test-only-e2e-bearer-token-00000000".into());
    cfg.client_key = Some(exocortex_server::sse::derive_client_sse_key(
        &CLUSTER_KEY,
        "test-only-e2e-bearer-token-00000000",
    ));
    let connection_ready = Arc::new(tokio::sync::Notify::new());
    cfg.connection_ready = Some(connection_ready.clone());
    let sync = tokio::spawn(run_sse_sync(cfg, cache.clone(), 0, None));
    tokio::time::timeout(HARNESS_STARTUP_TIMEOUT, connection_ready.notified())
        .await
        .expect("SSE subscriber establishes its live stream");

    // Producer: register + submit over real gRPC.
    let mut client = IngestServiceClient::connect(format!("http://{addr}"))
        .await
        .unwrap();
    client
        .register_source(authed(exocortex_wire::signing::registration(
            &PRODUCER_KEY,
            "org",
            "session://e2e",
            "session-wrapup",
            3,
            "session",
            "n",
            exocortex_wire::ingest::v1::ProducerKind::CodingAgent,
        )))
        .await
        .unwrap();

    let target = test_mem("chained-target", 9);
    let b = IngestBatch {
        org_id: "org".into(),
        source_uri: "session://e2e".into(),
        producer_id: "session-wrapup".into(),
        batch_id: "chain-1".into(),
        mapping_version: "session-wrapup:1.0.0".into(),
        ontology_fingerprint: onto.fingerprint.0.to_vec(),
        ceiling: 3,
        checksum: String::new(),
        observed_at: None,
        recorded_at: None,
        snapshot: None,
        memories: vec![MemoryDraft {
            draft_key: "k1".into(),
            id: String::new(),
            memory_type: "General".into(),
            title: target.title.to_string(),
            content: "chained".into(),
            tags: vec![],
            visibility: 3,
            valid_from: None,
            valid_until: None,
            external_key: None,
        }],
        relationships: vec![],
        producer: Some(ProducerIdentity {
            node_id: "n".into(),
            agent_id: "a".into(),
            adapter_id: String::new(),
            hmac_signature: vec![],

            client_metadata: None,
        }),
    };
    let ack = client
        .submit(authed(signed(b.clone())))
        .await
        .unwrap()
        .into_inner();
    assert_eq!(ack.accepted, 1, "batch accepted over gRPC: {ack:?}");

    // The committed id: derive from the storage stream (single memory).
    let committed = {
        use futures::StreamExt;
        let mut ms = storage.stream_all_memories().await;
        let mut found = None;
        while let Some(Ok(m)) = ms.next().await {
            if m.title == target.title {
                found = Some(m.id);
            }
        }
        found.expect("committed row present")
    };

    let subscriber_visibility =
        exocortex_ops::operations::ops_vc("org", "e2e", exocortex_kernel::Visibility::Org);
    let stored = storage
        .get_memory(&committed)
        .await
        .unwrap()
        .expect("committed row remains readable");
    assert!(
        exocortex_storage::memory_visible(&stored, &subscriber_visibility),
        "the authenticated subscriber principal can see the committed row"
    );

    // §23 #18: the sibling observes it through the feed within 500ms.
    let vc = exocortex_ops::VisibilityContext {
        user_id: "u".into(),
        org_id: "org".into(),
        project_ids: Default::default(),
        team_ids: Default::default(),
        max_visibility: exocortex_kernel::Visibility::Org,
    };
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(500);
    let mut seen = false;
    while tokio::time::Instant::now() < deadline {
        if cache.get_memory("org", &committed, &vc).is_some() {
            seen = true;
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    }
    sync.abort();
    assert!(
        seen,
        "sibling client observed the commit via SSE within 500ms (version={:?}, node_sync_lsn={})",
        cache.version("org"),
        keepalive.health.load().sync_lsn,
    );
}

/// §23 #18 literal chain: an MCP protocol request writes the local cache and
/// durable WAL, the synchronizer drains that exact entry, and a different
/// SSE-backed client observes the backend commit inside the 500ms budget.
#[tokio::test(flavor = "multi_thread")]
async fn mcp_wal_sync_backend_sse_sibling_is_one_chain_under_500ms() {
    let (node, storage, onto, addr) = boot().await;
    let _keepalive = node;

    let (sibling, writer) = LocalCache::new(64 * 1024 * 1024);
    let sibling = Arc::new(sibling);
    {
        let cache = sibling.clone();
        let storage = storage.clone();
        tokio::spawn(async move { cache.run(storage, writer).await });
    }
    sibling
        .reseed_from_storage(&*storage, &"org".into())
        .await
        .unwrap();
    sibling.flush().await;

    let mut sync_cfg =
        SseSyncConfig::new(format!("http://{addr}"), CLUSTER_KEY, onto.fingerprint.0);
    sync_cfg.bearer = Some("test-only-e2e-bearer-token-00000000".into());
    sync_cfg.client_key = Some(exocortex_server::sse::derive_client_sse_key(
        &CLUSTER_KEY,
        "test-only-e2e-bearer-token-00000000",
    ));
    let live = Arc::new(tokio::sync::Notify::new());
    sync_cfg.connection_ready = Some(live.clone());
    let sync = tokio::spawn(run_sse_sync(sync_cfg, sibling.clone(), 0, None));
    tokio::time::timeout(HARNESS_STARTUP_TIMEOUT, live.notified())
        .await
        .expect("sibling SSE is live before the harness write");

    let data = tempfile::tempdir().unwrap();
    let mut mcp = McpProcess::spawn(data.path());
    mcp.send(&[
        serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "acceptance", "version": "1"}}
        }),
        serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}}),
        serde_json::json!({
            "jsonrpc": "2.0", "id": 2, "method": "tools/call",
            "params": {"name": "exocortex.end_session", "arguments": {
                "session_id": "e2e", "project_id": "p", "memories": [{
                    "draft_key": "m", "memory_type": "General", "title": "Literal MCP WAL SSE chain",
                    "content": "one continuous acceptance path", "visibility": "org"
                }], "edges": []
            }}
        }),
        serde_json::json!({
            "jsonrpc": "2.0", "id": 3, "method": "tools/call",
            "params": {"name": "exocortex.search_memories", "arguments": {"query": "Literal MCP WAL SSE chain", "limit": 5}}
        }),
    ]);
    assert!(mcp.read().get("result").is_some(), "MCP initialize");
    let ack = mcp.read();
    assert_eq!(
        serde_json::from_str::<serde_json::Value>(
            ack["result"]["content"][0]["text"].as_str().unwrap()
        )
        .unwrap()["sync_pending"],
        true,
        "harness request durably enters the WAL"
    );
    let local = mcp.read();
    let local_payload: serde_json::Value =
        serde_json::from_str(local["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert_eq!(
        local_payload["memories"].as_array().unwrap().len(),
        1,
        "same-process local cache sees the write"
    );
    drop(mcp);

    let wal = Arc::new(exocortex_client::wal::Wal::open(&data.path().join("wal")).unwrap());
    let entry = wal
        .pending_entries()
        .unwrap()
        .into_iter()
        .next()
        .expect("durable pending entry");
    let local_id = entry.memory_ids[0];
    let endpoint = tonic::transport::Endpoint::from_shared(format!("http://{addr}")).unwrap();
    let mut ingest = IngestServiceClient::new(endpoint.connect().await.unwrap());
    let started = tokio::time::Instant::now();
    let report = exocortex_client::drain::drain_once(
        &wal,
        &mut ingest,
        &PRODUCER_KEY,
        onto.fingerprint.0,
        "org",
        Some("test-only-e2e-bearer-token-00000000"),
        &onto,
        "literal-chain-client",
    )
    .await
    .unwrap();
    assert_eq!(report.synced, 1, "the exact WAL entry reaches the backend");
    assert_eq!(
        entry.memory_ids,
        vec![local_id],
        "the drained WAL row is stable"
    );

    let committed_id = {
        use futures::StreamExt;
        let mut rows = storage.stream_all_memories().await;
        let mut found = None;
        while let Some(Ok(memory)) = rows.next().await {
            if memory.title == "Literal MCP WAL SSE chain" {
                found = Some(memory.id);
            }
        }
        found.expect("the drained WAL row is committed under its server identity")
    };

    let vc = exocortex_ops::operations::ops_vc("org", "e2e", exocortex_kernel::Visibility::Org);
    tokio::time::timeout(std::time::Duration::from_millis(500), async {
        while sibling.get_memory("org", &committed_id, &vc).is_none() {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("distinct sibling observes the synced WAL entry within 500ms");
    assert!(started.elapsed() < std::time::Duration::from_millis(500));
    sync.abort();
}

/// R-T16a under the shipped identity contract (B8/B9: external identity
/// is (org, source, table_uuid, logical_pk, mapping_version); snapshot id
/// and hash ride PROVENANCE, not identity). A re-sync of the same row
/// under a new snapshot upserts the SAME id with the new snapshot stamped
/// — one current row, never a duplicate — while a different logical_pk is
/// a genuinely new assertion that appends. (The old "two rows" assertion
/// passed only against the double's version stack, a model the Falkor
/// backend does not have — audit ST7/ST8.)
#[tokio::test(flavor = "multi_thread")]
async fn two_sync_snapshot_bump_upserts_same_row_new_pk_appends() {
    let (node, storage, onto, addr) = boot().await;
    let _keepalive = node;
    let mut client = IngestServiceClient::connect(format!("http://{addr}"))
        .await
        .unwrap();
    client
        .register_source(authed(exocortex_wire::signing::registration(
            &PRODUCER_KEY,
            "org",
            "iceberg://warehouse/orders",
            "external-sync",
            3,
            "custom",
            "n",
            exocortex_wire::ingest::v1::ProducerKind::CodingAgent,
        )))
        .await
        .unwrap();

    let s1 = ext_batch(
        onto.fingerprint.0,
        "s1",
        "order-7",
        "payments owned by team-payments",
    );
    let ack1 = client.submit(authed(s1)).await.unwrap().into_inner();
    assert_eq!(ack1.accepted, 1, "first sync lands: {ack1:?}");

    let s2 = ext_batch(
        onto.fingerprint.0,
        "s2",
        "order-7",
        "payments owned by team-platform",
    );
    let ack2 = client.submit(authed(s2)).await.unwrap().into_inner();
    assert_eq!(ack2.accepted, 1, "second sync lands: {ack2:?}");

    // A different row is a genuinely new assertion.
    let s3 = ext_batch(
        onto.fingerprint.0,
        "s2",
        "order-8",
        "payments owned by team-platform",
    );
    let ack3 = client.submit(authed(s3)).await.unwrap().into_inner();
    assert_eq!(ack3.accepted, 1, "new logical_pk appends: {ack3:?}");

    use futures::StreamExt;
    let mut ms = storage.stream_all_memories().await;
    let mut rows = Vec::new();
    while let Some(Ok(m)) = ms.next().await {
        if m.title.contains("payments owned by") {
            rows.push(m);
        }
    }
    // order-7 exists ONCE (upserted in place, newest content) and order-8
    // exists as its own row.
    assert_eq!(rows.len(), 2, "one row per external key: {rows:?}");
    let order7 = rows
        .iter()
        .find(|m| matches!(&m.provenance, exocortex_kernel::Provenance::ExternalSnapshot(e) if e.external_key.logical_pk.as_slice() == b"order-7"))
        .expect("order-7 row present");
    assert_eq!(
        order7.title, "payments owned by team-platform",
        "same-key re-sync upserts the current content"
    );
    let snap = match &order7.provenance {
        exocortex_kernel::Provenance::ExternalSnapshot(e) => e,
        other => panic!("external provenance, got {other:?}"),
    };
    assert_eq!(
        snap.snapshot_id.as_str(),
        "s2",
        "provenance carries the LATEST snapshot id"
    );
}

/// Deterministic test memory (fixed id from `n`).
fn test_mem(title: &str, n: u8) -> exocortex_kernel::Memory {
    use exocortex_kernel::{Memory, MemoryContext, Provenance, Visibility, LSN};
    Memory {
        id: exocortex_kernel::MemoryId([n; 16]),
        memory_type: 3,
        title: title.into(),
        content: format!("content {title}"),
        summary: None,
        tags: Default::default(),
        visibility: Visibility::Org,
        provenance: Provenance::Asserted {
            author: "t".into(),
            producer_kind: None,
        },
        context: MemoryContext {
            timestamp: chrono::Utc::now(),
            project_id: None,
            project_path: None,
            team_id: None,
            tenant_id: None,
            session_id: None,
            user_id: None,
            created_by: None,
            files_involved: Default::default(),
            languages: Default::default(),
            frameworks: Default::default(),
            technologies: Default::default(),
            git_commit: None,
            git_branch: None,
            working_directory: None,
            entities: Default::default(),
            additional_metadata: serde_json::Value::Null,
        },
        importance: exocortex_kernel::memory::F01::new(0.5).unwrap(),
        confidence: exocortex_kernel::memory::F01::new(0.8).unwrap(),
        effectiveness: None,
        usage_count: 0,
        valid_from: chrono::Utc::now(),
        valid_until: None,
        recorded_at: chrono::Utc::now(),
        invalidated_by: None,
        embedding: None,
        lsn: LSN::new_local(0),
    }
}