@dev-loops/core 1.0.2-pre.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -195,6 +195,17 @@ gates:
195
195
  fanout:
196
196
  maxAnglesPerGroup: 3
197
197
  maxConcurrent: 4
198
+ # The table is global; a group is only emitted for a gate that actually
199
+ # resolves at least one of its angles, so a group naming preApproval-only
200
+ # angles is inert for the draft/spike gates (their angle sets never include
201
+ # these), and vice versa. The first four groups name draft-gate surfaces;
202
+ # the design-* and finalization groups name preApproval-exclusive angles so
203
+ # a grouped preApproval round collapses to one reviewer per group instead of
204
+ # scattering those angles across arbitrary auto-chunked leftover units.
205
+ # finalization names only correctness-final/ui-validation: contradiction-lens
206
+ # is deliberately NOT grouped here because it is also a draft-gate angle, and
207
+ # a global group naming it would peel it into a finalization unit in the draft
208
+ # gate too. It stays an auto-chunk leftover in both gates.
198
209
  groups:
199
210
  - name: docs-surface
200
211
  angles: [docs, link-check, config-drift, contract-surface]
@@ -204,6 +215,12 @@ gates:
204
215
  angles: [correctness, input-validation]
205
216
  - name: determinism-state
206
217
  angles: [determinism, state-concurrency]
218
+ - name: design-simplicity
219
+ angles: [dry, kiss, yagni, deep]
220
+ - name: design-solid
221
+ angles: [srp, soc, ocp, lsp, isp, dip]
222
+ - name: finalization
223
+ angles: [correctness-final, ui-validation]
207
224
  preApproval:
208
225
  angles:
209
226
  - name: dry
@@ -0,0 +1,80 @@
1
+ // Canonical closing-reference primitives shared by the create-pr / edit-pr
2
+ // wrappers so both guard a body's closing reference against the branch's own
3
+ // resolved issue with one implementation. A body swap that re-points the
4
+ // reference at a different issue would otherwise pass silently, and a merge
5
+ // would then close the wrong issue — this is the fail-closed backstop against
6
+ // that data-integrity hole.
7
+
8
+ import { extractClosingIssueNumbers as extractCanonicalClosingRefs } from "../loop/issue-refinement-artifact.mjs";
9
+
10
+ // Every issue number the body's closing references name. Delegates to the ONE
11
+ // canonical body-spec parser so the closing-keyword vocabulary (close/closes/
12
+ // closed, fix/fixes/fixed, resolve/resolves/resolved, any case), the cross-repo
13
+ // `owner/repo#N` form, fenced/inline-code stripping (a `Closes #N` inside a
14
+ // ```fenced``` example or `inline code` span does not auto-close on GitHub and
15
+ // must not spoof the guard), and de-duplication stay owned in ONE place — the
16
+ // guard never re-implements them.
17
+ export function extractClosingIssueNumbers(body) {
18
+ if (!body || typeof body !== "string") return [];
19
+ return extractCanonicalClosingRefs(body);
20
+ }
21
+
22
+ // True when the body carries any closing keyword.
23
+ export function detectClosingKeyword(body) {
24
+ return extractClosingIssueNumbers(body).length > 0;
25
+ }
26
+
27
+ // The issue number from the body's first closing reference, or null when the
28
+ // body carries none. Back-compat surface (create-pr's `--issue` missing-reference
29
+ // check); the mismatch guard uses extractClosingIssueNumbers to see every one.
30
+ export function extractClosingIssueNumber(body) {
31
+ const all = extractClosingIssueNumbers(body);
32
+ return all.length > 0 ? all[0] : null;
33
+ }
34
+
35
+ // Branch slug `[<prefix>/]issue-<N>[-<slug>]` -> N. Matches the dev-loop
36
+ // worktree default branch name and the prefixed form (e.g. a `dl/`-prefixed
37
+ // slug). Returns null when the branch encodes no issue number.
38
+ const BRANCH_ISSUE_PATTERN = /(?:^|\/)issue-(\d+)(?:-|$)/u;
39
+ export function extractIssueFromBranchSlug(branch) {
40
+ if (!branch || typeof branch !== "string") return null;
41
+ const match = BRANCH_ISSUE_PATTERN.exec(branch.trim());
42
+ return match ? Number(match[1]) : null;
43
+ }
44
+
45
+ // Resolve the issue a PR is expected to close from its own facts. The branch
46
+ // slug is authoritative (it encodes the issue the loop cut the branch for);
47
+ // the PR's GitHub-derived closingIssuesReferences is the fallback. Returns null
48
+ // when neither yields an issue — a genuinely issue-less PR, which is exempt.
49
+ export function resolveExpectedIssueFromPrContext(ctx) {
50
+ if (!ctx || typeof ctx !== "object") return null;
51
+ const fromBranch = extractIssueFromBranchSlug(ctx.headRefName);
52
+ if (fromBranch !== null) return fromBranch;
53
+ const refs = Array.isArray(ctx.closingIssuesReferences) ? ctx.closingIssuesReferences : [];
54
+ for (const ref of refs) {
55
+ const n = typeof ref === "number" ? ref : Number(ref?.number);
56
+ if (Number.isInteger(n) && n > 0) return n;
57
+ }
58
+ return null;
59
+ }
60
+
61
+ // Compare the body's closing reference against the branch's resolved issue.
62
+ // Returns a named refusal string when they disagree, else null. A waiver
63
+ // bypasses; an unresolved expected issue (issue-less) is exempt; a body with no
64
+ // closing reference has nothing to mislink and is exempt (only a present-and-
65
+ // disagreeing reference is refused, never a missing one).
66
+ export function resolveClosingRefMismatch({ body, expectedIssue, allowCrossIssue = false }) {
67
+ if (allowCrossIssue) return null;
68
+ if (!Number.isInteger(expectedIssue)) return null;
69
+ const closing = extractClosingIssueNumbers(body);
70
+ if (closing.length === 0) return null;
71
+ // Refuse when ANY closing reference disagrees — GitHub closes every one, so a
72
+ // correct first reference does not excuse a wrong second (a single-issue
73
+ // dev-loop PR closes only its branch's issue; a deliberate multi/cross-issue
74
+ // reference uses the waiver).
75
+ const disagreeing = closing.find((n) => n !== expectedIssue);
76
+ if (disagreeing !== undefined) {
77
+ return `CLOSING-REF-BRANCH-MISMATCH: the body closes #${disagreeing} but the branch resolves to issue #${expectedIssue} — refusing a mismatched closing reference (pass --allow-cross-issue to record a deliberate cross-issue reference)`;
78
+ }
79
+ return null;
80
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * ISSUE/PR-ID GUARD for generated comment bodies.
3
3
  *
4
- * Mandate (#1731, operator directive): generated gate/review/verdict comment
4
+ * Mandate (operator directive): generated gate/review/verdict comment
5
5
  * bodies must NEVER emit raw issue or PR ids. Public comment surfaces are
6
6
  * world-readable, and a bare `#<digits>` in a comment body is auto-linked by
7
7
  * GitHub to that issue/PR — leaking internal cross-references and violating
@@ -119,7 +119,7 @@ export function extractIssuePrIds(body) {
119
119
  const BARE_ISSUE_PR_ID_RE = /#+(?=\d)/g;
120
120
 
121
121
  /**
122
- * The sanctioned pre-guard transform for GENERATED comment bodies (#1922):
122
+ * The sanctioned pre-guard transform for GENERATED comment bodies:
123
123
  * neutralize a bare `#<digits>` auto-link token to a guard-safe, non-auto-linking
124
124
  * form by stripping the leading `#` (`#123` -> `123`). Auto-link syntax requires
125
125
  * the leading `#`, so the result neither auto-links on GitHub nor trips
@@ -1,44 +1,34 @@
1
1
  /**
2
2
  * Shared deterministic helpers for Copilot-related GitHub data.
3
- *
4
- * These are pure functions with no filesystem or network dependencies.
5
- * Owner: packages/core — reusable deterministic logic consumed by both
6
- * scripts and other packages/core modules.
3
+ * Pure functions with no filesystem or network dependencies.
7
4
  */
8
5
 
9
6
  import { GATE_REVIEW_VERDICT_SET } from "../loop/policy-constants.mjs";
10
7
  import { trimmedOrNull } from "../loop/normalize.mjs";
11
8
 
12
- // Exported so anything deciding "is there a real prior review" uses the same
13
- // whitelist as the loop-state reader — two copies could drift, and a guard
9
+ // Same whitelist as the loop-state reader: two copies could drift, and a guard
14
10
  // acting on the gate's behalf must agree with the gate about what a submitted
15
11
  // review is.
16
12
  export const SUBMITTED_REVIEW_STATES = new Set(["APPROVED", "CHANGES_REQUESTED", "COMMENTED", "DISMISSED"]);
17
13
  const GATE_REVIEW_NAMES = new Set(["draft_gate", "pre_approval_gate"]);
18
- // `review` (the standalone review entrypoint, upsert-checkpoint-verdict.mjs's
19
- // `--gate review`) is a RECOGNIZED gate header — it is identified, not
20
- // absent — but carries no draft/pre-approval evidence by design (#1808 AC3).
21
- // Recognizing it (rather than leaving it unrecognized) is what lets
22
- // parseGateReviewCommentFields below short-circuit to null the instant a
23
- // `review` header is seen, instead of falling through to the lenient
24
- // draft_gate/pre_approval_gate token scan — the fallthrough that previously
25
- // let a `review` verdict whose findings text merely MENTIONED "draft_gate"
26
- // get recorded as real draft-gate evidence (a draft-gate bypass).
14
+ // `review` is a RECOGNIZED gate header that carries no draft/pre-approval
15
+ // evidence by design. Recognizing it lets
16
+ // parseGateReviewCommentFields short-circuit to null on a `review` header
17
+ // instead of falling through to the lenient draft_gate/pre_approval_gate token
18
+ // scan — the fallthrough that would otherwise record a `review` verdict whose
19
+ // findings merely mention "draft_gate" as real draft-gate evidence (a
20
+ // draft-gate bypass).
27
21
  const NON_EVIDENCE_GATE_NAMES = new Set(["review"]);
28
22
  const RECOGNIZED_GATE_NAMES = new Set([...GATE_REVIEW_NAMES, ...NON_EVIDENCE_GATE_NAMES]);
29
23
  const GATE_EXECUTION_MODES = new Set(["fanout_fanin", "inline_single_agent"]);
30
- // Size-budget outcome vocabulary — mirrors
31
- // check-size-budget.mjs's computeSizeBudget outcome enum exactly; this file
32
- // never recomputes the outcome, only round-trips it through the verdict
33
- // comment.
24
+ // Size-budget outcome vocabulary; mirrors check-size-budget.mjs's
25
+ // computeSizeBudget outcome enum exactly. This file only round-trips it.
34
26
  const GATE_SIZE_OUTCOMES = new Set(["pass", "escalate", "block"]);
35
27
 
36
- // The literal header line the gate review body always emits first
37
- // (upsert-checkpoint-verdict.mjs's renderGateReviewCommentBody, re-exported
38
- // from there). Owned here so the machine-artifact filter below and every
39
- // consumer that needs to recognize "is this a real gate verdict surface" read
40
- // the same producer-owned literal instead of restating it. Line-start anchored
41
- // (`m`) so a quoted header in a reply/blockquote can't match.
28
+ // The literal header line the gate review body emits first (producer:
29
+ // upsert-checkpoint-verdict.mjs's renderGateReviewCommentBody). Owned here so
30
+ // every consumer reads the same literal instead of restating it. Line-start
31
+ // anchored (`m`) so a quoted header in a reply/blockquote can't match.
42
32
  export const GATE_REVIEW_COMMENT_HEADER_RE = /^###\s+Gate review:\s*`(draft_gate|pre_approval_gate)`\s*$/m;
43
33
 
44
34
  /** Returns the matched gate name when `body` carries a genuine gate verdict header, else null. */
@@ -49,48 +39,31 @@ export function matchGateReviewCommentHeader(body) {
49
39
  }
50
40
 
51
41
  // Machine-authored gate artifacts that must never win the newest-gate-marker
52
- // tie-break in summarizeGateReviewComments/summarizeGateReviewCommentMarkers:
53
- // a historical standalone findings review always embedded this gate's name in
54
- // its header line and could quote the current head sha inside a finding's own
55
- // free text (the lenient gate-name+hex-token fallback in
56
- // parseGateReviewCommentFields would otherwise happily match that), and the
57
- // historical deferred-summary PR comment quoted a gate name plus a sha-shaped
58
- // id in its table rows the same way. Both are excluded HERE, inside the two
59
- // shared summarizers, because this module is the true merge point: every
60
- // consumer (detect-checkpoint-evidence.mjs, pre-pr-ready-gate.mjs,
61
- // ready-for-review.mjs, request-copilot-review.mjs) calls
62
- // summarizeGateReviewComments/summarizeGateReviewCommentMarkers to turn a raw
63
- // comment/review list into a gate verdict, so filtering here — rather than
64
- // per-caller — covers all of them by construction.
42
+ // tie-break in the two summarizers below: a historical standalone findings
43
+ // review or deferred-summary comment embeds a gate name and a sha-shaped id
44
+ // that the lenient parseGateReviewCommentFields fallback would otherwise match.
45
+ // Excluded here because this module is the merge point every consumer routes
46
+ // through.
65
47
  //
66
- // Anchored to the start of a line (`^` with `m`) so only a marker rendered as
67
- // the first character of its own line is excluded — a genuine verdict
68
- // comment whose findings summary merely QUOTES the marker text mid-line (for
69
- // example, describing this very mechanism) still counts as evidence. Both
70
- // producers render their marker at column 0, so the anchor costs nothing
71
- // against genuine artifacts.
72
- // The set covers exactly three marker tokens: the per-round review round
73
- // marker (gate-findings-review), post-gate-findings.mjs's opt-in findings
74
- // COMMENT marker (gate-findings gate=...), and the historical
75
- // deferred-summary comment. Without the findings-comment marker, that comment
76
- // parses as a verdict marker candidate (its "Gate fan-out findings:"/
77
- // "Reviewed head:" lines yield gate+headSha) and the verdict upsert claims
78
- // and overwrites it in place, silently destroying the round's visible
79
- // findings record. Every branch is delimiter-anchored — the token must be
80
- // followed by whitespace or the closing `-->` — so no suffixed `<token>-<x>`
81
- // variant ever matches.
48
+ // Line-anchored (`^` with `m`) so only a marker at column 0 is excluded; a
49
+ // genuine verdict whose findings merely QUOTE the marker mid-line still counts.
50
+ // The set covers exactly three tokens: the per-round review marker
51
+ // (gate-findings-review), post-gate-findings.mjs's findings-COMMENT marker
52
+ // (gate-findings), and the deferred-summary comment. Without the
53
+ // findings-comment marker, that comment parses as a verdict candidate and the
54
+ // verdict upsert overwrites it in place, silently destroying the round's
55
+ // findings record. Every branch is delimiter-anchored (token followed by
56
+ // whitespace or `-->`) so no suffixed `<token>-<x>` variant matches.
82
57
  const GATE_MACHINE_ARTIFACT_MARKER_RE = /^<!--\s*dev-loops:(?:gate-findings-review|gate-findings|deferred-summary)(?=\s|-->)/mu;
83
58
 
84
59
  export function isGateMachineArtifactBody(body) {
85
60
  if (typeof body !== "string" || !GATE_MACHINE_ARTIFACT_MARKER_RE.test(body)) {
86
61
  return false;
87
62
  }
88
- // A gate round now posts ONE PR review carrying BOTH the verdict header and
89
- // the gate-findings-review marker (the findings it files live on that same
90
- // surface). Such a body IS the verdict, not a separate machine artifact, so
91
- // the producer-owned verdict header wins over the artifact marker. Only a
92
- // marker-bearing body with NO genuine verdict header (a historical standalone
93
- // findings review or deferred-summary comment) stays excluded.
63
+ // A gate round posts ONE PR review carrying BOTH the verdict header and the
64
+ // gate-findings-review marker. Such a body IS the verdict, so the
65
+ // producer-owned header wins over the artifact marker. Only a marker-bearing
66
+ // body with NO verdict header stays excluded.
94
67
  return matchGateReviewCommentHeader(body) === null;
95
68
  }
96
69
 
@@ -101,16 +74,10 @@ export function isCopilotLogin(login) {
101
74
  /**
102
75
  * Resolve whether Copilot is present as a reviewer on a PR from the REVIEW
103
76
  * surface only — requested reviewers plus submitted reviews — never from
104
- * assignees (#1670).
105
- *
106
- * Copilot review is configured in two ways: Copilot is either formally listed
107
- * in the PR's `requested_reviewers`, or it is a configured auto-reviewer
108
- * (`copilot-pull-request-reviewer[bot]`) that submits an actual review without
109
- * ever appearing in `requested_reviewers`. Both are review-surface facts.
110
- * Assignment is a disjoint surface and must never decide presence: on a
111
- * reviewer-configured repo Copilot is never an assignee, so an assignee-based
112
- * proxy would falsely report a fully-configured Copilot reviewer as absent and
113
- * could let the gate skip the Copilot-convergence requirement on a false premise.
77
+ * assignees. Assignment is a disjoint surface: on a reviewer-configured
78
+ * repo Copilot is never an assignee, so an assignee-based proxy would falsely
79
+ * report a configured Copilot reviewer as absent and let the gate skip the
80
+ * Copilot-convergence requirement on a false premise.
114
81
  *
115
82
  * @param {object} params
116
83
  * @param {boolean} [params.requested] - Copilot is listed in the PR's requested_reviewers
@@ -129,12 +96,12 @@ export function resolveCopilotReviewPresence({ requested = false, reviews = [] }
129
96
  return { present: sources.length > 0, sources };
130
97
  }
131
98
 
132
- // Anti-summon literal: bare-text `@copilot` or a `/copilot*` slash command. Both
133
- // the write-side sanitizer and the read-side guard scan key off this shape so a
134
- // gate-evidence comment can quote the rule (inside a code span/fenced block)
135
- // without arming the request-copilot-review.mjs anti-summon guard. The token
136
- // regex carries the same left word-boundary as the guard regex so the sanitizer
137
- // never mangles text the guard would not arm on (e.g. user@copilot.example).
99
+ // Anti-summon literal: bare-text `@copilot` or a `/copilot*` slash command.
100
+ // Both the write-side sanitizer and the read-side guard key off this shape so a
101
+ // gate-evidence comment can quote the rule (in a code span/fence) without arming
102
+ // the request-copilot-review.mjs anti-summon guard. The token regex carries the
103
+ // same left word-boundary as the guard regex so the sanitizer never mangles text
104
+ // the guard would not arm on (e.g. user@copilot.example).
138
105
  const COPILOT_SUMMON_TOKEN_RE = /(?<=^|\W)(@copilot|\/copilot[a-z0-9_-]*)/gi;
139
106
  const COPILOT_SUMMON_WORD_BOUNDARY_RE = /(?:^|\W)(@copilot|\/copilot)(?:$|\W)/i;
140
107
  // GFM inline code span: an N-backtick run, lazy content, closed by a same-length
@@ -145,8 +112,6 @@ const ZERO_WIDTH_JOINER = "\u200D";
145
112
 
146
113
  // Apply `transformLine` to every markdown line OUTSIDE a fenced code block
147
114
  // (```/~~~), leaving fence-delimiter lines and fenced content untouched.
148
- // Mirrors the fenced-block tracking scripts/docs/validate-rule-ownership.mjs
149
- // uses for its own lexical scan.
150
115
  function transformNonFencedLines(text, transformLine) {
151
116
  const lines = String(text).split(/\r?\n/);
152
117
  let inFencedBlock = false;
@@ -207,19 +172,15 @@ function lineArmsSummonGuard(line) {
207
172
  const ZWJ_FALLBACK_RE = /(?<=^|\W)([@/])(copilot)/gi;
208
173
 
209
174
  // Sanitize one line, verifying against the guard scan. Backtick-wrapping is the
210
- // primary neutralization (visible, greppable), but pre-existing backticks on the
211
- // line can destabilize it two ways: an UNBALANCED stray backtick pairs with an
212
- // inserted one and re-exposes the token to the guard's span-stripping, and
213
- // adjacent spans (e.g. a span ending right before the token's new wrap) can make
214
- // the wrapped line re-tokenize differently on the next pass, re-wrapping the
215
- // token and growing the comment by one backtick per rewrite. The wrapped result
216
- // is therefore accepted only when it is BOTH guard-inert AND a fixed point of
217
- // the wrapper (re-wrapping it changes nothing); otherwise fall back to inserting
218
- // a zero-width joiner into the residual tokens still outside the wrapped line's
219
- // spans — invisible, guard-inert, and idempotent (the joined token no longer
220
- // matches the summon shape). Working on the wrapped line (not the original)
221
- // preserves every stable backtick wrap and keeps the joiner out of legitimate
222
- // pre-existing code spans.
175
+ // primary neutralization (visible, greppable), but pre-existing backticks can
176
+ // destabilize it: an unbalanced stray backtick re-exposes the token to the
177
+ // guard's span-stripping, and adjacent spans can make the wrapped line
178
+ // re-tokenize on the next pass and grow by a backtick per rewrite. So the
179
+ // wrapped result is accepted only when it is BOTH guard-inert AND a fixed point
180
+ // of the wrapper; otherwise fall back to a zero-width joiner in the residual
181
+ // tokens outside the wrapped line's spans — invisible, guard-inert, and
182
+ // idempotent. Working on the wrapped line preserves stable wraps and keeps the
183
+ // joiner out of legitimate pre-existing code spans.
223
184
  function sanitizeSummonLine(line) {
224
185
  const wrapped = wrapBareSummonTokensInLine(line);
225
186
  if (!lineArmsSummonGuard(wrapped) && wrapBareSummonTokensInLine(wrapped) === wrapped) {
@@ -232,12 +193,10 @@ export function sanitizeCopilotSummonTokens(text) {
232
193
  return transformNonFencedLines(String(text), sanitizeSummonLine);
233
194
  }
234
195
 
235
- // Drop all markdown code content (fenced blocks entirely, inline code spans
236
- // per line) from `text`, leaving only the bare-text markdown to scan. Unlike
237
- // transformNonFencedLines (which leaves fenced lines verbatim — correct for
238
- // sanitizing, where code content must not be rewritten), fenced content here
239
- // must be REMOVED rather than kept: leaving it in place would let bare text
240
- // inside a fence still match the anti-summon scan.
196
+ // Drop all markdown code content (fenced blocks entirely, inline spans per
197
+ // line) from `text`, leaving only bare-text markdown to scan. Unlike
198
+ // transformNonFencedLines, fenced content here must be REMOVED, not kept:
199
+ // leaving it would let bare text inside a fence still match the summon scan.
241
200
  function stripMarkdownCodeForScan(text) {
242
201
  const lines = String(text).split(/\r?\n/);
243
202
  let inFencedBlock = false;
@@ -306,11 +265,10 @@ function stripGateCommentMarkdown(rawLine) {
306
265
  return line.trim();
307
266
  }
308
267
 
309
- // Recognizes BOTH evidence gates (draft_gate/pre_approval_gate) and the
310
- // non-evidence `review` gate — parseGateReviewCommentFields below relies on
311
- // `review` coming back as an identified value (not null) so it can
312
- // short-circuit to non-evidence explicitly, rather than leaving the field
313
- // null and falling through to the lenient token-scan fallback.
268
+ // Recognizes BOTH evidence gates and the non-evidence `review` gate:
269
+ // parseGateReviewCommentFields relies on `review` coming back identified (not
270
+ // null) so it can short-circuit rather than fall through to the lenient
271
+ // token-scan fallback.
314
272
  function normalizeGateReviewName(value) {
315
273
  const normalized = stripOptionalCodeTicks(value).toLowerCase();
316
274
  return RECOGNIZED_GATE_NAMES.has(normalized) ? normalized : null;
@@ -383,21 +341,13 @@ function parseGateReviewCommentFields(body) {
383
341
  }
384
342
  const line = stripped;
385
343
 
386
- // First-NON-EMPTY-wins per field: a genuine comment renders its structured
387
- // block first, so the first column-0 match for each field is normally the
388
- // real one. A free-text field (findings summary, next action) rendered
389
- // later in the SAME comment can embed a newline plus a spoofed
390
- // "Verdict: clean" (or any other field label) at column 0; capturing only
391
- // the first match (rather than the last) stops that later line from
392
- // winning and flipping/nulling the field. But the label regex's
393
- // `\s*(.+)$` also matches a label followed by nothing but whitespace,
394
- // capturing an empty string — for the enum fields (gate/headSha/verdict/
395
- // executionMode) an empty capture normalizes to null already, so the
396
- // `=== null` guard below naturally stays open for a later, genuine line.
397
- // The two free-text fields (findingsSummary, nextAction) do NOT normalize
398
- // through an enum, so an empty capture must be checked for explicitly:
399
- // treat it as no-capture (leave the field open) rather than locking it to
400
- // "" and hiding a real line that renders after it.
344
+ // First-NON-EMPTY-wins per field: the first column-0 match is the genuine
345
+ // structured block. A later free-text field (findings, next action) can
346
+ // embed a spoofed "Verdict: clean" at column 0; capturing only the first
347
+ // match stops that from flipping the field. Enum fields normalize an empty
348
+ // capture (label + whitespace only) to null, so their `=== null` guard
349
+ // stays open for a later genuine line; the two free-text fields do NOT, so
350
+ // an empty capture is checked explicitly and treated as no-capture.
401
351
  let match = line.match(/^(?:[-*]\s*)?(?:gate(?:\s+name)?|gate\s+review)\s*:\s*(.+)$/iu);
402
352
  if (match) {
403
353
  if (fields.gate === null) {
@@ -426,9 +376,7 @@ function parseGateReviewCommentFields(body) {
426
376
  if (match) {
427
377
  if (fields.findingsSummary === null) {
428
378
  const candidate = match[1].trim();
429
- // An empty capture (label followed only by whitespace) is treated as
430
- // no-capture: leave the field open so a later, genuine line can still
431
- // win instead of first-wins locking it to "".
379
+ // Empty capture treated as no-capture (see first-non-empty-wins above).
432
380
  if (candidate.length > 0) {
433
381
  fields.findingsSummary = candidate;
434
382
  }
@@ -457,9 +405,8 @@ function parseGateReviewCommentFields(body) {
457
405
  const modeToken = sepMatch ? sepMatch[1].trim() : rest;
458
406
  const reasonToken = sepMatch ? sepMatch[2].trim() : "";
459
407
  fields.executionMode = normalizeGateExecutionMode(modeToken);
460
- // Only record an inline reason for inline_single_agent. A trailing
461
- // "— text" on a fanout_fanin (or invalid) mode line must not surface an
462
- // inconsistent mode/reason pair, so leave inlineReason null otherwise.
408
+ // Only record an inline reason for inline_single_agent; a trailing
409
+ // "— text" on any other mode must not surface an inconsistent pair.
463
410
  if (reasonToken.length > 0 && fields.executionMode === "inline_single_agent") {
464
411
  fields.inlineReason = reasonToken;
465
412
  }
@@ -496,18 +443,11 @@ function parseGateReviewCommentFields(body) {
496
443
  }
497
444
  }
498
445
 
499
- // An explicit, RECOGNIZED `review` gate field is authoritative and returns
500
- // null here — before the lenient token-scan fallback below ever runs. A
501
- // `review` verdict comment carries no draft/pre-approval evidence by
502
- // design (#1808 AC3); without this short circuit, `fields.gate` would stay
503
- // "review" (not one of the two evidence gates) but the lenient fallback
504
- // below only fires when `!fields.gate` — so a *recognized* `review` gate
505
- // would otherwise skip the fallback yet still return non-null fields keyed
506
- // to "review", which is harmless for the two summarizers here (they only
507
- // read `.draft_gate`/`.pre_approval_gate`) but leaves the non-evidence
508
- // contract implicit rather than explicit. Stated plainly: an identified
509
- // non-evidence gate must never be treated as an unidentified body, and an
510
- // unidentified body is the ONLY case the token-scan fallback exists for.
446
+ // A recognized `review` gate is authoritative and returns null before the
447
+ // lenient token-scan fallback runs: a `review` verdict carries no
448
+ // draft/pre-approval evidence by design. An identified
449
+ // non-evidence gate must never be treated as an unidentified body, which is
450
+ // the only case the token-scan fallback exists for.
511
451
  if (NON_EVIDENCE_GATE_NAMES.has(fields.gate)) {
512
452
  return null;
513
453
  }
@@ -528,9 +468,8 @@ function parseGateReviewCommentFields(body) {
528
468
  }
529
469
 
530
470
  if (!fields.headSha) {
531
- // Prefer SHA following a "head" context marker to avoid false
532
- // matches on plain-text numeric IDs (issue/comment IDs, etc.)
533
- // Example: "pre_approval_gate for head e284c2e341" or "commit abc1234def"
471
+ // Prefer SHA following a "head" context marker to avoid false matches on
472
+ // plain-text numeric IDs (issue/comment IDs, etc.).
534
473
  const ctxShaMatch = flatBody.match(
535
474
  /\b(?:head|sha|commit)\b\s*(?:sha)?\s*[:=]?\s*`?\b([0-9a-f]{7,64})\b`?/iu
536
475
  );
@@ -586,14 +525,12 @@ export function parseGateReviewCommentMarkerBody(body) {
586
525
  };
587
526
  }
588
527
 
589
- // Which GitHub surface carries a gate verdict. The poster needs it to pick the
590
- // right in-place correction endpoint on a same-head rerun (a PR review is PUT
591
- // to pulls/{pr}/reviews/{id}; a legacy verdict issue comment is PATCHed to
592
- // issues/comments/{id}). Anything that is not the review surface — including a
593
- // raw issue-comment payload with no `surface` field — is issue_comment, so the
594
- // historical shape survives untouched. SINGLE definition: a restatement that
595
- // misses a future third surface would silently route its body to the
596
- // issue-comment endpoint, where it does not live.
528
+ // Which GitHub surface carries a gate verdict; the poster uses it to pick the
529
+ // in-place correction endpoint on a same-head rerun (review → PUT
530
+ // pulls/{pr}/reviews/{id}; issue comment → PATCH issues/comments/{id}).
531
+ // Anything not the review surface (including a payload with no `surface` field)
532
+ // is issue_comment. SINGLE definition: a restatement missing a future third
533
+ // surface would misroute its body to the issue-comment endpoint.
597
534
  export function normalizeVerdictSurface(value) {
598
535
  return value === "review" ? "review" : "issue_comment";
599
536
  }
@@ -711,18 +648,13 @@ export function summarizeGateReviewCommentMarkers(comments, { headSha } = {}) {
711
648
  }
712
649
 
713
650
  /**
714
- * Resolve the draft-gate round-reset timestamp (ms) used to suppress stale Copilot
715
- * review rounds from the count (#896 consistency).
716
- *
717
- * When the draft gate was re-passed clean on a DIFFERENT head than the current one,
718
- * only Copilot reviews submitted after that re-pass should count toward the round
719
- * cap. Returning the re-pass `updatedAt` (ms) lets {@link summarizeCopilotReviews}
720
- * drop earlier rounds. Returns null when no reset applies (no clean draft gate, or
721
- * the clean draft gate is already on the current head).
722
- *
723
- * Both detect-pr-gate-coordination-state and request-copilot-review must derive the
724
- * reset identically, or the two scripts disagree on the completed round count and
725
- * the cap (the inconsistency reported in #896). This is the single shared source.
651
+ * Resolve the draft-gate round-reset timestamp (ms) used to suppress stale
652
+ * Copilot review rounds from the count. When the draft gate re-passed
653
+ * clean on a DIFFERENT head, only Copilot reviews after that re-pass count
654
+ * toward the round cap; returning the re-pass `updatedAt` (ms) lets
655
+ * summarizeCopilotReviews drop earlier rounds. Null when no reset applies.
656
+ * Single shared source: detect-pr-gate-coordination-state and
657
+ * request-copilot-review must derive the reset identically.
726
658
  *
727
659
  * @param {object} params
728
660
  * @param {{ verdict?: string|null, headSha?: string|null, updatedAt?: string|null }|null} params.draftGate