remem-ai 0.5.96

Persistent memory for Claude Code and OpenAI Codex 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
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
use anyhow::{bail, Result};
use rusqlite::{params, Connection, OptionalExtension};

use super::merge::MergeResult;
use crate::memory::lifecycle::MemoryLifecycleOp;
use crate::memory::operation::{insert_operation_log, MemoryOperationInput, MemoryOperationPlan};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct ApplyOutcome {
    pub merged_id: i64,
    pub operation_id: i64,
}

pub(super) fn apply(
    conn: &mut Connection,
    project: &str,
    result: &MergeResult,
) -> Result<ApplyOutcome> {
    let tx = conn.transaction()?;
    let superseded_ids =
        validate_dream_superseded_ids(&tx, project, &result.memory_type, &result.superseded_ids)?;
    validate_dream_target_topic(
        &tx,
        project,
        &result.memory_type,
        &result.topic_key,
        &superseded_ids,
    )?;
    let state_key = crate::memory::state_key::derive_state_key(
        &result.memory_type,
        Some(&result.topic_key),
        &result.title,
        &result.content,
    )
    .map(|decision| decision.state_key);
    let operation_input = MemoryOperationInput {
        source: "dream".to_string(),
        actor: "dream".to_string(),
        source_project: project.to_string(),
        owner_scope: "repo".to_string(),
        owner_key: project.to_string(),
        memory_type: result.memory_type.clone(),
        topic_key: Some(result.topic_key.clone()),
        state_key: state_key.clone(),
        source_candidate_id: None,
        confidence: None,
    };

    // Upsert the merged memory (reuses existing topic_key upsert logic)
    let merged_id = crate::memory::insert_memory_full(
        &tx,
        Some("dream"),
        project,
        Some(&result.topic_key),
        &result.title,
        &result.content,
        &result.memory_type,
        None,
        None,
        "project",
        None,
    )?;
    let actual_superseded_ids = superseded_ids
        .into_iter()
        .filter(|id| *id != merged_id)
        .collect::<Vec<_>>();

    crate::memory::lifecycle::soft_supersede(
        &tx,
        project,
        &actual_superseded_ids,
        Some(merged_id),
    )?;
    let op = if result.superseded_ids.is_empty() {
        MemoryLifecycleOp::Add
    } else {
        MemoryLifecycleOp::Update
    };
    let plan = MemoryOperationPlan::new(op, state_key, "dream consolidation applied")
        .with_target_memory_id(Some(merged_id))
        .with_superseded_ids(actual_superseded_ids.clone());
    let operation_id = insert_operation_log(&tx, &operation_input, &plan, Some(merged_id))?;
    crate::memory::edge::insert_merged_into_edges(
        &tx,
        &actual_superseded_ids,
        merged_id,
        crate::memory::edge::MemoryEdgeWriteContext {
            source_operation_id: Some(operation_id),
            reason: Some("dream consolidation merged memories"),
            ..Default::default()
        },
    )?;

    tx.commit()?;
    Ok(ApplyOutcome {
        merged_id,
        operation_id,
    })
}

fn validate_dream_superseded_ids(
    conn: &Connection,
    project: &str,
    memory_type: &str,
    superseded_ids: &[i64],
) -> Result<Vec<i64>> {
    let mut seen = std::collections::HashSet::with_capacity(superseded_ids.len());
    let mut valid = Vec::new();
    for id in superseded_ids.iter().copied().filter(|id| seen.insert(*id)) {
        let exists: bool = conn.query_row(
            "SELECT EXISTS(
                 SELECT 1 FROM memories
                 WHERE id = ?1
                   AND project = ?2
                   AND memory_type = ?3
                   AND COALESCE(
                        owner_scope,
                        CASE WHEN COALESCE(scope, 'project') = 'global' THEN 'user' ELSE 'repo' END
                   ) = 'repo'
                   AND COALESCE(
                        owner_key,
                        CASE WHEN COALESCE(scope, 'project') = 'global' THEN 'user:default' ELSE project END
                   ) = ?2
             )",
            params![id, project, memory_type],
            |row| row.get(0),
        )?;
        if !exists {
            bail!("dream superseded memory id={id} is outside project/type/owner neighborhood");
        }
        valid.push(id);
    }
    Ok(valid)
}

fn validate_dream_target_topic(
    conn: &Connection,
    project: &str,
    memory_type: &str,
    topic_key: &str,
    superseded_ids: &[i64],
) -> Result<()> {
    let existing_id = conn
        .query_row(
            "SELECT id FROM memories
             WHERE project = ?1
               AND memory_type = ?2
               AND topic_key = ?3
               AND COALESCE(
                    owner_scope,
                    CASE WHEN COALESCE(scope, 'project') = 'global' THEN 'user' ELSE 'repo' END
               ) = 'repo'
               AND COALESCE(
                    owner_key,
                    CASE WHEN COALESCE(scope, 'project') = 'global' THEN 'user:default' ELSE project END
               ) = ?1
             ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END,
                      updated_at_epoch DESC,
                      id DESC
             LIMIT 1",
            params![project, memory_type, topic_key],
            |row| row.get::<_, i64>(0),
        )
        .optional()?;
    let Some(existing_id) = existing_id else {
        return Ok(());
    };
    if superseded_ids.contains(&existing_id) {
        return Ok(());
    }
    bail!(
        "dream target topic_key collides with memory id={existing_id} outside superseded neighborhood"
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::insert_memory;
    use crate::memory::tests_helper::setup_memory_schema;
    use rusqlite::{params, Connection};

    fn setup() -> (Connection, String) {
        let conn = Connection::open_in_memory().expect("in-memory db");
        setup_memory_schema(&conn);
        let project = "test-dream-apply".to_owned();
        (conn, project)
    }

    fn active_count(conn: &Connection, project: &str, topic_key: &str) -> i64 {
        conn.query_row(
            "SELECT COUNT(*) FROM memories WHERE project = ?1 AND topic_key = ?2 AND status = 'active'",
            params![project, topic_key],
            |row| row.get(0),
        )
        .expect("active count should query")
    }

    fn status_for_id(conn: &Connection, id: i64) -> String {
        conn.query_row(
            "SELECT status FROM memories WHERE id = ?1",
            params![id],
            |row| row.get(0),
        )
        .expect("status should query")
    }

    #[test]
    fn test_apply_upserts_merged_memory() {
        let (mut conn, project) = setup();
        let result = MergeResult {
            topic_key: "merged-topic".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Merged title".to_owned(),
            content: "Merged content".to_owned(),
            superseded_ids: vec![],
        };
        apply(&mut conn, &project, &result).expect("apply");

        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM memories WHERE project = ?1 AND topic_key = ?2",
                params![project, "merged-topic"],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(count, 1);
    }

    /// Whether the FTS index can return `id` via a MATCH on the term.
    /// For content='memories' fts5, rowid lookups proxy the source row,
    /// so MATCH is the authoritative probe for index membership.
    fn fts_indexed(conn: &Connection, id: i64, term: &str) -> bool {
        let mut stmt = conn
            .prepare(
                "SELECT 1 FROM memories_fts \
                 WHERE memories_fts MATCH ?1 AND rowid = ?2",
            )
            .expect("prepare fts probe");
        stmt.exists(params![term, id])
            .expect("fts probe should run")
    }

    #[test]
    fn test_apply_handles_duplicate_superseded_ids() -> Result<()> {
        // Codex review: a hallucinated duplicate id from the LLM must not
        // re-fire the memories_au trigger on a row that has already been
        // removed from memories_fts (which can surface as "database disk
        // image is malformed").
        let (mut conn, project) = setup();
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            None,
            "duplicateterm",
            "duplicate content",
            "decision",
            None,
        )?;

        let result = MergeResult {
            topic_key: "dup-merged".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Merged title".to_owned(),
            content: "Merged content".to_owned(),
            superseded_ids: vec![old_id, old_id, old_id],
        };
        apply(&mut conn, &project, &result)?;

        assert_eq!(status_for_id(&conn, old_id), "stale");
        assert!(
            !fts_indexed(&conn, old_id, "duplicateterm"),
            "duplicated supersede must still leave the row out of memories_fts"
        );
        let edge_count: i64 = conn.query_row(
            "SELECT COUNT(*) FROM memory_edges WHERE from_memory_id = ?1",
            params![old_id],
            |row| row.get(0),
        )?;
        assert_eq!(edge_count, 1);
        Ok(())
    }

    #[test]
    fn test_apply_removes_superseded_from_fts_index() {
        let (mut conn, project) = setup();
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            None,
            "uniqueoldtitle",
            "uniqueoldcontent",
            "decision",
            None,
        )
        .expect("insert");
        assert!(
            fts_indexed(&conn, old_id, "uniqueoldtitle"),
            "fresh insert must be indexed in memories_fts"
        );

        let result = MergeResult {
            topic_key: "fts-merged".to_owned(),
            memory_type: "decision".to_owned(),
            title: "New title".to_owned(),
            content: "New content".to_owned(),
            superseded_ids: vec![old_id],
        };
        apply(&mut conn, &project, &result).expect("apply");

        assert_eq!(status_for_id(&conn, old_id), "stale");
        assert!(
            !fts_indexed(&conn, old_id, "uniqueoldtitle"),
            "superseded memory must not match in memories_fts"
        );
    }

    #[test]
    fn test_apply_keeps_reused_topic_key_merge_active() -> Result<()> {
        let (mut conn, project) = setup();
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            Some("reused-topic"),
            "Old reused title",
            "oldreusedneedle content",
            "decision",
            None,
        )?;

        let result = MergeResult {
            topic_key: "reused-topic".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Merged reused title".to_owned(),
            content: "mergedreusedneedle content".to_owned(),
            superseded_ids: vec![old_id],
        };
        apply(&mut conn, &project, &result)?;

        assert_eq!(status_for_id(&conn, old_id), "active");
        assert_eq!(active_count(&conn, &project, "reused-topic"), 1);
        assert!(
            fts_indexed(&conn, old_id, "mergedreusedneedle"),
            "merged memory must remain searchable after topic_key reuse"
        );
        assert!(
            !fts_indexed(&conn, old_id, "oldreusedneedle"),
            "old content must not remain indexed after the upsert"
        );
        let operation: String = conn.query_row(
            "SELECT operation FROM memory_operation_log ORDER BY id DESC LIMIT 1",
            [],
            |row| row.get(0),
        )?;
        assert_eq!(operation, "update");
        Ok(())
    }

    #[test]
    fn test_apply_rejects_target_topic_collision_outside_superseded_neighborhood() -> Result<()> {
        let (mut conn, project) = setup();
        insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            Some("collision-topic"),
            "Unrelated title",
            "unrelated content",
            "decision",
            None,
        )?;
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            Some("old-topic"),
            "Old title",
            "old content",
            "decision",
            None,
        )?;

        let result = MergeResult {
            topic_key: "collision-topic".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Merged title".to_owned(),
            content: "merged content".to_owned(),
            superseded_ids: vec![old_id],
        };

        let error = apply(&mut conn, &project, &result).expect_err("collision should fail");
        assert!(
            error.to_string().contains("target topic_key collides"),
            "expected collision error, got: {error:?}"
        );
        assert_eq!(status_for_id(&conn, old_id), "active");
        let log_count: i64 =
            conn.query_row("SELECT COUNT(*) FROM memory_operation_log", [], |row| {
                row.get(0)
            })?;
        assert_eq!(log_count, 0);
        Ok(())
    }

    #[test]
    fn test_apply_marks_superseded_stale() {
        let (mut conn, project) = setup();
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            None,
            "old title",
            "old content",
            "decision",
            None,
        )
        .expect("insert");

        let result = MergeResult {
            topic_key: "new-merged".to_owned(),
            memory_type: "decision".to_owned(),
            title: "New title".to_owned(),
            content: "New content".to_owned(),
            superseded_ids: vec![old_id],
        };
        apply(&mut conn, &project, &result).expect("apply");

        assert_eq!(status_for_id(&conn, old_id), "stale");
    }

    #[test]
    fn test_apply_records_operation_log_for_superseded_ids() -> Result<()> {
        let (mut conn, project) = setup();
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            None,
            "old title",
            "old content",
            "decision",
            None,
        )?;

        let result = MergeResult {
            topic_key: "logged-merged".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Logged title".to_owned(),
            content: "Logged content".to_owned(),
            superseded_ids: vec![old_id],
        };
        apply(&mut conn, &project, &result)?;

        let (operation_id, operation, result_memory_id, superseded_ids): (
            i64,
            String,
            i64,
            String,
        ) = conn.query_row(
            "SELECT id, operation, result_memory_id, superseded_ids
             FROM memory_operation_log
             ORDER BY id DESC
             LIMIT 1",
            [],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
        )?;
        assert_eq!(operation, "update");
        assert_ne!(result_memory_id, old_id);
        assert_eq!(
            serde_json::from_str::<Vec<i64>>(&superseded_ids)?,
            vec![old_id]
        );
        let edge: (String, i64, i64, Option<i64>) = conn.query_row(
            "SELECT edge_type, from_memory_id, to_memory_id, source_operation_id
             FROM memory_edges
             WHERE from_memory_id = ?1 AND to_memory_id = ?2",
            params![old_id, result_memory_id],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
        )?;
        assert_eq!(
            edge,
            (
                "merged_into".to_string(),
                old_id,
                result_memory_id,
                Some(operation_id)
            )
        );
        Ok(())
    }

    #[test]
    fn test_apply_rolls_back_when_memory_edge_insert_fails() -> Result<()> {
        let (mut conn, project) = setup();
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            Some("old-topic"),
            "old title",
            "old content",
            "decision",
            None,
        )?;
        conn.execute_batch(
            "CREATE TRIGGER fail_memory_edge_insert
             BEFORE INSERT ON memory_edges
             BEGIN
                 SELECT RAISE(FAIL, 'forced memory edge failure');
             END;",
        )?;

        let result = MergeResult {
            topic_key: "merged-topic".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Merged title".to_owned(),
            content: "Merged content".to_owned(),
            superseded_ids: vec![old_id],
        };

        let error = apply(&mut conn, &project, &result).expect_err("apply should fail");
        let error_chain = format!("{error:?}");
        assert!(
            error_chain.contains("forced memory edge failure"),
            "expected memory edge trigger failure, got: {error_chain}"
        );

        let log_count: i64 =
            conn.query_row("SELECT COUNT(*) FROM memory_operation_log", [], |row| {
                row.get(0)
            })?;
        let edge_count: i64 =
            conn.query_row("SELECT COUNT(*) FROM memory_edges", [], |row| row.get(0))?;
        assert_eq!(active_count(&conn, &project, "merged-topic"), 0);
        assert_eq!(status_for_id(&conn, old_id), "active");
        assert_eq!(log_count, 0);
        assert_eq!(edge_count, 0);
        Ok(())
    }

    #[test]
    fn test_apply_rolls_back_when_stale_mark_update_fails() {
        let (mut conn, project) = setup();
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            Some("old-topic"),
            "old title",
            "old content",
            "decision",
            None,
        )
        .expect("insert old memory");
        conn.execute_batch(
            "CREATE TRIGGER fail_stale_update
             BEFORE UPDATE OF status ON memories
             WHEN NEW.status = 'stale'
             BEGIN
                 SELECT RAISE(FAIL, 'forced stale update failure');
             END;",
        )
        .expect("trigger should install");

        let result = MergeResult {
            topic_key: "merged-topic".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Merged title".to_owned(),
            content: "Merged content".to_owned(),
            superseded_ids: vec![old_id],
        };

        let error = apply(&mut conn, &project, &result).expect_err("apply should fail");
        assert!(
            error.to_string().contains("forced stale update failure"),
            "expected trigger failure, got: {error:?}"
        );

        assert_eq!(active_count(&conn, &project, "merged-topic"), 0);
        assert_eq!(status_for_id(&conn, old_id), "active");
    }

    #[test]
    fn test_apply_rolls_back_when_operation_log_insert_fails() -> Result<()> {
        let (mut conn, project) = setup();
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            Some("old-topic"),
            "old title",
            "old content",
            "decision",
            None,
        )?;
        conn.execute_batch(
            "CREATE TRIGGER fail_operation_log_insert
             BEFORE INSERT ON memory_operation_log
             BEGIN
                 SELECT RAISE(FAIL, 'forced operation log failure');
             END;",
        )?;

        let result = MergeResult {
            topic_key: "merged-topic".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Merged title".to_owned(),
            content: "Merged content".to_owned(),
            superseded_ids: vec![old_id],
        };

        let error = apply(&mut conn, &project, &result).expect_err("apply should fail");
        let error_chain = format!("{error:?}");
        assert!(
            error_chain.contains("forced operation log failure"),
            "expected operation log trigger failure, got: {error_chain}"
        );

        let log_count: i64 =
            conn.query_row("SELECT COUNT(*) FROM memory_operation_log", [], |row| {
                row.get(0)
            })?;
        assert_eq!(active_count(&conn, &project, "merged-topic"), 0);
        assert_eq!(status_for_id(&conn, old_id), "active");
        assert_eq!(log_count, 0);
        Ok(())
    }

    #[test]
    fn test_apply_evicts_superseded_rows_from_fts() {
        let (mut conn, project) = setup();
        let old_id = insert_memory(
            &conn,
            Some("sess-1"),
            &project,
            None,
            "old searchable title",
            "supersededneedle older content",
            "decision",
            None,
        )
        .expect("insert old memory");

        let pre_hits: Vec<i64> = conn
            .prepare("SELECT rowid FROM memories_fts WHERE memories_fts MATCH ?1")
            .unwrap()
            .query_map(params!["supersededneedle"], |r| r.get::<_, i64>(0))
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        assert_eq!(
            pre_hits,
            vec![old_id],
            "FTS index should locate the original row before apply"
        );

        let result = MergeResult {
            topic_key: "merged-topic".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Merged title".to_owned(),
            content: "Merged content".to_owned(),
            superseded_ids: vec![old_id],
        };
        apply(&mut conn, &project, &result).expect("apply");

        let post_hits: Vec<i64> = conn
            .prepare("SELECT rowid FROM memories_fts WHERE memories_fts MATCH ?1")
            .unwrap()
            .query_map(params!["supersededneedle"], |r| r.get::<_, i64>(0))
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        assert!(
            post_hits.is_empty(),
            "FTS MATCH must not return superseded rows after apply, got: {post_hits:?}"
        );

        // The merged memory should still be searchable.
        let merged_hits: Vec<i64> = conn
            .prepare("SELECT rowid FROM memories_fts WHERE memories_fts MATCH ?1")
            .unwrap()
            .query_map(params!["Merged"], |r| r.get::<_, i64>(0))
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        assert_eq!(
            merged_hits.len(),
            1,
            "merged memory should remain indexed in FTS"
        );
    }

    #[test]
    fn test_apply_is_atomic_on_invalid_superseded_id() {
        // ID 99999 does not exist — stale-mark must fail, and the upsert must be rolled back.
        let (mut conn, project) = setup();
        let result = MergeResult {
            topic_key: "atomic-merged".to_owned(),
            memory_type: "decision".to_owned(),
            title: "Atomic title".to_owned(),
            content: "Atomic content".to_owned(),
            superseded_ids: vec![99999],
        };
        assert!(
            apply(&mut conn, &project, &result).is_err(),
            "apply must fail when a superseded id does not exist"
        );

        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM memories WHERE project = ?1 AND topic_key = ?2",
                params![project, "atomic-merged"],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(count, 0, "upsert must be rolled back when stale-mark fails");
    }
}