Repository navigation
Expand file tree
/
Copy pathexecute.mjs
More file actions
3089 lines (2952 loc) · 299 KB
/
Copy pathexecute.mjs
File metadata and controls
3089 lines (2952 loc) · 299 KB
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
#!/usr/bin/env node
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* fleet-write/execute — the relay's executor: the writes a validated payload
* asked for, in order, as the fleet App, on a GitHub Actions runner.
*
* GITHUB_EVENT_PATH=event.json FLEET_WRITE_SENDER=login GITHUB_TOKEN=… node scripts/pm/fleet-write/execute.mjs # client_payload from the event file
* node scripts/pm/fleet-write/execute.mjs --payload-file payload.json # the same, payload from disk
* node scripts/pm/fleet-write/execute.mjs --self-test # offline: a fake platform, no network
*
* ## Where this runs, and what it holds
*
* `.github/workflows/fleet-write.yml` runs this as its last step, after the
* validator refused nothing and `actions/create-github-app-token` minted an
* installation token narrowed to `payload.repo` — plus, for a `transfer`
* stroke alone, the transfer's one target (`tokenRepositoriesOf` in
* `validate.mjs`) — and to `PERMISSIONS` (`ops.mjs`). That token arrives in `GITHUB_TOKEN`, from the environment
* only: it is never printed, never written to a file, never placed in an
* argument; every string this file emits is scrubbed of it, and the runner's
* own secret masking is the second net, not the first. The App's private key
* never reaches this process at all — the mint is the action's.
*
* ## The sender gate — authorization comes from the TARGET repo
*
* `github.event.sender.login` is the login GitHub resolved from the token that
* sent the dispatch. Before the first write this file asks the target repo
* what that login may do there — `GET /repos/{repo}/collaborators/{login}/permission`
* — and refuses unless the answer is `write`, `maintain` or `admin`
* (GitHub folds `maintain` into `permission: write`; `role_name` carries the
* exact role, and both are read). A refusal is a run failure with zero writes.
* There is no sender allowlist: GitHub's write permission on the target IS
* the authorization, so a seat that can push to a repo can write to it as the
* fleet, and one that cannot, cannot — whichever repo the dispatch landed on.
* The gate runs on EVERY repository the token reaches: a transfer stroke is
* refused unless the sender holds write on the source AND the target, the
* same pair GitHub itself requires of a person who transfers a card.
*
* ## The run
*
* Every action is validated AGAIN here (defence in depth: the executor trusts
* the validator's rule, not the step that ran it), then its requests are
* issued in order with the App token: REST calls straight from the op table;
* the pull-request GraphQL ops resolve the pull's node id with one GET first,
* and land only when the answer's `pullRequest` SHOWS the state the op table
* declares for them (`PR_LANDED_STATE` in `ops.mjs`) — a 200 with `data` and
* no `errors` whose pull is not in that state is a FAILED action naming what
* the answer showed, exactly as a REST 4xx is; a `transfer` reads the issue (refusing a pull request, or a card that no
* longer answers from the source — already moved) and the target repository,
* then sends `transferIssue` with both node ids and accepts only an answer
* that places the card on the target. A transfer that fails prints the
* installation remedy `transferRemedy` spells, in the log and the summary.
* A `workflow_dispatch` is one POST the platform answers 204 to with no body,
* carrying the inputs the op table closes for that file and nothing else
* (`WORKFLOW_DISPATCH_INPUTS`: none for the shard-timings refresh,
* `refresh_version_pr: "true"` alone for `release.yml`, its bookkeeping lane)
* — its row reads `accepted`; the run it started is read back by the SEAT
* (`dispatch.mjs`), never here, because the answer carries no run id, and the
* token that request spends `actions: write` on reaches that path and the
* failed-jobs re-run below, and no other (`ops.mjs`, `REFUSED_PATH_FAMILIES`).
* A `run_rerun_failed` is fenced on the run and read back HERE (the section
* of that name below).
* The FIRST failure stops the run — later actions are NOT attempted, and the
* summary says which — because a seat that dispatched five related writes
* must be able to read exactly where the board was left. A 404 on a directed
* label DELETE is the label already being gone: idempotent success, the same
* reading `label-write.mjs` takes.
*
* Every write goes through `write-pace.mjs` like every other fleet write: the
* gap between two writes and the back-off marker a platform refusal writes
* apply on the runner too (the runner's own home holds the log; nothing is
* shared with a seat container, and the twenty-action cap bounds the run).
* No egress proxy stands in front of the runner, so the throttle reads none
* of its answers as the proxy's (`proxyAnswered`, `write-pace.mjs`): a 403
* here is GitHub's and takes the platform back-off path.
*
* ## Rule ⑤ on the runner — the executor announces the batch
*
* That log is fresh on every run and nothing reaches it from the seat, so a
* seat's `--announce-batch` never applies here: left to rule ① alone, a stroke
* of fifteen `issue_create` actions landed fifteen cards 3 s apart — 42 s from
* one identity, the burst rule ⑤ exists to prevent. This file holds the whole
* stroke, so it announces the batch itself: after the sender gate and before
* the first write, a stroke carrying `DEFAULT_BATCH_THRESHOLD` or more
* content-creating actions (`CONTENT_CREATING_OPS`, read off the op table in
* `dispatch.mjs`) gets ONE `announceBatch` (kind `BATCH_KIND`) for its writes
* from the first through the last content-creating one (`strokePacing`), so
* each of those leaves `DEFAULT_BATCH_GAP_MS` after the one before; below the
* threshold rule ①'s gap is unchanged. The transcript and the summary say so
* in one line (`batchAnnouncedText`). Two refusals guard it, both before the
* first write:
*
* - a stroke whose pacing the relay job cannot hold — its `timeout-minutes`
* less the allowance an ordinary stroke has — is REFUSED with zero writes
* (exit 2, `strokeBudgetRefusal`), exactly as the packer refuses it at the
* seat (`dispatch.mjs`, its batch-gap section): run anyway, it could
* outlive the job, which the platform cancels mid-stroke with no summary.
* ⛔ Never a shorter gap instead;
* - an announcement the pace log cannot record is REFUSED (exit 10), the way
* `paceWrite` refuses an unrecordable write: unpaced is the state the
* throttle exists to prevent.
*
* ## The base sync — `pr_update_branch`, confirmed by MEASURE
*
* `PUT /repos/{repo}/pulls/{n}/update-branch` answers 202 "Updating pull
* request branch." and merges asynchronously, so the answer is an acceptance,
* not a landing. `confirmUpdateBranch` therefore polls `GET /pulls/{n}` every
* `UPDATE_BRANCH_POLL_MS` for up to `UPDATE_BRANCH_WINDOW_MS` until the head
* is no longer `expected_head_sha`, then reads `GET /repos/{repo}/commits/{sha}`
* and prints old → new head with the merge commit's author as the platform
* names it — the fleet-identity reading this op exists for, in the row and the
* summary, so every real sync measures it. A window that expires is a FAILED
* action whose sentence says UNCONFIRMED (the merge may still land; read the
* pull, ⛔ never re-send), and the stroke stops there: a `pr_ready` queued
* behind the sync never runs on an unconfirmed head.
*
* A 422 is two different things, and its sentence is never the judge — the
* executor MEASURES: it re-reads the pull (a head that is no longer the
* expected sha is a FAILED action naming both — the platform's "expected head
* sha didn't match"), then `GET /repos/{repo}/compare/{base}...{head}`:
* `behind_by` 0 means there was nothing to merge and the action LANDED as a
* no-op, the row saying so and quoting the platform; anything else — a head
* still behind its base, so the platform refused (an enqueued pull's "cannot
* update" answer is read here, as a FAILED row), or a measure that could not
* be read — is FAILED with the platform's sentence, never a no-op by default.
* Any other status is FAILED as every REST 4xx is. The PUT is paced like
* every other write verb.
*
* ## The failed-jobs re-run — `run_rerun_failed`, fenced on the RUN and read back
*
* The five fences on the run and its pull (`RERUN_FAILED_FENCES` in
* `ops.mjs`: the workflow, the event, once, failed, the head) are facts about
* the run, so this file is where they are AUTHORITATIVE
* (`rerunFailedPreflight`). It first reads the job list of the run's attempt
* 1, which is the read-back's baseline: the names of the jobs that concluded
* `failure`. It then reads `GET /repos/{repo}/actions/runs/{run_id}` and, for
* the pull the run names (`pull_requests[0].number`), that pull's own
* `GET /repos/{repo}/pulls/{n}` — the last two requests before the POST — and
* judges the five fences on those answers. The head fence compares the run's
* `head_sha` with the pull's CURRENT head from that GET, never with the copy
* the run embeds, and a run naming no pull is refused by name without a pull
* read. A run or pull that could not be read, a fence that fails (every
* failing one named, with what was read), a baseline that could not be read
* whole, or a baseline with no failed job stops the action with the POST NOT
* SENT: its row says `not sent`, zero writes, exit 5. A run re-run, or a pull
* pushed to, by anyone between the seat's request and these reads is refused
* here. ⛔ The seat wrapper's earlier check is advisory and is never trusted
* in place of this one.
*
* The POST answers 201 with an empty body, which is an acceptance, not a
* landing. `confirmRerunFailed` re-reads the run every `RERUN_FAILED_POLL_MS`
* for up to `RERUN_FAILED_WINDOW_MS` until it shows `run_attempt` 2, then
* reads attempt 2's job list and lands only on `rerunFailedReadBack`
* (`ops.mjs`): every baseline job listed there is `queued` or
* `in_progress`, at least one is, and the row names the new attempt and
* those job ids. A baseline job not listed yet is named on the row, because
* a job is listed when its needs finish. A failed job listed `completed` in
* attempt 2 is a FAILED action. A window that never shows attempt 2, or that
* never settles, is a FAILED action whose sentence says UNCONFIRMED: the
* re-run may still start, so read the run and ⛔ never re-send. A re-send
* would meet attempt 2 at the `once` fence anyway, and be refused there with
* zero writes. Every read is an unpaced GET, and the one write is paced like
* every write verb.
*
* ## The hierarchy link — `sub_issue_add` / `sub_issue_remove`, fenced on the CARDS and read back
*
* The fences on the two cards (`SUB_ISSUE_FENCES` in `ops.mjs`: parent,
* child, and free for an add or listed for a remove) are facts about the
* board, so this file is where they are AUTHORITATIVE (`subIssuePreflight`):
* it reads the parent's and the child's own `GET /repos/{repo}/issues/{n}`,
* then — only when both pass — the child's `GET …/issues/{child}/parent` for
* an add, or the parent's sub-issue list (`readSubIssues`: every page at the
* endpoint's maximum, to a cap; a walk past the cap is a truncated SUBSET and
* never read as absent) for a remove, and judges every fence on those
* answers. A fence that fails — every failing one named, with what was read —
* stops the action with the write NOT SENT: its row says `not sent`, zero
* writes, exit 5. The body the write carries is `{ sub_issue_id }`, the id
* the CHILD's own answer gave, ⛔ never a number and never `replace_parent`.
*
* An add whose child already answers to THIS parent sends nothing: it is a
* measured no-op, landed only when the parent's list reads the child back
* (row status `not sent`, its result saying `no-op`). Every other write's
* answer — 201 for the add, 200 for the remove — is an acceptance, not a
* landing: `confirmSubIssue` re-reads the parent's list every
* `SUB_ISSUE_POLL_MS` for up to `SUB_ISSUE_WINDOW_MS` and lands the action
* only on `subIssueReadBack` (`ops.mjs`): the list lists the child's id
* (add) or no longer does (remove). A non-2xx answer is a FAILED action with
* the platform's sentence and nothing read back; a list that never settles,
* or never reads whole, is a FAILED action whose sentence says UNCONFIRMED:
* read the parent and ⛔ never re-send. Every read is an unpaced GET, and the
* one write is paced like every write verb.
*
* ## The mailbox branch delete — `mailbox_branch_delete`
*
* Its fences and its landing are listed once, in `ops.mjs`'s header ("The one
* row that deletes a ref"); they are AUTHORITATIVE here, each that fails named.
*
* ## The advisory rows that write — fenced on the ADVISORY, printing none of its text
*
* `ops.mjs`'s header section "The rows that write a security advisory"
* is the authority, and its "The one row that READS an advisory" for the read
* below; this is where their fences and landings are measured.
*
* - `advisory_report` is ONE POST of the row's body to the private-report
* endpoint, and nothing is read first. It LANDS on a 2xx whose answer
* carries a `ghsa_id` in its shape (`advisoryReportReadBack`): the row
* names that id and the state, and a notice annotation names the id
* (`relayAdvisoryAnnotationMessage`, `dispatch.mjs`), so the seat follows
* with `advisory_collaborators_add`. A 2xx without an id is a FAILED
* action whose sentence says UNCONFIRMED — a report may have been filed,
* so ⛔ never re-sent.
* - `advisory_create` is the same shape: ONE POST of the row's body to the
* bare collection, nothing read first, LANDED on a 2xx whose answer
* carries a `ghsa_id` and reads state `draft` (`advisoryCreateReadBack`),
* its row (`advisoryCreateLandedText`) and annotation naming the id. A 2xx
* without an id is UNCONFIRMED, one in another state FAILED: neither is
* ever re-sent.
* - `advisory_collaborators_add`, `advisory_versions` and `advisory_state`
* are fenced HERE, where the fences are AUTHORITATIVE
* (`advisoryPreflight`): the executor reads
* `GET /repos/{repo}/security-advisories/{ghsa_id}`, the last request
* before the PATCH, and judges `ADVISORY_FENCES` on that answer — a read
* that is not a 200 advisory, an answer naming another advisory, a state
* the action may not act in (`triage` / `draft` for the collaborators;
* `draft` for the versions; `ADVISORY_TRANSITIONS` for a state change:
* `draft` from `triage` or `closed`, `closed` from `triage` or `draft`,
* `published` from `draft` alone, a target the table does not name from
* nothing), a list the versions may not replace whole, or a publish whose
* versions are not set (the `versions` fence) stops the action with the
* PATCH NOT SENT: its row says `not sent`, zero writes, exit 5.
* The collaborators' logins are merged case-insensitively
* (`advisoryCollaboratorPlan`): when every login asked for is already a
* collaborator nothing is sent, the row `not sent` and its result saying
* `no-op`, exit 0. Otherwise the ONE PATCH carries exactly
* `{ collaborating_users }` — the existing logins as the advisory listed
* them, then the missing ones — or exactly `{ state }`, the one asked for —
* or, for the versions, the table's `{ vulnerabilities }`, the entries alone.
* The action LANDS only on its own answer (`confirmAdvisory`): every login
* sent listed (`advisoryReadBack`), exactly the entries sent listed on a
* draft (`advisoryVersionsReadBack`), or the state asked for shown
* (`advisoryStateReadBack`) — a publish only when its answer also lists
* exactly the entries its GET read, and then, alone of this row's
* landings, with a notice annotation naming the id
* (`relayAdvisoryAnnotationMessage`, `dispatch.mjs`), public once
* published. A non-2xx is a FAILED action carrying its
* cause and then `ADVISORY_ACCESS_REMEDY`; a 2xx that does not show the
* result is a FAILED action naming what it shows.
*
* ⛔ The payload reaches this file through the event file (`readEventPayload`,
* `validate.mjs`), never through `env:`, and the text this path prints — row,
* log line, step summary, annotation — is built from the advisory's id, its
* state, its collaborators' logins and counts ALONE (`advisoryReportLandedText`, `advisoryCreateLandedText`,
* `advisoryLandedText`, `advisoryVersionsLandedText`, `advisoryStateLandedText`, `advisoryFenceText`, each
* value in its own shape through `advisoryPrintable`), plus, on a refusal,
* its CAUSE (`advisoryRefusalCause`): the platform's `message` and
* `documentation_url` from the refusal's own answer — each capped
* (`ADVISORY_REFUSAL_MESSAGE_CAP`, `ADVISORY_REFUSAL_URL_CAP`) and flattened to
* one table-safe line, never its `errors` or the rest of its body — so the
* reading a seat puts to the maintainer carries the reason, whatever message
* the platform chose. A message or a URL that reproduces any prose of the
* payload or of the advisory the preflight read (`advisoryProseOf`, a
* 16-character window) is WITHHELD and the row says so. `resultOf`,
* which reads an answer's `html_url`, never sees an advisory's answer. The
* self-test files a report and a draft and serves advisories carrying a marker in
* their summary, description and vulnerabilities and in every other field, and finds
* it in no line this file emits; its ablation is recorded in the PR that
* landed this. The GET is an unpaced read; the POST and the PATCH are paced
* like every write verb.
*
* ## The read — `advisory_read`, sealed before anything leaves (`advisoryReadAction`)
*
* ONE `GET /repos/{repo}/security-advisories/{ghsa_id}`, nothing written. A
* GET that never reached the platform (the call threw: `rest`'s status 0) is a
* FAILED action with `ADVISORY_READ_UNREACHED` and the row status
* `not reached` — no HTTP status, no grant remedy, ⛔ never the exception's
* message. On an answer, the executor judges `ADVISORY_READ_FENCES` on it — a 200 advisory, the
* one the action names, and a row whose `senderGate` the table knows
* (`target-write`, by the maintainer's ruling `ops.mjs` records: the sender
* gate this stroke already passed before the GET; any other value closed) —
* and on any failure seals nothing and emits nothing: a FAILED action, exit 5,
* whose row names the fences and the status alone. Otherwise it seals
* `ADVISORY_READ_FIELDS` of the answer to the action's `public_key`
* (`advisoryReadPlaintext`, `sealAdvisoryRead`, bound to the request id, the
* action's index and the id) and emits the sealed answer as notice parts
* (`advisoryReadParts`, `relayAdvisoryReadAnnotationMessage`) — the ONE
* channel back, the one a seat container can read. A seal that throws is a
* FAILED action with `ADVISORY_READ_SEAL_FAILED`, ⛔ never the exception's
* message, and no part; one too large for the run's ten notices is a FAILED
* action naming its counts, and no part. It LANDS only on a 200 whose fences
* hold and whose seal succeeded and fit.
*
* ⛔ What this path prints — the row, the log line, the step summary — is the
* HTTP status, the counts and `advisoryReadCall`, the call with the id left
* out. Never the id, the state, the platform's message unless
* `ADVISORY_PLATFORM_MESSAGES` names it, or any field of the answer; the
* notices carry the ciphertext alone. The self-test serves the marker in the
* summary, the description and the vulnerabilities and finds it in no line,
* row, summary or annotation, nor in the sealed answer's bytes, and opens the
* parts back to the GET's fields byte for byte; the ablation is recorded in
* the pull request that landed this.
*
* ## The assignees and labels legs — `pr_create` with `assignees` / `labels`, the requests that read an earlier answer
*
* The op table spells each leg's path with a placeholder and `fromAnswer:
* 'number'` (`ops.mjs`, its header). Within one action the requests run in
* order and the FIRST answer — the create's — is kept; a descriptor carrying
* `fromAnswer` is filled from that answer, ⛔ never from a later leg's
* (the assignee POST answers the issue object, which happens to carry a
* number, and the label POST answers an array, which carries none; neither
* is the create) — `fillFromAnswer`: the field must be a positive integer,
* and the path is the placeholder replaced by it, so the pull the assignee
* or label lands on is the one the platform answered, ⛔ never one the
* request named. An answer without it is a FAILED action with the leg NOT
* SENT — its row says so, status `not sent` — and the stroke stops there as
* on any failure. Each leg's landing is judged by its answer against what
* was sent (`requestLanded`): the assignee leg's `assignees` against
* `assigned` — GitHub documents a login the caller cannot apply as "silently
* ignored", the 201 still answered; the label leg's answer, the pull's whole
* label set, against `labelled` — a name sent and not listed did not land.
* An answer listing fewer than sent is a FAILED action naming the missing
* login or name, never a quiet partial; MORE than sent is not judged (the
* Auto Label workflow writes `documentation` and `size/*` on open, additively,
* so both sets land). The row prints the assignees, or the labels, as the
* platform lists them (`resultOf`). Both legs are paced like every other
* write verb.
*
* ## The governed-review follow-up — after `pr_ready`, ⛔ never after `pr_create`
*
* Once a `governedReview` row's own requests have landed (`GOVERNED_REVIEW_OPS`
* in `ops.mjs`, its header section of this name: `pr_ready` alone, at the pull
* the action names — the draft open summons nobody, because a human is asked
* only at the seat's hand-off, `pr_request_reviewers` after its `## 席位核对`
* ACCEPT and a same-head `## Contract review` PASS, so a `pr_create` is the
* create plus the legs the caller spelled and nothing reads the pull's files
* there), `requestGovernedReview` reads the pull's file list in
* full (`readPullFiles`: every page, a cap that reds as a truncated subset) and
* hands the paths to `governedReviewPlan`, a pure function over the register:
* `governedPathsIn` scoped to `payload.repo` through `repoIdForSlug`, then
* `landingTierOf` over the matched slice — a Tier H hit is the only answer that
* sends anything; a Tier S or ungoverned diff, or a target outside
* `GOVERNED_REPOS`, is ONE row saying so and zero writes. On a Tier H hit it
* reads the pull (its author, pending `requested_reviewers`, `assignees`) and
* its submitted reviews, and the plan is the `GOVERNED_APPROVERS` accounts
* NOT in that union — requested, assigned or reviewed, the coverage the H43
* patrol reads — so a re-run, a `pr_ready` after the seat's hand-off, or the
* platform's own CODEOWNERS request landing first costs no write. The pull's
* own author is never requested (GitHub answers 422) — a missing approver
* who IS the author is ASSIGNED instead, the documented fallback. The writes
* are what `governedReviewRequests` spells, judged by `requestLanded` as the
* legs above are (`requested` against the pull's pending requests, `assigned`
* against its assignees), one row each, paced like every write verb. An
* unreadable file list, pull or review list, a truncated walk, or a refused
* write is a FAILED action — the pull is open or ready, the row says what was
* not sent, and the stroke stops there as on any failure: silence here is the
* defect this follow-up exists to close, so it is never a quiet skip.
*
* ## The step summary — what a person reads back
*
* `$GITHUB_STEP_SUMMARY` gets one table per run: request id · sender and its
* role · session · target, then one row per request — op, endpoint, HTTP
* status, and the resulting id / url — and a last line saying how many landed
* or where it stopped. Text is passed through unchanged: attribution stays
* the session id inside the text, per protocol.
*
* ## The annotations — the numbers a seat CAN read
*
* A seat container reads neither this job's log (the endpoint answers 302 to
* blob storage its egress proxy refuses) nor its step summary (the check
* run's `output.summary` is null), but it does read the check run's
* annotations. So for every action whose op creates or moves a card
* (`ANNOTATED_OPS` in `dispatch.mjs`) and whose request LANDED, this file
* prints ONE workflow command to stdout — a `notice` titled
* `fleet-write <op>` whose message `relayAnnotationMessage` spells as
* `fleet-write action=<i> op=<op> number=<n> url=<url>` — and the runner turns
* it into an annotation. The number and url are read from the platform's
* ANSWER to that request (`ANNOTATION_ANSWERS`: the created issue's
* `number` / `html_url`, the `transferIssue` answer's `issue.number` /
* `issue.url`), ⛔ never from the request; an answer that carries neither, or
* a message `parseRelayAnnotation` would not read back as exactly this
* number, url and landing repository, emits nothing and says so — the
* reader's fallback then finds the card. No other op emits one. The
* platform keeps 10 notice annotations per step and 50 per job and drops the
* rest without a word (actions/toolkit `docs/problem-matchers.md`), so a
* stroke past ten such ops names only its first ten; `dispatch.mjs`'s header
* section of the same name is the reader's half. The message is escaped the
* way actions/toolkit `command.ts` escapes a command's data and properties.
*
* ## Exit codes — capture them BEFORE any pipe
*
* 0 every action landed.
* 2 the payload was refused (the reasons are printed and summarised) — or the
* stroke's rule ⑤ pacing is over the relay job's budget; zero writes.
* 3 PREREQUISITE NOT MET — no token, no sender, the permission read did
* not answer, or the platform was unreachable; zero writes.
* 4 the sender is not authorized on the target repo; zero writes.
* 5 an action FAILED; the summary names it and which earlier ones landed —
* a `run_rerun_failed` refused at a fence among them, its POST not sent,
* and an `advisory_collaborators_add`, `advisory_versions` or
* `advisory_state` refused at a fence, its PATCH not sent, and an `advisory_read` refused at a fence,
* whose seal failed or did not fit — nothing of it emitted.
* 10 the write throttle refused (its prescription was printed), or a stroke's
* rule ⑤ batch could not be recorded; zero writes in that second case.
*/
import { appendFileSync, readFileSync } from 'node:fs';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { isEntrypoint } from '../../invoked-as.mjs';
// The register and the approver list, READ — never restated here (the ops.mjs header, "The governed-review follow-up").
import { GOVERNED_TIER_H, GOVERNED_TIER_S, governedPathsIn, landingTierOf, pullPathsFrom, repoIdForSlug } from '../check-governed-merges.mjs';
import { GOVERNED_APPROVERS } from '../check-governed-queue-guard.mjs';
import { scrub } from '../fleet-token.mjs';
import { classifyHttp } from '../label-write.mjs';
import { announceBatch, EXIT_WRITE_PACE_REFUSED, fmtDuration, isWriteMethod, noteResponse, paceFilePath, paceWrite, releaseWriteLease, unrecordableText } from '../write-pace.mjs';
import {
ADVISORY_ANNOTATED_OPS,
ADVISORY_PUBLISH_OP,
ADVISORY_READ_OPS,
ANNOTATED_OPS,
parseRelayAdvisoryAnnotation,
parseRelayAdvisoryReadAnnotation,
parseRelayAnnotation,
RELAY_ANNOTATION_PREFIX,
relayAdvisoryAnnotationMessage,
relayAdvisoryReadAnnotationMessage,
relayAnnotationMessage,
strokeBudgetRefusal,
strokePacing,
} from './dispatch.mjs';
import {
ADVISORY_ACCESS_REMEDY,
ADVISORY_OPEN_STATES,
ADVISORY_READ_ACCESS_REMEDY,
ADVISORY_READ_FIELDS,
ADVISORY_READ_SEAL_FAILED,
ADVISORY_READ_UNREACHED,
ADVISORY_READ_UNREACHED_STATUS,
advisoryReadAad,
advisoryReadCall,
advisoryReadFenceFailures,
advisoryReadFenceText,
advisoryReadLandedText,
advisoryReadOverCapText,
advisoryReadParts,
advisoryReadPlaintext,
openAdvisoryRead,
sealAdvisoryRead,
ADVISORY_STATE_SHAPE,
ADVISORY_TRANSITIONS,
ADVISORY_PUBLISHED_STATE,
ADVISORY_VERSIONS_STATES,
advisoryVersionsLandedText,
advisoryVersionsOf,
advisoryVersionsOnTheWire,
advisoryVersionsReadBack,
GHSA_ID_SHAPE,
advisoryCollaboratorLogins,
advisoryCollaboratorPlan,
advisoryCreateLandedText,
advisoryCreateReadBack,
advisoryFenceFailures,
advisoryFenceText,
advisoryLandedText,
advisoryPlatformText,
advisoryReadBack,
advisoryReportLandedText,
advisoryReportReadBack,
advisoryStateLandedText,
advisoryStateReadBack,
GOVERNED_REVIEW_FILES_PAGE_CAP,
GOVERNED_REVIEW_FILES_PAGE_SIZE,
GOVERNED_REVIEW_OPS,
LOGIN_SHAPE,
MAILBOX_LABEL,
OPS,
PERMISSIONS,
PR_LANDED_STATE,
RERUN_FAILED_ATTEMPT,
answerPlaceholder,
failedJobNames,
governedReviewRequests,
rerunFailedFenceFailures,
rerunFailedFenceText,
rerunFailedLandedText,
rerunFailedPullNumber,
rerunFailedReadBack,
subIssueAlreadyHere,
subIssueCardFailure,
subIssueFenceFailures,
subIssueFenceText,
subIssueLandedText,
subIssueReadBack,
transferRemedy,
} from './ops.mjs';
import { EVENT_PATH_ENV, readEventPayload, refusalText, tokenRepositoriesOf, validatePayload } from './validate.mjs';
const SELF_PATH = fileURLToPath(import.meta.url);
const DEFAULT_API = 'https://api.github.com';
export const EXIT_OK = 0;
export const EXIT_REFUSED = 2;
export const EXIT_PREREQUISITE = 3;
export const EXIT_SENDER_REFUSED = 4;
export const EXIT_ACTION_FAILED = 5;
/** The environment variable the workflow hands `github.event.sender.login` through. */
export const SENDER_ENV = 'FLEET_WRITE_SENDER';
/** The `kind` a stroke's rule ⑤ announcement is recorded under in the runner's pace log (header). */
export const BATCH_KIND = 'fleet-write stroke';
/** The roles that carry write permission on the target — GitHub's legacy base roles plus the exact role names. */
export const ALLOWED_PERMISSIONS = Object.freeze(['admin', 'write']);
export const ALLOWED_ROLE_NAMES = Object.freeze(['admin', 'maintain', 'write']);
// ---------------------------------------------------------------------------
// Pure core
// ---------------------------------------------------------------------------
/**
* What the permission read means. `verdict` is one of:
* `allowed` — write, maintain or admin; `role` names it;
* `refused` — a lesser role, or not a collaborator at all (404);
* `prerequisite` — the read did not answer (route, credential, 5xx).
*/
export function senderVerdict({ status, json } = {}) {
if (status === 200 && json && typeof json === 'object') {
const permission = typeof json.permission === 'string' ? json.permission : '';
const roleName = typeof json.role_name === 'string' ? json.role_name : '';
const allowed = ALLOWED_PERMISSIONS.includes(permission) || ALLOWED_ROLE_NAMES.includes(roleName);
return { verdict: allowed ? 'allowed' : 'refused', role: roleName || permission || 'none', permission, roleName };
}
if (status === 404) return { verdict: 'refused', role: 'not a collaborator', permission: '', roleName: '' };
return { verdict: 'prerequisite', role: '', permission: '', roleName: '' };
}
/** `owner/name` from an issue's `repository_url`, or null — where the card answers from NOW. */
export function repoOfIssue(json) {
const m = /\/repos\/([^/]+\/[^/]+)$/.exec(String(json?.repository_url ?? ''));
return m ? m[1] : null;
}
/**
* Did this answer land the request? A 404 on a directed label DELETE is the label already being gone.
* A pull-request mutation lands only when its answer SHOWS the state the op table declares for it
* (`PR_LANDED_STATE`, carried on the descriptor as `landed`) — a 200 with `data` and no `errors` is
* the platform accepting the request, not the pull being in that state.
*/
export function requestLanded(req, { status, json } = {}) {
if (req.graphql) {
if (status !== 200 || !json || typeof json !== 'object') return { ok: false, why: `HTTP ${status}` };
if (Array.isArray(json.errors) && json.errors.length) return { ok: false, why: `GraphQL: ${json.errors.map((e) => e?.message ?? 'error').join('; ')}` };
if (!json.data) return { ok: false, why: 'GraphQL: no data' };
if (req.graphql.target_repo !== undefined) {
// A transfer lands only when the answer places the card on the target.
const moved = json.data[req.graphql.mutation]?.issue;
const where = moved?.repository?.nameWithOwner;
if (!moved || !Number.isInteger(moved.number)) return { ok: false, why: 'GraphQL: the answer carries no transferred issue' };
if (String(where ?? '').toLowerCase() !== req.graphql.target_repo.toLowerCase()) return { ok: false, why: `GraphQL: the answer places the issue on ${where ?? 'no repository'}, not ${req.graphql.target_repo}` };
}
if (req.graphql.pull !== undefined) {
const landed = req.graphql.landed;
if (!landed || typeof landed.holds !== 'function') return { ok: false, why: `the op table declares no landed state for ${req.graphql.mutation}, so its answer cannot be judged — a 200 alone is not a landing` };
const pr = json.data[req.graphql.mutation]?.pullRequest;
if (!pr || typeof pr !== 'object') return { ok: false, why: 'GraphQL: the answer carries no pullRequest' };
if (!landed.holds(pr)) return { ok: false, why: `GraphQL: HTTP 200 with no errors, but the answer shows ${pullStateText(pr)} — the op asked for ${landed.wants}` };
}
return { ok: true, why: '' };
}
if (status >= 200 && status < 300) {
// The assignees leg (header): a 2xx whose answer lists fewer logins than sent is a FAILED action, never a quiet partial.
if (Array.isArray(req.assigned)) {
const listed = assigneeLogins(json);
const missing = req.assigned.filter((login) => !listed.some((l) => l.toLowerCase() === login.toLowerCase()));
if (missing.length) {
return { ok: false, why: `HTTP ${status}, but the answer lists ${listed.length ? listed.join(', ') : 'no assignees'} — ${missing.join(', ')} not assigned (GitHub ignores a login the repository cannot assign without a word: it must be a collaborator the repository can assign)` };
}
}
// The governed-review request (header): the answer is the pull with its PENDING requests; a login sent and not listed did not land.
if (Array.isArray(req.requested)) {
const listed = reviewerLogins(json);
const missing = req.requested.filter((login) => !listed.some((l) => l.toLowerCase() === login.toLowerCase()));
if (missing.length) {
return { ok: false, why: `HTTP ${status}, but the answer lists ${listed.length ? listed.join(', ') : 'no requested reviewers'} — ${missing.join(', ')} not requested (the endpoint answers the pull with its pending review requests, so a login it lacks was not written; read the pull on the board before anything else)` };
}
}
// The labels leg (header): the answer is the pull's whole label set; a name sent and not listed did not land.
if (Array.isArray(req.labelled)) {
const listed = labelNames(json);
const missing = req.labelled.filter((name) => !listed.some((l) => l.toLowerCase() === name.toLowerCase()));
if (missing.length) {
return { ok: false, why: `HTTP ${status}, but the answer lists ${listed.length ? listed.join(', ') : 'no labels'} — ${missing.join(', ')} not applied (the labels endpoint answers the pull's whole label set, so a name it lacks was not written; read the pull on the board before anything else)` };
}
}
return { ok: true, why: '' };
}
if (status === 404 && req.idempotent404) return { ok: true, why: 'already absent', idempotent: true };
return { ok: false, why: `HTTP ${status}${typeof json?.message === 'string' ? ` — ${json.message}` : ''}` };
}
/** The logins an issue or pull answer lists as assigned, in the platform's order; `[]` when it lists none. Pure. */
export function assigneeLogins(json) {
return Array.isArray(json?.assignees) ? json.assignees.map((u) => (typeof u?.login === 'string' ? u.login : null)).filter(Boolean) : [];
}
/** The names a labels answer (an array of label objects) lists, in the platform's order; `[]` when it lists none. Pure. */
export function labelNames(json) {
return Array.isArray(json) ? json.map((l) => (typeof l?.name === 'string' ? l.name : null)).filter(Boolean) : [];
}
/** The logins a pull answer lists as PENDING review requests (`requested_reviewers`), in the platform's order; `[]` when none. Pure. */
export function reviewerLogins(json) {
return Array.isArray(json?.requested_reviewers) ? json.requested_reviewers.map((u) => (typeof u?.login === 'string' ? u.login : null)).filter(Boolean) : [];
}
/** The logins that have SUBMITTED a review in a reviews answer — any state but `PENDING` (unsubmitted); `[]` when none. Pure. */
export function reviewedLogins(json) {
return Array.isArray(json) ? json.filter((r) => r?.state !== 'PENDING').map((r) => (typeof r?.user?.login === 'string' ? r.user.login : null)).filter(Boolean) : [];
}
/**
* The governed-review plan for ONE pull (header: "The governed-review follow-up"). Pure — the executor reads
* the file list, the pull and its reviews, hands them in, and sends exactly what comes back:
*
* repoId the register id of `repo`, or null for a target outside `GOVERNED_REPOS` (no row governs it);
* matched the governed slice of `paths` (`governedPathsIn`), for the row's wording;
* tier `H` when the slice lands on an authorized approval, `S` when every hit is Tier S, null when no
* governed row is hit — read through `landingTierOf` over the MATCHED slice, never over nothing
* (an empty slice answers H there, fail-closed, which is the wrong answer for "send a request");
* covered the approvers already requested, assigned or holding a submitted review — the H43 union;
* toRequest on a Tier H hit, the approvers not covered and not the pull's author;
* toAssign on a Tier H hit, the author when it is an uncovered approver (a request naming it is a 422).
*
* Logins are matched as GitHub matches them, case-insensitively; the answer keeps `approvers`' own spelling and order.
*/
export function governedReviewPlan({ paths, repo, author = null, requested = [], assigned = [], reviewed = [], approvers = GOVERNED_APPROVERS } = {}) {
const repoId = repoIdForSlug(repo);
const matched = repoId ? governedPathsIn(Array.isArray(paths) ? paths : [], repoId) : [];
const tier = matched.length === 0 ? null : landingTierOf(matched);
const lower = (list) => (Array.isArray(list) ? list : []).map((l) => String(l).toLowerCase());
const have = new Set([...lower(requested), ...lower(assigned), ...lower(reviewed)]);
const list = Array.isArray(approvers) ? approvers : [];
const covered = list.filter((a) => have.has(a.toLowerCase()));
const missing = tier === GOVERNED_TIER_H ? list.filter((a) => !have.has(a.toLowerCase())) : [];
const isAuthor = (a) => typeof author === 'string' && a.toLowerCase() === author.toLowerCase();
return { repoId, matched, tier, covered, toRequest: missing.filter((a) => !isAuthor(a)), toAssign: missing.filter(isAuthor) };
}
/** The words the follow-up's verdict row prints for a plan — what was hit, who is covered, what will be sent. Pure. */
export function governedReviewText(plan, { repo, files, approvers = GOVERNED_APPROVERS } = {}) {
const hits = plan.matched.map((s) => `\`${s.glob}\`×${s.files.length}`).join(', ');
if (plan.repoId === null) return `governed review: ${repo} is outside GOVERNED_REPOS, so no register row governs it — ${files} file(s), no review requested`;
if (plan.tier === null) return `governed review: no governed row hit across ${files} file(s) — no review requested`;
if (plan.tier === GOVERNED_TIER_S) return `governed review: Tier S (${hits}) lands on a seat's review of record — no review requested`;
const named = (logins) => logins.map((l) => `\`${l}\``).join(', ');
const sending = [plan.toRequest.length ? `requesting ${named(plan.toRequest)}` : '', plan.toAssign.length ? `assigning the author ${named(plan.toAssign)} (a request naming the author is a 422)` : ''].filter(Boolean).join(' and ');
if (!sending) return `governed review: Tier H (${hits}) — ${named(approvers)} already requested, assigned or reviewed; nothing to send`;
return `governed review: Tier H (${hits}) — ${plan.covered.length ? `${named(plan.covered)} already covered; ` : ''}${sending}`;
}
/**
* A descriptor carrying `fromAnswer` filled from its action's FIRST request's
* answer — the create's (header): `{ req }` with the placeholder replaced by
* the positive integer that answer carries at the field, or `{ fail }` — the
* sentence the row prints — when no answer carries it. Pure; never throws.
*/
export function fillFromAnswer(req, prev) {
const field = req.fromAnswer;
const placeholder = answerPlaceholder(field);
if (typeof req.path !== 'string' || !req.path.includes(placeholder)) return { fail: `the op table spells a fromAnswer leg whose path ${req.path} carries no ${placeholder} placeholder — a bug in ops.mjs, not in the payload` };
if (!prev) return { fail: `the op table spells a fromAnswer leg as the FIRST request of its action, so no answer carries ${field} yet — a bug in ops.mjs, not in the payload` };
const value = prev.json?.[field];
if (!Number.isInteger(value) || value < 1) return { fail: `${prev.call} answered HTTP ${prev.status} without a positive integer ${field} (got ${JSON.stringify(value ?? null)}), so the leg ${req.verb} ${req.path} was NOT SENT — read the pull on the board before anything else` };
return { req: { ...req, path: req.path.replaceAll(placeholder, String(value)) } };
}
/**
* A pull request's state as a mutation answered it — every field the row selected, so a failure names
* what came back and a landing names how (armed, or already in the merge queue).
*/
export function pullStateText(pr) {
const bits = [`#${pr.number}`];
if (typeof pr.isDraft === 'boolean') bits.push(pr.isDraft ? 'draft' : 'ready');
if ('autoMergeRequest' in pr) bits.push(pr.autoMergeRequest ? `auto-merge ${pr.autoMergeRequest.mergeMethod ?? ''}`.trim() : 'auto-merge off');
if (typeof pr.isInMergeQueue === 'boolean') bits.push(pr.isInMergeQueue ? 'in the merge queue' : 'not in the merge queue');
if (typeof pr.isMergeQueueEnabled === 'boolean') bits.push(pr.isMergeQueueEnabled ? 'its base has a merge queue' : 'its base has no merge queue');
return bits.join(' · ');
}
/** The base sync's answer of acceptance, its confirmation window and its poll interval (header). */
export const UPDATE_BRANCH_ACCEPTED = 202;
export const UPDATE_BRANCH_WINDOW_MS = 60_000;
export const UPDATE_BRANCH_POLL_MS = 3_000;
const shortSha = (sha) => String(sha ?? '').slice(0, 7);
/** A compare ref (`owner:branch`) as a path segment — the branch's own slashes stay slashes. */
const refSegment = (label) => encodeURIComponent(label).replace(/%2F/g, '/');
/**
* Did the base sync LAND? Judged by measure, never by the answer's sentence
* (header): a 202 is confirmed by polling the pull's head off the expected sha
* inside the window, then reading the merge commit's author; a 422 is a no-op
* only when the head is still the expected sha AND the compare measures it not
* behind its base. Returns `{ ok, why, result }` — `result` the row's text on
* a landing. Never throws on a status.
*/
export async function confirmUpdateBranch(req, answer, payload, api, t, { sleep, now, windowMs = UPDATE_BRANCH_WINDOW_MS, pollMs = UPDATE_BRANCH_POLL_MS } = {}) {
const { pull, expectedHeadSha } = req.updateBranch;
const pullPath = `/repos/${payload.repo}/pulls/${pull}`;
const said = (r) => `${r.call} -> HTTP ${r.status}${r.detail ? ` (${r.detail})` : ''}`;
const platform = `HTTP ${answer.status}${answer.detail ? ` — ${answer.detail}` : ''}`;
if (answer.status === 422) {
const pr = await rest(api, pullPath, {}, t);
if (pr.status !== 200 || typeof pr.json?.head?.sha !== 'string') return { ok: false, why: `${platform}; the pull could not be re-read to tell a no-op from a refusal (${said(pr)})` };
if (pr.json.head.sha !== expectedHeadSha) return { ok: false, why: `${platform}; the head is ${shortSha(pr.json.head.sha)}, not the expected ${shortSha(expectedHeadSha)} — re-read the pull and send its current head` };
const baseLabel = pr.json.base?.label;
const headLabel = pr.json.head?.label;
if (typeof baseLabel !== 'string' || typeof headLabel !== 'string') return { ok: false, why: `${platform}; the pull's base and head labels could not be read, so the compare that tells a no-op from a refusal was not taken` };
const baseRef = typeof pr.json.base?.ref === 'string' ? pr.json.base.ref : baseLabel;
const cmp = await rest(api, `/repos/${payload.repo}/compare/${refSegment(baseLabel)}...${refSegment(headLabel)}`, {}, t);
if (cmp.status !== 200 || !Number.isInteger(cmp.json?.behind_by)) return { ok: false, why: `${platform}; the compare could not be read to tell a no-op from a refusal (${said(cmp)})` };
if (cmp.json.behind_by === 0) return { ok: true, why: '', result: `no-op: head ${shortSha(expectedHeadSha)} is not behind ${baseRef} (behind_by 0), nothing to merge; the platform said "${answer.detail}"` };
return { ok: false, why: `${platform}; the head is behind ${baseRef} by ${cmp.json.behind_by} commit(s), so the platform refused the sync — not a no-op` };
}
if (answer.status !== UPDATE_BRANCH_ACCEPTED) return { ok: false, why: platform };
const started = now();
let head = null;
for (;;) {
const pr = await rest(api, pullPath, {}, t);
if (pr.status === 200 && typeof pr.json?.head?.sha === 'string') {
head = pr.json.head.sha;
if (head !== expectedHeadSha) {
const commit = await rest(api, `/repos/${payload.repo}/commits/${head}`, {}, t);
const author = commit.status === 200 && commit.json ? `${commit.json.author?.login ?? 'no login'} (${commit.json.commit?.author?.name ?? '?'})` : `unread (${said(commit)})`;
return { ok: true, why: '', result: `head ${shortSha(expectedHeadSha)} → ${shortSha(head)} · merge commit author ${author}` };
}
}
if (now() - started >= windowMs) break;
await sleep(pollMs);
}
return { ok: false, why: `HTTP ${UPDATE_BRANCH_ACCEPTED} accepted, but the head ${head === null ? 'could not be read' : `is still ${shortSha(head)}`} ${windowMs} ms later — UNCONFIRMED: the merge may still land; read the pull before anything else, ⛔ do not re-send` };
}
/** The failed-jobs re-run's read-back window and poll interval (header): the run is re-read until it shows the new attempt. */
export const RERUN_FAILED_WINDOW_MS = 60_000;
export const RERUN_FAILED_POLL_MS = 3_000;
/** An attempt's job list is walked at the endpoint's page maximum, to a cap — a walk past it is a truncated SUBSET. */
export const RERUN_FAILED_JOBS_PAGE_SIZE = 100;
export const RERUN_FAILED_JOBS_PAGE_CAP = 10;
/**
* One attempt's job list, every page: `{ jobs }`, or `{ fail: { call, status, why } }` for a page that did not
* answer 200 with a `jobs` array, or a walk past `RERUN_FAILED_JOBS_PAGE_CAP` pages. Never throws.
*/
async function readAttemptJobs(repo, runId, attempt, api, t) {
const jobs = [];
const call = `GET /repos/${repo}/actions/runs/${runId}/attempts/${attempt}/jobs`;
for (let page = 1; page <= RERUN_FAILED_JOBS_PAGE_CAP; page++) {
const r = await rest(api, `/repos/${repo}/actions/runs/${runId}/attempts/${attempt}/jobs?per_page=${RERUN_FAILED_JOBS_PAGE_SIZE}&page=${page}`, {}, t);
if (r.status !== 200 || !Array.isArray(r.json?.jobs)) return { fail: { call, status: r.status, why: `${call} -> HTTP ${r.status}${r.detail ? ` (${r.detail})` : ''}: attempt ${attempt}'s job list could not be read` } };
jobs.push(...r.json.jobs);
const total = Number.isInteger(r.json.total_count) ? r.json.total_count : null;
if (r.json.jobs.length < RERUN_FAILED_JOBS_PAGE_SIZE || (total !== null && jobs.length >= total)) return { jobs };
}
return { fail: { call, status: 200, why: `attempt ${attempt}'s job list hit its ${RERUN_FAILED_JOBS_PAGE_CAP}-page cap with ${jobs.length} job(s) collected and more pending — a truncated list is a SUBSET` } };
}
/**
* The fences, AUTHORITATIVE (header: "The failed-jobs re-run"): attempt 1's job list (the read-back's baseline),
* then the run, then the pull it names — the last two reads before the POST — judged against
* `RERUN_FAILED_FENCES`. The pull's head is the pull's OWN answer, never the run's embedded copy. Returns
* `{ run, pull, failed }` to send, or `{ fail: why }` — the sentence the row prints, the POST NOT SENT. Never throws
* on a status.
*/
export async function rerunFailedPreflight(req, payload, api, t) {
const { runId } = req.rerunFailed;
const baseline = await readAttemptJobs(payload.repo, runId, RERUN_FAILED_ATTEMPT, api, t);
const run = await rest(api, `/repos/${payload.repo}/actions/runs/${runId}`, {}, t);
if (run.status !== 200 || !run.json || typeof run.json !== 'object') {
return { fail: `${run.call} -> HTTP ${run.status}${run.detail ? ` (${run.detail})` : ''}: the run could not be read, so its fences were not judged — nothing sent` };
}
// The head fence's read: the pull the run names, by its own GET. A run naming none is judged without it and refused by name.
const number = rerunFailedPullNumber(run.json);
let pull = null;
if (number !== null) {
const p = await rest(api, `/repos/${payload.repo}/pulls/${number}`, {}, t);
if (p.status !== 200 || !p.json || typeof p.json !== 'object') {
return { fail: `${p.call} -> HTTP ${p.status}${p.detail ? ` (${p.detail})` : ''}: pull #${number}, the run's pull request, could not be read, so the head fence was not judged — nothing sent` };
}
pull = p.json;
}
const failures = rerunFailedFenceFailures(run.json, pull);
if (failures.length) return { fail: `REFUSED at the relay's fence on run ${runId}, nothing sent — ${rerunFailedFenceText(failures)}` };
if (baseline.fail) return { fail: `${baseline.fail.why}, so the read-back has no baseline — nothing sent` };
const failed = failedJobNames(baseline.jobs);
if (!failed.length) return { fail: `attempt ${RERUN_FAILED_ATTEMPT} of run ${runId} lists ${baseline.jobs.length} job(s) and none concluded failure, so a re-run's read-back would have nothing to confirm — nothing sent` };
return { run: run.json, pull, failed };
}
/**
* Did the re-run LAND? Judged by reading the run back, never by the 201 (header): the run re-read until it shows
* the new attempt, then that attempt's job list judged by `rerunFailedReadBack`. Returns `{ ok, why, result }` —
* `result` the row's text on a landing, naming the new attempt's job ids. Never throws on a status.
*/
export async function confirmRerunFailed(req, answer, pre, payload, api, t, { sleep, now, windowMs = RERUN_FAILED_WINDOW_MS, pollMs = RERUN_FAILED_POLL_MS } = {}) {
const platform = `HTTP ${answer.status}${answer.detail ? ` — ${answer.detail}` : ''}`;
if (!(answer.status >= 200 && answer.status < 300)) return { ok: false, why: platform };
const { runId } = req.rerunFailed;
const want = RERUN_FAILED_ATTEMPT + 1;
const started = now();
let last = 'nothing was read back';
for (;;) {
const run = await rest(api, `/repos/${payload.repo}/actions/runs/${runId}`, {}, t);
if (run.status !== 200 || !run.json || typeof run.json !== 'object') last = `${run.call} -> HTTP ${run.status}${run.detail ? ` (${run.detail})` : ''}: the run could not be re-read`;
else if (run.json.run_attempt !== want) last = rerunFailedReadBack({ failed: pre.failed, run: run.json }).why;
else {
const listed = await readAttemptJobs(payload.repo, runId, want, api, t);
if (listed.fail) last = listed.fail.why;
else {
const v = rerunFailedReadBack({ failed: pre.failed, run: run.json, jobs: listed.jobs });
if (v.ok) return { ok: true, why: '', result: rerunFailedLandedText(v) };
if (!v.pending) return { ok: false, why: `${platform} accepted, but ${v.why} — read the run before anything else, ⛔ do not re-send` };
last = v.why;
}
}
if (now() - started >= windowMs) break;
await sleep(pollMs);
}
return { ok: false, why: `${platform} accepted, but ${last} ${windowMs} ms later — UNCONFIRMED: the re-run may still start; read the run before anything else, ⛔ do not re-send (a second send meets attempt ${want} at the once fence and is refused)` };
}
/** The hierarchy link's read-back window and poll interval (header): the parent's list is re-read until it settles. */
export const SUB_ISSUE_WINDOW_MS = 30_000;
export const SUB_ISSUE_POLL_MS = 3_000;
/** A parent's sub-issue list is walked at the endpoint's page maximum, to a cap — a walk past it is a truncated SUBSET. */
export const SUB_ISSUE_LIST_PAGE_SIZE = 100;
export const SUB_ISSUE_LIST_PAGE_CAP = 10;
/**
* A parent's sub-issue list, every page: `{ items }`, or `{ fail }` — the sentence — for a page that did not answer
* 200 with an array, or a walk past `SUB_ISSUE_LIST_PAGE_CAP` pages. Never throws.
*/
async function readSubIssues(repo, parent, api, t) {
const items = [];
const call = `GET /repos/${repo}/issues/${parent}/sub_issues`;
for (let page = 1; page <= SUB_ISSUE_LIST_PAGE_CAP; page++) {
const r = await rest(api, `/repos/${repo}/issues/${parent}/sub_issues?per_page=${SUB_ISSUE_LIST_PAGE_SIZE}&page=${page}`, {}, t);
if (r.status !== 200 || !Array.isArray(r.json)) return { fail: `${call} -> HTTP ${r.status}${r.detail ? ` (${r.detail})` : ''}: #${parent}'s sub-issue list could not be read` };
items.push(...r.json);
if (r.json.length < SUB_ISSUE_LIST_PAGE_SIZE) return { items };
}
return { fail: `#${parent}'s sub-issue list hit its ${SUB_ISSUE_LIST_PAGE_CAP}-page cap with ${items.length} entries collected and more pending — a truncated list is a SUBSET, never read as absent` };
}
/**
* The fences, AUTHORITATIVE (header: "The hierarchy link"): the parent's and the child's own answers, then — only
* when both pass — the child's parent read (add) or the parent's whole list (remove), judged against
* `SUB_ISSUE_FENCES`. Returns `{ childId, already }` to proceed — `already` an add whose child answers to THIS
* parent, the no-op — or `{ fail: why }`, the sentence the row prints, the write NOT SENT. Never throws on a status.
*/
export async function subIssuePreflight(req, payload, api, t) {
const { mode, parent, child } = req.subIssue;
const repo = payload.repo;
const ctx = { mode, repo, parentNumber: parent, childNumber: child };
ctx.parent = await rest(api, `/repos/${repo}/issues/${parent}`, {}, t);
ctx.child = await rest(api, `/repos/${repo}/issues/${child}`, {}, t);
if (subIssueCardFailure(ctx.parent, repo, parent) === null && subIssueCardFailure(ctx.child, repo, child) === null) {
if (mode === 'add') ctx.childParent = await rest(api, `/repos/${repo}/issues/${child}/parent`, {}, t);
else ctx.list = await readSubIssues(repo, parent, api, t);
}
const failures = subIssueFenceFailures(ctx);
if (failures.length) return { fail: `REFUSED at the relay's fence on #${parent} ← #${child}, nothing sent — ${subIssueFenceText(failures)}` };
return { childId: ctx.child.json.id, already: mode === 'add' && subIssueAlreadyHere(ctx) };
}
/**
* Did the hierarchy link LAND? Judged by reading the parent's list back, never by the answer (header). `answer`
* is the write's, or null for the no-op, which sent nothing. Returns `{ ok, why, result }`. Never throws on a status.
*/
export async function confirmSubIssue(req, answer, pre, payload, api, t, { sleep, now, windowMs = SUB_ISSUE_WINDOW_MS, pollMs = SUB_ISSUE_POLL_MS } = {}) {
const { mode, parent, child } = req.subIssue;
const platform = answer ? `HTTP ${answer.status}${answer.detail ? ` — ${answer.detail}` : ''}` : null;
if (answer && !(answer.status >= 200 && answer.status < 300)) return { ok: false, why: platform };
const started = now();
let last = 'nothing was read back';
for (;;) {
const list = await readSubIssues(payload.repo, parent, api, t);
if (list.fail) last = list.fail;
else {
const v = subIssueReadBack({ mode, childId: pre.childId, items: list.items });
if (v.ok) return { ok: true, why: '', result: subIssueLandedText({ mode, parentNumber: parent, childNumber: child, childId: pre.childId, count: v.count, noop: !answer }) };
last = v.why;
}
if (now() - started >= windowMs) break;
await sleep(pollMs);
}
if (!answer) return { ok: false, why: `nothing sent — #${child}'s parent read named #${parent}, but ${last} ${windowMs} ms later: the two reads disagree; read #${parent}'s sub-issues before anything else` };
return { ok: false, why: `${platform} accepted, but ${last} ${windowMs} ms later — UNCONFIRMED: read #${parent}'s sub-issues before anything else, ⛔ do not re-send` };
}
/**
* The mailbox branch delete's fences on the reads (header): `[]` to send, else one sentence per fence that fails —
* an unread pull is one, judged alone. `pull`, `open` and `ref` are `rest` answers; a 404 ref fences nothing. Pure.
*/
export function mailboxBranchFenceFailures({ repo, branch, pull, open, ref }) {
if (pull?.status !== 200 || !pull.json || typeof pull.json !== 'object') return [`${pull?.call} -> HTTP ${pull?.status}: the pull could not be read`];
const pr = pull.json;
const out = [];
if (pr.state !== 'closed') out.push(`the pull is ${pr.state}, not closed`);
if (!labelNames(pr.labels).includes(MAILBOX_LABEL)) out.push(`the pull does not carry ${MAILBOX_LABEL}`);
if (pr.head?.ref !== branch) out.push(`the pull's head is ${pr.head?.ref ?? 'unread'}, not ${branch}`);
if (String(pr.head?.repo?.full_name ?? '').toLowerCase() !== repo.toLowerCase()) out.push(`the pull's head lives on ${pr.head?.repo?.full_name ?? 'no repository'}, not ${repo}`);
if (open?.status !== 200 || !Array.isArray(open.json)) out.push(`${open?.call} -> HTTP ${open?.status}: the open pulls on ${branch} could not be read`);
else if (open.json.length) out.push(`open pull(s) ${open.json.map((p) => `#${p?.number}`).join(', ')} have ${branch} as head — the DELETE would close them`);
const at = ref?.status === 200 && ref.json?.ref === `refs/heads/${branch}` ? ref.json.object?.sha : undefined;
if (ref?.status !== 404 && typeof at !== 'string') out.push(`${ref?.call} -> HTTP ${ref?.status}: the ref ${branch} could not be read`);
else if (ref?.status !== 404 && at !== pr.head?.sha) out.push(`${branch} is at ${at.slice(0, 12)}, not the pull's head ${String(pr.head?.sha ?? 'unread').slice(0, 12)} — a commit pushed after the close is not the mailbox's`);
return out;
}
/** The fences, AUTHORITATIVE (header): the three reads, then `{}` to send or `{ fail }`, the DELETE NOT SENT. Never throws. */
export async function mailboxBranchPreflight(req, payload, api, t) {
const { pull, branch } = req.mailboxBranch;
const repo = payload.repo;
const pr = await rest(api, `/repos/${repo}/pulls/${pull}`, {}, t);
const open = await rest(api, `/repos/${repo}/pulls?state=open&head=${encodeURIComponent(`${repo.split('/')[0]}:${branch}`)}`, {}, t);
const ref = await rest(api, `/repos/${repo}/git/ref/heads/${branch}`, {}, t);
const failures = mailboxBranchFenceFailures({ repo, branch, pull: pr, open, ref });
return failures.length ? { fail: `REFUSED at the relay's fence on #${pull}'s head ${branch}, nothing sent — ${failures.join('; ')}` } : {};
}
/** Did the delete LAND? The ref read back absent (header); a ref still there, or unread, is FAILED. Never throws. */
export async function confirmMailboxBranch(req, answer, payload, api, t) {
const { branch } = req.mailboxBranch;
const back = await rest(api, `/repos/${payload.repo}/git/ref/heads/${branch}`, {}, t);
const platform = `HTTP ${answer.status}${answer.detail ? ` — ${answer.detail}` : ''}`;
if (back.status !== 404) return { ok: false, why: `${platform}, but ${back.call} answered HTTP ${back.status}: the branch ${back.status === 200 ? 'is still there' : 'could not be read back'} — read it before anything else` };
return { ok: true, why: '', idempotent: !(answer.status >= 200 && answer.status < 300), result: `deleted ${branch} (read back absent)` };
}
/**
* The advisory's fences, AUTHORITATIVE (header: "The advisory rows that write"): its own GET, judged against
* `ADVISORY_FENCES` — for `advisory_collaborators_add` an open advisory (`ADVISORY_OPEN_STATES`), for
* `advisory_versions` a draft (`ADVISORY_VERSIONS_STATES`) whose whole list the entries may replace, for
* `advisory_state` a transition `ADVISORY_TRANSITIONS` allows — a target it does not name has no from-states and fails
* closed — and for a publish the versions set first — then, for the collaborators, the merge. Returns
* `{ plan, state, known, versions }` (`plan` null but for the collaborators, `plan.missing` empty the no-op; `known`
* the advisory's own text, which a later refusal's cause may never quote; `versions` the entries a publish's GET read,
* which its answer must list again) to proceed, or `{ fail }`, the sentence the row prints, the PATCH NOT SENT. ⛔ That
* sentence carries nothing of the answer but what `advisoryFenceText` prints and, on a refused read, its cause
* (`advisoryRefusalCause`). Never throws.
*/
export async function advisoryPreflight(req, payload, api, t) {
const spec = req.advisoryCollaborators ?? req.advisoryVersions ?? req.advisoryState;
const { ghsaId } = spec;
const to = req.advisoryState ? req.advisoryState.to : null;
const versions = req.advisoryVersions ? req.advisoryVersions.versions : null;
const from = to ? (Object.hasOwn(ADVISORY_TRANSITIONS, to) ? ADVISORY_TRANSITIONS[to] : []) : versions ? ADVISORY_VERSIONS_STATES : ADVISORY_OPEN_STATES;
const read = await rest(api, `/repos/${payload.repo}/security-advisories/${ghsaId}`, {}, t);
const failures = advisoryFenceFailures({ ghsaId, answer: read, from, to, ...(versions ? { versions } : {}) });
if (failures.length) {
const refused = !(read.status >= 200 && read.status < 300);
return { fail: `REFUSED at the relay's fence on ${ghsaId}, nothing sent — ${advisoryFenceText(failures)}${refused ? `; ${advisoryRefusalCause(read, advisoryProseOf(spec))}; ${ADVISORY_ACCESS_REMEDY}` : ''}` };
}
const known = advisoryProseOf(read.json);
if (to) return { plan: null, state: read.json.state, known, versions: to === ADVISORY_PUBLISHED_STATE ? advisoryVersionsOf(read.json).entries : null };
if (versions) return { plan: null, state: read.json.state, known, versions: null };
return { plan: advisoryCollaboratorPlan({ existing: advisoryCollaboratorLogins(read.json), requested: spec.add }), state: read.json.state, known, versions: null };
}
// ---------------------------------------------------------------------------
// An advisory refusal's CAUSE — the platform's own `message` and `documentation_url`, capped, ⛔ never the payload.
// ---------------------------------------------------------------------------
/** The longest platform `message` an advisory refusal prints, in characters; a longer one is cut and says so. */
export const ADVISORY_REFUSAL_MESSAGE_CAP = 200;
/** The longest `documentation_url` an advisory refusal prints; a longer one is not printed at all (a cut URL misleads). */
export const ADVISORY_REFUSAL_URL_CAP = 200;
/** A `documentation_url` the row may print: https, a host, a path, and nothing that could break a row or a table. */
const REFUSAL_URL_SHAPE = /^https:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?\/[^\s"'`<>|\\]*$/;
/** How much of a known text has to reappear in the platform's answer before the answer is read as quoting it. */
const QUOTE_WINDOW = 16;
/** Known text shorter than this is not looked for — and nothing that short carries a finding. */
const QUOTE_MIN = 8;
/**
* Every string the payload or an advisory's answer carries that a refusal's cause may never quote — the prose.
* An id, a state or a login is left out: each is printable in its own shape anyway (`advisoryPrintable`). So is
* every URL-shaped word: an advisory's own `url` shares its path with GitHub's documentation (both name
* `security-advisories`), and a link carries no finding — the prose around it stays in. Pure.
*/
export function advisoryProseOf(value, out = []) {
if (typeof value === 'string') {
const prose = value.split(/\s+/).filter((w) => !/^[a-z][a-z0-9+.-]*:\/\//i.test(w)).join(' ');
if (prose.length >= QUOTE_MIN && !GHSA_ID_SHAPE.test(prose) && !LOGIN_SHAPE.test(prose) && !ADVISORY_STATE_SHAPE.test(prose)) out.push(prose);
} else if (Array.isArray(value)) {
for (const v of value) advisoryProseOf(v, out);
} else if (value && typeof value === 'object') {
for (const v of Object.values(value)) advisoryProseOf(v, out);