aidaemon 0.9.32

A personal AI agent that runs as a background daemon, accessible via Telegram, Slack, or Discord, with tool use, MCP integration, and persistent memory
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
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;

use chrono::Utc;
use once_cell::sync::Lazy;
use regex::Regex;
use tracing::warn;

use crate::traits::StateStore;

use super::{extract_key_error_line, semantic_failure_limit, MAX_CONSECUTIVE_SAME_TOOL};

/// Context accumulated during handle_message for post-task learning.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum ReplayNoteCategory {
    PlanRevision,
    EvidenceGate,
    ValidationFailure,
    RetryReason,
}

impl ReplayNoteCategory {
    fn as_str(&self) -> &'static str {
        match self {
            Self::PlanRevision => "plan_revision",
            Self::EvidenceGate => "evidence_gate",
            Self::ValidationFailure => "validation_failure",
            Self::RetryReason => "retry_reason",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ReplayNote {
    pub(super) category: ReplayNoteCategory,
    pub(super) code: String,
    pub(super) summary: String,
    pub(super) blocking: bool,
}

#[derive(Clone)]
pub(super) struct LearningContext {
    pub(super) user_text: String,
    pub(super) intent_domains: Vec<String>,
    pub(super) tool_calls: Vec<String>,     // "tool_name(summary)"
    pub(super) errors: Vec<(String, bool)>, // (error_text, was_recovered)
    pub(super) first_error: Option<String>,
    pub(super) recovery_actions: Vec<String>,
    #[allow(dead_code)] // Reserved for duration-based learning
    pub(super) start_time: chrono::DateTime<Utc>,
    pub(super) completed_naturally: bool,
    pub(super) explicit_positive_signals: u32,
    pub(super) explicit_negative_signals: u32,
    pub(super) replay_notes: Vec<ReplayNote>,
}

impl LearningContext {
    pub(super) fn record_replay_note(
        &mut self,
        category: ReplayNoteCategory,
        code: impl Into<String>,
        summary: impl Into<String>,
        blocking: bool,
    ) {
        const MAX_REPLAY_NOTES: usize = 24;

        let code = code.into().trim().to_string();
        let summary = summary.into().trim().to_string();
        if code.is_empty() || summary.is_empty() {
            return;
        }

        let note = ReplayNote {
            category,
            code,
            summary,
            blocking,
        };
        if self.replay_notes.contains(&note) {
            return;
        }
        if self.replay_notes.len() >= MAX_REPLAY_NOTES {
            self.replay_notes.remove(0);
        }
        self.replay_notes.push(note);
    }
}

/// Process learning from a completed task - runs in background.
pub(super) async fn process_learning(
    state: &Arc<dyn StateStore>,
    ctx: LearningContext,
) -> anyhow::Result<()> {
    use crate::memory::{expertise, procedures};

    // Determine if task was successful
    let unrecovered_errors = ctx
        .errors
        .iter()
        .filter(|(_, recovered)| !recovered)
        .count();
    let task_success = if ctx.explicit_negative_signals > 0 {
        false
    } else if ctx.explicit_positive_signals > 0 {
        true
    } else {
        ctx.completed_naturally && unrecovered_errors == 0
    };

    // 1. Update expertise for detected domains
    let domains = expertise::detect_domains(&ctx.intent_domains);
    for domain in &domains {
        let error = if !task_success {
            ctx.errors.first().map(|(e, _)| e.as_str())
        } else {
            None
        };
        if let Err(e) = state.increment_expertise(domain, task_success, error).await {
            warn!(domain = %domain, error = %e, "Failed to update expertise");
        }
    }

    // 2. Save procedure evidence for both successful and failed workflows.
    // This lets us accumulate failure_count for repeated bad paths.
    if ctx.tool_calls.len() >= 2 {
        let generalized = procedures::generalize_procedure(&ctx.tool_calls);
        let base_name = procedures::generate_procedure_name(&ctx.user_text);
        let keyed_name = procedures::generate_procedure_keyed_name(&base_name, &generalized);
        let procedure = procedures::create_procedure_with_outcome(
            keyed_name,
            procedures::extract_trigger_pattern(&ctx.user_text),
            generalized,
            task_success,
        );
        if let Err(e) = state.upsert_procedure(&procedure).await {
            warn!(procedure = %procedure.name, error = %e, "Failed to save procedure");
        }
    }

    // 3. Learn error-solution if error was recovered
    if let Some(error) = ctx.first_error.clone() {
        if !ctx.recovery_actions.is_empty() {
            let solution = procedures::create_error_solution(
                procedures::extract_error_pattern(&error),
                domains.into_iter().next(),
                procedures::summarize_solution(&ctx.recovery_actions),
                Some(ctx.recovery_actions.clone()),
            );
            if let Err(e) = state.insert_error_solution(&solution).await {
                warn!(error_pattern = %solution.error_pattern, error = %e, "Failed to save error solution");
            }
        }
    }

    if !ctx.replay_notes.is_empty() {
        record_reasoning_failure_patterns(state, &ctx, task_success).await;
    }

    Ok(())
}

async fn record_reasoning_failure_patterns(
    state: &Arc<dyn StateStore>,
    ctx: &LearningContext,
    task_success: bool,
) {
    let mut seen: HashSet<(String, String)> = HashSet::new();
    for note in ctx.replay_notes.iter().filter(|note| note.blocking) {
        let trigger_context = format!("{}:{}", note.category.as_str(), note.code);
        let action = reasoning_action_for_note(note);
        if !seen.insert((trigger_context.clone(), action.to_string())) {
            continue;
        }

        let confidence = reasoning_confidence_for_note(note, task_success);
        if let Err(e) = state
            .record_behavior_pattern(
                "reasoning_failure",
                &note.summary,
                Some(&trigger_context),
                Some(action),
                confidence,
                1,
            )
            .await
        {
            warn!(
                trigger_context = %trigger_context,
                action = %action,
                error = %e,
                "Failed to save reasoning failure pattern"
            );
        }
    }
}

fn reasoning_action_for_note(note: &ReplayNote) -> &'static str {
    match note.code.as_str() {
        "missing_pre_execution_evidence" => "gather_direct_evidence_before_mutation",
        "plan_rejected" => "replan_first_risky_step_before_execution",
        "critique_rejected" => "address_critique_and_replan",
        "target_scope_violation" => "confirm_target_scope_before_mutation",
        "tool_contract_violation" => "fix_tool_arguments_before_retry",
        "contradictory_file_evidence" => "recheck_conflicting_state_before_completion",
        "verification_pending" => "run_verification_before_claiming_success",
        "verification_unavailable_in_phase" => "surface_partial_result_until_verification_can_run",
        "validation_budget_exhausted" => "reduce_scope_when_validation_budget_exhausts",
        "execution_budget_exhausted" => "reduce_scope_or_abandon_when_execution_budget_exhausts",
        "retry_step" => "retry_only_when_failure_is_local_and_correctable",
        "replan_required" => "replan_after_logic_or_environment_failure",
        _ => "review_reasoning_trace_before_retry",
    }
}

fn reasoning_confidence_for_note(note: &ReplayNote, task_success: bool) -> f32 {
    let base = match note.code.as_str() {
        "missing_pre_execution_evidence" | "verification_pending" => 0.78,
        "target_scope_violation" => 0.84,
        "plan_rejected" | "critique_rejected" => 0.72,
        "contradictory_file_evidence" => 0.76,
        "validation_budget_exhausted" | "execution_budget_exhausted" => 0.68,
        "retry_step" | "replan_required" => 0.58,
        _ => 0.52,
    };
    if task_success {
        (base - 0.08_f32).clamp(0.25_f32, 0.96_f32)
    } else {
        (base + 0.06_f32).clamp(0.25_f32, 0.96_f32)
    }
}

#[allow(dead_code)] // Used by targeted replay/learning tests and future replay surfacing.
pub(in crate::agent) fn summarize_replay_notes(notes: &[ReplayNote]) -> String {
    if notes.is_empty() {
        return String::new();
    }

    let mut grouped: BTreeMap<&'static str, Vec<String>> = BTreeMap::new();
    for note in notes {
        grouped
            .entry(note.category.as_str())
            .or_default()
            .push(note.summary.clone());
    }

    let mut sections = Vec::new();
    for (category, items) in grouped {
        let unique: Vec<String> = items.into_iter().fold(Vec::new(), |mut acc, item| {
            if !acc.contains(&item) {
                acc.push(item);
            }
            acc
        });
        if unique.is_empty() {
            continue;
        }
        sections.push(format!("{}: {}", category, unique.join(" | ")));
    }
    sections.join("\n")
}

/// Classify the stall cause from recent errors for actionable guidance.
pub(super) fn classify_stall(
    learning_ctx: &LearningContext,
    deferred_no_tool_error_marker: &str,
    tool_failure_count: &HashMap<String, usize>,
) -> (&'static str, &'static str) {
    let any_locked = tool_failure_count
        .iter()
        .any(|(name, count)| *count >= semantic_failure_limit(name));
    if any_locked {
        return (
            "Tool Locked Out",
            "I ran into repeated errors with a command and got locked out. Try rephrasing or specifying the exact command to use.",
        );
    }

    let recent_errors: String = learning_ctx
        .errors
        .iter()
        .rev()
        .take(5)
        .map(|(e, _)| e.to_lowercase())
        .collect::<Vec<_>>()
        .join(" ");

    if recent_errors.contains("rate limit") || recent_errors.contains("429") {
        (
            "Rate Limited",
            "I'm being rate-limited right now. Try again in a few minutes.",
        )
    } else if recent_errors.contains("timed out") || recent_errors.contains("timeout") {
        (
            "Timeout",
            "Responses are taking too long right now. This usually resolves on its own -- try again shortly, or try a simpler request.",
        )
    } else if recent_errors.contains("network") || recent_errors.contains("connection") {
        (
            "Network Error",
            "There seems to be a connectivity issue. Check your network connection and try again.",
        )
    } else if is_tool_policy_block(&recent_errors) {
        (
            "Tool Policy Block",
            "A step was blocked by safety policy. Try adjusting the request or running the blocked command yourself.",
        )
    } else if is_edit_target_drift(&recent_errors) {
        (
            "Edit Target Drift",
            "I had trouble editing files because the content changed while I was working. Try again so I can re-read the files first.",
        )
    } else if looks_like_provider_server_error(&recent_errors) {
        (
            "Server Error",
            "I'm experiencing temporary server issues. Try again in a few minutes.",
        )
    } else if recent_errors.contains("unknown tool") {
        (
            "Unknown Tool",
            "Something went wrong on my end. This usually resolves on retry -- try again, or rephrase your request.",
        )
    } else if recent_errors.contains("unauthorized")
        || recent_errors.contains("api key")
        || recent_errors.contains("authentication failed")
        || recent_errors.contains("invalid auth")
    {
        (
            "Authentication",
            "There may be an issue with API credentials. Check your provider configuration.",
        )
    } else if recent_errors.contains(deferred_no_tool_error_marker) {
        (
            "Deferred No-Tool Loop",
            "I'm having trouble processing this request. Could you try rephrasing it or breaking it into smaller steps?",
        )
    } else {
        (
            "Stuck",
            "Try rephrasing your request or providing more specific guidance.",
        )
    }
}

fn is_tool_policy_block(recent_errors: &str) -> bool {
    recent_errors.contains("not in the safe command list")
        || recent_errors.contains("safe command list")
        || recent_errors.contains("use 'terminal' for this command")
        || recent_errors.contains("requires approval")
        || recent_errors.contains("not allowed")
}

fn is_edit_target_drift(recent_errors: &str) -> bool {
    recent_errors.contains("text not found in")
        || recent_errors.contains("text not found")
        || recent_errors.contains("search string not found")
        || recent_errors.contains("needle not found")
}

fn looks_like_provider_server_error(recent_errors: &str) -> bool {
    const PROVIDER_SERVER_PATTERNS: &[&str] = &[
        "internal server error",
        "bad gateway",
        "service unavailable",
        "gateway timeout",
        "status code 500",
        "status code: 500",
        "status 500",
        "http 500",
        "status code 502",
        "status code: 502",
        "status 502",
        "http 502",
        "status code 503",
        "status code: 503",
        "status 503",
        "http 503",
    ];
    if PROVIDER_SERVER_PATTERNS
        .iter()
        .any(|needle| recent_errors.contains(needle))
    {
        return true;
    }

    let mentions_provider = ["provider", "openai", "anthropic", "api", "llm"]
        .iter()
        .any(|needle| recent_errors.contains(needle));
    mentions_provider && recent_errors.contains("server error")
}

fn user_friendly_tool_description(tool_name: &str) -> &'static str {
    match tool_name {
        "terminal" => "command execution",
        "web_search" | "web_fetch" => "web access",
        "http_request" => "API access",
        "cli_agent" => "external agent",
        "edit_file" | "write_file" | "read_file" => "file operations",
        "browser" => "browser interaction",
        _ => "other capability",
    }
}

pub(super) fn format_tool_failure_summary(tool_failure_count: &HashMap<String, usize>) -> String {
    let blocked_labels: BTreeSet<&'static str> = tool_failure_count
        .iter()
        .filter(|(name, count)| **count >= semantic_failure_limit(name))
        .map(|(name, _)| user_friendly_tool_description(name))
        .collect();

    if blocked_labels.is_empty() {
        return String::new();
    }

    let mut summary = String::from("Blocked capabilities due to repeated errors:\n");
    for label in blocked_labels {
        summary.push_str("- ");
        summary.push_str(label);
        summary.push('\n');
    }
    summary.push('\n');
    summary
}

/// Graceful response when task timeout is reached.
pub(super) fn graceful_timeout_response(
    learning_ctx: &LearningContext,
    elapsed: Duration,
) -> String {
    let activity = categorize_tool_calls(&learning_ctx.tool_calls);
    let mut summary = format!(
        "I've been working on this for {} minutes and reached the time limit. \
            Here's what I accomplished so far:\n\n{}\
            The task may be incomplete. You can ask me to continue where I left off or try breaking it into smaller parts.",
        elapsed.as_secs() / 60,
        activity,
    );
    if summary.len() > 1500 {
        let mut t = 1500;
        while t > 0 && !summary.is_char_boundary(t) {
            t -= 1;
        }
        summary.truncate(t);
        summary.push('');
    }
    summary
}

/// Graceful response when task token budget is exhausted.
pub(super) fn graceful_budget_response(
    learning_ctx: &LearningContext,
    _tokens_used: u64,
) -> String {
    let activity = categorize_tool_calls(&learning_ctx.tool_calls);
    let mut summary = format!(
        "I've reached my processing limit for this task. \
            Here's what I accomplished so far:\n\n{}\
            The task may be incomplete. You can ask me to continue where I left off.",
        activity,
    );
    // Cap to avoid bloating conversation history while preserving key context.
    if summary.len() > 1500 {
        let mut t = 1500;
        while t > 0 && !summary.is_char_boundary(t) {
            t -= 1;
        }
        summary.truncate(t);
        summary.push('');
    }
    summary
}

/// Graceful response when a scheduled run hits its per-run budget.
pub(super) fn graceful_scheduled_run_budget_response(
    learning_ctx: &LearningContext,
    tokens_used: i64,
    budget_per_check: i64,
) -> String {
    let activity = categorize_tool_calls(&learning_ctx.tool_calls);
    let mut summary = format!(
        "This scheduled run hit its per-run processing budget (used {} / {} tokens). \
            Here's what I accomplished so far:\n\n{}\
            The run stopped because it no longer looked productive enough to keep extending automatically. \
            If this task legitimately needs more room, raise `budget_per_check`.",
        tokens_used, budget_per_check, activity,
    );
    if summary.len() > 1500 {
        let mut t = 1500;
        while t > 0 && !summary.is_char_boundary(t) {
            t -= 1;
        }
        summary.truncate(t);
        summary.push('');
    }
    summary
}

/// Graceful response when a goal hits its daily token budget.
pub(super) fn graceful_goal_daily_budget_response(
    learning_ctx: &LearningContext,
    tokens_used_today: i64,
    budget_daily: i64,
    is_scheduled_goal: bool,
) -> String {
    let tool_count = learning_ctx.tool_calls.len();
    let error_count = learning_ctx.errors.len();
    let next_reset = Utc::now()
        .date_naive()
        .succ_opt()
        .and_then(|d| d.and_hms_opt(0, 0, 0))
        .map(|dt| dt.format("%B %-d, %Y 00:00 UTC").to_string())
        .unwrap_or_else(|| "the next UTC day boundary".to_string());
    let scope = if is_scheduled_goal {
        "This scheduled goal hit its daily processing budget"
    } else {
        "This goal hit its daily processing budget"
    };
    let mut msg = format!(
        "{} (used {} / {} tokens). The budget resets at {}. ",
        scope, tokens_used_today, budget_daily, next_reset
    );
    if tool_count > 0 || error_count > 0 {
        msg.push_str(&format!(
            "Here's what I accomplished so far: {} steps completed",
            tool_count
        ));
        if error_count > 0 {
            msg.push_str(&format!(", {} issues encountered", error_count));
        }
        msg.push_str(".\n\n");
    }
    if is_scheduled_goal {
        msg.push_str(
            "To prevent this, raise the scheduled goal's `budget_daily` or reduce how often it runs.",
        );
    } else {
        msg.push_str("You can ask me to continue this later, or increase the goal's daily budget.");
    }
    msg
}

/// Graceful response when agent is stalled (no progress).
pub(super) fn graceful_stall_response(
    learning_ctx: &LearningContext,
    sent_file_successfully: bool,
    deferred_no_tool_error_marker: &str,
    tool_failure_count: &HashMap<String, usize>,
) -> String {
    let (_label, suggestion) = classify_stall(
        learning_ctx,
        deferred_no_tool_error_marker,
        tool_failure_count,
    );
    let activity = categorize_tool_calls(&learning_ctx.tool_calls);
    let error_explanation = format_error_explanation(&learning_ctx.errors);
    let failure_summary = format_tool_failure_summary(tool_failure_count);
    if sent_file_successfully {
        let mut msg = String::from(
            "I sent the requested file(s), but ran into issues with the remaining steps.\n\n",
        );
        if !activity.is_empty() {
            msg.push_str(&activity);
        }
        if !error_explanation.is_empty() {
            msg.push_str(&error_explanation);
        }
        if !failure_summary.is_empty() {
            msg.push_str(&failure_summary);
        }
        msg.push_str(suggestion);
        msg
    } else {
        let mut msg = String::from("I wasn't able to complete this task.\n\n");
        if !activity.is_empty() {
            msg.push_str(&activity);
            msg.push('\n');
        }
        if !error_explanation.is_empty() {
            msg.push_str(&error_explanation);
        }
        if !failure_summary.is_empty() {
            msg.push_str(&failure_summary);
        }
        msg.push_str(suggestion);
        msg
    }
}

/// Graceful response when agent stalled after making meaningful progress.
pub(super) fn graceful_partial_stall_response(
    learning_ctx: &LearningContext,
    sent_file_successfully: bool,
    deferred_no_tool_error_marker: &str,
    tool_failure_count: &HashMap<String, usize>,
) -> String {
    let (_label, suggestion) = classify_stall(
        learning_ctx,
        deferred_no_tool_error_marker,
        tool_failure_count,
    );
    let activity = categorize_tool_calls(&learning_ctx.tool_calls);
    let error_explanation = format_error_explanation(&learning_ctx.errors);
    let failure_summary = format_tool_failure_summary(tool_failure_count);
    if sent_file_successfully {
        let mut msg = String::from(
            "I completed the main deliverable but wasn't able to finish everything.\n\n",
        );
        if !activity.is_empty() {
            msg.push_str(&activity);
        }
        if !error_explanation.is_empty() {
            msg.push_str(&error_explanation);
        }
        if !failure_summary.is_empty() {
            msg.push_str(&failure_summary);
        }
        msg.push_str(suggestion);
        msg
    } else {
        let mut msg =
            String::from("I made some progress but wasn't able to fully complete the task.\n\n");
        if !activity.is_empty() {
            msg.push_str(&activity);
            msg.push('\n');
        }
        if !error_explanation.is_empty() {
            msg.push_str(&error_explanation);
        }
        if !failure_summary.is_empty() {
            msg.push_str(&failure_summary);
        }
        msg.push_str(suggestion);
        msg
    }
}

/// Graceful response when repetitive tool calls are detected.
pub(super) fn graceful_repetitive_response(
    learning_ctx: &LearningContext,
    _tool_name: &str,
) -> String {
    let activity = categorize_tool_calls(&learning_ctx.tool_calls);
    let error_explanation = format_error_explanation(&learning_ctx.errors);
    let mut msg = String::from("I seem to be stuck on this task.\n\n");
    if !activity.is_empty() {
        msg.push_str("Here's what I've done so far:\n");
        msg.push_str(&activity);
        msg.push('\n');
    }
    if !error_explanation.is_empty() {
        msg.push_str(&error_explanation);
    }
    msg.push_str("Could you try a different approach or provide more specific instructions?");
    msg
}

/// Graceful response when hard iteration cap is reached (legacy mode).
pub(super) fn graceful_cap_response(learning_ctx: &LearningContext, _iterations: usize) -> String {
    let activity = categorize_tool_calls(&learning_ctx.tool_calls);
    let mut summary = format!(
        "I've reached my processing limit for this task. \
            Here's what I accomplished so far:\n\n{}\
            The task may be incomplete. You can ask me to continue where I left off or try breaking it into smaller parts.",
        activity,
    );
    if summary.len() > 1500 {
        let mut t = 1500;
        while t > 0 && !summary.is_char_boundary(t) {
            t -= 1;
        }
        summary.truncate(t);
        summary.push('');
    }
    summary
}

/// Determine whether the current task execution is making productive progress,
/// warranting a token budget auto-extension.
///
/// Criteria:
/// 1. At most one stall detected (`stall_count <= 1`)
/// 2. Same-tool repetition: if count ≥ `MAX_CONSECUTIVE_SAME_TOOL`, check diversity
///    (`unique * 2 > count`); if not diverse OR count ≥ `MAX_CONSECUTIVE_SAME_TOOL + 4`
///    → not productive
/// 3. Error rate: unrecovered errors * 2 < max(1, total_successful)
/// 4. Minimum 3 successful tool calls
pub(super) fn is_productive(
    learning_ctx: &LearningContext,
    stall_count: usize,
    consecutive_same_tool_count: usize,
    consecutive_same_tool_unique_args: usize,
    total_successful_tool_calls: usize,
) -> bool {
    // 1. Allow one transient stall (e.g., provider timeout) before disqualifying.
    if stall_count > 1 {
        return false;
    }

    // 2. Same-tool repetition check
    let diverse_limit = MAX_CONSECUTIVE_SAME_TOOL + 4;
    if consecutive_same_tool_count >= diverse_limit {
        return false;
    }
    if consecutive_same_tool_count >= MAX_CONSECUTIVE_SAME_TOOL {
        let is_diverse = consecutive_same_tool_unique_args * 2 > consecutive_same_tool_count;
        if !is_diverse {
            return false;
        }
    }

    // 3. Error rate: unrecovered errors must be < half of successful calls
    let unrecovered = learning_ctx
        .errors
        .iter()
        .filter(|(_, recovered)| !recovered)
        .count();
    let denominator = total_successful_tool_calls.max(1);
    if unrecovered * 2 >= denominator {
        return false;
    }

    // 4. Minimum activity threshold — require more than one or two lucky calls,
    // but do not force long runs to hit a high fixed bar before they can
    // continue. Three successful tool calls is enough to prove the run is
    // underway without blocking short productive tasks.
    if total_successful_tool_calls < 3 {
        return false;
    }

    // 5. Error ratio sanity: at least 75% of activity should be successful
    let total_activity = total_successful_tool_calls + unrecovered;
    if total_activity > 0 && total_successful_tool_calls * 4 < total_activity * 3 {
        return false;
    }

    true
}

/// Format a user-facing explanation of what went wrong, from the error list.
fn format_error_explanation(errors: &[(String, bool)]) -> String {
    if errors.is_empty() {
        return String::new();
    }

    // Build deduped list from the most recent errors (the final blocker is most
    // relevant). We take the last 5 to avoid processing the entire history, but
    // prioritize recency over first-seen order.
    // If same line appears both recovered and unrecovered, prefer unrecovered (worse case).
    let recent_start = errors.len().saturating_sub(5);
    let mut seen: Vec<(String, bool)> = Vec::new();
    for (error_text, recovered) in errors[recent_start..].iter() {
        let key_line = extract_key_error_line(error_text);
        if key_line.is_empty() {
            continue;
        }
        let redacted = redact_error_line_for_summary(&key_line);
        if let Some(existing) = seen.iter_mut().find(|(line, _)| *line == redacted) {
            // If new occurrence is unrecovered, upgrade to unrecovered
            if !recovered {
                existing.1 = false;
            }
        } else {
            seen.push((redacted, *recovered));
        }
    }

    if seen.is_empty() {
        return String::new();
    }

    let mut result = String::from("Issues encountered:\n");
    for (line, recovered) in seen.iter().take(3) {
        result.push_str("- ");
        result.push_str(line);
        if *recovered {
            result.push_str(" (resolved)");
        }
        result.push('\n');
    }
    result.push('\n');
    result
}

static ABS_UNIX_PATH_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"/(?:Users|home|etc)/[^\s]+").expect("unix path regex must compile"));
static ABS_WINDOWS_PATH_RE: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"[A-Z]:[\\/][^\s]+").expect("windows path regex must compile"));

fn split_trailing_path_punctuation(raw: &str) -> (&str, &str) {
    let mut idx = raw.len();
    for (i, ch) in raw.char_indices().rev() {
        if matches!(ch, ')' | ']' | '}' | ',' | ';' | ':' | '.' | '"' | '\'') {
            idx = i;
            continue;
        }
        break;
    }
    (&raw[..idx], &raw[idx..])
}

fn abbreviate_absolute_path(path: &str) -> String {
    let (core, suffix) = split_trailing_path_punctuation(path);
    let tail = core
        .rsplit(['/', '\\'])
        .find(|segment| !segment.is_empty())
        .unwrap_or(core);
    format!("[path:.../{}]{}", tail, suffix)
}

fn redact_error_line_for_summary(key_line: &str) -> String {
    let unix_summarized = ABS_UNIX_PATH_RE
        .replace_all(key_line, |caps: &regex::Captures<'_>| {
            abbreviate_absolute_path(caps.get(0).map(|m| m.as_str()).unwrap_or_default())
        })
        .to_string();
    let windows_summarized = ABS_WINDOWS_PATH_RE
        .replace_all(&unix_summarized, |caps: &regex::Captures<'_>| {
            abbreviate_absolute_path(caps.get(0).map(|m| m.as_str()).unwrap_or_default())
        })
        .to_string();
    crate::tools::sanitize::redact_secrets(&windows_summarized)
}

/// Categorize tool calls into a human-readable activity summary.
/// Convert a raw `"tool_name(args)"` entry into a user-friendly display string.
///
/// This avoids the `tool_name(...)` format that `strip_tool_name_references`
/// would replace with "that".  Output uses "Display Name — args" instead.
pub(in crate::agent) fn display_tool_call(call: &str) -> String {
    let (name, args) = match call.find('(') {
        Some(idx) => {
            let n = &call[..idx];
            let a = call[idx + 1..].trim_end_matches(')');
            (n, a)
        }
        None => (call, ""),
    };
    let display_name = match name {
        "manage_memories" => "Searched memories",
        "remember_fact" => "Saved to memory",
        "search_files" => "Searched files",
        "read_file" => "Read file",
        "write_file" => "Wrote file",
        "edit_file" => "Edited file",
        "terminal" | "run_command" => "Ran command",
        "web_search" => "Web search",
        "web_fetch" => "Fetched URL",
        "http_request" => "HTTP request",
        "goal_trace" => "Checked goal history",
        "tool_trace" => "Checked tool history",
        "manage_goals" | "scheduled_goal_runs" => "Checked goals",
        "send_file" => "Sent file",
        "list_files" | "project_inspect" => "Listed files",
        "spawn_agent" => "Spawned agent",
        "cli_agent" => "Delegated to agent",
        _ => name,
    };
    if args.is_empty() {
        display_name.to_string()
    } else {
        format!("{}{}", display_name, args)
    }
}

///
/// Parses entries like `"read_file(Hero.jsx)"` and `"terminal(\`pip install fpdf\`)"` into
/// grouped categories so the next interaction can understand what was already done.
pub(in crate::agent) fn categorize_tool_calls(tool_calls: &[String]) -> String {
    let mut files_read: Vec<&str> = Vec::new();
    let mut files_written: Vec<&str> = Vec::new();
    let mut commands_run: Vec<&str> = Vec::new();
    let mut files_sent: Vec<&str> = Vec::new();
    let mut searches: Vec<&str> = Vec::new();
    let mut external_reads: Vec<&str> = Vec::new();
    let mut other: Vec<&str> = Vec::new();

    let mut failed_mutations: Vec<&str> = Vec::new();

    for entry in tool_calls {
        // Detect and strip [FAILED] suffix — failed tool calls are tracked
        // separately so activity summaries don't claim success on failures.
        let (clean_entry, is_failed) = if let Some(stripped) = entry.strip_suffix(" [FAILED]") {
            (stripped, true)
        } else {
            (entry.as_str(), false)
        };

        // Parse "tool_name(summary)" format
        let (name, args) = match clean_entry.find('(') {
            Some(idx) => {
                let name = &clean_entry[..idx];
                let args = clean_entry[idx + 1..].trim_end_matches(')');
                (name, args)
            }
            None => (clean_entry, ""),
        };

        // Failed write/edit operations go to a separate bucket.
        if is_failed && matches!(name, "write_file" | "edit_file") {
            if !args.is_empty() {
                failed_mutations.push(args);
            }
            continue;
        }

        match name {
            "read_file" => files_read.push(args),
            "write_file" | "edit_file" => files_written.push(args),
            "terminal" | "run_command" => commands_run.push(args),
            "send_file" | "send_media" => files_sent.push(args),
            "web_search" | "search_files" => searches.push(args),
            "web_fetch" | "http_request" => external_reads.push(args),
            "project_inspect" => files_read.push(args),
            _ => {
                if !args.is_empty() {
                    other.push(args);
                }
            }
        }
    }

    let mut sections = Vec::new();

    if !files_read.is_empty() {
        let items: Vec<&str> = files_read.iter().copied().take(15).collect();
        sections.push(format!("Files read: {}", items.join(", ")));
    }
    if !files_written.is_empty() {
        let items: Vec<&str> = files_written.iter().copied().take(10).collect();
        sections.push(format!("Files written: {}", items.join(", ")));
    }
    if !commands_run.is_empty() {
        let items: Vec<&str> = commands_run.iter().copied().take(10).collect();
        sections.push(format!("Commands run: {}", items.join(", ")));
    }
    if !files_sent.is_empty() {
        let items: Vec<&str> = files_sent.iter().copied().take(5).collect();
        sections.push(format!("Files sent: {}", items.join(", ")));
    }
    if !searches.is_empty() {
        let items: Vec<&str> = searches.iter().copied().take(5).collect();
        sections.push(format!("Searches: {}", items.join(", ")));
    }
    if !external_reads.is_empty() {
        let items: Vec<&str> = external_reads.iter().copied().take(8).collect();
        sections.push(format!("External sources checked: {}", items.join(", ")));
    }
    if !failed_mutations.is_empty() {
        let items: Vec<&str> = failed_mutations.iter().copied().take(5).collect();
        sections.push(format!(
            "Failed writes (permission/error): {}",
            items.join(", ")
        ));
    }

    if sections.is_empty() {
        return String::new();
    }

    let mut result = String::from("Activity summary:\n");
    for section in &sections {
        result.push_str("- ");
        result.push_str(section);
        result.push('\n');
    }
    result.push('\n');
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::embeddings::EmbeddingService;
    use crate::state::SqliteStateStore;
    use crate::traits::StateStore;
    use std::sync::Arc;

    #[test]
    fn test_categorize_tool_calls_groups_correctly() {
        let calls = vec![
            "read_file(Hero.jsx)".to_string(),
            "read_file(App.jsx)".to_string(),
            "terminal(`pip install fpdf`)".to_string(),
            "write_file(generate_pdf.py)".to_string(),
            "terminal(`python3 generate_pdf.py`)".to_string(),
            "send_file(Guide.pdf)".to_string(),
            "web_search(top things Chantilly VA)".to_string(),
            "project_inspect(chantilly-va-site)".to_string(),
        ];
        let result = categorize_tool_calls(&calls);
        assert!(result.contains("Files read:"));
        assert!(result.contains("Hero.jsx"));
        assert!(result.contains("chantilly-va-site"));
        assert!(result.contains("Files written:"));
        assert!(result.contains("generate_pdf.py"));
        assert!(result.contains("Commands run:"));
        assert!(result.contains("Files sent:"));
        assert!(result.contains("Guide.pdf"));
        assert!(result.contains("Searches:"));
    }

    #[test]
    fn test_categorize_tool_calls_empty() {
        let result = categorize_tool_calls(&[]);
        assert!(result.is_empty());
    }

    #[test]
    fn test_display_tool_call_survives_sanitization() {
        use crate::tools::sanitize::sanitize_user_facing_reply;

        let tool_calls = vec![
            "manage_memories(search)",
            "manage_memories(list_scheduled)",
            "search_files(twitter|schedule|cancelled|removed)",
            "goal_trace()",
            "terminal(`cd /tmp && find ~ -type d -name \"aidaemon\"`)",
            "read_file(src/main.rs)",
            "write_file(output.txt)",
            "web_search(rust async patterns)",
        ];

        let mut summary = String::from("Here's what I did before the background task started:\n");
        for (i, call) in tool_calls.iter().enumerate() {
            summary.push_str(&format!("{}. {}\n", i + 1, display_tool_call(call)));
        }

        let sanitized = sanitize_user_facing_reply(&summary);

        // The sanitized output should NOT contain "that" replacements
        assert!(
            !sanitized.contains("\n1. that\n"),
            "display_tool_call output was stripped by sanitizer: {}",
            sanitized
        );
        // Should preserve meaningful content
        assert!(
            sanitized.contains("Searched memories"),
            "sanitized: {}",
            sanitized
        );
        assert!(
            sanitized.contains("Searched files"),
            "sanitized: {}",
            sanitized
        );
        assert!(
            sanitized.contains("Checked goal history"),
            "sanitized: {}",
            sanitized
        );
        assert!(
            sanitized.contains("Ran command"),
            "sanitized: {}",
            sanitized
        );
        assert!(sanitized.contains("Read file"), "sanitized: {}", sanitized);
        assert!(sanitized.contains("Wrote file"), "sanitized: {}", sanitized);
        assert!(sanitized.contains("Web search"), "sanitized: {}", sanitized);
    }

    #[test]
    fn test_categorize_tool_calls_limits_items() {
        let calls: Vec<String> = (0..20)
            .map(|i| format!("read_file(file_{}.rs)", i))
            .collect();
        let result = categorize_tool_calls(&calls);
        // Should include max 15 files
        assert!(result.contains("file_14.rs"));
        assert!(!result.contains("file_15.rs"));
    }

    #[test]
    fn test_graceful_budget_response_includes_activity() {
        let ctx = LearningContext {
            user_text: "Create a PDF".to_string(),
            intent_domains: vec![],
            tool_calls: vec![
                "read_file(App.jsx)".to_string(),
                "terminal(`pip install fpdf`)".to_string(),
                "write_file(gen.py)".to_string(),
                "send_file(out.pdf)".to_string(),
            ],
            errors: vec![],
            first_error: None,
            recovery_actions: vec![],
            start_time: Utc::now(),
            completed_naturally: false,
            explicit_positive_signals: 0,
            explicit_negative_signals: 0,
            replay_notes: Vec::new(),
        };
        let result = graceful_budget_response(&ctx, 500_000);
        assert!(result.contains("processing limit"));
        assert!(result.contains("Activity summary:"));
        assert!(result.contains("Files read: App.jsx"));
        assert!(result.contains("Files sent: out.pdf"));
        // Should NOT contain internal details
        assert!(!result.contains("500000 tokens"));
        assert!(!result.contains("tool calls executed"));
        assert!(!result.contains("errors encountered"));
    }

    #[test]
    fn test_graceful_budget_response_caps_length() {
        let calls: Vec<String> = (0..100)
            .map(|i| {
                format!(
                    "terminal(`very long command number {} that does things`)",
                    i
                )
            })
            .collect();
        let ctx = LearningContext {
            user_text: "big task".to_string(),
            intent_domains: vec![],
            tool_calls: calls,
            errors: vec![],
            first_error: None,
            recovery_actions: vec![],
            start_time: Utc::now(),
            completed_naturally: false,
            explicit_positive_signals: 0,
            explicit_negative_signals: 0,
            replay_notes: Vec::new(),
        };
        let result = graceful_budget_response(&ctx, 500_000);
        assert!(result.len() <= 1502); // 1500 + "…"
    }

    #[test]
    fn test_graceful_goal_daily_budget_response_mentions_budget_and_reset() {
        let ctx = LearningContext {
            user_text: "run the scheduled build".to_string(),
            intent_domains: vec![],
            tool_calls: vec![
                "system_info({})".to_string(),
                "write_file(index.html)".to_string(),
            ],
            errors: vec![("temporary issue".to_string(), false)],
            first_error: None,
            recovery_actions: vec![],
            start_time: Utc::now(),
            completed_naturally: false,
            explicit_positive_signals: 0,
            explicit_negative_signals: 0,
            replay_notes: Vec::new(),
        };

        let result = graceful_goal_daily_budget_response(&ctx, 60, 60, true);
        assert!(result.contains("scheduled goal hit its daily processing budget"));
        assert!(result.contains("used 60 / 60 tokens"));
        assert!(result.contains("00:00 UTC"));
        assert!(result.contains("budget_daily"));
    }

    #[test]
    fn test_graceful_partial_stall_response_mentions_progress() {
        let ctx = LearningContext {
            user_text: "fix build".to_string(),
            intent_domains: vec![],
            tool_calls: vec![
                "read_file(Cargo.toml)".to_string(),
                "run_command(cargo build)".to_string(),
                "edit_file(src/lib.rs)".to_string(),
                "run_command(cargo build)".to_string(),
            ],
            errors: vec![("Text not found in src/lib.rs".to_string(), false)],
            first_error: None,
            recovery_actions: vec![],
            start_time: Utc::now(),
            completed_naturally: false,
            explicit_positive_signals: 0,
            explicit_negative_signals: 0,
            replay_notes: Vec::new(),
        };
        let result = graceful_partial_stall_response(&ctx, false, "deferred", &HashMap::new());
        assert!(result.contains("some progress"));
        assert!(result.contains("Activity summary:"));
        // Error explanation should appear since ctx has an error
        assert!(result.contains("Issues encountered:"));
        assert!(result.contains("not found"));
        // Should NOT contain internal details
        assert!(!result.contains("tool calls executed"));
        assert!(!result.contains("errors encountered"));
        assert!(!result.contains("Stopping reason"));
    }

    #[test]
    fn test_graceful_stall_response_includes_failure_summary() {
        let ctx = make_learning_ctx();
        let mut tool_failure_count = HashMap::new();
        tool_failure_count.insert("terminal".to_string(), semantic_failure_limit("terminal"));
        let result = graceful_stall_response(&ctx, false, "deferred-no-tool", &tool_failure_count);
        assert!(result.contains("Blocked capabilities due to repeated errors:"));
        assert!(result.contains("command execution"));
        assert!(!result.contains("terminal"));
    }

    fn make_learning_ctx() -> LearningContext {
        LearningContext {
            user_text: "deploy the app".to_string(),
            intent_domains: vec![],
            tool_calls: vec![
                "read_file(main.rs)".to_string(),
                "terminal(`cargo build`)".to_string(),
                "write_file(deploy.sh)".to_string(),
                "terminal(`./deploy.sh`)".to_string(),
            ],
            errors: vec![],
            first_error: None,
            recovery_actions: vec![],
            start_time: Utc::now(),
            completed_naturally: false,
            explicit_positive_signals: 0,
            explicit_negative_signals: 0,
            replay_notes: Vec::new(),
        }
    }

    #[test]
    fn test_is_productive_happy_path() {
        let ctx = make_learning_ctx();
        assert!(is_productive(&ctx, 0, 0, 0, 10));
    }

    #[test]
    fn test_is_productive_stalling() {
        let ctx = make_learning_ctx();
        assert!(is_productive(&ctx, 1, 0, 0, 10));
        assert!(!is_productive(&ctx, 2, 0, 0, 10));
    }

    #[test]
    fn test_is_productive_too_many_errors() {
        let mut ctx = make_learning_ctx();
        ctx.errors = vec![
            ("error 1".to_string(), false),
            ("error 2".to_string(), false),
            ("error 3".to_string(), false),
        ];
        // 3 unrecovered errors, 5 successful → 3*2=6 >= 5 → not productive
        assert!(!is_productive(&ctx, 0, 0, 0, 5));
    }

    #[test]
    fn test_is_productive_low_activity() {
        let ctx = make_learning_ctx();
        // Only 2 successful tool calls → below minimum
        assert!(!is_productive(&ctx, 0, 0, 0, 2));
    }

    #[test]
    fn test_is_productive_short_productive_run() {
        let ctx = make_learning_ctx();
        assert!(is_productive(&ctx, 0, 0, 0, 3));
    }

    #[test]
    fn test_is_productive_diverse_args_ok() {
        let ctx = make_learning_ctx();
        // At MAX_CONSECUTIVE_SAME_TOOL consecutive same tool calls, but diverse args → productive
        assert!(is_productive(
            &ctx,
            0,
            MAX_CONSECUTIVE_SAME_TOOL,
            MAX_CONSECUTIVE_SAME_TOOL / 2 + 2,
            20
        ));
    }

    #[test]
    fn test_is_productive_same_args_not_ok() {
        let ctx = make_learning_ctx();
        // At MAX_CONSECUTIVE_SAME_TOOL consecutive same tool calls, too few unique args → not diverse
        assert!(!is_productive(&ctx, 0, MAX_CONSECUTIVE_SAME_TOOL, 3, 20));
    }

    #[test]
    fn test_is_productive_diverse_but_over_20() {
        let ctx = make_learning_ctx();
        // Over the diverse limit (MAX + 4) → not productive regardless of diversity
        assert!(!is_productive(
            &ctx,
            0,
            MAX_CONSECUTIVE_SAME_TOOL + 4,
            MAX_CONSECUTIVE_SAME_TOOL,
            25
        ));
    }

    fn ctx_with_single_error(error: &str) -> LearningContext {
        LearningContext {
            user_text: "do something".to_string(),
            intent_domains: vec![],
            tool_calls: vec![],
            errors: vec![(error.to_string(), false)],
            first_error: None,
            recovery_actions: vec![],
            start_time: Utc::now(),
            completed_naturally: false,
            explicit_positive_signals: 0,
            explicit_negative_signals: 0,
            replay_notes: Vec::new(),
        }
    }

    #[test]
    fn test_classify_stall_prefers_tool_policy_block() {
        let ctx = ctx_with_single_error(
            "Command 'npm install tailwindcss' is not in the safe command list. Use 'terminal' for this command.",
        );
        let (label, suggestion) = classify_stall(&ctx, "deferred-no-tool", &HashMap::new());
        assert_eq!(label, "Tool Policy Block");
        assert!(suggestion.contains("safety policy"));
    }

    #[test]
    fn test_classify_stall_detects_edit_target_drift() {
        let ctx = ctx_with_single_error(
            "Text not found in ~/projects/oaxaca-mezcal-tours/src/components/ContactForm.jsx. The old_text did not match.",
        );
        let (label, suggestion) = classify_stall(&ctx, "deferred-no-tool", &HashMap::new());
        assert_eq!(label, "Edit Target Drift");
        assert!(suggestion.contains("re-read"));
    }

    #[test]
    fn test_classify_stall_ignores_generic_5000_values() {
        let ctx = ctx_with_single_error("Exceeded 5000 characters while building summary.");
        let (label, _) = classify_stall(&ctx, "deferred-no-tool", &HashMap::new());
        assert_eq!(label, "Stuck");
    }

    #[test]
    fn test_classify_stall_detects_provider_server_status_codes() {
        let ctx = ctx_with_single_error("OpenAI API returned status code 503 Service Unavailable.");
        let (label, _) = classify_stall(&ctx, "deferred-no-tool", &HashMap::new());
        assert_eq!(label, "Server Error");
    }

    #[test]
    fn test_classify_stall_detects_tool_lockout_from_counts() {
        let ctx = make_learning_ctx();
        let mut tool_failure_count = HashMap::new();
        tool_failure_count.insert("terminal".to_string(), semantic_failure_limit("terminal"));
        let (label, suggestion) = classify_stall(&ctx, "deferred-no-tool", &tool_failure_count);
        assert_eq!(label, "Tool Locked Out");
        assert!(suggestion.contains("locked out"));
    }

    #[test]
    fn test_tool_failure_summary_format() {
        let mut tool_failure_count = HashMap::new();
        tool_failure_count.insert("terminal".to_string(), semantic_failure_limit("terminal"));
        tool_failure_count.insert(
            "web_search".to_string(),
            semantic_failure_limit("web_search"),
        );
        tool_failure_count.insert("web_fetch".to_string(), semantic_failure_limit("web_fetch"));
        let summary = format_tool_failure_summary(&tool_failure_count);
        assert!(summary.contains("Blocked capabilities due to repeated errors:"));
        assert!(summary.contains("- command execution"));
        assert!(summary.contains("- web access"));
        let web_access_mentions = summary.matches("web access").count();
        assert_eq!(web_access_mentions, 1, "web access should be deduplicated");
    }

    #[test]
    fn test_tool_failure_summary_labels_http_request_as_api_access() {
        let mut tool_failure_count = HashMap::new();
        tool_failure_count.insert(
            "http_request".to_string(),
            semantic_failure_limit("http_request"),
        );
        let summary = format_tool_failure_summary(&tool_failure_count);
        assert!(summary.contains("- API access"));
        assert!(!summary.contains("other capability"));
    }

    #[test]
    fn test_summarize_replay_notes_groups_categories() {
        let summary = summarize_replay_notes(&[
            ReplayNote {
                category: ReplayNoteCategory::PlanRevision,
                code: "plan_rejected".to_string(),
                summary: "Rejected the first deploy step.".to_string(),
                blocking: true,
            },
            ReplayNote {
                category: ReplayNoteCategory::ValidationFailure,
                code: "verification_pending".to_string(),
                summary: "Verification was still pending.".to_string(),
                blocking: true,
            },
        ]);
        assert!(summary.contains("plan_revision: Rejected the first deploy step."));
        assert!(summary.contains("validation_failure: Verification was still pending."));
    }

    #[tokio::test]
    async fn test_process_learning_records_reasoning_failure_patterns() {
        let db_file = tempfile::NamedTempFile::new().unwrap();
        let db_path = db_file.path().display().to_string();
        let embedding_service = Arc::new(EmbeddingService::new().unwrap());
        let state = Arc::new(
            SqliteStateStore::new(&db_path, 32, None, embedding_service)
                .await
                .unwrap(),
        );

        let ctx = LearningContext {
            user_text: "deploy the app".to_string(),
            intent_domains: vec!["deploy".to_string()],
            tool_calls: vec!["read_file(src/main.rs)".to_string()],
            errors: Vec::new(),
            first_error: None,
            recovery_actions: Vec::new(),
            start_time: Utc::now(),
            completed_naturally: false,
            explicit_positive_signals: 0,
            explicit_negative_signals: 1,
            replay_notes: vec![ReplayNote {
                category: ReplayNoteCategory::ValidationFailure,
                code: "verification_pending".to_string(),
                summary: "Blocked completion until final verification could run.".to_string(),
                blocking: true,
            }],
        };

        process_learning(&(state.clone() as Arc<dyn StateStore>), ctx)
            .await
            .unwrap();

        let patterns = state.get_behavior_patterns(0.0).await.unwrap();
        let pattern = patterns
            .iter()
            .find(|pattern| pattern.pattern_type == "reasoning_failure")
            .expect("reasoning failure pattern");
        assert_eq!(
            pattern.trigger_context.as_deref(),
            Some("validation_failure:verification_pending")
        );
        assert_eq!(
            pattern.action.as_deref(),
            Some("run_verification_before_claiming_success")
        );
    }

    #[test]
    fn test_format_error_explanation_empty_on_no_errors() {
        let result = format_error_explanation(&[]);
        assert!(result.is_empty());
    }

    #[test]
    fn test_format_error_explanation_marks_recovered() {
        let errors = vec![
            ("command not found: drush".to_string(), true),
            (
                "Unable to install modules entity_reference".to_string(),
                false,
            ),
        ];
        let result = format_error_explanation(&errors);
        assert!(result.contains("Issues encountered:"));
        assert!(result.contains("command not found: drush (resolved)"));
        assert!(result.contains("Unable to install modules entity_reference"));
        // The unrecovered error should NOT have "(resolved)"
        assert!(!result.contains("entity_reference (resolved)"));
    }

    #[test]
    fn test_format_error_explanation_dedup_prefers_unrecovered() {
        let errors = vec![
            ("Error: command not found: drush".to_string(), true),
            ("Error: command not found: drush".to_string(), false),
        ];
        let result = format_error_explanation(&errors);
        // Same error appears twice — once recovered, once not. Should show as unrecovered.
        assert!(result.contains("command not found: drush"));
        assert!(!result.contains("(resolved)"));
        // Should only appear once (deduped)
        assert_eq!(result.matches("command not found: drush").count(), 1);
    }

    #[test]
    fn test_format_error_explanation_preserves_order() {
        let errors = vec![
            ("Error: first problem".to_string(), false),
            ("Error: second problem".to_string(), false),
            ("Error: third problem".to_string(), false),
        ];
        let result = format_error_explanation(&errors);
        let first_pos = result.find("first problem").unwrap();
        let second_pos = result.find("second problem").unwrap();
        let third_pos = result.find("third problem").unwrap();
        assert!(first_pos < second_pos);
        assert!(second_pos < third_pos);
    }

    #[test]
    fn test_format_error_explanation_redacts_secrets() {
        // sk- followed by 20+ alphanumeric chars matches the API key pattern
        let errors = vec![(
            "Error: Invalid API key sk-abcdefghijklmnopqrstuvwxyz1234567890ABCDEF".to_string(),
            false,
        )];
        let result = format_error_explanation(&errors);
        assert!(result.contains("Issues encountered:"));
        assert!(!result.contains("sk-abcdef"));
        assert!(result.contains("[REDACTED:"));
    }

    #[test]
    fn test_format_error_explanation_keeps_safe_path_tail() {
        let errors = vec![(
            "Error: Text not found in /Users/alice/projects/plants-site/src/main.rs.".to_string(),
            false,
        )];
        let result = format_error_explanation(&errors);
        assert!(result.contains("[path:.../main.rs]."));
        assert!(!result.contains("/Users/alice/projects/plants-site/src/main.rs"));
        assert!(!result.contains("[REDACTED:File path]"));
    }

    #[test]
    fn test_format_error_explanation_prefers_recent_errors() {
        // When more than 5 errors exist, only the last 5 should be considered.
        // This ensures the user sees the final blocker, not stale resolved issues.
        let errors: Vec<(String, bool)> = (1..=8)
            .map(|i| (format!("Error: problem number {}", i), i <= 3))
            .collect();
        let result = format_error_explanation(&errors);
        // Errors 1-3 are old (indices 0-2) and should be skipped (recent_start=3).
        assert!(
            !result.contains("problem number 1"),
            "Stale error 1 should not appear"
        );
        assert!(
            !result.contains("problem number 2"),
            "Stale error 2 should not appear"
        );
        assert!(
            !result.contains("problem number 3"),
            "Stale error 3 should not appear"
        );
        // Recent errors (4-8) should be represented (display capped at 3 deduped).
        // At minimum, the most recent errors should appear.
        assert!(
            result.contains("problem number"),
            "Recent errors should appear"
        );
    }

    #[test]
    fn test_graceful_stall_includes_error_explanation() {
        let mut ctx = make_learning_ctx();
        ctx.errors = vec![(
            "Unable to install modules entity_reference due to missing modules".to_string(),
            false,
        )];
        let result = graceful_stall_response(&ctx, false, "deferred-no-tool", &HashMap::new());
        assert!(result.contains("Issues encountered:"));
        assert!(result.contains("Unable to install modules entity_reference"));
    }

    #[test]
    fn test_graceful_stall_no_error_section_when_clean() {
        let ctx = make_learning_ctx(); // no errors
        let result = graceful_stall_response(&ctx, false, "deferred-no-tool", &HashMap::new());
        assert!(!result.contains("Issues encountered:"));
    }
}