dsh-session-superagent 0.10.12 → 2.0.1

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/docs/README.md CHANGED
@@ -7,6 +7,7 @@
7
7
  | [README](../README.md) | 第一次接触这个插件:它做什么、怎么装、界面在哪、故障排查 |
8
8
  | [SETUP](../SETUP.md) | 让 coding agent 陪操作者安装:只读探测、一次一问、计划确认、首轮唤醒验收 |
9
9
  | [01-架构](01-架构.md) | 要改服务端逻辑:分层、11 步轮询管线、状态文件与落盘规则 |
10
+ | [设计-会话级导航与运行时](设计-会话级导航与运行时.md) | 当前实验线统一契约:项目会话即 Lead、全局左栏 + 会话右栏、session scope、验收与踩坑 |
10
11
  | [design-system](design-system.md) | 要改界面:35 个设计 token、常用组件类、加页面的检查清单 |
11
12
  | [official-gui-ia](official-gui-ia.md) | 想知道「官方原版长什么样、我们砍了什么、为什么」 |
12
13
  | [awesome-submission](awesome-submission.md) | 要提交到 awesome-dsh-plugin:现成的 YAML、图标、核对结论 |
@@ -2,7 +2,7 @@
2
2
 
3
3
  所有工具都支持 `format: 'json'`,返回带 `schemaVersion` 的对象(当前 `1`)。
4
4
 
5
- **稳定性**:`稳定` = 不会无故改名或删除;`实验` = 可能变化,请容忍缺失。
5
+ **稳定性**:`稳定` = 不会无故改名或删除;`实验` = 可能变化,请容忍缺失;`可选` = 只在特定状态出现,出现时名称固定。
6
6
 
7
7
  ## watch_status
8
8
 
@@ -30,6 +30,7 @@
30
30
  |---|---|
31
31
  | `repo` | 稳定 |
32
32
  | `provider` | 稳定 |
33
+ | `executionMode` | 稳定 |
33
34
  | `sessionId` | 稳定 |
34
35
  | `enabled` | 稳定 |
35
36
  | `intervalSec` | 稳定 |
@@ -38,6 +39,7 @@
38
39
  | `activeHours` | 稳定 |
39
40
  | `labels` | 稳定 |
40
41
  | `onlyAssigned` | 稳定 |
42
+ | `onlyNewComments` | 稳定 |
41
43
  | `batchLimit` | 稳定 |
42
44
  | `maxWakesPerHour` | 稳定 |
43
45
  | `sessionMaxWakes` | 稳定 |
@@ -54,6 +56,7 @@
54
56
  | `silentWakes` | 稳定 |
55
57
  | `cursor` | 实验 |
56
58
  | `lastPoll` | 稳定 |
59
+ | `poll` | 可选 |
57
60
  | `lastWake` | 稳定 |
58
61
  | `lastError` | 稳定 |
59
62
  | `lastErrorKind` | 稳定 |
@@ -0,0 +1,91 @@
1
+ # 主理鱼模块化房间设计(实验仓)
2
+
3
+ 基线:`dsh-session-superagent@1.0.0` / main `95b5a72`。目标是在现有水位 v2 上补齐官方原型中适合单人产品的能力,不引入飞书、多人授权或团队多角色。
4
+
5
+ - **官方**:Source/Policy/Ticket/Executor/Delivery 全套组织级模型,UI 与宿主功能同插件但按 `src/client`、`src/app`、`src/core`、`src/executor` 分层。
6
+ - **我们**:保留主理鱼现有 watcher 与水位 v2,只新增单人需要的独立小房间和显式宿主端口;飞书、多人和团队角色不进入依赖图。
7
+ - **为什么更好**:保留已验证的 GitHub/Gitee、UI 和交付能力,只补真实缺口;每个房间可独立测试、独立合并,不把单用户产品变成团队编排系统。
8
+
9
+ ## 总体约束
10
+
11
+ - 每房只写自己的实现与测试;生产入口、路由、面板总装和依赖检查由 Lead 统一修改。
12
+ - 纯函数房间不得读 `process.env`、不得直接联网或写宿主状态;I/O 通过显式端口注入。
13
+ - 所有状态转换返回新对象,不修改入参;投影只读并冻结。
14
+ - 未完成、未知和明确空集合必须区分;未知计数用 `null`。
15
+ - 不复制水位 v2 的 `obs`:Ticket 管执行生命周期,`obs` 继续管外部条目交付/处置。
16
+
17
+ ## 共享 DTO
18
+
19
+ ### Ticket
20
+
21
+ ```jsonc
22
+ {
23
+ "id": "ticket:github:o/r#1",
24
+ "threadKey": "github:o/r#1",
25
+ "status": "open | assigned | waiting | ended",
26
+ "ownerSessionId": null,
27
+ "workdir": null,
28
+ "assignmentId": null,
29
+ "resumeCount": 0,
30
+ "createdAt": "ISO",
31
+ "updatedAt": "ISO",
32
+ "endedAt": null,
33
+ "endReason": null,
34
+ "history": [{ "at": "ISO", "type": "created|assigned|waiting|ended|resumed", "detail": "" }]
35
+ }
36
+ ```
37
+
38
+ 只有显式人类动作可以 resume;后续评论归属与执行生命周期是两个不同决策。
39
+
40
+ ### ThreadSubscription
41
+
42
+ ```jsonc
43
+ { "threadKey": "github:o/r#1", "ticketId": "ticket:github:o/r#1", "sessionId": "session-a", "active": true, "createdAt": "ISO" }
44
+ ```
45
+
46
+ `routeThreadEvent` 只返回 `deliver / resume / eval / ignore` 及归属,不直接唤醒或执行。订阅记录另存 `ticketStatus/endReason`,总装通过 `syncTicketState` 同步;ended 后的人类普通评论可 resume,`human-stop` 不得自动复活。
47
+
48
+ ### Assignment
49
+
50
+ ```jsonc
51
+ { "id": "assign:<ticket>:1", "ticketId": "ticket:github:o/r#1", "sessionId": "worker-session", "workdir": "absolute path", "status": "assigned|waiting|ended", "attempts": 1 }
52
+ ```
53
+
54
+ Executor 端口由宿主注入:`start / prompt / status / stop`。房间不自行创建子代理。
55
+
56
+ ### OutboxMessage
57
+
58
+ ```jsonc
59
+ { "id": "deterministic-id", "ticketId": "ticket:github:o/r#1", "channel": {}, "body": "", "status": "pending|sending|sent|failed|gone", "attempts": 0, "nextAt": "ISO", "createdAt": "ISO", "updatedAt": "ISO" }
60
+ ```
61
+
62
+ 持久化由 `commit(nextState, expectedState)` 端口完成;生产接线使用现有单写者状态事务。重复消息 ID 不得产生第二次外部发送。claim 写入带宿主编号的 `leaseUntil` 租约,只有租约过期才允许其他进程 recover;活跃租约不能被当成崩溃残留重发。GitHub/Gitee 评论带不可见 marker,worker prompt 复用稳定 messageId。
63
+
64
+ ### Admission
65
+
66
+ 确定性 gate 先执行,只有 gate 放行才调用 assessment。模型 assessment 不能推翻确定性拒绝;结果必须带 stage、disposition 与 reason。
67
+
68
+ ## 文件与写作用域
69
+
70
+ | 房间 | 文件 | 测试 | 允许的房间依赖 |
71
+ |---|---|---|---|
72
+ | Ticket 生命周期 | `lib/rooms/ticket-state.js` | `test/ticket-state.test.mjs` | 无 |
73
+ | Thread 订阅 | `lib/rooms/thread-subscription.js` | `test/thread-subscription.test.mjs` | 无 |
74
+ | 单用户 Assignment | `lib/rooms/execution-assignment.js` | `test/execution-assignment.test.mjs` | `ticket-state` |
75
+ | DSH Executor 适配 | `lib/rooms/executor-host.js` | `test/executor-host.test.mjs` | 无(仅宿主与通用 redact) |
76
+ | 持久化 Outbox | `lib/rooms/outbox.js` | `test/outbox.test.mjs` | 无 |
77
+ | 两层 Eval | `lib/rooms/admission-eval.js` | `test/admission-eval.test.mjs` | 无 |
78
+ | Source 扩展 | `lib/rooms/source-registry.js`、`lib/rooms/skill-pack.js` | `test/source-registry.test.mjs`、`test/skill-pack.test.mjs` | `data-provider` |
79
+ | Ticket/执行/草稿投影 | `lib/rooms/ticket-projection.js`、`lib/rooms/draft.js` | 同名测试 | 无 |
80
+ | 提示词与 i18n | `lib/rooms/prompt-config.js`、`lib/rooms/i18n.js` | 同名测试 | 无 |
81
+ | 运行时编排 | `lib/rooms/modular-runtime.js` | `test/modular-runtime.test.mjs` | Ticket/订阅/Assignment/Admission/投影/提示词 |
82
+ | Outbox 宿主适配 | `lib/rooms/modular-outbox-host.js` | `test/modular-outbox-host.test.mjs` | `outbox` |
83
+
84
+ ## 验收
85
+
86
+ 1. 每房独立测试覆盖正常、反向、幂等、重启/并发边界(适用时)。
87
+ 2. `scripts/check-rooms.mjs` 扩展到上述房间,禁止跨房拿内部实现。
88
+ 3. Lead 集成后才修改 `lib/index.js`、`client.js`、package exports、路由与文档。
89
+ 4. 全量测试、隔离 profile、另起实例、独立审查全部通过前不推送;验证后只推独立实验仓。
90
+ 5. **UI 模组另设人工门禁**:先本地展示官方对照截图与真实交互,用户明确确认前,即使自动测试通过也不推送。
91
+ 6. **双盲 Debug**:每批产物至少两组互不知情的独立审查,A 核心黑盒对抗、B 官方 UI 对照;不得预先提供实现思路、已知问题或其他审查结论。
package/lib/gh-format.js CHANGED
@@ -414,7 +414,7 @@ export function buildCommentBatchQuery(count) {
414
414
  const parts = []
415
415
  for (let i = 0; i < n; i += 1) {
416
416
  parts.push(' i' + i + ': issue(number: $n' + i + ') { number'
417
- + ' comments(last: 1) { nodes { author { login } createdAt } }'
417
+ + ' comments(last: 1) { totalCount nodes { author { login } createdAt databaseId } }'
418
418
  + ' timelineItems(last: 5, itemTypes: [CROSS_REFERENCED_EVENT]) { nodes { ... on CrossReferencedEvent {'
419
419
  + ' source { __typename ... on PullRequest { number state url isDraft reviewDecision mergeable statusCheckRollup { state } } } } } }')
420
420
  }
@@ -451,6 +451,52 @@ export function parseCommentBatch(payload) {
451
451
  return out
452
452
  }
453
453
 
454
+ /**
455
+ * REST 兜底取「全线程最后一条评论」的 gh 参数。
456
+ *
457
+ * 为什么不能再用 `per_page=1&sort=created&direction=desc`:GitHub 的 issue comments
458
+ * 接口**不支持** `sort` / `direction`(那是 issue 列表的参数),传了会被**静默忽略**,
459
+ * 于是 `per_page=1` 恒返回**最早**一条 —— 唤醒消息里的「最后评论」一直停在第一条,
460
+ * 会话误判成「对方没回复」后继续 ack(Issue #39 Bug 2)。
461
+ * 唯一正确的口径:拉满一页(接口上限 100)+ `--paginate` 取全线程,再用 jq 取每页最后一条。
462
+ * `--paginate` 下 `--jq` 是**逐页**执行的,stdout 每页一行;全线程最后一条在最后一行,
463
+ * 所以解析必须看最后一行(见 `parseLastComment`),否则超过 100 条时只看得到第 100 条。
464
+ *
465
+ * 出处:https://docs.github.com/en/rest/issues/comments#list-issue-comments
466
+ */
467
+ export function lastCommentArgs(repo, number) {
468
+ return [
469
+ 'api',
470
+ 'repos/' + String(repo) + '/issues/' + String(number) + '/comments?per_page=100',
471
+ '--paginate',
472
+ '--jq',
473
+ '.[-1] | {login: .user.login, at: .created_at}',
474
+ ]
475
+ }
476
+
477
+ /**
478
+ * 解析 `lastCommentArgs` 的 stdout:取**最后一条有效记录**。
479
+ *
480
+ * 跳过空行与空页标记:`--paginate` 的最后一页为空时,jq 对空数组输出 `null`,
481
+ * 它不是评论,跳过它才能拿到上一页的最后一条。
482
+ * 空 / 坏 JSON / 不是对象 / `login` 为空 → `null`(调用方少显示一行,绝不阻断唤醒)。
483
+ * 尾部是坏 JSON 时**不回退**到上一条:宁可少一行,也不展示可能已经过期的评论。
484
+ */
485
+ export function parseLastComment(stdout) {
486
+ const lines = String(stdout ?? '').split(/\r\n|\n|\r/)
487
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
488
+ const line = lines[i].trim()
489
+ if (!line || line === 'null') continue
490
+ let parsed = null
491
+ try { parsed = JSON.parse(line) } catch { return null }
492
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
493
+ const login = parsed.login ? String(parsed.login).trim() : ''
494
+ if (!login) return null
495
+ return { login, at: parsed.at ? String(parsed.at) : '' }
496
+ }
497
+ return null
498
+ }
499
+
454
500
  /**
455
501
  * 关闭原因 / 反复重开的提示。
456
502
  *
@@ -616,3 +662,158 @@ export function isOfflineMode(env = process.env) {
616
662
  const raw = String((env && env.DSH_SUPERAGENT_OFFLINE) || '').trim().toLowerCase()
617
663
  return raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on'
618
664
  }
665
+
666
+ /**
667
+ * PR 响应监控的搜索查询串:一次拿回「我们提给别人的 open PR + 最近评论」。
668
+ *
669
+ * 为什么用 GraphQL 而不是 REST `GET /search/issues`:REST 的评论 id 是另一套编号,
670
+ * 而水位必须用**能和评论一一对应**的那个数字 id;GraphQL 里就是 `databaseId`
671
+ * (`id` 是 base64 的 node id,既不能转数字也不能比大小)。
672
+ * 为什么 `comments(last: 10)` 只取最后 10 条:取全量会把一次搜索撑成几十 KB。
673
+ * **这是有代价的**:一个轮询间隔内被刷出 >10 条评论时,多出来的更早那几条永久低于
674
+ * 水位、再也不会被报(`lib/index.js` 的 `pollPrOnce` 里记了同一条限制)。正解是
675
+ * pageInfo 分页或 REST `issues/{n}/comments?since=` 增量,属跨任务改造。
676
+ * 别把这段读成「多出来的用不到」—— 它是「暂时认了」。
677
+ * 为什么 `type: ISSUE`:GraphQL 的搜索类型里 PR 属于 ISSUE,`is:pr` 再收窄到 PR。
678
+ *
679
+ * 查询串是对上游的固定契约(改一个字段名就静默查不到),测试里逐字符锁死。
680
+ */
681
+ export function buildPrSearchQuery({ base, first = 20 } = {}) {
682
+ // 仓库名直接拼进 GraphQL 字符串字面量:`"` / `\` 会把整条查询变成语法错误,
683
+ // 而 gh 只会回一句 "Expected Name"(不告诉我们是哪个字符)—— 先在本地转义。
684
+ const repo = String(base ?? '').trim().replace(/\\/g, '\\\\').replace(/"/g, '\\"')
685
+ // first 超出 1..100 会被 GitHub 直接 400(搜索一页上限 100),夹住,别让整轮轮询失败
686
+ const raw = Number(first)
687
+ const limit = Number.isFinite(raw) ? Math.max(1, Math.min(100, Math.trunc(raw))) : 20
688
+ return 'query{search(query:"repo:' + repo + ' is:pr is:open author:@me",type:ISSUE,first:' + limit + '){'
689
+ // hasNextPage:列表是否被 `first` 截断。被截断时**不能**剪掉不在窗口里的 PR 的水位 ——
690
+ // 否则那个 PR 回窗后会按 seenId=0 把旧评论全部重报(2026-11-13 外部 review 复现)。
691
+ + 'pageInfo{hasNextPage}'
692
+ + 'nodes{... on PullRequest{number title isDraft headRefName headRepository{nameWithOwner}'
693
+ // last:100 是单页上限。hasPreviousPage 为真说明这个 PR 还有更早的评论没拿到 —— 首次同步
694
+ // 时不能把水位推到 max,否则更早那些评论永久低于水位(同一条外部 review 的第 3 点)。
695
+ + ' baseRepository{nameWithOwner} comments(last:100){pageInfo{hasPreviousPage} nodes{databaseId author{login}'
696
+ + ' createdAt body}}}}}}'
697
+ }
698
+
699
+ /** GraphQL 的 `errors` 是数组;取第一条可读的 message(没有就返回空串)。 */
700
+ function graphqlErrorMessage(errors) {
701
+ const list = Array.isArray(errors) ? errors : []
702
+ for (const error of list) {
703
+ const message = error && typeof error === 'object' ? String(error.message ?? '').trim() : ''
704
+ if (message) return message
705
+ }
706
+ return ''
707
+ }
708
+
709
+ /**
710
+ * 解析 `gh api graphql` 的 stdout。
711
+ *
712
+ * 为什么要「防御性归一」而不是直接展开:这些字段全部可能**合法地**缺失 ——
713
+ * fork 被删除时 `headRepository` / `baseRepository` 是 `null`(不是异常,只是这条 PR
714
+ * 已经没法再跟),GraphQL 部分失败时 `comments` 整个字段都不在,搜索结果是 union
715
+ * (`Issue` 上内联片段不成立,节点里没有 `number`)。任何一处抛异常都会让整轮轮询失败,
716
+ * 而 PR 响应监控最怕的正是「静默不叫醒」。
717
+ *
718
+ * 返回 `{ ok: true, prs }`;失败时 `{ ok: false, error }`(error 是给人/面板看的一句话)。
719
+ */
720
+ export function parsePrSearch(stdout) {
721
+ const text = String(stdout ?? '').trim()
722
+ if (!text) {
723
+ return { ok: false, error: 'gh 没有返回内容(可能是代理拦截或未登录 —— 跑 watch_doctor 看凭证)' }
724
+ }
725
+ let payload = null
726
+ try {
727
+ payload = JSON.parse(text)
728
+ } catch {
729
+ return { ok: false, error: '返回内容不是合法 JSON:可能是代理干扰,或 gh 输出了非 JSON 的错误页' }
730
+ }
731
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
732
+ return { ok: false, error: '返回内容不是 JSON 对象' }
733
+ }
734
+ const search = payload.data && payload.data.search
735
+ if (!search || typeof search !== 'object') {
736
+ // 部分失败(仓库不可见 / 限流 / 语法错)时上游只给 errors:把原因带回去,
737
+ // 别让调用方只看到一句「没有 data」。
738
+ const why = graphqlErrorMessage(payload.errors)
739
+ return { ok: false, error: why || '返回里没有 data.search' }
740
+ }
741
+ const nodes = Array.isArray(search.nodes) ? search.nodes : []
742
+ // 列表被截断(还有下一页):调用方要用它决定「这轮能不能剪水位」
743
+ const hasNextPage = Boolean(search.pageInfo && search.pageInfo.hasNextPage === true)
744
+ const prs = []
745
+ for (const node of nodes) {
746
+ if (!node || typeof node !== 'object') continue
747
+ // union 的其它成员(Issue)上内联片段不成立,节点里没有 number —— 跳过。
748
+ // 为什么用 Number.isFinite 而不是 Number():GraphQL 的 number 是 Int,本来就是 number,
749
+ // 而 Number(null) 是 0、Number('') 也是 0 —— 会把「没有编号」的节点收成 number=0 的脏 PR。
750
+ if (!Number.isFinite(node.number)) continue
751
+ const number = node.number
752
+ prs.push({
753
+ number,
754
+ title: String(node.title ?? ''),
755
+ isDraft: node.isDraft === true,
756
+ // 分支名:唤醒消息里要显示(「PR 号/标题/分支」),Gitee 侧对应 head.ref
757
+ headRef: node.headRefName ? String(node.headRefName) : null,
758
+ // fork 被删除时是 null:输出 null,绝不抛
759
+ headRepo: node.headRepository && node.headRepository.nameWithOwner
760
+ ? String(node.headRepository.nameWithOwner)
761
+ : null,
762
+ baseRepo: node.baseRepository && node.baseRepository.nameWithOwner
763
+ ? String(node.baseRepository.nameWithOwner)
764
+ : null,
765
+ comments: normalizePrComments(node.comments),
766
+ // 这个 PR 的评论窗口是否被截断(`comments(last:100)` 还有更早的没拿到):
767
+ // 首次同步(seenId=0)遇到它时不能把水位推到 max,否则更早那些评论永久低于水位。
768
+ commentsTruncated: Boolean(
769
+ node.comments && node.comments.pageInfo && node.comments.pageInfo.hasPreviousPage === true,
770
+ ),
771
+ })
772
+ }
773
+ return { ok: true, prs, hasNextPage }
774
+ }
775
+
776
+ /**
777
+ * 评论归一:`databaseId` → `id`,`author.login` → `author`。
778
+ *
779
+ * 没有 `databaseId` 的评论 `id` 会是 `NaN`:它在 `pickNewComments`(Task 1)里
780
+ * 永远不满足 `id > 水位`,因此既不唤醒也不推进水位 —— 上游不会给这种数据,
781
+ * 这里保留原样,不静默丢掉评论本身。
782
+ */
783
+ function normalizePrComments(comments) {
784
+ const nodes = comments && Array.isArray(comments.nodes) ? comments.nodes : []
785
+ const out = []
786
+ for (const node of nodes) {
787
+ if (!node || typeof node !== 'object') continue
788
+ out.push({
789
+ // 必须是 databaseId,不是 GraphQL 的 id(base64 node id,没法比大小)
790
+ id: Number(node.databaseId),
791
+ author: node.author && node.author.login ? String(node.author.login) : '',
792
+ createdAt: node.createdAt ? String(node.createdAt) : '',
793
+ body: node.body === undefined || node.body === null ? '' : String(node.body),
794
+ })
795
+ }
796
+ return out
797
+ }
798
+
799
+ /**
800
+ * 把一条评论压成**单行**:`@作者 时间: 正文`。
801
+ *
802
+ * 为什么必须压成一行:面板/日志里一条评论只占一行,正文里的换行会把它拆成多行,
803
+ * 后面的行就脱离了「这一条评论」的语境,可能被当成独立指令(和 `buildPrWakeText`
804
+ * 逐行加 `>` 是同一类问题)。
805
+ * 为什么正文不截断:评论最值钱的往往是最后一句「这里还有问题」,截断等于把结论丢掉;
806
+ * 太长交给展示层用省略号处理,不在这里静默丢内容。
807
+ * 作者缺失(账号被删除时上游给 null)只留时间与正文,不输出 `@` 空壳。
808
+ */
809
+ export function formatPrCommentLine(comment) {
810
+ if (!comment || typeof comment !== 'object') return ''
811
+ // 先剥掉 `@` 再统一补一个,`@iJetLi` 与 `iJetLi` 不会变成 `@@iJetLi`
812
+ const author = String(comment.author ?? '').trim().replace(/^@+/, '')
813
+ const at = String(comment.createdAt ?? '').trim()
814
+ // 换行与连续空白一起压平:`\r\n`、`\n\n`、行首缩进都只算一个空格
815
+ const body = String(comment.body ?? '').replace(/\s+/g, ' ').trim()
816
+ const head = [author ? '@' + author : '', at].filter(Boolean).join(' ')
817
+ if (!head) return body
818
+ return body ? head + ': ' + body : head
819
+ }
package/lib/gitee.js CHANGED
@@ -44,6 +44,7 @@ export function normalizeGiteeItem(raw, { kind = 'issue' } = {}) {
44
44
  // PR 才是数字(number = 14)。**别转 Number** —— 转了就全变 0,去重和 ack 全部失效。
45
45
  number: item.number === 0 || item.number ? String(item.number) : String(item.id || ''),
46
46
  title: String(item.title || ''),
47
+ body: String(item.body || ''),
47
48
  state,
48
49
  // Gitee 用 'rejected' 表示「关闭且不修」;state_reason 只有 reopened 会被下游用来警示
49
50
  state_reason: String(item.state_reason || (String(item.state || '').toLowerCase() === 'reopened' ? 'reopened' : '')) || null,
@@ -133,29 +134,47 @@ export async function listGiteeItems({ repo, token = '', perPage = 20, since = '
133
134
  }
134
135
 
135
136
  /** 某条 issue/PR 的最后一条评论(谁、什么时候)——唤醒消息用它回答「现在是有人在等吗」。 */
136
- export async function fetchGiteeLastComment({ repo, token = '', item, selfLogin = '', fetchImpl } = {}) {
137
+ export async function fetchGiteeLastComment({ repo, token = '', item, selfLogin = '', fetchImpl, withStatus = false } = {}) {
137
138
  // 编号可能是字符串(issue 形如 IKSQJH)也可能是数字(PR 形如 14):都按原样拼进 URL
138
139
  const number = item && item.number != null ? String(item.number) : ''
139
- if (!number) return null
140
+ if (!number) return withStatus ? { ok: false, status: 0, error: 'number is required' } : null
140
141
  const kind = item && item.pull_request ? 'pulls' : 'issues'
141
142
  // 审核 M2:Gitee **不认** `sort=created&direction=desc`(那是 GitHub 的参数),
142
143
  // 以前照抄过来,`per_page=1` 拿到的是**最早**一条评论 —— 于是「最后评论」永远是第一条。
143
144
  // Gitee 只按创建时间正序返回,所以翻到最后一页取末条。
144
145
  let last = null
146
+ let truncated = false
145
147
  for (let page = 1; page <= 5; page += 1) {
146
148
  const res = await request(`/repos/${repo}/${kind}/${number}/comments?per_page=100&page=${page}`, { token, fetchImpl })
147
- if (!res.ok || !Array.isArray(res.data) || res.data.length === 0) break
149
+ // 默认返回值继续保持「展示失败就省略」的旧语义。onlyNewComments 传 withStatus,
150
+ // 把请求失败与真正的空评论区分开,绝不能把失败当成没有新评论而推进水位。
151
+ if (!res.ok || !Array.isArray(res.data)) {
152
+ if (withStatus) return { ok: false, status: res.status, error: res.error || '评论列表不是数组' }
153
+ break
154
+ }
155
+ if (res.data.length === 0) break
148
156
  last = res.data[res.data.length - 1]
149
157
  if (res.data.length < 100) break
158
+ // 第 5 页仍满:仅严格模式多查第 6 页。空页证明恰好 500 条;非空才是真的截断。
159
+ // 默认展示路径不多发请求,继续保持原来的 5 页上限与失败静默语义。
160
+ if (page === 5) {
161
+ truncated = true
162
+ if (withStatus) {
163
+ const next = await request(`/repos/${repo}/${kind}/${number}/comments?per_page=100&page=6`, { token, fetchImpl })
164
+ if (!next.ok || !Array.isArray(next.data)) return { ok: false, status: next.status, error: next.error || '评论列表不是数组' }
165
+ truncated = next.data.length > 0
166
+ }
167
+ }
150
168
  }
151
- if (!last) return null
169
+ if (!last) return withStatus ? { ok: true, comment: null } : null
152
170
  const login = (last.user && last.user.login) || ''
153
- return {
171
+ const comment = {
154
172
  login,
155
173
  at: last.created_at || null,
156
174
  // 自己留的评论不算「有人在等」——和 GitHub 那条 GraphQL 分支保持同一口径
157
175
  self: Boolean(selfLogin) && login === selfLogin,
158
176
  }
177
+ return withStatus ? { ok: true, comment, truncated } : comment
159
178
  }
160
179
 
161
180
  /** 打标签(ack 用)。Gitee 对 issue 有这个端点;PR 视同 issue。
@@ -167,6 +186,25 @@ export async function addGiteeLabel({ repo, token = '', number, label, fetchImpl
167
186
  }
168
187
 
169
188
  /** 回写处理结论(ack 的可选 Delivery)。PR 与 issue 的端点不同,调用方必须给 kind。 */
189
+ export async function fetchGiteeItemComments({ repo, token = '', number, kind = 'issue', perPage = 100, fetchImpl } = {}) {
190
+ if (kind === 'pull') return fetchGiteePrComments({ repo, token, number, perPage, fetchImpl })
191
+ const comments = []
192
+ let truncated = false
193
+ for (let page = 1; page <= 5; page += 1) {
194
+ const res = await request(`/repos/${repo}/issues/${number}/comments?per_page=${perPage}&page=${page}`, { token, fetchImpl })
195
+ if (!res.ok) return { ok: false, status: res.status, error: res.error }
196
+ if (!Array.isArray(res.data)) return { ok: false, status: res.status, error: '评论列表不是数组' }
197
+ comments.push(...res.data.map((comment) => ({ id: comment.id, body: comment.body || '', user: comment.user, created_at: comment.created_at })))
198
+ if (res.data.length < perPage) return { ok: true, comments, truncated: false }
199
+ if (page === 5) {
200
+ const next = await request(`/repos/${repo}/issues/${number}/comments?per_page=${perPage}&page=6`, { token, fetchImpl })
201
+ if (!next.ok || !Array.isArray(next.data)) return { ok: false, status: next.status, error: next.error || '评论列表不是数组' }
202
+ truncated = next.data.length > 0
203
+ }
204
+ }
205
+ return { ok: true, comments, truncated }
206
+ }
207
+
170
208
  export async function addGiteeComment({ repo, token = '', number, body, kind = 'issue', fetchImpl } = {}) {
171
209
  const segment = kind === 'pull' ? 'pulls' : 'issues'
172
210
  return request(`/repos/${repo}/${segment}/${number}/comments`, { token, method: 'POST', body: { body: String(body || '') }, fetchImpl })
@@ -209,6 +247,14 @@ export function mapGiteeRepoAccess(repo, info = {}) {
209
247
  }
210
248
  }
211
249
 
250
+ /** 写后重读单个 issue/PR,供 ack 返回真实 post-cursor。 */
251
+ export async function getGiteeItem({ repo, number, token = '', kind = 'issue', fetchImpl } = {}) {
252
+ const segment = kind === 'pull' ? 'pulls' : 'issues'
253
+ const res = await request(`/repos/${repo}/${segment}/${number}`, { token, fetchImpl })
254
+ if (!res.ok) return { ok: false, status: res.status, error: res.error }
255
+ return { ok: true, item: normalizeGiteeItem(res.data, { kind }) }
256
+ }
257
+
212
258
  /**
213
259
  * 确保 ack 标签存在(Gitee 不会像 GitHub 那样「打标签时自动建」)。
214
260
  *
@@ -296,3 +342,132 @@ export function giteeHasLabel(list, name) {
296
342
  if (!target) return false
297
343
  return (Array.isArray(list) ? list : []).some((item) => String(item && item.name) === target)
298
344
  }
345
+
346
+ /**
347
+ * 编号归一:缺失 / 空串一律给 `NaN`(调用方按「跳过」处理)。
348
+ *
349
+ * 为什么不直接 `Number()`:`Number(null)` / `Number('')` / `Number(' ')` 都是 **0**,
350
+ * 会把「没有编号」的条目收成 `number: 0` / `id: 0` 的脏数据 ——
351
+ * 前者让 `isForkPr` 永远判不出 fork,后者让 `id > 水位` 永远为假(评论静默丢失)。
352
+ */
353
+ function toNumberId(value) {
354
+ if (value === null || value === undefined) return NaN
355
+ if (typeof value === 'string' && value.trim() === '') return NaN
356
+ return Number(value)
357
+ }
358
+
359
+ /**
360
+ * 「别人仓库里、由本人提的」PR 列表(PR 响应监控用)。
361
+ *
362
+ * 为什么必须按仓库拉:Gitee 没有 GitHub 那种全局 PR 搜索,只能
363
+ * `GET /repos/{base}/pulls`。真机核对(2026-11-13):
364
+ * - `state=open` 只要开着的;
365
+ * - `author={self}` 是**服务端过滤**,实测有效;
366
+ * - `head={user}`(不带分支)返回 0 条 —— 别拿它当过滤条件;
367
+ * - `sort=updated&direction=desc` 让最新的 PR 排前面(下游按顺序消费)。
368
+ *
369
+ * 输出形状是 Task 5(pollPrOnce)唯一消费的契约:
370
+ * `isForkPr` 读 headRepo/baseRepo,唤醒消息读 title/headRef,
371
+ * 所以这里少归一一个字段,PR 就会静默从候选里消失。
372
+ *
373
+ * 防御性归一:fork 仓库被删除时 `head.repo` 是 `null`(不是异常),
374
+ * 输出 `headRepo: null` 交给 `isForkPr` 判「非 fork」跳过;绝不在解析里抛。
375
+ *
376
+ * 为什么 `number` 统一转数字:Gitee 的 PR 编号真机是数字(issue 才是 IKSQJH 那种字符串),
377
+ * 但历史上有字符串形态;统一成数字后 `pruneSeen` / `advanceSeen`(按 String 存键)
378
+ * 与 `Number.isFinite` 判定都不会被脏数据带偏。没有有限编号的条目直接跳过,
379
+ * 免得收成 `number: 0` 的脏 PR。
380
+ */
381
+ export async function listGiteePrs({ repo, token = '', author = '', perPage = 100, fetchImpl } = {}) {
382
+ // Gitee 的 per_page 上限是 100(超过回 400);非法值回落到默认 100
383
+ const size = Math.max(1, Math.min(100, Number(perPage) || 100))
384
+ const authorQ = String(author || '').trim() ? '&author=' + encodeURIComponent(String(author).trim()) : ''
385
+ const res = await request(
386
+ `/repos/${repo}/pulls?state=open&sort=updated&direction=desc&per_page=${size}${authorQ}`,
387
+ { token, fetchImpl },
388
+ )
389
+ if (!res.ok) return { ok: false, status: res.status, error: res.error }
390
+ // 200 但不是数组(网关把错误包成 {"message":"..."} 也回 200)不能当成「没有 PR」:
391
+ // 下游会把空列表读成「本轮没新 PR」,静默漏掉唤醒
392
+ if (!Array.isArray(res.data)) return { ok: false, status: res.status, error: 'PR 列表不是数组' }
393
+ const prs = []
394
+ for (const raw of res.data) {
395
+ const item = raw && typeof raw === 'object' ? raw : {}
396
+ const number = toNumberId(item.number)
397
+ if (!Number.isFinite(number)) continue
398
+ const head = item.head && typeof item.head === 'object' ? item.head : {}
399
+ const base = item.base && typeof item.base === 'object' ? item.base : {}
400
+ prs.push({
401
+ number,
402
+ title: String(item.title || ''),
403
+ // 草稿态:Gitee 的列表里既有布尔 `draft`,也可能只给 `state: 'draft'`(同文件 normalizeGiteeState
404
+ // 就是这么判的)。只认 `draft === true` 会在真机恒为 false —— 契约字段静默失效。
405
+ draft: item.draft === true || String(item.state || '').toLowerCase() === 'draft',
406
+ headRepo: (head.repo && head.repo.full_name) ? String(head.repo.full_name) : null,
407
+ baseRepo: (base.repo && base.repo.full_name) ? String(base.repo.full_name) : null,
408
+ headLogin: (head.user && head.user.login) ? String(head.user.login) : null,
409
+ headRef: head.ref ? String(head.ref) : null,
410
+ })
411
+ }
412
+ // `truncated`:拿满一整页时列表**可能**还有下一页(Gitee 没有 hasNextPage)。
413
+ // 调用方靠它决定「这轮能不能剪掉不在列表里的 PR 的水位」—— 剪了会让那只 PR
414
+ // 回窗后按 seenId=0 把旧评论全部重报。宁可多留一条水位,也不要重报。
415
+ return { ok: true, prs, truncated: prs.length >= size }
416
+ }
417
+
418
+ /**
419
+ * 某条 PR 的**讨论评论**(PR 响应监控用)。
420
+ *
421
+ * 为什么是 `/pulls/{n}/comments?comment_type=pr_comment`:真机核对(2026-11-13),
422
+ * PR 的讨论评论走这里;`/issues/{n}/comments` 对 PR 直接 **404**,别混用。
423
+ * `direction=desc` 让最新的评论排在**首条** —— 下游取最新评论要取 `[0]`,
424
+ * 按 id 比对则不受顺序影响。
425
+ *
426
+ * `id` 必须 `Number()`:Gitee 的评论 id 可能以字符串返回,
427
+ * 而 `pickNewComments`(lib/pr-watch.js)拿它和数字水位比 ——
428
+ * `'999' > 1000` 在字符串比较里是 true,不转就会把旧评论当新评论、每轮重复叫醒。
429
+ *
430
+ * 失败返回 `{ ok: false, status, error }`,**不**给空数组:
431
+ * 空数组会被下游读成「没有新评论」,静默漏掉一次唤醒。
432
+ */
433
+ export async function fetchGiteePrComments({ repo, token = '', number, perPage = 100, fetchImpl } = {}) {
434
+ // 没有编号就别发请求:否则 URL 会拼成 /pulls/undefined/comments,拿回 404 还看不出是参数错了。
435
+ // 0 与负数同样是非法 PR 编号(toNumberId 只挡 null/undefined/空白串)
436
+ const id = toNumberId(number)
437
+ if (!Number.isFinite(id) || id <= 0) return { ok: false, status: 0, error: 'number is required' }
438
+ const size = Math.max(1, Math.min(100, Number(perPage) || 100))
439
+ const comments = []
440
+ // 翻页:`per_page` 最大 100,只拉第一页时首窗之后的评论永远看不到
441
+ // (2026-11-13 外部 review 的第 3 点:已有 id 1..14、服务端只回 5..14,
442
+ // 首轮 seen=14 后 id 1..4 永久低于水位)。Gitee 用 `page` 参数翻。
443
+ const maxPages = 10 // 1000 条封顶:病态 PR 不能把一轮轮询拖成分钟级
444
+ let truncated = false
445
+ for (let page = 1; page <= maxPages; page += 1) {
446
+ const res = await request(
447
+ `/repos/${repo}/pulls/${id}/comments?comment_type=pr_comment&direction=desc&per_page=${size}&page=${page}`,
448
+ { token, fetchImpl },
449
+ )
450
+ if (!res.ok) return { ok: false, status: res.status, error: res.error }
451
+ // 同列表:200 但正文不是数组时不能当成「没有评论」
452
+ if (!Array.isArray(res.data)) return { ok: false, status: res.status, error: '评论列表不是数组' }
453
+ if (res.data.length === 0) break
454
+ for (const raw of res.data) {
455
+ const item = raw && typeof raw === 'object' ? raw : {}
456
+ const commentId = toNumberId(item.id)
457
+ // 没有可比较的 id 就没法做水位:跳过,免得 NaN 让「新评论」判定永远为假
458
+ if (!Number.isFinite(commentId)) continue
459
+ comments.push({
460
+ id: commentId,
461
+ // 评论者账号被删除时 user 是 null:给空串(与 GitHub 侧 parsePrSearch 同类型),
462
+ // normalizeSelf('') 归一成空串,与任何真实账号都不等 → 按「非本人」处理,别抛
463
+ author: (item.user && item.user.login) ? String(item.user.login) : '',
464
+ body: String(item.body || ''),
465
+ createdAt: item.created_at ? String(item.created_at) : '',
466
+ })
467
+ }
468
+ // 不满一页说明到底了;满页才继续翻
469
+ if (res.data.length < size) break
470
+ if (page === maxPages) truncated = true
471
+ }
472
+ return { ok: true, comments, truncated }
473
+ }