dsh-inbox-bridge 2.19.3 → 2.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,560 +1,608 @@
1
- #!/usr/bin/env node
2
- // GitHub inbox — turn GitHub-side facts (main-branch CI, open PR checks/reviews,
3
- // issue and PR comments) into one-line local events so a development agent does
4
- // not have to wait for the user to mention a failure.
5
- //
6
- // Owns:
7
- // - pure event extraction / dedupe / recovery logic (unit-tested, no network)
8
- // - the `gh` transport (single 20s timeout per call, failures become a
9
- // `github-inbox: skipped (...)` line with exit code 0)
10
- // - local state `.work/github-inbox/state.json` and the append-only log
11
- // `.work/github-inbox/pending.md`
12
- //
13
- // Not owned here: scheduling (see .work/github-inbox/README.md; the repository
14
- // intentionally does not create a Windows scheduled task).
15
- import fs from "node:fs";
16
- import path from "node:path";
17
- import { execFileSync } from "node:child_process";
18
- import { fileURLToPath } from "node:url";
19
-
20
- /** Fallback repository when nothing else names one: --repo, INBOX_REPO, or the git remote. */
21
- export const REPO = "unknown/unknown";
22
-
23
- /** The repository this process watches; `--repo` or INBOX_REPO overrides. */
24
- let activeRepo = REPO;
25
-
26
- export function setRepo(repo) {
27
- if (typeof repo === "string" && /^[\w.-]+\/[\w.-]+$/u.test(repo)) activeRepo = repo;
28
- }
29
-
30
- export function watchedRepo() {
31
- return activeRepo;
32
- }
33
-
34
- /**
35
- * Who this inbox speaks for: `{ kind, login, token }`. Null means "do not
36
- * filter", which is only honest when the caller really is the only identity.
37
- */
38
- let activeIdentity = null;
39
-
40
- export function setIdentity(identity) {
41
- if (!identity || typeof identity !== "object") {
42
- activeIdentity = null;
43
- return;
44
- }
45
- const login =
46
- typeof identity.login === "string" && identity.login.length > 0 ? identity.login : null;
47
- const token =
48
- typeof identity.token === "string" && identity.token.length > 0 ? identity.token : null;
49
- activeIdentity = { kind: identity.kind === "app" ? "app" : "user", login, token };
50
- }
51
-
52
- export function watchedIdentity() {
53
- return activeIdentity;
54
- }
55
-
56
- /** Login the events are filtered against; null means "no filter". */
57
- export function meLogin() {
58
- return activeIdentity?.login ?? null;
59
- }
60
-
61
- export const MAX_SEEN = 500;
62
- export const GH_TIMEOUT_MS = 20_000;
63
-
64
- const FAILED_CONCLUSIONS = new Set(["failure", "timed_out", "startup_failure", "action_required"]);
65
- const FAILED_CHECK_STATES = new Set([
66
- "FAILURE",
67
- "ERROR",
68
- "TIMED_OUT",
69
- "CANCELLED",
70
- "ACTION_REQUIRED",
71
- "STARTUP_FAILURE",
72
- ]);
73
- const RUN_FIELDS =
74
- "databaseId,name,displayTitle,conclusion,headSha,headBranch,workflowName,createdAt,url";
75
- const PR_FIELDS =
76
- "number,title,headRefName,url,statusCheckRollup,reviewDecision,updatedAt,author,reviewRequests,assignees,isDraft,mergeStateStatus";
77
- // Order inside one notice: something to fix first, then what is waiting on a
78
- // person, then conversation.
79
- const KIND_ORDER = { recovered: 0, security: 1, ci: 2, pr: 3, comment: 4, issue: 5 };
80
- /** How a GitHub notification reason maps onto the role vocabulary. */
81
- const NOTIFICATION_ROLES = {
82
- review_requested: "reviewer",
83
- assign: "assignee",
84
- author: "author",
85
- state_change: "author",
86
- mention: "mention",
87
- team_mention: "mention",
88
- comment: "mention",
89
- subscribed: "mention",
90
- ci_activity: "ci",
91
- };
92
-
93
- const USAGE = `github-inbox — GitHub event inbox for local development
94
-
95
- Usage:
96
- node scripts/github-inbox.mjs [--poll] [--all] [--json] [--quiet]
97
-
98
- --poll (default) fetch events, dedupe against state, print only new ones
99
- --all print the latest 20 main-branch runs and open PR check status
100
- --json machine-readable output
101
- --quiet suppress the "no new events" status line (new events still print)
102
- --repeat list current events without the local seen filter (the bridge owns delivery state)
103
- --repo <owner/name> watch a repository; repeat for several
104
- (default: INBOX_REPO, comma or space separated, else this git remote)
105
- --clear <scope> mark the notification threads this poll read as read:
106
- repo (the watched repositories) or off (default off; the
107
- bridge sets it). GitHub has no "done" API, so this clears
108
- the unread badge, not the inbox history. Only threads from
109
- the repositories this instance reads are touched.
110
-
111
- Security: open Dependabot and code-scanning alerts are read as well. A repository
112
- without either feature answers 403/404, which is reported (in --json)
113
- instead of skipped, so one missing feature never hides the rest.
114
-
115
- State: .work/github-inbox/state.json (one slice per repository)
116
- History: .work/github-inbox/pending.md`;
117
-
118
- // ---------------------------------------------------------------------------
119
- // Small shared helpers
120
- // ---------------------------------------------------------------------------
121
-
122
- export function singleLine(value) {
123
- return String(value ?? "")
124
- .replace(/\s+/gu, " ")
125
- .trim();
126
- }
127
-
128
- function compact(parts) {
129
- return parts.filter(Boolean).join(" ").replace(/\s+/gu, " ").trim();
130
- }
131
-
132
- function pad(value) {
133
- return String(value).padStart(2, "0");
134
- }
135
-
136
- function localDay(date) {
137
- const value = date instanceof Date && !Number.isNaN(date.getTime()) ? date : new Date();
138
- return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;
139
- }
140
-
141
- function localClock(value) {
142
- const date = value instanceof Date ? value : new Date(value);
143
- if (Number.isNaN(date.getTime())) return localClock(new Date());
144
- return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
145
- }
146
-
147
- function toIso(value) {
148
- const date = value instanceof Date ? value : new Date(value ?? Date.now());
149
- return Number.isNaN(date.getTime()) ? new Date().toISOString() : date.toISOString();
150
- }
151
-
152
- function excerptOf(text, limit = 120) {
153
- const firstLine =
154
- String(text ?? "")
155
- .split(/\r?\n/u)
156
- .map((line) => line.trim())
157
- .find(Boolean) ?? "";
158
- const stripped = firstLine.replace(/^[#>*\-+\s]+/u, "").trim();
159
- return (stripped || singleLine(text)).slice(0, limit);
160
- }
161
-
162
- function issueNumberFromApiUrl(url) {
163
- const match = /\/issues\/(\d+)(?:[/?#].*)?$/u.exec(String(url ?? ""));
164
- return match ? Number(match[1]) : null;
165
- }
166
-
167
- function commentIdFromApiUrl(url) {
168
- const match = /\/comments\/(\d+)(?:[/?#].*)?$/u.exec(String(url ?? ""));
169
- return match ? match[1] : null;
170
- }
171
-
172
- // ---------------------------------------------------------------------------
173
- // Pure state / event logic (no network, no filesystem)
174
- // ---------------------------------------------------------------------------
175
-
176
- export function normalizeState(state) {
177
- const source = state && typeof state === "object" ? state : {};
178
- const seen = {};
179
- if (source.seen && typeof source.seen === "object" && !Array.isArray(source.seen)) {
180
- for (const [key, value] of Object.entries(source.seen)) {
181
- if (typeof key === "string" && typeof value === "string") seen[key] = value;
182
- }
183
- }
184
- const lastPrStatus = {};
185
- if (
186
- source.lastPrStatus &&
187
- typeof source.lastPrStatus === "object" &&
188
- !Array.isArray(source.lastPrStatus)
189
- ) {
190
- for (const [number, digest] of Object.entries(source.lastPrStatus)) {
191
- if (typeof digest === "string") lastPrStatus[number] = digest;
192
- }
193
- }
194
- const lastRun =
195
- source.lastRun && typeof source.lastRun === "object" && source.lastRun.id != null
196
- ? { id: source.lastRun.id, conclusion: source.lastRun.conclusion ?? null }
197
- : null;
198
- const lastPoll =
199
- source.lastPoll && typeof source.lastPoll === "object"
200
- ? {
201
- at: typeof source.lastPoll.at === "string" ? source.lastPoll.at : null,
202
- as: typeof source.lastPoll.as === "string" ? source.lastPoll.as : null,
203
- repo: typeof source.lastPoll.repo === "string" ? source.lastPoll.repo : null,
204
- durationMs: Number.isFinite(source.lastPoll.durationMs) ? source.lastPoll.durationMs : null,
205
- events: Number.isFinite(source.lastPoll.events) ? source.lastPoll.events : null,
206
- }
207
- : null;
208
- return {
209
- version: 2,
210
- lastPollAt: typeof source.lastPollAt === "string" ? source.lastPollAt : null,
211
- lastPoll,
212
- seen,
213
- lastRun,
214
- lastPrStatus,
215
- };
216
- }
217
-
218
- /**
219
- * One repo's slice of the state file. A 2.0/2.1 file kept everything at the top
220
- * level for the single repo it watched; it is adopted as the slice of the repo
221
- * its last poll named, so the first multi-repo poll does not re-send the world.
222
- */
223
- export function normalizeStateFile(state) {
224
- const source = state && typeof state === "object" ? state : {};
225
- const repos = {};
226
- if (source.repos && typeof source.repos === "object" && !Array.isArray(source.repos)) {
227
- for (const [repo, slice] of Object.entries(source.repos)) {
228
- if (/^[\w.-]+\/[\w.-]+$/u.test(repo)) repos[repo] = normalizeState(slice);
229
- }
230
- }
231
- if (Object.keys(repos).length === 0 && (source.seen || source.lastPollAt)) {
232
- const legacy = normalizeState(source);
233
- const repo = legacy.lastPoll?.repo ?? null;
234
- if (repo) repos[repo] = legacy;
235
- }
236
- return { version: 2, repos };
237
- }
238
-
239
- export function sliceOf(stateFile, repo) {
240
- const file = normalizeStateFile(stateFile);
241
- return file.repos[repo] ?? normalizeState({});
242
- }
243
-
244
- /**
245
- * Attach the repository to every event and put it in the key. The same PR
246
- * number in two repositories is two different facts; a shared queue must not
247
- * collapse them into one.
248
- */
249
- export function tagEvents(repo, events = []) {
250
- return (Array.isArray(events) ? events : []).map((event) => ({
251
- ...event,
252
- repo,
253
- key: `${repo}#${event.key}`,
254
- }));
255
- }
256
-
257
- const IN_PROGRESS_CHECK_STATES = new Set(["QUEUED", "IN_PROGRESS", "PENDING", "WAITING", "REQUESTED"]);
258
-
259
- // A pull request that cannot be merged is work, even when nothing failed: the
260
- // branch has to be rebased or the conflict resolved. These two states are the
261
- // ones a person has to act on; BLOCKED/UNSTABLE are already covered by the
262
- // review and check digests.
263
- const BLOCKED_MERGE_STATES = new Set(["DIRTY", "BEHIND"]);
264
-
265
- export function mergeBlocker(pr) {
266
- const state = String(pr?.mergeStateStatus ?? "").toUpperCase();
267
- if (BLOCKED_MERGE_STATES.has(state)) return state;
268
- // `gh pr list --json mergeable` answers CONFLICTING when the merge is dirty;
269
- // accept it so the older field shape keeps working.
270
- return String(pr?.mergeable ?? "").toUpperCase() === "CONFLICTING" ? "DIRTY" : null;
271
- }
272
-
273
- export function prStatusDigest(pr) {
274
- // 摘要只反映“需要你处理的状态”:失败的检查与评审决定。
275
- // 进行中或成功完成的检查不进 key,否则同一 PR 在检查跑完前会被反复当成新事件。
276
- const failing = failingCheckNames(pr).sort();
277
- const blocker = mergeBlocker(pr);
278
- // 只在真的冲突/落后时才把合并状态写进 key:合并干净的 PR 保持原来的 key,
279
- // 已投递的事实不会因为一次格式变化被重新提醒一次。
280
- const merge = blocker ? `|merge:${blocker}` : "";
281
- return `failed[${failing.join(",")}]|review:${String(pr?.reviewDecision ?? "").toUpperCase() || "NONE"}${merge}`;
282
- }
283
-
284
- export function failingCheckNames(pr) {
285
- const rollup = Array.isArray(pr?.statusCheckRollup) ? pr.statusCheckRollup : [];
286
- return rollup
287
- .filter((check) => {
288
- const state = String(check?.state ?? "").toUpperCase();
289
- const conclusion = String(check?.conclusion ?? "").toUpperCase();
290
- return FAILED_CHECK_STATES.has(state) || FAILED_CHECK_STATES.has(conclusion);
291
- })
292
- .map((check) => check?.name ?? check?.context ?? check?.workflowName ?? "check");
293
- }
294
-
295
- export function extractRunEvents(runs = [], state = {}) {
296
- const list = Array.isArray(runs) ? runs.filter(Boolean) : [];
297
- const previous = normalizeState(state);
298
- // A first poll has nothing to compare against: the window may hold failures
299
- // that people already know about (a red run from two days ago). Report only
300
- // the newest completed run — the current state of the branch — and let the
301
- // next poll start from that baseline.
302
- const bootstrap = !previous.lastPollAt;
303
- const newestCompleted = list.find((run) => run.conclusion);
304
- const events = [];
305
- const seenGroups = new Set();
306
- for (const run of list) {
307
- const id = run.databaseId ?? run.id;
308
- if (id == null || !FAILED_CONCLUSIONS.has(run.conclusion)) continue;
309
- if (bootstrap && run !== newestCompleted) continue;
310
- // A startup failure almost always means the runner could not start the
311
- // job (billing, permissions): no code change fixes it, so it is grouped
312
- // and reported once instead of once per retried run.
313
- const infra = run.conclusion === "startup_failure";
314
- const group = `${singleLine(run.workflowName ?? run.name ?? "ci")}|${singleLine(
315
- run.headBranch ?? "",
316
- )}`;
317
- if (seenGroups.has(group)) continue;
318
- seenGroups.add(group);
319
- events.push({
320
- key: infra ? `infra:${group}` : `run:${id}`,
321
- kind: infra ? "infra" : "ci",
322
- label: "CI",
323
- runId: id,
324
- group,
325
- conclusion: run.conclusion,
326
- title: singleLine(run.displayTitle ?? run.name ?? ""),
327
- name: singleLine(run.name ?? ""),
328
- sha: String(run.headSha ?? "").slice(0, 7),
329
- url: run.url ?? run.html_url ?? "",
330
- at: run.createdAt ?? run.created_at ?? null,
331
- });
332
- }
333
-
334
- // Recovered: the newest completed run succeeded and the previous poll left
335
- // off on a failed run. In-progress runs are ignored so a fix pushed between
336
- // two polls is still reported once the run finishes.
337
- const completed = list.filter((run) => run.conclusion);
338
- const latest = completed[0];
339
- const lastRun = normalizeState(state).lastRun;
340
- if (
341
- latest &&
342
- latest.conclusion === "success" &&
343
- lastRun &&
344
- FAILED_CONCLUSIONS.has(lastRun.conclusion)
345
- ) {
346
- const id = latest.databaseId ?? latest.id;
347
- events.push({
348
- key: `run:${id}:recovered`,
349
- kind: "recovered",
350
- label: "CI",
351
- runId: id,
352
- conclusion: "success",
353
- group: `${singleLine(latest.workflowName ?? latest.name ?? "ci")}|${singleLine(
354
- latest.headBranch ?? "",
355
- )}`,
356
- title: singleLine(latest.displayTitle ?? latest.name ?? ""),
357
- name: singleLine(latest.name ?? ""),
358
- sha: String(latest.headSha ?? "").slice(0, 7),
359
- url: latest.url ?? latest.html_url ?? "",
360
- at: latest.createdAt ?? latest.created_at ?? null,
361
- });
362
- }
363
- return events;
364
- }
365
-
366
- /**
367
- * How `me` is involved in one pull request: `author`, `reviewer`, `assignee`,
368
- * or null (not involved). `me === null` means "no filter" and returns `any`.
369
- * Review requests arrive as `reviewRequests` from `gh pr list` and as
370
- * `requested_reviewers` from the REST API; both shapes are accepted.
371
- */
372
- export function prRole(pr, me) {
373
- if (!me) return "any";
374
- const login = (entry) => entry?.login ?? null;
375
- if (login(pr?.author) === me) return "author";
376
- const reviewers = Array.isArray(pr?.reviewRequests)
377
- ? pr.reviewRequests
378
- : Array.isArray(pr?.requested_reviewers)
379
- ? pr.requested_reviewers
380
- : [];
381
- if (reviewers.some((entry) => login(entry) === me)) return "reviewer";
382
- if ((Array.isArray(pr?.assignees) ? pr.assignees : []).some((entry) => login(entry) === me))
383
- return "assignee";
384
- return null;
385
- }
386
-
387
- /**
388
- * Whether `text` mentions `login`. GitHub renders App mentions without the
389
- * `[bot]` suffix, so `noema-agent[bot]` is matched as `noema-agent`.
390
- */
391
- export function mentionsLogin(text, login) {
392
- if (!login) return false;
393
- const handle = login.replace(/\[bot\]$/u, "");
394
- if (handle.length === 0) return false;
395
- const escaped = handle.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
396
- return new RegExp(`(^|[^\\w./-])@${escaped}(?![\\w-])`, "iu").test(String(text ?? ""));
397
- }
398
-
399
- export function extractPrEvents(prs = [], { me = null } = {}) {
400
- const events = [];
401
- for (const pr of Array.isArray(prs) ? prs : []) {
402
- const number = pr?.number;
403
- if (!number) continue;
404
- const role = prRole(pr, me);
405
- // An event belongs to an identity, not to a repository: the reviewer asked
406
- // for me is my task, the author waiting for someone else is not.
407
- if (role === null) continue;
408
- const review = String(pr?.reviewDecision ?? "").toUpperCase();
409
- const failing = failingCheckNames(pr);
410
- const blocker = mergeBlocker(pr);
411
- const reasons = [];
412
- if (role === "reviewer") {
413
- // Already reviewed: the ball is back with the author.
414
- if (review === "CHANGES_REQUESTED") continue;
415
- reasons.push("review requested from you");
416
- } else {
417
- if (failing.length) reasons.push(`checks failed: ${failing.slice(0, 4).join(", ")}`);
418
- if (review === "CHANGES_REQUESTED") reasons.push("changes requested");
419
- // Merging is the author's job, not the reviewer's: a reviewer reading a
420
- // conflicted PR has nothing to do about the conflict.
421
- if (blocker === "DIRTY") reasons.push("merge conflict with the base branch");
422
- if (blocker === "BEHIND") reasons.push("behind the base branch");
423
- }
424
- if (reasons.length === 0) continue;
425
- // A reviewer's key must not move when checks change: it is the same review
426
- // task until they actually review.
427
- const digest = role === "reviewer" ? "review-requested" : prStatusDigest(pr);
428
- events.push({
429
- key: `pr:${number}:${role}:${digest}`,
430
- kind: "pr",
431
- role,
432
- repo: activeRepo,
433
- label: "PR",
434
- number,
435
- title: singleLine(pr?.title ?? ""),
436
- headRefName: pr?.headRefName ?? "",
437
- reasons,
438
- url: pr?.url ?? "",
439
- at: pr?.updatedAt ?? pr?.updated_at ?? null,
440
- });
441
- }
442
- return events;
443
- }
444
-
445
- export function extractNotificationEvents(notifications = [], { repo = REPO } = {}) {
446
- const events = [];
447
- for (const notification of Array.isArray(notifications) ? notifications : []) {
448
- const subject = notification?.subject;
449
- if (!subject) continue;
450
- // CI suites are covered by the main-branch run feed; PR check state is
451
- // covered by the open-PR feed. Keep this feed for comments / issues only.
452
- if (subject.type !== "Issue" && subject.type !== "PullRequest") continue;
453
- if (notification.reason === "ci_activity") continue;
454
- const number = issueNumberFromApiUrl(subject.url);
455
- if (!number) continue;
456
- const commentId = commentIdFromApiUrl(subject.latest_comment_url);
457
- const repoFullName = notification.repository?.full_name ?? repo;
458
- const htmlBase = `https://github.com/${repoFullName}/issues/${number}`;
459
- const subjectKind = subject.type === "PullRequest" ? "PR" : "issue";
460
- const title = singleLine(subject.title ?? `#${number}`);
461
- const at = notification.updated_at ?? null;
462
- const role = NOTIFICATION_ROLES[notification.reason] ?? "mention";
463
- if (commentId) {
464
- events.push({
465
- key: `comment:${commentId}:${role}`,
466
- kind: "comment",
467
- role,
468
- repo: repoFullName,
469
- label: "Comment",
470
- ref: `${subjectKind} #${number}`,
471
- title,
472
- url: `${htmlBase}#issuecomment-${commentId}`,
473
- at,
474
- });
475
- } else if (subject.type === "Issue") {
476
- events.push({
477
- key: `issue:${number}:${role}:${at ?? ""}`,
478
- kind: "issue",
479
- role,
480
- repo: repoFullName,
481
- label: "Issue",
482
- ref: `#${number}`,
483
- title,
484
- url: htmlBase,
485
- at,
486
- });
487
- }
488
- // A PullRequest notification without a comment (assignment, review,
489
- // check suite) is covered by the open-PR feed, which carries the check
490
- // digest; emitting an "issue" line here would duplicate or mislabel it.
491
- }
492
- return events;
493
- }
494
-
495
- export function extractCommentEvents(comments = [], { me = null } = {}) {
496
- const events = [];
497
- for (const comment of Array.isArray(comments) ? comments : []) {
498
- const id = comment?.id;
499
- if (id == null) continue;
500
- // Without an identity every comment in the repository is "news"; with one,
501
- // only a comment that names me is a task for me.
502
- if (me && (comment?.user?.login === me || !mentionsLogin(comment?.body, me))) continue;
503
- const number = issueNumberFromApiUrl(comment.issue_url);
504
- events.push({
505
- key: `comment:${id}:mention`,
506
- kind: "comment",
507
- role: "mention",
508
- repo: activeRepo,
509
- label: "Comment",
510
- ref: number ? `#${number}` : "comment",
511
- title: excerptOf(comment.body) || `comment by ${comment.user?.login ?? "unknown"}`,
512
- url: comment.html_url ?? "",
513
- at: comment.created_at ?? comment.updated_at ?? null,
514
- });
515
- }
516
- return events;
517
- }
518
-
519
- export function extractIssueEvents(issues = [], state = {}, { me = null } = {}) {
520
- const since =
521
- typeof state?.lastPollAt === "string" && Number.isFinite(Date.parse(state.lastPollAt))
522
- ? Date.parse(state.lastPollAt)
523
- : null;
524
- const events = [];
525
- for (const issue of Array.isArray(issues) ? issues : []) {
526
- if (!issue || issue.pull_request || issue.number == null) continue;
527
- const role = me
528
- ? issue?.user?.login === me
529
- ? "author"
530
- : (Array.isArray(issue?.assignees) ? issue.assignees : []).some(
531
- (entry) => entry?.login === me,
532
- )
533
- ? "assignee"
534
- : mentionsLogin(issue?.body, me)
535
- ? "mention"
536
- : null
537
- : "any";
538
- if (role === null) continue;
539
- // Only issues that started after the previous poll are news; an old issue
540
- // that mentions me is caught by the comment feed when someone replies.
541
- const createdAt = Date.parse(issue.created_at ?? issue.createdAt ?? "");
542
- if (since != null && Number.isFinite(createdAt) && createdAt <= since) continue;
543
- events.push({
544
- key: `issue:${issue.number}:${role}:${issue.updated_at ?? issue.updatedAt ?? ""}`,
545
- kind: "issue",
546
- role,
547
- repo: activeRepo,
548
- label: "Issue",
549
- ref: `#${issue.number}`,
550
- title: singleLine(issue.title ?? ""),
551
- url: issue.html_url ?? "",
552
- at: issue.created_at ?? issue.createdAt ?? null,
553
- });
554
- }
555
- return events;
556
- }
557
-
1
+ #!/usr/bin/env node
2
+ // GitHub inbox — turn GitHub-side facts (main-branch CI, open PR checks/reviews,
3
+ // issue and PR comments) into one-line local events so a development agent does
4
+ // not have to wait for the user to mention a failure.
5
+ //
6
+ // Owns:
7
+ // - pure event extraction / dedupe / recovery logic (unit-tested, no network)
8
+ // - the `gh` transport (single 20s timeout per call, failures become a
9
+ // `github-inbox: skipped (...)` line with exit code 0)
10
+ // - local state `.work/github-inbox/state.json` and the append-only log
11
+ // `.work/github-inbox/pending.md`
12
+ //
13
+ // Not owned here: scheduling (see .work/github-inbox/README.md; the repository
14
+ // intentionally does not create a Windows scheduled task).
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+ import { execFileSync } from "node:child_process";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ /** Fallback repository when nothing else names one: --repo, INBOX_REPO, or the git remote. */
21
+ export const REPO = "unknown/unknown";
22
+
23
+ /** The repository this process watches; `--repo` or INBOX_REPO overrides. */
24
+ let activeRepo = REPO;
25
+
26
+ export function setRepo(repo) {
27
+ if (typeof repo === "string" && /^[\w.-]+\/[\w.-]+$/u.test(repo)) activeRepo = repo;
28
+ }
29
+
30
+ export function watchedRepo() {
31
+ return activeRepo;
32
+ }
33
+
34
+ /**
35
+ * Who this inbox speaks for: `{ kind, login, token }`. Null means "do not
36
+ * filter", which is only honest when the caller really is the only identity.
37
+ */
38
+ let activeIdentity = null;
39
+
40
+ export function setIdentity(identity) {
41
+ if (!identity || typeof identity !== "object") {
42
+ activeIdentity = null;
43
+ return;
44
+ }
45
+ const login =
46
+ typeof identity.login === "string" && identity.login.length > 0 ? identity.login : null;
47
+ const token =
48
+ typeof identity.token === "string" && identity.token.length > 0 ? identity.token : null;
49
+ activeIdentity = { kind: identity.kind === "app" ? "app" : "user", login, token };
50
+ }
51
+
52
+ export function watchedIdentity() {
53
+ return activeIdentity;
54
+ }
55
+
56
+ /** Login the events are filtered against; null means "no filter". */
57
+ export function meLogin() {
58
+ return activeIdentity?.login ?? null;
59
+ }
60
+
61
+ export const MAX_SEEN = 500;
62
+ export const GH_TIMEOUT_MS = 20_000;
63
+
64
+ const FAILED_CONCLUSIONS = new Set(["failure", "timed_out", "startup_failure", "action_required"]);
65
+ const FAILED_CHECK_STATES = new Set([
66
+ "FAILURE",
67
+ "ERROR",
68
+ "TIMED_OUT",
69
+ "CANCELLED",
70
+ "ACTION_REQUIRED",
71
+ "STARTUP_FAILURE",
72
+ ]);
73
+ const RUN_FIELDS =
74
+ "databaseId,name,displayTitle,conclusion,headSha,headBranch,workflowName,createdAt,url,event";
75
+ const PR_FIELDS =
76
+ "number,title,headRefName,headRefOid,url,statusCheckRollup,reviewDecision,updatedAt,author,reviewRequests,assignees,isDraft,mergeStateStatus";
77
+ // Order inside one notice: something to fix first, then what is waiting on a
78
+ // person, then conversation.
79
+ const KIND_ORDER = { recovered: 0, security: 1, ci: 2, pr: 3, review: 4, comment: 5, issue: 6 };
80
+ /** How a GitHub notification reason maps onto the role vocabulary. */
81
+ const NOTIFICATION_ROLES = {
82
+ review_requested: "reviewer",
83
+ assign: "assignee",
84
+ author: "author",
85
+ state_change: "author",
86
+ mention: "mention",
87
+ team_mention: "mention",
88
+ comment: "mention",
89
+ subscribed: "mention",
90
+ ci_activity: "ci",
91
+ };
92
+
93
+ const USAGE = `github-inbox — GitHub event inbox for local development
94
+
95
+ Usage:
96
+ node scripts/github-inbox.mjs [--poll] [--all] [--json] [--quiet]
97
+
98
+ --poll (default) fetch events, dedupe against state, print only new ones
99
+ --all print the latest 20 main-branch runs and open PR check status
100
+ --json machine-readable output
101
+ --quiet suppress the "no new events" status line (new events still print)
102
+ --repeat list current events without the local seen filter (the bridge owns delivery state)
103
+ --repo <owner/name> watch a repository; repeat for several
104
+ (default: INBOX_REPO, comma or space separated, else this git remote)
105
+ --clear <scope> mark the notification threads this poll read as read:
106
+ repo (the watched repositories) or off (default off; the
107
+ bridge sets it). GitHub has no "done" API, so this clears
108
+ the unread badge, not the inbox history. Only threads from
109
+ the repositories this instance reads are touched.
110
+
111
+ Security: open Dependabot and code-scanning alerts are read as well. A repository
112
+ without either feature answers 403/404, which is reported (in --json)
113
+ instead of skipped, so one missing feature never hides the rest.
114
+
115
+ State: .work/github-inbox/state.json (one slice per repository)
116
+ History: .work/github-inbox/pending.md`;
117
+
118
+ // ---------------------------------------------------------------------------
119
+ // Small shared helpers
120
+ // ---------------------------------------------------------------------------
121
+
122
+ export function singleLine(value) {
123
+ return String(value ?? "")
124
+ .replace(/\s+/gu, " ")
125
+ .trim();
126
+ }
127
+
128
+ function compact(parts) {
129
+ return parts.filter(Boolean).join(" ").replace(/\s+/gu, " ").trim();
130
+ }
131
+
132
+ function pad(value) {
133
+ return String(value).padStart(2, "0");
134
+ }
135
+
136
+ function localDay(date) {
137
+ const value = date instanceof Date && !Number.isNaN(date.getTime()) ? date : new Date();
138
+ return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;
139
+ }
140
+
141
+ function localClock(value) {
142
+ const date = value instanceof Date ? value : new Date(value);
143
+ if (Number.isNaN(date.getTime())) return localClock(new Date());
144
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
145
+ }
146
+
147
+ function toIso(value) {
148
+ const date = value instanceof Date ? value : new Date(value ?? Date.now());
149
+ return Number.isNaN(date.getTime()) ? new Date().toISOString() : date.toISOString();
150
+ }
151
+
152
+ function excerptOf(text, limit = 120) {
153
+ const firstLine =
154
+ String(text ?? "")
155
+ .split(/\r?\n/u)
156
+ .map((line) => line.trim())
157
+ .find(Boolean) ?? "";
158
+ const stripped = firstLine.replace(/^[#>*\-+\s]+/u, "").trim();
159
+ return (stripped || singleLine(text)).slice(0, limit);
160
+ }
161
+
162
+ function issueNumberFromApiUrl(url) {
163
+ const match = /\/issues\/(\d+)(?:[/?#].*)?$/u.exec(String(url ?? ""));
164
+ return match ? Number(match[1]) : null;
165
+ }
166
+
167
+ function commentIdFromApiUrl(url) {
168
+ const match = /\/comments\/(\d+)(?:[/?#].*)?$/u.exec(String(url ?? ""));
169
+ return match ? match[1] : null;
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Pure state / event logic (no network, no filesystem)
174
+ // ---------------------------------------------------------------------------
175
+
176
+ export function normalizeState(state) {
177
+ const source = state && typeof state === "object" ? state : {};
178
+ const seen = {};
179
+ if (source.seen && typeof source.seen === "object" && !Array.isArray(source.seen)) {
180
+ for (const [key, value] of Object.entries(source.seen)) {
181
+ if (typeof key === "string" && typeof value === "string") seen[key] = value;
182
+ }
183
+ }
184
+ const lastPrStatus = {};
185
+ if (
186
+ source.lastPrStatus &&
187
+ typeof source.lastPrStatus === "object" &&
188
+ !Array.isArray(source.lastPrStatus)
189
+ ) {
190
+ for (const [number, digest] of Object.entries(source.lastPrStatus)) {
191
+ if (typeof digest === "string") lastPrStatus[number] = digest;
192
+ }
193
+ }
194
+ const lastRun =
195
+ source.lastRun && typeof source.lastRun === "object" && source.lastRun.id != null
196
+ ? { id: source.lastRun.id, conclusion: source.lastRun.conclusion ?? null }
197
+ : null;
198
+ const lastPoll =
199
+ source.lastPoll && typeof source.lastPoll === "object"
200
+ ? {
201
+ at: typeof source.lastPoll.at === "string" ? source.lastPoll.at : null,
202
+ as: typeof source.lastPoll.as === "string" ? source.lastPoll.as : null,
203
+ repo: typeof source.lastPoll.repo === "string" ? source.lastPoll.repo : null,
204
+ durationMs: Number.isFinite(source.lastPoll.durationMs) ? source.lastPoll.durationMs : null,
205
+ events: Number.isFinite(source.lastPoll.events) ? source.lastPoll.events : null,
206
+ }
207
+ : null;
208
+ return {
209
+ version: 2,
210
+ lastPollAt: typeof source.lastPollAt === "string" ? source.lastPollAt : null,
211
+ lastPoll,
212
+ seen,
213
+ lastRun,
214
+ lastPrStatus,
215
+ };
216
+ }
217
+
218
+ /**
219
+ * One repo's slice of the state file. A 2.0/2.1 file kept everything at the top
220
+ * level for the single repo it watched; it is adopted as the slice of the repo
221
+ * its last poll named, so the first multi-repo poll does not re-send the world.
222
+ */
223
+ export function normalizeStateFile(state) {
224
+ const source = state && typeof state === "object" ? state : {};
225
+ const repos = {};
226
+ if (source.repos && typeof source.repos === "object" && !Array.isArray(source.repos)) {
227
+ for (const [repo, slice] of Object.entries(source.repos)) {
228
+ if (/^[\w.-]+\/[\w.-]+$/u.test(repo)) repos[repo] = normalizeState(slice);
229
+ }
230
+ }
231
+ if (Object.keys(repos).length === 0 && (source.seen || source.lastPollAt)) {
232
+ const legacy = normalizeState(source);
233
+ const repo = legacy.lastPoll?.repo ?? null;
234
+ if (repo) repos[repo] = legacy;
235
+ }
236
+ return { version: 2, repos };
237
+ }
238
+
239
+ export function sliceOf(stateFile, repo) {
240
+ const file = normalizeStateFile(stateFile);
241
+ return file.repos[repo] ?? normalizeState({});
242
+ }
243
+
244
+ /**
245
+ * Attach the repository to every event and put it in the key. The same PR
246
+ * number in two repositories is two different facts; a shared queue must not
247
+ * collapse them into one.
248
+ */
249
+ export function tagEvents(repo, events = []) {
250
+ return (Array.isArray(events) ? events : []).map((event) => ({
251
+ ...event,
252
+ repo,
253
+ key: `${repo}#${event.key}`,
254
+ }));
255
+ }
256
+
257
+ const IN_PROGRESS_CHECK_STATES = new Set(["QUEUED", "IN_PROGRESS", "PENDING", "WAITING", "REQUESTED"]);
258
+
259
+ // A pull request that cannot be merged is work, even when nothing failed: the
260
+ // branch has to be rebased or the conflict resolved. These two states are the
261
+ // ones a person has to act on; BLOCKED/UNSTABLE are already covered by the
262
+ // review and check digests.
263
+ const BLOCKED_MERGE_STATES = new Set(["DIRTY", "BEHIND"]);
264
+
265
+ export function mergeBlocker(pr) {
266
+ const state = String(pr?.mergeStateStatus ?? "").toUpperCase();
267
+ if (BLOCKED_MERGE_STATES.has(state)) return state;
268
+ // `gh pr list --json mergeable` answers CONFLICTING when the merge is dirty;
269
+ // accept it so the older field shape keeps working.
270
+ return String(pr?.mergeable ?? "").toUpperCase() === "CONFLICTING" ? "DIRTY" : null;
271
+ }
272
+
273
+ export function prStatusDigest(pr) {
274
+ // 摘要只反映“需要你处理的状态”:失败的检查与评审决定。
275
+ // 进行中或成功完成的检查不进 key,否则同一 PR 在检查跑完前会被反复当成新事件。
276
+ const failing = failingCheckNames(pr).sort();
277
+ const blocker = mergeBlocker(pr);
278
+ // 只在真的冲突/落后时才把合并状态写进 key:合并干净的 PR 保持原来的 key,
279
+ // 已投递的事实不会因为一次格式变化被重新提醒一次。
280
+ const merge = blocker ? `|merge:${blocker}` : "";
281
+ return `failed[${failing.join(",")}]|review:${String(pr?.reviewDecision ?? "").toUpperCase() || "NONE"}${merge}`;
282
+ }
283
+
284
+ export function failingCheckNames(pr) {
285
+ const rollup = Array.isArray(pr?.statusCheckRollup) ? pr.statusCheckRollup : [];
286
+ return rollup
287
+ .filter((check) => {
288
+ const state = String(check?.state ?? "").toUpperCase();
289
+ const conclusion = String(check?.conclusion ?? "").toUpperCase();
290
+ return FAILED_CHECK_STATES.has(state) || FAILED_CHECK_STATES.has(conclusion);
291
+ })
292
+ .map((check) => check?.name ?? check?.context ?? check?.workflowName ?? "check");
293
+ }
294
+
295
+ export function extractRunEvents(runs = [], state = {}) {
296
+ const list = Array.isArray(runs) ? runs.filter(Boolean) : [];
297
+ const previous = normalizeState(state);
298
+ // A first poll has nothing to compare against: the window may hold failures
299
+ // that people already know about (a red run from two days ago). Report only
300
+ // the newest completed run — the current state of the branch — and let the
301
+ // next poll start from that baseline.
302
+ const bootstrap = !previous.lastPollAt;
303
+ const newestCompleted = list.find((run) => run.conclusion);
304
+ const events = [];
305
+ const seenGroups = new Set();
306
+ for (const run of list) {
307
+ const id = run.databaseId ?? run.id;
308
+ if (id == null || !FAILED_CONCLUSIONS.has(run.conclusion)) continue;
309
+ if (bootstrap && run !== newestCompleted) continue;
310
+ // A startup failure almost always means the runner could not start the
311
+ // job (billing, permissions): no code change fixes it, so it is grouped
312
+ // and reported once instead of once per retried run.
313
+ const infra = run.conclusion === "startup_failure";
314
+ // A scheduled workflow is the one thing nobody is watching run: it fires at
315
+ // night on the default branch, and its failure looks exactly like the last
316
+ // push failing unless the fact says which one it was.
317
+ const scheduled = String(run.event ?? "") === "schedule";
318
+ const group = `${singleLine(run.workflowName ?? run.name ?? "ci")}|${singleLine(
319
+ run.headBranch ?? "",
320
+ )}`;
321
+ if (seenGroups.has(group)) continue;
322
+ seenGroups.add(group);
323
+ events.push({
324
+ key: infra ? `infra:${group}` : `run:${id}`,
325
+ kind: infra ? "infra" : "ci",
326
+ label: scheduled ? "Scheduled" : "CI",
327
+ runId: id,
328
+ group,
329
+ scheduled,
330
+ conclusion: run.conclusion,
331
+ title: singleLine(run.displayTitle ?? run.name ?? ""),
332
+ name: singleLine(run.name ?? ""),
333
+ sha: String(run.headSha ?? "").slice(0, 7),
334
+ url: run.url ?? run.html_url ?? "",
335
+ at: run.createdAt ?? run.created_at ?? null,
336
+ });
337
+ }
338
+
339
+ // Recovered: the newest completed run succeeded and the previous poll left
340
+ // off on a failed run. In-progress runs are ignored so a fix pushed between
341
+ // two polls is still reported once the run finishes.
342
+ const completed = list.filter((run) => run.conclusion);
343
+ const latest = completed[0];
344
+ const lastRun = normalizeState(state).lastRun;
345
+ if (
346
+ latest &&
347
+ latest.conclusion === "success" &&
348
+ lastRun &&
349
+ FAILED_CONCLUSIONS.has(lastRun.conclusion)
350
+ ) {
351
+ const id = latest.databaseId ?? latest.id;
352
+ events.push({
353
+ key: `run:${id}:recovered`,
354
+ kind: "recovered",
355
+ label: String(latest.event ?? "") === "schedule" ? "Scheduled" : "CI",
356
+ runId: id,
357
+ conclusion: "success",
358
+ group: `${singleLine(latest.workflowName ?? latest.name ?? "ci")}|${singleLine(
359
+ latest.headBranch ?? "",
360
+ )}`,
361
+ title: singleLine(latest.displayTitle ?? latest.name ?? ""),
362
+ name: singleLine(latest.name ?? ""),
363
+ sha: String(latest.headSha ?? "").slice(0, 7),
364
+ url: latest.url ?? latest.html_url ?? "",
365
+ at: latest.createdAt ?? latest.created_at ?? null,
366
+ });
367
+ }
368
+ return events;
369
+ }
370
+
371
+ /**
372
+ * How `me` is involved in one pull request: `author`, `reviewer`, `assignee`,
373
+ * or null (not involved). `me === null` means "no filter" and returns `any`.
374
+ * Review requests arrive as `reviewRequests` from `gh pr list` and as
375
+ * `requested_reviewers` from the REST API; both shapes are accepted.
376
+ */
377
+ export function prRole(pr, me) {
378
+ if (!me) return "any";
379
+ const login = (entry) => entry?.login ?? null;
380
+ if (login(pr?.author) === me) return "author";
381
+ const reviewers = Array.isArray(pr?.reviewRequests)
382
+ ? pr.reviewRequests
383
+ : Array.isArray(pr?.requested_reviewers)
384
+ ? pr.requested_reviewers
385
+ : [];
386
+ if (reviewers.some((entry) => login(entry) === me)) return "reviewer";
387
+ if ((Array.isArray(pr?.assignees) ? pr.assignees : []).some((entry) => login(entry) === me))
388
+ return "assignee";
389
+ return null;
390
+ }
391
+
392
+ /**
393
+ * Whether `text` mentions `login`. GitHub renders App mentions without the
394
+ * `[bot]` suffix, so `noema-agent[bot]` is matched as `noema-agent`.
395
+ */
396
+ export function mentionsLogin(text, login) {
397
+ if (!login) return false;
398
+ const handle = login.replace(/\[bot\]$/u, "");
399
+ if (handle.length === 0) return false;
400
+ const escaped = handle.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
401
+ return new RegExp(`(^|[^\\w./-])@${escaped}(?![\\w-])`, "iu").test(String(text ?? ""));
402
+ }
403
+
404
+ export function extractPrEvents(prs = [], { me = null } = {}) {
405
+ const events = [];
406
+ for (const pr of Array.isArray(prs) ? prs : []) {
407
+ const number = pr?.number;
408
+ if (!number) continue;
409
+ const role = prRole(pr, me);
410
+ // An event belongs to an identity, not to a repository: the reviewer asked
411
+ // for me is my task, the author waiting for someone else is not.
412
+ if (role === null) continue;
413
+ const review = String(pr?.reviewDecision ?? "").toUpperCase();
414
+ const failing = failingCheckNames(pr);
415
+ const blocker = mergeBlocker(pr);
416
+ const reasons = [];
417
+ if (role === "reviewer") {
418
+ // Already reviewed: the ball is back with the author.
419
+ if (review === "CHANGES_REQUESTED") continue;
420
+ reasons.push("review requested from you");
421
+ } else {
422
+ if (failing.length) reasons.push(`checks failed: ${failing.slice(0, 4).join(", ")}`);
423
+ if (review === "CHANGES_REQUESTED") reasons.push("changes requested");
424
+ // Merging is the author's job, not the reviewer's: a reviewer reading a
425
+ // conflicted PR has nothing to do about the conflict.
426
+ if (blocker === "DIRTY") reasons.push("merge conflict with the base branch");
427
+ if (blocker === "BEHIND") reasons.push("behind the base branch");
428
+ }
429
+ if (reasons.length === 0) continue;
430
+ // A reviewer's key must not move when checks change: it is the same review
431
+ // task until they actually review.
432
+ const digest = role === "reviewer" ? "review-requested" : prStatusDigest(pr);
433
+ events.push({
434
+ key: `pr:${number}:${role}:${digest}`,
435
+ kind: "pr",
436
+ role,
437
+ repo: activeRepo,
438
+ label: "PR",
439
+ number,
440
+ title: singleLine(pr?.title ?? ""),
441
+ headRefName: pr?.headRefName ?? "",
442
+ reasons,
443
+ url: pr?.url ?? "",
444
+ at: pr?.updatedAt ?? pr?.updated_at ?? null,
445
+ });
446
+ }
447
+ return events;
448
+ }
449
+
450
+ /**
451
+ * Review comments on pull requests I authored. GitHub has no "done" state for a
452
+ * comment, so the only honest closure is the code itself: a comment is written
453
+ * against a commit (`commit_id`), and once the branch has moved past that commit
454
+ * the remark has been answered. The key therefore carries the comment id, while
455
+ * the event is only reported while the comment still sits on the current tip —
456
+ * a push that addresses it makes the source go quiet, which closes it.
457
+ */
458
+ export function extractReviewCommentEvents(comments = [], { me = null, prs = [] } = {}) {
459
+ const mine = new Map();
460
+ for (const pr of Array.isArray(prs) ? prs : []) {
461
+ if (pr?.number != null && prRole(pr, me) === "author") mine.set(pr.number, pr);
462
+ }
463
+ const events = [];
464
+ for (const comment of Array.isArray(comments) ? comments : []) {
465
+ const number = Number(String(comment?.pull_request_url ?? "").split("/").pop());
466
+ const pr = mine.get(number);
467
+ if (!pr) continue;
468
+ // My own replies are not news.
469
+ if (me && comment?.user?.login === me) continue;
470
+ const written = comment?.commit_id ?? null;
471
+ if (pr.headRefOid && written && String(pr.headRefOid) !== String(written)) continue;
472
+ const id = comment?.id;
473
+ if (!id) continue;
474
+ const where = [comment?.path, comment?.line ?? comment?.original_line]
475
+ .filter((part) => part != null && part !== "")
476
+ .join(":");
477
+ events.push({
478
+ key: `pr:${number}:review:${id}`,
479
+ kind: "review",
480
+ role: "author",
481
+ repo: activeRepo,
482
+ label: "Review",
483
+ number,
484
+ ref: where,
485
+ title: `${comment?.user?.login ?? "someone"}: ${singleLine(comment?.body ?? "").slice(0, 120)}`,
486
+ url: comment?.html_url ?? pr?.url ?? "",
487
+ at: comment?.created_at ?? null,
488
+ });
489
+ }
490
+ return events;
491
+ }
492
+
493
+ export function extractNotificationEvents(notifications = [], { repo = REPO } = {}) {
494
+ const events = [];
495
+ for (const notification of Array.isArray(notifications) ? notifications : []) {
496
+ const subject = notification?.subject;
497
+ if (!subject) continue;
498
+ // CI suites are covered by the main-branch run feed; PR check state is
499
+ // covered by the open-PR feed. Keep this feed for comments / issues only.
500
+ if (subject.type !== "Issue" && subject.type !== "PullRequest") continue;
501
+ if (notification.reason === "ci_activity") continue;
502
+ const number = issueNumberFromApiUrl(subject.url);
503
+ if (!number) continue;
504
+ const commentId = commentIdFromApiUrl(subject.latest_comment_url);
505
+ const repoFullName = notification.repository?.full_name ?? repo;
506
+ const htmlBase = `https://github.com/${repoFullName}/issues/${number}`;
507
+ const subjectKind = subject.type === "PullRequest" ? "PR" : "issue";
508
+ const title = singleLine(subject.title ?? `#${number}`);
509
+ const at = notification.updated_at ?? null;
510
+ const role = NOTIFICATION_ROLES[notification.reason] ?? "mention";
511
+ if (commentId) {
512
+ events.push({
513
+ key: `comment:${commentId}:${role}`,
514
+ kind: "comment",
515
+ role,
516
+ repo: repoFullName,
517
+ label: "Comment",
518
+ ref: `${subjectKind} #${number}`,
519
+ title,
520
+ url: `${htmlBase}#issuecomment-${commentId}`,
521
+ at,
522
+ });
523
+ } else if (subject.type === "Issue") {
524
+ events.push({
525
+ key: `issue:${number}:${role}:${at ?? ""}`,
526
+ kind: "issue",
527
+ role,
528
+ repo: repoFullName,
529
+ label: "Issue",
530
+ ref: `#${number}`,
531
+ title,
532
+ url: htmlBase,
533
+ at,
534
+ });
535
+ }
536
+ // A PullRequest notification without a comment (assignment, review,
537
+ // check suite) is covered by the open-PR feed, which carries the check
538
+ // digest; emitting an "issue" line here would duplicate or mislabel it.
539
+ }
540
+ return events;
541
+ }
542
+
543
+ export function extractCommentEvents(comments = [], { me = null } = {}) {
544
+ const events = [];
545
+ for (const comment of Array.isArray(comments) ? comments : []) {
546
+ const id = comment?.id;
547
+ if (id == null) continue;
548
+ // Without an identity every comment in the repository is "news"; with one,
549
+ // only a comment that names me is a task for me.
550
+ if (me && (comment?.user?.login === me || !mentionsLogin(comment?.body, me))) continue;
551
+ const number = issueNumberFromApiUrl(comment.issue_url);
552
+ events.push({
553
+ key: `comment:${id}:mention`,
554
+ kind: "comment",
555
+ role: "mention",
556
+ repo: activeRepo,
557
+ label: "Comment",
558
+ ref: number ? `#${number}` : "comment",
559
+ title: excerptOf(comment.body) || `comment by ${comment.user?.login ?? "unknown"}`,
560
+ url: comment.html_url ?? "",
561
+ at: comment.created_at ?? comment.updated_at ?? null,
562
+ });
563
+ }
564
+ return events;
565
+ }
566
+
567
+ export function extractIssueEvents(issues = [], state = {}, { me = null } = {}) {
568
+ const since =
569
+ typeof state?.lastPollAt === "string" && Number.isFinite(Date.parse(state.lastPollAt))
570
+ ? Date.parse(state.lastPollAt)
571
+ : null;
572
+ const events = [];
573
+ for (const issue of Array.isArray(issues) ? issues : []) {
574
+ if (!issue || issue.pull_request || issue.number == null) continue;
575
+ const role = me
576
+ ? issue?.user?.login === me
577
+ ? "author"
578
+ : (Array.isArray(issue?.assignees) ? issue.assignees : []).some(
579
+ (entry) => entry?.login === me,
580
+ )
581
+ ? "assignee"
582
+ : mentionsLogin(issue?.body, me)
583
+ ? "mention"
584
+ : null
585
+ : "any";
586
+ if (role === null) continue;
587
+ // Only issues that started after the previous poll are news; an old issue
588
+ // that mentions me is caught by the comment feed when someone replies.
589
+ const createdAt = Date.parse(issue.created_at ?? issue.createdAt ?? "");
590
+ if (since != null && Number.isFinite(createdAt) && createdAt <= since) continue;
591
+ events.push({
592
+ key: `issue:${issue.number}:${role}:${issue.updated_at ?? issue.updatedAt ?? ""}`,
593
+ kind: "issue",
594
+ role,
595
+ repo: activeRepo,
596
+ label: "Issue",
597
+ ref: `#${issue.number}`,
598
+ title: singleLine(issue.title ?? ""),
599
+ url: issue.html_url ?? "",
600
+ at: issue.created_at ?? issue.createdAt ?? null,
601
+ });
602
+ }
603
+ return events;
604
+ }
605
+
558
606
  const SEVERITY_ORDER = ["critical", "high", "medium", "low"];
559
607
 
560
608
  function severityRank(word) {
@@ -630,452 +678,501 @@ export function extractSecurityEvents(alerts = []) {
630
678
  return events;
631
679
  }
632
680
 
633
- export function extractEvents(
634
- { runs = [], prs = [], notifications = [], comments = [], issues = [], security = [] } = {},
635
- state = {},
636
- { me = null } = {},
637
- ) {
638
- const events = [
639
- ...extractRunEvents(runs, state),
640
- ...extractPrEvents(prs, { me }),
641
- ...extractNotificationEvents(notifications),
642
- ...extractCommentEvents(comments, { me }),
643
- ...extractIssueEvents(issues, state, { me }),
644
- ...extractSecurityEvents(security),
645
- ];
646
- // Every event names the repository it came from and how this identity is
647
- // involved, so delivery never has to guess either from the session's cwd.
648
- return events.map((event) => ({
649
- repo: activeRepo,
650
- role: event.kind === "ci" || event.kind === "recovered" ? "ci" : "any",
651
- ...event,
652
- }));
653
- }
654
-
655
- export function sortEvents(events = []) {
656
- return [...events].sort(
657
- (left, right) => (KIND_ORDER[left.kind] ?? 9) - (KIND_ORDER[right.kind] ?? 9),
658
- );
659
- }
660
-
661
- export function diffEvents(events = [], state = {}) {
662
- const seen = normalizeState(state).seen;
663
- const fresh = [];
664
- const inBatch = new Set();
665
- for (const event of Array.isArray(events) ? events : []) {
666
- if (!event || !event.key || inBatch.has(event.key)) continue;
667
- if (Object.prototype.hasOwnProperty.call(seen, event.key)) continue;
668
- inBatch.add(event.key);
669
- fresh.push(event);
670
- }
671
- return fresh;
672
- }
673
-
674
- export function updateState(
675
- state,
676
- { runs = [], prs = [], events = [], now = new Date(), meta = null } = {},
677
- ) {
678
- const previous = normalizeState(state);
679
- const seen = { ...previous.seen };
680
- const stamp = toIso(now);
681
- for (const event of Array.isArray(events) ? events : []) {
682
- // First-seen timestamp is kept: a repeated poll must not rewrite history.
683
- if (event?.key && !Object.prototype.hasOwnProperty.call(seen, event.key))
684
- seen[event.key] = stamp;
685
- }
686
- const completed = (Array.isArray(runs) ? runs : []).filter((run) => run && run.conclusion);
687
- const newestCompleted = completed[0];
688
- const lastRun = newestCompleted
689
- ? {
690
- id: newestCompleted.databaseId ?? newestCompleted.id,
691
- conclusion: newestCompleted.conclusion,
692
- }
693
- : previous.lastRun;
694
- const lastPrStatus = {};
695
- for (const pr of Array.isArray(prs) ? prs : []) {
696
- if (pr?.number != null) lastPrStatus[pr.number] = prStatusDigest(pr);
697
- }
698
- return {
699
- version: 1,
700
- lastPollAt: stamp,
701
- // What the last poll actually did: which identity read the repository and how
702
- // long it took. `status` reports this instead of guessing.
703
- lastPoll: {
704
- at: stamp,
705
- as: meta?.as ?? previous.lastPoll?.as ?? null,
706
- repo: meta?.repo ?? previous.lastPoll?.repo ?? null,
707
- durationMs: meta?.durationMs ?? previous.lastPoll?.durationMs ?? null,
708
- events: Array.isArray(events) ? events.length : 0,
709
- },
710
- seen: Object.fromEntries(Object.entries(seen).slice(-MAX_SEEN)),
711
- lastRun,
712
- lastPrStatus,
713
- };
714
- }
715
-
716
- // One poll, with every remote read injected so tests stay fully offline.
717
- // A failed `gh run list` / `gh pr list` aborts the poll (state untouched, so
718
- // the events are retried on the next poll); a failed comments feed is tolerated.
719
- export function pollOnce({
720
- state,
721
- repeat = false,
722
- now = new Date(),
723
- me = null,
724
- clear = "off",
725
- fetchRuns,
726
- fetchPrs,
727
- fetchFeed = () => ({ ok: true, source: "none", notifications: [], comments: [], issues: [] }),
728
- fetchIssues,
729
- fetchSecurity,
730
- markRead,
731
- } = {}) {
732
- const runsResult =
733
- typeof fetchRuns === "function" ? fetchRuns() : { ok: false, reason: "no run source" };
734
- if (!runsResult || runsResult.ok !== true) {
735
- return { skipped: runsResult?.reason ?? "gh run list failed" };
736
- }
737
- const prsResult = typeof fetchPrs === "function" ? fetchPrs() : { ok: true, value: [] };
738
- if (!prsResult || prsResult.ok !== true) {
739
- return { skipped: prsResult?.reason ?? "gh pr list failed" };
740
- }
741
- const feedResult = typeof fetchFeed === "function" ? fetchFeed(state) : { ok: true };
742
- const feed = feedResult && feedResult.ok === true ? feedResult : {};
743
- // 独立拉取 open issues:GitHub 的 notifications 只包含“你订阅的线程”,
744
- // 公开仓库里别人新开的 issue 不会出现在那里,收件箱会因此静默漏掉协作请求。
745
- const issuesResult =
746
- typeof fetchIssues === "function" ? fetchIssues() : { ok: true, value: [] };
747
- const issues = [];
748
- const issueNumbers = new Set();
749
- for (const issue of [
750
- ...(Array.isArray(issuesResult.value) ? issuesResult.value : []),
751
- ...(Array.isArray(feed.issues) ? feed.issues : []),
752
- ]) {
753
- const number = issue?.number;
754
- if (number != null && issueNumbers.has(number)) continue;
755
- if (number != null) issueNumbers.add(number);
756
- issues.push(issue);
757
- }
758
- // Security advisories are optional: a repository without Dependabot, or a
759
- // token without the security scopes, answers 403/404. That must not skip the
760
- // poll — it only means this instance cannot see those facts, and the reason
761
- // is reported instead of swallowed.
762
- const securityResult =
763
- typeof fetchSecurity === "function" ? fetchSecurity() : { alerts: [], notes: [] };
764
- const security = Array.isArray(securityResult?.alerts) ? securityResult.alerts : [];
765
- const securityNotes = Array.isArray(securityResult?.notes) ? securityResult.notes : [];
766
- const payload = {
767
- // The default branch always counts; a feature branch counts only while this
768
- // identity has an open PR from it.
769
- runs: filterRuns(
770
- Array.isArray(runsResult.value) ? runsResult.value : [],
771
- Array.isArray(prsResult.value) ? prsResult.value : [],
772
- me,
773
- ),
774
- prs: Array.isArray(prsResult.value) ? prsResult.value : [],
775
- notifications: Array.isArray(feed.notifications) ? feed.notifications : [],
776
- comments: Array.isArray(feed.comments) ? feed.comments : [],
777
- issues,
778
- security,
779
- };
780
- const events = extractEvents(payload, state, { me });
781
- const fresh = sortEvents(repeat ? events : diffEvents(events, state));
782
- const nextState = updateState(state, { ...payload, events, now });
783
- // Reading a thread and leaving it unread is what makes an inbox unusable:
784
- // once the poll has turned these threads into events, mark them read.
785
- const threads = clearableThreads(payload.notifications, { scope: clear, repo: activeRepo });
786
- const cleared =
787
- threads.length > 0 && typeof markRead === "function"
788
- ? markRead(threads)
789
- : { cleared: [], failed: [] };
790
- return {
791
- events,
792
- fresh,
793
- nextState,
794
- cleared: cleared.cleared ?? [],
795
- clearFailed: cleared.failed ?? [],
796
- source: feed.ok === true ? (feed.source ?? null) : null,
797
- feedSkipped:
798
- feedResult && feedResult.ok === false ? (feedResult.reason ?? "feed failed") : null,
799
- securityNotes,
800
- };
801
- }
802
-
803
- // ---------------------------------------------------------------------------
804
- // Event formatting
805
- // ---------------------------------------------------------------------------
806
-
807
- export function formatEvent(event) {
808
- const title = singleLine(event.title ?? "").slice(0, 140);
809
- const sha = event.sha ? `(${event.sha})` : "";
810
- const url = singleLine(event.url ?? "");
811
- const role = event.role && event.role !== "any" && event.role !== "ci" ? `/${event.role}` : "";
812
- switch (event.kind) {
813
- case "ci": {
814
- const conclusion = event.conclusion === "failure" ? "failed" : (event.conclusion ?? "failed");
815
- return compact([`[CI] run ${event.runId}`, `${conclusion}:`, title, sha, url]);
816
- }
817
- case "recovered":
818
- return compact([`[CI] recovered: run ${event.runId} succeeded:`, title, sha, url]);
819
- case "pr":
820
- return compact([
821
- `[PR${role}] #${event.number}`,
822
- `${(event.reasons ?? []).join("; ")}:`,
823
- title,
824
- url,
825
- ]);
826
- case "comment":
827
- return compact([`[Comment${role}] ${event.ref ?? ""}:`, title, url]);
828
- case "issue":
829
- return compact([`[Issue${role}] ${event.ref ?? ""}:`, title, url]);
830
- case "security":
831
- return compact([`[${event.label ?? "Security"}]${event.ref ? ` ${event.ref}` : ""}`, title, url]);
832
- default:
833
- return compact([`[${event.label ?? event.kind ?? "event"}${role}]`, title, url]);
834
- }
835
- }
836
-
837
- function formatRunLine(run) {
838
- const id = run?.databaseId ?? run?.id ?? "?";
839
- const sha = String(run?.headSha ?? "").slice(0, 7);
840
- return compact([
841
- "[run]",
842
- run?.conclusion ?? run?.status ?? "running",
843
- String(id),
844
- sha,
845
- run?.createdAt ?? run?.created_at ?? "",
846
- "|",
847
- singleLine(run?.name ?? ""),
848
- "|",
849
- singleLine(run?.displayTitle ?? ""),
850
- "|",
851
- singleLine(run?.url ?? run?.html_url ?? ""),
852
- ]);
853
- }
854
-
855
- function formatPrLine(pr) {
856
- const checks = (Array.isArray(pr?.statusCheckRollup) ? pr.statusCheckRollup : [])
857
- .map((check) => {
858
- const name = check?.name ?? check?.context ?? check?.workflowName ?? "check";
859
- const state = check?.conclusion || check?.state || check?.status || "unknown";
860
- return `${name}=${state}`;
861
- })
862
- .join(",");
863
- return compact([
864
- "[pr]",
865
- `#${pr?.number ?? "?"}`,
866
- singleLine(pr?.headRefName ?? ""),
867
- `review=${pr?.reviewDecision || "none"}`,
868
- `updated=${pr?.updatedAt ?? pr?.updated_at ?? ""}`,
869
- "|",
870
- singleLine(pr?.title ?? ""),
871
- "|",
872
- `checks: ${checks || "no-checks"}`,
873
- "|",
874
- singleLine(pr?.url ?? ""),
875
- ]);
876
- }
877
-
878
- // ---------------------------------------------------------------------------
879
- // Local state / history files
880
- // ---------------------------------------------------------------------------
881
-
882
- export function readStateFile(file) {
883
- try {
884
- const raw = fs.readFileSync(file, "utf8");
885
- // The file is multi-repository: normalise it as a file, not as one slice, or
886
- // every poll would start from an empty `seen` and re-derive `lastRun`.
887
- return normalizeStateFile(JSON.parse(raw));
888
- } catch {
889
- // Missing or corrupt state must never break a poll; it only means the
890
- // first poll sees everything as new.
891
- return normalizeStateFile({});
892
- }
893
- }
894
-
895
- export function writeStateFile(file, state) {
896
- fs.mkdirSync(path.dirname(file), { recursive: true });
897
- const temp = `${file}.tmp`;
898
- fs.writeFileSync(temp, `${JSON.stringify(state, null, 2)}\n`, "utf8");
899
- try {
900
- fs.renameSync(temp, file);
901
- } catch {
902
- fs.copyFileSync(temp, file);
903
- fs.unlinkSync(temp);
904
- }
905
- }
906
-
907
- export function appendPendingEvents(file, events, now = new Date()) {
908
- if (!Array.isArray(events) || events.length === 0) return;
909
- fs.mkdirSync(path.dirname(file), { recursive: true });
910
- const day = localDay(now);
911
- const existing = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
912
- const lines = events.map((event) => `- ${localClock(event.at ?? now)} ${formatEvent(event)}`);
913
- let text = existing;
914
- if (!text.trim()) {
915
- text =
916
- "# GitHub inbox - new events\n\nAppended by `scripts/github-inbox.mjs`; newest at the bottom.\n";
917
- }
918
- if (!new RegExp(`(^|\\n)## ${day}(\\n|$)`, "u").test(text)) {
919
- text = `${text.replace(/\s*$/u, "")}\n\n## ${day}\n`;
920
- }
921
- const separator = text.endsWith("\n") ? "" : "\n";
922
- fs.writeFileSync(file, `${text}${separator}${lines.join("\n")}\n`, "utf8");
923
- }
924
-
925
- // ---------------------------------------------------------------------------
926
- // `gh` transport
927
- // ---------------------------------------------------------------------------
928
-
929
- let cachedGhExecutable;
930
-
931
- function resolveGhExecutable({ env = process.env, platform = process.platform } = {}) {
932
- if (cachedGhExecutable !== undefined) return cachedGhExecutable;
933
- const override = env.INBOX_GH;
934
- if (override) {
935
- cachedGhExecutable = override;
936
- return cachedGhExecutable;
937
- }
938
- if (platform === "win32") {
939
- try {
940
- const listed = execFileSync("where.exe", ["gh"], {
941
- encoding: "utf8",
942
- windowsHide: true,
943
- timeout: 5000,
944
- });
945
- const executable = listed
946
- .split(/\r?\n/u)
947
- .map((line) => line.trim())
948
- .find((line) => /\.exe$/iu.test(line) && line.length > 0);
949
- if (executable) {
950
- cachedGhExecutable = executable;
951
- return cachedGhExecutable;
952
- }
953
- } catch {
954
- // Fall through to the bare command below.
955
- }
956
- }
957
- cachedGhExecutable = "gh";
958
- return cachedGhExecutable;
959
- }
960
-
961
- export function describeGhError(error) {
962
- if (!error) return "unknown gh failure";
963
- const code = String(error.code ?? "");
964
- if (code === "ETIMEDOUT" || /timed?\s?out/iu.test(String(error.message ?? ""))) {
965
- return `gh timed out after ${Math.round(GH_TIMEOUT_MS / 1000)}s`;
966
- }
967
- const stderr = error.stderr ? String(error.stderr) : "";
968
- const stdout = error.stdout ? String(error.stdout) : "";
969
- const lastLine = (stderr || stdout).trim().split(/\r?\n/u).filter(Boolean).pop();
970
- const status = typeof error.status === "number" ? `exit ${error.status}` : "";
971
- const message = String(error.message ?? "").split(/\r?\n/u)[0] ?? "";
972
- return singleLine(
973
- [lastLine, status || message, code === "ENOENT" ? "gh not found" : ""]
974
- .filter(Boolean)
975
- .join(" | "),
976
- ).slice(0, 200);
977
- }
978
-
979
- function ghJson(args, { cwd, timeout = GH_TIMEOUT_MS } = {}) {
980
- let executable;
981
- try {
982
- executable = resolveGhExecutable();
983
- } catch (error) {
984
- return { ok: false, reason: describeGhError(error) };
985
- }
986
- const token = activeIdentity?.token ?? null;
987
- try {
988
- const stdout = execFileSync(executable, args, {
989
- cwd,
990
- encoding: "utf8",
991
- timeout,
992
- windowsHide: true,
993
- maxBuffer: 32 * 1024 * 1024,
994
- stdio: ["ignore", "pipe", "pipe"],
995
- // An App installation token only exists for this call: `gh` reads
996
- // GH_TOKEN, so the ambient login is never used for a configured identity.
997
- ...(token ? { env: { ...process.env, GH_TOKEN: token, GITHUB_TOKEN: token } } : {}),
998
- });
999
- return { ok: true, value: JSON.parse(stdout) };
1000
- } catch (error) {
1001
- return { ok: false, reason: describeGhError(error) };
1002
- }
1003
- }
1004
-
1005
- let cachedLogin;
1006
-
1007
- /**
1008
- * The login the events are filtered against. An explicit `identity.login` wins;
1009
- * otherwise the ambient `gh` login is asked once per process. A failed lookup
1010
- * returns null (no filter) rather than inventing an identity.
1011
- */
1012
- export function resolveLogin(cwd) {
1013
- const explicit = meLogin();
1014
- if (explicit) return explicit;
1015
- if (cachedLogin !== undefined) return cachedLogin;
1016
- const result = ghJson(["api", "user"], { cwd });
1017
- const login = result.ok ? (result.value?.login ?? null) : null;
1018
- cachedLogin = login;
1019
- if (login && activeIdentity) activeIdentity = { ...activeIdentity, login };
1020
- return login;
1021
- }
1022
-
1023
- export function fetchRuns(cwd) {
1024
- // No `--branch`: a branch you opened a PR from is watched too (see
1025
- // `filterRuns`), so its failures are not invisible until the PR is merged.
1026
- return ghJson(["run", "list", "--limit", "40", "--json", RUN_FIELDS], {
1027
- cwd,
1028
- });
1029
- }
1030
-
1031
- /**
1032
- * Branches whose runs are worth reading: the default branch, plus the branches
1033
- * of PRs this identity opened. Other people's feature branches stay out — their
1034
- * failures are not this agent's work.
1035
- */
1036
- export function watchedBranches(prs = [], me = null) {
1037
- const branches = new Set(["main"]);
1038
- for (const pr of Array.isArray(prs) ? prs : []) {
1039
- const branch = pr?.headRefName;
1040
- if (typeof branch !== "string" || branch.length === 0) continue;
1041
- if (prRole(pr, me) !== null) branches.add(branch);
1042
- }
1043
- return branches;
1044
- }
1045
-
1046
- export function filterRuns(runs = [], prs = [], me = null) {
1047
- const branches = watchedBranches(prs, me);
1048
- return (Array.isArray(runs) ? runs : []).filter((run) =>
1049
- branches.has(String(run?.headBranch ?? "")),
1050
- );
1051
- }
1052
-
1053
- export function fetchOpenIssues(cwd) {
1054
- return ghJson(
1055
- ["api", `repos/${activeRepo}/issues?state=open&sort=updated&direction=desc&per_page=30`],
1056
- { cwd },
1057
- );
1058
- }
1059
-
1060
- export function fetchOpenPullRequests(cwd) {
1061
- return ghJson(["pr", "list", "--state", "open", "--json", PR_FIELDS], { cwd });
1062
- }
1063
-
1064
- /**
1065
- * Open security advisories for the watched repository. Never fatal: a private
1066
- * repository on a free plan, a disabled Dependabot, or a token without the
1067
- * `security_events` scope all answer 403/404, and the poll continues.
1068
- */
1069
- export function fetchSecurityAlerts(cwd) {
1070
- const wanted = [
1071
- { source: "dependabot", path: "dependabot/alerts" },
1072
- { source: "code-scanning", path: "code-scanning/alerts" },
1073
- ];
1074
- const alerts = [];
1075
- const notes = [];
1076
- for (const { source, path } of wanted) {
1077
- const result = ghJson(["api", `repos/${activeRepo}/${path}?state=open&per_page=20`], { cwd });
1078
- if (!result.ok) {
681
+ export function extractEvents(
682
+ {
683
+ runs = [],
684
+ prs = [],
685
+ notifications = [],
686
+ comments = [],
687
+ issues = [],
688
+ security = [],
689
+ reviews = [],
690
+ } = {},
691
+ state = {},
692
+ { me = null } = {},
693
+ ) {
694
+ const events = [
695
+ ...extractRunEvents(runs, state),
696
+ ...extractPrEvents(prs, { me }),
697
+ ...extractReviewCommentEvents(reviews, { me, prs }),
698
+ ...extractNotificationEvents(notifications),
699
+ ...extractCommentEvents(comments, { me }),
700
+ ...extractIssueEvents(issues, state, { me }),
701
+ ...extractSecurityEvents(security),
702
+ ];
703
+ // Every event names the repository it came from and how this identity is
704
+ // involved, so delivery never has to guess either from the session's cwd.
705
+ return events.map((event) => ({
706
+ repo: activeRepo,
707
+ role: event.kind === "ci" || event.kind === "recovered" ? "ci" : "any",
708
+ ...event,
709
+ }));
710
+ }
711
+
712
+ export function sortEvents(events = []) {
713
+ return [...events].sort(
714
+ (left, right) => (KIND_ORDER[left.kind] ?? 9) - (KIND_ORDER[right.kind] ?? 9),
715
+ );
716
+ }
717
+
718
+ export function diffEvents(events = [], state = {}) {
719
+ const seen = normalizeState(state).seen;
720
+ const fresh = [];
721
+ const inBatch = new Set();
722
+ for (const event of Array.isArray(events) ? events : []) {
723
+ if (!event || !event.key || inBatch.has(event.key)) continue;
724
+ if (Object.prototype.hasOwnProperty.call(seen, event.key)) continue;
725
+ inBatch.add(event.key);
726
+ fresh.push(event);
727
+ }
728
+ return fresh;
729
+ }
730
+
731
+ export function updateState(
732
+ state,
733
+ { runs = [], prs = [], events = [], now = new Date(), meta = null } = {},
734
+ ) {
735
+ const previous = normalizeState(state);
736
+ const seen = { ...previous.seen };
737
+ const stamp = toIso(now);
738
+ for (const event of Array.isArray(events) ? events : []) {
739
+ // First-seen timestamp is kept: a repeated poll must not rewrite history.
740
+ if (event?.key && !Object.prototype.hasOwnProperty.call(seen, event.key))
741
+ seen[event.key] = stamp;
742
+ }
743
+ const completed = (Array.isArray(runs) ? runs : []).filter((run) => run && run.conclusion);
744
+ const newestCompleted = completed[0];
745
+ const lastRun = newestCompleted
746
+ ? {
747
+ id: newestCompleted.databaseId ?? newestCompleted.id,
748
+ conclusion: newestCompleted.conclusion,
749
+ }
750
+ : previous.lastRun;
751
+ const lastPrStatus = {};
752
+ for (const pr of Array.isArray(prs) ? prs : []) {
753
+ if (pr?.number != null) lastPrStatus[pr.number] = prStatusDigest(pr);
754
+ }
755
+ return {
756
+ version: 1,
757
+ lastPollAt: stamp,
758
+ // What the last poll actually did: which identity read the repository and how
759
+ // long it took. `status` reports this instead of guessing.
760
+ lastPoll: {
761
+ at: stamp,
762
+ as: meta?.as ?? previous.lastPoll?.as ?? null,
763
+ repo: meta?.repo ?? previous.lastPoll?.repo ?? null,
764
+ durationMs: meta?.durationMs ?? previous.lastPoll?.durationMs ?? null,
765
+ events: Array.isArray(events) ? events.length : 0,
766
+ },
767
+ seen: Object.fromEntries(Object.entries(seen).slice(-MAX_SEEN)),
768
+ lastRun,
769
+ lastPrStatus,
770
+ };
771
+ }
772
+
773
+ // One poll, with every remote read injected so tests stay fully offline.
774
+ // A failed `gh run list` / `gh pr list` aborts the poll (state untouched, so
775
+ // the events are retried on the next poll); a failed comments feed is tolerated.
776
+ export function pollOnce({
777
+ state,
778
+ repeat = false,
779
+ now = new Date(),
780
+ me = null,
781
+ clear = "off",
782
+ fetchRuns,
783
+ fetchPrs,
784
+ fetchFeed = () => ({ ok: true, source: "none", notifications: [], comments: [], issues: [] }),
785
+ fetchIssues,
786
+ fetchSecurity,
787
+ fetchReviews,
788
+ markRead,
789
+ } = {}) {
790
+ const runsResult =
791
+ typeof fetchRuns === "function" ? fetchRuns() : { ok: false, reason: "no run source" };
792
+ if (!runsResult || runsResult.ok !== true) {
793
+ return { skipped: runsResult?.reason ?? "gh run list failed" };
794
+ }
795
+ const prsResult = typeof fetchPrs === "function" ? fetchPrs() : { ok: true, value: [] };
796
+ if (!prsResult || prsResult.ok !== true) {
797
+ return { skipped: prsResult?.reason ?? "gh pr list failed" };
798
+ }
799
+ const feedResult = typeof fetchFeed === "function" ? fetchFeed(state) : { ok: true };
800
+ const feed = feedResult && feedResult.ok === true ? feedResult : {};
801
+ // 独立拉取 open issues:GitHub 的 notifications 只包含“你订阅的线程”,
802
+ // 公开仓库里别人新开的 issue 不会出现在那里,收件箱会因此静默漏掉协作请求。
803
+ const issuesResult =
804
+ typeof fetchIssues === "function" ? fetchIssues() : { ok: true, value: [] };
805
+ const issues = [];
806
+ const issueNumbers = new Set();
807
+ for (const issue of [
808
+ ...(Array.isArray(issuesResult.value) ? issuesResult.value : []),
809
+ ...(Array.isArray(feed.issues) ? feed.issues : []),
810
+ ]) {
811
+ const number = issue?.number;
812
+ if (number != null && issueNumbers.has(number)) continue;
813
+ if (number != null) issueNumbers.add(number);
814
+ issues.push(issue);
815
+ }
816
+ // Security advisories are optional: a repository without Dependabot, or a
817
+ // token without the security scopes, answers 403/404. That must not skip the
818
+ // poll — it only means this instance cannot see those facts, and the reason
819
+ // is reported instead of swallowed.
820
+ const securityResult =
821
+ typeof fetchSecurity === "function" ? fetchSecurity() : { alerts: [], notes: [] };
822
+ const security = Array.isArray(securityResult?.alerts) ? securityResult.alerts : [];
823
+ const securityNotes = Array.isArray(securityResult?.notes) ? securityResult.notes : [];
824
+ // Review comments are a feed like the others: a token that cannot read them
825
+ // reports nothing, and that must not skip the poll.
826
+ const reviewsResult =
827
+ typeof fetchReviews === "function" ? fetchReviews() : { ok: true, value: [] };
828
+ const reviews =
829
+ reviewsResult && reviewsResult.ok === true && Array.isArray(reviewsResult.value)
830
+ ? reviewsResult.value
831
+ : [];
832
+ const payload = {
833
+ // The default branch always counts; a feature branch counts only while this
834
+ // identity has an open PR from it.
835
+ runs: filterRuns(
836
+ Array.isArray(runsResult.value) ? runsResult.value : [],
837
+ Array.isArray(prsResult.value) ? prsResult.value : [],
838
+ me,
839
+ ),
840
+ prs: Array.isArray(prsResult.value) ? prsResult.value : [],
841
+ notifications: Array.isArray(feed.notifications) ? feed.notifications : [],
842
+ comments: Array.isArray(feed.comments) ? feed.comments : [],
843
+ issues,
844
+ security,
845
+ reviews,
846
+ };
847
+ const events = extractEvents(payload, state, { me });
848
+ const fresh = sortEvents(repeat ? events : diffEvents(events, state));
849
+ const nextState = updateState(state, { ...payload, events, now });
850
+ // Reading a thread and leaving it unread is what makes an inbox unusable:
851
+ // once the poll has turned these threads into events, mark them read.
852
+ const threads = clearableThreads(payload.notifications, { scope: clear, repo: activeRepo });
853
+ const cleared =
854
+ threads.length > 0 && typeof markRead === "function"
855
+ ? markRead(threads)
856
+ : { cleared: [], failed: [] };
857
+ return {
858
+ events,
859
+ fresh,
860
+ nextState,
861
+ cleared: cleared.cleared ?? [],
862
+ clearFailed: cleared.failed ?? [],
863
+ source: feed.ok === true ? (feed.source ?? null) : null,
864
+ feedSkipped:
865
+ feedResult && feedResult.ok === false ? (feedResult.reason ?? "feed failed") : null,
866
+ securityNotes,
867
+ };
868
+ }
869
+
870
+ // ---------------------------------------------------------------------------
871
+ // Event formatting
872
+ // ---------------------------------------------------------------------------
873
+
874
+ export function formatEvent(event) {
875
+ const title = singleLine(event.title ?? "").slice(0, 140);
876
+ const sha = event.sha ? `(${event.sha})` : "";
877
+ const url = singleLine(event.url ?? "");
878
+ const role = event.role && event.role !== "any" && event.role !== "ci" ? `/${event.role}` : "";
879
+ switch (event.kind) {
880
+ case "ci": {
881
+ const conclusion = event.conclusion === "failure" ? "failed" : (event.conclusion ?? "failed");
882
+ return compact([
883
+ `[${event.label ?? "CI"}] run ${event.runId}`,
884
+ `${conclusion}:`,
885
+ title,
886
+ sha,
887
+ url,
888
+ ]);
889
+ }
890
+ case "recovered":
891
+ return compact([
892
+ `[${event.label ?? "CI"}] recovered: run ${event.runId} succeeded:`,
893
+ title,
894
+ sha,
895
+ url,
896
+ ]);
897
+ case "pr":
898
+ return compact([
899
+ `[PR${role}] #${event.number}`,
900
+ `${(event.reasons ?? []).join("; ")}:`,
901
+ title,
902
+ url,
903
+ ]);
904
+ case "comment":
905
+ return compact([`[Comment${role}] ${event.ref ?? ""}:`, title, url]);
906
+ case "review":
907
+ return compact([
908
+ `[Review${role}] #${event.number}${event.ref ? ` ${event.ref}` : ""}:`,
909
+ title,
910
+ url,
911
+ ]);
912
+ case "issue":
913
+ return compact([`[Issue${role}] ${event.ref ?? ""}:`, title, url]);
914
+ case "security":
915
+ return compact([`[${event.label ?? "Security"}]${event.ref ? ` ${event.ref}` : ""}`, title, url]);
916
+ default:
917
+ return compact([`[${event.label ?? event.kind ?? "event"}${role}]`, title, url]);
918
+ }
919
+ }
920
+
921
+ function formatRunLine(run) {
922
+ const id = run?.databaseId ?? run?.id ?? "?";
923
+ const sha = String(run?.headSha ?? "").slice(0, 7);
924
+ return compact([
925
+ "[run]",
926
+ run?.conclusion ?? run?.status ?? "running",
927
+ String(id),
928
+ sha,
929
+ run?.createdAt ?? run?.created_at ?? "",
930
+ "|",
931
+ singleLine(run?.name ?? ""),
932
+ "|",
933
+ singleLine(run?.displayTitle ?? ""),
934
+ "|",
935
+ singleLine(run?.url ?? run?.html_url ?? ""),
936
+ ]);
937
+ }
938
+
939
+ function formatPrLine(pr) {
940
+ const checks = (Array.isArray(pr?.statusCheckRollup) ? pr.statusCheckRollup : [])
941
+ .map((check) => {
942
+ const name = check?.name ?? check?.context ?? check?.workflowName ?? "check";
943
+ const state = check?.conclusion || check?.state || check?.status || "unknown";
944
+ return `${name}=${state}`;
945
+ })
946
+ .join(",");
947
+ return compact([
948
+ "[pr]",
949
+ `#${pr?.number ?? "?"}`,
950
+ singleLine(pr?.headRefName ?? ""),
951
+ `review=${pr?.reviewDecision || "none"}`,
952
+ `updated=${pr?.updatedAt ?? pr?.updated_at ?? ""}`,
953
+ "|",
954
+ singleLine(pr?.title ?? ""),
955
+ "|",
956
+ `checks: ${checks || "no-checks"}`,
957
+ "|",
958
+ singleLine(pr?.url ?? ""),
959
+ ]);
960
+ }
961
+
962
+ // ---------------------------------------------------------------------------
963
+ // Local state / history files
964
+ // ---------------------------------------------------------------------------
965
+
966
+ export function readStateFile(file) {
967
+ try {
968
+ const raw = fs.readFileSync(file, "utf8");
969
+ // The file is multi-repository: normalise it as a file, not as one slice, or
970
+ // every poll would start from an empty `seen` and re-derive `lastRun`.
971
+ return normalizeStateFile(JSON.parse(raw));
972
+ } catch {
973
+ // Missing or corrupt state must never break a poll; it only means the
974
+ // first poll sees everything as new.
975
+ return normalizeStateFile({});
976
+ }
977
+ }
978
+
979
+ export function writeStateFile(file, state) {
980
+ fs.mkdirSync(path.dirname(file), { recursive: true });
981
+ const temp = `${file}.tmp`;
982
+ fs.writeFileSync(temp, `${JSON.stringify(state, null, 2)}\n`, "utf8");
983
+ try {
984
+ fs.renameSync(temp, file);
985
+ } catch {
986
+ fs.copyFileSync(temp, file);
987
+ fs.unlinkSync(temp);
988
+ }
989
+ }
990
+
991
+ export function appendPendingEvents(file, events, now = new Date()) {
992
+ if (!Array.isArray(events) || events.length === 0) return;
993
+ fs.mkdirSync(path.dirname(file), { recursive: true });
994
+ const day = localDay(now);
995
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
996
+ const lines = events.map((event) => `- ${localClock(event.at ?? now)} ${formatEvent(event)}`);
997
+ let text = existing;
998
+ if (!text.trim()) {
999
+ text =
1000
+ "# GitHub inbox - new events\n\nAppended by `scripts/github-inbox.mjs`; newest at the bottom.\n";
1001
+ }
1002
+ if (!new RegExp(`(^|\\n)## ${day}(\\n|$)`, "u").test(text)) {
1003
+ text = `${text.replace(/\s*$/u, "")}\n\n## ${day}\n`;
1004
+ }
1005
+ const separator = text.endsWith("\n") ? "" : "\n";
1006
+ fs.writeFileSync(file, `${text}${separator}${lines.join("\n")}\n`, "utf8");
1007
+ }
1008
+
1009
+ // ---------------------------------------------------------------------------
1010
+ // `gh` transport
1011
+ // ---------------------------------------------------------------------------
1012
+
1013
+ let cachedGhExecutable;
1014
+
1015
+ function resolveGhExecutable({ env = process.env, platform = process.platform } = {}) {
1016
+ if (cachedGhExecutable !== undefined) return cachedGhExecutable;
1017
+ const override = env.INBOX_GH;
1018
+ if (override) {
1019
+ cachedGhExecutable = override;
1020
+ return cachedGhExecutable;
1021
+ }
1022
+ if (platform === "win32") {
1023
+ try {
1024
+ const listed = execFileSync("where.exe", ["gh"], {
1025
+ encoding: "utf8",
1026
+ windowsHide: true,
1027
+ timeout: 5000,
1028
+ });
1029
+ const executable = listed
1030
+ .split(/\r?\n/u)
1031
+ .map((line) => line.trim())
1032
+ .find((line) => /\.exe$/iu.test(line) && line.length > 0);
1033
+ if (executable) {
1034
+ cachedGhExecutable = executable;
1035
+ return cachedGhExecutable;
1036
+ }
1037
+ } catch {
1038
+ // Fall through to the bare command below.
1039
+ }
1040
+ }
1041
+ cachedGhExecutable = "gh";
1042
+ return cachedGhExecutable;
1043
+ }
1044
+
1045
+ export function describeGhError(error) {
1046
+ if (!error) return "unknown gh failure";
1047
+ const code = String(error.code ?? "");
1048
+ if (code === "ETIMEDOUT" || /timed?\s?out/iu.test(String(error.message ?? ""))) {
1049
+ return `gh timed out after ${Math.round(GH_TIMEOUT_MS / 1000)}s`;
1050
+ }
1051
+ const stderr = error.stderr ? String(error.stderr) : "";
1052
+ const stdout = error.stdout ? String(error.stdout) : "";
1053
+ const lastLine = (stderr || stdout).trim().split(/\r?\n/u).filter(Boolean).pop();
1054
+ const status = typeof error.status === "number" ? `exit ${error.status}` : "";
1055
+ const message = String(error.message ?? "").split(/\r?\n/u)[0] ?? "";
1056
+ return singleLine(
1057
+ [lastLine, status || message, code === "ENOENT" ? "gh not found" : ""]
1058
+ .filter(Boolean)
1059
+ .join(" | "),
1060
+ ).slice(0, 200);
1061
+ }
1062
+
1063
+ function ghJson(args, { cwd, timeout = GH_TIMEOUT_MS } = {}) {
1064
+ let executable;
1065
+ try {
1066
+ executable = resolveGhExecutable();
1067
+ } catch (error) {
1068
+ return { ok: false, reason: describeGhError(error) };
1069
+ }
1070
+ const token = activeIdentity?.token ?? null;
1071
+ try {
1072
+ const stdout = execFileSync(executable, args, {
1073
+ cwd,
1074
+ encoding: "utf8",
1075
+ timeout,
1076
+ windowsHide: true,
1077
+ maxBuffer: 32 * 1024 * 1024,
1078
+ stdio: ["ignore", "pipe", "pipe"],
1079
+ // An App installation token only exists for this call: `gh` reads
1080
+ // GH_TOKEN, so the ambient login is never used for a configured identity.
1081
+ ...(token ? { env: { ...process.env, GH_TOKEN: token, GITHUB_TOKEN: token } } : {}),
1082
+ });
1083
+ return { ok: true, value: JSON.parse(stdout) };
1084
+ } catch (error) {
1085
+ return { ok: false, reason: describeGhError(error) };
1086
+ }
1087
+ }
1088
+
1089
+ let cachedLogin;
1090
+
1091
+ /**
1092
+ * The login the events are filtered against. An explicit `identity.login` wins;
1093
+ * otherwise the ambient `gh` login is asked once per process. A failed lookup
1094
+ * returns null (no filter) rather than inventing an identity.
1095
+ */
1096
+ export function resolveLogin(cwd) {
1097
+ const explicit = meLogin();
1098
+ if (explicit) return explicit;
1099
+ if (cachedLogin !== undefined) return cachedLogin;
1100
+ const result = ghJson(["api", "user"], { cwd });
1101
+ const login = result.ok ? (result.value?.login ?? null) : null;
1102
+ cachedLogin = login;
1103
+ if (login && activeIdentity) activeIdentity = { ...activeIdentity, login };
1104
+ return login;
1105
+ }
1106
+
1107
+ export function fetchRuns(cwd) {
1108
+ // No `--branch`: a branch you opened a PR from is watched too (see
1109
+ // `filterRuns`), so its failures are not invisible until the PR is merged.
1110
+ return ghJson(["run", "list", "--limit", "40", "--json", RUN_FIELDS], {
1111
+ cwd,
1112
+ });
1113
+ }
1114
+
1115
+ /**
1116
+ * Branches whose runs are worth reading: the default branch, plus the branches
1117
+ * of PRs this identity opened. Other people's feature branches stay out — their
1118
+ * failures are not this agent's work.
1119
+ */
1120
+ export function watchedBranches(prs = [], me = null) {
1121
+ const branches = new Set(["main"]);
1122
+ for (const pr of Array.isArray(prs) ? prs : []) {
1123
+ const branch = pr?.headRefName;
1124
+ if (typeof branch !== "string" || branch.length === 0) continue;
1125
+ if (prRole(pr, me) !== null) branches.add(branch);
1126
+ }
1127
+ return branches;
1128
+ }
1129
+
1130
+ export function filterRuns(runs = [], prs = [], me = null) {
1131
+ const branches = watchedBranches(prs, me);
1132
+ return (Array.isArray(runs) ? runs : []).filter((run) =>
1133
+ branches.has(String(run?.headBranch ?? "")),
1134
+ );
1135
+ }
1136
+
1137
+ export function fetchOpenIssues(cwd) {
1138
+ return ghJson(
1139
+ ["api", `repos/${activeRepo}/issues?state=open&sort=updated&direction=desc&per_page=30`],
1140
+ { cwd },
1141
+ );
1142
+ }
1143
+
1144
+ export function fetchOpenPullRequests(cwd) {
1145
+ return ghJson(["pr", "list", "--state", "open", "--json", PR_FIELDS], { cwd });
1146
+ }
1147
+
1148
+ /**
1149
+ * Review comments across the open pull requests, newest first. One call for the
1150
+ * whole repository is cheaper than one per PR, and it is where "someone asked me
1151
+ * to change something" actually lives: a review request says a review is wanted,
1152
+ * not what was said.
1153
+ */
1154
+ export function fetchReviewComments(cwd) {
1155
+ return ghJson(
1156
+ ["api", `repos/${activeRepo}/pulls/comments?sort=created&direction=desc&per_page=30`],
1157
+ { cwd },
1158
+ );
1159
+ }
1160
+
1161
+ /**
1162
+ * Open security advisories for the watched repository. Never fatal: a private
1163
+ * repository on a free plan, a disabled Dependabot, or a token without the
1164
+ * `security_events` scope all answer 403/404, and the poll continues.
1165
+ */
1166
+ export function fetchSecurityAlerts(cwd) {
1167
+ const wanted = [
1168
+ { source: "dependabot", path: "dependabot/alerts" },
1169
+ { source: "code-scanning", path: "code-scanning/alerts" },
1170
+ ];
1171
+ const alerts = [];
1172
+ const notes = [];
1173
+ for (const { source, path } of wanted) {
1174
+ const result = ghJson(["api", `repos/${activeRepo}/${path}?state=open&per_page=20`], { cwd });
1175
+ if (!result.ok) {
1079
1176
  const reason = String(result.reason ?? "");
1080
1177
  // gh reports a 404 "no analysis found" as a scope problem and suggests
1081
1178
  // admin:repo_hook, which cannot read code scanning. Say what actually
@@ -1088,386 +1185,387 @@ export function fetchSecurityAlerts(cwd) {
1088
1185
  : needsScope
1089
1186
  ? `${source} needs the security_events scope (gh auth refresh -h github.com -s security_events)`
1090
1187
  : `${source} unavailable (${reason})`,
1091
- );
1092
- continue;
1093
- }
1094
- for (const alert of Array.isArray(result.value) ? result.value : []) {
1095
- alerts.push({ source, alert });
1096
- }
1097
- }
1098
- return { alerts, notes };
1099
- }
1100
-
1101
- export function notificationsSince(state, cwd) {
1102
- const since =
1103
- typeof state?.lastPollAt === "string" && Number.isFinite(Date.parse(state.lastPollAt))
1104
- ? state.lastPollAt
1105
- : new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
1106
- const comments = ghJson(
1107
- ["api", `repos/${activeRepo}/issues/comments?since=${encodeURIComponent(since)}&per_page=100`],
1108
- { cwd },
1109
- );
1110
- const issues = ghJson(
1111
- ["api", `repos/${activeRepo}/issues?state=all&sort=created&direction=desc&per_page=30`],
1112
- {
1113
- cwd,
1114
- },
1115
- );
1116
- if (!comments.ok) {
1117
- if (issues.ok) {
1118
- return {
1119
- ok: true,
1120
- source: "issues",
1121
- comments: [],
1122
- issues: Array.isArray(issues.value) ? issues.value : [],
1123
- };
1124
- }
1125
- return {
1126
- ok: false,
1127
- reason: `comment fallback failed (${comments.reason}) and issue fallback failed (${issues.reason})`,
1128
- };
1129
- }
1130
- return {
1131
- ok: true,
1132
- source: "comments",
1133
- comments: Array.isArray(comments.value) ? comments.value : [],
1134
- issues: issues.ok && Array.isArray(issues.value) ? issues.value : [],
1135
- };
1136
- }
1137
-
1138
- /**
1139
- * Notification threads this poll may mark as read. GitHub's REST API can only
1140
- * mark a thread read (there is no "done" mutation), so the inbox stays as
1141
- * history while the unread badge stops growing.
1142
- */
1143
- export function clearableThreads(notifications = [], { scope = "repo", repo = REPO } = {}) {
1144
- if (scope === "off") return [];
1145
- // Only the repositories this instance reads. Marking the rest of the account
1146
- // read is a decision for a person, not for a background poll.
1147
- const wanted = (Array.isArray(notifications) ? notifications : []).filter(
1148
- (thread) => thread?.repository?.full_name === repo,
1149
- );
1150
- return wanted.map((thread) => String(thread?.id ?? "")).filter((id) => id.length > 0);
1151
- }
1152
-
1153
- /** Mark notification threads read, one PATCH per thread. Never throws. */
1154
- export function markThreadsRead(ids = [], cwd) {
1155
- const cleared = [];
1156
- const failed = [];
1157
- for (const id of ids) {
1158
- const result = ghJson(["api", "-X", "PATCH", `notifications/threads/${id}`], { cwd });
1159
- if (result.ok) cleared.push(id);
1160
- else failed.push({ id, reason: result.reason });
1161
- }
1162
- return { cleared, failed };
1163
- }
1164
-
1165
- export function fetchFeed(state, cwd) {
1166
- // A GitHub App has no user notification stream: the endpoint answers
1167
- // `403 Resource not accessible by integration`. Reading the repository feeds
1168
- // directly is the same information without a guaranteed failure per poll.
1169
- if (activeIdentity?.kind === "app") return notificationsSince(state, cwd);
1170
- const notifications = ghJson(["api", `repos/${activeRepo}/notifications`], { cwd });
1171
- if (notifications.ok) {
1172
- return {
1173
- ok: true,
1174
- source: "notifications",
1175
- notifications: Array.isArray(notifications.value) ? notifications.value : [],
1176
- };
1177
- }
1178
- const fallback = notificationsSince(state, cwd);
1179
- if (fallback.ok) return fallback;
1180
- return {
1181
- ok: false,
1182
- reason: `gh api notifications failed (${notifications.reason}); ${fallback.reason}`,
1183
- };
1184
- }
1185
-
1186
- // ---------------------------------------------------------------------------
1187
- // CLI
1188
- // ---------------------------------------------------------------------------
1189
-
1190
- export function parseArgs(argv = []) {
1191
- const options = {
1192
- repos: [],
1193
- repeat: false,
1194
- mode: "poll",
1195
- json: false,
1196
- quiet: false,
1197
- help: false,
1198
- clear: (process.env.INBOX_CLEAR ?? "off").trim() || "off",
1199
- };
1200
- const fromEnv = (process.env.INBOX_REPO ?? "")
1201
- .split(/[,\s]+/u)
1202
- .map((entry) => entry.trim())
1203
- .filter(Boolean);
1204
- options.repos.push(...fromEnv);
1205
- for (const argument of argv) {
1206
- if (argument === "--repeat") {
1207
- options.repeat = true;
1208
- continue;
1209
- }
1210
- if (argument === "--repo") {
1211
- options.expectRepo = true;
1212
- continue;
1213
- }
1214
- if (options.expectRepo) {
1215
- // A caller that hands over a list ("--repo a,b") means several watches,
1216
- // same as INBOX_REPO; a repository name never contains a comma.
1217
- options.repos.push(...argument.split(/[,\s]+/u).filter(Boolean));
1218
- options.expectRepo = false;
1219
- continue;
1220
- }
1221
- if (argument === "--clear") {
1222
- options.expectClear = true;
1223
- continue;
1224
- }
1225
- if (options.expectClear) {
1226
- if (!["off", "repo"].includes(argument)) {
1227
- throw new Error(
1228
- `not a clearing scope: ${argument} (use off or repo; clearing the whole account is not supported)`,
1229
- );
1230
- }
1231
- options.clear = argument;
1232
- options.expectClear = false;
1233
- continue;
1234
- }
1235
- if (argument === "--poll") options.mode = "poll";
1236
- else if (argument === "--all") options.mode = "all";
1237
- else if (argument === "--json") options.json = true;
1238
- else if (argument === "--quiet") options.quiet = true;
1239
- else if (argument === "--help" || argument === "-h") options.help = true;
1240
- else throw new Error(`unknown option: ${argument}`);
1241
- }
1242
- if (options.expectRepo) throw new Error("`--repo` needs a value");
1243
- if (options.expectClear) throw new Error("`--clear` needs a value");
1244
- options.repos = [...new Set(options.repos.map((repo) => repo.trim()).filter(Boolean))];
1245
- for (const repo of options.repos) {
1246
- if (!/^[\w.-]+\/[\w.-]+$/u.test(repo)) throw new Error(`not an owner/name repository: ${repo}`);
1247
- }
1248
- return options;
1249
- }
1250
-
1251
- /** The workspace's GitHub remote, so a poll with no `--repo` still knows where to look. */
1252
- function repoFromGit(cwd) {
1253
- try {
1254
- const url = execFileSync("git", ["remote", "get-url", "origin"], {
1255
- cwd,
1256
- encoding: "utf8",
1257
- timeout: GH_TIMEOUT_MS,
1258
- windowsHide: true,
1259
- stdio: ["ignore", "pipe", "ignore"],
1260
- }).trim();
1261
- const match = url.match(/github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/u);
1262
- return match ? `${match[1]}/${match[2]}` : null;
1263
- } catch {
1264
- return null;
1265
- }
1266
- }
1267
-
1268
- function printSkipped(options, reason) {
1269
- if (options.json) {
1270
- console.log(JSON.stringify({ repo: activeRepo, skipped: reason }, null, 2));
1271
- } else {
1272
- console.log(`github-inbox: skipped (${reason})`);
1273
- }
1274
- return 0;
1275
- }
1276
-
1277
- /** Identity passed by the plugin: `INBOX_IDENTITY_{KIND,LOGIN,TOKEN}`. */
1278
- function identityFromEnv(env = process.env) {
1279
- const login = env.INBOX_IDENTITY_LOGIN || null;
1280
- const token = env.INBOX_IDENTITY_TOKEN || null;
1281
- const kind = env.INBOX_IDENTITY_KIND === "app" ? "app" : "user";
1282
- if (!login && !token) return null;
1283
- return { kind, login, token };
1284
- }
1285
-
1286
- function runPoll({ repoRoot, stateFile, pendingFile, state, options, now, me, repos }) {
1287
- const fresh = [];
1288
- const skipped = [];
1289
- const notices = [];
1290
- const securityNotes = [];
1291
- const cleared = [];
1292
- const clearFailed = [];
1293
- const nextRepos = { ...normalizeStateFile(state).repos };
1294
-
1295
- for (const repo of repos) {
1296
- const slice = nextRepos[repo] ?? normalizeState({});
1297
- setRepo(repo);
1298
- const repoStartedAt = Date.now();
1299
- const result = pollOnce({
1300
- state: slice,
1301
- repeat: options.repeat === true,
1302
- now,
1303
- me,
1304
- clear: options.clear ?? "off",
1305
- markRead: (ids) => markThreadsRead(ids, repoRoot),
1306
- fetchRuns: () => fetchRuns(repoRoot),
1307
- fetchPrs: () => fetchOpenPullRequests(repoRoot),
1308
- fetchIssues: () => fetchOpenIssues(repoRoot),
1309
- fetchFeed: (currentState) => fetchFeed(currentState, repoRoot),
1310
- fetchSecurity: () => fetchSecurityAlerts(repoRoot),
1311
- });
1312
- if (result.skipped) {
1313
- skipped.push({ repo, reason: result.skipped });
1314
- continue;
1315
- }
1316
- // Keys carry the repository: the same PR number in two repositories is two
1317
- // different facts, and the queue must not collapse them into one.
1318
- const tagged = tagEvents(repo, result.fresh);
1319
- fresh.push(...tagged);
1320
- cleared.push(...(result.cleared ?? []));
1321
- clearFailed.push(...(result.clearFailed ?? []));
1322
- if (result.feedSkipped) notices.push(`${repo}: feed skipped (${result.feedSkipped})`);
1323
- // A repository without Dependabot / code scanning answers 403 on every poll.
1324
- // That is a standing fact about the install, not news per minute, so it is
1325
- // reported in `--json` and by `doctor` instead of the per-poll log line.
1326
- for (const note of result.securityNotes ?? []) securityNotes.push(`${repo}: ${note}`);
1327
- nextRepos[repo] = {
1328
- ...result.nextState,
1329
- lastPoll: {
1330
- at: result.nextState.lastPollAt,
1331
- as: me ?? null,
1332
- repo,
1333
- durationMs: Date.now() - repoStartedAt,
1334
- events: result.fresh.length,
1335
- },
1336
- };
1337
- }
1338
-
1339
- if (Object.keys(nextRepos).length === 0) {
1340
- return printSkipped(options, skipped[0]?.reason ?? "no repository to watch");
1341
- }
1342
- const withMeta = { version: 2, repos: nextRepos };
1343
- writeStateFile(stateFile, withMeta);
1344
- if (fresh.length > 0) appendPendingEvents(pendingFile, fresh, now);
1345
-
1346
- if (options.json) {
1347
- console.log(
1348
- JSON.stringify(
1349
- {
1350
- command: "poll",
1351
- repos: Object.keys(nextRepos),
1352
- polledAt: toIso(now),
1353
- skipped,
1354
- fresh,
1355
- cleared,
1356
- clearFailed,
1357
- securityNotes,
1358
- stateFile,
1359
- pendingFile,
1360
- state: withMeta,
1361
- },
1362
- null,
1363
- 2,
1364
- ),
1365
- );
1366
- } else {
1367
- for (const event of fresh) console.log(formatEvent(event));
1368
- if (cleared.length > 0 && !options.quiet) {
1369
- console.log(`github-inbox: cleared ${cleared.length} notification(s)`);
1370
- }
1371
- for (const entry of clearFailed) {
1372
- if (!options.quiet) console.log(`github-inbox: could not clear ${entry.id} (${entry.reason})`);
1373
- }
1374
- if (fresh.length === 0 && !options.quiet) {
1375
- console.log(`github-inbox: no new events (polled ${toIso(now)}, ${repos.join(", ")})`);
1376
- }
1377
- for (const entry of skipped) {
1378
- if (!options.quiet) console.log(`github-inbox: skipped ${entry.repo} (${entry.reason})`);
1379
- }
1380
- for (const notice of notices) {
1381
- if (!options.quiet) console.log(`github-inbox: ${notice}`);
1382
- }
1383
- }
1384
-
1385
- return 0;
1386
- }
1387
-
1388
- function runAll({ repoRoot, stateFile, pendingFile, state, options, now, me, repos }) {
1389
- const file = normalizeStateFile(state);
1390
- for (const repo of repos) {
1391
- setRepo(repo);
1392
- const runsResult = fetchRuns(repoRoot);
1393
- if (!runsResult.ok) return printSkipped(options, `${repo}: ${runsResult.reason}`);
1394
- const prsResult = fetchOpenPullRequests(repoRoot);
1395
- if (!prsResult.ok) return printSkipped(options, `${repo}: ${prsResult.reason}`);
1396
- const runs = (Array.isArray(runsResult.value) ? runsResult.value : []).slice(0, 20);
1397
- const prs = Array.isArray(prsResult.value) ? prsResult.value : [];
1398
- const slice = file.repos[repo] ?? normalizeState({});
1399
-
1400
- if (options.json) {
1401
- console.log(
1402
- JSON.stringify(
1403
- { command: "all", repo, polledAt: toIso(now), runs, prs, stateFile, pendingFile, state: slice },
1404
- null,
1405
- 2,
1406
- ),
1407
- );
1408
- continue;
1409
- }
1410
-
1411
- console.log(
1412
- `github-inbox: all | repo ${repo} | as ${me ?? "(unfiltered)"} | polled ${toIso(now)} | seen ${Object.keys(slice.seen).length}/${MAX_SEEN}`,
1413
- );
1414
- console.log(`github-inbox: main runs (newest first) — ${runs.length}`);
1415
- for (const run of runs) console.log(formatRunLine(run));
1416
- console.log(`github-inbox: open PRs — ${prs.length}`);
1417
- for (const pr of prs) console.log(formatPrLine(pr, me));
1418
- console.log(
1419
- `github-inbox: lastPollAt=${slice.lastPollAt ?? "(none)"} lastRun=${
1420
- slice.lastRun ? `${slice.lastRun.id} ${slice.lastRun.conclusion}` : "(none)"
1421
- }`,
1422
- );
1423
- console.log(`github-inbox: state=${stateFile} pending=${pendingFile}`);
1424
- }
1425
- return 0;
1426
- }
1427
-
1428
- function runCli(argv) {
1429
- const options = parseArgs(argv);
1430
- if (options.help) {
1431
- console.log(USAGE);
1432
- return 0;
1433
- }
1434
- const repoRoot = process.cwd();
1435
- const inferred = repoFromGit(repoRoot);
1436
- const repos = options.repos.length > 0 ? options.repos : inferred ? [inferred] : [];
1437
- setRepo(repos[0] ?? null);
1438
- setIdentity(identityFromEnv());
1439
- // Resolved once per poll: it decides which events belong to this identity.
1440
- const me = resolveLogin(repoRoot);
1441
- const workDir = path.join(repoRoot, ".work", "github-inbox");
1442
- const stateFile = path.join(workDir, "state.json");
1443
- const pendingFile = path.join(workDir, "pending.md");
1444
- const now = new Date();
1445
- const state = readStateFile(stateFile);
1446
- if (repos.length === 0) return printSkipped(options, "no repository: pass --repo or add a git remote");
1447
- if (options.mode === "all") {
1448
- return runAll({ repoRoot, stateFile, pendingFile, state, options, now, me, repos });
1449
- }
1450
- return runPoll({ repoRoot, stateFile, pendingFile, state, options, now, me, repos });
1451
- }
1452
-
1453
- const isDirectInvocation = (() => {
1454
- if (!process.argv[1]) return false;
1455
- try {
1456
- const scriptPath = fileURLToPath(import.meta.url);
1457
- const argvPath = path.resolve(process.argv[1]);
1458
- return process.platform === "win32"
1459
- ? scriptPath.toLowerCase() === argvPath.toLowerCase()
1460
- : scriptPath === argvPath;
1461
- } catch {
1462
- return false;
1463
- }
1464
- })();
1465
-
1466
- if (isDirectInvocation) {
1467
- try {
1468
- process.exitCode = runCli(process.argv.slice(2));
1469
- } catch (error) {
1470
- console.log(`github-inbox: failed (${singleLine(error?.message ?? error)})`);
1471
- process.exitCode = 1;
1472
- }
1473
- }
1188
+ );
1189
+ continue;
1190
+ }
1191
+ for (const alert of Array.isArray(result.value) ? result.value : []) {
1192
+ alerts.push({ source, alert });
1193
+ }
1194
+ }
1195
+ return { alerts, notes };
1196
+ }
1197
+
1198
+ export function notificationsSince(state, cwd) {
1199
+ const since =
1200
+ typeof state?.lastPollAt === "string" && Number.isFinite(Date.parse(state.lastPollAt))
1201
+ ? state.lastPollAt
1202
+ : new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
1203
+ const comments = ghJson(
1204
+ ["api", `repos/${activeRepo}/issues/comments?since=${encodeURIComponent(since)}&per_page=100`],
1205
+ { cwd },
1206
+ );
1207
+ const issues = ghJson(
1208
+ ["api", `repos/${activeRepo}/issues?state=all&sort=created&direction=desc&per_page=30`],
1209
+ {
1210
+ cwd,
1211
+ },
1212
+ );
1213
+ if (!comments.ok) {
1214
+ if (issues.ok) {
1215
+ return {
1216
+ ok: true,
1217
+ source: "issues",
1218
+ comments: [],
1219
+ issues: Array.isArray(issues.value) ? issues.value : [],
1220
+ };
1221
+ }
1222
+ return {
1223
+ ok: false,
1224
+ reason: `comment fallback failed (${comments.reason}) and issue fallback failed (${issues.reason})`,
1225
+ };
1226
+ }
1227
+ return {
1228
+ ok: true,
1229
+ source: "comments",
1230
+ comments: Array.isArray(comments.value) ? comments.value : [],
1231
+ issues: issues.ok && Array.isArray(issues.value) ? issues.value : [],
1232
+ };
1233
+ }
1234
+
1235
+ /**
1236
+ * Notification threads this poll may mark as read. GitHub's REST API can only
1237
+ * mark a thread read (there is no "done" mutation), so the inbox stays as
1238
+ * history while the unread badge stops growing.
1239
+ */
1240
+ export function clearableThreads(notifications = [], { scope = "repo", repo = REPO } = {}) {
1241
+ if (scope === "off") return [];
1242
+ // Only the repositories this instance reads. Marking the rest of the account
1243
+ // read is a decision for a person, not for a background poll.
1244
+ const wanted = (Array.isArray(notifications) ? notifications : []).filter(
1245
+ (thread) => thread?.repository?.full_name === repo,
1246
+ );
1247
+ return wanted.map((thread) => String(thread?.id ?? "")).filter((id) => id.length > 0);
1248
+ }
1249
+
1250
+ /** Mark notification threads read, one PATCH per thread. Never throws. */
1251
+ export function markThreadsRead(ids = [], cwd) {
1252
+ const cleared = [];
1253
+ const failed = [];
1254
+ for (const id of ids) {
1255
+ const result = ghJson(["api", "-X", "PATCH", `notifications/threads/${id}`], { cwd });
1256
+ if (result.ok) cleared.push(id);
1257
+ else failed.push({ id, reason: result.reason });
1258
+ }
1259
+ return { cleared, failed };
1260
+ }
1261
+
1262
+ export function fetchFeed(state, cwd) {
1263
+ // A GitHub App has no user notification stream: the endpoint answers
1264
+ // `403 Resource not accessible by integration`. Reading the repository feeds
1265
+ // directly is the same information without a guaranteed failure per poll.
1266
+ if (activeIdentity?.kind === "app") return notificationsSince(state, cwd);
1267
+ const notifications = ghJson(["api", `repos/${activeRepo}/notifications`], { cwd });
1268
+ if (notifications.ok) {
1269
+ return {
1270
+ ok: true,
1271
+ source: "notifications",
1272
+ notifications: Array.isArray(notifications.value) ? notifications.value : [],
1273
+ };
1274
+ }
1275
+ const fallback = notificationsSince(state, cwd);
1276
+ if (fallback.ok) return fallback;
1277
+ return {
1278
+ ok: false,
1279
+ reason: `gh api notifications failed (${notifications.reason}); ${fallback.reason}`,
1280
+ };
1281
+ }
1282
+
1283
+ // ---------------------------------------------------------------------------
1284
+ // CLI
1285
+ // ---------------------------------------------------------------------------
1286
+
1287
+ export function parseArgs(argv = []) {
1288
+ const options = {
1289
+ repos: [],
1290
+ repeat: false,
1291
+ mode: "poll",
1292
+ json: false,
1293
+ quiet: false,
1294
+ help: false,
1295
+ clear: (process.env.INBOX_CLEAR ?? "off").trim() || "off",
1296
+ };
1297
+ const fromEnv = (process.env.INBOX_REPO ?? "")
1298
+ .split(/[,\s]+/u)
1299
+ .map((entry) => entry.trim())
1300
+ .filter(Boolean);
1301
+ options.repos.push(...fromEnv);
1302
+ for (const argument of argv) {
1303
+ if (argument === "--repeat") {
1304
+ options.repeat = true;
1305
+ continue;
1306
+ }
1307
+ if (argument === "--repo") {
1308
+ options.expectRepo = true;
1309
+ continue;
1310
+ }
1311
+ if (options.expectRepo) {
1312
+ // A caller that hands over a list ("--repo a,b") means several watches,
1313
+ // same as INBOX_REPO; a repository name never contains a comma.
1314
+ options.repos.push(...argument.split(/[,\s]+/u).filter(Boolean));
1315
+ options.expectRepo = false;
1316
+ continue;
1317
+ }
1318
+ if (argument === "--clear") {
1319
+ options.expectClear = true;
1320
+ continue;
1321
+ }
1322
+ if (options.expectClear) {
1323
+ if (!["off", "repo"].includes(argument)) {
1324
+ throw new Error(
1325
+ `not a clearing scope: ${argument} (use off or repo; clearing the whole account is not supported)`,
1326
+ );
1327
+ }
1328
+ options.clear = argument;
1329
+ options.expectClear = false;
1330
+ continue;
1331
+ }
1332
+ if (argument === "--poll") options.mode = "poll";
1333
+ else if (argument === "--all") options.mode = "all";
1334
+ else if (argument === "--json") options.json = true;
1335
+ else if (argument === "--quiet") options.quiet = true;
1336
+ else if (argument === "--help" || argument === "-h") options.help = true;
1337
+ else throw new Error(`unknown option: ${argument}`);
1338
+ }
1339
+ if (options.expectRepo) throw new Error("`--repo` needs a value");
1340
+ if (options.expectClear) throw new Error("`--clear` needs a value");
1341
+ options.repos = [...new Set(options.repos.map((repo) => repo.trim()).filter(Boolean))];
1342
+ for (const repo of options.repos) {
1343
+ if (!/^[\w.-]+\/[\w.-]+$/u.test(repo)) throw new Error(`not an owner/name repository: ${repo}`);
1344
+ }
1345
+ return options;
1346
+ }
1347
+
1348
+ /** The workspace's GitHub remote, so a poll with no `--repo` still knows where to look. */
1349
+ function repoFromGit(cwd) {
1350
+ try {
1351
+ const url = execFileSync("git", ["remote", "get-url", "origin"], {
1352
+ cwd,
1353
+ encoding: "utf8",
1354
+ timeout: GH_TIMEOUT_MS,
1355
+ windowsHide: true,
1356
+ stdio: ["ignore", "pipe", "ignore"],
1357
+ }).trim();
1358
+ const match = url.match(/github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/u);
1359
+ return match ? `${match[1]}/${match[2]}` : null;
1360
+ } catch {
1361
+ return null;
1362
+ }
1363
+ }
1364
+
1365
+ function printSkipped(options, reason) {
1366
+ if (options.json) {
1367
+ console.log(JSON.stringify({ repo: activeRepo, skipped: reason }, null, 2));
1368
+ } else {
1369
+ console.log(`github-inbox: skipped (${reason})`);
1370
+ }
1371
+ return 0;
1372
+ }
1373
+
1374
+ /** Identity passed by the plugin: `INBOX_IDENTITY_{KIND,LOGIN,TOKEN}`. */
1375
+ function identityFromEnv(env = process.env) {
1376
+ const login = env.INBOX_IDENTITY_LOGIN || null;
1377
+ const token = env.INBOX_IDENTITY_TOKEN || null;
1378
+ const kind = env.INBOX_IDENTITY_KIND === "app" ? "app" : "user";
1379
+ if (!login && !token) return null;
1380
+ return { kind, login, token };
1381
+ }
1382
+
1383
+ function runPoll({ repoRoot, stateFile, pendingFile, state, options, now, me, repos }) {
1384
+ const fresh = [];
1385
+ const skipped = [];
1386
+ const notices = [];
1387
+ const securityNotes = [];
1388
+ const cleared = [];
1389
+ const clearFailed = [];
1390
+ const nextRepos = { ...normalizeStateFile(state).repos };
1391
+
1392
+ for (const repo of repos) {
1393
+ const slice = nextRepos[repo] ?? normalizeState({});
1394
+ setRepo(repo);
1395
+ const repoStartedAt = Date.now();
1396
+ const result = pollOnce({
1397
+ state: slice,
1398
+ repeat: options.repeat === true,
1399
+ now,
1400
+ me,
1401
+ clear: options.clear ?? "off",
1402
+ markRead: (ids) => markThreadsRead(ids, repoRoot),
1403
+ fetchRuns: () => fetchRuns(repoRoot),
1404
+ fetchPrs: () => fetchOpenPullRequests(repoRoot),
1405
+ fetchIssues: () => fetchOpenIssues(repoRoot),
1406
+ fetchFeed: (currentState) => fetchFeed(currentState, repoRoot),
1407
+ fetchSecurity: () => fetchSecurityAlerts(repoRoot),
1408
+ fetchReviews: () => fetchReviewComments(repoRoot),
1409
+ });
1410
+ if (result.skipped) {
1411
+ skipped.push({ repo, reason: result.skipped });
1412
+ continue;
1413
+ }
1414
+ // Keys carry the repository: the same PR number in two repositories is two
1415
+ // different facts, and the queue must not collapse them into one.
1416
+ const tagged = tagEvents(repo, result.fresh);
1417
+ fresh.push(...tagged);
1418
+ cleared.push(...(result.cleared ?? []));
1419
+ clearFailed.push(...(result.clearFailed ?? []));
1420
+ if (result.feedSkipped) notices.push(`${repo}: feed skipped (${result.feedSkipped})`);
1421
+ // A repository without Dependabot / code scanning answers 403 on every poll.
1422
+ // That is a standing fact about the install, not news per minute, so it is
1423
+ // reported in `--json` and by `doctor` instead of the per-poll log line.
1424
+ for (const note of result.securityNotes ?? []) securityNotes.push(`${repo}: ${note}`);
1425
+ nextRepos[repo] = {
1426
+ ...result.nextState,
1427
+ lastPoll: {
1428
+ at: result.nextState.lastPollAt,
1429
+ as: me ?? null,
1430
+ repo,
1431
+ durationMs: Date.now() - repoStartedAt,
1432
+ events: result.fresh.length,
1433
+ },
1434
+ };
1435
+ }
1436
+
1437
+ if (Object.keys(nextRepos).length === 0) {
1438
+ return printSkipped(options, skipped[0]?.reason ?? "no repository to watch");
1439
+ }
1440
+ const withMeta = { version: 2, repos: nextRepos };
1441
+ writeStateFile(stateFile, withMeta);
1442
+ if (fresh.length > 0) appendPendingEvents(pendingFile, fresh, now);
1443
+
1444
+ if (options.json) {
1445
+ console.log(
1446
+ JSON.stringify(
1447
+ {
1448
+ command: "poll",
1449
+ repos: Object.keys(nextRepos),
1450
+ polledAt: toIso(now),
1451
+ skipped,
1452
+ fresh,
1453
+ cleared,
1454
+ clearFailed,
1455
+ securityNotes,
1456
+ stateFile,
1457
+ pendingFile,
1458
+ state: withMeta,
1459
+ },
1460
+ null,
1461
+ 2,
1462
+ ),
1463
+ );
1464
+ } else {
1465
+ for (const event of fresh) console.log(formatEvent(event));
1466
+ if (cleared.length > 0 && !options.quiet) {
1467
+ console.log(`github-inbox: cleared ${cleared.length} notification(s)`);
1468
+ }
1469
+ for (const entry of clearFailed) {
1470
+ if (!options.quiet) console.log(`github-inbox: could not clear ${entry.id} (${entry.reason})`);
1471
+ }
1472
+ if (fresh.length === 0 && !options.quiet) {
1473
+ console.log(`github-inbox: no new events (polled ${toIso(now)}, ${repos.join(", ")})`);
1474
+ }
1475
+ for (const entry of skipped) {
1476
+ if (!options.quiet) console.log(`github-inbox: skipped ${entry.repo} (${entry.reason})`);
1477
+ }
1478
+ for (const notice of notices) {
1479
+ if (!options.quiet) console.log(`github-inbox: ${notice}`);
1480
+ }
1481
+ }
1482
+
1483
+ return 0;
1484
+ }
1485
+
1486
+ function runAll({ repoRoot, stateFile, pendingFile, state, options, now, me, repos }) {
1487
+ const file = normalizeStateFile(state);
1488
+ for (const repo of repos) {
1489
+ setRepo(repo);
1490
+ const runsResult = fetchRuns(repoRoot);
1491
+ if (!runsResult.ok) return printSkipped(options, `${repo}: ${runsResult.reason}`);
1492
+ const prsResult = fetchOpenPullRequests(repoRoot);
1493
+ if (!prsResult.ok) return printSkipped(options, `${repo}: ${prsResult.reason}`);
1494
+ const runs = (Array.isArray(runsResult.value) ? runsResult.value : []).slice(0, 20);
1495
+ const prs = Array.isArray(prsResult.value) ? prsResult.value : [];
1496
+ const slice = file.repos[repo] ?? normalizeState({});
1497
+
1498
+ if (options.json) {
1499
+ console.log(
1500
+ JSON.stringify(
1501
+ { command: "all", repo, polledAt: toIso(now), runs, prs, stateFile, pendingFile, state: slice },
1502
+ null,
1503
+ 2,
1504
+ ),
1505
+ );
1506
+ continue;
1507
+ }
1508
+
1509
+ console.log(
1510
+ `github-inbox: all | repo ${repo} | as ${me ?? "(unfiltered)"} | polled ${toIso(now)} | seen ${Object.keys(slice.seen).length}/${MAX_SEEN}`,
1511
+ );
1512
+ console.log(`github-inbox: main runs (newest first) — ${runs.length}`);
1513
+ for (const run of runs) console.log(formatRunLine(run));
1514
+ console.log(`github-inbox: open PRs — ${prs.length}`);
1515
+ for (const pr of prs) console.log(formatPrLine(pr, me));
1516
+ console.log(
1517
+ `github-inbox: lastPollAt=${slice.lastPollAt ?? "(none)"} lastRun=${
1518
+ slice.lastRun ? `${slice.lastRun.id} ${slice.lastRun.conclusion}` : "(none)"
1519
+ }`,
1520
+ );
1521
+ console.log(`github-inbox: state=${stateFile} pending=${pendingFile}`);
1522
+ }
1523
+ return 0;
1524
+ }
1525
+
1526
+ function runCli(argv) {
1527
+ const options = parseArgs(argv);
1528
+ if (options.help) {
1529
+ console.log(USAGE);
1530
+ return 0;
1531
+ }
1532
+ const repoRoot = process.cwd();
1533
+ const inferred = repoFromGit(repoRoot);
1534
+ const repos = options.repos.length > 0 ? options.repos : inferred ? [inferred] : [];
1535
+ setRepo(repos[0] ?? null);
1536
+ setIdentity(identityFromEnv());
1537
+ // Resolved once per poll: it decides which events belong to this identity.
1538
+ const me = resolveLogin(repoRoot);
1539
+ const workDir = path.join(repoRoot, ".work", "github-inbox");
1540
+ const stateFile = path.join(workDir, "state.json");
1541
+ const pendingFile = path.join(workDir, "pending.md");
1542
+ const now = new Date();
1543
+ const state = readStateFile(stateFile);
1544
+ if (repos.length === 0) return printSkipped(options, "no repository: pass --repo or add a git remote");
1545
+ if (options.mode === "all") {
1546
+ return runAll({ repoRoot, stateFile, pendingFile, state, options, now, me, repos });
1547
+ }
1548
+ return runPoll({ repoRoot, stateFile, pendingFile, state, options, now, me, repos });
1549
+ }
1550
+
1551
+ const isDirectInvocation = (() => {
1552
+ if (!process.argv[1]) return false;
1553
+ try {
1554
+ const scriptPath = fileURLToPath(import.meta.url);
1555
+ const argvPath = path.resolve(process.argv[1]);
1556
+ return process.platform === "win32"
1557
+ ? scriptPath.toLowerCase() === argvPath.toLowerCase()
1558
+ : scriptPath === argvPath;
1559
+ } catch {
1560
+ return false;
1561
+ }
1562
+ })();
1563
+
1564
+ if (isDirectInvocation) {
1565
+ try {
1566
+ process.exitCode = runCli(process.argv.slice(2));
1567
+ } catch (error) {
1568
+ console.log(`github-inbox: failed (${singleLine(error?.message ?? error)})`);
1569
+ process.exitCode = 1;
1570
+ }
1571
+ }