rungate 0.8.7 → 0.8.10

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.
Files changed (49) hide show
  1. package/gates/.gate-salt +1 -1
  2. package/hooks/StaleTTLCleanup.hook.ts +13 -5
  3. package/hooks/VerifyPhaseLock.hook.ts +8 -0
  4. package/hooks/lib/findWorkflow.ts +19 -3
  5. package/lib/active-workflow.ts +57 -0
  6. package/lib/ai-review-rounds.ts +223 -10
  7. package/lib/ai-review-suppression.ts +80 -127
  8. package/lib/ai-review-threads.ts +182 -6
  9. package/lib/board-mirror.ts +438 -0
  10. package/lib/cli-commands.ts +133 -0
  11. package/lib/config-readers.ts +34 -0
  12. package/lib/crc-reading.ts +655 -0
  13. package/lib/criterion-issue-census.ts +325 -0
  14. package/lib/filing-plan.ts +381 -0
  15. package/lib/generators/agents-md.ts +15 -11
  16. package/lib/git-isolation.ts +32 -0
  17. package/lib/github.ts +66 -0
  18. package/lib/issue-decomposition.ts +523 -0
  19. package/lib/issue-filing-gate.ts +304 -19
  20. package/lib/issue-repair.ts +225 -0
  21. package/lib/live-issues.ts +442 -0
  22. package/lib/project-state-shape.ts +30 -0
  23. package/lib/prose-self-distance.ts +414 -0
  24. package/lib/review-tool-agreement.ts +364 -15
  25. package/lib/sc-ids.ts +31 -1
  26. package/lib/scaffold/ai-review-findings.ts +64 -3
  27. package/lib/scaffold/ai-review-step.ts +501 -82
  28. package/lib/scaffold/owned-files.ts +60 -2
  29. package/lib/scaffold/steps.ts +130 -4
  30. package/lib/spec-deps.ts +257 -0
  31. package/lib/spec-evidence.ts +479 -0
  32. package/lib/spec-placement.ts +430 -0
  33. package/lib/spec-template.ts +206 -0
  34. package/lib/stage-ladder.ts +628 -0
  35. package/lib/worktree-cleanup.ts +438 -3
  36. package/package.json +12 -4
  37. package/scripts/ai-review-findings.ts +12 -17
  38. package/scripts/ai-review-threads.ts +51 -3
  39. package/scripts/audit-spec-evidence.ts +246 -0
  40. package/scripts/audit-specs.ts +27 -0
  41. package/scripts/board-conformance.ts +765 -0
  42. package/scripts/board-mirror.ts +344 -0
  43. package/scripts/board-snapshot.ts +459 -0
  44. package/scripts/create-spec.ts +8 -34
  45. package/scripts/criterion-inventory.ts +649 -0
  46. package/scripts/extract-constraints.ts +108 -9
  47. package/scripts/plan-deps.ts +378 -0
  48. package/scripts/plan-issues.ts +701 -0
  49. package/scripts/plan-spec.ts +371 -0
@@ -8,36 +8,41 @@
8
8
  * unresolved set — so a repeat became *marked* rather than *dropped*. This is
9
9
  * the half that drops it.
10
10
  *
11
- * ## Why the prior state arrives as a file and not as a fetch
11
+ * ## Since AC-1 the prior set is the pull request's review threads
12
+ *
13
+ * The ledger keyed a repeat by `file + cited line text + summary`, which a
14
+ * reformat moves — measured on #1616 as 11 threads for 3 findings. A thread
15
+ * is GitHub's own answer to the same question, so AC-1 moved the gate onto
16
+ * it: `priorKeysFrom` reads the list the carry step fetched and nothing else.
17
+ * The ledger reader is kept as `ledgerPriorKeysFrom`, called by no production
18
+ * path, until AC-5 stops writing the snapshot it parses.
12
19
  *
13
- * The generated job runs `ai-review-carry` → the reviewer →
14
- * `ai-review-persist`, **which upserts this round into the ledger comment** →
15
- * `ai-review-run`, which invokes the adjudicator. A gate that fetched the
16
- * ledger itself would read a comment that already contains the payload it is
17
- * deciding about: every finding would match a "prior" key that is its own,
18
- * every round would suppress everything, and the outcome would be CLEAN
19
- * forever. The carry step is the last position holding the state as it was
20
- * before the reviewer ran, so it writes a snapshot and this reads it.
20
+ * ## Why the prior state arrives as a file and not as a fetch
21
21
  *
22
- * ## Two files, because one of them cannot say why it is absent
22
+ * Unchanged, and for a sharper reason than before. The generated job runs
23
+ * `ai-review-carry` → the reviewer → `ai-review-threads` (the poster, **which
24
+ * posts this round's threads**) → `ai-review-run` (this gate). So a fetch
25
+ * here would not be safe at all: by the time this gate runs, the poster has
26
+ * already opened this round's threads, and a live fetch would read them as
27
+ * prior, suppress the entire payload and report CLEAN forever.
23
28
  *
24
- * The snapshot carries BYTES and exists only on the READ path. The carry file
25
- * carries the STATE and is written on every path by the single `carry_state`
26
- * site. An absent snapshot therefore never means "no earlier findings" — the
27
- * carry file says which of `AI_REVIEW_CARRY_READ`, `AI_REVIEW_CARRY_ABSENT`
28
- * and `AI_REVIEW_CARRY_UNMEASURED` produced it. Collapsing those is #1568, in
29
- * the half that decides a required check.
29
+ * The file is what makes the gate correct, and it does not depend on where in
30
+ * a YAML file somebody put a step. The carry step runs before the reviewer,
31
+ * so the list it writes cannot contain this round's work whatever the later
32
+ * order becomes. `test/ai-review-suppression.test.ts` (AS-4) asserts the
33
+ * ordering that matters — `ai-review-carry` precedes both the poster and this
34
+ * gate — rather than the one this comment used to assert.
30
35
  *
31
36
  * ## Every refusal suppresses NOTHING
32
37
  *
33
38
  * There is one direction of error this module is allowed to make. Re-posting
34
39
  * an advisory that was already answered is loud, cheap and self-correcting;
35
- * dropping a finding that is still live is silent and permanent. So an
36
- * unreadable carry file, an unreadable snapshot, a stale snapshot, an
37
- * unrecognised identity rule and a ledger that will not parse all produce the
38
- * same behaviour — report everything — and each produces a DIFFERENT sentence
39
- * saying so, because "nothing was a repeat" and "nothing could be compared"
40
- * are different facts about this round's report.
40
+ * dropping a finding that is still live is silent and permanent. So a thread
41
+ * list that was never fetched, one that was cut off mid-write, and one that
42
+ * parsed into something that is not a list all produce the same behaviour —
43
+ * report everything — and each produces a DIFFERENT sentence saying so
44
+ * (AC-4), because "nothing was a repeat" and "nothing could be compared" are
45
+ * different facts about this round's report.
41
46
  *
42
47
  * ## It never sees a blocking finding
43
48
  *
@@ -56,6 +61,7 @@ import {
56
61
  readLedger,
57
62
  type ReviewFinding,
58
63
  } from "./ai-review-rounds";
64
+ import { threadReadingFromJson } from "./ai-review-threads";
59
65
  import {
60
66
  AI_REVIEW_CARRY_ABSENT,
61
67
  AI_REVIEW_CARRY_READ,
@@ -67,10 +73,12 @@ import type { AiReviewSuppressionGate } from "./scaffold/ai-review-findings";
67
73
 
68
74
  /** What the gate reads, so a test can drive it without a filesystem. */
69
75
  export interface SuppressionInputs {
70
- /** The carry file's contents, or `null` when it could not be read. */
71
- carry: string | null;
72
- /** The snapshot's contents, or `null` when it could not be read. */
73
- snapshot: string | null;
76
+ /**
77
+ * The review-thread list the carry step fetched, or `null` when the file
78
+ * was not there. Since AC-1 this is the ONLY thing the gate decides from —
79
+ * see `priorKeysFrom`.
80
+ */
81
+ threads: string | null;
74
82
  /** The text at a finding's cited line NOW, or `undefined`. */
75
83
  lineTextFor: (finding: ReviewFinding) => string | undefined;
76
84
  }
@@ -81,114 +89,59 @@ export type PriorKeys =
81
89
  | { status: "UNMEASURED"; reason: string };
82
90
 
83
91
  /**
84
- * The carry file's first line, which is the one site that decided the state.
92
+ * THE PRIOR SET, read from the pull request's own review threads (AC-1).
85
93
  *
86
- * Read rather than re-derived: the walker already made this decision against
87
- * the live API, and a second reading here would be a second decider over the
88
- * same question — which is the shape #1568 cost three rounds of #1569.
89
- */
90
- export function carryStateOf(carry: string | null): string | null {
91
- if (carry === null) return null;
92
- const first = carry.split("\n", 1)[0] ?? "";
93
- const prefix = `${AI_REVIEW_CARRY_STATE_KEY}=`;
94
- return first.startsWith(prefix) ? first.slice(prefix.length).trim() : null;
95
- }
96
-
97
- /**
98
- * Split the snapshot into the round it precedes and the ledger body.
94
+ * ## Why a thread and not the ledger
99
95
  *
100
- * `round` is `null` when the header is missing or not an integer, and that is
101
- * a REFUSAL rather than a default: a snapshot that cannot say which round it
102
- * precedes cannot be shown to predate this one.
103
- */
104
- export function readSnapshot(snapshot: string): { round: number | null; body: string } {
105
- const at = snapshot.indexOf("\n");
106
- const head = at === -1 ? snapshot : snapshot.slice(0, at);
107
- const body = at === -1 ? "" : snapshot.slice(at + 1);
108
- const prefix = `${AI_REVIEW_SNAPSHOT_ROUND_KEY}=`;
109
- if (!head.startsWith(prefix)) return { round: null, body };
110
- const raw = head.slice(prefix.length).trim();
111
- return { round: /^\d+$/.test(raw) ? Number(raw) : null, body };
112
- }
113
-
114
- /**
115
- * Turn the two files into the keys earlier rounds raised, or the sentence
116
- * saying they could not be established.
96
+ * The ledger answers "was this raised before?" with a text heuristic —
97
+ * `file + the text at the cited line + summary` — and a reformat moves the
98
+ * key, so round 4 cannot tell it is re-raising round 1's finding. Measured on
99
+ * #1616: **11 threads for 3 distinct findings**, re-raised across four rounds
100
+ * while the line numbers moved under them. A thread is the authoritative
101
+ * answer to the same question: the comment is on the pull request, or it is
102
+ * not.
103
+ *
104
+ * ## A RESOLVED thread is still a prior key
105
+ *
106
+ * This is the one place this reader and `carryForwardFromThreads` deliberately
107
+ * disagree, and the difference is the question each is asking:
108
+ *
109
+ * | Reader | Question | Resolved thread |
110
+ * |---|---|---|
111
+ * | this gate | has this already been **raised**? | yes — do not post it twice |
112
+ * | carry-forward | is this still **unanswered**? | no — a human answered it |
113
+ *
114
+ * A gate that treated resolution as "not raised" would re-post a thread the
115
+ * moment someone resolved it, which is the duplicate-per-round failure the
116
+ * whole increment exists to prevent, aimed at the people who are doing the
117
+ * work.
118
+ *
119
+ * ## Self-suppression is prevented by WHERE THE LIST IS FETCHED, not by a guard
120
+ *
121
+ * The ledger reader needed a provenance header because the ledger is written
122
+ * *during* the job, before the adjudicator reads it. Threads are no better on
123
+ * that count — `ai-review-threads` posts this round's threads BEFORE
124
+ * `ai-review-run` adjudicates, so a list fetched at adjudication time would
125
+ * contain them.
126
+ *
127
+ * What rules self-suppression out is that the list is not fetched here. It is
128
+ * fetched by `ai-review-carry`, which runs before the reviewer and therefore
129
+ * before anything this round could have posted, and handed to this gate as a
130
+ * file. That property lives in the workflow's step order and is asserted
131
+ * there; see `test/ai-review-suppression.test.ts` (AS-4), which pins
132
+ * `ai-review-carry` ahead of both the poster and the adjudicator.
117
133
  *
118
134
  * Exported and pure so the battery can drive every refusal without a
119
135
  * filesystem, and so there is one place to mutate.
120
136
  */
121
- export function priorKeysFrom(carry: string | null, snapshot: string | null): PriorKeys {
122
- const state = carryStateOf(carry);
123
- if (state === null) {
124
- return {
125
- status: "UNMEASURED",
126
- reason:
127
- "the carry step's own reading could not be read, so whether this pull request has " +
128
- "earlier rounds is unknown",
129
- };
130
- }
131
- if (state === AI_REVIEW_CARRY_UNMEASURED) {
132
- return {
133
- status: "UNMEASURED",
134
- reason: "the carry step reported that the pull request's history could not be read",
135
- };
136
- }
137
- // A complete reading, and the answer is that there is nothing to compare
138
- // against. MEASURED with no keys, which is not the same statement as the
139
- // branch above and must not print the same sentence.
140
- if (state === AI_REVIEW_CARRY_ABSENT) return { status: "MEASURED", keys: [] };
141
- if (state !== AI_REVIEW_CARRY_READ) {
142
- return {
143
- status: "UNMEASURED",
144
- reason: `the carry step reported a state this reader does not know (${JSON.stringify(state)})`,
145
- };
146
- }
147
-
148
- if (snapshot === null) {
149
- return {
150
- status: "UNMEASURED",
151
- reason:
152
- "the carry step read the pull request's history and the copy it left for this step " +
153
- "could not be read",
154
- };
155
- }
156
- const { round, body } = readSnapshot(snapshot);
157
- if (round === null) {
158
- return {
159
- status: "UNMEASURED",
160
- reason:
161
- "the history copy does not say which round it precedes, so it cannot be shown to " +
162
- "predate this round's own findings",
163
- };
164
- }
165
-
166
- const reading = priorFindings(readLedger(body));
167
- if (reading.status !== AI_REVIEW_PRIOR_MEASURED) {
137
+ export function priorKeysFrom(threads: string | null): PriorKeys {
138
+ const reading = threadReadingFromJson(threads);
139
+ if (reading.status !== "MEASURED") {
168
140
  return { status: "UNMEASURED", reason: reading.reason };
169
141
  }
170
-
171
- // THE ORDERING GUARD. A snapshot taken after the persist step is the same
172
- // comment fetched the same way and is byte-shaped like a correct one; the
173
- // only tell is that it already holds this round. Without this, the wrong
174
- // ordering suppresses the entire payload and reports CLEAN every round.
175
- const stale = reading.prior.filter(p => typeof p.round === "number" && p.round >= round);
176
- if (stale.length > 0) {
177
- return {
178
- status: "UNMEASURED",
179
- reason:
180
- `the history copy holds ${stale.length} finding(s) from round ${round} or later, so it ` +
181
- `was taken AFTER this round was recorded rather than before it. Suppressing against it ` +
182
- `would drop this round's own findings`,
183
- };
184
- }
185
-
186
- // `unmeasuredRounds` and `unkeyableRounds` are deliberately NOT a refusal.
187
- // Both mean the key set is INCOMPLETE, and an incomplete key set suppresses
188
- // less than a complete one — the direction this module is allowed to be
189
- // wrong in. Refusing on them would turn a partially readable history into
190
- // no history at all, which is the same report with a worse sentence.
191
- return { status: "MEASURED", keys: reading.keys };
142
+ // Open and resolved alike. The fold that distinguishes them belongs to
143
+ // carry-forward, for the reason tabled above.
144
+ return { status: "MEASURED", keys: reading.threads.map(t => t.key) };
192
145
  }
193
146
 
194
147
  /**
@@ -201,7 +154,7 @@ export function priorKeysFrom(carry: string | null, snapshot: string | null): Pr
201
154
  */
202
155
  export function aiReviewSuppressionGate(inputs: SuppressionInputs): AiReviewSuppressionGate {
203
156
  return (candidates: readonly unknown[]) => {
204
- const prior = priorKeysFrom(inputs.carry, inputs.snapshot);
157
+ const prior = priorKeysFrom(inputs.threads);
205
158
  if (prior.status === "UNMEASURED") {
206
159
  return { repeat: candidates.map(() => null), unmeasured: prior.reason };
207
160
  }
@@ -23,8 +23,115 @@
23
23
  * therefore reachable from a test over a recorded response, including the
24
24
  * two that only a live fork or a line outside a hunk would otherwise produce.
25
25
  */
26
- import { reviewThreadRequests, type AiReviewFindingsReading } from "./scaffold/ai-review-findings";
27
- import type { AiReviewThreadRequest } from "./scaffold/ai-review-findings";
26
+ import type { ThreadReading } from "./ai-review-rounds";
27
+ import { reviewThreadRequests, threadKeyFrom } from "./scaffold/ai-review-findings";
28
+ import type { AiReviewFindingsReading, AiReviewThreadRequest } from "./scaffold/ai-review-findings";
29
+
30
+ /**
31
+ * One review thread as the GraphQL query returns it, before anything is
32
+ * trusted about it. Both fields are `unknown`: a partial response drops
33
+ * fields rather than failing, so the shape is asserted here and nowhere else.
34
+ */
35
+ export interface RawReviewThread {
36
+ isResolved: unknown;
37
+ /** The body of the thread's FIRST comment — the one the poster wrote. */
38
+ body: unknown;
39
+ }
40
+
41
+ /**
42
+ * Turn what GitHub returned into the reading `carryForwardFromThreads` takes.
43
+ *
44
+ * @param raw the threads, or `null`/`undefined` when the list could not be
45
+ * read at all — a network failure, a missing token, a GraphQL error.
46
+ * @param reason what to call the unreadable case. Only used when `raw` is
47
+ * absent, and it is a parameter because the caller is the only thing that
48
+ * knows which way the fetch failed.
49
+ *
50
+ * ## An unmarked thread is DROPPED, not keyed to the empty string
51
+ *
52
+ * Only a thread carrying the #1618 marker names a finding. Every thread
53
+ * posted before #1618 and every thread a person opened carries none, and
54
+ * they are real threads that are not evidence about any finding. Collapsing
55
+ * them to `""` would make one resolved human comment answer every unkeyable
56
+ * finding on the pull request at once.
57
+ *
58
+ * ## Only the literal `true` is resolution
59
+ *
60
+ * A partial response drops fields rather than failing, and a finding answered
61
+ * by an omission is the silent direction of error. Anything that is not
62
+ * exactly `true` reads as open.
63
+ */
64
+ export function threadReading(
65
+ raw: readonly RawReviewThread[] | null | undefined,
66
+ reason: string,
67
+ ): ThreadReading {
68
+ if (raw === null || raw === undefined) return { status: "UNMEASURED", reason };
69
+ const threads: { key: string; isResolved: boolean }[] = [];
70
+ for (const t of raw) {
71
+ // A NULL NODE IS A THREAD, NOT A CRASH. A GraphQL connection returns a
72
+ // null node for an entry the token cannot see — a thread on a deleted
73
+ // file, or one hidden by a permission — and `t.body` on it throws a
74
+ // TypeError straight past this function's callers. That is the one
75
+ // failure mode this module is built to not have: an undecidable thread
76
+ // is dropped, which carries its finding, and the whole point is that the
77
+ // reading degrades rather than exploding. Dropping is also right on the
78
+ // merits — a node nobody can read names no finding and answers none.
79
+ if (t === null || typeof t !== "object") continue;
80
+ const key = threadKeyFrom(t.body);
81
+ if (key === null) continue;
82
+ threads.push({ key, isResolved: t.isResolved === true });
83
+ }
84
+ return { status: "MEASURED", threads };
85
+ }
86
+
87
+ /**
88
+ * The three ways the file on the runner can fail to be a thread list.
89
+ *
90
+ * One sentence per FACT, and no two facts share one. "Nobody fetched it",
91
+ * "the fetch was cut off mid-write" and "the fetch returned an error object
92
+ * instead of threads" are three different things to go and look at, and a
93
+ * reader that prints the same sentence for all three has told the next person
94
+ * only that something went wrong. Exported so a case can assert on the
95
+ * sentence rather than on a substring of it — a `toContain` goes green on a
96
+ * message that was narrowed to say less.
97
+ */
98
+ export const THREADS_NOT_READ =
99
+ "the pull request's review threads were not read, so whether a finding was already raised is unknown";
100
+ export const THREADS_UNPARSEABLE =
101
+ "the review-thread list was written but does not parse, so it was cut off or is not the list it claims to be";
102
+ export const THREADS_NOT_A_LIST =
103
+ "the review-thread list parsed and is not a list, which is the shape a GraphQL error response has";
104
+
105
+ /**
106
+ * The same reading, taken from the bytes a bash step left on the runner.
107
+ *
108
+ * `threadReading` takes parsed nodes because that is the shape a test can
109
+ * drive; this is the production path, and it exists so that the JSON parse —
110
+ * the one step between GitHub's answer and the decision — is somewhere a
111
+ * negative control can reach. Every failure produces a NAMED sentence and an
112
+ * UNMEASURED reading, never an empty list: an empty list is the assertion
113
+ * "this pull request has no threads", which suppresses nothing while claiming
114
+ * to have looked, and is exactly how a repeat-suppressor goes quietly dead.
115
+ *
116
+ * An empty STRING is absence, not a parse failure. A step that wrote no bytes
117
+ * and a step that wrote nothing are the same event seen twice.
118
+ */
119
+ export function threadReadingFromJson(text: string | null | undefined): ThreadReading {
120
+ if (text === null || text === undefined || text === "") {
121
+ return { status: "UNMEASURED", reason: THREADS_NOT_READ };
122
+ }
123
+ let parsed: unknown;
124
+ try {
125
+ parsed = JSON.parse(text);
126
+ } catch {
127
+ return { status: "UNMEASURED", reason: THREADS_UNPARSEABLE };
128
+ }
129
+ if (!Array.isArray(parsed)) return { status: "UNMEASURED", reason: THREADS_NOT_A_LIST };
130
+ // The per-node decisions stay in ONE place. A second loop here would be a
131
+ // second decider over "is this thread usable", and a mutation of either
132
+ // would leave the other holding every case up.
133
+ return threadReading(parsed as readonly RawReviewThread[], THREADS_NOT_READ);
134
+ }
28
135
 
29
136
  /**
30
137
  * The single non-zero exit. Declared once, so a mutant can set it to `0` and
@@ -45,6 +152,7 @@ export const AI_REVIEW_THREADS_REFUSAL = 1;
45
152
  * | `NOTHING_TO_POST` | 0 | no | the review located nothing to anchor |
46
153
  * | `UNMEASURED` | 0 | no | there was no reading to post FROM |
47
154
  * | `DEGRADED_NO_WRITE` | 0 | no | the token cannot write; see below |
155
+ * | `BLOCKED_BY_PENDING_REVIEW` | 0 | no | the pull request is locked; see below |
48
156
  * | `FAILED` | any | **yes** | the producer is broken |
49
157
  *
50
158
  * `UNMEASURED` is not a quieter `NOTHING_TO_POST`. A review that did not run
@@ -56,6 +164,7 @@ export type AiReviewThreadOutcome =
56
164
  | "NOTHING_TO_POST"
57
165
  | "UNMEASURED"
58
166
  | "DEGRADED_NO_WRITE"
167
+ | "BLOCKED_BY_PENDING_REVIEW"
59
168
  | "FAILED";
60
169
 
61
170
  /** What the API said. `status` is `null` for a failure that never got one. */
@@ -85,6 +194,33 @@ const UNPROCESSABLE = 422;
85
194
  /** HTTP 403 — the documented answer to a token without `pull-requests: write`. */
86
195
  const FORBIDDEN = 403;
87
196
 
197
+ /**
198
+ * The OTHER 422, and the reason the status code alone cannot be the branch.
199
+ *
200
+ * GitHub allows one pending review per identity per pull request. When a
201
+ * previous round left one open, every `createReviewComment` on that pull
202
+ * request answers 422 with this condition — and the identity is the job's own
203
+ * `github-actions[bot]`, so there is no UI anybody can clear it from.
204
+ *
205
+ * Matched on the condition rather than on the serialised body: the message is
206
+ * a JSON document the API is free to reformat, and a detector that a
207
+ * whitespace change defeats is the second shape in
208
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
209
+ */
210
+ const PENDING_REVIEW_CONDITION = /pending review/i;
211
+
212
+ /**
213
+ * One binding, so a mutation of it is observable. Both halves are required:
214
+ * the status narrows it to a validation refusal, the condition says WHICH —
215
+ * and the wrong direction here is the expensive one, because a false positive
216
+ * turns a genuinely broken producer into a green check.
217
+ */
218
+ function isPendingReviewRefusal(answer: AiReviewThreadResponse): boolean {
219
+ return (
220
+ !answer.ok && answer.status === UNPROCESSABLE && PENDING_REVIEW_CONDITION.test(answer.message)
221
+ );
222
+ }
223
+
88
224
  /**
89
225
  * Post every comment a reading calls for, and say which of the four
90
226
  * no-comment states this was if none appeared.
@@ -117,6 +253,7 @@ const FORBIDDEN = 403;
117
253
  export async function postReviewThreads(
118
254
  reading: AiReviewFindingsReading,
119
255
  post: AiReviewThreadPoster,
256
+ keyFor?: (finding: Record<string, unknown>) => string | null,
120
257
  ): Promise<AiReviewThreadsResult> {
121
258
  const detail: string[] = [];
122
259
 
@@ -127,7 +264,7 @@ export async function postReviewThreads(
127
264
  return { outcome: "UNMEASURED", attempted: 0, posted: 0, demoted: 0, detail };
128
265
  }
129
266
 
130
- const requests = reviewThreadRequests(reading);
267
+ const requests = reviewThreadRequests(reading, keyFor);
131
268
  if (requests.length === 0) {
132
269
  detail.push("the reading located no finding that could be anchored to a path in this diff");
133
270
  return { outcome: "NOTHING_TO_POST", attempted: 0, posted: 0, demoted: 0, detail };
@@ -136,12 +273,26 @@ export async function postReviewThreads(
136
273
  let posted = 0;
137
274
  let demoted = 0;
138
275
  let forbidden = 0;
276
+ let pending = 0;
139
277
  let failed = 0;
140
278
 
141
279
  for (const request of requests) {
142
280
  const where = request.line === null ? request.path : `${request.path}:${request.line}`;
143
281
  let answer = await post(request);
144
282
 
283
+ // Before the demotion, because the demotion cannot clear this one and a
284
+ // second request would buy a second identical 422. The lock is on the
285
+ // review, not on the anchor.
286
+ if (isPendingReviewRefusal(answer)) {
287
+ pending += 1;
288
+ detail.push(
289
+ `${where}: 422 — this pull request already holds a pending review by this identity, so no ` +
290
+ `comment can be added to it. That is a state of the pull request, not a finding this ` +
291
+ `producer got wrong; dropping to file level answers the same way.`,
292
+ );
293
+ continue;
294
+ }
295
+
145
296
  // The demotion, and only from a line. A file-level request that is
146
297
  // refused has nothing left to drop.
147
298
  if (!answer.ok && answer.status === UNPROCESSABLE && request.line !== null) {
@@ -166,15 +317,24 @@ export async function postReviewThreads(
166
317
  detail.push(`${where}: ${answer.status ?? "no status"} — ${answer.message}`);
167
318
  }
168
319
 
169
- // Order matters. A real failure outranks the fork excuse, and both outrank
170
- // a partial success — a round that posted three of four comments has lost
171
- // a finding and must say so.
320
+ // Order matters. A real failure outranks the fork excuse and the pending
321
+ // -review lock, and all three outrank a partial success — a round that
322
+ // posted three of four comments has lost a finding and must say so.
172
323
  if (failed > 0) {
173
324
  return { outcome: "FAILED", attempted: requests.length, posted, demoted, detail };
174
325
  }
175
326
  if (forbidden > 0) {
176
327
  return { outcome: "DEGRADED_NO_WRITE", attempted: requests.length, posted, demoted, detail };
177
328
  }
329
+ if (pending > 0) {
330
+ return {
331
+ outcome: "BLOCKED_BY_PENDING_REVIEW",
332
+ attempted: requests.length,
333
+ posted,
334
+ demoted,
335
+ detail,
336
+ };
337
+ }
178
338
  detail.push(
179
339
  `posted ${posted} review ${posted === 1 ? "comment" : "comments"}` +
180
340
  (demoted === 0 ? "" : `, ${demoted} at file level after a line was refused`),
@@ -182,6 +342,22 @@ export async function postReviewThreads(
182
342
  return { outcome: "POSTED", attempted: requests.length, posted, demoted, detail };
183
343
  }
184
344
 
345
+ /**
346
+ * How an annotation may open, given what actually reached the diff.
347
+ *
348
+ * Both non-refusing degradations — the fork token and the pending-review
349
+ * lock — are selected on a COUNT of refusals and never on `posted === 0`, so
350
+ * either can be reached with comments already posted. Both used to open by
351
+ * saying none were, one line below an accurate `posted N` summary. The claim
352
+ * is about the round, so it is derived from the round rather than written
353
+ * into each branch.
354
+ */
355
+ export function threadsLandedPhrase(result: AiReviewThreadsResult): string {
356
+ return result.posted === 0
357
+ ? "No review threads were created"
358
+ : `Only ${result.posted} of ${result.attempted} review threads were created`;
359
+ }
360
+
185
361
  /** The exit code a round's outcome earns. Only `FAILED` refuses. */
186
362
  export function aiReviewThreadsExitCode(result: AiReviewThreadsResult): number {
187
363
  return result.outcome === "FAILED" ? AI_REVIEW_THREADS_REFUSAL : 0;