dsh-session-superagent 0.9.115 → 0.9.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/gh-format.js CHANGED
@@ -1,466 +1,466 @@
1
- // GitHub 交互层:把 API 的数据变成「人话」和「可判断的结论」。
2
- //
3
- // 从 watch.js 拆出来的理由:另一半是**调度与状态**(去重水位、退避、时段、合并写)。
4
- // 两块的修改动机完全不同 —— 改「唤醒消息多一行」不需要看调度代码,反之亦然。
5
- // 拆完 watch.js 从 883 行降到 ~470 行,这边自成一体、对 watch.js 零依赖(已用脚本核对过)。
6
- //
7
- // 约定:本文件只做「解析 / 归类 / 措辞」,不发请求、不碰状态。
8
-
9
- /**
10
- * 把 `gh` 调用的结果整理成给 agent 看的一段文本。
11
- *
12
- * 为什么要单独抽出来:`github` 工具原来只贴原始 stderr + `[exit code: N]`,
13
- * agent 拿到「gh: HTTP 404」还得自己猜该动什么。这里统一补上分类与下一步。
14
- * 依据:GitHub 官方要求「do not ignore repeated 4xx/5xx」——
15
- * 失败必须带着可执行的动作回到调用方。
16
- * 出处:https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api
17
- */
18
- export function formatGhCall({ code, text, classify }) {
19
- const body = String(text || '').trim() || '(empty)'
20
- const failed = Number(code) !== 0
21
- const why = failed ? classify(body) : null
22
- // 304 是「没变化」,不是失败:别让调用方以为出错了
23
- if (why && why.kind === 'notmodified') {
24
- return body + String.fromCharCode(10) + why.hint + String.fromCharCode(10) + '[exit code: ' + code + '][kind: notmodified]'
25
- }
26
- if (failed) {
27
- return body + String.fromCharCode(10) + why.hint + String.fromCharCode(10) + '[exit code: ' + code + '][kind: ' + why.kind + ']'
28
- }
29
- return body + String.fromCharCode(10) + '[exit code: ' + code + ']'
30
- }
31
- export function classifyGhError(detail) {
32
- const text = String(detail || '')
33
- // 长 URL 压缩,避免一整条 API 地址占满面板
34
- const short = text
35
- .replace(/Get "https?:\/\/[^"]{16,}"/g, 'GitHub API 请求')
36
- .replace(/Post "https?:\/\/[^"]{16,}"/g, 'GitHub API 请求')
37
- .slice(0, 200)
38
-
39
- if (/HTTP 401|Bad credentials|requires authentication/i.test(text)) {
40
- return { kind: 'auth', short, hint: '(gh 登录失效:跑 gh auth login,或在面板填 token)' }
41
- }
42
- if (/HTTP 403|rate limit|API rate limit exceeded/i.test(text)) {
43
- return { kind: 'ratelimit', short, hint: '(被 GitHub 限流:等几分钟,或换成带 token 的凭证)' }
44
- }
45
- if (/HTTP 50[0234]|Bad Gateway|Service Unavailable|Gateway Time-?out/i.test(text)) {
46
- return { kind: 'gateway', short, hint: '(GitHub 或本地代理短暂故障:已按退避自动重试,不需要手动处理;持续出现就检查代理)' }
47
- }
48
- if (/ENOENT|not found.*gh|gh: command not found/i.test(text)) {
49
- return { kind: 'nogh', short, hint: '(找不到 gh 命令:确认已安装且在 PATH)' }
50
- }
51
- // 条件请求命中:gh 把 304 当失败(非 2xx 就 exit 1),但语义是「没有变化」,不是错误
52
- if (/HTTP 304|304 Not Modified|not modified/i.test(text)) {
53
- return { kind: 'notmodified', short, hint: '(没有变化 —— 条件请求命中 304,这不是错误)' }
54
- }
55
- // 仓库改名/转移:GitHub 会回 301 或 "has moved",客户看到的却只是「没动静」
56
- if (/moved permanently|has moved|HTTP 301|Repository has been moved/i.test(text)) {
57
- return { kind: 'moved', short, hint: '(仓库改名或转移了:用新地址重新添加,或把守改成新的 owner/name)' }
58
- }
59
- if (/HTTP 404|Not Found|not found/i.test(text) && !/command not found/i.test(text)) {
60
- return { kind: 'notfound', short, hint: '(仓库不存在或没权限:检查 owner/name)' }
61
- }
62
- if (/EOF|i\/o timeout|connection reset|dial tcp|TLS handshake|no such host|proxyconnect|timeout|context deadline exceeded|certificate|x509|self.signed|unable to get local issuer/i.test(text)) {
63
- return { kind: 'network', short, hint: '(网络抖动:这一轮没连上 GitHub,已按退避自动重试,不需要手动处理)' }
64
- }
1
+ // GitHub 交互层:把 API 的数据变成「人话」和「可判断的结论」。
2
+ //
3
+ // 从 watch.js 拆出来的理由:另一半是**调度与状态**(去重水位、退避、时段、合并写)。
4
+ // 两块的修改动机完全不同 —— 改「唤醒消息多一行」不需要看调度代码,反之亦然。
5
+ // 拆完 watch.js 从 883 行降到 ~470 行,这边自成一体、对 watch.js 零依赖(已用脚本核对过)。
6
+ //
7
+ // 约定:本文件只做「解析 / 归类 / 措辞」,不发请求、不碰状态。
8
+
9
+ /**
10
+ * 把 `gh` 调用的结果整理成给 agent 看的一段文本。
11
+ *
12
+ * 为什么要单独抽出来:`github` 工具原来只贴原始 stderr + `[exit code: N]`,
13
+ * agent 拿到「gh: HTTP 404」还得自己猜该动什么。这里统一补上分类与下一步。
14
+ * 依据:GitHub 官方要求「do not ignore repeated 4xx/5xx」——
15
+ * 失败必须带着可执行的动作回到调用方。
16
+ * 出处:https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api
17
+ */
18
+ export function formatGhCall({ code, text, classify }) {
19
+ const body = String(text || '').trim() || '(empty)'
20
+ const failed = Number(code) !== 0
21
+ const why = failed ? classify(body) : null
22
+ // 304 是「没变化」,不是失败:别让调用方以为出错了
23
+ if (why && why.kind === 'notmodified') {
24
+ return body + String.fromCharCode(10) + why.hint + String.fromCharCode(10) + '[exit code: ' + code + '][kind: notmodified]'
25
+ }
26
+ if (failed) {
27
+ return body + String.fromCharCode(10) + why.hint + String.fromCharCode(10) + '[exit code: ' + code + '][kind: ' + why.kind + ']'
28
+ }
29
+ return body + String.fromCharCode(10) + '[exit code: ' + code + ']'
30
+ }
31
+ export function classifyGhError(detail) {
32
+ const text = String(detail || '')
33
+ // 长 URL 压缩,避免一整条 API 地址占满面板
34
+ const short = text
35
+ .replace(/Get "https?:\/\/[^"]{16,}"/g, 'GitHub API 请求')
36
+ .replace(/Post "https?:\/\/[^"]{16,}"/g, 'GitHub API 请求')
37
+ .slice(0, 200)
38
+
39
+ if (/HTTP 401|Bad credentials|requires authentication/i.test(text)) {
40
+ return { kind: 'auth', short, hint: '(gh 登录失效:跑 gh auth login,或在面板填 token)' }
41
+ }
42
+ if (/HTTP 403|rate limit|API rate limit exceeded/i.test(text)) {
43
+ return { kind: 'ratelimit', short, hint: '(被 GitHub 限流:等几分钟,或换成带 token 的凭证)' }
44
+ }
45
+ if (/HTTP 50[0234]|Bad Gateway|Service Unavailable|Gateway Time-?out/i.test(text)) {
46
+ return { kind: 'gateway', short, hint: '(GitHub 或本地代理短暂故障:已按退避自动重试,不需要手动处理;持续出现就检查代理)' }
47
+ }
48
+ if (/ENOENT|not found.*gh|gh: command not found/i.test(text)) {
49
+ return { kind: 'nogh', short, hint: '(找不到 gh 命令:确认已安装且在 PATH)' }
50
+ }
51
+ // 条件请求命中:gh 把 304 当失败(非 2xx 就 exit 1),但语义是「没有变化」,不是错误
52
+ if (/HTTP 304|304 Not Modified|not modified/i.test(text)) {
53
+ return { kind: 'notmodified', short, hint: '(没有变化 —— 条件请求命中 304,这不是错误)' }
54
+ }
55
+ // 仓库改名/转移:GitHub 会回 301 或 "has moved",客户看到的却只是「没动静」
56
+ if (/moved permanently|has moved|HTTP 301|Repository has been moved/i.test(text)) {
57
+ return { kind: 'moved', short, hint: '(仓库改名或转移了:用新地址重新添加,或把守改成新的 owner/name)' }
58
+ }
59
+ if (/HTTP 404|Not Found|not found/i.test(text) && !/command not found/i.test(text)) {
60
+ return { kind: 'notfound', short, hint: '(不存在或没权限 —— 私有仓库也回 404:检查 owner/name 与 token)' }
61
+ }
62
+ if (/EOF|i\/o timeout|connection reset|dial tcp|TLS handshake|no such host|proxyconnect|timeout|context deadline exceeded|certificate|x509|self.signed|unable to get local issuer/i.test(text)) {
63
+ return { kind: 'network', short, hint: '(网络抖动:这一轮没连上 GitHub,已按退避自动重试,不需要手动处理)' }
64
+ }
65
65
  // 兜底也要给下一步:客户看到一条没归类的错误,最怕「那我该做什么」
66
- return { kind: 'other', short, hint: '(没归类的错误:已按退避自动重试;持续出现就跑 watch_doctor 看检查清单,或把这行贴给对方)' }
67
- }
68
-
69
- /**
70
- * 解析 `gh api --include` 的输出:状态行 / 响应头 / 空行 / 正文。
71
- *
72
- * 为什么用它而不是直接 `gh api`:GitHub 官方文档明确说
73
- * 「Make authenticated conditional requests, so that unchanged data does not count against
74
- * your primary rate limit」—— 带上 If-None-Match 后,没变化时拿 304,
75
- * 304 **不计入**速率限制。对一个每 N 秒轮询的工具,这是最直接的省额度手段。
76
- *
77
- * 出处:https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api
78
- */
79
- export function parseGhInclude(stdout) {
80
- const text = String(stdout || '')
81
- const LF = String.fromCharCode(10)
82
- const blank = LF + LF
83
- const idx = text.indexOf(blank)
84
- const head = idx < 0 ? text : text.slice(0, idx)
85
- const body = idx < 0 ? text.trim() : text.slice(idx + blank.length)
86
- const lines = head.split(LF)
87
- const statusParts = String(lines[0] || '').split(' ')
88
- const status = Number(statusParts[1]) || 0
89
- const header = (name) => {
90
- const needle = name.toLowerCase() + ':'
91
- for (const line of lines) {
92
- if (line.toLowerCase().startsWith(needle)) return line.slice(needle.length).trim()
93
- }
94
- return null
95
- }
96
- const numeric = (name) => {
97
- const raw = header(name)
98
- const value = Number(raw)
99
- return Number.isFinite(value) ? value : null
100
- }
101
- const resetSeconds = numeric('x-ratelimit-reset')
102
- // Stage 2 限流(secondary rate limit)用 Retry-After 告诉你等多久;primary 用 x-ratelimit-reset
103
- const retryAfterRaw = header('retry-after')
104
- return {
105
- status,
106
- etag: header('etag'),
107
- remaining: numeric('x-ratelimit-remaining'),
108
- limit: numeric('x-ratelimit-limit'),
109
- resetAt: resetSeconds ? new Date(resetSeconds * 1000).toISOString() : null,
110
- retryAfter: Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : null,
111
- // GitHub 用这个头告诉你「这个 endpoint 至少隔多久再问」——忽略它会白撞额度
112
- pollInterval: (() => { const raw = header('x-poll-interval'); return raw && Number.isFinite(Number(raw)) ? Number(raw) : null })(),
113
- body,
114
- }
115
- }
116
-
117
- /**
118
- * 额度自适应:GitHub 主额度快用完时,不要继续按固定间隔撞墙。
119
- *
120
- * 依据:GitHub 每次响应都带 `X-RateLimit-Remaining` / `X-RateLimit-Reset`
121
- * (实测 `gh api --include` 的输出里就是这几个头)。
122
- * 剩余低于阈值时,把下一次轮询推到额度重置时间(最多等 1 小时),而不是继续发请求。
123
- */
124
- /**
125
- * GitHub 的「第二阶段限流」会在 403/429 响应里带 `Retry-After: <秒>`。
126
- * 按它等,比我们瞎猜一个退避时间准确得多。
127
- * 依据:GitHub 暴露头里明确包含 `Retry-After`(实测 `gh api --include` 的
128
- * Access-Control-Expose-Headers 一行里就能看到),且官方限流文档要求遵守它。
129
- */
130
- export function retryAfterMs(retryAfter, { capMs = 3600 * 1000 } = {}) {
131
- const seconds = Number(retryAfter)
132
- if (!Number.isFinite(seconds) || seconds <= 0) return 0
133
- return Math.min(capMs, Math.round(seconds * 1000))
134
- }
135
-
136
- export function throttleDelayMs({ remaining, resetAt, now = Date.now(), threshold = 500, capMs = 3600 * 1000 } = {}) {
137
- if (remaining === null || remaining === undefined) return 0
138
- if (Number(remaining) >= Number(threshold)) return 0
139
- const reset = Date.parse(resetAt || '')
140
- if (!Number.isFinite(reset)) return Math.min(capMs, 5 * 60 * 1000)
141
- const wait = reset - now + 1000
142
- if (wait <= 0) return 0
143
- return Math.min(capMs, wait)
144
- }
145
-
146
- /**
147
- * 去同步抖动:给每个 watcher 一个**确定性的**起始偏移,避免 N 条守在同一条时间线上一起发车。
148
- *
149
- * 为什么不用随机数:随机数每次启动都不同,调试时对不上;用 id 的哈希则「同一条守永远同一个偏移」,
150
- * 既错峰又可复现。范围固定在 [0, windowMs)。
151
- *
152
- * 依据:AWS Architecture Blog 的《Exponential Backoff And Jitter》——同步发车会让
153
- * 下游在整点承压,加入抖动后峰值被摊平。(https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)
154
- */
155
- export function jitterMs(key, windowMs) {
156
- const width = Math.max(0, Math.floor(Number(windowMs) || 0))
157
- if (width === 0) return 0
158
- const text = String(key || '')
159
- let hash = 0
160
- for (let i = 0; i < text.length; i += 1) hash = (hash * 31 + text.charCodeAt(i)) % 1000003
161
- return hash % width
162
- }
163
-
164
- /**
165
- * 把「为什么没叫醒」做成可统计的分布。
166
- *
167
- * 背景:我们每轮只留最近 5 条过滤记录(`filteredLog`),客户想知道
168
- * 「为什么我加的标签一条都没被叫醒」时看不出全貌。这里按原因累计次数,
169
- * 面板上就能直接读「不在标签白名单: ai-fix × 37」这种结论。
170
- *
171
- * 依据:GitHub 的 issue 过滤语义本身就是「限定词 + 集合运算」
172
- * (label:/assignee:/state:…,见 GitHub 文档「Filtering and searching issues」),
173
- * 所以「被哪条限定词刷掉」比「被刷掉」更值得告诉用户。
174
- */
175
- export function countReasons(counts, reason, { maxKinds = 12 } = {}) {
176
- const map = { ...(counts || {}) }
177
- if (!reason) return map
178
- const key = String(reason).slice(0, 60)
179
- map[key] = (Number(map[key]) || 0) + 1
180
- const entries = Object.entries(map).sort((a, b) => b[1] - a[1]).slice(0, maxKinds)
181
- return Object.fromEntries(entries)
182
- }
183
-
184
- /**
185
- * 仓库权限提示:只读仓库上我们**没法**回写结果(评论、打标签都会 403)。
186
- *
187
- * 依据:`GET /repos/{owner}/{repo}` 返回 `permissions.push`,官方文档里这个对象就是
188
- * "你有没有写权限"的权威来源。事先知道,比跑到一半才发现 403 好。
189
- * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
190
- */
191
- export function accessNote(repoAccess) {
192
- if (!repoAccess || typeof repoAccess !== 'object') return ''
193
- if (repoAccess.push === true) return ''
194
- if (repoAccess.push === false) {
195
- return '你对 ' + String(repoAccess.repo || '这个仓库') + ' 只有读权限:能看、能被叫醒,但没法回写评论或打标签 —— '
196
- + '要么换有写权限的 token,要么把结论写在本地/PR 描述里。'
197
- }
198
- return ''
199
- }
200
-
201
- /**
202
- * 仓库结构提示:主理鱼只认 issue/PR,所以「这个仓库没有 issue」要提前说。
203
- *
204
- * 依据:`GET /repos/{owner}/{repo}` 返回 `has_issues` / `fork` / `parent.full_name`
205
- * (本机实测这三个字段都在:`{fork, has_issues, parent, private}`)。
206
- * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
207
- */
208
- export function repoStructureNote(repoAccess) {
209
- if (!repoAccess || typeof repoAccess !== 'object') return ''
210
- const repo = String(repoAccess.repo || '这个仓库')
211
- if (repoAccess.archived === true) {
212
- return repo + ' 已归档:GitHub 上归档仓库是只读的,评论和打标签都会失败 —— 守它只能看、不能回写。'
213
- }
214
- if (repoAccess.disabled === true) {
215
- return repo + ' 已被禁用:这个仓库当前不可用,主理鱼不会拿到任何条目。'
216
- }
217
- if (repoAccess.hasIssues === false) {
218
- return repo + ' 关闭了 Issues —— 主理鱼只认 issue / PR,这里不会有任何条目可接。'
219
- }
220
- if (repoAccess.fork === true && repoAccess.parent && repoAccess.hasIssues !== true) {
221
- return repo + ' 是 ' + String(repoAccess.parent) + ' 的 fork。fork 默认不带 Issues,'
222
- + 'issue 大多落在上游 —— 确认你要守的是哪一个(守上游就把仓库填成 ' + String(repoAccess.parent) + ')。'
223
- }
224
- return ''
225
- }
226
-
227
- /**
228
- * 仓库能力徽章:把「这条守到底能不能干活」压缩成几个短标签。
229
- *
230
- * 依据:`GET /repos` 的 `archived` / `disabled` / `private` / `fork` / `has_issues` / `permissions.push`
231
- * 就是全部需要的判断依据(本机实测 atom/atom 的 `archived` 为 true)。
232
- * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
233
- */
234
- export function repoBadges(repoAccess) {
235
- if (!repoAccess || typeof repoAccess !== 'object') return []
236
- const badges = []
237
- // 归档仓库在 GitHub 上是完全只读的:评论、打标签都会失败 —— 比"没有写权限"更彻底
238
- if (repoAccess.archived === true) badges.push({ text: '已归档', tone: 'warning' })
239
- if (repoAccess.disabled === true) badges.push({ text: '已禁用', tone: 'danger' })
240
- if (repoAccess.hasIssues === false) badges.push({ text: '无 Issues', tone: 'warning' })
241
- if (repoAccess.fork === true && repoAccess.parent && repoAccess.hasIssues !== true) {
242
- badges.push({ text: 'fork · 上游 ' + String(repoAccess.parent), tone: 'outline' })
243
- }
244
- if (repoAccess.push === false) badges.push({ text: '只读', tone: 'warning' })
245
- if (repoAccess.private === true) badges.push({ text: '私有', tone: 'outline' })
246
- return badges
247
- }
248
-
249
- /**
250
- * 仓库名纠错:404 之后从搜索结果里挑一个最像的,别让客户自己猜。
251
- *
252
- * 依据:`GET /search/repositories?q=<name>+in:name` 能按仓库名检索;
253
- * **但它走独立的 search 池**(本机实测 response header:`x-ratelimit-limit: 30`,
254
- * 即 30 次/分钟,远小于 core 的 5000)—— 所以只能在 404 之后偶尔调用,绝不能每轮轮询都用。
255
- * 出处:https://docs.github.com/en/rest/search/search#search-repositories
256
- */
257
- export function pickSuggestion(query, candidates) {
258
- const wanted = String(query || '').trim().toLowerCase()
259
- if (!wanted) return null
260
- const list = Array.isArray(candidates) ? candidates.filter((name) => typeof name === 'string') : []
261
- const exactName = wanted.includes('/') ? wanted.split('/')[1] : wanted
262
- // 优先级:仓库名完全相同 > 名字里包含 > 仅 owner 相同(最后这种基本没价值,直接丢)
263
- const sameName = list.find((name) => name.toLowerCase().endsWith('/' + exactName))
264
- if (sameName) return sameName
265
- const contains = list.find((name) => name.toLowerCase().includes(exactName) && exactName.length >= 4)
266
- return contains || null
267
- }
268
-
269
- /**
270
- * 「最后是谁在说话」:一条 issue 的最后评论者与时间。
271
- *
272
- * 为什么要它:会话被叫醒后第一件事就是判断「是不是已经有人处理了」。
273
- * 只给 issue 作者和更新时间不够 —— 更新时间可能是我自己打的标签引起的。
274
- *
275
- * 代价:每条 issue 一次 `GET /issues/{n}/comments`,所以只在**评论数 > 0** 且**批次前几条**里取,
276
- * 失败就静默省略(宁可少一行,不要拖慢唤醒)。
277
- * 出处:https://docs.github.com/en/rest/issues/comments#list-issue-comments
278
- */
279
- export function commentSummaryLine(lastComment, viewer) {
280
- if (!lastComment || typeof lastComment !== 'object') return ''
281
- const login = lastComment.login ? String(lastComment.login) : ''
282
- // 最后一条是"我们自己"发的,意义完全不同:那不是"有人在处理",而是上一轮留下的痕迹。
283
- // 依据:GET /user 返回当前 token 对应的账号(本机实测:`gh api user --jq .login` → 我们的账号名)。
284
- // 出处:https://docs.github.com/en/rest/users/users#get-the-authenticated-user
285
- const isSelf = Boolean(login && viewer && login.toLowerCase() === String(viewer).toLowerCase())
286
- const who = login ? (isSelf ? '我(上一轮留的)' : '@' + login) : ''
287
- const when = lastComment.at ? String(lastComment.at) : ''
288
- if (!who && !when) return ''
289
- return [who, when].filter(Boolean).join(' ')
290
- }
291
-
292
- /**
293
- * 批量取"最后一条评论"的 GraphQL 查询:一次请求拿 N 条,别一条一个 REST 调用。
294
- *
295
- * 依据:GraphQL 支持别名(alias)在同一请求里查多个 issue,且计费按点数而非请求数;
296
- * 但我们只用它的"批量"能力,复杂度极低(一个 repository + N 个 issue 别名)。
297
- * 出处:https://docs.github.com/en/graphql
298
- */
299
- export function buildCommentBatchQuery(count) {
300
- const n = Math.max(0, Math.min(10, Number(count) || 0))
301
- const parts = []
302
- for (let i = 0; i < n; i += 1) {
303
- parts.push(' i' + i + ': issue(number: $n' + i + ') { number'
304
- + ' comments(last: 1) { nodes { author { login } createdAt } }'
305
- + ' timelineItems(last: 5, itemTypes: [CROSS_REFERENCED_EVENT]) { nodes { ... on CrossReferencedEvent {'
306
- + ' source { __typename ... on PullRequest { number state url isDraft reviewDecision mergeable statusCheckRollup { state } } } } } }')
307
- }
308
- const vars = Array.from({ length: n }, (_, i) => '$n' + i + ': Int!').join(', ')
309
- return 'query($owner: String!, $name: String!' + (n > 0 ? ', ' + vars : '') + ') {'
310
- + ' repository(owner: $owner, name: $name) {'
311
- + String.fromCharCode(10) + parts.join(String.fromCharCode(10)) + String.fromCharCode(10)
312
- + '} }'
313
- }
314
-
315
- /**
316
- * 解析批量结果:把 {i0: {number, comments:{nodes:[…]}}} 摊平成 {number: {login, at}}。
317
- * 单个 issue 不存在时 GraphQL 会在 `errors` 里报 NOT_FOUND,但同请求里别的 issue 仍然有值 ——
318
- * 所以我们**只看 data,不因为 errors 整体放弃**。
319
- */
320
- export function parseCommentBatch(payload) {
321
- const out = {}
322
- const repo = payload && payload.data && payload.data.repository
323
- if (!repo || typeof repo !== 'object') return out
324
- for (const value of Object.values(repo)) {
325
- if (!value || typeof value !== 'object') continue
326
- const nodes = value.comments && value.comments.nodes
327
- const node = Array.isArray(nodes) && nodes.length > 0 ? nodes[nodes.length - 1] : null
328
- if (!node) continue
329
- const login = node.author && node.author.login ? String(node.author.login) : ''
330
- const linked = pickLinkedPullRequests(value.timelineItems && value.timelineItems.nodes)
331
- if (!login && linked.length === 0) continue
332
- out[String(value.number)] = {
333
- login,
334
- at: node.createdAt ? String(node.createdAt) : '',
335
- linked,
336
- }
337
- }
338
- return out
339
- }
340
-
341
- /**
342
- * 关闭原因 / 反复重开的提示。
343
- *
344
- * 依据:issue 对象有 `state_reason`(本机实测 `cli/cli` 上大量 `not_planned`;
345
- * 重新打开时会变成 `reopened`)。出处:https://docs.github.com/en/rest/issues/issues
346
- *
347
- * 为什么要它:主理鱼看到 closed 就跳过,但"被标成 not_planned 后又被重开"的条目
348
- * 恰恰是最需要人看一眼的 —— 说明之前判断"不做"是错的,或者有人在坚持。
349
- */
350
- export function stateReasonNote(item) {
351
- if (!item || typeof item !== 'object') return ''
352
- const reason = item.state_reason || item.stateReason
353
- if (!reason) return ''
354
- if (reason === 'reopened') return '这条被重新打开过(之前关过,判"不做"可能不对)'
355
- if (item.state === 'closed' && reason === 'not_planned') return '关闭原因:不做(not planned)'
356
- if (item.state === 'closed' && reason === 'completed') return '关闭原因:已完成'
357
- return ''
358
- }
359
-
360
- /**
361
- * 有没有人认领(assignee)。
362
- *
363
- * 依据:issue 对象的 `assignees` 数组;GitHub 的过滤语法里也有现成的 `assignee:` 限定词
364
- * (我们自己的过滤器 `onlyAssigned` 就基于它)。
365
- * 出处:https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/filtering-and-searching-issues-and-pull-requests
366
- *
367
- * 注意:**"无人认领更紧急"是产品判断,不是 GitHub 的规则**(本轮没找到官方依据),
368
- * 所以只在消息里如实标注,加权默认关闭。
369
- */
370
- export function assignmentNote(item) {
371
- if (!item || typeof item !== 'object') return ''
372
- const list = Array.isArray(item.assignees) ? item.assignees.filter(Boolean) : []
373
- if (list.length > 0) return ''
374
- return '未认领'
375
- }
376
-
377
- /**
378
- * 分诊信号表:单一口径,回答「我们到底看哪些信号、哪些是事实、哪些是判断、默认开不开」。
379
- *
380
- * 为什么要这张表:信号散落在代码里,客户看不见我们的取舍;写进这里之后
381
- * `/state` 会回传、面板能直接展示,改权重也不用改两处。
382
- *
383
- * `kind`:fact = GitHub 给的事实;judgment = 我们的产品判断(无官方依据)。
384
- */
385
- export const TRIAGE_SIGNALS = [
386
- { key: 'reopened', label: '被重新打开', kind: 'fact', weight: 100, default: true, why: 'state_reason=reopened,说明之前判"不做"被推翻' },
387
- { key: 'comments', label: '有人评论', kind: 'fact', weight: 10, default: true, why: '在等回应' },
388
- { key: 'labels', label: '带标签', kind: 'fact', weight: 5, default: true, why: '命中过某个分类' },
389
- { key: 'unassigned', label: '无人认领', kind: 'judgment', weight: 3, default: false, why: '团队经验:没人认领更该看 —— 无官方依据,故默认关' },
390
- { key: 'stale', label: '长期没动静', kind: 'fact', weight: 2, default: false, why: 'open 且超过 30 天没更新(stale bot 默认 60 天)—— 默认只展示,开启后 +2 分' },
391
- ]
392
-
393
- /**
394
- * 「躺了多久」:open 且长期没更新 —— stale bot 的世界标准是 60 天(actions/stale 默认值)。
395
- *
396
- * 依据:actions/stale 的 `days-before-stale` 默认 **60** 天
397
- * (https://github.com/actions/stale#readme),社区普遍用 30/60 两档。
398
- * 我们只**展示**,默认不参与排序(和 unassigned 一样:先给事实,判断交给用户)。
399
- */
400
- export function stalenessNote(item, options = {}) {
401
- if (!item || typeof item !== 'object') return ''
402
- const state = String(item.state || '')
403
- if (state && state !== 'open') return ''
404
- const stamp = item.updated_at || item.updatedAt
405
- const at = Date.parse(stamp || '')
406
- if (!Number.isFinite(at)) return ''
407
- // 括号别省:Number(now) || (Date.now() - at) 会把 now 自己当成毫秒差(写错过一次)
408
- const days = Math.floor(((Number(options.now) || Date.now()) - at) / (24 * 3600 * 1000))
409
- if (!Number.isFinite(days) || days < 0) return ''
410
- const threshold = Number(options.thresholdDays) || 30
411
- if (days < threshold) return ''
412
- return '躺了 ' + days + ' 天'
413
- }
414
-
415
- /**
416
- * 从 cross-reference 时间线里挑出关联的 PR。
417
- *
418
- * 依据:`timelineItems(itemTypes: [CROSS_REFERENCED_EVENT])` 会给出引用过这条 issue 的 PR;
419
- * 注意 `source` 是 union,**必须带 `__typename`** 才能选到 PullRequest 的字段
420
- * (直接选 `source { number }` 会报 "Selections can't be made directly on unions")。
421
- * 出处:https://docs.github.com/en/graphql/reference/objects#crossreferencedevent
422
- */
423
- export function pickLinkedPullRequests(nodes) {
424
- const list = Array.isArray(nodes) ? nodes : []
425
- const seen = new Set()
426
- const out = []
427
- for (const node of list) {
428
- const source = node && node.source
429
- if (!source || source.__typename !== 'PullRequest' || !source.number) continue
430
- if (seen.has(source.number)) continue
431
- seen.add(source.number)
432
- out.push({
433
- number: source.number,
434
- state: String(source.state || ''),
435
- url: String(source.url || ''),
436
- draft: source.isDraft === true,
437
- review: String(source.reviewDecision || ''),
438
- mergeable: String(source.mergeable || ''),
439
- ci: String((source.statusCheckRollup && source.statusCheckRollup.state) || ''),
440
- })
441
- }
442
- // open 的排前面(说明真在做),merged 其次,closed 最后
443
- const rank = { OPEN: 0, MERGED: 1, CLOSED: 2 }
444
- return out.sort((a, b) => (rank[a.state] ?? 9) - (rank[b.state] ?? 9))
445
- }
446
-
447
- /** 「已经有 PR 在做了」——避免会话重复干活。 */
448
- export function linkedPrNote(linked) {
449
- const list = Array.isArray(linked) ? linked.filter((item) => item && item.number) : []
450
- if (list.length === 0) return ''
451
- const first = list[0]
452
- const stateText = first.state === 'OPEN' ? '进行中' : first.state === 'MERGED' ? '已合并' : first.state === 'CLOSED' ? '已关闭' : String(first.state || '')
453
- // 草稿 PR 说明"还没准备好":别让会话以为对方在推进
454
- const draftText = first.state === 'OPEN' && first.draft === true ? '·草稿' : ''
455
- // 「卡在哪」比「有 PR」更有用:有冲突 / 等 review 是会话接管前最该知道的
456
- const blocked = first.state === 'OPEN'
457
- ? (first.mergeable === 'CONFLICTING' ? '·有冲突' : '')
458
- + (first.review === 'REVIEW_REQUIRED' ? '·等 review' : '')
459
- + (first.review === 'CHANGES_REQUESTED' ? '·被要求修改' : '')
460
- // CI 状态同样是"该不该接管"的依据:失败可能是可修的,运行中等它出结果
461
- + (first.ci === 'FAILURE' || first.ci === 'ERROR' ? '·CI 失败' : '')
462
- + (first.ci === 'PENDING' || first.ci === 'EXPECTED' ? '·CI 运行中' : '')
463
- : ''
464
- return '已有 PR #' + first.number + (stateText || draftText || blocked ? '(' + stateText + draftText + blocked + ')' : '')
465
- + (list.length > 1 ? ' 等 ' + list.length + ' 个' : '')
466
- }
66
+ return { kind: 'other', short, hint: '(没归类的错误:已按退避自动重试;持续出现就跑 watch_doctor 看检查清单,或把这行贴给对方)' }
67
+ }
68
+
69
+ /**
70
+ * 解析 `gh api --include` 的输出:状态行 / 响应头 / 空行 / 正文。
71
+ *
72
+ * 为什么用它而不是直接 `gh api`:GitHub 官方文档明确说
73
+ * 「Make authenticated conditional requests, so that unchanged data does not count against
74
+ * your primary rate limit」—— 带上 If-None-Match 后,没变化时拿 304,
75
+ * 304 **不计入**速率限制。对一个每 N 秒轮询的工具,这是最直接的省额度手段。
76
+ *
77
+ * 出处:https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api
78
+ */
79
+ export function parseGhInclude(stdout) {
80
+ const text = String(stdout || '')
81
+ const LF = String.fromCharCode(10)
82
+ const blank = LF + LF
83
+ const idx = text.indexOf(blank)
84
+ const head = idx < 0 ? text : text.slice(0, idx)
85
+ const body = idx < 0 ? text.trim() : text.slice(idx + blank.length)
86
+ const lines = head.split(LF)
87
+ const statusParts = String(lines[0] || '').split(' ')
88
+ const status = Number(statusParts[1]) || 0
89
+ const header = (name) => {
90
+ const needle = name.toLowerCase() + ':'
91
+ for (const line of lines) {
92
+ if (line.toLowerCase().startsWith(needle)) return line.slice(needle.length).trim()
93
+ }
94
+ return null
95
+ }
96
+ const numeric = (name) => {
97
+ const raw = header(name)
98
+ const value = Number(raw)
99
+ return Number.isFinite(value) ? value : null
100
+ }
101
+ const resetSeconds = numeric('x-ratelimit-reset')
102
+ // Stage 2 限流(secondary rate limit)用 Retry-After 告诉你等多久;primary 用 x-ratelimit-reset
103
+ const retryAfterRaw = header('retry-after')
104
+ return {
105
+ status,
106
+ etag: header('etag'),
107
+ remaining: numeric('x-ratelimit-remaining'),
108
+ limit: numeric('x-ratelimit-limit'),
109
+ resetAt: resetSeconds ? new Date(resetSeconds * 1000).toISOString() : null,
110
+ retryAfter: Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : null,
111
+ // GitHub 用这个头告诉你「这个 endpoint 至少隔多久再问」——忽略它会白撞额度
112
+ pollInterval: (() => { const raw = header('x-poll-interval'); return raw && Number.isFinite(Number(raw)) ? Number(raw) : null })(),
113
+ body,
114
+ }
115
+ }
116
+
117
+ /**
118
+ * 额度自适应:GitHub 主额度快用完时,不要继续按固定间隔撞墙。
119
+ *
120
+ * 依据:GitHub 每次响应都带 `X-RateLimit-Remaining` / `X-RateLimit-Reset`
121
+ * (实测 `gh api --include` 的输出里就是这几个头)。
122
+ * 剩余低于阈值时,把下一次轮询推到额度重置时间(最多等 1 小时),而不是继续发请求。
123
+ */
124
+ /**
125
+ * GitHub 的「第二阶段限流」会在 403/429 响应里带 `Retry-After: <秒>`。
126
+ * 按它等,比我们瞎猜一个退避时间准确得多。
127
+ * 依据:GitHub 暴露头里明确包含 `Retry-After`(实测 `gh api --include` 的
128
+ * Access-Control-Expose-Headers 一行里就能看到),且官方限流文档要求遵守它。
129
+ */
130
+ export function retryAfterMs(retryAfter, { capMs = 3600 * 1000 } = {}) {
131
+ const seconds = Number(retryAfter)
132
+ if (!Number.isFinite(seconds) || seconds <= 0) return 0
133
+ return Math.min(capMs, Math.round(seconds * 1000))
134
+ }
135
+
136
+ export function throttleDelayMs({ remaining, resetAt, now = Date.now(), threshold = 500, capMs = 3600 * 1000 } = {}) {
137
+ if (remaining === null || remaining === undefined) return 0
138
+ if (Number(remaining) >= Number(threshold)) return 0
139
+ const reset = Date.parse(resetAt || '')
140
+ if (!Number.isFinite(reset)) return Math.min(capMs, 5 * 60 * 1000)
141
+ const wait = reset - now + 1000
142
+ if (wait <= 0) return 0
143
+ return Math.min(capMs, wait)
144
+ }
145
+
146
+ /**
147
+ * 去同步抖动:给每个 watcher 一个**确定性的**起始偏移,避免 N 条守在同一条时间线上一起发车。
148
+ *
149
+ * 为什么不用随机数:随机数每次启动都不同,调试时对不上;用 id 的哈希则「同一条守永远同一个偏移」,
150
+ * 既错峰又可复现。范围固定在 [0, windowMs)。
151
+ *
152
+ * 依据:AWS Architecture Blog 的《Exponential Backoff And Jitter》——同步发车会让
153
+ * 下游在整点承压,加入抖动后峰值被摊平。(https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)
154
+ */
155
+ export function jitterMs(key, windowMs) {
156
+ const width = Math.max(0, Math.floor(Number(windowMs) || 0))
157
+ if (width === 0) return 0
158
+ const text = String(key || '')
159
+ let hash = 0
160
+ for (let i = 0; i < text.length; i += 1) hash = (hash * 31 + text.charCodeAt(i)) % 1000003
161
+ return hash % width
162
+ }
163
+
164
+ /**
165
+ * 把「为什么没叫醒」做成可统计的分布。
166
+ *
167
+ * 背景:我们每轮只留最近 5 条过滤记录(`filteredLog`),客户想知道
168
+ * 「为什么我加的标签一条都没被叫醒」时看不出全貌。这里按原因累计次数,
169
+ * 面板上就能直接读「不在标签白名单: ai-fix × 37」这种结论。
170
+ *
171
+ * 依据:GitHub 的 issue 过滤语义本身就是「限定词 + 集合运算」
172
+ * (label:/assignee:/state:…,见 GitHub 文档「Filtering and searching issues」),
173
+ * 所以「被哪条限定词刷掉」比「被刷掉」更值得告诉用户。
174
+ */
175
+ export function countReasons(counts, reason, { maxKinds = 12 } = {}) {
176
+ const map = { ...(counts || {}) }
177
+ if (!reason) return map
178
+ const key = String(reason).slice(0, 60)
179
+ map[key] = (Number(map[key]) || 0) + 1
180
+ const entries = Object.entries(map).sort((a, b) => b[1] - a[1]).slice(0, maxKinds)
181
+ return Object.fromEntries(entries)
182
+ }
183
+
184
+ /**
185
+ * 仓库权限提示:只读仓库上我们**没法**回写结果(评论、打标签都会 403)。
186
+ *
187
+ * 依据:`GET /repos/{owner}/{repo}` 返回 `permissions.push`,官方文档里这个对象就是
188
+ * "你有没有写权限"的权威来源。事先知道,比跑到一半才发现 403 好。
189
+ * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
190
+ */
191
+ export function accessNote(repoAccess) {
192
+ if (!repoAccess || typeof repoAccess !== 'object') return ''
193
+ if (repoAccess.push === true) return ''
194
+ if (repoAccess.push === false) {
195
+ return '你对 ' + String(repoAccess.repo || '这个仓库') + ' 只有读权限:能看、能被叫醒,但没法回写评论或打标签 —— '
196
+ + '要么换有写权限的 token,要么把结论写在本地/PR 描述里。'
197
+ }
198
+ return ''
199
+ }
200
+
201
+ /**
202
+ * 仓库结构提示:主理鱼只认 issue/PR,所以「这个仓库没有 issue」要提前说。
203
+ *
204
+ * 依据:`GET /repos/{owner}/{repo}` 返回 `has_issues` / `fork` / `parent.full_name`
205
+ * (本机实测这三个字段都在:`{fork, has_issues, parent, private}`)。
206
+ * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
207
+ */
208
+ export function repoStructureNote(repoAccess) {
209
+ if (!repoAccess || typeof repoAccess !== 'object') return ''
210
+ const repo = String(repoAccess.repo || '这个仓库')
211
+ if (repoAccess.archived === true) {
212
+ return repo + ' 已归档:GitHub 上归档仓库是只读的,评论和打标签都会失败 —— 守它只能看、不能回写。'
213
+ }
214
+ if (repoAccess.disabled === true) {
215
+ return repo + ' 已被禁用:这个仓库当前不可用,主理鱼不会拿到任何条目。'
216
+ }
217
+ if (repoAccess.hasIssues === false) {
218
+ return repo + ' 关闭了 Issues —— 主理鱼只认 issue / PR,这里不会有任何条目可接。'
219
+ }
220
+ if (repoAccess.fork === true && repoAccess.parent && repoAccess.hasIssues !== true) {
221
+ return repo + ' 是 ' + String(repoAccess.parent) + ' 的 fork。fork 默认不带 Issues,'
222
+ + 'issue 大多落在上游 —— 确认你要守的是哪一个(守上游就把仓库填成 ' + String(repoAccess.parent) + ')。'
223
+ }
224
+ return ''
225
+ }
226
+
227
+ /**
228
+ * 仓库能力徽章:把「这条守到底能不能干活」压缩成几个短标签。
229
+ *
230
+ * 依据:`GET /repos` 的 `archived` / `disabled` / `private` / `fork` / `has_issues` / `permissions.push`
231
+ * 就是全部需要的判断依据(本机实测 atom/atom 的 `archived` 为 true)。
232
+ * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
233
+ */
234
+ export function repoBadges(repoAccess) {
235
+ if (!repoAccess || typeof repoAccess !== 'object') return []
236
+ const badges = []
237
+ // 归档仓库在 GitHub 上是完全只读的:评论、打标签都会失败 —— 比"没有写权限"更彻底
238
+ if (repoAccess.archived === true) badges.push({ text: '已归档', tone: 'warning' })
239
+ if (repoAccess.disabled === true) badges.push({ text: '已禁用', tone: 'danger' })
240
+ if (repoAccess.hasIssues === false) badges.push({ text: '无 Issues', tone: 'warning' })
241
+ if (repoAccess.fork === true && repoAccess.parent && repoAccess.hasIssues !== true) {
242
+ badges.push({ text: 'fork · 上游 ' + String(repoAccess.parent), tone: 'outline' })
243
+ }
244
+ if (repoAccess.push === false) badges.push({ text: '只读', tone: 'warning' })
245
+ if (repoAccess.private === true) badges.push({ text: '私有', tone: 'outline' })
246
+ return badges
247
+ }
248
+
249
+ /**
250
+ * 仓库名纠错:404 之后从搜索结果里挑一个最像的,别让客户自己猜。
251
+ *
252
+ * 依据:`GET /search/repositories?q=<name>+in:name` 能按仓库名检索;
253
+ * **但它走独立的 search 池**(本机实测 response header:`x-ratelimit-limit: 30`,
254
+ * 即 30 次/分钟,远小于 core 的 5000)—— 所以只能在 404 之后偶尔调用,绝不能每轮轮询都用。
255
+ * 出处:https://docs.github.com/en/rest/search/search#search-repositories
256
+ */
257
+ export function pickSuggestion(query, candidates) {
258
+ const wanted = String(query || '').trim().toLowerCase()
259
+ if (!wanted) return null
260
+ const list = Array.isArray(candidates) ? candidates.filter((name) => typeof name === 'string') : []
261
+ const exactName = wanted.includes('/') ? wanted.split('/')[1] : wanted
262
+ // 优先级:仓库名完全相同 > 名字里包含 > 仅 owner 相同(最后这种基本没价值,直接丢)
263
+ const sameName = list.find((name) => name.toLowerCase().endsWith('/' + exactName))
264
+ if (sameName) return sameName
265
+ const contains = list.find((name) => name.toLowerCase().includes(exactName) && exactName.length >= 4)
266
+ return contains || null
267
+ }
268
+
269
+ /**
270
+ * 「最后是谁在说话」:一条 issue 的最后评论者与时间。
271
+ *
272
+ * 为什么要它:会话被叫醒后第一件事就是判断「是不是已经有人处理了」。
273
+ * 只给 issue 作者和更新时间不够 —— 更新时间可能是我自己打的标签引起的。
274
+ *
275
+ * 代价:每条 issue 一次 `GET /issues/{n}/comments`,所以只在**评论数 > 0** 且**批次前几条**里取,
276
+ * 失败就静默省略(宁可少一行,不要拖慢唤醒)。
277
+ * 出处:https://docs.github.com/en/rest/issues/comments#list-issue-comments
278
+ */
279
+ export function commentSummaryLine(lastComment, viewer) {
280
+ if (!lastComment || typeof lastComment !== 'object') return ''
281
+ const login = lastComment.login ? String(lastComment.login) : ''
282
+ // 最后一条是"我们自己"发的,意义完全不同:那不是"有人在处理",而是上一轮留下的痕迹。
283
+ // 依据:GET /user 返回当前 token 对应的账号(本机实测:`gh api user --jq .login` → 我们的账号名)。
284
+ // 出处:https://docs.github.com/en/rest/users/users#get-the-authenticated-user
285
+ const isSelf = Boolean(login && viewer && login.toLowerCase() === String(viewer).toLowerCase())
286
+ const who = login ? (isSelf ? '我(上一轮留的)' : '@' + login) : ''
287
+ const when = lastComment.at ? String(lastComment.at) : ''
288
+ if (!who && !when) return ''
289
+ return [who, when].filter(Boolean).join(' ')
290
+ }
291
+
292
+ /**
293
+ * 批量取"最后一条评论"的 GraphQL 查询:一次请求拿 N 条,别一条一个 REST 调用。
294
+ *
295
+ * 依据:GraphQL 支持别名(alias)在同一请求里查多个 issue,且计费按点数而非请求数;
296
+ * 但我们只用它的"批量"能力,复杂度极低(一个 repository + N 个 issue 别名)。
297
+ * 出处:https://docs.github.com/en/graphql
298
+ */
299
+ export function buildCommentBatchQuery(count) {
300
+ const n = Math.max(0, Math.min(10, Number(count) || 0))
301
+ const parts = []
302
+ for (let i = 0; i < n; i += 1) {
303
+ parts.push(' i' + i + ': issue(number: $n' + i + ') { number'
304
+ + ' comments(last: 1) { nodes { author { login } createdAt } }'
305
+ + ' timelineItems(last: 5, itemTypes: [CROSS_REFERENCED_EVENT]) { nodes { ... on CrossReferencedEvent {'
306
+ + ' source { __typename ... on PullRequest { number state url isDraft reviewDecision mergeable statusCheckRollup { state } } } } } }')
307
+ }
308
+ const vars = Array.from({ length: n }, (_, i) => '$n' + i + ': Int!').join(', ')
309
+ return 'query($owner: String!, $name: String!' + (n > 0 ? ', ' + vars : '') + ') {'
310
+ + ' repository(owner: $owner, name: $name) {'
311
+ + String.fromCharCode(10) + parts.join(String.fromCharCode(10)) + String.fromCharCode(10)
312
+ + '} }'
313
+ }
314
+
315
+ /**
316
+ * 解析批量结果:把 {i0: {number, comments:{nodes:[…]}}} 摊平成 {number: {login, at}}。
317
+ * 单个 issue 不存在时 GraphQL 会在 `errors` 里报 NOT_FOUND,但同请求里别的 issue 仍然有值 ——
318
+ * 所以我们**只看 data,不因为 errors 整体放弃**。
319
+ */
320
+ export function parseCommentBatch(payload) {
321
+ const out = {}
322
+ const repo = payload && payload.data && payload.data.repository
323
+ if (!repo || typeof repo !== 'object') return out
324
+ for (const value of Object.values(repo)) {
325
+ if (!value || typeof value !== 'object') continue
326
+ const nodes = value.comments && value.comments.nodes
327
+ const node = Array.isArray(nodes) && nodes.length > 0 ? nodes[nodes.length - 1] : null
328
+ if (!node) continue
329
+ const login = node.author && node.author.login ? String(node.author.login) : ''
330
+ const linked = pickLinkedPullRequests(value.timelineItems && value.timelineItems.nodes)
331
+ if (!login && linked.length === 0) continue
332
+ out[String(value.number)] = {
333
+ login,
334
+ at: node.createdAt ? String(node.createdAt) : '',
335
+ linked,
336
+ }
337
+ }
338
+ return out
339
+ }
340
+
341
+ /**
342
+ * 关闭原因 / 反复重开的提示。
343
+ *
344
+ * 依据:issue 对象有 `state_reason`(本机实测 `cli/cli` 上大量 `not_planned`;
345
+ * 重新打开时会变成 `reopened`)。出处:https://docs.github.com/en/rest/issues/issues
346
+ *
347
+ * 为什么要它:主理鱼看到 closed 就跳过,但"被标成 not_planned 后又被重开"的条目
348
+ * 恰恰是最需要人看一眼的 —— 说明之前判断"不做"是错的,或者有人在坚持。
349
+ */
350
+ export function stateReasonNote(item) {
351
+ if (!item || typeof item !== 'object') return ''
352
+ const reason = item.state_reason || item.stateReason
353
+ if (!reason) return ''
354
+ if (reason === 'reopened') return '这条被重新打开过(之前关过,判"不做"可能不对)'
355
+ if (item.state === 'closed' && reason === 'not_planned') return '关闭原因:不做(not planned)'
356
+ if (item.state === 'closed' && reason === 'completed') return '关闭原因:已完成'
357
+ return ''
358
+ }
359
+
360
+ /**
361
+ * 有没有人认领(assignee)。
362
+ *
363
+ * 依据:issue 对象的 `assignees` 数组;GitHub 的过滤语法里也有现成的 `assignee:` 限定词
364
+ * (我们自己的过滤器 `onlyAssigned` 就基于它)。
365
+ * 出处:https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/filtering-and-searching-issues-and-pull-requests
366
+ *
367
+ * 注意:**"无人认领更紧急"是产品判断,不是 GitHub 的规则**(本轮没找到官方依据),
368
+ * 所以只在消息里如实标注,加权默认关闭。
369
+ */
370
+ export function assignmentNote(item) {
371
+ if (!item || typeof item !== 'object') return ''
372
+ const list = Array.isArray(item.assignees) ? item.assignees.filter(Boolean) : []
373
+ if (list.length > 0) return ''
374
+ return '未认领'
375
+ }
376
+
377
+ /**
378
+ * 分诊信号表:单一口径,回答「我们到底看哪些信号、哪些是事实、哪些是判断、默认开不开」。
379
+ *
380
+ * 为什么要这张表:信号散落在代码里,客户看不见我们的取舍;写进这里之后
381
+ * `/state` 会回传、面板能直接展示,改权重也不用改两处。
382
+ *
383
+ * `kind`:fact = GitHub 给的事实;judgment = 我们的产品判断(无官方依据)。
384
+ */
385
+ export const TRIAGE_SIGNALS = [
386
+ { key: 'reopened', label: '被重新打开', kind: 'fact', weight: 100, default: true, why: 'state_reason=reopened,说明之前判"不做"被推翻' },
387
+ { key: 'comments', label: '有人评论', kind: 'fact', weight: 10, default: true, why: '在等回应' },
388
+ { key: 'labels', label: '带标签', kind: 'fact', weight: 5, default: true, why: '命中过某个分类' },
389
+ { key: 'unassigned', label: '无人认领', kind: 'judgment', weight: 3, default: false, why: '团队经验:没人认领更该看 —— 无官方依据,故默认关' },
390
+ { key: 'stale', label: '长期没动静', kind: 'fact', weight: 2, default: false, why: 'open 且超过 30 天没更新(stale bot 默认 60 天)—— 默认只展示,开启后 +2 分' },
391
+ ]
392
+
393
+ /**
394
+ * 「躺了多久」:open 且长期没更新 —— stale bot 的世界标准是 60 天(actions/stale 默认值)。
395
+ *
396
+ * 依据:actions/stale 的 `days-before-stale` 默认 **60** 天
397
+ * (https://github.com/actions/stale#readme),社区普遍用 30/60 两档。
398
+ * 我们只**展示**,默认不参与排序(和 unassigned 一样:先给事实,判断交给用户)。
399
+ */
400
+ export function stalenessNote(item, options = {}) {
401
+ if (!item || typeof item !== 'object') return ''
402
+ const state = String(item.state || '')
403
+ if (state && state !== 'open') return ''
404
+ const stamp = item.updated_at || item.updatedAt
405
+ const at = Date.parse(stamp || '')
406
+ if (!Number.isFinite(at)) return ''
407
+ // 括号别省:Number(now) || (Date.now() - at) 会把 now 自己当成毫秒差(写错过一次)
408
+ const days = Math.floor(((Number(options.now) || Date.now()) - at) / (24 * 3600 * 1000))
409
+ if (!Number.isFinite(days) || days < 0) return ''
410
+ const threshold = Number(options.thresholdDays) || 30
411
+ if (days < threshold) return ''
412
+ return '躺了 ' + days + ' 天'
413
+ }
414
+
415
+ /**
416
+ * 从 cross-reference 时间线里挑出关联的 PR。
417
+ *
418
+ * 依据:`timelineItems(itemTypes: [CROSS_REFERENCED_EVENT])` 会给出引用过这条 issue 的 PR;
419
+ * 注意 `source` 是 union,**必须带 `__typename`** 才能选到 PullRequest 的字段
420
+ * (直接选 `source { number }` 会报 "Selections can't be made directly on unions")。
421
+ * 出处:https://docs.github.com/en/graphql/reference/objects#crossreferencedevent
422
+ */
423
+ export function pickLinkedPullRequests(nodes) {
424
+ const list = Array.isArray(nodes) ? nodes : []
425
+ const seen = new Set()
426
+ const out = []
427
+ for (const node of list) {
428
+ const source = node && node.source
429
+ if (!source || source.__typename !== 'PullRequest' || !source.number) continue
430
+ if (seen.has(source.number)) continue
431
+ seen.add(source.number)
432
+ out.push({
433
+ number: source.number,
434
+ state: String(source.state || ''),
435
+ url: String(source.url || ''),
436
+ draft: source.isDraft === true,
437
+ review: String(source.reviewDecision || ''),
438
+ mergeable: String(source.mergeable || ''),
439
+ ci: String((source.statusCheckRollup && source.statusCheckRollup.state) || ''),
440
+ })
441
+ }
442
+ // open 的排前面(说明真在做),merged 其次,closed 最后
443
+ const rank = { OPEN: 0, MERGED: 1, CLOSED: 2 }
444
+ return out.sort((a, b) => (rank[a.state] ?? 9) - (rank[b.state] ?? 9))
445
+ }
446
+
447
+ /** 「已经有 PR 在做了」——避免会话重复干活。 */
448
+ export function linkedPrNote(linked) {
449
+ const list = Array.isArray(linked) ? linked.filter((item) => item && item.number) : []
450
+ if (list.length === 0) return ''
451
+ const first = list[0]
452
+ const stateText = first.state === 'OPEN' ? '进行中' : first.state === 'MERGED' ? '已合并' : first.state === 'CLOSED' ? '已关闭' : String(first.state || '')
453
+ // 草稿 PR 说明"还没准备好":别让会话以为对方在推进
454
+ const draftText = first.state === 'OPEN' && first.draft === true ? '·草稿' : ''
455
+ // 「卡在哪」比「有 PR」更有用:有冲突 / 等 review 是会话接管前最该知道的
456
+ const blocked = first.state === 'OPEN'
457
+ ? (first.mergeable === 'CONFLICTING' ? '·有冲突' : '')
458
+ + (first.review === 'REVIEW_REQUIRED' ? '·等 review' : '')
459
+ + (first.review === 'CHANGES_REQUESTED' ? '·被要求修改' : '')
460
+ // CI 状态同样是"该不该接管"的依据:失败可能是可修的,运行中等它出结果
461
+ + (first.ci === 'FAILURE' || first.ci === 'ERROR' ? '·CI 失败' : '')
462
+ + (first.ci === 'PENDING' || first.ci === 'EXPECTED' ? '·CI 运行中' : '')
463
+ : ''
464
+ return '已有 PR #' + first.number + (stateText || draftText || blocked ? '(' + stateText + draftText + blocked + ')' : '')
465
+ + (list.length > 1 ? ' 等 ' + list.length + ' 个' : '')
466
+ }