dirge-agent 0.7.3

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
use std::sync::Arc;

use rig::completion::ToolDefinition;
use rig::tool::Tool;
use serde::Deserialize;

use crate::agent::tools::{AskSender, PermCheck, ToolError, check_perm};
use crate::extras::memory_provider::MemoryProvider;

pub struct MemoryTool {
    pub permission: Option<PermCheck>,
    pub ask_tx: Option<AskSender>,
    // dirge-bov5: dyn-dispatched provider so alternative backends
    // (vector store, MCP, remote sync) can plug in without churning
    // the call sites. `Arc<MemoryToolStore>` is the default and
    // coerces to this trait object via unsizing.
    store: Arc<dyn MemoryProvider>,
    /// Optional cross-project (global) memory tier. When present, an action
    /// with `scope: "global"` routes here instead of the per-project
    /// `store`; absent, a global request falls back to the project store.
    global_store: Option<Arc<dyn MemoryProvider>>,
}

impl MemoryTool {
    pub fn new(
        store: Arc<dyn MemoryProvider>,
        permission: Option<PermCheck>,
        ask_tx: Option<AskSender>,
    ) -> Self {
        Self {
            permission,
            ask_tx,
            store,
            global_store: None,
        }
    }

    /// Attach the global (cross-project) memory tier. `None` is a no-op.
    pub fn with_global(mut self, global_store: Option<Arc<dyn MemoryProvider>>) -> Self {
        self.global_store = global_store;
        self
    }

    /// Pick the store an action targets. `scope == "global"` selects the
    /// global tier when configured; everything else (including a global
    /// request with no global tier) uses the per-project store.
    fn scoped_store(&self, scope: Option<&str>) -> &Arc<dyn MemoryProvider> {
        match scope {
            Some("global") => self.global_store.as_ref().unwrap_or(&self.store),
            _ => &self.store,
        }
    }
}

#[derive(Deserialize)]
pub struct Args {
    action: String,
    #[serde(default = "default_target")]
    target: String,
    content: Option<String>,
    old_text: Option<String>,
    /// UMP memory kind (types.ts:8-13). One of: semantic, episodic,
    /// procedural, working, identity. Defaults to "procedural".
    #[serde(default = "default_kind")]
    kind: Option<String>,
    /// Full-text query for the `search` action (dirge-q8wt).
    #[serde(default)]
    query: Option<String>,
    /// Memory scope: "project" (default) for facts about THIS repo, or
    /// "global" for durable cross-project user preferences that should
    /// follow the user everywhere.
    #[serde(default)]
    scope: Option<String>,
}

fn default_target() -> String {
    "memory".to_string()
}

fn default_kind() -> Option<String> {
    None
}

impl Tool for MemoryTool {
    const NAME: &'static str = "memory";

    type Error = ToolError;
    type Args = Args;
    type Output = String;

    async fn definition(&self, _prompt: String) -> ToolDefinition {
        ToolDefinition {
            name: "memory".to_string(),
            description: r#"Persistent long-term memory for project facts and pitfalls.

SAVE WHEN: the user corrects you or says "remember this"; you discover build/test commands, conventions, architecture patterns, or library quirks; something was tried and failed (pitfall).

TARGETS: "memory" (facts, conventions, build, architecture), "pitfalls" (anti-patterns, things tried and failed).

KINDS (optional, default "procedural"): semantic (durable fact), episodic (past event), procedural (how-to rule), working (short-lived), identity (who the user/agent is).

ACTIONS:
- view: inline entries + breadcrumb index for a target
- add: new entry (content)
- replace: update matched entry (old_text + content)
- remove: archive matched entry (old_text); restorable
- restore: un-archive a removed entry (old_text)
- expand: full text of one entry by id/substring (old_text)
- search: full-text search across all memory (query)

old_text matches a unique substring or the exact "urn:ump:…" id from view/index."#
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "enum": ["view", "add", "replace", "remove", "restore", "expand", "search"],
                        "description": "The action to perform."
                    },
                    "target": {
                        "type": "string",
                        "enum": ["memory", "pitfalls"],
                        "description": "Which memory store: 'memory' for project facts, 'pitfalls' for anti-patterns."
                    },
                    "content": {
                        "type": "string",
                        "description": "The entry content. Required for 'add' and 'replace'."
                    },
                    "old_text": {
                        "type": "string",
                        "description": "Short unique substring identifying the entry to replace, remove, restore, or expand — or the entry's exact 'urn:ump:…' id from view's meta / the breadcrumb index."
                    },
                    "query": {
                        "type": "string",
                        "description": "Full-text query for the 'search' action."
                    },
                    "kind": {
                        "type": "string",
                        "enum": ["semantic", "episodic", "procedural", "working", "identity"],
                        "description": "The UMP memory kind. Defaults to 'procedural'. See KINDS above."
                    },
                    "scope": {
                        "type": "string",
                        "enum": ["project", "global"],
                        "description": "Where the entry lives: 'project' (default) for facts about THIS repo; 'global' for durable user preferences that should follow the user across every project."
                    }
                },
                "required": ["action"]
            }),
        }
    }

    async fn call(&self, args: Args) -> Result<String, ToolError> {
        check_perm(&self.permission, &self.ask_tx, "memory", &args.action).await?;

        let target = validate_target(&args.target)?;
        // Route to the project or global tier per `scope` (default project).
        let store = self.scoped_store(args.scope.as_deref());

        match args.action.as_str() {
            "view" => {
                let resp = store.view(target);
                Ok(serde_json::to_string_pretty(&resp)
                    .unwrap_or_else(|_| r#"{"error":"serialization failed"}"#.to_string()))
            }
            // dirge-5feg: the tool layer fires `on_memory_write`
            // exactly once after each successful CRUD, regardless of
            // which provider impl handled the call. Providers are
            // forbidden from calling the hook themselves to avoid
            // double-firing through wrappers.
            //
            // dirge-ix7n: the third hook arg carries action-specific
            // semantics — `content` for add/replace, `old_text` for
            // remove. The trait doc on `on_memory_write` calls this
            // out as `payload` to avoid the "always a new value"
            // misreading.
            "add" => {
                let content = crate::agent::tools::required_nonblank(
                    args.content.as_deref(),
                    "content",
                    "add",
                )?;
                let resp = store
                    .add(target, content, args.kind.as_deref())
                    .map_err(ToolError::Msg)?;
                crate::agent::review::fire_memory_write(store.as_ref(), "add", target, content);
                Ok(serde_json::to_string_pretty(&resp)
                    .unwrap_or_else(|_| r#"{"error":"serialization failed"}"#.to_string()))
            }
            "replace" => {
                let old_text = crate::agent::tools::required_nonblank(
                    args.old_text.as_deref(),
                    "old_text",
                    "replace",
                )?;
                let content = crate::agent::tools::required_nonblank(
                    args.content.as_deref(),
                    "content",
                    "replace",
                )?;
                let resp = store
                    .replace(target, old_text, content, args.kind.as_deref())
                    .map_err(ToolError::Msg)?;
                crate::agent::review::fire_memory_write(store.as_ref(), "replace", target, content);
                Ok(serde_json::to_string_pretty(&resp)
                    .unwrap_or_else(|_| r#"{"error":"serialization failed"}"#.to_string()))
            }
            "remove" => {
                let old_text = crate::agent::tools::required_nonblank(
                    args.old_text.as_deref(),
                    "old_text",
                    "remove",
                )?;
                let resp = store.remove(target, old_text).map_err(ToolError::Msg)?;
                crate::agent::review::fire_memory_write(store.as_ref(), "remove", target, old_text);
                Ok(serde_json::to_string_pretty(&resp)
                    .unwrap_or_else(|_| r#"{"error":"serialization failed"}"#.to_string()))
            }
            "restore" => {
                let old_text = crate::agent::tools::required_nonblank(
                    args.old_text.as_deref(),
                    "old_text",
                    "restore",
                )?;
                let resp = store.restore(target, old_text).map_err(ToolError::Msg)?;
                crate::agent::review::fire_memory_write(
                    store.as_ref(),
                    "restore",
                    target,
                    old_text,
                );
                Ok(serde_json::to_string_pretty(&resp)
                    .unwrap_or_else(|_| r#"{"error":"serialization failed"}"#.to_string()))
            }
            // expand/search are reads — no on_memory_write fire.
            // Both span targets, so `target` is ignored.
            "expand" => {
                let old_text = crate::agent::tools::required_nonblank(
                    args.old_text.as_deref(),
                    "old_text",
                    "expand",
                )?;
                let resp = store.expand(old_text).map_err(ToolError::Msg)?;
                Ok(serde_json::to_string_pretty(&resp)
                    .unwrap_or_else(|_| r#"{"error":"serialization failed"}"#.to_string()))
            }
            "search" => {
                let query = crate::agent::tools::required_nonblank(
                    args.query.as_deref(),
                    "query",
                    "search",
                )?;
                let resp = store.search(query).map_err(ToolError::Msg)?;
                Ok(serde_json::to_string_pretty(&resp)
                    .unwrap_or_else(|_| r#"{"error":"serialization failed"}"#.to_string()))
            }
            _ => Err(ToolError::Msg(format!(
                "Unknown action '{}'. Use: view, add, replace, remove, restore, expand, search.",
                args.action
            ))),
        }
    }
}

fn validate_target(target: &str) -> Result<&str, ToolError> {
    match target {
        "memory" | "pitfalls" => Ok(target),
        _ => Err(ToolError::Msg(format!(
            "Invalid target '{}'. Use 'memory' or 'pitfalls'.",
            target
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extras::dirge_paths::ProjectPaths;
    use crate::extras::memory_db::SqliteMemoryStore;
    use std::sync::atomic::{AtomicU32, Ordering};

    static TEST_COUNTER: AtomicU32 = AtomicU32::new(0);

    fn temp_store() -> (Arc<dyn MemoryProvider>, std::path::PathBuf) {
        let n = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("dirge-mem-tool-test-{}-{}", std::process::id(), n));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join(".git")).unwrap();
        let paths = ProjectPaths::new(&dir);
        let store: Arc<dyn MemoryProvider> = Arc::new(SqliteMemoryStore::load(&paths).unwrap());
        (store, dir)
    }

    fn make_runtime() -> tokio::runtime::Runtime {
        tokio::runtime::Builder::new_current_thread()
            .enable_time()
            .build()
            .unwrap()
    }

    /// `scope: "global"` routes the write to the global tier, leaving the
    /// project store untouched. A second independent store stands in for
    /// the global tier.
    #[test]
    fn scope_global_routes_to_the_global_store() {
        let (project, _pd) = temp_store();
        let (global, _gd) = temp_store();
        let tool = MemoryTool::new(project.clone(), None, None).with_global(Some(global.clone()));
        let rt = make_runtime();

        rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: Some("user prefers TDD".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: Some("global".into()),
        }))
        .expect("global add should succeed");

        assert!(
            global
                .view("memory")
                .to_string()
                .contains("user prefers TDD"),
            "the entry must land in the global store"
        );
        assert!(
            !project
                .view("memory")
                .to_string()
                .contains("user prefers TDD"),
            "the project store must be untouched"
        );
    }

    #[test]
    fn test_add_and_view() {
        let (store, _dir) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();

        // Add an entry.
        let result = rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: Some("build command: cargo build --release".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }));
        assert!(result.is_ok(), "add failed: {:?}", result);
        let resp: serde_json::Value = serde_json::from_str(&result.unwrap()).expect("valid JSON");
        assert_eq!(resp["success"], true);
        assert_eq!(resp["entry_count"], 1);

        // View — should see the entry.
        let result = rt.block_on(tool.call(Args {
            action: "view".into(),
            target: "memory".into(),
            content: None,
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }));
        let resp: serde_json::Value = serde_json::from_str(&result.unwrap()).expect("valid JSON");
        let entries = resp["entries"].as_array().unwrap();
        assert_eq!(entries.len(), 1);
        assert!(entries[0].as_str().unwrap().contains("cargo build"));
    }

    #[test]
    fn test_add_to_pitfalls() {
        let (store, _dir) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();

        let result = rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "pitfalls".into(),
            content: Some("Don't use async in the render loop".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }));
        assert!(result.is_ok());
        let resp: serde_json::Value = serde_json::from_str(&result.unwrap()).expect("valid JSON");
        assert_eq!(resp["target"], "pitfalls");
    }

    #[test]
    fn test_duplicate_rejected() {
        let (store, _dir) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();

        rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: Some("same entry".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();

        let result = rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: Some("same entry".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }));
        assert!(result.is_err());
    }

    #[test]
    fn test_replace_by_substring() {
        let (store, _dir) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();

        rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: Some("build command: cargo build".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();

        let result = rt.block_on(tool.call(Args {
            action: "replace".into(),
            target: "memory".into(),
            content: Some("build command: cargo build --release".into()),
            old_text: Some("cargo build".into()),
            kind: None,
            query: None,
            scope: None,
        }));
        let resp: serde_json::Value = serde_json::from_str(&result.unwrap()).expect("valid JSON");
        assert_eq!(resp["success"], true);

        // Verify the entry was replaced.
        let result = rt.block_on(tool.call(Args {
            action: "view".into(),
            target: "memory".into(),
            content: None,
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }));
        let resp: serde_json::Value = serde_json::from_str(&result.unwrap()).expect("valid JSON");
        let entries = resp["entries"].as_array().unwrap();
        assert!(entries[0].as_str().unwrap().contains("--release"));
    }

    #[test]
    fn test_remove_entry() {
        let (store, _dir) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();

        rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: Some("temp entry to remove".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();

        let result = rt.block_on(tool.call(Args {
            action: "remove".into(),
            target: "memory".into(),
            content: None,
            old_text: Some("temp entry".into()),
            kind: None,
            query: None,
            scope: None,
        }));
        let resp: serde_json::Value = serde_json::from_str(&result.unwrap()).expect("valid JSON");
        assert_eq!(resp["success"], true);

        // Verify empty.
        let result = rt.block_on(tool.call(Args {
            action: "view".into(),
            target: "memory".into(),
            content: None,
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }));
        let resp: serde_json::Value = serde_json::from_str(&result.unwrap()).expect("valid JSON");
        assert_eq!(resp["entry_count"], 0);
    }

    #[test]
    fn test_invalid_target_rejected() {
        let (store, _dir) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();

        let result = rt.block_on(tool.call(Args {
            action: "view".into(),
            target: "user".into(),
            content: None,
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid target"));
    }

    #[test]
    fn test_missing_content_for_add() {
        let (store, _dir) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();

        let result = rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: None,
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }));
        assert!(result.is_err());
    }

    #[test]
    fn test_definition_includes_both_targets() {
        let (store, _dir) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();
        let def = rt.block_on(tool.definition(String::new()));
        assert!(def.description.contains("memory"));
        assert!(def.description.contains("pitfalls"));
    }

    /// dirge-bov5 — `MemoryTool` routes through the `MemoryProvider`
    /// trait so an alternative backend (vector store, MCP-backed,
    /// etc.) receives every call. Verifies a custom recording
    /// provider sees both writes and reads.
    #[test]
    fn integration_tool_routes_calls_through_custom_provider() {
        use crate::extras::memory_provider::MemoryProvider;
        use serde_json::json;
        use std::sync::Mutex;

        #[derive(Default)]
        struct RecordingProvider {
            calls: Mutex<Vec<String>>,
        }
        impl MemoryProvider for RecordingProvider {
            fn name(&self) -> &str {
                "recording"
            }
            fn view(&self, target: &str) -> serde_json::Value {
                self.calls.lock().unwrap().push(format!("view:{}", target));
                json!({ "entries": [], "count": 0 })
            }
            fn add(
                &self,
                target: &str,
                content: &str,
                _kind: Option<&str>,
            ) -> Result<serde_json::Value, String> {
                self.calls
                    .lock()
                    .unwrap()
                    .push(format!("add:{}:{}", target, content));
                Ok(json!({ "success": true, "entry_count": 1 }))
            }
            fn replace(
                &self,
                target: &str,
                old: &str,
                content: &str,
                _kind: Option<&str>,
            ) -> Result<serde_json::Value, String> {
                self.calls
                    .lock()
                    .unwrap()
                    .push(format!("replace:{}:{}:{}", target, old, content));
                Ok(json!({ "success": true }))
            }
            fn remove(&self, target: &str, old: &str) -> Result<serde_json::Value, String> {
                self.calls
                    .lock()
                    .unwrap()
                    .push(format!("remove:{}:{}", target, old));
                Ok(json!({ "success": true }))
            }
        }

        let provider = Arc::new(RecordingProvider::default());
        let tool = MemoryTool::new(provider.clone() as Arc<dyn MemoryProvider>, None, None);
        let rt = make_runtime();

        rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: Some("from-tool".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();
        rt.block_on(tool.call(Args {
            action: "view".into(),
            target: "memory".into(),
            content: None,
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();
        rt.block_on(tool.call(Args {
            action: "replace".into(),
            target: "memory".into(),
            content: Some("new".into()),
            old_text: Some("from-tool".into()),
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();
        rt.block_on(tool.call(Args {
            action: "remove".into(),
            target: "memory".into(),
            content: None,
            old_text: Some("new".into()),
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();

        let calls = provider.calls.lock().unwrap();
        assert_eq!(
            *calls,
            vec![
                "add:memory:from-tool".to_string(),
                "view:memory".to_string(),
                "replace:memory:from-tool:new".to_string(),
                "remove:memory:new".to_string(),
            ],
            "custom provider must receive every tool call verbatim"
        );
    }

    /// dirge-5feg — the tool layer fires `on_memory_write` exactly
    /// once per successful CRUD, regardless of whether the
    /// provider's CRUD impl self-fired. `view` does NOT fire the
    /// hook (it's not a write).
    #[test]
    fn integration_tool_layer_fires_on_memory_write_once_per_crud() {
        use crate::extras::memory_provider::MemoryProvider;
        use serde_json::json;
        use std::sync::Mutex;

        #[derive(Default)]
        struct RecordingHookProvider {
            hooks: Mutex<Vec<(String, String, String)>>,
        }
        impl MemoryProvider for RecordingHookProvider {
            fn name(&self) -> &str {
                "hook-recorder"
            }
            // CRUD impls deliberately do NOT call on_memory_write —
            // the tool layer is supposed to.
            fn view(&self, _: &str) -> serde_json::Value {
                json!({ "entries": [] })
            }
            fn add(
                &self,
                _: &str,
                _: &str,
                _kind: Option<&str>,
            ) -> Result<serde_json::Value, String> {
                Ok(json!({ "success": true }))
            }
            fn replace(
                &self,
                _: &str,
                _: &str,
                _: &str,
                _kind: Option<&str>,
            ) -> Result<serde_json::Value, String> {
                Ok(json!({ "success": true }))
            }
            fn remove(&self, _: &str, _: &str) -> Result<serde_json::Value, String> {
                Ok(json!({ "success": true }))
            }
            fn on_memory_write(&self, action: &str, target: &str, content: &str) {
                self.hooks
                    .lock()
                    .unwrap()
                    .push((action.into(), target.into(), content.into()));
            }
        }

        let provider = Arc::new(RecordingHookProvider::default());
        let tool = MemoryTool::new(provider.clone() as Arc<dyn MemoryProvider>, None, None);
        let rt = make_runtime();

        // view does NOT fire the hook.
        rt.block_on(tool.call(Args {
            action: "view".into(),
            target: "memory".into(),
            content: None,
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();
        assert!(
            provider.hooks.lock().unwrap().is_empty(),
            "view must not fire on_memory_write"
        );

        // add → one fire with the content.
        rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: Some("alpha".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();
        // replace → one fire with the new content.
        rt.block_on(tool.call(Args {
            action: "replace".into(),
            target: "memory".into(),
            content: Some("beta".into()),
            old_text: Some("alpha".into()),
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();
        // remove → one fire with the old_text (no new content).
        rt.block_on(tool.call(Args {
            action: "remove".into(),
            target: "pitfalls".into(),
            content: None,
            old_text: Some("beta".into()),
            kind: None,
            query: None,
            scope: None,
        }))
        .unwrap();

        let hooks = provider.hooks.lock().unwrap();
        assert_eq!(
            *hooks,
            vec![
                ("add".into(), "memory".into(), "alpha".into()),
                ("replace".into(), "memory".into(), "beta".into()),
                ("remove".into(), "pitfalls".into(), "beta".into()),
            ],
            "tool layer must fire on_memory_write exactly once per CRUD"
        );
    }

    /// End-to-end: every action the SYSTEM_PROMPT names for the memory
    /// tool must succeed against a real MemoryTool with valid args.
    /// If this fails, the prompt is lying to the model. See dirge-yqmo.
    #[test]
    fn integration_prompt_actions_all_executable() {
        use crate::agent::prompt::SYSTEM_PROMPT;

        let memory_line = SYSTEM_PROMPT
            .lines()
            .find(|l| l.trim_start().starts_with("- memory:"))
            .expect("SYSTEM_PROMPT should describe the memory tool");

        // Extract candidate action words from the prompt.
        let known_actions = [
            "view", "add", "replace", "remove", "restore", "expand", "search",
        ];
        let prompt_actions: Vec<&str> = known_actions
            .iter()
            .copied()
            .filter(|a| {
                memory_line
                    .split(|c: char| !c.is_alphanumeric() && c != '_')
                    .any(|w| w == *a)
            })
            .collect();
        assert_eq!(
            prompt_actions.len(),
            known_actions.len(),
            "prompt should list all real actions; got {:?}",
            prompt_actions
        );

        let (store, _dir) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();

        // Seed an entry so replace/remove have something to match.
        rt.block_on(tool.call(Args {
            action: "add".into(),
            target: "memory".into(),
            content: Some("seed: build command cargo test".into()),
            old_text: None,
            kind: None,
            query: None,
            scope: None,
        }))
        .expect("seed add should succeed");

        for action in &prompt_actions {
            let args = match *action {
                "view" => Args {
                    action: "view".into(),
                    target: "memory".into(),
                    content: None,
                    old_text: None,
                    kind: None,
                    query: None,
                    scope: None,
                },
                "add" => Args {
                    action: "add".into(),
                    target: "memory".into(),
                    content: Some(format!("entry-for-{}", action)),
                    old_text: None,
                    kind: None,
                    query: None,
                    scope: None,
                },
                "replace" => Args {
                    action: "replace".into(),
                    target: "memory".into(),
                    content: Some("seed: build command cargo test --release".into()),
                    old_text: Some("seed:".into()),
                    kind: None,
                    query: None,
                    scope: None,
                },
                "remove" => Args {
                    action: "remove".into(),
                    target: "memory".into(),
                    content: None,
                    old_text: Some("entry-for-add".into()),
                    kind: None,
                    query: None,
                    scope: None,
                },
                // Runs after "remove" archived entry-for-add, so the
                // restore has a tombstoned entry to revive.
                "restore" => Args {
                    action: "restore".into(),
                    target: "memory".into(),
                    content: None,
                    old_text: Some("entry-for-add".into()),
                    kind: None,
                    query: None,
                    scope: None,
                },
                // Runs after "restore", so entry-for-add is active.
                "expand" => Args {
                    action: "expand".into(),
                    target: "memory".into(),
                    content: None,
                    old_text: Some("entry-for-add".into()),
                    kind: None,
                    query: None,
                    scope: None,
                },
                "search" => Args {
                    action: "search".into(),
                    target: "memory".into(),
                    content: None,
                    old_text: None,
                    kind: None,
                    query: Some("seed".into()),
                    scope: None,
                },
                _ => unreachable!(),
            };
            let result = rt.block_on(tool.call(args));
            assert!(
                result.is_ok(),
                "prompt-advertised action '{}' failed end-to-end: {:?}",
                action,
                result
            );
        }
    }
}