greengate-runtime 4.12.0

The amont hook logic: registry, dispatchers, checks and the trust model
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
//! Collect: turn the passes of detached Workflows into cluster tokens
//! (ADR-0017), cheaply, at the start of a hook.
//!
//! With nothing pending it costs one `stat` and spawns no `kubectl`. With
//! something pending it takes the pending file's lock without waiting (busy
//! means somebody else is collecting: return), and asks the cluster ONE
//! question per hook process: `kubectl get workflows,pods -l 'greengate.run in
//! (…)' -o json`, under a 1 s request timeout and a wall deadline. A failed
//! read keeps every record for the next hook.
//!
//! What a pod proves is read from its `containerStatuses` and
//! `initContainerStatuses` alone, as ADR-0016's Job does. The Workflow's and
//! its nodes' phases say only that the pod FINISHED: gate code can write what
//! Argo's executor reads, so a phase is never a pass. The pod must also be
//! the one submitted (its owner is the saved Workflow UID; its images, tree
//! and command are the frozen ones), and the token written is the one frozen
//! at submission.

use std::sync::atomic::{AtomicBool, Ordering};

use crate::attest::{BlockRefusal, SignerBlock};
use crate::json_read::Value;

use super::super::{
    capture, in_cluster_signer, judge, last_line, log_line, parse_pod_object, record_token, Call,
    Fallback, JobEnd, Kube, PodFacts, State, PLATFORM, RUN_LABEL_KEY,
};
use super::pending::{GateState, Pending, PendingError, RecordPhase, Store};
use super::sign::{SIGNER_LABEL, SIGNER_LABEL_VALUE};
use super::workflow::{check_pod, check_workflow, node_name, template_name, TTL_SECS};

/// The wall deadline for the one batched call. `kubectl`'s own request timeout
/// is 1 s; this bounds the process around it.
const COLLECT_SECS: u64 = 5;
/// Bound on each `patch` of `--stop`, and on all of them together.
const PATCH_SECS: u64 = 10;
const STOP_SECS: u64 = 30;
/// An intent no Workflow appeared for in this long was never created.
// holds-until: an apiserver slower than this to show a created Workflow — a
// create that lands after the grace is not adopted, and its gates run at the
// push instead
const INTENT_GRACE_SECS: u64 = 600;
/// A record outlives its Workflow's TTL by this long, then goes whatever the
/// cluster says.
const EXPIRY_SLACK_SECS: u64 = 3600;

/// Once per hook process, however many callers ask. Process-scoped on
/// purpose: a hook runs as one process and asks the cluster one question, so
/// `stamps` inside a hook, or `--status` after a collect, do not repeat it;
/// the next hook is a new process and asks again.
static COLLECTED: AtomicBool = AtomicBool::new(false);

/// Why a collect learned nothing, or could not keep what it learned.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Trouble {
    /// Another collect, or a submission, holds the pending file.
    Busy,
    /// The cluster did not answer.
    NotReached(String),
    /// The pending file could not be read or written.
    StoreFailed(PendingError),
}

impl std::fmt::Display for Trouble {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Trouble::Busy => write!(f, "another collect is running"),
            Trouble::NotReached(why) => write!(f, "cluster not reached: {why}"),
            Trouble::StoreFailed(why) => write!(f, "pending store failed: {why}"),
        }
    }
}

/// A Workflow that left the pending file in this collect, for `--status`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Settled {
    pub name: String,
    /// The Workflow's last phase in plain words.
    pub phase: RecordPhase,
    pub passed: Vec<String>,
    pub failed: Vec<String>,
}

/// What a collect did.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct Collected {
    /// Passes written as cluster tokens.
    pub passes: usize,
    /// Workflows still pending afterwards.
    pub pending: usize,
    /// The Workflows this collect finished with.
    pub settled: Vec<Settled>,
    pub trouble: Option<Trouble>,
}

impl Collected {
    fn troubled(trouble: Trouble) -> Collected {
        Collected {
            trouble: Some(trouble),
            ..Collected::default()
        }
    }
}

/// A gate judged a pass: the token to write, frozen at submission.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Pass {
    gate: String,
    tree: String,
    token: String,
    provenance: String,
}

/// What one record became.
#[derive(Debug)]
struct Resolution {
    /// The record as it stands now.
    record: Pending,
    /// Whether it leaves the pending file: its Workflow is finished and judged,
    /// or gone. A pass whose token is not written keeps it there all the same.
    leaves: bool,
    passes: Vec<Pass>,
    /// One `cluster.log` line per gate that is not a pass: `(gate, why)`.
    notes: Vec<(String, String)>,
}

/// What the in-cluster signer's ConfigMap came to for one record
/// (`greengate.cluster.signer in-cluster`).
#[derive(Debug, Clone, PartialEq, Eq)]
enum Signed {
    /// Checked and filed in the local attestation notes: the principal it
    /// verified as. The next push publishes it.
    Filed(String),
    /// No ConfigMap yet, or none could be read or filed: the record waits.
    NotReady,
    /// A block that does not check: the laptop signs at the push.
    /// `namespace` is the signer's, where the ConfigMap can be read.
    Refused {
        refusal: BlockRefusal,
        namespace: String,
    },
    /// The signer judged no gate a pass: the laptop signs at the push.
    Skipped(String),
}

/// Asks what the signer wrote for a record; `None` in the laptop mode.
type SignerLookup<'a> = Option<&'a mut dyn FnMut(&Pending) -> Signed>;

/// Collect, once per hook process. Called at the start of pre-commit and
/// pre-push, by `amont stamps`, `amont cluster collect` and `rehearse
/// --status`.
pub(crate) fn collect() -> Collected {
    if COLLECTED.swap(true, Ordering::SeqCst) {
        return Collected::default();
    }
    Store::here().map_or_else(Collected::default, |store| collect_from(&store))
}

fn collect_from(store: &Store) -> Collected {
    if !store.exists() {
        return Collected::default();
    }
    // Busy: another hook is collecting, or a submission is writing.
    let Some(held) = store.try_lock() else {
        return Collected::troubled(Trouble::Busy);
    };
    let records = match store.read() {
        Ok(records) => records,
        Err(why) => {
            log_line("collect", &why.to_string());
            return Collected::troubled(Trouble::StoreFailed(why));
        }
    };
    if records.is_empty() {
        return Collected::default();
    }
    let now = crate::gate_evidence::now();
    let mut kept: Vec<Pending> = Vec::new();
    let mut settled: Vec<Settled> = Vec::new();
    let mut passes = 0;
    let mut unreached: Vec<String> = Vec::new();
    // Read only with something pending: one git call.
    let signer_namespace = in_cluster_signer();
    for group in by_cluster(records) {
        let kube = Kube {
            kubeconfig: group[0].kubeconfig.clone(),
            namespace: group[0].namespace.clone(),
        };
        match fetch(&kube, &group) {
            Ok(list) => {
                // The signer's ConfigMaps: asked at most once per group, and
                // only once a record needs them.
                let labels: Vec<String> = group.iter().map(|r| r.label.clone()).collect();
                let mut configmaps: Option<Result<Value, String>> = None;
                let mut lookup = |record: &Pending| -> Signed {
                    let Some(namespace) = &signer_namespace else {
                        return Signed::NotReady;
                    };
                    let answer = configmaps.get_or_insert_with(|| {
                        let signer = Kube {
                            kubeconfig: kube.kubeconfig.clone(),
                            namespace: namespace.clone(),
                        };
                        let read = fetch_blocks(&signer, &labels);
                        if let Err(why) = &read {
                            log_line(
                                "collect",
                                &format!("the signer's blocks could not be read: {why}"),
                            );
                        }
                        read
                    });
                    match answer {
                        Ok(list) => match_block(record, list, namespace),
                        Err(_) => Signed::NotReady,
                    }
                };
                for mut record in group {
                    let done = if signer_namespace.is_none() {
                        // Nothing awaits a signer the machine no longer uses.
                        record.awaiting_signer = false;
                        settle(resolve(record, &list, now), None)
                    } else if record.awaiting_signer {
                        settle_awaiting(record, now, &mut lookup)
                    } else {
                        settle(resolve(record, &list, now), Some(&mut lookup))
                    };
                    passes += done.written;
                    settled.extend(done.settled);
                    kept.extend(done.record);
                }
            }
            Err(why) => {
                log_line("collect", &format!("the cluster could not be read: {why}"));
                // The rollback says an unreadable record expires: it does,
                // even when the cluster cannot be asked.
                let (old, young): (Vec<Pending>, Vec<Pending>) =
                    group.into_iter().partition(|r| is_expired(r, now));
                for record in &old {
                    if record.awaiting_signer && signer_namespace.is_some() {
                        unsigned_at_ttl(record);
                        continue;
                    }
                    log_line(
                        record.gates.first().map_or("collect", |g| g.id.as_str()),
                        &format!(
                            "detached {}: older than the Workflow TTL; dropped",
                            record.name
                        ),
                    );
                }
                kept.extend(young);
                unreached.push(format!(
                    "{why} (namespace {}, kubeconfig {})",
                    kube.namespace,
                    kube.kubeconfig.display()
                ));
            }
        }
    }
    let trouble = match (store.write(&held, &kept), unreached) {
        (Err(why), _) => {
            log_line(
                "collect",
                &format!("cluster-pending was not updated: {why}"),
            );
            Some(Trouble::StoreFailed(why))
        }
        // Any group left unasked is named, even when another answered.
        (Ok(()), why) if !why.is_empty() => Some(Trouble::NotReached(why.join("; "))),
        (Ok(()), _) => None,
    };
    Collected {
        passes,
        pending: kept.len(),
        settled,
        trouble,
    }
}

fn is_expired(record: &Pending, now: u64) -> bool {
    now > record.submitted + TTL_SECS + EXPIRY_SLACK_SECS
}

/// Whether the pending file at `path` still lists a run that has not
/// outlived its Workflow by [`EXPIRY_SLACK_SECS`]: what `collect` would keep.
/// `Ok(false)` for no file; `Err` for a file this version cannot read.
pub(crate) fn lists_live(path: &std::path::Path, now: u64) -> Result<bool, String> {
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(e.to_string()),
    };
    Ok(super::pending::parse_file(&text)?
        .iter()
        .any(|record| !is_expired(record, now)))
}

/// The records grouped by the cluster they live on: one call each.
fn by_cluster(records: Vec<Pending>) -> Vec<Vec<Pending>> {
    let mut groups: Vec<Vec<Pending>> = Vec::new();
    for record in records {
        match groups
            .iter_mut()
            .find(|g| g[0].kubeconfig == record.kubeconfig && g[0].namespace == record.namespace)
        {
            Some(group) => group.push(record),
            None => groups.push(vec![record]),
        }
    }
    groups
}

/// The one batched call: every Workflow and pod carrying one of the records'
/// run labels.
fn fetch(kube: &Kube, records: &[Pending]) -> Result<Value, String> {
    let labels: Vec<&str> = records.iter().map(|r| r.label.as_str()).collect();
    let selector = format!("{RUN_LABEL_KEY} in ({})", labels.join(","));
    get_json(kube, "workflows,pods", &selector)
}

/// The one batched call of `in-cluster` signing, in the signer namespace:
/// every signer ConfigMap carrying one of the records' run labels, under the
/// same request timeout and deadline as [`fetch`].
fn fetch_blocks(signer: &Kube, labels: &[String]) -> Result<Value, String> {
    let selector = format!(
        "{SIGNER_LABEL}={SIGNER_LABEL_VALUE},{RUN_LABEL_KEY} in ({})",
        labels.join(",")
    );
    get_json(signer, "configmaps", &selector)
}

fn get_json(kube: &Kube, what: &str, selector: &str) -> Result<Value, String> {
    let mut cmd = kube.command(
        "--request-timeout=1s",
        &["get", what, "-l", selector, "-o", "json"],
    );
    match capture(&mut cmd, COLLECT_SECS) {
        Call::Ok(json) => crate::json_read::parse(&json)
            .ok_or_else(|| "kubectl printed something that is not JSON".to_string()),
        Call::Refused(e) | Call::NotStarted(e) | Call::TimedOut(e) => Err(last_line(&e)),
    }
}

/// What settling a resolution left.
struct Settlement {
    /// The record if it stays in the file.
    record: Option<Pending>,
    /// Tokens written.
    written: usize,
    /// The record's end, when it left the file.
    settled: Option<Settled>,
}

/// [`settle_with`], writing tokens to the cluster note.
fn settle(resolution: Resolution, signer: SignerLookup) -> Settlement {
    settle_with(
        resolution,
        |pass| record_token(&pass.tree, &pass.token, &pass.provenance),
        signer,
    )
}

/// Write the passes of a resolution through `write` and log its notes. A pass
/// whose token was not written returns its gate to waiting and keeps the
/// record in the file, finished Workflow or not, so that the next collect
/// tries again.
///
/// With a `signer` (`in-cluster`), a record that leaves with a pass asks it
/// for the block first, and each gate's `collected` line waits for the
/// answer, so that it is said once: with the principal when the block was
/// filed, plainly beside the reason when the laptop signs. A block not there
/// yet keeps the record, awaiting it, its tokens written.
fn settle_with(
    resolution: Resolution,
    mut write: impl FnMut(&Pass) -> Result<(), Fallback>,
    signer: SignerLookup,
) -> Settlement {
    let Resolution {
        mut record,
        leaves,
        passes,
        notes,
    } = resolution;
    for (gate, why) in &notes {
        log_line(gate, why);
    }
    let mut written = 0;
    let mut unwritten = 0;
    for pass in &passes {
        match write(pass) {
            Ok(()) => {
                written += 1;
                if signer.is_none() {
                    say_collected(&pass.gate, &pass.tree);
                }
            }
            Err(why) => {
                log_line(
                    &pass.gate,
                    &format!("detached: the pass was not recorded: {why}"),
                );
                unwritten += 1;
                for gate in record.gates.iter_mut().filter(|g| g.id == pass.gate) {
                    gate.state = GateState::Waiting;
                }
            }
        }
    }
    if !leaves || unwritten > 0 {
        return Settlement {
            record: Some(record),
            written,
            settled: None,
        };
    }
    if let Some(lookup) = signer {
        if record.gates.iter().any(|g| g.state == GateState::Passed) {
            let signed = lookup(&record);
            if signed == Signed::NotReady {
                say_signed(&record, &signed);
                record.awaiting_signer = true;
                return Settlement {
                    record: Some(record),
                    written,
                    settled: None,
                };
            }
            say_signed(&record, &signed);
        }
    }
    Settlement {
        written,
        ..ended(record)
    }
}

/// A record whose passes are written and which awaits the signer's block:
/// filed, refused or skipped, it leaves; past the Workflow's TTL and its
/// slack it leaves unsigned; otherwise it stays. No token is written again.
fn settle_awaiting(
    record: Pending,
    now: u64,
    lookup: &mut dyn FnMut(&Pending) -> Signed,
) -> Settlement {
    if is_expired(&record, now) {
        unsigned_at_ttl(&record);
        return ended(record);
    }
    let signed = lookup(&record);
    say_signed(&record, &signed);
    if signed == Signed::NotReady {
        return Settlement {
            record: Some(record),
            written: 0,
            settled: None,
        };
    }
    ended(record)
}

/// The record leaves the file: its end, for `--status`.
fn ended(record: Pending) -> Settlement {
    let ids = |state: GateState| -> Vec<String> {
        record
            .gates
            .iter()
            .filter(|g| g.state == state)
            .map(|g| g.id.clone())
            .collect()
    };
    let settled = Settled {
        name: record.name.clone(),
        phase: record.phase,
        passed: ids(GateState::Passed),
        failed: ids(GateState::Failed),
    };
    Settlement {
        record: None,
        written: 0,
        settled: Some(settled),
    }
}

/// The gates of `record` that passed.
fn passed(record: &Pending) -> impl Iterator<Item = &str> {
    record
        .gates
        .iter()
        .filter(|g| g.state == GateState::Passed)
        .map(|g| g.id.as_str())
}

/// The line a collected pass is announced with when the laptop signs it as
/// today (no in-cluster signer). stderr: `greengate stamps --json` collects
/// first, and its stdout is the JSON object alone.
fn say_collected(gate: &str, tree: &str) {
    eprintln!(
        "collected the cluster pass of {} for tree {}",
        crate::ui::sanitize(gate),
        short(tree)
    );
}

/// A collected gate in the in-cluster signer mode: `collected <gate> for
/// tree <short>; <rest>`, one line, whether the signer's block was filed
/// (`signed by <principal>`) or the laptop signs it (why, and what to do).
fn say_collected_unsigned(gate: &str, tree: &str, rest: &str) {
    eprintln!(
        "collected {} for tree {}; {}",
        crate::ui::sanitize(gate),
        short(tree),
        crate::ui::sanitize(rest)
    );
}

/// What a person checks after a refusal, by its cause.
fn next_step(record: &Pending, refusal: &BlockRefusal, namespace: &str) -> String {
    match refusal {
        BlockRefusal::Signer(_) => {
            format!("check {} lists cluster-signer@{PLATFORM}", signers_shown())
        }
        BlockRefusal::Content(_) => {
            format!(
                "see kubectl --kubeconfig {} -n {namespace} get configmap {}",
                record.kubeconfig.display(),
                record.name
            )
        }
        BlockRefusal::StaleSigner(_) => {
            "roll the attest-signer image to this greengate release".to_string()
        }
    }
}

/// What the signer's answer means for each passed gate of `record`, said.
fn say_signed(record: &Pending, signed: &Signed) {
    for gate in passed(record) {
        match signed {
            Signed::Filed(principal) => {
                say_collected_unsigned(gate, &record.tree, &format!("signed by {principal}"))
            }
            Signed::NotReady => {
                eprintln!(
                    "signer block for {} not ready; next collect retries",
                    crate::ui::sanitize(gate)
                );
            }
            Signed::Refused { refusal, namespace } => {
                log_line(
                    gate,
                    &format!(
                        "detached {}: signer block refused: {}",
                        record.name,
                        refusal.reason()
                    ),
                );
                say_collected_unsigned(
                    gate,
                    &record.tree,
                    &format!(
                        "signer block refused: {}; the laptop signs it; {}",
                        refusal.reason(),
                        next_step(record, refusal, namespace)
                    ),
                );
            }
            Signed::Skipped(why) => say_collected_unsigned(
                gate,
                &record.tree,
                &format!("signer skipped: {why}; the laptop signs it"),
            ),
        }
    }
}

/// An awaiting record past the Workflow's TTL: logged and said, per gate.
fn unsigned_at_ttl(record: &Pending) {
    for gate in passed(record) {
        log_line(
            gate,
            &format!("detached {}: unsigned: no signer block", record.name),
        );
        say_collected_unsigned(
            gate,
            &record.tree,
            "signer block did not arrive before the Workflow TTL; the laptop signs it",
        );
    }
}

/// The signers file a refusal points at: the repository's, or where it
/// belongs when there is none.
fn signers_shown() -> String {
    crate::attest::default_signers()
        .or_else(|| {
            crate::git::stdout(&["rev-parse", "--show-toplevel"])
                .map(|top| std::path::Path::new(&top).join(".github/allowed_signers"))
        })
        .map_or_else(
            || ".github/allowed_signers".to_string(),
            |p| shown_from_top(&p),
        )
}

/// `path` relative to the repository's top level when it is inside it (a
/// refusal line stays short), else as it is.
fn shown_from_top(path: &std::path::Path) -> String {
    crate::git::stdout(&["rev-parse", "--show-toplevel"])
        .and_then(|top| {
            path.strip_prefix(&top)
                .ok()
                .map(|rel| rel.display().to_string())
        })
        .unwrap_or_else(|| path.display().to_string())
}

/// The signer's ConfigMap for `record` in `configmaps`: named after its
/// Workflow, labelled with its run and as a signer block.
fn signer_configmap<'a>(record: &Pending, configmaps: &'a Value) -> Option<&'a Value> {
    configmaps
        .get("items")
        .map(Value::items)
        .unwrap_or(&[])
        .iter()
        .find(|cm| {
            let metadata = cm.get("metadata");
            let labels = metadata.and_then(|m| m.get("labels"));
            text(metadata, "name") == Some(record.name.as_str())
                && text(labels, RUN_LABEL_KEY) == Some(record.label.as_str())
                && text(labels, SIGNER_LABEL) == Some(SIGNER_LABEL_VALUE)
        })
}

/// What the signer wrote for `record` in `configmaps` (in `namespace`):
/// nothing yet, a skip, or a block [`judge_block`] judges, then files under
/// the tree, and under the snapshot commit when this repository has it.
fn match_block(record: &Pending, configmaps: &Value, namespace: &str) -> Signed {
    let Some(cm) = signer_configmap(record, configmaps) else {
        return Signed::NotReady;
    };
    let fields = cm.get("data");
    let block = text(fields, "block").unwrap_or("");
    if block.is_empty() {
        return Signed::Skipped(
            text(fields, "skipped")
                .filter(|why| !why.is_empty())
                .unwrap_or("no reason given")
                .to_string(),
        );
    }
    let signers = crate::attest::default_signers();
    let checked = match judge_block(record, block, signers.as_deref()) {
        Ok(checked) => checked,
        Err(refusal) => {
            return Signed::Refused {
                refusal,
                namespace: namespace.to_string(),
            }
        }
    };
    let commit = &record.source.oid;
    let mut keys = vec![record.tree.as_str()];
    if !commit.is_empty()
        && crate::git::succeeds(&["cat-file", "-e", &format!("{commit}^{{commit}}")])
    {
        keys.push(commit);
    }
    match crate::attest::file_signer_block(&checked.body, &keys) {
        Ok(()) => Signed::Filed(checked.principal),
        Err(why) => {
            log_line(
                passed(record).next().unwrap_or("collect"),
                &format!(
                    "detached {}: the signer block could not be filed ({why}); the next collect retries",
                    record.name
                ),
            );
            Signed::NotReady
        }
    }
}

/// `block` judged for `record`: checked by attest's reader and verifier
/// against `signers`, the repository's `allowed_signers` (the file a
/// push-time verification reads), for the record's tree, naming every gate
/// that passed in it. Writes nothing; the verification runs `ssh-keygen`.
fn judge_block(
    record: &Pending,
    block: &str,
    signers: Option<&std::path::Path>,
) -> Result<SignerBlock, BlockRefusal> {
    let Some(signers) = signers else {
        return Err(BlockRefusal::Signer(
            "the repository has no allowed_signers".into(),
        ));
    };
    // Only a block under greensummit's names checks (ADR-0073), so what is
    // filed, and later published, sits under a ref whose header is its own.
    let checked = crate::attest::signer_block(block, &record.tree, signers)?;
    let missing: Vec<&str> = passed(record)
        .filter(|g| !checked.gates.iter().any(|named| named == g))
        .collect();
    if !missing.is_empty() {
        return Err(BlockRefusal::Content(format!(
            "it does not name {}",
            missing.join(" ")
        )));
    }
    Ok(checked)
}

fn short(oid: &str) -> &str {
    oid.get(..8).unwrap_or(oid)
}

fn text<'a>(v: Option<&'a Value>, key: &str) -> Option<&'a str> {
    v?.get(key).and_then(Value::as_str)
}

pub(super) fn kind_of<'a>(list: &'a Value, kind: &'a str) -> impl Iterator<Item = &'a Value> {
    list.get("items")
        .map(Value::items)
        .unwrap_or(&[])
        .iter()
        .filter(move |i| text(Some(i), "kind") == Some(kind))
}

/// The pod of the Workflow `uid` that ran `node`: named so by Argo's
/// annotation, owned by that Workflow, and a Pod node of the Workflow's own
/// status of the template the gate was submitted under.
pub(super) fn pod_of<'a>(
    list: &'a Value,
    wf: &Value,
    name: &str,
    uid: &str,
    task: &str,
) -> Option<&'a Value> {
    let node = node_name(name, task);
    let recorded = wf
        .get("status")
        .and_then(|s| s.get("nodes"))
        .map(Value::members)
        .unwrap_or(&[])
        .iter()
        .map(|(_, n)| n)
        .find(|n| {
            text(Some(n), "name") == Some(node.as_str())
                && text(Some(n), "type") == Some("Pod")
                && text(Some(n), "templateName") == Some(template_name(task).as_str())
        })?;
    kind_of(list, "Pod").find(|pod| {
        let metadata = pod.get("metadata");
        let annotations = metadata.and_then(|m| m.get("annotations"));
        let owned = metadata
            .and_then(|m| m.get("ownerReferences"))
            .map(Value::items)
            .unwrap_or(&[])
            .iter()
            .any(|o| {
                text(Some(o), "kind") == Some("Workflow")
                    && text(Some(o), "uid") == Some(uid)
                    && text(Some(o), "name") == Some(name)
                    && o.get("controller").is_some_and(Value::is_true)
            });
        // The node id is required, not optional: a pod that does not name its
        // node cannot be bound to the Workflow's record of it.
        let node_id = text(annotations, "workflows.argoproj.io/node-id");
        owned
            && text(annotations, "workflows.argoproj.io/node-name") == Some(node.as_str())
            && node_id.is_some()
            && node_id == text(Some(recorded), "id")
    })
}

/// The Job-shaped end of a Workflow pod, from `main`'s termination status
/// alone: exit 0 is `Complete`, any other exit is `Failed`, and a container
/// that has not terminated is `Running`. Workflow and node phases are never
/// read here: gate code can write what Argo's executor reports from.
pub(super) fn end_from_main(main: &State) -> JobEnd {
    match main {
        State::Terminated { exit: Some(0), .. } => JobEnd::Complete,
        State::Terminated { reason, .. } => JobEnd::Failed(if reason.is_empty() {
            "Error".to_string()
        } else {
            reason.clone()
        }),
        State::Absent | State::Waiting | State::Running => JobEnd::Running,
    }
}

/// Why a pod that never ended `main` is no pass, as the pod says it.
fn unfinished(facts: &PodFacts) -> String {
    if let Some(w) = facts.fetch.failed() {
        format!("fetch {w}")
    } else if let Some(w) = facts.prepare.failed() {
        format!("prepare {w}")
    } else {
        "the pod ended without a verdict from main".to_string()
    }
}

/// Decide what the cluster's answer means for one record. Pure.
fn resolve(record: Pending, list: &Value, now: u64) -> Resolution {
    let mut notes: Vec<(String, String)> = Vec::new();
    let wf = kind_of(list, "Workflow").find(|w| {
        text(w.get("metadata"), "name") == Some(record.name.as_str())
            && text(
                w.get("metadata").and_then(|m| m.get("labels")),
                RUN_LABEL_KEY,
            ) == Some(record.label.as_str())
    });
    // The record ends here, its waiting gates failed, one note each.
    let drop_all = |mut record: Pending, why: &str| {
        let notes = record
            .waiting()
            .map(|g| (g.id.clone(), format!("detached {}: {why}", record.name)))
            .collect();
        for gate in record
            .gates
            .iter_mut()
            .filter(|g| g.state == GateState::Waiting)
        {
            gate.state = GateState::Failed;
        }
        record.phase = RecordPhase::Gone;
        Resolution {
            record,
            leaves: true,
            passes: Vec::new(),
            notes,
        }
    };
    let Some(wf) = wf else {
        return if record.uid.is_some() {
            drop_all(
                record,
                "the Workflow is gone (its TTL passed, or it was deleted)",
            )
        } else if is_expired(&record, now) || now > record.submitted + INTENT_GRACE_SECS {
            drop_all(record, "the Workflow never appeared")
        } else {
            // A create that may still land: the intent stays.
            Resolution {
                record,
                leaves: false,
                passes: Vec::new(),
                notes,
            }
        };
    };
    if is_expired(&record, now) {
        return drop_all(record, "older than the Workflow TTL");
    }
    let found_uid = text(wf.get("metadata"), "uid").map(str::to_string);
    let uid = match (&record.uid, &found_uid) {
        (Some(saved), Some(found)) if saved == found => saved.clone(),
        (Some(_), _) => {
            return drop_all(
                record,
                "another Workflow than the one submitted holds the name",
            )
        }
        (None, Some(found)) => match check_workflow(wf, &record) {
            Ok(()) => found.clone(),
            Err(why) => {
                return drop_all(record, &format!("not the Workflow submitted: {why}"));
            }
        },
        (None, None) => return drop_all(record, "the Workflow has no UID"),
    };
    let phase = RecordPhase::parse(text(wf.get("status"), "phase").unwrap_or(""));
    let mut passes: Vec<Pass> = Vec::new();
    let mut gates = record.gates.clone();
    for gate in gates.iter_mut().filter(|g| g.state == GateState::Waiting) {
        let Some(pod) = pod_of(list, wf, &record.name, &uid, &gate.task) else {
            if phase.finished() {
                gate.state = GateState::Failed;
                notes.push((
                    gate.id.clone(),
                    format!(
                        "detached {}: no pod of {} was found ({})",
                        record.name,
                        gate.task,
                        phase.as_str()
                    ),
                ));
            }
            continue;
        };
        if let Err(why) = check_pod(pod, gate, &record) {
            gate.state = GateState::Failed;
            notes.push((
                gate.id.clone(),
                format!(
                    "detached {}: the pod is not the one submitted: {why}",
                    record.name
                ),
            ));
            continue;
        }
        let Some(facts) = parse_pod_object(pod, "main") else {
            if phase.finished() {
                gate.state = GateState::Failed;
                notes.push((
                    gate.id.clone(),
                    format!("detached {}: the pod's status cannot be read", record.name),
                ));
            }
            continue;
        };
        let end = end_from_main(&facts.gate);
        if end == JobEnd::Running {
            if phase.finished() {
                gate.state = GateState::Failed;
                notes.push((
                    gate.id.clone(),
                    format!("detached {}: {}", record.name, unfinished(&facts)),
                ));
            }
            continue;
        }
        match judge(&end, &facts, &record.tree, gate.prepare.as_deref()) {
            Ok(image_id) => {
                gate.state = GateState::Passed;
                passes.push(Pass {
                    gate: gate.id.clone(),
                    tree: record.tree.clone(),
                    token: gate.token.clone(),
                    provenance: format!(
                        "platform={PLATFORM} image={image_id} job={uid} name={} bundle=0",
                        node_name(&record.name, &gate.task)
                    ),
                });
            }
            Err(fallback) => {
                gate.state = GateState::Failed;
                notes.push((
                    gate.id.clone(),
                    format!("detached {}: {}", record.name, fallback),
                ));
            }
        }
    }
    let settled = gates.iter().all(|g| g.state != GateState::Waiting);
    Resolution {
        leaves: settled || phase.finished(),
        record: Pending {
            uid: Some(uid),
            phase,
            gates,
            ..record
        },
        passes,
        notes,
    }
}

/// `amont cluster collect`: exit 0 when it asked the cluster (or had nothing
/// to ask, or another collect is at it), 1 when it learned nothing or could
/// not keep what it learned, 2 on usage.
pub fn collect_command(args: &[std::ffi::OsString]) -> i32 {
    if args.iter().any(|a| a == "--help" || a == "-h") {
        println!("usage: {} cluster collect", crate::names::BIN);
        return 0;
    }
    match args.first().and_then(|a| a.to_str()) {
        Some("collect") if args.len() == 1 => {
            let done = collect();
            match &done.trouble {
                Some(Trouble::Busy) => {
                    eprintln!("{}; nothing was asked of the cluster", Trouble::Busy);
                    0
                }
                Some(trouble) => {
                    eprintln!("{trouble}");
                    1
                }
                None => {
                    eprintln!(
                        "collected {} cluster pass{}; {} Workflow{} still pending",
                        done.passes,
                        if done.passes == 1 { "" } else { "es" },
                        done.pending,
                        if done.pending == 1 { "" } else { "s" },
                    );
                    0
                }
            }
        }
        _ => {
            eprintln!("usage: {} cluster collect", crate::names::BIN);
            2
        }
    }
}

/// `rehearse --status`: one line per pending Workflow, its phase as the last
/// collect saw it and the gates collected so far.
pub(crate) fn status_lines() -> Vec<String> {
    let Some(store) = Store::here() else {
        return Vec::new();
    };
    match store.read() {
        Ok(records) => records.iter().map(describe).collect(),
        Err(why) => {
            eprintln!("cluster run records cannot be read: {why}");
            Vec::new()
        }
    }
}

/// The Workflows a collect finished with, for the person who asked.
pub(crate) fn settled_lines(settled: &[Settled]) -> Vec<String> {
    settled
        .iter()
        .map(|run| {
            let mut parts: Vec<String> = Vec::new();
            if !run.passed.is_empty() {
                parts.push(format!("collected: {}", run.passed.join(" ")));
            }
            if !run.failed.is_empty() {
                parts.push(format!(
                    "did not pass: {} — see cluster.log; the gate runs at the push",
                    run.failed.join(" ")
                ));
            }
            format!(
                "cluster run {} {}: {}",
                run.name,
                run.phase.plain(),
                parts.join("; ")
            )
        })
        .collect()
}

fn describe(record: &Pending) -> String {
    let named = |label: &str, state: GateState| -> Option<String> {
        let ids: Vec<&str> = record
            .gates
            .iter()
            .filter(|g| g.state == state)
            .map(|g| g.id.as_str())
            .collect();
        (!ids.is_empty()).then(|| format!("{label}: {}", ids.join(" ")))
    };
    let fields: Vec<String> = [
        named("collected", GateState::Passed),
        named("did not pass", GateState::Failed),
        named("waiting", GateState::Waiting),
    ]
    .into_iter()
    .flatten()
    .collect();
    let follow = if record.phase.finished() {
        String::new()
    } else {
        format!(
            " (follow: kubectl -n {} get wf {})",
            record.namespace, record.name
        )
    };
    format!(
        "cluster run {}: {}{}{follow}",
        record.name,
        record.phase.plain(),
        if fields.is_empty() {
            String::new()
        } else {
            format!(" — {}", fields.join("; "))
        }
    )
}

/// The command that does by hand what `--stop` does for one Workflow.
fn terminate_command(record: &Pending) -> String {
    format!(
        "kubectl --kubeconfig {} -n {} patch workflow {} --type merge -p '{{\"spec\":{{\"shutdown\":\"Terminate\"}}}}'",
        shell_quote(&record.kubeconfig.to_string_lossy()),
        record.namespace,
        record.name
    )
}

/// `text` as one word for a POSIX shell.
fn shell_quote(text: &str) -> String {
    format!("'{}'", text.replace('\'', "'\\''"))
}

/// What `rehearse --stop` did to the pending Workflows.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct Stopped {
    /// One line per Workflow asked to terminate.
    pub done: Vec<String>,
    /// One line per Workflow that was not, with the command to do it by hand.
    pub failed: Vec<String>,
}

/// `rehearse --stop`: ask the cluster to terminate every pending Workflow,
/// each call and all of them bounded. Once the overall deadline is gone the
/// rest are reported as not attempted.
pub(crate) fn stop_pending() -> Stopped {
    let mut report = Stopped::default();
    let Some(store) = Store::here() else {
        return report;
    };
    let records = match store.read() {
        Ok(records) => records,
        Err(why) => {
            report
                .failed
                .push(format!("cluster run records cannot be read: {why}"));
            return report;
        }
    };
    let until = std::time::Instant::now() + std::time::Duration::from_secs(STOP_SECS);
    for record in &records {
        let left = until.saturating_duration_since(std::time::Instant::now());
        if left.is_zero() {
            report.failed.push(format!(
                "cluster run {} was not attempted: the stop deadline passed — {}",
                record.name,
                terminate_command(record)
            ));
            continue;
        }
        let kube = Kube {
            kubeconfig: record.kubeconfig.clone(),
            namespace: record.namespace.clone(),
        };
        let patched = kube.bounded(
            &[
                "patch",
                "workflow",
                &record.name,
                "--type",
                "merge",
                "-p",
                "{\"spec\":{\"shutdown\":\"Terminate\"}}",
            ],
            left.as_secs().clamp(1, PATCH_SECS),
        );
        match patched {
            Ok(()) => report
                .done
                .push(format!("terminating cluster run {}", record.name)),
            Err(why) => report.failed.push(format!(
                "could not terminate cluster run {}: {why} — {}",
                record.name,
                terminate_command(record)
            )),
        }
    }
    report
}

#[cfg(test)]
pub(in crate::cluster::detached) mod tests {
    use super::super::pending::tests::sample;
    use super::*;

    #[test]
    fn judge_block_refuses_a_block_under_the_old_names() {
        use crate::attest::tests::{block_with, both_names_signer, dir, OLD_FORMAT, OLD_NAMESPACE};
        use greensummit::format::SUMMIT;
        let scratch = dir("judge-legacy");
        let (key, signers) = both_names_signer(&scratch);
        let tree = "0123456789012345678901234567890123456789";
        let mut record = sample("wf-legacy");
        record.tree = tree.to_string();
        // Validly signed under its own namespace, which the signers file
        // trusts: the refusal is the one-set read and nothing else.
        let body = block_with(OLD_FORMAT, OLD_NAMESPACE, tree, &key);
        match judge_block(&record, &body, Some(&signers)) {
            Err(BlockRefusal::StaleSigner(why)) => {
                assert!(why.contains(OLD_FORMAT), "{why}");
                assert!(why.contains(SUMMIT.format), "{why}");
            }
            other => panic!("expected a content refusal, got {other:?}"),
        }
        let _ = std::fs::remove_dir_all(&scratch); // best-effort temp cleanup; a leftover dir cannot change the verdict
    }

    #[test]
    fn a_stale_signer_is_told_to_roll_its_image_not_to_read_the_configmap() {
        let record = sample("wf-stale");
        let said = next_step(
            &record,
            &BlockRefusal::StaleSigner("x".into()),
            "attest-signer",
        );
        assert!(said.contains("roll the attest-signer image"), "{said}");
        assert!(!said.contains("configmap"), "{said}");
    }

    #[test]
    fn judge_block_accepts_a_greensummit_block() {
        use crate::attest::tests::{block_with, both_names_signer, dir};
        use greensummit::format::SUMMIT;
        let scratch = dir("judge-green");
        let (key, signers) = both_names_signer(&scratch);
        let tree = "0123456789012345678901234567890123456789";
        let mut record = sample("wf-green");
        record.tree = tree.to_string();
        let body = block_with(SUMMIT.format, SUMMIT.namespace, tree, &key);
        let checked =
            judge_block(&record, &body, Some(&signers)).expect("a greensummit block judges");
        assert_eq!(checked.gates, ["suite"]);
        let _ = std::fs::remove_dir_all(&scratch); // best-effort temp cleanup; a leftover dir cannot change the verdict
    }

    #[test]
    fn lists_live_skips_a_run_past_its_ttl_and_reads_the_owner_format() {
        let dir = std::env::temp_dir().join(format!("greengate-lists-live-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir); // best-effort: a scratch path; absent or left behind is harmless
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join(super::super::PENDING_FILE);
        let now = 1_800_000_000;
        assert_eq!(lists_live(&file, now), Ok(false), "no file, no run");
        let mut live = super::super::pending::tests::sample("wf-live");
        live.submitted = now;
        let mut gone = super::super::pending::tests::sample("wf-gone");
        gone.submitted = now - TTL_SECS - EXPIRY_SLACK_SECS - 1;
        std::fs::write(&file, super::super::pending::render_file(&[gone.clone()])).unwrap();
        assert_eq!(
            lists_live(&file, now),
            Ok(false),
            "a run past its TTL is not live"
        );
        std::fs::write(&file, super::super::pending::render_file(&[gone, live])).unwrap();
        assert_eq!(lists_live(&file, now), Ok(true));
        std::fs::write(&file, "not json").unwrap();
        assert!(lists_live(&file, now).is_err());
    }

    pub(in crate::cluster::detached) fn fixture(name: &str) -> String {
        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../greengate/tests/it/fixtures/argo");
        std::fs::read_to_string(dir.join(name)).expect("fixture")
    }

    /// `text` without the whitespace outside strings, so a replacement does
    /// not depend on how the fixture was indented.
    pub(in crate::cluster::detached) fn compact(text: &str) -> String {
        let (mut out, mut in_string, mut escaped) = (String::new(), false, false);
        for c in text.chars() {
            if in_string {
                out.push(c);
                match (escaped, c) {
                    (true, _) => escaped = false,
                    (false, '\\') => escaped = true,
                    (false, '"') => in_string = false,
                    (false, _) => {}
                }
            } else if c == '"' {
                in_string = true;
                out.push(c);
            } else if !c.is_whitespace() {
                out.push(c);
            }
        }
        out
    }

    /// What the cluster answers for `record`: the first live run's pod, made
    /// the pod of task `g0` of the Workflow, and a Workflow in `phase` whose
    /// node for it is in `node_phase`. `tweak` edits the pod's compact text.
    fn list_for(
        record: &Pending,
        phase: &str,
        node_phase: &str,
        tweak: impl Fn(String) -> String,
    ) -> Value {
        let node = node_name(&record.name, "g0");
        let pod = compact(&fixture("pod-succeeded.json"))
            .replace(
                "\"workflows.argoproj.io/node-name\":\"greengate-handrun-pqtbl\"",
                &format!("\"workflows.argoproj.io/node-name\":\"{node}\""),
            )
            .replace(
                "\"workflows.argoproj.io/node-id\":\"greengate-handrun-pqtbl\"",
                "\"workflows.argoproj.io/node-id\":\"node-g0\"",
            )
            .replace("greengate-handrun-pqtbl", &record.name)
            .replace("b8eb52b7-8ede-4c1f-bd94-9ada529eec97", "uid-1")
            .replace("handrun-2", &record.label);
        let wf = format!(
            "{{\"kind\":\"Workflow\",\"metadata\":{{\"name\":\"{}\",\"uid\":\"uid-1\",\
             \"labels\":{{\"greengate.run\":\"{}\"}}}},\"status\":{{\"phase\":\"{phase}\",\
             \"nodes\":{{\"node-g0\":{{\"id\":\"node-g0\",\"name\":\"{node}\",\"type\":\"Pod\",\
             \"templateName\":\"gate-g0\",\"phase\":\"{node_phase}\"}}}}}}}}",
            record.name, record.label
        );
        let list = format!("{{\"kind\":\"List\",\"items\":[{wf},{}]}}", tweak(pod));
        crate::json_read::parse(&list).expect("list json")
    }

    #[test]
    fn a_workflow_phase_is_only_ever_finished_or_not() {
        for (phase, finished) in [
            ("Succeeded", true),
            ("Failed", true),
            ("Error", true),
            ("Running", false),
            ("Pending", false),
            ("", false),
        ] {
            assert_eq!(RecordPhase::parse(phase).finished(), finished, "{phase}");
        }
    }

    /// `main` alone decides: exit 0 is the only pass, whatever else the pod
    /// or the Workflow says.
    #[test]
    fn the_end_of_a_pod_comes_from_main_alone() {
        let ended = |exit, reason: &str| State::Terminated {
            exit: Some(exit),
            reason: reason.into(),
            message: String::new(),
        };
        assert_eq!(end_from_main(&ended(0, "Completed")), JobEnd::Complete);
        assert_eq!(
            end_from_main(&ended(1, "Error")),
            JobEnd::Failed("Error".into())
        );
        assert_eq!(
            end_from_main(&ended(137, "OOMKilled")),
            JobEnd::Failed("OOMKilled".into())
        );
        assert_eq!(end_from_main(&State::Running), JobEnd::Running);
        assert_eq!(end_from_main(&State::Waiting), JobEnd::Running);
        assert_eq!(end_from_main(&State::Absent), JobEnd::Running);
    }

    fn record_of_the_fixture() -> Pending {
        let mut record = sample("greengate-rh-test");
        record.uid = Some("uid-1".into());
        record.label = "label-1".into();
        record.tree = "13b5ee2d54389399fa2738f084a1b653b5844028".into();
        record.source.oid = "7e04624939f8c93f774d570276af8643c61f0320".into();
        record.gates[0].argv = vec!["python3".into(), "scripts/check-module-cycles.py".into()];
        record.gates[0].prepare = None;
        record.gates[0].digest =
            "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c".into();
        record
    }

    fn collected(record: Pending, list: &Value) -> Resolution {
        resolve(record, list, 1_700_000_100)
    }

    /// The first live run, collected: a pass written under the FROZEN token,
    /// and the finished Workflow leaves the file.
    #[test]
    fn the_live_fixture_is_a_pass() {
        let record = record_of_the_fixture();
        let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
        let done = collected(record, &list);
        assert!(done.notes.is_empty(), "{:?}", done.notes);
        assert_eq!(done.passes.len(), 1, "{done:?}");
        assert_eq!(
            done.passes[0].token, "pre-push-lint@abc",
            "the frozen token"
        );
        assert!(done.passes[0].provenance.contains("platform=x86_64-linux"));
        assert!(done.leaves, "a finished Workflow leaves the file");
    }

    /// The node and the Workflow say Succeeded; `main` exited 1. Phases only
    /// say the pod finished.
    #[test]
    fn a_succeeded_node_with_a_failed_main_is_no_pass() {
        let record = record_of_the_fixture();
        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
            p.replacen(
                "\"exitCode\":0,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
                "\"exitCode\":1,\"finishedAt\":\"2026-11-03T04:40:34Z\"",
                1,
            )
        });
        let done = collected(record, &list);
        assert!(done.passes.is_empty(), "{done:?}");
        assert_eq!(done.notes.len(), 1, "{done:?}");
        assert!(done.notes[0].1.contains("exit 1"), "{:?}", done.notes);
    }

    #[test]
    fn a_pod_of_another_workflow_uid_is_not_this_ones() {
        let record = record_of_the_fixture();
        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
            p.replace("\"uid\":\"uid-1\"", "\"uid\":\"uid-other\"")
        });
        let done = collected(record, &list);
        assert!(done.passes.is_empty(), "{done:?}");
    }

    #[test]
    fn a_pod_with_another_image_or_command_is_not_the_submission() {
        for tweak in [
            |p: String| {
                p.replace(
                    "sha256:fa7a661059493955d9590559a3ff62bc956fedd83f41eea739e73d1996797f7c",
                    &format!("sha256:{}", "0".repeat(64)),
                )
            },
            |p: String| p.replace("scripts/check-module-cycles.py", "scripts/other.py"),
            |p: String| {
                p.replace(
                    "tree 13b5ee2d54389399fa2738f084a1b653b5844028",
                    "tree 0000000000000000000000000000000000000000",
                )
            },
        ] {
            let record = record_of_the_fixture();
            let list = list_for(&record, "Succeeded", "Succeeded", tweak);
            let done = collected(record, &list);
            assert!(done.passes.is_empty(), "{done:?}");
            assert_eq!(done.notes.len(), 1, "{done:?}");
        }
    }

    #[test]
    fn a_running_workflow_keeps_its_waiting_gates() {
        let record = record_of_the_fixture();
        let list = list_for(&record, "Running", "Running", |p| {
            // `main` has not terminated: the same state, reopened as running
            p.replace(
                "\"terminated\":{\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
                "\"running\":{\"startedAt\":\"t\",\"containerID\":\"containerd://72683744e4b32662fcdee44e7d5fd846899a8b994145dfc21a07ee4d385f3989\"",
            )
        });
        let done = collected(record, &list);
        assert!(done.passes.is_empty(), "{done:?}");
        assert!(!done.leaves);
        assert_eq!(done.record.gates[0].state, GateState::Waiting);
        assert_eq!(done.record.phase, RecordPhase::Running);
    }

    #[test]
    fn a_workflow_gone_after_its_ttl_drops_the_record_with_one_note() {
        let record = record_of_the_fixture();
        let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
        let done = collected(record, &empty);
        assert!(done.leaves);
        assert_eq!(done.record.phase, RecordPhase::Gone);
        assert_eq!(done.record.phase.plain(), "gone (TTL passed or deleted)");
        assert_eq!(done.notes.len(), 1, "{done:?}");
    }

    /// A create whose answer was lost: no Workflow yet, so the intent stays
    /// for a while, and goes once the grace has passed.
    #[test]
    fn an_intent_with_no_workflow_waits_then_goes() {
        let mut record = record_of_the_fixture();
        record.uid = None;
        let empty = crate::json_read::parse("{\"kind\":\"List\",\"items\":[]}").expect("json");
        let young = resolve(record.clone(), &empty, record.submitted + 60);
        assert!(!young.leaves);
        let old = resolve(
            record.clone(),
            &empty,
            record.submitted + INTENT_GRACE_SECS + 1,
        );
        assert!(old.leaves);
        assert_eq!(old.notes.len(), 1);
    }

    /// The Workflow finished and passed, but the token cannot be written: the
    /// record stays, its gate waiting, and the next collect writes the token.
    #[test]
    fn a_pass_whose_token_cannot_be_written_keeps_the_record() {
        let record = record_of_the_fixture();
        let list = list_for(&record, "Succeeded", "Succeeded", |p| p);
        let refuse = |_: &Pass| Err(Fallback::NotProved("git refused".into()));
        let first = settle_with(resolve(record.clone(), &list, 1_700_000_100), refuse, None);
        assert_eq!(first.written, 0);
        assert!(
            first.settled.is_none(),
            "the run has not ended for the person"
        );
        let kept = first.record.expect("the record survives");
        assert_eq!(kept.gates[0].state, GateState::Waiting);

        let mut tokens = Vec::new();
        let second = settle_with(
            resolve(kept, &list, 1_700_000_200),
            |pass| {
                tokens.push(pass.token.clone());
                Ok(())
            },
            None,
        );
        assert_eq!(second.written, 1);
        assert_eq!(tokens, ["pre-push-lint@abc"]);
        assert!(second.record.is_none());
        let ended = second.settled.expect("now it ends");
        assert_eq!(ended.passed, ["pre-push-lint"]);
    }

    /// A finished Workflow whose pod status cannot be read fails the gate.
    #[test]
    fn an_unreadable_pod_status_on_a_finished_workflow_fails_the_gate() {
        let record = record_of_the_fixture();
        let list = list_for(&record, "Failed", "Failed", |p| {
            p.replace(
                "\"name\":\"greengate-rh-test\",\"namespace\"",
                "\"namex\":\"greengate-rh-test\",\"namespace\"",
            )
        });
        let done = collected(record, &list);
        assert!(done.passes.is_empty());
        assert_eq!(done.notes.len(), 1, "{done:?}");
        assert!(
            done.notes[0].1.contains("status cannot be read"),
            "{done:?}"
        );
    }

    /// A pod that does not name its node cannot be bound to the Workflow's.
    #[test]
    fn a_pod_without_a_node_id_is_not_bound() {
        let record = record_of_the_fixture();
        let list = list_for(&record, "Succeeded", "Succeeded", |p| {
            p.replace(
                "workflows.argoproj.io/node-id",
                "workflows.argoproj.io/node-idx",
            )
        });
        let done = collected(record, &list);
        assert!(done.passes.is_empty(), "{done:?}");
    }

    #[test]
    fn a_record_older_than_the_ttl_expires_whatever_the_cluster_says() {
        let record = record_of_the_fixture();
        assert!(!is_expired(&record, record.submitted + TTL_SECS));
        assert!(is_expired(
            &record,
            record.submitted + TTL_SECS + EXPIRY_SLACK_SECS + 1
        ));
    }
}