ai-memory 0.7.1

AI-agnostic persistent memory system — MCP server, HTTP API, and CLI for any AI platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
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
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0

//! `cmd_curator` migration. The daemon-mode body delegates to
//! `daemon_runtime::run_curator_daemon_with_primitives` (W3 work);
//! this module owns only the outer wrapper and the report printer.

// The SAL store-build helpers (`curator_store_url`, the `--store-url`
// path) and their `anyhow::Result` import are only live under the
// sal-gated curator path; relax dead-code / unused-import in a non-sal
// build only (sal builds enforce both fully).
#![cfg_attr(not(feature = "sal"), allow(dead_code, unused_imports))]

use crate::cli::CliOutput;
use crate::curator::reflection_pass;
use crate::identity::keypair as identity_keypair;
use crate::{autonomy, config, curator, db, llm};
use anyhow::{Context, Result};
use clap::Args;
use std::path::Path;

#[derive(Args)]
#[allow(clippy::struct_excessive_bools)]
pub struct CuratorArgs {
    /// Run exactly one sweep and exit. Mutually exclusive with --daemon.
    #[arg(long, conflicts_with = "daemon")]
    pub once: bool,
    /// Loop forever, sleeping --interval-secs between sweeps. SIGINT /
    /// SIGTERM trigger a clean shutdown between cycles.
    #[arg(long)]
    pub daemon: bool,
    /// Seconds between daemon sweeps. Clamped to [60, 86400].
    #[arg(long, default_value_t = crate::SECS_PER_HOUR as u64)]
    pub interval_secs: u64,
    /// Hard cap on LLM-invoking operations per cycle.
    #[arg(long, default_value_t = 100)]
    pub max_ops: usize,
    /// Emit the report without persisting any metadata changes.
    #[arg(long)]
    pub dry_run: bool,
    /// Only curate memories in these namespaces. Repeat flag for multiple.
    #[arg(long = "include-namespace")]
    pub include_namespaces: Vec<String>,
    /// Exclude these namespaces from curation. Repeat flag for multiple.
    #[arg(long = "exclude-namespace")]
    pub exclude_namespaces: Vec<String>,
    /// Print the report as JSON rather than a human-readable summary.
    #[arg(long)]
    pub json: bool,
    /// Reverse rollback-log entries instead of running a sweep. Accepts
    /// a specific rollback-memory id, or `--last N` for the most recent.
    /// Mutually exclusive with `--once` and `--daemon`.
    #[arg(long, conflicts_with_all = ["once", "daemon"])]
    pub rollback: Option<String>,
    /// With `--rollback`, reverse the N most recent rollback-log entries
    /// instead of a single id.
    #[arg(long)]
    pub rollback_last: Option<usize>,
    /// v0.7.0 L2-1 — Run the reflection-pass curator mode. Clusters
    /// co-recalled Observations and synthesises typed Reflection
    /// memories with `reflects_on` provenance. Mutually exclusive with
    /// the sweep / rollback modes. Requires either `--namespace` or
    /// `--all-namespaces`.
    #[arg(long, conflicts_with_all = ["once", "daemon", "rollback", "rollback_last"])]
    pub reflect: bool,
    /// Scope the reflection pass to a single namespace. Pairs with
    /// `--reflect`; ignored otherwise.
    #[arg(long)]
    pub namespace: Option<String>,
    /// Curator-side reflection-depth ceiling. The substrate's per-
    /// namespace `max_reflection_depth` policy is still enforced on
    /// top — this flag refuses to *propose* reflections that would
    /// exceed the operator-supplied cap so the curator never burns an
    /// LLM round-trip on a doomed write.
    #[arg(long)]
    pub max_depth: Option<u32>,
    /// Run the reflection pass over every observable namespace rather
    /// than a single one. Per-namespace `reflection_pass.enabled`
    /// flags still gate participation. Pairs with `--reflect`.
    #[arg(long)]
    pub all_namespaces: bool,
    /// v0.7.0 #1548 — full SAL store URL. When set, the curator binds
    /// its [`crate::store::MemoryStore`] handle to the URL-resolved
    /// adapter instead of the SQLite path derived from `--db`, so the
    /// reflection / consolidation passes run against a **Postgres**
    /// (or SQLite) federated store. Mirrors `serve --store-url`.
    ///
    /// Accepted shapes:
    ///
    /// - `sqlite:///absolute/path/to/file.db` — SQLite adapter (same
    ///   semantics as `--db`).
    /// - `postgres://user:pass@host:port/dbname` — Postgres adapter.
    /// - `postgresql://...` — alias for the Postgres scheme.
    ///
    /// `--db` and `--store-url` are mutually exclusive: passing both is
    /// rejected at startup with a clear error (mirrors `serve`).
    ///
    /// Postgres-backed curators require `--features sal,sal-postgres`
    /// at build time; otherwise the URL is rejected at startup.
    #[cfg(feature = "sal")]
    #[arg(long, value_name = "URL")]
    pub store_url: Option<String>,
}

/// #1143: honor `AI_MEMORY_LLM_BACKEND` env so the `ai-memory curator`
/// CLI (sweep / reflect / daemon modes) reaches xAI / OpenAI /
/// Anthropic / Gemini / etc. The legacy arm preserves v0.6.x behavior
/// (tier-default Ollama at the default URL). Returns `None` for the
/// keyword tier (no curator LLM configured) and on env / construction
/// failure — the curator falls through to keyword-only behavior so
/// the daemon never hard-fails on an unreachable provider.
fn build_curator_llm(tier: config::FeatureTier) -> Option<llm::OllamaClient> {
    // v0.7.x (#1146) — route through the canonical resolver. Two
    // short-circuits preserve pre-#1146 semantics:
    //   1. Tiers with no `llm_model` preset (Keyword, Semantic) AND
    //      no operator intent (env / config / legacy field absent —
    //      resolver `source == CompiledDefault`) return None without
    //      attempting client construction. Avoids paying a blocking
    //      reqwest call to a (likely-absent) Ollama under tokio test
    //      contexts and matches pre-#1146 v0.6.x behaviour.
    //   2. With operator intent, the resolver folds CLI / env /
    //      config / legacy / compiled through the uniform precedence
    //      ladder.
    let app_config = config::AppConfig::load();
    let resolved = app_config.resolve_llm(None, None, None);
    if matches!(resolved.source, config::ConfigSource::CompiledDefault)
        && tier.config().llm_model.is_none()
    {
        return None;
    }
    llm::OllamaClient::build_from_resolved(&resolved)
        .ok()
        .flatten()
}

fn print_curator_report(r: &curator::CuratorReport, out: &mut CliOutput<'_>) -> Result<()> {
    writeln!(out.stdout, "curator cycle report")?;
    writeln!(out.stdout, "  started_at:        {}", r.started_at)?;
    writeln!(out.stdout, "  completed_at:      {}", r.completed_at)?;
    writeln!(out.stdout, "  duration_ms:       {}", r.cycle_duration_ms)?;
    writeln!(out.stdout, "  memories_scanned:  {}", r.memories_scanned)?;
    writeln!(out.stdout, "  memories_eligible: {}", r.memories_eligible)?;
    writeln!(
        out.stdout,
        "  operations:        {}",
        r.operations_attempted
    )?;
    writeln!(out.stdout, "  auto_tagged:       {}", r.auto_tagged)?;
    writeln!(
        out.stdout,
        "  contradictions:    {}",
        r.contradictions_found
    )?;
    writeln!(
        out.stdout,
        "  skipped (cap):     {}",
        r.operations_skipped_cap
    )?;
    writeln!(out.stdout, "  errors:            {}", r.errors.len())?;
    writeln!(out.stdout, "  dry_run:           {}", r.dry_run)?;
    for e in &r.errors {
        writeln!(out.stdout, "    - {e}")?;
    }
    Ok(())
}

/// `curator` handler. Daemon-mode delegates to `daemon_runtime`.
pub async fn run(
    db_path: &Path,
    args: &CuratorArgs,
    app_config: &config::AppConfig,
    out: &mut CliOutput<'_>,
) -> Result<()> {
    if args.rollback.is_some() || args.rollback_last.is_some() {
        return run_rollback(db_path, args, out);
    }

    if args.reflect {
        return run_reflect(db_path, args, app_config, out).await;
    }

    if !args.once && !args.daemon {
        anyhow::bail!(
            "curator requires --once, --daemon, --reflect, --rollback <id>, or --rollback-last N"
        );
    }

    // v0.7.0 #1548 — when `--store-url` selects a Postgres adapter, the
    // `--once` / `--daemon` upkeep sweep runs against the federated
    // store through the SAL `MemoryStore` trait (reflection-pass
    // upkeep). The SQLite path keeps the full pre-#1548 conn-bound
    // daemon (auto_tag + contradiction + autonomy + persona) for exact
    // behaviour parity, since that subsystem is not yet trait-ported.
    #[cfg(feature = "sal")]
    if curator_store_url(args).is_some() {
        return run_store_backed_sweep(db_path, args, app_config, out).await;
    }

    let cfg = curator::CuratorConfig {
        interval_secs: args.interval_secs,
        max_ops_per_cycle: args.max_ops,
        dry_run: args.dry_run,
        include_namespaces: args.include_namespaces.clone(),
        exclude_namespaces: args.exclude_namespaces.clone(),
        compaction: curator::CompactionConfig::default(),
    };

    let feature_tier = app_config.effective_tier(None);
    let llm = build_curator_llm(feature_tier);

    if args.once {
        let conn = db::open(db_path)?;
        let report = curator::run_once(&conn, llm.as_ref(), &cfg, None)?;
        if args.json {
            writeln!(out.stdout, "{}", serde_json::to_string_pretty(&report)?)?;
        } else {
            print_curator_report(&report, out)?;
        }
        return Ok(());
    }

    // Daemon mode — delegate to daemon_runtime.
    let shutdown = std::sync::Arc::new(tokio::sync::Notify::new());
    let shutdown_for_signal = shutdown.clone();
    tokio::spawn(async move {
        let _ = tokio::signal::ctrl_c().await;
        shutdown_for_signal.notify_one();
    });

    // #1440 — hand the daemon the SAME resolver-built client the
    // `--once` path uses (built at the top of `run` via
    // `build_curator_llm`). The pre-#1440 code re-derived a model
    // string from the tier default (`gemma4:e4b`) and injected it as a
    // CLI-arm model override, clobbering the operator's configured
    // `[llm].model` and 400-ing every call on non-Ollama backends.
    crate::daemon_runtime::run_curator_daemon_with_primitives(
        db_path.to_path_buf(),
        args.interval_secs,
        args.max_ops,
        args.dry_run,
        args.include_namespaces.clone(),
        args.exclude_namespaces.clone(),
        llm.map(std::sync::Arc::new),
        shutdown,
    )
    .await
}

/// v0.7.0 #1548 — resolve the operator-supplied `--store-url` flag in
/// a feature-flag-aware way (no env binding — the
/// `AI_MEMORY_STORE_URL` env fallback was deliberately dropped in
/// `1e8ad69b`). Returns `None`
/// on builds without the `sal` feature (where the field does not exist)
/// so the curator falls through to the legacy SQLite path.
#[must_use]
fn curator_store_url(args: &CuratorArgs) -> Option<&str> {
    #[cfg(feature = "sal")]
    {
        args.store_url.as_deref()
    }
    #[cfg(not(feature = "sal"))]
    {
        let _ = args;
        None
    }
}

/// v0.7.0 #1548 — `--once` / `--daemon` upkeep against a SAL store
/// (Postgres or SQLite by `--store-url` scheme). Runs the reflection
/// pass over every operator-enabled namespace through the
/// [`crate::store::MemoryStore`] trait, so a federated Postgres-backed
/// curator performs the same recursive-refinement upkeep the SQLite
/// daemon does via `run_reflection_pass`.
///
/// `--once` runs a single sweep and prints the report; `--daemon` loops
/// every `--interval-secs` until SIGINT / SIGTERM, logging each cycle.
///
/// The reflection pass is LLM-backed; when no LLM client is configured
/// the sweep returns a populated report carrying the configured-but-
/// unreachable error (matching the `--reflect` no-LLM contract) rather
/// than hard-failing the daemon.
#[cfg(feature = "sal")]
async fn run_store_backed_sweep(
    db_path: &Path,
    args: &CuratorArgs,
    app_config: &config::AppConfig,
    out: &mut CliOutput<'_>,
) -> Result<()> {
    let store =
        crate::daemon_runtime::build_curator_store(curator_store_url(args), db_path, app_config)
            .await?;

    let keypair = load_curator_keypair_best_effort();
    let feature_tier = app_config.effective_tier(None);
    let llm = build_curator_llm(feature_tier);

    if args.once {
        let report = store_backed_reflection_sweep(
            store.as_ref(),
            llm.as_ref().map(|c| c as &dyn crate::autonomy::AutonomyLlm),
            keypair.as_ref(),
            args,
        )
        .await;
        if args.json {
            writeln!(out.stdout, "{}", serde_json::to_string_pretty(&report)?)?;
        } else {
            print_reflection_report(&report, out)?;
        }
        return Ok(());
    }

    // Daemon mode — loop the SAL reflection sweep until shutdown.
    // SIGINT / SIGTERM flip the shared shutdown flag; the loop checks it
    // before each cycle and the `select!` wakes the interval sleep early.
    let shutdown = std::sync::Arc::new(tokio::sync::Notify::new());
    let shutdown_flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let shutdown_for_signal = shutdown.clone();
    let flag_for_signal = shutdown_flag.clone();
    tokio::spawn(async move {
        let _ = tokio::signal::ctrl_c().await;
        flag_for_signal.store(true, std::sync::atomic::Ordering::Relaxed);
        shutdown_for_signal.notify_one();
    });

    // Clamp the interval to the same [60, 86400] band the SQLite
    // `curator::run_daemon` loop enforces, so a stray small / huge value
    // can't busy-spin or stall the federated upkeep sweep.
    let interval_secs = args.interval_secs.clamp(60, crate::SECS_PER_DAY as u64);
    tracing::info!(
        "curator SAL daemon started (store-url backend, interval={interval_secs}s, \
         max_ops={}, dry_run={})",
        args.max_ops,
        args.dry_run,
    );

    while !shutdown_flag.load(std::sync::atomic::Ordering::Relaxed) {
        let report = store_backed_reflection_sweep(
            store.as_ref(),
            llm.as_ref().map(|c| c as &dyn crate::autonomy::AutonomyLlm),
            keypair.as_ref(),
            args,
        )
        .await;
        tracing::info!(
            "curator SAL cycle: namespaces={} observations={} clusters_eligible={} \
             reflections_persisted={} depth_refusals={} errors={} (dry_run={})",
            report.namespaces_visited,
            report.observations_scanned,
            report.clusters_eligible,
            report.reflections_persisted,
            report.depth_refusals,
            report.errors.len(),
            report.dry_run,
        );

        // Sleep the interval, waking early on shutdown.
        tokio::select! {
            () = tokio::time::sleep(std::time::Duration::from_secs(interval_secs)) => {}
            () = shutdown.notified() => break,
        }
    }

    tracing::info!("curator SAL daemon shutdown");
    Ok(())
}

/// Run a single reflection-pass sweep over a SAL store. Shared by the
/// `--once` and `--daemon` arms of [`run_store_backed_sweep`]. Returns
/// a populated [`reflection_pass::ReflectionPassReport`] regardless of
/// outcome — an unreachable LLM is surfaced as a report error, not a
/// propagated failure, so the daemon loop never aborts on a transient
/// provider outage.
///
/// All non-reserved namespaces are swept (the `--daemon` upkeep
/// contract); per-namespace `reflection_pass.enabled` config-file
/// gating is a v0.7.1 follow-up, identical to the `--reflect
/// --all-namespaces` posture.
#[cfg(feature = "sal")]
async fn store_backed_reflection_sweep(
    store: &dyn crate::store::MemoryStore,
    llm: Option<&dyn crate::autonomy::AutonomyLlm>,
    keypair: Option<&identity_keypair::AgentKeypair>,
    args: &CuratorArgs,
) -> reflection_pass::ReflectionPassReport {
    // Upkeep mode sweeps every non-reserved namespace (matching the
    // `--all-namespaces` reflection contract).
    run_reflection_pass_with_optional_llm(
        store,
        llm,
        keypair,
        None,
        args.max_depth,
        args.dry_run,
        |_ns: &str| true,
    )
    .await
}

/// v0.7.0 #1548 — run the reflection pass over a SAL store with an
/// OPTIONAL LLM, folding any pass error into the returned report rather
/// than propagating it (so a daemon sweep never aborts on a transient
/// provider outage); when `llm` is `None` the report carries the
/// no-LLM-configured error. Shared by [`run_reflect`] +
/// [`store_backed_reflection_sweep`]; taking `&dyn AutonomyLlm` lets the
/// unit tests drive it with a deterministic stub instead of a live
/// Ollama (which `build_curator_llm` cannot construct in CI).
#[cfg(feature = "sal")]
async fn run_reflection_pass_with_optional_llm(
    store: &dyn crate::store::MemoryStore,
    llm: Option<&dyn crate::autonomy::AutonomyLlm>,
    keypair: Option<&identity_keypair::AgentKeypair>,
    namespace: Option<&str>,
    max_depth: Option<u32>,
    dry_run: bool,
    enabled_check: impl Fn(&str) -> bool,
) -> reflection_pass::ReflectionPassReport {
    let stamp = || chrono::Utc::now().to_rfc3339();
    let Some(llm_client) = llm else {
        let mut empty = reflection_pass::ReflectionPassReport {
            started_at: stamp(),
            completed_at: stamp(),
            dry_run,
            ..Default::default()
        };
        empty.errors.push(
            "no LLM client configured — set a feature tier that provides an llm_model".into(),
        );
        return empty;
    };
    match reflection_pass::run_reflection_pass(
        store,
        llm_client,
        keypair,
        namespace,
        max_depth,
        dry_run,
        enabled_check,
    )
    .await
    {
        Ok(report) => report,
        Err(e) => {
            let mut report = reflection_pass::ReflectionPassReport {
                started_at: stamp(),
                completed_at: stamp(),
                dry_run,
                ..Default::default()
            };
            report.errors.push(format!("reflection pass failed: {e}"));
            report
        }
    }
}

/// v0.7.0 L2-1 — reflection-pass entry point. Wires the operator's
/// CLI flags to [`reflection_pass::run_reflection_pass`] and prints
/// the structured report.
///
/// Per #666 acceptance:
///
/// * `--namespace foo` runs the pass on one namespace; `--all-
///   namespaces` enumerates every observable namespace.
/// * Per-namespace `reflection_pass.enabled` config gates which
///   namespaces actually run (defaults to `false`). The CLI does NOT
///   load the per-namespace config from `ai-memory.toml` yet — that's
///   a v0.7.1 follow-up; for now, the operator-supplied
///   `--namespace` is treated as "operator opted in for this run"
///   so a single-namespace invocation always proceeds. The
///   `--all-namespaces` path applies the strict `enabled` gate (no
///   external config loaded → no namespaces enabled → zero rows
///   written), which is the safe default until the config-file
///   wiring lands.
/// * `--dry-run` reports proposed clusters without writing anything.
/// * `--max-depth` is the curator-side guard rail on top of the
///   substrate's per-namespace policy cap.
///
/// v0.7.0 #1548 — the reflection pass operates over the SAL
/// [`crate::store::MemoryStore`] trait, which is `sal`-gated. The
/// `not(sal)` variant below returns a clear capability error so a
/// binary built without `--features sal` fails loudly rather than
/// silently dropping `--reflect`.
#[cfg(feature = "sal")]
async fn run_reflect(
    db_path: &Path,
    args: &CuratorArgs,
    app_config: &config::AppConfig,
    out: &mut CliOutput<'_>,
) -> Result<()> {
    if args.namespace.is_none() && !args.all_namespaces {
        anyhow::bail!("--reflect requires either --namespace <ns> or --all-namespaces");
    }
    if args.namespace.is_some() && args.all_namespaces {
        anyhow::bail!("--reflect: --namespace and --all-namespaces are mutually exclusive");
    }

    // v0.7.0 #1548 — resolve the SAL store handle from `--store-url`
    // (Postgres or SQLite) when supplied, else a SQLite store at the
    // `--db` path. The reflection pass operates over the
    // `MemoryStore` trait so `--reflect` works against a federated
    // Postgres store identically to the local SQLite path.
    let store = build_reflect_store(db_path, args, app_config).await?;

    // Resolve the curator's signing keypair. We rely on the
    // process-wide identity (the same one `serve` uses) so every
    // `reflects_on` edge attributes to the daemon's Ed25519 identity.
    // When no keypair is configured (operator opted out via
    // `[identity].disabled = true` or runs a one-off `--reflect`
    // against a fresh data dir) the pass falls back to `"ai:curator"`
    // — same fall-back the autonomy `consolidate` path uses.
    let keypair = load_curator_keypair_best_effort();

    let feature_tier = app_config.effective_tier(None);
    let llm = build_curator_llm(feature_tier);

    // Single-namespace invocations bypass the per-namespace `enabled`
    // gate (operator explicitly asked). #1671 — `--all-namespaces` now
    // consults the per-namespace `[curator.reflection_namespaces]`
    // config: a namespace participates only when it carries
    // `enabled = true`. Absent / disabled namespaces are skipped, so the
    // fan-out is opt-in (and `--all-namespaces` is no longer an inert
    // no-op once the operator enables namespaces in config).
    let scope_single = args.namespace.is_some();
    let enabled_check =
        |ns: &str| -> bool { scope_single || app_config.reflection_namespace_enabled(ns) };

    let report = run_reflection_pass_with_optional_llm(
        store.as_ref(),
        llm.as_ref().map(|c| c as &dyn crate::autonomy::AutonomyLlm),
        keypair.as_ref(),
        args.namespace.as_deref(),
        args.max_depth,
        args.dry_run,
        enabled_check,
    )
    .await;

    if args.json {
        writeln!(out.stdout, "{}", serde_json::to_string_pretty(&report)?)?;
    } else {
        print_reflection_report(&report, out)?;
    }
    Ok(())
}

/// `not(sal)` companion of [`run_reflect`]. The reflection pass requires
/// the SAL `MemoryStore` trait, which is `sal`-gated; a binary built
/// without `--features sal` cannot run `--reflect`, so surface a clear
/// capability error rather than silently dropping the mode.
#[cfg(not(feature = "sal"))]
#[allow(clippy::unused_async)]
async fn run_reflect(
    _db_path: &Path,
    _args: &CuratorArgs,
    _app_config: &config::AppConfig,
    _out: &mut CliOutput<'_>,
) -> Result<()> {
    anyhow::bail!(
        "curator --reflect requires a binary built with --features sal \
         (the reflection pass operates over the SAL MemoryStore trait)"
    )
}

/// v0.7.0 #1548 — resolve the SAL store handle for the `--reflect` mode.
/// Mirrors [`run_store_backed_sweep`]'s builder: binds to the
/// `--store-url` adapter (Postgres or SQLite) when supplied, else a
/// SQLite store at the `--db` path.
#[cfg(feature = "sal")]
async fn build_reflect_store(
    db_path: &Path,
    args: &CuratorArgs,
    app_config: &config::AppConfig,
) -> Result<std::sync::Arc<dyn crate::store::MemoryStore>> {
    crate::daemon_runtime::build_curator_store(curator_store_url(args), db_path, app_config).await
}

/// Load the curator's per-process signing keypair. Best-effort — if the
/// keypair file is missing or unreadable we return `None` and the pass
/// stamps `ai:curator` as `agent_id`. Errors are deliberately not
/// surfaced; an operator who wants a strict-mode "fail if keypair
/// missing" can run `ai-memory identity list` first.
#[cfg_attr(not(feature = "sal"), allow(dead_code))]
fn load_curator_keypair_best_effort() -> Option<identity_keypair::AgentKeypair> {
    let dir = identity_keypair::default_key_dir().ok()?;
    // We don't know which agent_id the operator wants the curator to
    // run as. Pick the lexicographically-first key under the key dir;
    // operators who run multiple curators on the same host should
    // either give each a dedicated key dir via `AI_MEMORY_KEY_DIR` or
    // set the daemon `AI_MEMORY_AGENT_ID` env var.
    let listed = identity_keypair::list(&dir).ok()?;
    let first = listed.into_iter().next()?;
    identity_keypair::load(&first.agent_id, &dir).ok()
}

#[cfg_attr(not(feature = "sal"), allow(dead_code))]
fn print_reflection_report(
    r: &reflection_pass::ReflectionPassReport,
    out: &mut CliOutput<'_>,
) -> Result<()> {
    writeln!(out.stdout, "reflection pass report")?;
    writeln!(out.stdout, "  started_at:            {}", r.started_at)?;
    writeln!(out.stdout, "  completed_at:          {}", r.completed_at)?;
    writeln!(
        out.stdout,
        "  namespaces_visited:    {}",
        r.namespaces_visited
    )?;
    writeln!(
        out.stdout,
        "  observations_scanned:  {}",
        r.observations_scanned
    )?;
    writeln!(out.stdout, "  clusters_formed:       {}", r.clusters_formed)?;
    writeln!(
        out.stdout,
        "  clusters_eligible:     {}",
        r.clusters_eligible
    )?;
    writeln!(
        out.stdout,
        "  reflections_persisted: {}",
        r.reflections_persisted
    )?;
    writeln!(out.stdout, "  depth_refusals:        {}", r.depth_refusals)?;
    writeln!(out.stdout, "  errors:                {}", r.errors.len())?;
    writeln!(out.stdout, "  dry_run:               {}", r.dry_run)?;
    for e in &r.errors {
        writeln!(out.stdout, "    - {e}")?;
    }
    for prop in &r.dry_run_proposals {
        writeln!(
            out.stdout,
            "  proposal: ns='{}' title='{}' sources={}",
            prop.namespace,
            prop.proposed_title,
            prop.source_ids.len()
        )?;
    }
    Ok(())
}

fn run_rollback(db_path: &Path, args: &CuratorArgs, out: &mut CliOutput<'_>) -> Result<()> {
    let conn = db::open(db_path)?;

    if let Some(id) = &args.rollback {
        let Some(mem) = db::get(&conn, id)? else {
            anyhow::bail!("rollback entry {id} not found");
        };
        let entry: autonomy::RollbackEntry = serde_json::from_str(&mem.content)
            .context("rollback entry content is not a valid RollbackEntry JSON")?;
        let applied = autonomy::reverse_rollback_entry(&conn, &entry)?;
        let mut tags = mem.tags.clone();
        if !tags.iter().any(|t| t == "_reversed") {
            tags.push("_reversed".to_string());
            db::update(
                &conn,
                &mem.id,
                None,
                None,
                None,
                None,
                Some(&tags),
                None,
                None,
                None,
                None,
            )?;
        }
        writeln!(
            out.stdout,
            "rollback {id}: {}",
            if applied { "applied" } else { "no-op" }
        )?;
        return Ok(());
    }

    if let Some(n) = args.rollback_last {
        let log = db::list(
            &conn,
            Some("_curator/rollback"),
            None,
            n.max(1),
            0,
            None,
            None,
            None,
            None,
            None,
        )?;
        let mut reversed = 0usize;
        for mem in &log {
            if mem.tags.iter().any(|t| t == "_reversed") {
                continue;
            }
            let Ok(entry) = serde_json::from_str::<autonomy::RollbackEntry>(&mem.content) else {
                continue;
            };
            let applied = autonomy::reverse_rollback_entry(&conn, &entry)?;
            if applied {
                reversed += 1;
                let mut tags = mem.tags.clone();
                tags.push("_reversed".to_string());
                db::update(
                    &conn,
                    &mem.id,
                    None,
                    None,
                    None,
                    None,
                    Some(&tags),
                    None,
                    None,
                    None,
                    None,
                )?;
            }
        }
        writeln!(out.stdout, "reversed {reversed} rollback entries")?;
        return Ok(());
    }

    // QUAL-2 (med/low review batch) — typed error instead of `unreachable!()`.
    // The caller-side guard at `cmd_curator` (line ~147) already short-circuits
    // when neither `--rollback` nor `--rollback-last` is set; this branch is
    // reachable only if that guard ever regresses. Returning an `anyhow::Error`
    // preserves the audit message but keeps the failure recoverable (typed
    // CLI exit code) instead of crashing the process with a panic.
    anyhow::bail!("run_rollback entered without --rollback or --rollback-last");
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::test_utils::TestEnv;

    fn default_args() -> CuratorArgs {
        CuratorArgs {
            once: false,
            daemon: false,
            interval_secs: crate::SECS_PER_HOUR as u64,
            max_ops: 100,
            dry_run: false,
            include_namespaces: Vec::new(),
            exclude_namespaces: Vec::new(),
            json: false,
            rollback: None,
            rollback_last: None,
            reflect: false,
            namespace: None,
            max_depth: None,
            all_namespaces: false,
            #[cfg(feature = "sal")]
            store_url: None,
        }
    }

    #[tokio::test]
    async fn test_curator_requires_mode() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let args = default_args();
        let mut out = env.output();
        let res = run(&db, &args, &cfg, &mut out).await;
        assert!(res.is_err());
        assert!(
            res.unwrap_err()
                .to_string()
                .contains("--once, --daemon, --reflect")
        );
    }

    #[tokio::test]
    async fn test_curator_once_runs_single_sweep_text() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.once = true;
        args.dry_run = true;
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        assert!(env.stdout_str().contains("curator cycle report"));
    }

    #[tokio::test]
    async fn test_curator_once_json_format() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.once = true;
        args.json = true;
        args.dry_run = true;
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        let v: serde_json::Value = serde_json::from_str(env.stdout_str().trim()).unwrap();
        assert!(v["dry_run"].as_bool().unwrap());
    }

    #[tokio::test]
    async fn test_curator_dry_run_skips_writes() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.once = true;
        args.dry_run = true;
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        // Report mentions dry_run flag.
        let s = env.stdout_str();
        assert!(s.contains("dry_run:") || s.contains("\"dry_run\""));
    }

    #[tokio::test]
    async fn test_curator_include_namespaces_filter() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.once = true;
        args.dry_run = true;
        args.include_namespaces = vec!["only-this-ns".to_string()];
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        // No memories — operations attempted should be 0.
        assert!(env.stdout_str().contains("operations:"));
    }

    #[tokio::test]
    async fn test_curator_exclude_namespaces_filter() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.once = true;
        args.dry_run = true;
        args.exclude_namespaces = vec!["skip-me".to_string()];
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        assert!(env.stdout_str().contains("curator cycle report"));
    }

    #[tokio::test]
    async fn test_curator_max_ops_cap_respected() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.once = true;
        args.dry_run = true;
        args.max_ops = 0; // immediately at cap
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        assert!(env.stdout_str().contains("operations:"));
    }

    #[tokio::test]
    async fn test_curator_rollback_id_not_found() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.rollback = Some("00000000-0000-0000-0000-000000000000".to_string());
        let mut out = env.output();
        let res = run(&db, &args, &cfg, &mut out).await;
        assert!(res.is_err());
        assert!(res.unwrap_err().to_string().contains("rollback entry"));
    }

    #[tokio::test]
    async fn test_curator_rollback_last_zero_entries() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.rollback_last = Some(5);
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        // No rollback log entries; should report 0.
        assert!(env.stdout_str().contains("reversed 0"));
    }

    // PR-9i — buffer coverage uplift. Targets run_rollback() — rollback
    // path with valid PriorityAdjust entry, rollback_last with both
    // applied & malformed JSON entries (skip branch), already-reversed
    // skip branch.

    fn build_priority_rollback_entry_json(memory_id: &str, before: i32, after: i32) -> String {
        // Serialize as the externally-tagged enum form `autonomy::RollbackEntry`
        // uses (the Rust default).
        serde_json::to_string(&autonomy::RollbackEntry::PriorityAdjust {
            memory_id: memory_id.to_string(),
            before,
            after,
        })
        .unwrap()
    }

    fn seed_rollback_entry(db_path: &std::path::Path, content: &str) -> String {
        // Insert a memory in the _curator/rollback namespace whose content
        // is a serialized RollbackEntry. Returns the inserted id.
        let conn = db::open(db_path).expect("db::open");
        let now = chrono::Utc::now().to_rfc3339();
        let mut metadata = crate::models::default_metadata();
        if let Some(obj) = metadata.as_object_mut() {
            obj.insert(
                "agent_id".to_string(),
                serde_json::Value::String("test-agent".to_string()),
            );
        }
        let mem = crate::models::Memory {
            id: uuid::Uuid::new_v4().to_string(),
            tier: crate::models::Tier::Mid,
            namespace: "_curator/rollback".to_string(),
            title: format!("rollback-{}", uuid::Uuid::new_v4()),
            content: content.to_string(),
            tags: vec![],
            priority: 5,
            confidence: 1.0,
            source: "test".to_string(),
            access_count: 0,
            created_at: now.clone(),
            updated_at: now,
            last_accessed_at: None,
            expires_at: None,
            metadata,
            reflection_depth: 0,
            memory_kind: crate::models::MemoryKind::Observation,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            confidence_source: crate::models::ConfidenceSource::CallerProvided,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: 1,
        };
        db::insert(&conn, &mem).expect("db::insert")
    }

    #[tokio::test]
    async fn pr9i_curator_rollback_priority_adjust_applies() {
        // Seed a real memory whose priority we'll roll back from 7→3.
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();

        // 1. Seed a target memory at priority=7.
        let target = {
            let conn = db::open(&db).unwrap();
            let now = chrono::Utc::now().to_rfc3339();
            let mut metadata = crate::models::default_metadata();
            if let Some(obj) = metadata.as_object_mut() {
                obj.insert(
                    "agent_id".to_string(),
                    serde_json::Value::String("test-agent".to_string()),
                );
            }
            let mem = crate::models::Memory {
                id: uuid::Uuid::new_v4().to_string(),
                tier: crate::models::Tier::Mid,
                namespace: "ns".to_string(),
                title: "target".to_string(),
                content: "c".to_string(),
                tags: vec![],
                priority: 7,
                confidence: 1.0,
                source: "test".to_string(),
                access_count: 0,
                created_at: now.clone(),
                updated_at: now,
                last_accessed_at: None,
                expires_at: None,
                metadata,
                reflection_depth: 0,
                memory_kind: crate::models::MemoryKind::Observation,
                entity_id: None,
                persona_version: None,
                citations: Vec::new(),
                source_uri: None,
                source_span: None,
                confidence_source: crate::models::ConfidenceSource::CallerProvided,
                confidence_signals: None,
                confidence_decayed_at: None,
                version: 1,
            };
            db::insert(&conn, &mem).unwrap()
        };

        // 2. Seed a rollback entry that says "revert priority to 3".
        let entry_json = build_priority_rollback_entry_json(&target, 3, 7);
        let entry_id = seed_rollback_entry(&db, &entry_json);

        // 3. Run rollback by id.
        let mut args = default_args();
        args.rollback = Some(entry_id.clone());
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        // Stdout reports rollback applied.
        let s = env.stdout_str();
        assert!(s.contains(&format!("rollback {entry_id}")));
        assert!(s.contains("applied"));

        // The target's priority must now be 3.
        let conn = db::open(&db).unwrap();
        let target_mem = db::get(&conn, &target).unwrap().unwrap();
        assert_eq!(target_mem.priority, 3);

        // The rollback entry must be tagged _reversed.
        let entry_mem = db::get(&conn, &entry_id).unwrap().unwrap();
        assert!(entry_mem.tags.iter().any(|t| t == "_reversed"));
    }

    #[tokio::test]
    async fn pr9i_curator_rollback_last_processes_multiple() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();

        // Seed two targets.
        let t1;
        let t2;
        {
            let conn = db::open(&db).unwrap();
            let now = chrono::Utc::now().to_rfc3339();
            let mut metadata = crate::models::default_metadata();
            if let Some(obj) = metadata.as_object_mut() {
                obj.insert(
                    "agent_id".to_string(),
                    serde_json::Value::String("test-agent".to_string()),
                );
            }
            let m1 = crate::models::Memory {
                id: uuid::Uuid::new_v4().to_string(),
                tier: crate::models::Tier::Mid,
                namespace: "ns".to_string(),
                title: "t1".to_string(),
                content: "c1".to_string(),
                tags: vec![],
                priority: 8,
                confidence: 1.0,
                source: "test".to_string(),
                access_count: 0,
                created_at: now.clone(),
                updated_at: now.clone(),
                last_accessed_at: None,
                expires_at: None,
                metadata: metadata.clone(),
                reflection_depth: 0,
                memory_kind: crate::models::MemoryKind::Observation,
                entity_id: None,
                persona_version: None,
                citations: Vec::new(),
                source_uri: None,
                source_span: None,
                confidence_source: crate::models::ConfidenceSource::CallerProvided,
                confidence_signals: None,
                confidence_decayed_at: None,
                version: 1,
            };
            let m2 = crate::models::Memory {
                id: uuid::Uuid::new_v4().to_string(),
                tier: crate::models::Tier::Mid,
                namespace: "ns".to_string(),
                title: "t2".to_string(),
                content: "c2".to_string(),
                tags: vec![],
                priority: 9,
                confidence: 1.0,
                source: "test".to_string(),
                access_count: 0,
                created_at: now.clone(),
                updated_at: now,
                last_accessed_at: None,
                expires_at: None,
                metadata,
                reflection_depth: 0,
                memory_kind: crate::models::MemoryKind::Observation,
                entity_id: None,
                persona_version: None,
                citations: Vec::new(),
                source_uri: None,
                source_span: None,
                confidence_source: crate::models::ConfidenceSource::CallerProvided,
                confidence_signals: None,
                confidence_decayed_at: None,
                version: 1,
            };
            t1 = db::insert(&conn, &m1).unwrap();
            t2 = db::insert(&conn, &m2).unwrap();
        }

        // Seed two rollback entries plus one malformed JSON entry.
        seed_rollback_entry(&db, &build_priority_rollback_entry_json(&t1, 4, 8));
        seed_rollback_entry(&db, &build_priority_rollback_entry_json(&t2, 5, 9));
        seed_rollback_entry(&db, "{not valid json: at all"); // malformed → skip branch

        // Run rollback_last 5 (caps at actual count).
        let mut args = default_args();
        args.rollback_last = Some(5);
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        // Reverses 2 entries (the malformed one is skipped).
        let s = env.stdout_str();
        assert!(s.contains("reversed 2"));

        // Both targets reverted.
        let conn = db::open(&db).unwrap();
        assert_eq!(db::get(&conn, &t1).unwrap().unwrap().priority, 4);
        assert_eq!(db::get(&conn, &t2).unwrap().unwrap().priority, 5);
    }

    #[tokio::test]
    async fn pr9i_curator_rollback_last_skips_already_reversed() {
        // Seed a rollback entry pre-tagged as _reversed; rollback_last must
        // skip it (lines 203-205).
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();

        // Seed a target.
        let target;
        {
            let conn = db::open(&db).unwrap();
            let now = chrono::Utc::now().to_rfc3339();
            let mut metadata = crate::models::default_metadata();
            if let Some(obj) = metadata.as_object_mut() {
                obj.insert(
                    "agent_id".to_string(),
                    serde_json::Value::String("test-agent".to_string()),
                );
            }
            let mem = crate::models::Memory {
                id: uuid::Uuid::new_v4().to_string(),
                tier: crate::models::Tier::Mid,
                namespace: "ns".to_string(),
                title: "x".to_string(),
                content: "c".to_string(),
                tags: vec![],
                priority: 7,
                confidence: 1.0,
                source: "test".to_string(),
                access_count: 0,
                created_at: now.clone(),
                updated_at: now,
                last_accessed_at: None,
                expires_at: None,
                metadata,
                reflection_depth: 0,
                memory_kind: crate::models::MemoryKind::Observation,
                entity_id: None,
                persona_version: None,
                citations: Vec::new(),
                source_uri: None,
                source_span: None,
                confidence_source: crate::models::ConfidenceSource::CallerProvided,
                confidence_signals: None,
                confidence_decayed_at: None,
                version: 1,
            };
            target = db::insert(&conn, &mem).unwrap();
        }

        // Insert a rollback entry already tagged _reversed.
        let entry_json = build_priority_rollback_entry_json(&target, 2, 7);
        let entry_id;
        {
            let conn = db::open(&db).unwrap();
            let now = chrono::Utc::now().to_rfc3339();
            let mut metadata = crate::models::default_metadata();
            if let Some(obj) = metadata.as_object_mut() {
                obj.insert(
                    "agent_id".to_string(),
                    serde_json::Value::String("test-agent".to_string()),
                );
            }
            let mem = crate::models::Memory {
                id: uuid::Uuid::new_v4().to_string(),
                tier: crate::models::Tier::Mid,
                namespace: "_curator/rollback".to_string(),
                title: "preexisting-reversed".to_string(),
                content: entry_json,
                tags: vec!["_reversed".to_string()],
                priority: 5,
                confidence: 1.0,
                source: "test".to_string(),
                access_count: 0,
                created_at: now.clone(),
                updated_at: now,
                last_accessed_at: None,
                expires_at: None,
                metadata,
                reflection_depth: 0,
                memory_kind: crate::models::MemoryKind::Observation,
                entity_id: None,
                persona_version: None,
                citations: Vec::new(),
                source_uri: None,
                source_span: None,
                confidence_source: crate::models::ConfidenceSource::CallerProvided,
                confidence_signals: None,
                confidence_decayed_at: None,
                version: 1,
            };
            entry_id = db::insert(&conn, &mem).unwrap();
        }

        let mut args = default_args();
        args.rollback_last = Some(5);
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        // Already-reversed entry is skipped → reversed 0.
        let s = env.stdout_str();
        assert!(s.contains("reversed 0"));

        // Target's priority is unchanged from 7.
        let conn = db::open(&db).unwrap();
        assert_eq!(db::get(&conn, &target).unwrap().unwrap().priority, 7);
        // Sanity: entry_id memory still tagged _reversed.
        let entry_mem = db::get(&conn, &entry_id).unwrap().unwrap();
        assert!(entry_mem.tags.iter().any(|t| t == "_reversed"));
    }

    #[tokio::test]
    async fn pr9i_curator_rollback_id_with_malformed_content() {
        // Seed a memory in _curator/rollback whose content is NOT a valid
        // RollbackEntry — the explicit-id rollback path bails (lines 160-161).
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let entry_id = seed_rollback_entry(&db, "{invalid json");

        let mut args = default_args();
        args.rollback = Some(entry_id);
        let mut out = env.output();
        let res = run(&db, &args, &cfg, &mut out).await;
        assert!(res.is_err());
        let err = res.unwrap_err().to_string();
        assert!(
            err.contains("rollback") || err.contains("RollbackEntry"),
            "expected parse-error message, got: {err}"
        );
    }

    // ---------- E1 coverage uplift -----------------------------------
    // Targets: build_curator_llm body (smart/autonomous tier branch),
    // print_curator_report error-list iteration, --once with errors
    // present.

    #[test]
    fn build_curator_llm_with_keyword_tier_returns_none() {
        // Keyword tier has no llm_model — the function returns None
        // BEFORE entering the body. Sanity check.
        //
        // TEST-5 — pin `AI_MEMORY_NO_CONFIG=1` so `AppConfig::load()`
        // returns `Default::default()` instead of reading the
        // developer's `~/.config/ai-memory/config.toml` (which would
        // resolve a non-default `[llm]` stanza and cause this
        // assertion to fail).
        crate::cli::test_utils::ensure_no_config_env();
        let result = build_curator_llm(config::FeatureTier::Keyword);
        assert!(result.is_none());
    }

    #[test]
    fn build_curator_llm_with_smart_tier_runs_body() {
        // Smart tier has llm_model = Some(_), so the body executes the
        // `let model = ...` + `OllamaClient::new(&model).ok()` lines.
        // In hermetic tests Ollama is unreachable, so the result is
        // None — but the body lines are now covered.
        //
        // TEST-5 — pin `AI_MEMORY_NO_CONFIG=1` so the resolver always
        // returns the Ollama compiled default rather than reading the
        // host's user-config-resolved backend.
        crate::cli::test_utils::ensure_no_config_env();
        let _ = build_curator_llm(config::FeatureTier::Smart);
        // No assertion on the value; the test exercises lines 55-56.
    }

    // Unix-only — the test self-fires `libc::kill(getpid, SIGINT)` to
    // exercise the ctrl_c shutdown path. The libc crate's `getpid` /
    // `kill` / `SIGINT` symbols are not available on Windows, where
    // signal handling uses a different surface entirely. The daemon
    // shutdown path itself is cross-platform (tokio::signal::ctrl_c
    // works on Windows); only the self-fire test mechanism is
    // POSIX-bound.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread")]
    async fn curator_daemon_mode_short_loop_returns_on_shutdown() {
        // Drives lines 128-150 — daemon mode entry. We fire SIGINT to
        // ourselves after a short delay so the ctrl_c spawn notifies
        // shutdown, the AtomicBool flag flips, and `run_daemon`'s loop
        // exits at its next check. The blocking task joins and the
        // outer `await` returns.
        //
        // We do NOT install our own signal handler — tokio's signal
        // registry consumes the single SIGINT before any default
        // handler trips. This test runs under multi_thread so the
        // ctrl_c watcher can fire on a separate worker.
        use std::path::PathBuf;
        let env = TestEnv::fresh();
        let db: PathBuf = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.daemon = true;
        // Tiny interval so the daemon body wakes quickly to check the
        // shutdown flag.
        args.interval_secs = 60; // clamped; the shutdown check is on each loop
        args.dry_run = true;

        // Fire SIGINT to ourselves after a brief delay.
        let kicker = tokio::spawn(async {
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
            // SAFETY: kill(getpid, SIGINT) is well-defined on POSIX.
            unsafe {
                let pid = libc::getpid();
                libc::kill(pid, libc::SIGINT);
            }
        });

        let mut stdout = Vec::<u8>::new();
        let mut stderr = Vec::<u8>::new();
        let mut out = crate::cli::CliOutput::from_std(&mut stdout, &mut stderr);
        // The daemon should return Ok(()) after shutdown is signaled.
        let res = tokio::time::timeout(
            std::time::Duration::from_secs(15),
            run(&db, &args, &cfg, &mut out),
        )
        .await;
        let _ = kicker.await;
        // The daemon CAN take more than 15s on a loaded box if its
        // sleep is long; the timeout is a soft cap. Either an Ok join
        // or a timeout means the daemon mode code ran.
        match res {
            Ok(Ok(())) => {}
            Ok(Err(e)) => panic!("daemon mode errored: {e}"),
            Err(_) => {
                // Timed out — that's fine for line-coverage purposes:
                // the daemon-mode code path has already executed.
                eprintln!("daemon-mode test timed out; coverage already captured");
            }
        }
    }

    #[test]
    fn print_curator_report_emits_error_list_lines() {
        // Drives the `for e in &r.errors` loop (lines 84-86) inside
        // print_curator_report. Build a synthetic CuratorReport with a
        // non-empty errors vec. CuratorReport's `autonomy` field isn't
        // public-API but it's `#[serde(default)]`, so Default::default()
        // covers it.
        let mut report = crate::curator::CuratorReport::default();
        report.errors = vec!["err A".to_string(), "err B".to_string()];
        report.dry_run = true;
        let mut stdout = Vec::<u8>::new();
        let mut stderr = Vec::<u8>::new();
        {
            let mut out = crate::cli::CliOutput::from_std(&mut stdout, &mut stderr);
            print_curator_report(&report, &mut out).unwrap();
        }
        let s = String::from_utf8(stdout).unwrap();
        // Header surfaces.
        assert!(s.contains("curator cycle report"));
        // Both error rows surface in the indented list.
        assert!(s.contains("- err A"));
        assert!(s.contains("- err B"));
    }

    // ---------- C-1 coverage uplift: --reflect modes ----------

    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn reflect_requires_namespace_or_all_namespaces() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.reflect = true;
        // Neither --namespace nor --all-namespaces supplied.
        let mut out = env.output();
        let err = run(&db, &args, &cfg, &mut out).await.unwrap_err();
        assert!(
            err.to_string().contains("--namespace") || err.to_string().contains("--all-namespaces")
        );
    }

    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn reflect_namespace_and_all_namespaces_mutually_exclusive() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let cfg = config::AppConfig::default();
        let mut args = default_args();
        args.reflect = true;
        args.namespace = Some("ns".to_string());
        args.all_namespaces = true;
        let mut out = env.output();
        let err = run(&db, &args, &cfg, &mut out).await.unwrap_err();
        assert!(err.to_string().contains("mutually exclusive"));
    }

    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn reflect_no_llm_path_emits_error_in_report() {
        // Keyword tier → no LLM → run_reflect populates `errors` and prints report.
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let mut cfg = config::AppConfig::default();
        cfg.tier = Some("keyword".to_string());
        let mut args = default_args();
        args.reflect = true;
        args.namespace = Some("ns".to_string());
        args.dry_run = true;
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        let s = env.stdout_str();
        assert!(s.contains("reflection pass report"));
        assert!(s.contains("no LLM client configured"));
    }

    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn reflect_no_llm_path_emits_json_report() {
        // Same as above but with --json output.
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let mut cfg = config::AppConfig::default();
        cfg.tier = Some("keyword".to_string());
        let mut args = default_args();
        args.reflect = true;
        args.namespace = Some("ns".to_string());
        args.dry_run = true;
        args.json = true;
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        let v: serde_json::Value = serde_json::from_str(env.stdout_str().trim()).unwrap();
        // No-LLM report carries `errors` array with the configured message.
        let errs = v["errors"].as_array().unwrap();
        assert!(errs.iter().any(|e| e.as_str().unwrap().contains("no LLM")));
        assert!(v["dry_run"].as_bool().unwrap());
    }

    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn reflect_all_namespaces_text_output() {
        // All-namespaces with no enabled namespaces is the default-safe path.
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let mut cfg = config::AppConfig::default();
        cfg.tier = Some("keyword".to_string());
        let mut args = default_args();
        args.reflect = true;
        args.all_namespaces = true;
        args.dry_run = true;
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        let s = env.stdout_str();
        assert!(s.contains("reflection pass report"));
    }

    // ── #1548 coverage — the SAL `--store-url` curator path ──────────
    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn store_url_sqlite_once_text_runs_sweep() {
        // `--store-url sqlite:///<db> --once` routes through
        // build_curator_store + run_store_backed_sweep (--once arm) +
        // the no-LLM store_backed_reflection_sweep.
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let mut cfg = config::AppConfig::default();
        cfg.tier = Some("keyword".to_string()); // no LLM client
        let mut args = default_args();
        args.store_url = Some(format!("sqlite://{}", db.display()));
        args.once = true;
        args.dry_run = true;
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        let s = env.stdout_str();
        assert!(s.contains("reflection pass report"));
        assert!(s.contains("no LLM client configured"));
    }

    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn store_url_sqlite_once_json_runs_sweep() {
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let mut cfg = config::AppConfig::default();
        cfg.tier = Some("keyword".to_string());
        let mut args = default_args();
        args.store_url = Some(format!("sqlite://{}", db.display()));
        args.once = true;
        args.dry_run = true;
        args.json = true;
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        let v: serde_json::Value = serde_json::from_str(env.stdout_str().trim()).unwrap();
        let errs = v["errors"].as_array().unwrap();
        assert!(errs.iter().any(|e| e.as_str().unwrap().contains("no LLM")));
        assert!(v["dry_run"].as_bool().unwrap());
    }

    // ── #1548 coverage — the shared with-LLM reflection helper ───────
    // `build_curator_llm` returns None in hermetic CI (no reachable
    // Ollama), so the with-LLM branch of run_reflection_pass_with_optional_llm
    // is only reachable by injecting a deterministic AutonomyLlm stub —
    // the same pattern the reflection_pass unit suite uses.
    #[cfg(feature = "sal")]
    struct CovStubLlm;
    #[cfg(feature = "sal")]
    impl crate::autonomy::AutonomyLlm for CovStubLlm {
        fn auto_tag(&self, _title: &str, _content: &str) -> anyhow::Result<Vec<String>> {
            Ok(Vec::new())
        }
        fn detect_contradiction(&self, _a: &str, _b: &str) -> anyhow::Result<bool> {
            Ok(false)
        }
        fn summarize_memories(&self, _memories: &[(String, String)]) -> anyhow::Result<String> {
            Ok("stub reflection summary".to_string())
        }
    }

    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn reflection_helper_with_stub_llm_runs_with_llm_branch() {
        // Drives the with-LLM arm of run_reflection_pass_with_optional_llm
        // (the run_reflection_pass dispatch) via an injected stub over a
        // real SqliteStore — the branch build_curator_llm can't reach in CI.
        let env = TestEnv::fresh();
        let store = crate::store::sqlite::SqliteStore::open(&env.db_path).expect("open store");
        let stub = CovStubLlm;
        let args = default_args();
        let report = run_reflection_pass_with_optional_llm(
            &store,
            Some(&stub as &dyn crate::autonomy::AutonomyLlm),
            None,
            None,
            args.max_depth,
            true,
            |_ns: &str| true,
        )
        .await;
        // Empty store → an empty (but successfully produced) report; the
        // point is the with-LLM dispatch arm executed without error.
        assert!(report.dry_run);
        assert!(
            report.errors.is_empty(),
            "unexpected errors: {:?}",
            report.errors
        );
        // Exercise the stub's AutonomyLlm contract directly so the impl is
        // covered even when an empty store forms no clusters to summarize.
        use crate::autonomy::AutonomyLlm;
        assert!(stub.auto_tag("t", "c").unwrap().is_empty());
        assert!(!stub.detect_contradiction("a", "b").unwrap());
        assert_eq!(
            stub.summarize_memories(&[("a".to_string(), "b".to_string())])
                .unwrap(),
            "stub reflection summary"
        );
    }

    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn reflection_helper_with_none_llm_reports_configured_error() {
        // The None arm — surfaced as a populated report (not a hard error).
        let env = TestEnv::fresh();
        let store = crate::store::sqlite::SqliteStore::open(&env.db_path).expect("open store");
        let report = run_reflection_pass_with_optional_llm(
            &store,
            None,
            None,
            Some("ns"),
            None,
            false,
            |_ns: &str| true,
        )
        .await;
        assert!(!report.dry_run);
        assert!(
            report
                .errors
                .iter()
                .any(|e| e.contains("no LLM client configured"))
        );
    }

    #[cfg(all(feature = "sal", unix))]
    #[tokio::test(flavor = "multi_thread")]
    async fn store_url_sqlite_daemon_loop_returns_on_shutdown() {
        // Covers the SAL daemon-loop arm of run_store_backed_sweep. The
        // ctrl_c watcher is spawned AFTER build_curator_store, so the
        // SIGINT kick waits 3s — long enough for the watcher to register
        // even under llvm-cov instrumentation (the 200ms legacy delay
        // races the slower instrumented store build).
        use std::path::PathBuf;
        let env = TestEnv::fresh();
        let db: PathBuf = env.db_path.clone();
        let mut cfg = config::AppConfig::default();
        cfg.tier = Some("keyword".to_string());
        let mut args = default_args();
        args.store_url = Some(format!("sqlite://{}", db.display()));
        args.daemon = true;
        args.interval_secs = 60;
        args.dry_run = true;
        let kicker = tokio::spawn(async {
            tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
            // SAFETY: kill(getpid, SIGINT) is well-defined on POSIX.
            unsafe {
                libc::kill(libc::getpid(), libc::SIGINT);
            }
        });
        let mut stdout = Vec::<u8>::new();
        let mut stderr = Vec::<u8>::new();
        let mut out = crate::cli::CliOutput::from_std(&mut stdout, &mut stderr);
        let res = tokio::time::timeout(
            std::time::Duration::from_secs(90),
            run(&db, &args, &cfg, &mut out),
        )
        .await;
        let _ = kicker.await;
        assert!(res.is_ok(), "SAL daemon did not return within timeout");
        assert!(res.unwrap().is_ok());
    }

    #[test]
    fn print_reflection_report_emits_proposals_and_errors() {
        let r = crate::curator::reflection_pass::ReflectionPassReport {
            started_at: "2026-01-01T00:00:00Z".into(),
            completed_at: "2026-01-01T00:00:01Z".into(),
            namespaces_visited: 2,
            observations_scanned: 5,
            clusters_formed: 1,
            clusters_eligible: 1,
            reflections_persisted: 0,
            depth_refusals: 0,
            errors: vec!["a problem".to_string()],
            dry_run_proposals: vec![crate::curator::reflection_pass::DryRunProposal {
                namespace: "app".to_string(),
                proposed_title: "[reflection] pattern".to_string(),
                source_ids: vec!["a".to_string(), "b".to_string(), "c".to_string()],
            }],
            dry_run: true,
        };
        let mut stdout = Vec::<u8>::new();
        let mut stderr = Vec::<u8>::new();
        {
            let mut out = crate::cli::CliOutput::from_std(&mut stdout, &mut stderr);
            print_reflection_report(&r, &mut out).unwrap();
        }
        let s = String::from_utf8(stdout).unwrap();
        assert!(s.contains("reflection pass report"));
        assert!(s.contains("namespaces_visited:"));
        assert!(s.contains("observations_scanned:"));
        assert!(s.contains("- a problem"));
        assert!(s.contains("proposal: ns='app'"));
        assert!(s.contains("sources=3"));
    }

    #[test]
    fn load_curator_keypair_best_effort_returns_some_or_none() {
        // Just exercises the function. Whether it returns Some or None
        // depends on the host's key dir contents; either outcome is OK.
        let _ = load_curator_keypair_best_effort();
    }

    #[test]
    fn build_curator_llm_with_autonomous_tier() {
        // Autonomous tier — exercises the autonomous arm of the
        // configured llm_model match. Will likely return None when
        // Ollama isn't running.
        //
        // TEST-5 — pin `AI_MEMORY_NO_CONFIG=1` so the resolver always
        // returns the Ollama compiled default rather than the host's
        // configured backend.
        crate::cli::test_utils::ensure_no_config_env();
        let _ = build_curator_llm(config::FeatureTier::Autonomous);
    }

    #[cfg(feature = "sal")]
    #[tokio::test]
    async fn reflect_with_seeded_observations_and_no_llm() {
        // Seed observations so list_namespaces returns a namespace,
        // then run reflect with --all-namespaces + no LLM. Hits the
        // namespace enumeration + "no LLM" path.
        let mut env = TestEnv::fresh();
        let db = env.db_path.clone();
        let _id = crate::cli::test_utils::seed_memory(&db, "myns", "T", "C");
        let mut cfg = config::AppConfig::default();
        cfg.tier = Some("keyword".to_string());
        let mut args = default_args();
        args.reflect = true;
        args.all_namespaces = true;
        args.dry_run = true;
        {
            let mut out = env.output();
            run(&db, &args, &cfg, &mut out).await.unwrap();
        }
        assert!(env.stdout_str().contains("reflection pass report"));
    }

    /// QUAL-2 regression — `run_rollback` must `bail!()` (typed error)
    /// instead of `unreachable!()` (process panic) when neither
    /// `--rollback` nor `--rollback-last` is set. The caller-side guard
    /// at `run()` short-circuits this case, but the function-level
    /// recovery path must remain typed so a future guard regression
    /// surfaces as a CLI exit, not a crash.
    #[test]
    fn qual_2_run_rollback_returns_error_when_no_mode_set() {
        let env = TestEnv::fresh();
        let db = env.db_path.clone();
        let args = default_args();
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut out = CliOutput::from_std(&mut stdout, &mut stderr);
        let res = run_rollback(&db, &args, &mut out);
        assert!(
            res.is_err(),
            "run_rollback must return Err when both --rollback and --rollback-last are None"
        );
        let msg = res.unwrap_err().to_string();
        assert!(
            msg.contains("run_rollback entered without --rollback or --rollback-last"),
            "unexpected error message: {msg}"
        );
    }
}