Repository navigation
Expand file tree
/
Copy pathexecute.mjs
More file actions
4867 lines (4693 loc) · 488 KB
/
Copy pathexecute.mjs
File metadata and controls
4867 lines (4693 loc) · 488 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
* on the stroke's own repository (`WORKFLOW_DISPATCH_BY_REPO`: none for the
* shard-timings refresh, `refresh_version_pr: "true"` alone for `release.yml`,
* its bookkeeping lane, `apps: "affected"` alone for cloud's
* `deploy-staging.yml`)
* — 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), a `pr_enqueue_front` on the pull and its queue, and a
* `pr_dequeue` on the pull, its queue and its cause.
* 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 front-of-queue enqueue — `pr_enqueue_front`, fenced on the PULL and its QUEUE and read back
*
* The fences (`ENQUEUE_FRONT_FENCES` in `ops.mjs`: open, ready, the head,
* not Version Packages, no governed path, the human-merge line count, a
* queue read whole, no entry already jumped) are facts about the pull and the
* queue, so this file is where they are AUTHORITATIVE
* (`enqueueFrontPreflight`): the pull's own `GET /repos/{repo}/pulls/{n}`,
* its whole file list (every page, the governed slice through the register
* as the governed-review follow-up reads it), then its base's queue by
* GraphQL query (`MERGE_QUEUE_READ_QUERY`, unpaced: a query writes nothing)
* — the last reads before the mutation. A read that fails or a fence that
* fails stops the action with the mutation NOT SENT, zero writes, exit 5.
* The mutation sends the node id and the expected head (`expectedHeadOid`).
* GraphQL errors on it are a FAILED action naming the grant when the
* platform says "not accessible by integration". A 200 is an acceptance:
* `confirmEnqueueFront` re-reads the queue every `ENQUEUE_FRONT_POLL_MS` for
* up to `ENQUEUE_FRONT_WINDOW_MS` and lands only on `enqueueFrontReadBack`
* (the entry jumped, nothing ahead). Queued without the jump, or behind
* another, is FAILED at once and says the pull IS queued — ⛔ never re-sent.
*
* Over the human-merge line the `size` fence asks for the SIZE lift
* (`ops.mjs`, "The SIZE lift"): only then are the pull's reviews read, after
* the queue (`GET …/pulls/{n}/reviews`, one page at the endpoint's maximum, a
* full page read as unreadable) and reduced by the queue guard's
* `authorizedApprovalVerdict`; an approval that is not on the head reads the
* action's `approval_comment` by its own GET. Unread, unauthorised, elsewhere,
* carried by nobody or by a comment holding a seat signature on any line
* (`readSignatureLine`, passed in), the line holds and the mutation is NOT SENT.
*
* ## The dequeue — `pr_dequeue`, fenced on the PULL, its QUEUE and its CAUSE, audited, and read back
*
* One action, one function (`dequeueAction`): the fences (`DEQUEUE_FENCES` in
* `ops.mjs`) are AUTHORITATIVE here (`dequeuePreflight`), judged on the
* pull's own GET, its base's queue read with each entry's merge-group rollup
* (`DEQUEUE_QUEUE_READ_QUERY`, unpaced) and — for `seat-asks` alone — the
* landing seat its body's signed trailer names (`readPrBodyTrailer`; none
* named is a refusal, the comments unread) and then its comments, every page
* to a cap, a comment counting only when the relay wrote it and its first
* line is a signature naming that seat, its account and the dispatching
* session (`signedByLandingSeat`). A read or fence that fails writes NOTHING,
* exit 5, and so does a pull whose read carries no node id. Then the ONE
* audit comment, a paced POST, whose 201 with an id is required before
* anything else is sent; then the mutation on the node id that same pull
* read answered (no second read between the comment and the mutation); then
* the queue re-read every `DEQUEUE_POLL_MS` for up to `DEQUEUE_WINDOW_MS`
* until it no longer lists the pull, and the pull's own GET read open with
* `merged` false (`dequeuePullAfter`) twice, one `DEQUEUE_POLL_MS` apart. GraphQL errors are FAILED naming the
* grant when the platform says "not accessible by integration"; a pull that
* merged, or closed, inside the window is FAILED naming it; a read-back that
* still lists the pull after the window is FAILED, UNCONFIRMED. Every failure after the comment names the
* comment, which stands: the run's row is the outcome it points to.
*
* ## 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 mailbox conversation lock — `conversation_lock` / `conversation_unlock`
*
* Their fences and their landing are listed once, in `ops.mjs`'s header ("The
* two rows that lock and unlock a conversation"); they are AUTHORITATIVE here
* (`mailboxLockPreflight`, `confirmMailboxLock`), 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`), and the seat is done
* (`advisory_collaborators_add` only when a maintainer asks for it). 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 listing — `advisory_list`, projected, padded and sealed before anything leaves (`advisoryListAction`)
*
* The row's gate first: a `senderGate` other than `target-write` (the gate
* this stroke already passed) is a FAILED action with ZERO requests. Then,
* for each state of `ADVISORY_LIST_STATES` in order, one walk of the
* collection's GETs (`advisoryListPagePath`), nothing written: a page fails
* its fences (`advisoryListPageFailure`: 200, a list, every item an advisory
* in the state asked for, its severity and dates in their declared shapes) ⇒
* FAILED, naming the status alone, with
* `ADVISORY_LIST_ACCESS_REMEDY` on a refusal; a page that never reached the
* platform ⇒ FAILED with `ADVISORY_LIST_UNREACHED` and the row status
* `not reached`; every page's `Link` is read through `advisoryListNextCursor`,
* and a link it refuses ⇒ FAILED; a short page whose link names no next page,
* or a full one whose link names none, ends the walk, and a short page that
* still names one ⇒ FAILED with `ADVISORY_LIST_SHORT_PAGE_NEXT`; a full page
* with a next link is followed only on the cursor it admits, ⛔ never the link
* itself; an advisory met twice ⇒ FAILED; a walk still pending
* after `ADVISORY_LIST_PAGE_CAP` pages ⇒ FAILED, never a truncated answer.
* Otherwise it projects each advisory to `ADVISORY_LIST_FIELDS`
* (`advisoryListPlaintext`), pads the JSON to `ADVISORY_LIST_PADDED_BYTES`
* (`advisoryListPadded`: over it ⇒ FAILED, nothing emitted), seals it to the
* action's `public_key` under `advisorySealAad` and emits exactly
* `ADVISORY_READ_MAX_PARTS` notice parts — a seal that throws, is not
* base64url or is not exactly the channel's size ⇒ FAILED with
* `ADVISORY_READ_SEAL_FAILED` and no part. Every failure seals and emits
* nothing. `rest` hands the answer's `Link` header back for this walk.
*
* ⛔ What this path prints — the row, the log line, the step summary — is
* `advisoryListCall`, the last page's HTTP status and one fixed sentence:
* `ADVISORY_LIST_LANDED` or the failure's. Never an id, a count, a state, a
* severity, a cursor, a page number, or a byte or part count. The self-test
* serves items carrying a summary, a description, vulnerabilities and a
* marker in each, and finds the marker in no line, row, summary or
* annotation, nor in the opened plaintext.
*
* ## The note — `advisory_note`, opened here, appended once and read back (`advisoryNoteAction`)
*
* The relay's key first: the private half (the repository secret the workflow
* hands the execute step for a note's stroke alone, `ADVISORY_NOTE_KEY_ENV`,
* read once and deleted from this process's environment) is judged against the
* committed public half (`advisoryNoteKeyFailure`); none, a null committed half
* or a pair made apart is a FAILED action before any request. Then the
* advisory's GET and `ADVISORY_NOTE_FENCES` on it — a 2xx, the advisory named,
* a state in `ADVISORY_NOTE_STATES` (never published or withdrawn), a
* description that is text or null; the open (`openAdvisoryNote`, bound to the
* request id, the action's index, the op and the id — anything else is
* `ADVISORY_NOTE_OPEN_FAILED`); the section judged again
* (`advisoryNoteSectionFailure` — the seat's check is never trusted alone);
* every line of the judged section of at least `ADVISORY_NOTE_MASK_MIN_CHARS`
* handed to the runner's `::add-mask::` (`maskCommand`; the runner never
* echoes it), save one that occurs in the note's own notice
* (`advisoryNoteMaskValues`: masked, it would star the line the seat reads); a
* SECOND fenced GET immediately before the write, refused if the description
* changed since the first — the platform offers no conditional write on it;
* the cap, `ADVISORY_DESCRIPTION_MAX_CHARS` code points. Then ONE PATCH of
* `{ description }` — the text read, byte for byte, `ADVISORY_NOTE_SEPARATOR`
* and the section (`advisoryNoteDescription`) — and the read-back: the PATCH's
* answer, then a GET after it, each exactly that text (`advisoryNoteReadBack`;
* other text before the section is a raced write). A PATCH that threw is
* UNCONFIRMED and a read-back that fails is FAILED, each saying
* `ADVISORY_NOTE_NOT_RESENT`. Residual window: a write landing between the
* second GET and the PATCH is overwritten undetected (about one round trip);
* one after the PATCH is caught by the read-back.
*
* ⛔ What this path prints — the row, the log line, the step summary, the ONE
* notice — is the call, the status, the id, the state, byte counts and the
* section's HMAC-SHA256 under the seat's one-time digest key (never a bare
* digest a reader could test a guess against); a refusal quotes the platform
* only in `ADVISORY_PLATFORM_MESSAGES`. Never a byte of the note, the
* description or the key. The self-test serves both texts with a marker and
* finds it — as text, URI-encoded, hex or base64 — in no line, row, summary,
* annotation, pace line or real process's output.
*
* ## 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 `workflows` row's split: when EVERY governed hit is that row and the
* target is in its `split.repos` (`workflowSplitReadable`), the follow-up
* reads the queue guard's own measure — `readWorkflowDiff`, imported, merge
* base → head (`workflowReadingFor`: the compare answers the merge base, the
* checkout must be the target by its origin, the two commits are fetched by
* sha at depth 1 when missing) — and a reading that says S requests nobody.
* ⛔ Fail closed: no checkout, a commit missing, git throwing, an unread
* compare, an H reading, a mixed pull or a repository outside `split.repos`
* requests exactly as the path-only plan, and the verdict row says which.
*
* The low-risk skills arm (maintainer ruling 2026-11-14 on #33501,
* 「同意 把低风险的 Tier H 放权给座位」): when EVERY governed hit is a catalog
* row carrying `lowRisk` for the target (`lowRiskArmReadable`), the follow-up
* reads the arm's own reading with the register's own readers
* (`lowRiskReadingFor`: `pullLowRiskReading` over the pull answer,
* `pullCatalogStatuses` over the file walk, `fetchTimelineOver` over the relay
* token, and `pullChangesetReading` / `pullCatalogReading` from the checkout
* once the compare answers the merge base and the head is fetched by sha at
* depth `ahead_by + 1`), hands it to `governedReviewPlan`, and the arm's own
* `lowRiskArmVerdict` decides: Tier S requests nobody. ⛔ Fail closed: a
* condition broken (`Clause-②` not a bare `no`, a `security` label now or
* removed, a catalog path named for security, auth or permission, a catalog
* file added, deleted, renamed or not regular, a changeset releasing more than
* the skills catalog, a path off the allowlist), a reading not made (no
* checkout, an unread timeline, a refused compare, a head past
* `LOW_RISK_FETCH_DEPTH_CAP`, another repository, a failed fetch), a mixed
* pull or a repository outside `lowRisk.repos` requests exactly as the
* path-only plan, and the verdict row says why.
*
* ## 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 { execFileSync } from 'node:child_process';
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 {
applyLowRiskArm,
applyWorkflowSplit,
fetchTimelineOver,
GOVERNED_TIER_H,
GOVERNED_TIER_S,
governedPathsIn,
HUMAN_MERGE_LINE_THRESHOLD,
landingTierOf,
LOW_RISK_ARM_RULING,
pullCatalogReading,
pullCatalogStatuses,
pullChangesetReading,
pullLowRiskReading,
pullPathsFrom,
readWorkflowDiff,
repoIdForSlug,
slugFromRemote,
} from '../check-governed-merges.mjs';
import { authorizedApprovalVerdict, GOVERNED_APPROVERS, unreadableApproval } from '../check-governed-queue-guard.mjs';
import { readSignatureLine } from '../check-half-states.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,
advisoryNoteSectionFailure,
parseRelayAdvisoryAnnotation,
parseRelayAdvisoryNoteAnnotation,
parseRelayAdvisoryReadAnnotation,
parseRelayAnnotation,
readPrBodyTrailer,
RELAY_ANNOTATION_PREFIX,
relayAdvisoryAnnotationMessage,
relayAdvisoryNoteAnnotationMessage,
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,
advisorySealAad,
ADVISORY_DESCRIPTION_MAX_CHARS,
ADVISORY_NOTE_KEY_ENV,
ADVISORY_NOTE_MASK_MIN_CHARS,
ADVISORY_NOTE_NOT_RESENT,
ADVISORY_NOTE_OPEN_FAILED,
ADVISORY_NOTE_RELAY_PUBLIC_KEY,
ADVISORY_NOTE_SEPARATOR,
ADVISORY_NOTE_STATES,
advisoryDescriptionOf,
advisoryNoteDescription,
advisoryNoteDigest,
advisoryNoteFenceFailures,
advisoryNoteKeyFailure,
advisoryNoteLandedText,
advisoryNotePrivateKey,
advisoryNoteReadBack,
codePoints,
openAdvisoryNote,
sealAdvisoryNote,
ADVISORY_LIST_ACCESS_REMEDY,
ADVISORY_LIST_CAP_HIT,
ADVISORY_LIST_CURSOR_REFUSED,
ADVISORY_LIST_FIELDS,
ADVISORY_LIST_LANDED,
ADVISORY_LIST_OVER_CAP,
ADVISORY_LIST_PAGE_CAP,
ADVISORY_LIST_PAGE_SIZE,
ADVISORY_LIST_PADDED_BYTES,
ADVISORY_LIST_REPEATED,
ADVISORY_LIST_SHORT_PAGE_NEXT,
ADVISORY_LIST_SENDER_REFUSED,
ADVISORY_LIST_STATES,
ADVISORY_LIST_UNREACHED,
ADVISORY_READ_MAX_PARTS,
ADVISORY_READ_MAX_SEALED_CHARS,
ADVISORY_READ_SENDER_GATES,
advisoryListCall,
advisoryListDisplay,
advisoryListNextCursor,
advisoryListPadded,
advisoryListPageFailure,
advisoryListPagePath,
advisoryListPlaintext,
advisoryListProjection,
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,
MERGE_QUEUE_READ_QUERY,
RERUN_FAILED_ATTEMPT,
answerPlaceholder,
enqueueFrontFenceFailures,
enqueueFrontFenceText,
enqueueFrontLandedText,
enqueueFrontReadBack,
enqueueFrontSizeLift,
ENQUEUE_FRONT_REVIEWS_PAGE_SIZE,
DEQUEUE_QUEUE_READ_QUERY,
RELAY_COMMENT_AUTHOR,
signedByLandingSeat,
dequeueAuditBody,
dequeueCauseReading,
dequeueFenceFailures,
dequeueFenceText,
dequeueLandedText,
dequeuePullAfter,
dequeueReadBack,
mergeQueueOf,
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.
* A refusal keeps its status; the platform's `message` is printed only when it reproduces no prose of the body sent
* (`advisoryProseOf`, the `QUOTE_WINDOW` test `advisoryRefusalCause` applies), so a refusal that echoes an issue's
* title or body cannot carry it into the row, the log line or the step summary.
*/
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 };
if (typeof json?.message !== 'string') return { ok: false, why: `HTTP ${status}` };
const known = advisoryProseOf(req?.body);
if (quotesKnown(json.message, known) || quotesKnown(flattenRefusalText(json.message), [...known, ...known.map(flattenRefusalText)])) {
return { ok: false, why: `HTTP ${status} — the platform's message is not printed: it quotes the body sent, and no row prints that` };
}
return { ok: false, why: `HTTP ${status} — ${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).
*
* `workflowDiff` is the queue guard's own reading (`readWorkflowDiff`, see `workflowReadingFor`), handed to
* `applyWorkflowSplit`: only a MEASURED reading can move the `workflows` row to S, and only in its `split.repos`;
* null — every path-only call — keeps that row H, so the answer is byte-identical to the path-only plan.
*
* `lowRisk` is the low-risk skills arm's own reading (`pullLowRiskReading`, see `lowRiskReadingFor`), handed to
* `applyLowRiskArm` after the split, exactly as the register's `governedTierFor` chains them: only a reading
* `lowRiskArmVerdict` holds to every condition moves the catalog rows to S; null, or any reading it cannot hold,
* keeps them H, so a path-only call answers as before. `lowRiskVerdict` is that verdict, or null when no arm row
* was hit, for the row's words.
*
* 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, workflowDiff = null, lowRisk = null } = {}) {
const repoId = repoIdForSlug(repo);
const matched = repoId ? governedPathsIn(Array.isArray(paths) ? paths : [], repoId) : [];
const read = matched.length === 0 ? [] : applyLowRiskArm(applyWorkflowSplit(matched, repoId, workflowDiff), repoId, lowRisk);
const tier = matched.length === 0 ? null : landingTierOf(read);
const lowRiskVerdict = read.find((s) => s?.lowRiskVerdict)?.lowRiskVerdict ?? null;
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, lowRiskVerdict, 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}`;
}
/**
* Whether the `workflows` split may be READ for this plan (header: "The governed-review follow-up"): a Tier H plan
* whose EVERY governed hit is a row with `split` naming this repository. Pure. `{ read: true }`, or `{ read: false,
* why }` — the words the verdict row adds, so the log says which case kept the path-only H. ⛔ Any other governed
* hit (Tier S or H) keeps the plan exactly as the path-only reading answers: a mixed pull is never split here.
*/
export function workflowSplitReadable(plan) {
const hits = Array.isArray(plan?.matched) ? plan.matched : [];
const splitRows = hits.filter((s) => s?.split);
if (plan?.tier !== GOVERNED_TIER_H || splitRows.length === 0) return { read: false, why: null };
const others = hits.filter((s) => !s?.split);
if (others.length > 0) return { read: false, why: `another governed row is hit too (${others.map((s) => `\`${s.glob}\``).join(', ')}), so the path-only tier stands` };
const outside = splitRows.filter((s) => !s.split.repos.includes(plan.repoId));
if (outside.length > 0) return { read: false, why: `${plan.repoId} is not in the row's split.repos (${outside[0].split.repos.join(', ')}), so the path-only tier stands` };
return { read: true, why: null };
}
/**
* Whether the low-risk skills arm may be READ for this plan (header: "The governed-review follow-up"): a Tier H plan
* whose EVERY governed hit is a row carrying `lowRisk` for this repository. Pure; the same `{ read, why }` shape as
* `workflowSplitReadable`. A cost gate only — it can keep a plan H, never move one to S; the tier is the arm's
* (`applyLowRiskArm` in `governedReviewPlan`), which reads any other row beside a catalog row as H anyway, so a
* mixed pull or another repository costs no timeline walk, compare or fetch.
*/
export function lowRiskArmReadable(plan) {
const hits = Array.isArray(plan?.matched) ? plan.matched : [];
const armRows = hits.filter((s) => s?.lowRisk);
if (plan?.tier !== GOVERNED_TIER_H || armRows.length === 0) return { read: false, why: null };
const others = hits.filter((s) => !s?.lowRisk);
if (others.length > 0) return { read: false, why: `another governed row is hit too (${others.map((s) => `\`${s.glob}\``).join(', ')}), so the path-only tier stands` };
const outside = armRows.filter((s) => !(Array.isArray(s.lowRisk.repos) && s.lowRisk.repos.includes(plan.repoId)));
if (outside.length > 0) return { read: false, why: `${plan.repoId} is not in the row's lowRisk.repos (${(outside[0].lowRisk.repos ?? []).join(', ')}), so the path-only tier stands` };
return { read: true, why: null };
}
/**
* How far past its merge base a head may be for the relay to read its catalog files: the head is fetched at
* depth `ahead_by + 1`, which holds the merge base (every commit on the shortest path from the head down to it
* lies in the compare's ahead set), so `pullCatalogReading` computes the merge base in this checkout. Past it,
* the reading is NOT MEASURED and the approvers are requested.
*/
export const LOW_RISK_FETCH_DEPTH_CAP = 200;
const FULL_SHA = /^[0-9a-f]{40}$/;
const GIT_FETCH_TIMEOUT_MS = 120_000;
/**
* The workflow reading for ONE pull, merge base → head, the queue guard's `pull_request` leg (`readWorkflowDiff`
* imported, ⛔ no second reader): `GET /repos/{repo}/compare/{base.sha}...{head.sha}` answers the merge base; the
* checkout must be `repo` by its `origin` (`slugFromRemote`); the two commits are fetched by sha at depth 1 when the
* checkout lacks them (the relay checks out `main` at depth 1, anonymously — the repository is public), then
* verified present; the diff is read with the merge base as base AND inventory base. `git(argv)` returns stdout and
* throws — the seam; null is "no checkout". ⛔ Fail closed: every failure answers `{ measured: false, reason }`,
* which `applyWorkflowSplit` reads as Tier H. Never throws.
*/
export async function workflowReadingFor({ repo, paths, pr, api, t, git = null }) {
const unmeasured = (reason, extra = {}) => ({ measured: false, reason, base: null, head: null, files: [], ...extra });
if (typeof git !== 'function') return unmeasured('no checkout was handed to this run, so the workflow diff cannot be read');
const head = pr?.head?.sha;
const tip = pr?.base?.sha;
if (!FULL_SHA.test(String(head)) || !FULL_SHA.test(String(tip))) return unmeasured("the pull's head or base sha could not be read off its answer");
const cmp = await rest(api, `/repos/${repo}/compare/${tip}...${head}`, {}, t);
const mergeBase = cmp.json?.merge_base_commit?.sha;
if (cmp.status !== 200 || !FULL_SHA.test(String(mergeBase))) return unmeasured(`${cmp.call} -> HTTP ${cmp.status}${cmp.detail ? ` (${cmp.detail})` : ''}: the merge base could not be read`, { head });
const first = (error) => String(error?.stderr || error?.message || error).trim().split('\n')[0];
try {
const origin = slugFromRemote(git(['remote', 'get-url', 'origin']));
if (!origin || origin.toLowerCase() !== String(repo).toLowerCase()) return unmeasured(`the checkout is ${origin ?? 'an unparsed origin'}, not ${repo}, so it cannot vouch for this pull's commits`, { base: mergeBase, head });
} catch (error) {