rungate 0.8.8 → 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 (44) 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 +102 -9
  7. package/lib/ai-review-threads.ts +71 -3
  8. package/lib/board-mirror.ts +438 -0
  9. package/lib/cli-commands.ts +133 -0
  10. package/lib/config-readers.ts +34 -0
  11. package/lib/crc-reading.ts +655 -0
  12. package/lib/criterion-issue-census.ts +325 -0
  13. package/lib/filing-plan.ts +381 -0
  14. package/lib/generators/agents-md.ts +15 -11
  15. package/lib/git-isolation.ts +32 -0
  16. package/lib/github.ts +66 -0
  17. package/lib/issue-decomposition.ts +523 -0
  18. package/lib/issue-filing-gate.ts +304 -19
  19. package/lib/issue-repair.ts +225 -0
  20. package/lib/live-issues.ts +442 -0
  21. package/lib/project-state-shape.ts +30 -0
  22. package/lib/sc-ids.ts +31 -1
  23. package/lib/scaffold/ai-review-step.ts +222 -48
  24. package/lib/scaffold/owned-files.ts +60 -2
  25. package/lib/scaffold/steps.ts +130 -4
  26. package/lib/spec-deps.ts +257 -0
  27. package/lib/spec-evidence.ts +479 -0
  28. package/lib/spec-placement.ts +430 -0
  29. package/lib/spec-template.ts +206 -0
  30. package/lib/stage-ladder.ts +628 -0
  31. package/lib/worktree-cleanup.ts +438 -3
  32. package/package.json +12 -4
  33. package/scripts/ai-review-threads.ts +10 -1
  34. package/scripts/audit-spec-evidence.ts +246 -0
  35. package/scripts/audit-specs.ts +27 -0
  36. package/scripts/board-conformance.ts +765 -0
  37. package/scripts/board-mirror.ts +344 -0
  38. package/scripts/board-snapshot.ts +459 -0
  39. package/scripts/create-spec.ts +8 -34
  40. package/scripts/criterion-inventory.ts +649 -0
  41. package/scripts/extract-constraints.ts +108 -9
  42. package/scripts/plan-deps.ts +378 -0
  43. package/scripts/plan-issues.ts +701 -0
  44. package/scripts/plan-spec.ts +371 -0
package/gates/.gate-salt CHANGED
@@ -1 +1 @@
1
- aa5de92c18a7ad774cc3515f189890d60c365654621a8966ece5b0a3d5dff616
1
+ b3f611f4544c955941ff527106a0f7260cb49e435e814901388c5d79e5dbf9ad
@@ -75,15 +75,15 @@ if (PROJECT_ROOT) try {
75
75
 
76
76
  // Branch cleanup (#516, #1079). Thin trigger: lib/branch-cleanup.ts holds
77
77
  // every decision. This arm issues `git push origin --delete`, the one
78
- // irreversible thing this hook does and the only thing in it that reaches a
79
- // remote, at EVERY SessionStart from the shared checkout — so it is DISARMED
80
- // by default and signals nothing. Set RUNGATE_BRANCH_CLEANUP=1 to arm it.
78
+ // IRREVERSIBLE thing this hook does, at EVERY SessionStart from the shared
79
+ // checkout — DISARMED by default; set RUNGATE_BRANCH_CLEANUP=1 to arm. The
80
+ // rescue below reaches the remote too and IS armed: a delete destroys a
81
+ // commit's last copy, a push only creates a ref and never --forces.
81
82
  //
82
83
  // A disarmed arm and a run that could not resolve the repository both say so
83
84
  // by name: zero deletions has three causes here and only one is a clean
84
85
  // sweep. `.claude/rungate/hooks.json` names this arming and the #1079 slug
85
- // refusal as the two things that must BOTH hold before this hook may be
86
- // reconsidered for consumer deployment.
86
+ // refusal as the two that must BOTH hold before consumer deployment.
87
87
  if (PROJECT_ROOT) try {
88
88
  const { runBranchCleanupArm } = await import('../lib/branch-cleanup.ts');
89
89
  const br = await runBranchCleanupArm({ projectRoot: PROJECT_ROOT, maxAgeDays: 7 });
@@ -129,11 +129,19 @@ if (PROJECT_ROOT) try {
129
129
  }
130
130
  }
131
131
  } catch (e) { log(`GAP scan error: ${e}`); }
132
+ // Stranded work (#1038): a push CREATES a ref where the branch arm destroys one.
133
+ let rescued = 0;
134
+ if (PROJECT_ROOT) try {
135
+ const { rescueStrandedBranches, rescueReportLines } = await import('../lib/worktree-cleanup.ts');
136
+ const rs = rescueStrandedBranches(PROJECT_ROOT); rescued = rs.pushed.length;
137
+ for (const line of rescueReportLines(rs)) log(line);
138
+ } catch (e) { log(`STRANDED rescue error: ${e}`); }
132
139
 
133
140
  const parts: string[] = [];
134
141
  if (deletedCount > 0) parts.push(`${deletedCount} removed`);
135
142
  if (orphansSignalled > 0) parts.push(`${orphansSignalled} orphaned processes signalled`);
136
143
  if (gapWarns > 0) parts.push(`${gapWarns} gap warnings`);
144
+ if (rescued > 0) parts.push(`${rescued} stranded branch(es) pushed`);
137
145
  if (parts.length > 0) {
138
146
  console.log(`Stale TTL cleanup: ${parts.join(', ')}`);
139
147
  } else {
@@ -31,6 +31,7 @@ import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
31
31
  import { join } from 'path';
32
32
  import { parseHookInput } from './lib/parseStdin';
33
33
  import { verifyPhaseRefusal } from '../lib/issue-create-override';
34
+ import { isRunDirectory } from '../lib/active-workflow';
34
35
  import { filingGate, ledgerPath, recordAdjudication } from '../lib/issue-filing-gate';
35
36
 
36
37
  const WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(process.env.HOME!, '.rungate');
@@ -42,6 +43,10 @@ function findActiveWorkflow(): { path: string; data: any } | null {
42
43
  try {
43
44
  for (const entry of readdirSync(WORK_DIR, { withFileTypes: true })) {
44
45
  if (!entry.isDirectory()) continue;
46
+ // `.archive/<slug>/workflow-state.json` matches the nested shape below,
47
+ // so without this an ARCHIVED run decides the lock. One did, for eight
48
+ // days — see lib/active-workflow.ts for the reading.
49
+ if (!isRunDirectory(entry.name)) continue;
45
50
  const wfPath = join(WORK_DIR, entry.name, 'workflow-state.json');
46
51
  if (existsSync(wfPath)) {
47
52
  try {
@@ -56,6 +61,9 @@ function findActiveWorkflow(): { path: string; data: any } | null {
56
61
  try {
57
62
  for (const sub of readdirSync(nested, { withFileTypes: true })) {
58
63
  if (!sub.isDirectory()) continue;
64
+ // Both readings, or the defect survives one level deeper — see
65
+ // lib/active-workflow.ts, which holds the reading and the why.
66
+ if (!isRunDirectory(sub.name)) continue;
59
67
  const nestedWf = join(nested, sub.name, 'workflow-state.json');
60
68
  if (!existsSync(nestedWf)) continue;
61
69
  try {
@@ -9,8 +9,13 @@
9
9
 
10
10
  import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
11
11
  import { join } from 'path';
12
+ import { isRunDirectory } from '../../lib/active-workflow';
12
13
 
13
- const RUNGATE_WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.RUNGATE_WORK_DIR || join(process.env.HOME!, '.rungate');
14
+ // `PAI_WORK_DIR` second, as every sibling resolves it — VerifyPhaseLock,
15
+ // StaleTTLCleanup, AgentVerdictCapture and lib/issue-filing-gate.ts all read
16
+ // the same three in the same order. This file read RUNGATE_WORK_DIR twice,
17
+ // so a consumer still on the legacy variable silently got `~/.rungate`.
18
+ const RUNGATE_WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(process.env.HOME!, '.rungate');
14
19
 
15
20
  interface WorkflowState {
16
21
  path: string;
@@ -36,8 +41,18 @@ export function findWorkflowForIssue(issueNum?: string, phases?: string[], repo?
36
41
  };
37
42
 
38
43
  try {
44
+ // Hidden entries are the work dir's own bookkeeping, not runs — and
45
+ // `Priority 3` below is an mtime fallback, so `.archive`'s newest state
46
+ // file outranks every live run. That is #1648. Both levels, for the
47
+ // reason in lib/active-workflow.ts.
48
+ //
49
+ // Blast radius, since an earlier version of this comment got it wrong:
50
+ // `CommitEnforcement.hook.ts` is the ONLY hook importing this module.
51
+ // `IssueCloseGuard` and `AutoVerifyGate` use `findWorkflowState` from
52
+ // `./utils`, a third implementation of this scan that is still
53
+ // unfiltered — #1668. Fixing this file does not reach them.
39
54
  const dirs = readdirSync(RUNGATE_WORK_DIR, { withFileTypes: true })
40
- .filter(d => d.isDirectory());
55
+ .filter(d => d.isDirectory() && isRunDirectory(d.name));
41
56
 
42
57
  for (const d of dirs) {
43
58
  // Level 1: direct children
@@ -46,7 +61,8 @@ export function findWorkflowForIssue(issueNum?: string, phases?: string[], repo?
46
61
  // Level 2: nested subdirectories (e.g., pai/361)
47
62
  const subDir = join(RUNGATE_WORK_DIR, d.name);
48
63
  try {
49
- const subDirs = readdirSync(subDir, { withFileTypes: true }).filter(sd => sd.isDirectory());
64
+ const subDirs = readdirSync(subDir, { withFileTypes: true })
65
+ .filter(sd => sd.isDirectory() && isRunDirectory(sd.name));
50
66
  for (const sd of subDirs) {
51
67
  collectWorkflow(join(subDir, sd.name, 'workflow-state.json'), `${d.name}/${sd.name}`);
52
68
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Which directories under the work dir hold a LIVE run (#1648).
3
+ *
4
+ * `hooks/VerifyPhaseLock.hook.ts` picks the most recently modified
5
+ * `workflow-state.json` under `$RUNGATE_WORK_DIR` and refuses
6
+ * `gh issue create` when its phase is `VERIFY`. It scans each entry and then
7
+ * each entry's subdirectories, which is how a run nested one level deep is
8
+ * found — and it is also how `.archive/<slug>/workflow-state.json` is found,
9
+ * because `.archive` is just another directory to `readdirSync`.
10
+ *
11
+ * **Measured 2026-10-29 on this machine.** The newest state file anywhere
12
+ * under `~/.rungate` was
13
+ * `.archive/pai-harness-892/workflow-state.json`, modified 21 October, phase
14
+ * `VERIFY`. Three live run directories existed and none of them was in
15
+ * VERIFY: `pai-harness-169` DONE, `pai-harness-630` DONE, `pai-harness-65`
16
+ * GOAL. So every `gh issue create` reaching Bash on this machine had been
17
+ * refused for eight days on behalf of a run that finished, and the refusal
18
+ * named a `verifyBlockers[]` array in a file nobody was writing to.
19
+ *
20
+ * That is the worst failure mode a workflow gate has. It does not look like a
21
+ * bug — it looks like the gate working — and the documented way out is to
22
+ * apply an override label, so the pressure it creates is to mislabel issues.
23
+ * `lib/issue-create-override.ts` already records that happening once: #362,
24
+ * #363 and #364 all wear `follow-up` and none of them is follow-up work.
25
+ *
26
+ * ## The rule, and why it is about the dot and not about `.archive`
27
+ *
28
+ * A run directory is named for the slug of the run — `pai-harness-892`,
29
+ * `agentgrit-311`. Nothing names a run with a leading dot, and the work dir's
30
+ * own bookkeeping is what uses them. So the predicate is "not hidden" rather
31
+ * than "not `.archive`": a list of one name has to be extended by whoever adds
32
+ * the second kind of bookkeeping directory, and they will not know to.
33
+ *
34
+ * ## It has to guard BOTH readings
35
+ *
36
+ * The hook reads twice — `<run>/workflow-state.json` and
37
+ * `<run>/<sub>/workflow-state.json` — and the first version of this fix
38
+ * filtered only the outer one. That leaves the same defect one level deeper:
39
+ * a hidden bookkeeping directory INSIDE a live run is still read, and being
40
+ * written last it still outranks the live run by mtime.
41
+ *
42
+ * One filtered reading beside one unfiltered reading of the same question is
43
+ * the fourth shape in `.claude/rules/checks-must-be-able-to-fail.md`. No
44
+ * behavioural case can tell them apart while the outer one is right, so the
45
+ * end-to-end suite plants `<run>/.archive` directly and the mutation that
46
+ * removes the inner guard reddens exactly that case and no other.
47
+ */
48
+
49
+ /**
50
+ * Does this entry under the work directory hold a run that is still going?
51
+ *
52
+ * Hidden entries are the work dir's own bookkeeping, not runs. `.archive` is
53
+ * the one that exists today and the one that caused #1648.
54
+ */
55
+ export function isRunDirectory(name: string): boolean {
56
+ return !name.startsWith(".");
57
+ }
@@ -1301,21 +1301,72 @@ export function selectLedgerComment(
1301
1301
  * bare array would discard the history of every pull request mid-flight at
1302
1302
  * the moment the new writer merged.
1303
1303
  */
1304
- export function readLedger(body: unknown): LedgerReading {
1305
- if (typeof body !== "string") return { status: AI_REVIEW_LEDGER_ABSENT };
1306
- const marker = body.indexOf(AI_REVIEW_LEDGER_COMMENT_MARKER);
1307
- if (marker === -1) return { status: AI_REVIEW_LEDGER_ABSENT };
1304
+ export const LEDGER_PAYLOAD_FOUND = "LEDGER_PAYLOAD_FOUND";
1305
+ export const LEDGER_PAYLOAD_NO_MARKER = "LEDGER_PAYLOAD_NO_MARKER";
1306
+ export const LEDGER_PAYLOAD_NO_FENCE = "LEDGER_PAYLOAD_NO_FENCE";
1307
+ export const LEDGER_PAYLOAD_UNCLOSED = "LEDGER_PAYLOAD_UNCLOSED";
1308
+
1309
+ /**
1310
+ * Four arms, not two — one object type per status rather than one carrying a
1311
+ * union of three. TypeScript narrows a discriminated union by eliminating
1312
+ * ARMS, so three `if (status === …) return` checks against a single
1313
+ * three-literal arm eliminate none of it and `payload.text` stays an error.
1314
+ */
1315
+ export type LedgerPayload =
1316
+ | { readonly status: typeof LEDGER_PAYLOAD_FOUND; readonly text: string }
1317
+ | { readonly status: typeof LEDGER_PAYLOAD_NO_MARKER }
1318
+ | { readonly status: typeof LEDGER_PAYLOAD_NO_FENCE }
1319
+ | { readonly status: typeof LEDGER_PAYLOAD_UNCLOSED };
1308
1320
 
1321
+ /**
1322
+ * Where the ledger's JSON payload starts and stops. THE ONLY SITE.
1323
+ *
1324
+ * The fence rule is `indexOf("```json")` from the marker, then
1325
+ * `indexOf("\n```")` from there, and the obvious alternative —
1326
+ * `split("```json")[1].split("```")[0]` — is wrong on live data rather than
1327
+ * in theory: a ledger whose stored finding quotes a fenced code block is cut
1328
+ * at the quote. On 2026-10-27 that cut a 27,252-character ledger at 18,021,
1329
+ * and the text at the cut was a reviewer quoting the recipe that did the
1330
+ * cutting.
1331
+ *
1332
+ * It is one exported function because it was briefly two. #1633 round 6
1333
+ * found `readLedger` and `ledgerRawRounds` each computing these three
1334
+ * offsets, agreeing by convention with nothing enforcing it — the *two
1335
+ * deciders that agree* shape in `.claude/rules/checks-must-be-able-to-fail.md`,
1336
+ * where no behavioural test can tell them apart and a mutation of either
1337
+ * leaves the other holding the case up. They cannot now disagree, because
1338
+ * there is only one of them.
1339
+ *
1340
+ * `scripts/record-ai-review-unmeasured.ts` still cuts its own, because it
1341
+ * needs the whole DOCUMENT rather than the payload — it splices annotated
1342
+ * rounds back in, and the bare-array and `{rounds}` shapes are written back
1343
+ * differently. That one is a declared second decider and it is narrower:
1344
+ * it indexes from the start of the body rather than from the marker.
1345
+ */
1346
+ export function ledgerPayloadText(body: unknown): LedgerPayload {
1347
+ if (typeof body !== "string") return { status: LEDGER_PAYLOAD_NO_MARKER };
1348
+ const marker = body.indexOf(AI_REVIEW_LEDGER_COMMENT_MARKER);
1349
+ if (marker === -1) return { status: LEDGER_PAYLOAD_NO_MARKER };
1309
1350
  const fence = body.indexOf("```json", marker);
1310
- if (fence === -1) {
1351
+ if (fence === -1) return { status: LEDGER_PAYLOAD_NO_FENCE };
1352
+ const start = body.indexOf("\n", fence);
1353
+ const close = start === -1 ? -1 : body.indexOf("\n```", start);
1354
+ if (close === -1) return { status: LEDGER_PAYLOAD_UNCLOSED };
1355
+ return { status: LEDGER_PAYLOAD_FOUND, text: body.slice(start + 1, close) };
1356
+ }
1357
+
1358
+ export function readLedger(body: unknown): LedgerReading {
1359
+ const payload = ledgerPayloadText(body);
1360
+ if (payload.status === LEDGER_PAYLOAD_NO_MARKER) {
1361
+ return { status: AI_REVIEW_LEDGER_ABSENT };
1362
+ }
1363
+ if (payload.status === LEDGER_PAYLOAD_NO_FENCE) {
1311
1364
  return ledgerUnreadable(
1312
1365
  "the ledger comment is present and holds no ```json block, so the rounds it " +
1313
1366
  "recorded cannot be read; it is not being treated as an empty ledger",
1314
1367
  );
1315
1368
  }
1316
- const start = body.indexOf("\n", fence);
1317
- const close = start === -1 ? -1 : body.indexOf("\n```", start);
1318
- if (close === -1) {
1369
+ if (payload.status === LEDGER_PAYLOAD_UNCLOSED) {
1319
1370
  return ledgerUnreadable(
1320
1371
  "the ledger comment's ```json block is not closed, so it was truncated in " +
1321
1372
  "transit or in storage and the rounds it recorded cannot be read",
@@ -1324,7 +1375,7 @@ export function readLedger(body: unknown): LedgerReading {
1324
1375
 
1325
1376
  let parsed: unknown;
1326
1377
  try {
1327
- parsed = JSON.parse(body.slice(start + 1, close));
1378
+ parsed = JSON.parse(payload.text);
1328
1379
  } catch (e) {
1329
1380
  return ledgerUnreadable(
1330
1381
  `the ledger comment's JSON block could not be parsed (${
@@ -1363,6 +1414,48 @@ export function readLedger(body: unknown): LedgerReading {
1363
1414
  };
1364
1415
  }
1365
1416
 
1417
+ /**
1418
+ * The ledger's round entries **as written**, for readers that need a field
1419
+ * `LedgerRound` does not carry.
1420
+ *
1421
+ * `readLedger` is the reading; this is the same bytes with nothing dropped.
1422
+ * The `unmeasured` key is the case that forced it — `lib/ai-review-unmeasured.ts`
1423
+ * adds it in a second pass and `toLedgerRound` has no slot for it, so counting
1424
+ * how many rounds were `declined` rather than `no_payload` means going back to
1425
+ * the entry.
1426
+ *
1427
+ * **It does not compute the fence** — `ledgerPayloadText` does, for this and
1428
+ * for `readLedger` both, so the two cannot disagree about where the payload
1429
+ * is (#1633 round 6).
1430
+ *
1431
+ * `null` means `readLedger` would not have returned READ either — absent,
1432
+ * unfenced, unparseable, or an object with no `rounds` array. A caller wanting
1433
+ * to know WHICH should ask `readLedger`; this answers only "hand me the
1434
+ * entries".
1435
+ *
1436
+ * **IT CANNOT THROW**, and the reason is structural rather than a catch. A
1437
+ * reader of a RANGE calls it once per pull request,
1438
+ * and an exception from one of them would abort the whole reading and lose
1439
+ * the other forty-five — the exact failure the jq recipe this replaces had.
1440
+ * Refusing one entry costs one `UNMEASURED` line.
1441
+ */
1442
+ export function ledgerRawRounds(body: unknown): unknown[] | null {
1443
+ if (readLedger(body).status !== AI_REVIEW_LEDGER_READ) return null;
1444
+ const payload = ledgerPayloadText(body);
1445
+ /* c8 ignore next — narrowing the union; a READ reading implies FOUND. */
1446
+ if (payload.status !== LEDGER_PAYLOAD_FOUND) return null;
1447
+ // No try/catch, deliberately. READ means `readLedger` already parsed THIS
1448
+ // STRING — the same bytes from the same function — so a catch here could
1449
+ // never fire, and a guard against a state nothing can produce is a guard
1450
+ // no test can prove (`.claude/rules/checks-must-be-able-to-fail.md`). What
1451
+ // makes the throw impossible is the single fence site, and that is
1452
+ // asserted rather than defended against.
1453
+ const parsed: unknown = JSON.parse(payload.text);
1454
+ if (Array.isArray(parsed)) return parsed;
1455
+ const rounds = (parsed as Record<string, unknown>)[AI_REVIEW_LEDGER_ROUNDS_KEY];
1456
+ return Array.isArray(rounds) ? rounds : null;
1457
+ }
1458
+
1366
1459
  /**
1367
1460
  * How deep a legacy bare-array ledger is, derived from its length (#1447).
1368
1461
  *
@@ -152,6 +152,7 @@ export const AI_REVIEW_THREADS_REFUSAL = 1;
152
152
  * | `NOTHING_TO_POST` | 0 | no | the review located nothing to anchor |
153
153
  * | `UNMEASURED` | 0 | no | there was no reading to post FROM |
154
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 |
155
156
  * | `FAILED` | any | **yes** | the producer is broken |
156
157
  *
157
158
  * `UNMEASURED` is not a quieter `NOTHING_TO_POST`. A review that did not run
@@ -163,6 +164,7 @@ export type AiReviewThreadOutcome =
163
164
  | "NOTHING_TO_POST"
164
165
  | "UNMEASURED"
165
166
  | "DEGRADED_NO_WRITE"
167
+ | "BLOCKED_BY_PENDING_REVIEW"
166
168
  | "FAILED";
167
169
 
168
170
  /** What the API said. `status` is `null` for a failure that never got one. */
@@ -192,6 +194,33 @@ const UNPROCESSABLE = 422;
192
194
  /** HTTP 403 — the documented answer to a token without `pull-requests: write`. */
193
195
  const FORBIDDEN = 403;
194
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
+
195
224
  /**
196
225
  * Post every comment a reading calls for, and say which of the four
197
226
  * no-comment states this was if none appeared.
@@ -244,12 +273,26 @@ export async function postReviewThreads(
244
273
  let posted = 0;
245
274
  let demoted = 0;
246
275
  let forbidden = 0;
276
+ let pending = 0;
247
277
  let failed = 0;
248
278
 
249
279
  for (const request of requests) {
250
280
  const where = request.line === null ? request.path : `${request.path}:${request.line}`;
251
281
  let answer = await post(request);
252
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
+
253
296
  // The demotion, and only from a line. A file-level request that is
254
297
  // refused has nothing left to drop.
255
298
  if (!answer.ok && answer.status === UNPROCESSABLE && request.line !== null) {
@@ -274,15 +317,24 @@ export async function postReviewThreads(
274
317
  detail.push(`${where}: ${answer.status ?? "no status"} — ${answer.message}`);
275
318
  }
276
319
 
277
- // Order matters. A real failure outranks the fork excuse, and both outrank
278
- // a partial success — a round that posted three of four comments has lost
279
- // 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.
280
323
  if (failed > 0) {
281
324
  return { outcome: "FAILED", attempted: requests.length, posted, demoted, detail };
282
325
  }
283
326
  if (forbidden > 0) {
284
327
  return { outcome: "DEGRADED_NO_WRITE", attempted: requests.length, posted, demoted, detail };
285
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
+ }
286
338
  detail.push(
287
339
  `posted ${posted} review ${posted === 1 ? "comment" : "comments"}` +
288
340
  (demoted === 0 ? "" : `, ${demoted} at file level after a line was refused`),
@@ -290,6 +342,22 @@ export async function postReviewThreads(
290
342
  return { outcome: "POSTED", attempted: requests.length, posted, demoted, detail };
291
343
  }
292
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
+
293
361
  /** The exit code a round's outcome earns. Only `FAILED` refuses. */
294
362
  export function aiReviewThreadsExitCode(result: AiReviewThreadsResult): number {
295
363
  return result.outcome === "FAILED" ? AI_REVIEW_THREADS_REFUSAL : 0;