crtx 0.1.1

CLI for the Cortex supervisory memory substrate.
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
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
//! `cortex memory ...` — Phase 2 memory command surface.
//!
//! BUILD_SPEC Phase 2 requires `memory accept` and `memory search --explain`.

use clap::{Args, Subcommand};
use cortex_core::{
    accepted_axiom_source_commits, compose_policy_outcomes, is_axiom_source_commit_fresh,
    parse_authority_feedback_loop, parse_axiom_execution_trust, parse_cortex_context_trust,
    AuditRecordId, ClaimCeiling, ClaimProofState, MemoryId, PolicyContribution, PolicyOutcome,
    ProvenanceClass, SemanticTrustClass, SemanticUse,
    AXIOM_EXECUTION_TRUST_SOURCE_COMMIT_STALE_INVARIANT, CORTEX_AXIOM_ACCEPTED_SOURCE_COMMITS_ENV,
};
use cortex_memory::{
    AdmissionDecision, AdmissionEnvelopeError, AdmissionLifecycle, AdmissionSemanticTrustInput,
    AxiomMemoryAdmissionRequest, AxiomTrustExchangeAdmissionRequest, TrustExchangeAdmission,
};
use cortex_retrieval::{
    compose_fuzzy_boost, compose_lexical_semantic, cosine_similarity, extract_snippet, query_fts5,
    resolve_conflicts, score, snippet_ansi_highlighted, snippet_plain_text, tokenize_query,
    AuthorityLevel, AuthorityProofHint, ConflictingMemoryInput, EmbedRecord, Embedder,
    LexicalDocument, LexicalIndex, LocalStubEmbedder, OllamaEmbedder, ProofClosureHint,
    ScoreComponent, ScoreInputs, STUB_BACKEND_ID,
};
use cortex_store::proof::verify_memory_proof_closure;
use cortex_store::repo::memories::{
    accept_open_contradiction_contribution, accept_proof_closure_contribution,
    ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID, ACCEPT_SEMANTIC_TRUST_RULE_ID,
};
use cortex_store::repo::EmbeddingRepo;
use cortex_store::repo::{
    ContradictionRepo, MemoryAcceptanceAudit, MemoryRecord, MemoryRepo, MemorySessionUse,
    OutcomeMemoryRelationRecord,
};
use cortex_store::Pool;
use rusqlite::params as rparams;
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::{fs, io};

use crate::cmd::open_default_store;
use crate::config::EmbeddingBackend;
use crate::exit::Exit;
use crate::output::{self, Envelope};

/// `cortex memory ...` subcommands.
#[derive(Debug, Subcommand)]
pub enum MemorySub {
    /// Directly record an operator fact as an active memory — no reflection required.
    ///
    /// This is the fastest path to storing something: the operator writes the
    /// claim text and it lands in the active memory store immediately, bypassing
    /// the reflection pipeline. Use it when you know the fact you want stored.
    ///
    /// The memory gets `local_unsigned` ceiling, `operator_note` provenance,
    /// and `single_family` semantic trust — the same as any locally-produced
    /// memory, but admitted directly rather than through reflection.
    Note(NoteArgs),
    /// Accept a candidate memory into the durable active memory set.
    Accept(AcceptArgs),
    /// Validate an AXIOM admission envelope without persisting memory.
    AdmitAxiom(AdmitAxiomArgs),
    /// List durable active memories, optionally filtered by tag.
    List(ListArgs),
    /// Search durable memories.
    Search(SearchArgs),
    /// Enrich memories with Ollama semantic embeddings (additive; BLAKE3 unchanged).
    Embed(EmbedArgs),
    /// Operator-applied tag mutation surface (deferred — see invariant
    /// `memory.tag.write_path_pending_authority_revalidation`).
    #[command(subcommand)]
    Tag(TagSub),
    /// Record a session outcome (helpful / not-helpful) against a memory.
    #[command(subcommand)]
    Outcome(OutcomeSub),
    /// Surface unvalidated, low-confidence, or stale memories for review.
    Health(HealthArgs),
}

/// `cortex memory embed` arguments.
///
/// Walks all active memories; for each memory that has a BLAKE3 embedding
/// but no Ollama embedding, computes an Ollama embedding and writes it.
/// Already-enriched memories are skipped (idempotent).
#[derive(Debug, Args)]
pub struct EmbedArgs {
    /// Dry-run: show how many memories would be enriched without writing
    /// any embeddings.
    #[arg(long)]
    pub preview: bool,

    /// Ollama model to use (overrides config). Default: `nomic-embed-text`.
    #[arg(long, value_name = "MODEL")]
    pub model: Option<String>,

    /// Ollama endpoint (overrides config). Default: `http://localhost:11434`.
    #[arg(long, value_name = "URL")]
    pub endpoint: Option<String>,

    /// Expected embedding dimensionality (must match the model). Default: 768.
    #[arg(long, value_name = "DIM", default_value = "768")]
    pub dim: usize,
}

/// `cortex memory accept <memory_id>` arguments.
#[derive(Debug, Args)]
pub struct AcceptArgs {
    /// Candidate memory identifier to accept.
    #[arg(value_name = "MEMORY_ID")]
    pub candidate_id: MemoryId,
}

/// `cortex memory admit-axiom --file <path>|--json <json>` arguments.
///
/// Either supply a single ADR 0038 admission envelope (`--file` / `--json`),
/// or supply one or more pai-axiom field-level trust exchange envelopes
/// (`--cortex-context-trust`, `--axiom-execution-trust`,
/// `--authority-feedback-loop`). The field-level path mirrors ADR 0042/0043
/// requirements and emits the named per-source quarantine outputs on
/// stderr along with the JSON envelope on stdout.
#[derive(Debug, Args)]
pub struct AdmitAxiomArgs {
    /// Path to an ADR 0038 AXIOM admission envelope JSON file.
    #[arg(
        long,
        value_name = "PATH",
        conflicts_with_all = [
            "json",
            "cortex_context_trust",
            "axiom_execution_trust",
            "authority_feedback_loop",
        ]
    )]
    pub file: Option<PathBuf>,

    /// Inline ADR 0038 AXIOM admission envelope JSON.
    #[arg(
        long,
        value_name = "JSON",
        conflicts_with_all = [
            "file",
            "cortex_context_trust",
            "axiom_execution_trust",
            "authority_feedback_loop",
        ]
    )]
    pub json: Option<String>,

    /// Path to a pai-axiom cortex_context_trust v1 envelope JSON file.
    #[arg(long, value_name = "PATH")]
    pub cortex_context_trust: Option<PathBuf>,

    /// Path to a pai-axiom axiom_execution_trust v1 envelope JSON file.
    #[arg(long, value_name = "PATH")]
    pub axiom_execution_trust: Option<PathBuf>,

    /// Path to a pai-axiom authority_feedback_loop v1 record JSON file.
    #[arg(long, value_name = "PATH")]
    pub authority_feedback_loop: Option<PathBuf>,

    /// Explicit lifecycle assertion — only `candidate_only` is admissible.
    #[arg(long, value_name = "LIFECYCLE", default_value = "candidate_only")]
    pub lifecycle: String,

    /// Treat the admission lineage as derived from a quarantined ancestor.
    #[arg(long)]
    pub derived_from_quarantined: bool,
}

/// `cortex memory search <query>` arguments.
#[derive(Debug, Args)]
pub struct SearchArgs {
    /// Query text.
    #[arg(value_name = "QUERY")]
    pub query: String,

    /// Print component-level retrieval explanation when search is wired.
    #[arg(long)]
    pub explain: bool,

    /// Restrict matches to memories whose `domains_json` carries this tag.
    /// Repeat the flag to AND multiple tags together; an active memory must
    /// carry every supplied tag to be returned.
    #[arg(long = "tag", value_name = "TAG")]
    pub tag: Vec<String>,

    /// Opt-in fuzzy retrieval over the FTS5 trigram mirror (Phase 4.B).
    ///
    /// Default OFF: the lexical + salience baseline ships byte-for-byte
    /// unchanged. When set, FTS5 BM25 ranks are blended with the
    /// deterministic lexical scorer at weight
    /// [`cortex_retrieval::FUZZY_BOOST_WEIGHT`] so a typo-of-one-character
    /// query still surfaces an otherwise-unmatched memory while exact
    /// lexical hits stay dominant.
    #[arg(long)]
    pub fuzzy: bool,

    /// Opt-in semantic reranking via the Phase 4.C embedding composer.
    ///
    /// When set, query text is embedded with the BLAKE3 stub backend
    /// (`LocalStubEmbedder`) and cosine similarity against per-memory
    /// embeddings is blended into the final score via
    /// `compose_lexical_semantic`. Memories whose embeddings are absent
    /// in the store are scored with `sem_score = 0.0` (graceful
    /// degradation).
    ///
    /// Semantic embeddings for each memory are computed on-demand at
    /// search time using the same deterministic BLAKE3 stub the
    /// `EmbeddingRepo` writes; no offline pre-computation step is needed
    /// for the stub backend.
    #[arg(long)]
    pub semantic: bool,

    /// Show a highlighted text snippet for each result instead of the full claim.
    ///
    /// The snippet is a `MAX_SNIPPET_CHARS`-character window centred on the
    /// first query-term match in the memory's claim, with matched terms
    /// highlighted. On colour-capable terminals, matched terms are displayed
    /// in bold. In `--json` mode, a `snippet` field is added to each result
    /// carrying the plain-text window and `highlight_ranges` (byte-offset
    /// pairs into the window).
    #[arg(long)]
    pub snippet: bool,
}

/// `cortex memory tag ...` subcommands — stubbed-out tag-mutation surface.
///
/// Tag writes are deferred until the operator-temporal-use authority closure
/// (ADR 0023 / ADR 0026 §4 — the same `Allow` gate that `memory accept`
/// composes) is wired honestly for arbitrary durable-row metadata mutation.
/// See [`TAG_WRITE_PENDING_INVARIANT`] for the stable invariant the deferred
/// path emits, and the comment on [`tag`] for the reasoning.
#[derive(Debug, Subcommand)]
pub enum TagSub {
    /// Add a tag to a memory's `domains_json` (deferred).
    Add(TagAddArgs),
    /// Remove a tag from a memory's `domains_json` (deferred).
    Remove(TagRemoveArgs),
}

/// `cortex memory tag add <memory-id> <tag>` arguments.
#[derive(Debug, Args)]
pub struct TagAddArgs {
    /// Memory id whose `domains_json` should gain a tag.
    #[arg(value_name = "MEMORY_ID")]
    pub memory_id: MemoryId,
    /// Tag to add to the memory's `domains_json`.
    #[arg(value_name = "TAG")]
    pub tag: String,
}

/// `cortex memory tag remove <memory-id> <tag>` arguments.
#[derive(Debug, Args)]
pub struct TagRemoveArgs {
    /// Memory id whose `domains_json` should lose a tag.
    #[arg(value_name = "MEMORY_ID")]
    pub memory_id: MemoryId,
    /// Tag to remove from the memory's `domains_json`.
    #[arg(value_name = "TAG")]
    pub tag: String,
}

/// `cortex memory outcome ...` subcommands.
#[derive(Debug, Subcommand)]
pub enum OutcomeSub {
    /// Record a helpful / not-helpful verdict for a memory used in a session.
    Record(OutcomeRecordArgs),
}

/// `cortex memory outcome record` arguments.
#[derive(Debug, Args)]
pub struct OutcomeRecordArgs {
    /// Memory id whose outcome is being recorded.
    #[arg(long, value_name = "ID")]
    pub memory_id: MemoryId,

    /// Session in which the memory was used.
    #[arg(long, value_name = "SESSION_ID")]
    pub session: String,

    /// Verdict: `helpful` or `not-helpful`.
    #[arg(long, value_name = "RESULT")]
    pub result: OutcomeResult,

    /// Optional operator note attached to the outcome record.
    #[arg(long, value_name = "TEXT")]
    pub note: Option<String>,
}

/// Verdict supplied to `cortex memory outcome record --result`.
#[derive(Debug, Clone, PartialEq, Eq, clap::ValueEnum)]
pub enum OutcomeResult {
    /// Memory was helpful in the session.
    Helpful,
    /// Memory was not helpful in the session.
    NotHelpful,
}

/// `cortex memory health` arguments.
#[derive(Debug, Args)]
pub struct HealthArgs {
    /// Show only memories that have never appeared in a session use record.
    #[arg(long)]
    pub unvalidated_only: bool,

    /// Memories older than this many days are flagged as stale (default 30).
    #[arg(long, value_name = "DAYS", default_value = "30")]
    pub older_than: u32,

    /// Flag memories whose `confidence` column is below this value.
    #[arg(long, value_name = "FLOAT", default_value = "0.5")]
    pub confidence_below: f64,
}

/// Stable invariant emitted when `cortex memory outcome record` is called with
/// an unknown or non-active memory id.
pub const OUTCOME_MEMORY_NOT_FOUND_INVARIANT: &str = "memory.outcome.memory_not_found";

/// Stable invariant emitted when an operator invokes the deferred tag-write
/// surface. The invariant unblocks once the concurrent temporal-authority
/// closure lands the operator-temporal-use contributor for arbitrary
/// durable-row mutation (the same gate `memory accept` already composes).
pub const TAG_WRITE_PENDING_INVARIANT: &str =
    "memory.tag.write_path_pending_authority_revalidation";

/// Phase 2.6 T3 closure: stable invariant emitted on the operator
/// temporal-use contributor for `cortex memory accept` when the CLI
/// surface has no bound operator key.
///
/// Per `docs/design/PHASE_2_6_temporal_authority_revalidation_audit.md`
/// §2.2 row "`cortex memory accept` operator temporal use", the surface
/// today carries no `--operator-attestation` flag, so the contributor
/// literally has nothing to revalidate. Pivoting the literal `Allow`
/// (with the misleading rationale "operator CLI invocation is the
/// attested current-use action") to `Warn` with this stable invariant
/// keeps the surface operational without claiming temporal authority.
///
/// ADR 0026 §4 forbids BreakGlass substituting for a required attestation
/// contributor; this `Warn` is the *honest no-attestation floor* — NOT a
/// BreakGlass substitution — so the store-side check accepts it (see
/// [`cortex_store::repo::memories::require_attestation_not_break_glassed`]).
pub const ACCEPT_OPERATOR_TEMPORAL_AUTHORITY_WARN_NO_ATTESTATION_INVARIANT: &str =
    "memory.accept.operator_temporal_authority.warn_no_attestation";

/// `cortex memory list` arguments.
///
/// Lists durable active memories without scoring them, optionally filtered
/// by tag. `--tag` is repeatable and ANDs together — a memory must carry
/// every supplied tag to be returned.
#[derive(Debug, Args)]
pub struct ListArgs {
    /// Restrict the listing to memories whose `domains_json` carries this
    /// tag. Repeat the flag to AND multiple tags together.
    #[arg(long = "tag", value_name = "TAG")]
    pub tag: Vec<String>,
}

/// `cortex memory note` arguments.
#[derive(Debug, Args)]
pub struct NoteArgs {
    /// The fact to record as an active memory. Keep it to one clear claim.
    pub claim: String,

    /// Domain tags (repeat for multiple: --domain cortex --domain publish).
    #[arg(long = "domain", value_name = "TAG")]
    pub domains: Vec<String>,

    /// Optional confidence override (0.0 – 1.0). Defaults to 0.9 for operator notes.
    #[arg(long, default_value = "0.9")]
    pub confidence: f64,
}

/// Run a `cortex memory ...` command.
pub fn run(sub: MemorySub) -> Exit {
    match sub {
        MemorySub::Note(args) => note(args),
        MemorySub::Accept(args) => accept(args),
        MemorySub::AdmitAxiom(args) => admit_axiom(args),
        MemorySub::List(args) => list(args),
        MemorySub::Search(args) => search(args),
        MemorySub::Embed(args) => embed(args),
        MemorySub::Tag(sub) => tag(sub),
        MemorySub::Outcome(sub) => outcome(sub),
        MemorySub::Health(args) => health(args),
    }
}

/// `cortex memory tag ...` dispatcher.
///
/// T3 temporal-authority closure is now live across 5 surfaces. The
/// deferred hard-refusal has been replaced with the real composed-policy
/// write path using the same operator-temporal-use `Warn` floor that
/// `memory accept` composes (ADR 0026 §4, ADR 0023). The stable
/// invariant [`TAG_WRITE_PENDING_INVARIANT`] is kept for documentation;
/// the function body no longer emits it.
fn tag(sub: TagSub) -> Exit {
    match sub {
        TagSub::Add(args) => add_tag(args),
        TagSub::Remove(args) => remove_tag(args),
    }
}

fn add_tag(args: TagAddArgs) -> Exit {
    let pool = match open_default_store("memory tag add") {
        Ok(pool) => pool,
        Err(exit) => {
            if output::json_enabled() {
                let payload = json!({ "detail": "failed to open store" });
                let envelope = Envelope::new("cortex.memory.tag.add", exit, payload);
                return output::emit(&envelope, exit);
            }
            return exit;
        }
    };

    // Operator temporal-use gate: the same honest no-attestation Warn floor
    // that `memory accept` composes. No operator key is bound on this CLI
    // surface; the floor is Warn rather than a misleading Allow.
    let operator_temporal_contribution = tag_operator_temporal_contribution();

    let policy = cortex_core::compose_policy_outcomes(vec![operator_temporal_contribution], None);
    match policy.final_outcome {
        cortex_core::PolicyOutcome::Quarantine | cortex_core::PolicyOutcome::Reject => {
            let exit = Exit::PreconditionUnmet;
            if output::json_enabled() {
                let payload = json!({
                    "detail": format!(
                        "invariant={TAG_WRITE_PENDING_INVARIANT}: \
                         operator temporal authority gate blocked tag mutation"
                    )
                });
                let envelope = Envelope::new("cortex.memory.tag.add", exit, payload);
                return output::emit(&envelope, exit);
            }
            eprintln!(
                "cortex memory tag add: invariant={TAG_WRITE_PENDING_INVARIANT} \
                 operator temporal authority gate blocked tag mutation"
            );
            return exit;
        }
        _ => {}
    }

    let repo = MemoryRepo::new(&pool);
    match repo.add_domain_tag(&args.memory_id, &args.tag, chrono::Utc::now()) {
        Ok(true) => {
            let id = args.memory_id.to_string();
            let tag = &args.tag;
            if !output::json_enabled() {
                println!("memory tag add: tag '{tag}' added to {id}");
                return Exit::Ok;
            }
            let payload = json!({
                "memory_id": id,
                "tag": tag,
                "added": true,
                "persisted": true,
            });
            let envelope = Envelope::new("cortex.memory.tag.add", Exit::Ok, payload);
            output::emit(&envelope, Exit::Ok)
        }
        Ok(false) => {
            let id = args.memory_id.to_string();
            let tag = &args.tag;
            if !output::json_enabled() {
                println!("memory tag add: tag '{tag}' already present on {id}");
                return Exit::Ok;
            }
            let payload = json!({
                "memory_id": id,
                "tag": tag,
                "added": false,
                "persisted": false,
            });
            let envelope = Envelope::new("cortex.memory.tag.add", Exit::Ok, payload);
            output::emit(&envelope, Exit::Ok)
        }
        Err(cortex_store::StoreError::Validation(msg)) => {
            let exit = Exit::PreconditionUnmet;
            if output::json_enabled() {
                let payload = json!({ "detail": format!("precondition unmet: {msg}") });
                let envelope = Envelope::new("cortex.memory.tag.add", exit, payload);
                return output::emit(&envelope, exit);
            }
            eprintln!("cortex memory tag add: precondition unmet: {msg}");
            exit
        }
        Err(err) => {
            let exit = Exit::Internal;
            if output::json_enabled() {
                let payload = json!({ "detail": format!("internal error: {err}") });
                let envelope = Envelope::new("cortex.memory.tag.add", exit, payload);
                return output::emit(&envelope, exit);
            }
            eprintln!("cortex memory tag add: internal error: {err}");
            exit
        }
    }
}

fn remove_tag(args: TagRemoveArgs) -> Exit {
    let pool = match open_default_store("memory tag remove") {
        Ok(pool) => pool,
        Err(exit) => {
            if output::json_enabled() {
                let payload = json!({ "detail": "failed to open store" });
                let envelope = Envelope::new("cortex.memory.tag.remove", exit, payload);
                return output::emit(&envelope, exit);
            }
            return exit;
        }
    };

    // Operator temporal-use gate: same Warn floor as add_tag / memory accept.
    let operator_temporal_contribution = tag_operator_temporal_contribution();

    let policy = cortex_core::compose_policy_outcomes(vec![operator_temporal_contribution], None);
    match policy.final_outcome {
        cortex_core::PolicyOutcome::Quarantine | cortex_core::PolicyOutcome::Reject => {
            let exit = Exit::PreconditionUnmet;
            if output::json_enabled() {
                let payload = json!({
                    "detail": format!(
                        "invariant={TAG_WRITE_PENDING_INVARIANT}: \
                         operator temporal authority gate blocked tag mutation"
                    )
                });
                let envelope = Envelope::new("cortex.memory.tag.remove", exit, payload);
                return output::emit(&envelope, exit);
            }
            eprintln!(
                "cortex memory tag remove: invariant={TAG_WRITE_PENDING_INVARIANT} \
                 operator temporal authority gate blocked tag mutation"
            );
            return exit;
        }
        _ => {}
    }

    let repo = MemoryRepo::new(&pool);
    match repo.remove_domain_tag(&args.memory_id, &args.tag, chrono::Utc::now()) {
        Ok(true) => {
            let id = args.memory_id.to_string();
            let tag = &args.tag;
            if !output::json_enabled() {
                println!("memory tag remove: tag '{tag}' removed from {id}");
                return Exit::Ok;
            }
            let payload = json!({
                "memory_id": id,
                "tag": tag,
                "removed": true,
                "persisted": true,
            });
            let envelope = Envelope::new("cortex.memory.tag.remove", Exit::Ok, payload);
            output::emit(&envelope, Exit::Ok)
        }
        Ok(false) => {
            let id = args.memory_id.to_string();
            let tag = &args.tag;
            if !output::json_enabled() {
                println!("memory tag remove: tag '{tag}' not present on {id}");
                return Exit::Ok;
            }
            let payload = json!({
                "memory_id": id,
                "tag": tag,
                "removed": false,
                "persisted": false,
            });
            let envelope = Envelope::new("cortex.memory.tag.remove", Exit::Ok, payload);
            output::emit(&envelope, Exit::Ok)
        }
        Err(cortex_store::StoreError::Validation(msg)) => {
            let exit = Exit::PreconditionUnmet;
            if output::json_enabled() {
                let payload = json!({ "detail": format!("precondition unmet: {msg}") });
                let envelope = Envelope::new("cortex.memory.tag.remove", exit, payload);
                return output::emit(&envelope, exit);
            }
            eprintln!("cortex memory tag remove: precondition unmet: {msg}");
            exit
        }
        Err(err) => {
            let exit = Exit::Internal;
            if output::json_enabled() {
                let payload = json!({ "detail": format!("internal error: {err}") });
                let envelope = Envelope::new("cortex.memory.tag.remove", exit, payload);
                return output::emit(&envelope, exit);
            }
            eprintln!("cortex memory tag remove: internal error: {err}");
            exit
        }
    }
}

/// Build the operator temporal-use contributor for tag mutation surfaces.
///
/// Mirrors the pattern used by `memory accept`: no operator attestation is
/// bound on this CLI surface, so the contributor votes `Warn` with the
/// stable honest-floor invariant rather than a misleading `Allow`. ADR 0026
/// §4 still applies — any future contributor that returns `Quarantine` /
/// `Reject` would compose through the total order without override.
fn tag_operator_temporal_contribution() -> PolicyContribution {
    PolicyContribution::new(
        ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID,
        PolicyOutcome::Warn,
        format!(
            "{ACCEPT_OPERATOR_TEMPORAL_AUTHORITY_WARN_NO_ATTESTATION_INVARIANT}: \
             no operator attestation bound on this CLI surface; accepting at the honest floor",
        ),
    )
    .expect("tag operator temporal contribution shape is valid")
}

fn outcome(sub: OutcomeSub) -> Exit {
    match sub {
        OutcomeSub::Record(args) => outcome_record(args),
    }
}

fn outcome_record(args: OutcomeRecordArgs) -> Exit {
    if args.session.trim().is_empty() {
        eprintln!("cortex memory outcome record: --session must not be empty");
        return outcome_record_failure_envelope(Exit::Usage, "session must not be empty", None);
    }

    let pool = match open_default_store("memory outcome record") {
        Ok(pool) => pool,
        Err(exit) => return outcome_record_failure_envelope(exit, "failed to open store", None),
    };
    let repo = MemoryRepo::new(&pool);

    // Validate that the memory exists and is active.
    let memory = match repo.get_by_id(&args.memory_id) {
        Ok(Some(m)) if m.status == "active" => m,
        Ok(Some(_)) => {
            let detail = format!(
                "{OUTCOME_MEMORY_NOT_FOUND_INVARIANT}: memory {} exists but is not active",
                args.memory_id
            );
            eprintln!("cortex memory outcome record: {detail}");
            return outcome_record_failure_envelope(
                Exit::PreconditionUnmet,
                &detail,
                Some(args.memory_id.to_string()),
            );
        }
        Ok(None) => {
            let detail = format!(
                "{OUTCOME_MEMORY_NOT_FOUND_INVARIANT}: memory {} not found",
                args.memory_id
            );
            eprintln!("cortex memory outcome record: {detail}");
            return outcome_record_failure_envelope(
                Exit::PreconditionUnmet,
                &detail,
                Some(args.memory_id.to_string()),
            );
        }
        Err(err) => {
            let detail = format!("failed to look up memory {}: {err}", args.memory_id);
            eprintln!("cortex memory outcome record: {detail}");
            return outcome_record_failure_envelope(
                Exit::Internal,
                &detail,
                Some(args.memory_id.to_string()),
            );
        }
    };

    let now = chrono::Utc::now();

    // Write the session-use edge so cross_session_use_count is reconciled.
    let session_use = MemorySessionUse {
        memory_id: memory.id,
        session_id: args.session.clone(),
        first_used_at: now,
        last_used_at: now,
        use_count: 1,
    };
    if let Err(err) = repo.record_session_use(&session_use) {
        let detail = format!("failed to record session use: {err}");
        eprintln!("cortex memory outcome record: {detail}");
        return outcome_record_failure_envelope(
            Exit::Internal,
            &detail,
            Some(args.memory_id.to_string()),
        );
    }

    // Map helpful/not-helpful to an OutcomeMemoryRelation variant.
    let relation = match args.result {
        OutcomeResult::Helpful => cortex_core::OutcomeMemoryRelation::Used,
        OutcomeResult::NotHelpful => cortex_core::OutcomeMemoryRelation::Rejected,
    };
    let result_name = match args.result {
        OutcomeResult::Helpful => "helpful",
        OutcomeResult::NotHelpful => "not-helpful",
    };

    // Build a deterministic outcome_ref from the session + memory id + result.
    let outcome_ref = format!(
        "outcome:{}:{}:{}",
        args.session, args.memory_id, result_name
    );

    // Include an optional note in a source event id field if provided,
    // encoded as a reference string rather than a real event (no event write required).
    let relation_record = OutcomeMemoryRelationRecord {
        outcome_ref: outcome_ref.clone(),
        memory_id: args.memory_id,
        relation,
        recorded_at: now,
        source_event_id: None,
        validation_scope: None,
        validating_principal_id: None,
        evidence_ref: None,
    };

    if let Err(err) = repo.record_outcome_relation(&relation_record, None) {
        let detail = format!("failed to record outcome relation: {err}");
        eprintln!("cortex memory outcome record: {detail}");
        return outcome_record_failure_envelope(
            Exit::Internal,
            &detail,
            Some(args.memory_id.to_string()),
        );
    }

    if !output::json_enabled() {
        println!(
            "outcome recorded: memory {} marked {} for session {}",
            args.memory_id, result_name, args.session
        );
        if let Some(note) = &args.note {
            println!("  note: {note}");
        }
        return Exit::Ok;
    }

    let payload = json!({
        "memory_id": args.memory_id.to_string(),
        "session_id": args.session,
        "result": result_name,
        "outcome_ref": outcome_ref,
        "note": args.note,
        "persisted": true,
    });
    let envelope = Envelope::new("cortex.memory.outcome.record", Exit::Ok, payload);
    output::emit(&envelope, Exit::Ok)
}

fn outcome_record_failure_envelope(exit: Exit, detail: &str, memory_id: Option<String>) -> Exit {
    if !output::json_enabled() {
        return exit;
    }
    let payload = json!({
        "memory_id": memory_id,
        "detail": detail,
        "persisted": false,
    });
    let envelope = Envelope::new("cortex.memory.outcome.record", exit, payload);
    output::emit(&envelope, exit)
}

fn health(args: HealthArgs) -> Exit {
    let pool = match open_default_store("memory health") {
        Ok(pool) => pool,
        Err(exit) => return health_failure_envelope(exit, "failed to open store"),
    };

    let conn = pool.prepare("SELECT id, confidence, created_at, validation_epoch, cross_session_use_count FROM memories WHERE status = 'active';");
    let mut stmt = match conn {
        Ok(s) => s,
        Err(err) => {
            let detail = format!("failed to prepare health query: {err}");
            eprintln!("cortex memory health: {detail}");
            return health_failure_envelope(Exit::Internal, &detail);
        }
    };

    let cutoff_days = i64::from(args.older_than);
    let cutoff_dt = chrono::Utc::now() - chrono::Duration::days(cutoff_days);
    let cutoff_rfc = cutoff_dt.to_rfc3339();

    #[derive(Debug)]
    struct HealthRow {
        id: String,
        confidence: f64,
        created_at: String,
        validation_epoch: Option<i64>,
        cross_session_use_count: Option<i64>,
    }

    let rows_result = stmt.query_map(rparams![], |row| {
        Ok(HealthRow {
            id: row.get(0)?,
            confidence: row.get(1)?,
            created_at: row.get(2)?,
            validation_epoch: row.get(3)?,
            cross_session_use_count: row.get(4)?,
        })
    });

    let rows = match rows_result {
        Ok(r) => r,
        Err(err) => {
            let detail = format!("failed to query active memories: {err}");
            eprintln!("cortex memory health: {detail}");
            return health_failure_envelope(Exit::Internal, &detail);
        }
    };

    let mut total = 0u64;
    let mut low_confidence_ids: Vec<String> = Vec::new();
    let mut never_validated_ids: Vec<String> = Vec::new();
    let mut older_than_ids: Vec<String> = Vec::new();
    let mut no_outcome_ids: Vec<String> = Vec::new();

    for row_result in rows {
        let row = match row_result {
            Ok(r) => r,
            Err(err) => {
                let detail = format!("failed to read health row: {err}");
                eprintln!("cortex memory health: {detail}");
                return health_failure_envelope(Exit::Internal, &detail);
            }
        };
        total += 1;

        if row.confidence < args.confidence_below {
            low_confidence_ids.push(row.id.clone());
        }

        let validation_epoch = row.validation_epoch.unwrap_or(0);
        if validation_epoch == 0 {
            never_validated_ids.push(row.id.clone());
        }

        // Memories created before the cutoff are "old".
        if row.created_at.as_str() < cutoff_rfc.as_str() {
            older_than_ids.push(row.id.clone());
        }

        // Memories with zero cross-session use have no outcome records.
        let use_count = row.cross_session_use_count.unwrap_or(0);
        if use_count == 0 {
            no_outcome_ids.push(row.id.clone());
        }
    }

    // When --unvalidated-only, restrict to the never-validated set.
    if args.unvalidated_only {
        let nv_ids: std::collections::BTreeSet<&str> =
            never_validated_ids.iter().map(|s| s.as_str()).collect();
        low_confidence_ids.retain(|id| nv_ids.contains(id.as_str()));
        older_than_ids.retain(|id| nv_ids.contains(id.as_str()));
        no_outcome_ids.retain(|id| nv_ids.contains(id.as_str()));
    }

    let json_mode = output::json_enabled();
    if !json_mode {
        println!("memory health:");
        println!("  total active: {total}");
        println!(
            "  low confidence (<{}): {}",
            args.confidence_below,
            low_confidence_ids.len()
        );
        println!("  never validated: {}", never_validated_ids.len());
        println!(
            "  older than {} days: {}",
            args.older_than,
            older_than_ids.len()
        );
        println!("  no outcome recorded: {}", no_outcome_ids.len());
        return Exit::Ok;
    }

    let payload = json!({
        "total_active": total,
        "low_confidence_count": low_confidence_ids.len(),
        "never_validated_count": never_validated_ids.len(),
        "older_than_days_count": older_than_ids.len(),
        "no_outcome_count": no_outcome_ids.len(),
        "older_than_days": args.older_than,
        "confidence_below": args.confidence_below,
        "low_confidence_ids": low_confidence_ids,
        "never_validated_ids": never_validated_ids,
        "older_than_ids": older_than_ids,
        "no_outcome_ids": no_outcome_ids,
    });
    let envelope = Envelope::new("cortex.memory.health", Exit::Ok, payload);
    output::emit(&envelope, Exit::Ok)
}

fn health_failure_envelope(exit: Exit, detail: &str) -> Exit {
    if !output::json_enabled() {
        return exit;
    }
    let payload = json!({
        "detail": detail,
        "total_active": 0,
    });
    let envelope = Envelope::new("cortex.memory.health", exit, payload);
    output::emit(&envelope, exit)
}

fn accept(args: AcceptArgs) -> Exit {
    let pool = match open_default_store("memory accept") {
        Ok(pool) => pool,
        Err(exit) => return memory_accept_envelope(exit, None, "failed to open store", None),
    };
    let repo = MemoryRepo::new(&pool);
    let audit = MemoryAcceptanceAudit {
        id: AuditRecordId::new(),
        actor_json: json!({"kind": "cli", "command": "memory accept"}),
        reason: "operator accepted candidate memory via CLI".to_string(),
        source_refs_json: json!([args.candidate_id.to_string()]),
        created_at: chrono::Utc::now(),
    };

    let (policy, proof_closure) = match compose_memory_accept_policy(&pool, &args.candidate_id) {
        Ok(value) => value,
        Err(exit) => return exit,
    };

    match cortex_memory::accept(
        &repo,
        &args.candidate_id,
        chrono::Utc::now(),
        &audit,
        &policy,
        &proof_closure,
    ) {
        Ok(id) => {
            let id_str = id.to_string();
            if !output::json_enabled() {
                println!("cortex memory accept: accepted {id_str}");
            }
            memory_accept_envelope(Exit::Ok, Some(id_str), "accepted", Some(&policy))
        }
        Err(err) => {
            eprintln!("cortex memory accept: {err}");
            memory_accept_envelope(
                Exit::PreconditionUnmet,
                None,
                &err.to_string(),
                Some(&policy),
            )
        }
    }
}

/// `cortex memory note` — directly admit an operator-written fact as an active memory.
///
/// Bypasses the reflection pipeline: the claim goes straight into the active
/// memory store without needing a candidate stage or an LLM. This is the
/// fastest path from "I want this remembered" to "it is remembered".
fn note(args: NoteArgs) -> Exit {
    let json = output::json_enabled();
    let claim = args.claim.trim().to_string();
    if claim.is_empty() {
        if !json { eprintln!("memory note: claim must not be empty"); }
        return Exit::Usage;
    }
    if args.confidence < 0.0 || args.confidence > 1.0 {
        if !json { eprintln!("memory note: confidence must be in [0.0, 1.0]"); }
        return Exit::Usage;
    }

    let pool = match open_default_store("memory note") {
        Ok(pool) => pool,
        Err(exit) => {
            if !json { eprintln!("memory note: failed to open store"); }
            return exit;
        }
    };
    let repo = MemoryRepo::new(&pool);
    let now = chrono::Utc::now();
    let id = MemoryId::new();

    // Build and insert the candidate directly.
    let domains: Vec<String> = if args.domains.is_empty() {
        vec!["operator_note".to_string()]
    } else {
        args.domains.clone()
    };

    let candidate = cortex_store::repo::memories::MemoryCandidate {
        id,
        memory_type: "operator_note".to_string(),
        claim: claim.clone(),
        confidence: args.confidence,
        authority: "operator".to_string(),
        domains_json: serde_json::to_value(&domains).unwrap_or(serde_json::json!([])),
        source_events_json: serde_json::json!([]),
        source_episodes_json: serde_json::json!([]),
        salience_json: serde_json::json!({}),
        applies_when_json: serde_json::json!(null),
        does_not_apply_when_json: serde_json::json!(null),
        created_at: now,
        updated_at: now,
    };

    if let Err(err) = repo.insert_candidate(&candidate) {
        if !json { eprintln!("memory note: failed to insert candidate: {err}"); }
        return Exit::Internal;
    }

    // Promote directly to active — operator note is self-attesting.
    if let Err(err) = repo.set_active(&id, now) {
        if !json { eprintln!("memory note: failed to activate memory: {err}"); }
        return Exit::Internal;
    }

    let id_str = id.to_string();
    if !json {
        println!("memory note: recorded {id_str}");
        println!("  claim:   {claim}");
        println!("  domains: {}", domains.join(", "));
    }
    output::emit(
        &output::Envelope::new(
            "cortex.memory.note",
            Exit::Ok,
            serde_json::json!({
                "memory_id": id_str,
                "claim": claim,
                "domains": domains,
                "confidence": args.confidence,
                "status": "active",
            }),
        ),
        Exit::Ok,
    )
}

/// Compose the ADR 0026 acceptance policy for `cortex memory accept`.
///
/// The CLI operator boundary fails closed for `PARTIAL` / `BROKEN` proof
/// closure and for any open durable contradiction touching the candidate slot.
/// `semantic_trust` and `operator_temporal_use` contributors are wired as
/// `Allow` because the CLI itself is the operator boundary for this command:
/// the operator's invocation is the attested action and the store-boundary
/// envelope still refuses the write if any *other* required contributor
/// surfaced `Quarantine` or `Reject`.
fn compose_memory_accept_policy(
    pool: &Pool,
    candidate_id: &MemoryId,
) -> Result<(cortex_core::PolicyDecision, cortex_core::ProofClosureReport), Exit> {
    let proof_report = verify_memory_proof_closure(pool, candidate_id).map_err(|err| {
        eprintln!("cortex memory accept: proof closure preflight failed: {err}");
        Exit::PreconditionUnmet
    })?;
    let proof_contribution = accept_proof_closure_contribution(&proof_report);

    let candidate_ref = candidate_id.to_string();
    let contradictions = ContradictionRepo::new(pool).list_open().map_err(|err| {
        eprintln!("cortex memory accept: contradiction preflight failed: {err}");
        Exit::PreconditionUnmet
    })?;
    let open_contradictions = contradictions
        .iter()
        .filter(|row| row.left_ref == candidate_ref || row.right_ref == candidate_ref)
        .count();
    let contradiction_contribution = accept_open_contradiction_contribution(open_contradictions);

    // The current `cortex memory accept` command does not yet take an AXIOM
    // admission envelope or an explicit operator key; the semantic trust
    // contributor votes `Allow` because the candidate's lineage was
    // validated upstream by the AXIOM admission path. The operator
    // temporal-use contributor is the Phase 2.6 T3 honest floor: there
    // is no bound operator key to revalidate, so the contributor votes
    // `Warn` with the stable invariant
    // [`ACCEPT_OPERATOR_TEMPORAL_AUTHORITY_WARN_NO_ATTESTATION_INVARIANT`]
    // rather than a literal `Allow` claiming the CLI invocation is itself
    // an attested current-use action. ADR 0026 §4 still applies: any
    // future contributor that returns `Quarantine` / `Reject` composes
    // through the total order without subsystem-local override.
    let semantic_trust_contribution = PolicyContribution::new(
        ACCEPT_SEMANTIC_TRUST_RULE_ID,
        PolicyOutcome::Allow,
        "operator CLI invocation: candidate passed lineage validation upstream",
    )
    .expect("static semantic trust contribution shape is valid");
    let operator_temporal_use_contribution = PolicyContribution::new(
        ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID,
        PolicyOutcome::Warn,
        format!(
            "{ACCEPT_OPERATOR_TEMPORAL_AUTHORITY_WARN_NO_ATTESTATION_INVARIANT}: no operator attestation bound on this CLI surface; accepting at the honest floor",
        ),
    )
    .expect("static operator temporal use contribution shape is valid");

    let decision = compose_policy_outcomes(
        vec![
            proof_contribution,
            contradiction_contribution,
            semantic_trust_contribution,
            operator_temporal_use_contribution,
        ],
        None,
    );
    Ok((decision, proof_report))
}

fn memory_accept_envelope(
    exit: Exit,
    memory_id: Option<String>,
    detail: &str,
    policy: Option<&cortex_core::PolicyDecision>,
) -> Exit {
    if !output::json_enabled() {
        return exit;
    }
    // Phase 2.6 T3: surface the composed policy contributors on the
    // envelope so an operator inspecting the JSON sees the
    // `memory.accept.operator_temporal_use` contributor's outcome plus
    // the
    // `memory.accept.operator_temporal_authority.warn_no_attestation`
    // invariant when the surface is at the honest no-attestation floor.
    let payload = if let Some(policy) = policy {
        json!({
            "memory_id": memory_id,
            "detail": detail,
            "policy_outcome": {
                "final_outcome": policy.final_outcome,
                "contributing": policy.contributing,
                "discarded": policy.discarded,
            },
        })
    } else {
        json!({
            "memory_id": memory_id,
            "detail": detail,
        })
    };
    let mut envelope = Envelope::new("cortex.memory.accept", exit, payload);
    if let Some(policy) = policy {
        envelope = envelope.with_policy_outcome(json!({
            "final_outcome": policy.final_outcome,
            "contributing": policy.contributing,
            "discarded": policy.discarded,
        }));
    }
    output::emit(&envelope, exit)
}

fn admit_axiom(args: AdmitAxiomArgs) -> Exit {
    if args.cortex_context_trust.is_some()
        || args.axiom_execution_trust.is_some()
        || args.authority_feedback_loop.is_some()
    {
        return admit_axiom_trust_exchange(args);
    }

    let input = match read_axiom_admission_input(&args) {
        Ok(input) => input,
        Err(err) => {
            eprintln!("cortex memory admit-axiom: {err}");
            return admit_axiom_failure_envelope(Exit::PreconditionUnmet, &err.to_string());
        }
    };

    let request = match AxiomMemoryAdmissionRequest::from_json_envelope(&input) {
        Ok(request) => request,
        Err(AdmissionEnvelopeError::InvalidEnvelope { message }) => {
            eprintln!("cortex memory admit-axiom: invalid AXIOM admission envelope: {message}");
            return admit_axiom_failure_envelope(
                Exit::QuarantinedInput,
                &format!("invalid AXIOM admission envelope: {message}"),
            );
        }
    };

    let decision = request.admission_decision();
    let policy = request.policy_decision();
    let semantic = request.semantic_trust_report(AdmissionSemanticTrustInput::new(
        SemanticUse::CandidateMemory,
    ));
    let (decision_name, exit) = match decision {
        AdmissionDecision::AdmitCandidate => ("admit_candidate", Exit::Ok),
        AdmissionDecision::Quarantine { .. } => ("quarantine", Exit::QuarantinedInput),
        AdmissionDecision::Reject { .. } => ("reject", Exit::QuarantinedInput),
    };

    let report = json!({
        "command": "memory admit-axiom",
        "decision": decision_name,
        "policy_outcome": policy.final_outcome,
        "policy_contributing": policy.contributing,
        "candidate_state": request.candidate_state,
        "semantic_intended_use": semantic.intended_use,
        "provenance_class": semantic.provenance_class,
        "semantic_trust": semantic.semantic_trust.semantic_trust,
        "semantic_policy_outcome": semantic.semantic_trust.policy_outcome,
        "semantic_claim_ceiling": semantic.semantic_trust.claim_ceiling,
        "semantic_reasons": semantic.semantic_trust.reasons,
        "explicit_non_promotion": request.explicit_non_promotion,
        "persisted": false,
    });
    if output::json_enabled() {
        let policy_summary = serde_json::json!({
            "final_outcome": policy.final_outcome,
            "contributing": policy.contributing,
        });
        let envelope = Envelope::new("cortex.memory.admit_axiom", exit, report)
            .with_policy_outcome(policy_summary);
        return output::emit(&envelope, exit);
    }
    println!(
        "{}",
        serde_json::to_string_pretty(&report).expect("admission report is serializable")
    );

    exit
}

fn admit_axiom_failure_envelope(exit: Exit, detail: &str) -> Exit {
    if !output::json_enabled() {
        return exit;
    }
    let payload = json!({
        "command": "memory admit-axiom",
        "decision": "error",
        "detail": detail,
        "persisted": false,
    });
    let envelope = Envelope::new("cortex.memory.admit_axiom", exit, payload);
    output::emit(&envelope, exit)
}

fn read_axiom_admission_input(args: &AdmitAxiomArgs) -> Result<String, io::Error> {
    match (args.file.as_ref(), args.json.as_ref()) {
        (Some(path), None) => fs::read_to_string(path),
        (None, Some(json)) => Ok(json.clone()),
        (None, None) => Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "admit-axiom requires --file, --json, or a pai-axiom trust exchange flag",
        )),
        (Some(_), Some(_)) => Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "--file and --json are mutually exclusive",
        )),
    }
}

fn parse_admission_lifecycle(value: &str) -> Result<AdmissionLifecycle, String> {
    match value {
        "candidate_only" => Ok(AdmissionLifecycle::CandidateOnly),
        "validated" => Ok(AdmissionLifecycle::Validated),
        "promoted" => Ok(AdmissionLifecycle::Promoted),
        "stale" => Ok(AdmissionLifecycle::Stale),
        "quarantined" => Ok(AdmissionLifecycle::Quarantined),
        "unknown" => Ok(AdmissionLifecycle::Unknown),
        other => Err(format!(
            "unsupported lifecycle `{other}`; expected one of \
candidate_only, validated, promoted, stale, quarantined, unknown"
        )),
    }
}

fn admit_axiom_trust_exchange(args: AdmitAxiomArgs) -> Exit {
    let lifecycle = match parse_admission_lifecycle(&args.lifecycle) {
        Ok(lifecycle) => lifecycle,
        Err(err) => {
            eprintln!("cortex memory admit-axiom: {err}");
            return admit_axiom_failure_envelope(Exit::Usage, &err);
        }
    };

    let exec_path = match args.axiom_execution_trust.as_ref() {
        Some(path) => path,
        None => {
            let detail = "--axiom-execution-trust is required for trust exchange admission";
            eprintln!("cortex memory admit-axiom: {detail}");
            return admit_axiom_failure_envelope(Exit::Usage, detail);
        }
    };
    // Pai-axiom P6 closure (2026-05-12 follow-up): the authority feedback
    // loop record is the load-bearing carrier for the
    // `same_loop_promotion_must_be_false`, `authority_claims.over_authorized`,
    // and `target_domain_validation.not_pass` gates. Without it, those rules
    // are structurally unreachable and a sender could win admission by
    // simply omitting the record. The trust-exchange path therefore now
    // fails closed when `--authority-feedback-loop` is absent.
    if args.authority_feedback_loop.is_none() {
        let detail = "axiom.admission.authority_feedback_loop.missing --authority-feedback-loop is required for trust exchange admission (P6 closure: the feedback-loop record carries the same_loop_promotion / authority_claims / target_domain_validation gates that pai-axiom relies on)";
        eprintln!("cortex memory admit-axiom: {detail}");
        return admit_axiom_failure_envelope(Exit::Usage, detail);
    }
    // Pai-axiom P6 follow-up (2026-05-12 red team Attack B): four
    // downstream gates in `cortex-memory/src/trust_exchange.rs` only fire
    // when the cortex_context_trust envelope is present —
    //   (1) quarantine propagation (`axiom.admission.quarantine.propagated`),
    //   (2) `cortex_context_trust.redaction_state.blocks_critical_premise`,
    //   (3) `cortex_context_trust.proof_state.state.unusable` (failed),
    //   (4) `cortex_context_trust.proof_state.state.unusable` (missing).
    // Each is gated behind `if let Some(ctx) = &self.cortex_context_trust`
    // and silently no-ops when the envelope is absent. A sender that omits
    // `--cortex-context-trust` therefore wins admission by structural skip,
    // mirroring exactly the class the authority-feedback-loop closure above
    // was meant to close. The trust-exchange path now fails closed when
    // `--cortex-context-trust` is absent, BEFORE any policy rule fires.
    if args.cortex_context_trust.is_none() {
        let detail = "axiom.admission.cortex_context_trust.missing --cortex-context-trust is required for trust exchange admission (P6 follow-up: the context-trust envelope is the load-bearing carrier for four downstream gates — quarantine propagation, redaction-state-blocks-critical-premise, proof-state-failed, and proof-state-missing — that silently no-op when the envelope is absent)";
        eprintln!("cortex memory admit-axiom: {detail}");
        return admit_axiom_failure_envelope(Exit::Usage, detail);
    }
    let exec_bytes = match fs::read_to_string(exec_path) {
        Ok(bytes) => bytes,
        Err(err) => {
            let detail = format!(
                "failed to read axiom_execution_trust at {}: {err}",
                exec_path.display()
            );
            eprintln!("cortex memory admit-axiom: {detail}");
            return admit_axiom_failure_envelope(Exit::PreconditionUnmet, &detail);
        }
    };
    let exec = match parse_axiom_execution_trust(&exec_bytes) {
        Ok(envelope) => envelope,
        Err(err) => {
            let detail = format!("invalid axiom_execution_trust envelope: {}", err.reason);
            eprintln!(
                "cortex memory admit-axiom: invariant={} {detail}",
                err.invariant
            );
            return admit_axiom_failure_envelope(Exit::QuarantinedInput, &detail);
        }
    };

    // Receiver-side freshness gate (closes the gap surfaced by the
    // 2026-05-13 live exchange against axiom packet SHA `9a15d281`: the
    // `stale-pai-axiom-sha` fixture was admitted instead of refused). The
    // accept-list defaults to a small Cortex-owned set of known-good axiom
    // SHAs (ADR 0042 acceptance pin + subsequent syncs + test fixtures);
    // operators may rotate without re-deploy via
    // `CORTEX_AXIOM_ACCEPTED_SOURCE_COMMITS`. The check runs AFTER the
    // structural `tool_provenance.source_commit.invalid_format` check
    // (handled inside `parse_axiom_execution_trust`'s schema validation)
    // and BEFORE the admission policy composition fires, so a stale SHA
    // refuses with a single deterministic invariant rather than
    // intermingling with downstream policy outcomes.
    {
        let accepted = accepted_axiom_source_commits();
        if !is_axiom_source_commit_fresh(&exec.tool_provenance.source_commit, &accepted) {
            let detail = format!(
                "tool_provenance.source_commit `{}` is not on the Cortex-side acceptance list \
                 (defaults documented at `cortex_core::DEFAULT_ACCEPTED_AXIOM_SOURCE_COMMITS`; \
                 operator rotation via `{CORTEX_AXIOM_ACCEPTED_SOURCE_COMMITS_ENV}`)",
                exec.tool_provenance.source_commit,
            );
            eprintln!(
                "cortex memory admit-axiom: invariant={AXIOM_EXECUTION_TRUST_SOURCE_COMMIT_STALE_INVARIANT} {detail}",
            );
            return admit_axiom_failure_envelope(Exit::QuarantinedInput, &detail);
        }
    }

    let mut request = AxiomTrustExchangeAdmissionRequest::new(exec, lifecycle)
        .with_derived_from_quarantined(args.derived_from_quarantined);

    if let Some(path) = args.cortex_context_trust.as_ref() {
        let bytes = match fs::read_to_string(path) {
            Ok(bytes) => bytes,
            Err(err) => {
                let detail = format!(
                    "failed to read cortex_context_trust at {}: {err}",
                    path.display()
                );
                eprintln!("cortex memory admit-axiom: {detail}");
                return admit_axiom_failure_envelope(Exit::PreconditionUnmet, &detail);
            }
        };
        match parse_cortex_context_trust(&bytes) {
            Ok(envelope) => {
                request = request.with_cortex_context_trust(envelope);
            }
            Err(err) => {
                let detail = format!("invalid cortex_context_trust envelope: {}", err.reason);
                eprintln!(
                    "cortex memory admit-axiom: invariant={} {detail}",
                    err.invariant
                );
                return admit_axiom_failure_envelope(Exit::QuarantinedInput, &detail);
            }
        }
    }

    if let Some(path) = args.authority_feedback_loop.as_ref() {
        let bytes = match fs::read_to_string(path) {
            Ok(bytes) => bytes,
            Err(err) => {
                let detail = format!(
                    "failed to read authority_feedback_loop at {}: {err}",
                    path.display()
                );
                eprintln!("cortex memory admit-axiom: {detail}");
                return admit_axiom_failure_envelope(Exit::PreconditionUnmet, &detail);
            }
        };
        match parse_authority_feedback_loop(&bytes) {
            Ok(envelope) => {
                request = request.with_authority_feedback_loop(envelope);
            }
            Err(err) => {
                let detail = format!("invalid authority_feedback_loop envelope: {}", err.reason);
                eprintln!(
                    "cortex memory admit-axiom: invariant={} {detail}",
                    err.invariant
                );
                return admit_axiom_failure_envelope(Exit::QuarantinedInput, &detail);
            }
        }
    }

    let decision = request.decide();
    emit_trust_exchange_diagnostic(&decision);
    emit_trust_exchange_envelope(&decision)
}

fn emit_trust_exchange_diagnostic(decision: &TrustExchangeAdmission) {
    let invariants = decision.invariants();
    eprintln!(
        "cortex memory admit-axiom: decision={} policy_outcome={:?}",
        decision.decision_name(),
        decision.policy_decision().final_outcome
    );
    if !invariants.is_empty() {
        eprintln!(
            "cortex memory admit-axiom: failing_edges={}",
            invariants.join(",")
        );
    }
    if let Some(outputs) = decision.named_quarantine_outputs() {
        for invariant in outputs.invariants() {
            eprintln!("cortex memory admit-axiom: named_quarantine_output={invariant}");
        }
    }
    if let Some(forbidden) = decision.forbidden_uses() {
        let names: Vec<String> = forbidden
            .iter()
            .map(|use_| {
                serde_json::to_value(use_)
                    .ok()
                    .and_then(|value| value.as_str().map(ToOwned::to_owned))
                    .unwrap_or_else(|| "unknown".to_string())
            })
            .collect();
        eprintln!(
            "cortex memory admit-axiom: forbidden_uses={}",
            names.join(",")
        );
    }
}

fn emit_trust_exchange_envelope(decision: &TrustExchangeAdmission) -> Exit {
    let exit = match decision {
        TrustExchangeAdmission::AdmitCandidate { .. } => Exit::Ok,
        TrustExchangeAdmission::Quarantine { .. } | TrustExchangeAdmission::Reject { .. } => {
            Exit::QuarantinedInput
        }
    };

    let policy = decision.policy_decision();
    let forbidden_uses = decision
        .forbidden_uses()
        .map(|uses| serde_json::to_value(uses).unwrap_or(serde_json::Value::Null))
        .unwrap_or(serde_json::Value::Null);
    let failing_edges: Vec<&str> = decision.invariants();
    let named_outputs = decision
        .named_quarantine_outputs()
        .map(|outputs| serde_json::to_value(outputs).unwrap_or(serde_json::Value::Null))
        .unwrap_or(serde_json::Value::Null);

    let report = json!({
        "command": "memory admit-axiom",
        "mode": "trust_exchange",
        "decision": decision.decision_name(),
        "policy_outcome": policy.final_outcome,
        "policy_contributing": policy.contributing,
        "policy_discarded": policy.discarded,
        "failing_edges": failing_edges,
        "named_quarantine_outputs": named_outputs,
        "forbidden_uses": forbidden_uses,
        "persisted": false,
    });

    if !output::json_enabled() {
        println!(
            "{}",
            serde_json::to_string_pretty(&report).expect("trust exchange report is serializable")
        );
        return exit;
    }
    let policy_summary = json!({
        "final_outcome": policy.final_outcome,
        "contributing": policy.contributing,
    });
    let envelope = Envelope::new("cortex.memory.admit_axiom", exit, report)
        .with_policy_outcome(policy_summary);
    output::emit(&envelope, exit)
}

fn search(args: SearchArgs) -> Exit {
    if args.query.trim().is_empty() {
        eprintln!("cortex memory search: QUERY must not be empty");
        return search_failure_envelope(Exit::Usage, "QUERY must not be empty");
    }

    // Phase 4.B+: tokenize the query for snippet extraction (--snippet flag).
    // Build once and reuse across all result memories.
    let query_terms: Vec<String> = tokenize_query(&args.query);

    // Phase 4.C: when --semantic is requested, embed the query before opening
    // the store so we fail-closed on embed errors before any DB access.
    //
    // We try Ollama first (richer semantic signal). If Ollama is unavailable or
    // not configured, we fall back to the BLAKE3 stub silently.
    let (query_embed, semantic_backend_id): (Option<Vec<f32>>, Option<String>) = if args.semantic {
        let ollama_backend_id = resolve_ollama_backend_id();
        let ollama_result = ollama_backend_id.as_ref().and_then(|(bid, embedder)| {
            match embedder.embed(args.query.trim(), &[]) {
                Ok(vec) => Some((vec, bid.clone())),
                Err(_) => None, // silent fallback to BLAKE3
            }
        });
        if let Some((vec, bid)) = ollama_result {
            (Some(vec), Some(bid))
        } else {
            // Fallback: BLAKE3 stub.
            let embedder = LocalStubEmbedder::new();
            match embedder.embed(args.query.trim(), &[]) {
                Ok(vec) => (Some(vec), Some(STUB_BACKEND_ID.to_string())),
                Err(err) => {
                    let detail = format!("semantic embed failed for query: {err}");
                    eprintln!("cortex memory search: {detail}");
                    return search_failure_envelope(Exit::Internal, &detail);
                }
            }
        }
    } else {
        (None, None)
    };

    let pool = match open_default_store("memory search") {
        Ok(pool) => pool,
        Err(exit) => return search_failure_envelope(exit, "failed to open store"),
    };
    let repo = MemoryRepo::new(&pool);
    let memories = match repo.list_by_status("active") {
        Ok(memories) => memories,
        Err(err) => {
            eprintln!("cortex memory search: failed to read active memories: {err}");
            return search_failure_envelope(
                Exit::Internal,
                &format!("failed to read active memories: {err}"),
            );
        }
    };
    let mut proof_states = BTreeMap::new();
    for memory in &memories {
        let proof = match verify_memory_proof_closure(&pool, &memory.id) {
            Ok(proof) => proof,
            Err(err) => {
                eprintln!(
                    "cortex memory search: failed to verify memory {} proof closure: {err}",
                    memory.id
                );
                return search_failure_envelope(
                    Exit::PreconditionUnmet,
                    &format!("failed to verify memory {} proof closure: {err}", memory.id),
                );
            }
        };
        if let Err(err) = proof.require_current_use_allowed() {
            eprintln!(
                "cortex memory search: memory {} excluded from default retrieval use: {err}",
                memory.id
            );
            return search_failure_envelope(
                Exit::PreconditionUnmet,
                &format!(
                    "memory {} excluded from default retrieval use: {err}",
                    memory.id
                ),
            );
        }
        proof_states.insert(memory.id.to_string(), ClaimProofState::from(proof.state()));
    }
    if let Err(err) = gate_open_contradictions_for_default_search(&pool, &memories) {
        eprintln!("cortex memory search: {err}");
        return search_failure_envelope(Exit::PreconditionUnmet, &err);
    }
    let documents = memories.iter().map(memory_document).collect::<Vec<_>>();
    let index = LexicalIndex::new(documents);
    let hits = match index.search_with_tag_filter(&args.query, &args.tag) {
        Ok(hits) => hits,
        Err(err) => {
            eprintln!("cortex memory search: {err}");
            return search_failure_envelope(Exit::Usage, &err.to_string());
        }
    };

    // Phase 4.B fuzzy boost (opt-in). When --fuzzy is OFF this map stays
    // empty and the composition helper returns the deterministic lexical
    // score unchanged: the default retrieval path is byte-for-byte
    // identical to the pre-Phase-4.B baseline.
    let mut fuzzy_scores: BTreeMap<String, f32> = BTreeMap::new();
    let mut fuzzy_only_hits: Vec<&MemoryRecord> = Vec::new();
    if args.fuzzy {
        let fts_limit = std::cmp::max(hits.len() * 2, 16);
        let fts_hits = match query_fts5(&repo, &args.query, fts_limit) {
            Ok(hits) => hits,
            Err(err) => {
                eprintln!("cortex memory search: fuzzy retrieval failed: {err}");
                return search_failure_envelope(
                    Exit::Internal,
                    &format!("fuzzy retrieval failed: {err}"),
                );
            }
        };
        let lexical_ids: BTreeSet<String> =
            hits.iter().map(|hit| hit.document.id.to_string()).collect();
        let tag_filtered_ids: BTreeSet<String> = memories
            .iter()
            .filter(|memory| {
                if args.tag.is_empty() {
                    true
                } else {
                    let domains = memory
                        .domains_json
                        .as_array()
                        .map(|values| {
                            values
                                .iter()
                                .filter_map(|value| value.as_str().map(str::to_string))
                                .collect::<BTreeSet<_>>()
                        })
                        .unwrap_or_default();
                    args.tag.iter().all(|tag| domains.contains(tag))
                }
            })
            .map(|memory| memory.id.to_string())
            .collect();
        for fts_hit in fts_hits {
            let id_str = fts_hit.memory_id.to_string();
            if !tag_filtered_ids.contains(&id_str) {
                // Fuzzy hits inherit the same tag-filter pre-pass that
                // the lexical scorer applies — fuzzy must not bypass
                // operator-supplied --tag scope.
                continue;
            }
            fuzzy_scores.insert(id_str.clone(), fts_hit.normalized_score);
            if !lexical_ids.contains(&id_str) {
                if let Some(memory) = memories
                    .iter()
                    .find(|memory| memory.id == fts_hit.memory_id)
                {
                    fuzzy_only_hits.push(memory);
                }
            }
        }
    }

    let json_mode = output::json_enabled();
    if hits.is_empty() && fuzzy_only_hits.is_empty() {
        if !json_mode {
            println!("cortex memory search: no matches");
            return Exit::Ok;
        }
        let payload = json!({
            "query": args.query,
            "match_count": 0,
            "matches": [],
            "claim_ceiling": "local_unsigned",
            "forbidden_uses": [
                "compliance_evidence",
                "cross_system_trust_decision",
                "external_reporting",
            ],
        });
        let envelope = Envelope::new("cortex.memory.search", Exit::Ok, payload);
        return output::emit(&envelope, Exit::Ok);
    }

    // Phase 2.6 D3 closure: prefetch authoritative validation_epoch for each
    // active memory. Retrieval scoring MUST use this durable column instead of
    // the candidate-author-controlled `salience_json["validation"]`.
    let mut validation_epochs: BTreeMap<String, u32> = BTreeMap::new();
    for memory in &memories {
        let epoch = match repo.validation_epoch_for(&memory.id) {
            Ok(epoch) => epoch.unwrap_or(0),
            Err(err) => {
                eprintln!(
                    "cortex memory search: failed to read validation_epoch for memory {}: {err}",
                    memory.id
                );
                return search_failure_envelope(
                    Exit::Internal,
                    &format!(
                        "failed to read validation_epoch for memory {}: {err}",
                        memory.id
                    ),
                );
            }
        };
        validation_epochs.insert(memory.id.to_string(), epoch);
    }

    let mut matches = Vec::new();
    for hit in hits {
        let Some(memory) = memories.iter().find(|memory| memory.id == hit.document.id) else {
            continue;
        };
        let validation_epoch = validation_epochs
            .get(&memory.id.to_string())
            .copied()
            .unwrap_or(0);
        // Phase 4.B: when --fuzzy is ON we compose the existing
        // deterministic lexical match with the FTS5 BM25 normalised
        // score. When --fuzzy is OFF the map is empty and the helper
        // returns the lexical_match unchanged, preserving the baseline.
        let fuzz = if args.fuzzy {
            fuzzy_scores
                .get(&memory.id.to_string())
                .copied()
                .unwrap_or(0.0)
        } else {
            0.0
        };
        // Phase 4.C: when --semantic is ON, look up (or on-demand compute)
        // the memory embedding and blend cosine similarity into the score.
        // Prefers Ollama embedding when available; silently falls back to BLAKE3.
        let sem_score =
            if let (Some(ref qembed), Some(ref bid)) = (&query_embed, &semantic_backend_id) {
                compute_or_warm_embedding(&pool, memory, qembed, bid)
            } else {
                None
            };
        let lexical_input = if args.semantic {
            compose_lexical_semantic(hit.explanation.lexical_match, fuzz, sem_score)
        } else if args.fuzzy {
            compose_fuzzy_boost(hit.explanation.lexical_match, fuzz)
        } else {
            hit.explanation.lexical_match
        };
        let explanation = score(score_inputs(memory, lexical_input, validation_epoch));
        if !json_mode {
            let claim_display = if args.snippet {
                let term_refs: Vec<&str> = query_terms.iter().map(|s| s.as_str()).collect();
                let snippet = extract_snippet(&memory.claim, &term_refs);
                snippet_ansi_highlighted(&snippet)
            } else {
                memory.claim.clone()
            };
            if args.semantic {
                println!(
                    "{}\t{:.4}\tsem={:.4}\t{}",
                    memory.id,
                    explanation.final_score,
                    sem_score.unwrap_or(0.0),
                    claim_display
                );
            } else {
                println!(
                    "{}\t{:.4}\t{}",
                    memory.id, explanation.final_score, claim_display
                );
            }
        }
        let proof_state = proof_states
            .get(&memory.id.to_string())
            .copied()
            .unwrap_or(ClaimProofState::Unknown);
        let uncertainty = retrieval_uncertainty(memory, proof_state);
        if args.explain && !json_mode {
            print_component("lexical_match", explanation.lexical_match);
            print_component("semantic_similarity", explanation.semantic_similarity);
            print_component("brightness", explanation.brightness);
            print_component("domain_overlap", explanation.domain_overlap);
            print_component("validation", explanation.validation);
            print_component("authority_weight", explanation.authority_weight);
            print_component("contradiction_risk", explanation.contradiction_risk);
            print_component("staleness_penalty", explanation.staleness_penalty);
            print_uncertainty(uncertainty);
        }
        if json_mode {
            let mut entry = json!({
                "memory_id": memory.id.to_string(),
                "claim": memory.claim,
                "final_score": explanation.final_score,
            });
            if args.semantic {
                entry["sem_score"] = json!(sem_score.unwrap_or(0.0));
            }
            if args.snippet {
                let term_refs: Vec<&str> = query_terms.iter().map(|s| s.as_str()).collect();
                let snippet = extract_snippet(&memory.claim, &term_refs);
                let ranges: Vec<[usize; 2]> = snippet
                    .highlight_ranges
                    .iter()
                    .map(|r| [r.start, r.end])
                    .collect();
                entry["snippet"] = json!({
                    "text": snippet_plain_text(&snippet),
                    "truncated": snippet.truncated,
                    "highlight_ranges": ranges,
                });
            }
            if args.explain {
                entry["explanation"] = json!({
                    "lexical_match": component_value(explanation.lexical_match),
                    "semantic_similarity": component_value(explanation.semantic_similarity),
                    "brightness": component_value(explanation.brightness),
                    "domain_overlap": component_value(explanation.domain_overlap),
                    "validation": component_value(explanation.validation),
                    "authority_weight": component_value(explanation.authority_weight),
                    "contradiction_risk": component_value(explanation.contradiction_risk),
                    "staleness_penalty": component_value(explanation.staleness_penalty),
                });
                entry["uncertainty"] = json!({
                    "proof_state": wire_string(uncertainty.proof_state),
                    "provenance_class": wire_string(uncertainty.provenance_class),
                    "semantic_trust": wire_string(uncertainty.semantic_trust),
                    "claim_ceiling": wire_string(uncertainty.claim_ceiling),
                });
            }
            matches.push(entry);
        }
    }

    // Phase 4.B fuzzy-only hits: memories the FTS5 mirror surfaced that
    // the deterministic lexical scorer did NOT see. Their lexical_match
    // component is 0 by construction; the composition adds the
    // FUZZY_BOOST_WEIGHT fraction of their normalized FTS5 score so the
    // typo-of-one-character case has somewhere to land in the output.
    for memory in fuzzy_only_hits {
        let validation_epoch = validation_epochs
            .get(&memory.id.to_string())
            .copied()
            .unwrap_or(0);
        let fuzz = fuzzy_scores
            .get(&memory.id.to_string())
            .copied()
            .unwrap_or(0.0);
        // Phase 4.C: fuzzy-only hits also benefit from semantic reranking.
        // Prefers Ollama embedding when available; silently falls back to BLAKE3.
        let sem_score =
            if let (Some(ref qembed), Some(ref bid)) = (&query_embed, &semantic_backend_id) {
                compute_or_warm_embedding(&pool, memory, qembed, bid)
            } else {
                None
            };
        let lexical_input = if args.semantic {
            compose_lexical_semantic(0.0, fuzz, sem_score)
        } else {
            compose_fuzzy_boost(0.0, fuzz)
        };
        let explanation = score(score_inputs(memory, lexical_input, validation_epoch));
        if !json_mode {
            let claim_display = if args.snippet {
                let term_refs: Vec<&str> = query_terms.iter().map(|s| s.as_str()).collect();
                let snippet = extract_snippet(&memory.claim, &term_refs);
                snippet_ansi_highlighted(&snippet)
            } else {
                memory.claim.clone()
            };
            if args.semantic {
                println!(
                    "{}\t{:.4}\tsem={:.4}\t{}",
                    memory.id,
                    explanation.final_score,
                    sem_score.unwrap_or(0.0),
                    claim_display
                );
            } else {
                println!(
                    "{}\t{:.4}\t{}",
                    memory.id, explanation.final_score, claim_display
                );
            }
        }
        let proof_state = proof_states
            .get(&memory.id.to_string())
            .copied()
            .unwrap_or(ClaimProofState::Unknown);
        let uncertainty = retrieval_uncertainty(memory, proof_state);
        if args.explain && !json_mode {
            print_component("lexical_match", explanation.lexical_match);
            print_component("semantic_similarity", explanation.semantic_similarity);
            print_component("brightness", explanation.brightness);
            print_component("domain_overlap", explanation.domain_overlap);
            print_component("validation", explanation.validation);
            print_component("authority_weight", explanation.authority_weight);
            print_component("contradiction_risk", explanation.contradiction_risk);
            print_component("staleness_penalty", explanation.staleness_penalty);
            print_uncertainty(uncertainty);
        }
        if json_mode {
            let mut entry = json!({
                "memory_id": memory.id.to_string(),
                "claim": memory.claim,
                "final_score": explanation.final_score,
            });
            if args.semantic {
                entry["sem_score"] = json!(sem_score.unwrap_or(0.0));
            }
            if args.snippet {
                let term_refs: Vec<&str> = query_terms.iter().map(|s| s.as_str()).collect();
                let snippet = extract_snippet(&memory.claim, &term_refs);
                let ranges: Vec<[usize; 2]> = snippet
                    .highlight_ranges
                    .iter()
                    .map(|r| [r.start, r.end])
                    .collect();
                entry["snippet"] = json!({
                    "text": snippet_plain_text(&snippet),
                    "truncated": snippet.truncated,
                    "highlight_ranges": ranges,
                });
            }
            if args.explain {
                entry["explanation"] = json!({
                    "lexical_match": component_value(explanation.lexical_match),
                    "semantic_similarity": component_value(explanation.semantic_similarity),
                    "brightness": component_value(explanation.brightness),
                    "domain_overlap": component_value(explanation.domain_overlap),
                    "validation": component_value(explanation.validation),
                    "authority_weight": component_value(explanation.authority_weight),
                    "contradiction_risk": component_value(explanation.contradiction_risk),
                    "staleness_penalty": component_value(explanation.staleness_penalty),
                });
                entry["uncertainty"] = json!({
                    "proof_state": wire_string(uncertainty.proof_state),
                    "provenance_class": wire_string(uncertainty.provenance_class),
                    "semantic_trust": wire_string(uncertainty.semantic_trust),
                    "claim_ceiling": wire_string(uncertainty.claim_ceiling),
                });
            }
            matches.push(entry);
        }
    }

    // Phase 4.C: when semantic reranking is ON, re-sort the JSON match list
    // by the composed final_score so the output order reflects blended
    // scores rather than the original lexical-insertion order.
    if args.semantic && json_mode {
        matches.sort_by(|a, b| {
            let sa = a["final_score"].as_f64().unwrap_or(0.0);
            let sb = b["final_score"].as_f64().unwrap_or(0.0);
            sb.partial_cmp(&sa).unwrap_or(std::cmp::Ordering::Equal)
        });
    }

    if !json_mode {
        return Exit::Ok;
    }
    let payload = json!({
        "query": args.query,
        "match_count": matches.len(),
        "matches": matches,
        "claim_ceiling": "local_unsigned",
        "forbidden_uses": [
            "compliance_evidence",
            "cross_system_trust_decision",
            "external_reporting",
        ],
    });
    let envelope = Envelope::new("cortex.memory.search", Exit::Ok, payload);
    output::emit(&envelope, Exit::Ok)
}

/// `cortex memory embed` — enrich active memories with Ollama semantic embeddings.
///
/// For each active memory:
/// 1. Check whether a BLAKE3 embedding exists (it always should after a search).
/// 2. Check whether an Ollama embedding already exists under the target backend_id.
/// 3. If Ollama embedding is absent: call Ollama, write the row.
///
/// Memories that already have an Ollama embedding are skipped (idempotent).
/// `--preview` performs the same walk but writes nothing.
fn embed(args: EmbedArgs) -> Exit {
    // Resolve the Ollama embedder — CLI flags override config.
    let cfg = EmbeddingBackend::resolve();
    let (cfg_endpoint, cfg_model, cfg_timeout_ms) = match cfg {
        EmbeddingBackend::Ollama {
            endpoint,
            model,
            timeout_ms,
            ..
        } => (endpoint, model, timeout_ms),
        EmbeddingBackend::Stub => (
            cortex_retrieval::DEFAULT_OLLAMA_ENDPOINT.to_string(),
            cortex_retrieval::DEFAULT_OLLAMA_EMBED_MODEL.to_string(),
            30_000u64,
        ),
    };

    let endpoint = args.endpoint.unwrap_or(cfg_endpoint);
    let model = args.model.unwrap_or(cfg_model);
    let dim = args.dim;
    let timeout_ms = cfg_timeout_ms;

    let ollama_backend_id = OllamaEmbedder::backend_id_for(&model, dim);

    let embedder = match OllamaEmbedder::new(&endpoint, &model, dim) {
        Ok(e) => e.with_timeout_ms(timeout_ms),
        Err(err) => {
            eprintln!("cortex memory embed: failed to configure Ollama embedder: {err}");
            return Exit::Usage;
        }
    };

    let pool = match open_default_store("memory embed") {
        Ok(pool) => pool,
        Err(exit) => return exit,
    };
    let repo = MemoryRepo::new(&pool);
    let embed_repo = EmbeddingRepo::new(&pool);

    let memories = match repo.list_by_status("active") {
        Ok(m) => m,
        Err(err) => {
            eprintln!("cortex memory embed: failed to list active memories: {err}");
            return Exit::Internal;
        }
    };

    let total = memories.len();
    let mut would_enrich = 0usize;
    let mut enriched = 0usize;
    let mut errors = 0usize;

    for memory in &memories {
        // Check whether an Ollama embedding already exists.
        let has_ollama = match embed_repo.read(&memory.id, &ollama_backend_id) {
            Ok(Some(_)) => true,
            Ok(None) => false,
            Err(err) => {
                eprintln!(
                    "cortex memory embed: warning: failed to check Ollama embedding for {}: {err}",
                    memory.id
                );
                false
            }
        };

        if has_ollama {
            // Already enriched — idempotent skip.
            continue;
        }

        would_enrich += 1;

        if args.preview {
            // Dry-run: just count.
            continue;
        }

        // Compute the Ollama embedding.
        let tags: Vec<String> = memory
            .domains_json
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(ToString::to_string))
                    .collect()
            })
            .unwrap_or_default();

        let vector = match embedder.embed(&memory.claim, &tags) {
            Ok(v) => v,
            Err(err) => {
                eprintln!(
                    "cortex memory embed: failed to embed memory {}: {err}",
                    memory.id
                );
                errors += 1;
                continue;
            }
        };

        // Build and write the embedding record.
        let record =
            match EmbedRecord::new(memory.id, &ollama_backend_id, vector, chrono::Utc::now()) {
                Ok(r) => r,
                Err(err) => {
                    eprintln!(
                        "cortex memory embed: failed to build embed record for {}: {err}",
                        memory.id
                    );
                    errors += 1;
                    continue;
                }
            };

        if let Err(err) = embed_repo.write(&record) {
            eprintln!(
                "cortex memory embed: failed to write embedding for {}: {err}",
                memory.id
            );
            errors += 1;
            continue;
        }

        enriched += 1;
    }

    // Report.
    if args.preview {
        let json_mode = output::json_enabled();
        if !json_mode {
            println!(
                "cortex memory embed --preview: {would_enrich}/{total} memories would be enriched with {model}:{dim}"
            );
            return Exit::Ok;
        }
        let payload = serde_json::json!({
            "preview": true,
            "total_active": total,
            "would_enrich": would_enrich,
            "already_enriched": total - would_enrich,
            "model": model,
            "dim": dim,
            "backend_id": ollama_backend_id,
        });
        let envelope = Envelope::new("cortex.memory.embed", Exit::Ok, payload);
        return output::emit(&envelope, Exit::Ok);
    }

    let json_mode = output::json_enabled();
    if !json_mode {
        println!("Enriched {enriched}/{total} memories with {model}:{dim}");
        if errors > 0 {
            eprintln!("cortex memory embed: {errors} error(s) during enrichment");
        }
        return if errors > 0 { Exit::Internal } else { Exit::Ok };
    }

    let exit = if errors > 0 { Exit::Internal } else { Exit::Ok };
    let payload = serde_json::json!({
        "preview": false,
        "total_active": total,
        "enriched": enriched,
        "already_enriched": total - would_enrich,
        "errors": errors,
        "model": model,
        "dim": dim,
        "backend_id": ollama_backend_id,
    });
    let envelope = Envelope::new("cortex.memory.embed", exit, payload);
    output::emit(&envelope, exit)
}

fn list(args: ListArgs) -> Exit {
    let pool = match open_default_store("memory list") {
        Ok(pool) => pool,
        Err(exit) => return list_failure_envelope(exit, "failed to open store", &args.tag),
    };
    let repo = MemoryRepo::new(&pool);
    let memories = if args.tag.is_empty() {
        match repo.list_by_status("active") {
            Ok(memories) => memories,
            Err(err) => {
                eprintln!("cortex memory list: failed to read active memories: {err}");
                return list_failure_envelope(
                    Exit::Internal,
                    &format!("failed to read active memories: {err}"),
                    &args.tag,
                );
            }
        }
    } else {
        match repo.list_by_status_with_tags("active", &args.tag) {
            Ok(memories) => memories,
            Err(err) => {
                eprintln!("cortex memory list: failed to read tag-filtered active memories: {err}");
                return list_failure_envelope(
                    Exit::Internal,
                    &format!("failed to read tag-filtered active memories: {err}"),
                    &args.tag,
                );
            }
        }
    };

    let json_mode = output::json_enabled();
    if !json_mode {
        if memories.is_empty() {
            println!("cortex memory list: no matches");
            return Exit::Ok;
        }
        for memory in &memories {
            let tags = string_array(&memory.domains_json).join(",");
            println!("{}\t{}\t{}", memory.id, tags, memory.claim);
        }
        return Exit::Ok;
    }

    let entries: Vec<serde_json::Value> = memories
        .iter()
        .map(|memory| {
            json!({
                "memory_id": memory.id.to_string(),
                "claim": memory.claim,
                "authority": memory.authority,
                "domains": string_array(&memory.domains_json),
                "updated_at": memory.updated_at.to_rfc3339(),
            })
        })
        .collect();
    let payload = json!({
        "tag_filter": args.tag,
        "match_count": entries.len(),
        "matches": entries,
    });
    let envelope = Envelope::new("cortex.memory.list", Exit::Ok, payload);
    output::emit(&envelope, Exit::Ok)
}

fn list_failure_envelope(exit: Exit, detail: &str, tag_filter: &[String]) -> Exit {
    if !output::json_enabled() {
        return exit;
    }
    let payload = json!({
        "detail": detail,
        "tag_filter": tag_filter,
        "matches": [],
        "match_count": 0,
    });
    let envelope = Envelope::new("cortex.memory.list", exit, payload);
    output::emit(&envelope, exit)
}

fn search_failure_envelope(exit: Exit, detail: &str) -> Exit {
    if !output::json_enabled() {
        return exit;
    }
    let payload = json!({
        "detail": detail,
        "matches": [],
        "match_count": 0,
    });
    let envelope = Envelope::new("cortex.memory.search", exit, payload);
    output::emit(&envelope, exit)
}

fn component_value(component: ScoreComponent) -> serde_json::Value {
    json!({
        "raw": component.raw,
        "weight": component.weight,
        "contribution": component.contribution,
    })
}

fn gate_open_contradictions_for_default_search(
    pool: &Pool,
    memories: &[MemoryRecord],
) -> Result<(), String> {
    let active_by_id = memories
        .iter()
        .map(|memory| (memory.id.to_string(), memory))
        .collect::<BTreeMap<_, _>>();
    let contradictions = ContradictionRepo::new(pool)
        .list_open()
        .map_err(|err| format!("failed to read open contradictions: {err}"))?;

    let mut affected_ids = BTreeSet::new();
    let mut conflict_edges = BTreeMap::<String, BTreeSet<String>>::new();
    for contradiction in contradictions {
        let left_active = active_by_id.contains_key(&contradiction.left_ref);
        let right_active = active_by_id.contains_key(&contradiction.right_ref);
        if !left_active && !right_active {
            continue;
        }
        if !(left_active && right_active) {
            return Err(format!(
                "open contradiction {} references unavailable memory and cannot be resolved for default retrieval",
                contradiction.id
            ));
        }
        affected_ids.insert(contradiction.left_ref.clone());
        affected_ids.insert(contradiction.right_ref.clone());
        conflict_edges
            .entry(contradiction.left_ref.clone())
            .or_default()
            .insert(contradiction.right_ref.clone());
        conflict_edges
            .entry(contradiction.right_ref)
            .or_default()
            .insert(contradiction.left_ref);
    }

    if affected_ids.is_empty() {
        return Ok(());
    }

    let inputs = affected_ids
        .iter()
        .filter_map(|id| active_by_id.get(id.as_str()).copied())
        .map(|memory| {
            ConflictingMemoryInput::new(
                memory.id.to_string(),
                Some(memory.id.to_string()),
                memory.claim.clone(),
                AuthorityProofHint {
                    authority: authority_level(&memory.authority),
                    proof: ProofClosureHint::FullChainVerified,
                },
            )
            .with_conflicts(
                conflict_edges
                    .get(&memory.id.to_string())
                    .map(|ids| ids.iter().cloned().collect())
                    .unwrap_or_default(),
            )
        })
        .collect::<Vec<_>>();

    let output = resolve_conflicts(&inputs, &[]);
    output
        .require_default_use_allowed()
        .map_err(|err| format!("open contradiction blocks default retrieval use: {err}"))
}

fn authority_level(authority: &str) -> AuthorityLevel {
    match authority {
        "user" | "operator" => AuthorityLevel::High,
        "tool" | "system" => AuthorityLevel::Medium,
        _ => AuthorityLevel::Low,
    }
}

fn memory_document(memory: &MemoryRecord) -> LexicalDocument {
    LexicalDocument::accepted_memory(
        memory.id,
        memory.claim.clone(),
        string_array(&memory.domains_json),
    )
}

fn score_inputs(memory: &MemoryRecord, lexical_match: f32, validation_epoch: u32) -> ScoreInputs {
    // Phase 2.6 D3 closure: retrieval validation weight is gated by the
    // authoritative `validation_epoch` column (advanced only by an ADR 0026 +
    // ADR 0020 §6 gated `Validated` outcome edge), NOT by the
    // candidate-author-controlled `salience_json["validation"]` blob. A memory
    // with no `Validated` edge gets zero validation weight regardless of what
    // it claims in its insert-time JSON; a memory with a `Validated` edge
    // gets full validation weight (1.0). The bool-to-f32 collapse keeps the
    // retrieval surface honest until ADR 0017's staleness/window logic glues
    // into the durable side; the audit explicitly forbids reading the
    // candidate-author JSON blob as ground truth.
    let validation = if validation_epoch > 0 { 1.0 } else { 0.0 };
    ScoreInputs {
        lexical_match,
        brightness: json_number(&memory.salience_json, "score")
            .or_else(|| json_number(&memory.salience_json, "brightness"))
            .unwrap_or(0.5),
        domain_overlap: 0.0,
        validation,
        authority_weight: if memory.authority == "user" { 1.0 } else { 0.5 },
        contradiction_risk: json_number(&memory.salience_json, "contradiction_risk").unwrap_or(0.0),
        staleness_penalty: json_number(&memory.salience_json, "staleness_penalty").unwrap_or(0.0),
    }
}

/// Phase 4.C: look up a memory's embedding from the store under `backend_id`;
/// if absent, fall back to the BLAKE3 stub (on-demand embed + warm).
/// Returns the cosine similarity against `query_embed`, or `None` on error
/// (graceful degradation — the search still returns results, just without
/// the semantic score).
///
/// The `backend_id` preference order (chosen by the caller based on what
/// was used to embed the query):
///   1. Ollama backend id (e.g. `"ollama:nomic-embed-text:768"`) — preferred.
///   2. `STUB_BACKEND_ID` (`"stub:blake3-v1"`) — always available, never
///      semantic, but keeps the pipeline operational when Ollama is absent.
///
/// When the requested Ollama embedding is absent for a given memory we do NOT
/// fall through to BLAKE3 here — the caller already chose a backend by
/// embedding the query with one specific embedder. Mixing backends in the
/// similarity comparison would produce meaningless scores (different vector
/// spaces). The BLAKE3 fallback only applies at the query-embed level (in
/// `search()`), not here.
///
/// The BLAKE3 on-demand warm path is retained for the `STUB_BACKEND_ID` case
/// so the store accumulates BLAKE3 embeddings for free during searches.
fn compute_or_warm_embedding(
    pool: &cortex_store::Pool,
    memory: &cortex_store::repo::MemoryRecord,
    query_embed: &[f32],
    backend_id: &str,
) -> Option<f32> {
    let embed_repo = EmbeddingRepo::new(pool);

    // Try to read the stored embedding for the requested backend.
    let record_opt = match embed_repo.read(&memory.id, backend_id) {
        Ok(r) => r,
        Err(err) => {
            eprintln!(
                "cortex memory search: failed to read embedding ({backend_id}) for memory {}: {err}",
                memory.id
            );
            return None;
        }
    };

    let mem_vec: Vec<f32> = if let Some(record) = record_opt {
        record.vector
    } else if backend_id == STUB_BACKEND_ID {
        // BLAKE3 on-demand warm path: embed and write back to the store.
        let embedder = LocalStubEmbedder::new();
        let tags = memory
            .domains_json
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(ToString::to_string))
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();
        let vec = match embedder.embed(&memory.claim, &tags) {
            Ok(v) => v,
            Err(err) => {
                eprintln!(
                    "cortex memory search: failed to embed memory {} with stub: {err}",
                    memory.id
                );
                return None;
            }
        };
        // Write back; ignore failure (graceful degradation).
        match EmbedRecord::new(memory.id, STUB_BACKEND_ID, vec.clone(), chrono::Utc::now()) {
            Ok(record) => {
                if let Err(err) = embed_repo.write(&record) {
                    eprintln!(
                        "cortex memory search: warning: failed to warm BLAKE3 embedding for memory {}: {err}",
                        memory.id
                    );
                }
            }
            Err(err) => {
                eprintln!(
                    "cortex memory search: warning: failed to build BLAKE3 embed record for memory {}: {err}",
                    memory.id
                );
            }
        }
        vec
    } else {
        // Ollama embedding absent for this memory — graceful degradation to 0.0.
        // Do NOT mix vector spaces: return None so the score is 0.0 rather than
        // computing cosine similarity across incompatible embeddings.
        return None;
    };

    Some(cosine_similarity(query_embed, &mem_vec))
}

/// Resolve the Ollama embedder from config/env, returning `(backend_id, embedder)`.
/// Returns `None` if the Ollama backend is not configured or construction fails.
fn resolve_ollama_backend_id() -> Option<(String, OllamaEmbedder)> {
    match EmbeddingBackend::resolve() {
        EmbeddingBackend::Ollama {
            endpoint,
            model,
            dim,
            timeout_ms,
        } => {
            let embedder = OllamaEmbedder::new(&endpoint, &model, dim).ok()?;
            let bid = embedder.backend_id().to_string();
            Some((bid, embedder.with_timeout_ms(timeout_ms)))
        }
        EmbeddingBackend::Stub => None,
    }
}

fn print_component(name: &str, component: ScoreComponent) {
    println!(
        "  {name}: raw={:.4} weight={:.4} contribution={:.4}",
        component.raw, component.weight, component.contribution
    );
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct RetrievalUncertainty {
    proof_state: ClaimProofState,
    provenance_class: ProvenanceClass,
    semantic_trust: SemanticTrustClass,
    claim_ceiling: ClaimCeiling,
}

fn retrieval_uncertainty(
    memory: &MemoryRecord,
    proof_state: ClaimProofState,
) -> RetrievalUncertainty {
    let (provenance_class, semantic_trust) = match memory.authority.as_str() {
        "user" | "operator" => (
            ProvenanceClass::OperatorAttested,
            SemanticTrustClass::SingleFamily,
        ),
        "tool" | "system" => (
            ProvenanceClass::ToolObserved,
            SemanticTrustClass::SingleFamily,
        ),
        _ => (
            ProvenanceClass::RuntimeDerived,
            SemanticTrustClass::CandidateOnly,
        ),
    };
    let claim_ceiling = ClaimCeiling::LocalUnsigned
        .min(proof_state.claim_ceiling())
        .min(provenance_class.claim_ceiling())
        .min(semantic_trust.claim_ceiling());

    RetrievalUncertainty {
        proof_state,
        provenance_class,
        semantic_trust,
        claim_ceiling,
    }
}

fn print_uncertainty(uncertainty: RetrievalUncertainty) {
    println!("  proof_state: {}", wire_string(uncertainty.proof_state));
    println!(
        "  provenance_class: {}",
        wire_string(uncertainty.provenance_class)
    );
    println!(
        "  semantic_trust: {}",
        wire_string(uncertainty.semantic_trust)
    );
    println!(
        "  claim_ceiling: {}",
        wire_string(uncertainty.claim_ceiling)
    );
}

fn wire_string<T: serde::Serialize>(value: T) -> String {
    serde_json::to_value(value)
        .ok()
        .and_then(|value| value.as_str().map(ToOwned::to_owned))
        .unwrap_or_else(|| "unknown".to_string())
}

fn string_array(value: &serde_json::Value) -> Vec<String> {
    value
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|value| value.as_str().map(ToString::to_string))
        .collect()
}

fn json_number(value: &serde_json::Value, key: &str) -> Option<f32> {
    value.get(key)?.as_f64().map(|value| value as f32)
}