dsh-session-superagent 0.8.94 → 0.8.96

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/CHANGELOG.md CHANGED
@@ -2,6 +2,66 @@
2
2
 
3
3
  格式参照 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
+ ## [0.8.96] - 2026-11-02 —— index.js 量完不拆;顺手加文档体检
6
+
7
+ ### 一、为什么**不**拆 index.js(知识库第 45 条)
8
+ 用拆 watch.js 的同一套方法量化:
9
+ ```
10
+ 基建区 1000 行 / 注册区 796 行
11
+ 注册区用到的基建名字:25 个(占 46 个定义)
12
+ 每条路由平均跨度:53 行
13
+ ```
14
+ 对比 watch.js 那次是**零依赖单向关系**,这边是 25 个共享符号 ——
15
+ 拆开等于给每条路由传一大包依赖或造"上帝对象",复杂度从一维变两维。
16
+ 它已是"上基建、下注册"的纵向结构,**不拆**。
17
+
18
+ ### 二、顺手加的:文档体检
19
+ 45+ 篇文档互相引用,写错的链接没人会发现。新增 `scripts/check-docs.mjs`:
20
+ - 扫全部 Markdown,只查仓库内相对链接;
21
+ - 额外查**孤儿文档**(`docs/kb/*.md` 没被索引 = 客户永远看不到)。
22
+
23
+ 首跑结果:
24
+ ```
25
+ 扫描 66 篇 Markdown,63 个内部链接目标
26
+ PASS 所有内部链接都能解析
27
+ PASS 知识库文档全部被索引
28
+ ```
29
+ 都健康 —— 但**这是运气不是保证**。已接入 preflight(第 10 项)。
30
+
31
+ ### 测试
32
+ - 138 例全过;preflight **10 项**全过。
33
+
34
+ ## [0.8.95] - 2026-11-02 —— 按「改动轴」拆开 watch.js(883 → 486 行)
35
+
36
+ ### 学到的(知识库第 44 条)
37
+ 判断该不该拆,看的是「**改一个功能要不要同时读几块不相干的地方**」,不是行数。
38
+ `lib/watch.js` 里混着两类东西:**调度与状态**(水位/抖动/退避/时段/合并写)
39
+ 和 **GitHub 交互与措辞**(错误归类/Retry-After/徽章/提示语/GraphQL 批量),修改动机完全不同。
40
+
41
+ ### 先核对依赖,再动手
42
+ 脚本统计两块之间的引用:
43
+ ```
44
+ tail 用到的 head 名字:(无)
45
+ head 用到的 tail 名字:assignmentNote, commentSummaryLine, linkedPrNote, stalenessNote, stateReasonNote
46
+ ```
47
+ 尾部 422 行对前半**零依赖**,只被 `formatWatchText` 用到 5 个函数 —— 这种单向稀疏依赖才适合拆。
48
+
49
+ ### 结果
50
+ | 文件 | 行数 | 职责 |
51
+ |---|---|---|
52
+ | `lib/watch.js` | 883 → **486** | 调度与状态 |
53
+ | `lib/gh-format.js` | **430**(新) | 解析/归类/措辞,不发请求、不碰状态 |
54
+
55
+ `watch.js` 转出 19 个名字,`index.js` 与 8 个测试文件**一行未改**。
56
+
57
+ ### 拆完必须同步的三处(都有专门门禁守着)
58
+ 1. `sync-profile.mjs` 的 `TARGETS` —— 漏了就是「新文件不进 profile → 插件整体挂不上」,这个坑踩过;
59
+ 2. `preflight.mjs` 的语法检查列表(现在 6 个文件);
60
+ 3. `contract.mjs --update` 确认接口形状未变。
61
+
62
+ ### 测试
63
+ - 138 例全过;preflight 9 项全过。
64
+
5
65
  ## [0.8.94] - 2026-11-02 —— 面板顶部直接告诉你「该重启了」
6
66
 
7
67
  ### 学到的(知识库第 43 条)
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  <img src="assets/icon-180.png" width="88" height="88" alt="">
4
4
 
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
- [![Version](https://img.shields.io/badge/version-0.8.94-green.svg)](https://github.com/MYCF711/dsh-session-superagent/releases)
6
+ [![Version](https://img.shields.io/badge/version-0.8.96-green.svg)](https://github.com/MYCF711/dsh-session-superagent/releases)
7
7
  [![npm](https://img.shields.io/npm/v/dsh-session-superagent.svg)](https://www.npmjs.com/package/dsh-session-superagent)
8
8
  [![dsh](https://img.shields.io/badge/DeepSeek%20Harness-plugin-orange.svg)](https://github.com/topics/dsh-plugin)
9
9
 
@@ -143,7 +143,7 @@ dsh plugin --profile <profile> add dsh-session-superagent@latest
143
143
  ```bash
144
144
  node --test # 103 例单测
145
145
  node scripts/ui-audit.mjs # 11 项 UI 指标(写死颜色 / 自造 token / 官方结构采用 …)
146
- node scripts/preflight.mjs # 9 项门禁(含上面两条,外加 profile 一致性、路由面、包内容)
146
+ node scripts/preflight.mjs # 10 项门禁(含上面两条,外加 profile 一致性、路由面、包内容)
147
147
  node scripts/render-preview.mjs preview.html # 双主题静态预览,直接浏览器打开
148
148
  ```
149
149
 
package/client.js CHANGED
@@ -14,7 +14,7 @@ window.__ModuleLoader__.load({
14
14
  const { useCallback, useEffect, useRef, useState } = React
15
15
 
16
16
  // 客户端版本探针:每次模块加载写一次,用来确认浏览器里跑的是哪一版
17
- const CLIENT_VERSION = '0.8.94'
17
+ const CLIENT_VERSION = '0.8.96'
18
18
  let BASE = '/session-superagent'
19
19
  /**
20
20
  * 挑「最新的那个服务端实例」。
@@ -0,0 +1,430 @@
1
+ // GitHub 交互层:把 API 的数据变成「人话」和「可判断的结论」。
2
+ //
3
+ // 从 watch.js 拆出来的理由:另一半是**调度与状态**(去重水位、退避、时段、合并写)。
4
+ // 两块的修改动机完全不同 —— 改「唤醒消息多一行」不需要看调度代码,反之亦然。
5
+ // 拆完 watch.js 从 883 行降到 ~470 行,这边自成一体、对 watch.js 零依赖(已用脚本核对过)。
6
+ //
7
+ // 约定:本文件只做「解析 / 归类 / 措辞」,不发请求、不碰状态。
8
+
9
+ export function classifyGhError(detail) {
10
+ const text = String(detail || '')
11
+ // 长 URL 压缩,避免一整条 API 地址占满面板
12
+ const short = text
13
+ .replace(/Get "https?:\/\/[^"]{16,}"/g, 'GitHub API 请求')
14
+ .replace(/Post "https?:\/\/[^"]{16,}"/g, 'GitHub API 请求')
15
+ .slice(0, 200)
16
+
17
+ if (/HTTP 401|Bad credentials|requires authentication/i.test(text)) {
18
+ return { kind: 'auth', short, hint: '(gh 登录失效:跑 gh auth login,或在面板填 token)' }
19
+ }
20
+ if (/HTTP 403|rate limit|API rate limit exceeded/i.test(text)) {
21
+ return { kind: 'ratelimit', short, hint: '(被 GitHub 限流:等几分钟,或换成带 token 的凭证)' }
22
+ }
23
+ if (/ENOENT|not found.*gh|gh: command not found/i.test(text)) {
24
+ return { kind: 'nogh', short, hint: '(找不到 gh 命令:确认已安装且在 PATH)' }
25
+ }
26
+ if (/HTTP 404|HTTP 403|Not Found[\s\S]*404|Not Found/.test(text)) {
27
+ return { kind: 'notfound', short, hint: '(仓库不存在或没权限:检查 owner/name)' }
28
+ }
29
+ if (/EOF|i\/o timeout|connection reset|dial tcp|TLS handshake|no such host|proxyconnect|timeout/i.test(text)) {
30
+ return { kind: 'network', short, hint: '(网络抖动:这一轮没连上 GitHub,已按退避自动重试,不需要手动处理)' }
31
+ }
32
+ return { kind: 'other', short, hint: '' }
33
+ }
34
+
35
+ /**
36
+ * 解析 `gh api --include` 的输出:状态行 / 响应头 / 空行 / 正文。
37
+ *
38
+ * 为什么用它而不是直接 `gh api`:GitHub 官方文档明确说
39
+ * 「Make authenticated conditional requests, so that unchanged data does not count against
40
+ * your primary rate limit」—— 带上 If-None-Match 后,没变化时拿 304,
41
+ * 304 **不计入**速率限制。对一个每 N 秒轮询的工具,这是最直接的省额度手段。
42
+ *
43
+ * 出处:https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api
44
+ */
45
+ export function parseGhInclude(stdout) {
46
+ const text = String(stdout || '')
47
+ const LF = String.fromCharCode(10)
48
+ const blank = LF + LF
49
+ const idx = text.indexOf(blank)
50
+ const head = idx < 0 ? text : text.slice(0, idx)
51
+ const body = idx < 0 ? text.trim() : text.slice(idx + blank.length)
52
+ const lines = head.split(LF)
53
+ const statusParts = String(lines[0] || '').split(' ')
54
+ const status = Number(statusParts[1]) || 0
55
+ const header = (name) => {
56
+ const needle = name.toLowerCase() + ':'
57
+ for (const line of lines) {
58
+ if (line.toLowerCase().startsWith(needle)) return line.slice(needle.length).trim()
59
+ }
60
+ return null
61
+ }
62
+ const numeric = (name) => {
63
+ const raw = header(name)
64
+ const value = Number(raw)
65
+ return Number.isFinite(value) ? value : null
66
+ }
67
+ const resetSeconds = numeric('x-ratelimit-reset')
68
+ // Stage 2 限流(secondary rate limit)用 Retry-After 告诉你等多久;primary 用 x-ratelimit-reset
69
+ const retryAfterRaw = header('retry-after')
70
+ return {
71
+ status,
72
+ etag: header('etag'),
73
+ remaining: numeric('x-ratelimit-remaining'),
74
+ limit: numeric('x-ratelimit-limit'),
75
+ resetAt: resetSeconds ? new Date(resetSeconds * 1000).toISOString() : null,
76
+ retryAfter: Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : null,
77
+ body,
78
+ }
79
+ }
80
+
81
+ /**
82
+ * 额度自适应:GitHub 主额度快用完时,不要继续按固定间隔撞墙。
83
+ *
84
+ * 依据:GitHub 每次响应都带 `X-RateLimit-Remaining` / `X-RateLimit-Reset`
85
+ * (实测 `gh api --include` 的输出里就是这几个头)。
86
+ * 剩余低于阈值时,把下一次轮询推到额度重置时间(最多等 1 小时),而不是继续发请求。
87
+ */
88
+ /**
89
+ * GitHub 的「第二阶段限流」会在 403/429 响应里带 `Retry-After: <秒>`。
90
+ * 按它等,比我们瞎猜一个退避时间准确得多。
91
+ * 依据:GitHub 暴露头里明确包含 `Retry-After`(实测 `gh api --include` 的
92
+ * Access-Control-Expose-Headers 一行里就能看到),且官方限流文档要求遵守它。
93
+ */
94
+ export function retryAfterMs(retryAfter, { capMs = 3600 * 1000 } = {}) {
95
+ const seconds = Number(retryAfter)
96
+ if (!Number.isFinite(seconds) || seconds <= 0) return 0
97
+ return Math.min(capMs, Math.round(seconds * 1000))
98
+ }
99
+
100
+ export function throttleDelayMs({ remaining, resetAt, now = Date.now(), threshold = 500, capMs = 3600 * 1000 } = {}) {
101
+ if (remaining === null || remaining === undefined) return 0
102
+ if (Number(remaining) >= Number(threshold)) return 0
103
+ const reset = Date.parse(resetAt || '')
104
+ if (!Number.isFinite(reset)) return Math.min(capMs, 5 * 60 * 1000)
105
+ const wait = reset - now + 1000
106
+ if (wait <= 0) return 0
107
+ return Math.min(capMs, wait)
108
+ }
109
+
110
+ /**
111
+ * 去同步抖动:给每个 watcher 一个**确定性的**起始偏移,避免 N 条守在同一条时间线上一起发车。
112
+ *
113
+ * 为什么不用随机数:随机数每次启动都不同,调试时对不上;用 id 的哈希则「同一条守永远同一个偏移」,
114
+ * 既错峰又可复现。范围固定在 [0, windowMs)。
115
+ *
116
+ * 依据:AWS Architecture Blog 的《Exponential Backoff And Jitter》——同步发车会让
117
+ * 下游在整点承压,加入抖动后峰值被摊平。(https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)
118
+ */
119
+ export function jitterMs(key, windowMs) {
120
+ const width = Math.max(0, Math.floor(Number(windowMs) || 0))
121
+ if (width === 0) return 0
122
+ const text = String(key || '')
123
+ let hash = 0
124
+ for (let i = 0; i < text.length; i += 1) hash = (hash * 31 + text.charCodeAt(i)) % 1000003
125
+ return hash % width
126
+ }
127
+
128
+ /**
129
+ * 把「为什么没叫醒」做成可统计的分布。
130
+ *
131
+ * 背景:我们每轮只留最近 5 条过滤记录(`filteredLog`),客户想知道
132
+ * 「为什么我加的标签一条都没被叫醒」时看不出全貌。这里按原因累计次数,
133
+ * 面板上就能直接读「不在标签白名单: ai-fix × 37」这种结论。
134
+ *
135
+ * 依据:GitHub 的 issue 过滤语义本身就是「限定词 + 集合运算」
136
+ * (label:/assignee:/state:…,见 GitHub 文档「Filtering and searching issues」),
137
+ * 所以「被哪条限定词刷掉」比「被刷掉」更值得告诉用户。
138
+ */
139
+ export function countReasons(counts, reason, { maxKinds = 12 } = {}) {
140
+ const map = { ...(counts || {}) }
141
+ if (!reason) return map
142
+ const key = String(reason).slice(0, 60)
143
+ map[key] = (Number(map[key]) || 0) + 1
144
+ const entries = Object.entries(map).sort((a, b) => b[1] - a[1]).slice(0, maxKinds)
145
+ return Object.fromEntries(entries)
146
+ }
147
+
148
+ /**
149
+ * 仓库权限提示:只读仓库上我们**没法**回写结果(评论、打标签都会 403)。
150
+ *
151
+ * 依据:`GET /repos/{owner}/{repo}` 返回 `permissions.push`,官方文档里这个对象就是
152
+ * "你有没有写权限"的权威来源。事先知道,比跑到一半才发现 403 好。
153
+ * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
154
+ */
155
+ export function accessNote(repoAccess) {
156
+ if (!repoAccess || typeof repoAccess !== 'object') return ''
157
+ if (repoAccess.push === true) return ''
158
+ if (repoAccess.push === false) {
159
+ return '你对 ' + String(repoAccess.repo || '这个仓库') + ' 只有读权限:能看、能被叫醒,但没法回写评论或打标签 —— '
160
+ + '要么换有写权限的 token,要么把结论写在本地/PR 描述里。'
161
+ }
162
+ return ''
163
+ }
164
+
165
+ /**
166
+ * 仓库结构提示:主理鱼只认 issue/PR,所以「这个仓库没有 issue」要提前说。
167
+ *
168
+ * 依据:`GET /repos/{owner}/{repo}` 返回 `has_issues` / `fork` / `parent.full_name`
169
+ * (本机实测这三个字段都在:`{fork, has_issues, parent, private}`)。
170
+ * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
171
+ */
172
+ export function repoStructureNote(repoAccess) {
173
+ if (!repoAccess || typeof repoAccess !== 'object') return ''
174
+ const repo = String(repoAccess.repo || '这个仓库')
175
+ if (repoAccess.archived === true) {
176
+ return repo + ' 已归档:GitHub 上归档仓库是只读的,评论和打标签都会失败 —— 守它只能看、不能回写。'
177
+ }
178
+ if (repoAccess.disabled === true) {
179
+ return repo + ' 已被禁用:这个仓库当前不可用,主理鱼不会拿到任何条目。'
180
+ }
181
+ if (repoAccess.hasIssues === false) {
182
+ return repo + ' 关闭了 Issues —— 主理鱼只认 issue / PR,这里不会有任何条目可接。'
183
+ }
184
+ if (repoAccess.fork === true && repoAccess.parent && repoAccess.hasIssues !== true) {
185
+ return repo + ' 是 ' + String(repoAccess.parent) + ' 的 fork。fork 默认不带 Issues,'
186
+ + 'issue 大多落在上游 —— 确认你要守的是哪一个(守上游就把仓库填成 ' + String(repoAccess.parent) + ')。'
187
+ }
188
+ return ''
189
+ }
190
+
191
+ /**
192
+ * 仓库能力徽章:把「这条守到底能不能干活」压缩成几个短标签。
193
+ *
194
+ * 依据:`GET /repos` 的 `archived` / `disabled` / `private` / `fork` / `has_issues` / `permissions.push`
195
+ * 就是全部需要的判断依据(本机实测 atom/atom 的 `archived` 为 true)。
196
+ * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
197
+ */
198
+ export function repoBadges(repoAccess) {
199
+ if (!repoAccess || typeof repoAccess !== 'object') return []
200
+ const badges = []
201
+ // 归档仓库在 GitHub 上是完全只读的:评论、打标签都会失败 —— 比"没有写权限"更彻底
202
+ if (repoAccess.archived === true) badges.push({ text: '已归档', tone: 'warning' })
203
+ if (repoAccess.disabled === true) badges.push({ text: '已禁用', tone: 'danger' })
204
+ if (repoAccess.hasIssues === false) badges.push({ text: '无 Issues', tone: 'warning' })
205
+ if (repoAccess.fork === true && repoAccess.parent && repoAccess.hasIssues !== true) {
206
+ badges.push({ text: 'fork · 上游 ' + String(repoAccess.parent), tone: 'outline' })
207
+ }
208
+ if (repoAccess.push === false) badges.push({ text: '只读', tone: 'warning' })
209
+ if (repoAccess.private === true) badges.push({ text: '私有', tone: 'outline' })
210
+ return badges
211
+ }
212
+
213
+ /**
214
+ * 仓库名纠错:404 之后从搜索结果里挑一个最像的,别让客户自己猜。
215
+ *
216
+ * 依据:`GET /search/repositories?q=<name>+in:name` 能按仓库名检索;
217
+ * **但它走独立的 search 池**(本机实测 response header:`x-ratelimit-limit: 30`,
218
+ * 即 30 次/分钟,远小于 core 的 5000)—— 所以只能在 404 之后偶尔调用,绝不能每轮轮询都用。
219
+ * 出处:https://docs.github.com/en/rest/search/search#search-repositories
220
+ */
221
+ export function pickSuggestion(query, candidates) {
222
+ const wanted = String(query || '').trim().toLowerCase()
223
+ if (!wanted) return null
224
+ const list = Array.isArray(candidates) ? candidates.filter((name) => typeof name === 'string') : []
225
+ const exactName = wanted.includes('/') ? wanted.split('/')[1] : wanted
226
+ // 优先级:仓库名完全相同 > 名字里包含 > 仅 owner 相同(最后这种基本没价值,直接丢)
227
+ const sameName = list.find((name) => name.toLowerCase().endsWith('/' + exactName))
228
+ if (sameName) return sameName
229
+ const contains = list.find((name) => name.toLowerCase().includes(exactName) && exactName.length >= 4)
230
+ return contains || null
231
+ }
232
+
233
+ /**
234
+ * 「最后是谁在说话」:一条 issue 的最后评论者与时间。
235
+ *
236
+ * 为什么要它:会话被叫醒后第一件事就是判断「是不是已经有人处理了」。
237
+ * 只给 issue 作者和更新时间不够 —— 更新时间可能是我自己打的标签引起的。
238
+ *
239
+ * 代价:每条 issue 一次 `GET /issues/{n}/comments`,所以只在**评论数 > 0** 且**批次前几条**里取,
240
+ * 失败就静默省略(宁可少一行,不要拖慢唤醒)。
241
+ * 出处:https://docs.github.com/en/rest/issues/comments#list-issue-comments
242
+ */
243
+ export function commentSummaryLine(lastComment, viewer) {
244
+ if (!lastComment || typeof lastComment !== 'object') return ''
245
+ const login = lastComment.login ? String(lastComment.login) : ''
246
+ // 最后一条是"我们自己"发的,意义完全不同:那不是"有人在处理",而是上一轮留下的痕迹。
247
+ // 依据:GET /user 返回当前 token 对应的账号(本机实测:`gh api user --jq .login` → 我们的账号名)。
248
+ // 出处:https://docs.github.com/en/rest/users/users#get-the-authenticated-user
249
+ const isSelf = Boolean(login && viewer && login.toLowerCase() === String(viewer).toLowerCase())
250
+ const who = login ? (isSelf ? '我(上一轮留的)' : '@' + login) : ''
251
+ const when = lastComment.at ? String(lastComment.at) : ''
252
+ if (!who && !when) return ''
253
+ return [who, when].filter(Boolean).join(' ')
254
+ }
255
+
256
+ /**
257
+ * 批量取"最后一条评论"的 GraphQL 查询:一次请求拿 N 条,别一条一个 REST 调用。
258
+ *
259
+ * 依据:GraphQL 支持别名(alias)在同一请求里查多个 issue,且计费按点数而非请求数;
260
+ * 但我们只用它的"批量"能力,复杂度极低(一个 repository + N 个 issue 别名)。
261
+ * 出处:https://docs.github.com/en/graphql
262
+ */
263
+ export function buildCommentBatchQuery(count) {
264
+ const n = Math.max(0, Math.min(10, Number(count) || 0))
265
+ const parts = []
266
+ for (let i = 0; i < n; i += 1) {
267
+ parts.push(' i' + i + ': issue(number: $n' + i + ') { number'
268
+ + ' comments(last: 1) { nodes { author { login } createdAt } }'
269
+ + ' timelineItems(last: 5, itemTypes: [CROSS_REFERENCED_EVENT]) { nodes { ... on CrossReferencedEvent {'
270
+ + ' source { __typename ... on PullRequest { number state url isDraft reviewDecision mergeable statusCheckRollup { state } } } } } }')
271
+ }
272
+ const vars = Array.from({ length: n }, (_, i) => '$n' + i + ': Int!').join(', ')
273
+ return 'query($owner: String!, $name: String!' + (n > 0 ? ', ' + vars : '') + ') {'
274
+ + ' repository(owner: $owner, name: $name) {'
275
+ + String.fromCharCode(10) + parts.join(String.fromCharCode(10)) + String.fromCharCode(10)
276
+ + '} }'
277
+ }
278
+
279
+ /**
280
+ * 解析批量结果:把 {i0: {number, comments:{nodes:[…]}}} 摊平成 {number: {login, at}}。
281
+ * 单个 issue 不存在时 GraphQL 会在 `errors` 里报 NOT_FOUND,但同请求里别的 issue 仍然有值 ——
282
+ * 所以我们**只看 data,不因为 errors 整体放弃**。
283
+ */
284
+ export function parseCommentBatch(payload) {
285
+ const out = {}
286
+ const repo = payload && payload.data && payload.data.repository
287
+ if (!repo || typeof repo !== 'object') return out
288
+ for (const value of Object.values(repo)) {
289
+ if (!value || typeof value !== 'object') continue
290
+ const nodes = value.comments && value.comments.nodes
291
+ const node = Array.isArray(nodes) && nodes.length > 0 ? nodes[nodes.length - 1] : null
292
+ if (!node) continue
293
+ const login = node.author && node.author.login ? String(node.author.login) : ''
294
+ const linked = pickLinkedPullRequests(value.timelineItems && value.timelineItems.nodes)
295
+ if (!login && linked.length === 0) continue
296
+ out[String(value.number)] = {
297
+ login,
298
+ at: node.createdAt ? String(node.createdAt) : '',
299
+ linked,
300
+ }
301
+ }
302
+ return out
303
+ }
304
+
305
+ /**
306
+ * 关闭原因 / 反复重开的提示。
307
+ *
308
+ * 依据:issue 对象有 `state_reason`(本机实测 `cli/cli` 上大量 `not_planned`;
309
+ * 重新打开时会变成 `reopened`)。出处:https://docs.github.com/en/rest/issues/issues
310
+ *
311
+ * 为什么要它:主理鱼看到 closed 就跳过,但"被标成 not_planned 后又被重开"的条目
312
+ * 恰恰是最需要人看一眼的 —— 说明之前判断"不做"是错的,或者有人在坚持。
313
+ */
314
+ export function stateReasonNote(item) {
315
+ if (!item || typeof item !== 'object') return ''
316
+ const reason = item.state_reason || item.stateReason
317
+ if (!reason) return ''
318
+ if (reason === 'reopened') return '这条被重新打开过(之前关过,判"不做"可能不对)'
319
+ if (item.state === 'closed' && reason === 'not_planned') return '关闭原因:不做(not planned)'
320
+ if (item.state === 'closed' && reason === 'completed') return '关闭原因:已完成'
321
+ return ''
322
+ }
323
+
324
+ /**
325
+ * 有没有人认领(assignee)。
326
+ *
327
+ * 依据:issue 对象的 `assignees` 数组;GitHub 的过滤语法里也有现成的 `assignee:` 限定词
328
+ * (我们自己的过滤器 `onlyAssigned` 就基于它)。
329
+ * 出处:https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/filtering-and-searching-issues-and-pull-requests
330
+ *
331
+ * 注意:**"无人认领更紧急"是产品判断,不是 GitHub 的规则**(本轮没找到官方依据),
332
+ * 所以只在消息里如实标注,加权默认关闭。
333
+ */
334
+ export function assignmentNote(item) {
335
+ if (!item || typeof item !== 'object') return ''
336
+ const list = Array.isArray(item.assignees) ? item.assignees.filter(Boolean) : []
337
+ if (list.length > 0) return ''
338
+ return '未认领'
339
+ }
340
+
341
+ /**
342
+ * 分诊信号表:单一口径,回答「我们到底看哪些信号、哪些是事实、哪些是判断、默认开不开」。
343
+ *
344
+ * 为什么要这张表:信号散落在代码里,客户看不见我们的取舍;写进这里之后
345
+ * `/state` 会回传、面板能直接展示,改权重也不用改两处。
346
+ *
347
+ * `kind`:fact = GitHub 给的事实;judgment = 我们的产品判断(无官方依据)。
348
+ */
349
+ export const TRIAGE_SIGNALS = [
350
+ { key: 'reopened', label: '被重新打开', kind: 'fact', weight: 100, default: true, why: 'state_reason=reopened,说明之前判"不做"被推翻' },
351
+ { key: 'comments', label: '有人评论', kind: 'fact', weight: 10, default: true, why: '在等回应' },
352
+ { key: 'labels', label: '带标签', kind: 'fact', weight: 5, default: true, why: '命中过某个分类' },
353
+ { key: 'unassigned', label: '无人认领', kind: 'judgment', weight: 3, default: false, why: '团队经验:没人认领更该看 —— 无官方依据,故默认关' },
354
+ { key: 'stale', label: '长期没动静', kind: 'fact', weight: 2, default: false, why: 'open 且超过 30 天没更新(stale bot 默认 60 天)—— 默认只展示,开启后 +2 分' },
355
+ ]
356
+
357
+ /**
358
+ * 「躺了多久」:open 且长期没更新 —— stale bot 的世界标准是 60 天(actions/stale 默认值)。
359
+ *
360
+ * 依据:actions/stale 的 `days-before-stale` 默认 **60** 天
361
+ * (https://github.com/actions/stale#readme),社区普遍用 30/60 两档。
362
+ * 我们只**展示**,默认不参与排序(和 unassigned 一样:先给事实,判断交给用户)。
363
+ */
364
+ export function stalenessNote(item, options = {}) {
365
+ if (!item || typeof item !== 'object') return ''
366
+ const state = String(item.state || '')
367
+ if (state && state !== 'open') return ''
368
+ const stamp = item.updated_at || item.updatedAt
369
+ const at = Date.parse(stamp || '')
370
+ if (!Number.isFinite(at)) return ''
371
+ // 括号别省:Number(now) || (Date.now() - at) 会把 now 自己当成毫秒差(写错过一次)
372
+ const days = Math.floor(((Number(options.now) || Date.now()) - at) / (24 * 3600 * 1000))
373
+ if (!Number.isFinite(days) || days < 0) return ''
374
+ const threshold = Number(options.thresholdDays) || 30
375
+ if (days < threshold) return ''
376
+ return '躺了 ' + days + ' 天'
377
+ }
378
+
379
+ /**
380
+ * 从 cross-reference 时间线里挑出关联的 PR。
381
+ *
382
+ * 依据:`timelineItems(itemTypes: [CROSS_REFERENCED_EVENT])` 会给出引用过这条 issue 的 PR;
383
+ * 注意 `source` 是 union,**必须带 `__typename`** 才能选到 PullRequest 的字段
384
+ * (直接选 `source { number }` 会报 "Selections can't be made directly on unions")。
385
+ * 出处:https://docs.github.com/en/graphql/reference/objects#crossreferencedevent
386
+ */
387
+ export function pickLinkedPullRequests(nodes) {
388
+ const list = Array.isArray(nodes) ? nodes : []
389
+ const seen = new Set()
390
+ const out = []
391
+ for (const node of list) {
392
+ const source = node && node.source
393
+ if (!source || source.__typename !== 'PullRequest' || !source.number) continue
394
+ if (seen.has(source.number)) continue
395
+ seen.add(source.number)
396
+ out.push({
397
+ number: source.number,
398
+ state: String(source.state || ''),
399
+ url: String(source.url || ''),
400
+ draft: source.isDraft === true,
401
+ review: String(source.reviewDecision || ''),
402
+ mergeable: String(source.mergeable || ''),
403
+ ci: String((source.statusCheckRollup && source.statusCheckRollup.state) || ''),
404
+ })
405
+ }
406
+ // open 的排前面(说明真在做),merged 其次,closed 最后
407
+ const rank = { OPEN: 0, MERGED: 1, CLOSED: 2 }
408
+ return out.sort((a, b) => (rank[a.state] ?? 9) - (rank[b.state] ?? 9))
409
+ }
410
+
411
+ /** 「已经有 PR 在做了」——避免会话重复干活。 */
412
+ export function linkedPrNote(linked) {
413
+ const list = Array.isArray(linked) ? linked.filter((item) => item && item.number) : []
414
+ if (list.length === 0) return ''
415
+ const first = list[0]
416
+ const stateText = first.state === 'OPEN' ? '进行中' : first.state === 'MERGED' ? '已合并' : first.state === 'CLOSED' ? '已关闭' : String(first.state || '')
417
+ // 草稿 PR 说明"还没准备好":别让会话以为对方在推进
418
+ const draftText = first.state === 'OPEN' && first.draft === true ? '·草稿' : ''
419
+ // 「卡在哪」比「有 PR」更有用:有冲突 / 等 review 是会话接管前最该知道的
420
+ const blocked = first.state === 'OPEN'
421
+ ? (first.mergeable === 'CONFLICTING' ? '·有冲突' : '')
422
+ + (first.review === 'REVIEW_REQUIRED' ? '·等 review' : '')
423
+ + (first.review === 'CHANGES_REQUESTED' ? '·被要求修改' : '')
424
+ // CI 状态同样是"该不该接管"的依据:失败可能是可修的,运行中等它出结果
425
+ + (first.ci === 'FAILURE' || first.ci === 'ERROR' ? '·CI 失败' : '')
426
+ + (first.ci === 'PENDING' || first.ci === 'EXPECTED' ? '·CI 运行中' : '')
427
+ : ''
428
+ return '已有 PR #' + first.number + (stateText || draftText || blocked ? '(' + stateText + draftText + blocked + ')' : '')
429
+ + (list.length > 1 ? ' 等 ' + list.length + ' 个' : '')
430
+ }
package/lib/index.js CHANGED
@@ -31,7 +31,7 @@ import {
31
31
 
32
32
  export const name = 'dsh-session-superagent'
33
33
  /** 服务端版本:随 package.json 同步(meta 测试守着)。客户端据此挑「最新的那个实例」。 */
34
- export const SERVER_VERSION = '0.8.94'
34
+ export const SERVER_VERSION = '0.8.96'
35
35
  export const inject = ['tools', 'agents', 'webServer']
36
36
 
37
37
  /** 仅供测试:读写状态文件(生产代码不要用)。 */
package/lib/watch.js CHANGED
@@ -459,425 +459,28 @@ export function mergeFilters(base, patch) {
459
459
  *
460
460
  * @returns {{ kind: string, short: string, hint: string }}
461
461
  */
462
- export function classifyGhError(detail) {
463
- const text = String(detail || '')
464
- // 长 URL 压缩,避免一整条 API 地址占满面板
465
- const short = text
466
- .replace(/Get "https?:\/\/[^"]{16,}"/g, 'GitHub API 请求')
467
- .replace(/Post "https?:\/\/[^"]{16,}"/g, 'GitHub API 请求')
468
- .slice(0, 200)
469
-
470
- if (/HTTP 401|Bad credentials|requires authentication/i.test(text)) {
471
- return { kind: 'auth', short, hint: '(gh 登录失效:跑 gh auth login,或在面板填 token)' }
472
- }
473
- if (/HTTP 403|rate limit|API rate limit exceeded/i.test(text)) {
474
- return { kind: 'ratelimit', short, hint: '(被 GitHub 限流:等几分钟,或换成带 token 的凭证)' }
475
- }
476
- if (/ENOENT|not found.*gh|gh: command not found/i.test(text)) {
477
- return { kind: 'nogh', short, hint: '(找不到 gh 命令:确认已安装且在 PATH)' }
478
- }
479
- if (/HTTP 404|HTTP 403|Not Found[\s\S]*404|Not Found/.test(text)) {
480
- return { kind: 'notfound', short, hint: '(仓库不存在或没权限:检查 owner/name)' }
481
- }
482
- if (/EOF|i\/o timeout|connection reset|dial tcp|TLS handshake|no such host|proxyconnect|timeout/i.test(text)) {
483
- return { kind: 'network', short, hint: '(网络抖动:这一轮没连上 GitHub,已按退避自动重试,不需要手动处理)' }
484
- }
485
- return { kind: 'other', short, hint: '' }
486
- }
487
-
488
- /**
489
- * 解析 `gh api --include` 的输出:状态行 / 响应头 / 空行 / 正文。
490
- *
491
- * 为什么用它而不是直接 `gh api`:GitHub 官方文档明确说
492
- * 「Make authenticated conditional requests, so that unchanged data does not count against
493
- * your primary rate limit」—— 带上 If-None-Match 后,没变化时拿 304,
494
- * 304 **不计入**速率限制。对一个每 N 秒轮询的工具,这是最直接的省额度手段。
495
- *
496
- * 出处:https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api
497
- */
498
- export function parseGhInclude(stdout) {
499
- const text = String(stdout || '')
500
- const LF = String.fromCharCode(10)
501
- const blank = LF + LF
502
- const idx = text.indexOf(blank)
503
- const head = idx < 0 ? text : text.slice(0, idx)
504
- const body = idx < 0 ? text.trim() : text.slice(idx + blank.length)
505
- const lines = head.split(LF)
506
- const statusParts = String(lines[0] || '').split(' ')
507
- const status = Number(statusParts[1]) || 0
508
- const header = (name) => {
509
- const needle = name.toLowerCase() + ':'
510
- for (const line of lines) {
511
- if (line.toLowerCase().startsWith(needle)) return line.slice(needle.length).trim()
512
- }
513
- return null
514
- }
515
- const numeric = (name) => {
516
- const raw = header(name)
517
- const value = Number(raw)
518
- return Number.isFinite(value) ? value : null
519
- }
520
- const resetSeconds = numeric('x-ratelimit-reset')
521
- // Stage 2 限流(secondary rate limit)用 Retry-After 告诉你等多久;primary 用 x-ratelimit-reset
522
- const retryAfterRaw = header('retry-after')
523
- return {
524
- status,
525
- etag: header('etag'),
526
- remaining: numeric('x-ratelimit-remaining'),
527
- limit: numeric('x-ratelimit-limit'),
528
- resetAt: resetSeconds ? new Date(resetSeconds * 1000).toISOString() : null,
529
- retryAfter: Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : null,
530
- body,
531
- }
532
- }
533
-
534
- /**
535
- * 额度自适应:GitHub 主额度快用完时,不要继续按固定间隔撞墙。
536
- *
537
- * 依据:GitHub 每次响应都带 `X-RateLimit-Remaining` / `X-RateLimit-Reset`
538
- * (实测 `gh api --include` 的输出里就是这几个头)。
539
- * 剩余低于阈值时,把下一次轮询推到额度重置时间(最多等 1 小时),而不是继续发请求。
540
- */
541
- /**
542
- * GitHub 的「第二阶段限流」会在 403/429 响应里带 `Retry-After: <秒>`。
543
- * 按它等,比我们瞎猜一个退避时间准确得多。
544
- * 依据:GitHub 暴露头里明确包含 `Retry-After`(实测 `gh api --include` 的
545
- * Access-Control-Expose-Headers 一行里就能看到),且官方限流文档要求遵守它。
546
- */
547
- export function retryAfterMs(retryAfter, { capMs = 3600 * 1000 } = {}) {
548
- const seconds = Number(retryAfter)
549
- if (!Number.isFinite(seconds) || seconds <= 0) return 0
550
- return Math.min(capMs, Math.round(seconds * 1000))
551
- }
552
-
553
- export function throttleDelayMs({ remaining, resetAt, now = Date.now(), threshold = 500, capMs = 3600 * 1000 } = {}) {
554
- if (remaining === null || remaining === undefined) return 0
555
- if (Number(remaining) >= Number(threshold)) return 0
556
- const reset = Date.parse(resetAt || '')
557
- if (!Number.isFinite(reset)) return Math.min(capMs, 5 * 60 * 1000)
558
- const wait = reset - now + 1000
559
- if (wait <= 0) return 0
560
- return Math.min(capMs, wait)
561
- }
562
-
563
- /**
564
- * 去同步抖动:给每个 watcher 一个**确定性的**起始偏移,避免 N 条守在同一条时间线上一起发车。
565
- *
566
- * 为什么不用随机数:随机数每次启动都不同,调试时对不上;用 id 的哈希则「同一条守永远同一个偏移」,
567
- * 既错峰又可复现。范围固定在 [0, windowMs)。
568
- *
569
- * 依据:AWS Architecture Blog 的《Exponential Backoff And Jitter》——同步发车会让
570
- * 下游在整点承压,加入抖动后峰值被摊平。(https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)
571
- */
572
- export function jitterMs(key, windowMs) {
573
- const width = Math.max(0, Math.floor(Number(windowMs) || 0))
574
- if (width === 0) return 0
575
- const text = String(key || '')
576
- let hash = 0
577
- for (let i = 0; i < text.length; i += 1) hash = (hash * 31 + text.charCodeAt(i)) % 1000003
578
- return hash % width
579
- }
580
-
581
- /**
582
- * 把「为什么没叫醒」做成可统计的分布。
583
- *
584
- * 背景:我们每轮只留最近 5 条过滤记录(`filteredLog`),客户想知道
585
- * 「为什么我加的标签一条都没被叫醒」时看不出全貌。这里按原因累计次数,
586
- * 面板上就能直接读「不在标签白名单: ai-fix × 37」这种结论。
587
- *
588
- * 依据:GitHub 的 issue 过滤语义本身就是「限定词 + 集合运算」
589
- * (label:/assignee:/state:…,见 GitHub 文档「Filtering and searching issues」),
590
- * 所以「被哪条限定词刷掉」比「被刷掉」更值得告诉用户。
591
- */
592
- export function countReasons(counts, reason, { maxKinds = 12 } = {}) {
593
- const map = { ...(counts || {}) }
594
- if (!reason) return map
595
- const key = String(reason).slice(0, 60)
596
- map[key] = (Number(map[key]) || 0) + 1
597
- const entries = Object.entries(map).sort((a, b) => b[1] - a[1]).slice(0, maxKinds)
598
- return Object.fromEntries(entries)
599
- }
600
-
601
- /**
602
- * 仓库权限提示:只读仓库上我们**没法**回写结果(评论、打标签都会 403)。
603
- *
604
- * 依据:`GET /repos/{owner}/{repo}` 返回 `permissions.push`,官方文档里这个对象就是
605
- * "你有没有写权限"的权威来源。事先知道,比跑到一半才发现 403 好。
606
- * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
607
- */
608
- export function accessNote(repoAccess) {
609
- if (!repoAccess || typeof repoAccess !== 'object') return ''
610
- if (repoAccess.push === true) return ''
611
- if (repoAccess.push === false) {
612
- return '你对 ' + String(repoAccess.repo || '这个仓库') + ' 只有读权限:能看、能被叫醒,但没法回写评论或打标签 —— '
613
- + '要么换有写权限的 token,要么把结论写在本地/PR 描述里。'
614
- }
615
- return ''
616
- }
617
-
618
- /**
619
- * 仓库结构提示:主理鱼只认 issue/PR,所以「这个仓库没有 issue」要提前说。
620
- *
621
- * 依据:`GET /repos/{owner}/{repo}` 返回 `has_issues` / `fork` / `parent.full_name`
622
- * (本机实测这三个字段都在:`{fork, has_issues, parent, private}`)。
623
- * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
624
- */
625
- export function repoStructureNote(repoAccess) {
626
- if (!repoAccess || typeof repoAccess !== 'object') return ''
627
- const repo = String(repoAccess.repo || '这个仓库')
628
- if (repoAccess.archived === true) {
629
- return repo + ' 已归档:GitHub 上归档仓库是只读的,评论和打标签都会失败 —— 守它只能看、不能回写。'
630
- }
631
- if (repoAccess.disabled === true) {
632
- return repo + ' 已被禁用:这个仓库当前不可用,主理鱼不会拿到任何条目。'
633
- }
634
- if (repoAccess.hasIssues === false) {
635
- return repo + ' 关闭了 Issues —— 主理鱼只认 issue / PR,这里不会有任何条目可接。'
636
- }
637
- if (repoAccess.fork === true && repoAccess.parent && repoAccess.hasIssues !== true) {
638
- return repo + ' 是 ' + String(repoAccess.parent) + ' 的 fork。fork 默认不带 Issues,'
639
- + 'issue 大多落在上游 —— 确认你要守的是哪一个(守上游就把仓库填成 ' + String(repoAccess.parent) + ')。'
640
- }
641
- return ''
642
- }
643
-
644
- /**
645
- * 仓库能力徽章:把「这条守到底能不能干活」压缩成几个短标签。
646
- *
647
- * 依据:`GET /repos` 的 `archived` / `disabled` / `private` / `fork` / `has_issues` / `permissions.push`
648
- * 就是全部需要的判断依据(本机实测 atom/atom 的 `archived` 为 true)。
649
- * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
650
- */
651
- export function repoBadges(repoAccess) {
652
- if (!repoAccess || typeof repoAccess !== 'object') return []
653
- const badges = []
654
- // 归档仓库在 GitHub 上是完全只读的:评论、打标签都会失败 —— 比"没有写权限"更彻底
655
- if (repoAccess.archived === true) badges.push({ text: '已归档', tone: 'warning' })
656
- if (repoAccess.disabled === true) badges.push({ text: '已禁用', tone: 'danger' })
657
- if (repoAccess.hasIssues === false) badges.push({ text: '无 Issues', tone: 'warning' })
658
- if (repoAccess.fork === true && repoAccess.parent && repoAccess.hasIssues !== true) {
659
- badges.push({ text: 'fork · 上游 ' + String(repoAccess.parent), tone: 'outline' })
660
- }
661
- if (repoAccess.push === false) badges.push({ text: '只读', tone: 'warning' })
662
- if (repoAccess.private === true) badges.push({ text: '私有', tone: 'outline' })
663
- return badges
664
- }
665
-
666
- /**
667
- * 仓库名纠错:404 之后从搜索结果里挑一个最像的,别让客户自己猜。
668
- *
669
- * 依据:`GET /search/repositories?q=<name>+in:name` 能按仓库名检索;
670
- * **但它走独立的 search 池**(本机实测 response header:`x-ratelimit-limit: 30`,
671
- * 即 30 次/分钟,远小于 core 的 5000)—— 所以只能在 404 之后偶尔调用,绝不能每轮轮询都用。
672
- * 出处:https://docs.github.com/en/rest/search/search#search-repositories
673
- */
674
- export function pickSuggestion(query, candidates) {
675
- const wanted = String(query || '').trim().toLowerCase()
676
- if (!wanted) return null
677
- const list = Array.isArray(candidates) ? candidates.filter((name) => typeof name === 'string') : []
678
- const exactName = wanted.includes('/') ? wanted.split('/')[1] : wanted
679
- // 优先级:仓库名完全相同 > 名字里包含 > 仅 owner 相同(最后这种基本没价值,直接丢)
680
- const sameName = list.find((name) => name.toLowerCase().endsWith('/' + exactName))
681
- if (sameName) return sameName
682
- const contains = list.find((name) => name.toLowerCase().includes(exactName) && exactName.length >= 4)
683
- return contains || null
684
- }
685
-
686
- /**
687
- * 「最后是谁在说话」:一条 issue 的最后评论者与时间。
688
- *
689
- * 为什么要它:会话被叫醒后第一件事就是判断「是不是已经有人处理了」。
690
- * 只给 issue 作者和更新时间不够 —— 更新时间可能是我自己打的标签引起的。
691
- *
692
- * 代价:每条 issue 一次 `GET /issues/{n}/comments`,所以只在**评论数 > 0** 且**批次前几条**里取,
693
- * 失败就静默省略(宁可少一行,不要拖慢唤醒)。
694
- * 出处:https://docs.github.com/en/rest/issues/comments#list-issue-comments
695
- */
696
- export function commentSummaryLine(lastComment, viewer) {
697
- if (!lastComment || typeof lastComment !== 'object') return ''
698
- const login = lastComment.login ? String(lastComment.login) : ''
699
- // 最后一条是"我们自己"发的,意义完全不同:那不是"有人在处理",而是上一轮留下的痕迹。
700
- // 依据:GET /user 返回当前 token 对应的账号(本机实测:`gh api user --jq .login` → 我们的账号名)。
701
- // 出处:https://docs.github.com/en/rest/users/users#get-the-authenticated-user
702
- const isSelf = Boolean(login && viewer && login.toLowerCase() === String(viewer).toLowerCase())
703
- const who = login ? (isSelf ? '我(上一轮留的)' : '@' + login) : ''
704
- const when = lastComment.at ? String(lastComment.at) : ''
705
- if (!who && !when) return ''
706
- return [who, when].filter(Boolean).join(' ')
707
- }
708
-
709
- /**
710
- * 批量取"最后一条评论"的 GraphQL 查询:一次请求拿 N 条,别一条一个 REST 调用。
711
- *
712
- * 依据:GraphQL 支持别名(alias)在同一请求里查多个 issue,且计费按点数而非请求数;
713
- * 但我们只用它的"批量"能力,复杂度极低(一个 repository + N 个 issue 别名)。
714
- * 出处:https://docs.github.com/en/graphql
715
- */
716
- export function buildCommentBatchQuery(count) {
717
- const n = Math.max(0, Math.min(10, Number(count) || 0))
718
- const parts = []
719
- for (let i = 0; i < n; i += 1) {
720
- parts.push(' i' + i + ': issue(number: $n' + i + ') { number'
721
- + ' comments(last: 1) { nodes { author { login } createdAt } }'
722
- + ' timelineItems(last: 5, itemTypes: [CROSS_REFERENCED_EVENT]) { nodes { ... on CrossReferencedEvent {'
723
- + ' source { __typename ... on PullRequest { number state url isDraft reviewDecision mergeable statusCheckRollup { state } } } } } }')
724
- }
725
- const vars = Array.from({ length: n }, (_, i) => '$n' + i + ': Int!').join(', ')
726
- return 'query($owner: String!, $name: String!' + (n > 0 ? ', ' + vars : '') + ') {'
727
- + ' repository(owner: $owner, name: $name) {'
728
- + String.fromCharCode(10) + parts.join(String.fromCharCode(10)) + String.fromCharCode(10)
729
- + '} }'
730
- }
731
-
732
- /**
733
- * 解析批量结果:把 {i0: {number, comments:{nodes:[…]}}} 摊平成 {number: {login, at}}。
734
- * 单个 issue 不存在时 GraphQL 会在 `errors` 里报 NOT_FOUND,但同请求里别的 issue 仍然有值 ——
735
- * 所以我们**只看 data,不因为 errors 整体放弃**。
736
- */
737
- export function parseCommentBatch(payload) {
738
- const out = {}
739
- const repo = payload && payload.data && payload.data.repository
740
- if (!repo || typeof repo !== 'object') return out
741
- for (const value of Object.values(repo)) {
742
- if (!value || typeof value !== 'object') continue
743
- const nodes = value.comments && value.comments.nodes
744
- const node = Array.isArray(nodes) && nodes.length > 0 ? nodes[nodes.length - 1] : null
745
- if (!node) continue
746
- const login = node.author && node.author.login ? String(node.author.login) : ''
747
- const linked = pickLinkedPullRequests(value.timelineItems && value.timelineItems.nodes)
748
- if (!login && linked.length === 0) continue
749
- out[String(value.number)] = {
750
- login,
751
- at: node.createdAt ? String(node.createdAt) : '',
752
- linked,
753
- }
754
- }
755
- return out
756
- }
757
-
758
- /**
759
- * 关闭原因 / 反复重开的提示。
760
- *
761
- * 依据:issue 对象有 `state_reason`(本机实测 `cli/cli` 上大量 `not_planned`;
762
- * 重新打开时会变成 `reopened`)。出处:https://docs.github.com/en/rest/issues/issues
763
- *
764
- * 为什么要它:主理鱼看到 closed 就跳过,但"被标成 not_planned 后又被重开"的条目
765
- * 恰恰是最需要人看一眼的 —— 说明之前判断"不做"是错的,或者有人在坚持。
766
- */
767
- export function stateReasonNote(item) {
768
- if (!item || typeof item !== 'object') return ''
769
- const reason = item.state_reason || item.stateReason
770
- if (!reason) return ''
771
- if (reason === 'reopened') return '这条被重新打开过(之前关过,判"不做"可能不对)'
772
- if (item.state === 'closed' && reason === 'not_planned') return '关闭原因:不做(not planned)'
773
- if (item.state === 'closed' && reason === 'completed') return '关闭原因:已完成'
774
- return ''
775
- }
776
-
777
- /**
778
- * 有没有人认领(assignee)。
779
- *
780
- * 依据:issue 对象的 `assignees` 数组;GitHub 的过滤语法里也有现成的 `assignee:` 限定词
781
- * (我们自己的过滤器 `onlyAssigned` 就基于它)。
782
- * 出处:https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/filtering-and-searching-issues-and-pull-requests
783
- *
784
- * 注意:**"无人认领更紧急"是产品判断,不是 GitHub 的规则**(本轮没找到官方依据),
785
- * 所以只在消息里如实标注,加权默认关闭。
786
- */
787
- export function assignmentNote(item) {
788
- if (!item || typeof item !== 'object') return ''
789
- const list = Array.isArray(item.assignees) ? item.assignees.filter(Boolean) : []
790
- if (list.length > 0) return ''
791
- return '未认领'
792
- }
793
-
794
- /**
795
- * 分诊信号表:单一口径,回答「我们到底看哪些信号、哪些是事实、哪些是判断、默认开不开」。
796
- *
797
- * 为什么要这张表:信号散落在代码里,客户看不见我们的取舍;写进这里之后
798
- * `/state` 会回传、面板能直接展示,改权重也不用改两处。
799
- *
800
- * `kind`:fact = GitHub 给的事实;judgment = 我们的产品判断(无官方依据)。
801
- */
802
- export const TRIAGE_SIGNALS = [
803
- { key: 'reopened', label: '被重新打开', kind: 'fact', weight: 100, default: true, why: 'state_reason=reopened,说明之前判"不做"被推翻' },
804
- { key: 'comments', label: '有人评论', kind: 'fact', weight: 10, default: true, why: '在等回应' },
805
- { key: 'labels', label: '带标签', kind: 'fact', weight: 5, default: true, why: '命中过某个分类' },
806
- { key: 'unassigned', label: '无人认领', kind: 'judgment', weight: 3, default: false, why: '团队经验:没人认领更该看 —— 无官方依据,故默认关' },
807
- { key: 'stale', label: '长期没动静', kind: 'fact', weight: 2, default: false, why: 'open 且超过 30 天没更新(stale bot 默认 60 天)—— 默认只展示,开启后 +2 分' },
808
- ]
809
-
810
- /**
811
- * 「躺了多久」:open 且长期没更新 —— stale bot 的世界标准是 60 天(actions/stale 默认值)。
812
- *
813
- * 依据:actions/stale 的 `days-before-stale` 默认 **60** 天
814
- * (https://github.com/actions/stale#readme),社区普遍用 30/60 两档。
815
- * 我们只**展示**,默认不参与排序(和 unassigned 一样:先给事实,判断交给用户)。
816
- */
817
- export function stalenessNote(item, options = {}) {
818
- if (!item || typeof item !== 'object') return ''
819
- const state = String(item.state || '')
820
- if (state && state !== 'open') return ''
821
- const stamp = item.updated_at || item.updatedAt
822
- const at = Date.parse(stamp || '')
823
- if (!Number.isFinite(at)) return ''
824
- // 括号别省:Number(now) || (Date.now() - at) 会把 now 自己当成毫秒差(写错过一次)
825
- const days = Math.floor(((Number(options.now) || Date.now()) - at) / (24 * 3600 * 1000))
826
- if (!Number.isFinite(days) || days < 0) return ''
827
- const threshold = Number(options.thresholdDays) || 30
828
- if (days < threshold) return ''
829
- return '躺了 ' + days + ' 天'
830
- }
831
-
832
- /**
833
- * 从 cross-reference 时间线里挑出关联的 PR。
834
- *
835
- * 依据:`timelineItems(itemTypes: [CROSS_REFERENCED_EVENT])` 会给出引用过这条 issue 的 PR;
836
- * 注意 `source` 是 union,**必须带 `__typename`** 才能选到 PullRequest 的字段
837
- * (直接选 `source { number }` 会报 "Selections can't be made directly on unions")。
838
- * 出处:https://docs.github.com/en/graphql/reference/objects#crossreferencedevent
839
- */
840
- export function pickLinkedPullRequests(nodes) {
841
- const list = Array.isArray(nodes) ? nodes : []
842
- const seen = new Set()
843
- const out = []
844
- for (const node of list) {
845
- const source = node && node.source
846
- if (!source || source.__typename !== 'PullRequest' || !source.number) continue
847
- if (seen.has(source.number)) continue
848
- seen.add(source.number)
849
- out.push({
850
- number: source.number,
851
- state: String(source.state || ''),
852
- url: String(source.url || ''),
853
- draft: source.isDraft === true,
854
- review: String(source.reviewDecision || ''),
855
- mergeable: String(source.mergeable || ''),
856
- ci: String((source.statusCheckRollup && source.statusCheckRollup.state) || ''),
857
- })
858
- }
859
- // open 的排前面(说明真在做),merged 其次,closed 最后
860
- const rank = { OPEN: 0, MERGED: 1, CLOSED: 2 }
861
- return out.sort((a, b) => (rank[a.state] ?? 9) - (rank[b.state] ?? 9))
862
- }
863
-
864
- /** 「已经有 PR 在做了」——避免会话重复干活。 */
865
- export function linkedPrNote(linked) {
866
- const list = Array.isArray(linked) ? linked.filter((item) => item && item.number) : []
867
- if (list.length === 0) return ''
868
- const first = list[0]
869
- const stateText = first.state === 'OPEN' ? '进行中' : first.state === 'MERGED' ? '已合并' : first.state === 'CLOSED' ? '已关闭' : String(first.state || '')
870
- // 草稿 PR 说明"还没准备好":别让会话以为对方在推进
871
- const draftText = first.state === 'OPEN' && first.draft === true ? '·草稿' : ''
872
- // 「卡在哪」比「有 PR」更有用:有冲突 / 等 review 是会话接管前最该知道的
873
- const blocked = first.state === 'OPEN'
874
- ? (first.mergeable === 'CONFLICTING' ? '·有冲突' : '')
875
- + (first.review === 'REVIEW_REQUIRED' ? '·等 review' : '')
876
- + (first.review === 'CHANGES_REQUESTED' ? '·被要求修改' : '')
877
- // CI 状态同样是"该不该接管"的依据:失败可能是可修的,运行中等它出结果
878
- + (first.ci === 'FAILURE' || first.ci === 'ERROR' ? '·CI 失败' : '')
879
- + (first.ci === 'PENDING' || first.ci === 'EXPECTED' ? '·CI 运行中' : '')
880
- : ''
881
- return '已有 PR #' + first.number + (stateText || draftText || blocked ? '(' + stateText + draftText + blocked + ')' : '')
882
- + (list.length > 1 ? ' 等 ' + list.length + ' 个' : '')
883
- }
462
+ // 拆分后:GitHub 交互层在 gh-format.js,这里转出以保持既有调用方不变
463
+ import {
464
+ assignmentNote, commentSummaryLine, linkedPrNote, stalenessNote, stateReasonNote,
465
+ } from './gh-format.js'
466
+ export {
467
+ TRIAGE_SIGNALS,
468
+ accessNote,
469
+ assignmentNote,
470
+ buildCommentBatchQuery,
471
+ classifyGhError,
472
+ commentSummaryLine,
473
+ countReasons,
474
+ jitterMs,
475
+ linkedPrNote,
476
+ parseCommentBatch,
477
+ parseGhInclude,
478
+ pickLinkedPullRequests,
479
+ pickSuggestion,
480
+ repoBadges,
481
+ repoStructureNote,
482
+ retryAfterMs,
483
+ stalenessNote,
484
+ stateReasonNote,
485
+ throttleDelayMs,
486
+ } from './gh-format.js'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-session-superagent",
3
- "version": "0.8.94",
3
+ "version": "0.8.96",
4
4
  "description": "Session-level superagent for DeepSeek Harness: watch a GitHub repository and wake a session when something needs doing. Credentials never reach the model.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",