dirge-agent 0.13.9

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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
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>>,
    /// dirge-ygm3: gate the background-review actions (`mark`, `supersede`).
    /// These record procedural outcomes and contradiction supersessions that
    /// the background review pass infers from the transcript — the interactive
    /// agent must not self-grade or self-supersede. When `false` (the default,
    /// the main agent's instance) those actions are absent from the tool
    /// schema AND rejected at the call layer; the review runner gets a separate
    /// instance built with `true`.
    review_actions: bool,
}

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,
            review_actions: false,
        }
    }

    /// 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
    }

    /// Enable the background-review-only actions (`mark`/`supersede`). Set on
    /// the instance handed to the review runner, never the main agent's.
    pub fn with_review_actions(mut self, enabled: bool) -> Self {
        self.review_actions = enabled;
        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, overview. Defaults to "procedural".
    #[serde(default = "default_kind")]
    kind: Option<String>,
    /// Full-text query for the `search` action (dirge-q8wt).
    #[serde(default)]
    query: Option<String>,
    /// Outcome for the `mark` action (dirge-zygq): "success" or
    /// "failure". Records a procedural playbook's real-world result.
    #[serde(default)]
    outcome: Option<String>,
    /// Contradiction type for the `supersede` action (dirge-fa10):
    /// `true` when the user flatly denied the old fact (discounts the
    /// successor's confidence), `false`/absent for a natural update.
    #[serde(default)]
    harsh: Option<bool>,
    /// 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 {
        // dirge-ygm3: `mark`/`supersede` are background-review-only. They live
        // in the action enum (parameters), not the prose description, so gating
        // them changes only the schema's allowed values — never the
        // length-checked description. The review runner's instance sets
        // `review_actions = true`; the main agent's leaves them out entirely.
        let mut actions = vec![
            "view", "add", "replace", "remove", "restore", "expand", "search",
        ];
        let mut action_desc = "The action to perform.".to_string();
        if self.review_actions {
            actions.push("mark");
            actions.push("supersede");
            action_desc.push_str(
                " 'mark' records a procedural playbook's outcome (old_text + \
                 outcome=success|failure). 'supersede' retires a contradicted fact \
                 (old_text) and writes a corrected one (content), keeping the old as \
                 an audit record — use it instead of 'replace' when a fact CHANGED \
                 rather than was reworded.",
            );
        }
        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 (fact), episodic (event), procedural (rule), working (short-lived), identity (user/agent), overview (singular project orientation; adding one replaces it).

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: {
                let mut params = serde_json::json!({
                    "type": "object",
                    "properties": {
                        "action": {
                            "type": "string",
                            "enum": actions,
                            "description": action_desc
                        },
                        "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", "overview"],
                            "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"]
                });
                // dirge-ygm3: the mark/supersede-only params travel with their
                // actions — present only on the review instance.
                if self.review_actions
                    && let Some(props) = params["properties"].as_object_mut()
                {
                    props.insert(
                        "outcome".to_string(),
                        serde_json::json!({
                            "type": "string",
                            "enum": ["success", "failure"],
                            "description": "For the 'mark' action: whether a procedural playbook worked ('success') or failed ('failure') in practice."
                        }),
                    );
                    props.insert(
                        "harsh".to_string(),
                        serde_json::json!({
                            "type": "boolean",
                            "description": "For the 'supersede' action: true when the user flatly DENIED the old fact (discounts the new fact's confidence); false/omitted for a natural update like a changed preference."
                        }),
                    );
                }
                params
            },
        }
    }

    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());

        // dirge-ygm3: defense in depth — `mark`/`supersede` are absent from
        // this instance's schema unless review_actions is on, but reject them
        // at the call layer too so a hand-crafted call can't reach them on the
        // interactive agent's tool.
        if !self.review_actions && matches!(args.action.as_str(), "mark" | "supersede") {
            return Err(ToolError::Msg(format!(
                "Action '{}' is only available to the background review pass.",
                args.action
            )));
        }

        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()))
            }
            // supersede writes a NEW corrected entry, so the hook payload
            // is the new content (like add/replace), not the old_text.
            "supersede" => {
                let old_text = crate::agent::tools::required_nonblank(
                    args.old_text.as_deref(),
                    "old_text",
                    "supersede",
                )?;
                let content = crate::agent::tools::required_nonblank(
                    args.content.as_deref(),
                    "content",
                    "supersede",
                )?;
                let resp = store
                    .supersede(
                        target,
                        old_text,
                        content,
                        args.kind.as_deref(),
                        args.harsh.unwrap_or(false),
                    )
                    .map_err(ToolError::Msg)?;
                crate::agent::review::fire_memory_write(
                    store.as_ref(),
                    "supersede",
                    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",
                )?;
                // dirge-4hld: search can do blocking work — SQLite I/O for the
                // builtin store, and a network embedding round-trip for the
                // hybrid provider. Off-load to the blocking pool so it never
                // parks an async runtime worker.
                let store = store.clone();
                let query = query.to_string();
                let resp = tokio::task::spawn_blocking(move || store.search(&query))
                    .await
                    .map_err(|e| ToolError::Msg(format!("memory search task failed: {e}")))?
                    .map_err(ToolError::Msg)?;
                Ok(serde_json::to_string_pretty(&resp)
                    .unwrap_or_else(|_| r#"{"error":"serialization failed"}"#.to_string()))
            }
            // mark records an outcome signal (dirge-zygq), not a content
            // CRUD — like expand it mutates a usage counter, so no
            // on_memory_write fire.
            "mark" => {
                let old_text = crate::agent::tools::required_nonblank(
                    args.old_text.as_deref(),
                    "old_text",
                    "mark",
                )?;
                let outcome = crate::agent::tools::required_nonblank(
                    args.outcome.as_deref(),
                    "outcome",
                    "mark",
                )?;
                let success = match outcome {
                    "success" => true,
                    "failure" => false,
                    other => {
                        return Err(ToolError::Msg(format!(
                            "Invalid outcome '{other}'. Use 'success' or 'failure'."
                        )));
                    }
                };
                let resp = store
                    .record_outcome(target, old_text, success)
                    .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, mark, supersede.",
                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()
    }

    /// Minimal `Args` with everything but `action` defaulted.
    fn action_args(action: &str) -> Args {
        Args {
            action: action.into(),
            target: "memory".into(),
            content: None,
            old_text: None,
            kind: None,
            query: None,
            outcome: None,
            harsh: None,
            scope: None,
        }
    }

    fn action_enum(tool: &MemoryTool, rt: &tokio::runtime::Runtime) -> Vec<String> {
        let def = rt.block_on(tool.definition(String::new()));
        def.parameters["properties"]["action"]["enum"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap().to_string())
            .collect()
    }

    /// dirge-ygm3: the main agent's instance (default) must not advertise the
    /// background-review actions in its schema.
    #[test]
    fn default_tool_hides_review_actions_from_schema() {
        let (store, _d) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();
        let actions = action_enum(&tool, &rt);
        assert!(
            !actions.iter().any(|a| a == "mark" || a == "supersede"),
            "main agent schema must omit mark/supersede: {actions:?}",
        );
        // The base actions are still all present.
        for a in [
            "view", "add", "replace", "remove", "restore", "expand", "search",
        ] {
            assert!(actions.iter().any(|x| x == a), "missing base action {a}");
        }
    }

    /// The review runner's instance exposes mark/supersede.
    #[test]
    fn review_tool_exposes_review_actions() {
        let (store, _d) = temp_store();
        let tool = MemoryTool::new(store, None, None).with_review_actions(true);
        let rt = make_runtime();
        let actions = action_enum(&tool, &rt);
        assert!(
            actions.iter().any(|a| a == "mark"),
            "mark present: {actions:?}"
        );
        assert!(
            actions.iter().any(|a| a == "supersede"),
            "supersede present: {actions:?}",
        );
    }

    /// Defense in depth: even a hand-crafted call is rejected on the main
    /// agent's (non-review) instance.
    #[test]
    fn default_tool_rejects_review_actions_at_call_layer() {
        let (store, _d) = temp_store();
        let tool = MemoryTool::new(store, None, None);
        let rt = make_runtime();
        for action in ["mark", "supersede"] {
            let err = rt
                .block_on(tool.call(action_args(action)))
                .expect_err("must be rejected");
            let msg = format!("{err:?}");
            assert!(
                msg.contains("background review"),
                "reject reason names the gate: {msg}",
            );
        }
    }

    /// The review instance can actually record an outcome.
    #[test]
    fn review_tool_accepts_mark() {
        let (store, _d) = temp_store();
        store
            .add("memory", "run cargo fmt before commit", Some("procedural"))
            .unwrap();
        let tool = MemoryTool::new(store, None, None).with_review_actions(true);
        let rt = make_runtime();
        let mut args = action_args("mark");
        args.old_text = Some("cargo fmt".into());
        args.outcome = Some("success".into());
        let out = rt
            .block_on(tool.call(args))
            .expect("mark succeeds on review tool");
        assert!(out.contains("success"), "outcome recorded: {out}");
    }

    /// `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()),
            outcome: None,
            harsh: None,
        }))
        .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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
            outcome: None,
            harsh: 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,
                    outcome: None,
                    harsh: None,
                },
                "add" => Args {
                    action: "add".into(),
                    target: "memory".into(),
                    content: Some(format!("entry-for-{}", action)),
                    old_text: None,
                    kind: None,
                    query: None,
                    scope: None,
                    outcome: None,
                    harsh: 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,
                    outcome: None,
                    harsh: None,
                },
                "remove" => Args {
                    action: "remove".into(),
                    target: "memory".into(),
                    content: None,
                    old_text: Some("entry-for-add".into()),
                    kind: None,
                    query: None,
                    scope: None,
                    outcome: None,
                    harsh: 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,
                    outcome: None,
                    harsh: 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,
                    outcome: None,
                    harsh: None,
                },
                "search" => Args {
                    action: "search".into(),
                    target: "memory".into(),
                    content: None,
                    old_text: None,
                    kind: None,
                    query: Some("seed".into()),
                    scope: None,
                    outcome: None,
                    harsh: None,
                },
                _ => unreachable!(),
            };
            let result = rt.block_on(tool.call(args));
            assert!(
                result.is_ok(),
                "prompt-advertised action '{}' failed end-to-end: {:?}",
                action,
                result
            );
        }
    }
}