remem-ai 0.6.42

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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
use std::collections::HashSet;

use anyhow::{anyhow, bail, Context, Result};
use rusqlite::{params, params_from_iter, Connection, OptionalExtension};
use serde::Serialize;

const ACTIVE_STATUS: &str = "active";
const DEFAULT_ACTOR: &str = "cli";
const DEFAULT_REASON: &str = "manual suppression";

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SuppressionTarget {
    pub kind: String,
    pub id: Option<i64>,
    pub value: Option<String>,
}

impl SuppressionTarget {
    pub fn label(&self) -> String {
        match (self.id, self.value.as_deref()) {
            (Some(id), _) => format!("{}:{id}", self.kind),
            (None, Some(value)) => format!("{}:{value}", self.kind),
            (None, None) => self.kind.clone(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct SuppressionRecord {
    pub id: i64,
    pub owner_scope: Option<String>,
    pub owner_key: Option<String>,
    pub target_kind: String,
    pub target_id: Option<i64>,
    pub target_value: Option<String>,
    pub reason: String,
    pub actor: String,
    pub status: String,
    pub created_at_epoch: i64,
    pub updated_at_epoch: i64,
}

#[derive(Debug, Clone, Serialize)]
pub struct FeedbackRecord {
    pub id: i64,
    pub target_kind: String,
    pub target_id: Option<i64>,
    pub target_value: Option<String>,
    pub feedback: String,
    pub source: String,
    pub context_injection_item_id: Option<i64>,
    pub session_id: Option<String>,
    pub project: Option<String>,
    pub reason: Option<String>,
    pub created_at_epoch: i64,
}

#[derive(Debug, Clone)]
pub struct SuppressRequest<'a> {
    pub target: SuppressionTarget,
    pub reason: Option<&'a str>,
    pub actor: Option<&'a str>,
}

#[derive(Debug, Clone)]
pub struct FeedbackRequest<'a> {
    pub target: SuppressionTarget,
    pub feedback: &'a str,
    pub source: Option<&'a str>,
    pub context_injection_item_id: Option<i64>,
    pub session_id: Option<&'a str>,
    pub project: Option<&'a str>,
    pub reason: Option<&'a str>,
}

pub fn parse_target(raw: &str) -> Result<SuppressionTarget> {
    let input = raw.trim();
    if input.is_empty() {
        bail!("suppression target cannot be empty");
    }
    if let Ok(id) = input.parse::<i64>() {
        if id <= 0 {
            bail!("memory target id must be positive");
        }
        return Ok(SuppressionTarget {
            kind: "memory".to_string(),
            id: Some(id),
            value: None,
        });
    }

    let Some((kind_raw, value_raw)) = input.split_once(':') else {
        return Ok(SuppressionTarget {
            kind: "topic_key".to_string(),
            id: None,
            value: Some(input.to_string()),
        });
    };
    let kind = normalize_kind(kind_raw)?;
    let value = value_raw.trim();
    if value.is_empty() {
        bail!("suppression target value cannot be empty");
    }

    if id_target_kind(&kind) {
        let id = value
            .parse::<i64>()
            .with_context(|| format!("{kind} target requires an integer id"))?;
        if id <= 0 {
            bail!("{kind} target id must be positive");
        }
        return Ok(SuppressionTarget {
            kind,
            id: Some(id),
            value: None,
        });
    }

    Ok(SuppressionTarget {
        kind,
        id: None,
        value: Some(value.to_string()),
    })
}

pub fn memory_policy_filter_sql(alias: &str) -> String {
    format!(
        "NOT EXISTS (
             SELECT 1
             FROM memory_suppressions ms
             WHERE ms.status = 'active'
               AND (
                    (ms.target_kind = 'memory' AND ms.target_id = {alias}.id)
                 OR (ms.target_kind = 'topic_key'
                     AND ms.target_value IS NOT NULL
                     AND {alias}.topic_key = ms.target_value)
                 OR (ms.target_kind = 'entity'
                     AND ms.target_value IS NOT NULL
                     AND EXISTS (
                         SELECT 1
                         FROM memory_entities ms_me
                         JOIN entities ms_e ON ms_e.id = ms_me.entity_id
                         WHERE ms_me.memory_id = {alias}.id
                           AND lower(ms_e.canonical_name) = lower(ms.target_value)
                     ))
                 OR (ms.target_kind = 'pattern'
                     AND ms.target_value IS NOT NULL
                     AND (
                         instr(lower({alias}.title), lower(ms.target_value)) > 0
                      OR instr(lower({alias}.content), lower(ms.target_value)) > 0
                     ))
               )
         )"
    )
}

pub fn user_claim_policy_filter_sql(alias: &str) -> String {
    format!(
        "NOT EXISTS (
             SELECT 1
             FROM memory_suppressions ms
             WHERE ms.status = 'active'
               AND (
                    (ms.target_kind = 'user_claim' AND ms.target_id = {alias}.id)
                 OR (ms.target_kind = 'pattern'
                     AND ms.target_value IS NOT NULL
                     AND (
                         instr(lower({alias}.claim_text), lower(ms.target_value)) > 0
                      OR instr(lower({alias}.claim_key), lower(ms.target_value)) > 0
                     ))
               )
         )"
    )
}

pub fn user_claim_is_policy_suppressed(conn: &Connection, claim_id: i64) -> Result<bool> {
    let sql = format!(
        "SELECT NOT ({}) FROM user_context_claims WHERE id = ?1",
        user_claim_policy_filter_sql("user_context_claims")
    );
    conn.query_row(&sql, [claim_id], |row| row.get::<_, bool>(0))
        .optional()?
        .context("user-context claim disappeared during suppression check")
}

pub fn active_suppressed_memory_ids(conn: &Connection, ids: &[i64]) -> Result<HashSet<i64>> {
    if ids.is_empty() {
        return Ok(HashSet::new());
    }
    let placeholders = (1..=ids.len())
        .map(|idx| format!("?{idx}"))
        .collect::<Vec<_>>()
        .join(", ");
    let sql = format!(
        "SELECT m.id
         FROM memories m
         WHERE m.id IN ({placeholders})
           AND NOT ({})",
        memory_policy_filter_sql("m")
    );
    let mut stmt = conn.prepare(&sql)?;
    let rows = stmt.query_map(params_from_iter(ids.iter()), |row| row.get::<_, i64>(0))?;
    let suppressed = crate::db::query::collect_rows(rows)?;
    Ok(suppressed.into_iter().collect())
}

pub fn has_active_suppressions(conn: &Connection) -> Result<bool> {
    let count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM memory_suppressions WHERE status = 'active'",
        [],
        |row| row.get(0),
    )?;
    Ok(count > 0)
}

pub fn create_suppression(
    conn: &Connection,
    req: &SuppressRequest<'_>,
) -> Result<SuppressionRecord> {
    validate_target(&req.target)?;
    let reason = normalize_text(req.reason, DEFAULT_REASON)?;
    let actor = normalize_text(req.actor, DEFAULT_ACTOR)?;
    if let Some(existing) = load_active_suppression_for_target(conn, &req.target)? {
        return Ok(existing);
    }
    let now = chrono::Utc::now().timestamp();
    let tx = conn.unchecked_transaction()?;
    tx.execute(
        "INSERT INTO memory_suppressions
         (owner_scope, owner_key, target_kind, target_id, target_value, reason, actor,
          status, created_at_epoch, updated_at_epoch)
         VALUES (NULL, NULL, ?1, ?2, ?3, ?4, ?5, 'active', ?6, ?6)",
        params![
            req.target.kind,
            req.target.id,
            req.target.value,
            reason,
            actor,
            now
        ],
    )
    .context("insert memory suppression")?;
    crate::memory::preference::compilation::enqueue_for_suppression_targets(
        &tx,
        std::slice::from_ref(&req.target),
    )?;
    let record = load_suppression(&tx, tx.last_insert_rowid())?;
    tx.commit()?;
    Ok(record)
}

pub fn revoke_suppression_arg(
    conn: &Connection,
    arg: &str,
    reason: Option<&str>,
    actor: Option<&str>,
) -> Result<Vec<SuppressionRecord>> {
    let actor = normalize_text(actor, DEFAULT_ACTOR)?;
    let reason = normalize_text(reason, "manual unsuppression")?;
    if let Ok(id) = arg.trim().parse::<i64>() {
        if let Some(record) = load_suppression_optional(conn, id)? {
            if record.status != ACTIVE_STATUS {
                bail!("suppression {id} is already {}", record.status);
            }
            return revoke_suppression_ids(conn, &[id], &reason, &actor);
        }
    }
    let target = parse_target(arg)?;
    let active = active_suppressions_for_target(conn, &target)?;
    if active.is_empty() {
        bail!("no active suppression found for {}", target.label());
    }
    let ids = active.iter().map(|record| record.id).collect::<Vec<_>>();
    revoke_suppression_ids(conn, &ids, &reason, &actor)
}

pub fn record_feedback(conn: &Connection, req: &FeedbackRequest<'_>) -> Result<FeedbackRecord> {
    validate_target(&req.target)?;
    let feedback = normalize_feedback(req.feedback)?;
    let source = normalize_text(req.source, DEFAULT_ACTOR)?;
    let reason = optional_trimmed(req.reason);
    let session_id = optional_trimmed(req.session_id);
    let project = optional_trimmed(req.project);
    let now = chrono::Utc::now().timestamp();
    conn.execute(
        "INSERT INTO memory_feedback
         (target_kind, target_id, target_value, feedback, source,
          context_injection_item_id, session_id, project, reason, created_at_epoch)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
        params![
            req.target.kind,
            req.target.id,
            req.target.value,
            feedback,
            source,
            req.context_injection_item_id,
            session_id,
            project,
            reason,
            now,
        ],
    )
    .context("insert memory feedback")?;
    load_feedback(conn, conn.last_insert_rowid())
}

pub fn list_suppressions(
    conn: &Connection,
    include_inactive: bool,
) -> Result<Vec<SuppressionRecord>> {
    let sql = if include_inactive {
        "SELECT id, owner_scope, owner_key, target_kind, target_id, target_value,
                reason, actor, status, created_at_epoch, updated_at_epoch
         FROM memory_suppressions
         ORDER BY updated_at_epoch DESC, id DESC"
    } else {
        "SELECT id, owner_scope, owner_key, target_kind, target_id, target_value,
                reason, actor, status, created_at_epoch, updated_at_epoch
         FROM memory_suppressions
         WHERE status = 'active'
         ORDER BY updated_at_epoch DESC, id DESC"
    };
    let mut stmt = conn.prepare(sql)?;
    let rows = stmt.query_map([], suppression_from_row)?;
    crate::db::query::collect_rows(rows)
}

pub fn active_suppressions_for_memory(
    conn: &Connection,
    memory_id: i64,
) -> Result<Vec<SuppressionRecord>> {
    let mut stmt = conn.prepare(
        "SELECT ms.id, ms.owner_scope, ms.owner_key, ms.target_kind, ms.target_id,
                ms.target_value, ms.reason, ms.actor, ms.status,
                ms.created_at_epoch, ms.updated_at_epoch
         FROM memory_suppressions ms
         JOIN memories m ON m.id = ?1
         WHERE ms.status = 'active'
           AND (
                (ms.target_kind = 'memory' AND ms.target_id = m.id)
             OR (ms.target_kind = 'topic_key'
                 AND ms.target_value IS NOT NULL
                 AND m.topic_key = ms.target_value)
             OR (ms.target_kind = 'entity'
                 AND ms.target_value IS NOT NULL
                 AND EXISTS (
                     SELECT 1
                     FROM memory_entities ms_me
                     JOIN entities ms_e ON ms_e.id = ms_me.entity_id
                     WHERE ms_me.memory_id = m.id
                       AND lower(ms_e.canonical_name) = lower(ms.target_value)
                 ))
             OR (ms.target_kind = 'pattern'
                 AND ms.target_value IS NOT NULL
                 AND (
                     instr(lower(m.title), lower(ms.target_value)) > 0
                  OR instr(lower(m.content), lower(ms.target_value)) > 0
                 ))
           )
         ORDER BY ms.updated_at_epoch DESC, ms.id DESC",
    )?;
    let rows = stmt.query_map([memory_id], suppression_from_row)?;
    crate::db::query::collect_rows(rows)
}

fn revoke_suppression_ids(
    conn: &Connection,
    ids: &[i64],
    reason: &str,
    actor: &str,
) -> Result<Vec<SuppressionRecord>> {
    let now = chrono::Utc::now().timestamp();
    let tx = conn.unchecked_transaction()?;
    let active = ids
        .iter()
        .map(|id| load_suppression(&tx, *id))
        .collect::<Result<Vec<_>>>()?;
    for id in ids {
        let updated = tx.execute(
            "UPDATE memory_suppressions
             SET status = 'revoked',
                 reason = ?1,
                 actor = ?2,
                 updated_at_epoch = ?3
             WHERE id = ?4 AND status = 'active'",
            params![reason, actor, now, id],
        )?;
        if updated != 1 {
            bail!("suppression {id} was not active during revocation");
        }
    }
    let targets = active
        .into_iter()
        .map(|record| SuppressionTarget {
            kind: record.target_kind,
            id: record.target_id,
            value: record.target_value,
        })
        .collect::<Vec<_>>();
    crate::memory::preference::compilation::enqueue_for_suppression_targets(&tx, &targets)?;
    let mut revoked = Vec::new();
    for id in ids {
        revoked.push(load_suppression(&tx, *id)?);
    }
    tx.commit()?;
    Ok(revoked)
}

fn load_active_suppression_for_target(
    conn: &Connection,
    target: &SuppressionTarget,
) -> Result<Option<SuppressionRecord>> {
    let mut active = active_suppressions_for_target(conn, target)?;
    Ok(active.pop())
}

fn active_suppressions_for_target(
    conn: &Connection,
    target: &SuppressionTarget,
) -> Result<Vec<SuppressionRecord>> {
    let mut stmt = conn.prepare(
        "SELECT id, owner_scope, owner_key, target_kind, target_id, target_value,
                reason, actor, status, created_at_epoch, updated_at_epoch
         FROM memory_suppressions
         WHERE status = 'active'
           AND target_kind = ?1
           AND (
                (target_id IS NOT NULL AND target_id = ?2)
             OR (target_value IS NOT NULL AND target_value = ?3)
           )
         ORDER BY updated_at_epoch DESC, id DESC",
    )?;
    let rows = stmt.query_map(
        params![target.kind, target.id, target.value],
        suppression_from_row,
    )?;
    crate::db::query::collect_rows(rows)
}

fn load_suppression(conn: &Connection, id: i64) -> Result<SuppressionRecord> {
    load_suppression_optional(conn, id)?.ok_or_else(|| anyhow!("suppression {id} not found"))
}

fn load_suppression_optional(conn: &Connection, id: i64) -> Result<Option<SuppressionRecord>> {
    conn.query_row(
        "SELECT id, owner_scope, owner_key, target_kind, target_id, target_value,
                reason, actor, status, created_at_epoch, updated_at_epoch
         FROM memory_suppressions
         WHERE id = ?1",
        [id],
        suppression_from_row,
    )
    .optional()
    .map_err(Into::into)
}

fn load_feedback(conn: &Connection, id: i64) -> Result<FeedbackRecord> {
    conn.query_row(
        "SELECT id, target_kind, target_id, target_value, feedback, source,
                context_injection_item_id, session_id, project, reason, created_at_epoch
         FROM memory_feedback
         WHERE id = ?1",
        [id],
        feedback_from_row,
    )
    .optional()?
    .ok_or_else(|| anyhow!("feedback {id} not found"))
}

fn suppression_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<SuppressionRecord> {
    Ok(SuppressionRecord {
        id: row.get(0)?,
        owner_scope: row.get(1)?,
        owner_key: row.get(2)?,
        target_kind: row.get(3)?,
        target_id: row.get(4)?,
        target_value: row.get(5)?,
        reason: row.get(6)?,
        actor: row.get(7)?,
        status: row.get(8)?,
        created_at_epoch: row.get(9)?,
        updated_at_epoch: row.get(10)?,
    })
}

fn feedback_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<FeedbackRecord> {
    Ok(FeedbackRecord {
        id: row.get(0)?,
        target_kind: row.get(1)?,
        target_id: row.get(2)?,
        target_value: row.get(3)?,
        feedback: row.get(4)?,
        source: row.get(5)?,
        context_injection_item_id: row.get(6)?,
        session_id: row.get(7)?,
        project: row.get(8)?,
        reason: row.get(9)?,
        created_at_epoch: row.get(10)?,
    })
}

fn validate_target(target: &SuppressionTarget) -> Result<()> {
    normalize_kind(&target.kind)?;
    match target.kind.as_str() {
        "memory" | "user_claim" | "user_candidate" => {
            if target.id.is_none() {
                bail!("{} suppression target requires an id", target.kind);
            }
        }
        "topic_key" | "entity" | "pattern" => {
            if target
                .value
                .as_deref()
                .is_none_or(|value| value.trim().is_empty())
            {
                bail!("{} suppression target requires a value", target.kind);
            }
        }
        "summary" => {
            if target.id.is_none() && target.value.as_deref().is_none_or(str::is_empty) {
                bail!("summary suppression target requires an id or value");
            }
        }
        _ => unreachable!("normalize_kind accepted an unknown target kind"),
    }
    Ok(())
}

fn normalize_kind(raw: &str) -> Result<String> {
    let normalized = raw.trim().replace('-', "_");
    let kind = match normalized.as_str() {
        "memory" | "mem" => "memory",
        "claim" | "user_claim" | "user_context_claim" => "user_claim",
        "candidate" | "user_candidate" => "user_candidate",
        "topic" | "topic_key" => "topic_key",
        "entity" => "entity",
        "pattern" => "pattern",
        "summary" | "summary_line" => "summary",
        _ => bail!("unsupported suppression target kind: {raw}"),
    };
    Ok(kind.to_string())
}

fn id_target_kind(kind: &str) -> bool {
    matches!(kind, "memory" | "user_claim" | "user_candidate")
}

fn normalize_feedback(raw: &str) -> Result<&'static str> {
    match raw.trim().replace('-', "_").as_str() {
        "relevant" => Ok("relevant"),
        "not_relevant" => Ok("not_relevant"),
        "harmful" => Ok("harmful"),
        "stale" => Ok("stale"),
        "too_noisy" => Ok("too_noisy"),
        _ => bail!("unsupported feedback value: {raw}"),
    }
}

fn normalize_text<'a>(value: Option<&'a str>, default: &'a str) -> Result<String> {
    let normalized = value.unwrap_or(default).trim();
    if normalized.is_empty() {
        bail!("value cannot be empty");
    }
    Ok(normalized.to_string())
}

fn optional_trimmed(value: Option<&str>) -> Option<String> {
    value
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
}

#[cfg(test)]
mod tests {
    use anyhow::Result;
    use rusqlite::{params, Connection};

    use super::*;
    use crate::db::test_support::ScopedTestDataDir;

    #[test]
    fn parse_target_accepts_memory_claim_and_text_keys() -> Result<()> {
        assert_eq!(
            parse_target("42")?,
            SuppressionTarget {
                kind: "memory".to_string(),
                id: Some(42),
                value: None,
            }
        );
        assert_eq!(
            parse_target("claim:7")?,
            SuppressionTarget {
                kind: "user_claim".to_string(),
                id: Some(7),
                value: None,
            }
        );
        assert_eq!(
            parse_target("topic:rust")?,
            SuppressionTarget {
                kind: "topic_key".to_string(),
                id: None,
                value: Some("rust".to_string()),
            }
        );
        assert_eq!(
            parse_target("rust")?,
            SuppressionTarget {
                kind: "topic_key".to_string(),
                id: None,
                value: Some("rust".to_string()),
            }
        );
        Ok(())
    }

    #[test]
    fn suppression_records_and_revokes_policy_without_deleting_memory() -> Result<()> {
        let conn = Connection::open_in_memory()?;
        crate::migrate::run_migrations(&conn)?;
        conn.execute(
            "INSERT INTO memories
             (id, project, topic_key, title, content, memory_type, created_at_epoch, updated_at_epoch, status)
             VALUES (1, '/repo', 'topic-a', 'Suppressed', 'body', 'decision', 10, 10, 'active')",
            [],
        )?;
        let target = parse_target("memory:1")?;
        let record = create_suppression(
            &conn,
            &SuppressRequest {
                target: target.clone(),
                reason: Some("stale"),
                actor: Some("test"),
            },
        )?;
        assert_eq!(record.status, "active");
        assert_eq!(active_suppressed_memory_ids(&conn, &[1])?.len(), 1);
        let still_exists: i64 =
            conn.query_row("SELECT COUNT(*) FROM memories WHERE id = 1", [], |row| {
                row.get(0)
            })?;
        assert_eq!(still_exists, 1);

        let revoked = revoke_suppression_arg(&conn, &record.id.to_string(), None, None)?;
        assert_eq!(revoked[0].status, "revoked");
        assert!(active_suppressed_memory_ids(&conn, &[1])?.is_empty());
        Ok(())
    }

    #[test]
    fn preference_suppression_and_revocation_enqueue_fresh_compiles() -> Result<()> {
        let _dir = ScopedTestDataDir::new("preference-suppression-compile");
        crate::runtime_config::init_config()?;
        crate::runtime_config::set_config_value("rule_compilation.enabled", "true")?;
        let conn = crate::db::open_db()?;
        conn.execute(
            "INSERT INTO memories
             (id, project, topic_key, title, content, memory_type, created_at_epoch,
              updated_at_epoch, status, scope)
             VALUES (1, '/repo', 'package-manager', 'Preference', 'Use bun, not npm',
                     'preference', 10, 10, 'active', 'project')",
            [],
        )?;
        conn.execute(
            "INSERT INTO memory_preference_reinforcements
             (memory_id, reinforcement_count, last_reinforced_at_epoch,
              created_at_epoch, updated_at_epoch, machine_checkable)
             VALUES (1, 3, 10, 10, 10, 1)",
            [],
        )?;

        let record = create_suppression(
            &conn,
            &SuppressRequest {
                target: parse_target("memory:1")?,
                reason: Some("test suppression"),
                actor: Some("test"),
            },
        )?;
        let first_job: i64 = conn.query_row(
            "SELECT id FROM jobs
             WHERE job_type = 'compile_rules' AND project = '/repo' AND state = 'pending'",
            [],
            |row| row.get(0),
        )?;
        conn.execute(
            "UPDATE jobs SET state = 'processing' WHERE id = ?1",
            params![first_job],
        )?;

        revoke_suppression_arg(&conn, &record.id.to_string(), None, None)?;

        let states: (i64, i64) = conn.query_row(
            "SELECT SUM(state = 'processing'), SUM(state = 'pending')
             FROM jobs WHERE job_type = 'compile_rules' AND project = '/repo'",
            [],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )?;
        assert_eq!(states, (1, 1));
        Ok(())
    }

    #[test]
    fn entity_and_pattern_suppressions_match_memory_policy_filter() -> Result<()> {
        let conn = Connection::open_in_memory()?;
        crate::migrate::run_migrations(&conn)?;
        conn.execute(
            "INSERT INTO memories
             (id, project, title, content, memory_type, created_at_epoch, updated_at_epoch, status)
             VALUES (1, '/repo', 'Graphiti note', 'entity body', 'decision', 10, 10, 'active'),
                    (2, '/repo', 'Other', 'contains private phrase', 'decision', 11, 11, 'active')",
            [],
        )?;
        conn.execute(
            "INSERT OR IGNORE INTO entities(id, canonical_name, entity_type, created_at_epoch)
             VALUES (1, 'Graphiti', 'tool', 10)",
            [],
        )?;
        conn.execute(
            "INSERT OR IGNORE INTO memory_entities(memory_id, entity_id)
             VALUES (1, 1)",
            [],
        )?;
        create_suppression(
            &conn,
            &SuppressRequest {
                target: parse_target("entity:graphiti")?,
                reason: None,
                actor: None,
            },
        )?;
        create_suppression(
            &conn,
            &SuppressRequest {
                target: parse_target("pattern:private phrase")?,
                reason: None,
                actor: None,
            },
        )?;
        let rows: Vec<i64> = {
            let sql = format!(
                "SELECT m.id FROM memories m WHERE {} ORDER BY m.id",
                memory_policy_filter_sql("m")
            );
            let mut stmt = conn.prepare(&sql)?;
            let rows = stmt.query_map([], |row| row.get::<_, i64>(0))?;
            crate::db::query::collect_rows(rows)?
        };
        assert!(rows.is_empty());
        Ok(())
    }

    #[test]
    fn feedback_records_event_without_mutating_target() -> Result<()> {
        let conn = Connection::open_in_memory()?;
        crate::migrate::run_migrations(&conn)?;
        conn.execute(
            "INSERT INTO memories
             (id, project, title, content, memory_type, created_at_epoch, updated_at_epoch, status)
             VALUES (1, '/repo', 'Feedback target', 'body', 'decision', 10, 10, 'active')",
            [],
        )?;
        let feedback = record_feedback(
            &conn,
            &FeedbackRequest {
                target: parse_target("memory:1")?,
                feedback: "not-relevant",
                source: Some("test"),
                context_injection_item_id: None,
                session_id: Some("s1"),
                project: Some("/repo"),
                reason: Some("wrong task"),
            },
        )?;
        assert_eq!(feedback.feedback, "not_relevant");
        let status: String = conn.query_row(
            "SELECT status FROM memories WHERE id = ?1",
            params![1],
            |row| row.get(0),
        )?;
        assert_eq!(status, "active");
        Ok(())
    }
}