rch-common 2.1.20

Shared types and utilities for Remote Compilation Helper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
//! Canonical placement / visibility / strict-remote controls
//! (bd-session-history-remediation-ocv9i.13.5).
//!
//! The complete session-history analysis kept turning up agents reaching for
//! folklore knobs — `RCH_WORKER`, `RCH_VISIBILITY`, `RCH_QUEUE_WHEN_BUSY`,
//! `RCH_FORCE_REMOTE`, `RCH_REQUIRE_REMOTE`, daemon wait timeouts, and
//! worker-scoped target dirs — to compensate for opaque selection and proof
//! semantics. Those controls were read in a dozen different places, some were
//! *silently ignored* (`RCH_FORCE_REMOTE` had no effect in the hook path), and
//! none of them were surfaced back to the agent so it could tell what RCH
//! actually did.
//!
//! This module is the single source of truth that makes them first-class:
//!
//! * [`placement_controls`] — the canonical registry (name, aliases, value
//!   semantics) consumed by `rch capabilities` so the knobs are discoverable.
//! * [`resolve_placement`] — a *pure* env → [`PlacementPlan`] resolver. It is
//!   deterministic (takes a getter closure rather than touching the process
//!   environment) and it never silently drops a control: an unrecognized value
//!   or a superseded alias becomes a [`ControlDiagnostic`] rather than a quiet
//!   no-op.
//! * [`StrictRemotePolicy`] — the canonical force-vs-require distinction, the
//!   single fix for the most-confused pair of knobs. `RCH_FORCE_REMOTE` means
//!   *always attempt offload but still fail open*; `RCH_REQUIRE_REMOTE` means
//!   *fail closed — refuse local fallback* (proof mode).
//! * [`evaluate_requested_worker`] — a pure admissibility evaluator. A
//!   requested worker that is unavailable, admin-disabled, bypassed,
//!   wrong-platform, missing a runtime, project-excluded, or full yields a
//!   structured refusal keyed to the stable [`IncidentReasonCode`] taxonomy
//!   plus a concrete next action — never a silent swap to a different worker.
//!
//! Everything here is clock-free and I/O-free so it is cheap on the hook hot
//! path and exhaustively unit-testable.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::incident::{ControlState, IncidentReasonCode};
use crate::schema_versions::{SchemaComponent, current_version};
use crate::types::{WorkerSelectionDiagnostic, WorkerSelectionDiagnosticDecision};

// ---------------------------------------------------------------------------
// Canonical control vocabulary
// ---------------------------------------------------------------------------

/// Strict-remote / proof policy, resolved from the env precedence
/// `RCH_REQUIRE_REMOTE` > `RCH_FORCE_REMOTE`.
///
/// These two knobs were the most conflated pair in the session evidence, so the
/// distinction is encoded in the type rather than left to prose:
///
/// * [`Off`](Self::Off) — heuristics decide; local fallback is allowed.
/// * [`ForceRemote`](Self::ForceRemote) — always *attempt* offload (bypass the
///   `min_local_time` / speedup gating) but still **fail open** to local if no
///   worker can take it.
/// * [`RequireRemote`](Self::RequireRemote) — **fail closed**: refuse local
///   fallback entirely (proof mode). Implies the force-remote intent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum StrictRemotePolicy {
    /// Heuristics decide; local fallback allowed.
    #[default]
    Off,
    /// Always attempt offload, but fail open to local.
    ForceRemote,
    /// Fail closed: never fall back to local (proof mode).
    RequireRemote,
}

impl StrictRemotePolicy {
    /// Stable lowercase token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            StrictRemotePolicy::Off => "off",
            StrictRemotePolicy::ForceRemote => "force_remote",
            StrictRemotePolicy::RequireRemote => "require_remote",
        }
    }

    /// True when local fallback is refused (proof mode).
    #[must_use]
    pub fn fail_closed(self) -> bool {
        matches!(self, StrictRemotePolicy::RequireRemote)
    }

    /// True when offload should always be attempted (force or require),
    /// bypassing the local-runtime / speedup heuristics.
    #[must_use]
    pub fn forces_offload(self) -> bool {
        matches!(
            self,
            StrictRemotePolicy::ForceRemote | StrictRemotePolicy::RequireRemote
        )
    }
}

/// Queue-when-busy policy. Defaults to enabled (the daemon may hold a request
/// for a worker rather than immediately falling back to local).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueuePolicy {
    /// Wait for a worker to free up (default).
    #[default]
    QueueWhenBusy,
    /// Never queue; fall back to local immediately when workers are busy.
    NoQueue,
}

impl QueuePolicy {
    /// Stable lowercase token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            QueuePolicy::QueueWhenBusy => "queue_when_busy",
            QueuePolicy::NoQueue => "no_queue",
        }
    }

    /// True when the request should wait for a worker.
    #[must_use]
    pub fn waits(self) -> bool {
        matches!(self, QueuePolicy::QueueWhenBusy)
    }
}

/// Hook output visibility. `default` means "no explicit override; use config".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum VisibilityMode {
    /// No explicit env override — defer to config.
    #[default]
    Default,
    /// Suppress hook output.
    None,
    /// One-line summary.
    Summary,
    /// Verbose per-step output.
    Verbose,
}

impl VisibilityMode {
    /// Stable lowercase token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            VisibilityMode::Default => "default",
            VisibilityMode::None => "none",
            VisibilityMode::Summary => "summary",
            VisibilityMode::Verbose => "verbose",
        }
    }

    /// Parse a canonical `RCH_VISIBILITY` value (`none` / `summary` /
    /// `verbose`). Returns `None` for unrecognized values so the caller can
    /// raise a diagnostic instead of silently ignoring it.
    fn parse(value: &str) -> Option<VisibilityMode> {
        match value.trim().to_ascii_lowercase().as_str() {
            "none" | "quiet" => Some(VisibilityMode::None),
            "summary" => Some(VisibilityMode::Summary),
            "verbose" => Some(VisibilityMode::Verbose),
            _ => None,
        }
    }
}

/// Worker-scoped target-dir policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TargetDirPolicy {
    /// Pooled, reuse-friendly remote target dir (default).
    #[default]
    Pooled,
    /// Legacy unique-per-job remote target dir (`RCH_DISABLE_TARGET_REUSE`).
    PerJob,
    /// Caller pinned a worker-scoped `CARGO_TARGET_DIR`.
    WorkerScoped,
}

impl TargetDirPolicy {
    /// Stable lowercase token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            TargetDirPolicy::Pooled => "pooled",
            TargetDirPolicy::PerJob => "per_job",
            TargetDirPolicy::WorkerScoped => "worker_scoped",
        }
    }
}

// ---------------------------------------------------------------------------
// Control registry (capabilities discovery)
// ---------------------------------------------------------------------------

/// The category a control belongs to, for grouping in discovery surfaces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ControlKind {
    /// Worker placement / selection.
    Placement,
    /// Strict-remote / proof policy.
    StrictRemote,
    /// Queue-when-busy policy.
    Queue,
    /// Daemon wait timeout.
    WaitTimeout,
    /// Output visibility.
    Visibility,
    /// Worker-scoped target dir.
    TargetDir,
    /// Requested execution profile.
    Profile,
    /// Self-healing master switch.
    SelfHealing,
}

/// A single canonical control: its primary env var, accepted aliases, the
/// equivalent CLI flag (if any), and human/agent-facing value semantics. This
/// is the registry `rch capabilities` renders so agents stop discovering knobs
/// by folklore.
#[derive(Debug, Clone, Copy)]
pub struct PlacementControl {
    /// Canonical environment variable name.
    pub canonical_env: &'static str,
    /// Accepted aliases (documented, mapped to the canonical control).
    pub aliases: &'static [&'static str],
    /// Equivalent CLI flag, when one exists.
    pub flag: Option<&'static str>,
    /// Which family the control belongs to.
    pub kind: ControlKind,
    /// Accepted value form (e.g. `worker id`, `0|1`, `secs`).
    pub value_form: &'static str,
    /// One-line description of the effect.
    pub description: &'static str,
}

/// The canonical placement/visibility/strict/queue/wait control registry.
///
/// Adding a knob here is the *only* place it needs to be declared for discovery
/// — `rch capabilities` derives its env-var list from this slice.
#[must_use]
pub fn placement_controls() -> &'static [PlacementControl] {
    const CONTROLS: &[PlacementControl] = &[
        PlacementControl {
            canonical_env: "RCH_WORKER",
            aliases: &["RCH_WORKERS"],
            flag: None,
            kind: ControlKind::Placement,
            value_form: "worker-id[,worker-id...]",
            description: "Request specific worker(s) by id. Still passes capability/admission \
                          checks; an inadmissible requested worker is refused with a reason code.",
        },
        PlacementControl {
            canonical_env: "RCH_PRESET",
            aliases: &[],
            flag: None,
            kind: ControlKind::Profile,
            value_form: "profile-name",
            description: "Request a named execution profile (recorded as requested_profile).",
        },
        PlacementControl {
            canonical_env: "RCH_REQUIRE_REMOTE",
            aliases: &[],
            flag: None,
            kind: ControlKind::StrictRemote,
            value_form: "0|1",
            description: "Fail closed: refuse local fallback (proof mode). Takes precedence over \
                          RCH_FORCE_REMOTE.",
        },
        PlacementControl {
            canonical_env: "RCH_FORCE_REMOTE",
            aliases: &[],
            flag: None,
            kind: ControlKind::StrictRemote,
            value_form: "0|1",
            description: "Always attempt offload (bypass local-time/speedup gating) but still \
                          fail open to local. Distinct from RCH_REQUIRE_REMOTE.",
        },
        PlacementControl {
            canonical_env: "RCH_QUEUE_WHEN_BUSY",
            aliases: &[],
            flag: None,
            kind: ControlKind::Queue,
            value_form: "0|1 (default 1)",
            description: "Wait for a busy worker instead of immediately falling back to local. \
                          Set 0 to disable queueing.",
        },
        PlacementControl {
            canonical_env: "RCH_DAEMON_WAIT_RESPONSE_TIMEOUT_SECS",
            aliases: &["RCH_DAEMON_RESPONSE_TIMEOUT_SECS"],
            flag: None,
            kind: ControlKind::WaitTimeout,
            value_form: "secs (>0)",
            description: "Maximum time to wait for a queued worker before falling back.",
        },
        PlacementControl {
            canonical_env: "RCH_VISIBILITY",
            aliases: &["RCH_QUIET", "RCH_VERBOSE"],
            flag: None,
            kind: ControlKind::Visibility,
            value_form: "none|summary|verbose",
            description: "Hook output verbosity. RCH_QUIET=>none, RCH_VERBOSE=>verbose.",
        },
        PlacementControl {
            canonical_env: "RCH_DISABLE_TARGET_REUSE",
            aliases: &[],
            flag: None,
            kind: ControlKind::TargetDir,
            value_form: "0|1",
            description: "Use a legacy unique-per-job remote target dir instead of the pooled, \
                          reuse-friendly dir.",
        },
        PlacementControl {
            canonical_env: "RCH_NO_SELF_HEALING",
            aliases: &[],
            flag: Some("--no-self-healing"),
            kind: ControlKind::SelfHealing,
            value_form: "0|1",
            description: "Master switch disabling hook->daemon autostart and daemon hook install.",
        },
    ];
    CONTROLS
}

// ---------------------------------------------------------------------------
// Diagnostics
// ---------------------------------------------------------------------------

/// Severity of a control diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ControlDiagnosticLevel {
    /// Informational (e.g. an alias was canonicalized).
    Info,
    /// The value could not be applied as written and a fallback was used.
    Warning,
}

/// A single diagnostic explaining how a control was interpreted. The whole
/// point: a knob that cannot be applied as written is *reported*, never
/// silently dropped.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ControlDiagnostic {
    /// Canonical control this diagnostic concerns.
    pub control: String,
    /// Severity.
    pub level: ControlDiagnosticLevel,
    /// What happened / what to do.
    pub message: String,
}

impl ControlDiagnostic {
    fn info(control: &str, message: impl Into<String>) -> Self {
        Self {
            control: control.to_string(),
            level: ControlDiagnosticLevel::Info,
            message: message.into(),
        }
    }

    fn warning(control: &str, message: impl Into<String>) -> Self {
        Self {
            control: control.to_string(),
            level: ControlDiagnosticLevel::Warning,
            message: message.into(),
        }
    }
}

// ---------------------------------------------------------------------------
// Requested-worker admissibility
// ---------------------------------------------------------------------------

/// Outcome class for an explicitly requested worker. Every non-`Honored`
/// variant is a *structured refusal*: the requested worker is not silently
/// swapped for another.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RequestedWorkerStatus {
    /// No worker was explicitly requested.
    NotRequested,
    /// A worker was requested but has not yet been evaluated against the fleet.
    Requested,
    /// The requested worker is admissible and was honored.
    Honored,
    /// The requested worker is unknown/unreachable/drained.
    Unavailable,
    /// The requested worker was disabled by an operator.
    AdminDisabled,
    /// The requested worker is in transient quarantine (temporary bypass).
    TemporarilyBypassed,
    /// The requested worker's OS/arch does not match the build target.
    WrongPlatform,
    /// The requested worker lacks the required runtime/toolchain/target.
    MissingRuntime,
    /// The requested worker is excluded because it already runs this project.
    ProjectExcluded,
    /// The requested worker has no free slots for this request.
    NoFreeSlots,
}

impl RequestedWorkerStatus {
    /// Stable lowercase token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            RequestedWorkerStatus::NotRequested => "not_requested",
            RequestedWorkerStatus::Requested => "requested",
            RequestedWorkerStatus::Honored => "honored",
            RequestedWorkerStatus::Unavailable => "unavailable",
            RequestedWorkerStatus::AdminDisabled => "admin_disabled",
            RequestedWorkerStatus::TemporarilyBypassed => "temporarily_bypassed",
            RequestedWorkerStatus::WrongPlatform => "wrong_platform",
            RequestedWorkerStatus::MissingRuntime => "missing_runtime",
            RequestedWorkerStatus::ProjectExcluded => "project_excluded",
            RequestedWorkerStatus::NoFreeSlots => "no_free_slots",
        }
    }

    /// True when the request was refused (a worker was named but cannot be used
    /// as asked).
    #[must_use]
    pub fn is_refusal(self) -> bool {
        !matches!(
            self,
            RequestedWorkerStatus::NotRequested
                | RequestedWorkerStatus::Requested
                | RequestedWorkerStatus::Honored
        )
    }
}

/// The facts an evaluator needs about an explicitly requested worker. The hook
/// fills these from the daemon's per-worker selection diagnostics; tests fill
/// them directly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestedWorkerFacts {
    /// The requested worker id (empty/none means "no request").
    pub requested: Option<String>,
    /// Whether the worker is a known, configured worker.
    pub exists: bool,
    /// Operator explicitly disabled this worker.
    pub admin_disabled: bool,
    /// Worker is draining or drained (out of service by operator intent).
    pub draining_or_drained: bool,
    /// Worker is reachable / responding.
    pub reachable: bool,
    /// Worker is in transient quarantine (temporary bypass).
    pub temporarily_bypassed: bool,
    /// Worker OS/arch matches the build target.
    pub platform_matches: bool,
    /// Worker has the required runtime/toolchain/target.
    pub has_required_runtime: bool,
    /// Worker already runs this project (active-project exclusion).
    pub project_excluded: bool,
    /// Worker has enough configured total capacity for the request eventually.
    pub has_total_capacity: bool,
    /// Worker has enough free slots for the request.
    pub has_free_slots: bool,
    /// Estimated core count for the request (the `-j` lever the reader can lower).
    /// Retained so a capacity refusal can name the concrete numbers that collided
    /// and the exact `-j` value that would fit (rch#35).
    pub estimated_cores: u32,
    /// The worker's total configured slots (its hard capacity ceiling).
    pub total_slots: u32,
    /// Stable incident class for a remaining selector denial, if any.
    pub admission_denial_code: Option<IncidentReasonCode>,
    /// Human-readable selector reason for a remaining admission denial.
    pub admission_denial_reason: Option<String>,
}

impl RequestedWorkerFacts {
    /// Facts for "no worker requested".
    #[must_use]
    pub fn none() -> Self {
        Self {
            requested: None,
            exists: false,
            admin_disabled: false,
            draining_or_drained: false,
            reachable: true,
            temporarily_bypassed: false,
            platform_matches: true,
            has_required_runtime: true,
            project_excluded: false,
            has_total_capacity: true,
            has_free_slots: true,
            estimated_cores: 0,
            total_slots: 0,
            admission_denial_code: None,
            admission_denial_reason: None,
        }
    }

    /// Facts for a fully admissible requested worker (test/clarity helper).
    #[must_use]
    pub fn admissible(id: impl Into<String>) -> Self {
        Self {
            requested: Some(id.into()),
            exists: true,
            ..Self::none()
        }
    }

    /// Build canonical requested-worker facts from daemon selection diagnostics.
    #[must_use]
    pub fn from_diagnostic(
        requested: impl Into<String>,
        worker: &WorkerSelectionDiagnostic,
    ) -> Self {
        let toolchain_inadmissible = worker
            .reason_codes
            .iter()
            .any(|code| code.starts_with("toolchain."));
        let admission_denial_code =
            (worker.final_decision == WorkerSelectionDiagnosticDecision::Deny).then(|| {
                if worker
                    .reason_codes
                    .iter()
                    .any(|code| code == "pressure.critical")
                {
                    IncidentReasonCode::CriticalPressure
                } else if worker.reason_codes.iter().any(|code| {
                    code.starts_with("topology.")
                        || code.starts_with("preflight.")
                        || code.starts_with("convergence.")
                        || code.starts_with("reliability.")
                }) {
                    IncidentReasonCode::HardPreflight
                } else {
                    IncidentReasonCode::NoAdmissibleWorkers
                }
            });
        Self {
            requested: Some(requested.into()),
            exists: true,
            admin_disabled: worker.status.eq_ignore_ascii_case("disabled"),
            draining_or_drained: worker.status.to_ascii_lowercase().contains("drain"),
            reachable: !worker.status.eq_ignore_ascii_case("unreachable"),
            temporarily_bypassed: worker.circuit_state.eq_ignore_ascii_case("open")
                || worker.status.to_ascii_lowercase().contains("bypass"),
            platform_matches: !worker
                .reason_codes
                .iter()
                .any(|code| code.contains("os_arch") || code.contains("platform")),
            has_required_runtime: worker.runtime_available && !toolchain_inadmissible,
            project_excluded: worker.active_project_excluded,
            has_total_capacity: worker.total_slots >= worker.estimated_cores,
            has_free_slots: worker.available_slots >= worker.estimated_cores,
            estimated_cores: worker.estimated_cores,
            total_slots: worker.total_slots,
            admission_denial_code,
            admission_denial_reason: admission_denial_code.map(|_| worker.final_reason.clone()),
        }
    }
}

/// The structured result of evaluating a requested worker.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RequestedWorkerOutcome {
    /// Outcome class.
    pub status: RequestedWorkerStatus,
    /// Stable incident reason code (`RCH-Innn`) for a refusal, when applicable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
    /// Concrete next action for the agent on a refusal.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_action: Option<String>,
}

impl RequestedWorkerOutcome {
    /// Outcome for "no worker requested".
    #[must_use]
    pub fn not_requested() -> Self {
        Self {
            status: RequestedWorkerStatus::NotRequested,
            reason_code: None,
            next_action: None,
        }
    }

    /// Outcome for "requested, pending fleet evaluation".
    #[must_use]
    pub fn requested() -> Self {
        Self {
            status: RequestedWorkerStatus::Requested,
            reason_code: None,
            next_action: None,
        }
    }

    fn honored() -> Self {
        Self {
            status: RequestedWorkerStatus::Honored,
            reason_code: None,
            next_action: None,
        }
    }

    fn refused(
        status: RequestedWorkerStatus,
        code: IncidentReasonCode,
        next_action: impl Into<String>,
    ) -> Self {
        Self {
            status,
            reason_code: Some(code.code().to_string()),
            next_action: Some(next_action.into()),
        }
    }
}

/// Evaluate an explicitly requested worker against the fleet facts.
///
/// The order is most-specific-first so the *primary* reason a worker cannot be
/// used is the one reported. Each refusal maps to a stable
/// [`IncidentReasonCode`] and carries a concrete next action — the request is
/// never silently rerouted to a different worker.
#[must_use]
pub fn evaluate_requested_worker(facts: &RequestedWorkerFacts) -> RequestedWorkerOutcome {
    let Some(id) = facts.requested.as_deref().filter(|s| !s.trim().is_empty()) else {
        return RequestedWorkerOutcome::not_requested();
    };

    if !facts.exists {
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::Unavailable,
            IncidentReasonCode::NoAdmissibleWorkers,
            format!("'{id}' is not a configured worker; run `rch workers list` to see valid ids"),
        );
    }
    if facts.admin_disabled {
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::AdminDisabled,
            IncidentReasonCode::NoAdmissibleWorkers,
            format!(
                "'{id}' is operator-disabled; re-enable with `rch workers enable {id}` or request another worker"
            ),
        );
    }
    if facts.draining_or_drained || !facts.reachable {
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::Unavailable,
            IncidentReasonCode::NoAdmissibleWorkers,
            format!(
                "'{id}' is draining/unreachable; wait for it to return or request another worker"
            ),
        );
    }
    if facts.temporarily_bypassed {
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::TemporarilyBypassed,
            IncidentReasonCode::CircuitOpen,
            format!(
                "'{id}' is in transient quarantine; wait for auto-rejoin or request another worker"
            ),
        );
    }
    if !facts.platform_matches {
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::WrongPlatform,
            IncidentReasonCode::OsArchMismatch,
            format!("'{id}' OS/arch does not match the build target; request a matching worker"),
        );
    }
    if !facts.has_required_runtime {
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::MissingRuntime,
            IncidentReasonCode::MissingRuntimeToolchainTarget,
            format!(
                "'{id}' lacks the required runtime/toolchain/target; install it or request another worker"
            ),
        );
    }
    if facts.project_excluded {
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::ProjectExcluded,
            IncidentReasonCode::ActiveProjectExclusion,
            format!(
                "'{id}' already runs this project (active-project exclusion); request another worker"
            ),
        );
    }
    if !facts.has_total_capacity {
        // Name the two counts that collided and the exact `-j` value that fits, so
        // the reader is not left guessing that `-j` is the lever — the common
        // trigger is an unbounded `cargo build`/`run` that inherited the configured
        // `build_slots` default against a deliberately small pinned worker (rch#35).
        let next_action = if facts.total_slots > 0 && facts.estimated_cores > 0 {
            format!(
                "'{id}' has {total} total slot(s) but the request is estimated at {cores} core(s); \
                 pass -j {total} (or fewer), or request a larger worker",
                total = facts.total_slots,
                cores = facts.estimated_cores,
            )
        } else {
            format!(
                "'{id}' cannot fit the requested core count; lower the request (-j) or request a larger worker"
            )
        };
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::NoFreeSlots,
            IncidentReasonCode::InsufficientSlots,
            next_action,
        );
    }
    if !facts.has_free_slots {
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::NoFreeSlots,
            IncidentReasonCode::InsufficientSlots,
            format!(
                "'{id}' has no free slots right now; queue with RCH_QUEUE_WHEN_BUSY=1 or request another worker"
            ),
        );
    }
    if let Some(code) = facts.admission_denial_code {
        let reason = facts
            .admission_denial_reason
            .as_deref()
            .unwrap_or("worker admission denied");
        let next_action = match code {
            IncidentReasonCode::CriticalPressure => format!(
                "'{id}' failed admission under critical pressure ({reason}); remediate worker pressure or request another worker"
            ),
            IncidentReasonCode::HardPreflight => format!(
                "'{id}' failed a hard preflight ({reason}); run `rch diagnose -- <command>`, remediate the preflight, or request another worker"
            ),
            _ => format!(
                "'{id}' failed worker admission ({reason}); run `rch diagnose -- <command>` or request another worker"
            ),
        };
        return RequestedWorkerOutcome::refused(
            RequestedWorkerStatus::Unavailable,
            code,
            next_action,
        );
    }
    RequestedWorkerOutcome::honored()
}

// ---------------------------------------------------------------------------
// The resolved plan
// ---------------------------------------------------------------------------

/// The canonical, agent-facing resolution of all placement controls for a
/// single request. Field names are exactly the explicit-control surface the
/// session-history report asked to be made first-class.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct PlacementPlan {
    /// Schema version (`SchemaComponent::PlacementPlan`).
    pub schema_version: String,
    /// Worker(s) the caller explicitly requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_worker: Option<String>,
    /// Requested execution profile.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_profile: Option<String>,
    /// The worker actually selected (filled once selection runs).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effective_worker: Option<String>,
    /// Strict-remote / proof policy.
    pub strict_remote_policy: StrictRemotePolicy,
    /// Queue-when-busy policy.
    pub queue_policy: QueuePolicy,
    /// Output visibility mode.
    pub visibility_mode: VisibilityMode,
    /// Resolved wait timeout in milliseconds, when explicitly set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wait_timeout_ms: Option<u64>,
    /// Worker-scoped target-dir policy.
    pub target_dir_policy: TargetDirPolicy,
    /// Requested-worker admissibility outcome.
    pub requested_worker_outcome: RequestedWorkerOutcome,
    /// How each control was interpreted (superseded aliases, bad values, ...).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub diagnostics: Vec<ControlDiagnostic>,
}

impl PlacementPlan {
    /// The current placement-plan schema version.
    #[must_use]
    pub fn schema_version() -> &'static str {
        current_version(SchemaComponent::PlacementPlan)
    }

    /// Record the worker selection finally honored.
    #[must_use]
    pub fn with_effective_worker(mut self, worker: Option<String>) -> Self {
        self.effective_worker = worker;
        self
    }

    /// Replace the requested-worker outcome (after fleet evaluation).
    #[must_use]
    pub fn with_requested_worker_outcome(mut self, outcome: RequestedWorkerOutcome) -> Self {
        self.requested_worker_outcome = outcome;
        self
    }

    /// Bridge to the sparse [`ControlState`] embedded in incident events: only
    /// explicitly-set / non-default fields are carried, matching the
    /// incident-ledger convention of recording *why* a build was steered.
    #[must_use]
    pub fn control_state(&self) -> ControlState {
        ControlState {
            requested_worker: self.requested_worker.clone(),
            requested_profile: self.requested_profile.clone(),
            strict_remote_policy: self.strict_remote_policy != StrictRemotePolicy::Off,
            queue_policy: (self.queue_policy != QueuePolicy::default())
                .then(|| self.queue_policy.as_str().to_string()),
            visibility_mode: (self.visibility_mode != VisibilityMode::Default)
                .then(|| self.visibility_mode.as_str().to_string()),
            wait_timeout_ms: self.wait_timeout_ms,
            target_dir_policy: (self.target_dir_policy != TargetDirPolicy::default())
                .then(|| self.target_dir_policy.as_str().to_string()),
        }
    }
}

/// Repo-standard env truthiness (`1`/`true`/`yes`/`on`/`enabled`).
///
/// Public because it IS the repo standard: every surface that reads a boolean
/// environment variable must agree on what `RCH_FOO=0` means, and the way that
/// agreement breaks is two modules each spelling it out for themselves
/// (bd-e92eh was exactly that shape for `RCH_JSON`).
#[must_use]
pub fn env_truthy(value: &str) -> bool {
    matches!(
        value.trim().to_ascii_lowercase().as_str(),
        "1" | "true" | "yes" | "on" | "enabled"
    )
}

/// Repo-standard env falsiness for default-enabled flags
/// (`0`/`false`/`no`/`off`/`disabled`).
fn env_falsy(value: &str) -> bool {
    matches!(
        value.trim().to_ascii_lowercase().as_str(),
        "0" | "false" | "no" | "off" | "disabled"
    )
}

/// Resolve every placement control from the environment into a single
/// [`PlacementPlan`].
///
/// `get` is the environment accessor — `|k| std::env::var(k).ok()` in the hook,
/// a map lookup in tests. The function is otherwise pure: no clock, no I/O, no
/// global state. It never silently drops a control; anything it cannot apply as
/// written becomes a [`ControlDiagnostic`].
///
/// The returned plan has no `effective_worker` (selection has not run yet) and a
/// `requested_worker_outcome` of `NotRequested`/`Requested`; callers refine both
/// once the daemon answers.
pub fn resolve_placement<F>(get: F) -> PlacementPlan
where
    F: Fn(&str) -> Option<String>,
{
    let mut diagnostics = Vec::new();

    // --- requested worker(s): RCH_WORKER (canonical) + RCH_WORKERS (alias) ---
    let worker_primary = get("RCH_WORKER").filter(|v| !v.trim().is_empty());
    let worker_alias = get("RCH_WORKERS").filter(|v| !v.trim().is_empty());
    let requested_worker = match (&worker_primary, &worker_alias) {
        (Some(p), Some(a)) => {
            diagnostics.push(ControlDiagnostic::info(
                "RCH_WORKER",
                "RCH_WORKER and its alias RCH_WORKERS are both set; merging both into the requested set",
            ));
            Some(merge_worker_lists(p, a))
        }
        (Some(p), None) => Some(p.trim().to_string()),
        (None, Some(a)) => {
            diagnostics.push(ControlDiagnostic::info(
                "RCH_WORKERS",
                "RCH_WORKERS is an alias for the canonical RCH_WORKER",
            ));
            Some(a.trim().to_string())
        }
        (None, None) => None,
    };

    // --- requested profile: RCH_PRESET ---
    let requested_profile = get("RCH_PRESET").filter(|v| !v.trim().is_empty());

    // --- strict remote: RCH_REQUIRE_REMOTE > RCH_FORCE_REMOTE ---
    let require_remote = get("RCH_REQUIRE_REMOTE").is_some_and(|v| env_truthy(&v));
    let force_remote = get("RCH_FORCE_REMOTE").is_some_and(|v| env_truthy(&v));
    let strict_remote_policy = if require_remote {
        if force_remote {
            diagnostics.push(ControlDiagnostic::info(
                "RCH_REQUIRE_REMOTE",
                "RCH_REQUIRE_REMOTE (fail-closed) supersedes RCH_FORCE_REMOTE (fail-open)",
            ));
        }
        StrictRemotePolicy::RequireRemote
    } else if force_remote {
        StrictRemotePolicy::ForceRemote
    } else {
        StrictRemotePolicy::Off
    };

    // --- queue-when-busy: default enabled ---
    let queue_policy = match get("RCH_QUEUE_WHEN_BUSY") {
        None => QueuePolicy::QueueWhenBusy,
        Some(v) if env_falsy(&v) => QueuePolicy::NoQueue,
        Some(v) if env_truthy(&v) || v.trim().is_empty() => QueuePolicy::QueueWhenBusy,
        Some(v) => {
            diagnostics.push(ControlDiagnostic::warning(
                "RCH_QUEUE_WHEN_BUSY",
                format!("unrecognized value {v:?}; interpreted as enabled (queue_when_busy)"),
            ));
            QueuePolicy::QueueWhenBusy
        }
    };

    // --- wait timeout: RCH_DAEMON_WAIT_RESPONSE_TIMEOUT_SECS (alias _RESPONSE_) ---
    let (wait_timeout_ms, wait_diag) = resolve_wait_timeout(&get);
    diagnostics.extend(wait_diag);

    // --- visibility: RCH_VISIBILITY (canonical), RCH_QUIET / RCH_VERBOSE aliases ---
    let (visibility_mode, vis_diag) = resolve_visibility(&get);
    diagnostics.extend(vis_diag);

    // --- target dir policy ---
    let target_dir_policy = if get("RCH_DISABLE_TARGET_REUSE").is_some_and(|v| env_truthy(&v)) {
        TargetDirPolicy::PerJob
    } else if get("CARGO_TARGET_DIR")
        .map(|v| v.contains(".rch-target") || v.contains("rch-worker"))
        .unwrap_or(false)
    {
        TargetDirPolicy::WorkerScoped
    } else {
        TargetDirPolicy::Pooled
    };

    let requested_worker_outcome = if requested_worker.is_some() {
        RequestedWorkerOutcome::requested()
    } else {
        RequestedWorkerOutcome::not_requested()
    };

    PlacementPlan {
        schema_version: PlacementPlan::schema_version().to_string(),
        requested_worker,
        requested_profile: requested_profile.map(|v| v.trim().to_string()),
        effective_worker: None,
        strict_remote_policy,
        queue_policy,
        visibility_mode,
        wait_timeout_ms,
        target_dir_policy,
        requested_worker_outcome,
        diagnostics,
    }
}

/// Resolve placement with the box-level role applied BENEATH the
/// per-call environment (bd-wywsj): role sets the DEFAULT posture,
/// explicit env always wins.
///
/// * `Dispatcher`: when NEITHER `RCH_REQUIRE_REMOTE` nor
///   `RCH_FORCE_REMOTE` is present (presence — even with a falsy
///   value — is an explicit per-call decision), the strict-remote
///   policy defaults to fail-closed [`StrictRemotePolicy::RequireRemote`]
///   so a saturated fleet QUEUES instead of repopulating local rustc
///   on the orchestrator. A diagnostic records the role default.
/// * `Worker` / `Hybrid`: identical to [`resolve_placement`] — the
///   box is (or may be) the compute; fail-open stays the default.
pub fn resolve_placement_with_role<F>(get: F, role: crate::BoxRole) -> PlacementPlan
where
    F: Fn(&str) -> Option<String>,
{
    let strict_env_present =
        get("RCH_REQUIRE_REMOTE").is_some() || get("RCH_FORCE_REMOTE").is_some();
    let mut plan = resolve_placement(get);
    if role == crate::BoxRole::Dispatcher
        && !strict_env_present
        && plan.strict_remote_policy == StrictRemotePolicy::Off
    {
        plan.strict_remote_policy = StrictRemotePolicy::RequireRemote;
        plan.diagnostics.push(ControlDiagnostic::info(
            "general.role",
            "role=dispatcher defaults offloadable builds to fail-closed + queue \
             (set RCH_REQUIRE_REMOTE=0 or RCH_FORCE_REMOTE=1 per call to override)",
        ));
    }
    plan
}

/// Merge two comma-separated worker lists, trimming and de-duplicating while
/// preserving first-seen order.
fn merge_worker_lists(primary: &str, alias: &str) -> String {
    let mut seen = Vec::new();
    for part in primary
        .split(',')
        .chain(alias.split(','))
        .map(str::trim)
        .filter(|p| !p.is_empty())
    {
        if !seen.contains(&part) {
            seen.push(part);
        }
    }
    seen.join(",")
}

/// Resolve the wait timeout from the canonical var or its alias.
fn resolve_wait_timeout<F>(get: &F) -> (Option<u64>, Vec<ControlDiagnostic>)
where
    F: Fn(&str) -> Option<String>,
{
    const CANONICAL: &str = "RCH_DAEMON_WAIT_RESPONSE_TIMEOUT_SECS";
    const ALIAS: &str = "RCH_DAEMON_RESPONSE_TIMEOUT_SECS";
    let mut diags = Vec::new();

    let (name, raw) = match (get(CANONICAL), get(ALIAS)) {
        (Some(v), _) => (CANONICAL, Some(v)),
        (None, Some(v)) => {
            diags.push(ControlDiagnostic::info(
                ALIAS,
                "RCH_DAEMON_RESPONSE_TIMEOUT_SECS also applies to non-wait queries; \
                 prefer RCH_DAEMON_WAIT_RESPONSE_TIMEOUT_SECS for the queue wait timeout",
            ));
            (ALIAS, Some(v))
        }
        (None, None) => (CANONICAL, None),
    };

    let Some(raw) = raw else {
        return (None, diags);
    };
    match raw.trim().parse::<u64>() {
        Ok(secs) if secs > 0 => (Some(secs.saturating_mul(1000)), diags),
        _ => {
            diags.push(ControlDiagnostic::warning(
                name,
                format!("invalid timeout {raw:?}; expected a positive integer in seconds; using the default"),
            ));
            (None, diags)
        }
    }
}

/// Resolve the visibility mode from the canonical var or its quiet/verbose
/// aliases.
fn resolve_visibility<F>(get: &F) -> (VisibilityMode, Vec<ControlDiagnostic>)
where
    F: Fn(&str) -> Option<String>,
{
    let mut diags = Vec::new();

    if let Some(raw) = get("RCH_VISIBILITY") {
        match VisibilityMode::parse(&raw) {
            Some(mode) => return (mode, diags),
            None => {
                diags.push(ControlDiagnostic::warning(
                    "RCH_VISIBILITY",
                    format!("unrecognized value {raw:?}; expected none|summary|verbose; deferring to config"),
                ));
                // Fall through to the alias checks rather than silently ignoring.
            }
        }
    }
    if get("RCH_QUIET").is_some_and(|v| env_truthy(&v)) {
        return (VisibilityMode::None, diags);
    }
    if get("RCH_VERBOSE").is_some_and(|v| env_truthy(&v)) {
        return (VisibilityMode::Verbose, diags);
    }
    (VisibilityMode::Default, diags)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{RequiredRuntime, WorkerId, WorkerSelectionDiagnosticDecision};
    use std::collections::HashMap;

    /// Build an env getter over a fixed map (no process-env mutation, so tests
    /// stay deterministic and race-free).
    fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let map: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        move |k: &str| map.get(k).cloned()
    }

    fn admissibility_diagnostic() -> WorkerSelectionDiagnostic {
        WorkerSelectionDiagnostic {
            worker_id: WorkerId::new("css"),
            status: "healthy".to_string(),
            circuit_state: "closed".to_string(),
            pressure_state: "healthy".to_string(),
            pressure_reason_code: "pressure.healthy".to_string(),
            success_rate: Some(1.0),
            min_success_rate: 0.8,
            fallback_min_success_rate: 0.5,
            required_runtime: RequiredRuntime::Rust,
            runtime_available: true,
            available_slots: 8,
            total_slots: 8,
            estimated_cores: 2,
            active_project_excluded: false,
            final_decision: WorkerSelectionDiagnosticDecision::Allow,
            final_reason: "eligible".to_string(),
            reason_codes: vec![],
        }
    }

    // --- strict-remote precedence -----------------------------------------

    #[test]
    fn strict_remote_off_by_default() {
        let plan = resolve_placement(env(&[]));
        assert_eq!(plan.strict_remote_policy, StrictRemotePolicy::Off);
        assert!(!plan.strict_remote_policy.fail_closed());
        assert!(!plan.strict_remote_policy.forces_offload());
    }

    #[test]
    fn force_remote_is_fail_open() {
        let plan = resolve_placement(env(&[("RCH_FORCE_REMOTE", "1")]));
        assert_eq!(plan.strict_remote_policy, StrictRemotePolicy::ForceRemote);
        assert!(plan.strict_remote_policy.forces_offload());
        assert!(!plan.strict_remote_policy.fail_closed());
    }

    // --- box role (bd-wywsj) ----------------------------------------------

    #[test]
    fn dispatcher_role_defaults_fail_closed_with_env_override() {
        use crate::BoxRole;
        // Bare dispatcher: fail-closed + queue by default, with the
        // role default named in a diagnostic.
        let plan = resolve_placement_with_role(env(&[]), BoxRole::Dispatcher);
        assert_eq!(
            plan.strict_remote_policy,
            StrictRemotePolicy::RequireRemote,
            "dispatcher must never repopulate local rustc by default"
        );
        assert_eq!(plan.queue_policy, QueuePolicy::QueueWhenBusy);
        assert!(
            plan.diagnostics.iter().any(|d| d.control == "general.role"),
            "the role default must be visible in diagnostics"
        );
        // Env presence — even FALSY — is an explicit per-call override.
        let opted_out =
            resolve_placement_with_role(env(&[("RCH_REQUIRE_REMOTE", "0")]), BoxRole::Dispatcher);
        assert_eq!(opted_out.strict_remote_policy, StrictRemotePolicy::Off);
        // Explicit fail-open force wins over the role default too.
        let forced =
            resolve_placement_with_role(env(&[("RCH_FORCE_REMOTE", "1")]), BoxRole::Dispatcher);
        assert_eq!(forced.strict_remote_policy, StrictRemotePolicy::ForceRemote);
        // And explicit fail-closed is unchanged.
        let required =
            resolve_placement_with_role(env(&[("RCH_REQUIRE_REMOTE", "1")]), BoxRole::Dispatcher);
        assert_eq!(
            required.strict_remote_policy,
            StrictRemotePolicy::RequireRemote
        );
    }

    #[test]
    fn worker_and_hybrid_roles_change_nothing() {
        use crate::BoxRole;
        for role in [BoxRole::Worker, BoxRole::Hybrid] {
            let plan = resolve_placement_with_role(env(&[]), role);
            let baseline = resolve_placement(env(&[]));
            assert_eq!(plan.strict_remote_policy, baseline.strict_remote_policy);
            assert_eq!(plan.queue_policy, baseline.queue_policy);
            assert_eq!(
                plan.diagnostics.len(),
                baseline.diagnostics.len(),
                "{role:?} must add no diagnostics"
            );
        }
    }

    #[test]
    fn require_remote_is_fail_closed() {
        let plan = resolve_placement(env(&[("RCH_REQUIRE_REMOTE", "true")]));
        assert_eq!(plan.strict_remote_policy, StrictRemotePolicy::RequireRemote);
        assert!(plan.strict_remote_policy.fail_closed());
        assert!(plan.strict_remote_policy.forces_offload());
    }

    #[test]
    fn require_remote_supersedes_force_remote_with_diagnostic() {
        let plan = resolve_placement(env(&[
            ("RCH_REQUIRE_REMOTE", "1"),
            ("RCH_FORCE_REMOTE", "1"),
        ]));
        assert_eq!(plan.strict_remote_policy, StrictRemotePolicy::RequireRemote);
        assert!(
            plan.diagnostics
                .iter()
                .any(|d| d.control == "RCH_REQUIRE_REMOTE"
                    && d.level == ControlDiagnosticLevel::Info),
            "expected a precedence diagnostic, got {:?}",
            plan.diagnostics
        );
    }

    // --- queue-when-busy ---------------------------------------------------

    #[test]
    fn queue_defaults_enabled() {
        let plan = resolve_placement(env(&[]));
        assert_eq!(plan.queue_policy, QueuePolicy::QueueWhenBusy);
        assert!(plan.queue_policy.waits());
    }

    #[test]
    fn queue_disabled_by_zero() {
        let plan = resolve_placement(env(&[("RCH_QUEUE_WHEN_BUSY", "0")]));
        assert_eq!(plan.queue_policy, QueuePolicy::NoQueue);
        assert!(!plan.queue_policy.waits());
    }

    #[test]
    fn queue_unrecognized_value_warns_not_silently_ignored() {
        let plan = resolve_placement(env(&[("RCH_QUEUE_WHEN_BUSY", "maybe")]));
        assert_eq!(plan.queue_policy, QueuePolicy::QueueWhenBusy);
        assert!(
            plan.diagnostics
                .iter()
                .any(|d| d.control == "RCH_QUEUE_WHEN_BUSY"
                    && d.level == ControlDiagnosticLevel::Warning)
        );
    }

    // --- wait timeout ------------------------------------------------------

    #[test]
    fn wait_timeout_seconds_to_ms() {
        let plan = resolve_placement(env(&[("RCH_DAEMON_WAIT_RESPONSE_TIMEOUT_SECS", "120")]));
        assert_eq!(plan.wait_timeout_ms, Some(120_000));
    }

    #[test]
    fn wait_timeout_alias_emits_info() {
        let plan = resolve_placement(env(&[("RCH_DAEMON_RESPONSE_TIMEOUT_SECS", "45")]));
        assert_eq!(plan.wait_timeout_ms, Some(45_000));
        assert!(
            plan.diagnostics
                .iter()
                .any(|d| d.control == "RCH_DAEMON_RESPONSE_TIMEOUT_SECS"
                    && d.level == ControlDiagnosticLevel::Info)
        );
    }

    #[test]
    fn wait_timeout_invalid_warns_and_falls_back() {
        let plan = resolve_placement(env(&[("RCH_DAEMON_WAIT_RESPONSE_TIMEOUT_SECS", "soon")]));
        assert_eq!(plan.wait_timeout_ms, None);
        assert!(
            plan.diagnostics
                .iter()
                .any(|d| d.level == ControlDiagnosticLevel::Warning)
        );
    }

    // --- visibility --------------------------------------------------------

    #[test]
    fn visibility_canonical_values() {
        for (raw, expected) in [
            ("none", VisibilityMode::None),
            ("summary", VisibilityMode::Summary),
            ("verbose", VisibilityMode::Verbose),
        ] {
            let plan = resolve_placement(env(&[("RCH_VISIBILITY", raw)]));
            assert_eq!(plan.visibility_mode, expected);
        }
    }

    #[test]
    fn visibility_quiet_and_verbose_aliases() {
        let quiet = resolve_placement(env(&[("RCH_QUIET", "1")]));
        assert_eq!(quiet.visibility_mode, VisibilityMode::None);
        let verbose = resolve_placement(env(&[("RCH_VERBOSE", "1")]));
        assert_eq!(verbose.visibility_mode, VisibilityMode::Verbose);
    }

    #[test]
    fn visibility_invalid_warns_then_falls_back_to_alias() {
        let plan = resolve_placement(env(&[("RCH_VISIBILITY", "ultra"), ("RCH_QUIET", "1")]));
        // Invalid canonical value is reported, and the alias still applies.
        assert_eq!(plan.visibility_mode, VisibilityMode::None);
        assert!(
            plan.diagnostics.iter().any(
                |d| d.control == "RCH_VISIBILITY" && d.level == ControlDiagnosticLevel::Warning
            )
        );
    }

    // --- requested worker / profile / target dir ---------------------------

    #[test]
    fn requested_worker_and_profile_captured() {
        let plan = resolve_placement(env(&[("RCH_WORKER", "css"), ("RCH_PRESET", "fast")]));
        assert_eq!(plan.requested_worker.as_deref(), Some("css"));
        assert_eq!(plan.requested_profile.as_deref(), Some("fast"));
        assert_eq!(
            plan.requested_worker_outcome.status,
            RequestedWorkerStatus::Requested
        );
    }

    #[test]
    fn worker_alias_merges_and_dedupes() {
        let plan = resolve_placement(env(&[
            ("RCH_WORKER", "css, ovh-a"),
            ("RCH_WORKERS", "ovh-a,ovh-b"),
        ]));
        assert_eq!(plan.requested_worker.as_deref(), Some("css,ovh-a,ovh-b"));
        assert!(plan.diagnostics.iter().any(|d| d.control == "RCH_WORKER"));
    }

    #[test]
    fn target_dir_policy_variants() {
        let pooled = resolve_placement(env(&[]));
        assert_eq!(pooled.target_dir_policy, TargetDirPolicy::Pooled);
        let per_job = resolve_placement(env(&[("RCH_DISABLE_TARGET_REUSE", "1")]));
        assert_eq!(per_job.target_dir_policy, TargetDirPolicy::PerJob);
        let scoped = resolve_placement(env(&[("CARGO_TARGET_DIR", "/tmp/.rch-target/css")]));
        assert_eq!(scoped.target_dir_policy, TargetDirPolicy::WorkerScoped);
    }

    // --- requested-worker admissibility ------------------------------------

    #[test]
    fn evaluate_not_requested() {
        let out = evaluate_requested_worker(&RequestedWorkerFacts::none());
        assert_eq!(out.status, RequestedWorkerStatus::NotRequested);
        assert!(out.reason_code.is_none());
    }

    #[test]
    fn evaluate_honored() {
        let out = evaluate_requested_worker(&RequestedWorkerFacts::admissible("css"));
        assert_eq!(out.status, RequestedWorkerStatus::Honored);
        assert!(out.reason_code.is_none());
        assert!(!out.status.is_refusal());
    }

    #[test]
    fn evaluate_unknown_worker_refused() {
        let facts = RequestedWorkerFacts {
            requested: Some("ghost".into()),
            exists: false,
            ..RequestedWorkerFacts::none()
        };
        let out = evaluate_requested_worker(&facts);
        assert_eq!(out.status, RequestedWorkerStatus::Unavailable);
        assert_eq!(out.reason_code.as_deref(), Some("RCH-I001"));
        assert!(
            out.next_action
                .as_deref()
                .unwrap()
                .contains("rch workers list")
        );
        assert!(out.status.is_refusal());
    }

    #[test]
    fn evaluate_admin_disabled_refused() {
        let facts = RequestedWorkerFacts {
            admin_disabled: true,
            ..RequestedWorkerFacts::admissible("css")
        };
        let out = evaluate_requested_worker(&facts);
        assert_eq!(out.status, RequestedWorkerStatus::AdminDisabled);
        assert_eq!(out.reason_code.as_deref(), Some("RCH-I001"));
        assert!(
            out.next_action
                .as_deref()
                .unwrap()
                .contains("rch workers enable")
        );
    }

    #[test]
    fn evaluate_wrong_platform_refused() {
        let facts = RequestedWorkerFacts {
            platform_matches: false,
            ..RequestedWorkerFacts::admissible("css")
        };
        let out = evaluate_requested_worker(&facts);
        assert_eq!(out.status, RequestedWorkerStatus::WrongPlatform);
        assert_eq!(
            out.reason_code.as_deref(),
            Some(IncidentReasonCode::OsArchMismatch.code())
        );
    }

    #[test]
    fn evaluate_missing_runtime_refused() {
        let facts = RequestedWorkerFacts {
            has_required_runtime: false,
            ..RequestedWorkerFacts::admissible("css")
        };
        let out = evaluate_requested_worker(&facts);
        assert_eq!(out.status, RequestedWorkerStatus::MissingRuntime);
        assert_eq!(
            out.reason_code.as_deref(),
            Some(IncidentReasonCode::MissingRuntimeToolchainTarget.code())
        );
    }

    #[test]
    fn evaluate_project_excluded_refused() {
        let facts = RequestedWorkerFacts {
            project_excluded: true,
            ..RequestedWorkerFacts::admissible("css")
        };
        let out = evaluate_requested_worker(&facts);
        assert_eq!(out.status, RequestedWorkerStatus::ProjectExcluded);
        assert_eq!(
            out.reason_code.as_deref(),
            Some(IncidentReasonCode::ActiveProjectExclusion.code())
        );
    }

    #[test]
    fn evaluate_no_slots_refused() {
        let facts = RequestedWorkerFacts {
            has_free_slots: false,
            ..RequestedWorkerFacts::admissible("css")
        };
        let out = evaluate_requested_worker(&facts);
        assert_eq!(out.status, RequestedWorkerStatus::NoFreeSlots);
        assert_eq!(
            out.reason_code.as_deref(),
            Some(IncidentReasonCode::InsufficientSlots.code())
        );
    }

    #[test]
    fn evaluate_insufficient_capacity_refused_without_queue_advice() {
        let mut diagnostic = admissibility_diagnostic();
        diagnostic.worker_id = WorkerId::new("tiny");
        diagnostic.available_slots = 1;
        diagnostic.total_slots = 1;
        diagnostic.estimated_cores = 2;
        let facts = RequestedWorkerFacts::from_diagnostic("tiny", &diagnostic);
        let out = evaluate_requested_worker(&facts);
        assert_eq!(out.status, RequestedWorkerStatus::NoFreeSlots);
        assert_eq!(
            out.reason_code.as_deref(),
            Some(IncidentReasonCode::InsufficientSlots.code())
        );
        let next_action = out.next_action.expect("capacity refusal needs an action");
        // Names the concrete counts and the -j lever (rch#35), not just a vague
        // "lower the request", and still carries no queue advice.
        assert!(
            next_action.contains("1 total slot"),
            "should name total slots: {next_action}"
        );
        assert!(
            next_action.contains("2 core"),
            "should name estimated cores: {next_action}"
        );
        assert!(
            next_action.contains("-j 1"),
            "should name the exact -j value that fits: {next_action}"
        );
        assert!(!next_action.contains("RCH_QUEUE_WHEN_BUSY"));
    }

    #[test]
    fn diagnostic_toolchain_refusal_maps_to_missing_runtime_code() {
        let mut diagnostic = admissibility_diagnostic();
        diagnostic.final_decision = WorkerSelectionDiagnosticDecision::Deny;
        diagnostic.final_reason = "toolchain version mismatch".to_string();
        diagnostic.reason_codes = vec!["toolchain.version_mismatch".to_string()];
        let facts = RequestedWorkerFacts::from_diagnostic("css", &diagnostic);
        let out = evaluate_requested_worker(&facts);
        assert_eq!(out.status, RequestedWorkerStatus::MissingRuntime);
        assert_eq!(
            out.reason_code.as_deref(),
            Some(IncidentReasonCode::MissingRuntimeToolchainTarget.code())
        );
    }

    #[test]
    fn remaining_diagnostic_denials_never_report_honored() {
        let cases = [
            (
                "critical pressure",
                "pressure.critical",
                IncidentReasonCode::CriticalPressure,
            ),
            (
                "topology preflight failed",
                "topology.preflight_failed",
                IncidentReasonCode::HardPreflight,
            ),
            (
                "success rate below fallback floor",
                "health.below_fallback_min_success_rate",
                IncidentReasonCode::NoAdmissibleWorkers,
            ),
        ];

        for (reason, reason_code, expected_incident) in cases {
            let mut diagnostic = admissibility_diagnostic();
            diagnostic.final_decision = WorkerSelectionDiagnosticDecision::Deny;
            diagnostic.final_reason = reason.to_string();
            diagnostic.reason_codes = vec![reason_code.to_string()];
            let facts = RequestedWorkerFacts::from_diagnostic("css", &diagnostic);
            let out = evaluate_requested_worker(&facts);
            assert!(out.status.is_refusal(), "{reason_code} must be refused");
            assert_eq!(out.reason_code.as_deref(), Some(expected_incident.code()));
            assert!(out.next_action.is_some());
        }
    }

    #[test]
    fn evaluate_temporary_bypass_refused() {
        let facts = RequestedWorkerFacts {
            temporarily_bypassed: true,
            ..RequestedWorkerFacts::admissible("css")
        };
        let out = evaluate_requested_worker(&facts);
        assert_eq!(out.status, RequestedWorkerStatus::TemporarilyBypassed);
        assert_eq!(
            out.reason_code.as_deref(),
            Some(IncidentReasonCode::CircuitOpen.code())
        );
    }

    #[test]
    fn refusal_priority_is_most_specific_first() {
        // An unknown worker that is also missing a runtime reports "unavailable"
        // (existence is the primary blocker), not "missing_runtime".
        let facts = RequestedWorkerFacts {
            requested: Some("ghost".into()),
            exists: false,
            has_required_runtime: false,
            ..RequestedWorkerFacts::none()
        };
        assert_eq!(
            evaluate_requested_worker(&facts).status,
            RequestedWorkerStatus::Unavailable
        );
    }

    // --- plan -> control-state bridge & serialization ----------------------

    #[test]
    fn control_state_bridge_is_sparse() {
        // Default plan -> empty control state (nothing explicitly set).
        let plan = resolve_placement(env(&[]));
        assert!(plan.control_state().is_empty());
    }

    #[test]
    fn control_state_bridge_carries_set_fields() {
        let plan = resolve_placement(env(&[
            ("RCH_WORKER", "css"),
            ("RCH_REQUIRE_REMOTE", "1"),
            ("RCH_QUEUE_WHEN_BUSY", "0"),
        ]));
        let cs = plan.control_state();
        assert_eq!(cs.requested_worker.as_deref(), Some("css"));
        assert!(cs.strict_remote_policy);
        assert_eq!(cs.queue_policy.as_deref(), Some("no_queue"));
        assert!(!cs.is_empty());
    }

    #[test]
    fn plan_round_trips_through_json() {
        let plan = resolve_placement(env(&[("RCH_WORKER", "css"), ("RCH_FORCE_REMOTE", "1")]))
            .with_effective_worker(Some("ovh-a".to_string()))
            .with_requested_worker_outcome(evaluate_requested_worker(
                &RequestedWorkerFacts::admissible("css"),
            ));
        let v = serde_json::to_value(&plan).unwrap();
        assert_eq!(v["strict_remote_policy"], "force_remote");
        assert_eq!(v["queue_policy"], "queue_when_busy");
        assert_eq!(v["requested_worker"], "css");
        assert_eq!(v["effective_worker"], "ovh-a");
        assert_eq!(v["requested_worker_outcome"]["status"], "honored");
        let back: PlacementPlan = serde_json::from_value(v).unwrap();
        assert_eq!(back, plan);
    }

    #[test]
    fn schema_version_is_pinned() {
        let plan = resolve_placement(env(&[]));
        assert_eq!(plan.schema_version, PlacementPlan::schema_version());
    }

    // --- registry invariants ----------------------------------------------

    #[test]
    fn registry_canonical_names_unique_and_distinct_from_aliases() {
        let controls = placement_controls();
        let mut names = std::collections::HashSet::new();
        for c in controls {
            assert!(
                names.insert(c.canonical_env),
                "duplicate canonical env {}",
                c.canonical_env
            );
        }
        // No alias collides with a canonical name.
        for c in controls {
            for alias in c.aliases {
                assert!(
                    !names.contains(alias),
                    "alias {alias} collides with a canonical name"
                );
            }
        }
    }

    #[test]
    fn registry_covers_the_audited_controls() {
        let controls = placement_controls();
        let has = |n: &str| controls.iter().any(|c| c.canonical_env == n);
        for required in [
            "RCH_WORKER",
            "RCH_REQUIRE_REMOTE",
            "RCH_FORCE_REMOTE",
            "RCH_QUEUE_WHEN_BUSY",
            "RCH_VISIBILITY",
            "RCH_NO_SELF_HEALING",
        ] {
            assert!(has(required), "registry missing audited control {required}");
        }
    }
}