remem-ai 0.6.93

Local-first coding agent memory for Claude Code and OpenAI Codex
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
use super::*;
use crate::memory;
use anyhow::Result;
use rusqlite::{params, Connection};
mod plan;
mod preference_rules;

const STASH: &str = "/Users/lifcc/Desktop/code/AI/tool/stash";
const NOW: i64 = 1_780_000_000;

fn setup_conn() -> Connection {
    let conn = Connection::open_in_memory().unwrap();
    crate::migrate::run_migrations(&conn).unwrap();
    conn
}

fn seed_stash_pollution(conn: &Connection) {
    let memory_rows = [
        (
            1001,
            "Stash DnD sensors",
            "Stash DnD uses pointer sensors for drag and drop.",
            "architecture",
            "stash-ui",
            0.95,
            None,
        ),
        (
            1002,
            "Stash dev server",
            "Stash dev server runs on Vite port 5173.",
            "discovery",
            "stash-dev",
            0.95,
            Some(NOW + 86_400),
        ),
        (
            1010,
            "Codex sandbox",
            "Codex CLI uses workspace-write sandbox approvals.",
            "discovery",
            "codex-sandbox",
            0.95,
            None,
        ),
        (
            1011,
            "Codex approval prompts",
            "Codex approval prompts require explicit confirm before destructive commands.",
            "procedure",
            "codex-sandbox",
            0.95,
            None,
        ),
        (
            1020,
            "Grok API payloads",
            "Grok API supports image reference payloads.",
            "discovery",
            "grok-api",
            0.95,
            None,
        ),
        (
            1021,
            "Warp macOS launch",
            "Warp terminal launch behavior depends on macOS app routing.",
            "discovery",
            "macos",
            0.95,
            None,
        ),
        (
            1030,
            "Preference: direct UI critique",
            "Prefer direct UI critique in Stash reviews.",
            "preference",
            "stash-ui",
            0.95,
            None,
        ),
        (
            1031,
            "Preference: Stash UI critique",
            "For Stash UI reviews, prefer direct critique and avoid decorative fluff.",
            "preference",
            "stash-ui",
            0.95,
            None,
        ),
        (
            1032,
            "Preference: concise critique",
            "Prefer concise UI critique when reviewing Stash.",
            "preference",
            "stash-ui",
            0.95,
            None,
        ),
        (
            1040,
            "Stash dev server health",
            "Stash dev server is currently healthy on localhost:5173.",
            "session_activity",
            "stash-dev",
            0.95,
            Some(NOW - 3600),
        ),
        (
            1050,
            "Ambiguous sidebar behavior",
            "The sidebar behavior may belong to Stash or a generic browser tool.",
            "discovery",
            "stash-ui",
            0.42,
            None,
        ),
        (
            1060,
            "Stash repo Codex approval UI",
            "Stash repo implements Codex approval UI copy for its own settings screen.",
            "discovery",
            "stash-ui",
            0.95,
            None,
        ),
    ];

    for (id, title, content, memory_type, topic_domain, confidence, expires_at_epoch) in memory_rows
    {
        conn.execute(
            "INSERT INTO memories
             (id, session_id, project, topic_key, title, content, memory_type,
              created_at_epoch, updated_at_epoch, status, scope, source_project,
              target_project, owner_scope, owner_key, topic_domain,
              routing_confidence, context_class, expires_at_epoch)
             VALUES
             (?1, 'stash-session', ?2, ?3, ?4, ?5, ?6,
              ?7, ?8, 'active', 'project', ?2, ?2, 'repo', ?2, ?9, ?10,
              'startup_core', ?11)",
            params![
                id,
                STASH,
                format!("topic-{id}"),
                title,
                content,
                memory_type,
                NOW - (2000 - id),
                NOW - (2000 - id),
                topic_domain,
                confidence,
                expires_at_epoch
            ],
        )
        .unwrap();
    }
    conn.execute(
        "UPDATE memories
         SET owner_scope = NULL, owner_key = NULL, routing_confidence = 0.42
         WHERE id = 1050",
        [],
    )
    .unwrap();
    conn.execute(
        "INSERT INTO memories
         (id, session_id, project, topic_key, title, content, memory_type,
          created_at_epoch, updated_at_epoch, status, scope, source_project,
          target_project, owner_scope, owner_key, topic_domain,
          routing_confidence, context_class)
         VALUES
         (1051, 'stash-session', ?1, 'topic-1051', 'Backfilled route',
          'A v019 backfilled route should still be reviewed when confidence is missing.',
          'discovery', ?2, ?2, 'active', 'project', ?1, ?1, 'repo', ?1,
          'stash-ui', NULL, 'startup_core')",
        params![STASH, NOW - 10],
    )
    .unwrap();
    conn.execute(
        "INSERT INTO memories
         (id, session_id, project, topic_key, title, content, memory_type,
          created_at_epoch, updated_at_epoch, status, scope, source_project,
          target_project, owner_scope, owner_key, topic_domain,
          routing_confidence, context_class)
         VALUES
         (1033, 'stash-session', ?1, 'topic-1033', 'Preference: global UI critique',
          'Prefer direct UI critique for all product reviews.',
          'preference', ?2, ?2, 'active', 'global', ?1, NULL, 'user',
          'user:default', 'user-preference', 0.95, 'startup_core')",
        params![STASH, NOW - 9],
    )
    .unwrap();

    let workstream_rows = [
        (2001, "Finish Stash drag-and-drop polish", "stash-ui", 0.95),
        (2010, "Build Grok image API wrapper", "grok-api", 0.95),
        (2011, "Fix Warp terminal startup routing", "macos", 0.95),
        (2012, "Investigate Hermes MCP transport", "hermes", 0.95),
        (2020, "Polish Stash sidebar interactions", "stash-ui", 0.95),
        (2021, "Stash sidebar polish follow-up", "stash-ui", 0.95),
    ];

    for (id, title, topic_domain, confidence) in workstream_rows {
        conn.execute(
            "INSERT INTO workstreams
             (id, project, title, status, progress, created_at_epoch, updated_at_epoch,
              source_project, target_project, owner_scope, owner_key, topic_domain,
              routing_confidence, context_class)
             VALUES (?1, ?2, ?3, 'active', 'in progress', ?4, ?5,
                     ?2, ?2, 'repo', ?2, ?6, ?7, 'startup_core')",
            params![
                id,
                STASH,
                title,
                NOW - (3000 - id),
                NOW - (3000 - id),
                topic_domain,
                confidence
            ],
        )
        .unwrap();
    }
}

fn refs(items: &[&str]) -> Vec<String> {
    items.iter().map(|value| value.to_string()).collect()
}

fn has_ref(items: &[AuditItem], object_ref: &str) -> bool {
    items.iter().any(|item| item.object_ref == object_ref)
}

#[test]
fn stash_pollution_audit_classifies_cleanup_buckets() -> Result<()> {
    let conn = setup_conn();
    seed_stash_pollution(&conn);

    let report = audit_scope(
        &conn,
        &ScopeAuditRequest {
            project: STASH,
            limit: 100,
            now_epoch: NOW,
        },
    )?;

    assert!(has_ref(&report.likely_correct_repo_memory, "memory:1001"));
    assert!(has_ref(&report.likely_correct_repo_memory, "memory:1002"));
    assert!(has_ref(
        &report.likely_correct_repo_memory,
        "workstream:2001"
    ));

    let pollution = &report.likely_cross_tool_domain_pollution;
    assert!(has_ref(pollution, "memory:1010"));
    assert!(has_ref(pollution, "memory:1011"));
    assert!(has_ref(pollution, "memory:1020"));
    assert!(has_ref(pollution, "memory:1021"));
    assert!(has_ref(pollution, "workstream:2010"));
    assert!(has_ref(pollution, "workstream:2011"));
    assert!(has_ref(pollution, "workstream:2012"));
    assert!(!has_ref(pollution, "memory:1060"));

    let codex = pollution
        .iter()
        .find(|item| item.object_ref == "memory:1010")
        .unwrap();
    assert_eq!(codex.suggested_owner_scope.as_deref(), Some("tool"));
    assert_eq!(codex.suggested_owner_key.as_deref(), Some("codex-cli"));
    assert_eq!(codex.suggested_target_project, None);

    assert!(report
        .duplicate_preferences
        .iter()
        .any(|cluster| cluster.cluster_key == "ui-critique"
            && cluster.canonical_ref == "memory:1032"
            && cluster.refs.contains(&"memory:1030".to_string())
            && cluster.refs.contains(&"memory:1032".to_string())
            && !cluster.refs.contains(&"memory:1033".to_string())));
    assert!(report
        .duplicate_workstreams
        .iter()
        .any(|cluster| cluster.cluster_key == "stash-sidebar-polish"
            && cluster.canonical_ref == "workstream:2020"
            && cluster.refs.contains(&"workstream:2020".to_string())
            && cluster.refs.contains(&"workstream:2021".to_string())));
    assert!(has_ref(&report.stale_temporal_facts, "memory:1040"));
    assert!(has_ref(&report.low_confidence_routing, "memory:1050"));
    assert!(has_ref(&report.low_confidence_routing, "memory:1051"));
    assert!(has_ref(&report.low_confidence_routing, "memory:1060"));
    Ok(())
}

#[test]
fn reroute_defaults_to_dry_run_and_confirm_preserves_provenance() -> Result<()> {
    let conn = setup_conn();
    seed_stash_pollution(&conn);
    let parsed_refs = parse_object_refs(&refs(&["memory:1010,memory:1011"]))?;

    let preview = reroute_objects(
        &conn,
        &RerouteRequest {
            refs: &parsed_refs,
            owner_scope: "tool",
            owner_key: "codex-cli",
            target_project: TargetProjectUpdate::Clear,
            topic_domain: Some("codex-sandbox"),
            context_class: Some("search_only"),
            routing_confidence: Some(1.0),
            reason: Some("Stash scope cleanup"),
            dry_run: false,
            confirm: false,
        },
    )?;

    assert!(preview.dry_run);
    assert_eq!(preview.affected.len(), 2);
    let unchanged: (String, String, Option<String>, String) = conn.query_row(
        "SELECT owner_scope, owner_key, target_project, status FROM memories WHERE id = 1010",
        [],
        |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
    )?;
    assert_eq!(
        unchanged,
        (
            "repo".to_string(),
            STASH.to_string(),
            Some(STASH.to_string()),
            "active".to_string()
        )
    );
    let event_count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM events WHERE event_type = 'scope_cleanup'",
        [],
        |row| row.get(0),
    )?;
    assert_eq!(event_count, 0);

    let applied = reroute_objects(
        &conn,
        &RerouteRequest {
            refs: &parsed_refs,
            owner_scope: "tool",
            owner_key: "codex-cli",
            target_project: TargetProjectUpdate::Clear,
            topic_domain: Some("codex-sandbox"),
            context_class: Some("search_only"),
            routing_confidence: Some(1.0),
            reason: Some("Stash scope cleanup"),
            dry_run: false,
            confirm: true,
        },
    )?;

    assert!(!applied.dry_run);
    let routed: (String, String, Option<String>, String, String) = conn.query_row(
        "SELECT owner_scope, owner_key, target_project, source_project, status
         FROM memories WHERE id = 1010",
        [],
        |row| {
            Ok((
                row.get(0)?,
                row.get(1)?,
                row.get(2)?,
                row.get(3)?,
                row.get(4)?,
            ))
        },
    )?;
    assert_eq!(
        routed,
        (
            "tool".to_string(),
            "codex-cli".to_string(),
            None,
            STASH.to_string(),
            "active".to_string()
        )
    );
    let event_count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM events WHERE event_type = 'scope_cleanup'",
        [],
        |row| row.get(0),
    )?;
    assert_eq!(event_count, 2);
    Ok(())
}

#[test]
fn audit_limit_is_applied_per_bucket_after_classification() -> Result<()> {
    let conn = setup_conn();
    let now = NOW;
    for id in 1..=8 {
        conn.execute(
            "INSERT INTO memories
             (id, session_id, project, topic_key, title, content, memory_type,
              created_at_epoch, updated_at_epoch, status, scope, source_project,
              target_project, owner_scope, owner_key, topic_domain,
              routing_confidence, context_class)
             VALUES
             (?1, 'limit-session', ?2, ?3, ?4, 'Stash repo UI memory.',
              'discovery', ?5, ?5, 'active', 'project', ?2, ?2, 'repo',
              ?2, 'stash-ui', 0.95, 'startup_core')",
            params![
                id,
                STASH,
                format!("topic-limit-{id}"),
                format!("Correct repo memory {id}"),
                now + id
            ],
        )?;
    }
    conn.execute(
        "INSERT INTO memories
         (id, session_id, project, topic_key, title, content, memory_type,
          created_at_epoch, updated_at_epoch, status, scope, source_project,
          target_project, owner_scope, owner_key, topic_domain,
          routing_confidence, context_class)
         VALUES
         (99, 'limit-session', ?1, 'topic-old-codex', 'Codex sandbox',
          'Codex CLI uses workspace-write sandbox approvals.', 'discovery',
          ?2, ?2, 'active', 'project', ?1, ?1, 'repo', ?1, 'codex-sandbox',
          0.95, 'startup_core')",
        params![STASH, now - 10_000],
    )?;

    let report = audit_scope(
        &conn,
        &ScopeAuditRequest {
            project: STASH,
            limit: 1,
            now_epoch: now,
        },
    )?;

    assert_eq!(report.likely_correct_repo_memory.len(), 1);
    assert_eq!(report.likely_cross_tool_domain_pollution.len(), 1);
    assert_eq!(
        report.likely_cross_tool_domain_pollution[0].object_ref,
        "memory:99"
    );
    Ok(())
}

#[test]
fn reroute_trims_owner_scope_and_key_before_persisting() -> Result<()> {
    let conn = setup_conn();
    seed_stash_pollution(&conn);
    let parsed_refs = parse_object_refs(&refs(&["memory:1010"]))?;

    reroute_objects(
        &conn,
        &RerouteRequest {
            refs: &parsed_refs,
            owner_scope: " tool ",
            owner_key: " codex-cli ",
            target_project: TargetProjectUpdate::Clear,
            topic_domain: Some("codex-sandbox"),
            context_class: None,
            routing_confidence: Some(1.0),
            reason: Some("trim owner fields"),
            dry_run: false,
            confirm: true,
        },
    )?;

    let routed: (String, String, Option<String>, String) = conn.query_row(
        "SELECT owner_scope, owner_key, target_project, context_class
         FROM memories WHERE id = 1010",
        [],
        |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
    )?;
    assert_eq!(
        routed,
        (
            "tool".to_string(),
            "codex-cli".to_string(),
            None,
            "search_only".to_string()
        )
    );
    Ok(())
}

#[test]
fn archive_mixed_refs_does_not_hard_delete_and_rolls_back_on_invalid_ref() -> Result<()> {
    let conn = setup_conn();
    seed_stash_pollution(&conn);
    let parsed_refs = parse_object_refs(&refs(&["memory:1040", "workstream:2010"]))?;

    let preview = archive_objects(
        &conn,
        &ArchiveRequest {
            refs: &parsed_refs,
            reason: Some("not startup context"),
            dry_run: false,
            confirm: false,
        },
    )?;
    assert!(preview.dry_run);
    assert_eq!(
        conn.query_row("SELECT status FROM memories WHERE id = 1040", [], |row| {
            row.get::<_, String>(0)
        })?,
        "active"
    );

    let applied = archive_objects(
        &conn,
        &ArchiveRequest {
            refs: &parsed_refs,
            reason: Some("not startup context"),
            dry_run: false,
            confirm: true,
        },
    )?;
    assert!(!applied.dry_run);
    assert_eq!(
        conn.query_row("SELECT status FROM memories WHERE id = 1040", [], |row| {
            row.get::<_, String>(0)
        })?,
        "archived"
    );
    assert_eq!(
        conn.query_row(
            "SELECT status FROM workstreams WHERE id = 2010",
            [],
            |row| { row.get::<_, String>(0) }
        )?,
        "paused"
    );
    let remaining: i64 =
        conn.query_row("SELECT COUNT(*) FROM memories WHERE id = 1040", [], |row| {
            row.get(0)
        })?;
    assert_eq!(remaining, 1);

    let conn = setup_conn();
    seed_stash_pollution(&conn);
    let bad_refs = parse_object_refs(&refs(&["memory:1040", "workstream:999"]))?;
    let err = archive_objects(
        &conn,
        &ArchiveRequest {
            refs: &bad_refs,
            reason: Some("rollback test"),
            dry_run: false,
            confirm: true,
        },
    )
    .expect_err("invalid mixed refs should fail");
    assert!(err.to_string().contains("workstream:999 not found"));
    assert_eq!(
        conn.query_row("SELECT status FROM memories WHERE id = 1040", [], |row| {
            row.get::<_, String>(0)
        })?,
        "active"
    );
    Ok(())
}

#[test]
fn merge_preferences_keeps_one_active_preference_with_merged_content() -> Result<()> {
    let conn = setup_conn();
    seed_stash_pollution(&conn);

    let preview = merge_preferences(
        &conn,
        &MergePreferencesRequest {
            project: STASH,
            dry_run: false,
            confirm: false,
        },
    )?;
    assert!(preview.dry_run);
    assert_eq!(preview.clusters.len(), 1);
    assert_eq!(preview.clusters[0].canonical_ref, "memory:1032");
    let merged = preview.clusters[0].merged_content.as_deref().unwrap();
    assert!(merged.contains("direct UI critique"));
    assert!(merged.contains("avoid decorative fluff"));
    assert!(merged.contains("concise UI critique"));
    assert_eq!(
        conn.query_row("SELECT status FROM memories WHERE id = 1030", [], |row| {
            row.get::<_, String>(0)
        })?,
        "active"
    );

    let applied = merge_preferences(
        &conn,
        &MergePreferencesRequest {
            project: STASH,
            dry_run: false,
            confirm: true,
        },
    )?;
    assert!(!applied.dry_run);
    assert_eq!(applied.affected.len(), 3);
    let canonical_mutation = applied
        .affected
        .iter()
        .find(|mutation| mutation.object_ref == "memory:1032")
        .expect("canonical mutation should be reported");
    assert_eq!(
        canonical_mutation.new_owner.owner_scope.as_deref(),
        Some("repo")
    );
    let canonical: (String, String, String, String, String) = conn.query_row(
        "SELECT status, content, owner_scope, owner_key, target_project
         FROM memories WHERE id = 1032",
        [],
        |row| {
            Ok((
                row.get(0)?,
                row.get(1)?,
                row.get(2)?,
                row.get(3)?,
                row.get(4)?,
            ))
        },
    )?;
    assert_eq!(canonical.0, "active");
    assert!(canonical.1.contains("direct UI critique"));
    assert!(canonical.1.contains("avoid decorative fluff"));
    assert!(canonical.1.contains("concise UI critique"));
    assert_eq!(canonical.2, "repo");
    assert_eq!(canonical.3, STASH);
    assert_eq!(canonical.4, STASH);
    for id in [1030, 1031] {
        assert_eq!(
            conn.query_row(
                "SELECT status, source_project FROM memories WHERE id = ?1",
                params![id],
                |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
            )?,
            ("stale".to_string(), STASH.to_string())
        );
    }
    let global_pref: (String, String, Option<String>) = conn.query_row(
        "SELECT status, owner_scope, target_project FROM memories WHERE id = 1033",
        [],
        |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
    )?;
    assert_eq!(
        global_pref,
        ("active".to_string(), "user".to_string(), None)
    );
    let prefs = memory::preference::query_project_preferences(&conn, STASH, 10)?;
    let ui_prefs = prefs
        .iter()
        .filter(|pref| pref.text.contains("UI critique"))
        .count();
    assert_eq!(ui_prefs, 1);
    let event_count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM events WHERE event_type = 'scope_cleanup'",
        [],
        |row| row.get(0),
    )?;
    assert_eq!(event_count, 3);
    let duplicate_edges = conn
        .prepare(
            "SELECT from_memory_id, to_memory_id, edge_type
             FROM memory_edges
             WHERE edge_type = 'duplicates'
             ORDER BY from_memory_id ASC",
        )?
        .query_map([], |row| {
            Ok((
                row.get::<_, i64>(0)?,
                row.get::<_, i64>(1)?,
                row.get::<_, String>(2)?,
            ))
        })?
        .collect::<std::result::Result<Vec<_>, _>>()?;
    assert_eq!(
        duplicate_edges,
        vec![
            (1030, 1032, "duplicates".to_string()),
            (1031, 1032, "duplicates".to_string())
        ]
    );
    Ok(())
}

#[test]
fn cleanup_plan_normalizes_legacy_repo_target_in_activation_receipt() -> Result<()> {
    let conn = setup_conn();
    seed_stash_pollution(&conn);
    conn.execute(
        "UPDATE memories SET target_project = NULL WHERE id IN (1030, 1031, 1032)",
        [],
    )?;

    let plan = build_preference_cleanup_plan(&conn, STASH)?;
    assert_eq!(plan.groups.len(), 1);
    let current_id = plan.groups[0].current_id;
    let applied = apply_memory_cleanup_plan(&conn, &plan)?;
    assert_eq!(applied.groups_applied, 1);
    assert_eq!(applied.current_ids, vec![current_id]);
    assert_eq!(
        conn.query_row(
            "SELECT target_project FROM memory_activation_requests
             WHERE result_memory_id = ?1 AND route_kind = 'scope_cleanup'",
            [current_id],
            |row| row.get::<_, String>(0),
        )?,
        STASH
    );
    assert_eq!(
        conn.query_row(
            "SELECT target_project FROM memories WHERE id = ?1",
            [current_id],
            |row| row.get::<_, Option<String>>(0),
        )?,
        None
    );
    Ok(())
}

#[test]
fn object_ref_parser_requires_explicit_kind_and_dedupes() -> Result<()> {
    let parsed = parse_object_refs(&refs(&["memory:1, workstream:2", "memory:1"]))?;
    assert_eq!(
        parsed,
        vec![
            ObjectRef::memory(1),
            ObjectRef {
                kind: ScopeObjectKind::Workstream,
                id: 2
            }
        ]
    );
    let err = parse_object_refs(&refs(&["1"])).expect_err("bare ids should fail");
    assert!(err.to_string().contains("kind prefix"));
    assert_eq!(
        memory_refs_from_ids(&[3, 3, 4])?,
        vec![ObjectRef::memory(3), ObjectRef::memory(4)]
    );
    Ok(())
}