eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
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
use std::future::Future;
use std::time::Duration;

use crate::models::{
    ARTIFACT_SUMMARY_SCHEMA_V1, ERROR_SCHEMA_V2, INSTALL_CHECK_SCHEMA_V1, INSTALL_PLAN_SCHEMA_V1,
    MESH_EVENT_SCHEMA_V1, MESH_PEER_GROUP_BINDING_SCHEMA_V1, MESH_PEER_POLICY_SCHEMA_V1,
    MESH_POLICY_DECISION_SCHEMA_V1, MESH_POLICY_FAILURE_SURFACE_SCHEMA_V1,
    MESH_STORAGE_STATUS_SCHEMA_V1, RESPONSE_SCHEMA_V2, SINGLEFLIGHT_KEY_SCHEMA_V1,
    SINGLEFLIGHT_POSTURE_SCHEMA_V1, SYMBOL_EVIDENCE_LINKS_SCHEMA_V1, SYMBOL_SNAPSHOT_SCHEMA_V1,
    UPDATE_PLAN_SCHEMA_V1,
};

pub mod adaptive_scheduler;
pub mod agent_detect;
pub mod agent_docs;
pub mod agentsmd;
pub mod artifact;
pub mod artifact_relocation;
pub mod ask;
pub mod attest;
pub mod audit;
pub mod audit_lane;
pub mod backup;
pub mod bayes;
pub mod bayes_backfill;
pub mod beads_integrity;
pub mod budget;
pub mod budget_delta_recommender;
pub mod capabilities;
pub mod cass_prefetch;
pub mod causal;
pub mod certificate;
pub mod check;
pub mod claims;
pub mod completion_audit;
pub mod config_explain;
pub mod config_surface;
pub mod conformal;
pub mod contention;
pub mod context;
pub mod context_delta;
pub mod contradiction_detect;
pub mod contradiction_guard;
pub mod contradiction_resolution;
pub mod curate;
pub mod decide;
pub mod degraded_aggregation;
pub mod degraded_honesty;
pub mod derived_asset;
pub mod derived_asset_freshness;
pub mod determinism;
pub mod disk_pressure;
pub mod docs_bootstrap;
pub mod doctor;
pub mod doctor_fixers;
pub mod doctor_runtime;
pub mod duplicate_work_detector;
pub mod economy;
pub mod effect;
pub mod environment_attestation;
pub mod error_diagnosis;
pub mod error_recall;
pub mod explanation_latency_budget;
pub mod feedback;
pub mod focus;
pub mod focus_suggest;
pub mod git_ahead;
pub mod global_promotion;
pub mod global_store;
pub mod graph_audit;
pub mod graph_diff;
pub mod graph_memory_budget;
pub mod graph_telemetry;
pub mod handoff;
pub mod health;
pub mod house_rules;
pub mod hygiene_beads_state;
pub mod hygiene_classifier;
pub mod hygiene_coordination;
pub mod impact;
pub mod index;
pub mod influence;
pub mod init;
pub mod install;
pub mod journal;
pub mod jsonl_import;
pub mod lab;
pub mod learn;
pub mod legacy_import;
pub mod memory;
pub mod memory_debt;
pub mod memory_drift;
pub mod memory_lifecycle;
pub mod memory_scope;
pub mod model;
pub mod orient;
pub mod outcome;
pub mod ownership_snapshot;
pub mod path_safety;
pub mod perf_forensics;
pub mod perf_live;
pub mod plan;
pub mod preflight;
pub mod preflight_guard;
pub mod primer;
pub mod procedure;
pub mod profile;
pub mod proof_verify;
pub mod provenance_health;
pub mod qos;
pub mod quarantine;
pub mod query_miss_cluster;
pub mod read_fence;
pub mod recall;
pub mod recorder;
pub mod rehearse;
pub mod remote_embed;
pub mod repro;
pub mod resume;
pub mod retrieval_affinity;
pub mod rule;
pub mod sandbox;
pub mod search;
pub mod sentinel;
pub mod session_budget;
pub mod shadow_tuning;
pub mod singleflight;
pub mod situation;
pub mod source_run;
pub mod sprt;
pub mod status;
pub mod store_integrity;
pub mod streams;
pub mod subscribe;
pub mod suggest_links;
pub mod support_bundle;
pub mod swarm_brief;
pub mod swarm_brief_delta;
pub mod swarm_next_action;
pub mod symbol_graph;
pub mod tailscale_probe;
pub mod task_frame;
pub mod trauma_guard;
pub mod tripwire;
pub mod trust_report;
pub mod unsafe_claim_planner;
pub mod verify;
pub mod verify_ledger;
pub mod why;
pub mod witness_retention;
pub mod workspace;
pub mod write_owner;

pub use budget::{BudgetDimension, BudgetExceeded, BudgetSnapshot, RequestBudget};
pub use context::{AccessLevel, CapabilitySet, CommandCancellation, CommandContext};
pub use outcome::{
    CliCancelReason, CliOutcomeClass, CliOutcomeSummary, EXIT_CANCELLED, EXIT_PANICKED,
    OutcomeFeedbackSummary, OutcomeRecordOptions, OutcomeRecordReport, OutcomeRecordStatus,
    outcome_class, outcome_exit_code, record_outcome,
};
pub use write_owner::{
    WRITE_OWNER_STATUS_SCHEMA_V1, WRITE_SPOOL_BACKPRESSURE_CODE,
    WRITE_SPOOL_BACKPRESSURE_SCHEMA_V1, WRITE_SPOOL_STATUS_SCHEMA_V1, WriteHandle, WriteOperation,
    WriteOwner, WriteOwnerStatus, WriteResult, WriteSpool, WriteSpoolBackpressureError,
    WriteSpoolBackpressureReason, WriteSpoolBatch, WriteSpoolConfig, WriteSpoolDurability,
    WriteSpoolFailure, WriteSpoolIntent, WriteSpoolIntentKind, WriteSpoolRecord,
    WriteSpoolRecordStatus, WriteSpoolStatus, WriteSpoolTicket,
};

pub const VERSION_PROVENANCE_SCHEMA_V1: &str = "ee.version.provenance.v1";
pub const BUILD_TIMESTAMP_POLICY: &str = "omitted_for_reproducibility";

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BuildFeature {
    pub name: &'static str,
    pub enabled: bool,
}

impl BuildFeature {
    #[must_use]
    pub const fn new(name: &'static str, enabled: bool) -> Self {
        Self { name, enabled }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SupportedSchema {
    pub name: &'static str,
    pub schema: &'static str,
}

impl SupportedSchema {
    #[must_use]
    pub const fn new(name: &'static str, schema: &'static str) -> Self {
        Self { name, schema }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildProvenanceDegradation {
    pub code: &'static str,
    pub severity: &'static str,
    pub message: &'static str,
    pub repair: &'static str,
}

impl BuildProvenanceDegradation {
    #[must_use]
    pub const fn new(
        code: &'static str,
        severity: &'static str,
        message: &'static str,
        repair: &'static str,
    ) -> Self {
        Self {
            code,
            severity,
            message,
            repair,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BuildInfo {
    pub package: &'static str,
    pub version: &'static str,
    pub git_commit: Option<&'static str>,
    pub git_tag: Option<&'static str>,
    pub git_dirty: Option<bool>,
    pub target_triple: &'static str,
    pub target_arch: &'static str,
    pub target_os: &'static str,
    pub build_profile: &'static str,
    pub release_channel: &'static str,
    pub build_timestamp_policy: &'static str,
    pub min_db_migration: u32,
    pub max_db_migration: u32,
}

#[must_use]
pub fn build_info() -> BuildInfo {
    let (min_db_migration, max_db_migration) = db_migration_range();
    BuildInfo {
        package: env!("CARGO_PKG_NAME"),
        version: env!("CARGO_PKG_VERSION"),
        git_commit: clean_build_metadata(option_env!("VERGEN_GIT_SHA")),
        git_tag: clean_build_metadata(option_env!("VERGEN_GIT_DESCRIBE")),
        git_dirty: parse_build_bool(option_env!("VERGEN_GIT_DIRTY")),
        target_triple: clean_build_metadata(option_env!("EE_BUILD_TARGET")).unwrap_or("unknown"),
        target_arch: std::env::consts::ARCH,
        target_os: std::env::consts::OS,
        build_profile: build_profile(),
        release_channel: release_channel(),
        build_timestamp_policy: BUILD_TIMESTAMP_POLICY,
        min_db_migration,
        max_db_migration,
    }
}

#[must_use]
pub fn build_features() -> Vec<BuildFeature> {
    vec![
        BuildFeature::new("fts5", cfg!(feature = "fts5")),
        BuildFeature::new("json", cfg!(feature = "json")),
        BuildFeature::new("embed-fast", cfg!(feature = "embed-fast")),
        BuildFeature::new("lexical-bm25", cfg!(feature = "lexical-bm25")),
        BuildFeature::new("graph", cfg!(feature = "graph")),
        BuildFeature::new(
            "differential-networkx",
            cfg!(feature = "differential-networkx"),
        ),
        BuildFeature::new("mcp", cfg!(feature = "mcp")),
        BuildFeature::new("serve", cfg!(feature = "serve")),
        BuildFeature::new("science-analytics", cfg!(feature = "science-analytics")),
    ]
}

#[must_use]
pub fn supported_schemas() -> Vec<SupportedSchema> {
    vec![
        SupportedSchema::new("response", RESPONSE_SCHEMA_V2),
        SupportedSchema::new("error", ERROR_SCHEMA_V2),
        SupportedSchema::new(
            "typed_memory_fields",
            crate::models::memory::TYPED_MEMORY_FIELDS_SCHEMA_V2,
        ),
        SupportedSchema::new("decide_record", decide::DECIDE_RECORD_SCHEMA_V1),
        SupportedSchema::new("decide_list", decide::DECIDE_LIST_SCHEMA_V1),
        SupportedSchema::new("decide_revisit", decide::DECIDE_REVISIT_SCHEMA_V1),
        SupportedSchema::new("version_provenance", VERSION_PROVENANCE_SCHEMA_V1),
        SupportedSchema::new("symbol_snapshot", SYMBOL_SNAPSHOT_SCHEMA_V1),
        SupportedSchema::new("symbol_evidence_links", SYMBOL_EVIDENCE_LINKS_SCHEMA_V1),
        SupportedSchema::new(
            "memory_drift_snapshot",
            memory_drift::MEMORY_DRIFT_SNAPSHOT_SCHEMA_V1,
        ),
        SupportedSchema::new(
            "memory_drift_queue",
            memory_drift::MEMORY_DRIFT_QUEUE_SCHEMA_V1,
        ),
        SupportedSchema::new(
            "memory_drift_report",
            memory_drift::MEMORY_DRIFT_REPORT_SCHEMA_V1,
        ),
        SupportedSchema::new("install_check", INSTALL_CHECK_SCHEMA_V1),
        SupportedSchema::new("install_plan", INSTALL_PLAN_SCHEMA_V1),
        SupportedSchema::new("host_profile", profile::HOST_PROFILE_PROBE_SCHEMA_V1),
        SupportedSchema::new(
            "profile_config_plan",
            profile::PROFILE_CONFIG_PLAN_SCHEMA_V1,
        ),
        SupportedSchema::new("config_get", config_surface::CONFIG_GET_SCHEMA_V1),
        SupportedSchema::new("config_set", config_surface::CONFIG_SET_SCHEMA_V1),
        SupportedSchema::new(
            "verification_recipe",
            profile::VERIFICATION_RECIPE_SCHEMA_V1,
        ),
        SupportedSchema::new("runtime_profile", profile::RUNTIME_PROFILE_SCHEMA_V1),
        SupportedSchema::new("update_plan", UPDATE_PLAN_SCHEMA_V1),
        SupportedSchema::new("artifact_summary", ARTIFACT_SUMMARY_SCHEMA_V1),
        SupportedSchema::new(
            "derived_asset_store_summary",
            derived_asset::DERIVED_ASSET_STORE_SUMMARY_SCHEMA_V1,
        ),
        SupportedSchema::new(
            "artifact_relocation",
            artifact_relocation::ARTIFACT_RELOCATION_SCHEMA_V1,
        ),
        SupportedSchema::new("compare_result", perf_forensics::COMPARE_RESULT_SCHEMA_V1),
        SupportedSchema::new("budget_check", perf_forensics::BUDGET_CHECK_SCHEMA_V1),
        SupportedSchema::new("perf_live", perf_live::PERF_LIVE_SCHEMA_V1),
        SupportedSchema::new("swarm_brief", swarm_brief::SWARM_BRIEF_SCHEMA_V1),
        SupportedSchema::new("insights", "ee.insights.v1"),
        SupportedSchema::new("context_pack_dna", "ee.context.pack_dna.v1"),
        SupportedSchema::new("why_causal", "ee.why.causal.v1"),
        SupportedSchema::new("health_structural", "ee.health.structural.v1"),
        SupportedSchema::new("status_skyline", "ee.status.skyline.v1"),
        SupportedSchema::new("memory_impact_analysis", "ee.memory.impact_analysis.v1"),
        SupportedSchema::new("proximity", "ee.proximity.v1"),
        SupportedSchema::new(
            "graph_witness_prune",
            witness_retention::WITNESS_PRUNE_REPORT_SCHEMA_V1,
        ),
        SupportedSchema::new("why_augmented", "ee.why.v1"),
        SupportedSchema::new("context_augmented", "ee.context.v1"),
        SupportedSchema::new("mesh_event", MESH_EVENT_SCHEMA_V1),
        SupportedSchema::new("mesh_peer_group_binding", MESH_PEER_GROUP_BINDING_SCHEMA_V1),
        SupportedSchema::new("mesh_peer_policy", MESH_PEER_POLICY_SCHEMA_V1),
        SupportedSchema::new("mesh_policy_decision", MESH_POLICY_DECISION_SCHEMA_V1),
        SupportedSchema::new(
            "mesh_policy_failure_surface",
            MESH_POLICY_FAILURE_SURFACE_SCHEMA_V1,
        ),
        SupportedSchema::new("mesh_storage_status", MESH_STORAGE_STATUS_SCHEMA_V1),
        SupportedSchema::new("singleflight_key", SINGLEFLIGHT_KEY_SCHEMA_V1),
        SupportedSchema::new("singleflight_posture", SINGLEFLIGHT_POSTURE_SCHEMA_V1),
        SupportedSchema::new("proof_check", proof_verify::PROOF_CHECK_SCHEMA_V1),
        SupportedSchema::new(
            "disk_pressure_diagnostics",
            disk_pressure::DISK_PRESSURE_DIAGNOSTICS_SCHEMA_V1,
        ),
        SupportedSchema::new(
            "agent_harness_log_classifier",
            disk_pressure::AGENT_HARNESS_LOG_CLASSIFIER_SCHEMA_V1,
        ),
        SupportedSchema::new(
            "artifact_retention_diagnostics",
            disk_pressure::ARTIFACT_RETENTION_DIAGNOSTICS_SCHEMA_V1,
        ),
        SupportedSchema::new(
            "build_admission_diagnostics",
            disk_pressure::BUILD_ADMISSION_DIAGNOSTICS_SCHEMA_V1,
        ),
        SupportedSchema::new(
            "pack_quality_report",
            crate::eval::PACK_QUALITY_REPORT_SCHEMA_V1,
        ),
    ]
}

#[must_use]
pub fn db_migration_range() -> (u32, u32) {
    let min = crate::db::MIGRATIONS
        .first()
        .map_or(0, crate::db::Migration::version);
    let max = crate::db::MIGRATIONS
        .last()
        .map_or(0, crate::db::Migration::version);
    (min, max)
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VersionReport {
    pub build: BuildInfo,
    pub features: Vec<BuildFeature>,
    pub schemas: Vec<SupportedSchema>,
    pub degradations: Vec<BuildProvenanceDegradation>,
}

impl VersionReport {
    #[must_use]
    pub fn gather() -> Self {
        let build = build_info();
        let mut degradations = Vec::new();

        if build.git_commit.is_none() && build.git_tag.is_none() && build.git_dirty.is_none() {
            degradations.push(BuildProvenanceDegradation::new(
                "git_metadata_unavailable",
                "low",
                "Git source metadata was not provided by the build.",
                "Build with VERGEN_GIT_SHA, VERGEN_GIT_DESCRIBE, and VERGEN_GIT_DIRTY set.",
            ));
        }

        if build.target_triple == "unknown" {
            degradations.push(BuildProvenanceDegradation::new(
                "target_triple_unavailable",
                "low",
                "Target triple was not provided by the build.",
                "Build with EE_BUILD_TARGET set to the target triple.",
            ));
        }

        Self {
            build,
            features: build_features(),
            schemas: supported_schemas(),
            degradations,
        }
    }

    #[must_use]
    pub fn provenance_available(&self) -> bool {
        self.degradations.is_empty()
    }
}

fn clean_build_metadata(value: Option<&'static str>) -> Option<&'static str> {
    match value {
        Some(value)
            if !value.is_empty()
                && !value.contains('/')
                && !value.contains('\\')
                && !value.contains('=')
                && !value.contains('\n')
                && !value.contains('\r') =>
        {
            Some(value)
        }
        _ => None,
    }
}

fn parse_build_bool(value: Option<&'static str>) -> Option<bool> {
    match clean_build_metadata(value) {
        Some("true" | "1" | "yes") => Some(true),
        Some("false" | "0" | "no") => Some(false),
        _ => None,
    }
}

const fn build_profile() -> &'static str {
    if cfg!(debug_assertions) {
        "debug"
    } else {
        "release"
    }
}

fn release_channel() -> &'static str {
    match option_env!("EE_RELEASE_CHANNEL") {
        Some("stable") => "stable",
        Some("beta") => "beta",
        Some("nightly") => "nightly",
        Some("dev") => "dev",
        _ if cfg!(debug_assertions) => "dev",
        _ => "stable",
    }
}

pub const CLI_RUNTIME_WORKERS: usize = 1;

pub type RuntimeResult<T> = Result<T, Box<asupersync::Error>>;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RuntimeProfile {
    CurrentThread,
}

impl RuntimeProfile {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::CurrentThread => "current_thread",
        }
    }

    #[must_use]
    pub const fn worker_threads(self) -> usize {
        match self {
            Self::CurrentThread => CLI_RUNTIME_WORKERS,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RuntimeStatus {
    pub engine: &'static str,
    pub profile: RuntimeProfile,
    pub async_boundary: &'static str,
}

impl RuntimeStatus {
    #[must_use]
    pub const fn worker_threads(self) -> usize {
        self.profile.worker_threads()
    }
}

#[must_use]
pub const fn runtime_status() -> RuntimeStatus {
    RuntimeStatus {
        engine: "asupersync",
        profile: RuntimeProfile::CurrentThread,
        async_boundary: "core",
    }
}

/// Lower bound on the CLI blocking pool. Two threads, so a single long
/// blocking task cannot starve every other offloaded call, and no more,
/// because a command that never offloads should pay almost nothing.
const CLI_BLOCKING_POOL_MIN_THREADS: usize = 0;
const CLI_BLOCKING_POOL_FLOOR: usize = 2;

/// Upper bound on the CLI blocking pool.
///
/// These tasks are blocking file I/O, not CPU work, so the useful ceiling is
/// set by how many concurrent reads the storage layer can absorb rather than
/// by core count. A 64-core build host should not open 64 blocking threads for
/// a one-shot `ee doctor`.
const CLI_BLOCKING_POOL_CEILING: usize = 16;

/// Size the CLI blocking pool from the host's parallelism, clamped.
///
/// GH #35: with no pool installed, `asupersync`'s offload helper falls back to
/// `spawn_blocking_on_thread`, which creates a fresh OS thread per call and
/// never reuses it - bounded only in *concurrency*, not in total count. On a
/// store whose WAL still holds its frames that means one thread per frame read,
/// per connection open: ~19,400 short-lived threads to read a 5.5 MB file.
/// A real pool makes thread creation O(cores) instead of O(reads).
#[must_use]
pub fn cli_blocking_pool_threads() -> (usize, usize) {
    let parallelism =
        std::thread::available_parallelism().map_or(CLI_BLOCKING_POOL_FLOOR, |n| n.get());
    let max = parallelism.clamp(CLI_BLOCKING_POOL_FLOOR, CLI_BLOCKING_POOL_CEILING);
    (CLI_BLOCKING_POOL_MIN_THREADS, max)
}

pub fn build_cli_runtime() -> RuntimeResult<asupersync::runtime::Runtime> {
    // Every `ee` runtime is built here - this is the only `RuntimeBuilder` in
    // the crate, and the daemon's write-owner runtime comes through it too - so
    // installing the blocking pool at this one seam covers every entry point
    // that opens a database. A pool present on one command and missing on
    // another is exactly the shape of defect GH #35 reported.
    let (min_blocking, max_blocking) = cli_blocking_pool_threads();
    asupersync::runtime::RuntimeBuilder::current_thread()
        .thread_name_prefix("ee-runtime")
        .blocking_threads(min_blocking, max_blocking)
        .build()
        .map_err(Box::new)
}

pub fn run_cli_future<F, T>(future: F) -> RuntimeResult<T>
where
    F: Future<Output = T>,
{
    let runtime = build_cli_runtime()?;
    Ok(runtime.block_on(future))
}

/// Run a synchronous CLI operation with an explicit, bounded production
/// request context.
///
/// The context is minted by [`asupersync::runtime::Runtime`] so it inherits
/// the runtime's drivers and capability mask. This is the production root for
/// sync adapters that must pass a caller-owned [`asupersync::Cx`] into async
/// search, pack, or index work; those adapters must not recover authority via
/// `Cx::current()` or manufacture it with a test constructor.
pub fn run_cli_with_cx<F, Fut, T>(timeout: Duration, operation: F) -> RuntimeResult<T>
where
    F: FnOnce(asupersync::Cx) -> Fut,
    Fut: Future<Output = T>,
{
    let runtime = build_cli_runtime()?;
    let bootstrap = runtime.request_cx_with_budget(asupersync::Budget::INFINITE);
    let budget = bootstrap.budget_for_timeout(timeout);
    let cx = runtime.request_cx_with_budget(budget);
    Ok(runtime.block_on(async move {
        let _ambient = asupersync::Cx::set_current(Some(cx.clone()));
        operation(cx).await
    }))
}

/// Single-quote a repair-hint argument whenever it contains
/// shell-significant characters, so the copy-pasteable retarget command
/// stays executable for workspace paths with spaces or quotes. Same rules
/// as the CLI's `shell_quote_cli_arg`.
#[must_use]
fn shell_quote_repair_arg(value: &str) -> String {
    if value.is_empty() {
        "''".to_owned()
    } else if value
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | '/' | ':'))
    {
        value.to_owned()
    } else {
        format!("'{}'", value.replace('\'', "'\\''"))
    }
}

struct StorelessWorkspaceAssessment {
    addressed_store_path: String,
    addressed_workspace_path: String,
    addressed_workspace_argument: String,
    discovery: crate::core::orient::NearbyStoreScanAssessment,
    candidate_retargets: Vec<StorelessWorkspaceRetarget>,
    init_command: String,
    recovery_actions: Vec<crate::models::RecoveryAction>,
}

struct StorelessWorkspaceRetarget {
    store: crate::core::orient::NearbyStore,
    arguments: String,
}

impl StorelessWorkspaceAssessment {
    fn inspect(database_path: &std::path::Path) -> Self {
        Self::inspect_with_discovery(
            database_path,
            std::time::Duration::from_millis(crate::core::orient::NEARBY_STORE_SCAN_BUDGET_MS),
            None,
        )
    }

    fn inspect_with_discovery(
        database_path: &std::path::Path,
        budget: std::time::Duration,
        registry_path: Option<&std::path::Path>,
    ) -> Self {
        let addressed_store_path = database_path.display().to_string();
        let addressed_workspace = storeless_workspace_root(database_path);
        let addressed_workspace_path = addressed_workspace.display().to_string();
        let addressed_workspace_argument = format!(
            "--workspace {}",
            shell_quote_repair_arg(&addressed_workspace_path)
        );
        let discovery = crate::core::orient::discover_nearby_stores_for_database_with_registry(
            &addressed_workspace,
            database_path,
            budget,
            registry_path,
        );
        let candidate_retargets = storeless_workspace_candidate_retargets(&discovery);
        let init_command = format!("ee init {addressed_workspace_argument}");
        let recovery_actions = storeless_workspace_recovery_actions(
            &addressed_store_path,
            &addressed_workspace_path,
            &addressed_workspace_argument,
            &candidate_retargets,
            &init_command,
        );
        Self {
            addressed_store_path,
            addressed_workspace_path,
            addressed_workspace_argument,
            discovery,
            candidate_retargets,
            init_command,
            recovery_actions,
        }
    }

    fn repair(&self) -> String {
        let looked_for = &self.addressed_store_path;
        let mut repair = format!(
            "Re-check --workspace addressing with {} (looked for {looked_for})",
            self.addressed_workspace_argument
        );
        if let Some((best, additional)) = self.candidate_retargets.split_first() {
            repair.push_str(&format!(
                "; a populated store exists at {} ({} docs) — retarget with {}",
                best.store.workspace_root, best.store.documents, best.arguments,
            ));
            if !additional.is_empty() {
                repair.push_str(". Other nearby populated stores:");
                for (index, retarget) in additional.iter().enumerate() {
                    if index > 0 {
                        repair.push(';');
                    }
                    repair.push_str(&format!(
                        " {} ({} docs) — retarget with {}",
                        retarget.store.workspace_root, retarget.store.documents, retarget.arguments,
                    ));
                }
            }
        }
        match self.discovery.outcome {
            crate::core::orient::NearbyStoreScanOutcome::Complete => {
                if self.candidate_retargets.is_empty() {
                    repair.push_str(
                        ". Nearby-store discovery completed and found no populated stores",
                    );
                }
            }
            crate::core::orient::NearbyStoreScanOutcome::Truncated => repair.push_str(
                ". Nearby-store discovery was truncated; listed results are partial, and an empty list is not evidence that no populated store exists",
            ),
            crate::core::orient::NearbyStoreScanOutcome::TruncatedRegistryUnavailable => repair.push_str(
                ". Nearby-store discovery was truncated because the optional workspace registry was unavailable; locally proved results remain actionable, and an empty list is not evidence that no populated store exists",
            ),
            crate::core::orient::NearbyStoreScanOutcome::Unavailable => repair.push_str(
                ". Nearby-store discovery was unavailable; listed results, if any, are partial, and no complete nearby-store conclusion is available",
            ),
        }
        repair.push_str(&format!(
            ". Only if you intended to create a NEW store here: {}",
            self.init_command
        ));
        repair
    }

    fn details_json(&self) -> String {
        serde_json::json!({
            "addressedStorePath": self.addressed_store_path,
            "addressedWorkspacePath": self.addressed_workspace_path,
            "storeDiscovery": {
                "outcome": self.discovery.outcome,
                "nearbyStores": self.discovery.stores,
            }
        })
        .to_string()
    }
}

fn storeless_workspace_candidate_retargets(
    discovery: &crate::core::orient::NearbyStoreScanAssessment,
) -> Vec<StorelessWorkspaceRetarget> {
    if discovery.outcome == crate::core::orient::NearbyStoreScanOutcome::Unavailable {
        return Vec::new();
    }
    discovery
        .stores
        .iter()
        .cloned()
        .map(|store| {
            let database = std::path::Path::new(&store.store_dir).join("ee.db");
            let arguments = format!(
                "--workspace {} --database {}",
                shell_quote_repair_arg(&store.workspace_root),
                shell_quote_repair_arg(&database.display().to_string())
            );
            StorelessWorkspaceRetarget { store, arguments }
        })
        .collect()
}

fn storeless_workspace_root(database_path: &std::path::Path) -> std::path::PathBuf {
    let database_parent = database_path.parent();
    let is_default_workspace_database = database_path
        .file_name()
        .is_some_and(|name| name == "ee.db")
        && database_parent
            .and_then(std::path::Path::file_name)
            .is_some_and(|name| name == ".ee");
    (if is_default_workspace_database {
        database_parent.and_then(std::path::Path::parent)
    } else {
        database_parent
    })
    .unwrap_or_else(|| std::path::Path::new("."))
    .to_path_buf()
}

fn storeless_workspace_recovery_actions(
    addressed_store_path: &str,
    addressed_workspace_path: &str,
    addressed_workspace_argument: &str,
    retargets: &[StorelessWorkspaceRetarget],
    init_command: &str,
) -> Vec<crate::models::RecoveryAction> {
    let mut addressed = crate::models::RecoveryAction::flag(
        1,
        "--workspace",
        addressed_workspace_path.to_owned(),
        "Re-check the exact addressed workspace before selecting another store.",
    );
    addressed.example = Some(addressed_workspace_argument.to_owned());
    let mut actions = vec![addressed];
    if retargets.is_empty() {
        let mut database = crate::models::RecoveryAction::env(
            2,
            "EE_DATABASE_PATH",
            addressed_store_path,
            "Re-check the exact addressed database override before initializing a new store.",
        );
        database.example = Some(format!(
            "EE_DATABASE_PATH={}",
            shell_quote_repair_arg(addressed_store_path)
        ));
        actions.push(database);
    }
    for (index, retarget) in retargets.iter().enumerate() {
        let priority = u8::try_from(index.saturating_add(2)).unwrap_or(u8::MAX - 1);
        let mut action = crate::models::RecoveryAction::flag(
            priority,
            "--workspace",
            retarget.store.workspace_root.clone(),
            format!(
                "Retarget to this ranked populated workspace ({} live memories).",
                retarget.store.documents
            ),
        );
        action.example = Some(retarget.arguments.clone());
        actions.push(action);
    }
    let init_priority = u8::try_from(actions.len().saturating_add(1)).unwrap_or(u8::MAX);
    actions.push(crate::models::RecoveryAction {
        priority: init_priority,
        kind: crate::models::RecoveryKind::Seed,
        rationale:
            "Only initialize when this exact addressed workspace was intentionally chosen for a new store."
                .to_owned(),
        env_name: None,
        value_hint: None,
        config_path: None,
        config_key: None,
        flag_name: None,
        command: Some(init_command.to_owned()),
        results_in: None,
        example: None,
    });
    actions
}

/// Repair guidance for a storeless-workspace miss with safe ordering:
/// re-check addressing first, rank populated stores next, and mention `ee
/// init` last and only conditionally. A lookup miss must not mechanically
/// plant a new empty store at a mistyped path.
#[must_use]
pub fn storeless_workspace_repair(database_path: &std::path::Path) -> String {
    StorelessWorkspaceAssessment::inspect(database_path).repair()
}

/// Canonical storeless-workspace miss error
/// (bd-workspace-miss-init-suggestion-sfjvq): the stable
/// `workspace_store_missing` identity with its own process exit code, the
/// exact looked-for path in the message, and the safe recovery ordering from
/// [`storeless_workspace_repair`] — re-check addressing first, nearby
/// populated stores second, `ee init` last and explicitly conditional.
#[must_use]
pub fn storeless_workspace_error(database_path: &std::path::Path) -> crate::models::DomainError {
    let assessment = StorelessWorkspaceAssessment::inspect(database_path);
    let repair = assessment.repair();
    let details_json = assessment.details_json();
    crate::models::DomainError::WorkspaceStoreMissing {
        message: format!("Database not found at {}", database_path.display()),
        repair: Some(repair),
        details_json,
        recovery_actions: assessment.recovery_actions,
    }
}

/// Require an already-addressed database path to exist without opening it.
///
/// `DbConnection::open_file` is create-capable because `ee init` owns store
/// creation. Lookup and ordinary write surfaces must preflight the exact path
/// first so a typo cannot plant a new store. Only a genuine `NotFound` is an
/// addressing miss; permission and other inspection failures remain storage
/// errors rather than being misreported as an absent workspace.
pub fn ensure_addressed_database_exists(
    database_path: &std::path::Path,
) -> Result<(), crate::models::DomainError> {
    match std::fs::symlink_metadata(database_path) {
        Ok(metadata) if metadata.file_type().is_file() => Ok(()),
        Ok(metadata) if metadata.file_type().is_symlink() => {
            match std::fs::metadata(database_path) {
                Ok(target) if target.file_type().is_file() => Ok(()),
                Ok(_) => Err(crate::models::DomainError::Storage {
                    message: format!(
                        "Addressed database symlink does not target a regular file: {}",
                        database_path.display()
                    ),
                    repair: Some("ee doctor --workspace . --json".to_owned()),
                }),
                Err(error) => Err(crate::models::DomainError::Storage {
                    message: format!(
                        "Failed to inspect addressed database symlink target {}: {error}",
                        database_path.display()
                    ),
                    repair: Some("ee doctor --workspace . --json".to_owned()),
                }),
            }
        }
        Ok(_) => Err(crate::models::DomainError::Storage {
            message: format!(
                "Addressed database path is not a regular file: {}",
                database_path.display()
            ),
            repair: Some("ee doctor --workspace . --json".to_owned()),
        }),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            Err(storeless_workspace_error(database_path))
        }
        Err(error) => Err(crate::models::DomainError::Storage {
            message: format!(
                "Failed to inspect addressed database {}: {error}",
                database_path.display()
            ),
            repair: Some("ee doctor --workspace . --json".to_owned()),
        }),
    }
}

/// Serialize a value to JSON, returning a stable error envelope on failure.
///
/// Use for display-only `to_json()` methods where failure should produce valid JSON
/// rather than an empty string. For machine-facing APIs, prefer returning `Result`.
#[must_use]
pub fn serialize_or_error<T: serde::Serialize>(value: &T) -> String {
    serde_json::to_string(value).unwrap_or_else(|error| {
        serde_json::json!({
            "error": "serialization_failed",
            "message": error.to_string(),
        })
        .to_string()
    })
}

/// Serialize a value to pretty JSON, returning a stable error envelope on failure.
#[must_use]
pub fn serialize_pretty_or_error<T: serde::Serialize>(value: &T) -> String {
    serde_json::to_string_pretty(value).unwrap_or_else(|error| {
        serde_json::to_string_pretty(&serde_json::json!({
            "error": "serialization_failed",
            "message": error.to_string(),
        }))
        .unwrap_or_else(|_| {
            r#"{"error":"serialization_failed","message":"serialization fallback failed"}"#
                .to_owned()
        })
    })
}

/// Convert a duration to milliseconds without wrapping on long-running processes.
#[must_use]
pub(crate) fn duration_millis_saturating(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

#[cfg(test)]
mod tests {
    use std::fmt::Debug;
    use std::time::Duration;

    use asupersync::{LabConfig, LabRuntime};

    use super::{
        BUILD_TIMESTAMP_POLICY, CLI_BLOCKING_POOL_CEILING, CLI_BLOCKING_POOL_FLOOR, RuntimeProfile,
        StorelessWorkspaceAssessment, VERSION_PROVENANCE_SCHEMA_V1, VersionReport,
        build_cli_runtime, build_features, build_info, clean_build_metadata,
        cli_blocking_pool_threads, db_migration_range, duration_millis_saturating,
        parse_build_bool, run_cli_future, runtime_status, serialize_or_error,
        serialize_pretty_or_error, shell_quote_repair_arg, storeless_workspace_candidate_retargets,
        supported_schemas,
    };

    type TestResult = Result<(), String>;

    fn ensure(condition: bool, message: impl Into<String>) -> TestResult {
        if condition {
            Ok(())
        } else {
            Err(message.into())
        }
    }

    fn ensure_equal<T>(actual: &T, expected: &T, context: &str) -> TestResult
    where
        T: Debug + PartialEq,
    {
        if actual == expected {
            Ok(())
        } else {
            Err(format!("{context}: expected {expected:?}, got {actual:?}"))
        }
    }

    // GH #35: with no blocking pool on the runtime, asupersync's offload helper
    // falls back to `spawn_blocking_on_thread` - a fresh OS thread per call,
    // never reused, bounded only in concurrency. On a store whose WAL still
    // holds its frames that becomes one thread per frame read per connection
    // open: ~19,400 short-lived threads to read a 5.5 MB file. These pin the
    // seam that makes thread creation O(cores) instead of O(reads).

    #[test]
    fn every_cli_runtime_installs_a_blocking_pool() -> TestResult {
        // `build_cli_runtime` is the only `RuntimeBuilder` in the crate, and the
        // daemon's write-owner runtime is built through it too, so this single
        // assertion covers every entry point that can open a database. If a
        // second runtime construction is ever added, it must come through here
        // or this guarantee silently stops holding.
        let runtime = build_cli_runtime().map_err(|error| format!("build runtime: {error}"))?;
        ensure(
            runtime.blocking_handle().is_some(),
            "the CLI runtime must carry a blocking pool, or every offloaded \
             call spawns and discards its own OS thread",
        )
    }

    #[test]
    fn blocking_pool_is_bounded_and_never_eager() -> TestResult {
        let (min, max) = cli_blocking_pool_threads();
        ensure(max > 0, "a zero maximum disables the pool entirely")?;
        ensure(
            min == 0,
            "the pool must not spawn threads eagerly; a command that never \
             offloads should pay nothing for the pool existing",
        )?;
        ensure(
            max >= CLI_BLOCKING_POOL_FLOOR,
            "one long blocking task must not be able to starve every other \
             offloaded call",
        )?;
        ensure(
            max <= CLI_BLOCKING_POOL_CEILING,
            "a 64-core host must not open 64 blocking threads for one-shot ee",
        )?;
        Ok(())
    }

    #[test]
    fn blocking_pool_size_tracks_host_parallelism() -> TestResult {
        let (_, max) = cli_blocking_pool_threads();
        let parallelism =
            std::thread::available_parallelism().map_or(CLI_BLOCKING_POOL_FLOOR, |n| n.get());
        let expected = parallelism.clamp(CLI_BLOCKING_POOL_FLOOR, CLI_BLOCKING_POOL_CEILING);
        ensure_equal(
            &max,
            &expected,
            "pool ceiling is derived from available_parallelism, not hardcoded",
        )
    }

    #[test]
    fn build_info_uses_cargo_metadata() -> TestResult {
        let info = build_info();
        ensure_equal(
            &info.package,
            &"eidetic-engine",
            "package name must match Cargo metadata",
        )?;
        ensure(
            !info.version.is_empty(),
            "package version must not be empty",
        )?;
        ensure_equal(
            &info.build_timestamp_policy,
            &BUILD_TIMESTAMP_POLICY,
            "timestamp policy",
        )?;
        ensure(
            info.min_db_migration <= info.max_db_migration,
            "database migration range must be ordered",
        )
    }

    #[test]
    fn storeless_repair_arg_quoting_keeps_retarget_commands_executable() -> TestResult {
        ensure_equal(
            &shell_quote_repair_arg("/plain/path-1.2:x"),
            &"/plain/path-1.2:x".to_owned(),
            "plain paths stay unquoted",
        )?;
        ensure_equal(
            &shell_quote_repair_arg("/tmp/nearby store root"),
            &"'/tmp/nearby store root'".to_owned(),
            "a spaced path must be single-quoted",
        )?;
        ensure_equal(
            &shell_quote_repair_arg("/tmp/it's here"),
            &"'/tmp/it'\\''s here'".to_owned(),
            "an embedded single quote must be escaped",
        )?;
        ensure_equal(
            &shell_quote_repair_arg(""),
            &"''".to_owned(),
            "an empty value must stay a visible empty argument",
        )
    }

    #[test]
    fn version_report_uses_stable_ordered_contracts() -> TestResult {
        let report = VersionReport::gather();
        ensure_equal(
            &report.features.first().map(|feature| feature.name),
            &Some("fts5"),
            "first feature",
        )?;
        ensure_equal(
            &report
                .schemas
                .iter()
                .any(|schema| schema.schema == VERSION_PROVENANCE_SCHEMA_V1),
            &true,
            "version schema advertised",
        )?;
        ensure_equal(
            &report.provenance_available(),
            &report.degradations.is_empty(),
            "availability mirrors degradations",
        )
    }

    #[test]
    fn build_feature_flags_are_deterministically_ordered() -> TestResult {
        let names: Vec<&str> = build_features()
            .iter()
            .map(|feature| feature.name)
            .collect();
        ensure_equal(
            &names,
            &vec![
                "fts5",
                "json",
                "embed-fast",
                "lexical-bm25",
                "graph",
                "differential-networkx",
                "mcp",
                "serve",
                "science-analytics",
            ],
            "feature order",
        )
    }

    #[test]
    fn supported_schemas_include_response_error_and_version() -> TestResult {
        let schemas: Vec<&str> = supported_schemas()
            .iter()
            .map(|schema| schema.name)
            .collect();
        ensure_equal(
            &schemas,
            &vec![
                "response",
                "error",
                "typed_memory_fields",
                "decide_record",
                "decide_list",
                "decide_revisit",
                "version_provenance",
                "symbol_snapshot",
                "symbol_evidence_links",
                "memory_drift_snapshot",
                "memory_drift_queue",
                "memory_drift_report",
                "install_check",
                "install_plan",
                "host_profile",
                "profile_config_plan",
                "config_get",
                "config_set",
                "verification_recipe",
                "runtime_profile",
                "update_plan",
                "artifact_summary",
                "derived_asset_store_summary",
                "artifact_relocation",
                "compare_result",
                "budget_check",
                "perf_live",
                "swarm_brief",
                "insights",
                "context_pack_dna",
                "why_causal",
                "health_structural",
                "status_skyline",
                "memory_impact_analysis",
                "proximity",
                "graph_witness_prune",
                "why_augmented",
                "context_augmented",
                "mesh_event",
                "mesh_peer_group_binding",
                "mesh_peer_policy",
                "mesh_policy_decision",
                "mesh_policy_failure_surface",
                "mesh_storage_status",
                "singleflight_key",
                "singleflight_posture",
                "proof_check",
                "disk_pressure_diagnostics",
                "agent_harness_log_classifier",
                "artifact_retention_diagnostics",
                "build_admission_diagnostics",
                "pack_quality_report",
            ],
            "schema names",
        )
    }

    #[test]
    fn supported_schemas_advertise_current_response_envelope() -> TestResult {
        let response = supported_schemas()
            .into_iter()
            .find(|schema| schema.name == "response")
            .ok_or_else(|| "response schema should be advertised".to_string())?;
        let legacy_schema = ["ee", "response", "v1"].join(".");

        ensure_equal(
            &response.schema,
            &crate::models::RESPONSE_SCHEMA_V2,
            "response schema id",
        )?;
        ensure(
            response.schema != legacy_schema,
            "supported schemas must not advertise the legacy response envelope",
        )
    }

    #[test]
    fn db_migration_range_matches_declared_migrations() -> TestResult {
        let (min, max) = db_migration_range();
        ensure(min > 0, "minimum migration should be known")?;
        ensure(max >= min, "maximum migration should be >= minimum")
    }

    #[test]
    fn build_metadata_sanitizer_rejects_path_like_values() -> TestResult {
        ensure_equal(
            &clean_build_metadata(Some("abc123")),
            &Some("abc123"),
            "plain metadata",
        )?;
        ensure_equal(
            &clean_build_metadata(Some("/tmp/build/path-like-value")),
            &None,
            "path metadata must be redacted",
        )?;
        ensure_equal(
            &clean_build_metadata(Some("BUILD_META=value")),
            &None,
            "assignment metadata must be redacted",
        )
    }

    #[test]
    fn build_bool_parser_accepts_stable_literals() -> TestResult {
        ensure_equal(&parse_build_bool(Some("true")), &Some(true), "true")?;
        ensure_equal(&parse_build_bool(Some("0")), &Some(false), "zero")?;
        ensure_equal(&parse_build_bool(Some("maybe")), &None, "unknown bool")
    }

    #[test]
    fn runtime_status_reports_asupersync_current_thread_bootstrap() -> TestResult {
        let status = runtime_status();
        ensure_equal(&status.engine, &"asupersync", "runtime engine")?;
        ensure_equal(
            &status.profile,
            &RuntimeProfile::CurrentThread,
            "runtime profile",
        )?;
        ensure_equal(
            &status.profile.as_str(),
            &"current_thread",
            "runtime profile label",
        )?;
        ensure_equal(&status.worker_threads(), &1, "runtime worker count")?;
        ensure_equal(&status.async_boundary, &"core", "runtime async boundary")
    }

    #[test]
    fn cli_runtime_executes_future_to_completion() -> TestResult {
        let result = run_cli_future(async { 42_u8 })
            .map_err(|error| format!("failed to build Asupersync runtime: {error}"))?;

        ensure_equal(&result, &42, "runtime future result")
    }

    #[test]
    fn lab_runtime_seed_is_deterministic_for_runtime_contract_tests() -> TestResult {
        let first = LabRuntime::new(LabConfig::new(7));
        let second = LabRuntime::new(LabConfig::new(7));

        ensure_equal(&first.now(), &second.now(), "lab runtime start time")?;
        ensure_equal(&first.steps(), &second.steps(), "lab runtime step count")
    }

    #[test]
    fn serialize_or_error_produces_valid_json_on_success() -> TestResult {
        #[derive(serde::Serialize)]
        struct TestData {
            name: String,
            count: u32,
        }
        let data = TestData {
            name: "test".to_string(),
            count: 42,
        };
        let json = serialize_or_error(&data);
        ensure(
            json.contains("\"name\":\"test\""),
            "should contain name field",
        )?;
        ensure(json.contains("\"count\":42"), "should contain count field")
    }

    #[test]
    fn serialize_or_error_produces_error_envelope_on_failure() -> TestResult {
        use std::collections::HashMap;
        let mut map: HashMap<Vec<u8>, String> = HashMap::new();
        map.insert(vec![0xFF], "invalid key".to_string());
        let json = serialize_or_error(&map);
        let parsed: serde_json::Value =
            serde_json::from_str(&json).map_err(|error| error.to_string())?;
        ensure(
            parsed.get("error").and_then(serde_json::Value::as_str) == Some("serialization_failed"),
            "should contain error marker in valid JSON",
        )
    }

    #[test]
    fn serialization_error_fallback_escapes_error_messages() -> TestResult {
        use serde::ser::{Error as _, Serialize, Serializer};

        struct FailsWithQuotedMessage;

        impl Serialize for FailsWithQuotedMessage {
            fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                Err(S::Error::custom("bad \"quoted\" serializer\nmessage"))
            }
        }

        let compact = serialize_or_error(&FailsWithQuotedMessage);
        let compact_json: serde_json::Value =
            serde_json::from_str(&compact).map_err(|error| error.to_string())?;
        ensure_equal(
            &compact_json
                .get("error")
                .and_then(serde_json::Value::as_str),
            &Some("serialization_failed"),
            "compact fallback error code",
        )?;
        ensure(
            compact_json
                .get("message")
                .and_then(serde_json::Value::as_str)
                .is_some_and(|message| message.contains("\"quoted\"")),
            "compact fallback preserves quoted error text",
        )?;

        let pretty = serialize_pretty_or_error(&FailsWithQuotedMessage);
        let pretty_json: serde_json::Value =
            serde_json::from_str(&pretty).map_err(|error| error.to_string())?;
        ensure_equal(
            &pretty_json.get("error").and_then(serde_json::Value::as_str),
            &Some("serialization_failed"),
            "pretty fallback error code",
        )
    }

    #[test]
    fn serialize_pretty_or_error_produces_formatted_json() -> TestResult {
        #[derive(serde::Serialize)]
        struct TestData {
            value: u32,
        }
        let data = TestData { value: 1 };
        let json = serialize_pretty_or_error(&data);
        ensure(json.contains('\n'), "pretty output should have newlines")
    }

    #[test]
    fn duration_millis_saturating_caps_overflow() -> TestResult {
        ensure_equal(
            &duration_millis_saturating(Duration::from_millis(42)),
            &42,
            "ordinary millisecond duration",
        )?;
        ensure_equal(
            &duration_millis_saturating(Duration::from_secs(u64::MAX)),
            &u64::MAX,
            "overflowing millisecond duration saturates",
        )
    }

    #[test]
    fn storeless_assessment_propagates_truncated_discovery_without_creating_state() -> TestResult {
        let temp = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = temp.path().join("partial workspace's path");
        std::fs::create_dir_all(workspace.join(".git")).map_err(|error| error.to_string())?;
        let database = workspace.join(".ee").join("ee.db");
        let absent_registry = temp.path().join("absent-registry.db");

        let assessment = StorelessWorkspaceAssessment::inspect_with_discovery(
            &database,
            Duration::ZERO,
            Some(&absent_registry),
        );
        let details: serde_json::Value =
            serde_json::from_str(&assessment.details_json()).map_err(|error| error.to_string())?;
        let repair = assessment.repair();

        ensure_equal(
            &details.pointer("/storeDiscovery/outcome"),
            &Some(&serde_json::json!("truncated")),
            "truncated store-discovery outcome",
        )?;
        ensure(
            details.pointer("/storeDiscovery/truncated").is_none()
                && details.pointer("/storeDiscovery/scanned").is_none(),
            "ambiguous discovery booleans must be absent from the canonical assessment",
        )?;
        ensure(
            repair.contains("discovery was truncated")
                && repair.contains("not evidence that no populated store exists")
                && !repair.contains("discovery completed and found no populated stores"),
            format!("truncated recovery must not claim complete/no-nearby truth: {repair}"),
        )?;
        ensure(
            repair.contains("ee init --workspace '") && !repair.contains("--workspace ."),
            format!("conditional init must quote the exact addressed workspace: {repair}"),
        )?;
        ensure(
            !workspace.join(".ee").exists() && !database.exists() && !absent_registry.exists(),
            "truncated read-only assessment must not create a store or registry",
        )
    }

    #[test]
    fn storeless_assessment_reports_global_registry_failure_without_creating_state() -> TestResult {
        let temp = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = temp.path().join("unavailable workspace");
        std::fs::create_dir_all(workspace.join(".git")).map_err(|error| error.to_string())?;
        let database = workspace.join(".ee").join("ee.db");
        let invalid_registry = temp.path().join("invalid-registry.db");
        let registry_bytes = b"not a sqlite registry";
        std::fs::write(&invalid_registry, registry_bytes).map_err(|error| error.to_string())?;

        let assessment = StorelessWorkspaceAssessment::inspect_with_discovery(
            &database,
            Duration::from_secs(5),
            Some(&invalid_registry),
        );
        let details: serde_json::Value =
            serde_json::from_str(&assessment.details_json()).map_err(|error| error.to_string())?;
        let repair = assessment.repair();

        ensure_equal(
            &details.pointer("/storeDiscovery/outcome"),
            &Some(&serde_json::json!("unavailable")),
            "global registry-unavailable store-discovery outcome",
        )?;
        ensure(
            repair.contains("discovery was unavailable")
                && repair.contains("no complete nearby-store conclusion is available")
                && !repair.contains("locally proved results remain actionable")
                && !repair.contains("discovery completed and found no populated stores"),
            format!("globally unavailable recovery must suppress unproved retargets: {repair}"),
        )?;
        ensure(
            assessment.candidate_retargets.is_empty(),
            "globally unavailable discovery must not create retarget authority",
        )?;
        ensure(
            !workspace.join(".ee").exists()
                && !database.exists()
                && std::fs::read(&invalid_registry)
                    .map_err(|error| error.to_string())?
                    .as_slice()
                    == registry_bytes,
            "unavailable read-only assessment must not create a store or mutate its registry",
        )
    }

    #[test]
    fn registry_failure_keeps_locally_proved_retarget_recovery_actions() -> TestResult {
        let discovery = crate::core::orient::NearbyStoreScanAssessment {
            stores: vec![crate::core::orient::NearbyStore {
                workspace_root: "/tmp/locally proved workspace".to_owned(),
                store_dir: "/tmp/locally proved workspace/.ee".to_owned(),
                documents: 99,
                last_write: Some("2026-08-10T14:15:16Z".to_owned()),
                provenance: crate::core::orient::NearbyStoreProvenance::ChildScan,
            }],
            outcome: crate::core::orient::NearbyStoreScanOutcome::TruncatedRegistryUnavailable,
        };

        let retargets = storeless_workspace_candidate_retargets(&discovery);
        ensure(
            retargets.len() == 1
                && retargets[0].store.provenance
                    == crate::core::orient::NearbyStoreProvenance::ChildScan
                && retargets[0]
                    .arguments
                    .contains("--workspace '/tmp/locally proved workspace'"),
            "a registry failure must keep the locally proved retarget actionable".to_owned(),
        )?;

        let unavailable = crate::core::orient::NearbyStoreScanAssessment {
            outcome: crate::core::orient::NearbyStoreScanOutcome::Unavailable,
            ..discovery
        };
        ensure(
            storeless_workspace_candidate_retargets(&unavailable).is_empty(),
            "a globally unavailable scan must not create retarget authority".to_owned(),
        )
    }
}