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/lib/index.js CHANGED
@@ -14,8 +14,8 @@
14
14
  */
15
15
  import { execFileSync, spawn } from 'node:child_process'
16
16
  import { createHash, randomUUID } from 'node:crypto'
17
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
18
- import os, { homedir } from 'node:os'
17
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
19
  import { dirname, isAbsolute, join } from 'node:path'
20
20
  import { fileURLToPath } from 'node:url'
21
21
 
@@ -25,37 +25,52 @@ import Schema from '@deepseek-ai/schemastery'
25
25
 
26
26
  import { redact } from './redact.js'
27
27
  import { decodeBody, truncateUtf8 } from './body.js'
28
- import { quotaDeferText, isOfflineMode } from './gh-format.js'
29
- import { listGiteeItems, fetchGiteeLastComment, addGiteeLabel, addGiteeComment, ensureGiteeLabel, giteeWhoami, giteeRepo, mapGiteeRepoAccess, DEFAULT_ACK_LABEL_GITEE, giteeLabels, giteeHasLabel, isValidGiteeLabel, suggestGiteeLabel } from './gitee.js'
28
+ import { quotaDeferText, isOfflineMode, lastCommentArgs, parseLastComment, buildPrSearchQuery, parsePrSearch } from './gh-format.js'
29
+ // PR 响应监控:纯函数层单独一个文件(水位/判定/措辞都要能离线钉住)。
30
+ // 注意别拿错 `pruneSeen`/`advanceSeen` —— PR 版操作 `{prNumber: commentId}`,
31
+ // issue 版(lib/watch.js,见下面那段导入)操作 `{number: updatedAt}`,签名不同。
32
+ import { normalizeSelf, isForkPr, pickNewComments, buildPrWakeText } from './pr-watch.js'
33
+ // PR 列表与评论:Gitee 没有 gh,只能自己发 HTTP;同一文件里其它 Gitee 调用走那条导入。
34
+ import { listGiteePrs, fetchGiteePrComments, fetchGiteeItemComments } from './gitee.js'
35
+ import { listGiteeItems, fetchGiteeLastComment, giteeWhoami, giteeRepo, mapGiteeRepoAccess, DEFAULT_ACK_LABEL_GITEE, giteeLabels, giteeHasLabel, isValidGiteeLabel, suggestGiteeLabel } from './gitee.js'
30
36
  // 门禁实现已经抽到独立包(G2):主插件只消费包的稳定接口,不再内嵌规则。
31
37
  // `lib/gates.js` 保留成兼容 re-export,旧调用点(历史测试 / 外部脚本)不用改。
32
38
  import { createGate, loadGateConfig, lintText, optimizePrompt, listModels, readGateScope, writeGateConfig, validateConfig } from '@mycf711/dsh-gate'
33
39
  import { migrateState, CURRENT_STATE_SCHEMA } from './state-migration.js'
40
+ import { migrateV1Watermark, observe as observeV2, handle as handleV2, mergeWatermarkStates } from './rooms/watermark-state.js'
41
+ import { decideWatermark } from './rooms/watermark-decision.js'
42
+ import { issueCursor, issueKey, createGithubProvider, createGiteeProvider } from './rooms/data-provider.js'
43
+ import { commitDeliveryReceipt } from './rooms/delivery.js'
44
+ import { projectRecords, projectExecution, projectDeployment } from './rooms/ticket-projection.js'
45
+ import { createSourceRegistry } from './rooms/source-registry.js'
46
+ import { createDraft, editDraft, clearDraft } from './rooms/draft.js'
47
+ import { ensureTicket, routeRuntimeEvent, completeRuntimeTicket, startRuntimeAssignment, runtimeThreadKey, evaluateAdmission, renderRuntimePrompt } from './rooms/modular-runtime.js'
48
+ import { createModularOutboxHost } from './rooms/modular-outbox-host.js'
49
+ import { createDshExecutor } from './rooms/executor-host.js'
34
50
  import { runExclusiveUpdate, spawnPluginUpdate, validateUpdateBody } from './update.js'
35
51
  import { compareSemver, isStrictSemver } from './semver.js'
36
52
  import {
37
- effectiveIntervalMs, planWakeSettlement, advanceSeen, applyWatcherAction, batchFresh, decideWake, DEFAULT_ACK_LABEL, DEFAULT_BRAND_NAME, DEFAULT_PRIORITY, formatWatchText,
53
+ effectiveIntervalMs, planWakeSettlement, applyWatcherAction, batchFresh, decideWake, clearBackoff, DEFAULT_ACK_LABEL, DEFAULT_BRAND_NAME, DEFAULT_PRIORITY, formatWatchText,
38
54
  defaultAckLabelFor, normalizeBrandName,
39
- recordPendingWake, clearPending, pendingRetry,
40
55
  wakeQuality,
41
56
  parseRepoSpec, markGiteeReopened,
42
- TRIAGE_SIGNALS, accessNote, wakeCriteria, sessionMissingVerdict, buildCommentBatchQuery, classifyGhError, commentSummaryLine, parseCommentBatch, pickSuggestion, repoStructureNote, countReasons, filterReason, formatGhCall, diagnoseEmptyBody, diagnoseBadBody, isAuthBroken, hasAckLabel, jitterMs, parseGhInclude, retryAfterMs, throttleDelayMs, inActiveHours, newestUpdatedAt, nextDelayMs, enterActiveHoursDefer, recordOtherError, permanentBackoffMs, RETRY_BUDGET_ATTEMPTS, RETRY_SLOW_CAP_MINUTES, pushAbsorbed, pushFiltered, normalizeFilters, partitionItems, passesFilters,
57
+ TRIAGE_SIGNALS, accessNote, wakeCriteria, sessionMissingVerdict, buildCommentBatchQuery, classifyGhError, commentSummaryLine, parseCommentBatch, pickSuggestion, repoStructureNote, countReasons, filterReason, formatGhCall, diagnoseEmptyBody, diagnoseBadBody, isAuthBroken, hasAckLabel, jitterMs, parseGhInclude, retryAfterMs, throttleDelayMs, inActiveHours, nextDelayMs, enterActiveHoursDefer, recordOtherError, permanentBackoffMs, RETRY_BUDGET_ATTEMPTS, RETRY_SLOW_CAP_MINUTES, pushFiltered, normalizeFilters, passesFilters,
43
58
  shouldRunCleanup,
44
59
  bumpDailyWakes,
45
60
  busierThanUsual,
46
61
  countCapped,
47
- statusView,
62
+ statusView, pollHealth, STOPPED_STATES, isWatcherEnabled,
48
63
  dailySummary,
49
64
  suggestSessionCap,
50
65
  itemTrace,
51
66
  splitBatch,
52
- mergeFilters, mergePollResult, mergeWakeTexts, pushEvent, silentStreak, msUntilActiveWindow, nextWaketimeAt, pruneSeen, sessionWakesLastHour, pruneWakeTimes, pushHistory, recordReported, staleWorktrees, worktreePlan,
67
+ mergeFilters, mergePollResult, mergeWakeTexts, pushEvent, silentStreak, msUntilActiveWindow, nextWaketimeAt, sessionWakesLastHour, pruneWakeTimes, pushHistory, staleWorktrees, worktreePlan,
53
68
  validateActiveHours,
54
69
  } from './watch.js'
55
70
 
56
71
  export const name = 'dsh-session-superagent'
57
72
  /** 服务端版本:随 package.json 同步(meta 测试守着)。客户端据此挑「最新的那个实例」。 */
58
- export const SERVER_VERSION = '0.10.12'
73
+ export const SERVER_VERSION = '2.0.1'
59
74
  export const inject = ['tools', 'agents', 'webServer']
60
75
  /** 一条会话每小时最多被唤醒几次(跨所有守累计)。单守上限挡不住多守叠加。 */
61
76
  // 本进程启动时刻:用来区分「刚重启还没轮到」与「定时器真的丢了」
@@ -123,6 +138,10 @@ const formatTraceText = (traces) => {
123
138
  }
124
139
 
125
140
  const DEFAULT_SESSION_WAKES = 12
141
+ // 两条守(issue / PR)共用同一句回执文案:各写一份就会悄悄漂移,
142
+ // 而客户/模型都靠这句话判断「仓库名该怎么写」。
143
+ const REPO_SPEC_ERROR = '仓库要写成 owner/name 或 gitee:owner/name,这些不对:'
144
+ const OBSERVE_FLAG_TEXT = 'observe-only(只记录不唤醒)'
126
145
  /** 单次唤醒最多铺开几条(面板的占位符要显示这个真值,不能写死)。 */
127
146
  const DEFAULT_BATCH_LIMIT = 5
128
147
  // 面板里的「默认值提示」也要从这里来:JSON Schema 的 default 就是给表单做提示用的
@@ -143,6 +162,9 @@ function toolError(args, message) {
143
162
  if (args && args.format === 'json') return JSON.stringify({ schemaVersion: 1, ok: false, error: message })
144
163
  return '[error: ' + message + ']'
145
164
  }
165
+ function ackWatcherReplacedMessage(id) {
166
+ return '远端标签可能已写入,但本地水位未推进:守 ' + id + ' 在 ack 结算前已被删除或替换'
167
+ }
146
168
  /** 全局上限:每条守一个定时器,无限建等于自造 DoS(审核 T19)。 */
147
169
  const MAX_WATCHERS_TOTAL = 200
148
170
 
@@ -201,8 +223,91 @@ export function resolveBrandConfig(options = {}) {
201
223
  /** 隔离区回收的最小间隔:没有超额时不必每次唤醒都跑 git。 */
202
224
  const CLEANUP_INTERVAL_MS = 10 * 60 * 1000
203
225
 
226
+ // `gh api` 只有显式 `--input -` 才从 stdin 读取请求体;只写 child.stdin 会发空 body。
227
+ function githubApiRequest(method, path, body) {
228
+ const write = !['GET', 'HEAD'].includes(method)
229
+ const argv = ['api', '-X', method, path, '--header', 'Accept: application/vnd.github+json']
230
+ const input = write && body ? body : undefined
231
+ if (input !== undefined) argv.push('--input', '-')
232
+ return { argv, input }
233
+ }
234
+
235
+ /**
236
+ * 仅供测试:`runManualPoll` 的分流目标可被替换(同 `authStatusCache` 的做法)。
237
+ * 平时是 null,生产路径完全不受影响 —— 这是模块级状态,`__test.setManualPoller`
238
+ * 与 `apply()` 里的 `runManualPoll` 必须看到同一份。
239
+ */
240
+ let manualPollerOverride = null
241
+
242
+ /**
243
+ * 仅供测试:读「这条守还有没有排着、且还能真 fire 的 boot tick」。
244
+ *
245
+ * `bootTimers` 活在 `apply()` 里(每次挂载一份),所以这里留一个指向当前实例的读数函数,
246
+ * `apply()` 挂载时把它接上。没挂载过就是「没有」,生产路径不受影响。
247
+ *
248
+ * 为什么需要它:`startWatcher` 会给新守排一个 0~5 秒的 boot tick(`jitterMs` 按 id 定死,
249
+ * `pr:o/revive#s1` 是 3338ms)。「恢复只补跑一轮」的用例若只 `sleep(150)` 再数调用数,
250
+ * boot tick 还没 fire —— 把撤销逻辑删掉它也照样绿,挡不住要守的那个回归。
251
+ *
252
+ * 为什么读数要看句柄而不是「map 里有没有这个 key」:撤销块是
253
+ * `clearTimeout(boot)` + `bootTimers.delete(id)` 两件事,只删前一行时 key 照样没了,
254
+ * 于是「map 里没有 = 已撤销」是个假的等号;而那个 timer 3.4 秒后仍会 fire、真再跑一轮
255
+ * (对抗性审计 m2 变体实测)。所以 `apply()` 另记一份**不删**的 `bootArmed`,
256
+ * 这里读句柄的 `_destroyed`:`clearTimeout` 之后(以及 fire 之后)它才是 true。
257
+ * Node 的 Timeout 没有公开的存活判断,`_destroyed` 是唯一可观测信号;万一哪天字段没了
258
+ * 会读到「还活着」而让用例变红(fail-loud),不会静默放过回归。
259
+ */
260
+ let bootTimerProbe = () => false
261
+
262
+ /** 仅供测试覆盖进程启动时刻;生产始终走 PROCESS_STARTED_AT。 */
263
+ let bootProbeOverride = () => undefined
264
+ function bootPollBootAt() {
265
+ return Number(bootProbeOverride()) || Number(PROCESS_STARTED_AT) || 0
266
+ }
267
+
268
+ /**
269
+ * 仅供测试:这条守的 interval 定时器是否还在。
270
+ *
271
+ * 与上一条互补:上一条问「boot tick 撤了没」,这条问「interval 还在不在」。
272
+ * 少了它,「恢复后根本没有任何定时器」(= 用户报的「恢复后不触发」)也会绿 ——
273
+ * 因为那一步把 `bootTimers` 也一起变空了,两个否定式断言同时满足(对抗性审计 m3 变体)。
274
+ */
275
+ const watchTimerProbe = (id) => sharedTimers.has(String(id))
276
+
204
277
  /** 仅供测试:读写状态文件(生产代码不要用)。 */
205
- export const __test = { readState, writeState, hardenSecretsFile, wakeMerged, flushWakeQueue, wakeQueueCount, clearWakeQueues, pollWithItems, settleNotModified, setAuthStatusCache: (text) => { authStatusCache = { at: text ? Date.now() : 0, text } } }
278
+ export const __test = {
279
+ readState, writeState, commitModularState, hardenSecretsFile, wakeMerged, flushWakeQueue, wakeQueueCount, clearWakeQueues,
280
+ outboxMarker, withOutboxMarker, hasOutboxMarker, findOutboxComment,
281
+ projectModular: (state) => buildModularProjection(state, {}),
282
+ recordRuntimeDelivery, deliverWorkerItem, deliverWorkerBatch, filterAdmissionBatch, completeRuntimeForAck, mutateRuntime,
283
+ pollWithItems, pollPrOnce, settleNotModified, githubApiRequest,
284
+ setAuthStatusCache: (text) => { authStatusCache = { at: text ? Date.now() : 0, text } },
285
+ setBootAt: (at) => {
286
+ bootProbeOverride = at === null || at === undefined ? () => undefined : () => Number(at)
287
+ return () => { bootProbeOverride = () => undefined }
288
+ },
289
+ /**
290
+ * 仅供测试:替换「人工触发轮询」真正调用的 poller。
291
+ *
292
+ * 为什么要这个缝:路由层要断言「恢复后真的补跑了一轮、且只跑一轮」,
293
+ * 而真实 poller 会去打 GitHub / Gitee;离线开关 `DSH_SUPERAGENT_NO_POLL`
294
+ * 又会把轮询整个关掉 —— 两者之间没有可观察的接缝。
295
+ * 传 `null` 还原。返回还原函数,`t.after` 里调用即可(避免用例间互相污染)。
296
+ */
297
+ setManualPoller: (fn) => {
298
+ manualPollerOverride = typeof fn === 'function' ? fn : null
299
+ return () => { manualPollerOverride = null }
300
+ },
301
+ /**
302
+ * 仅供测试:这条守是否还排着一个**能真 fire** 的 boot tick。
303
+ * **纯只读**:没有还原语义(不像上一条要换绑什么),读数函数由 `apply()` 接上。
304
+ * 注意它读的是**最近一次 `apply()` 那份实例**的账;跨实例断言请用
305
+ * `import('../lib/index.js?cachebust=…')` 拿独立模块(各自独立的 probe)。
306
+ */
307
+ bootTimerPending: (id) => bootTimerProbe(id),
308
+ /** 仅供测试:这条守的 interval 定时器还在不在(只读)。 */
309
+ watchTimerPending: (id) => watchTimerProbe(id),
310
+ }
206
311
 
207
312
  // 审核 T30:这四个路径以前在**模块加载那一刻**定死 ——
208
313
  // 测试里改 `process.env.DSH_SUPERAGENT_STATE` 之后,已经加载的实例仍然指着老目录,
@@ -265,14 +370,24 @@ function readState() {
265
370
  try {
266
371
  // 先显式迁移,再做兼容归一;未来版本会抛错并落到 .bak,不盲目按旧代码读取。
267
372
  const parsed = migrateState(JSON.parse(raw)).state
268
- for (const entry of Object.values(parsed.watchers || {})) { normalizePaused(entry); normalizeAckLabel(entry) }
373
+ for (const [id, value] of Object.entries(parsed.watchers || {})) {
374
+ const entry = migrateV1Watermark(value)
375
+ if (entry.kind === 'pr' || id.startsWith('pr:')) syncPrCommentsProjection(entry)
376
+ normalizePaused(entry); normalizeAckLabel(entry)
377
+ parsed.watchers[id] = entry
378
+ }
269
379
  stateSource = 'ok'
270
380
  return parsed
271
381
  } catch {
272
382
  // 主文件坏了:试试备份
273
383
  try {
274
384
  const backup = migrateState(JSON.parse(readFileSync(stateFile() + '.bak', 'utf8'))).state
275
- for (const entry of Object.values(backup.watchers || {})) { normalizePaused(entry); normalizeAckLabel(entry) }
385
+ for (const [id, value] of Object.entries(backup.watchers || {})) {
386
+ const entry = migrateV1Watermark(value)
387
+ if (entry.kind === 'pr' || id.startsWith('pr:')) syncPrCommentsProjection(entry)
388
+ normalizePaused(entry); normalizeAckLabel(entry)
389
+ backup.watchers[id] = entry
390
+ }
276
391
  stateSource = 'backup'
277
392
  // 把备份写回主文件,避免下次还走恢复路径
278
393
  try { writeFileSync(stateFile(), JSON.stringify(backup, null, 2)) } catch {}
@@ -320,12 +435,7 @@ function normalizeAckLabel(entry) {
320
435
  * 所以不能只判 `=== false`:字符串 "false"、数字 0、"0" 都算暂停,缺省才算启用。
321
436
  */
322
437
  function isEnabled(entry) {
323
- if (!entry) return false
324
- const value = entry.enabled
325
- if (value === undefined || value === null) return true
326
- if (value === false || value === 0) return false
327
- const text = String(value).trim().toLowerCase()
328
- return !(text === 'false' || text === '0' || text === 'no' || text === 'off')
438
+ return isWatcherEnabled(entry)
329
439
  }
330
440
 
331
441
  function normalizePaused(entry) {
@@ -346,25 +456,383 @@ function normalizePaused(entry) {
346
456
  * 180 秒冷却期一过,同一条又被算成「新动态」再叫醒一次。
347
457
  */
348
458
  function mergeWatermark(diskEntry, memEntry) {
349
- if (!diskEntry) return memEntry
350
- if (!memEntry) return diskEntry
459
+ if (!diskEntry) return migrateV1Watermark(memEntry)
460
+ if (!memEntry) return migrateV1Watermark(diskEntry)
351
461
  const out = { ...diskEntry, ...memEntry }
352
462
  const seen = { ...(diskEntry.seen || {}) }
353
463
  for (const [key, at] of Object.entries(memEntry.seen || {})) {
354
- const prev = seen[key]
355
- if (!prev || Date.parse(at) >= Date.parse(prev)) seen[key] = at
464
+ if (!seen[key] || Date.parse(at) >= Date.parse(seen[key])) seen[key] = at
356
465
  }
357
466
  out.seen = seen
358
- // lastPoll 同理:晚的那个才是事实
359
- if (diskEntry.lastPoll && (!out.lastPoll || Date.parse(diskEntry.lastPoll) > Date.parse(out.lastPoll))) {
360
- out.lastPoll = diskEntry.lastPoll
361
- }
467
+ if (diskEntry.lastPoll && (!out.lastPoll || Date.parse(diskEntry.lastPoll) > Date.parse(out.lastPoll))) out.lastPoll = diskEntry.lastPoll
468
+ const v2 = mergeWatermarkStates(migrateV1Watermark(diskEntry), migrateV1Watermark(memEntry))
469
+ out.watermarkVersion = v2.watermarkVersion
470
+ out.round = v2.round
471
+ out.obs = v2.obs
362
472
  return out
363
473
  }
364
474
 
475
+ // KB: concurrent-isolation.md —— 跨进程写锁必须覆盖完整 read-merge-rename。
476
+ function acquireStateWriteLock() {
477
+ const path = stateFile() + '.lock'
478
+ for (let attempt = 0; attempt < 600; attempt += 1) {
479
+ try {
480
+ return openSync(path, 'wx')
481
+ } catch (error) {
482
+ // Windows create-new 竞争会返回 EPERM;锁文件也可能在查询前被另一方删除。
483
+ // 有界重试避免 TOCTOU;持续 ACL 错误最终以 writeError 暴露,不伪装成功。
484
+ const contended = error && (error.code === 'EEXIST' || error.code === 'EPERM')
485
+ if (!contended) throw error
486
+ // 进程崩溃可能留下锁文件;超过 60 秒才允许回收,活锁不能被抢。
487
+ try {
488
+ if (Date.now() - statSync(path).mtimeMs > 60000) { unlinkSync(path); continue }
489
+ } catch { /* 锁刚被别的进程释放/替换,下一轮重新创建 */ }
490
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.min(50, 5 + attempt))
491
+ }
492
+ }
493
+ throw new Error('state write lock timed out')
494
+ }
495
+
496
+ const MODULAR_STATE_KEYS = Object.freeze(['tickets', 'subscriptions', 'assignments', 'outbox', 'draft', 'promptConfig', 'locale', 'executorPaused'])
497
+
498
+ function buildModularProjection(state, ctx = {}) {
499
+ const tickets = state.tickets
500
+ const subscriptions = state.subscriptions && state.subscriptions.subscriptions !== undefined
501
+ ? state.subscriptions.subscriptions
502
+ : state.subscriptions
503
+ const assignments = state.assignments
504
+ const outbox = state.outbox && Array.isArray(state.outbox.outbox) ? state.outbox.outbox : state.outbox
505
+ const workerActive = Object.values(assignments || {}).some((assignment) => assignment && String(assignment.sessionId || '').startsWith('worker-') && assignment.status !== 'ended')
506
+ const workerUnavailable = workerActive && !ctx.sessionController
507
+ const health = []
508
+ if (lastWriteError) health.push({ name: 'state', state: 'error', detail: lastWriteError.message || null })
509
+ if (workerActive || Object.keys(tickets || {}).length > 0) {
510
+ health.push({ name: 'executor', state: workerUnavailable ? 'paused' : 'ready', detail: workerUnavailable ? 'sessionController unavailable for worker' : workerActive ? 'worker' : 'inline' })
511
+ }
512
+ return {
513
+ records: projectRecords({ tickets, subscriptions, assignments, outbox }),
514
+ execution: projectExecution({ tickets, subscriptions, assignments, outbox, health, paused: state.executorPaused === true || workerUnavailable }),
515
+ deployment: projectDeployment({ health, stateDir: stateDir(), problem: lastWriteError }),
516
+ draft: state.draft || null,
517
+ actions: true,
518
+ locale: state.locale === 'en' ? 'en' : 'zh',
519
+ }
520
+ }
521
+
522
+ function requestSessionScope(req, body = {}) {
523
+ const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
524
+ const querySession = String(url.searchParams.get('sessionId') || '').trim()
525
+ const bodySession = String(body && body.sessionId || '').trim()
526
+ if (querySession && bodySession && querySession !== bodySession) {
527
+ return { error: 'query and body sessionId must match' }
528
+ }
529
+ const scope = String(url.searchParams.get('scope') || body && body.scope || '').trim()
530
+ if (scope && scope !== 'global') return { error: 'scope must be global when supplied' }
531
+ const sessionId = bodySession || querySession
532
+ if (scope === 'global' && sessionId) return { error: 'scope=global cannot be combined with sessionId' }
533
+ return {
534
+ sessionId,
535
+ explicitGlobal: scope === 'global',
536
+ // 无 sessionId 是旧全局面板的兼容入口;只有显式 scope=global 才回显会话 goal/草稿。
537
+ legacyGlobal: !sessionId && scope !== 'global',
538
+ }
539
+ }
540
+
541
+ function directSessionId(value) {
542
+ const text = String(value || '').trim()
543
+ return text && !text.startsWith('worker-') ? text : ''
544
+ }
545
+
546
+ function ticketSessionIds(state, ticket) {
547
+ const ids = new Set()
548
+ const directOwner = directSessionId(ticket && ticket.ownerSessionId)
549
+ if (directOwner) return new Set([directOwner])
550
+ const assignment = ticket && state.assignments && state.assignments[ticket.assignmentId]
551
+ const assignmentSession = directSessionId(assignment && assignment.sessionId)
552
+ if (assignmentSession) return new Set([assignmentSession])
553
+ const subscriptions = state.subscriptions && state.subscriptions.subscriptions !== undefined
554
+ ? state.subscriptions.subscriptions
555
+ : state.subscriptions
556
+ for (const row of Object.values(subscriptions || {})) {
557
+ if (!row || row.ticketId !== ticket.id || row.active !== true) continue
558
+ const sessionId = directSessionId(row.sessionId)
559
+ if (sessionId) ids.add(sessionId)
560
+ }
561
+ if (ids.size > 0) return ids
562
+
563
+ const workerOwned = String(ticket && ticket.ownerSessionId || '').startsWith('worker-')
564
+ || String(assignment && assignment.sessionId || '').startsWith('worker-')
565
+ || Object.values(subscriptions || {}).some((row) => row && row.ticketId === ticket.id
566
+ && String(row.sessionId || '').startsWith('worker-'))
567
+ if (!workerOwned) return ids
568
+ // worker Ticket 的 owner 是 worker-*;项目会话只能由唯一匹配的 worker watcher 反推。
569
+ // 同仓库若有多会话 worker 守,旧数据没有足够归属证据,必须 fail closed。
570
+ const threadKey = String(ticket && ticket.threadKey || '')
571
+ const separator = threadKey.lastIndexOf('#')
572
+ const threadPrefix = separator > 0 ? threadKey.slice(0, separator) : ''
573
+ for (const watcher of Object.values(state.watchers || {})) {
574
+ if (!watcher || watcher.executionMode !== 'worker') continue
575
+ const prefix = (watcher.provider === 'gitee' ? 'gitee' : 'github') + ':' + String(watcher.repo || '')
576
+ const sessionId = directSessionId(watcher.sessionId)
577
+ if (threadPrefix && prefix === threadPrefix && sessionId) ids.add(sessionId)
578
+ }
579
+ return ids
580
+ }
581
+
582
+ function ticketBelongsToSession(state, ticket, sessionId) {
583
+ if (!ticket || !sessionId) return false
584
+ const owners = ticketSessionIds(state, ticket)
585
+ return owners.size === 1 && owners.has(sessionId)
586
+ }
587
+
588
+ function modularOutboxRows(state) {
589
+ return Array.isArray(state.outbox) ? state.outbox
590
+ : state.outbox && Array.isArray(state.outbox.outbox) ? state.outbox.outbox : []
591
+ }
592
+
593
+ function outboxBelongsToSession(state, message, sessionId) {
594
+ if (!message || !sessionId) return false
595
+ const ticket = state.tickets && state.tickets[message.ticketId]
596
+ if (ticket) return ticketBelongsToSession(state, ticket, sessionId)
597
+ const watcherId = String(message.channel && message.channel.watcherId || '')
598
+ const watcher = watcherId && state.watchers && state.watchers[watcherId]
599
+ if (watcher) return watcher.sessionId === sessionId
600
+ return false
601
+ }
602
+
603
+ function scopeModularStateToSession(state, sessionId) {
604
+ const tickets = Object.fromEntries(Object.entries(state.tickets || {})
605
+ .filter(([, ticket]) => ticketBelongsToSession(state, ticket, sessionId)))
606
+ const ticketIds = new Set(Object.keys(tickets))
607
+ const subscriptionRows = state.subscriptions && state.subscriptions.subscriptions !== undefined
608
+ ? state.subscriptions.subscriptions
609
+ : state.subscriptions
610
+ const subscriptions = Object.fromEntries(Object.entries(subscriptionRows || {})
611
+ .filter(([, row]) => row && ticketIds.has(row.ticketId)))
612
+ const assignments = Object.fromEntries(Object.entries(state.assignments || {})
613
+ .filter(([, row]) => row && ticketIds.has(row.ticketId)))
614
+ const outbox = modularOutboxRows(state).filter((message) => outboxBelongsToSession(state, message, sessionId))
615
+ const draftTicketId = String(state.draft && (state.draft.ticketId
616
+ || state.draft.value && state.draft.value.ticketId
617
+ || state.draft.base && state.draft.base.ticketId) || '')
618
+ return {
619
+ ...state,
620
+ tickets,
621
+ subscriptions: state.subscriptions && state.subscriptions.subscriptions !== undefined
622
+ ? { ...state.subscriptions, subscriptions }
623
+ : subscriptions,
624
+ assignments,
625
+ outbox: state.outbox && !Array.isArray(state.outbox) && Array.isArray(state.outbox.outbox)
626
+ ? { ...state.outbox, outbox }
627
+ : outbox,
628
+ draft: draftTicketId && ticketIds.has(draftTicketId) ? state.draft : null,
629
+ }
630
+ }
631
+
632
+ function modularVersionOf(state) {
633
+ return Number.isSafeInteger(state && state.modularVersion) && state.modularVersion >= 0 ? state.modularVersion : 0
634
+ }
635
+
636
+ async function mutateRuntime(mutator, attempts = 4) {
637
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
638
+ const current = readState()
639
+ const result = await mutator(current)
640
+ const next = result && result.state ? result.state : result
641
+ const written = commitModularState(modularVersionOf(current), () => next)
642
+ if (!written.writeError) return result && result.state ? { ...result, state: written } : written
643
+ if (!/CAS conflict|MODULAR_CAS_CONFLICT/i.test(written.writeError.message)) throw new Error(written.writeError.message)
644
+ }
645
+ throw new Error('modular state CAS retries exhausted')
646
+ }
647
+
648
+ async function recordRuntimeDelivery(entry, item, ctx = null) {
649
+ const threadKey = runtimeThreadKey({ provider: entry.provider || 'github', repo: entry.repo, number: item.number })
650
+ const mode = entry.executionMode === 'worker' ? 'worker' : 'inline'
651
+ const workdir = entry.workdir || process.cwd()
652
+ const event = {
653
+ threadKey,
654
+ id: String(item.cursor || item.updated_at || item.key || `${threadKey}:initial`),
655
+ type: item.lastComment ? 'comment' : 'update',
656
+ actor: !item.lastComment ? 'system'
657
+ : item.lastComment.self || /\[bot\]$|^bot$|(?:^|[-_])bot$/i.test(String(item.lastComment.login || '')) ? 'agent'
658
+ : 'human',
659
+ body: String(item.lastComment && item.lastComment.text || item.title || ''),
660
+ at: new Date().toISOString(),
661
+ }
662
+ return mutateRuntime(async (state) => {
663
+ const routed = await routeRuntimeEvent(state, event, {
664
+ mode, sessionId: entry.sessionId, workdir, deferExecution: true,
665
+ executor: ctx && ctx.sessionController ? createDshExecutor(ctx) : undefined,
666
+ })
667
+ if (routed.disposition === 'eval' && !routed.ticket) {
668
+ const ensured = ensureTicket(routed.state, {
669
+ threadKey, sessionId: entry.sessionId, workdir, mode,
670
+ at: event.at, eventId: event.id,
671
+ })
672
+ return { ...ensured, disposition: 'deliver' }
673
+ }
674
+ return routed
675
+ })
676
+ }
677
+
678
+ async function completeRuntimeForAck(ctx, entry, number, eventId) {
679
+ const ticketId = `ticket:${entry.provider || 'github'}:${entry.repo}#${number}`
680
+ return mutateRuntime(async (state) => {
681
+ if (!state.tickets || !state.tickets[ticketId]) return { state }
682
+ return completeRuntimeTicket(state, ticketId, {
683
+ mode: entry.executionMode === 'worker' ? 'worker' : 'inline',
684
+ executor: entry.executionMode === 'worker' ? createDshExecutor(ctx) : undefined,
685
+ reason: 'completed', eventId, at: new Date().toISOString(),
686
+ })
687
+ })
688
+ }
689
+
690
+ async function sendRuntimeOutboxMessage(ctx, message, providers = []) {
691
+ const channel = message.channel || {}
692
+ if (channel.type === 'worker') {
693
+ const receipt = await startRuntimeAssignment(await readState(), {
694
+ ticketId: message.ticketId,
695
+ executor: createDshExecutor(ctx),
696
+ prompt: message.body,
697
+ messageId: message.id,
698
+ })
699
+ return { ok: true, receipt }
700
+ }
701
+ if (channel.type !== 'ack') return { ok: false, error: 'unknown outbox channel: ' + String(channel.type) }
702
+ const state = readState()
703
+ const entry = state.watchers && (state.watchers[channel.watcherId] || Object.values(state.watchers).find((watcher) => watcher && watcher.repo === channel.repo))
704
+ if (!entry) return { ok: false, error: 'watcher not found for outbox ack: ' + String(channel.repo) }
705
+ if (channel.watcherCreatedAt && entry.createdAt && channel.watcherCreatedAt !== entry.createdAt) {
706
+ return { ok: false, error: 'watcher generation changed for outbox ack: ' + String(channel.repo) }
707
+ }
708
+ const sources = createSourceRegistry([
709
+ createGithubProvider({ run, env: ghEnv() }),
710
+ createGiteeProvider({ token: String(readSecrets().giteeToken || '') }),
711
+ ...providers,
712
+ ])
713
+ const provider = sources.get(entry.provider, 'ack')
714
+ let alreadySent = false
715
+ if (channel.comment) {
716
+ const marker = await findOutboxComment(entry, channel.number, channel.kind, message.id)
717
+ if (!marker.ok) return { ok: false, stage: 'comment', error: marker.error }
718
+ alreadySent = marker.found
719
+ }
720
+ const ack = await provider.acknowledge({
721
+ repo: channel.repo, number: channel.number, label: channel.label, kind: channel.kind,
722
+ note: channel.comment && !alreadySent ? withOutboxMarker(message.body, message.id) : '',
723
+ })
724
+ return { ...ack, alreadySent }
725
+ }
726
+
727
+ const RUNTIME_OUTBOX_HOSTS_KEY = Symbol.for('dsh-session-superagent.modularOutboxHosts')
728
+ const runtimeOutboxHosts = (globalThis[RUNTIME_OUTBOX_HOSTS_KEY] ||= new Map())
729
+
730
+ function runtimeOutbox(ctx, providers = []) {
731
+ if (!ctx || (typeof ctx !== 'object' && typeof ctx !== 'function')) {
732
+ return createModularOutboxHost({
733
+ readState: async () => readState(), commitModularState,
734
+ send: (message) => sendRuntimeOutboxMessage(ctx, message, providers),
735
+ })
736
+ }
737
+ const key = stateFile()
738
+ let slot = runtimeOutboxHosts.get(key)
739
+ if (!slot) {
740
+ slot = { ctx, providers, host: null }
741
+ slot.host = createModularOutboxHost({
742
+ readState: async () => readState(), commitModularState,
743
+ send: (message) => sendRuntimeOutboxMessage(slot.ctx, message, slot.providers),
744
+ })
745
+ runtimeOutboxHosts.set(key, slot)
746
+ }
747
+ // 热重载会换 ctx 与模块实例,但同一 stateFile 的 flush/recover 世代必须共享。
748
+ slot.ctx = ctx
749
+ slot.providers = providers
750
+ return slot.host
751
+ }
752
+
753
+ function workerOutbox(ctx) {
754
+ return runtimeOutbox(ctx)
755
+ }
756
+
757
+ async function deliverWorkerItem(ctx, entry, item, prompt) {
758
+ const runtime = await recordRuntimeDelivery(entry, item, ctx)
759
+ const ticket = runtime.ticket
760
+ if (!ticket || ticket.status === 'ended') return { ok: false, key: String(item.key || item.number), error: runtime.reason || 'ticket ended' }
761
+ const id = 'worker:' + createHash('sha1').update(JSON.stringify([ticket.id, item.updated_at || '', item.body || ''])).digest('hex').slice(0, 24)
762
+ const host = workerOutbox(ctx)
763
+ await host.enqueue({
764
+ id, ticketId: ticket.id,
765
+ channel: { type: 'worker', repo: entry.repo, number: String(item.number) },
766
+ body: String(prompt || ''),
767
+ })
768
+ if (readState().executorPaused === true) return { ok: true, status: 'queued', paused: true, state: await host.read() }
769
+ const report = await host.flush({ ticketId: ticket.id, limit: 4 })
770
+ const current = report.results.find((result) => result.id === id)
771
+ const persisted = await host.read()
772
+ const messages = Array.isArray(persisted.outbox) ? persisted.outbox : persisted.outbox && persisted.outbox.outbox || []
773
+ const stored = messages.find((message) => message.id === id)
774
+ const ok = current && current.status === 'sent' || stored && stored.status === 'sent'
775
+ return {
776
+ ok: Boolean(ok), key: String(item.key || item.number), ticketId: ticket.id,
777
+ status: current && current.status || stored && stored.status || 'unknown',
778
+ error: current && current.error || (!ok ? 'worker delivery not settled' : null),
779
+ }
780
+ }
781
+
782
+ async function deliverWorkerBatch(ctx, entry, listed, promptForItem) {
783
+ const results = []
784
+ for (const item of listed) {
785
+ try {
786
+ results.push(await deliverWorkerItem(ctx, entry, item, promptForItem(item)))
787
+ } catch (error) {
788
+ results.push({ ok: false, key: String(item.key || item.number), error: String(error && error.message || error) })
789
+ }
790
+ }
791
+ const deliveredItems = listed.filter((item, index) => results[index] && results[index].ok)
792
+ const firstError = results.find((result) => !result.ok)
793
+ return {
794
+ ok: deliveredItems.length > 0,
795
+ results,
796
+ deliveredItems,
797
+ reason: firstError && firstError.error || null,
798
+ }
799
+ }
800
+
801
+ function optionalAdmissionService(ctx, name) {
802
+ // Cordis 的 Context 代理:未 inject 的服务直接读属性会抛;ctx.get() 才是可选服务入口。
803
+ try {
804
+ if (ctx && typeof ctx.get === 'function') {
805
+ const service = ctx.get(name)
806
+ if (service) return service
807
+ }
808
+ } catch {}
809
+ // 测试与普通对象宿主仍允许直接挂属性;Cordis 代理抛错时按未提供处理。
810
+ try { return ctx && ctx[name] } catch { return undefined }
811
+ }
812
+
813
+ async function filterAdmissionBatch(ctx, items, deps = {}) {
814
+ const gate = deps.admissionGate || optionalAdmissionService(ctx, 'admissionGate') || (() => 'accept')
815
+ const assessment = deps.admissionAssessment || optionalAdmissionService(ctx, 'admissionAssessment') || (() => 'accept')
816
+ const accepted = []
817
+ for (const item of items) {
818
+ const result = await evaluateAdmission({ candidate: item, gate, assessment })
819
+ if (result.disposition === 'accept') accepted.push(item)
820
+ }
821
+ return accepted
822
+ }
823
+
824
+ function commitModularState(expectedVersion, mutate) {
825
+ if (typeof mutate !== 'function') throw new TypeError('modular state mutator is required')
826
+ return writeState(readState(), { expectedModularVersion: expectedVersion, modularMutator: mutate })
827
+ }
828
+
365
829
  function writeState(state, options = {}) {
830
+ let lockFd = null
366
831
  try {
367
832
  mkdirSync(stateDir(), { recursive: true })
833
+ // 单写者锁覆盖整个 read-merge-rename:round 的读取与递增顺序由锁决定,
834
+ // 不是两个实例各自拿旧快照后靠时钟猜谁新。
835
+ lockFd = acquireStateWriteLock()
368
836
  // 合并写:调用方手里的 state 可能是很久以前读的快照(宿主重载、两个实例交替写),
369
837
  // 直接整份覆盖会把别人刚建的 watcher 抹掉 —— 真机上丢过两条(一条是用户的)。
370
838
  // 规则:盘上有、内存里没有的条目一律保留;只有墓碑里的 id 才允许消失。
@@ -374,6 +842,28 @@ function writeState(state, options = {}) {
374
842
  // 普通旧快照写入没有这个选项,仍然不能绕过墓碑把已删守复活。
375
843
  for (const id of (Array.isArray(options.revive) ? options.revive : [])) delete tombstones[id]
376
844
  const merged = { ...disk, ...state }
845
+ // 模块化状态不走旧快照覆盖:普通 watcher 写入保留盘上最新值;只有锁内
846
+ // CAS mutator 可以修改 Ticket/Outbox 等字段。
847
+ for (const key of MODULAR_STATE_KEYS) {
848
+ if (disk[key] !== undefined) merged[key] = disk[key]
849
+ else if (!options.modularMutator) delete merged[key]
850
+ }
851
+ if (disk.modularVersion !== undefined) merged.modularVersion = disk.modularVersion
852
+ else if (!options.modularMutator) delete merged.modularVersion
853
+ if (options.modularMutator) {
854
+ const expected = options.expectedModularVersion
855
+ if (!Number.isSafeInteger(expected) || expected < 0 || modularVersionOf(disk) !== expected) {
856
+ const error = new Error(`modular state CAS conflict: expected ${String(expected)}, actual ${modularVersionOf(disk)}`)
857
+ error.code = 'MODULAR_CAS_CONFLICT'
858
+ throw error
859
+ }
860
+ const next = options.modularMutator(disk)
861
+ if (!next || typeof next !== 'object') throw new TypeError('modular state mutator must return an object')
862
+ for (const key of MODULAR_STATE_KEYS) {
863
+ if (Object.hasOwn(next, key)) merged[key] = next[key]
864
+ }
865
+ merged.modularVersion = expected + 1
866
+ }
377
867
  merged.watchers = { ...(disk.watchers || {}) }
378
868
  for (const [id, watcher] of Object.entries(state.watchers || {})) {
379
869
  merged.watchers[id] = mergeWatermark(merged.watchers[id], watcher)
@@ -405,6 +895,8 @@ function writeState(state, options = {}) {
405
895
  if (!existsSync(stateFile() + '.bak')) {
406
896
  try { writeFileSync(stateFile() + '.bak', text) } catch {}
407
897
  }
898
+ lastWriteError = null
899
+ delete merged.writeError
408
900
  return merged
409
901
  } catch (error) {
410
902
  // 写盘失败以前是**静默**的:唤醒已经发出去了,`seen` 却没落盘 → 下一轮重复唤醒,
@@ -418,6 +910,11 @@ function writeState(state, options = {}) {
418
910
  live.writeError = lastWriteError
419
911
  return live
420
912
  } catch { return state /* 兜底:写状态的失败不该让一个 turn 崩掉 */ }
913
+ } finally {
914
+ if (lockFd !== null) {
915
+ try { closeSync(lockFd) } catch {}
916
+ try { unlinkSync(stateFile() + '.lock') } catch {}
917
+ }
421
918
  }
422
919
  }
423
920
 
@@ -556,6 +1053,47 @@ function goalView(ctx, sessionId) {
556
1053
  } catch { return null }
557
1054
  }
558
1055
 
1056
+ // `gh` 单次调用的超时(毫秒)。到时被杀会返回 `code: 'timeout'`,不能当仓库/网络错误退避。
1057
+ const GH_TIMEOUT_MS = 45000
1058
+ // gh 命令超时后的重试间隔(毫秒):网络抖一下,30 秒后再来,别进 30 分钟的指数退避。
1059
+ const GH_TIMEOUT_RETRY_MS = 30000
1060
+
1061
+ /**
1062
+ * 判断一次 gh 调用是不是「超时被杀」,而不是命令本身出错。
1063
+ * `run()` 超时时 resolve({ code: 'timeout' });spawn 失败是 'spawn-error'。
1064
+ * 另兼容 stderr 里带 timeout 字样(gh 有时自己打 `timeout executing gh` 但退出码非 0)。
1065
+ */
1066
+ function isGhTimeout(res) {
1067
+ if (!res) return false
1068
+ if (res.code === 'timeout') return true
1069
+ const text = String(res.stderr || '') + String(res.stdout || '')
1070
+ return /timeout executing|context deadline exceeded|i\/o timeout/i.test(text)
1071
+ }
1072
+
1073
+ /**
1074
+ * gh 超时的统一处理:**不** bumpFailure,只记一句人话 + 短间隔重试。
1075
+ *
1076
+ * 为什么不能复用 `classifyGhError`:它把超时归到 `network` 分类,而 `network` 走
1077
+ * 指数退避 —— 最长 30 分钟。steam++ 一抖,每轮都是 `timeout executing gh`,
1078
+ * 但 GitHub 那边明明有东西;退避半小时正好是用户抱怨的「一抖就长时间不叫」。
1079
+ *
1080
+ * 两个调用点(issue 守的列表失败 / PR 守的列表失败)必须共用:上一版只修了 issue 守,
1081
+ * PR 守仍按 `classifyGhError` 退避到 30 分钟(PR #65 review 实测
1082
+ * `{"consecutiveFailures":1,"nextAt":"…","lastError":"pr poll: timeout executing gh"}`)。
1083
+ *
1084
+ * 返回 `true` 表示「已按超时处理,调用方直接 return」。
1085
+ */
1086
+ function absorbGhTimeout(entry, res) {
1087
+ if (!isGhTimeout(res)) return false
1088
+ entry.lastError = 'gh 命令超时(' + Math.round(GH_TIMEOUT_MS / 1000) + ' 秒)—— 多半是网络或代理卡住,'
1089
+ + Math.round(GH_TIMEOUT_RETRY_MS / 1000) + ' 秒后重试'
1090
+ entry.nextAt = new Date(Date.now() + GH_TIMEOUT_RETRY_MS).toISOString()
1091
+ entry.deferReason = 'timeout'
1092
+ entry.needsReauth = false
1093
+ noteEvent(entry, 'timeout', entry.lastError)
1094
+ return true
1095
+ }
1096
+
559
1097
  /** Environment for every gh call: a panel token wins over the CLI login. */
560
1098
  function ghEnv() {
561
1099
  const s = readSecrets()
@@ -587,6 +1125,79 @@ function agentsService(ctx) {
587
1125
  try { return ctx.agents } catch { return undefined }
588
1126
  }
589
1127
 
1128
+ /**
1129
+ * 查这个会话有没有**正在跑的子任务**。
1130
+ *
1131
+ * 为什么需要它:`decideWake` 只看 `agent.status`,而 `dsh-agent-loop` 的 status
1132
+ * 只反映它自己的 phase(`phase.kind === 'idle' || 'maintenance' ? 'idle' : 'running'`,
1133
+ * 见 `@deepseek-ai/dsh-agent-loop/lib/index.js:555`)。子任务在跑时主 agent 仍是
1134
+ * `idle` —— 于是「主任务在等子任务」这种正忙的状态被判成空闲,唤醒消息直接插进
1135
+ * 正在进行的多子任务工作流里(2026-11-15 用户实测:主任务没在对话、两个子任务在跑,
1136
+ * 通知照发)。
1137
+ *
1138
+ * 判定源与 `dsh-subagent` 的 `listDescendants` 一致(其 `lib/index.js:2380-2435`):
1139
+ * `sessionQuery.observeSession(id)` 的 `projections.values.subagentCatalog`,
1140
+ * 再对每个 child 用 `sessions.get(childId) !== undefined` 判活跃。
1141
+ * 拿不到服务时返回 `{ known: false }` —— 调用方按旧行为继续,不能因为查不了就永远不叫醒。
1142
+ */
1143
+ async function runningSubagents(ctx, sessionId) {
1144
+ const query = ctx && typeof ctx.get === 'function' ? ctx.get('sessionQuery') : undefined
1145
+ const sessions = ctx && typeof ctx.get === 'function' ? ctx.get('sessions') : undefined
1146
+ if (!query || typeof query.observeSession !== 'function') return { known: false, running: 0 }
1147
+ // 判定不了就是判定不了,**不能**返回 known:true / running:0 —— 那等于把所有
1148
+ // 并发子任务当成不存在,唤醒会直接落进它们中间。
1149
+ if (!sessions || typeof sessions.get !== 'function') return { known: false, running: 0 }
1150
+
1151
+ // 与宿主 `listDescendants` 同一语义(dsh-subagent/lib/index.js:2380-2445):
1152
+ // **递归**走每一层 catalog。只 observeSession(root) 只能看到直接 child,
1153
+ // running 的 grandchild 会漏 —— 主任务照样被打扰(2026-11-14T18:31:37Z review 实证 1)。
1154
+ // 用显式栈而不是递归调用,避免深层子代理把调用栈打穿;visited 防环。
1155
+ const visited = new Set([String(sessionId)])
1156
+ let frontier = [String(sessionId)]
1157
+ const running = []
1158
+ let depth = 0
1159
+ const MAX_DEPTH = 16
1160
+ while (frontier.length > 0 && depth < MAX_DEPTH) {
1161
+ const next = []
1162
+ for (const parentId of frontier) {
1163
+ let handle
1164
+ try {
1165
+ handle = await query.observeSession(parentId)
1166
+ const catalog = handle && handle.projections && handle.projections.values
1167
+ ? handle.projections.values.subagentCatalog
1168
+ : undefined
1169
+ if (!Array.isArray(catalog)) continue
1170
+ for (const entry of catalog) {
1171
+ if (!entry || !entry.id) continue
1172
+ const id = String(entry.id)
1173
+ if (visited.has(id)) continue
1174
+ visited.add(id)
1175
+ // `unknown` 行是宿主自己标了「模式不明」的诊断行,不当 child 计数;
1176
+ // 但它的子树仍要展开(宿主也是这么走的)。
1177
+ if (entry.mode !== 'unknown') {
1178
+ let live = false
1179
+ try { live = sessions.get(id) !== undefined } catch { live = false }
1180
+ if (live) running.push(id)
1181
+ }
1182
+ // `external` 的子树不展开(宿主 listDescendants 同样 `children = []`)。
1183
+ if (entry.mode === 'external') continue
1184
+ next.push(id)
1185
+ }
1186
+ } catch {
1187
+ // 单个 catalog 读失败:跳过这一支(宿主记 diagnostic),不要因此误判「没有子任务」。
1188
+ // 但也不能return known:false —— 其它分支还能证明有工作在跑。
1189
+ } finally {
1190
+ try {
1191
+ if (handle && typeof handle[Symbol.dispose] === 'function') handle[Symbol.dispose]()
1192
+ } catch { /* 释放失败不影响本轮判定 */ }
1193
+ }
1194
+ }
1195
+ frontier = next
1196
+ depth += 1
1197
+ }
1198
+ return { known: true, running: running.length, ids: running }
1199
+ }
1200
+
590
1201
  /** gh CLI 可用性探针:5 分钟缓存,别让面板每 5 秒都 spawn 一次 gh。 */
591
1202
  const ghHealthCache = { at: 0, value: null }
592
1203
  // 只在失败路径上调用:确认凭证到底还有没有效(真机上令牌失效时 gh 输出为空)
@@ -755,6 +1366,7 @@ function offlineGhReply(args) {
755
1366
  if (joined.includes('--version')) return 'gh version 2.0.0 (offline)'
756
1367
  if (joined.includes('api -i user')) return 'HTTP/2.0 200 OK' + String.fromCharCode(13, 10) + String.fromCharCode(13, 10)
757
1368
  if (joined.includes('api user')) return 'offline-user'
1369
+ if (joined.includes('/comments') && joined.includes('per_page=100')) return '[]'
758
1370
  if (joined.includes('labels')) return '{}'
759
1371
  const repoMatch = joined.match(new RegExp('repos/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)'))
760
1372
  return JSON.stringify({ full_name: repoMatch ? repoMatch[1] : 'offline/repo', private: false, items: [], total_count: 0 })
@@ -861,7 +1473,9 @@ const wakeBuffers = new Map()
861
1473
  // 只存内存;**未送达不推进水位**,所以宿主重启后下一轮会按原事件重建队列,不会丢。
862
1474
  const WAKE_QUEUE_RETRY_MS = Number(process.env.DSH_SUPERAGENT_WAKE_QUEUE_RETRY_MS) || 5000
863
1475
  const wakeQueues = new Map()
864
- const isBusyWakeResult = (result) => /agent busy|会话正忙/i.test(String(result && result.reason || ''))
1476
+ // `busy: true` 覆盖「主任务空闲但子任务在跑」这类拒绝:它不是投递失败,
1477
+ // 应当排队重试而不是退避(2026-11-14T18:31:37Z review 实证 3)。
1478
+ const isBusyWakeResult = (result) => Boolean(result && result.busy === true) || /agent busy|会话正忙/i.test(String(result && result.reason || ''))
865
1479
 
866
1480
  function wakeQueueCount(sessionId, ctx) {
867
1481
  const queue = wakeQueues.get(sessionId)
@@ -874,27 +1488,50 @@ function scheduleWakeFlush(ctx, sessionId, delay = WAKE_QUEUE_RETRY_MS) {
874
1488
  if (!queue || queue.timer || queue.items.length === 0) return
875
1489
  queue.timer = setTimeout(() => {
876
1490
  queue.timer = null
877
- flushWakeQueue(ctx, sessionId)
1491
+ // 子任务闸要 await 探针;这里不关心单次结果,失败由下一轮重试兜底。
1492
+ flushWakeQueue(ctx, sessionId)?.catch(() => {})
878
1493
  }, delay)
879
1494
  if (queue.timer && typeof queue.timer.unref === 'function') queue.timer.unref()
880
1495
  }
881
1496
 
1497
+ // 不用 async:async 会给每个调用套一层新 Promise,`p1 === p2` 永远不成立,
1498
+ // 而单飞锁的语义正是「后来的调用拿到同一个 Promise」。
882
1499
  function flushWakeQueue(ctx, sessionId) {
883
1500
  const queue = wakeQueues.get(sessionId)
884
1501
  if (!queue || queue.items.length === 0 || (queue.ctx && queue.ctx !== ctx)) return
885
- const item = queue.items[0]
886
- const result = wake(ctx, sessionId, item.text)
887
- if (isBusyWakeResult(result)) {
888
- scheduleWakeFlush(ctx, sessionId)
889
- return
890
- }
891
- // 只有离开队首的这一条才结算:成功记已送达;非 busy 失败交给原有错误/重试逻辑。
892
- queue.items.shift()
893
- for (const cb of item.settled) {
894
- try { cb(result) } catch { /* 单个 watcher 的结算失败不能堵住后面的队列 */ }
895
- }
896
- if (queue.items.length > 0) scheduleWakeFlush(ctx, sessionId, 0)
897
- else wakeQueues.delete(sessionId)
1502
+ // 单飞:同一个队列同时只能有一次 flush 在跑。
1503
+ // 不加锁时,timer 触发的 flush 与 poll 触发的 flush 会同时挂在 `await runningSubagents()`
1504
+ // 上,两边都读到同一个 `queue.items[0]`,随后各自 wake / shift / 执行 settled ——
1505
+ // 一条消息发两遍、结算两遍(2026-11-14T19:08:48Z review 实证:sent=2、queued=0、
1506
+ // successfulSettlements=2,期望 1/0/1)。后来的调用直接复用前一个 Promise,
1507
+ // 等它结束后再按队列现状决定要不要继续。
1508
+ if (queue.flushing) return queue.flushing
1509
+ queue.flushing = (async () => {
1510
+ try {
1511
+ const item = queue.items[0]
1512
+ if (!item) return
1513
+ // 出队前重新探一次子任务:消息已经排在队列里,**不代表**现在可以插话 ——
1514
+ // 排队时主任务空闲,flush 时子任务可能已经起来了
1515
+ // (2026-11-14T18:31:37Z review 实证 2:已排队的 flush 绕过了子任务闸,
1516
+ // 队列清空 + 水位推进,那条评论就再也送不到了)。
1517
+ const subagents = await runningSubagents(ctx, sessionId)
1518
+ const result = wake(ctx, sessionId, item.text, subagents)
1519
+ if (isBusyWakeResult(result)) {
1520
+ scheduleWakeFlush(ctx, sessionId)
1521
+ return
1522
+ }
1523
+ // 只有离开队首的这一条才结算:成功记已送达;非 busy 失败交给原有错误/重试逻辑。
1524
+ queue.items.shift()
1525
+ for (const cb of item.settled) {
1526
+ try { cb(result) } catch { /* 单个 watcher 的结算失败不能堵住后面的队列 */ }
1527
+ }
1528
+ if (queue.items.length > 0) scheduleWakeFlush(ctx, sessionId, 0)
1529
+ else wakeQueues.delete(sessionId)
1530
+ } finally {
1531
+ queue.flushing = null
1532
+ }
1533
+ })()
1534
+ return queue.flushing
898
1535
  }
899
1536
 
900
1537
  function enqueueWake(ctx, sessionId, text, settled, key) {
@@ -926,7 +1563,9 @@ function clearWakeQueues(ctx) {
926
1563
 
927
1564
  function wakeMerged(ctx, sessionId, text, onSettled, queueKey = '', brandName = DEFAULT_BRAND_NAME) {
928
1565
  // 同一事件已在队列里时不重复入队;先尝试 flush,空闲时会立即把旧队列送完。
929
- flushWakeQueue(ctx, sessionId)
1566
+ // 不 await:flush 要等子任务探针,而这里必须同步返回「是否已入队」——
1567
+ // `hasQueuedWake` 读的是同一份队列,fire-and-forget 不会改变判断结果。
1568
+ flushWakeQueue(ctx, sessionId)?.catch(() => {})
930
1569
  if (hasQueuedWake(sessionId, queueKey, ctx)) {
931
1570
  const result = { ok: false, queued: true, reason: '会话正忙(agent busy),该事件已在队列中,不重复入队' }
932
1571
  if (onSettled) onSettled(result)
@@ -937,13 +1576,15 @@ function wakeMerged(ctx, sessionId, text, onSettled, queueKey = '', brandName =
937
1576
  buf.parts.push(text)
938
1577
  if (onSettled) buf.settled.push(onSettled)
939
1578
  if (buf.timer) return { ok: true, merged: true, pending: buf.parts.length }
940
- buf.timer = setTimeout(() => {
1579
+ buf.timer = setTimeout(async () => {
941
1580
  wakeBuffers.delete(sessionId)
942
1581
  let result = { ok: false, reason: '合并后没有内容可发(这几条都已被处理过)—— 不用管,下一轮会重新判断' }
943
1582
  try {
944
1583
  const merged = mergeWakeTexts(buf.parts, { brandName })
945
1584
  if (merged) {
946
- result = wake(ctx, sessionId, merged)
1585
+ // 合并窗口(WAKE_WINDOW_MS)以内子任务可能已经起来了 —— 发出前再确认一次,
1586
+ // 别让「主任务空闲、子任务在跑」这种状态被判成可以插话。
1587
+ result = wake(ctx, sessionId, merged, await runningSubagents(ctx, sessionId))
947
1588
  if (isBusyWakeResult(result)) result = enqueueWake(ctx, sessionId, merged, buf.settled, queueKey)
948
1589
  }
949
1590
  } catch (error) {
@@ -959,12 +1600,49 @@ function wakeMerged(ctx, sessionId, text, onSettled, queueKey = '', brandName =
959
1600
  return { ok: true, merged: true, pending: buf.parts.length }
960
1601
  }
961
1602
 
962
- function wake(ctx, sessionId, text) {
1603
+ function outboxMarker(id) {
1604
+ const safe = String(id || '').replace(/[^A-Za-z0-9:_.-]/g, '')
1605
+ if (!safe) throw new TypeError('outbox marker id is required')
1606
+ return `<!-- dsh-outbox:${safe} -->`
1607
+ }
1608
+
1609
+ function withOutboxMarker(body, id) {
1610
+ return String(body || '') + '\n\n' + outboxMarker(id)
1611
+ }
1612
+
1613
+ function hasOutboxMarker(body, id) {
1614
+ return String(body || '').includes(outboxMarker(id))
1615
+ }
1616
+
1617
+ async function findOutboxComment(entry, number, kind, id, deps = {}) {
1618
+ if (entry.provider === 'gitee') {
1619
+ const result = await fetchGiteeItemComments({
1620
+ repo: entry.repo, number, kind,
1621
+ token: String(readSecrets().giteeToken || ''), fetchImpl: deps.fetchImpl,
1622
+ })
1623
+ if (!result.ok) return { ok: false, error: String(result.error || result.status || 'comment readback failed') }
1624
+ if (result.truncated) return { ok: false, error: 'comment readback truncated; refusing to risk a duplicate outbox comment' }
1625
+ return { ok: true, found: (result.comments || []).some((comment) => hasOutboxMarker(comment.body, id)) }
1626
+ }
1627
+ const runImpl = deps.run || run
1628
+ for (let page = 1; page <= 5; page += 1) {
1629
+ const result = await runImpl('gh', ['api', `repos/${entry.repo}/issues/${number}/comments?per_page=100&page=${page}&sort=created&direction=desc`], { timeoutMs: 20000, env: ghEnv() })
1630
+ if (result.code !== 0) return { ok: false, error: redact(result.stderr || result.stdout || 'comment readback failed').slice(0, 200) }
1631
+ let comments
1632
+ try { comments = JSON.parse(String(result.stdout || '[]')) } catch { return { ok: false, error: 'comment readback is not valid JSON' } }
1633
+ if (!Array.isArray(comments)) return { ok: false, error: 'comment readback is not an array' }
1634
+ if (comments.some((comment) => hasOutboxMarker(comment.body, id))) return { ok: true, found: true }
1635
+ if (comments.length < 100) return { ok: true, found: false }
1636
+ }
1637
+ return { ok: false, error: 'comment readback truncated; refusing to risk a duplicate outbox comment' }
1638
+ }
1639
+
1640
+ function wake(ctx, sessionId, text, subagents = null) {
963
1641
  const agents = agentsService(ctx)
964
1642
  const agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : undefined
965
1643
  if (!agent) return { ok: false, reason: '这个会话已经不在宿主里了 —— 宿主重启过,或这个会话被关掉了;面板里刷新一下,还在就重建这条主理鱼' }
966
1644
 
967
- const allowed = decideWake(agent.status)
1645
+ const allowed = decideWake(agent.status, subagents)
968
1646
  if (!allowed.ok) return allowed
969
1647
 
970
1648
  // 审核 M1:这是**唯一必进模型上下文**的出口,以前一个字符都不脱敏 ——
@@ -1019,8 +1697,20 @@ function hardenSecretsFile(file) {
1019
1697
  return secretsHardened
1020
1698
  }
1021
1699
  try {
1022
- const user = os.userInfo().username
1023
- execFileSync('icacls', [file, '/inheritance:r', '/grant:r', user + ':F'], { stdio: 'ignore', timeout: 15000 })
1700
+ const systemRoot = process.env.SystemRoot || process.env.windir
1701
+ if (!systemRoot) throw new Error('SystemRoot 未设置')
1702
+ // Git Bash 的 /usr/bin/whoami 不支持 /user;明确调用 Windows 版本并只解析 ASCII SID。
1703
+ const whoami = join(systemRoot, 'System32', 'whoami.exe')
1704
+ const identity = execFileSync(whoami, ['/user', '/fo', 'csv', '/nh'], { encoding: 'buffer', timeout: 15000 }).toString('latin1')
1705
+ const userSid = identity.match(/\bS-\d+(?:-\d+)+\b/i)?.[0]
1706
+ if (!userSid) throw new Error('无法读取当前用户 SID')
1707
+ // /grant:r 只替换指定主体的 ACE,不会清掉其他显式 ACE。普通组用固定 SID,
1708
+ // 同时删除 grant 与 deny,避免本地化名称和预置 deny 让 token 继续暴露或本人也读不到。
1709
+ const ordinaryGroups = ['*S-1-5-11', '*S-1-5-32-545', '*S-1-1-0']
1710
+ execFileSync('icacls', [
1711
+ file, '/inheritance:r', '/grant:r', `*${userSid}:F`,
1712
+ '/remove:g', ...ordinaryGroups, '/remove:d', ...ordinaryGroups,
1713
+ ], { stdio: 'ignore', timeout: 15000 })
1024
1714
  secretsHardened = 'win32-acl'
1025
1715
  } catch {
1026
1716
  secretsHardened = 'failed'
@@ -1235,6 +1925,28 @@ async function viewerLogin(provider = 'github') {
1235
1925
  return login || cached.login
1236
1926
  }
1237
1927
 
1928
+ /** 取单个 PR 的最新评论 id:watch_pr_ack 不传 commentId 时,用它把水位推到「最新」。 */
1929
+ async function fetchLatestPrCommentId(repo, number, provider, token = '') {
1930
+ if (provider === 'gitee') {
1931
+ const res = await fetchGiteePrComments({ repo, token, number, perPage: 1 })
1932
+ if (!res.ok) return { ok: false, error: res.error || ('status ' + res.status) }
1933
+ const first = (res.comments || [])[0]
1934
+ return { ok: true, id: first ? Number(first.id) : null }
1935
+ }
1936
+ // GitHub:REST 单 PR 评论,per_page=1 + 按创建时间倒序 → [0] 就是最新。
1937
+ // 不用 GraphQL 是因为这里只要一个 id,REST 更短也更不容易被 schema 变更打到。
1938
+ const res = await run('gh', ['api', `repos/${repo}/issues/${number}/comments?per_page=1&sort=created&direction=desc`], { timeoutMs: 45000, env: ghEnv() })
1939
+ if (res.code !== 0) {
1940
+ const msg = String(res.stderr || res.stdout || '').trim().slice(0, 200)
1941
+ return { ok: false, error: msg || ('gh exit ' + res.code) }
1942
+ }
1943
+ let comments
1944
+ try { comments = JSON.parse(String(res.stdout || '')) } catch { return { ok: false, error: '返回内容不是合法 JSON' } }
1945
+ if (!Array.isArray(comments)) return { ok: false, error: '评论列表不是数组' }
1946
+ const first = comments[0]
1947
+ return { ok: true, id: first ? Number(first.id) : null }
1948
+ }
1949
+
1238
1950
  async function fetchLastComments(repo, items, maxItems = 3, options = {}) {
1239
1951
  // Gitee:没有 GraphQL 批量,逐条 REST。条数本来就只取前 3 条,代价可接受。
1240
1952
  // Gitee 的条目不一定带 comments 计数,所以这里不按计数过滤,直接取前几条。
@@ -1283,15 +1995,190 @@ async function fetchLastComments(repo, items, maxItems = 3, options = {}) {
1283
1995
  // 兜底:逐条 REST(GraphQL 不可用时仍要能工作)
1284
1996
  await Promise.all(targets.map(async (item) => {
1285
1997
  try {
1286
- const res = await run('gh', ['api', `repos/${repo}/issues/${item.number}/comments?per_page=1&sort=created&direction=desc`,
1287
- '--jq', '.[0] | {login: .user.login, at: .created_at}'], { timeoutMs: 12000, env: ghEnv() })
1998
+ const res = await run('gh', lastCommentArgs(repo, item.number), { timeoutMs: 12000, env: ghEnv() })
1288
1999
  if (res.code !== 0) return
1289
- const parsed = JSON.parse(res.stdout)
1290
- if (parsed && parsed.login) mark(item, { login: parsed.login, at: parsed.at })
2000
+ const parsed = parseLastComment(res.stdout)
2001
+ if (parsed) mark(item, parsed)
1291
2002
  } catch { /* 少一行信息,不阻断唤醒 */ }
1292
2003
  }))
1293
2004
  }
1294
2005
 
2006
+ /**
2007
+ * onlyNewComments 的严格评论探针。
2008
+ *
2009
+ * 与 fetchLastComments 的展示用途不同:这里必须区分「确实没有评论」和「没查成功」。
2010
+ * 每个条目的结果是 { ok, at };at 为 null 只表示两类目标接口都成功且都没有评论。
2011
+ */
2012
+ function validCommentTime(value) {
2013
+ const text = String(value || '')
2014
+ return text && Number.isFinite(Date.parse(text)) ? text : null
2015
+ }
2016
+
2017
+ function newestCommentTime(times) {
2018
+ const valid = times.map(validCommentTime).filter(Boolean)
2019
+ if (valid.length === 0) return null
2020
+ return valid.reduce((latest, at) => Date.parse(at) > Date.parse(latest) ? at : latest)
2021
+ }
2022
+
2023
+ function combineCommentResults(...results) {
2024
+ if (results.some((result) => !result || result.ok !== true)) return { ok: false, at: null }
2025
+ const at = newestCommentTime(results.map((result) => result.at))
2026
+ const newest = results.filter((result) => result.at === at && result.id !== undefined && result.id !== null).at(-1)
2027
+ const counts = results.map((result) => Number(result.count)).filter((count) => Number.isFinite(count) && count >= 0)
2028
+ return {
2029
+ ok: true,
2030
+ at,
2031
+ ...(newest ? { id: newest.id } : {}),
2032
+ ...(counts.length > 0 ? { count: counts.reduce((sum, count) => sum + count, 0) } : {}),
2033
+ channels: results.map((result) => ({ at: result.at || null, count: result.count ?? null })),
2034
+ }
2035
+ }
2036
+
2037
+ async function githubDiscussionRest(repo, item, ghRun) {
2038
+ try {
2039
+ const res = await ghRun('gh', lastCommentArgs(repo, item.number), { timeoutMs: 12000, env: ghEnv() })
2040
+ if (res.code !== 0) return { ok: false, at: null }
2041
+ const text = String(res.stdout || '')
2042
+ const parsed = parseLastComment(text)
2043
+ if (parsed) {
2044
+ const at = validCommentTime(parsed.at)
2045
+ return at ? { ok: true, at } : { ok: false, at: null }
2046
+ }
2047
+ // lastCommentArgs 的 --jq 对空页输出 null;只有这种输出才代表真的无评论。
2048
+ const lines = text.split(/\r\n|\n|\r/).map((line) => line.trim()).filter(Boolean)
2049
+ if (lines.length > 0 && lines.every((line) => line === 'null')) return { ok: true, at: null }
2050
+ // 删除账号的评论 login 可能为空,parseLastComment 为展示会省略;过滤仍可使用它的时间。
2051
+ const last = lines.at(-1)
2052
+ try {
2053
+ const raw = JSON.parse(last)
2054
+ const at = validCommentTime(raw && raw.at)
2055
+ return at ? { ok: true, at } : { ok: false, at: null }
2056
+ } catch {
2057
+ return { ok: false, at: null }
2058
+ }
2059
+ } catch {
2060
+ return { ok: false, at: null }
2061
+ }
2062
+ }
2063
+
2064
+ async function githubDiscussionTimes(repo, items, ghRun) {
2065
+ const out = new Map()
2066
+ const [owner, name] = String(repo).split('/')
2067
+ for (let offset = 0; offset < items.length; offset += 10) {
2068
+ const targets = items.slice(offset, offset + 10)
2069
+ const fallback = new Set(targets)
2070
+ try {
2071
+ const query = buildCommentBatchQuery(targets.length)
2072
+ const args = ['api', 'graphql', '-f', 'query=' + query, '-F', 'owner=' + owner, '-F', 'name=' + name]
2073
+ targets.forEach((item, i) => args.push('-F', 'n' + i + '=' + item.number))
2074
+ const res = await ghRun('gh', args, { timeoutMs: 15000, env: ghEnv() })
2075
+ if (res.code !== 0) throw new Error('graphql failed')
2076
+ const payload = JSON.parse(String(res.stdout || '{}'))
2077
+ const repository = payload && payload.data && payload.data.repository
2078
+ if (!repository || typeof repository !== 'object') throw new Error('graphql repository missing')
2079
+ // 复用展示链的批量 parser;同时直接检查原始 alias,以区分空评论与缺失/失败 alias。
2080
+ const parsed = parseCommentBatch(payload)
2081
+ targets.forEach((item, i) => {
2082
+ const raw = repository['i' + i]
2083
+ const nodes = raw && raw.comments && raw.comments.nodes
2084
+ if (!raw || !Array.isArray(nodes)) return
2085
+ if (nodes.length === 0) {
2086
+ out.set(String(item.number), { ok: true, at: null, count: 0 })
2087
+ fallback.delete(item)
2088
+ return
2089
+ }
2090
+ const info = parsed[String(item.number)]
2091
+ const rawLast = nodes[nodes.length - 1]
2092
+ const at = validCommentTime(info && info.at ? info.at : rawLast && rawLast.createdAt)
2093
+ if (!at) return
2094
+ out.set(String(item.number), {
2095
+ ok: true,
2096
+ at,
2097
+ ...(rawLast && rawLast.databaseId ? { id: rawLast.databaseId } : {}),
2098
+ ...(Number.isFinite(Number(raw.comments && raw.comments.totalCount)) ? { count: Number(raw.comments.totalCount) } : {}),
2099
+ })
2100
+ fallback.delete(item)
2101
+ })
2102
+ } catch { /* 整批失败时下面逐条 REST 重试 */ }
2103
+ await Promise.all([...fallback].map(async (item) => {
2104
+ out.set(String(item.number), await githubDiscussionRest(repo, item, ghRun))
2105
+ }))
2106
+ }
2107
+ return out
2108
+ }
2109
+
2110
+ async function githubReviewTime(repo, item, ghRun) {
2111
+ try {
2112
+ // PR 行内 review comments 不在 issue discussion GraphQL 里,必须另查 pulls 端点。
2113
+ // 与 issue comments 不同,这个端点支持 sort=created&direction=desc。
2114
+ const path = `repos/${repo}/pulls/${item.number}/comments?per_page=100&sort=created&direction=desc`
2115
+ const res = await ghRun('gh', ['api', path], { timeoutMs: 12000, env: ghEnv() })
2116
+ if (res.code !== 0) return { ok: false, at: null }
2117
+ const data = JSON.parse(String(res.stdout || ''))
2118
+ if (!Array.isArray(data)) return { ok: false, at: null }
2119
+ if (data.length === 0) return { ok: true, at: null, count: 0 }
2120
+ const times = data.map((comment) => comment && comment.created_at)
2121
+ if (times.some((at) => !validCommentTime(at))) return { ok: false, at: null }
2122
+ return { ok: true, at: newestCommentTime(times), count: data.length, id: data[0] && data[0].id }
2123
+ } catch {
2124
+ return { ok: false, at: null }
2125
+ }
2126
+ }
2127
+
2128
+ async function giteeCommentTime(entry, item, fetchImpl) {
2129
+ try {
2130
+ const token = String(readSecrets().giteeToken || '')
2131
+ const discussion = await fetchGiteeLastComment({
2132
+ repo: entry.repo, token, item, fetchImpl, withStatus: true,
2133
+ })
2134
+ if (!discussion.ok || discussion.truncated) return { ok: false, at: null }
2135
+ const discussionAt = discussion.comment ? validCommentTime(discussion.comment.at) : null
2136
+ if (discussion.comment && !discussionAt) return { ok: false, at: null }
2137
+ if (!item.pull_request) return {
2138
+ ok: true, at: discussionAt, count: Number(item.comments) || 0,
2139
+ channels: [{ at: discussionAt, count: Number(item.comments) || 0 }],
2140
+ }
2141
+ const review = await fetchGiteePrComments({
2142
+ repo: entry.repo, token, number: item.number, perPage: 100, fetchImpl,
2143
+ })
2144
+ if (!review.ok) return { ok: false, at: null }
2145
+ const reviewTimes = (review.comments || []).map((comment) => comment.createdAt)
2146
+ if (reviewTimes.some((at) => !validCommentTime(at))) return { ok: false, at: null }
2147
+ return {
2148
+ ok: true,
2149
+ at: newestCommentTime([discussionAt, ...reviewTimes]),
2150
+ count: (Number(item.comments) || 0) + (review.comments || []).length,
2151
+ id: (review.comments || []).reduce((max, comment) => Math.max(max, Number(comment.id) || 0), 0) || undefined,
2152
+ channels: [
2153
+ { at: discussionAt, count: Number(item.comments) || 0 },
2154
+ { at: newestCommentTime(reviewTimes), count: (review.comments || []).length },
2155
+ ],
2156
+ }
2157
+ } catch {
2158
+ return { ok: false, at: null }
2159
+ }
2160
+ }
2161
+
2162
+ async function collectCommentTimes(entry, items, deps = {}) {
2163
+ const out = new Map()
2164
+ if (entry.provider === 'gitee') {
2165
+ const fetchImpl = typeof deps.fetchImpl === 'function' ? deps.fetchImpl : globalThis.fetch
2166
+ await Promise.all(items.map(async (item) => {
2167
+ out.set(String(item.number), await giteeCommentTime(entry, item, fetchImpl))
2168
+ }))
2169
+ return out
2170
+ }
2171
+ const ghRun = typeof deps.ghRun === 'function' ? deps.ghRun : run
2172
+ const discussions = await githubDiscussionTimes(entry.repo, items, ghRun)
2173
+ await Promise.all(items.map(async (item) => {
2174
+ const rawDiscussion = discussions.get(String(item.number)) || { ok: false, at: null }
2175
+ const discussion = { ...rawDiscussion, count: rawDiscussion.count ?? (Number(item.comments) || 0) }
2176
+ const review = item.pull_request ? await githubReviewTime(entry.repo, item, ghRun) : { ok: true, at: null }
2177
+ out.set(String(item.number), combineCommentResults(discussion, review))
2178
+ }))
2179
+ return out
2180
+ }
2181
+
1295
2182
  async function pollOnce(ctx, entry, baseMs, brand = null) {
1296
2183
  // 活跃时段要**在拉 API 之前**判断:以前放在后面,夜里照样每 N 秒打一次 GitHub,纯浪费。
1297
2184
  // 不在时段内就把下一次轮询安排到"开门那一刻",攒着的条目不会多等一个周期。
@@ -1310,7 +2197,9 @@ async function pollOnce(ctx, entry, baseMs, brand = null) {
1310
2197
  // 没有 ETag,就用 `since` 只取「上次水位之后更新过」的条目 —— 省的是每轮的解析与带宽。
1311
2198
  // 安全边际 30 分钟:宁可多读一轮,也不能因为时钟偏差漏掉一条。首次轮询没有水位,仍然全量。
1312
2199
  const sinceIso = (() => {
1313
- const base = entry.cursor || entry.lastPoll
2200
+ // onlyNewComments 首次/失败重试不能拿 lastPoll 当水位:评论探针失败时 lastPoll 仍会前进,
2201
+ // 但那条旧 updated_at 的条目下一轮仍必须回到候选集。普通模式保持原 since 语义。
2202
+ const base = (entry.filters && entry.filters.onlyNewComments ? null : entry.lastPoll)
1314
2203
  if (!base) return ''
1315
2204
  const t = Date.parse(base)
1316
2205
  if (!Number.isFinite(t)) return ''
@@ -1373,6 +2262,8 @@ async function pollOnce(ctx, entry, baseMs, brand = null) {
1373
2262
  const res = await run('gh', args, { timeoutMs: 45000, env: ghEnv() })
1374
2263
  entry.lastPoll = new Date().toISOString()
1375
2264
  if (res.code !== 0) {
2265
+ // gh 超时(网络/代理卡住):不算「仓库有问题」,也不该退避到 30 分钟。
2266
+ if (absorbGhTimeout(entry, res)) return
1376
2267
  // gh 把 304 当失败(非 2xx 就 exit 1):这不是错误,是「条件请求命中」
1377
2268
  if (/HTTP 304|304 Not Modified|not modified/i.test(String(res.stderr || '') + String(res.stdout || ''))) {
1378
2269
  settleNotModified(entry)
@@ -1456,20 +2347,93 @@ async function pollOnce(ctx, entry, baseMs, brand = null) {
1456
2347
  * 抽出来是为了让 GitHub 与 Gitee 共用同一套判定 —— 两家只有「怎么拿数据」不同,
1457
2348
  * 「要不要叫醒、叫醒说什么、水位怎么走」必须完全一致,否则同一条 bug 要修两遍。
1458
2349
  */
1459
- async function pollWithItems(ctx, entry, baseMs, parsed, brand = null) {
2350
+ function applyV2(entry, next) {
2351
+ return Object.assign(entry, next)
2352
+ }
2353
+
2354
+ function syncPrCommentsProjection(entry, openNumbers = null) {
2355
+ const allowed = openNumbers ? new Set(openNumbers.map(String)) : null
2356
+ const previous = entry.seenComments && typeof entry.seenComments === 'object' ? entry.seenComments : {}
2357
+ const out = {}
2358
+ for (const [key, row] of Object.entries(entry.obs || {})) {
2359
+ if (!key.startsWith('pr:')) continue
2360
+ const number = key.slice(3).split('/')[0]
2361
+ if (allowed && !allowed.has(number)) continue
2362
+ const cursor = Number(row.handled && row.handled.cursor || row.delivered && row.delivered.cursor || row.cursor)
2363
+ if (Number.isFinite(cursor) && cursor > 0) out[number] = Math.max(Number(out[number]) || 0, cursor)
2364
+ }
2365
+ for (const [number, value] of Object.entries(previous)) {
2366
+ if (allowed && !allowed.has(number)) continue
2367
+ if (out[number] === undefined) out[number] = Number(value) || 0
2368
+ }
2369
+ entry.seenComments = out
2370
+ }
2371
+
2372
+ function prepareV2Poll(entry, items, ackLabel, { allowRetry = true } = {}) {
2373
+ for (const item of items) {
2374
+ const key = issueKey(item)
2375
+ const row = entry.obs && entry.obs[key]
2376
+ const cursor = item.__v2Cursor || issueCursor(item, { ackLabel })
2377
+ if (row && row.legacy) {
2378
+ const seenAt = Date.parse(String(entry.seen && entry.seen[item.number] || ''))
2379
+ const itemAt = Date.parse(String(item.updated_at || ''))
2380
+ const changedAfterSeen = Number.isFinite(seenAt) && Number.isFinite(itemAt) && itemAt > seenAt
2381
+ applyV2(entry, observeV2(entry, key, cursor, { round: entry.round + 1 }))
2382
+ if (changedAfterSeen) {
2383
+ entry.obs = { ...entry.obs, [key]: { ...entry.obs[key], undelivered: true } }
2384
+ }
2385
+ } else if (!row && entry.v1Migrated && entry.cursor) {
2386
+ const floor = Date.parse(String(entry.cursor))
2387
+ const itemAt = Date.parse(String(item.updated_at || ''))
2388
+ if (Number.isFinite(floor) && Number.isFinite(itemAt) && itemAt <= floor) {
2389
+ applyV2(entry, observeV2(entry, key, cursor, { round: entry.round + 1 }))
2390
+ }
2391
+ }
2392
+ }
2393
+ entry.v1Migrated = false
2394
+ const records = items.map((item) => ({
2395
+ key: issueKey(item),
2396
+ cursor: item.__v2Cursor || issueCursor(item, { ackLabel }),
2397
+ item,
2398
+ }))
2399
+ const decision = decideWatermark({
2400
+ items: records,
2401
+ obs: entry.obs,
2402
+ now: Date.now(),
2403
+ cooldownMs: Number(entry.cooldownMs) || DEFAULT_COOLDOWN_MS,
2404
+ batchLimit: Math.max(1, Number(entry.batchLimit) || 5),
2405
+ wakeTimes: entry.wakeTimes,
2406
+ maxWakesPerHour: entry.maxWakesPerHour,
2407
+ })
2408
+ const candidates = allowRetry ? decision.candidates : decision.fresh
2409
+ return { records, decision, fresh: candidates.map((record) => record.item) }
2410
+ }
2411
+
2412
+ function commitV2Listed(entry, prepared, listed) {
2413
+ if (!prepared) return
2414
+ const selected = new Set(listed)
2415
+ const records = prepared.records.filter((record) => selected.has(record.item))
2416
+ const settled = commitDeliveryReceipt({
2417
+ state: entry,
2418
+ listed: records,
2419
+ receipt: { ok: true, deliveredKeys: records.map((record) => record.key) },
2420
+ })
2421
+ applyV2(entry, settled.state)
2422
+ }
2423
+
2424
+ async function pollWithItems(ctx, entry, baseMs, parsed, brand = null, deps = {}) {
2425
+ Object.assign(entry, migrateV1Watermark(entry))
2426
+ const wakeFn = typeof deps.wake === 'function' ? deps.wake : wakeMerged
1460
2427
  const pendingEtag = parsed.etag
2428
+ let commentProbeFailed = false
1461
2429
  const commitEtag = () => { if (pendingEtag) entry.etag = pendingEtag }
1462
2430
  let items
1463
2431
  try {
1464
2432
  items = JSON.parse(parsed.body)
1465
2433
  } catch {
1466
- // 空/坏内容:先看凭证,再谈代理 —— 真机上令牌失效时 gh 输出为空,
1467
- // 而原来的文案一律怪「代理干扰」,客户会去查一个不存在的代理。
1468
2434
  const authText = await ghAuthStatusText()
1469
2435
  const diag = diagnoseBadBody({ bodyText: parsed.body, authStatusText: authText })
1470
2436
  if (diag && diag.kind === 'auth') entry.needsReauth = true
1471
- // 兜底不再默认「可能是代理干扰」:那会把客户往网络上游带。
1472
- // 现在只有确诊是网关页才说代理;其余情况指向 watch_doctor 与本仓库 issue。
1473
2437
  setEntryError(entry, (diag ? diag.hint : '(返回内容不是合法 JSON:先跑 watch_doctor;确认不是凭证问题就带上这段提 issue)') + ' —— 已按退避自动重试')
1474
2438
  bumpFailure(entry, baseMs)
1475
2439
  if (diag && diag.kind === 'auth') {
@@ -1484,13 +2448,8 @@ async function pollWithItems(ctx, entry, baseMs, parsed, brand = null) {
1484
2448
  entry.needsReauth = false
1485
2449
  entry.consecutiveFailures = 0
1486
2450
  entry.nextAt = null
1487
- // 触发要有许可:过滤器不通过的条目根本不进候选集,也不写 seen 水位
1488
- // 记忆要有遗忘:seen 只增不减会问成几 MB 的字典
1489
- entry.seen = pruneSeen(entry.seen)
1490
2451
  const ackLabel = entry.ackLabel || defaultAckLabel(entry.provider, brand && brand.defaultAckLabels)
1491
- // 幂等痕迹留在 GitHub 上:带 ack 标签的条目直接跳过(换机器、删状态都不会重报)
1492
- const considered = []
1493
- // 每轮重置:这行要被读成「本轮跳过多少」,累计值会越滚越大、误导客户
2452
+ let considered = []
1494
2453
  entry.filterCounts = {}
1495
2454
  for (const item of items) {
1496
2455
  if (hasAckLabel(item, ackLabel)) {
@@ -1506,39 +2465,51 @@ async function pollWithItems(ctx, entry, baseMs, parsed, brand = null) {
1506
2465
  }
1507
2466
  considered.push(item)
1508
2467
  }
1509
- // Gitee 没有 state_reason:用上一轮记下的状态自己判「重新打开」(GitHub 有原生字段,不覆盖)
2468
+ if (entry.filters && entry.filters.onlyNewComments === true && considered.length > 0) {
2469
+ const commentTimes = await collectCommentTimes(entry, considered, deps)
2470
+ const withNewComments = []
2471
+ for (const item of considered) {
2472
+ const key = String(item.number)
2473
+ const result = commentTimes.get(key) || { ok: false, at: null }
2474
+ if (!result.ok) {
2475
+ commentProbeFailed = true
2476
+ entry.filterCounts = countReasons(entry.filterCounts, '评论获取失败')
2477
+ entry.filteredLog = pushFiltered(entry.filteredLog, { at: entry.lastPoll, number: item.number, title: String(item.title || '').slice(0, 80), reason: '评论获取失败' })
2478
+ continue
2479
+ }
2480
+ if (!result.at) {
2481
+ entry.filterCounts = countReasons(entry.filterCounts, '无新评论')
2482
+ entry.filteredLog = pushFiltered(entry.filteredLog, { at: entry.lastPoll, number: item.number, title: String(item.title || '').slice(0, 80), reason: '无新评论' })
2483
+ continue
2484
+ }
2485
+ withNewComments.push({
2486
+ ...item,
2487
+ updated_at: result.at,
2488
+ __v2Cursor: 'c:' + createHash('sha256').update(JSON.stringify(result.channels || [{ at: result.at, count: result.count ?? item.comments ?? null }])).digest('hex').slice(0, 20),
2489
+ })
2490
+ }
2491
+ considered = withNewComments
2492
+ }
1510
2493
  if (entry.provider === 'gitee') {
1511
2494
  entry.lastStates = markGiteeReopened(items, entry.lastStates || {})
1512
2495
  }
1513
- // 记住最近一条"被重新打开"的 issue:这是最该被看见的信号。
1514
- // **必须放在 markGiteeReopened 之后** —— 以前写在前面,Gitee 判出来的 reopened 那一轮已经算完,
1515
- // 下一轮 lastStates 已是 open,永远不再触发(T8 审计发现)。
1516
2496
  const reopened = items.find((item) => (item.state_reason || '') === 'reopened')
1517
- // 以前只写不清:一条 issue 重新打开过一次,面板就永远挂着「被重新打开」。
1518
- // 这一页里已经看不到它(或它又关了)就清掉 —— 它描述的是「最近一次轮询的事实」。
1519
2497
  if (reopened) entry.lastReopened = reopened.number
1520
2498
  else if (entry.lastReopened && !items.some((item) => String(item.number) === String(entry.lastReopened))) {
1521
2499
  entry.lastReopened = null
1522
2500
  }
1523
- const { fresh, absorbed } = partitionItems(considered, entry, { cooldownMs: Number(entry.cooldownMs) || DEFAULT_COOLDOWN_MS })
1524
-
1525
- if (absorbed.length > 0) {
1526
- entry.seen = advanceSeen(entry.seen, absorbed)
1527
- entry.lastAbsorbed = absorbed.length
1528
- // 记下来才能回答「这条为什么没叫醒我」—— 以前只能说「被吸收/仅观察/或早就有」三合一
1529
- entry.absorbedLog = pushAbsorbed(entry.absorbedLog, absorbed, entry.lastPoll)
1530
- const newestAbsorbed = newestUpdatedAt(absorbed)
1531
- if (!entry.cursor || Date.parse(newestAbsorbed) > Date.parse(entry.cursor)) entry.cursor = newestAbsorbed
1532
- }
2501
+ const v2Prepared = prepareV2Poll(entry, considered, ackLabel, {
2502
+ allowRetry: !(entry.filters && entry.filters.onlyNewComments),
2503
+ })
2504
+ const fresh = v2Prepared.fresh
1533
2505
  if (fresh.length === 0) {
1534
- // 这一轮没有新增:上一轮的说法(比如「仅观察:本会唤醒 4 条」)已经过期了
1535
2506
  entry.lastDeferred = null
1536
- // 没有待办就不会有「攒着」的问题,可以安全前移
2507
+ entry.deferReason = null
1537
2508
  commitEtag()
2509
+ if (commentProbeFailed) delete entry.etag
1538
2510
  return
1539
2511
  }
1540
2512
 
1541
- // 仅观察模式(对标官方 observe):照常判定,但只记录「本会唤醒哪几条」,不真唤醒
1542
2513
  if (entry.observe === true) {
1543
2514
  entry.lastDeferred = '仅观察:本轮本会唤醒 ' + fresh.length + ' 条(' + fresh.slice(0, 5).map((i) => '#' + i.number).join(' ') + ')'
1544
2515
  entry.deferReason = 'observe'
@@ -1549,14 +2520,15 @@ async function pollWithItems(ctx, entry, baseMs, parsed, brand = null) {
1549
2520
  ok: false,
1550
2521
  reason: 'observe',
1551
2522
  })
1552
- entry.seen = advanceSeen(entry.seen, fresh)
1553
- entry.cursor = newestUpdatedAt(fresh) || entry.cursor
1554
- // 仅观察模式已经把这一轮记完了(seen/cursor 都前移),ETag 同步前移
2523
+ const selected = new Set(fresh)
2524
+ for (const record of v2Prepared.records.filter((item) => selected.has(item.item))) {
2525
+ applyV2(entry, observeV2(entry, record.key, record.cursor, { round: entry.round + 1, force: true }))
2526
+ }
1555
2527
  commitEtag()
2528
+ if (commentProbeFailed) delete entry.etag
1556
2529
  return
1557
2530
  }
1558
2531
 
1559
- // 会话级上限(跨守累计):单守上限 × 守数量 = 实际频率,光有单守上限挡不住
1560
2532
  const sessionCap = Math.max(1, Number(entry.sessionMaxWakes) || DEFAULT_SESSION_WAKES)
1561
2533
  const sessionUsed = sessionWakesLastHour(Object.values(readState().watchers || {}), entry.sessionId)
1562
2534
  if (sessionUsed >= sessionCap) {
@@ -1566,11 +2538,9 @@ async function pollWithItems(ctx, entry, baseMs, parsed, brand = null) {
1566
2538
  return
1567
2539
  }
1568
2540
 
1569
- // 每小时唤醒上限:宁可攒着,也不要连续叫醒把上下文打爆
1570
2541
  const cap = Math.max(1, Number(entry.maxWakesPerHour) || 6)
1571
2542
  entry.wakeTimes = pruneWakeTimes(entry.wakeTimes)
1572
2543
  if (entry.wakeTimes.length >= cap) {
1573
- // 只记原因,绝不动 seen/cursor —— 否则「攒着」等于「丢掉」
1574
2544
  const freeAt = nextWaketimeAt(entry.wakeTimes, cap)
1575
2545
  const waitMin = Math.max(1, Math.round((freeAt - Date.now()) / 60000))
1576
2546
  entry.lastDeferred = `每小时最多唤醒 ${cap} 次,已攒 ${fresh.length} 条待处理(约 ${waitMin} 分钟后可再唤醒)`
@@ -1579,62 +2549,44 @@ async function pollWithItems(ctx, entry, baseMs, parsed, brand = null) {
1579
2549
  return
1580
2550
  }
1581
2551
 
1582
- // 条目不丢:水位照常全部前移,消息里只铺开前 N 条,其余给编号
1583
- // 审核 T21:这里原来有个从没用过的 const limit(死代码),且兜底值写成 || 3,
1584
- // 与创建时的 batchLimit=5 口径分裂。统一成 5,并删掉死变量。
1585
2552
  const batchLimit = Math.max(1, Number(entry.batchLimit) || 5)
1586
- // 「提过但没回执」的条目再提一次:水位线不会因为「没 ack」而回退,所以它们平时永远不会再出现。
1587
- // 并进这一轮,但**不挤掉新条目**:先排新条目,剩下的位置才给重提的。
1588
- const pendingResult = pendingRetry(entry.pending, items, {})
1589
- if (pendingResult.stillPending && Object.keys(pendingResult.stillPending).length !== Object.keys(entry.pending || {}).length) {
1590
- entry.pending = pendingResult.stillPending
1591
- }
1592
- const { listed, rest } = splitBatch(fresh, batchLimit, entry.priorityOrder || entry.priority)
1593
- if (pendingResult.retry.length > 0 && listed.length < batchLimit) {
1594
- const room = batchLimit - listed.length
1595
- const numbersAlready = new Set(listed.map((item) => String(item.number)))
1596
- const extra = pendingResult.retry.filter((item) => !numbersAlready.has(String(item.number))).slice(0, room)
1597
- listed.push(...extra)
1598
- }
1599
- // 暂停/删除可能发生在这一轮轮询期间:以盘上为准
2553
+ let { listed, rest } = splitBatch(fresh, batchLimit, entry.priorityOrder || entry.priority)
2554
+ listed = await filterAdmissionBatch(ctx, listed, deps)
2555
+ if (listed.length === 0) {
2556
+ entry.lastDeferred = '两层准入评估未放行,本轮不唤醒'
2557
+ entry.deferReason = 'admission'
2558
+ noteEvent(entry, 'admission', entry.lastDeferred)
2559
+ return
2560
+ }
1600
2561
  const liveEntry = (readState().watchers || {})[entry.id]
1601
2562
  if (!liveEntry || !isEnabled(liveEntry)) {
1602
2563
  entry.lastDeferred = '本轮期间被暂停或删除,跳过唤醒'
1603
2564
  return
1604
2565
  }
1605
- // 会话忙就别开隔离区了:白建一个没人用的 worktree
1606
- const liveAgents = agentsService(ctx)
1607
- const liveAgent = liveAgents && typeof liveAgents.get === 'function' ? liveAgents.get(entry.sessionId) : undefined
1608
- if (!liveAgent) {
1609
- // 「找不到会话」有两种:宿主刚启动还没加载(临时),或真被删了(永久)。
1610
- // 2026-11-04 真机:重启后第一轮就报「会话已不在:请删除或重建」,可那个会话明明开着。
1611
- // 所以先给宽限期:期内只写 lastDeferred(不记失败、不退避),过了才认定真的没了。
1612
- const verdict = sessionMissingVerdict({ missingSince: entry.sessionMissingSince })
1613
- if (verdict.justNow) entry.sessionMissingSince = verdict.startedAt
1614
- if (verdict.grace) {
1615
- entry.lastDeferred = '会话尚未就绪(宿主可能刚启动):约 ' + verdict.waitMin + ' 分钟后仍找不到才报错'
2566
+ if (entry.executionMode !== 'worker') {
2567
+ const liveAgents = agentsService(ctx)
2568
+ const liveAgent = liveAgents && typeof liveAgents.get === 'function' ? liveAgents.get(entry.sessionId) : undefined
2569
+ if (!liveAgent) {
2570
+ const verdict = sessionMissingVerdict({ missingSince: entry.sessionMissingSince })
2571
+ if (verdict.justNow) entry.sessionMissingSince = verdict.startedAt
2572
+ if (verdict.grace) {
2573
+ entry.lastDeferred = '会话尚未就绪(宿主可能刚启动):约 ' + verdict.waitMin + ' 分钟后仍找不到才报错'
2574
+ return
2575
+ }
2576
+ setEntryError(entry, '会话已不在(连续 ' + verdict.waitedMin + ' 分钟找不到):确认该会话是否已被删除,再决定是否重建这条主理鱼')
2577
+ bumpFailure(entry, baseMs)
2578
+ return
2579
+ }
2580
+ entry.sessionMissingSince = null
2581
+ const gate = decideWake(liveAgent && liveAgent.status, await runningSubagents(ctx, entry.sessionId))
2582
+ if (!gate.ok) {
2583
+ entry.lastDeferred = '会话正忙,下一轮重试'
1616
2584
  return
1617
2585
  }
1618
- // 超过宽限期仍找不到:别开隔离区,也别假装在盯。
1619
- // 必须走 bumpFailure —— 否则这条会每 intervalSec 打一次 GitHub,永不退避(第四轮审核指出)。
1620
- setEntryError(entry, '会话已不在(连续 ' + verdict.waitedMin + ' 分钟找不到):确认该会话是否已被删除,再决定是否重建这条主理鱼')
1621
- bumpFailure(entry, baseMs)
1622
- return
1623
- }
1624
- // 找得到就清掉「缺失计时」,下次重启不会带着旧时间戳
1625
- entry.sessionMissingSince = null
1626
- const gate = decideWake(liveAgent && liveAgent.status)
1627
- if (!gate.ok) {
1628
- entry.lastDeferred = '会话正忙,下一轮重试'
1629
- return
1630
- }
1631
2586
 
1632
- // 会话忙时**不要**先开隔离区:`git worktree add`(本机实测 0.19s,大仓库更久)
1633
- // 加上回收过期副本的若干次 git 调用,全都是白发 —— 因为 decideWake 之后一定会拒绝。
1634
- {
1635
2587
  const agents = agentsService(ctx)
1636
2588
  const agent = agents && typeof agents.get === 'function' ? agents.get(entry.sessionId) : undefined
1637
- const pre = decideWake(agent && agent.status)
2589
+ const pre = decideWake(agent && agent.status, await runningSubagents(ctx, entry.sessionId))
1638
2590
  if (!pre.ok) {
1639
2591
  entry.lastDeferred = '会话正忙(' + String(pre.reason || '') + '),这一轮不准备隔离区,下一轮再试'
1640
2592
  return
@@ -1642,96 +2594,479 @@ async function pollWithItems(ctx, entry, baseMs, parsed, brand = null) {
1642
2594
  }
1643
2595
  const isolation = await prepareIsolation(entry)
1644
2596
  if (isolation && isolation.dir) entry.lastWorktree = isolation.dir
1645
- // 批次前几条补「最后是谁在说话」(最多 3 条,失败静默)
1646
2597
  await fetchLastComments(entry.repo, listed, 3, {
1647
2598
  provider: entry.provider,
1648
2599
  token: entry.provider === 'gitee' ? String(readSecrets().giteeToken || '') : '',
1649
2600
  })
1650
- // 首次同步:这条守刚建好,或者宿主换了机器(cursor 还是 null)。
1651
- // 此时"有动态"其实是"仓库里本来就有这些待处理",说成新动态会让人以为刚刚发生。
1652
- const firstSync = !entry.cursor
1653
- const wakeText = formatWatchText(entry.repo, listed, {
1654
- // 品牌名(issue #11):抬头【…】与面板/诊断共用同一份配置
2601
+ const firstSync = !entry.lastWake
2602
+ const wakeOptions = {
1655
2603
  brandName: brand ? brand.brandName : undefined,
1656
2604
  more: rest.length,
1657
2605
  firstSync,
1658
2606
  restNumbers: rest.map((item) => item.number),
1659
2607
  isolation,
1660
- // entry.goal 之前只写不读:现在真的进唤醒消息
1661
2608
  goal: entry.goal || '',
1662
- // 只传「绑没绑智能体账号」这个布尔量:**不把路径写进唤醒消息**(会进模型上下文与对话记录,
1663
- // 顺带把本机用户名和目录结构带出去)。路径由用户在需要时自己给。
1664
2609
  identityBound: Boolean(readSecrets().ghConfigDir),
1665
- // 只读仓库要在任务书里直说,否则会话会去试写然后吃 403
1666
2610
  access: accessNote(entry.repoAccess),
1667
- // 完成标准要可观测(Given-When-Then 的思路):三件事缺一不算完成
1668
- // 三条完成标准抽在 lib/watch.js 里(纯函数,可被用例覆盖):
1669
- // 这里曾经引用过不存在的 `iso`,只在"会话空闲真的发消息"时才爆 ReferenceError。
1670
2611
  criteria: wakeCriteria({ isolation }),
1671
- // 「为什么是这几条」:把本轮的筛选依据一并写进任务书
1672
2612
  changedTotal: fresh.length,
1673
2613
  batchLimit: listed.length,
1674
2614
  skippedReasons: entry.filterCounts || {},
1675
- // 这条以前被叫醒过吗?history 里一直有数据,但消息从没用过
1676
2615
  seenBefore: (() => {
1677
2616
  const map = {}
1678
- // 审核 T37 M2:`|| []` 挡不住 `42`(不是 iterable)—— 会让这条守永久退避。
1679
2617
  for (const event of (Array.isArray(entry.history) ? entry.history : [])) {
1680
2618
  for (const n of event.numbers || []) map[String(n)] = map[String(n)] || event.at
1681
2619
  }
1682
2620
  return map
1683
2621
  })(),
1684
- // 上次 ack 时留的话(watch_ack 的 note):同一条再被叫醒时一并带回
1685
2622
  acked: entry.acked && typeof entry.acked === 'object' ? entry.acked : null,
1686
- })
1687
- entry.lastWakeCount = fresh.length
2623
+ }
2624
+ const wakeText = formatWatchText(entry.repo, listed, wakeOptions)
1688
2625
  entry.lastBatch = listed.map((item) => item.number)
1689
- // 记账一律放到「真正发送之后」:
1690
- // 之前是入队即记账 —— 会话忙时 decideWake 会拒绝,次数却已经记了、seen 也已经推进,
1691
- // 于是那几条既不会重试(seen 已推进)又白白占掉名额。这是会丢消息的 bug。
1692
- const wakeQueueKey = entry.id + '|' + fresh.map((item) => String(item.number) + '@' + String(item.updated_at || '')).join(',')
1693
- wakeMerged(ctx, entry.sessionId, wakeText, (result) => {
1694
- // 审核 T20:结算逻辑抽成纯函数 planWakeSettlement()(有单测),这里只负责落副作用。
2626
+ const settleWakeResult = async (result, committedListed = listed) => {
1695
2627
  const settled = planWakeSettlement(entry, {
1696
2628
  ok: result.ok,
1697
2629
  reason: result.reason,
2630
+ busy: result.busy === true,
1698
2631
  fresh,
2632
+ listed,
1699
2633
  firstSync,
1700
2634
  baseMs,
1701
2635
  })
1702
- entry.lastWake = settled.lastWake
1703
- entry.lastWakeCount = settled.lastWakeCount
1704
- entry.lastBatch = settled.lastBatch
1705
- entry.history = settled.history
1706
- if (settled.error) setEntryError(entry, settled.error)
1707
- if (settled.advanceWatermark) {
1708
- entry.silentWakes = settled.silentWakes
1709
- if (settled.ackedRecovered && entry.prevWakeAt) noteEvent(entry, 'acked', '上一次唤醒有回音(ack 出现过了)')
1710
- entry.prevWakeAt = settled.prevWakeAt
1711
- entry.wakeTimes = settled.wakeTimes
1712
- entry.dailyWakes = settled.dailyWakes
1713
- entry.lastDeferred = settled.lastDeferred
1714
- entry.deferReason = settled.deferReason
1715
- noteEvent(entry, settled.eventKind, settled.eventText)
1716
- entry.seen = settled.seen
1717
- entry.lastReported = settled.lastReported
1718
- entry.cursor = settled.cursor
1719
- // 「叫醒未回执」跟踪(Ticket 状态机的最小版):提过的条目记下来,
1720
- // 下一轮若仍开着且没 ack,会再提一次(有次数上限与冷却期,见 pendingRetry)。
1721
- try {
1722
- entry.pending = recordPendingWake(entry.pending, listed.map((item) => item.number))
1723
- } catch { /* 记账失败不影响唤醒 */ }
1724
- commitEtag()
2636
+ entry.lastWake = settled.lastWake
2637
+ entry.lastWakeCount = settled.lastWakeCount
2638
+ entry.lastBatch = settled.lastBatch
2639
+ entry.history = settled.history
2640
+ if (settled.error) setEntryError(entry, settled.error)
2641
+ if (settled.advanceWatermark) {
2642
+ if (entry.executionMode !== 'worker') {
2643
+ for (const item of committedListed) {
2644
+ try { await recordRuntimeDelivery(entry, item, ctx) } catch (error) {
2645
+ setEntryError(entry, 'Ticket 登记失败(唤醒已送达):' + String(error && error.message || error))
2646
+ }
2647
+ }
2648
+ }
2649
+ const head = committedListed[0] || listed[0]
2650
+ entry.lastWakeItem = head
2651
+ ? {
2652
+ number: String(head.number ?? ''),
2653
+ title: Array.from(String(head.title || '').replace(/\s+/g, ' ')).slice(0, 60).join(''),
2654
+ kind: head.pull_request ? 'pr' : 'issue',
2655
+ }
2656
+ : null
2657
+ entry.silentWakes = settled.silentWakes
2658
+ if (settled.ackedRecovered && entry.prevWakeAt) noteEvent(entry, 'acked', '上一次唤醒有回音(ack 出现过了)')
2659
+ entry.prevWakeAt = settled.prevWakeAt
2660
+ entry.wakeTimes = settled.wakeTimes
2661
+ entry.dailyWakes = settled.dailyWakes
2662
+ entry.lastDeferred = settled.lastDeferred
2663
+ entry.deferReason = settled.deferReason
2664
+ noteEvent(entry, settled.eventKind, settled.eventText)
2665
+ commitV2Listed(entry, v2Prepared, committedListed)
2666
+ commitEtag()
2667
+ if (commentProbeFailed) delete entry.etag
2668
+ } else {
2669
+ noteEvent(entry, 'wake-failed', entry.lastError)
2670
+ entry.deferReason = settled.deferReason
2671
+ if (settled.lastDeferred) entry.lastDeferred = settled.lastDeferred
2672
+ if (settled.bumpBackoff) bumpFailure(entry, baseMs)
2673
+ }
2674
+ persistEntry(entry)
2675
+ }
2676
+ if (entry.executionMode === 'worker') {
2677
+ const outcome = await deliverWorkerBatch(ctx, entry, listed, (item) => formatWatchText(entry.repo, [item], {
2678
+ ...wakeOptions, more: 0, restNumbers: [], changedTotal: 1, batchLimit: 1,
2679
+ }))
2680
+ await settleWakeResult({ ok: outcome.ok, reason: outcome.reason, busy: false }, outcome.deliveredItems)
2681
+ return
2682
+ }
2683
+ const wakeQueueKey = entry.id + '|' + fresh.map((item) => String(item.number) + '@' + String(item.updated_at || '')).join(',')
2684
+ wakeFn(ctx, entry.sessionId, wakeText, (result) => {
2685
+ settleWakeResult(result, listed).catch((error) => {
2686
+ setEntryError(entry, '唤醒结算失败:' + String(error && error.message || error))
2687
+ persistEntry(entry)
2688
+ })
2689
+ }, wakeQueueKey, brand ? brand.brandName : undefined)
2690
+ }
2691
+
2692
+ /** 一条唤醒消息里最多铺开几条 PR 评论(Gitee 的 per_page 是 100,停机恢复时会一次拿到很多)。 */
2693
+ const MAX_PR_COMMENTS_PER_WAKE = 10
2694
+
2695
+ /**
2696
+ * PR 响应轮询(PR 版;issue 版是 pollOnce/pollWithItems,两者刻意分开)。
2697
+ *
2698
+ * 三条不能破的规矩:
2699
+ * 1. **只读**:只拉「我开的、还开着的 PR」和它们的评论,绝不写评论/标签/状态。
2700
+ * 回评由会话看过唤醒消息之后自己做 —— 这是设计约束,不是图省事。
2701
+ * 2. **水位只在真正消费之后前移**:碰见 observe、无新评论、退避、唤醒失败一律不动
2702
+ * `seenComments`;否则会话忙的那一轮评论就永久丢了(AGENTS 坑表第 2 条的同类问题)。
2703
+ * 3. `seenComments` 是人手也会改的状态字段,可能被改成 null / 数组 / 字符串:
2704
+ * 读的时候一律兜底,写之前先归一成对象。
2705
+ *
2706
+ * `deps` 只为测试注入(生产不传):{ ghRun, fetchImpl, wake, selfLogin }。
2707
+ */
2708
+ /**
2709
+ * 一批新评论里最新的 id。
2710
+ *
2711
+ * **不能取末条。** Gitee 的评论接口带 `direction=desc`(最新在首条),GitHub 的
2712
+ * `comments(last:10)` 是升序(最新在末条)—— 两种顺序都被真实接口用过。取末条在
2713
+ * Gitee 上会退到最旧那一条:`advanceSeen` 是「只许前进」,没前进就等于这一批
2714
+ * 评论每条都要重报一轮,12 条评论叫醒 12 次、对方看到 12 条重复回评。
2715
+ * 取 max 才与设计文档「seenComments[pr] = 最新评论 id」的语义一致。
2716
+ */
2717
+ function latestCommentId(list) {
2718
+ let max = 0
2719
+ for (const comment of Array.isArray(list) ? list : []) {
2720
+ const id = Number(comment && comment.id)
2721
+ if (Number.isFinite(id) && id > max) max = id
2722
+ }
2723
+ return max
2724
+ }
2725
+
2726
+ /**
2727
+ * 首次同步时把一个 PR 的讨论评论**全部**拉下来(REST 分页)。
2728
+ *
2729
+ * 为什么不用 GraphQL 里那份:`comments(last:100)` 单页上限就是 100,超过就看不到
2730
+ * 更早的 —— 而首次同步(seenId=0)恰恰需要最旧那条,否则水位一推,更早的评论
2731
+ * 永久低于水位、再也不会被报(2026-11-13 外部 review 的第 3 点:已有 id 1..14、
2732
+ * 服务端只回 5..14,首轮 seen=14 后 1..4 永远不再唤醒)。REST 支持 `page` 翻页。
2733
+ *
2734
+ * 只在首次同步走这里;之后的增量用 GraphQL 随列表带回来的那 100 条就够(每轮新评论
2735
+ * 通常只有几条)。翻页 10 页(1000 条)封顶,病态 PR 不能把一轮轮询拖成分钟级。
2736
+ */
2737
+ async function fetchAllIssueComments(ghRun, repo, number) {
2738
+ const all = []
2739
+ const maxPages = 10
2740
+ for (let page = 1; page <= maxPages; page += 1) {
2741
+ const res = await ghRun('gh', ['api', `repos/${repo}/issues/${number}/comments?per_page=100&page=${page}`], {
2742
+ timeoutMs: 45_000,
2743
+ env: ghEnv(),
2744
+ })
2745
+ if (!res || res.code !== 0) {
2746
+ return { ok: false, error: redact(String((res && res.stderr) || '拉取 PR 评论失败').trim()) }
2747
+ }
2748
+ let data = null
2749
+ try {
2750
+ data = JSON.parse(String((res && res.stdout) || ''))
2751
+ } catch {
2752
+ return { ok: false, error: '评论返回不是合法 JSON' }
2753
+ }
2754
+ if (!Array.isArray(data)) return { ok: false, error: '评论列表不是数组' }
2755
+ if (data.length === 0) break
2756
+ for (const item of data) {
2757
+ const cid = Number(item && item.id)
2758
+ if (!Number.isFinite(cid)) continue
2759
+ all.push({
2760
+ id: cid,
2761
+ author: item.user && item.user.login ? String(item.user.login) : '',
2762
+ body: String(item.body || ''),
2763
+ createdAt: item.created_at ? String(item.created_at) : '',
2764
+ })
2765
+ }
2766
+ if (data.length < 100) break
2767
+ }
2768
+ return { ok: true, comments: all }
2769
+ }
2770
+
2771
+ async function pollPrOnce(ctx, entry, baseMs, brand = null, deps = {}) {
2772
+ Object.assign(entry, migrateV1Watermark(entry))
2773
+ const ghRun = typeof deps.ghRun === 'function' ? deps.ghRun : run
2774
+ const wakeFn = typeof deps.wake === 'function' ? deps.wake : wakeMerged
2775
+ const provider = entry.provider === 'gitee' ? 'gitee' : 'github'
2776
+ const now = () => new Date().toISOString()
2777
+
2778
+ if (entry.activeHours) {
2779
+ if (!inActiveHours(entry.activeHours)) {
2780
+ enterActiveHoursDefer(entry, msUntilActiveWindow(entry.activeHours), entry.activeHours)
2781
+ noteEvent(entry, 'defer', entry.lastDeferred)
2782
+ return
2783
+ }
2784
+ }
2785
+ if (entry.nextAt && Date.now() < Date.parse(entry.nextAt)) return
2786
+
2787
+ await flushWakeQueue(ctx, entry.sessionId)
2788
+ const afterFlush = readState().watchers[entry.id]
2789
+ if (afterFlush && afterFlush.seenComments && typeof afterFlush.seenComments === 'object') {
2790
+ entry.seenComments = afterFlush.seenComments
2791
+ }
2792
+ if (afterFlush && afterFlush.obs) {
2793
+ entry.obs = afterFlush.obs
2794
+ entry.round = afterFlush.round
2795
+ syncPrCommentsProjection(entry)
2796
+ }
2797
+
2798
+ const token = provider === 'gitee' ? (readSecrets().giteeToken || '') : ''
2799
+ const self = deps.selfLogin !== undefined ? String(deps.selfLogin || '') : ((await viewerLogin(provider)) || '')
2800
+ if (!normalizeSelf(self)) {
2801
+ setEntryError(entry, '取不到当前账号(gh / gitee 未登录或凭证失效),本轮跳过:判断不了哪些评论不是自己发的')
2802
+ bumpFailure(entry, baseMs)
2803
+ noteEvent(entry, 'error', entry.lastError)
2804
+ return
2805
+ }
2806
+
2807
+ let prs = null
2808
+ let failure = null
2809
+ let ghRes = null
2810
+ let listComplete = true
2811
+ if (provider === 'gitee') {
2812
+ const res = await listGiteePrs({ repo: entry.repo, token, author: self, fetchImpl: deps.fetchImpl })
2813
+ if (res && res.ok) {
2814
+ prs = res.prs
2815
+ listComplete = !res.truncated
2816
+ } else failure = (res && res.error) || '拉取 PR 列表失败'
2817
+ } else {
2818
+ const res = await ghRun('gh', ['api', 'graphql', '-f', 'query=' + buildPrSearchQuery({ base: entry.repo, first: 100 })], { timeoutMs: 45_000, env: ghEnv() })
2819
+ ghRes = res
2820
+ const parsed = parsePrSearch(String((res && res.stdout) || ''))
2821
+ if (parsed.ok) {
2822
+ prs = parsed.prs
2823
+ listComplete = !parsed.hasNextPage
2824
+ } else {
2825
+ const stderr = redact(String((res && res.stderr) || '').trim())
2826
+ failure = stderr && res && res.code !== 0 ? stderr : parsed.error
2827
+ }
2828
+ }
2829
+
2830
+ if (failure) {
2831
+ if (absorbGhTimeout(entry, ghRes)) return
2832
+ setEntryError(entry, 'pr poll: ' + redact(String(failure)).slice(0, 300))
2833
+ bumpFailure(entry, baseMs)
2834
+ noteEvent(entry, 'error', entry.lastError)
2835
+ return
2836
+ }
2837
+ if (!Array.isArray(prs)) prs = []
2838
+
2839
+ entry.lastPoll = now()
2840
+ entry.lastError = null
2841
+ entry.needsReauth = false
2842
+ entry.consecutiveFailures = 0
2843
+ entry.nextAt = null
2844
+
2845
+ const followed = prs.filter((pr) => isForkPr(pr))
2846
+
2847
+ const seenObject = entry.seenComments && typeof entry.seenComments === 'object' && !Array.isArray(entry.seenComments) ? entry.seenComments : {}
2848
+ if (listComplete) {
2849
+ const open = followed.map((pr) => pr.number)
2850
+ const allowed = new Set(open.map(String))
2851
+ for (const key of Object.keys(entry.obs || {})) {
2852
+ if (key.startsWith('pr:') && !allowed.has(key.slice(3).split('/')[0])) delete entry.obs[key]
2853
+ }
2854
+ syncPrCommentsProjection(entry, open)
2855
+ } else {
2856
+ entry.seenComments = seenObject
2857
+ syncPrCommentsProjection(entry)
2858
+ noteEvent(entry, 'defer', 'PR 列表可能被截断(' + prs.length + ' 条),本轮不剪水位')
2859
+ }
2860
+
2861
+ const batches = []
2862
+ const me = normalizeSelf(self)
2863
+ for (const pr of followed) {
2864
+ const key = `pr:${pr.number}/comment`
2865
+ const row = entry.obs && entry.obs[key]
2866
+ const seenId = Number(row && row.legacy
2867
+ ? entry.seenComments[pr.number]
2868
+ : ((row && (row.handled && row.handled.cursor || row.delivered && row.delivered.cursor || row.cursor))
2869
+ ?? entry.seenComments[pr.number])) || 0
2870
+ let comments = null
2871
+ if (provider === 'gitee') {
2872
+ const res = await fetchGiteePrComments({ repo: entry.repo, token, number: pr.number, fetchImpl: deps.fetchImpl })
2873
+ if (!res || !res.ok) {
2874
+ setEntryError(entry, 'pr comments #' + pr.number + ': ' + redact(String((res && res.error) || '拉取 PR 评论失败')).slice(0, 300))
2875
+ noteEvent(entry, 'error', entry.lastError)
2876
+ continue
2877
+ }
2878
+ comments = res.comments
2879
+ } else if (seenId === 0) {
2880
+ const all = await fetchAllIssueComments(ghRun, entry.repo, pr.number)
2881
+ if (!all.ok) {
2882
+ setEntryError(entry, 'pr comments #' + pr.number + ': ' + redact(String(all.error || '拉取 PR 评论失败')).slice(0, 300))
2883
+ noteEvent(entry, 'error', entry.lastError)
2884
+ continue
2885
+ }
2886
+ comments = all.comments
2887
+ } else {
2888
+ comments = Array.isArray(pr.comments) ? pr.comments : []
2889
+ }
2890
+ if (entry.obs && entry.obs[key] && entry.obs[key].legacy) {
2891
+ applyV2(entry, observeV2(entry, key, latestCommentId(comments), {
2892
+ round: entry.round + 1, legacyCursor: seenId,
2893
+ }))
2894
+ }
2895
+ const fresh = pickNewComments(comments, seenId).filter((comment) => {
2896
+ const author = normalizeSelf(comment && comment.author)
2897
+ return author !== '' && author !== me
2898
+ })
2899
+ if (fresh.length > 0) {
2900
+ const cursor = latestCommentId(comments)
2901
+ const decision = decideWatermark({
2902
+ items: [{ key, cursor, item: pr }], obs: entry.obs, now: Date.now(),
2903
+ cooldownMs: 0, batchLimit: entry.batchLimit, wakeTimes: entry.wakeTimes,
2904
+ maxWakesPerHour: entry.maxWakesPerHour,
2905
+ })
2906
+ if (decision.candidates.length > 0) batches.push({ number: pr.number, pr, fresh, v2Key: key })
2907
+ }
2908
+ }
2909
+
2910
+ if (batches.length === 0) {
2911
+ entry.deferReason = 'unchanged'
2912
+ entry.lastDeferred = null
2913
+ return
2914
+ }
2915
+
2916
+ const total = batches.reduce((sum, batch) => sum + batch.fresh.length, 0)
2917
+
2918
+ if (entry.observe === true) {
2919
+ entry.deferReason = 'observe'
2920
+ entry.lastDeferred = '仅观察:本轮本会唤醒 ' + total + ' 条(' + batches.slice(0, 5).map((batch) => '#' + batch.number + '×' + batch.fresh.length).join(' ') + ')'
2921
+ noteEvent(entry, 'observe', entry.lastDeferred)
2922
+ return
2923
+ }
2924
+
2925
+ const sessionCap = Math.max(1, Number(entry.sessionMaxWakes) || DEFAULT_SESSION_WAKES)
2926
+ const sessionUsed = sessionWakesLastHour(Object.values(readState().watchers || {}), entry.sessionId)
2927
+ if (sessionUsed >= sessionCap) {
2928
+ entry.lastDeferred = '这条会话一小时内已被唤醒 ' + sessionUsed + ' 次(上限 ' + sessionCap + '),已攒 ' + total + ' 条待处理'
2929
+ entry.deferReason = 'cap-session'
2930
+ noteEvent(entry, 'cap-session', entry.lastDeferred)
2931
+ return
2932
+ }
2933
+
2934
+ const cap = Math.max(1, Number(entry.maxWakesPerHour) || 6)
2935
+ entry.wakeTimes = pruneWakeTimes(entry.wakeTimes)
2936
+ if (entry.wakeTimes.length >= cap) {
2937
+ const freeAt = nextWaketimeAt(entry.wakeTimes, cap)
2938
+ const waitMin = Math.max(1, Math.round((freeAt - Date.now()) / 60000))
2939
+ entry.lastDeferred = `每小时最多唤醒 ${cap} 次,已攒 ${total} 条待处理(约 ${waitMin} 分钟后可再唤醒)`
2940
+ entry.deferReason = 'cap-watcher'
2941
+ noteEvent(entry, 'cap-watcher', entry.lastDeferred)
2942
+ return
2943
+ }
2944
+
2945
+ const subGate = decideWake('idle', await runningSubagents(ctx, entry.sessionId))
2946
+ if (!subGate.ok) {
2947
+ entry.lastDeferred = String(subGate.reason || '子任务在跑') + ',已攒 ' + total + ' 条待处理'
2948
+ entry.deferReason = 'busy'
2949
+ noteEvent(entry, 'defer', entry.lastDeferred)
2950
+ return
2951
+ }
2952
+
2953
+ const auditMode = entry.auditMode === 'inline' ? 'inline' : 'subagent'
2954
+ const auditLines = []
2955
+ if (entry.audit === true) auditLines.push('审计: 开启(' + auditMode + ' 模式)')
2956
+ if (entry.adversarialAudit === true) auditLines.push('对抗性审计: 开启(' + auditMode + ' 模式)')
2957
+
2958
+ const listedByPr = new Map()
2959
+ const sections = batches.map((batch) => {
2960
+ const ordered = [...batch.fresh].sort((a, b) => Number(a.id) - Number(b.id))
2961
+ const listed = ordered.slice(0, MAX_PR_COMMENTS_PER_WAKE)
2962
+ listedByPr.set(batch.number, listed)
2963
+ const rest = batch.fresh.length - listed.length
2964
+ let text = buildPrWakeText({
2965
+ base: entry.repo,
2966
+ number: batch.number,
2967
+ title: batch.pr.title,
2968
+ branch: batch.pr.headRef,
2969
+ comments: listed,
2970
+ goal: entry.goal,
2971
+ audit: entry.audit === true,
2972
+ adversarialAudit: entry.adversarialAudit === true,
2973
+ auditMode: entry.auditMode,
2974
+ })
2975
+ if (rest > 0) {
2976
+ text = text.replace(/^[^\n]*/, '【PR 响应】' + entry.repo + '#' + batch.number + ' 有 ' + batch.fresh.length + ' 条新评论(只展开前 ' + listed.length + ' 条)')
2977
+ text += '\n还有 ' + rest + ' 条没展开(一条消息最多列 ' + MAX_PR_COMMENTS_PER_WAKE + ' 条),回评前在 PR 页看全量。'
2978
+ }
2979
+ return text
2980
+ })
2981
+ let wakeText = sections.join('\n\n')
2982
+ if (auditLines.length > 0) wakeText += '\n\n' + auditLines.join('\n')
2983
+
2984
+ const wakeQueueKey = 'pr|' + entry.id + '|' + batches.map((batch) => batch.number + '@' + latestCommentId(batch.fresh)).join(',')
2985
+ wakeFn(ctx, entry.sessionId, wakeText, (result) => {
2986
+ if (result && result.ok) {
2987
+ const records = batches.map((batch) => ({
2988
+ key: batch.v2Key || `pr:${batch.number}/comment`,
2989
+ cursor: latestCommentId(listedByPr.get(batch.number) || []),
2990
+ item: batch.pr,
2991
+ }))
2992
+ const settled = commitDeliveryReceipt({
2993
+ state: entry, listed: records,
2994
+ receipt: { ok: true, deliveredKeys: records.map((record) => record.key) },
2995
+ })
2996
+ applyV2(entry, settled.state)
2997
+ syncPrCommentsProjection(entry)
2998
+ entry.lastWake = now()
2999
+ entry.wakeTimes = pruneWakeTimes([...(Array.isArray(entry.wakeTimes) ? entry.wakeTimes : []), Date.now()])
3000
+ entry.lastWakeCount = total
3001
+ entry.lastBatch = batches.map((batch) => batch.number)
3002
+ entry.deferReason = null
3003
+ entry.lastDeferred = null
3004
+ entry.consecutiveFailures = 0
3005
+ entry.nextAt = null
3006
+ noteEvent(entry, 'wake', 'PR 唤醒:' + batches.map((batch) => '#' + batch.number + '×' + batch.fresh.length).join(' '))
1725
3007
  } else {
1726
- // 保留水位,下一轮重试这次事件
1727
- noteEvent(entry, 'wake-failed', entry.lastError)
1728
- entry.deferReason = settled.deferReason
1729
- if (settled.lastDeferred) entry.lastDeferred = settled.lastDeferred
1730
- if (settled.bumpBackoff) bumpFailure(entry, baseMs)
1731
- } persistEntry(entry)
3008
+ const reason = String((result && result.reason) || '')
3009
+ const busy = Boolean(result && result.queued) || /busy|running|idle|排队|队列|正忙/i.test(reason)
3010
+ if (busy) {
3011
+ entry.deferReason = 'busy'
3012
+ entry.lastDeferred = '会话正忙,下一轮重试'
3013
+ noteEvent(entry, 'wake-deferred', reason || entry.lastDeferred)
3014
+ } else {
3015
+ setEntryError(entry, 'wake: ' + (reason || '投递失败'))
3016
+ bumpFailure(entry, baseMs)
3017
+ noteEvent(entry, 'wake-failed', entry.lastError)
3018
+ }
3019
+ }
3020
+ persistEntry(entry)
1732
3021
  }, wakeQueueKey, brand ? brand.brandName : undefined)
1733
3022
  }
1734
3023
 
3024
+ function prStatusView(entries, sessionId = null) {
3025
+ const all = (Array.isArray(entries) ? entries : Object.values(entries || {}))
3026
+ .filter((w) => w && (w.kind === 'pr' || String(w.id || '').startsWith('pr:')))
3027
+ // 只看本会话的守:会话之间本来是隔离的,不按 sessionId 过滤会把别的会话的
3028
+ // repo / goal / workdir 一起抖出来(2026-11-13 外部 review 的 B8)。
3029
+ const list = sessionId ? all.filter((w) => w.sessionId === sessionId) : all
3030
+ const id = sessionId || (list[0] && list[0].sessionId) || null
3031
+ const used = id ? sessionWakesLastHour(list, id) : 0
3032
+ const cap = Number((list[0] && list[0].sessionMaxWakes)) || DEFAULT_SESSION_WAKES
3033
+ return {
3034
+ // 消费方靠它判断字段语义有没有变;改字段时这个数一起加
3035
+ schemaVersion: 1,
3036
+ session: { id, used, cap, capped: countCapped(list) },
3037
+ watchers: list.map((w) => {
3038
+ const seen = w.seenComments && typeof w.seenComments === 'object' && !Array.isArray(w.seenComments) ? w.seenComments : {}
3039
+ return {
3040
+ id: w.id || null,
3041
+ repo: w.repo || null,
3042
+ provider: w.provider === 'gitee' ? 'gitee' : 'github',
3043
+ sessionId: w.sessionId || null,
3044
+ kind: 'pr',
3045
+ enabled: w.enabled !== false,
3046
+ // 兜底值必须和新建默认值一致(60),否则面板回显 300、一保存就把 60 写成 300
3047
+ // —— 2026-11-17 用户实测(三条守全变 300)的根因就在这里。
3048
+ intervalSec: Number(w.intervalSec) || 60,
3049
+ seenComments: { ...seen },
3050
+ tracked: Object.keys(seen).length,
3051
+ observe: w.observe === true,
3052
+ activeHours: w.activeHours || null,
3053
+ audit: w.audit === true,
3054
+ adversarialAudit: w.adversarialAudit === true,
3055
+ auditMode: w.auditMode === 'inline' ? 'inline' : 'subagent',
3056
+ goal: w.goal || null,
3057
+ deferReason: w.deferReason || null,
3058
+ lastDeferred: w.lastDeferred || null,
3059
+ lastPoll: w.lastPoll || null,
3060
+ lastWake: w.lastWake || null,
3061
+ lastWakeCount: Number(w.lastWakeCount) || 0,
3062
+ consecutiveFailures: Number(w.consecutiveFailures) || 0,
3063
+ nextAt: w.nextAt || null,
3064
+ lastError: w.lastError || null,
3065
+ }
3066
+ }),
3067
+ }
3068
+ }
3069
+
1735
3070
  export function apply(ctx, options = {}) {
1736
3071
  // 品牌配置(issue #11):options 是 cordis 按 Config 校验后的对象;
1737
3072
  // 直接调用(单测 / 老宿主)时由 resolveBrandConfig 兜住默认值。
@@ -1749,6 +3084,14 @@ export function apply(ctx, options = {}) {
1749
3084
  const timers = sharedTimers
1750
3085
  // 一次性定时器(首轮错峰):**每实例一份** —— teardown 只清自己的,不碰别人的(审核 W5)
1751
3086
  const bootTimers = new Map()
3087
+ // 排过的 boot tick 句柄另记一份**从不删**的账:`bootTimers` 在撤销时会被 delete,
3088
+ // 从它读不出「那个 timer 到底被 clearTimeout 了没有」(只删一半的变异照样是空 map)。
3089
+ // 只给 `__test.bootTimerPending` 读,生产代码不碰。
3090
+ const bootArmed = new Map()
3091
+ bootTimerProbe = (id) => {
3092
+ const handle = bootArmed.get(String(id))
3093
+ return Boolean(handle && handle._destroyed !== true)
3094
+ }
1752
3095
 
1753
3096
 
1754
3097
  // 并发闸的唯一事实源:tick 和 HTTP「立刻」拿到的是两个不同的 entry 对象,
@@ -1789,6 +3132,34 @@ export function apply(ctx, options = {}) {
1789
3132
  } catch { /* 探测失败不影响主流程 */ }
1790
3133
  }
1791
3134
 
3135
+ /**
3136
+ * 人工触发的一轮轮询。三个入口共用:「立即」按钮、从暂停恢复、以及恢复后补跑。
3137
+ *
3138
+ * 三件事必须一起做,少一件就是用户报障那个「点了没反应」:
3139
+ * 1. **清退避**(`clearBackoff`)—— `pollPrOnce` 第 2 步就是退避早退,
3140
+ * PR 守在退避期里点「立即」会 0 次 gh 调用却回 `202 {polling:true}`;
3141
+ * 2. **尊重 `DSH_SUPERAGENT_NO_POLL`** —— `startWatcher` 尊重它(只登记不轮询),
3142
+ * 路由单测正是靠它避免真请求;新加的立即轮询不能绕过去;
3143
+ * 3. **`inFlight` 去重** —— 定时器与人工请求撞一起会开两个隔离区。
3144
+ *
3145
+ * 返回 `true` 表示已经排上(调用方回 202),`false` 表示没跑(已有轮询 / 离线开关)。
3146
+ */
3147
+ const runManualPoll = (entry) => {
3148
+ if (!entry || inFlight.has(entry.id)) return false
3149
+ // 装了测试替身就说明这条用例明确要求「这一轮要发生」,不看离线开关
3150
+ // (否则路由单测永远观察不到轮询到底有没有跑)。
3151
+ if (!manualPollerOverride && process.env.DSH_SUPERAGENT_NO_POLL === '1') return false
3152
+ // 清退避放在「确定要跑」之后:这一轮都不跑的时候不该顺手改掉操作者的退避状态。
3153
+ clearBackoff(entry)
3154
+ const everyMs = Math.max(30, Number(entry.intervalSec) || 60) * 1000
3155
+ const poller = manualPollerOverride || (entry.kind === 'pr' ? pollPrOnce : pollOnce)
3156
+ inFlight.add(entry.id)
3157
+ poller(ctx, entry, everyMs, brand)
3158
+ .catch(() => {})
3159
+ .finally(() => { inFlight.delete(entry.id); persistEntry(entry) })
3160
+ return true
3161
+ }
3162
+
1792
3163
  const startWatcher = (entry) => {
1793
3164
  if (timers.has(entry.id)) return
1794
3165
  const every = Math.max(30, Number(entry.intervalSec) || 60) * 1000
@@ -1805,7 +3176,10 @@ export function apply(ctx, options = {}) {
1805
3176
  if (inFlight.has(entry.id)) return
1806
3177
  inFlight.add(entry.id)
1807
3178
  try {
1808
- await pollOnce(ctx, entry, every, brand)
3179
+ // PR 守走 PR 版轮询:issue 版的 seen/ack/过滤器语义与 PR 完全不同(水位是评论 id),
3180
+ // 混在一起只会互相踩。区别只在轮询入口,退避/持久化/暂停这些公共逻辑共用。
3181
+ if (entry.kind === 'pr') await pollPrOnce(ctx, entry, every, brand)
3182
+ else await pollOnce(ctx, entry, every, brand)
1809
3183
  // GitHub 要求的间隔比我们的长:把下一轮推到它之后(成功路径也生效)
1810
3184
  const floor = (Number(entry.minIntervalSec) || 0) * 1000
1811
3185
  if (floor > every) entry.nextAt = new Date(Date.now() + floor).toISOString()
@@ -1828,9 +3202,10 @@ export function apply(ctx, options = {}) {
1828
3202
  if (firstDelay > 0) {
1829
3203
  // 这个一次性定时器**也要能取消**:以前只 unref 不登记,stop 之后它还会 fire 一次
1830
3204
  // (审核 W1)—— 删掉/暂停的守会「诈尸」轮询一轮。
1831
- const boot = setTimeout(() => { bootTimers.delete(entry.id); tick() }, firstDelay)
3205
+ const boot = setTimeout(() => { bootTimers.delete(entry.id); bootArmed.delete(entry.id); tick() }, firstDelay)
1832
3206
  boot.unref?.()
1833
3207
  bootTimers.set(entry.id, boot)
3208
+ bootArmed.set(entry.id, boot)
1834
3209
  } else {
1835
3210
  tick()
1836
3211
  }
@@ -1972,38 +3347,65 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
1972
3347
  path: '/session-superagent/state',
1973
3348
  handler: async (req, res) => {
1974
3349
  if (req.method !== 'GET') { res.statusCode = 405; res.end('method not allowed'); return }
1975
- const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
1976
- const focusSession = url.searchParams.get('sessionId') || ''
3350
+ const scope = requestSessionScope(req)
3351
+ if (scope.error) return json(res, 400, { error: scope.error })
3352
+ const focusSession = scope.sessionId
1977
3353
  const state = readState()
1978
3354
  // 审核 T37 M1:状态文件里只要有一个 `null` 值(手改、旧版写坏、半截写入),
1979
3355
  // `/state` 就会在 `w.id` 上抛 —— **整个面板全灭**。`watch_status` 早就有 filter(Boolean),
1980
3356
  // 这里漏了同一个过滤。
1981
3357
  const allWatchers = Object.values(state.watchers || {}).filter(Boolean)
3358
+ // sessionId 是服务端硬过滤,不只是前端隐藏;全局旧入口与 scope=global 才保留全量。
3359
+ const visibleWatchers = focusSession
3360
+ ? allWatchers.filter((watcher) => watcher.sessionId === focusSession)
3361
+ : allWatchers
1982
3362
  // 只有 GitHub 守才需要 `gh`:全 Gitee 的客户看到「gh 未登录」是纯噪音,
1983
3363
  // 而且那两条探测每次都要 spawn 一个进程(面板 5 秒一刷)。
1984
- const needsGh = allWatchers.some((w) => w && w.provider !== 'gitee')
3364
+ const needsGh = visibleWatchers.some((w) => w && w.provider !== 'gitee')
1985
3365
  if (needsGh) tokenScopes().catch(() => {})
1986
3366
  const gh = needsGh ? await ghHealth() : { ok: null, skipped: '没有 GitHub 守' }
1987
3367
  // 全局预算:守越多,每守分到的事件条数越少(100 条守时每人 2 条,总量 ≤ 240)
1988
- const perWatcherEvents = Math.max(1, Math.min(STATE_EVENTS_PER_WATCHER, Math.floor(STATE_EVENTS_BUDGET / Math.max(1, allWatchers.length))))
1989
- const watchers = allWatchers.map((w) => ({
3368
+ const perWatcherEvents = Math.max(1, Math.min(STATE_EVENTS_PER_WATCHER, Math.floor(STATE_EVENTS_BUDGET / Math.max(1, visibleWatchers.length))))
3369
+ const watchers = visibleWatchers.map((w) => ({
1990
3370
  id: w.id || (w.repo + '#' + w.sessionId),
1991
3371
  repo: w.repo,
1992
3372
  // 面板要能一眼分出 GitHub / Gitee:否则行内只能靠 id 前缀猜
1993
3373
  provider: w.provider === 'gitee' ? 'gitee' : 'github',
3374
+ executionMode: w.executionMode === 'worker' ? 'worker' : undefined,
1994
3375
  ackLabel: w.ackLabel || defaultAckLabel(w.provider, brand.defaultAckLabels),
1995
3376
  // 会话忙时真正排在 FIFO 里的条数;0 表示没有排队,不靠猜 lastDeferred。
1996
3377
  queuedWakes: wakeQueueCount(w.sessionId, ctx),
1997
3378
  sessionId: w.sessionId,
3379
+ // PR 响应监控(Task 6):面板靠 kind 决定「审计 / 对抗性审计 / 执行方式」三项显不显示。
3380
+ // 老状态文件没有 kind 字段,用 id 前缀兜底 —— 与 migratePrWatchers / prStatusView 同一判法。
3381
+ kind: w.kind === 'pr' || String(w.id || (w.repo + '#' + w.sessionId)).startsWith('pr:') ? 'pr' : 'issue',
1998
3382
  intervalSec: w.intervalSec,
1999
3383
  enabled: isEnabled(w),
2000
3384
  cursor: w.cursor ?? null,
2001
3385
  lastPoll: w.lastPoll ?? null,
3386
+ ...(() => {
3387
+ const health = pollHealth(w, { bootAt: bootPollBootAt() })
3388
+ return STOPPED_STATES.has(health.state) ? { poll: health.state } : {}
3389
+ })(),
2002
3390
  lastWake: w.lastWake ?? null,
2003
3391
  lastWakeCount: w.lastWakeCount ?? 0,
3392
+ // 最近唤醒的那一条(编号 + 标题 + 类型):弹层「正在处理哪一条」的唯一数据来源。
3393
+ // lastBatch 只有编号且客户端从不读;这里只回一条,条数看 lastWakeCount,
3394
+ // 否则 batchLimit 调大后 /state 会撞 50KB 门禁而弹层一行根本放不下。
3395
+ lastWakeItem: w.lastWakeItem && typeof w.lastWakeItem === 'object' ? w.lastWakeItem : null,
2004
3396
  lastAbsorbed: w.lastAbsorbed ?? 0,
2005
3397
  lastError: w.lastError ?? null,
2006
- filters: w.filters ?? null,
3398
+ // 面板只读/写这组 filters;skipBots/skipDrafts/skipClosed 是轮询内部配置。
3399
+ // 显式投影既保留 onlyNewComments,也避免每个守重复回传客户端从不读的三个布尔。
3400
+ filters: w.filters && typeof w.filters === 'object' && !Array.isArray(w.filters) ? {
3401
+ labels: Array.isArray(w.filters.labels) ? w.filters.labels : [],
3402
+ ignoreLabels: Array.isArray(w.filters.ignoreLabels) ? w.filters.ignoreLabels : [],
3403
+ onlyAssigned: w.filters.onlyAssigned === true,
3404
+ // 默认 false 省略以守住 20 守 /state 体积;客户端与 normalizeFilters 缺省都按 false。
3405
+ ...(w.filters.onlyNewComments === true ? { onlyNewComments: true } : {}),
3406
+ assignee: w.filters.assignee || null,
3407
+ allowAuthors: Array.isArray(w.filters.allowAuthors) ? w.filters.allowAuthors : [],
3408
+ } : null,
2007
3409
  batchLimit: w.batchLimit ?? 5,
2008
3410
  maxWakesPerHour: w.maxWakesPerHour ?? DEFAULT_WAKES_PER_HOUR,
2009
3411
  sessionMaxWakes: w.sessionMaxWakes ?? 12,
@@ -2011,24 +3413,33 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2011
3413
  nextAt: w.nextAt ?? null,
2012
3414
  lastDeferred: w.lastDeferred ?? null,
2013
3415
  observe: w.observe === true,
3416
+ // 审计三项:面板表单直接渲染它们,/state 少一个字段面板就安静地显示 undefined。
3417
+ audit: w.audit === true,
3418
+ adversarialAudit: w.adversarialAudit === true,
3419
+ auditMode: w.auditMode === 'inline' ? 'inline' : 'subagent',
2014
3420
  // 审核 T37 M2:`?? []` 只挡 null/undefined —— 字段是数字时 `.slice` 不是函数,`/state` 直接 500。
2015
3421
  filteredLog: (Array.isArray(w.filteredLog) ? w.filteredLog : []).slice(-5),
2016
3422
  filterCounts: w.filterCounts ?? {},
2017
3423
  repoAccess: w.repoAccess ?? null,
2018
3424
  lastReopened: w.lastReopened ?? null,
2019
3425
  priority: w.priority ?? null,
2020
- isolated: w.isolated === true,
2021
- workdir: w.workdir ?? null,
2022
- lastWorktree: w.lastWorktree ?? null,
3426
+ // PR 守不做隔离执行:`prepareIsolation` 要在 `entry.workdir` 的本地仓库里建 worktree,
3427
+ // 而 PR 在别人的仓库里,建出来的树对修复毫无用处。对外不再返回这几个字段,
3428
+ // 面板据此也不渲染「隔离执行 / 隔离工作目录」(2026-11-13 review B7)。
3429
+ ...(w.kind === 'pr' ? {} : {
3430
+ isolated: w.isolated === true,
3431
+ workdir: w.workdir ?? null,
3432
+ lastWorktree: w.lastWorktree ?? null,
3433
+ isolateKeepDays: w.isolateKeepDays ?? DEFAULT_ISOLATE_KEEP_DAYS,
3434
+ maxIsolated: w.maxIsolated ?? 5,
3435
+ }),
2023
3436
  activeHours: w.activeHours ?? null,
2024
- isolateKeepDays: w.isolateKeepDays ?? DEFAULT_ISOLATE_KEEP_DAYS,
2025
- maxIsolated: w.maxIsolated ?? 5,
2026
3437
  history: (Array.isArray(w.history) ? w.history : []).slice(-5),
2027
3438
  // 唤醒质量(《为什么做这个产品》的三个成功指标):没有这三个数,「不打断」只是信念
2028
3439
  quality: wakeQuality(w),
2029
3440
  events: (Array.isArray(w.events) ? w.events : []).slice(-perWatcherEvents),
2030
3441
  // 同一个仓库被别的会话也守着:客户该知道「还有谁在看」
2031
- otherSessions: allWatchers.filter((peer) => peer && peer.repo === w.repo && peer.sessionId !== w.sessionId).map((peer) => peer.sessionId),
3442
+ otherSessions: focusSession ? [] : visibleWatchers.filter((peer) => peer && peer.repo === w.repo && peer.sessionId !== w.sessionId).map((peer) => peer.sessionId),
2032
3443
  // 分类放在服务端做一次:面板按 kind 给「下一步」按钮,不用自己解析中文
2033
3444
  lastErrorKind: w.lastError ? classifyGhError(String(w.lastError)).kind : null,
2034
3445
  lastErrorAt: w.lastErrorAt || null,
@@ -2037,7 +3448,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2037
3448
  daily: dailySummary(w.dailyWakes),
2038
3449
  busy: busierThanUsual(dailySummary(w.dailyWakes)),
2039
3450
  silentWakes: w.silentWakes ?? 0,
2040
- note: w.goal ?? '',
3451
+ note: focusSession || scope.explicitGlobal ? (w.goal ?? '') : '',
2041
3452
  title: sessionTitle(w.sessionId),
2042
3453
  }))
2043
3454
  const stateBody = {
@@ -2050,7 +3461,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2050
3461
  stateSource,
2051
3462
  // 会话级用量:上限够不够,客户应该一眼看到(数据都在状态里,零新增请求)
2052
3463
  sessionUsage: (() => {
2053
- const list = Object.values(state.watchers || {})
3464
+ const list = visibleWatchers
2054
3465
  const usage = list.length === 0 ? null : sessionWakesLastHour(list, focusSession)
2055
3466
  const cap = list.length === 0 ? null : (Number(list[0].sessionMaxWakes) || 12)
2056
3467
  const capped = countCapped(list)
@@ -2063,7 +3474,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2063
3474
  runningVersion: SERVER_VERSION,
2064
3475
  triageSignals: TRIAGE_SIGNALS,
2065
3476
  tokenScopes: scopesCache.value || null,
2066
- isolation: isolationReport(Object.values(state.watchers || {})),
3477
+ isolation: isolationReport(visibleWatchers),
2067
3478
  sessionTitle: sessionTitle(focusSession),
2068
3479
  retryPolicy: { budgetAttempts: RETRY_BUDGET_ATTEMPTS, slowCapMinutes: RETRY_SLOW_CAP_MINUTES },
2069
3480
  defaults: { sessionMaxWakes: DEFAULT_SESSION_WAKES, maxWakesPerHour: DEFAULT_WAKES_PER_HOUR, isolateKeepDays: DEFAULT_ISOLATE_KEEP_DAYS, batchLimit: DEFAULT_BATCH_LIMIT },
@@ -2071,8 +3482,16 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2071
3482
  // 放在 stateBody 里就自动进了 ETag 的稳定字段:配置变了,下一次轮询一定不是 304。
2072
3483
  brandName: brand.brandName,
2073
3484
  defaultAckLabels: brand.defaultAckLabels,
2074
- watchers: watchers.map((w) => ({ ...w, goal: goalView(ctx, w.sessionId) })),
3485
+ watchers: watchers.map((w) => ({
3486
+ ...w,
3487
+ goal: focusSession || scope.explicitGlobal ? goalView(ctx, w.sessionId) : null,
3488
+ })),
2075
3489
  }
3490
+ stateBody.modular = buildModularProjection(
3491
+ focusSession ? scopeModularStateToSession(state, focusSession) : state,
3492
+ ctx,
3493
+ )
3494
+ if (scope.legacyGlobal) stateBody.modular = { ...stateBody.modular, draft: null }
2076
3495
  // ETag/304:面板每 5 秒拉一次 /state,没变化时没必要重传整份 JSON ——
2077
3496
  // 和我们自己对 GitHub 做的事一样,只是方向反过来(这次我们是服务端)。
2078
3497
  // 依据:RFC 9110 §15.4.5 规定 304 不带正文,客户端沿用本地缓存。
@@ -2187,6 +3606,224 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2187
3606
  return true
2188
3607
  }
2189
3608
 
3609
+ addRoute({
3610
+ kind: 'exact',
3611
+ path: '/session-superagent/tickets',
3612
+ handler: async (req, res) => {
3613
+ if (req.method === 'GET') {
3614
+ const scope = requestSessionScope(req)
3615
+ if (scope.error) return json(res, 400, { error: scope.error })
3616
+ const state = readState()
3617
+ const view = buildModularProjection(scope.sessionId ? scopeModularStateToSession(state, scope.sessionId) : state, ctx)
3618
+ return json(res, 200, { records: view.records, execution: view.execution })
3619
+ }
3620
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
3621
+ if (!guardWrite(req, res)) return
3622
+ const body = await readBody(req, res)
3623
+ if (!body) return
3624
+ const scope = requestSessionScope(req, body)
3625
+ if (scope.error) return json(res, 400, { error: scope.error })
3626
+ const action = String(body.action || '')
3627
+ const ticketId = String(body.ticketId || '')
3628
+ if (!['resume', 'stop', 'pause-processing', 'resume-processing'].includes(action)) return json(res, 400, { error: 'action must be resume, stop, pause-processing or resume-processing' })
3629
+ const state = readState()
3630
+ if (action === 'pause-processing' || action === 'resume-processing') {
3631
+ // executorPaused 是全局开关;会话页不能用无归属 ID 的动作暂停其他会话。
3632
+ if (scope.sessionId) return json(res, 403, { error: 'processing pause requires global scope', code: 'global_scope_required' })
3633
+ const next = commitModularState(modularVersionOf(state), (disk) => ({ ...disk, executorPaused: action === 'pause-processing' }))
3634
+ return json(res, 200, { ok: true, paused: next.executorPaused === true })
3635
+ }
3636
+ const ticket = state.tickets && state.tickets[ticketId]
3637
+ if (!ticket) return json(res, 404, { error: 'ticket not found: ' + ticketId })
3638
+ if (scope.sessionId && !ticketBelongsToSession(state, ticket, scope.sessionId)) {
3639
+ return json(res, 403, { error: 'cross-session Ticket write refused', code: 'cross_session_write', ticketId })
3640
+ }
3641
+ const assignment = state.assignments && state.assignments[ticket.assignmentId]
3642
+ const mode = assignment && String(assignment.sessionId).startsWith('worker-') ? 'worker' : 'inline'
3643
+ if (action === 'resume' && mode === 'inline') {
3644
+ const agents = agentsService(ctx)
3645
+ const live = agents && typeof agents.get === 'function' ? agents.get(ticket.ownerSessionId) : null
3646
+ if (!live) return json(res, 409, { error: 'resume session is missing; Ticket remains ended', ticket })
3647
+ const gate = decideWake(live.status, await runningSubagents(ctx, ticket.ownerSessionId))
3648
+ if (!gate.ok) return json(res, 409, { error: 'resume session is busy; Ticket remains ended', ticket })
3649
+ }
3650
+ try {
3651
+ const result = await mutateRuntime(async (current) => {
3652
+ if (scope.sessionId && !ticketBelongsToSession(current, current.tickets && current.tickets[ticketId], scope.sessionId)) {
3653
+ const error = new Error('cross-session Ticket write refused')
3654
+ error.code = 'CROSS_SESSION_WRITE'
3655
+ throw error
3656
+ }
3657
+ if (action === 'stop') return completeRuntimeTicket(current, ticketId, {
3658
+ mode, executor: mode === 'worker' ? createDshExecutor(ctx) : undefined,
3659
+ reason: 'human-stop', eventId: String(body.eventId || `stop:${Date.now()}`),
3660
+ })
3661
+ return routeRuntimeEvent(current, {
3662
+ threadKey: ticket.threadKey,
3663
+ id: String(body.eventId || `resume:${Date.now()}`),
3664
+ type: 'resume', actor: 'human', body: String(body.body || 'manual resume'),
3665
+ }, {
3666
+ mode, sessionId: ticket.ownerSessionId, workdir: ticket.workdir || process.cwd(), deferExecution: true,
3667
+ })
3668
+ })
3669
+ if (action === 'resume' && mode === 'worker') {
3670
+ const id = 'resume:' + createHash('sha1').update(ticketId + ':' + Date.now()).digest('hex').slice(0, 24)
3671
+ const host = workerOutbox(ctx)
3672
+ await host.enqueue({
3673
+ id, ticketId, channel: { type: 'worker', repo: ticket.threadKey, number: ticket.threadKey },
3674
+ body: renderRuntimePrompt('resume', { ticketId, reason: String(body.body || 'manual resume') }, { locale: state.locale }),
3675
+ })
3676
+ const report = await host.flush({ ticketId, limit: 4 })
3677
+ if (report.sent < 1) return json(res, 409, { error: 'worker resume was not settled', report })
3678
+ } else if (action === 'resume') {
3679
+ const prompt = renderRuntimePrompt('resume', { ticketId, reason: String(body.body || 'manual resume') }, { locale: state.locale })
3680
+ wakeMerged(ctx, result.ticket.ownerSessionId, prompt, (delivery) => {
3681
+ if (delivery && (delivery.ok || delivery.queued === true)) return
3682
+ mutateRuntime((current) => {
3683
+ const latest = current.tickets && current.tickets[ticketId]
3684
+ if (!latest || latest.assignmentId !== result.assignment.id) return { state: current }
3685
+ return completeRuntimeTicket(current, ticketId, {
3686
+ mode: 'inline', reason: 'resume-delivery-failed', eventId: `resume-failed:${ticketId}:${Date.now()}`,
3687
+ detail: String(delivery && delivery.reason || 'resume delivery failed'),
3688
+ })
3689
+ }).catch(() => {})
3690
+ }, 'resume:' + ticketId, brand.brandName)
3691
+ }
3692
+ return json(res, action === 'resume' && mode === 'inline' ? 202 : 200, { ok: true, ticket: result.ticket, assignment: result.assignment, queued: action === 'resume' && mode === 'inline' })
3693
+ } catch (error) {
3694
+ return json(res, error && error.code === 'CROSS_SESSION_WRITE' ? 403 : 409, { error: String(error && error.message || error) })
3695
+ }
3696
+ },
3697
+ })
3698
+ addRoute({
3699
+ kind: 'exact',
3700
+ path: '/session-superagent/outbox',
3701
+ handler: async (req, res) => {
3702
+ if (req.method === 'GET') {
3703
+ const scope = requestSessionScope(req)
3704
+ if (scope.error) return json(res, 400, { error: scope.error })
3705
+ const state = readState()
3706
+ const view = buildModularProjection(scope.sessionId ? scopeModularStateToSession(state, scope.sessionId) : state, ctx)
3707
+ return json(res, 200, { outbox: view.records.outbox })
3708
+ }
3709
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
3710
+ if (!guardWrite(req, res)) return
3711
+ const body = await readBody(req, res)
3712
+ if (!body) return
3713
+ const scope = requestSessionScope(req, body)
3714
+ if (scope.error) return json(res, 400, { error: scope.error })
3715
+ const ticketId = String(body.ticketId || '').trim()
3716
+ try {
3717
+ const host = runtimeOutbox(ctx, Array.isArray(options.providers) ? options.providers : [])
3718
+ if (!scope.sessionId) {
3719
+ const report = await host.flush({ limit: 100, ...(ticketId ? { ticketId } : {}) })
3720
+ return json(res, report.failed > 0 ? 409 : 200, report)
3721
+ }
3722
+ const state = readState()
3723
+ const scoped = scopeModularStateToSession(state, scope.sessionId)
3724
+ const ownedOutboxIds = new Set(modularOutboxRows(scoped).map((message) => message.ticketId).filter(Boolean))
3725
+ if (ticketId) {
3726
+ const ticket = state.tickets && state.tickets[ticketId]
3727
+ if (ticket && !ticketBelongsToSession(state, ticket, scope.sessionId)) {
3728
+ return json(res, 403, { error: 'cross-session Outbox flush refused', code: 'cross_session_write', ticketId })
3729
+ }
3730
+ if (!ticket && !ownedOutboxIds.has(ticketId)) return json(res, 404, { error: 'Outbox Ticket not found: ' + ticketId })
3731
+ }
3732
+ // 会话 flush 只逐 Ticket 处理自己的消息,并关闭全量 recover;否则会把其他会话
3733
+ // sending 的消息一起恢复/外发。全局旧入口仍走原来的整队列 flush。
3734
+ const ids = ticketId ? [ticketId] : [...ownedOutboxIds]
3735
+ const reports = []
3736
+ for (const id of ids) reports.push(await host.flush({ ticketId: id, limit: 100, recover: false }))
3737
+ const finalState = readState()
3738
+ const finalRows = modularOutboxRows(scopeModularStateToSession(finalState, scope.sessionId))
3739
+ const results = reports.flatMap((report) => report.results || [])
3740
+ const sent = results.filter((result) => result.status === 'sent').length
3741
+ const failed = results.filter((result) => result.status === 'failed').length
3742
+ const stale = results.filter((result) => result.status === 'stale').length
3743
+ const alreadySent = results.filter((result) => result.status === 'sent' && result.alreadySent).length
3744
+ const nextAt = reports.map((report) => report.nextAt).filter(Boolean).sort()[0] || null
3745
+ const report = {
3746
+ status: reports.length === 1 ? reports[0].status : failed ? 'failed' : sent ? 'sent' : 'empty',
3747
+ queueStatus: reports.length === 1 ? reports[0].queueStatus : (ids.length ? null : 'empty'),
3748
+ state: {
3749
+ outboxVersion: finalState.outbox && finalState.outbox.outboxVersion || 1,
3750
+ revision: modularVersionOf(finalState),
3751
+ outbox: finalRows,
3752
+ },
3753
+ recovery: null,
3754
+ recoveredIds: [],
3755
+ results,
3756
+ sent,
3757
+ failed,
3758
+ stale,
3759
+ alreadySent,
3760
+ nextAt,
3761
+ }
3762
+ return json(res, failed > 0 ? 409 : 200, report)
3763
+ } catch (error) {
3764
+ return json(res, 409, { error: String(error && error.message || error) })
3765
+ }
3766
+ },
3767
+ })
3768
+ addRoute({
3769
+ kind: 'exact',
3770
+ path: '/session-superagent/draft',
3771
+ handler: async (req, res) => {
3772
+ if (req.method === 'GET') {
3773
+ const scope = requestSessionScope(req)
3774
+ if (scope.error) return json(res, 400, { error: scope.error })
3775
+ const state = readState()
3776
+ const draft = scope.sessionId
3777
+ ? scopeModularStateToSession(state, scope.sessionId).draft
3778
+ : scope.explicitGlobal ? state.draft : null
3779
+ return json(res, 200, { draft: draft || null })
3780
+ }
3781
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
3782
+ if (!guardWrite(req, res)) return
3783
+ const body = await readBody(req, res)
3784
+ if (!body) return
3785
+ const scope = requestSessionScope(req, body)
3786
+ if (scope.error) return json(res, 400, { error: scope.error })
3787
+ const ticketId = String(body.ticketId || '').trim()
3788
+ if (!ticketId) return json(res, 400, { error: 'ticketId is required' })
3789
+ const revision = body.revision === undefined ? 0 : Number(body.revision)
3790
+ if (!Number.isSafeInteger(revision) || revision < 0) return json(res, 400, { error: 'revision must be a non-negative integer' })
3791
+ const state = readState()
3792
+ if (scope.sessionId) {
3793
+ const ticket = state.tickets && state.tickets[ticketId]
3794
+ if (!ticket) return json(res, 404, { error: 'ticket not found: ' + ticketId })
3795
+ if (!ticketBelongsToSession(state, ticket, scope.sessionId)) {
3796
+ return json(res, 403, { error: 'cross-session draft write refused', code: 'cross_session_write', ticketId })
3797
+ }
3798
+ if (state.draft && !scopeModularStateToSession(state, scope.sessionId).draft) {
3799
+ return json(res, 403, { error: 'draft belongs to another session', code: 'cross_session_write', ticketId })
3800
+ }
3801
+ }
3802
+ try {
3803
+ const current = state.draft || createDraft({ ticketId, body: '' }, { revision: 0 })
3804
+ if (revision !== current.revision) {
3805
+ return json(res, 409, { error: 'draft revision conflict', currentRevision: current.revision, expectedRevision: revision })
3806
+ }
3807
+ const nextRevision = current.revision + 1
3808
+ const nextDraft = body.clear === true
3809
+ ? clearDraft(current, { saved: { ticketId, body: '' }, revision: nextRevision })
3810
+ : editDraft(current, { ticketId, body: String(body.body || '') }, { revision: nextRevision })
3811
+ const next = commitModularState(modularVersionOf(state), (disk) => {
3812
+ if ((disk.draft && disk.draft.revision || 0) !== current.revision) {
3813
+ const error = new Error('draft revision conflict')
3814
+ error.code = 'DRAFT_REVISION_CONFLICT'
3815
+ throw error
3816
+ }
3817
+ return { ...disk, draft: nextDraft }
3818
+ })
3819
+ if (next.writeError) return json(res, 409, { error: next.writeError.message })
3820
+ return json(res, 200, { draft: next.draft })
3821
+ } catch (error) {
3822
+ return json(res, 400, { error: String(error && error.message || error) })
3823
+ }
3824
+ },
3825
+ })
3826
+
2190
3827
  // Create or update a watcher from the panel. The panel is session-scoped,
2191
3828
  // so it must send the session id it is bound to.
2192
3829
  addRoute({
@@ -2197,24 +3834,30 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2197
3834
  if (!guardWrite(req, res)) return // 来源不对:已回 403
2198
3835
  const body = await readBody(req, res)
2199
3836
  if (!body) return // 已回 413
3837
+ const scope = requestSessionScope(req, body)
3838
+ if (scope.error) return json(res, 400, { error: scope.error })
2200
3839
  // pause / resume / delete target an existing watcher by id; the
2201
3840
  // create path below is the default when no action is supplied.
2202
3841
  if (body.action) {
2203
3842
  const action = String(body.action)
2204
3843
  const id = String(body.id || '')
2205
3844
  const state = readState()
3845
+ const target = state.watchers && state.watchers[id]
3846
+ if (scope.sessionId && target && target.sessionId !== scope.sessionId) {
3847
+ return json(res, 403, { error: 'cross-session watcher write refused', code: 'cross_session_write', id })
3848
+ }
2206
3849
  // 立刻跑一次(对应 Claude Code Action 的 interactive 模式):
2207
3850
  // 不等定时器,马上轮询一次;仍然受 filters / ack 标签约束。
2208
3851
  if (action === 'poll') {
2209
- const entry = state.watchers && state.watchers[id]
3852
+ const entry = target
2210
3853
  if (!entry) return json(res, 404, { error: '没有这条主理鱼(' + id + ')—— 刷新面板看看它还在不在;可能是别的窗口刚删掉', code: 'unknown_watcher' })
2211
3854
  if (!isEnabled(entry)) return json(res, 409, { error: '这条主理鱼是暂停状态,先点「恢复」再试', code: 'paused' })
2212
3855
  if (inFlight.has(id)) return json(res, 409, { error: '上一轮轮询还没结束(网络慢或 GitHub 慢)—— 等十几秒再看', code: 'in_flight', id })
2213
- const every = Math.max(30, Number(entry.intervalSec) || 60) * 1000
2214
- inFlight.add(id)
2215
- pollOnce(ctx, entry, every, brand)
2216
- .catch(() => {})
2217
- .finally(() => { inFlight.delete(id); persistEntry(entry) })
3856
+ // 人工点「立即」= 明确要求现在就跑:先清退避窗口,否则 PR 守在
3857
+ // `pollPrOnce` 第 2 步的 `nextAt` 早退里静默跳过 —— 路由照回 202、
3858
+ // 前端转完圈就停,用户看到「点了没反应」(2026-11-17 真机 + PR #65 review 实证:
3859
+ // nextAt 还剩 25 分钟时点「立即」,gh 调用 0 次)。
3860
+ runManualPoll(entry)
2218
3861
  return json(res, 202, { ok: true, action, id, polling: true })
2219
3862
  }
2220
3863
  const result = applyWatcherAction(state, { action, id })
@@ -2226,7 +3869,20 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2226
3869
  if (result.deleted || !isEnabled(result)) stopWatcher(id)
2227
3870
  writeState(state)
2228
3871
  // 只有「显式启用」才重启轮询:result 可能是部分字段,缺 enabled 时不该把守拉起来
2229
- if ((result.enabled === true || String(result.enabled) === 'true') && state.watchers[id]) startWatcher(state.watchers[id])
3872
+ if ((result.enabled === true || String(result.enabled) === 'true') && state.watchers[id]) {
3873
+ startWatcher(state.watchers[id])
3874
+ // 手工恢复 = 明确要求「现在就跑」。`startWatcher` 两条路都不会立刻轮询:
3875
+ // 定时器已在(`timers.has`)就直接 return;不在则排一个 0~5 秒的 boot tick。
3876
+ // 而「立即」按钮又被暂停态挡着 —— 用户恢复完看不到任何反应。
3877
+ // 2026-11-17 用户实测:「从暂停恢复运行后也不触发」。
3878
+ const revived = state.watchers[id]
3879
+ if (runManualPoll(revived)) {
3880
+ // 这一跑就是「首轮」,把 `startWatcher` 刚排的 boot tick 撤掉 ——
3881
+ // 否则 5 秒内会连跑两轮(多一次 API 调用,`onlyNewComments` 下更明显)。
3882
+ const boot = bootTimers.get(id)
3883
+ if (boot) { clearTimeout(boot); bootTimers.delete(id) }
3884
+ }
3885
+ }
2230
3886
  return json(res, 200, result)
2231
3887
  }
2232
3888
  // 认三种写法:`owner/name` / `gitee:owner/name` / `https://gitee.com/owner/name`。
@@ -2235,7 +3891,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2235
3891
  if (!spec.ok) return json(res, 400, { error: spec.error })
2236
3892
  const repo = spec.repo
2237
3893
  const provider = spec.provider
2238
- const sessionId = String(body.sessionId || '').trim()
3894
+ const sessionId = scope.sessionId
2239
3895
  // 审核 T19:sessionId 以前无上限、无字符集校验 —— 它会进 id、落进状态文件、拼进唤醒消息。
2240
3896
  if (sessionId.length > 200) return json(res, 400, { error: 'sessionId too long (max 200)' })
2241
3897
  if (!sessionId) return json(res, 400, { error: 'sessionId is required (open the panel in the session that should be woken)' })
@@ -2252,9 +3908,17 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2252
3908
  const intervalSec = Math.max(30, Math.min(3600, Math.round(Number(body.intervalSec) || 60)))
2253
3909
  const state = readState()
2254
3910
  state.watchers = state.watchers || {}
3911
+ // PR 响应监控:面板的「监控类型」分段控件决定 id 前缀。
3912
+ // 同一仓库的 issue 守和 PR 守必须并存(互不覆盖),所以 PR 守的 id 多一层 `pr:`。
3913
+ // 工具侧(watch_pr_start)用的是同一前缀,两条创建路径才能认到同一条守。
3914
+ const isPrWatch = String(body.watchKind || body.kind || '') === 'pr'
2255
3915
  // id 里带 provider:同一个 owner/name 在两家可能都存在,混在一起会互相覆盖
2256
- const id = (provider === 'gitee' ? 'gitee:' : '') + repo + '#' + sessionId
2257
- const created = !(state.watchers && state.watchers[id])
3916
+ const id = (isPrWatch ? 'pr:' : '') + (provider === 'gitee' ? 'gitee:' : '') + repo + '#' + sessionId
3917
+ const existing = state.watchers && state.watchers[id]
3918
+ if (existing && existing.sessionId !== sessionId) {
3919
+ return json(res, 403, { error: 'watcher id ownership mismatch', code: 'cross_session_write', id })
3920
+ }
3921
+ const created = !existing
2258
3922
  // 审核 T19:新建没有任何上限 —— 100 次 POST 就是 100 条守(每条一个定时器)。
2259
3923
  // 工具路径早就有 MAX_WATCHERS_PER_SESSION,HTTP 路径漏了;这里再补一个全局上限。
2260
3924
  if (created) {
@@ -2269,15 +3933,37 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2269
3933
  return json(res, 429, { error: '全局最多 ' + MAX_WATCHERS_TOTAL + ' 条守' })
2270
3934
  }
2271
3935
  }
3936
+ if (body.executionMode !== undefined && !['inline', 'worker'].includes(String(body.executionMode))) {
3937
+ return json(res, 400, { error: 'executionMode must be inline or worker' })
3938
+ }
2272
3939
  const entry = state.watchers[id] || {
2273
3940
  id, repo, provider, sessionId, cursor: null, seen: {}, lastReported: {},
3941
+ executionMode: 'inline',
2274
3942
  cooldownMs: 180000, createdAt: new Date().toISOString(),
2275
3943
  filters: normalizeFilters(), batchLimit: 5, maxWakesPerHour: 6,
2276
3944
  wakeTimes: [], consecutiveFailures: 0, ackLabel: defaultAckLabel(provider, brand.defaultAckLabels),
2277
3945
  isolated: false, workdir: null,
2278
3946
  }
2279
3947
  entry.provider = provider
3948
+ if (body.executionMode !== undefined) entry.executionMode = String(body.executionMode)
2280
3949
  entry.intervalSec = intervalSec
3950
+ // PR 响应监控四项:面板提交的 watchKind 已经决定了 id 前缀,这里把类型与审计配置落进条目。
3951
+ // 编辑已有守时 body 可能不带这几项(工具调用方只改间隔),所以用 `undefined` 判「没传」而不是假值。
3952
+ if (isPrWatch) {
3953
+ entry.kind = 'pr'
3954
+ if (!entry.seenComments || typeof entry.seenComments !== 'object' || Array.isArray(entry.seenComments)) {
3955
+ entry.seenComments = {}
3956
+ }
3957
+ entry.audit = body.audit === undefined ? entry.audit === true : body.audit === true
3958
+ entry.adversarialAudit = body.adversarialAudit === undefined ? entry.adversarialAudit === true : body.adversarialAudit === true
3959
+ entry.auditMode = body.auditMode === undefined ? (entry.auditMode === 'inline' ? 'inline' : 'subagent') : (body.auditMode === 'inline' ? 'inline' : 'subagent')
3960
+ } else {
3961
+ // 从 PR 切回 issue:id 会变(没有 `pr:` 前缀),这里只是防御 —— 别让旧字段跟着新守。
3962
+ delete entry.seenComments
3963
+ delete entry.audit
3964
+ delete entry.adversarialAudit
3965
+ delete entry.auditMode
3966
+ }
2281
3967
  // 只有真正带了 goal 才覆盖:GUI 编辑保存不带这个字段,覆盖会清空
2282
3968
  if (typeof body.goal === 'string') entry.goal = body.goal.slice(0, 500)
2283
3969
  // 竞品蒸馏:触发要有许可(label/指派/跳过机器人草稿)、单次别铺开太多、每小时有上限
@@ -2339,14 +4025,14 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2339
4025
  warnings = pre.warnings || []
2340
4026
  if (pre.access) entry.repoAccess = pre.access
2341
4027
  }
2342
- state.watchers[id] = entry
4028
+ state.watchers[id] = migrateV1Watermark(entry)
2343
4029
  writeState(state)
2344
4030
  // 编辑已有 watcher 时,间隔/配置变化要立刻生效:startWatcher 会因为 timer 已存在而直接返回
2345
4031
  if (entry.enabled) {
2346
4032
  stopWatcher(id)
2347
4033
  probeAccess(entry).catch(() => {})
2348
4034
 
2349
- startWatcher(entry)
4035
+ startWatcher(state.watchers[id])
2350
4036
  }
2351
4037
  json(res, 200, { ok: true, id, repo, intervalSec, enabled: entry.enabled, warnings })
2352
4038
  },
@@ -2782,7 +4468,14 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2782
4468
  try {
2783
4469
  const state = readState()
2784
4470
  for (const entry of Object.values(state.watchers || {})) {
2785
- if (entry && entry.enabled) startWatcher(entry)
4471
+ if (!entry || !entry.enabled || !entry.id) continue
4472
+ try { startWatcher(entry) } catch (error) {
4473
+ // 单条坏守不能连累其他守;错误必须落盘,否则 doctor/readState 仍误报正常。
4474
+ try {
4475
+ entry.lastError = '启动挂载失败:' + String((error && error.message) || error).slice(0, 160)
4476
+ persistEntry(entry)
4477
+ } catch {}
4478
+ }
2786
4479
  }
2787
4480
  } catch {}
2788
4481
 
@@ -2803,6 +4496,11 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2803
4496
  format: { type: 'string', description: "'text' (default) or 'json'." },
2804
4497
  },
2805
4498
  async execute(args) {
4499
+ const toolAgents = agentsService(ctx)
4500
+ const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
4501
+ const sessionId = agent && agent.id
4502
+ if (!sessionId) return toolError(args, 'no live session — watch_ack must be called from a session turn')
4503
+
2806
4504
  // 编号允许两种:GitHub 是数字(14),Gitee 的 issue 是字符串(IKSQJH)。
2807
4505
  // 以前一律 Number(),Gitee 那边会被过滤成空数组,报「number is required」—— 看着像用户没填。
2808
4506
  const numbers = String(args.numbers || args.number || '')
@@ -2818,55 +4516,100 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2818
4516
  }
2819
4517
  const state = readState()
2820
4518
  const watchers = Object.values(state.watchers || {})
4519
+ // 只认 issue 守:同一个仓库可以同时有 issue 守和 PR 守,不区分 kind 时
4520
+ // 会选中 PR 守并去写 seen/cursor(PR 守的水位字段是 seenComments)——
4521
+ // 等于把 issue 的水位结构写进 PR 守,两边都错乱(2026-11-13 外部 review 的 B9)。
4522
+ const isPrWatcher = (w) => w && (w.kind === 'pr' || String(w.id || '').startsWith('pr:'))
4523
+ const isIssueWatcher = (w) => w && !isPrWatcher(w)
4524
+ // issue #54:同 repo 可由多会话各守一条,ack 的标签与水位只能属于 currentInitiator。
4525
+ const sessionIssueWatchers = watchers.filter((w) => isIssueWatcher(w) && w.sessionId === sessionId)
4526
+ const enabledSessionIssueWatchers = sessionIssueWatchers.filter((w) => w.enabled)
4527
+ if (!args.repo && enabledSessionIssueWatchers.length > 1) {
4528
+ return toolError(args, '本会话有 ' + enabledSessionIssueWatchers.length + ' 条启用中的 issue 守,请用 repo 指定:'
4529
+ + enabledSessionIssueWatchers.map((w) => w.repo).join(', '))
4530
+ }
2821
4531
  const entry = args.repo
2822
- ? watchers.find((w) => w && w.repo === String(args.repo))
2823
- : watchers.find((w) => w && w.enabled)
2824
- if (!entry) return toolError(args, 'no watcher for that repo — start one with watch_start first')
4532
+ ? sessionIssueWatchers.find((w) => w.repo === String(args.repo))
4533
+ : enabledSessionIssueWatchers[0]
4534
+ if (!entry) {
4535
+ // 只有本会话的 PR 守时才给 B9 提示;其它会话的 PR 守不能改变这里的错误语义。
4536
+ const prOnly = watchers.some((w) => isPrWatcher(w) && w.sessionId === sessionId
4537
+ && (!args.repo || w.repo === String(args.repo)))
4538
+ const otherSessions = watchers.some((w) => w && w.sessionId !== sessionId
4539
+ && (!args.repo || w.repo === String(args.repo)))
4540
+ return toolError(args, prOnly
4541
+ ? '这条是 PR 守 —— PR 的评论水位用 watch_pr_ack 推(watch_ack 只处理 issue 守)'
4542
+ : otherSessions
4543
+ ? (args.repo
4544
+ ? '本会话没有监控 ' + String(args.repo) + ' 的 issue 守;该 repo 有其它会话的守,不能代替本会话 ack —— 先 watch_start 建一条'
4545
+ : '本会话没有启用中的 issue 守;状态里有其它会话的守,不能代替本会话 ack —— 先 watch_start 建一条')
4546
+ : 'no watcher for that repo — start one with watch_start first')
4547
+ }
2825
4548
  const label = String(args.label || entry.ackLabel || defaultAckLabel(entry.provider, brand.defaultAckLabels))
2826
4549
  const note = typeof args.note === 'string' ? args.note.trim().slice(0, 200) : ''
2827
4550
  if (args.comment === true && !note) return toolError(args, 'comment:true 需要同时提供 note —— 不会发一条空评论')
2828
- // GitHub 不会因为加标签而自动建标签:不存在时返回 422。先幂等建一次(已存在也返回 422,忽略)。
2829
- // Gitee 没有「建标签」的独立端点(标签必须先存在),所以这边只打标签;
2830
- // 标签不存在时它会 404 —— 让调用方看到真实原因,别假装成功。
2831
- if (entry.provider !== 'gitee') {
2832
- await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/labels`, '-f', `name=${label}`, '-f', 'color=ededed'], { env: ghEnv() })
2833
- }
4551
+ const sources = createSourceRegistry([
4552
+ createGithubProvider({ run, env: ghEnv() }),
4553
+ createGiteeProvider({ token: String(readSecrets().giteeToken || '') }),
4554
+ ...(Array.isArray(options.providers) ? options.providers : []),
4555
+ ])
4556
+ const provider = sources.get(entry.provider, 'ack')
2834
4557
  const results = []
4558
+ const postCursors = new Map()
2835
4559
  let failed = null
2836
4560
  let labelNote = ''
2837
- // Gitee 打标签前要先确保标签存在(它不会像 GitHub 那样自动建)
2838
- if (entry.provider === 'gitee') {
2839
- const ensured = await ensureGiteeLabel({ repo: entry.repo, token: String(readSecrets().giteeToken || ''), label })
2840
- if (ensured.ok) labelNote = ensured.created ? '(已自动新建标签「' + label + '」)' : ''
2841
- else labelNote = '(标签「' + label + '」建不出来:' + String(ensured.error || ensured.status || '').slice(0, 80) + ')'
2842
- }
4561
+ const ackHost = runtimeOutbox(ctx, Array.isArray(options.providers) ? options.providers : [])
2843
4562
  for (const number of numbers) {
2844
- const res = entry.provider === 'gitee'
2845
- ? await (async () => {
2846
- const r = await addGiteeLabel({ repo: entry.repo, token: String(readSecrets().giteeToken || ''), number, label })
2847
- return { code: r.ok ? 0 : 1, stdout: '', stderr: r.ok ? '' : String(r.status || '') + ' ' + String(r.error || '') }
2848
- })()
2849
- : await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/issues/${number}/labels`, '-f', `labels[]=${label}`], { env: ghEnv() })
2850
- if (res.code !== 0) {
2851
- failed = { number, text: redact([res.stdout, res.stderr].filter(Boolean).join(' ').trim()).slice(0, 200), phase: 'label' }
4563
+ const ticketId = `ticket:${entry.provider || 'github'}:${entry.repo}#${number}`
4564
+ const eventCursor = entry.obs && entry.obs[issueKey({ number })] && entry.obs[issueKey({ number })].delivered
4565
+ ? entry.obs[issueKey({ number })].delivered.cursor
4566
+ : entry.seen && entry.seen[String(number)] || 'manual'
4567
+ const id = 'ack:' + createHash('sha1').update(JSON.stringify([
4568
+ entry.id, entry.createdAt || null, number, eventCursor,
4569
+ args.kind === 'pull' ? 'pull' : 'issue', args.comment === true, note, label,
4570
+ ])).digest('hex').slice(0, 24)
4571
+ await ackHost.enqueue({
4572
+ id, ticketId,
4573
+ channel: {
4574
+ type: 'ack', watcherId: entry.id, watcherCreatedAt: entry.createdAt || null, repo: entry.repo, number: String(number), label,
4575
+ kind: args.kind === 'pull' ? 'pull' : 'issue', comment: args.comment === true,
4576
+ },
4577
+ body: note,
4578
+ })
4579
+ const report = await ackHost.flush({ ticketId, limit: 4 })
4580
+ const current = report.results.find((result) => result.id === id)
4581
+ const persisted = await ackHost.read()
4582
+ const stored = persisted.outbox.find((message) => message.id === id)
4583
+ if (current && current.status !== 'sent' || !current && (!stored || stored.status !== 'sent')) {
4584
+ const failedResult = report.results.find((result) => result.status === 'failed') || current
4585
+ failed = {
4586
+ number,
4587
+ text: redact(failedResult && failedResult.error || report.error || 'ack failed').slice(0, 200),
4588
+ phase: failedResult && failedResult.receipt && failedResult.receipt.stage === 'comment' ? 'comment' : 'label',
4589
+ }
2852
4590
  break
2853
4591
  }
2854
- // Delivery(官方原型可吸收的一部分):处理结论不只留在本地,显式 comment:true 时回写原条目。
2855
- if (args.comment === true) {
2856
- const posted = entry.provider === 'gitee'
2857
- ? await (async () => {
2858
- const r = await addGiteeComment({ repo: entry.repo, token: String(readSecrets().giteeToken || ''), number, body: note, kind: args.kind === 'pull' ? 'pull' : 'issue' })
2859
- return { code: r.ok ? 0 : 1, stdout: '', stderr: r.ok ? '' : String(r.status || '') + ' ' + String(r.error || '') }
2860
- })()
2861
- : await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/issues/${number}/comments`, '-f', `body=${note}`], { env: ghEnv() })
2862
- if (posted.code !== 0) {
2863
- failed = { number, text: redact([posted.stdout, posted.stderr].filter(Boolean).join(' ').trim()).slice(0, 200), phase: 'comment' }
4592
+ const receipt = current && current.receipt
4593
+ if (!receipt || !receipt.cursor) {
4594
+ // 崩溃恢复后 sent 消息没有新的发送回执:只重做幂等标签与读回,不重复评论。
4595
+ const reread = await provider.acknowledge({ repo: entry.repo, number, label, kind: args.kind === 'pull' ? 'pull' : 'issue', note: '' })
4596
+ if (!reread.ok) {
4597
+ failed = { number, text: redact(reread.error || 'ack readback failed').slice(0, 200), phase: 'label' }
2864
4598
  break
2865
4599
  }
4600
+ postCursors.set(String(number), reread.cursor)
4601
+ } else {
4602
+ if (receipt.labelCreated) labelNote = '(已自动新建标签「' + label + '」)'
4603
+ postCursors.set(String(number), receipt.cursor)
2866
4604
  }
2867
4605
  results.push(number)
2868
4606
  }
2869
4607
  if (failed) {
4608
+ const current = readState().watchers && readState().watchers[entry.id]
4609
+ const sameGeneration = !entry.createdAt || !current || !current.createdAt || current.createdAt === entry.createdAt
4610
+ if (!current || current.sessionId !== sessionId || !isIssueWatcher(current) || !sameGeneration) {
4611
+ return toolError(args, ackWatcherReplacedMessage(entry.id))
4612
+ }
2870
4613
  // 失败要分两类:会自动恢复的(网络/限流/网关)和必须人动手的(登录/权限/编号)
2871
4614
  let why = classifyGhError(failed.text)
2872
4615
  // Gitee 的 404 有一个特例:仓库存在、**标签不存在**也是 404。
@@ -2893,13 +4636,35 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2893
4636
  const latest = readState()
2894
4637
  const live = latest.watchers && latest.watchers[entry.id]
2895
4638
  const nowIso = new Date().toISOString()
2896
- if (live) {
2897
- live.seen = advanceSeen(live.seen, results.map((number) => ({ number, updated_at: nowIso })))
2898
- // 打标签本身就是一次外部更新,把光标推到当下,避免自己把自己叫醒
2899
- live.cursor = nowIso
4639
+ const sameGeneration = !entry.createdAt || !live || !live.createdAt || live.createdAt === entry.createdAt
4640
+ if (!live || live.sessionId !== sessionId || !isIssueWatcher(live) || !sameGeneration) {
4641
+ return toolError(args, ackWatcherReplacedMessage(entry.id))
4642
+ }
4643
+ if (live && live.sessionId === sessionId && isIssueWatcher(live) && sameGeneration) {
2900
4644
  live.lastAcked = { numbers: results, label, at: nowIso }
2901
- // 回执到了,这条路走通了 —— 不用再提
2902
- live.pending = clearPending(live.pending, results)
4645
+ // 兼容投影直接更新,不参与 v2 决策,也不再依赖旧 helper。
4646
+ live.seen = { ...(live.seen || {}) }
4647
+ live.pending = { ...(live.pending || {}) }
4648
+ for (const number of results) {
4649
+ live.seen[String(number)] = nowIso
4650
+ delete live.pending[String(number)]
4651
+ }
4652
+ if (live) {
4653
+ for (const number of results) {
4654
+ const key = issueKey({ number })
4655
+ const cursor = postCursors.get(String(number))
4656
+ if (!cursor) return toolError(args, '远端标签已写入,但缺少 post-cursor,本地 handled 未提交')
4657
+ applyV2(live, handleV2(live, key, cursor, { round: live.round + 1, at: nowIso }))
4658
+ }
4659
+ }
4660
+ // 打标签本身就是一次外部更新,但**不要在这里推全局 `cursor`**:
4661
+ // `cursor` 是全仓库共享的 floor,一次单条 ack 就把它抬到当下,会把所有
4662
+ // 「本轮只在『另有 N 条』里出现」或「还压在上限/忙里没列出去」的条目一起
4663
+ // 判成旧闻(2026-11-20 真机 #131:ack #133 把 cursor 推到 17:30,而 #131
4664
+ // 的 updated_at 是 13:09,从此永久静默)。防「自己叫醒自己」已经由
4665
+ // 「整批都列出去 / 没有积压」时推进。
4666
+ // (此前写成「pending 为空才推」仍不够:唤醒被 cap / busy 挡住时 pending
4667
+ // 本来就是空的,而 fresh 一条都没消费 —— 一次任意 ack 就会把整页吞掉。)
2903
4668
  // 「叫醒之后」的闭环(见 docs/为什么做这个产品.md 诉求 2):
2904
4669
  // 以前只记「叫醒过」,不记「怎么处理的」—— 同一条被重开时会话只能重新判一遍。
2905
4670
  // 有界:只留最近 20 条,超出丢最旧的。
@@ -2911,6 +4676,13 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2911
4676
  }
2912
4677
  writeState(latest)
2913
4678
  }
4679
+ for (const number of results) {
4680
+ try {
4681
+ await completeRuntimeForAck(ctx, live, number, `ack:${entry.id}:${number}:${nowIso}`)
4682
+ } catch (error) {
4683
+ return toolError(args, '远端 ack 已完成,但 Ticket 收尾失败:' + String(error && error.message || error))
4684
+ }
4685
+ }
2914
4686
  if (args && args.format === 'json') {
2915
4687
  // labelNote 是「标签是新建的还是本来就有的」——JSON 分支以前把它丢了,消费方只能猜
2916
4688
  return JSON.stringify({ schemaVersion: 1, ok: true, repo: entry.repo, label, acked: results, at: nowIso, labelNote: labelNote || null, ...(args.comment === true ? { commented: true } : {}) })
@@ -2978,6 +4750,9 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
2978
4750
  async execute(args) {
2979
4751
  const lines = []
2980
4752
  const state = readState()
4753
+ const diskBootAt = state.server && state.server.startedAt ? Date.parse(state.server.startedAt) : NaN
4754
+ const bootAt = Math.max(Number.isFinite(diskBootAt) ? diskBootAt : 0, Number(PROCESS_STARTED_AT) || 0)
4755
+ const processBornAt = bootProbeOverride() || (Number(PROCESS_STARTED_AT) || 0)
2981
4756
  const all = Object.values(state.watchers || {})
2982
4757
  const wanted = args.repo ? all.filter((w) => w && w.repo === String(args.repo)) : all
2983
4758
 
@@ -3138,9 +4913,14 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3138
4913
  const intervalMs = (Number(entry.intervalSec) || 60) * 1000
3139
4914
  const staleMs = Math.max(intervalMs * 3, 5 * 60 * 1000)
3140
4915
  const age = Date.now() - Date.parse(entry.lastPoll)
3141
- const uptimeMs = state.server && state.server.startedAt ? Date.now() - Date.parse(state.server.startedAt) : Infinity
3142
- // 刚重启时 uptime 还不够一个停滞周期:陈旧只是「还没轮到」,不是故障
3143
- if (Number.isFinite(age) && age > staleMs && uptimeMs > staleMs) {
4916
+ const startedAt = bootProbeOverride() || (Number.isFinite(bootAt) && bootAt > 0 ? bootAt : NaN)
4917
+ const uptimeMs = Number.isFinite(startedAt) ? Date.now() - startedAt : Infinity
4918
+ const lastPollAt = Date.parse(entry.lastPoll)
4919
+ const beforeBoot = Number.isFinite(processBornAt) && processBornAt > 0
4920
+ && Number.isFinite(lastPollAt) && lastPollAt < processBornAt
4921
+ if (beforeBoot && uptimeMs > staleMs) {
4922
+ lines.push(`WARN ${entry.repo} 重启后还没轮询过(进程已启动 ${Math.round(uptimeMs / 60000)} 分钟,上次轮询在启动前 ${Math.round(age / 60000)} 分钟)—— 启动挂载可能失败,重启宿主或点「立即」重建轮询`)
4923
+ } else if (Number.isFinite(age) && age > staleMs && uptimeMs > staleMs) {
3144
4924
  lines.push(`WARN ${entry.repo} 已经 ${Math.round(age / 60000)} 分钟没轮询过(预期每 ${Math.round(intervalMs / 1000)} 秒)—— 定时器可能丢了`)
3145
4925
  } else if (Number.isFinite(age) && age > staleMs) {
3146
4926
  lines.push(`INFO ${entry.repo} 上次轮询是 ${Math.round(age / 60000)} 分钟前,但进程才启动 ${Math.round(uptimeMs / 60000)} 分钟 —— 刚重启,等下一轮即可`)
@@ -3189,8 +4969,9 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3189
4969
  if (write && args.confirm !== true) {
3190
4970
  return `[error: ${method} requires confirm: true — this plugin never writes to GitHub without an explicit flag]`
3191
4971
  }
3192
- const res = await run('gh', ['api', '-X', method, args.path, '--header', 'Accept: application/vnd.github+json'], {
3193
- input: write && args.body ? args.body : undefined, env: ghEnv(),
4972
+ const request = githubApiRequest(method, args.path, args.body)
4973
+ const res = await run('gh', request.argv, {
4974
+ input: request.input, env: ghEnv(),
3194
4975
  })
3195
4976
  const text = redact([res.stdout, res.stderr].filter(Boolean).join(String.fromCharCode(10)).trim())
3196
4977
  // 失败要带「下一步」:只贴 gh 的原始报错,调用方还得自己猜
@@ -3210,6 +4991,311 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3210
4991
  },
3211
4992
  }))
3212
4993
 
4994
+ // ── PR 响应监控:三个工具 ────────────────────────────────────────────────
4995
+ // 与 issue 守完全独立:id 一律带 `pr:` 前缀,`kind: 'pr'` 让调度器分流,
4996
+ // 这样同一个仓库的两条守(issue 一条、PR 一条)不会互相覆盖。
4997
+ ctx.tools.register(defineTool({
4998
+ name: 'watch_pr_start',
4999
+ description: 'Watch a repository\'s open pull requests and wake THIS session when reviewers leave new comments on them. Read-only: it never posts comments, labels or reviews — answering the review is the session\'s job. Works with GitHub (owner/name) and Gitee (prefix with gitee:). Idempotent per (repo, session). Default interval 300 s, minimum 30 s.',
5000
+ parameters: {
5001
+ repo: { type: 'string', required: true, description: 'owner/name (GitHub) 或 gitee:owner/name(Gitee);多个用空格或逗号分隔。' },
5002
+ intervalSec: { type: 'number', description: 'Polling interval in seconds, clamped to 30-3600, default 300.' },
5003
+ audit: { type: 'boolean', description: 'Append "审计: 开启" to the wake message so the session self-reviews before replying (default false).' },
5004
+ adversarialAudit: { type: 'boolean', description: 'Stronger form of audit: self-review adversarially before replying (default false).' },
5005
+ auditMode: { type: 'string', description: "How the audit runs: 'inline' (in-session) or 'subagent' (default)." },
5006
+ observe: { type: 'boolean', description: 'Observe only: record what WOULD be woken, never wake (and never advance the watermark).' },
5007
+ activeHours: { type: 'string', description: 'Wake only inside these windows, e.g. "09:00-12:00,14:00-23:00" (comma/semicolon-separated; supports overnight).' },
5008
+ goal: { type: 'string', description: 'Optional per-watcher goal appended to the wake message.' },
5009
+ maxWakesPerHour: { type: 'number', description: 'Max wakes per hour for this watcher, clamped to 1-60, default 6.' },
5010
+ sessionMaxWakes: { type: 'number', description: 'Max wakes per hour for the whole session (across watchers), clamped to 1-60, default 12.' },
5011
+ format: { type: 'string', description: "'text' (default) or 'json'." },
5012
+ },
5013
+ async execute(args) {
5014
+ const toolAgents = agentsService(ctx)
5015
+ const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
5016
+ const sessionId = agent && agent.id
5017
+ if (!sessionId) return toolError(args, 'no live session — watch_pr_start must be called from a session turn')
5018
+
5019
+ // 审计模式是**对外契约的一部分**(写进唤醒消息末尾),非法值宁可当场拒,别静默退回默认
5020
+ const auditMode = args.auditMode === undefined ? 'subagent' : String(args.auditMode)
5021
+ if (auditMode !== 'inline' && auditMode !== 'subagent') {
5022
+ return toolError(args, 'auditMode 只支持 inline / subagent(收到 ' + JSON.stringify(String(args.auditMode)) + ')')
5023
+ }
5024
+
5025
+ if (!String(args.repo || '').trim()) return toolError(args, 'repo is required(owner/name 或 gitee:owner/name)')
5026
+ const specs = String(args.repo).split(/[,\s]+/).map((item) => item.trim()).filter(Boolean)
5027
+ .map((item) => ({ item, spec: parseRepoSpec(item) }))
5028
+ const bad = specs.filter(({ spec }) => !spec.ok).map(({ item }) => item)
5029
+ if (bad.length > 0) return toolError(args, REPO_SPEC_ERROR + bad.join(', '))
5030
+
5031
+ // 上限**先判**:逐条判时第 2 个仓库超限,第 1 个已经写进状态并起了定时器 ——
5032
+ // 客户看到「报错但守还在跑」。这里把「本轮要新建几条」一次性算清再进循环。
5033
+ {
5034
+ const snapshot = readState()
5035
+ const newCount = specs.filter(({ spec }) => {
5036
+ const p = spec.provider === 'gitee' ? 'gitee' : 'github'
5037
+ const key = 'pr:' + (p === 'gitee' ? 'gitee:' : '') + `${spec.repo}#${sessionId}`
5038
+ return !(snapshot.watchers && snapshot.watchers[key])
5039
+ }).length
5040
+ // 上限只数**还在跑的**:watch_pr_stop 只是置 enabled=false,数全部会变成死结
5041
+ const mine = Object.values(snapshot.watchers || {}).filter((w) => w && w.sessionId === sessionId && w.enabled !== false)
5042
+ if (newCount > 0 && mine.length + newCount > MAX_WATCHERS_PER_SESSION) {
5043
+ return '一条会话最多同时挂 ' + MAX_WATCHERS_PER_SESSION + ' 条在跑的守(现在 ' + mine.length + ' 条,本次要新建 ' + newCount + ' 条)—— 先 watch_pr_stop 停掉不用的'
5044
+ }
5045
+ }
5046
+
5047
+ const applied = []
5048
+ for (const { spec } of specs) {
5049
+ const provider = spec.provider === 'gitee' ? 'gitee' : 'github'
5050
+ const id = 'pr:' + (provider === 'gitee' ? 'gitee:' : '') + `${spec.repo}#${sessionId}`
5051
+ const state = readState()
5052
+ const existing = state.watchers && state.watchers[id]
5053
+ const entry = existing || {
5054
+ id,
5055
+ repo: spec.repo,
5056
+ provider,
5057
+ sessionId,
5058
+ kind: 'pr',
5059
+ intervalSec: 300,
5060
+ seenComments: {},
5061
+ enabled: true,
5062
+ audit: false,
5063
+ adversarialAudit: false,
5064
+ auditMode: 'subagent',
5065
+ observe: false,
5066
+ goal: null,
5067
+ createdAt: new Date().toISOString(),
5068
+ }
5069
+ // 老状态文件里可能没有 kind / seenComments(或被人手改成 null):开始守之前补齐
5070
+ entry.kind = 'pr'
5071
+ if (!entry.seenComments || typeof entry.seenComments !== 'object' || Array.isArray(entry.seenComments)) entry.seenComments = {}
5072
+ entry.intervalSec = typeof args.intervalSec === 'number' && args.intervalSec > 0
5073
+ ? Math.max(30, Math.min(3600, Math.round(args.intervalSec)))
5074
+ : (Number(entry.intervalSec) || 60)
5075
+ if (typeof args.observe === 'boolean') entry.observe = args.observe
5076
+ if (typeof args.audit === 'boolean') entry.audit = args.audit
5077
+ if (typeof args.adversarialAudit === 'boolean') entry.adversarialAudit = args.adversarialAudit
5078
+ // 重跑(同一个 repo 再 watch_pr_start 一次)不传 auditMode 时保留原值:
5079
+ // 无条件赋值等于「改个 intervalSec 就把审计方式打回 subagent」,客户看不出为什么。
5080
+ if (args.auditMode !== undefined) entry.auditMode = auditMode
5081
+ if (typeof args.maxWakesPerHour === 'number' && Number.isFinite(args.maxWakesPerHour)) {
5082
+ entry.maxWakesPerHour = Math.max(1, Math.min(60, Math.round(args.maxWakesPerHour)))
5083
+ }
5084
+ if (typeof args.sessionMaxWakes === 'number' && Number.isFinite(args.sessionMaxWakes)) {
5085
+ entry.sessionMaxWakes = Math.max(1, Math.min(60, Math.round(args.sessionMaxWakes)))
5086
+ }
5087
+ if (typeof args.goal === 'string') entry.goal = args.goal.slice(0, 500)
5088
+ if (typeof args.activeHours === 'string') {
5089
+ const hoursCheck = validateActiveHours(args.activeHours)
5090
+ if (!hoursCheck.ok) return toolError(args, 'activeHours ' + hoursCheck.reason)
5091
+ entry.activeHours = hoursCheck.normalized || null
5092
+ }
5093
+ entry.enabled = true
5094
+ state.watchers = state.watchers || {}
5095
+ state.watchers[id] = migrateV1Watermark(entry)
5096
+ writeState(state, { revive: [id] })
5097
+ stopWatcher(id)
5098
+ startWatcher(state.watchers[id])
5099
+ const flags = []
5100
+ if (entry.observe === true) flags.push(OBSERVE_FLAG_TEXT)
5101
+ // 两项都要能出现:以前是 else if,两项都开时「审计」那行永远看不到
5102
+ //(2026-11-13 真实唤醒实测:客户两个都开了,消息里只剩「对抗性审计」)。
5103
+ if (entry.audit === true) flags.push('审计=' + entry.auditMode)
5104
+ if (entry.adversarialAudit === true) flags.push('对抗性审计=' + entry.auditMode)
5105
+ if (entry.activeHours) flags.push('activeHours=' + entry.activeHours)
5106
+ if (entry.goal) flags.push('goal=' + JSON.stringify(entry.goal.slice(0, 40)))
5107
+ applied.push({ id, repo: spec.repo, provider, entry, existing, flags })
5108
+ }
5109
+
5110
+ if (args && args.format === 'json') {
5111
+ const first = applied[0]
5112
+ const payload = {
5113
+ schemaVersion: 1,
5114
+ ok: true,
5115
+ repo: first.repo,
5116
+ provider: first.provider,
5117
+ sessionId,
5118
+ id: first.id,
5119
+ kind: 'pr',
5120
+ intervalSec: first.entry.intervalSec,
5121
+ seenComments: first.entry.seenComments,
5122
+ updated: Boolean(first.existing),
5123
+ audit: first.entry.audit === true,
5124
+ adversarialAudit: first.entry.adversarialAudit === true,
5125
+ auditMode: first.entry.auditMode,
5126
+ observe: first.entry.observe === true,
5127
+ activeHours: first.entry.activeHours || null,
5128
+ flags: first.flags,
5129
+ repos: applied.map((item) => ({ repo: item.repo, provider: item.provider, id: item.id, updated: Boolean(item.existing) })),
5130
+ }
5131
+ return JSON.stringify(payload, null, 2)
5132
+ }
5133
+ return applied.map((item) => `watching PR ${item.repo} → session ${sessionId} every ${item.entry.intervalSec}s`
5134
+ + (item.flags.length ? ' [' + item.flags.join(' ') + ']' : '')
5135
+ + (item.existing ? ' (updated existing watcher)' : '')).join(String.fromCharCode(10))
5136
+ },
5137
+ }))
5138
+
5139
+ ctx.tools.register(defineTool({
5140
+ name: 'watch_pr_status',
5141
+ description: 'Report PR watchers: which pull requests are tracked, how far the comment watermark has advanced, and whether a wake is deferred. Use format=json for machine-readable output. Read-only.',
5142
+ parameters: {
5143
+ format: { type: 'string', description: "'text' (default, human) or 'json' (same data, structured)." },
5144
+ },
5145
+ async execute(args) {
5146
+ const state = readState()
5147
+ const wsAgents = agentsService(ctx)
5148
+ const wsAgent = wsAgents && typeof wsAgents.currentInitiator === 'function' ? wsAgents.currentInitiator() : undefined
5149
+ const wsSessionId = (wsAgent && wsAgent.id) || undefined
5150
+ const view = prStatusView(state.watchers || {}, wsSessionId)
5151
+ if (args && args.format === 'json') return JSON.stringify(view, null, 2)
5152
+ if (view.watchers.length === 0) return '(no PR watchers)'
5153
+ const lines = view.watchers.map((w) => {
5154
+ const parts = [(w.provider === 'gitee' ? 'gitee:' : '') + w.repo, '→', w.sessionId, '| 每 ' + w.intervalSec + 's', '| 跟 ' + w.tracked + ' 个 PR']
5155
+ if (w.observe) parts.push('| 仅观察')
5156
+ if (!w.enabled) parts.push('| 已暂停')
5157
+ if (w.audit) parts.push('| 审计=' + w.auditMode)
5158
+ if (w.adversarialAudit) parts.push('| 对抗性审计=' + w.auditMode)
5159
+ return parts.join(' ')
5160
+ })
5161
+ // 只有需要你注意的才追加原因:十条守各带一行 lastPoll 就是十行长日志
5162
+ for (const w of view.watchers) {
5163
+ if (w.lastError) lines.push('WARN ' + w.repo + ':' + w.lastError)
5164
+ else if (w.deferReason && w.deferReason !== 'unchanged') lines.push('INFO ' + w.repo + ':' + (w.lastDeferred || w.deferReason))
5165
+ }
5166
+ return lines.join(String.fromCharCode(10))
5167
+ },
5168
+ }))
5169
+
5170
+ ctx.tools.register(defineTool({
5171
+ name: 'watch_pr_stop',
5172
+ description: 'Stop watching a repository\'s pull requests for this session. Default pauses it (state kept); delete:true removes it and leaves a tombstone. Does not touch issue watchers.',
5173
+ parameters: {
5174
+ repo: { type: 'string', required: true, description: 'owner/name (GitHub) or gitee:owner/name (Gitee).' },
5175
+ delete: { type: 'boolean', description: 'Delete the watcher and persist a tombstone instead of only pausing it (default false).' },
5176
+ format: { type: 'string', description: "'text' (default) or 'json'." },
5177
+ },
5178
+ async execute(args) {
5179
+ const toolAgents = agentsService(ctx)
5180
+ const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
5181
+ const sessionId = agent && agent.id
5182
+ if (!sessionId) return toolError(args, 'no live session — watch_pr_stop must be called from a session turn')
5183
+ const state = readState()
5184
+ const rawRepo = String(args.repo || '')
5185
+ // 与 watch_pr_start 同口径:先过 parseRepoSpec 归一,`gitee:` 前缀带不带、
5186
+ // `gitee.com/o/r` 这种 URL 都要能 stop 到 start 建的守 —— 否则 URL 建的守永远停不掉。
5187
+ const parsedSpec = parseRepoSpec(rawRepo)
5188
+ const repo = parsedSpec && parsedSpec.ok ? parsedSpec.repo : rawRepo
5189
+ const provider = parsedSpec && parsedSpec.ok ? parsedSpec.provider : (rawRepo.startsWith('gitee:') ? 'gitee' : 'github')
5190
+ const candidates = [
5191
+ 'pr:' + (provider === 'gitee' ? 'gitee:' : '') + `${repo}#${sessionId}`,
5192
+ // 模型常把 watch_pr_status 里的 repo 字段原样回传,带不带 gitee: 前缀都认
5193
+ 'pr:' + (provider === 'gitee' ? '' : 'gitee:') + `${repo}#${sessionId}`,
5194
+ ]
5195
+ const id = candidates.find((key) => state.watchers && state.watchers[key]) || candidates[0]
5196
+ if (!state.watchers || !state.watchers[id]) {
5197
+ const message = 'no PR watcher for ' + rawRepo + '(试过 ' + candidates.join(' / ') + ')'
5198
+ return (args && args.format === 'json') ? JSON.stringify({ schemaVersion: 1, ok: false, id, error: message }) : '[error: ' + message + ']'
5199
+ }
5200
+ // 先停再抹状态:正在收尾的 tick 可能把刚删的守写回来
5201
+ stopWatcher(id)
5202
+ if (args.delete === true) {
5203
+ delete state.watchers[id]
5204
+ state.deleted = { ...(state.deleted || {}), [id]: new Date().toISOString() }
5205
+ writeState(state)
5206
+ if (args && args.format === 'json') return JSON.stringify({ schemaVersion: 1, ok: true, id, repo: args.repo, deleted: true })
5207
+ return `deleted ${id}(deleted:true)`
5208
+ }
5209
+ state.watchers[id].enabled = false
5210
+ writeState(state)
5211
+ if (args && args.format === 'json') return JSON.stringify({ schemaVersion: 1, ok: true, id, repo: args.repo })
5212
+ return `stopped ${id}`
5213
+ },
5214
+ }))
5215
+
5216
+ ctx.tools.register(defineTool({
5217
+ name: 'watch_pr_ack',
5218
+ description: '把某个 PR 的评论水位推到指定评论 id(不传 commentId 就推到当前最新一条),用于「这条评论我看过了,别再叫我」。只动本会话在该仓库的 PR 守;只前进不回退。',
5219
+ parameters: {
5220
+ repo: { type: 'string', description: 'owner/name 或 gitee:owner/name;省略时要求本会话只有一条 PR 守,否则报错让你指定。' },
5221
+ pr: { type: 'number', required: true, description: 'PR 号。' },
5222
+ commentId: { type: 'number', description: '推到这条评论的 id(含);省略 = 推到当前最新一条(会现查一次 API)。' },
5223
+ format: { type: 'string', description: "'text' (default) or 'json'." },
5224
+ },
5225
+ async execute(args) {
5226
+ const toolAgents = agentsService(ctx)
5227
+ const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
5228
+ const sessionId = agent && agent.id
5229
+ if (!sessionId) return toolError(args, 'no live session — watch_pr_ack must be called from a session turn')
5230
+ const prNumber = Number(args.pr)
5231
+ if (!Number.isFinite(prNumber) || prNumber <= 0) return toolError(args, 'pr 必须是正整数')
5232
+ const state = readState()
5233
+ const watchers = Object.values(state.watchers || {}).filter((w) => w && w.kind === 'pr' && w.sessionId === sessionId)
5234
+ if (watchers.length === 0) return toolError(args, '本会话没有 PR 守(先 watch_pr_start 建一条)')
5235
+ let entry
5236
+ if (args.repo) {
5237
+ const rawRepo = String(args.repo)
5238
+ const parsedSpec = parseRepoSpec(rawRepo)
5239
+ const repo = parsedSpec && parsedSpec.ok ? parsedSpec.repo : rawRepo
5240
+ const provider = parsedSpec && parsedSpec.ok ? parsedSpec.provider : (rawRepo.startsWith('gitee:') ? 'gitee' : 'github')
5241
+ entry = watchers.find((w) => w.repo === repo && (w.provider || 'github') === provider)
5242
+ if (!entry) return toolError(args, '本会话没有监控 ' + rawRepo + ' 的 PR 守')
5243
+ } else if (watchers.length === 1) {
5244
+ entry = watchers[0]
5245
+ } else {
5246
+ return toolError(args, '本会话有 ' + watchers.length + ' 条 PR 守,请用 repo 指定:' + watchers.map((w) => w.repo).join(', '))
5247
+ }
5248
+ const number = String(prNumber)
5249
+ let targetId
5250
+ if (args.commentId !== undefined && args.commentId !== null && args.commentId !== '') {
5251
+ targetId = Number(args.commentId)
5252
+ if (!Number.isFinite(targetId) || targetId <= 0) return toolError(args, 'commentId 必须是正整数')
5253
+ } else {
5254
+ const token = String((readSecrets() && readSecrets().giteeToken) || '')
5255
+ const fetched = await fetchLatestPrCommentId(entry.repo, prNumber, entry.provider || 'github', token)
5256
+ if (!fetched.ok) return toolError(args, '拿最新评论失败:' + fetched.error)
5257
+ if (fetched.id === null) return toolError(args, '这个 PR 还没有评论(没什么可 ack 的)')
5258
+ targetId = fetched.id
5259
+ }
5260
+ // 重新读一次:上面可能 await 过网络,期间守可能被 watch_pr_stop 删掉
5261
+ const live = readState()
5262
+ const liveEntry = live.watchers && live.watchers[entry.id]
5263
+ if (!liveEntry) return toolError(args, '守已经不存在了(可能被 watch_pr_stop 删掉)')
5264
+ if (!liveEntry.seenComments || typeof liveEntry.seenComments !== 'object' || Array.isArray(liveEntry.seenComments)) liveEntry.seenComments = {}
5265
+ const before = Object.prototype.hasOwnProperty.call(liveEntry.seenComments, number) ? liveEntry.seenComments[number] : null
5266
+ if (liveEntry) {
5267
+ const key = `pr:${prNumber}/comment`
5268
+ const row = liveEntry.obs && liveEntry.obs[key]
5269
+ const current = row && row.legacy
5270
+ ? (Number(liveEntry.seenComments[number]) || 0)
5271
+ : (Number(row && (row.handled && row.handled.cursor || row.delivered && row.delivered.cursor || row.cursor)) || 0)
5272
+ if (targetId >= current) {
5273
+ applyV2(liveEntry, handleV2(liveEntry, key, targetId, {
5274
+ round: liveEntry.round + 1, at: new Date().toISOString(),
5275
+ }))
5276
+ }
5277
+ }
5278
+ syncPrCommentsProjection(liveEntry)
5279
+ const after = liveEntry.seenComments[number]
5280
+ const moved = before === null || Number(after) > Number(before)
5281
+ writeState(live)
5282
+ if (args.format === 'json') {
5283
+ return JSON.stringify({
5284
+ schemaVersion: 1,
5285
+ ok: true,
5286
+ id: liveEntry.id,
5287
+ repo: liveEntry.repo,
5288
+ provider: liveEntry.provider || 'github',
5289
+ pr: prNumber,
5290
+ before,
5291
+ seenCommentId: after,
5292
+ moved,
5293
+ })
5294
+ }
5295
+ return 'PR #' + prNumber + ' 评论水位 → ' + after + (before === null ? '(原为空)' : '(原 ' + before + ')')
5296
+ },
5297
+ }))
5298
+
3213
5299
  ctx.tools.register(defineTool({
3214
5300
  name: 'watch_start',
3215
5301
  description: 'Watch a repository and wake THIS session when its issues or pull requests change. Works with GitHub (owner/name) and Gitee (prefix with gitee:, e.g. gitee:owner/name; a gitee.com URL also works). Pass several repos in one call separated by spaces or commas to create several watchers at once. Idempotent per (repo, session). Default interval 60 s, minimum 30 s.',
@@ -3219,12 +5305,14 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3219
5305
  labels: { type: 'array', items: { type: 'string' }, description: 'Only handle items carrying one of these labels (whitelist).' },
3220
5306
  ignoreLabels: { type: 'array', items: { type: 'string' }, description: 'Skip items carrying any of these labels.' },
3221
5307
  onlyAssigned: { type: 'boolean', description: 'Only handle items assigned to someone (or to `assignee`).' },
5308
+ onlyNewComments: { type: 'boolean', description: '只看新评论:push、改标签等非评论更新不唤醒;GitHub/Gitee 的 discussion 与 PR review comments 都计入。priority.comments 仍只影响排序,不改变过滤。' },
3222
5309
  assignee: { type: 'string', description: 'With onlyAssigned: require this login.' },
3223
5310
  allowAuthors: { type: 'array', items: { type: 'string' }, description: '只要这些人提的(GitHub 登录名,可带 @)。空 = 谁都算。用来挡掉别人随手提的 issue。' },
3224
5311
  observe: { type: 'boolean', description: 'Observe only: record what WOULD be woken, never wake.' },
3225
5312
  isolated: { type: 'boolean', description: 'Run each wake in a throwaway git worktree.' },
5313
+ executionMode: { type: 'string', description: "'inline' wakes this session (default); 'worker' creates one persistent worker session per Ticket." },
3226
5314
  workdir: { type: 'string', description: 'Repository used for isolation worktrees (absolute path).' },
3227
- activeHours: { type: 'string', description: 'Wake only inside this window, e.g. "09:00-23:00" (supports overnight).' },
5315
+ activeHours: { type: 'string', description: 'Wake only inside these windows, e.g. "09:00-12:00,14:00-23:00" (comma/semicolon-separated; supports overnight).' },
3228
5316
  resume: { type: 'boolean', description: 'Only when the watcher is paused: resume it (default true). Pass false to change config while keeping it paused.' },
3229
5317
  format: { type: 'string', description: "'text' (default) or 'json'." },
3230
5318
  batchLimit: { type: 'number', description: 'Max items listed per wake (1-20, default 5).' },
@@ -3234,7 +5322,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3234
5322
  maxIsolated: { type: 'number', description: 'With isolated: keep at most this many worktrees, oldest removed first (1-50, default 5).' },
3235
5323
  goal: { type: 'string', description: 'Optional per-watcher goal appended to the wake message.' },
3236
5324
  ackLabel: { type: 'string', description: 'Label used as the handled marker (default ' + brand.defaultAckLabels.github + ' on GitHub / ' + brand.defaultAckLabels.gitee + ' on Gitee). Two sessions watching the same repo share it unless each sets its own.' },
3237
- priority: { type: 'object', description: 'Priority switches; only explicitly supplied keys are changed. Boolean keys: reopened, comments, labels, unassigned, stale. Defaults: reopened/comments/labels=true; unassigned/stale=false. additionalProperties are unrestricted.' },
5325
+ priority: { type: 'object', description: 'Priority switches; only explicitly supplied keys are changed. Boolean keys: reopened, comments, labels, unassigned, stale. Defaults: reopened/comments/labels=true; unassigned/stale=false. comments 只调整唤醒批内排序,不代表只看评论(过滤请用 onlyNewComments)。additionalProperties are unrestricted.' },
3238
5326
  },
3239
5327
  async execute(args) {
3240
5328
  const toolAgents = agentsService(ctx)
@@ -3256,7 +5344,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3256
5344
  if (bad.length > 0) {
3257
5345
  // 审核 T33 M4:以前坏值里可能混进 `undefined`(推断失败时),客户看到「这些不对:undefined」。
3258
5346
  const shown = bad.map((v) => (v === undefined || v === null || String(v).trim() === '' ? '(空)' : String(v))).join(', ')
3259
- return toolError(args, '仓库要写成 owner/name 或 gitee:owner/name,这些不对:' + shown)
5347
+ return toolError(args, REPO_SPEC_ERROR + shown)
3260
5348
  }
3261
5349
  if (parsedSpecs.length === 0) return toolError(args, '至少给一个仓库(owner/name)')
3262
5350
  const repoList = parsedSpecs.map(({ item, spec }) => ({ repo: spec.repo, provider: spec.provider, label: item }))
@@ -3266,6 +5354,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3266
5354
  const existing = state.watchers && state.watchers[id]
3267
5355
  const entry = existing || {
3268
5356
  id, repo, provider, sessionId,
5357
+ executionMode: 'inline',
3269
5358
  intervalSec: 60,
3270
5359
  cooldownMs: DEFAULT_COOLDOWN_MS,
3271
5360
  ackLabel: defaultAckLabel(provider, brand.defaultAckLabels),
@@ -3284,6 +5373,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3284
5373
  if (args.labels !== undefined) patch.labels = args.labels
3285
5374
  if (args.ignoreLabels !== undefined) patch.ignoreLabels = args.ignoreLabels
3286
5375
  if (args.onlyAssigned !== undefined) patch.onlyAssigned = args.onlyAssigned
5376
+ if (args.onlyNewComments !== undefined) patch.onlyNewComments = args.onlyNewComments
3287
5377
  if (args.assignee !== undefined) patch.assignee = args.assignee
3288
5378
  // 谁提的才算:参考官方原型的 Policy(谁来派活)。空数组 = 谁都算。
3289
5379
  if (args.allowAuthors !== undefined) patch.allowAuthors = args.allowAuthors
@@ -3291,6 +5381,10 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3291
5381
  if (typeof args.goal === 'string') entry.goal = args.goal.slice(0, 500)
3292
5382
  if (typeof args.observe === 'boolean') entry.observe = args.observe
3293
5383
  if (typeof args.isolated === 'boolean') entry.isolated = args.isolated
5384
+ if (args.executionMode !== undefined) {
5385
+ if (!['inline', 'worker'].includes(String(args.executionMode))) return toolError(args, 'executionMode must be inline or worker')
5386
+ entry.executionMode = String(args.executionMode)
5387
+ }
3294
5388
  // 与 HTTP 创建路径同口径:隔离开着但没给目录,就明确兜底到宿主 cwd。
3295
5389
  // 否则面板创建不告警、工具创建却被 doctor 警告,同一个配置两种结果。
3296
5390
  if (entry.isolated && !entry.workdir) entry.workdir = process.cwd()
@@ -3348,19 +5442,20 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3348
5442
  warnings = pre.warnings || []
3349
5443
  if (pre.access) entry.repoAccess = pre.access
3350
5444
  }
3351
- state.watchers[id] = entry
5445
+ state.watchers[id] = migrateV1Watermark(entry)
3352
5446
  // 显式 start 同 repo/session 表示要重建;只解除这个 id 的墓碑,不影响其他已删守。
3353
5447
  writeState(state, { revive: [id] })
3354
5448
  stopWatcher(id)
3355
- startWatcher(entry)
5449
+ startWatcher(state.watchers[id])
3356
5450
  const flags = []
3357
5451
  if (wasPaused && entry.enabled) flags.push('这条之前是暂停的,这次调用已恢复(只想改配置请传 resume: false)')
3358
5452
  if (wasPaused && !entry.enabled) flags.push('仍保持暂停(resume: false)')
3359
- if (entry.observe === true) flags.push('observe-only(只记录不唤醒)')
5453
+ if (entry.observe === true) flags.push(OBSERVE_FLAG_TEXT)
3360
5454
  if (entry.isolated === true) flags.push('isolated')
3361
5455
  if (entry.activeHours) flags.push('activeHours=' + entry.activeHours)
3362
5456
  if (entry.filters && entry.filters.labels && entry.filters.labels.length) flags.push('labels=' + entry.filters.labels.join(','))
3363
5457
  if (entry.filters && entry.filters.onlyAssigned) flags.push('onlyAssigned' + (entry.filters.assignee ? '(' + entry.filters.assignee + ')' : ''))
5458
+ if (entry.filters && entry.filters.onlyNewComments) flags.push('onlyNewComments')
3364
5459
  if (entry.filters && entry.filters.allowAuthors && entry.filters.allowAuthors.length) flags.push('作者=' + entry.filters.allowAuthors.join(','))
3365
5460
  if (entry.batchLimit) flags.push('batch=' + entry.batchLimit)
3366
5461
  if (entry.maxWakesPerHour) flags.push('perHour=' + entry.maxWakesPerHour)
@@ -3428,6 +5523,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3428
5523
  // 同一份数据:结构化视图 -> 文本只是它的一种渲染,两边永远对得上
3429
5524
  const view = statusView(list, {
3430
5525
  ...(wsSessionId ? { sessionId: wsSessionId } : {}),
5526
+ bootAt: bootPollBootAt(),
3431
5527
  // 状态视图里的默认 ack 与 /state 同源(issue #11)
3432
5528
  defaultAckLabels: brand.defaultAckLabels,
3433
5529
  })
@@ -3443,6 +5539,7 @@ const UPDATE_CACHE_MS = 10 * 60 * 1000
3443
5539
  if (w.activeHours) parts.push('| 时段 ' + w.activeHours)
3444
5540
  if (w.labels.length) parts.push('| 标签 ' + w.labels.join(','))
3445
5541
  if (w.onlyAssigned) parts.push('| 只看已指派')
5542
+ if (w.onlyNewComments) parts.push('| 只看新评论')
3446
5543
  const problems = []
3447
5544
  if (w.deferReason) problems.push('暂停:' + w.deferReason)
3448
5545
  if (w.silentWakes >= 2) problems.push('叫醒 ' + w.silentWakes + ' 次没回音')