Repository navigation
Expand file tree
/
Copy pathcheck-governed-queue-guard.mjs
More file actions
5491 lines (5341 loc) · 342 KB
/
Copy pathcheck-governed-queue-guard.mjs
File metadata and controls
5491 lines (5341 loc) · 342 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.
/**
* check-governed-queue-guard — the PREVENTION half of the governed-surface
* regime (#11704). The sibling `check-governed-merges.mjs` is the DETECTION
* half: it enumerates governed merges AFTER they land, report-only by design.
* This one runs on the merge-queue build and REFUSES.
*
* node scripts/pm/check-governed-queue-guard.mjs # in CI, from the event payload
* node scripts/pm/check-governed-queue-guard.mjs --self-test # offline, no network, no git
*
* ## Why a refusal exists at all, when the per-PR gate was retired
*
* The 2026-08-18 ruling retired `ADR maintainer approval` because it was RED
* ON EVERY GOVERNED PR by design — 红灯常态化本身有毒, a permanently red check
* trains everyone to ignore red — and because it sat outside the required set,
* so it never blocked anything anyway. Detection moved to the post-merge audit.
*
* Three years of that regime is not what happened next; three INCIDENTS are.
* #9550, #10580 and the #9319 landing each ended with a governed diff enqueued
* or merged with zero reviews, and each was caught by ACCIDENT — a merge
* conflict, a `GH006 branch locked` rejection on a concurrent push, a webhook
* that happened to wake a live seat. The card that recorded the second one
* (#10580) put the remaining question in one sentence, verbatim:
*
* > **Guard gap.** Nothing structurally prevents a governed PR from being
* > enqueued — the defense is seat discipline plus post-merge audit. […]
* > Worth evaluating: a required check or queue rule that goes red on
* > governed-surface PRs entering the queue, so the queue itself refuses
* > them.
*
* ⭐ THE DESIGN THAT KEEPS THIS FROM BECOMING THE RETIRED GATE AGAIN is the
* split by EVENT, and it is the single most load-bearing decision in this file:
*
* `merge_group` → a governed diff without an AUTHORIZED approval pinned to
* the PR's current head is a REFUSAL. The queue build is
* the last thing between a speculative merge and `main`,
* and it is the path a SEAT uses. This is the prevention.
* `pull_request` → the same finding is an EARLY WARNING that exits 0.
*
* The PR run must not redden, and not for politeness. A governed PR sitting as
* a draft while it waits for an authorized approval is the CORRECT resting
* state of the regime — 「四件套留 draft 等人批,⛔ 不翻正式不入队;获授权批准后
* 认领席落地。」 — so a check that is red on it is red on the healthy case,
* forever, which is precisely the poison the 2026-08-18 ruling named. The queue
* build, by contrast, is a state an UNAPPROVED governed PR should never be in
* at all; red there is red on the anomaly.
*
* ⭐ AND WHAT HAPPENS AFTER THE APPROVAL IS THIS CHECK'S OWN PASS PATH, which
* is why the queue leg is not only a refusal. Ruling C (#17971, maintainer
* 2026-09-13, verbatim 「C. approve 后不管后续改动都由席位落地:」) puts the
* landing in the CLAIMING SEAT's hands once an authorized APPROVED review is on
* record — 「席位落地 = 过落地前检、清标、ready、auto-merge,踢出/变基同法。」 — so
* the seat's ready → enqueue is the CORRECT next act there rather than a
* violation, and an ejection or a rebase costs no second click.
*
* ⚠️ The consequence is worth stating out loud rather than discovering: this
* guard CANNOT stop a maintainer merging a governed PR directly, and does not
* try. A direct merge produces no `merge_group` event. Under this regime that
* is not a hole — it is the OTHER landing, the one an UNAPPROVED governed PR
* still has: 「受管面由维护者人合或授权批准后席位落地」 (measured: #11387 was
* read as an incident for 13 minutes on exactly this confusion, until the
* maintainer answered 「是我合并的」). What this guard closes is the seat path
* taken with NEITHER of those: flip ready → enqueue → the queue is the entire
* review.
*
* ## What satisfies it — an AUTHORIZED approval, on ANY commit
*
* The predicate has three dated layers; the LATEST one is the one enforced,
* and each earlier layer still contributes the half that was not superseded.
*
* #8161 ruled the original predicate — 「门禁改成只要求「APPROVED review 存在」」/
* 「不要指定具体的人」 — because the identity proxy was then unsatisfiable:
* human and agent GitHub accounts are not stably partitioned (「人工专属账号 和
* agent 账户一直在切换,暂时没固定」), cloud sessions author under the
* maintainer's own account, and GitHub forbids self-approval — so an
* identity-keyed gate went permanently red exactly when the human WAS driving.
*
* 2026-08-27 NARROWED it. The maintainer asked, verbatim: 「需要我人工审查的,如果
* 我真的审查了,并且点了批准,也不能合并吗?还是要等我 bypass吗」 — and ruled the
* authorized set, verbatim: 「os-zhuang hotlong 批准算数」. ⭐ THAT HALF STANDS,
* and it is this predicate's whole identity control: only an account in
* `GOVERNED_APPROVERS` (the single source — protocol text references the
* constant, never copies the names) can satisfy this leg. What that ruling ALSO
* carried — that the approval's `commit_id` must equal the PR's CURRENT head
* sha — is the half 2026-09-04 superseded.
*
* 2026-09-04 UNPINNED it. Said in the live PM chat while a governed PR that an
* authorized approver had approved three times kept falling out of the merge
* queue, verbatim and untranslated:
*
* > 你的门禁有问题,只需要有人工批准记录就行,不需要卡最新的提交。
*
* So the queue leg passes a governed PR iff an account in `GOVERNED_APPROVERS`
* holds a latest-decisive review that is APPROVED — on ANY commit, with
* `commit_id` unread by the decision. This ruling supersedes the sha-pin half
* of the 2026-08-27 predicate and NOTHING else: the approver set of that ruling
* (「os-zhuang hotlong 批准算数」) stands, DISMISSED and superseded approvals
* still never count, an unauthorized APPROVED still never counts, and an empty
* or unreadable review list still fails closed. review → Approve → done: the
* queue merges, and the direct merge stays the fallback path.
*
* ⚖️ THE ACCEPTED COST, stated out loud rather than left to be discovered: a
* push after an approval is no longer re-reviewed by this gate — the approval
* rides through whatever is pushed next, and this file no longer knows the
* difference. The maintainer accepts it. It is the same shape of cost the
* 2026-08-12 ruling on the retired per-PR gate accepted when it dropped the
* identity proxy (「不要指定具体的人」, accepted cost: no signal can prove a
* review is human); the institutional-memory section of
* `check-governed-merges.mjs` carries that history.
*
* The head sha is still READ and still PRINTED — a queue log names the commit
* each approval was given on, so the cost above is visible at the moment it is
* being paid — but it DECIDES nothing. Two consequences follow and neither is
* optional: an unreadable head is no longer a refusal (a read that decides
* nothing may not block a landing), and ⛔ nothing may re-derive a refusal from
* that printed reading without a new ruling.
*
* #11704's retraction still bounds the design: attribution from the GitHub
* actor field is not a reading, so this guard stays keyed on the DIFF'S PATHS
* and on the review record — the one artifact that IS a deliberate, timestamped
* human act on the pull request — never on who pushed or merged.
*
* The #8161 identity concern did not vanish; it moved into a NORMATIVE
* prohibition landed with this predicate: ⛔ an agent seat never submits an
* approving review on a governed-surface PR, under ANY account. `os-zhuang` is
* also operated by agent seats, so with it in the authorized set the technical
* control is normative for any agent holding those credentials — same class as
* the seat-side no-merge rule. The Director's governed-merge audit reads the
* APPROVER as well as the merger; an agent-submitted governed approval is an
* incident. ⚠️ With the sha pin retired that prohibition carries more weight,
* not less: it is now the ONLY thing standing between an agent seat holding an
* authorized account and a governed landing it cleared for itself.
*
* ⚠️ An outstanding CHANGES_REQUESTED from ANOTHER reviewer does NOT flip the
* verdict here, and that is deliberate restraint rather than an oversight: the
* ruled predicate is one authorized APPROVED review (a reviewer's own later
* CHANGES_REQUESTED or DISMISSED does supersede their approval), and widening
* a governance gate past its own ruling is how gates acquire policy nobody
* agreed to. It is printed loudly as an informational line so a reader is
* never surprised by it. Widening it is a one-line maintainer decision.
*
* ## The ENQUEUE leg — the maintainer's own enqueue IS the review (2026-10-26)
*
* The maintainer, on the phone, where the button is "Merge when ready" (an
* enqueue) and the queue guard then still wanted a separate Approve — verbatim
* and untranslated (#26066):
*
* > 也就是说推送到我的手机上,以前都是需要我点一下核准,然后再点合并,以后我可以直接点合并是吗
* > 大部分我还是希望入队,但是我想省掉 Approve
*
* and the logins behind that click: 「os-zhuang 或 hotlong」 — both already in
* `GOVERNED_APPROVERS`, which stays the single source and does not grow. So the
* `merge_group` leg passes a governed pull request iff EITHER an authorized
* account holds a latest-decisive APPROVED review (the 2026-09-04 predicate
* above, unchanged and read FIRST) OR the account that put this entry in the
* queue is an authorized one. Everything else stands: an enqueue by any other
* account still needs the approval, Tier S still lands on its record, a fork is
* still lifted by nothing, and the bypass-rules direct merge is still the other
* landing.
*
* ⭐ WHY THIS IS NOT THE ACTOR-FIELD ATTRIBUTION #11704 RETRACTED. That
* retraction refused to read "who pushed or merged" as a review. The ruling
* that founded this regime (2026-08-18, carried in `check-governed-merges.mjs`)
* already named the enqueue as the record — 「人工合并即人工审核:governed PR 的审核
* 记录 = 你按下合并/入队那个动作本身」 — and the identity concern behind the
* retraction is answered for this leg exactly as it is for the approval leg,
* normatively: ⛔ no agent seat enqueues or arms auto-merge on an unapproved
* governed PR, under ANY account (AGENTS.md Prime Directive #14). An entry an
* authorized account made can therefore only be the human's click, as an
* authorized approval can only be the human's review. With this leg that
* prohibition carries the same weight the approval-side one does: it is the
* ONLY thing between an agent seat holding an authorized account and a governed
* landing it cleared for itself, and the post-merge audit reads the enqueuer
* the way it reads the approver.
*
* ⭐ THE READING, MEASURED on this repository on 2026-10-26 (REST): the actor
* of the NEWEST `added_to_merge_queue` timeline event. "Merge when ready" with
* checks pending ARMS auto-merge and the platform enqueues later; the add
* event's actor is then the account that armed it (#26154, #26011). A direct
* enqueue leaves an add event and never sets `auto_merge` (#26166). The pull
* object's `auto_merge.enabled_by` therefore answers the first path only, is
* null on the second and after a merge, and is not read. The timeline route
* answers `X-Accepted-GitHub-Permissions: issues=read; pull_requests=read`, so
* the workflow's existing `pull-requests: read` covers it.
*
* ⛔ UNDETERMINED IS NEVER A PASS, and never a refusal of its own: no add event,
* an add with no actor, an unreadable or truncated timeline (the newest event is
* on the LAST page), and a newest queue event that is a REMOVAL — the entry this
* build judges not yet on the timeline, so the add before it is an entry that
* already left — all leave the approval leg to decide alone, on its own exit
* code. ⚖️ The accepted cost, stated where it is paid: as with an approval on
* any commit, a push made after the click and before the entry lands is not
* re-reviewed here; and the click counts for THAT entry only — a seat's
* re-enqueue after an ejection is a new entry by a seat account, which needs
* the approval or another such click.
*
* ⚖️ THE COST: one timeline read per governed pull request the approval did
* not satisfy — never for one it did (MONOTONE, read SECOND, and a Tier S
* record is consulted only after it). The SIZE leg follows the same predicate
* through the sibling's lift (`sizeLiftFrom`, which reads the enqueue reading
* handed to it beside the approval verdict); an oversized pull request the
* governed leg already read costs no second timeline read.
*
* ## Ordering: the path test runs FIRST, and a clear diff costs zero API calls
*
* ⛔ Fail-open on an API error is WRONG in this file — this guard exists
* because everything else in the chain failed open — so an unreadable review
* list is a REFUSAL with its own distinct message and its own exit code, never
* a pass. But a diff that touches nothing governed must never be blocked by an
* API hiccup either, and the two requirements are reconciled by ORDER, not by
* tolerance: `runGuard` decomposes the diff and returns before constructing a
* single request when nothing governed is in it. The self-test pins that with
* a `fetchReviews` that THROWS if it is called at all — a spy, not a mock,
* because "we did not need the API" is the claim under test.
*
* ## Multi-PR merge groups, and the under-enumeration trap
*
* A merge group can carry SEVERAL pull requests. `merge_group.head_ref` names
* only the LAST one (`…/gh-readonly-queue/main/pr-<N>-<sha>`), so keying the
* whole group's diff to that one PR would check the wrong PR's reviews — and
* would do it in the direction that reads as compliance: PR B is approved,
* PR A's governed diff rides in behind it. Under-enumeration is the one
* direction a governed-surface reading must never be wrong in (#9902).
*
* So the group is decomposed PER COMMIT: each first-parent commit between
* `base_sha` and `head_sha` is one PR landing, its PR number read from its
* subject by the sibling's `pullNumberFromSubject` (both GitHub spellings),
* and every governed PR is checked on its OWN reviews. A commit that touches a
* governed path and names no PR is UNATTRIBUTED — its own refusal, with its
* own exit code, because a governed change nobody can attribute to a reviewable
* pull request is the most anomalous thing this file can encounter.
* `head_ref`'s PR number is used as a fallback only when the group holds
* exactly one commit, where it is unambiguous.
*
* The `pull_request` leg is NOT decomposed: its payload names the one pull
* request being judged, so every governed path is attributed to that number
* (a subject naming an issue would read the issue's reviews), and the paths
* are the net diff against the merge-base (a merge of `origin/main` on the
* branch would otherwise forecast every path `main` already landed). See
* `enumerateRows`; the `merge_group` reading above is unchanged by it.
*
* ## The generated-artifact exception is honoured, and that is not optional
*
* A generator-owned file sitting inside a governed surface makes routine
* traffic cross the fence, and a guard that refuses routine traffic is the same
* poison one level down. So the register's provenance exception is applied here
* through its own `applyGeneratedExceptions`, with provenance recomputed on this
* build's own tree — never a stored baseline, and fail-closed on every error
* path, exactly as the ruled constraints require.
*
* ⚖️ The original case for this — `.claude/workflows/docs-accuracy-audit.js`
* holding a required gate's own `--write` artifact, so EVERY page-adding docs PR
* touched the governed surface (measured 5-for-5 on #9866) — is GONE, and by a
* different remedy: on 2026-09-01 the maintainer ruled that list off the governed
* surface entirely (#13591, verbatim 「同意」). Its register row retired with it.
* The mechanism stays because the #11705 rows still need it, and because the
* shape recurs; ⛔ its absence from a diff is not a reason to relax anything.
*
* NOTHING about the exception is decided here: membership is the register's
* `generatedExceptionFor` and the recompute is its `recomputeProvenanceFor`,
* both imported rather than reimplemented, so this guard and the seat-side
* `--test` predicate cannot answer differently about the same diff. That
* sharing is a #11705 ruled constraint ("⛔ do not author a second mechanism")
* and it is also what makes a new register row reach this file for free.
*
* ⭐ THE JOB INSTALLS DEPENDENCIES, and that is what makes the #11705 rows
* (generator-owned files inside `skills/**`) answerable here at all. They
* recompute by running the generator's own `--check` through `pnpm … exec tsx`,
* so with no toolchain they used to fail closed on EVERY run: a spec PR
* carrying its regenerated `references/_index.md` stayed governed at
* merge-group time and needed a pinned approval, while the seat-side `--test`
* lifted the very same diff in a dev container. Two tools, same register, two
* answers — the one shape #11705's "⛔ do not author a second mechanism" exists
* to prevent, arrived at through the ENVIRONMENT rather than through a second
* copy of the code. The header used to file the install as a trade nobody had
* ruled on. The maintainer ruled it (2026-09-01, verbatim):
*
* > 纯生成的指针行(spec 源变更后再生成的 references/_index.md) 不需要我审核吧
*
* What the install does NOT do is soften anything. The exemption is still the
* register's own byte-exact recompute against this build's own tree, every
* error path still fail-closed, and hand-authored governed content — including
* a hand edit sitting in the same commit as a certified regeneration — still
* needs the pinned approval. The only thing that changed is that the recompute
* can now actually run.
*
* ⚠️ The degradation is deliberate and is the reason every toolchain step in
* the workflow is `continue-on-error`: a broken install (registry outage, cache
* miss, a PR that moves `pnpm-lock.yaml` out of sync) leaves this job in
* EXACTLY the state it was in before the install existed — the generator cannot
* spawn, the recompute answers "the generator toolchain is not available in
* this environment", and the path stays GOVERNED. A diff that touches nothing
* governed is still never blocked by any of it: the path test runs first and
* returns before provenance is consulted at all.
*
* ## The TIER leg: the references TIER of the governed surface (#17950/#18020)
*
* Everything above judges a governed diff as ONE population. On 2026-09-13 the
* maintainer tiered it, and the boundary put to them is the operative text, so
* it is reproduced rather than paraphrased (untranslated — rewriting a quoted
* ruling rewrites the ruling):
*
* > **事实层(席内契约复审档复核后入队)**:只有
* > `.claude/skills/pm-dispatch/references/**`——平台读数表、runbook、契约复核细则、
* > 车道文件、状态机细则。
*
* — answered 「我点头」. The other half of that boundary, the 规则层, is every
* remaining governed path and is quoted in full on #17950; ⛔ it is NOT excerpted
* here, because a partial rules-layer list read as the whole one is precisely
* the under-claim `check-governed-prose` exists to stop. The charter text landed
* as PR #18018; this leg is what made it ENFORCED rather than declared, which is
* the whole of #18020 — narrowly, for the one prefix quoted above.
*
* ⭐ SUPERSEDED 2026-09-18 (#19133, ruled 「同意改规则。」 on the skills seat's
* proposal; the amendment moved `.claude/settings.json` and `.claude/hooks/**`
* over too: 「我觉得这些我也没必要确认」): the quote above is reproduced as the
* ruling that STARTED this leg, not as the population it enforces today. #19133
* widened that population from the one prefix quoted above to the WHOLE of
* `.claude/**` — Tier S, in the register's own words — leaving Tier H as exactly
* the register's other rows. The register's `tier` field is the enumeration now;
* this leg asks `governedTierFor` for Tier S, never a prefix repeated here — see
* the "landing TIER" section below for the enforced definition, and read it live
* with `node scripts/pm/check-governed-merges.mjs --test <paths>` rather than
* trusting a prefix copied into prose, which is exactly what went stale once.
*
* So a governed diff whose governed paths are ALL Tier S — today, the whole of
* `.claude/**` — may land on a REVIEW OF RECORD in place of the authorized
* approval: the `## Contract review` comment — on the
* PULL REQUEST'S THREAD **or on its CARD'S** — that names the pull request's
* CURRENT head, carries a `Reviewed-by:` line, and declares a `Served-tier:`
* reading that STANDS -- its token being the NAME `CONTRACT_REVIEW_TIER`,
* ⛔ never a model identifier, which `AGENTS.md` lets land in no comment and a
* record IS one (#18060). Every governed path outside Tier S is Tier H, the
* rules layer, and keeps the predicate above byte-for-byte.
*
* ⭐ THE TWO CARRIERS ARE ONE DELIVERY, and the location is the governed text's
* to decide rather than this file's — quoted, untranslated, because it IS the
* criterion: 「复核记录 = 一条评论落 PR 或卡」
* (`references/contract-review.md`), 「记录 = 同形评论落 PR 或卡」 (`SKILL.md`
* 〈入队与落地〉). Until #18701 this leg read the PR thread ALONE while the
* sibling's `--pair`, its `--template` and the rule itself all said either, and
* the cost was measured on PR #18689: the seat's record sat on card #18426, the
* queue leg answered 「0 comment(s) read on the PR thread」, the pull request was
* dequeued `CI_FAILURE`, and only a SECOND COPY of the same comment on the PR
* thread cured it. The thread set now travels inside the imported reader (see
* `recordVerdict`), so the set this leg searches and the set `--template`
* offers cannot be edited apart — a cross-tool pin in `record-recognisers.mjs`'s
* self-test drives this guard to prove it.
*
* ⚖️ THE CARD IS DERIVED, never configured: from the pull request's own body
* by the closing-keyword / `Part of` / branch-name relation the whole regime
* pairs a PR with its card by (`deliveredCardNumber`, which asks
* `deliveryEvidence`). A pull request whose card cannot be derived — none
* named, or two named at equal strength — searches NO card thread and says so
* in the refusal. That is the refusing direction, which is the only direction a
* governed reading may be wrong in, and it leaves the PR-thread reading exactly
* as it was.
*
* ⭐ THE PROPERTY THAT MAKES THIS SAFE TO SHIP, and it is measured rather than
* asserted (see the battery): this leg is MONOTONE. It is consulted only for an
* entry the approval predicate did NOT satisfy, so it can turn a refusal into a
* pass and can never turn a pass into a refusal. A references-only PR that an
* authorized approver approved still clears on the approval alone, at exactly
* today's cost, and reads exactly today's words.
*
* ⭐ RECOGNITION IS IMPORTED, NEVER RE-IMPLEMENTED — and since #18701 the
* WHOLE reading is, not only the facts it is made of. `locateReviewOfRecord`
* (`record-recognisers.mjs`, the function that file composes the record
* reading with) is what this leg calls: heading marker, head-sha span test, newest-of
* resolution, `Reviewed-by:` key line, `Served-tier:` reader — and THE SET OF
* THREADS to run them over. That last one is the fact a spelled-out filter here
* could not copy, and it is what dequeued #18689.
*
* ⛔ So this file spells no filter of its own any more. What is left here is
* the TIER gate on top of the located record, which is this leg's own fact and
* nobody else's. The H51/H47 recognisers still own every line of the
* recognition; they are simply reached through the file that already composes
* them, which imports them at module scope — so a rename there stops that
* module loading and this leg fails CLOSED with the loader's own reason.
*
* ⚠️ THE IMPORT IS LAZY, AND THAT IS LOAD-BEARING — see `REVIEW_OF_RECORD_LOCATION`
* for the cycle it walks around, and `loadRecordRecognisers` for the rule that
* keeps the walk legal. A failed load is a REFUSAL, never a pass.
*
* ⚖️ THE COST: up to TWO extra thread reads (the PR's and its card's), bought
* ONLY for a references-tier pull request with no authorized approval — the
* population that is refused outright today, so nothing that passes now pays
* anything. The card's NUMBER costs nothing at all: it is read off the pull
* object the head read already fetches. The head sha, which decides
* nothing on the rules layer since 2026-09-04, IS decisive here: a record names
* a head, so a head this guard could not read can find no record. That is not a
* revival of the retired sha pin — it is the RECORD's own identity test, and it
* applies to nothing but this tier.
*
* ## The FOURTH leg: the SIZE line (#19036, maintainer ruling 2026-09-18)
*
* Everything above is keyed on PATHS or on a LABEL. On 2026-09-18 the
* maintainer ruled a limb keyed on the NUMBER, verbatim and untranslated:
*
* > 修改代码量超过某个行数(比如5000)就应该人工审核
*
* and on 2026-10-09 lowered the line, verbatim and untranslated:
*
* > 这种大额改动就应该人工审核,我还是建议5000行的人工审核门槛降到 3000,立卡。
*
* PR #19033 landed it seat-side: `testVerdict(paths, { size })` in the sibling
* carries a `size` limb, `HUMAN_MERGE_LINE_THRESHOLD` (3,000) is declared
* there ONCE, the comparison is `additions + deletions` STRICTLY greater, and
* generated files are INCLUDED — the case that prompted the ruling, PR #18971
* (+238,310 / −119, 237,706 of them regenerated), touched no governed path and
* landed through THIS leg's queue build on an AI review alone. The seat-side
* `--test` / `--pr` / `--branch` refused from that day; the queue did not,
* because `runGuard` handed the predicate no size (#19036, class (b): a
* declared contract the queue could not hold). This leg is the queue half.
*
* ⭐ IMPORTED, NEVER RESTATED — the ruled constraint, and the reason the
* ablation in the PR that landed this inverts the comparison in the SIBLING
* and watches THIS file's pins redden: the threshold, the comparison and the
* generated-files inclusion are `sizeVerdict`'s, reached through
* `testVerdict([], { size })` and judged by `landsByHumanMerge`. With an empty
* path list that call IS the size limb alone: the PATH limb is the governed
* leg's question, already answered on the LIFTED rows with the register's
* exception applied, and a raw path list handed here would judge it a second
* time without the lift — the two-mechanisms shape #11705 forbids. This file
* declares no threshold and spells no comparison; the self-test pins both
* absences against this file's own source.
*
* ⚖️ THE COST, and why EVERY queued pull request pays it: the size is a
* property of the pull request, not of a governed path, so it cannot ride the
* governed leg's head read — that read exists only for rows the register
* classes as governed, and the case this leg exists for (#18971's shape: over
* the line, NOTHING governed) never reaches it. So this leg reads
* `GET /pulls/{n}` once per queued pull request, through the SAME
* `makePullReader` the governed leg uses (the pull object already carries
* `additions` / `deletions`; the reader's shape grew a `size`, no second
* endpoint) and under the same `pull-requests: read` scope, nothing wider.
* Merge groups are small, so the bill is one read per PR per build, and the
* block prints its own count. The zero-cost-clear rendering above is scoped
* to say so (#15406's lesson, a third time).
*
* ⛔ FAIL-CLOSED ON AN UNREADABLE SIZE, and this is the one place the
* 2026-09-04 rule 「a read that decides nothing may not block a landing」 cuts
* the OTHER way: this read DECIDES. A pull read that fails, or a pull object
* with no `additions` / `deletions` pair, is a refusal on its own code (exit
* 9), never a size of zero and never a pass — the sibling's `--pr` refuses on
* exactly that absence (exit 1 there) for exactly that reason.
*
* ⭐ AN AUTHORIZED APPROVAL LIFTS THIS LIMB (maintainer ruling 2026-09-27,
* #20153), exactly as it lifts a Tier H path. Until that day the landed
* predicate said a human MERGE and nothing else — 「人工审核」 landed as the same
* terminal a governed diff has (ACCEPT on the card, `needs-user-decision` on
* the PR, a final 维护者速读, review requested from `GOVERNED_APPROVERS`) and
* the maintainer's own click (人工直合); the 2026-08-27 ruling had said
* "approval lifts" of PATHS, nothing had said it of the NUMBER, and this file
* refused to widen a gate past its own ruling. PR #20125 (about 11.5k changed
* lines, APPROVED by `os-zhuang`) was then dequeued twice on exactly this
* limb, and the maintainer ruled, verbatim and untranslated:
*
* > 所以阈值写死成 5000 行 , 维护者已经批准了就是可以合并。
*
* So this leg now reads THE SAME authorized-approval verdict the governed leg
* reads — `authorizedApprovalVerdict`, one derivation, on ANY commit, with
* DISMISSED, superseded and unauthorized approvals never counting and an
* unreadable review list failing closed — and hands it to the sibling through
* the same front door as the size: `testVerdict([], { size, approval })`. The
* LIFT itself is the sibling's (`sizeLiftFrom`, read by `landsByHumanMerge`
* through `sizeLimbFires`), so the queue and the seat-side `--pr` answer on one
* predicate; this file spells no lift condition of its own. The threshold, the
* strict comparison and the generated-files inclusion are UNCHANGED, and so is
* the FORK limb: no approval lifts a fork. After the approval the OWNING seat
* lands the pull request through the queue (席位落地); the maintainer's direct
* merge stays the other landing. ⭐ #19344 — THAT CLICK IS ONE BUTTON OPTION
* and this text names it: `main` mandates the queue and requires this check,
* so the only Merge that is not an enqueue is the Merge button's BYPASS-RULES
* option, offered only while the ruleset configures a bypass actor. While none
* was, the remedy named a terminal nobody could reach and PR #19024 was
* enqueued and refused three times. That it IS offered is a ruleset fact the
* pin reads. No review of record (Tier S) lifts this limb: the ruling names an
* authorized APPROVED review, and a seat's own record is not one.
*
* ⚖️ THE COST: one review read (`GET /pulls/{n}/reviews`) per queued pull
* request that is OVER the line — the population this leg refused outright
* before, so nothing that cleared pays anything new — and none at all when the
* governed leg already read that pull request's reviews on this build: the
* verdict object is reused, never re-derived. An unreadable review list on an
* oversized pull request refuses on exit 8 (over the line, no lift proven),
* never on 9, which stays "the SIZE could not be read": the words carry which.
*
* ⚠️ `pull_request` leg: SILENT, byte-identical, like the governed leg. The
* seat-side pre-check already refuses an oversized PR before it is armed, and
* the ruling this leg implements is about the LANDING. (The `pull_request`
* payload carries `additions` / `deletions` for free; a forecast there is a
* one-line maintainer decision, not taken here.)
*
* ## Exit codes — the refusal is impossible to read as clean
*
* 0 CLEAR — nothing governed in the diff (no API call was made), or every
* governed PR carries an authorized APPROVED review (on ANY
* commit — 2026-09-04) or was enqueued by an authorized
* account (2026-10-26), or this is the `pull_request`
* early-warning run.
* 3 REFUSED — governed, and at least one governed PR carries no authorized
* APPROVED review (none at all, unauthorized account, dismissed
* or superseded) and was not enqueued by an authorized account
* (another account, or an UNDETERMINED enqueuer) — and, on the
* references tier, no review of record on its current head
* either.
* Deliberately 3, the same code the sibling's `--test`
* answers "GOVERNED" with, so the two tools agree on the number
* that means "this diff is governed and unsatisfied".
* ⭐ NOT split per tier, deliberately: the FACT is the same one
* ("this governed diff is unsatisfied") and the two remedies
* differ, so the rendering carries the difference and the exit
* register stays the one a reader already knows.
* 4 REFUSED — governed, and the REVIEW LIST could not be read — or, on the
* references tier, one of the record's threads (the PR's or its
* card's), its head, or the imported recognisers could not be.
* Distinct from 3 on purpose: "nobody approved" and "we could
* not find out" are different facts and must be separable in a
* log. ⚠️ An unreadable PR HEAD is NOT this refusal any more —
* since 2026-09-04 the head decides nothing, so it is recorded
* as a missing reading and the review list alone judges.
* 5 REFUSED — governed paths on a commit attributable to no pull request.
* 8 REFUSED — a queued pull request is over the human-merge line:
* `additions + deletions` strictly greater than the sibling's
* `HUMAN_MERGE_LINE_THRESHOLD`, generated files included
* (#19036, the 2026-09-18 ruling) — and NO authorized APPROVED
* review lifts it (none, unauthorized, dismissed/superseded, or
* the review list could not be read; 2026-09-27, #20153), nor
* an enqueue by an authorized account (2026-10-26). The
* SIZE leg, not the governed one; its remedies are an authorized
* approval and then the owning seat's landing, or a human merge.
* 9 REFUSED — the SIZE leg could not READ a queued pull request's size (the
* pull read failed, or the object carries no pair), or the merge
* group names no pull request to read it from. Split from 8 the
* way 4 is split from 3.
* 1 CANNOT RUN — unusable event payload, unsupported event, unreadable git.
* Still non-zero, still red: this file has no green that means
* "did not look".
*
* ⭐ TWO legs, ONE exit, and the precedence is pinned: every leg's block is
* always printed, and the code is the GOVERNED leg's when it refuses, else
* the SIZE leg's (`groupExitCode`). The governed refusal sits on top because
* its remedy is the stricter one; the size refusal's remedy (an authorized
* approval, or a human merge) is the same terminal as Tier H — a group that
* is both governed-unsatisfied and oversized prints both limbs and exits 3.
*
* ## What this file does NOT do
*
* It does not make itself a required context. Branch protection is the
* maintainer's, and the #6865 two-step exists so that flip is visible and
* deliberate: a `REQUIRED_CONTEXTS` row in `scripts/check-required-contexts.mjs`
* plus the entry in Settings → Rulesets, in one sitting. Adding the registry
* row alone would put the context in `direction A — registered here, NOT in the
* live required set`, which that gate reports as a problem. The context name to
* pin is `CHECK_CONTEXT_NAME` below, and the self-test asserts the workflow's
* `name:` literal still equals it, so the pin cannot be taken against a name
* that has since drifted.
*/
import { execFileSync } from 'node:child_process';
import { appendFileSync, readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
GENERATED_SURFACE_EXCEPTIONS,
GOVERNED_REPOS,
GOVERNED_SURFACES,
GOVERNED_TIER_H,
GOVERNED_TIER_S,
HUMAN_MERGE_LINE_THRESHOLD,
SELF_REPO_ID,
applyGeneratedExceptions,
assertGovernedRepo,
generatedExceptionFor,
governedPathsIn,
governedSurfacesFor,
governedTierFor,
groupHitsByException,
landsByHumanMerge,
pullNumberFromSubject,
pullSizeFrom,
recomputeProvenanceFor,
renderLiftApprovals,
repoIdForSlug,
testVerdict,
} from './check-governed-merges.mjs';
import { isEntrypoint } from '../invoked-as.mjs';
// ── The self-test's own battery roster and floor (#13489) ──────────────────
//
// `failures.length === 0` used to be this self-test's ONLY success condition, so
// "every case held" and "the cases never ran" printed the same line. Closed the
// way PR #13487 validated on check-doc-authoring: what is pinned is the
// registered NAMES, not a number. Every section opens with `battery('<name>')`,
// every assertion is attributed to the battery most recently opened, and the
// floor requires the OPENED set to equal the DECLARED set with each battery at
// or above its own count.
//
// ⛔ A pinned TOTAL is not the repair: a battery dropping from 9 cases to 3
// keeps a total "right" the moment a sibling grows.
//
// The counts are a FLOOR, not an equality — adding cases is ordinary work and
// must not red. A battery BELOW its floor means cases stopped running; the
// remedy is to find what stopped registering.
const SELF_TEST_BATTERIES = Object.freeze({
'the register is READ, never restated (#9840)': 6,
'the exit contract as a table': 4,
'the merge-queue head ref': 6,
'event payloads, including the malformed ones': 5,
'the approval predicate': 3,
'⭐ The fail-open direction a naive `.some(r => r.state === \'APPROVED\')`': 5,
'the 2026-09-04 unpinned predicate (the queue leg\'s)': 12,
'decomposition, and the multi-PR group trap': 13,
'the verdict table, both events': 10,
'the pull_request leg is an EARLY WARNING and never reddens': 6,
'the replay fixtures: the three incidents this guard descends from': 11,
'⭐ the ordering guarantee, measured with a spy that THROWS': 7,
'the words a reader acts on (requirement (e))': 26,
'⭐ #14063 END TO END: what the dependency install actually buys': 9,
'the PR-head reader: throws, and the caller no longer refuses on it': 3,
'the WIRING pin: the workflow still spells this context name': 8,
'⭐ #14063: the environment the exemption needs, pinned to the YAML': 7,
'⭐ #15406: a CLEAR reached through a lift is not a clear that saw nothing': 10,
'⭐ #18020 → #19133 Tier S: a review of record, not an approval': 43,
'⭐ #18701: the record lives on the PR or its card, and BOTH are read': 14,
'⛔ #19036: the SIZE line at the queue — imported, per queued PR, fail-closed': 54,
'⭐ #19344: the remedy names a path the ruleset actually offers': 5,
'⛔ the queued pull-back: the remedy names no dequeue act a seat has': 4,
'⭐ the 2026-09-20 ruling: a certified PURE REGENERATION carries the record to the queued head': 13,
'the per-row repository scope (ruling B2, 2026-10-13)': 14,
'⭐ B′ with C: the record stands at the tier its FACE maps to, read off the committed paths': 8,
'the CODEOWNERS mirror: every Tier H register row routes to every GOVERNED_APPROVERS account, nothing else is routed, and the file says so': 12,
'⭐ the 2026-10-26 ENQUEUE leg: an authorized enqueuer is the human review': 28,
'⭐ the cheap early-warning leg: commits and trees, toolchain on demand': 20,
});
// DELETING an entry silences that battery's floor exactly as effectively as
// zeroing it, so the roster's own size is pinned too. Lowered 24 → 23 when the
// contract-review carrier battery left with the label it read (ruling record
// 5770886272 on #19061, letter B): the ordinary direction, one battery, one row.
// Raised 23 → 24 with the queued pull-back battery: one battery, one row.
// Raised 25 → 26 with the B′-with-C face battery (ruling record 6159870311): one battery, one row.
// Raised 26 → 27 with the CODEOWNERS mirror battery: one battery, one row.
// Raised 27 → 28 with the ENQUEUE leg battery (maintainer ruling 2026-10-26): one battery, one row.
// Raised 28 → 29 with the cheap early-warning leg battery: one battery, one row.
const SELF_TEST_BATTERY_FLOOR = 29;
// The key an assertion is filed under when no battery is open. It is not a
// declared battery, so it reds by the same set difference rather than silently
// inflating whichever battery happened to run last.
const UNATTRIBUTED_BATTERY = '(no battery open)';
const scriptDir = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(scriptDir, '..', '..');
/** The exit contract, named so the header's table is machine-checkable. */
export const EXIT_CLEAR = 0;
export const EXIT_CANNOT_RUN = 1;
export const EXIT_REFUSED_UNAPPROVED = 3;
export const EXIT_REFUSED_UNREADABLE = 4;
export const EXIT_REFUSED_UNATTRIBUTED = 5;
/**
* The SIZE leg's two refusals (#19036, the 2026-09-18 ruling). The same split,
* for the same reason: "this pull request is over the line" and "we could not
* read its size" are different facts, and the second one DECIDES here — unlike
* the PR head, whose read failing is a note — so it refuses on a code of its
* own. ⛔ Neither may ever be folded into the other, nor into 3/4.
*/
export const EXIT_REFUSED_OVERSIZED = 8;
export const EXIT_REFUSED_SIZE_UNREADABLE = 9;
/**
* The check-run name branch protection would pin, and the wiring it belongs
* to. Declared HERE rather than only in the YAML so the self-test can assert
* the workflow still spells it — the #6865 defect is a job rename detaching a
* required context silently, and a name that lives in exactly one place is a
* name nothing can pin.
*/
export const CHECK_CONTEXT_NAME = 'Governed Surface Queue Guard';
export const CHECK_WORKFLOW = 'governed-surface-guard.yml';
export const CHECK_JOB_ID = 'governed-surface-guard';
/** The events this guard understands, and what each one means to it. */
export const EVENT_MERGE_GROUP = 'merge_group';
export const EVENT_PULL_REQUEST = 'pull_request';
/**
* The ONLY accounts whose APPROVED review satisfies the `merge_group` leg
* (2026-08-27, verbatim: 「os-zhuang hotlong 批准算数」). ⭐ Single source, the
* `CONTRACT_REVIEW_TIER` pattern: protocol text references this constant and
* never copies the names; changing the set is a one-line maintainer decision
* here, nowhere else. The self-test pins the membership to the ruling, and the
* refusal/cleared renderings derive their named accounts from this array.
*/
export const GOVERNED_APPROVERS = Object.freeze(['os-zhuang', 'hotlong']);
// ── the CODEOWNERS mirror — the platform half of "both approvers are asked" ─
/**
* `.github/CODEOWNERS` is the platform's own review router: GitHub requests a
* code owner's review when a pull is opened READY or marked ready for review.
* It is a static file — it can import neither `GOVERNED_SURFACES` nor
* `GOVERNED_APPROVERS` — so the two stay in step the only way a static file
* can: this predicate reads it and the self-test reds when it drifts. ⛔ It is
* a pin inside this existing self-test, not a gate, a check-run or a patrol
* row: the fleet's own request on the draft open is the relay's
* governed-review follow-up (`fleet-write/ops.mjs`), and the gap both close is
* what the H43 patrol row keeps reading.
*
* `codeownersRows` parses the file's effective lines — a `#` comment to end of
* line stripped, blank lines dropped — into `{ pattern, owners, line }`.
* `codeownersPatternFor` spells the one CODEOWNERS pattern a register row maps
* to: its prefix or exact path, root-anchored. Both pure.
*/
export function codeownersRows(text) {
const rows = [];
String(text ?? '')
.split('\n')
.forEach((raw, i) => {
const line = raw.replace(/#.*$/, '').trim();
if (line === '') return;
const [pattern, ...owners] = line.split(/\s+/);
rows.push({ pattern, owners, line: i + 1 });
});
return rows;
}
export function codeownersPatternFor(surface) {
return `/${surface.prefix ?? surface.exact}`;
}
/**
* The verdict: `{ ok, problems, tierHPatterns }`. `ok` holds only when
* - every Tier H row of the register that governs `repo` has a CODEOWNERS
* line at exactly its pattern, naming exactly `@` + every account in
* `approvers` (order-free; nobody else, nobody fewer);
* - every other line — the enforcement chain's rows — names exactly that
* same owner set, so an enforcer cannot be routed to a subset;
* - no line routes a Tier S row's pattern: Tier S lands on a seat's review of
* record, and a code-owner request there would summon the maintainer for a
* landing that is not his;
* - the file's prose names `GOVERNED_APPROVERS`, so a reader finds the
* constant the owner list mirrors.
* Every problem is a sentence naming the row or line; the list is whole, never
* the first hit. Pure.
*/
export function codeownersMirrorVerdict({ text, approvers = GOVERNED_APPROVERS, repo = SELF_REPO_ID, register = GOVERNED_SURFACES } = {}) {
const rows = codeownersRows(text);
const wanted = [...approvers].map((a) => `@${a}`.toLowerCase()).sort();
const sameOwners = (owners) => JSON.stringify([...owners].map((o) => o.toLowerCase()).sort()) === JSON.stringify(wanted);
const problems = [];
// The rows that govern THIS repository, read from the register (ruling B2: the question has a repository in it).
// `register` is the register's own seam (`governedSurfacesFor`): the self-test hands in rows not on it yet.
const governing = governedSurfacesFor(repo, register);
const tierH = governing.filter((s) => s.tier === GOVERNED_TIER_H);
const tierHPatterns = tierH.map(codeownersPatternFor);
for (const surface of tierH) {
const pattern = codeownersPatternFor(surface);
const row = rows.find((r) => r.pattern === pattern);
if (!row) {
problems.push(`Tier H row \`${surface.id}\` (${surface.glob}) has no CODEOWNERS line at \`${pattern}\` — a pull touching it summons nobody when opened ready`);
continue;
}
if (!sameOwners(row.owners)) problems.push(`CODEOWNERS line ${row.line} \`${pattern}\` names ${row.owners.join(' ') || 'nobody'}, not every GOVERNED_APPROVERS account (${wanted.join(' ')}) — a Tier H pull then waits on an approver who is never asked`);
}
for (const row of rows) {
if (tierHPatterns.includes(row.pattern)) continue;
const tierS = governing.find((s) => s.tier === GOVERNED_TIER_S && codeownersPatternFor(s) === row.pattern);
if (tierS) problems.push(`CODEOWNERS line ${row.line} routes \`${row.pattern}\`, a Tier S row (\`${tierS.id}\`) that lands on a seat's review of record — a code-owner request there asks the maintainer for a landing that is not his`);
else if (!sameOwners(row.owners)) problems.push(`CODEOWNERS line ${row.line} \`${row.pattern}\` (an enforcement-chain row) names ${row.owners.join(' ') || 'nobody'}, not every GOVERNED_APPROVERS account (${wanted.join(' ')})`);
}
if (!/GOVERNED_APPROVERS/.test(String(text ?? ''))) problems.push('the file never names `GOVERNED_APPROVERS` — its header must say which constant the owner list mirrors');
return { ok: problems.length === 0, problems, tierHPatterns, rows };
}
// ── the landing TIER: Tier S lands on a review of record, Tier H on an approval ─
/**
* The two landing tiers, READ from the register (#19133, ruled 2026-09-18
* 「同意改规则。」 on the skills seat's proposal; the amendment moved
* `.claude/settings.json` and `.claude/hooks/**` over too: 「我觉得这些我也没
* 必要确认」). Every `GOVERNED_SURFACES` row carries `tier`, and
* `governedTierFor` — imported from the register's own file at module scope,
* like every other predicate this guard reads — derives a pull request's tier
* from the rows its GOVERNED paths hit. ⛔ Nothing here spells a prefix, a glob
* or a row: the #18020 references tier was a prefix constant declared here
* (`REFERENCES_TIER_PREFIX`, the fact layer alone); it is gone, and a seat
* reading the register gets the same answer to "what lands this on a record"
* as this guard does. The register's `.claude/**` row still AUDITS every path
* under it exactly as before — the tier is a LANDING rule inside the row, never
* a membership one, which is why ⛔ nothing here touches `GOVERNED_SURFACES`.
*
* `H` (人合) is the DEFAULT in every ambiguous case, because the two are not
* symmetric: reading a Tier H path as S lands a maintainer-owned file on a
* seat's own review, while reading a Tier S path as H costs one authorized
* approval — the maintainer is asked to look at a pull request they need not
* have, and the claiming seat lands it from there. An empty list answers H for
* the same reason (the register's `landingTierOf` does; see its docblock).
*
* ⭐ ALL, not ANY, and not a proportion: 「混合 diff 一条命中即整 PR 分叉」 is the
* regime's own rule one level up, and this is the same rule one level down. One
* Tier H path in the diff and the whole pull request is Tier H. The paths
* handed to `governedTierFor` are the GOVERNED paths of one entry —
* `decomposeGovernedWork` has already dropped everything the register does not
* match, so an ordinary source file riding along cannot demote it.
*/
export const TIER_H = GOVERNED_TIER_H;
export const TIER_S = GOVERNED_TIER_S;
/**
* The Tier S surfaces in the register's own glob spelling — for the WORDS a
* verdict prints, never for a second match (the match is `governedTierFor`).
*/
export function tierSGlobs() {
return GOVERNED_SURFACES.filter((s) => s.tier === GOVERNED_TIER_S).map((s) => s.glob).join(', ');
}
/**
* WHERE a review of record may live, in the words a refusal prints — a MIRROR
* of `REVIEW_OF_RECORD_LOCATION` in `record-recognisers.mjs`, which is the
* one place the set itself is declared (#18701).
*
* ⚠️ THIS IS A MIRROR, NOT THE SOURCE, and the reason is a MODULE-EVAL CYCLE.
* Importing `record-recognisers.mjs` — or `check-half-states.mjs`, which
* it imports — from here at MODULE SCOPE deadlocks both modules: that file's
* H43 resolves its governed register at module scope with a top-level
* `await loadGovernedRegister()`, which awaits `import('./check-governed-queue-guard.mjs')`
* — this file — for `GOVERNED_APPROVERS`. Adding the reverse edge deadlocks
* BOTH modules; measured on 2026-09-10, node exits 13 with "Detected unsettled
* top-level await" and `check-half-states.mjs` stops loading standalone as well.
* Re-measured on 2026-09-13 through `check-clause2-carriers.mjs`, and on
* 2026-09-23 through `record-recognisers.mjs`, which took its recognisers over —
* both import that file, and the INDIRECT edge deadlocks identically, exit 13.
* The references tier reaches the recognisers with a LAZY import taken after
* this module has finished evaluating — legal only because this file's own
* dispatch carries no top-level `await`, which `loadRecordRecognisers` states
* as a rule and the battery pins. That door is open to a FUNCTION BODY and shut
* to a module-scope binding, and `renderGuardVerdict` is pure and synchronous,
* so no lazy import can supply the words there. The READING half takes no mirror —
* `runGuard` fetches one thread per entry in the loaded `threads` list, so the
* set this file ACTS on is never a copy. Only the WORDS are copied, and the
* battery pins them to the constant loaded through the real lazy import, so
* drift in either direction reddens.
*/
export const REVIEW_OF_RECORD_LOCATION = 'the PR or its card';
/**
* `governedTierFor` — the register's own function, re-exported so this file's
* readers (`record-recognisers.mjs`'s cross-tool pin) and its battery keep
* one name. ⛔ Not a wrapper and not a copy: the register answers, this file
* relays. The tier docblock above carries the ALL-not-ANY rule and the H default.
*/
export { governedTierFor };
/** Where each imported recogniser lives. Named, so a failure can say which file. */
export const RECOGNISER_SOURCES = Object.freeze({
tier: './record-recognisers.mjs',
});
/**
* The recognisers the references tier reads a record with — IMPORTED, and
* imported LAZILY.
*
* ⭐ THE RULE THAT KEEPS THE LAZINESS LEGAL, and it is the one thing to read
* before touching this function: `check-half-states.mjs` resolves its governed
* register at MODULE SCOPE with a top-level await that imports THIS file. A
* module-scope import from here — direct, or indirect through
* `record-recognisers.mjs`, which imports that file — deadlocks both
* modules (node exits 13, "Detected unsettled top-level await"; measured both
* ways, see `REVIEW_OF_RECORD_LOCATION`). The cycle closes only while THIS module
* is still evaluating, so the import is taken from a function body, after
* evaluation has finished — which is true only because this file's dispatch
* carries NO top-level `await`. ⛔ Restore one and this leg deadlocks the merge
* queue build; the battery reads this file's own source to keep that honest.
*
* ⛔ Fail-CLOSED, like every other reading in this file: an absent or renamed
* export is `available: false` with a reason, and the caller turns that into a
* REFUSAL. A recogniser set that quietly half-loaded would decide a governance
* question with a parser nobody checked.
*
* Injectable for the same reason H43's own loader is: the battery drives every
* failure branch without touching the filesystem.
*/
export async function loadRecordRecognisers(load = (specifier) => import(specifier)) {
try {
const tier = await load(RECOGNISER_SOURCES.tier);
const found = {
locate: tier?.locateReviewOfRecord,
deliveredCard: tier?.deliveredCardNumber,
servedTierStands: tier?.servedTierStands,
isModelIdentifierToken: tier?.isModelIdentifierToken,
reviewFace: tier?.reviewFace,
threads: tier?.REVIEW_OF_RECORD_THREADS,
location: tier?.REVIEW_OF_RECORD_LOCATION,
};
const missing = [
...['locate', 'deliveredCard', 'servedTierStands', 'isModelIdentifierToken', 'reviewFace'].filter((key) => typeof found[key] !== 'function'),
...(Array.isArray(found.threads) && found.threads.length > 0 ? [] : ['threads']),
...(typeof found.location === 'string' && found.location.length > 0 ? [] : ['location']),
];
if (missing.length > 0) {
return {
available: false,
reason:
`the contract-review recognisers loaded but did not export what this leg reads (${missing.join(', ')}) — ` +
`they live in ${RECOGNISER_SOURCES.tier}, and a rename is the likely cause. ⛔ The repair is to follow ` +
'the rename, never to write a second parser here',
};
}
return { available: true, ...found };
} catch (error) {
return {
available: false,
reason: `the contract-review recognisers would not load: ${String(error?.message ?? error).split('\n')[0]}`,
};
}
}
/**
* What the pair's THREADS say about the review of record on this head.
*
* Pure — the rows and the head arrive as data, so every branch is offline-
* testable and the battery drives all five.
*
* @returns {{ state: 'unreadable', reason: string, cardNote: string|null }
* | { state: 'absent', read: object, cardNote: string|null }
* | { state: 'unsigned'|'below-tier'|'stands', where: string, id: number|null, at: string|null, sha: string, served: object, cardNote: string|null }}
*
* Five-valued, and the split is the file's usual one: `unreadable` is "we could
* not find out" (exit 4's fact), the other refusals are "it is not there or does
* not stand" (exit 3's). ⛔ Never fold them: a thread nobody could read and a
* thread with no record in it earn different remedies.
*
* ⭐ THE FILTER IS NOT SPELLED HERE ANY MORE, and that is the whole of #18701.
* It used to be — two lines, for `latestContractReviewOnHead`'s own documented
* reason (that finder returns an id and not the ROW, and the row is what the
* tier line is read from) — and the copy was correct about every fact it read.
* What it could not copy was the SET OF THREADS to read them over: the rule puts
* the record 「一条评论落 PR 或卡」 and this leg searched the pull request's
* thread alone, so a record posted where the governed text, this file's sibling
* and its own `--template` all say it may live was read as no record at all.
* Measured: PR #18689, dequeued `CI_FAILURE` with 「0 comment(s) read on the PR
* thread」 against a record sitting on card #18426, cured only by a second copy.
*
* So the whole reading is now `locateReviewOfRecord`, imported from the file
* that composes it. Two tools, one derivation of "the record on
* this head", and the thread set travels inside it rather than beside it. What
* is left here is the TIER gate on top of it, which is this leg's own fact:
* whether the record's `Served-tier:` stands, and whether its token is a model
* identifier that ⛔ must never be quoted back (#18060).
*
* ⭐ WHICH tier it must stand at is the FACE's (ruling record 6159870311 on
* #23352, letter B′ with C): `reviewFace`, imported with the rest, reads the
* pair's `paths` — the pull request's paths out of the merge group's committed
* trees, the list this leg already classified as governed — and the record
* stands only at the exact NAME that face maps to. On this leg every entry is
* governed, so the face is governed rules text and the name is
* `CONTRACT_REVIEW_TIER`; the mapping is read rather than assumed, so the leg
* and the rule cannot drift. ⛔ A pair that carries no path list cannot say
* which face it is on: UNREADABLE, never the cheaper tier.
*/
export function recordVerdict({ pair, recognisers, cardNote = null }) {
if (recognisers?.available !== true) {
return { state: 'unreadable', reason: recognisers?.reason ?? 'the contract-review recognisers were not loaded', cardNote };
}
if (!Array.isArray(pair?.paths) || pair.paths.length === 0) {
return {
state: 'unreadable',
cardNote,
reason:
`PR #${pair?.pr}'s file list was not handed to the record reading, so the face that made its review owed — ` +
'and with it the one tier the record must stand at — is unknown',
};
}
const face = recognisers.reviewFace(pair.paths, pair.repo);
const located = recognisers.locate(pair);
if (located.state === 'unreadable') {
return {
state: 'unreadable',
cardNote,
reason:
`${located.gaps.join(', ')} could not be read — a review of record NAMES a head and lives on one of ` +
`${recognisers.location}, so a head or a thread this guard could not read can find no record`,
};
}
if (located.state === 'absent') {
return {
state: 'absent',
read: located.read,
// Rendered HERE, where the thread set is in hand: the renderer is pure and
// synchronous and holds no recogniser, so a count it formatted itself
// would be a second place naming the threads.
readSummary: recognisers.threads.map((thread) => `${located.read[thread.number] ?? 0} on ${thread.words}`).join(' and '),
cardNote,
};
}