rungate 0.8.19 → 0.8.21

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.
package/gates/.gate-salt CHANGED
@@ -1 +1 @@
1
- 1267e343f5b54c7a006014564da4b6b404022b6f2934457d083b0f37734afe18
1
+ 36e88dc95acdd61bc72fdbbfffcae7a21722942437fbac2c5b2a5515cf2640ef
@@ -24,7 +24,7 @@
24
24
  * two that only a live fork or a line outside a hunk would otherwise produce.
25
25
  */
26
26
  import type { ThreadReading } from "./ai-review-rounds";
27
- import { reviewThreadRequests, threadKeyFrom } from "./scaffold/ai-review-findings";
27
+ import { escapeAnnotation, reviewThreadRequests, threadKeyFrom } from "./scaffold/ai-review-findings";
28
28
  import type { AiReviewFindingsReading, AiReviewThreadRequest } from "./scaffold/ai-review-findings";
29
29
 
30
30
  /**
@@ -254,6 +254,7 @@ export async function postReviewThreads(
254
254
  reading: AiReviewFindingsReading,
255
255
  post: AiReviewThreadPoster,
256
256
  keyFor?: (finding: Record<string, unknown>) => string | null,
257
+ fork?: boolean | null,
257
258
  ): Promise<AiReviewThreadsResult> {
258
259
  const detail: string[] = [];
259
260
 
@@ -306,10 +307,24 @@ export async function postReviewThreads(
306
307
  continue;
307
308
  }
308
309
  if (answer.status === FORBIDDEN) {
310
+ // #1992: the fork excuse holds only for a fork. A same-repository run
311
+ // whose token lost write is a broken producer, and degrading it would
312
+ // hide that behind a reason that does not apply.
313
+ if (fork === false) {
314
+ failed += 1;
315
+ detail.push(
316
+ `${where}: 403 — this token cannot write pull-request comments, and this run is not a fork ` +
317
+ `(${AI_REVIEW_PR_IS_FORK_VAR}=false), so the read-only-token excuse does not apply.`,
318
+ );
319
+ continue;
320
+ }
309
321
  forbidden += 1;
310
322
  detail.push(
311
323
  `${where}: 403 — this token cannot write pull-request comments. A pull_request run from a ` +
312
- `fork is handed a read-only token whatever the workflow declares.`,
324
+ `fork is handed a read-only token whatever the workflow declares.` +
325
+ (fork === true
326
+ ? ""
327
+ : ` Whether this run is a fork was not read (${AI_REVIEW_PR_IS_FORK_VAR} unset), so it is treated as one.`),
313
328
  );
314
329
  continue;
315
330
  }
@@ -358,6 +373,35 @@ export function threadsLandedPhrase(result: AiReviewThreadsResult): string {
358
373
  : `Only ${result.posted} of ${result.attempted} review threads were created`;
359
374
  }
360
375
 
376
+ /**
377
+ * The environment variable the workflow sets to say whether this run is a
378
+ * fork (#1992; the generator half is #2203). An environment variable and not
379
+ * a flag on purpose: a published CLI that does not know a flag refuses it,
380
+ * while an unknown variable is ignored, so the workflow can set it before or
381
+ * after this reader ships without reddening anything.
382
+ */
383
+ export const AI_REVIEW_PR_IS_FORK_VAR = "RUNGATE_PR_IS_FORK";
384
+
385
+ /**
386
+ * Read exactly: `"true"` and `"false"` are readings, anything else is unread
387
+ * (`null`). The same rule `.claude/rules/config-access.md` applies to a switch
388
+ * that turns a refusal on — a loose reading turns it on by accident.
389
+ */
390
+ export function prIsForkReading(raw: string | undefined): boolean | null {
391
+ return raw === "true" ? true : raw === "false" ? false : null;
392
+ }
393
+
394
+ /**
395
+ * Every line this command prints from a result's detail, escaped (#1992).
396
+ * Detail carries text the producer does not control — an API error message,
397
+ * a path a finding named — and a CR or LF printed raw starts a new line that
398
+ * the Actions runner reads as a workflow command. `escapeAnnotation` is the
399
+ * one escaper, so this does not grow a second.
400
+ */
401
+ export function threadsDetailLines(result: AiReviewThreadsResult, command: string): string[] {
402
+ return result.detail.map(line => `${command}: ${escapeAnnotation(line)}`);
403
+ }
404
+
361
405
  /** The exit code a round's outcome earns. Only `FAILED` refuses. */
362
406
  export function aiReviewThreadsExitCode(result: AiReviewThreadsResult): number {
363
407
  return result.outcome === "FAILED" ? AI_REVIEW_THREADS_REFUSAL : 0;
@@ -0,0 +1,292 @@
1
+ /**
2
+ * The board-intake move step as code (#2193, part 1 of #2183).
3
+ *
4
+ * `board-intake.yml`'s move step carried this logic as about 260 lines of
5
+ * shell, and its invariants were enforced only by regexes over the rendered
6
+ * YAML, so an edit could drop one with no test exercising what runs. Here
7
+ * each one is a branch a stub client drives (`test/board-intake-move.test.ts`):
8
+ *
9
+ * - **Every call is retried** (three tries, waits of 2 s and 4 s), and the
10
+ * third failure is API_FAILED, which says the board's state is UNKNOWN.
11
+ * A thrown error is never read as an answer.
12
+ * - **A null `node(id:)` is an id that did not resolve** (stale, invisible to
13
+ * this token, or a wrong project), refused by naming the id, never read as
14
+ * an empty list.
15
+ * - **A full page is not an absence.** Each connection asks `hasNextPage`, and
16
+ * "not found, and the page was full" is its own UNMEASURED refusal.
17
+ * - **The field and option are resolved by NAME**, so a renamed column is a
18
+ * refusal rather than a stale id writing the wrong column.
19
+ * - **A write is not a reading.** Each write is read back from the item AND
20
+ * from the project's search index, which is what the board draws, and only
21
+ * both agreeing is success. GitHub's built-in "Item added" automation fires
22
+ * on the same event and can land after this write, so there are three
23
+ * verified attempts, then a refusal naming which reading disagreed.
24
+ *
25
+ * It owns only the opened -> In review edge; merged and closed stay with
26
+ * GitHub's built-in workflows, so each transition has one decider.
27
+ */
28
+
29
+ /** A GraphQL call: resolves to the response's `data`, throws on failure, as the client does. */
30
+ export type GraphqlCall = (query: string, variables: Record<string, string>) => Promise<unknown>;
31
+
32
+ export interface MoveDeps {
33
+ graphql: GraphqlCall;
34
+ sleep: (ms: number) => Promise<void>;
35
+ /** Progress lines (one per attempt that did not settle). */
36
+ log: (line: string) => void;
37
+ }
38
+
39
+ export interface MoveInput {
40
+ projectId: string;
41
+ itemId: string;
42
+ column: string;
43
+ }
44
+
45
+ export type MoveRefusal =
46
+ | "NO_ITEM"
47
+ | "COLUMN_UNSEARCHABLE"
48
+ | "API_FAILED"
49
+ | "NULL_NODE"
50
+ | "WRONG_TYPE"
51
+ | "FIELDS_TRUNCATED"
52
+ | "NOT_RESOLVED"
53
+ | "VALUES_TRUNCATED"
54
+ | "INDEX_TRUNCATED"
55
+ | "INDEX_LAGGING"
56
+ | "OVERWRITTEN"
57
+ | "UNEXPECTED";
58
+
59
+ export type MoveResult = { ok: true; attempt: number; message: string } | { ok: false; reason: MoveRefusal; message: string };
60
+
61
+ /** How long to let a concurrent built-in write land before reading back. */
62
+ export const SETTLE_MS = 3000;
63
+
64
+ const FIELDS_QUERY = `query($project: ID!) {
65
+ node(id: $project) {
66
+ ... on ProjectV2 {
67
+ fields(first: 50) {
68
+ pageInfo { hasNextPage }
69
+ nodes { ... on ProjectV2SingleSelectField { id name options { id name } } }
70
+ }
71
+ }
72
+ }
73
+ }`;
74
+
75
+ const WRITE_MUTATION = `mutation($project: ID!, $item: ID!, $field: ID!, $option: String!) {
76
+ updateProjectV2ItemFieldValue(input: {
77
+ projectId: $project, itemId: $item, fieldId: $field,
78
+ value: { singleSelectOptionId: $option }
79
+ }) { projectV2Item { id } }
80
+ }`;
81
+
82
+ const VALUES_QUERY = `query($item: ID!) {
83
+ node(id: $item) {
84
+ ... on ProjectV2Item {
85
+ fieldValues(first: 50) {
86
+ pageInfo { hasNextPage }
87
+ nodes {
88
+ ... on ProjectV2ItemFieldSingleSelectValue {
89
+ name field { ... on ProjectV2FieldCommon { name } }
90
+ }
91
+ }
92
+ }
93
+ }
94
+ }
95
+ }`;
96
+
97
+ const INDEX_QUERY = `query($project: ID!, $q: String!) {
98
+ node(id: $project) {
99
+ ... on ProjectV2 {
100
+ items(first: 100, query: $q) {
101
+ pageInfo { hasNextPage }
102
+ nodes { id }
103
+ }
104
+ }
105
+ }
106
+ }`;
107
+
108
+ interface Page<T> {
109
+ pageInfo?: { hasNextPage?: boolean } | null;
110
+ nodes?: Array<T | null> | null;
111
+ }
112
+
113
+ class Refused extends Error {
114
+ constructor(
115
+ readonly reason: MoveRefusal,
116
+ message: string,
117
+ ) {
118
+ super(message);
119
+ }
120
+ }
121
+
122
+ /** One call, three tries. The third failure refuses; a thrown error is never an answer. */
123
+ async function call(deps: MoveDeps, query: string, variables: Record<string, string>): Promise<unknown> {
124
+ let last: unknown;
125
+ for (let attempt = 1; attempt <= 3; attempt++) {
126
+ try {
127
+ return await deps.graphql(query, variables);
128
+ } catch (e) {
129
+ last = e;
130
+ if (attempt < 3) await deps.sleep(attempt * 2000);
131
+ }
132
+ }
133
+ throw new Refused(
134
+ "API_FAILED",
135
+ `GitHub's GraphQL API failed three times. The item may or may not be on the board and its Status is UNKNOWN — this run measured nothing. Last error: ${(last as Error)?.message ?? String(last)}`,
136
+ );
137
+ }
138
+
139
+ /** Which id a read asked `node(id:)` about, and whether a write had been sent before it. */
140
+ interface ReadSite {
141
+ what: string;
142
+ id: string;
143
+ /** What the id names, and the input it came from, so the refusal blames the right one. */
144
+ names: "the project" | "the item";
145
+ input: "PROJECT_ID" | "ITEM_ID";
146
+ /** The type the query's inline fragment selects; any other type resolves with no connection. */
147
+ type: "ProjectV2" | "ProjectV2Item";
148
+ wrote: boolean;
149
+ }
150
+
151
+ /**
152
+ * The connection under `node`, or a refusal naming the id that did not
153
+ * resolve. Every clause of the message is drawn from `site`, never written
154
+ * for one call site, so it is true at all three (review of PR #2194, which
155
+ * found a fixed clause wrong at a different site in rounds 2 and 4).
156
+ */
157
+ function requireNode<T>(data: unknown, key: "fields" | "fieldValues" | "items", site: ReadSite): Page<T> {
158
+ const node = (data as { node?: Record<string, unknown> | null } | null | undefined)?.node;
159
+ // A node that RESOLVED but carries no connection is a different object
160
+ // type: the inline fragment did not apply. Said apart from a null node,
161
+ // which is an id that did not resolve (#2183, from PR #2194 round 6).
162
+ if (node !== null && node !== undefined && node[key] === undefined) {
163
+ throw new Refused(
164
+ "WRONG_TYPE",
165
+ `${site.what} is UNMEASURED and ${site.wrote ? "a write WAS sent before this read, so the board may already hold the new value" : "nothing was written"}: node(id: ${site.id}) resolved, but not to a ${site.type}, so ${site.input} names a different kind of object (an item id passed as the project, for example). This is NOT a stale id and NOT an empty board.`,
166
+ );
167
+ }
168
+ const page = node?.[key] as Page<T> | null | undefined;
169
+ if (!page) {
170
+ throw new Refused(
171
+ "NULL_NODE",
172
+ `${site.what} is UNMEASURED and ${site.wrote ? "a write WAS sent before this read, so the board may already hold the new value" : "nothing was written"}: node(id: ${site.id}) came back null, so ${site.names} did not resolve — the id is stale, names an object this token cannot see, or ${site.input} is wrong. This is NOT a missing field, NOT an unset column and NOT an empty board.`,
173
+ );
174
+ }
175
+ return page;
176
+ }
177
+
178
+ const truncated = (page: Page<unknown>) => page.pageInfo?.hasNextPage === true;
179
+ const present = <T>(page: Page<T>): T[] => (page.nodes ?? []).filter((n): n is T => n !== null && n !== undefined);
180
+
181
+ /** Move `itemId` to `column` on `projectId`, verified in both readings, or say why not. */
182
+ export async function moveToColumn(input: MoveInput, deps: MoveDeps): Promise<MoveResult> {
183
+ const { projectId, itemId, column } = input;
184
+ try {
185
+ if (!itemId) {
186
+ throw new Refused(
187
+ "NO_ITEM",
188
+ "The add step produced no itemId, so there is nothing to move. The item was NOT added and its Status is UNSET — this is not a board that merely missed a transition.",
189
+ );
190
+ }
191
+
192
+ // The index is read with `status:"<column>"`, and a double quote cannot be
193
+ // carried inside that phrase, so a column holding one could never be seen
194
+ // in the index and every write would be misreported as lagging or
195
+ // overwritten. Refused before anything is written (review of PR #2194).
196
+ if (/["\\]/.test(column)) {
197
+ throw new Refused(
198
+ "COLUMN_UNSEARCHABLE",
199
+ `The column name ${JSON.stringify(column)} contains a double quote or a backslash, which the project search query status:"<column>" cannot carry, so whether the card renders could never be read. Nothing was written. Rename the column, or pass one without either character.`,
200
+ );
201
+ }
202
+
203
+ const fields = requireNode<{ id?: string; name?: string; options?: Array<{ id: string; name: string }> }>(
204
+ await call(deps, FIELDS_QUERY, { project: projectId }),
205
+ "fields",
206
+ { what: "the project's field list", id: projectId, names: "the project", input: "PROJECT_ID", type: "ProjectV2", wrote: false },
207
+ );
208
+ const status = present(fields).find(f => f.name === "Status");
209
+ const fieldId = status?.id ?? "";
210
+ const optionId = status?.options?.find(o => o.name === column)?.id ?? "";
211
+ if (!fieldId && truncated(fields)) {
212
+ throw new Refused(
213
+ "FIELDS_TRUNCATED",
214
+ "The first 50 fields on this project do not include one named 'Status', AND there are more fields beyond that page — so this read is UNMEASURED, not a missing field. Nothing was written. Do not rename anything on the strength of this message; page the fields query instead.",
215
+ );
216
+ }
217
+ if (!fieldId || !optionId) {
218
+ throw new Refused(
219
+ "NOT_RESOLVED",
220
+ `Could not resolve the Status field or its '${column}' option on this project. ${fieldId ? `The Status field was found and its options were read in full${truncated(fields) ? " (the field list has more than one page, which does not affect its options)" : ""}, so this is not a truncated read` : "The whole field list was read, so this is not a truncated page"}. The item WAS added; only the transition failed. Someone renamed the field or the column — update COLUMN in this workflow to match the board.`,
221
+ );
222
+ }
223
+
224
+ let current = "";
225
+ for (let attempt = 1; attempt <= 3; attempt++) {
226
+ await call(deps, WRITE_MUTATION, { project: projectId, item: itemId, field: fieldId, option: optionId });
227
+ // Let a concurrent built-in write land, so the read-back sees the settled value.
228
+ await deps.sleep(SETTLE_MS);
229
+
230
+ const values = requireNode<{ name?: string; field?: { name?: string } }>(
231
+ await call(deps, VALUES_QUERY, { item: itemId }),
232
+ "fieldValues",
233
+ { what: "the item's field values, read back after the write", id: itemId, names: "the item", input: "ITEM_ID", type: "ProjectV2Item", wrote: true },
234
+ );
235
+ current = present(values).find(v => v.field?.name === "Status")?.name ?? "";
236
+ if (!current && truncated(values)) {
237
+ throw new Refused(
238
+ "VALUES_TRUNCATED",
239
+ "Status was not among this item's first 50 field values and there are more beyond that page, so the read-back is UNMEASURED — the write may well have worked. This is NOT a competing writer and NOT an unset column. Page the fieldValues query.",
240
+ );
241
+ }
242
+
243
+ // The field value is not what the board draws: the board renders from a
244
+ // search index that can disagree with the item data.
245
+ const index = requireNode<{ id?: string }>(
246
+ await call(deps, INDEX_QUERY, { project: projectId, q: `status:"${column}"` }),
247
+ "items",
248
+ { what: `the search index for the '${column}' column`, id: projectId, names: "the project", input: "PROJECT_ID", type: "ProjectV2", wrote: true },
249
+ );
250
+ const indexed = present(index).some(n => n.id === itemId);
251
+ if (!indexed && truncated(index)) {
252
+ throw new Refused(
253
+ "INDEX_TRUNCATED",
254
+ `More than 100 items match '${column}' in the project's search index and this item was not in the first page, so its membership is UNMEASURED — it may well be indexed and rendering. Do not read this as a missing card. Page the index query.`,
255
+ );
256
+ }
257
+
258
+ if (current === column && indexed) {
259
+ return {
260
+ ok: true,
261
+ attempt,
262
+ message: `Moved to '${column}' on attempt ${attempt}, confirmed in BOTH the item's field value and the project's search index — so the card will actually render. This workflow owns only the opened->In review edge; merged->Done and closed->Done remain GitHub's built-in project workflows, so exactly one decider writes each transition.`,
263
+ };
264
+ }
265
+ deps.log(
266
+ current === column
267
+ ? `Attempt ${attempt}: the field value reads '${column}' but the search index does not carry this item yet, so the board would not draw it. Re-writing to prompt a re-index.`
268
+ : `Attempt ${attempt}: wrote '${column}', read back '${current || "(nothing)"}' — a concurrent write won. Retrying.`,
269
+ );
270
+ }
271
+
272
+ if (current === column) {
273
+ throw new Refused(
274
+ "INDEX_LAGGING",
275
+ `The Status field reads '${column}' but after three attempts the project's SEARCH INDEX still does not list this item under it, and the board draws from the index. The data is right and the card is invisible — do not 'fix' the Status, it is already correct. Re-writing the same value is what repairs the index entry; if three did not take, the index is lagging and this needs a human to re-check later.`,
276
+ );
277
+ }
278
+ throw new Refused(
279
+ "OVERWRITTEN",
280
+ `Wrote '${column}' three times and the board still reads '${current || "(nothing)"}'. Something else is writing this item's Status and winning: check the project's built-in workflows for a rule that also fires on a pull request being added. The item IS on the board; only its column is wrong.`,
281
+ );
282
+ } catch (e) {
283
+ if (e instanceof Refused) return { ok: false, reason: e.reason, message: e.message };
284
+ // Anything else is a response this module did not expect, or a fault in it:
285
+ // named, never a stack trace and never an answer (review of PR #2194).
286
+ return {
287
+ ok: false,
288
+ reason: "UNEXPECTED",
289
+ message: `An unexpected response or fault stopped the move, so the item's Status is UNKNOWN — a write may or may not have been sent. ${(e as Error)?.message ?? String(e)}`,
290
+ };
291
+ }
292
+ }
@@ -389,10 +389,17 @@ export function criteriaNamedBy(
389
389
  issue: { readonly title: string; readonly body?: string | null },
390
390
  criterionIds: readonly string[],
391
391
  ): string[] {
392
- const text = `${issue.title}\n${issue.body ?? ""}`;
393
- return criterionIds.filter(
394
- id => oneScMentionPattern(id).test(text) && !declaresOwnCriterion(text, id),
395
- );
392
+ const lines = `${issue.title}\n${issue.body ?? ""}`.split("\n");
393
+ // Scored per mention, not per text (#1683): one checkbox stating an id must
394
+ // not suppress a mention elsewhere that serves it. A declaring checkbox
395
+ // accounts for the one mention it opens with and no other, so a second
396
+ // mention on the same line still counts (review of PR #2190). The id is
397
+ // named when ANY mention is not the one a checkbox states.
398
+ return criterionIds.filter(id => {
399
+ const one = oneScMentionPattern(id);
400
+ const every = new RegExp(one.source, one.flags.includes("g") ? one.flags : `${one.flags}g`);
401
+ return lines.some(line => (line.match(every)?.length ?? 0) > (declaresOwnCriterion(line, id) ? 1 : 0));
402
+ });
396
403
  }
397
404
 
398
405
  /**
@@ -282,6 +282,23 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
282
282
  summary: "Print the board's node id from config",
283
283
  usage: "rungate board-id [--project-root <dir>] (UNMEASURED and exit 2 when the config names no board)",
284
284
  },
285
+ // #2193 (part 1 of #2183): the board-intake move step as a tested command.
286
+ // `board-intake.yml` switches to it in #2183, once a release carries it.
287
+ "board-intake-move": {
288
+ script: "scripts/board-intake-move.ts",
289
+ summary: "Move a board item to a column, verified in the item and in the board's search index",
290
+ usage: "rungate board-intake-move --project <node-id> --item <item-id> --column <name> (exit 1 naming the cause on every refusal)",
291
+ },
292
+ // #2100. The prose half of declared work: `board-conformance`'s
293
+ // `declared-work` reading covers criteria and stage items. No
294
+ // `projectRootFlag`: it reads `process.cwd()`, which the child inherits.
295
+ "unaccounted-work": {
296
+ script: "scripts/unaccounted-work.ts",
297
+ summary: "Report undone work declared in a repository's prose that no open issue covers",
298
+ usage:
299
+ "rungate unaccounted-work [--project-root <dir>] [--repo <owner/name>] [--issues-fixture <file.json>] [--json] " +
300
+ "(exit 1 when work is unaccounted, 2 when a source could not be read)",
301
+ },
285
302
  // Reads a `gh pr view`-shaped payload on stdin, which the dispatcher passes
286
303
  // through (`stdio: "inherit"`), or `--fixture` offline.
287
304
  "audit-closing-references": {
@@ -233,6 +233,67 @@ export function assertOneJudgementPerPair(adjudications: readonly Adjudication[]
233
233
  }
234
234
  }
235
235
 
236
+ /**
237
+ * Refuse a record naming a criterion no spec states (#1643).
238
+ *
239
+ * The lookup in {@link censusRows} is a strict `===`, so a typo (`SC-9110`
240
+ * for `SC-9101`) matches nothing and the row reads UNADJUDICATED while a
241
+ * judgement sits in the file. Shape and duplicates are checked per record and
242
+ * per store; this needs the spec set, so it runs where the specs are in hand.
243
+ * It asks whether a criterion EXISTS, not whether it is ticked: a judgement
244
+ * survives an untick and still applies when the tick returns.
245
+ *
246
+ * The ISSUE half is {@link orphanedAdjudications}, and it reports rather than
247
+ * refuses: the census reads open issues only, so a judged issue closing is the
248
+ * ordinary lifecycle, and a refusal there would stop the whole census on it
249
+ * (review of PR #2192).
250
+ */
251
+ export function assertAdjudicationsResolve(adjudications: readonly Adjudication[], specs: readonly SpecRef[]): void {
252
+ const stated = new Set<string>();
253
+ for (const spec of specs) {
254
+ if (isTemplateSpec(spec.file)) continue;
255
+ for (const c of parseCriteria(spec.content)) stated.add(c.id);
256
+ }
257
+ const problems = adjudications.flatMap((a, at) =>
258
+ stated.has(a.criterion) ? [] : [`adjudication record ${at} names ${a.criterion}, which no spec states`],
259
+ );
260
+ if (problems.length > 0) {
261
+ throw new Error(
262
+ `${problems.join("; ")}. A judgement on a criterion that does not exist is never applied, so it would read ` +
263
+ `as nobody having judged. Fix the record.`,
264
+ );
265
+ }
266
+ }
267
+
268
+ /** A judgement whose issue is not among the issues the census read. */
269
+ export interface OrphanedAdjudication {
270
+ at: number;
271
+ record: Adjudication;
272
+ }
273
+
274
+ /**
275
+ * The judgements naming an issue not among `issues` (#1643): closed since, or
276
+ * mistyped. Each applies to no row, so the census still runs, and each is
277
+ * printed beside the rows so a mistyped number sits next to the UNADJUDICATED
278
+ * row it was meant for instead of vanishing.
279
+ */
280
+ export function orphanedAdjudications(
281
+ adjudications: readonly Adjudication[],
282
+ issues: readonly IssueRef[],
283
+ ): OrphanedAdjudication[] {
284
+ const fetched = new Set(issues.map(i => i.number));
285
+ return adjudications.flatMap((record, at) => (fetched.has(record.issue) ? [] : [{ at, record }]));
286
+ }
287
+
288
+ /** One line per orphaned judgement, saying why it applies to nothing. */
289
+ export function renderOrphaned(orphans: readonly OrphanedAdjudication[]): string[] {
290
+ return orphans.map(
291
+ ({ at, record }) =>
292
+ `ORPHANED: adjudication record ${at} (${record.criterion}, #${record.issue}) names an issue that is not ` +
293
+ `open: closed since, or mistyped. It applies to no row; fix its number, or remove it if the issue closed.`,
294
+ );
295
+ }
296
+
236
297
  /** Does this issue name this criterion, on a word boundary? */
237
298
  export function issueNames(issue: IssueRef, id: string): boolean {
238
299
  const pattern = oneScMentionPattern(id);
@@ -254,6 +315,7 @@ export function censusRows(
254
315
  adjudications: readonly Adjudication[],
255
316
  ): CensusRow[] {
256
317
  assertOneJudgementPerPair(adjudications);
318
+ assertAdjudicationsResolve(adjudications, specs);
257
319
  const rows: CensusRow[] = [];
258
320
 
259
321
  for (const spec of specs) {
@@ -370,3 +370,99 @@ export function report(findings: ClosureFinding[], scanned: number): string {
370
370
  blocks.join("\n\n")
371
371
  );
372
372
  }
373
+
374
+ /**
375
+ * A merged pull request and the issues GitHub says it closes (#1952).
376
+ *
377
+ * `closes` is `null` when the node carried no `closingIssuesReferences` at
378
+ * all: a field nobody selected and a pull request that closes nothing are
379
+ * different readings, and only the second is clean.
380
+ */
381
+ export interface MergedCloser {
382
+ pull: number;
383
+ closes: { number: number; state: string }[] | null;
384
+ /** GitHub's own count, so a cut-short list is visible as one. */
385
+ closesTotal: number;
386
+ }
387
+
388
+ /**
389
+ * One merged pull request's GraphQL node, as the audit reads it.
390
+ *
391
+ * `repo` (`owner/name`) drops a closing reference into ANOTHER repository:
392
+ * GitHub resolves `Fixes other/repo#42` across repositories, and that issue
393
+ * is not this tracker's #42 (review of #2181; board-flow and work-status
394
+ * filter the same way). A node with no `repository` is kept, so a fixture
395
+ * written without it still reads.
396
+ */
397
+ export function toMergedCloser(node: any, repo?: string): MergedCloser {
398
+ const refs = node?.closingIssuesReferences;
399
+ if (!refs || !Array.isArray(refs.nodes)) return { pull: Number(node?.number), closes: null, closesTotal: 0 };
400
+ const here = (n: any): boolean => {
401
+ const r = n?.repository;
402
+ if (!repo || !r) return true;
403
+ return `${r.owner?.login}/${r.name}`.toLowerCase() === repo.toLowerCase();
404
+ };
405
+ const all = refs.nodes as any[];
406
+ const kept = all.filter(here);
407
+ return {
408
+ pull: Number(node.number),
409
+ closes: kept.map((n: any) => ({ number: Number(n?.number), state: String(n?.state ?? "") })),
410
+ // The cut is judged on GitHub's count against what was RETURNED, before the
411
+ // cross-repo filter, so a filtered reference never reads as a truncation.
412
+ closesTotal: Number(refs.totalCount ?? all.length) - (all.length - kept.length),
413
+ };
414
+ }
415
+
416
+ export interface OpenCloserReading {
417
+ /** Each issue still OPEN while a merged pull request names it as closed. */
418
+ open: { pull: number; issue: number }[];
419
+ /** Pull requests whose closing list could not be read whole. */
420
+ unmeasured: number[];
421
+ }
422
+
423
+ /**
424
+ * SC-2751: every issue still OPEN that a merged pull request's closing
425
+ * reference names, paired with that pull request.
426
+ *
427
+ * #1937 merged with `closingIssuesReferences` resolving to #1948 before and
428
+ * after the merge, and #1948 stayed OPEN. The close GitHub was meant to make
429
+ * did not happen, and the rules forbid making it by hand (#925), so the only
430
+ * correct response is to report it: the tracker otherwise says shipped work
431
+ * is outstanding. A list GitHub cut short, or a node with no list, is
432
+ * UNMEASURED rather than clean — the missing reference may be the open one.
433
+ */
434
+ export function openWithMergedCloser(pulls: readonly MergedCloser[]): OpenCloserReading {
435
+ const open: OpenCloserReading["open"] = [];
436
+ const unmeasured: number[] = [];
437
+ for (const p of pulls) {
438
+ if (p.closes === null || p.closesTotal > p.closes.length) unmeasured.push(p.pull);
439
+ for (const issue of p.closes ?? []) {
440
+ if (issue.state === "OPEN") open.push({ pull: p.pull, issue: issue.number });
441
+ }
442
+ }
443
+ return { open, unmeasured };
444
+ }
445
+
446
+ /** The reading as text, naming both numbers in every finding. Empty says so. */
447
+ export function openCloserReport(reading: OpenCloserReading, scanned: number): string {
448
+ const lines = [`Merged-closer audit: ${scanned} merged pull requests scanned.`];
449
+ if (reading.open.length === 0 && reading.unmeasured.length === 0) {
450
+ lines.push("none: every issue a merged pull request closes is closed.");
451
+ }
452
+ for (const f of reading.open) lines.push(`- #${f.issue} is OPEN, but #${f.pull} merged closing it`);
453
+ for (const n of reading.unmeasured) {
454
+ lines.push(`- UNMEASURED: #${n}'s closing references could not be read whole, so an open one may be missing`);
455
+ }
456
+ return lines.join("\n");
457
+ }
458
+
459
+ /**
460
+ * The merged pull requests a GraphQL response carries, or `null` when it
461
+ * carries no list at all. A response with no `repository`, or no
462
+ * `pullRequests`, is no reading, not an empty one (review of #2181): read as
463
+ * `[]` it would print "none" in exactly the no-data case.
464
+ */
465
+ export function mergedPullNodes(data: any): unknown[] | null {
466
+ const nodes = data?.repository?.pullRequests?.nodes;
467
+ return Array.isArray(nodes) ? nodes : null;
468
+ }
@@ -304,3 +304,21 @@ export function selectRecentSessions<T extends { date: string }>(
304
304
  );
305
305
  return { rendered: ranked.slice(0, limit).map(d => d.s), undated };
306
306
  }
307
+
308
+ /**
309
+ * How many priorities `PROJECT-STATE.md` renders (#1946). The renderer emitted
310
+ * one line per priority under SC-300's 200-line cap, so the next writer to
311
+ * record a priority had to delete one to push, under pressure and with no rule
312
+ * about what was safe to delete. Now the document shows the first ones in the
313
+ * order `project-state.json` lists them and says how many more the json holds,
314
+ * so recording state no longer grows the document that reports it.
315
+ */
316
+ export const RENDERED_PRIORITIES_MAX = 12;
317
+
318
+ /** The priorities to render, and how many were left in the json. Pure. */
319
+ export function boundedPriorities(
320
+ priorities: readonly string[],
321
+ max: number = RENDERED_PRIORITIES_MAX,
322
+ ): { shown: string[]; omitted: number } {
323
+ return { shown: priorities.slice(0, max), omitted: Math.max(0, priorities.length - max) };
324
+ }