engram-core 0.21.1

AI Memory Infrastructure - Persistent memory for AI agents with semantic search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
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
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
//! Harness record handler — durable cross-session memory for harness events.
//!
//! Creates permanent memory records for decisions, handoffs, failed attempts,
//! verification results, risks, assumptions, bug reproductions, and issue updates.

use serde_json::{json, Value};
use std::collections::HashMap;

use super::HandlerContext;

const VALID_KINDS: &[&str] = &[
    "decision",
    "handoff",
    "failed_attempt",
    "bug_reproduction",
    "verification_result",
    "risk",
    "assumption",
    "issue_update",
];

/// Record a durable harness event with structured metadata for cross-session continuity.
///
/// Params:
/// - `kind` (string, required): one of the 8 valid harness event kinds
/// - `summary` (string, required): 1–500 chars — stored as memory content
/// - `details` (string, optional): appended to content after a blank line
/// - `source_paths` (array of strings, optional): relevant file paths
/// - `command` (string, optional): CLI/shell command that produced evidence
/// - `issue_number` (integer, optional): GitHub issue number
/// - `commit_sha` (string, optional): git commit SHA
/// - `evidence_refs` (array of strings, optional): free-form references
/// - `importance` (float 0.0–1.0, optional, default 0.7)
/// - `workspace` (string, optional, defaults to "default")
pub fn handle_harness_record(ctx: &HandlerContext, params: Value) -> Value {
    // ── Validate kind ────────────────────────────────────────────────────────
    let kind = match params.get("kind").and_then(|v| v.as_str()) {
        Some(k) => k.to_string(),
        None => {
            return json!({
                "error": "kind is required",
                "valid_kinds": VALID_KINDS,
            })
        }
    };
    if !VALID_KINDS.contains(&kind.as_str()) {
        return json!({
            "error": format!("invalid harness kind: {}", kind),
            "valid_kinds": VALID_KINDS,
        });
    }

    // ── Validate summary ─────────────────────────────────────────────────────
    let summary = match params.get("summary").and_then(|v| v.as_str()) {
        Some(s) => s.to_string(),
        None => return json!({"error": "summary is required"}),
    };
    if summary.is_empty() {
        return json!({"error": "summary must not be empty"});
    }
    if summary.len() > 500 {
        return json!({"error": "summary must be 500 characters or fewer"});
    }

    // ── Validate importance ──────────────────────────────────────────────────
    let importance: f32 = if let Some(v) = params.get("importance") {
        match v.as_f64() {
            Some(f) if (0.0..=1.0).contains(&f) => f as f32,
            Some(_) => return json!({"error": "importance must be between 0.0 and 1.0"}),
            None => return json!({"error": "importance must be a number"}),
        }
    } else {
        0.7
    };

    // ── Extract optional params ──────────────────────────────────────────────
    let details = match params.get("details").and_then(|v| v.as_str()) {
        Some(d) if d.len() > 8000 => {
            return json!({"error": "details must be ≤ 8000 characters"});
        }
        Some(d) => Some(d.to_string()),
        None => None,
    };

    let workspace = params
        .get("workspace")
        .and_then(|v| v.as_str())
        .unwrap_or("default")
        .to_string();

    let source_paths: Vec<String> = params
        .get("source_paths")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let command = params
        .get("command")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let issue_number = params.get("issue_number").and_then(|v| v.as_i64());

    let commit_sha = params
        .get("commit_sha")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let evidence_refs: Vec<String> = params
        .get("evidence_refs")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    // ── Build content ────────────────────────────────────────────────────────
    let content = match &details {
        Some(d) => format!("{}\n\n{}", summary, d),
        None => summary.clone(),
    };

    // ── Map kind → MemoryType ────────────────────────────────────────────────
    let memory_type = kind_to_memory_type(&kind);

    // ── Build tags ───────────────────────────────────────────────────────────
    let tags = vec!["harness".to_string(), kind.clone()];

    // ── Build metadata ───────────────────────────────────────────────────────
    let mut metadata: HashMap<String, Value> = HashMap::new();
    metadata.insert("harness_kind".to_string(), json!(kind));
    metadata.insert("source_paths".to_string(), json!(source_paths));
    metadata.insert("command".to_string(), json!(command));
    metadata.insert("issue_number".to_string(), json!(issue_number));
    metadata.insert("commit_sha".to_string(), json!(commit_sha));
    metadata.insert("evidence_refs".to_string(), json!(evidence_refs));

    // ── Create memory ────────────────────────────────────────────────────────
    let input = crate::types::CreateMemoryInput {
        content,
        memory_type,
        tags: tags.clone(),
        metadata,
        importance: Some(importance),
        workspace: Some(workspace.clone()),
        tier: crate::types::MemoryTier::Permanent,
        ..Default::default()
    };

    match ctx
        .storage
        .with_transaction(|conn| crate::storage::queries::create_memory(conn, &input))
    {
        Ok(memory) => json!({
            "memory_id": memory.id,
            "kind": kind,
            "workspace": workspace,
            "summary": summary,
            "tags": tags,
            "created_at": memory.created_at.to_rfc3339(),
        }),
        Err(e) => json!({"error": format!("Failed to create memory: {}", e)}),
    }
}

/// Return a structured summary of current project state for a fresh agent.
///
/// Params:
/// - `workspace` (optional string, defaults to "default")
/// - `max_records` (optional integer, default 10, max 50)
/// - `token_budget` (optional integer, default 2000)
/// - `include_git` (optional bool, default true)
pub fn handle_harness_status(ctx: &HandlerContext, params: Value) -> Value {
    let workspace = params
        .get("workspace")
        .and_then(|v| v.as_str())
        .unwrap_or("default")
        .to_string();

    let max_records = params
        .get("max_records")
        .and_then(|v| v.as_i64())
        .unwrap_or(10)
        .min(50);

    let token_budget = params
        .get("token_budget")
        .and_then(|v| v.as_i64())
        .unwrap_or(2000) as usize;

    let include_git = params
        .get("include_git")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);

    // ── Fetch recent harness records ─────────────────────────────────────────
    let options = crate::types::ListOptions {
        tags: Some(vec!["harness".to_string()]),
        limit: Some(max_records),
        sort_by: Some(crate::types::SortField::CreatedAt),
        sort_order: Some(crate::types::SortOrder::Desc),
        workspace: Some(workspace.clone()),
        ..Default::default()
    };

    let memories = match ctx
        .storage
        .with_connection(|conn| crate::storage::queries::list_memories(conn, &options))
    {
        Ok(m) => m,
        Err(e) => return json!({"error": format!("Failed to fetch harness records: {}", e)}),
    };

    // ── Group by kind ─────────────────────────────────────────────────────────
    let mut decisions: Vec<Value> = Vec::new();
    let mut blockers: Vec<Value> = Vec::new();
    let mut last_verification: Option<Value> = None;
    let mut last_handoff: Option<Value> = None;
    let mut recent_issue_updates: Vec<Value> = Vec::new();

    for mem in &memories {
        let kind = mem
            .metadata
            .get("harness_kind")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let summary = mem.content.lines().next().unwrap_or("").to_string();
        let created_at = mem.created_at.to_rfc3339();

        match kind.as_str() {
            "decision" => {
                let commit_sha = mem
                    .metadata
                    .get("commit_sha")
                    .cloned()
                    .unwrap_or(Value::Null);
                decisions.push(json!({
                    "memory_id": mem.id,
                    "summary": summary,
                    "created_at": created_at,
                    "commit_sha": commit_sha,
                }));
            }
            "risk" | "failed_attempt" => {
                blockers.push(json!({
                    "memory_id": mem.id,
                    "kind": kind,
                    "summary": summary,
                    "created_at": created_at,
                }));
            }
            "verification_result" if last_verification.is_none() => {
                let command = mem.metadata.get("command").cloned().unwrap_or(Value::Null);
                last_verification = Some(json!({
                    "memory_id": mem.id,
                    "summary": summary,
                    "created_at": created_at,
                    "command": command,
                }));
            }
            "verification_result" => {}
            "handoff" if last_handoff.is_none() => {
                last_handoff = Some(json!({
                    "memory_id": mem.id,
                    "summary": summary,
                    "created_at": created_at,
                }));
            }
            "handoff" => {}
            "issue_update" => {
                let issue_number = mem
                    .metadata
                    .get("issue_number")
                    .cloned()
                    .unwrap_or(Value::Null);
                recent_issue_updates.push(json!({
                    "memory_id": mem.id,
                    "summary": summary,
                    "issue_number": issue_number,
                    "created_at": created_at,
                }));
            }
            _ => {}
        }
    }

    // ── Optional git state ────────────────────────────────────────────────────
    let git_state = if include_git {
        let branch = run_command("git", &["branch", "--show-current"]);
        let dirty_raw = run_command("git", &["status", "--short"]);
        let dirty_files: Option<Vec<String>> =
            dirty_raw.map(|s| s.lines().take(10).map(|l| l.to_string()).collect());
        let commits_raw = run_command("git", &["log", "--oneline", "-5"]);
        let recent_commits: Option<Vec<String>> =
            commits_raw.map(|s| s.lines().map(|l| l.to_string()).collect());
        Some(json!({
            "branch": branch,
            "dirty_files": dirty_files,
            "recent_commits": recent_commits,
        }))
    } else {
        None
    };

    // ── suggested_next_action ─────────────────────────────────────────────────
    let suggested_next_action = if !blockers.is_empty() {
        format!(
            "Resolve {} known blocker(s) before proceeding.",
            blockers.len()
        )
    } else if let Some(ref h) = last_handoff {
        let s = h["summary"].as_str().unwrap_or("");
        let preview: String = s.chars().take(60).collect();
        format!("Continue from last handoff: {}.", preview)
    } else if !decisions.is_empty() {
        format!(
            "Review {} recent decision(s) and confirm alignment.",
            decisions.len()
        )
    } else {
        "No harness context found. Run harness_record to start tracking.".to_string()
    };

    // ── Assemble and apply token budget ───────────────────────────────────────
    let generated_at = chrono::Utc::now().to_rfc3339();

    // Build response, truncating from bottom if over budget
    loop {
        // current_objective: extracted from the most recent handoff's current_goal
        let current_objective = last_handoff
            .as_ref()
            .and_then(|h| {
                h["metadata"]["current_goal"]
                    .as_str()
                    .or_else(|| h["summary"].as_str())
            })
            .map(|s| s.chars().take(200).collect::<String>());

        let candidate = json!({
            "workspace": workspace,
            "generated_at": generated_at,
            "current_objective": current_objective,
            "active_issues": recent_issue_updates,
            "recent_decisions": decisions,
            "known_blockers": blockers,
            "last_verification": last_verification,
            "last_handoff": last_handoff,
            "recent_issue_updates": recent_issue_updates,
            "git_state": git_state,
            "suggested_next_action": suggested_next_action,
        });
        let serialized = candidate.to_string();
        // Token budget enforced with chars/4 heuristic (not BPE).
        // Actual tiktoken count may differ by ~20-30%.
        let estimated_tokens = serialized.len() / 4;
        if estimated_tokens <= token_budget
            || (decisions.is_empty() && blockers.is_empty() && recent_issue_updates.is_empty())
        {
            let mut result = candidate;
            result["token_estimate"] = json!(estimated_tokens);
            return result;
        }
        // Truncate the longest list first
        if !decisions.is_empty() {
            decisions.pop();
        } else if !blockers.is_empty() {
            blockers.pop();
        } else if !recent_issue_updates.is_empty() {
            recent_issue_updates.pop();
        } else {
            break;
        }
    }

    // Fallback (should not normally be reached)
    let current_objective = last_handoff
        .as_ref()
        .and_then(|h| {
            h["metadata"]["current_goal"]
                .as_str()
                .or_else(|| h["summary"].as_str())
        })
        .map(|s| s.chars().take(200).collect::<String>());

    json!({
        "workspace": workspace,
        "generated_at": generated_at,
        "current_objective": current_objective,
        "active_issues": recent_issue_updates,
        "recent_decisions": decisions,
        "known_blockers": blockers,
        "last_verification": last_verification,
        "last_handoff": last_handoff,
        "recent_issue_updates": recent_issue_updates,
        "git_state": git_state,
        "suggested_next_action": suggested_next_action,
        "token_estimate": 0,
    })
}

/// Generate a structured handoff packet for next-agent continuity.
///
/// Params:
/// - `current_goal` (string, required, ≤300 chars)
/// - `files_touched` (array of strings, optional)
/// - `decisions_made` (array of strings, optional)
/// - `tests_run` (array of strings, optional)
/// - `tests_not_run` (array of strings, optional)
/// - `known_risks` (array of strings, optional)
/// - `blockers` (array of strings, optional)
/// - `next_steps` (array of strings, required, min 1 item)
/// - `issue_numbers` (array of integers, optional)
/// - `plan_doc_paths` (array of strings, optional)
/// - `verification_evidence` (string, optional)
/// - `persist` (bool, optional, default true)
/// - `workspace` (string, optional, defaults to "default")
pub fn handle_harness_handoff(ctx: &HandlerContext, params: Value) -> Value {
    // ── Validate current_goal ────────────────────────────────────────────────
    let current_goal = match params.get("current_goal").and_then(|v| v.as_str()) {
        Some(g) => g.to_string(),
        None => return json!({"error": "current_goal is required"}),
    };
    if current_goal.len() > 300 {
        return json!({"error": "current_goal must be 300 characters or fewer"});
    }

    // ── Validate next_steps ──────────────────────────────────────────────────
    let next_steps: Vec<String> = match params.get("next_steps").and_then(|v| v.as_array()) {
        Some(arr) => arr
            .iter()
            .filter_map(|v| v.as_str().map(String::from))
            .collect(),
        None => return json!({"error": "next_steps is required"}),
    };
    if next_steps.is_empty() {
        return json!({"error": "next_steps must have at least one item"});
    }

    // ── Extract optional params ──────────────────────────────────────────────
    let files_touched: Vec<String> = params
        .get("files_touched")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let decisions_made: Vec<String> = params
        .get("decisions_made")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let tests_run: Vec<String> = params
        .get("tests_run")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let tests_not_run: Vec<String> = params
        .get("tests_not_run")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let known_risks: Vec<String> = params
        .get("known_risks")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let blockers: Vec<String> = params
        .get("blockers")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let issue_numbers: Vec<i64> = params
        .get("issue_numbers")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|v| v.as_i64()).collect())
        .unwrap_or_default();

    let plan_doc_paths: Vec<String> = params
        .get("plan_doc_paths")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let verification_evidence = params
        .get("verification_evidence")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let persist = params
        .get("persist")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);

    let workspace = params
        .get("workspace")
        .and_then(|v| v.as_str())
        .unwrap_or("default")
        .to_string();

    // ── Completion claim ─────────────────────────────────────────────────────
    let has_evidence = verification_evidence
        .as_deref()
        .map(|s| !s.is_empty())
        .unwrap_or(false);

    // ── Persist if requested ─────────────────────────────────────────────────
    let (handoff_id, created_at, persisted) = if persist {
        // Build content (≤1000 chars)
        let steps_text: String = next_steps
            .iter()
            .map(|s| format!("- {}", s))
            .collect::<Vec<_>>()
            .join("\n");
        let full_content = format!("{}\n\nNext steps:\n{}", current_goal, steps_text);
        let content = if full_content.len() > 1000 {
            // Truncate at a char boundary to avoid panicking on multi-byte UTF-8.
            let mut boundary = 1000;
            while !full_content.is_char_boundary(boundary) {
                boundary -= 1;
            }
            full_content[..boundary].to_string()
        } else {
            full_content
        };

        let mut metadata: HashMap<String, Value> = HashMap::new();
        metadata.insert("harness_kind".to_string(), json!("handoff"));
        metadata.insert("files_touched".to_string(), json!(files_touched));
        metadata.insert("decisions_made".to_string(), json!(decisions_made));
        metadata.insert("tests_run".to_string(), json!(tests_run));
        metadata.insert("tests_not_run".to_string(), json!(tests_not_run));
        metadata.insert("known_risks".to_string(), json!(known_risks));
        metadata.insert("blockers".to_string(), json!(blockers));
        metadata.insert("issue_numbers".to_string(), json!(issue_numbers));
        metadata.insert("plan_doc_paths".to_string(), json!(plan_doc_paths));
        metadata.insert(
            "verification_evidence".to_string(),
            json!(verification_evidence),
        );

        let input = crate::types::CreateMemoryInput {
            content,
            memory_type: crate::types::MemoryType::Checkpoint,
            tags: vec!["harness".to_string(), "handoff".to_string()],
            metadata,
            importance: Some(0.9),
            workspace: Some(workspace.clone()),
            tier: crate::types::MemoryTier::Permanent,
            ..Default::default()
        };

        match ctx
            .storage
            .with_transaction(|conn| crate::storage::queries::create_memory(conn, &input))
        {
            Ok(memory) => (Some(memory.id), memory.created_at.to_rfc3339(), true),
            Err(e) => return json!({"error": format!("Failed to persist handoff: {}", e)}),
        }
    } else {
        (None, chrono::Utc::now().to_rfc3339(), false)
    };

    // ── Build response ───────────────────────────────────────────────────────
    let mut response = json!({
        "handoff_id": handoff_id,
        "workspace": workspace,
        "current_goal": current_goal,
        "files_touched": files_touched,
        "decisions_made": decisions_made,
        "tests_run": tests_run,
        "tests_not_run": tests_not_run,
        "known_risks": known_risks,
        "blockers": blockers,
        "next_steps": next_steps,
        "issue_numbers": issue_numbers,
        "plan_doc_paths": plan_doc_paths,
        "verification_evidence": verification_evidence,
        "completion_claimed": has_evidence,
        "persisted": persisted,
        "created_at": created_at,
    });

    if !has_evidence {
        response["completion_warning"] =
            json!("No verification evidence provided. Do not claim this work is complete.");
    }

    response
}

/// Record a verification command outcome with exit code, output summary, and optional evidence.
///
/// Params:
/// - `command` (string, required, ≤200 chars): the command that was run
/// - `exit_code` (integer, required): 0 = success, non-zero = failure
/// - `passed` (bool, optional): explicit pass/fail; derived from exit_code == 0 if absent
/// - `output_summary` (string, required, ≤500 chars): concise summary
/// - `evidence_path` (string, optional): path to full output file or log
/// - `evidence_hash` (string, optional): SHA256 of full output for integrity
/// - `skipped_reason` (string, optional): if skipped, why
/// - `issue_numbers` (array of integers, optional)
/// - `memory_ids` (array of integers, optional)
/// - `workspace` (string, optional, defaults to "default")
/// - `importance` (float 0.0–1.0, optional, default 0.8)
pub fn handle_harness_verify(ctx: &HandlerContext, params: Value) -> Value {
    // ── Validate command ─────────────────────────────────────────────────────
    let command = match params.get("command").and_then(|v| v.as_str()) {
        Some(c) => c.to_string(),
        None => return json!({"error": "command is required"}),
    };
    if command.is_empty() {
        return json!({"error": "command must not be empty"});
    }
    if command.len() > 200 {
        return json!({"error": "command must be 200 characters or fewer"});
    }

    // ── Validate exit_code ───────────────────────────────────────────────────
    let exit_code = match params.get("exit_code").and_then(|v| v.as_i64()) {
        Some(c) => c,
        None => return json!({"error": "exit_code is required and must be an integer"}),
    };

    // ── Validate output_summary ──────────────────────────────────────────────
    let output_summary = match params.get("output_summary").and_then(|v| v.as_str()) {
        Some(s) => s.to_string(),
        None => return json!({"error": "output_summary is required"}),
    };
    if output_summary.is_empty() {
        return json!({"error": "output_summary must not be empty"});
    }
    if output_summary.len() > 500 {
        return json!({"error": "output_summary must be 500 characters or fewer"});
    }

    // ── Validate importance ──────────────────────────────────────────────────
    let importance: f32 = if let Some(v) = params.get("importance") {
        match v.as_f64() {
            Some(f) if (0.0..=1.0).contains(&f) => f as f32,
            Some(_) => return json!({"error": "importance must be between 0.0 and 1.0"}),
            None => return json!({"error": "importance must be a number"}),
        }
    } else {
        0.8
    };

    // ── Extract optional params ──────────────────────────────────────────────
    let skipped_reason = params
        .get("skipped_reason")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let skipped = skipped_reason.is_some();

    let passed = if skipped {
        // When skipped, passed is false (not a true pass)
        params
            .get("passed")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
    } else {
        params
            .get("passed")
            .and_then(|v| v.as_bool())
            .unwrap_or(exit_code == 0)
    };

    let evidence_path = params
        .get("evidence_path")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let evidence_hash = params
        .get("evidence_hash")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let issue_numbers: Vec<i64> = params
        .get("issue_numbers")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|v| v.as_i64()).collect())
        .unwrap_or_default();

    let memory_ids: Vec<i64> = params
        .get("memory_ids")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|v| v.as_i64()).collect())
        .unwrap_or_default();

    let workspace = params
        .get("workspace")
        .and_then(|v| v.as_str())
        .unwrap_or("default")
        .to_string();

    // ── Build content ────────────────────────────────────────────────────────
    let result_label = if skipped {
        "SKIP"
    } else if passed {
        "PASS"
    } else {
        "FAIL"
    };
    let content = format!(
        "{}\n\nResult: {}\n{}",
        command, result_label, output_summary
    );

    // ── Build tags ───────────────────────────────────────────────────────────
    let mut tags = vec!["harness".to_string(), "verification_result".to_string()];
    if !passed && !skipped {
        tags.push("verification_failed".to_string());
    }
    if skipped {
        tags.push("verification_skipped".to_string());
    }

    // ── Build metadata ───────────────────────────────────────────────────────
    let mut metadata: HashMap<String, Value> = HashMap::new();
    metadata.insert("harness_kind".to_string(), json!("verification_result"));
    metadata.insert("command".to_string(), json!(command));
    metadata.insert("exit_code".to_string(), json!(exit_code));
    metadata.insert("passed".to_string(), json!(passed));
    metadata.insert("skipped".to_string(), json!(skipped));
    metadata.insert("skipped_reason".to_string(), json!(skipped_reason));
    metadata.insert("evidence_path".to_string(), json!(evidence_path));
    metadata.insert("evidence_hash".to_string(), json!(evidence_hash));
    metadata.insert("issue_numbers".to_string(), json!(issue_numbers));
    metadata.insert("memory_ids".to_string(), json!(memory_ids));

    // ── Create memory ────────────────────────────────────────────────────────
    let input = crate::types::CreateMemoryInput {
        content,
        memory_type: crate::types::MemoryType::Checkpoint,
        tags: tags.clone(),
        metadata,
        importance: Some(importance),
        workspace: Some(workspace.clone()),
        tier: crate::types::MemoryTier::Permanent,
        ..Default::default()
    };

    match ctx
        .storage
        .with_transaction(|conn| crate::storage::queries::create_memory(conn, &input))
    {
        Ok(memory) => json!({
            "memory_id": memory.id,
            "command": command,
            "exit_code": exit_code,
            "passed": passed,
            "skipped": skipped,
            "output_summary": output_summary,
            "evidence_path": evidence_path,
            "evidence_hash": evidence_hash,
            "tags": tags,
            "workspace": workspace,
            "created_at": memory.created_at.to_rfc3339(),
        }),
        Err(e) => json!({"error": format!("Failed to create memory: {}", e)}),
    }
}

/// Run a shell command and return trimmed stdout, or None on error.
///
/// # Safety
///
/// All arguments passed to this function **must be compile-time string literals**.
/// Never pass user-supplied strings as `cmd` or `args` — doing so would be an
/// OS command injection vulnerability. This function is intentionally private
/// and restricted to internal harness introspection calls (e.g., reading git
/// metadata) where both the command and arguments are hard-coded at call sites.
fn run_command(cmd: &str, args: &[&str]) -> Option<String> {
    std::process::Command::new(cmd)
        .args(args)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

fn kind_to_memory_type(kind: &str) -> crate::types::MemoryType {
    match kind {
        "decision" => crate::types::MemoryType::Decision,
        "handoff" => crate::types::MemoryType::Checkpoint,
        "failed_attempt" => crate::types::MemoryType::Learning,
        "bug_reproduction" => crate::types::MemoryType::Episodic,
        "verification_result" => crate::types::MemoryType::Checkpoint,
        "risk" => crate::types::MemoryType::Note,
        "assumption" => crate::types::MemoryType::Note,
        "issue_update" => crate::types::MemoryType::Issue,
        _ => crate::types::MemoryType::Note,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mcp::handlers::HandlerContext;
    use crate::storage::Storage;
    use std::sync::Arc;

    fn test_ctx() -> HandlerContext {
        let storage = Storage::open_in_memory().expect("open in-memory storage");
        HandlerContext {
            storage,
            embedder: Arc::new(crate::embedding::TfIdfEmbedder::new(128)),
            fuzzy_engine: Arc::new(parking_lot::Mutex::new(crate::search::FuzzyEngine::new())),
            search_config: crate::search::SearchConfig::default(),
            realtime: None,
            embedding_cache: Arc::new(crate::embedding::EmbeddingCache::default()),
            search_cache: Arc::new(crate::search::SearchResultCache::new(
                crate::search::AdaptiveCacheConfig::default(),
            )),
            #[cfg(feature = "meilisearch")]
            meili: None,
            #[cfg(feature = "meilisearch")]
            meili_indexer: None,
            #[cfg(feature = "meilisearch")]
            meili_sync_interval: 300,
            #[cfg(feature = "langfuse")]
            langfuse_runtime: Arc::new(
                tokio::runtime::Builder::new_current_thread()
                    .build()
                    .unwrap(),
            ),
        }
    }

    #[test]
    fn test_decision_record_returns_memory_id_and_tags() {
        let ctx = test_ctx();
        let result = handle_harness_record(
            &ctx,
            json!({
                "kind": "decision",
                "summary": "Use SQLite for storage layer",
            }),
        );
        assert!(result.get("memory_id").is_some(), "should return memory_id");
        assert_eq!(result["kind"], "decision");
        let tags = result["tags"].as_array().unwrap();
        assert!(tags.iter().any(|t| t == "harness"));
        assert!(tags.iter().any(|t| t == "decision"));
    }

    #[test]
    fn test_failed_attempt_record_tags_and_type() {
        let ctx = test_ctx();
        let result = handle_harness_record(
            &ctx,
            json!({
                "kind": "failed_attempt",
                "summary": "Tried using DuckDB but it caused compile errors",
            }),
        );
        assert!(result.get("memory_id").is_some());
        let tags = result["tags"].as_array().unwrap();
        assert!(tags.iter().any(|t| t == "harness"));
        assert!(tags.iter().any(|t| t == "failed_attempt"));
    }

    #[test]
    fn test_verification_result_record() {
        let ctx = test_ctx();
        let result = handle_harness_record(
            &ctx,
            json!({
                "kind": "verification_result",
                "summary": "All 858 tests pass after refactor",
            }),
        );
        assert!(result.get("memory_id").is_some());
        let tags = result["tags"].as_array().unwrap();
        assert!(tags.iter().any(|t| t == "harness"));
        assert!(tags.iter().any(|t| t == "verification_result"));
    }

    #[test]
    fn test_invalid_kind_returns_error_with_valid_kinds() {
        let ctx = test_ctx();
        let result = handle_harness_record(
            &ctx,
            json!({
                "kind": "not_a_kind",
                "summary": "Something",
            }),
        );
        assert!(result.get("error").is_some());
        let error = result["error"].as_str().unwrap();
        assert!(error.contains("invalid harness kind"));
        assert!(result.get("valid_kinds").is_some());
    }

    #[test]
    fn test_empty_summary_returns_error() {
        let ctx = test_ctx();
        let result = handle_harness_record(
            &ctx,
            json!({
                "kind": "decision",
                "summary": "",
            }),
        );
        assert!(result.get("error").is_some());
    }

    #[test]
    fn test_summary_over_500_chars_returns_error() {
        let ctx = test_ctx();
        let long_summary = "x".repeat(501);
        let result = handle_harness_record(
            &ctx,
            json!({
                "kind": "decision",
                "summary": long_summary,
            }),
        );
        assert!(result.get("error").is_some());
        let error = result["error"].as_str().unwrap();
        assert!(error.contains("500"));
    }

    #[test]
    fn test_metadata_fields_stored_correctly() {
        let ctx = test_ctx();
        let result = handle_harness_record(
            &ctx,
            json!({
                "kind": "bug_reproduction",
                "summary": "Crash on empty input",
                "source_paths": ["src/lib.rs", "src/main.rs"],
                "command": "cargo test -- test_empty",
                "issue_number": 42,
                "commit_sha": "abc1234",
                "evidence_refs": ["https://github.com/org/repo/issues/42"],
            }),
        );
        assert!(
            result.get("memory_id").is_some(),
            "expected memory_id, got: {}",
            result
        );
        // Memory was created — verify the memory_id is a number
        assert!(result["memory_id"].as_i64().is_some());
    }

    #[test]
    fn test_importance_defaults_to_0_7() {
        let ctx = test_ctx();
        let result = handle_harness_record(
            &ctx,
            json!({
                "kind": "risk",
                "summary": "External API may rate-limit us",
            }),
        );
        // If no error, importance defaulted correctly
        assert!(result.get("memory_id").is_some());
    }

    #[test]
    fn test_importance_out_of_range_returns_error() {
        let ctx = test_ctx();
        let result = handle_harness_record(
            &ctx,
            json!({
                "kind": "decision",
                "summary": "Some decision",
                "importance": 1.5,
            }),
        );
        assert!(result.get("error").is_some());
    }

    // ── harness_status tests ────────────────────────────────────────────────

    #[test]
    fn test_harness_status_empty_workspace() {
        let ctx = test_ctx();
        let result = handle_harness_status(&ctx, json!({"workspace": "test_empty_ws"}));
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        assert_eq!(result["workspace"], "test_empty_ws");
        assert!(result["recent_decisions"].as_array().unwrap().is_empty());
        assert!(result["known_blockers"].as_array().unwrap().is_empty());
        assert!(result["recent_issue_updates"]
            .as_array()
            .unwrap()
            .is_empty());
        assert!(result.get("token_estimate").is_some());
        let suggestion = result["suggested_next_action"].as_str().unwrap();
        assert!(
            suggestion.contains("No harness context"),
            "got: {}",
            suggestion
        );
    }

    #[test]
    fn test_harness_status_with_decisions() {
        let ctx = test_ctx();
        let ws = "test_decisions_ws";
        handle_harness_record(
            &ctx,
            json!({"kind": "decision", "summary": "Use SQLite", "workspace": ws}),
        );
        handle_harness_record(
            &ctx,
            json!({"kind": "decision", "summary": "Use Axum", "workspace": ws}),
        );
        let result = handle_harness_status(&ctx, json!({"workspace": ws}));
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        let decisions = result["recent_decisions"].as_array().unwrap();
        assert_eq!(decisions.len(), 2, "expected 2 decisions, got: {}", result);
        assert!(decisions[0].get("memory_id").is_some());
        assert!(decisions[0].get("summary").is_some());
    }

    #[test]
    fn test_harness_status_with_blocker() {
        let ctx = test_ctx();
        let ws = "test_blocker_ws";
        handle_harness_record(
            &ctx,
            json!({"kind": "risk", "summary": "DB migration may fail", "workspace": ws}),
        );
        let result = handle_harness_status(&ctx, json!({"workspace": ws}));
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        let blockers = result["known_blockers"].as_array().unwrap();
        assert_eq!(blockers.len(), 1);
        let suggestion = result["suggested_next_action"].as_str().unwrap();
        assert!(
            suggestion.to_lowercase().contains("blocker"),
            "got: {}",
            suggestion
        );
    }

    #[test]
    fn test_harness_status_no_git() {
        let ctx = test_ctx();
        let result = handle_harness_status(&ctx, json!({"include_git": false}));
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        assert!(result["git_state"].is_null());
    }

    #[test]
    fn test_harness_status_token_budget() {
        let ctx = test_ctx();
        let ws = "test_budget_ws";
        for i in 0..20 {
            handle_harness_record(
                &ctx,
                json!({
                    "kind": "decision",
                    "summary": format!("Decision number {} with some content to pad size", i),
                    "workspace": ws,
                }),
            );
        }
        let result = handle_harness_status(&ctx, json!({"workspace": ws, "token_budget": 200}));
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        let decisions = result["recent_decisions"].as_array().unwrap();
        assert!(
            decisions.len() < 20,
            "expected truncation, got {} decisions",
            decisions.len()
        );
    }

    // ── harness_handoff tests ────────────────────────────────────────────────

    #[test]
    fn test_harness_handoff_basic() {
        let ctx = test_ctx();
        let result = handle_harness_handoff(
            &ctx,
            json!({
                "current_goal": "Implement search index v2",
                "files_touched": ["src/search.rs", "src/index.rs"],
                "decisions_made": ["Use BM25 scoring"],
                "tests_run": ["cargo test --lib"],
                "next_steps": ["Review PR #34", "Run full CI"],
                "verification_evidence": "873 tests passed",
            }),
        );
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        assert!(
            result["handoff_id"].as_i64().is_some(),
            "expected handoff_id, got: {}",
            result
        );
        assert_eq!(result["completion_claimed"], true);
        assert_eq!(result["persisted"], true);
        assert_eq!(result["current_goal"], "Implement search index v2");
    }

    #[test]
    fn test_harness_handoff_no_verification_evidence() {
        let ctx = test_ctx();
        let result = handle_harness_handoff(
            &ctx,
            json!({
                "current_goal": "Fix bug in parser",
                "next_steps": ["Run cargo test"],
            }),
        );
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        assert_eq!(result["completion_claimed"], false);
        assert!(result["completion_warning"].as_str().is_some());
        let warning = result["completion_warning"].as_str().unwrap();
        assert!(
            warning.contains("No verification evidence"),
            "got: {}",
            warning
        );
    }

    #[test]
    fn test_harness_handoff_no_persist() {
        let ctx = test_ctx();
        let result = handle_harness_handoff(
            &ctx,
            json!({
                "current_goal": "Draft only handoff",
                "next_steps": ["Check logs"],
                "persist": false,
            }),
        );
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        assert!(
            result["handoff_id"].is_null(),
            "expected null handoff_id, got: {}",
            result
        );
        assert_eq!(result["persisted"], false);
    }

    #[test]
    fn test_harness_handoff_missing_goal() {
        let ctx = test_ctx();
        let result = handle_harness_handoff(
            &ctx,
            json!({
                "next_steps": ["Do something"],
            }),
        );
        assert!(
            result.get("error").is_some(),
            "expected error, got: {}",
            result
        );
    }

    #[test]
    fn test_harness_handoff_empty_next_steps() {
        let ctx = test_ctx();
        let result = handle_harness_handoff(
            &ctx,
            json!({
                "current_goal": "Some goal",
                "next_steps": [],
            }),
        );
        assert!(
            result.get("error").is_some(),
            "expected error, got: {}",
            result
        );
    }

    // ── harness_verify tests ────────────────────────────────────────────────

    #[test]
    fn test_harness_verify_pass() {
        let ctx = test_ctx();
        let result = handle_harness_verify(
            &ctx,
            json!({
                "command": "cargo test --lib",
                "exit_code": 0,
                "output_summary": "873 tests passed, 0 failed",
            }),
        );
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        assert!(
            result["memory_id"].as_i64().is_some(),
            "expected memory_id, got: {}",
            result
        );
        assert_eq!(result["passed"], true);
        assert_eq!(result["skipped"], false);
        assert_eq!(result["command"], "cargo test --lib");
        let tags = result["tags"].as_array().unwrap();
        assert!(tags.iter().any(|t| t == "verification_result"));
        assert!(tags.iter().any(|t| t == "harness"));
    }

    #[test]
    fn test_harness_verify_fail() {
        let ctx = test_ctx();
        let result = handle_harness_verify(
            &ctx,
            json!({
                "command": "cargo test --lib",
                "exit_code": 1,
                "output_summary": "2 tests failed",
            }),
        );
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        assert_eq!(result["passed"], false);
        let tags = result["tags"].as_array().unwrap();
        assert!(tags.iter().any(|t| t == "verification_failed"));
    }

    #[test]
    fn test_harness_verify_skipped() {
        let ctx = test_ctx();
        let result = handle_harness_verify(
            &ctx,
            json!({
                "command": "cargo bench",
                "exit_code": 0,
                "output_summary": "benchmark skipped in CI",
                "skipped_reason": "benchmarks not run in CI environment",
            }),
        );
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        assert_eq!(result["skipped"], true);
        let tags = result["tags"].as_array().unwrap();
        assert!(tags.iter().any(|t| t == "verification_skipped"));
        // Content should contain SKIP label
        // We check via the output_summary field
        assert_eq!(result["output_summary"], "benchmark skipped in CI");
    }

    #[test]
    fn test_harness_verify_missing_command() {
        let ctx = test_ctx();
        let result = handle_harness_verify(
            &ctx,
            json!({
                "exit_code": 0,
                "output_summary": "all good",
            }),
        );
        assert!(
            result.get("error").is_some(),
            "expected error, got: {}",
            result
        );
    }

    #[test]
    fn test_harness_verify_missing_output_summary() {
        let ctx = test_ctx();
        let result = handle_harness_verify(
            &ctx,
            json!({
                "command": "cargo test",
                "exit_code": 0,
            }),
        );
        assert!(
            result.get("error").is_some(),
            "expected error, got: {}",
            result
        );
    }

    #[test]
    fn test_harness_verify_with_evidence() {
        let ctx = test_ctx();
        let result = handle_harness_verify(
            &ctx,
            json!({
                "command": "cargo test",
                "exit_code": 0,
                "output_summary": "873 passed",
                "evidence_path": "/tmp/test-output.log",
                "evidence_hash": "abc123def456",
                "issue_numbers": [37, 42],
                "memory_ids": [100, 200],
            }),
        );
        assert!(
            result.get("error").is_none(),
            "unexpected error: {}",
            result
        );
        assert_eq!(result["evidence_path"], "/tmp/test-output.log");
        assert_eq!(result["evidence_hash"], "abc123def456");
        assert!(result["memory_id"].as_i64().is_some());
    }

    #[test]
    fn test_tier_is_always_permanent() {
        // Verify via kind_to_memory_type that all kinds are handled,
        // and the tier field is set to Permanent in CreateMemoryInput.
        // This is structural — if it compiled and saved successfully
        // with tier=Permanent, the record creation passed.
        let ctx = test_ctx();
        for kind in VALID_KINDS {
            let result = handle_harness_record(
                &ctx,
                json!({
                    "kind": kind,
                    "summary": format!("Test for kind {}", kind),
                }),
            );
            assert!(
                result.get("memory_id").is_some(),
                "kind {} should succeed, got: {}",
                kind,
                result
            );
        }
    }
}