Repository navigation
Expand file tree
/
Copy pathrecord-recognisers.mjs
More file actions
3043 lines (2927 loc) · 258 KB
/
Copy pathrecord-recognisers.mjs
File metadata and controls
3043 lines (2927 loc) · 258 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.
/**
* record-recognisers — the readers of the ONE `## Contract review` record a
* Tier S pull request lands on, and the copyable record they read.
*
* node scripts/pm/record-recognisers.mjs --template # the record, copyable; no network
* node scripts/pm/record-recognisers.mjs --brief-template # the reviewer's brief, read-only shape built in; no network
* node scripts/pm/record-recognisers.mjs --template --paths PATH-ONE PATH-TWO # face and `Scope:` read off the PR's paths
* node scripts/pm/record-recognisers.mjs --self-test # offline, no network
* node scripts/pm/record-recognisers.mjs --help # this usage; no network
*
* ## What lives here, and why it is its own file
*
* Ruling record 5770886272 on #19061 (letter B) made three layers one: the
* gate label, the `--pair` landing pre-check and the independence pair are
* retired, and exactly one `## Contract review` record per Tier S pull request
* stays — the record `check-governed-queue-guard.mjs` reads in the merge group
* to release `.claude/**`. This file is what reads it, and nothing else:
*
* locateReviewOfRecord the record on this head, on the PR thread or its card
* deliveredCardNumber which card thread a pull request's record may sit on
* readServedTier the `Served-tier:` line, and `servedTierStands` on it — at the tier its face maps to
* reviewFace / REVIEW_FACES which face made the review owed, and the ONE tier NAME it stands at
* reviewScopeHits the at-tier review's scope floor — `reviewFace`'s `hits`, the record's `Scope:` line
* recordCarriesDesignJudgment whether a face's record carries item ④, the full review's design judgment
* readLocalRuns the `Local-runs:` line, and `localRunsStand` on it — judged when present, absent not re-judged
* contractReviewHandoff whose review a PR's contract review is — the newest `Contract-review-handoff:` line against the head; `readContractReviewHandoff` reads the line; `contractReviewClaims` (`readContractReviewClaim`, `contractReviewClaimLapse`) who holds the head; `contractReviewHold` (`readContractReviewHold`) whether a lane holds it — per head, the newest readable `Contract-review-hold:` line naming it, unreadable lines listed and never voiding, its age a reading never a lapse
* isModelIdentifierToken the token a refusal must never quote back
* REVIEW_OF_RECORD_THREADS the ONE thread set, and REVIEW_OF_RECORD_LOCATION its words
* unexplainedPathsBetween the pure-regeneration test a carried record re-runs, prose arm included
* isOutsideReviewSurface the prose faces a head may move on and keep its record
* contractReviewTemplateLines / contractReviewRecordLines what `--template` prints
* contractReviewBriefLines what `--brief-template` prints — the brief a seat hands its reviewer
* readMailboxLine / mailboxEvents / MAILBOX_KEYS the mailbox DOORBELL — `To: <seat>`, then one of the seven keys a `pm:mailbox` comment may carry, read; anything else refused
*
* Every definition below was MOVED, names unchanged, out of
* `check-clause2-carriers.mjs` at the ruling's last step, which deleted the
* rest of that file — its `--pair` sweep, its C1–C9 rows, its claim readers,
* its local copy of the retired label and the self-test battery for them. The
* docblocks moved with the code, and so did the self-test cases that pin these
* readers. Where a docblock names a retired row (C3, C4, C6, C7) or the
* `--pair` path, it is saying why a reading has the shape it has; ⛔ it is not
* saying the row still exists.
*
* ## ⚠️ Import it LAZILY, from a function body, and never at module scope
*
* This file imports `check-half-states.mjs`, which resolves its governed
* register at MODULE SCOPE with a top-level await that imports
* `check-governed-queue-guard.mjs`. So the guard reaching this file with a
* module-scope import closes a module-evaluation cycle and deadlocks both
* (node exits 13, "Detected unsettled top-level await"). The guard's
* `REVIEW_OF_RECORD_LOCATION` and `loadRecordRecognisers` docblocks carry the
* measurement and the rule: the import is taken lazily, after the guard has
* finished evaluating. ⛔ Nothing here may add a top-level `await` either.
*
* ## Where these readings are tested
*
* Twice, from both ends. This file's own `--self-test` (`pnpm
* check:pm-record-recognisers`, run by `lint.yml`) pins each reader offline and
* drives the queue guard once with the record `--template` prints, on each
* thread. The guard's `--self-test`, which the required `Governed Surface Queue
* Guard` check runs first, loads this file through the real lazy import and
* drives every state the queue acts on.
*
* ⛔ Nothing here reads a board, writes, or hangs a label. Rows, a head and an
* injected git reader in; a reading out. The verdict on top of it — which tier,
* which exit — is the guard's.
*/
// The self-test's reads of GOVERNED files, declared so a card editing either
// file derives this family (`dispatch-gates.mjs` `declaredSelfTestReads`; the
// row is `GOVERNED_READ_FLOOR` in `dispatch-gates.data.mjs`). The derivation
// grades it against the read the self-test really performs, so it cannot be
// satisfied by deleting either half.
// dispatch-gates: self-test-reads .claude/skills/pm-dispatch/references/project-forms.md .claude/skills/pm-dispatch/references/contract-review.md -- the mailbox doorbell battery pins each of the seven key templates verbatim in project-forms.md's 〈信箱 PR〉 section, the claim-line battery pins the `Contract-review-claim:` template and its lapse hours in contract-review.md, and the hold-line battery pins the `Contract-review-hold:` template and its listing hours there, so a change to any of those spellings is judged here
import process from 'node:process';
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { isEntrypoint } from '../invoked-as.mjs';
import {
CONTRACT_REVIEW_HEADING_MARKER,
H51_SHA_MIN_HEX,
branchNameTarget,
closingKeywordTargets,
contractReviewHeadMatch,
deliveryEvidence,
deliveryEvidenceNote,
latestMarkedComment,
partOfTargets,
readSignatureLine,
SEAT_SIGNATURE_SESSION_SOURCE,
stripSignatureLine,
} from './check-half-states.mjs';
// The tier `isModelIdentifierToken` refuses by VALUE. IMPORTED, never restated:
// `dispatch-gates.mjs` is the one line in `scripts/pm/**` where the model id is
// spelled as a value, and a second value site here is the drift that let a
// declared tier and a served one differ unnoticed (#17915).
// The default tier's VALUE is imported on the same rule, for the same refusal; its NAME is the second
// token a `Served-tier:` line may carry, on the face that maps to it. The published-schema face is the
// clause-② suspect surface (`SUSPECT_TIER_GLOBS`, test files excepted), applied by `deriveTier`, the one
// function that applies it — ⛔ never a second spelling of `packages/spec/src/**` here.
import {
CONTRACT_REVIEW_TIER,
CONTRACT_REVIEW_TIER_NAME,
SUSPECT_TIER_GLOBS,
TIER_DEFAULT,
TIER_DEFAULT_NAME,
deriveTier,
} from './dispatch-gates.mjs';
// The governed-rules face is the governed register itself — the same function the queue guard
// classifies a merge group's paths with. `dispatch-gates.mjs` already imports this module at module
// scope, so the edge adds no new module to this file's graph and no cycle.
import { SELF_REPO_ID, governedPathsIn } from './check-governed-merges.mjs';
// How an unreadable `Served-tier:` line is quoted back — the declaration
// line's own quoting helper, one spelling for both. The narrowing face is read
// with the fleet's ONE reader of that line, imported, ⛔ never a second parser.
import { quoteLine, readClause2Line } from './clause2-line.mjs';
// A mailbox message's `To:` line names a SEAT, spelled as the mailbox opener spells a seat — its
// `seatKey`, imported, ⛔ never a second seat shape. That file imports nothing of this graph's
// top-level-await half (only the relay validator and `gh-pages.mjs`), so the edge adds no cycle.
import { seatKey } from './mailbox-open.mjs';
// ── the tier FOLLOWS THE FACE that made the review owed ─────────────────────
//
// Ruling record 6159870311 on #23352 (letter B′ with C, maintainer 「同意」):
// whether an isolated contract review is OWED stays by surface — the three
// contract faces of `references/contract-review.md` — and ⛔ never by lane; the
// TIER of that review follows the face that made it owed. A published schema or
// governed rules text maps to `CONTRACT_REVIEW_TIER`; a review owed ONLY by a
// `Clause-②: yes` declaration (a widening in application or UI code, a
// translation key, a version declaration) maps to `TIER_DEFAULT`, run as the
// lane seat's review of record. Nothing retires: the contract-review tier's
// identity and value are untouched, and `dispatch-gates.data.mjs` stays the
// default tier's value site.
//
// ⛔ EXACT, never a floor. `servedTierStands` accepts the one NAME the face maps
// to and nothing else: this regime orders no tiers (`deriveTier` refuses to
// rank two either), so "at least this tier" is a reading no file here can make.
//
// ⭐ The FOURTH face (ruling record 6203713500 on #23692, letter B, maintainer
// 「B (推荐)」): ruling C (6053791774) stands as a face of its own under B′ — a
// `Clause-②: no` card that NARROWS a published accept set owes one isolated
// review at `CONTRACT_REVIEW_TIER`. The face is keyed on the one spelling
// `Clause-②: no (narrowing)`, written at the start of a line in the PR body and
// the changeset, and it is exact like the other three: a `TIER_DEFAULT` record
// does not stand on it. Records written at `TIER_DEFAULT` on narrowing-only pull
// requests before this face existed are not re-opened (the ruling's item 3).
/**
* The four contract faces, in the order a mixed diff is decided in, each with
* the NAME of the tier it maps to.
*
* `id` the token `--template --face` takes and `reviewFace` answers with
* `tierName` the ONE `Served-tier:` token a review owed on this face stands with
* `fullReview` whether a record on this face carries item ④, the design judgment. The project
* owner's order, transcribed on #25765 (2026-10-25, scope and cadence refined in
* ruling record 6396446237), makes the at-tier review of a published schema, a skill
* or an ADR a FULL review: ①②③ plus a judgment of the change against the code it
* cites and the scenario it is accepted against. Those three surfaces ARE the schema
* face and the rules face already — the governed register names `skills/**`,
* `.claude/**` and `docs/adr/**` — so ④ rides those two faces and no face is added.
* The maintainer's later ruling (record 6442046166, letter A) hangs ④ on the narrowing
* face too: a narrowing of a published accept set in runtime code alone is judged against
* the spec on `main` — does it take a declared capability away at the consumer, or make
* the spec's own refusal real? Only the declaration face, the lane seat's own review,
* carries no ④. `recordCarriesDesignJudgment` reads it.
* `words` how the face is named to a human
*
* ⭐ The face is read off the PULL REQUEST'S COMMITTED TREE, and ⛔ never off a
* seat's statement: its FILE LIST decides the schema and rules faces, the way
* the queue guard already classifies governed paths; the `Clause-②:` line its
* committed changeset carries decides the narrowing face, read by
* `readClause2Line` (`clause2-line.mjs`, the fleet's one reader of that line).
* The declaration face is what REMAINS: it is asked only of a review already
* owed, and a review owed with no schema, no governed path and no narrowing
* declared was owed by the `Clause-②: yes` line alone.
*/
export const REVIEW_FACES = Object.freeze([
Object.freeze({ id: 'schema', tierName: CONTRACT_REVIEW_TIER_NAME, fullReview: true, words: 'a published schema (the clause-② suspect surface, test files excepted)' }),
Object.freeze({ id: 'rules', tierName: CONTRACT_REVIEW_TIER_NAME, fullReview: true, words: 'governed rules text (a path the governed register names)' }),
Object.freeze({ id: 'narrowing', tierName: CONTRACT_REVIEW_TIER_NAME, fullReview: true, words: 'a `Clause-②: no (narrowing)` declaration (a published accept set narrowed; no schema and no governed path in the diff)' }),
Object.freeze({ id: 'declaration', tierName: TIER_DEFAULT_NAME, fullReview: false, words: 'the `Clause-②: yes` declaration alone (no schema, no governed path and no narrowing declared)' }),
]);
/** Every NAME a `Served-tier:` line can stand with — one per tier the faces map to, and nothing else. */
export const REVIEW_TIER_NAMES = Object.freeze([...new Set(REVIEW_FACES.map((face) => face.tierName))]);
/**
* Is this path a CHANGESET — the committed carrier of the `Clause-②:` line? A
* `.changeset/*.md` file other than the directory's own README. Pure.
*/
function isChangesetPath(path) {
const p = String(path ?? '');
return /^\.changeset\/[^/]+\.md$/.test(p) && p !== '.changeset/README.md';
}
/**
* Which face made this review owed, and the NAME of the tier it is therefore
* served at. Pure over its inputs.
*
* ⭐ A mixed diff maps to `CONTRACT_REVIEW_TIER` on ONE hit: a schema or governed
* path anywhere in the list decides it, the way one governed path governs the
* whole pull request. `hits` names the paths that decided, so a reader can see
* why — and, since ruling record 6184805932 on #23578 (letter C), it is also the
* SCOPE FLOOR of that review: `reviewScopeHits` below. A path-decided reading
* never consults `declaredOn`: every face after `rules` maps to a tier the paths
* already decided or to a cheaper one, so the declaration cannot move it.
*
* ⭐ Where the paths decide nothing, the DECLARATION decides (ruling record
* 6203713500, letter B), read out of `declaredOn` — the texts the `Clause-②:`
* line is written on: each committed changeset's text, and the PR body's where
* the caller holds it. A `narrowing` arm on ANY of them ⇒ the narrowing face
* (`yes (narrowing)` included: a diff that widens and narrows owes the narrowing
* face's review, as a mixed diff owes its one hit's); else a `malformed` line on
* any ⇒ UNREADABLE, because `readClause2Line` collapses a near-miss arm such as
* `(narrowed)` into `malformed` exactly so that it cannot read as no narrowing;
* else the declaration face.
*
* ⛔ A caller that hands NO declaration cannot say which of the two it is on, and
* gets the reading the committed tree still allows. A tree with a changeset in
* it carries a declaration carrier nobody read: UNREADABLE, ⛔ never the
* cheaper tier — the queue guard's rule for a pair with no path list, one level
* down. A tree with NO changeset carries no narrowing declaration at all — a
* narrowing of a published accept set moves a published package, and that
* ships a changeset — so the declaration face stands there exactly as before.
* UNREADABLE answers `face: null` and `tierName: null`, which `servedTierStands`
* stands nothing on, and a `reason`.
*
* `repo` selects the governed register's rows, as `governedPathsIn` requires;
* this file runs in `objectstack-ai/objectstack`, so that is the default.
*
* @param {string[]} paths the pull request's changed paths (its committed tree)
* @param {{ declaredOn?: string[] }} [declaration] the texts its `Clause-②:` line is read from
* @returns {{ face: 'schema'|'rules'|'narrowing'|'declaration', tierName: string, words: string, hits: { schema: string[], rules: string[] } }
* | { face: null, tierName: null, words: string, hits: { schema: string[], rules: string[] }, reason: string }}
*/
export function reviewFace(paths, repo = SELF_REPO_ID, { declaredOn } = {}) {
const list = (Array.isArray(paths) ? paths : []).filter((p) => typeof p === 'string' && p !== '');
// ⭐ No mandate rows are passed: the question is the SUSPECT surface alone, and
// an empty mandate table cannot make `deriveTier` throw on an ambiguity.
const schema = [...new Set(deriveTier(list, [], SUSPECT_TIER_GLOBS).suspects.map((s) => s.path))];
const rules = governedPathsIn(list, repo).flatMap((surface) => surface.files);
const hits = { schema, rules };
const unreadable = (reason) => ({ face: null, tierName: null, words: 'no face — UNREADABLE', hits, reason });
// ⛔ A face this table does not hold reads UNREADABLE, never a neighbouring face.
const named = (id) => {
const face = reviewFaceById(id);
return face === null ? unreadable(`REVIEW_FACES holds no \`${id}\` face`) : { face: face.id, tierName: face.tierName, words: face.words, hits };
};
if (schema.length > 0) return named('schema');
if (rules.length > 0) return named('rules');
const texts = (Array.isArray(declaredOn) ? declaredOn : []).filter((text) => typeof text === 'string');
if (texts.length === 0) {
const carrier = list.find(isChangesetPath);
return carrier === undefined
? named('declaration')
: unreadable(
`the paths decide no face and the committed tree carries ${carrier}, whose \`Clause-②:\` line decides between ` +
'the narrowing face and the declaration face, but no declaration was handed to read it',
);
}
const readings = texts.map((text) => readClause2Line(text));
if (readings.some((r) => r?.kind === 'declared' && r.arm === 'narrowing')) return named('narrowing');
const malformed = readings.find((r) => r?.kind === 'malformed');
if (malformed !== undefined) {
return unreadable(`a \`Clause-②:\` line reads malformed (${malformed.line}), so whether it declares a narrowing is unknown`);
}
return named('declaration');
}
/** The face a `--face` argument names, or null — the CLI's half of the same table. */
export function reviewFaceById(id) {
return REVIEW_FACES.find((face) => face.id === id) ?? null;
}
/**
* Does the record printed for this face carry item ④, the design judgment? Read off the face
* table's `fullReview` flag, ⛔ never a second list of faces. A null face is the bare template —
* the tier of a schema or governed-path face — so it does; below tier nothing does. Pure.
*/
export function recordCarriesDesignJudgment(face, tierName) {
return tierName === CONTRACT_REVIEW_TIER_NAME && (face === null || face.fullReview === true);
}
/**
* The SCOPE FLOOR of the at-tier review: every path `reviewFace` returns as
* `hits`, schema hits first, each once. Pure over the path list.
*
* Ruling record 6184805932 on #23578 (letter C, maintainer 「同意」): the TIER
* stays the one the face maps to, but the at-tier review of a mixed diff covers
* these paths plus every file their hunks make a claim about (a rule and the
* gate that enforces it are one change, read as one); the rest is the lane
* seat's ACCEPT at `TIER_DEFAULT`, exactly as a standalone pull request of those
* files. The record's `Scope:` line lists both halves, and may widen, ⛔ never
* narrow below this list. Tier H approval and the queue guard stay whole-PR:
* nothing here is read by the guard.
*
* ⭐ Read off `reviewFace`, never a second classification: the same function the
* queue guard decides the face with, so the floor cannot name a path the face
* did not count, nor miss one it did. Empty on every face the paths did not
* decide. ⭐ The narrowing face is at tier with NO path hit: its declaration is
* the pull request's own and names no path, so its floor is every path of the
* diff outside the prose faces — stated in the brief and on the `Scope:` line,
* which the reviewer fills, since no path list read here can single them out.
*
* @param {string[]} paths the pull request's changed paths (its committed tree)
* @returns {string[]}
*/
export function reviewScopeHits(paths, repo = SELF_REPO_ID) {
const { hits } = reviewFace(paths, repo);
return [...new Set([...hits.schema, ...hits.rules])];
}
// ── the pure-regeneration carry (maintainer 2026-09-20 「纯重生成提交不需要开达档复核记录」) ──
//
// A record binds to a head, so any push re-owes the review — a loop the reviewed
// seat cannot exit on a generated-artefact-dense surface: somebody else lands,
// baselines drift, the seat regenerates, the head moves, the record is owed
// again (four times in one round, two PASSed pull requests unlanded). The ruling
// narrows it: when the move is a PURE REGENERATION the record keeps pointing at
// the new head — the POINTER test replaced by the CONTENT test it stood for.
//
// ⛔ MACHINE-READ ON COMMITTED TREES, never a seat's statement, and the committed
// half is not stylistic: before `git add -A` one regeneration answers `git
// status`, `git diff --cached` and `git diff` three DIFFERENT ways, and the
// `--cached` reading is main's side, which looks exactly like the answer. ⭐ The
// `Regen-provenance:` line is a POINTER, NEVER the evidence: it names the record
// and the two commits so a later reader RE-RUNS the test, and a reader that
// cannot reach both answers with a GAP — UNJUDGED, ⛔ never clean.
//
// ⭐ The PROSE arm (ruling record 6159870311 on #23352, letter B′ with C): a head
// that moves ONLY on faces outside the review surface keeps the record too —
// the prose faces the ACCEPT reads sentence by sentence, never the reviewer.
// Decided exactly like the regeneration arm, on the two COMMITTED trees, and
// pointed at by the SAME `Regen-provenance:` line rather than a second one: the
// line is a pointer and never the evidence, so a second key would be a second
// grammar naming the same two commits, and the common move — a merge-forward
// that also fixes the changeset — is ONE hop that would otherwise need both.
/**
* The faces OUTSIDE the review surface — `references/contract-review.md`'s
* prose faces, which the ACCEPT reads sentence by sentence against the diff. A
* head move that touches only these (and generated artefacts, and main's
* carry-over) is no reason to re-review: nothing the reviewer judged moved.
*
* ⛔ An EXCLUSION table, named as one so the dispatch derivation reads it as a
* never-look-here list rather than as files this module opens (it opens none).
*
* `prefix` every path under this directory
* `basename` every file of this name, at any depth
*/
export const REVIEW_SURFACE_EXCLUDED_PROSE_FACES = Object.freeze([
Object.freeze({ id: 'changeset', prefix: '.changeset/' }),
Object.freeze({ id: 'changelog', basename: 'CHANGELOG.md' }),
Object.freeze({ id: 'docs-content', prefix: 'content/docs/' }),
Object.freeze({ id: 'docs-app', prefix: 'apps/docs/' }),
]);
/** Does this path lie on a prose face outside the review surface? Pure. */
export function isOutsideReviewSurface(path) {
const p = String(path ?? '');
return REVIEW_SURFACE_EXCLUDED_PROSE_FACES.some((face) =>
face.prefix !== undefined ? p.startsWith(face.prefix) : p === face.basename || p.endsWith(`/${face.basename}`),
);
}
/**
* One hop, as a seat posts it (the retired C3 row's remedy printed this shape):
* `Regen-provenance: RECORD-ID · OLD-HEAD → NEW-HEAD · COMMAND → (empty)`.
* Decoration is tolerated as `REVIEWED_BY_LINE` tolerates it — bullet, bold,
* backticked shas — since none of it changes which commits the line names; the
* tail after the second sha is the seat's own transcript and is deliberately
* UNREAD, because a reader re-runs its own command, never a pasted one.
*/
export const REGEN_PROVENANCE_LINE =
/^[\s>]*(?:[-*+]\s*)?\**\s*Regen-provenance\**\s*:\s*`?#?(\d+)`?\s*[·•]\s*`?([0-9a-fA-F]{7,40})`?\s*(?:→|->)\s*`?([0-9a-fA-F]{7,40})`?/;
/** Every hop the pair's threads carry, in thread order. ⛔ No head is judged here. */
export function regenProvenanceHops(pair) {
return REVIEW_OF_RECORD_THREADS.flatMap((t) => (Array.isArray(pair?.[t.rows]) ? pair[t.rows] : []))
.flatMap((row) => String(row?.body ?? '').split(/\r?\n/))
.map((line) => REGEN_PROVENANCE_LINE.exec(line))
.filter((m) => m !== null)
.map((m) => ({ record: Number(m[1]), from: m[2].toLowerCase(), to: m[3].toLowerCase() }));
}
/** Either sha abbreviates the other — a seat writes 7, the API writes 40. */
const shaMeets = (a, b) => a.startsWith(b) || b.startsWith(a);
/**
* The hops that chain BACK from this head, oldest first — `null` when none does.
* Several hops are ordinary: a PR is re-synced once per drift. ⛔ Two hops
* arriving at one head END the walk rather than being ranked, so a contradictory
* thread carries no chain — the only direction this may err in.
*/
export function regenChainToHead(pair) {
// ⭐ DE-DUPLICATED FIRST, on record + from + to. The reader searches BOTH
// carriers and the governed text trains the dual-carrier habit, so ONE hop
// posted on the PR and on its card arrives here twice — identical bytes, not
// ambiguity. Judged by the ambiguity test below it would END the walk and
// kill the carry in its most likely shape; two DIFFERENT hops into one head
// still do, which is the fact that test exists for.
const hops = [
...new Map(regenProvenanceHops(pair).map((h) => [`${h.record}\u0000${h.from}\u0000${h.to}`, h])).values(),
];
let target = String(pair?.headSha ?? '').toLowerCase();
if (target.length < H51_SHA_MIN_HEX) return null;
const chain = [];
const seen = new Set();
while (!seen.has(target)) {
seen.add(target);
const step = hops.filter((h) => shaMeets(h.to, target));
if (step.length !== 1) break;
chain.unshift(step[0]);
target = step[0].from;
}
return chain.length === 0 ? null : chain;
}
/**
* The ruled test on COMMITTED trees: which moved paths are explained by NONE of
* the arms of 「every touched path is a generated artefact OR THE MERGE COMMIT'S
* OWN CARRY-OVER FROM MAIN」, widened by the prose arm (a path on a face outside
* the review surface). Empty is the whole criterion.
*
* ⓪ the prose arm, `isOutsideReviewSurface`, read off the path alone: a moved
* prose path is explained whoever moved it, the pull request itself included —
* that is the whole of the exemption, and it is why this arm runs FIRST.
* ① the `merge=os-regen` attribute, read with `--source <to>` so
* `.gitattributes` itself comes out of that COMMIT rather than out of whatever
* the working tree holds. ② the carry-over arm: a path this pull request never
* touched AT EITHER HEAD moved only because `base` moved. ⛔ Without ② the
* exception never fires on the loop this card measured — a merge-forward lists
* every path main carried over, and a head-to-head diff reads them as hand-written.
*
* ⭐ The PR's OWN delta is read once per HEAD (`merge-base` + one name-only
* diff), never once per path: a path is byte-explained by `base` exactly when
* neither delta names it, which is the same verdict as comparing
* `git diff FROM TO -- p` with `git diff MB_FROM MB_TO -- p` per path, at four
* calls instead of two per path. The refusing direction is unchanged — a
* hand-resolved merge leaves its resolution in the delta at the NEW head, and a
* slipped-in edit in whichever delta carries it. `-z` throughout: a path may
* hold a space, a quote or a colon and the parse must not be the weak link.
*/
export function unexplainedPathsBetween(runGit, { from, to, base }) {
const names = (a, b) => String(runGit(['diff', '-z', '--name-only', a, b])).split('\0').filter((p) => p !== '');
const moved = names(from, to).filter((p) => !isOutsideReviewSurface(p));
if (moved.length === 0) return [];
const f = String(runGit(['check-attr', '--source', to, '-z', 'merge', '--stdin'], moved.join('\0'))).split('\0');
const hand = [];
for (let i = 0; i + 2 < f.length; i += 3) if (f[i + 2] !== 'os-regen') hand.push(f[i]);
if (hand.length === 0) return [];
const mergeBase = (rev) => String(runGit(['merge-base', base, rev])).trim();
const own = new Set([...names(mergeBase(from), from), ...names(mergeBase(to), to)]);
return hand.filter((p) => own.has(p));
}
const REGEN_CARRY_MEMO = new WeakMap();
/**
* Does a chain of certified pure regenerations carry the record to this head?
* Memoised per pair: a caller may ask more than once in one run, and two
* commits cannot change under one. ⛔ FOUR states, none foldable: `none` (no
* line — today's rule, unchanged), `refused` (a line that does NOT certify: an
* ordinary re-hang), `unreadable` (the environment could not answer), `carried`.
*
* @returns {{ state: 'none' } | { state: 'unreadable', gaps: string[] }
* | { state: 'refused', reason: string }
* | { state: 'carried', record: number, head: string, hops: number }}
*/
export function regenCarry(pair) {
if (pair === null || typeof pair !== 'object') return { state: 'none' };
if (!REGEN_CARRY_MEMO.has(pair)) REGEN_CARRY_MEMO.set(pair, computeRegenCarry(pair));
return REGEN_CARRY_MEMO.get(pair);
}
function computeRegenCarry(pair) {
const chain = regenChainToHead(pair);
if (chain === null) return { state: 'none' };
const records = [...new Set(chain.map((h) => h.record))];
if (records.length !== 1) {
return { state: 'refused', reason: `its \`Regen-provenance:\` hops name ${records.length} different records (${records.join(', ')}) and one chain carries ONE record` };
}
const runGit = pair?.runGit;
if (typeof runGit !== 'function') {
return { state: 'unreadable', gaps: [`PR #${pair?.pr}'s \`Regen-provenance:\` chain — this run holds no git reader, so the two committed trees were never compared`] };
}
// ⛔ The base ref is what separates 「what main brought」 from 「what the PR
// changed」, so a run that names none cannot answer at all — never clean.
const base = pair?.baseRef;
if (typeof base !== 'string' || base === '') {
return { state: 'unreadable', gaps: [`PR #${pair?.pr}'s base ref — this run names none, so the merge commit's own carry-over could not be told apart from a hand edit`] };
}
for (const hop of chain) {
const span = `${hop.from.slice(0, 10)}..${hop.to.slice(0, 10)}`;
let hand;
try {
hand = unexplainedPathsBetween(runGit, { from: hop.from, to: hop.to, base });
} catch (error) {
const why = String(error?.message ?? error).split('\n')[0];
return { state: 'unreadable', gaps: [`the committed trees ${span} against base \`${base}\` (${why}) — fetch both (\`git fetch origin pull/${pair?.pr}/head\`, \`git fetch origin ${hop.from}\`) and re-run`] };
}
if (hand.length > 0) {
return { state: 'refused', reason: `${span} moved ${hand.length} path(s) that lie on no prose face outside the review surface, carry no \`merge=os-regen\` attribute and are not what \`${base}\` brought (${hand.slice(0, 4).join(', ')}) — this pull request's own reviewed content moved, so it is neither a pure regeneration nor a prose-only move` };
}
}
// Expanded through git so the carried head is spelled at least as fully as
// the record spells it: the head-identity test is a PREFIX of the head, so an
// abbreviation SHORTER than the record's own span matches nothing.
let head = chain[0].from;
try {
head = String(runGit(['rev-parse', `${head}^{commit}`])).trim() || head;
} catch {
/* the diff already read both commits; an abbreviation is still usable */
}
return { state: 'carried', record: records[0], head, hops: chain.length };
}
/**
* A machine key line, in this file's ONE convention: the key is literal and
* case-sensitive, the decoration a seat writes without meaning anything by it
* (a leading blockquote, a list bullet, backtick or bold wrapping on the key
* and its colon) is tolerated, and the rest of the line is the raw value.
*
* Factored out rather than copied so a second key added later cannot arrive
* with a second convention -- the drift this file refuses one family over.
*/
function keyLineRegex(key) {
return new RegExp(`^[ \\t]*(?:>[ \\t]*)?(?:[-*][ \\t]+)?(?:\\*\\*)?\`?${key}\`?(?:\\*\\*)?[ \\t]*:(.*)$`);
}
/**
* The markdown decoration a VALUE may open with — stripped, in any order and
* any repetition, before the value's token is read. Written for the two
* authorship tokens of the retired C4 row; here it runs before `TIER_TOKEN`.
*
* ⭐ Measured, and the fix for a genuine asymmetry (#17346). The key regexes
* tolerate `**Implemented-by:**` — bold wrapping the key AND its colon — which
* is what every 2026-09-09 specimen writes. But the colon inside the bold means
* the captured VALUE opens with the closing `**`, and the old token regexes
* admitted a leading `**` only when a backtick or the token followed it with no
* space between: on `- **Implemented-by:** \`claude/issue-x\`` the value read
* `"** \`claude/issue-x\`"` and BOTH tokens answered `null`. So the key was
* recognised, the value was not, and the pair read `malformed` on a comment
* whose author had written a perfectly good identity — a false positive
* produced by the reader, which is a different fact from the corpus's own
* prose values and is fixed HERE rather than tolerated downstream.
*
* ⛔ It strips DECORATION only — spaces, `**`, backticks — never a word. The
* near misses the ruling turns on are untouched: `branch \`claude/…\``,
* `the dev on claude/…` and the corpus's `isolated <model> subagent` all stop
* the strip at their first letter, so the token is still required to be the
* FIRST thing after the colon and its decoration.
*/
const VALUE_DECORATION = /^(?:[ \t]+|\*\*|`)+/;
function stripValueDecoration(raw) {
return String(raw ?? '').replace(VALUE_DECORATION, '');
}
/**
* The `Reviewed-by:` key line, in `keyLineRegex`'s one convention — the regex the
* retired C4 row read it with, built the same way, so a record that row accepted
* still reads as SIGNED here. Its value is not judged: the record names a
* reviewer, and who that is stays human.
*/
export const REVIEWED_BY_LINE = keyLineRegex('Reviewed-by');
/**
* The `Served-tier:` key line -- the THIRD provenance fact a verdict declares
* about itself, read with `Reviewed-by:`'s own discipline (#17915).
*
* ⭐ A fact about what PRODUCED the verdict, never the verdict. `Reviewed-by:`
* says WHO rendered it; this says WHAT SERVED the round that rendered it. The
* READING behind it is the harness-stamped served-model field of the reviewer's
* own transcript, ⛔ never the dispatch `model` parameter, which is
* CONFIGURATION and not a reading -- that distinction is the whole defect: a
* passed parameter and a served tier can differ, and until this row nothing in
* the tree compared them, so a round served below tier cleared a carrier
* indistinguishably from one served at it.
*
* ⛔ But the reading stays in the transcript and the LINE carries only the
* constant's NAME -- 「值写常量名 `CONTRACT_REVIEW_TIER`」 -- because a record is
* a GitHub comment and `AGENTS.md` lets no model identifier land in one
* (#18060). See `CONTRACT_REVIEW_TIER_NAME` for why that costs no evidence.
*
* ⛔ The key is read ANYWHERE in the comment, on its own line. The rule text
* asks the author to put it FIRST (「同形含首行 `Served-tier:`」) because a
* reader should not have to hunt for it; a reader that REFUSED it below some
* line number would be rejecting correct records over decoration, which is the
* false-positive direction this file spends its self-test avoiding.
*/
const SERVED_TIER_LINE = keyLineRegex('Served-tier');
/**
* The value token -- an opaque tier identifier.
*
* ⭐ Closed on an alphanumeric or a `]`, so a real id keeps its whole shape
* (a bracketed context suffix included) while a trailing `.` or `,` stays with
* the prose. What a seat writes AFTER the token is its argument, which this
* file does not read -- so a value that opens with prose reads as that prose
* and compares unequal, loudly, rather than being scanned for a model name
* somewhere in the sentence. ⚠️ That looseness is precisely the false-positive
* mode measured on the hand-rolled probes this row replaces: a bare model-name
* token matched inside a QUOTED prior record, and a correct verdict came one
* grep away from being voided.
*/
const TIER_TOKEN = /^([A-Za-z0-9](?:[A-Za-z0-9._:[\]-]*[A-Za-z0-9\]])?)/;
/**
* The STAMP CONTROL that may precede the tier -- `N/M`, measured on the live
* corpus and named by the ruling itself.
*
* ⭐ Corrected from a fixture against the board, which is the correction this
* family has had to make before (#17346: the corpus moved and the discriminator
* did not). Every record the remediation rounds write spells the value
* `75/75 \`<tier>\`` -- the at-tier stamp count over the total, THEN the tier --
* and the ruling's own specimen is written the same way. A reader that demanded
* the tier token immediately after the colon would have refused every verdict
* produced under the rule it enforces, on its first day.
*
* ⛔ And the count is not decoration to be skipped: it IS the zero-hit control
* the discipline requires -- a stamp reading is void unless the same probe
* returned a non-zero count on the same transcript -- and a count that is not
* FULL is the 「回退证据」 whose own rule text voids the verdict entire. So it
* is read, and it is judged: absent, the tier alone decides (the ruling's
* minimum, and nothing the ruling permits is refused); present, it must be
* non-zero and total.
*/
const STAMP_CONTROL = /^(\d+)[ \t]*\/[ \t]*(\d+)(?![\d/])/;
/**
* Does a declared stamp control STAND? Absent is vacuous; present must be
* total and non-zero. One predicate, so the row and the note cannot disagree.
*/
export function servedStampsHold(stamps) {
return stamps === null || (stamps.total > 0 && stamps.atTier === stamps.total);
}
/**
* The token a `Served-tier:` line may carry -- a tier constant's NAME, ⛔ never
* its VALUE (#18060); ONE name per face, the one `reviewFace` maps it to.
*
* ⭐ `AGENTS.md` is unqualified about the surface: 「no model identifier lands in
* a PR title or body, a comment, a changeset, a doc or a code comment」 -- and a
* review of record IS a comment. The first spelling of this row compared the
* token to the constant's VALUE, so a record could clear a carrier ONLY by
* carrying a model identifier into the very artifact that rule names; the gate
* would have cemented the violation rather than a habit. The NAME is governed
* text, carries the same fact, and lands no identifier.
*
* ⭐ Nothing evidential is lost, and that is why this needed no ruling to trade
* away: the line was never the reading. 「⛔ 自述档位与传参皆非读数」 -- the
* reading is the seat's transcript grep against the constant's value, which
* produces no repository artifact at all. What the line carries is the
* DECLARATION plus its `N/N` stamp control, and both survive the rename.
*
* ⛔ Still EXACT: one accepted token per face, no family and no prefix floor.
*
* Both names are declared beside the constants they name, in
* `dispatch-gates.mjs`, and RE-EXPORTED here: the claim reader there compares a
* claim's `model:` value against the same token, and two spellings of one name
* in two files is the drift this file refuses one family over.
*/
export { CONTRACT_REVIEW_TIER_NAME, TIER_DEFAULT_NAME };
/**
* The id form of a model name -- the word claude, a hyphen, a model word.
*
* A SHAPE and not a list, so a model nobody has named yet binds for the same
* reason the shipped ones do -- the same rule `check-commit-card-trailers.mjs`
* binds over a trailer value, spelled here rather than imported because that
* file is the pre-push entrypoint and this one is imported by the merge-queue
* guard. The battery pins the two together through the constant's own value.
*/
const MODEL_IDENTIFIER_FORM = /\bclaude-[a-z]+(?:[-.][a-z0-9]+)*\b/i;
/**
* Is this token a model identifier -- the thing `AGENTS.md` keeps out of a
* comment?
*
* Two limbs: the VALUE of each tier a record may stand at -- the contract-review
* tier's, which is the token this row used to REQUIRE (so a record written
* correctly under the old rule is named for what it is, never read as an
* ordinary off-tier miss), and the default tier's, the value a seat writing the
* declaration face's record reaches for in place of its NAME -- and the id SHAPE.
*
* ⛔ A caller must NEVER echo a token this returns true for: quoting it back
* would put the identifier straight into the artifact the rule is about, which
* is how a refusal becomes a second violation.
*/
export function isModelIdentifierToken(value) {
const text = String(value ?? '');
return text === CONTRACT_REVIEW_TIER || text === TIER_DEFAULT || MODEL_IDENTIFIER_FORM.test(text);
}
/**
* The whole reading, as one verdict: at the tier the FACE maps to, on a control
* that stands.
*
* `tierName` is the NAME `reviewFace` answered for the pull request the record
* sits on; it defaults to `CONTRACT_REVIEW_TIER_NAME`, the tier both path-read
* faces map to and the only one a governed pull request can owe. ⛔ EXACT: a
* record naming the other tier does not stand on this face, in either
* direction, and a `tierName` that is not one of `REVIEW_TIER_NAMES` stands
* NOTHING -- a caller that lost the face fails closed, never open.
*/
export function servedTierStands(served, tierName = CONTRACT_REVIEW_TIER_NAME) {
return (
REVIEW_TIER_NAMES.includes(tierName) &&
served?.state === 'read' &&
served.value === tierName &&
servedStampsHold(served.stamps)
);
}
/**
* What one comment declares about the tier that served it.
*
* @returns {{ state: 'missing', stamps: null }
* | { state: 'unreadable', line: string, stamps: object|null }
* | { state: 'read', value: string, stamps: object|null }}
*
* Every shape carries `stamps`, so a caller never has to test for the key.
*
* `stamps` is the `N/M` control when the value carried one, `null` when it did
* not -- read here, judged by `servedStampsHold`, so the reading and the
* verdict stay two steps.
*
* Three-valued for the reason the retired authorship reader was four-valued: a carrier
* that was never started and one that was started and left unreadable are
* different facts about the seat that wrote it, and they earn different
* remedies. Both are refusals -- neither is a reading equal to the constant.
*/
export function readServedTier(text) {
for (const line of String(text ?? '').split(/\r?\n/)) {
const m = SERVED_TIER_LINE.exec(line);
if (!m) continue;
let rest = stripValueDecoration(m[1]);
let stamps = null;
const control = STAMP_CONTROL.exec(rest);
if (control) {
stamps = { atTier: Number(control[1]), total: Number(control[2]) };
rest = stripValueDecoration(rest.slice(control[0].length));
}
const token = TIER_TOKEN.exec(rest);
return token
? { state: 'read', value: token[1], stamps }
: { state: 'unreadable', line: quoteLine(line), stamps };
}
return { state: 'missing', stamps: null };
}
/**
* The `Local-runs:` key line -- the FOURTH provenance fact a verdict declares
* about itself: whether the round that rendered it ran anything locally.
*
* ⭐ The rule it makes visible is the review's read-only shape (the skill's
* contract-review reference: only the diff and the card are read, the check
* conclusions come from the head's check-runs, and the derived gate families
* are ⛔ never re-run locally). Measured on one shift: hand-written briefs
* told reviewers to open worktrees and re-run pins, ablations and type checks,
* at 250k to 430k tokens per review, and no line on any record showed it. The
* line carries `none` -- the shape held -- or `probe — REASON`, naming the ONE
* local run the rule was broken for and why; a probe with no reason names no
* deviation and is unreadable.
*
* ⛔ ABSENT IS NOT RE-JUDGED. Records written before this line existed carry no
* line, and they are landed records: a reader that refused them would re-open
* three PASS verdicts over a line nobody had been asked to write. So `missing`
* STANDS, `read` stands, and only a line that is present and cannot be graded
* refuses -- the one direction in which a new line can be added to a record
* without re-judging the corpus.
*
* ⛔ The key is read anywhere in the comment, on its own line, for the reason
* `Served-tier:` is: refusing a correct record over its position is the
* false-positive direction.
*/
const LOCAL_RUNS_LINE = keyLineRegex('Local-runs');
/** `probe`, a separator (an em dash, a hyphen pair, a hyphen or a colon), then the reason -- which must be there. */
const LOCAL_RUNS_PROBE = /^probe\b[ \t]*(?:—|--|-|:)?[ \t]*(.*)$/i;
/**
* What one comment declares about its local runs.
*
* @returns {{ state: 'missing' }
* | { state: 'unreadable', line: string }
* | { state: 'read', value: 'none', reason: null }
* | { state: 'read', value: 'probe', reason: string }}
*/
export function readLocalRuns(text) {
for (const line of String(text ?? '').split(/\r?\n/)) {
const m = LOCAL_RUNS_LINE.exec(line);
if (!m) continue;
const rest = stripValueDecoration(m[1]).replace(/(?:[ \t]|\*\*|`)+$/, '');
if (/^none$/i.test(rest)) return { state: 'read', value: 'none', reason: null };
const probe = LOCAL_RUNS_PROBE.exec(rest);
if (probe && probe[1].trim().length > 0) return { state: 'read', value: 'probe', reason: probe[1].trim() };
return { state: 'unreadable', line: quoteLine(line) };
}
return { state: 'missing' };
}
/** Does the `Local-runs:` reading STAND? Missing stands (not re-judged); read stands; unreadable does not. */
export function localRunsStand(reading) {
return reading?.state === 'missing' || reading?.state === 'read';
}
/**
* The `Contract-review-handoff:` key line -- the ONE way a dispatching seat
* hands its contract review to the triage seat, read with `Reviewed-by:`'s own
* key discipline.
*
* ⭐ The rule it makes machine-findable (the skill's contract-review reference,
* 〈复核归属与资格〉, and the triage duties' round step): the seat that
* dispatched the work runs the review at the contract-review tier. ONLY when
* that tier's call is quota-refused does the seat hand the review over -- it
* never reviews at a lower tier -- and the hand-off is one PR comment carrying
* this line beside the existing `needs:contract-review` label:
*
* Contract-review-handoff: triage — CONTRACT_REVIEW_TIER unavailable (HTTP 429, 2026-10-27T13:00Z) · head 1b03a9c3
*
* Three facts, each required: the TARGET (`triage`, the closed set of one), the
* TIER that was unavailable -- the constant's NAME, exactly as `Served-tier:`
* spells it, ⛔ never a model id -- with its reason and UTC time in the
* parentheses, and the HEAD the hand-off is for, 7 to 40 hex. A line missing
* any of them is started-and-unreadable: a hand-off nobody can date, or one
* that names no head, is the ambiguity this line exists to remove.
*
* ⛔ No gate reads it. The queue guard keeps reading the ONE `## Contract
* review` record; this line decides only WHO renders that record, and the
* triage seat's record is the same shape, `Reviewed-by:` naming the triage
* seat. `contractReviewHandoff` below is the reading a seat or patrol takes.
*/
export const CONTRACT_REVIEW_HANDOFF_KEY = 'Contract-review-handoff';
const CONTRACT_REVIEW_HANDOFF_LINE = keyLineRegex(CONTRACT_REVIEW_HANDOFF_KEY);
/** The same key as a MARKER over a whole comment body -- `latestMarkedComment`'s convention (multiline, `g`-less). */
const CONTRACT_REVIEW_HANDOFF_MARKER = new RegExp(CONTRACT_REVIEW_HANDOFF_LINE.source, 'm');
/** `triage`, a separator (an em dash, a hyphen pair, a hyphen or a colon), then the rest. */
const HANDOFF_TARGET = /^triage\b[ \t]*(?:—|--|-|:)?[ \t]*(.*)$/i;
/** `(reason, UTC time)` then ` · head SHA` -- the time is the LAST comma-separated item in the parentheses. */
const HANDOFF_TAIL = /^\(([^()]*?)[ \t]*,[ \t]*([^,()]+)\)[ \t]*·[ \t]*head[ \t]+`?([0-9a-fA-F]{7,40})`?[ \t]*$/;
/**
* What one comment declares as a hand-off of its contract review.
*
* @returns {{ state: 'missing' }
* | { state: 'unreadable', line: string }
* | { state: 'read', to: 'triage', tier: string, reason: string, at: string, head: string }}
*/
export function readContractReviewHandoff(text) {
for (const line of String(text ?? '').split(/\r?\n/)) {
const m = CONTRACT_REVIEW_HANDOFF_LINE.exec(line);
if (!m) continue;
const unreadable = { state: 'unreadable', line: quoteLine(line) };
const target = HANDOFF_TARGET.exec(stripValueDecoration(m[1]).replace(/(?:[ \t]|\*\*|`)+$/, ''));
if (!target) return unreadable;
// The tier is read by NAME, through the one token reader `Served-tier:` uses, so a model id
// written here is refused for the same reason it is refused there.
const named = stripValueDecoration(target[1]);
const tier = TIER_TOKEN.exec(named);
if (!tier || tier[1] !== CONTRACT_REVIEW_TIER_NAME) return unreadable;
const rest = stripValueDecoration(named.slice(tier[0].length));
const tail = /^unavailable\b[ \t]*(.*)$/i.exec(rest);
const parts = tail ? HANDOFF_TAIL.exec(tail[1].trim()) : null;
if (!parts || parts[1].trim() === '') return unreadable;
return { state: 'read', to: 'triage', tier: tier[1], reason: parts[1].trim(), at: parts[2].trim(), head: parts[3] };
}
return { state: 'missing' };
}
/**
* Whose review this pull request's contract review is, read off its comment thread:
*
* absent no hand-off line on any comment -- the dispatching seat's own review; a
* `needs:contract-review` label alone changes nothing here, and triage does not touch it
* triage the NEWEST hand-off line names the current head -- the triage seat renders the record
* stale the newest hand-off line names an earlier head -- the head moved past the hand-off, so
* it needs a fresh line or the seat's own review; triage does not act on it
* unreadable the thread or the head could not be read, or the newest hand-off line cannot be graded
*
* Newest governs, chosen by `latestMarkedComment` -- the one resolution this file's locator uses --
* and the head is matched by PREFIX, as `contractReviewHeadMatch` matches a record's span, so the
* abbreviated and the full spelling answer alike.
*
* @param {{ id?: number, body?: string, created_at?: string }[]} rows the PR's comment rows
* @param {string} headSha the pull request's current head
*/
export function contractReviewHandoff(rows, headSha) {
const gaps = [];
if (!Array.isArray(rows)) gaps.push("the pull request's comment thread");
const head = String(headSha ?? '').toLowerCase();
if (head.length < H51_SHA_MIN_HEX) gaps.push("the pull request's head sha");
if (gaps.length > 0) return { state: 'unreadable', gaps };
const newest = latestMarkedComment(rows, CONTRACT_REVIEW_HANDOFF_MARKER);
if (!newest) return { state: 'absent', read: rows.length };
const row = rows[newest.index];
const line = readContractReviewHandoff(row?.body);
const stamp = { id: row?.id ?? null, at: row?.created_at ?? null };
if (line.state !== 'read') return { state: 'unreadable', gaps: [`the newest hand-off line (comment ${stamp.id ?? '?'}) cannot be read: ${line.line ?? 'no line'}`], ...stamp };
// PREFIX either way, as `regenChainToHead` meets two spellings of one commit: the line may abbreviate the head.
const current = shaMeets(head, line.head.toLowerCase());
return { state: current ? 'triage' : 'stale', head: line.head, reason: line.reason, handedAt: line.at, ...stamp };
}
// ---------------------------------------------------------------------------
// The `Contract-review-claim:` line — one per head, so two reviewers never start on one
// ---------------------------------------------------------------------------
/**
* The `Contract-review-claim:` key line -- who has STARTED the contract review
* of one head, posted by that reviewer before it starts, lane seat or triage.
*
* ⭐ The rule it makes machine-findable (the skill's contract-review reference,
* 〈复核归属与资格〉): the lane reviews its own; the triage seat takes a review
* only when nobody is doing it. Before starting, every reviewer reads the PR:
* a record or a LIVE claim on the current head means do not start. Otherwise it
* posts ONE comment carrying this line first, then reviews:
*
* Contract-review-claim: session_01AavokzJ5DndAwitDXvKy4U · head 3beee64fe77741d07f035f1b80eeaa07e7280ab4 · 2026-10-28T12:18Z
*
* Three facts, each required, separated by the doorbell's dot: the SESSION that
* reviews (the signature line's session shape, `SEAT_SIGNATURE_SESSION_SOURCE`,
* imported, ⛔ never a second spelling), the head as the FULL 40-hex sha --
* the rule says full, because a claim is compared against a head that may move
* to a sibling sharing a short prefix -- and the UTC time to the minute (seconds
* allowed). Backtick wrapping on any value reads; a line missing a fact, or
* with a fourth part, is started-and-unreadable, and an unreadable claim is NO
* claim: it holds no head.
*
* A claim LAPSES (`contractReviewClaimLapse`) when the head moves, or
* {@link CONTRACT_REVIEW_CLAIM_LAPSE_HOURS} hours after it was posted -- the
* reviewer died -- after which the next reviewer may claim. A record on the
* head settles the review whatever any claim says; that is the caller's read
* (`locateReviewOfRecord`), never this one's. When a lane claim and a triage
* claim are both live on one head the LANE wins: triage withdraws by replying
* once and discards its subagent's work (`contractReviewClaims` names the
* holder).
*
* ⛔ No gate reads it. The queue guard keeps reading the ONE `## Contract
* review` record; this line is coordination between reviewers, never a merge
* condition. `contractReviewClaims` below is the reading a seat or the
* owed-review list (`check-owed-reviews.mjs`) takes.
*/
export const CONTRACT_REVIEW_CLAIM_KEY = 'Contract-review-claim';
/**
* The line exactly as the rule text prints it, placeholders included. This file's self-test pins it
* VERBATIM in `references/contract-review.md`, so the text and the reader cannot drift apart.
*/
export const CONTRACT_REVIEW_CLAIM_TEMPLATE = `${CONTRACT_REVIEW_CLAIM_KEY}: <session> · head <full sha> · <UTC>`;
/** Hours after posting that a claim with no record on its head lapses -- the rule's 「2 小时」. */
export const CONTRACT_REVIEW_CLAIM_LAPSE_HOURS = 2;
const CONTRACT_REVIEW_CLAIM_LINE = keyLineRegex(CONTRACT_REVIEW_CLAIM_KEY);
const CLAIM_SESSION = new RegExp(`^\`?(${SEAT_SIGNATURE_SESSION_SOURCE})\`?$`);
const CLAIM_HEAD = /^head[ \t]+`?([0-9a-fA-F]{40})`?$/;
const CLAIM_TIME = /^`?(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?Z)`?$/;
/**
* What one comment declares as a claim on a contract review. The FIRST claim
* line of the comment is read, after one leading signature line is set aside
* (`stripSignatureLine`, as every reader here does).
*
* @returns {{ state: 'missing' }
* | { state: 'unreadable', line: string }
* | { state: 'read', session: string, head: string, time: string, at: number }}
*/
export function readContractReviewClaim(text) {
for (const line of stripSignatureLine(String(text ?? '')).split(/\r?\n/)) {
const m = CONTRACT_REVIEW_CLAIM_LINE.exec(line);
if (!m) continue;
const unreadable = { state: 'unreadable', line: quoteLine(line) };
// Leading decoration is the key's (`stripValueDecoration`); trailing spaces and bold are the line's.
const parts = stripValueDecoration(m[1]).replace(/(?:[ \t]|\*\*)+$/, '').split(MAILBOX_SEPARATOR);
if (parts.length !== 3) return unreadable;
const session = CLAIM_SESSION.exec(parts[0]);
const head = CLAIM_HEAD.exec(parts[1]);
const time = CLAIM_TIME.exec(parts[2]);
const at = time ? Date.parse(time[1]) : Number.NaN;
if (!session || !head || !Number.isFinite(at)) return unreadable;
return { state: 'read', session: session[1], head: head[1].toLowerCase(), time: time[1], at };
}
return { state: 'missing' };
}
/**
* Is this claim still holding its head? Pure arithmetic, no thread read.
*
* live it names the current head and was posted under the lapse window ago
* head-moved it names another head -- the head moved past it
* expired it names the current head and was posted the lapse window ago or more
*
* `postedAt` is the comment's own `created_at` when the caller holds it -- the
* platform's stamp of when the claim was POSTED, which the rule times from --