@dev-loops/core 1.0.1 → 1.0.2-slim.0

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.
@@ -199,7 +199,7 @@ gates:
199
199
  - name: docs-surface
200
200
  angles: [docs, link-check, config-drift, contract-surface]
201
201
  - name: process
202
- angles: [scope, pr-description, gate-evidence, pr-checklist-matrix]
202
+ angles: [scope, pr-description, gate-evidence, pr-checklist]
203
203
  - name: correctness-input
204
204
  angles: [correctness, input-validation]
205
205
  - name: determinism-state
@@ -259,19 +259,24 @@ gates:
259
259
  - name: docs
260
260
  persona: docs
261
261
  prompt: "Review documentation correctness for the current change. Check that relative markdown links resolve, symlink-backed doc pointers resolve, navigable doc references are actual markdown links rather than bare backtick path mentions, command/script references still exist and use current names, and index/surface references match the current file tree. Also flag stale command references: removed or renamed npm scripts, CLI commands, or tool invocations that no longer match the current codebase. When the repo provides `scripts/docs/validate-links.mjs`, use it for the mechanical link pass; otherwise keep the review scoped to the touched doc surface and current change only."
262
- - name: pr-checklist-matrix
262
+ - name: pr-checklist
263
263
  mandatory: true
264
264
  persona: review
265
265
  prompt: |-
266
+ Verify the PR carries self-contained list-form Acceptance criteria and Definition of done
267
+ CHECKLISTS (never a matrix/table on the PR, never checkboxes inside table cells) that are
268
+ faithfully DERIVED from the linked issue's authoritative AC→DoD mapping matrix (#1951).
266
269
  Completeness is enforced deterministically (#1877): the pre_approval_gate fails closed on any
267
270
  unchecked `- [ ]` in the PR body's AC/DoD checklist, so this angle's completeness duty is
268
- machine-backed. Your remaining duty is TRUTHFULNESS, which the machine cannot check: verify
269
- that every checked `- [x]` box in the PR body's Acceptance criteria / Definition of done
270
- checklists is actually satisfied by the implementation — cite concrete code/test/behavior
271
- evidence; flag a dishonestly-ticked box as a blocking finding. Also verify the checked
272
- content mirrors the linked issue's AC/DoD/Non-goals matrix and that declared non-goals are
273
- respected (no scope creep). The boundary is explicit: the deterministic block enforces
274
- completeness (nothing left unchecked/forgotten); you verify each [x] is real.
271
+ machine-backed. Your remaining duty is TRUTHFULNESS + DERIVATION FIDELITY, which the machine
272
+ cannot check: verify that every checked `- [x]` box in the PR body's Acceptance criteria /
273
+ Definition of done checklists is actually satisfied by the implementation — cite concrete
274
+ code/test/behavior evidence; flag a dishonestly-ticked box as a blocking finding. Verify the
275
+ PR checklists faithfully reflect the issue matrix (every matrix row is represented, nothing
276
+ invented or dropped) and that declared non-goals are respected (no scope creep). Do NOT
277
+ require a matrix on the PR — the matrix lives on the issue; the PR carries the derived
278
+ checklists. The boundary is explicit: the deterministic block enforces completeness (nothing
279
+ left unchecked/forgotten); you verify each [x] is real and faithfully derived.
275
280
  - contradiction-lens
276
281
  - correctness-final
277
282
  - ui-validation
@@ -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
@@ -112,6 +112,44 @@ export function extractIssuePrIds(body) {
112
112
  return [...found];
113
113
  }
114
114
 
115
+ // A consecutive run of number-sign(s) immediately before a digit. Strip EVERY
116
+ // number-sign in the run (`#123` and `##123` alike leave `123`), or a leftover
117
+ // still auto-links AND trips the decode-aware guard. A lookahead consumes only
118
+ // the number-sign(s), keeping the digits.
119
+ const BARE_ISSUE_PR_ID_RE = /#+(?=\d)/g;
120
+
121
+ /**
122
+ * The sanctioned pre-guard transform for GENERATED comment bodies:
123
+ * neutralize a bare `#<digits>` auto-link token to a guard-safe, non-auto-linking
124
+ * form by stripping the leading `#` (`#123` -> `123`). Auto-link syntax requires
125
+ * the leading `#`, so the result neither auto-links on GitHub nor trips
126
+ * `guardCommentBodyNoIssuePrIds` — and because no decode path can reassemble a
127
+ * `#` from bare digits, the guard's entity-decode surface stays satisfied too.
128
+ *
129
+ * This is deliberately SEPARATE from `guardCommentBodyNoIssuePrIds`: the guard
130
+ * stays fail-closed for human-authored bodies (it must still REFUSE a bare id a
131
+ * person typed), while gate generators opt into this transform on their OWN
132
+ * generated finding text before handing it to the guard. It does NOT weaken the
133
+ * guard.
134
+ *
135
+ * Run on RAW text BEFORE any markdown sanitizer (sanitizeInline/sanitizeCodeSpan)
136
+ * emits its own numeric character references (e.g. `&#91;` for `[`): this strips
137
+ * `#` before digits without distinguishing an entity's digits from a bare id's,
138
+ * so applying it post-sanitize would corrupt an already-emitted entity
139
+ * (`&#91;` -> `&91;`).
140
+ *
141
+ * ponytail: strips only a LITERAL `#` before digits — every form a review agent
142
+ * actually authors (`#123`). It does NOT mirror the guard's full entity-decode
143
+ * surface; text already carrying an entity-encoded number-sign adjacent to
144
+ * digits (`&num;123`) is unreachable from reviewer prose, and the guard remains
145
+ * the fail-closed backstop for it. Returns non-string input unchanged (stringly
146
+ * callers coerce first).
147
+ */
148
+ export function neutralizeBareIssuePrIds(value) {
149
+ if (typeof value !== "string") return value;
150
+ return value.replace(BARE_ISSUE_PR_ID_RE, "");
151
+ }
152
+
115
153
  // A caller-supplied allowlist is normally already an array (or other
116
154
  // iterable) of ids. Guard the one mis-shaped input that would otherwise
117
155
  // silently produce the wrong set: a plain CSV string. `Array.from` over a
@@ -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
package/src/github/gh.mjs CHANGED
@@ -92,3 +92,52 @@ export async function ghGraphql(query, vars, env, runChild = defaultRunChild, {
92
92
  }
93
93
  return payload;
94
94
  }
95
+
96
+ const GET_USER_ID = [
97
+ "query($login:String!) {",
98
+ " user(login:$login) { id }",
99
+ "}",
100
+ ].join("\n");
101
+
102
+ const GET_ORG_ID = [
103
+ "query($login:String!) {",
104
+ " organization(login:$login) { id }",
105
+ "}",
106
+ ].join("\n");
107
+
108
+ /**
109
+ * Resolve a GitHub owner login to its node id and kind. Probes the user
110
+ * namespace first; a not-a-user probe failure (org logins make `gh api graphql`
111
+ * exit non-zero) falls through to the org namespace instead of throwing (#1949).
112
+ * A login that is neither a user nor an org fails closed with NO_USER_ID.
113
+ *
114
+ * The issue's "Proposed fix" wrapped only the user probe, but AC #3 requires
115
+ * NO_USER_ID for a genuinely non-existent owner; in production the org probe
116
+ * on a missing org also throws (non-zero exit), so both probes must be caught
117
+ * for the AC to hold. `cause` preserves the underlying org error for
118
+ * diagnostics. This does not change `ghGraphql`'s throw-on-non-zero-exit
119
+ * contract.
120
+ */
121
+ export async function resolveOwner(login, env, runChild) {
122
+ try {
123
+ const userPayload = await ghGraphql(GET_USER_ID, { login }, env, runChild);
124
+ if (userPayload?.data?.user?.id) {
125
+ return { id: userPayload.data.user.id, kind: "user" };
126
+ }
127
+ } catch {
128
+ // not a user login → fall through to the org probe
129
+ }
130
+ let orgError;
131
+ try {
132
+ const orgPayload = await ghGraphql(GET_ORG_ID, { login }, env, runChild);
133
+ if (orgPayload?.data?.organization?.id) {
134
+ return { id: orgPayload.data.organization.id, kind: "org" };
135
+ }
136
+ } catch (err) {
137
+ orgError = err;
138
+ }
139
+ throw Object.assign(
140
+ new Error(`Could not resolve owner ID for "${login}"`),
141
+ { code: "NO_USER_ID", cause: orgError },
142
+ );
143
+ }