rungate 0.8.27 → 0.8.29

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 (37) hide show
  1. package/bin/rungate.ts +5 -1
  2. package/gates/.gate-salt +1 -1
  3. package/lib/ai-review-threads.ts +258 -9
  4. package/lib/blocked-by-write.ts +95 -0
  5. package/lib/cli-commands.ts +29 -1
  6. package/lib/config-trackable.ts +91 -6
  7. package/lib/consumer-triage.ts +214 -0
  8. package/lib/finding-promotion.ts +37 -4
  9. package/lib/generators/agents-md.ts +68 -0
  10. package/lib/issue-decomposition.ts +85 -16
  11. package/lib/issue-filing-gate.ts +84 -23
  12. package/lib/live-issues.ts +5 -0
  13. package/lib/scaffold/adr-accepted-workflow.ts +5 -6
  14. package/lib/scaffold/board-project-step.ts +49 -0
  15. package/lib/scaffold/consumer-intake-workflow.ts +176 -0
  16. package/lib/scaffold/human-steps.ts +39 -3
  17. package/lib/scaffold/owned-files.ts +10 -0
  18. package/lib/scaffold/spec-scope.ts +228 -0
  19. package/lib/scaffold/specs-placed-workflow.ts +2 -5
  20. package/lib/scaffold/steps.ts +13 -1
  21. package/lib/scaffold/write-steps.ts +9 -1
  22. package/lib/spec-placement.ts +52 -0
  23. package/lib/success-doc.ts +1 -1
  24. package/lib/write-spec.ts +23 -3
  25. package/package.json +3 -1
  26. package/scripts/ai-review-threads.ts +102 -8
  27. package/scripts/board-conformance.ts +99 -0
  28. package/scripts/board-scope.ts +6 -3
  29. package/scripts/board-snapshot.ts +57 -2
  30. package/scripts/consumer-triage.ts +235 -0
  31. package/scripts/create-sc.ts +8 -6
  32. package/scripts/finding-promotion.ts +10 -6
  33. package/scripts/plan-deps.ts +58 -8
  34. package/scripts/plan-issues.ts +56 -6
  35. package/scripts/status-view.ts +955 -0
  36. package/scripts/sync-sc-status.ts +102 -12
  37. package/templates/process/adr-template.md +4 -1
package/bin/rungate.ts CHANGED
@@ -74,7 +74,11 @@ if (!existsSync(script)) {
74
74
  // Only added when the caller did not say otherwise, and only for commands
75
75
  // that accept the flag — a script that does not would read it as a
76
76
  // positional argument.
77
- const needsRoot = command.projectRootFlag && !rest.includes("--project-root");
77
+ // Either spelling counts as the caller saying so: `--project-root=<dir>` read
78
+ // as absent appended the cwd AFTER it, and a last-one-wins reader then took
79
+ // the cwd over the directory the caller named (review of #2365).
80
+ const givesRoot = rest.some(a => a === "--project-root" || a.startsWith("--project-root="));
81
+ const needsRoot = command.projectRootFlag && !givesRoot;
78
82
  const args = needsRoot ? [...rest, "--project-root", process.cwd()] : rest;
79
83
 
80
84
  // Run the script as an ENTRY MODULE, so `import.meta.main` is true inside it
package/gates/.gate-salt CHANGED
@@ -1 +1 @@
1
- c383a2a597db75009eb5771282d36d447270d59c07518a035e13962da1d45801
1
+ fa34c4041cab9c794b569ed4daed02557ad6f40c70974e16108c7011328b5ce0
@@ -24,6 +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 { nextCursor } from "./graphql-cursor";
27
28
  import { escapeAnnotation, reviewThreadRequests, threadKeyFrom } from "./scaffold/ai-review-findings";
28
29
  import type { AiReviewFindingsReading, AiReviewThreadRequest } from "./scaffold/ai-review-findings";
29
30
 
@@ -167,10 +168,59 @@ export type AiReviewThreadOutcome =
167
168
  | "BLOCKED_BY_PENDING_REVIEW"
168
169
  | "FAILED";
169
170
 
170
- /** What the API said. `status` is `null` for a failure that never got one. */
171
+ /**
172
+ * One entry of a refusal's structured `errors[]` (#2363). GitHub sends objects
173
+ * naming a `field` and a `code`, or bare strings, which arrive here as
174
+ * `{ message }`.
175
+ */
176
+ export interface AiReviewApiError {
177
+ field?: string;
178
+ code?: string;
179
+ message?: string;
180
+ }
181
+
182
+ /**
183
+ * What the API said. `status` is `null` for a failure that never got one.
184
+ * `errors` is the structured body when the refusal carried one; absent, the
185
+ * classifiers fall back to the message text.
186
+ */
171
187
  export type AiReviewThreadResponse =
172
188
  | { ok: true }
173
- | { ok: false; status: number | null; message: string };
189
+ | { ok: false; status: number | null; message: string; errors?: AiReviewApiError[] };
190
+
191
+ /**
192
+ * A thrown Octokit error as a refusal, keeping `response.data.errors` (#2363).
193
+ * The status and message alone threw away the one part GitHub states as data,
194
+ * which left every classifier matching serialized text.
195
+ */
196
+ export function refusalFrom(e: unknown): Extract<AiReviewThreadResponse, { ok: false }> {
197
+ const err = e as { status?: unknown; message?: unknown; response?: { data?: { errors?: unknown } } };
198
+ const status = typeof err.status === "number" ? err.status : null;
199
+ const message = typeof err.message === "string" ? err.message : String(e);
200
+ const raw = err.response?.data?.errors;
201
+ if (!Array.isArray(raw)) return { ok: false, status, message };
202
+ const errors: AiReviewApiError[] = raw.map(x => {
203
+ if (typeof x === "string") return { message: x };
204
+ const o = (x ?? {}) as Record<string, unknown>;
205
+ return {
206
+ ...(typeof o.field === "string" ? { field: o.field } : {}),
207
+ ...(typeof o.code === "string" ? { code: o.code } : {}),
208
+ ...(typeof o.message === "string" ? { message: o.message } : {}),
209
+ };
210
+ });
211
+ return { ok: false, status, message, errors };
212
+ }
213
+
214
+ /**
215
+ * The pull-request-level fallback (#2338): a finding GitHub refuses at the line
216
+ * AND at the file goes here instead of being lost. `existing` is every body
217
+ * already on the pull request's conversation, so a later round does not post
218
+ * the same finding again.
219
+ */
220
+ export interface AiReviewPullCommenter {
221
+ post: (body: string) => Promise<AiReviewThreadResponse>;
222
+ existing: readonly string[];
223
+ }
174
224
 
175
225
  /** Sends one comment. The only thing in this module that touches a network. */
176
226
  export type AiReviewThreadPoster = (
@@ -185,6 +235,8 @@ export interface AiReviewThreadsResult {
185
235
  posted: number;
186
236
  /** Of those, how many only succeeded after dropping to file level. */
187
237
  demoted: number;
238
+ /** Of those, how many went on the conversation because GitHub refused the file too (#2338). */
239
+ pullComments: number;
188
240
  /** One sentence per thing worth reading, in the order it happened. */
189
241
  detail: string[];
190
242
  }
@@ -209,6 +261,41 @@ const FORBIDDEN = 403;
209
261
  */
210
262
  const PENDING_REVIEW_CONDITION = /pending review/i;
211
263
 
264
+ /**
265
+ * The 422 that means "this path is not in the pull request's diff" — GitHub
266
+ * names the FIELD, either as `pull_request_review_thread.path` (the #1740
267
+ * reading: `… .path "could not be resolved"`) or as `"field":"path"` in its
268
+ * errors array. The bare word "path" anywhere in a message is not that
269
+ * (review of #2358): any other 422, a stale `commit_id` among them, is a
270
+ * request this producer got wrong and stays a failure rather than moving to
271
+ * the conversation.
272
+ */
273
+ const OFF_DIFF_CONDITION = /pull_request_review_thread\.path\b|"field"\s*:\s*"path"/;
274
+
275
+ /** The fields a refusal's structured body names, or `null` when it names none. */
276
+ function fieldsNamed(answer: Extract<AiReviewThreadResponse, { ok: false }>): string[] | null {
277
+ const fields = (answer.errors ?? []).flatMap(e => (e.field === undefined ? [] : [e.field]));
278
+ return fields.length === 0 ? null : fields;
279
+ }
280
+
281
+ /** Every piece of text a refusal carries: its message and each error's message. */
282
+ function refusalText(answer: Extract<AiReviewThreadResponse, { ok: false }>): string {
283
+ return [answer.message, ...(answer.errors ?? []).flatMap(e => (e.message === undefined ? [] : [e.message]))].join("\n");
284
+ }
285
+
286
+ /**
287
+ * The off-diff 422 (#2338), decided from `errors[].field` when GitHub named
288
+ * one (#2363): `path`, or a dotted name ending in `.path`, is off-diff and
289
+ * any other field is not, whatever the message says. With no field named, the
290
+ * text decides — the message and each error's own message — through {@link OFF_DIFF_CONDITION}.
291
+ */
292
+ function isOffDiffRefusal(answer: AiReviewThreadResponse): boolean {
293
+ if (answer.ok || answer.status !== UNPROCESSABLE) return false;
294
+ const fields = fieldsNamed(answer);
295
+ if (fields !== null) return fields.some(f => f === "path" || f.endsWith(".path"));
296
+ return OFF_DIFF_CONDITION.test(refusalText(answer));
297
+ }
298
+
212
299
  /**
213
300
  * One binding, so a mutation of it is observable. Both halves are required:
214
301
  * the status narrows it to a validation refusal, the condition says WHICH —
@@ -217,7 +304,7 @@ const PENDING_REVIEW_CONDITION = /pending review/i;
217
304
  */
218
305
  function isPendingReviewRefusal(answer: AiReviewThreadResponse): boolean {
219
306
  return (
220
- !answer.ok && answer.status === UNPROCESSABLE && PENDING_REVIEW_CONDITION.test(answer.message)
307
+ !answer.ok && answer.status === UNPROCESSABLE && PENDING_REVIEW_CONDITION.test(refusalText(answer))
221
308
  );
222
309
  }
223
310
 
@@ -255,6 +342,7 @@ export async function postReviewThreads(
255
342
  post: AiReviewThreadPoster,
256
343
  keyFor?: (finding: Record<string, unknown>) => string | null,
257
344
  fork?: boolean | null,
345
+ comment?: AiReviewPullCommenter,
258
346
  ): Promise<AiReviewThreadsResult> {
259
347
  const detail: string[] = [];
260
348
 
@@ -262,17 +350,21 @@ export async function postReviewThreads(
262
350
  detail.push(
263
351
  "the review produced no usable reading, so there was nothing to post — this is not a review that found nothing",
264
352
  );
265
- return { outcome: "UNMEASURED", attempted: 0, posted: 0, demoted: 0, detail };
353
+ return { outcome: "UNMEASURED", attempted: 0, posted: 0, demoted: 0, pullComments: 0, detail };
266
354
  }
267
355
 
268
356
  const requests = reviewThreadRequests(reading, keyFor);
269
357
  if (requests.length === 0) {
270
358
  detail.push("the reading located no finding that could be anchored to a path in this diff");
271
- return { outcome: "NOTHING_TO_POST", attempted: 0, posted: 0, demoted: 0, detail };
359
+ return { outcome: "NOTHING_TO_POST", attempted: 0, posted: 0, demoted: 0, pullComments: 0, detail };
272
360
  }
273
361
 
274
362
  let posted = 0;
275
363
  let demoted = 0;
364
+ let pullComments = 0;
365
+ const alreadyOnConversation = new Set((comment?.existing ?? []).map(threadKeyFrom).filter((k): k is string => k !== null));
366
+ /** Keys this call put on the conversation, so a repeat can say WHEN (review of #2358). */
367
+ const postedThisRound = new Set<string>();
276
368
  let forbidden = 0;
277
369
  let pending = 0;
278
370
  let failed = 0;
@@ -302,6 +394,56 @@ export async function postReviewThreads(
302
394
  if (answer.ok) demoted += 1;
303
395
  }
304
396
 
397
+ // #2338: refused at the file too. The path is not in this pull request's
398
+ // diff as GitHub sees it (a branch behind its base is the measured cause),
399
+ // so the finding goes on the conversation rather than nowhere.
400
+ if (
401
+ !answer.ok &&
402
+ answer.status === UNPROCESSABLE &&
403
+ comment !== undefined &&
404
+ !isPendingReviewRefusal(answer) &&
405
+ isOffDiffRefusal(answer)
406
+ ) {
407
+ const key = threadKeyFrom(request.body);
408
+ if (key !== null && alreadyOnConversation.has(key)) {
409
+ posted += 1;
410
+ pullComments += 1;
411
+ const when = postedThisRound.has(key) ? "earlier in this round" : "from an earlier round";
412
+ detail.push(`${where}: not in this pull request's diff, and already on its conversation ${when}, so not posted again`);
413
+ continue;
414
+ }
415
+ const viaConversation = await comment.post(
416
+ `**\`${where}\` is not in this pull request's diff, so this finding could not go on it.** ` +
417
+ `GitHub refused it ${request.line === null ? "at the file" : "at the line and at the file"}. ` +
418
+ `The branch may be behind its base; rebasing usually puts the file back in the diff.\n\n` +
419
+ request.body,
420
+ );
421
+ if (viaConversation.ok) {
422
+ // Within the round too: a second finding with this key is the same finding (review of #2358).
423
+ if (key !== null) {
424
+ alreadyOnConversation.add(key);
425
+ postedThisRound.add(key);
426
+ }
427
+ posted += 1;
428
+ pullComments += 1;
429
+ detail.push(`${where}: not in this pull request's diff (422 ${request.line === null ? "at the file" : "at the line and at the file"}), so it was posted on the conversation instead`);
430
+ continue;
431
+ }
432
+ // A 403 here is the token, not the finding: the fork branch below
433
+ // decides it exactly as it decides a refused review comment (review of
434
+ // #2358 — a fork's read-only token must degrade, never fail).
435
+ if (!viaConversation.ok && viaConversation.status === FORBIDDEN) {
436
+ answer = viaConversation;
437
+ } else {
438
+ failed += 1;
439
+ detail.push(
440
+ `${where}: not in this pull request's diff (422 ${request.line === null ? "at the file" : "at the line and at the file"}), and the conversation comment was refused too: ` +
441
+ `${viaConversation.status ?? "no status"} — ${viaConversation.message}`,
442
+ );
443
+ continue;
444
+ }
445
+ }
446
+
305
447
  if (answer.ok) {
306
448
  posted += 1;
307
449
  continue;
@@ -336,10 +478,10 @@ export async function postReviewThreads(
336
478
  // -review lock, and all three outrank a partial success — a round that
337
479
  // posted three of four comments has lost a finding and must say so.
338
480
  if (failed > 0) {
339
- return { outcome: "FAILED", attempted: requests.length, posted, demoted, detail };
481
+ return { outcome: "FAILED", attempted: requests.length, posted, demoted, pullComments, detail };
340
482
  }
341
483
  if (forbidden > 0) {
342
- return { outcome: "DEGRADED_NO_WRITE", attempted: requests.length, posted, demoted, detail };
484
+ return { outcome: "DEGRADED_NO_WRITE", attempted: requests.length, posted, demoted, pullComments, detail };
343
485
  }
344
486
  if (pending > 0) {
345
487
  return {
@@ -347,14 +489,16 @@ export async function postReviewThreads(
347
489
  attempted: requests.length,
348
490
  posted,
349
491
  demoted,
492
+ pullComments,
350
493
  detail,
351
494
  };
352
495
  }
353
496
  detail.push(
354
497
  `posted ${posted} review ${posted === 1 ? "comment" : "comments"}` +
355
- (demoted === 0 ? "" : `, ${demoted} at file level after a line was refused`),
498
+ (demoted === 0 ? "" : `, ${demoted} at file level after a line was refused`) +
499
+ (pullComments === 0 ? "" : `, ${pullComments} on the conversation because the file is not in this pull request's diff`),
356
500
  );
357
- return { outcome: "POSTED", attempted: requests.length, posted, demoted, detail };
501
+ return { outcome: "POSTED", attempted: requests.length, posted, demoted, pullComments, detail };
358
502
  }
359
503
 
360
504
  /**
@@ -406,3 +550,108 @@ export function threadsDetailLines(result: AiReviewThreadsResult, command: strin
406
550
  export function aiReviewThreadsExitCode(result: AiReviewThreadsResult): number {
407
551
  return result.outcome === "FAILED" ? AI_REVIEW_THREADS_REFUSAL : 0;
408
552
  }
553
+
554
+ /**
555
+ * #2306 — CRC-C3's clearing half. *A false positive clears by closing the
556
+ * thread with a short reason.* A thread the review opened and somebody
557
+ * resolved with no reply reads exactly like one nobody read: the merge is
558
+ * unblocked and the record says nothing (`reference/clearing-a-false-positive.md`,
559
+ * *What this procedure refuses*). So each review round names those threads on
560
+ * the pull request.
561
+ *
562
+ * It runs on the NEXT round, because GitHub offers no workflow event for a
563
+ * thread being resolved. A thread resolved after the last push is reported
564
+ * only if another push follows — a nudge with a known blind spot, not a gate.
565
+ */
566
+ export const UNREASONED_MARKER = "rungate:unreasoned-resolution:v1";
567
+
568
+ /** One thread resolved with no stated reason. */
569
+ export interface UnreasonedResolution {
570
+ id: string;
571
+ path: string | null;
572
+ /** The opening comment's link, when GitHub returned one. */
573
+ url: string | null;
574
+ }
575
+
576
+ export type UnreasonedReading =
577
+ | { status: "MEASURED"; unreasoned: UnreasonedResolution[] }
578
+ | { status: "UNMEASURED"; reason: string };
579
+
580
+ /** `{ author: { login }, body, url }`, asserted field by field. */
581
+ function commentOf(c: unknown): { login: string | null; body: string; url: string | null } | null {
582
+ if (c === null || typeof c !== "object") return null;
583
+ const o = c as { author?: unknown; body?: unknown; url?: unknown };
584
+ const author = o.author !== null && typeof o.author === "object" ? (o.author as { login?: unknown }).login : null;
585
+ return {
586
+ login: typeof author === "string" ? author : null,
587
+ body: typeof o.body === "string" ? o.body : "",
588
+ url: typeof o.url === "string" ? o.url : null,
589
+ };
590
+ }
591
+
592
+ /**
593
+ * The resolved threads that carry no reason.
594
+ *
595
+ * A thread counts only if it is resolved (the literal `true`, as in
596
+ * `threadReading`), its FIRST comment carries the finding-key marker — so it
597
+ * is the review's thread, not a person's — and no later comment is a reason.
598
+ * A reason is a non-blank reply by anybody other than the thread's opener: the
599
+ * bot answering itself is not somebody stating why the finding was cleared.
600
+ *
601
+ * A node that cannot be read is skipped, as `threadReading` skips it; a list
602
+ * that could not be read at all is UNMEASURED, never "none".
603
+ */
604
+ export function unreasonedResolutions(raw: readonly unknown[] | null | undefined, reason: string): UnreasonedReading {
605
+ if (raw === null || raw === undefined) return { status: "UNMEASURED", reason };
606
+ const unreasoned: UnreasonedResolution[] = [];
607
+ for (const t of raw) {
608
+ if (t === null || typeof t !== "object") continue;
609
+ const node = t as { id?: unknown; isResolved?: unknown; path?: unknown; comments?: unknown };
610
+ if (node.isResolved !== true || typeof node.id !== "string") continue;
611
+ const nodes =
612
+ node.comments !== null && typeof node.comments === "object"
613
+ ? (node.comments as { nodes?: unknown }).nodes
614
+ : undefined;
615
+ if (!Array.isArray(nodes) || nodes.length === 0) continue;
616
+ // Review of #2378: a thread whose comments were not read to their end —
617
+ // a second page, or a page that cannot say — may hold its reason past
618
+ // what was read. It is not reported: under-reporting is the safe
619
+ // direction for a record. `nextCursor` is the one reader (SC-2721).
620
+ if (nextCursor((node.comments as { pageInfo?: unknown }).pageInfo).kind !== "done") continue;
621
+ const first = commentOf(nodes[0]);
622
+ if (first === null || threadKeyFrom(first.body) === null) continue;
623
+ const answered = nodes
624
+ .slice(1)
625
+ .map(commentOf)
626
+ .some(c => c !== null && c.login !== first.login && c.body.trim() !== "");
627
+ if (answered) continue;
628
+ unreasoned.push({ id: node.id, path: typeof node.path === "string" ? node.path : null, url: first.url });
629
+ }
630
+ return { status: "MEASURED", unreasoned };
631
+ }
632
+
633
+ /**
634
+ * The conversation comment naming every unreasoned thread no earlier report
635
+ * named, or `null` when there is nothing new. Each thread carries its own
636
+ * marker, so a later round reports only threads resolved since.
637
+ */
638
+ export function unreasonedReport(list: readonly UnreasonedResolution[], existing: readonly string[]): string | null {
639
+ const reported = (id: string) => existing.some(b => b.includes(`<!-- ${UNREASONED_MARKER} ${id} -->`));
640
+ const fresh = list.filter(u => !reported(u.id));
641
+ if (fresh.length === 0) return null;
642
+ const lines = fresh.map(u => {
643
+ const where = u.path === null ? "a thread on the pull request" : `\`${u.path}\``;
644
+ return u.url === null ? `- ${where}` : `- ${where} — ${u.url}`;
645
+ });
646
+ return [
647
+ `**${fresh.length === 1 ? "A review thread was" : `${fresh.length} review threads were`} resolved with no stated reason** (CRC-C3).`,
648
+ "",
649
+ "The AI review opened these and they were resolved with no reply. A resolved thread with no reason reads " +
650
+ "the same as one nobody read. Reply in each thread with the reason, in one or two sentences naming the " +
651
+ "evidence. The procedure is `reference/clearing-a-false-positive.md`.",
652
+ "",
653
+ ...lines,
654
+ "",
655
+ ...fresh.map(u => `<!-- ${UNREASONED_MARKER} ${u.id} -->`),
656
+ ].join("\n");
657
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The one writer of `blocked by` links — #2345.
3
+ *
4
+ * `gh issue edit --add-blocked-by` exists only in recent `gh` releases. A
5
+ * consumer's self-hosted runner with an older `gh` failed every edge of a
6
+ * 35-issue plan with `unknown flag: --add-blocked-by` (2026-11-17). `gh api`
7
+ * is in every release, so links are written through the REST dependencies
8
+ * endpoint instead, and the runner's `gh` version stops mattering.
9
+ *
10
+ * **`issue_id` is the blocker's DATABASE id, not its number.** A number is
11
+ * accepted too and links whichever issue has that database id — measured
12
+ * 2026-11-05, recorded in `scripts/board-walkthrough.ts`. So each blocker's id
13
+ * is read first, and the blocked issue's links are read back once all are
14
+ * written: every blocker must be there, or the write is refused, never
15
+ * reported as wired. The read-back and not the POST's reply, because GitHub's
16
+ * documentation does not say which of the two issues that reply describes.
17
+ *
18
+ * **Calls, per blocked issue:** one id read per blocker not yet in `ids` (a
19
+ * caller writing many groups passes one map, so a blocker shared by many
20
+ * issues is read once), one POST per link, and one read-back. The REST
21
+ * endpoint takes one link per call, so a group can no longer be one call the
22
+ * way `issue edit --add-blocked-by a --add-blocked-by b` was.
23
+ */
24
+
25
+ /** How a `gh` call is made. Injected so a test never shells out. */
26
+ export type GhExec = (args: readonly string[]) => string;
27
+
28
+ function databaseId(repo: string, blocker: number, exec: GhExec, ids: Map<string, number>): number {
29
+ // Keyed by repository too: a dependency may cross repositories, so the same
30
+ // number in another repository is another issue (review of #2357).
31
+ const key = `${repo}#${blocker}`;
32
+ const known = ids.get(key);
33
+ if (known !== undefined) return known;
34
+ const raw = exec(["api", `repos/${repo}/issues/${blocker}`, "--jq", ".id"]).trim();
35
+ const id = Number(raw);
36
+ if (!Number.isSafeInteger(id) || id <= 0) {
37
+ throw new Error(`#${blocker}: could not read its database id (got "${raw.slice(0, 40)}"), so no link was written`);
38
+ }
39
+ ids.set(key, id);
40
+ return id;
41
+ }
42
+
43
+ export function addBlockers(
44
+ repo: string,
45
+ blocked: number,
46
+ blockers: readonly number[],
47
+ exec: GhExec,
48
+ ids: Map<string, number> = new Map(),
49
+ ): void {
50
+ if (blockers.length === 0) return;
51
+ // Every id before any write, so an unreadable one writes nothing for this issue.
52
+ const resolved = blockers.map(b => ({ number: b, id: databaseId(repo, b, exec, ids) }));
53
+ for (const b of resolved) {
54
+ exec(["api", "-X", "POST", `repos/${repo}/issues/${blocked}/dependencies/blocked_by`, "-F", `issue_id=${b.id}`]);
55
+ }
56
+ // One number per line: `--paginate` concatenates pages, so one JSON document would not parse.
57
+ const linked = new Set(
58
+ exec(["api", "--paginate", `repos/${repo}/issues/${blocked}/dependencies/blocked_by?per_page=100`, "--jq", ".[].number"])
59
+ .split("\n")
60
+ .map(l => l.trim())
61
+ .filter(l => l !== "")
62
+ .map(Number),
63
+ );
64
+ const missing = blockers.filter(b => !linked.has(b));
65
+ if (missing.length > 0) {
66
+ throw new Error(
67
+ `#${blocked}: the writes returned, but ${missing.map(b => `#${b}`).join(", ")} ${missing.length === 1 ? "is" : "are"} not among its blockers ` +
68
+ `on read-back (${linked.size === 0 ? "none" : [...linked].map(n => `#${n}`).join(", ")})`,
69
+ );
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Remove one `blocked by` link, through the same REST endpoint and by the same
75
+ * database id — `issue edit --remove-blocked-by` is missing from the same old
76
+ * `gh` (review of #2357). Read back afterwards: a link still there is refused.
77
+ */
78
+ export function removeBlocker(
79
+ repo: string,
80
+ blocked: number,
81
+ blocker: number,
82
+ exec: GhExec,
83
+ ids: Map<string, number> = new Map(),
84
+ ): void {
85
+ const id = databaseId(repo, blocker, exec, ids);
86
+ exec(["api", "-X", "DELETE", `repos/${repo}/issues/${blocked}/dependencies/blocked_by/${id}`]);
87
+ const linked = exec(["api", "--paginate", `repos/${repo}/issues/${blocked}/dependencies/blocked_by?per_page=100`, "--jq", ".[].number"])
88
+ .split("\n")
89
+ .map(l => l.trim())
90
+ .filter(l => l !== "")
91
+ .map(Number);
92
+ if (linked.includes(blocker)) {
93
+ throw new Error(`#${blocked}: the removal returned, but #${blocker} is still among its blockers on read-back`);
94
+ }
95
+ }
@@ -124,6 +124,17 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
124
124
  summary: "Report which success criteria are matched, unmatched or uncovered",
125
125
  usage: "rungate audit-specs",
126
126
  },
127
+ // #2360: a consumer ticks its own criteria from its own test claims. The
128
+ // script was in `files[]` and reachable from nothing, and it read
129
+ // `join(import.meta.dir, "..")` — run from node_modules it ticked nothing
130
+ // of the consumer's and reported on rungate's specs. `projectRootFlag` is
131
+ // load-bearing, as on `audit-spec-evidence`.
132
+ "sync-sc-status": {
133
+ script: "scripts/sync-sc-status.ts",
134
+ summary: "Tick each criterion a passing test claims, in this project's specs",
135
+ usage: "rungate sync-sc-status [--dry-run] [--report] [--only <SC-id,…>] [--project-root <dir>]",
136
+ projectRootFlag: true,
137
+ },
127
138
  // Registered because `create-spec` SHIPS and stamps every generated spec
128
139
  // with `evidence: required`, and this is the only thing that enforces that
129
140
  // key (#1639). Without the entry the published package emitted a document
@@ -244,6 +255,15 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
244
255
  "rungate plan-issues (--repair | --decompose) <plan.md> --repo <owner/name> [--write] [--json]",
245
256
  projectRootFlag: true,
246
257
  },
258
+ // ADR-020 Decision 1 (SC-2782): every open `from-consumer` issue with no
259
+ // verdict marker gets exactly one, from `lib/consumer-triage.ts`. Reads the
260
+ // tracker AND the tree (the opted-in specs place an issue), hence the root flag.
261
+ "consumer-triage": {
262
+ script: "scripts/consumer-triage.ts",
263
+ summary: "Give each consumer-filed issue with no verdict exactly one",
264
+ usage: "rungate consumer-triage --repo <owner/name> [--write] [--json]",
265
+ projectRootFlag: true,
266
+ },
247
267
  // #2275, onboarding existing specs. Read-only: what each spec holds, its
248
268
  // `board:` setting, and a looks-done hint per unticked criterion. It never
249
269
  // ticks. Reads the working directory, so it takes no root flag.
@@ -252,6 +272,14 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
252
272
  summary: "Spec criteria and opt-in, with looks-done hints",
253
273
  usage: "rungate board-scope [--spec <path>] [--json]",
254
274
  },
275
+ // #2330. The pinned "where we are" view as a command a consumer can run:
276
+ // every family's phases with their open issues and blockers. Reads the
277
+ // working directory and its origin remote, so it takes no root flag.
278
+ board: {
279
+ script: "scripts/status-view.ts",
280
+ summary: "Each phase's open issues and blockers",
281
+ usage: "rungate board [--repo <owner/name>] [--markdown] (repository defaults to GITHUB_REPOSITORY, then the origin remote)",
282
+ },
255
283
  // Step 5 of ADR-003. `plan-spec` turns the placement table into milestones;
256
284
  // this turns the ORDER of those milestones into `blocked by` edges, which is
257
285
  // AGENTS.md rule 4 — ordering is data, not prose.
@@ -310,7 +338,7 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
310
338
  // `projectRootFlag`: it reads `process.cwd()`, which the child inherits.
311
339
  "unaccounted-work": {
312
340
  script: "scripts/unaccounted-work.ts",
313
- summary: "Report undone work declared in a repository's prose that no open issue covers",
341
+ summary: "Undone work declared in prose that no open issue covers",
314
342
  usage:
315
343
  "rungate unaccounted-work [--project-root <dir>] [--repo <owner/name>] [--issues-fixture <file.json>] [--json] " +
316
344
  "(exit 1 when work is unaccounted, 2 when a source could not be read)",
@@ -107,7 +107,7 @@
107
107
  * measured before and after, and a single new entry reverts the write.
108
108
  */
109
109
  import { spawnSync } from "child_process";
110
- import { existsSync, readFileSync, unlinkSync, writeFileSync } from "fs";
110
+ import { existsSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
111
111
  import { join } from "path";
112
112
  import {
113
113
  DIRECTORY_CONFIG_FILES,
@@ -183,18 +183,34 @@ function matchedByIgnoreRules(root: string, paths: readonly string[]): Trackable
183
183
  return { ignored: paths.filter(p => matched.has(p)), failure: null };
184
184
  }
185
185
 
186
+ /** git's own refusal outside a repository: exit 128, and it says so. */
187
+ const NOT_A_REPOSITORY = /not a git repository/i;
188
+
189
+ /**
190
+ * Whether `root` is inside a work tree. "Outside" is only git's own exit-128
191
+ * refusal saying so, or a probe from inside `.git` itself; a git that could
192
+ * not run, or failed any other way, is a failure string, never "outside"
193
+ * (review of #2359 — the same fail-open in two callers).
194
+ */
195
+ function workTreeProbe(root: string): "inside" | "outside" | { failure: string } {
196
+ const r = git(root, ["rev-parse", "--is-inside-work-tree"]);
197
+ if (r.status === 128 && NOT_A_REPOSITORY.test(r.stderr)) return "outside";
198
+ if (r.status !== 0) return { failure: `git rev-parse failed (${r.status}): ${r.stderr.trim() || "no output"}` };
199
+ return r.stdout.trim() === "true" ? "inside" : "outside";
200
+ }
201
+
186
202
  /**
187
203
  * Whether this project's ignore rules mark the rungate config disposable.
188
204
  *
189
205
  * A project that is not a git repository has no ignore rules and nothing can
190
206
  * delete the file on a checkout, so that is `{ ignored: [], failure: null }`
191
- * and not an error — the harness scaffolds into trees that are not repos.
207
+ * and not an error — the harness scaffolds into trees that are not repos. A
208
+ * git that cannot answer is a `failure`, not that case.
192
209
  */
193
210
  export function configPathsIgnored(root: string): TrackableReading {
194
- const inside = git(root, ["rev-parse", "--is-inside-work-tree"]);
195
- if (inside.status !== 0 || inside.stdout.trim() !== "true") {
196
- return { ignored: [], failure: null };
197
- }
211
+ const probe = workTreeProbe(root);
212
+ if (probe === "outside") return { ignored: [], failure: null };
213
+ if (probe !== "inside") return { ignored: [], failure: probe.failure };
198
214
  return matchedByIgnoreRules(root, RUNGATE_CONFIG_IGNORE_PATHS);
199
215
  }
200
216
 
@@ -437,3 +453,72 @@ export function ensureConfigTrackable(
437
453
  `and is now committable; commit it, or the next branch switch deletes it)`,
438
454
  );
439
455
  }
456
+
457
+ /**
458
+ * The concrete files a set of owned-file rows names on disk. A row is a path,
459
+ * or a `<dir>/*<ext>` class (`.claude/agents/*.md`), expanded to the files of
460
+ * that directory with that extension. Absent files are left out: an ignore
461
+ * rule only matters for a file that was written. A directory that exists but
462
+ * cannot be listed is a `failure`, not an absence (review of #2359): only
463
+ * ENOENT means nothing was written there.
464
+ */
465
+ function ownedPathsOnDisk(root: string, rows: readonly string[]): { paths: string[]; failures: string[] } {
466
+ const out: string[] = [];
467
+ const failures: string[] = [];
468
+ for (const row of rows) {
469
+ const star = row.lastIndexOf("/*");
470
+ if (star === -1) {
471
+ if (existsSync(join(root, row))) out.push(row);
472
+ continue;
473
+ }
474
+ const dir = row.slice(0, star);
475
+ const ext = row.slice(star + 2);
476
+ let names: string[];
477
+ try {
478
+ names = readdirSync(join(root, dir));
479
+ } catch (e) {
480
+ const code = (e as NodeJS.ErrnoException).code;
481
+ // ENOENT: the directory was not written, so nothing in it can be ignored.
482
+ if (code !== "ENOENT") failures.push(`${dir} could not be listed (${code ?? (e as Error).message})`);
483
+ continue;
484
+ }
485
+ for (const n of names.sort()) if (n.endsWith(ext)) out.push(`${dir}/${n}`);
486
+ }
487
+ return { paths: out, failures };
488
+ }
489
+
490
+ /**
491
+ * #2347: name every owned file this scaffold left in a path the project's
492
+ * ignore rules match. Such a file is written, never committed, and so never
493
+ * ships, which on one consumer was the `/dry-run` command (`.claude/*`
494
+ * ignored, agents and rules negated, commands not). It only reports: whether
495
+ * scaffold should also make the path trackable is a decision recorded on
496
+ * #2347, not taken here. A tree that is not a repository has no ignore rules
497
+ * and gets no line; a git that cannot answer gets an UNMEASURED line, never
498
+ * a clean silence. "Not a repository" is only git's own exit-128 refusal
499
+ * saying so; a git that could not run, or failed any other way, is
500
+ * UNMEASURED (review of #2359).
501
+ */
502
+ export function reportIgnoredOwnedFiles(root: string, actions: string[], rows: readonly string[]): void {
503
+ const unmeasured = (why: string) =>
504
+ actions.push(`UNMEASURED: whether any file scaffold owns is ignored could not be read — ${why}`);
505
+ const probe = workTreeProbe(root);
506
+ if (probe === "outside") return;
507
+ if (probe !== "inside") {
508
+ unmeasured(probe.failure);
509
+ return;
510
+ }
511
+ const owned = ownedPathsOnDisk(root, rows);
512
+ for (const f of owned.failures) unmeasured(f);
513
+ const reading = matchedByIgnoreRules(root, owned.paths);
514
+ if (reading.failure !== null) {
515
+ unmeasured(reading.failure);
516
+ return;
517
+ }
518
+ for (const path of reading.ignored) {
519
+ actions.push(
520
+ `IGNORED: ${path} is written by scaffold, but this project's ignore rules match it, so it will not be ` +
521
+ `committed and will not ship; \`git check-ignore -v ${path}\` names the rule, and a \`!\` line after it un-ignores the path`,
522
+ );
523
+ }
524
+ }