Repository navigation
Expand file tree
/
Copy pathlabel-write.mjs
More file actions
4535 lines (4281 loc) · 364 KB
/
Copy pathlabel-write.mjs
File metadata and controls
4535 lines (4281 loc) · 364 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.
/**
* label-write — the four-step label/assignee write, as ONE spelling (#18085).
*
* node scripts/pm/label-write.mjs --repo owner/name --issue N --add pm:dispatched --remove pm:queue
* node scripts/pm/label-write.mjs --issue N --assign os-project-manager
* node scripts/pm/label-write.mjs --issue N --add skip-changeset --dry-run
* node scripts/pm/label-write.mjs --issue N --release --recheck-comment ID --comment-file release.md --resume-from BRANCH@SHA
* node scripts/pm/label-write.mjs --issue N --add pm:dispatched --remove pm:queue --assign LOGIN --comment-file claim.md
* node scripts/pm/label-write.mjs --issue PR --comment-file verdict.md --land
* node scripts/pm/label-write.mjs --issue PR --comment-file request.md --handoff
* node scripts/pm/label-write.mjs --issue PR --handoff --dry-run # the per-round H43/H48 reading, zero writes
* node scripts/pm/label-write.mjs --self-test # offline, no network at all
*
* ## Why this file exists
*
* `.claude/skills/pm-dispatch/SKILL.md` requires every label write to be four
* steps — 取现集 → 只增删目标 → 写合并集 → 回读 diff 对 union(现集, 增删) — and
* `references/rest-channel.md` named the channels. Its fallback for a seat whose
* REST channel is shut named exactly one tool: MCP `issue_write`. Lock 1 added
* that tool to `permissions.deny` in `.claude/settings.json`, so the documented
* recovery path terminated in a denial and the four steps had no single spelling
* at all — every seat retyped them, and the retyping is where a step gets
* dropped.
*
* So the steps are a program, not a paragraph. Every invocation performs all
* four and prints each with the UTC stamp the step was taken at.
*
* ## The channel order, and why the fallback is LAST
*
* Three verbs touch a label set and only one is destructive:
*
* POST /issues/{n}/labels adds the named labels, touches nothing else
* DELETE /issues/{n}/labels/{name} removes ONE label, BY NAME
* PATCH /issues/{n} {labels:[…]} replaces the whole set — DESTRUCTIVE
*
* The first two are what this tool spends by default: neither can strip a label
* a concurrent seat wrote between step ① and step ③, because neither names a
* label it was not asked to touch. The third is a read-modify-write across a
* network round trip and destroys anything that lands inside it — the measured
* loss on PR #10698 is one second wide, and `scripts/check-whole-set-label-write.mjs`
* bans its `PUT` sibling outright over this whole subtree.
*
* ⛔ This file therefore never issues `PUT /issues/{n}/labels`, in any spelling.
* The `PATCH /issues/{n}` fallback is a DIFFERENT endpoint carrying the SAME
* hazard, and it is reached only when the platform has refused the additive
* verbs outright — a seat with no additive channel and a stale label is worse
* off than one that spent a narrow race. Three things make it survivable, and
* all three are the reason it is allowed at all:
*
* 1. it is tried ONCE, only after a refusal, never as a first choice;
* 2. it echoes the CURRENT assignees back into the body. `issue_write`'s
* measured hazards (`references/readings-issue-fields.md`) are whole-set
* replacement AND the clearing of every field the write did not pass, so
* a body carrying `labels` alone silently un-assigns the card. The echo is
* what makes a label write a label write;
* 3. step ④ reads the card back and diffs it against the target, which is the
* only detection a whole-set write has. A label in the target the read-back
* lacks was stripped underneath: it is re-added ONCE and REPORTED.
*
* ## ⚠️ What this tool CANNOT measure, and therefore does not claim
*
* The refusal that motivated this card was not GitHub's and not the egress
* proxy's: a seat's own harness permission classifier refused a `curl -X DELETE`
* command before any request was made. That classifier judges the COMMAND a
* session is about to run. Whether it refuses `node scripts/pm/label-write.mjs`
* the way it refused a raw `curl` is a property of the calling session, is not
* observable from inside this process, and is ⛔ NOT asserted anywhere in this
* file or its output. A seat that is refused at that layer never reaches step ①,
* gets no exit code from here at all, and is in the exit-5 position by another
* route: it hands the write to a seat that has a channel.
*
* ## The transport — `OS_FLEET_TRANSPORT` direct | dispatch | auto
*
* A cloud seat container cannot write as the fleet directly (its proxy
* replaces the Authorization header), so step ③ has two transports and ONE
* shape: `direct` issues the additive verbs above with the token this process
* holds; `dispatch` packs the SAME verbs — the adds, the directed removes and
* the assignee change of this one write — into ONE `repository_dispatch` and
* `scripts/pm/fleet-write/dispatch.mjs` waits for the relay run that executes
* them as `objectstack-fleet[bot]`. Steps ①, ② and ④ are the same on both:
* reads are unaffected, and the read-back is what closes the write either
* way. `auto` (the default) picks `dispatch` in a cloud seat container and
* `direct` elsewhere, and prints which. The whole-set `PATCH` fallback below
* belongs to `direct` alone: the relay only has additive verbs. ⛔ Once a
* dispatch is ACCEPTED, its run is the only answer: no run in the start
* window, or none completed, is exit 6 under `auto` exactly as under
* `dispatch` — never a direct write after it. The relay may merely be queued,
* and the direct write would book the stroke against the seat's personal
* account instead of the fleet's and may land it twice
* (`fleet-write/dispatch.mjs`'s no-run conformance pins every sender to this).
*
* ## `--release` — reclaiming a SILENT claim, in ONE relay stroke, RELAY-ONLY
*
* A claim with no PR, no commit and no word on the card used to sit for days,
* because the lifecycle text said a silent seat "may be" recycled and named no
* actor, no clock and no write. The protocol now has both halves, and this is
* the write half (the text half is `RECLAIM_TEXT_PATH`, whose constant this
* file's self-test pins equal to `RECLAIM_AFTER_HOURS`):
*
* knock triage posts the owned-24h re-check on the card — a comment whose
* first line, after any markdown heading marks, is
* `RECHECK_COMMENT_KEY`. ⛔ This tool never writes the knock and
* never releases without one: `--recheck-comment ID` names it.
* clock the knock's `created_at` against the SERVER's clock — the `Date`
* header of the very response that returned the knock. ⛔ Never
* `Date.now()`: a container's clock is nobody's reading. Younger
* than `RECLAIM_AFTER_HOURS` ⇒ REFUSED, saying how long remains.
* silence the knock must still be the newest comment on the card. Anything
* said after it — by the holder or anyone — is read by a seat, not
* by this tool: it refuses, and triage re-knocks if that was no
* answer. A pushed branch with an OPEN pull request is produce too,
* so `--resume-from BRANCH@SHA` is checked against the branch's tip
* AND against the open pulls on that head before anything is sent.
* stroke ONE `repository_dispatch`, in this order: the `Release:` comment
* (the operator's provenance prose, with `Resume-from: BRANCH@SHA`
* and the clock reading appended by this tool), `pm:queue` on,
* `pm:dispatched` off, every assignee off. The holder's seat post
* is not an action here and cannot become one — every action
* names the card.
* judged the composed comment — the operator's text, the resume line and
* the clock reading — by post-stamped's `judgeBody` in comment mode,
* the ONE path `--comment-file` and post-stamped's own `--comment`
* take (`composeReleaseBody`): the stamp contract, the signature
* first line, the comment-mode keyed-line readers. An unsigned text
* is exit 2 with zero writes, before the stroke, its refusal
* post-stamped's own text naming this tool.
* read-back the card's labels and assignees against the ② target, and the
* release comment located on the board by its stored bytes
* (post-stamped's `pickRelayComment`). A board that disagrees is
* exit 4 and is NOT repaired: a re-add under the relay is a second
* write.
*
* ⛔ RELAY-ONLY. A release lands as `objectstack-fleet[bot]` through the relay
* or it does not land: a route that resolves to `direct` — a developer's
* machine, `OS_FLEET_TRANSPORT=direct`, a relay the board has switched off —
* is a PREREQUISITE refusal (exit 3) with zero writes, and an accepted
* dispatch with no run is UNCONFIRMED (exit 6) exactly as above, never a
* direct write after it. The seat whose silence is being reclaimed may be the
* fleet's own account; a release booked under a personal login is the
* half-state this mode exists to end, not a fallback.
*
* Why this file and not `close-cards.mjs`: a release IS a label/assignee
* transition — `pm:dispatched` → `pm:queue`, assignee cleared — with a
* provenance comment in front of it, so its arithmetic (`computeLabelTarget`,
* `computeAssigneeTarget`, `relayActions`, `readBackVerdict`) is already this
* file's, and the comment half is borrowed from post-stamped exactly the way
* close-cards borrows it. close-cards' plan file, skip matrix and resume are
* built to act on UNOWNED `pm:queue` cards and to CLOSE them; a release acts
* on an OWNED `pm:dispatched` card and leaves it open — the inverse of every
* skip row there. `--release` therefore owns its own plan: `--add`,
* `--remove`, `--assign`, `--unassign`, `--clear-assignees` and
* `--allow-two-states` are refused beside it.
*
* ## `--comment-file` — a claim, a release or a verdict as ONE relay stroke, RELAY-ONLY
*
* A seat's paired writes went out as two relay strokes because each tool sent its own: the `Claim:` or
* `Release:` comment through post-stamped, the labels and assignee through here; a verdict comment, then
* `pr_ready` + `automerge_enable` from a hand-written actions file. Each pair cost a second run and a second
* round trip the seat waited out. `--comment-file PATH` beside an ordinary plan folds the comment into the
* stroke this file already sends, in `--release`'s shape (`releaseActions`): the comment first, then the
* additive verbs. `--land` appends `pr_ready`, then `automerge_enable` (`rest-channel.md`'s order), to a
* stroke on a pull request; a stroke with `--land` may carry no label or assignee change at all.
*
* judged by post-stamped's `judgeBody`, the ONE path its own `--comment` takes: the stamp contract with
* `{{NOW}}` read by this act, the signature first line, a claim's keyed lines, a record's line,
* a record's tier (a record naming `CONTRACT_REVIEW_TIER` folds only with `--tier-evidence PATH`,
* the reviewing run's transcript `verify-review-tier.mjs` passes), the decision facets. A refusal
* is exit 2 with zero writes, its text post-stamped's own, naming this tool.
* paced as every stroke: the dispatch POST behind `write-pace`, every write in it spaced by the executor.
* read back after a success run, each part on its own line: `④ labels` and `④ assignees` against the ②
* target; `④ comment` located on the board by its stored bytes (`pickRelayComment`) and judged by
* post-stamped's `readBackVerdict` (stamp drift, byte class); under `--land`, `④ pull` — `draft`
* false on the REST read, and the arming the executor's landed check on `automerge_enable`'s own
* answer (an `autoMergeRequest`, or `isInMergeQueue`): REST `auto_merge` is unstable and ⛔ never
* a reason to re-arm (`readings-queue.md`), so it is printed and not judged. A part that
* disagrees is exit 4 and is NOT repaired — under the relay a re-send is a second write.
*
* ⛔ RELAY-ONLY, as `--release`: a fold exists only where a stroke does, so a route that resolves to `direct`
* is exit 3 with zero writes — send the comment through post-stamped and the labels here, as before. A comment
* with nothing to fold beside it is refused (exit 2): that write is post-stamped's.
*
* ## `--land` on a breaking or narrowing pull — the dogfood battery gate
*
* Pull-request CI skips the dogfood shards by design (two speeds); `.claude/agents/os-dev.md` makes up for it by
* having the dev run the full battery once on the final head of a pull whose title carries `!` before its colon or
* whose `Clause-②:` line carries a `(narrowing)` arm, and record it under the report's `dogfood_battery`. A pull that
* lands without that run is ejected by the queue's dogfood shards and takes its batch with it. So `--land` judges it
* BEFORE anything else in the fold (`landDogfoodGate`), on step ①'s own read of the pull's title and body:
*
* repo only a pull in a repository that CARRIES the battery is judged: `LAND_DOGFOOD_BATTERY_REPOS`, today
* objectstack-ai/objectstack alone — the one repository with the `@objectstack/dogfood` battery and the
* queue's dogfood shards. Anywhere else (cloud, hotcrm, …) the os-dev report can only say `n/a` and no
* queue shard can eject the pull, so judging it would refuse every marked pull for good: it is NOT
* judged, zero reads, and the fold prints a ✓ line naming the repository. A `--repo` that does not read
* as `owner/name` is judged as before — the battery repository stays fail-closed. A repository that
* gains a battery joins the list in the same pull that adds it.
*
* marker the title's `!` (`titleBreakingMarker`): everything before the title's FIRST colon, ending in `!`
* (`fix(pm)!: …`, `feat!: …`) — on main's bang subjects it agrees with the changeset-side reader
* (`check-adr-0087-registration.mjs`'s type, optional scope, `!:`) — measured equal on all 1331 bang subjects
* among the 8521 commit subjects of objectstack-ai/objectstack `origin/main` at `22438726f`, 0 disagreeing;
* or a `(narrowing)` arm read by `clause2-line.mjs`'s ONE reader — a `malformed` or a `near-miss` line is
* unreadable and refuses, never an absent arm; a body with no `Clause-②:` line at all declares no arm and
* is not judged, as Check Changeset reads it. No marker ⇒ not judged, zero extra reads.
* report the NEWEST `os-dev-report` on the card the pull delivers (`deliveredCardNumber`) among comments by the
* relay's identity or a governed approver (`recordAuthorTrusted`) — newest-of, marker and payload
* candidates are the patrol's readers, called, ⛔ never a second parser. When that report's `pr` names
* ANOTHER pull (siblings on one card), the newest trusted report whose `pr` names THIS pull, or none — a
* null or URL-less `pr` names no pull, so in that fallback it is not this pull's and is passed over too.
* A FOLD — one closing keyword per card, at equal strength — delivers no single card, and
* `deliveredCardNumber` reports that tie rather than break it (the queue guard's record pairing stays
* refusing on it). The gate then reads EVERY tied card (`deliveredCardsAtStrongest`, the same
* enumeration), each thread whole, under the same author filter and sibling rule, and lands when SOME
* tied card's report carries a battery the head reaches; the verdict never depends on which card is read
* first, and a refusal names every tied card and why each failed. A body naming no card still refuses.
* sha its `dogfood_battery` must open with a sha that is the pull's head, or that a first-parent walk from the
* head reaches over merges of the base alone: each step's commit has exactly two parents, the second one
* on the base branch (`GET /compare/{parent2}...{base}` answers `ahead` or `identical`).
*
* FAIL CLOSED: an unreadable marker, no card, no report, an unparsable one, an `n/a` battery, one naming no sha, a
* truncated thread (`LAND_COMMENT_PAGE_CAP`), an unreadable commit or compare, or a walk past `LAND_MERGE_HOP_CAP` is a
* refusal — ⛔ zero writes, the line quoting the title and naming the marker, the report comment and its
* `dogfood_battery` text, and what clears it (`landDogfoodRefusal`). NOT MEASURED is never a pass here. A read the
* platform did not answer (`doCall`'s verdict other than `ok`: refused, failed, rate-limited) is exit 3, PREREQUISITE,
* like every other unread in this file; a judged refusal is exit 2. The ✓ line says the sha alone was judged: whether
* the battery was full and its reds fixed or reported stays the L1 checklist's.
*
* ## `--handoff` — the seat's Tier H hand-off as ONE relay stroke, RELAY-ONLY
*
* pm-dispatch SKILL.md 〈路径分叉〉 ② and ③ make the hand-off three writes: the approval-request comment,
* `pm:awaiting-merge` on the pull, and a review request to every `GOVERNED_APPROVERS` account. Made by hand from a
* template that carried only the first, the other two were dropped and the pulls sat outside the maintainer's
* inbox and review queue. `--issue PR --comment-file request.md --handoff` makes all three in one stroke, in this
* order: the comment, `labels_add`, `assign` (the author), `pr_request_reviewers` (the rest).
*
* tier `check-governed-merges.mjs --pr OWNER/NAME#N --json`, spawned: the one reading that chains every
* split (workflows, the low-risk arm, `Rule-change:`) and the size limb. Three populations land by the
* maintainer and proceed: Tier H; the size limb firing (it lands the way Tier H does); and a declared
* narrowing — the queue guard's narrowed leg, which the tier tool has no limb for, read with that leg's
* own `narrowedReading` over the body and the committed changesets at the head (`readChangesetTexts`'
* rule: a changeset the head does not hold, deleted or renamed away, answers 404 and declares nothing),
* Tier S included. On Tier H the paths decide and ⛔ no changeset is read. Tier S (「Tier S 不交人」)
* and an ungoverned pull that declare no narrowing, and a fork (a proposal, adopted by the owning
* seat), are refused. A reading that did not answer is exit 3.
* records the ACCEPT on the pull's own thread, by check-half-states' H43 hand-off reading
* (`h43HandoffReading`): the NEWEST `## 席位核对` must read ACCEPT and be newer than the head's committer
* date (H69's comparison). The PASS the queue guard's way, with its own readers, ⛔ never re-spelled:
* `loadRecordRecognisers`, `readRecordThreads` over the pull AND the card it delivers
* (`REVIEW_OF_RECORD_LOCATION`), each cut to trusted authors, then `recordVerdict` and
* `recordPassVerdict` — the newest same-head record, signed, at the tier its FACE owes (`reviewFace`
* over every path the tier tool read, pre-lift — a path lifted as a pure regeneration included; off the
* tier route the narrowed leg's pair: the body and each changeset text, `narrowingDeclared` when a
* narrowing is declared on either line — so a code-only size-limb pull is on the declaration face at
* `TIER_DEFAULT` and a narrowing one on the narrowing face), one PASS line, no open grade. A PASS on an
* older head carried by a `Regen-provenance:` line is the guard's `regenCarry` to judge: the pair hands
* it this checkout's git (`handoffGitReader`, none for another repository) and the pull's `base.sha`.
* A `## 维护者速读` comment must be on the thread or be the request itself — H48's brief half.
* plan the approvers not requested, assigned or holding a submitted review (H43's union); the author among
* them is ASSIGNED, never requested (a request naming the author is a 422). A covered approver and a
* label already on cost no action. ⛔ `fleet-write/execute.mjs`'s `governedReviewPlan` is not called:
* its tier half reads the `.claude/**` row path-only, so it would request nobody on the very pulls
* `Rule-change:` makes Tier H.
* read-back besides the fold's labels, assignees and comment lines: `④ reviewers` against the pull's pending
* requests, then `④ H43` and `④ H48` — the patrol rows THEMSELVES (`h43GovernedReviewRequestGap`,
* `h48GovernedVerdictWithoutBrief`), asked of the pull as read back, on the tier reading's matched
* slice — plus one Tier H entry for the size limb or the declared narrowing when that is what admitted
* the pull (`handoffSlice`: otherwise both rows stand down and read ✓ with nobody asked) — and told the hand-off
* is DUE on the gate's own PASS. Any ✗ is exit 4, never repaired.
* once a pull already whole — the label on, every approver covered, a `## 维护者速读` brief on the thread —
* sends nothing and exits 0: ⛔ no second request comment. Short of the brief, the request is owed. A request whose signature names an uncovered approver is refused: a seat never
* requests its own account (「⛔ 永不请席位自身账号」).
*
* Every refusal is exit 2 with ZERO writes. `--dry-run` reads all of it, prints `now H43` / `now H48` for the
* pull as it stands and the stroke it would send, and sends nothing — it may omit `--comment-file`, so it is the
* per-round reading of a seat's own governed pulls (execution-duties' 四件读数器) without a full patrol run: exit 7
* when a `now` row reads ✗ (the hand-off is owed), 0 when both read ✓.
* `--handoff` owns its plan: `--land`, `--release` and every label or assignee flag are refused beside it.
*
* ## The read-back judge is HANDED to `sendFleetWrite`, never loaded by it
*
* Every send from this file passes `judge` (`readBackJudge`: post-stamped's `classifyReadBack` and
* `sentBodyLanded`). Without it `sendFleetWrite` loads the judge with a dynamic `import('../post-stamped.mjs')`
* once a stroke that carries a body has run, and that import never settles here: this file, post-stamped and
* `fleet-write/dispatch.mjs` import one another, so the three evaluate as ONE cycle whose completion waits on
* this file's top-level `await main(…)` — the very await the import sits under. Node then drains its event loop
* and exits 13 ("unsettled top-level await") after the relay run succeeded, with no `④` line printed, and a seat
* that re-runs posts the comment twice. The self-test drives both comment strokes through the REAL
* `sendFleetWrite` (`realTransport`: only fetch, clock, sleeps and throttle file are fake) to pin it.
*
* ## A retired lane alias is written as its lane
*
* An `--add` naming a retired lane spelling (`domain:engine`, `domain:services`,
* `domain:cli`, `domain:rest`) is rewritten to `domain:server` when the options
* are parsed — `rewriteRetiredLaneLabels` (`fleet-write/dispatch.mjs`) over the
* one alias map — so step ② computes its target on the label that will really
* land and step ④'s read-back diffs against it, on either transport; step ②
* prints one line per rewrite. ⛔ A rewrite, never a refusal. `--remove` is
* left literal: taking a retired label off a card has to name it.
*
* ## Exit codes — capture them BEFORE any pipe
*
* 0 the write landed AND the read-back matched the target.
* 2 usage.
* 3 PREREQUISITE NOT MET — no token, no route, or the credential is rate-limit
* exhausted. NOT MEASURED: nothing was written and nothing is claimed. A 403
* whose `x-ratelimit-remaining` is 0 lands here rather than in the fallback
* ON PURPOSE — rate-limit refusal binds the IDENTITY, so switching channels
* to keep writing is the same act as retrying, and every seat shares this one.
* 4 the write was accepted and the READ-BACK DISAGREES with the target. The
* diff is printed. This is the one exit that means the board is now in a
* state nobody asked for.
* 5 every channel refused. A seat in this position has no label channel: hand
* the write to a seat that has one by filing a card in the target lane.
* ⛔ Never MCP `issue_write` — lock 1 denies it, and it was the whole-set
* replace this tool exists to avoid in the first place.
* 6 UNCONFIRMED — the dispatch was accepted and its run did not appear, or
* did not complete, within the ceiling. The run URL is printed. Go READ
* the card; ⛔ never re-run blind: a second dispatch is a second write.
*
* 7 `--handoff --dry-run` only: a `now` row reads ✗ — the hand-off is OWED. Nothing was written.
*
* Under `--land`, 2 is also the dogfood battery gate's judged refusal and 3 a gate read the platform did not
* answer (header: that gate), ⛔ ZERO writes on both.
*
* Under `--release`, 2 is also every REFUSAL before the write — a knock too
* young (the remaining time is printed), a knock that is not the newest
* comment, a card that is not an owned `pm:dispatched` card, a branch whose
* tip is not the sha named or that has an open pull — and 3 is also a route
* that is not the relay. ⛔ ZERO writes on every one of them.
*
* `node scripts/pm/label-write.mjs … > /tmp/lw.log 2>&1; EXIT=$?; tail -40 /tmp/lw.log`
*
* ## The vocabularies are IMPORTED, never restated
*
* `PM_EXCLUSIVE_STATE_LABELS` (the ONE-OF states), `PM_STATE_CLAIM` (what each
* one claims on its own) and `PM_RESIDUE_LABELS` (what claims work is in flight)
* come from `check-half-states.mjs`, so the write side and the read-side patrol
* cannot come to disagree about what a state is. A target carrying two states is
* REFUSED — H29's finding written one layer earlier, at the act that would
* create the pair — and `--allow-two-states` is the declared exception, which
* still prints what it let through.
*
* ## The stateless write — an open card leaves a hand with a state, and a parked card with no holder
*
* `STATELESS_RULE_PATH` says 「开着的卡离手恒落一态」. The measured shape it closes: a seat landed `Part of`, or
* went offline leaving a stay-behind, and took `pm:dispatched` off with nothing in its place — the card then sat in
* no view (not the queue, not a lane, not the unlock scan, not the decision inbox) until triage happened on it by
* hand. `refuseStatelessWrite` is the ONE predicate, asked of a card's target at every door that strips a state:
*
* - this file, at step ② on step ①'s own read (the plain write, `--comment-file` and `--release` alike);
* - `fleet-write/dispatch.mjs`, for an actions file whose stroke takes a `pm:*` state off a card, parks one or
* assigns someone to one — the target READ once, before the dry-run exit, as the kind rule reads it;
* - `close-cards.mjs`, whose every pack closes the card it strips — pinned by asking the predicate of the pack.
*
* Two halves. The strip: a `pm:*` state the target drops on an OPEN issue while the target carries no state at all is
* REFUSED (exit 2, zero writes) — the legal exits all leave a state: the same write adds another state, adds
* `needs-user-decision`, or closes the card; a card with two states losing one keeps one. The holder: a target parked
* in `PARKED_STATE_LABELS` that keeps an assignee is REFUSED when this write moved a state or an assignee; a write
* that moved neither (a regrade) did not make the pair and passes. A `--release` (`pm:dispatched` → `pm:queue`, every
* assignee cleared) is legal by both halves, and the self-test pins it. A pull request carries no card state, so it
* is never judged. No flag lets either half through: every legal exit is a state.
*
* ## The kind rule — no pm state on a pull request, no `pm:awaiting-merge` on an issue
*
* `.claude/skills/pm-dispatch/SKILL.md` keeps the two inboxes apart: the six
* states are 「issue 上的信号」, `needs-user-decision` is 「只挂决策卡(issue)、⛔ 永不挂 PR」,
* and 「`pm:awaiting-merge` 只挂 PR、不入六态」. A PR that took a state label left
* the maintainer's awaiting-merge list for the decision box (cloud PR #3680,
* 2026-11-06). This file is the seat's label write door, so it enforces the
* rule for every write it makes — it is not the only door that can put a label
* on the board, and it claims nothing about the others: an `--add` naming one
* of the six states on a pull request,
* or `pm:awaiting-merge` on an issue, is REFUSED at step ② (exit 2) with zero
* writes — and so is a `--release` on a pull request, whose stroke adds
* `pm:queue`. The kind is step ①'s own read, no extra call: the card object's
* `pull_request` member and its `html_url` must AGREE on one kind; a read where
* they do not is refused too, ⛔ never guessed. A `--remove` is never refused —
* that is how a wrong label comes off — and both labels stay legal on their own
* kind. The labels are the imported vocabulary (`PM_EXCLUSIVE_STATE_LABELS`,
* `GOVERNED_PR_AWAITING_MERGE_LABEL`); the self-test pins each quoted rule as a
* substring of SKILL.md, so a reworded rule reds here rather than drifting.
*
* Both refusals — this one and the ONE-OF one — compare pm labels the way GitHub
* matches label names, case-insensitively (`labelKey`): `Needs-User-Decision`
* applies the existing `needs-user-decision`, so it is refused like it. The
* relay's own adding ops (`fleet-write/dispatch.mjs`: `labels_add`, `pr_create`,
* `issue_create`) ask this same `refuseKindLabels` before they send.
*
* ## The hand-set grade — a `priority:*` a person set is not changed by this tool
*
* A maintainer changed a card's grade on GitHub and triage changed it back.
* `references/filing-gate.md` now says 「人定的级 ⛔ 不改」, and tells a person's
* hand from the fleet's by an ALLOW-LIST read off the label event itself: the
* newest `labeled` event of the grade the card carries is the fleet's only when
* it carries `performed_via_github_app` or its actor is a bot
* (`objectstack-fleet[bot]` through the relay, `github-actions[bot]` from a
* workflow). Every other event is a person's — and so is a grade with no
* `labeled` event at all, or an events read the platform did not answer:
* what cannot be shown to be the fleet's is not treated as the fleet's.
*
* So a write whose target changes the card's set of `priority:*` labels reads
* the card's events first (one extra GET per 100 events, only on such a write;
* a first grade on an ungraded card reads nothing), and a grade a person set
* is REFUSED at step ② (exit 2) with zero writes. `unlabeled` events are not
* read: GitHub drops the app field on them, so the removing half of a session's
* own stroke reads like a hand. The one way through is the rule's own: the
* maintainer has ruled, and the comment folded into the write (`--comment-file`)
* carries a `Ruling-ref:` line citing his words. To disagree without a ruling,
* leave one line with the reason on the card as a comment, and nothing else:
* the grade and the card's state stay. ⛔ This is the seat's label door and claims nothing about the
* others: a write that reaches the board another way is not judged here.
*
* A grade the fleet wrote ON the maintainer's word is his too (`filing-gate.md`: 「代维护者落的级 … 才算人定」):
* the bot actor says who typed it, not whose grade it is. Such a write folds a comment whose line opens
* `Ruling-ref: priority:pN` — the grade it writes — before his words (`GRADE_RULING_MARK`), so a fleet-set grade whose
* `labeled` event has, within `RULING_COMMENT_WINDOW_MS` of it, a FLEET comment (the same allow-list as the event)
* with a line opening `Ruling-ref:` and that same grade is refused like a hand. Any other `Ruling-ref:` is not a
* grade he named and reads as nothing here: a lane seat's self-triage record citing the standing exception
* (`triage-duties.md`), a claim or dispatch citing a ruling comment id (`dispatch-runbook.md`), a line naming
* another grade, or one a person typed — so triage's 改判 of a self-triaged grade still lands. The marker is read
* past backticks and a quote set tight after the grade. The write agrees with that read: a folded `Ruling-ref:` lets a
* grade change past a person's (or his) grade only when it names every grade the write sets; one that names none is
* asked as if absent — refused there with the exact line to write, and over a grade the fleet may change anyway
* passed with a step ② line saying the new grade will read as the fleet's own. That costs one
* comments read (from the oldest fleet grade event minus the window), only when a carried grade reads as the fleet's;
* a read that does not answer is refused, never passed — the same rule as an unread events list.
*/
import process from 'node:process';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
// The self-test's at-tier transcript fixture names the tier's value from the one place it is declared.
import { CONTRACT_REVIEW_TIER } from './dispatch-gates.mjs';
import { fileURLToPath } from 'node:url';
import { isEntrypoint } from '../invoked-as.mjs';
import { EXIT_UNCONFIRMED, exitForResult, packRequest, resolveRoute, retiredLaneRewriteLine, rewriteRetiredLaneLabels, sendFleetWrite, unconfirmedText } from './fleet-write/dispatch.mjs';
import { refusalText as relayRefusalText } from './fleet-write/validate.mjs';
import { isProxyRefusal, isWriteMethod, noteResponse, paceWrite, releaseWriteLease } from './write-pace.mjs';
import {
DECISION_INBOX_LABEL,
EXIT_PREREQUISITE_NOT_MET,
GOVERNED_PR_AWAITING_MERGE_LABEL,
OS_DEV_REPORT_MARKER,
PM_EXCLUSIVE_STATE_LABELS,
PM_RESIDUE_LABELS,
PM_STATE_CLAIM,
PROXY_FLAG,
RELEASE_COMMENT_MARKER,
devReportPayloadCandidates,
latestMarkedComment,
markerMatches,
proxyRearmPlan,
resolveSweepRepo,
stripSignatureLine,
// `--handoff` (header): the H43 hand-off reading and the two patrol rows its read-back asks, CALLED, never re-spelled.
MAINTAINER_BRIEF_MARKER,
h43HandoffReading,
h43GovernedReviewRequestGap,
readSignatureLine,
h48GovernedVerdictWithoutBrief,
} from './check-half-states.mjs';
import { GOVERNED_TIER_H, GOVERNED_TIER_S, LOW_RISK_CHANGESET_PATH, sizeLimbFires, slugFromRemote } from './check-governed-merges.mjs';
// The `--land` dogfood gate's readers (header: `--land` on a breaking or narrowing pull), each CALLED from its owner:
// the one `Clause-②:` reader, the card a pull delivers, the relay's identity and the record leg's author trust.
import { quoteLine, readClause2Line } from './clause2-line.mjs';
import { deliveredCardNumber, deliveredCardsAtStrongest } from './record-recognisers.mjs';
import { RELAY_COMMENT_AUTHOR } from './fleet-write/ops.mjs';
import { GOVERNED_APPROVERS, NARROWED_RULING, RECOGNISER_SOURCES, loadRecordRecognisers, narrowedReading, readRecordThreads, recordAuthorTrusted, recordPassVerdict, recordTrustedAuthors, recordVerdict } from './check-governed-queue-guard.mjs';
// `--handoff`'s record reading loads the guard's recognisers through the guard's OWN loader, handed these two
// namespaces for the two specifiers it imports (`RECOGNISER_SOURCES`). ⛔ Never a dynamic import from here:
// `check-handover.mjs` imports post-stamped, which reaches this file through `fleet-write/dispatch.mjs`, so a dynamic
// import of it under this file's top-level `await main(…)` waits on that very await and node exits 13 (the same
// cycle the read-back judge section above describes). A static import evaluates with the cycle; neither namespace is
// touched at module scope.
import * as recordRecognisersModule from './record-recognisers.mjs';
import * as checkHandoverModule from './check-handover.mjs';
// The comment half of a release, borrowed exactly as close-cards borrows it:
// the one `comment` op, the stamp render, and the board-side read-back of the
// stored bytes. ⛔ None of these is touched at module scope — post-stamped
// reaches this file through `fleet-write/dispatch.mjs`, so a module-scope use
// here would read a binding that has not been initialised yet when
// post-stamped is the entrypoint.
import {
PLATFORM_COMMENT_FOOTER,
classifyReadBack,
judgeBody,
pickRelayComment,
readBackVerdict as commentReadBackVerdict,
relayAction,
sentBodyLanded,
substitutionSummary,
} from './post-stamped.mjs';
const SELF_PATH = fileURLToPath(import.meta.url);
const REPO_ROOT = new URL('../../', import.meta.url);
const API = 'https://api.github.com';
const TOKEN = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? '';
const PROXY_REARM_GUARD = 'OS_LABEL_WRITE_PROXY_REARMED';
/**
* The read-back judge every `sendFleetWrite` from this file is HANDED (header: the read-back judge). Built at
* call time, ⛔ never at module scope — the bindings are post-stamped's, unread until its evaluation is done.
*/
const readBackJudge = () => ({ classifyReadBack, sentBodyLanded });
export const EXIT_OK = 0;
export const EXIT_USAGE = 2;
export const EXIT_READ_BACK_MISMATCH = 4;
export const EXIT_PLATFORM_REFUSAL = 5;
/** `--handoff --dry-run` only: a `now` row reads ✗ — the hand-off is owed (header: exit codes). */
export const EXIT_HANDOFF_OWED = 7;
/**
* Re-exported so a caller reads ONE name rather than remembering that 3 is
* shared with the sweeper. `check-half-states.mjs` owns the value.
*/
export const EXIT_PREREQUISITE = EXIT_PREREQUISITE_NOT_MET;
// ---------------------------------------------------------------------------
// The pure core — every rule this tool has, as functions a self-test can drive
// with fixtures. The live path below is a thin fetch loop around them, so the
// arithmetic that decides what gets written is testable offline and the network
// leg has no judgement of its own.
// ---------------------------------------------------------------------------
/** Order-preserving de-duplication. A label named twice is one label. */
export function dedupe(values) {
const seen = new Set();
const out = [];
for (const v of values ?? []) {
if (seen.has(v)) continue;
seen.add(v);
out.push(v);
}
return out;
}
/** A repeatable comma list (`--add a,b --add c`), trimmed, de-duplicated, empties dropped. */
export function parseList(raw) {
const parts = [];
for (const chunk of Array.isArray(raw) ? raw : [raw]) {
for (const piece of String(chunk ?? '').split(',')) {
const value = piece.trim();
if (value) parts.push(value);
}
}
return dedupe(parts);
}
/**
* Step ② for labels: target = (current ∪ add) − remove, plus the plan that
* reaches it with the two NON-destructive verbs.
*
* The two `noop*` buckets are the idempotence this tool promises. Re-adding a
* label the card already carries issues no call and is a success; removing one
* it no longer carries issues no call and is a success. Neither is an error to
* report — a seat that re-runs a write because it could not read the first run's
* exit code must get the same answer, or the retry becomes its own hazard.
*/
export function computeLabelTarget({ current = [], add = [], remove = [] } = {}) {
const cur = dedupe(current);
const adds = dedupe(add);
const removes = dedupe(remove);
const removeSet = new Set(removes);
const currentSet = new Set(cur);
const target = [...cur.filter((l) => !removeSet.has(l)), ...adds.filter((l) => !currentSet.has(l) && !removeSet.has(l))];
return {
target,
addCalls: adds.filter((l) => !currentSet.has(l)),
removeCalls: removes.filter((l) => currentSet.has(l)),
noopAdds: adds.filter((l) => currentSet.has(l)),
noopRemoves: removes.filter((l) => !currentSet.has(l)),
};
}
/** Step ② for assignees. Same shape, same idempotence, and `clearAll` wins over both lists. */
export function computeAssigneeTarget({ current = [], assign = [], unassign = [], clearAll = false } = {}) {
const cur = dedupe(current);
if (clearAll) {
return { target: [], addCalls: [], removeCalls: cur, noopAdds: [], noopRemoves: [] };
}
const adds = dedupe(assign);
const removes = dedupe(unassign);
const removeSet = new Set(removes);
const currentSet = new Set(cur);
return {
target: [...cur.filter((l) => !removeSet.has(l)), ...adds.filter((l) => !currentSet.has(l) && !removeSet.has(l))],
addCalls: adds.filter((l) => !currentSet.has(l)),
removeCalls: removes.filter((l) => currentSet.has(l)),
noopAdds: adds.filter((l) => currentSet.has(l)),
noopRemoves: removes.filter((l) => !currentSet.has(l)),
};
}
/**
* A label as GitHub MATCHES it: label names compare case-insensitively, so adding `Needs-User-Decision`
* applies the existing `needs-user-decision`. Every pm-label refusal here (`refuseTwoStates`,
* `refuseKindLabels`) asks the vocabulary through this key, never by exact spelling.
*/
export function labelKey(label) {
return typeof label === 'string' ? label.toLowerCase() : label;
}
/**
* H29's finding, asked of a TARGET rather than of a board: would this write
* leave two ONE-OF state claims standing? Returns the sentence, or null.
*
* Reported at the act that would create the pair rather than by a patrol hours
* later, because the measured origin of every pair is the same: a TRANSITION
* written as an ADD instead of a REPLACE. That is exactly what `--add` without
* the matching `--remove` spells here, so this is the one place the mistake is
* still one keystroke from correct.
*/
export function refuseTwoStates(target = []) {
const keys = new Set((target ?? []).map(labelKey));
const present = PM_EXCLUSIVE_STATE_LABELS.filter((l) => keys.has(labelKey(l)));
if (present.length < 2) return null;
const named = present.map((l) => `\`${l}\` (${PM_STATE_CLAIM[l]})`).join(' + ');
return (
`the target carries ${present.length} pm STATE labels — ${named} — and the state labels are ONE-OF: ` +
'each is a claim about where the card IS, so two of them leave the queue view, the lane view, the unlock ' +
'scan and the decision inbox to pick which one they believe. A transition is a REPLACE: name the state ' +
'being left in `--remove` in this same write. Pass `--allow-two-states` only if two claims really are true ' +
'here, and say so on the card.'
);
}
/**
* The pm states a card is PARKED in — waiting in the queue, on an upstream, or behind a restart — and so held by
* nobody (`PARKED_RULE`, quoted from `KIND_RULE_PATH`'s state table; header: the stateless write).
*/
export const PARKED_STATE_LABELS = Object.freeze(['pm:queue', 'pm:blocked', 'pm:on-hold']);
export const PARKED_RULE = '`pm:queue` 卡恒无 assignee,有即半态;`pm:blocked`/`pm:on-hold` 同';
/** Where the stateless-write rule is written, and the phrase this file quotes from it (header: the stateless write). */
export const STATELESS_RULE_PATH = '.claude/skills/pm-dispatch/references/state-machine.md';
export const STATELESS_RULE = '开着的卡离手恒落一态';
/**
* The stateless write (header), asked of ONE card's TARGET: would this write take the last `pm:*` state off an OPEN
* card, or leave an assignee on a card parked in `PARKED_STATE_LABELS`? Returns the refusal sentence, or null.
*
* state the card's state as read (`open` | `closed`); a closed card is never judged — closing is the third exit.
* closes the same write closes the card (close-cards, a relay stroke carrying `issue_patch state: closed`).
* kind the card's kind (`readTargetKind`); a pull request carries no card state, so taking one off it is the
* kind rule's cleanup and is never judged here.
* current / target the label sets before and after the write.
* currentAssignees / assigneeTarget the assignee sets before and after the write.
*
* The strip half: a `pm:*` state on the card (one of `PM_EXCLUSIVE_STATE_LABELS` other than the inbox label) that the
* target drops, while the target carries NO state at all. The exits the rule names are all "the target still carries a
* state": the same write adds another state, or adds `needs-user-decision`; a card that carried two states and loses
* one (the ONE-OF repair) keeps one and passes too. The assignee half: the target is parked AND keeps an assignee, and
* THIS write moved a state or an assignee — a write that touches neither (a priority, a domain) did not make the pair
* and is not refused for it. Labels compare case-insensitively (`labelKey`), as GitHub matches them.
*/
export function refuseStatelessWrite({ state = 'open', closes = false, kind = KIND_ISSUE, current = [], target = [], currentAssignees = [], assigneeTarget = [] } = {}) {
if (state === 'closed' || closes || kind === KIND_PULL) return null;
const keysOf = (ls) => new Set((ls ?? []).map(labelKey));
const cur = keysOf(current);
const tgt = keysOf(target);
const pmStates = PM_EXCLUSIVE_STATE_LABELS.filter((l) => l !== DECISION_INBOX_LABEL);
const stripped = pmStates.filter((l) => cur.has(labelKey(l)) && !tgt.has(labelKey(l)));
const kept = PM_EXCLUSIVE_STATE_LABELS.filter((l) => tgt.has(labelKey(l)));
const tick = (ls) => ls.map((l) => `\`${l}\``).join(', ');
const rule = `${STATELESS_RULE_PATH}: 「${STATELESS_RULE}」`;
if (stripped.length && kept.length === 0) {
return (
`the write takes ${tick(stripped)} off an OPEN card and leaves it with NO state — ${rule}. A card no state names is ` +
'in no view: not the queue, not a lane, not the unlock scan, not the decision inbox, so nobody picks it up. Name ' +
`where it goes in this same write: \`--add\` the next state (\`pm:queue\` with its lane's \`domain:*\`, \`pm:blocked\` ` +
`with a \`Blocked-by:\` line, \`pm:on-hold\` with a \`Restart-when:\` line) or \`${DECISION_INBOX_LABEL}\` — or close the card.`
);
}
const parked = PARKED_STATE_LABELS.filter((l) => tgt.has(labelKey(l)));
const holders = dedupe(assigneeTarget ?? []);
if (!parked.length || !holders.length) return null;
const stateKeys = (set) => PM_EXCLUSIVE_STATE_LABELS.filter((l) => set.has(labelKey(l))).join(',');
const before = dedupe(currentAssignees ?? []);
const movedAssignees = before.length !== holders.length || holders.some((l) => !before.includes(l));
if (stateKeys(cur) === stateKeys(tgt) && !movedAssignees) return null;
return (
`the target parks the card in ${tick(parked)} and still assigns it to ${tick(holders)} — ${KIND_RULE_PATH}: 「${PARKED_RULE}」. A parked card is ` +
'held by nobody: the queue view reads an assigned card as claimed and skips it, so the work waits for a holder who ' +
'has already let go. Clear the assignee in this same write (`--clear-assignees`), or keep the card in the state its ' +
'holder is working it in.'
);
}
/** Where the hand-set grade rule is written, and the phrase this file quotes from it (header: the hand-set grade). */
export const HAND_SET_RULE_PATH = '.claude/skills/pm-dispatch/references/filing-gate.md';
export const HAND_SET_RULE = '人定的级 ⛔ 不改';
export const GRADE_LABEL_PREFIX = 'priority:';
export const RULING_REF_KEY = 'Ruling-ref:';
/** The grade read walks at most this many pages of a card's events (100 a page); a card with more is an incomplete read. */
export const GRADE_EVENT_PAGE_CAP = 10;
/** A grade-ruling comment this close to a fleet `labeled` event is the write's own fold: the grade is the maintainer's (header). */
export const RULING_COMMENT_WINDOW_MS = 120_000;
/** The marker `filing-gate.md` spells for a grade written on the maintainer's word: the key, then the grade it writes (header). */
export const GRADE_RULING_MARK = `${RULING_REF_KEY} ${GRADE_LABEL_PREFIX}pN`;
const gradeKeys = (labels) => dedupe((labels ?? []).map(labelKey).filter((l) => typeof l === 'string' && l.startsWith(GRADE_LABEL_PREFIX))).sort();
/** The grades a write CHANGES: every `priority:*` the card carries, when the target's set of them differs. An ungraded card changes none. */
export function gradesChanged({ current = [], target = [] } = {}) {
const carried = gradeKeys(current);
return carried.length === 0 || carried.join() === gradeKeys(target).join() ? [] : carried;
}
/** The allow-list (header): a label event is the fleet's only with an app on it or a bot for an actor. */
export function isFleetLabelEvent(event) {
return Boolean(event?.performed_via_github_app) || event?.actor?.type === 'Bot';
}
/** A `Ruling-ref:` line in the folded comment: at a line start, with something after the key. */
export function hasRulingRef(text) {
return String(text ?? '').split(/\r?\n/u).some((line) => line.startsWith(RULING_REF_KEY) && line.slice(RULING_REF_KEY.length).trim() !== '');
}
/** The newest `labeled` event of one grade, or undefined. */
const newestGradeEvent = (events, grade) => events.filter((e) => e?.event === 'labeled' && labelKey(e?.label?.name) === grade).at(-1);
/** The grade a `Ruling-ref:` line opens with — backticks, quotes and a quote set tight after it tolerated — or undefined. */
const GRADE_AT_LINE_START = new RegExp(`^[\\s\`'"*]*(${GRADE_LABEL_PREFIX}[A-Za-z0-9_-]+)`, 'iu');
/** A line opening `Ruling-ref:` whose first cited word is `grade` (`GRADE_RULING_MARK`): his ruling on THAT grade, not any ruling. */
export function hasGradeRuling(text, grade) {
return String(text ?? '').split(/\r?\n/u).some((line) => line.startsWith(RULING_REF_KEY) && labelKey(line.slice(RULING_REF_KEY.length).match(GRADE_AT_LINE_START)?.[1]) === grade);
}
/** The fleet's comment, within the window of a fleet label event, naming that event's grade after `Ruling-ref:`: the fold of a write on the maintainer's word. */
export function rulingCommentNear(event, comments = []) {
const at = Date.parse(event?.created_at ?? '');
const grade = labelKey(event?.label?.name);
if (!Number.isFinite(at) || typeof grade !== 'string') return undefined;
return (comments ?? []).find(
(c) => isFleetLabelEvent({ performed_via_github_app: c?.performed_via_github_app, actor: c?.user }) && Math.abs(Date.parse(c?.created_at ?? '') - at) <= RULING_COMMENT_WINDOW_MS && hasGradeRuling(c?.body, grade),
);
}
/** Where a fleet-set grade's ruling comments are read from: the oldest fleet event among the grades, minus the window; or null. */
export function rulingCommentsSince({ grades = [], events = null } = {}) {
if (!Array.isArray(events)) return null;
const times = grades
.map((g) => newestGradeEvent(events, g))
.filter((e) => e && isFleetLabelEvent(e))
.map((e) => Date.parse(e.created_at ?? ''))
.filter(Number.isFinite);
return times.length ? new Date(Math.min(...times) - RULING_COMMENT_WINDOW_MS).toISOString() : null;
}
/**
* The hand-set grade (header), asked of the grades ONE write changes. Returns the refusal sentence, or null.
*
* grades `gradesChanged`'s answer — the carried `priority:*` labels, as `labelKey` spells them.
* events the card's issue events, oldest first as the platform lists them; null when the read did not answer or
* ran past `GRADE_EVENT_PAGE_CAP`. Only `labeled` events are read (header: why not `unlabeled`).
* comments the card's comments around the fleet-set grades' events (`rulingCommentsSince`); null when that read did
* not answer. A fleet event with the fleet's `Ruling-ref: <that grade>` comment beside it is his grade (header).
* rulingRef the folded comment carries a `Ruling-ref:` line — the maintainer's ruling, cited; nothing is refused.
*/
export function refuseHandSetGrade({ grades = [], events = null, comments = [], rulingRef = false, ref = 'the card' } = {}) {
if (grades.length === 0 || rulingRef) return null;
const rule = `${HAND_SET_RULE_PATH}: 「${HAND_SET_RULE}」`;
const exits =
'A grade a person set stays. To disagree, leave one line with the reason on the card as a comment, and nothing else: the grade ' +
`and the card's state stay as they are; where the maintainer has already ruled, fold the comment into this write (\`--comment-file\`) with a line opening \`${GRADE_RULING_MARK}\` — the grade it writes — then his words.`;
if (!Array.isArray(events)) {
return (
`the write changes the grade of ${ref} and the card's label events could not be read in full (${GRADE_EVENT_PAGE_CAP} pages at most), so ` +
`nothing shows the fleet set ${grades.map((g) => `\`${g}\``).join(', ')} — ${rule}. ${exits}`
);
}
const byHand = [];
for (const grade of grades) {
const set = newestGradeEvent(events, grade);
if (set && isFleetLabelEvent(set)) {
if (!Array.isArray(comments)) {
byHand.push(`\`${grade}\` (set by the fleet at ${set.created_at ?? 'an unread time'}, and the comments beside it could not be read, so nothing shows it was not written on the maintainer's word)`);
continue;
}
const ruling = rulingCommentNear(set, comments);
if (!ruling) continue;
byHand.push(`\`${grade}\` (set by the fleet at ${set.created_at} on the maintainer's word: the fleet's comment ${ruling.id ?? 'unread'} beside it opens a line \`${RULING_REF_KEY} ${grade}\`)`);
continue;
}
byHand.push(
set
? `\`${grade}\` (set by \`${set.actor?.login ?? 'an unread actor'}\` at ${set.created_at ?? 'an unread time'}: actor type ${set.actor?.type ?? 'unread'}, no \`performed_via_github_app\`)`
: `\`${grade}\` (no \`labeled\` event for it on the card)`,
);
}
if (byHand.length === 0) return null;
return `the write changes the grade of ${ref}, and ${byHand.join(' and ')} is not the fleet's own grade — ${rule}. ${exits}`;
}
/** The hand-set refusal for a write whose folded `Ruling-ref:` would have let it through but names no grade it writes, with the exact fix. */
export function unnamedGradeRuling(handSet, written = []) {
const fix = written.length ? written.map((g) => `\`${RULING_REF_KEY} ${g} 「his words」\``).join(' and ') : `a \`${RULING_REF_KEY}\` line`;
return (
`${handSet.replace(/ — .*$/su, '')}. The folded \`${RULING_REF_KEY}\` would let it through, so this is a grade written on the maintainer's word — and its line names no grade ` +
`this write sets, so the new grade would read as the fleet's own and be changed again (${HAND_SET_RULE_PATH}: 「行首 \`${GRADE_RULING_MARK}\` 引原话才算人定」). Open the line ${fix} and send again.`
);
}
/** The card's comments since `since`, for the ruling read beside a fleet-set grade; null on any unanswered page or past the cap. */
async function readRulingComments({ doCall, base, since }) {
const all = [];
for (let page = 1; page <= GRADE_EVENT_PAGE_CAP; page += 1) {
const r = await doCall('comments-list', `${base}/comments?since=${encodeURIComponent(since)}&per_page=100&page=${page}`, {});
if (r.verdict !== 'ok' || !Array.isArray(r.json)) return null;
all.push(...r.json);
if (r.json.length < 100) return all;
}
return null;
}
/** The card's issue events for the grade read, or null when a page did not answer or the cap was reached with more to come. */
async function readLabelEvents({ doCall, base }) {
const all = [];
for (let page = 1; page <= GRADE_EVENT_PAGE_CAP; page += 1) {
const r = await doCall('events-list', `${base}/events?per_page=100&page=${page}`, {});
if (r.verdict !== 'ok' || !Array.isArray(r.json)) return null;
all.push(...r.json);
if (r.json.length < 100) return all;
}
return null;
}
/** Where the kind rule is written, and the three phrases of it this file quotes (header: the kind rule). */
export const KIND_RULE_PATH = '.claude/skills/pm-dispatch/SKILL.md';
export const KIND_RULE_STATES_ON_ISSUES = 'issue 上的信号';
export const KIND_RULE_DECISION_NEVER_ON_PR = '只挂决策卡(issue)、⛔ 永不挂 PR';
export const KIND_RULE_AWAITING_MERGE_PR_ONLY = '`pm:awaiting-merge` 只挂 PR、不入六态';
export const KIND_PULL = 'pull request';
export const KIND_ISSUE = 'issue';
/**
* Step ①'s card object, asked what it IS. Two members say it independently —
* `pull_request` (present, an object, on a PR; absent on an issue) and
* `html_url` (`/pull/N` or `/issues/N`) — and the answer is a kind only when
* BOTH agree. Anything else is `{ kind: null, why }`: ⛔ never a guess.
*/
export function readTargetKind(card) {
if (!card || typeof card !== 'object' || Array.isArray(card)) return { kind: null, why: 'the card read returned no object' };
const url = typeof card.html_url === 'string' ? card.html_url : '';
const byUrl = /\/pull\/\d+\/?$/.test(url) ? KIND_PULL : /\/issues\/\d+\/?$/.test(url) ? KIND_ISSUE : null;
const hasKey = Object.hasOwn(card, 'pull_request');
const byKey = !hasKey ? KIND_ISSUE : card.pull_request && typeof card.pull_request === 'object' ? KIND_PULL : null;
if (byUrl !== null && byUrl === byKey) return { kind: byUrl, why: null };
const keySaid = hasKey ? `\`pull_request\` is ${JSON.stringify(card.pull_request) ?? 'undefined'}` : '`pull_request` is absent';
return { kind: null, why: `${keySaid} and \`html_url\` is \`${url || '(absent)'}\` — they do not name one kind` };
}
/**
* The kind rule, asked of a write's ADDS (header: the kind rule). Returns the
* one refusal sentence, or null. Removals are not an input: taking a label off
* is never refused.
*/
export function refuseKindLabels({ kind, why = null, add = [], ref = 'the card' } = {}) {
const adds = dedupe(add ?? []);
const keys = new Set(adds.map(labelKey));
const states = PM_EXCLUSIVE_STATE_LABELS.filter((l) => keys.has(labelKey(l)));
const awaiting = keys.has(labelKey(GOVERNED_PR_AWAITING_MERGE_LABEL));
if (!states.length && !awaiting) return null;
const tick = (ls) => ls.map((l) => `\`${l}\``).join(', ');
const said = refuseKindText({ kind, why, states, awaiting, ref, tick });
if (said === null) return null;
// An add the refusal names, spelled other than the vocabulary, is named as written: the seat sees why it matched.
const named = kind === KIND_PULL ? states : kind === KIND_ISSUE ? [GOVERNED_PR_AWAITING_MERGE_LABEL] : [...states, ...(awaiting ? [GOVERNED_PR_AWAITING_MERGE_LABEL] : [])];
const byKey = new Map(named.map((l) => [labelKey(l), l]));
const respelt = adds.filter((l) => byKey.has(labelKey(l)) && byKey.get(labelKey(l)) !== l);
if (!respelt.length) return said;
return `${said} GitHub matches label names case-insensitively: ${respelt.map((l) => `\`${l}\` is \`${byKey.get(labelKey(l))}\``).join(', ')}.`;
}
function refuseKindText({ kind, why, states, awaiting, ref, tick }) {
const statesRule = `its 状态模型 lists the six states as 「${KIND_RULE_STATES_ON_ISSUES}」 and says 「${KIND_RULE_AWAITING_MERGE_PR_ONLY}」`;
const decisionRule = states.includes(DECISION_INBOX_LABEL) ? `, and of \`${DECISION_INBOX_LABEL}\` 「${KIND_RULE_DECISION_NEVER_ON_PR}」` : '';
const never = 'removing a label is never refused.';
if (kind === null || (kind !== KIND_PULL && kind !== KIND_ISSUE)) {
const governed = [...states, ...(awaiting ? [GOVERNED_PR_AWAITING_MERGE_LABEL] : [])];
return (
`${ref}'s kind could not be read (${why ?? 'no kind'}), and ${tick(governed)} ${governed.length > 1 ? 'are' : 'is'} legal on only one kind — ${KIND_RULE_PATH}: ` +
`${statesRule}${decisionRule} — so the write is refused rather than guessed; re-run once the card reads whole, and ${never}`
);
}
if (kind === KIND_PULL && states.length) {
return (
`${tick(states)} ${states.length > 1 ? 'are pm card STATES' : 'is a pm card STATE'} and ${ref} is a pull request — ${KIND_RULE_PATH}: ` +
`${statesRule}${decisionRule} — so a PR waiting on the maintainer carries \`${GOVERNED_PR_AWAITING_MERGE_LABEL}\` instead; ${never}`
);
}
if (kind === KIND_ISSUE && awaiting) {
return (
`\`${GOVERNED_PR_AWAITING_MERGE_LABEL}\` is the pull-request inbox label and ${ref} is an issue — ${KIND_RULE_PATH}: ` +
`「${KIND_RULE_AWAITING_MERGE_PR_ONLY}」 — so a card waiting on the maintainer's decision carries \`${DECISION_INBOX_LABEL}\` instead; ${never}`
);
}
return null;
}
/**
* A closed card whose target still claims work is in flight. Report-only: the
* write is not blocked, because a seat re-labelling a closed card usually knows
* why, and the standing `sweep-closed-cards.mjs --write` caller clears residue
* on its own schedule with no seat channel involved.
*/
export function residueNote({ state, target = [] } = {}) {
if (state !== 'closed') return null;
const present = PM_RESIDUE_LABELS.filter((l) => (target ?? []).includes(l));
if (present.length === 0) return null;
return (
`the card is CLOSED and the target still carries ${present.map((l) => `\`${l}\``).join(', ')} — residue that ` +
'claims work is in flight. Not blocked, and not this tool\'s to decide: the half-state patrol\'s closed-card ' +
'sweep clears it on its own schedule. Named here so the write is deliberate rather than accidental.'
);
}
/**
* Step ④'s verdict, in three buckets that mean three different things.
*
* `missing` — in the target, absent from the read-back. STRIPPED
* UNDERNEATH by a concurrent whole-set writer (or the
* write silently did not take). Re-add once, and REPORT.
* `survivedRemoval` — asked to be removed, still there. The directed DELETE
* did not take; re-issuing it is not a repair, so this is
* a mismatch.
* `concurrentAdds` — present, never in the target, never asked to be removed.
* ⛔ NOT a mismatch: an additive write by another seat is
* precisely what additive-first exists to preserve. It is
* printed because a seat should know the board moved.
*/
export function readBackVerdict({ target = [], removeCalls = [], readBack = [] } = {}) {
const back = new Set(readBack);
const targetSet = new Set(target);
const removed = new Set(removeCalls);
return {
missing: target.filter((l) => !back.has(l)),
survivedRemoval: removeCalls.filter((l) => back.has(l)),
concurrentAdds: readBack.filter((l) => !targetSet.has(l) && !removed.has(l)),
};
}
/** Is this verdict clean enough to exit 0? `concurrentAdds` deliberately does not count. */
export function verdictIsClean(verdict) {
return (verdict?.missing?.length ?? 0) === 0 && (verdict?.survivedRemoval?.length ?? 0) === 0;
}
/**
* The PATCH fallback body. `assignees` is ALWAYS present, even when no assignee
* change was asked for — that is the echo, and it is the difference between a
* label write and a label write that silently un-assigns the card.
*/
export function patchFallbackBody({ labelTarget = [], assigneeTarget = [] } = {}) {
return { labels: [...labelTarget], assignees: [...assigneeTarget] };
}
/**
* Step ③ as ONE relay stroke: the same additive verbs the direct plan issues,
* in the same order, as the relay's actions. Pure. An empty plan packs to no
* actions — and no dispatch leaves for it.
*/
export function relayActions({ issue, labels, assignees } = {}) {
const out = [];
if (labels?.addCalls?.length) out.push({ op: 'labels_add', issue, labels: [...labels.addCalls] });
if (labels?.removeCalls?.length) out.push({ op: 'labels_remove', issue, labels: [...labels.removeCalls] });
if (assignees?.addCalls?.length) out.push({ op: 'assign', issue, assignees: [...assignees.addCalls] });
if (assignees?.removeCalls?.length) out.push({ op: 'unassign', issue, assignees: [...assignees.removeCalls] });
return out;
}
/**
* What an HTTP answer MEANS for the op that asked. Pure, because this is the
* decision that routes between "try the fallback", "stop, nothing is measured"
* and "that was a success spelled as a 404".
*
* Four answers a status alone cannot give:
*
* - a `404` on a DELETE of ONE NAMED LABEL is the label already being gone.
* Idempotent success. On any other op a 404 is the egress refusing a path,
* because step ① already proved the card exists;
* - a `403`/`429` with `x-ratelimit-remaining: 0` is EXHAUSTION, not a shut
* channel. It must NOT reach the fallback: rate-limit refusal binds the
* identity, every seat on this board shares that identity, and continuing
* the same write through another channel is the same act as retrying;
* - `401`/`407` is the ROUTE or the credential — nothing about this card;
* - a thrown fetch (status 0) is the route too;
* - a 403 whose BODY is the egress proxy's ("not permitted through this
* proxy", a `documentation_url` that is not GitHub's) is the ROUTE as well
* — the request never reached the platform — so it is `prerequisite`,