ai-memory 0.7.1

AI-agnostic persistent memory system — MCP server, HTTP API, and CLI for any AI platform
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
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0

//! MCP `memory_delete` handler.

use crate::mcp::VectorIndex;
use crate::mcp::param_names;
use crate::mcp::registry::McpTool;
use crate::{db, validate};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::Path;

// --- D1.6 (#987): per-tool McpTool impl for `memory_delete` (lifecycle family) ---

/// v0.7.0 #972 D1.6 (#987) — request body for `memory_delete`.
#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
#[allow(dead_code)]
pub struct DeleteRequest {
    pub id: String,
}

/// v0.7.0 #972 D1.6 (#987) — `McpTool` impl for `memory_delete`.
#[allow(dead_code)]
pub struct DeleteTool;

impl McpTool for DeleteTool {
    fn name() -> &'static str {
        crate::mcp::registry::tool_names::MEMORY_DELETE
    }
    fn description() -> &'static str {
        "Delete a memory by ID."
    }
    fn docs() -> &'static str {
        "Hard-delete by id (removes row, embedding, FTS, links). Use memory_forget for bulk pattern delete (archives first)."
    }
    fn input_schema() -> Value {
        crate::mcp::registry::input_schema_for::<DeleteRequest>()
    }
    fn family() -> &'static str {
        crate::profile::Family::Lifecycle.name()
    }
}

#[cfg(test)]
mod d1_6_987_tests {
    //! D1.6 (#987) — schema parity for `memory_delete`.
    //! Shared helpers live at [`crate::mcp::parity_test_helpers`].
    use super::*;
    use crate::mcp::parity_test_helpers::{
        assert_descriptions_match, assert_property_set_parity, derived_props_for,
    };

    #[test]
    fn delete_parity_987() {
        let derived = derived_props_for::<DeleteRequest>();
        assert_property_set_parity("memory_delete", &derived);
        assert_descriptions_match("memory_delete", &derived);
    }

    #[test]
    fn delete_tool_metadata_987() {
        assert_eq!(DeleteTool::name(), "memory_delete");
        assert_eq!(DeleteTool::family(), "lifecycle");
    }
}

pub(super) fn handle_delete(
    conn: &rusqlite::Connection,
    db_path: &Path,
    params: &Value,
    vector_index: Option<&VectorIndex>,
    mcp_client: Option<&str>,
) -> Result<Value, String> {
    let id = params["id"]
        .as_str()
        .ok_or(crate::errors::msg::ID_REQUIRED)?;
    validate::validate_id(id).map_err(|e| e.to_string())?;

    // #913 (security-medium / SOC2, 2026-05-19) — admin/destructive
    // state-change audit. MCP `memory_delete` is the canonical
    // destructive operation; emit the forensic-chain row BEFORE the
    // permission gate + storage write so the audit trail captures the
    // caller's intent regardless of downstream outcome. Complementary
    // to `audit::emit(AuditAction::Delete)` further down which writes
    // the SIEM-shaped enterprise row AFTER the delete commits.
    let caller_for_forensic =
        crate::identity::resolve_agent_id(params["agent_id"].as_str(), mcp_client)
            .unwrap_or_else(|_| crate::identity::sentinels::ANONYMOUS_INVALID.to_string());
    crate::governance::audit::record_decision(
        &caller_for_forensic,
        "allow",
        crate::mcp::registry::tool_names::MEMORY_DELETE,
        "",
        json!({ "id": id }),
    );

    // Resolve the memory first so governance has owner context.
    let target = if let Some(m) = db::get(conn, id).map_err(|e| e.to_string())? {
        Some(m)
    } else {
        db::get_by_prefix(conn, id).map_err(|e| e.to_string())?
    };
    let Some(target) = target else {
        return Err(crate::errors::msg::MEMORY_NOT_FOUND.into());
    };

    // P5 (G9): snapshot fields the dispatcher needs BEFORE delete frees
    // the row. The dispatch itself is fire-and-forget after the DELETE
    // commits, but the payload is built from this owned snapshot.
    let snapshot_namespace = target.namespace.clone();
    let snapshot_title = target.title.clone();
    let snapshot_tier = target.tier.as_str().to_string();
    let snapshot_owner: Option<String> = target
        .metadata
        .get(param_names::AGENT_ID)
        .and_then(|v| v.as_str())
        .map(str::to_string);

    // v0.7.0 K9 — unified permission pipeline (delete-side).
    {
        use crate::permissions::{Op, PermissionContext, Permissions};
        let agent_id = crate::identity::resolve_agent_id(params["agent_id"].as_str(), mcp_client)
            .map_err(|e| e.to_string())?;
        let payload = json!({"id": target.id, "title": target.title});
        let ctx = PermissionContext {
            op: Op::MemoryDelete,
            namespace: target.namespace.clone(),
            agent_id,
            payload,
        };
        match Permissions::evaluate(&ctx, &[]) {
            crate::permissions::Decision::Allow | crate::permissions::Decision::Modify(_) => {}
            crate::permissions::Decision::Deny(reason) => {
                return Err(crate::governance::deny_message(
                    "delete",
                    crate::governance::DenyGate::PermissionRule,
                    &reason,
                ));
            }
            crate::permissions::Decision::Ask(prompt) => {
                return Ok(json!({
                    "status": "ask",
                    "reason": prompt,
                    "action": "delete",
                    "memory_id": target.id,
                }));
            }
        }
    }

    // Task 1.9: governance enforcement (delete-side).
    {
        use crate::models::{GovernanceDecision, GovernedAction};
        let agent_id = crate::identity::resolve_agent_id(params["agent_id"].as_str(), mcp_client)
            .map_err(|e| e.to_string())?;
        let mem_owner = target
            .metadata
            .get(param_names::AGENT_ID)
            .and_then(|v| v.as_str())
            .map(str::to_string);
        let payload = json!({"id": target.id, "title": target.title});
        match db::enforce_governance(
            conn,
            GovernedAction::Delete,
            &target.namespace,
            &agent_id,
            Some(&target.id),
            mem_owner.as_deref(),
            &payload,
        )
        .map_err(|e| e.to_string())?
        {
            GovernanceDecision::Allow => {}
            GovernanceDecision::Deny(refusal) => {
                return Err(crate::governance::deny_message(
                    "delete",
                    crate::governance::DenyGate::Governance,
                    &refusal.reason,
                ));
            }
            GovernanceDecision::Pending(pending_id) => {
                // v0.7.0 K4 — see the store-side companion call.
                crate::subscriptions::dispatch_approval_requested(conn, &pending_id, db_path);
                return Ok(json!({
                    "status": "pending",
                    "pending_id": pending_id,
                    "reason": crate::errors::msg::GOVERNANCE_REQUIRES_APPROVAL,
                    "action": "delete",
                    "memory_id": target.id,
                }));
            }
        }
    }

    let deleted = db::delete(conn, &target.id).map_err(|e| e.to_string())?;
    if deleted {
        if let Some(idx) = vector_index {
            idx.remove(&target.id);
        }
        // PR-5 (issue #487): security audit trail. No-op when disabled.
        crate::audit::emit(crate::audit::EventBuilder::new(
            crate::audit::AuditAction::Delete,
            crate::audit::actor(
                snapshot_owner
                    .clone()
                    .unwrap_or_else(|| "unknown".to_string()),
                mcp_client.map_or(crate::audit::synthesis_sources::HOST_FALLBACK, |_| {
                    crate::audit::synthesis_sources::MCP_CLIENT_INFO
                }),
                None,
            ),
            crate::audit::target_memory(
                target.id.clone(),
                snapshot_namespace.clone(),
                Some(snapshot_title.clone()),
                Some(snapshot_tier.clone()),
                None,
            ),
        ));
        // P5 (G9): fire `memory_delete` webhook AFTER the row is gone
        // (best-effort, fire-and-forget — same pattern as memory_store).
        let details = serde_json::to_value(crate::subscriptions::DeleteEventDetails {
            title: snapshot_title,
            tier: snapshot_tier,
        })
        .ok();
        crate::subscriptions::dispatch_event_with_details(
            conn,
            crate::mcp::registry::tool_names::MEMORY_DELETE,
            &target.id,
            &snapshot_namespace,
            snapshot_owner.as_deref(),
            db_path,
            details,
        );
        Ok(json!({"deleted": true}))
    } else {
        Err(crate::errors::msg::MEMORY_NOT_FOUND.into())
    }
}

#[cfg(test)]
mod tests {
    //! L0.7-3 Tier B chunk-A — coverage tests for `handle_delete`.
    //!
    //! Six-category template:
    //! A. happy path — full id + prefix resolution, response & DB side effect
    //! B. validation — missing / invalid id
    //! D. state-dependent — id not present
    //! E. idempotency — second delete returns not-found
    //! F. audit chain — emit() called (no-op without sink, but the path is taken)

    use super::*;
    use crate::models::{Memory, Tier};
    use crate::storage as db;

    fn fresh_conn() -> rusqlite::Connection {
        db::open(std::path::Path::new(":memory:")).expect("open in-memory db")
    }

    fn db_path() -> std::path::PathBuf {
        std::path::PathBuf::from(":memory:")
    }

    fn make_mem(title: &str, ns: &str) -> Memory {
        let now = chrono::Utc::now().to_rfc3339();
        Memory {
            id: uuid::Uuid::new_v4().to_string(),
            tier: Tier::Mid,
            namespace: ns.to_string(),
            title: title.to_string(),
            content: format!("c {title}"),
            tags: vec![],
            priority: 5,
            confidence: 1.0,
            source: "test".to_string(),
            access_count: 0,
            created_at: now.clone(),
            updated_at: now,
            last_accessed_at: None,
            expires_at: None,
            metadata: json!({"agent_id": "ai:alice"}),
            reflection_depth: 0,
            memory_kind: crate::models::MemoryKind::Observation,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            confidence_source: crate::models::ConfidenceSource::CallerProvided,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: 1,
        }
    }

    // A. happy path — full id
    #[test]
    fn happy_path_deletes_full_id() {
        let conn = fresh_conn();
        let mem = make_mem("doomed", "test");
        let id = db::insert(&conn, &mem).expect("insert");
        let db_path = db_path();
        let out =
            handle_delete(&conn, &db_path, &json!({"id": id.clone()}), None, None).expect("ok");
        assert_eq!(out["deleted"].as_bool(), Some(true));
        // DB side effect
        assert!(db::get(&conn, &id).unwrap().is_none(), "row removed");
    }

    // A. happy path — prefix resolution (no exact-id match, prefix matches)
    #[test]
    fn happy_path_prefix_resolution() {
        let conn = fresh_conn();
        let mut mem = make_mem("prefixed", "test");
        mem.id = "abcdef01-aaaa-bbbb-cccc-ddddeeeeffff".to_string();
        let id = db::insert(&conn, &mem).expect("insert");
        let db_path = db_path();
        let out = handle_delete(&conn, &db_path, &json!({"id": "abcdef01"}), None, None)
            .expect("prefix delete");
        assert_eq!(out["deleted"].as_bool(), Some(true));
        assert!(db::get(&conn, &id).unwrap().is_none());
    }

    // A. happy path — vector_index None branch (skipped) and Some-branch via API
    // The Some-branch needs a VectorIndex; we exercise it minimally below.
    #[test]
    fn happy_path_with_vector_index_removes_entry() {
        use crate::hnsw::VectorIndex;
        let conn = fresh_conn();
        let mem = make_mem("vec-target", "test");
        let id = db::insert(&conn, &mem).expect("insert");
        let idx = VectorIndex::empty();
        idx.insert(id.clone(), vec![0.1; 384]);
        let db_path = db_path();
        let out = handle_delete(
            &conn,
            &db_path,
            &json!({"id": id.clone()}),
            Some(&idx),
            Some("ai:claude-code"),
        )
        .expect("delete");
        assert_eq!(out["deleted"].as_bool(), Some(true));
    }

    // B. missing id
    #[test]
    fn missing_id_returns_error() {
        let conn = fresh_conn();
        let db_path = db_path();
        let err = handle_delete(&conn, &db_path, &json!({}), None, None).unwrap_err();
        assert!(err.contains("id is required"));
    }

    // B. invalid id format
    #[test]
    fn invalid_id_format_rejected() {
        let conn = fresh_conn();
        let db_path = db_path();
        let err = handle_delete(&conn, &db_path, &json!({"id": ""}), None, None).unwrap_err();
        assert!(!err.is_empty());
    }

    // D. unknown id
    #[test]
    fn unknown_id_returns_not_found() {
        let conn = fresh_conn();
        let db_path = db_path();
        let err = handle_delete(
            &conn,
            &db_path,
            &json!({"id": "deadbeef-1234-5678-9abc-def012345678"}),
            None,
            None,
        )
        .unwrap_err();
        assert!(err.contains("not found"));
    }

    // E. idempotency: deleting twice errors the second time
    #[test]
    fn double_delete_errors_second_time() {
        let conn = fresh_conn();
        let mem = make_mem("twice", "test");
        let id = db::insert(&conn, &mem).expect("insert");
        let db_path = db_path();
        let _ = handle_delete(&conn, &db_path, &json!({"id": id.clone()}), None, None)
            .expect("first delete");
        let err = handle_delete(&conn, &db_path, &json!({"id": id}), None, None).unwrap_err();
        assert!(err.contains("not found"));
    }

    // F. audit chain — emit is called via the audit module (no sink installed in
    // tests, so emission is a no-op, but the call path is exercised and covered).
    // We assert by re-fetching via list and confirming the row is gone — proving
    // the audit/emit codepath ran inline.
    #[test]
    fn happy_path_drives_audit_emit_call_path() {
        let conn = fresh_conn();
        let mem = make_mem("audit", "test");
        let id = db::insert(&conn, &mem).expect("insert");
        let db_path = db_path();
        // Pass an explicit agent_id to drive the resolve_agent_id branch
        let out = handle_delete(
            &conn,
            &db_path,
            &json!({"id": id, "agent_id": "ai:caller"}),
            None,
            Some("ai:claude-code"),
        )
        .expect("delete");
        assert_eq!(out["deleted"].as_bool(), Some(true));
    }

    // K9 / governance paths mutate the process-wide ACTIVE_PERMISSION_RULES
    // AND the process-wide PermissionsMode atomic. We hold BOTH locks for
    // the duration so concurrent tests don't race either knob:
    //   - `lock_permissions_mode_for_test` (config) — gates ACTIVE mode
    //   - `SHARED_PERMISSION_RULES_GUARD` (mcp/mod) — gates ACTIVE rules
    // The scope guard pins mode=Advisory and clears both registries on
    // drop so any panic mid-test leaves the next test seeing the default.
    fn lock_rules() -> std::sync::MutexGuard<'static, ()> {
        crate::mcp::SHARED_PERMISSION_RULES_GUARD
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    struct RulesScope {
        _rules: std::sync::MutexGuard<'static, ()>,
        _mode: std::sync::MutexGuard<'static, ()>,
    }
    impl Drop for RulesScope {
        fn drop(&mut self) {
            crate::permissions::clear_active_permission_rules_for_test();
            crate::config::clear_permissions_mode_override_for_test();
        }
    }
    fn rules_scope() -> RulesScope {
        let mode = crate::config::lock_permissions_mode_for_test();
        let rules = lock_rules();
        crate::permissions::clear_active_permission_rules_for_test();
        // Advisory keeps Ask as Ask (Enforce escalates Ask → Deny) and
        // still enforces explicit Deny rules.
        crate::config::override_active_permissions_mode_for_test(
            crate::config::PermissionsMode::Advisory,
        );
        RulesScope {
            _rules: rules,
            _mode: mode,
        }
    }

    // C. K9 Deny path
    #[test]
    fn k9_deny_rule_short_circuits() {
        use crate::permissions::{PermissionRule, RuleDecision, set_active_permission_rules};
        let _g = rules_scope();
        let conn = fresh_conn();
        let mem = make_mem("deny-target", "k9-deny-delete");
        let id = db::insert(&conn, &mem).expect("insert");
        let db_path = db_path();
        set_active_permission_rules(vec![PermissionRule {
            namespace_pattern: "k9-deny-delete".to_string(),
            op: "memory_delete".to_string(),
            agent_pattern: "*".to_string(),
            decision: RuleDecision::Deny,
            reason: Some("denied".to_string()),
        }]);
        let err = handle_delete(
            &conn,
            &db_path,
            &json!({"id": id, "agent_id": "ai:caller"}),
            None,
            None,
        )
        .unwrap_err();
        assert!(err.contains("denied"), "got: {err}");
    }

    // C. K9 Ask path — returns structured envelope, not error
    #[test]
    fn k9_ask_rule_returns_ask_envelope() {
        use crate::permissions::{PermissionRule, RuleDecision, set_active_permission_rules};
        let _g = rules_scope();
        let conn = fresh_conn();
        let mem = make_mem("ask-target", "k9-ask-delete");
        let id = db::insert(&conn, &mem).expect("insert");
        let db_path = db_path();
        set_active_permission_rules(vec![PermissionRule {
            namespace_pattern: "k9-ask-delete".to_string(),
            op: "memory_delete".to_string(),
            agent_pattern: "*".to_string(),
            decision: RuleDecision::Ask,
            reason: Some("operator approval required".to_string()),
        }]);
        let out = handle_delete(
            &conn,
            &db_path,
            &json!({"id": id, "agent_id": "ai:caller"}),
            None,
            None,
        )
        .expect("ask returns Ok");
        assert_eq!(out["status"].as_str(), Some("ask"));
        assert_eq!(out["action"].as_str(), Some("delete"));
    }

    // Helper: install a governance policy on `ns` that gates `delete`
    // at the given `delete_level`. The standard memory carries an
    // explicit `agent_id` so Owner-level checks have a target.
    fn install_delete_policy(
        conn: &rusqlite::Connection,
        ns: &str,
        delete_level: crate::models::GovernanceLevel,
        approver: crate::models::ApproverType,
        owner: &str,
    ) {
        use crate::models::{CorePolicy, GovernancePolicy, default_metadata};
        let policy = GovernancePolicy {
            core: CorePolicy {
                delete: delete_level,
                approver,
                ..CorePolicy::default()
            },
            ..Default::default()
        };
        let now = chrono::Utc::now().to_rfc3339();
        let mut metadata = default_metadata();
        if let Some(obj) = metadata.as_object_mut() {
            obj.insert(
                "agent_id".to_string(),
                serde_json::Value::String(owner.to_string()),
            );
            obj.insert(
                "governance".to_string(),
                serde_json::to_value(&policy).unwrap(),
            );
        }
        let standard = Memory {
            id: uuid::Uuid::new_v4().to_string(),
            tier: Tier::Long,
            namespace: format!("_standards-{ns}"),
            title: format!("std-{ns}"),
            content: "policy".to_string(),
            tags: vec![],
            priority: 9,
            confidence: 1.0,
            source: "test".to_string(),
            access_count: 0,
            created_at: now.clone(),
            updated_at: now,
            last_accessed_at: None,
            expires_at: None,
            metadata,
            reflection_depth: 0,
            memory_kind: crate::models::MemoryKind::Observation,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            confidence_source: crate::models::ConfidenceSource::CallerProvided,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: 1,
        };
        let sid = db::insert(conn, &standard).expect("insert standard");
        db::set_namespace_standard(conn, ns, &sid, None).expect("set standard");
    }

    // Governance Deny path (lines 93-94): owner-level delete by
    // non-owner. Requires Enforce mode (Advisory just logs).
    #[test]
    fn governance_deny_blocks_delete() {
        let _gate = crate::config::lock_permissions_mode_for_test();
        crate::config::override_active_permissions_mode_for_test(
            crate::config::PermissionsMode::Enforce,
        );
        let conn = fresh_conn();
        let ns = "gov-deny-del";
        install_delete_policy(
            &conn,
            ns,
            crate::models::GovernanceLevel::Owner,
            crate::models::ApproverType::Human,
            "ai:alice",
        );
        let mut mem = make_mem("target", ns);
        if let Some(obj) = mem.metadata.as_object_mut() {
            obj.insert(
                "agent_id".to_string(),
                serde_json::Value::String("ai:alice".to_string()),
            );
        }
        let id = db::insert(&conn, &mem).expect("insert");
        let db_path = db_path();
        let err = handle_delete(
            &conn,
            &db_path,
            &json!({"id": id, "agent_id": "ai:eve"}),
            None,
            None,
        )
        .unwrap_err();
        assert!(
            err.contains("governance") || err.contains("denied") || err.contains("owner"),
            "got: {err}"
        );
        crate::config::clear_permissions_mode_override_for_test();
    }

    // Governance Pending path (lines 96-105): Approve policy queues a
    // pending action and returns an envelope. Requires Enforce mode.
    #[test]
    fn governance_pending_returns_pending_envelope() {
        let _gate = crate::config::lock_permissions_mode_for_test();
        crate::config::override_active_permissions_mode_for_test(
            crate::config::PermissionsMode::Enforce,
        );
        let conn = fresh_conn();
        let ns = "gov-pending-del";
        install_delete_policy(
            &conn,
            ns,
            crate::models::GovernanceLevel::Approve,
            crate::models::ApproverType::Human,
            "ai:alice",
        );
        let mem = make_mem("target", ns);
        let id = db::insert(&conn, &mem).expect("insert");
        let db_path = db_path();
        let out = handle_delete(
            &conn,
            &db_path,
            &json!({"id": id, "agent_id": "ai:bob"}),
            None,
            None,
        )
        .expect("pending returns Ok");
        assert_eq!(out["status"].as_str(), Some("pending"));
        assert_eq!(out["action"].as_str(), Some("delete"));
        assert!(out["pending_id"].as_str().is_some());
        crate::config::clear_permissions_mode_override_for_test();
    }
}