dsh-session-superagent 0.9.6 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,51 @@
2
2
 
3
3
  格式参照 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
+ ## [0.9.8] - 2026-11-02 —— 时间线:回答"为什么这一轮没叫醒我"
6
+
7
+ ### 学到的(知识库第 57 条)
8
+ OTel 把一条日志定义成「时间戳 + 主体 + 结构化属性」;日志系统普遍**只留最近 N 条**——
9
+ "记录一切"本身会变成新的故障源。
10
+ <https://opentelemetry.io/docs/concepts/signals/logs/>
11
+
12
+ ### 问题
13
+ 原来只有一个 `lastDeferred` 字符串,只描述最后一次,看不出因果。
14
+ 客户问"我加了标签为什么没叫醒",我们只能看到屏幕上一句 + 累计计数。
15
+
16
+ ### 改法
17
+ `pushEvent(events, {kind, text}, 20)`:有界 20 条,kind 截 24、text 截 160(防脏数据撑大状态)。
18
+ 打点全在**既有分支**里,不新增逻辑:
19
+ `defer`(时段外)/ `ratelimit` / `unchanged`(304)/ `observe` /
20
+ `cap-session` / `cap-watcher` / `wake`(带条号)/ `wake-failed`。
21
+
22
+ 面板「判定」页新增「时间线(最近 20 条)」,按类型着色。
23
+
24
+ ### 测试
25
+ - 新增 2 例(纯函数有界与裁剪;判定页必须出现时间线与事件内容)。合计 **152 例**。
26
+
27
+ ## [0.9.7] - 2026-11-02 —— 隔离区回收节流:没超额就不必每次唤醒都跑 git
28
+
29
+ ### 学到的(知识库第 56 条)
30
+ 常规清理按**时间**跑,越界清理**立刻**跑 —— 两者混在一起,最坏就是每次业务请求都跑一遍 gc。
31
+
32
+ ### 问题
33
+ `cleanupWorktrees()` 每次唤醒都跑(间隔可短到 30 秒),里面是 `readdir` +
34
+ 每个过期副本 `worktree remove` + `prune` + `branch -D`。本机实测单次 git 调用 0.19s ——
35
+ 而绝大多数时候根本没有过期副本。
36
+
37
+ ### 改法(两条线,别只用一条)
38
+ | 条件 | 动作 |
39
+ |---|---|
40
+ | `count > keepCount` 超额 | **立刻跑**(不跑就会堆,违反数量线) |
41
+ | 距上次 < 10 分钟 | 跳过 |
42
+ | 其它 | 跑(兜底) |
43
+
44
+ 节流状态记在 `entry.lastCleanupAt`,**只在实际执行时更新** ——
45
+ "打算跑"不能算数(同 0.9.5 那条教训)。
46
+
47
+ ### 测试
48
+ - 新增 1 例(5 种情况)。合计 **150 例**。
49
+
5
50
  ## [0.9.6] - 2026-11-02 —— 会话忙时不再白开隔离区
6
51
 
7
52
  ### 学到的(知识库第 55 条)
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  <img src="assets/icon-180.png" width="88" height="88" alt="">
4
4
 
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
- [![Version](https://img.shields.io/badge/version-0.9.6-green.svg)](https://github.com/MYCF711/dsh-session-superagent/releases)
6
+ [![Version](https://img.shields.io/badge/version-0.9.8-green.svg)](https://github.com/MYCF711/dsh-session-superagent/releases)
7
7
  [![npm](https://img.shields.io/npm/v/dsh-session-superagent.svg)](https://www.npmjs.com/package/dsh-session-superagent)
8
8
  [![dsh](https://img.shields.io/badge/DeepSeek%20Harness-plugin-orange.svg)](https://github.com/topics/dsh-plugin)
9
9
 
package/client.js CHANGED
@@ -14,7 +14,7 @@ window.__ModuleLoader__.load({
14
14
  const { useCallback, useEffect, useRef, useState } = React
15
15
 
16
16
  // 客户端版本探针:每次模块加载写一次,用来确认浏览器里跑的是哪一版
17
- const CLIENT_VERSION = '0.9.6'
17
+ const CLIENT_VERSION = '0.9.8'
18
18
  let BASE = '/session-superagent'
19
19
  /**
20
20
  * 挑「最新的那个服务端实例」。
@@ -1226,6 +1226,20 @@ window.__ModuleLoader__.load({
1226
1226
  h('span', null, (watcher.title || '未命名会话') + ' · ' + sessionTag(watcher.sessionId))))
1227
1227
  }))))
1228
1228
 
1229
+ // 迷你时间线:回答"为什么这一轮没叫醒我"
1230
+ const timeline = h(Section, { key: 'timeline', title: '时间线(最近 20 条)' },
1231
+ watchers.length === 0
1232
+ ? h(Hint, null, '还没有守。添加一条之后,这里会记录每次唤醒、攒着、限流、回收。')
1233
+ : h('div', { className: 'dt-rows' }, watchers.flatMap((watcher) => (watcher.events || []).slice().reverse().map((event, index) => h('div', {
1234
+ key: watcher.repo + '-ev' + index,
1235
+ className: 'dt-row',
1236
+ },
1237
+ h('div', { className: 'dt-row-main' },
1238
+ h('div', { className: 'dt-row-title' },
1239
+ h(Tag, { tone: event.kind === 'wake' ? 'success' : event.kind === 'wake-failed' ? 'danger' : 'outline' }, event.kind),
1240
+ h('span', { className: 'dt-row-meta' }, ageText(event.at))),
1241
+ h('div', { className: 'dt-hint' }, watcher.repo + ' · ' + event.text)))))))
1242
+
1229
1243
  const trigger = h(Section, { title: '新增主理鱼' },
1230
1244
  h('div', { className: 'dt-form' },
1231
1245
  field('仓库', h(Input, { value: form.repo, placeholder: 'owner/name', onChange: (e) => setForm({ ...form, repo: e.target.value }) })),
@@ -1459,6 +1473,7 @@ window.__ModuleLoader__.load({
1459
1473
  snap.loading && !snap.body ? h(Hint, null, '正在读取…') : null,
1460
1474
  tab === 'overview' ? overview : null,
1461
1475
  tab === 'judge' ? judge : null,
1476
+ tab === 'judge' ? timeline : null,
1462
1477
  tab === 'trigger' ? trigger : null,
1463
1478
  tab === 'settings' ? settings : null,
1464
1479
  h(Modal, { open: glossary, title: '主理鱼术语表', onClose: () => setGlossary(false) },
package/lib/index.js CHANGED
@@ -26,15 +26,18 @@ import { decodeBody } from './body.js'
26
26
  import {
27
27
  advanceSeen, applyWatcherAction, batchFresh, decideWake, DEFAULT_ACK_LABEL, formatWatchText,
28
28
  TRIAGE_SIGNALS, accessNote, buildCommentBatchQuery, classifyGhError, commentSummaryLine, parseCommentBatch, pickSuggestion, repoStructureNote, countReasons, filterReason, hasAckLabel, jitterMs, parseGhInclude, retryAfterMs, throttleDelayMs, inActiveHours, newestUpdatedAt, nextDelayMs, pushFiltered, normalizeFilters, partitionItems, passesFilters,
29
- mergeFilters, mergePollResult, mergeWakeTexts, msUntilActiveWindow, nextWaketimeAt, pruneSeen, sessionWakesLastHour, pruneWakeTimes, pushHistory, recordReported, staleWorktrees, worktreePlan,
29
+ shouldRunCleanup,
30
+ mergeFilters, mergePollResult, mergeWakeTexts, pushEvent, msUntilActiveWindow, nextWaketimeAt, pruneSeen, sessionWakesLastHour, pruneWakeTimes, pushHistory, recordReported, staleWorktrees, worktreePlan,
30
31
  } from './watch.js'
31
32
 
32
33
  export const name = 'dsh-session-superagent'
33
34
  /** 服务端版本:随 package.json 同步(meta 测试守着)。客户端据此挑「最新的那个实例」。 */
34
- export const SERVER_VERSION = '0.9.6'
35
+ export const SERVER_VERSION = '0.9.8'
35
36
  export const inject = ['tools', 'agents', 'webServer']
36
37
  /** 一条会话每小时最多被唤醒几次(跨所有守累计)。单守上限挡不住多守叠加。 */
37
38
  const DEFAULT_SESSION_WAKES = 12
39
+ /** 隔离区回收的最小间隔:没有超额时不必每次唤醒都跑 git。 */
40
+ const CLEANUP_INTERVAL_MS = 10 * 60 * 1000
38
41
 
39
42
  /** 仅供测试:读写状态文件(生产代码不要用)。 */
40
43
  export const __test = { readState, writeState, hardenSecretsFile, wakeMerged }
@@ -325,6 +328,16 @@ function persistEntry(entry) {
325
328
  * 失败退避:连续失败就把下一次允许轮询的时间往后推(30s → 60 → 120 … 上限 30min)。
326
329
  * 竞品的教训很直白 —— 401 的时候还按 30 秒撞墙,只会把配额和日志一起打光。
327
330
  */
331
+ /**
332
+ * 记一条时间线事件(有界、只存在状态里)。
333
+ * 目的:回答"为什么这一轮没叫醒我" —— 以前只有 lastDeferred 一句,看不出前后因果。
334
+ */
335
+ function noteEvent(entry, kind, text) {
336
+ try {
337
+ entry.events = pushEvent(entry.events, { kind, text })
338
+ } catch { /* 观测失败不能影响主流程 */ }
339
+ }
340
+
328
341
  function bumpFailure(entry, baseMs) {
329
342
  entry.consecutiveFailures = (Number(entry.consecutiveFailures) || 0) + 1
330
343
  entry.nextAt = new Date(Date.now() + nextDelayMs(entry, baseMs || 60000)).toISOString()
@@ -334,13 +347,23 @@ function bumpFailure(entry, baseMs) {
334
347
  * 回收过期的隔离区:每次唤醒都会开一个新 worktree,不回收就会一直涨。
335
348
  * 只删 .dsh-zhuli/ 下超过 keepDays 天没动过的目录,删不掉就留着(不阻断唤醒)。
336
349
  */
337
- async function cleanupWorktrees(workdir, keepDays = 3, keepCount = 5) {
350
+ async function cleanupWorktrees(workdir, keepDays = 3, keepCount = 5, options = {}) {
338
351
  if (!workdir) return 0
339
352
  const BS = String.fromCharCode(92)
340
353
  const base = String(workdir).split(BS).join('/').replace(/\/+$/, '')
341
354
  const root = base + '/.dsh-zhuli'
342
355
  let names = []
343
356
  try { names = readdirSync(root) } catch { return 0 }
357
+
358
+ // 节流:没有超额就不必每次都跑 git(remove / prune / branch -D 都是进程级开销)
359
+ const decision = shouldRunCleanup({
360
+ count: names.length,
361
+ keepCount,
362
+ lastRunAt: Number(options.lastRunAt) || 0,
363
+ intervalMs: CLEANUP_INTERVAL_MS,
364
+ })
365
+ if (!decision.run) return 0
366
+ if (typeof options.onRun === 'function') options.onRun(decision.reason)
344
367
  const entries = []
345
368
  for (const name of names) {
346
369
  try { entries.push({ name, mtimeMs: statSync(root + '/' + name).mtimeMs }) } catch {}
@@ -376,7 +399,10 @@ async function prepareIsolation(entry) {
376
399
  const plan = worktreePlan({ workdir: entry.workdir, repo: entry.repo, sessionTag: entry.sessionId })
377
400
  try {
378
401
  // 先回收过期隔离区,再开新的
379
- await cleanupWorktrees(entry.workdir, Number(entry.isolateKeepDays) || 3, Number(entry.maxIsolated) || 5)
402
+ await cleanupWorktrees(entry.workdir, Number(entry.isolateKeepDays) || 3, Number(entry.maxIsolated) || 5, {
403
+ lastRunAt: Number(entry.lastCleanupAt) || 0,
404
+ onRun: () => { entry.lastCleanupAt = Date.now() },
405
+ })
380
406
  const res = await run('git', ['-C', entry.workdir, 'worktree', 'add', plan.dir, '-b', plan.branch], { timeoutMs: 45000 })
381
407
  if (res.code !== 0) {
382
408
  return { error: redact([res.stderr, res.stdout].filter(Boolean).join(' ')).slice(0, 200) }
@@ -774,6 +800,7 @@ async function pollOnce(ctx, entry, baseMs) {
774
800
  const wait = msUntilActiveWindow(entry.activeHours)
775
801
  entry.nextAt = new Date(Date.now() + wait).toISOString()
776
802
  entry.lastDeferred = `不在活跃时段(${entry.activeHours}),${Math.round(wait / 60000)} 分钟后开始`
803
+ noteEvent(entry, 'defer', entry.lastDeferred)
777
804
  return
778
805
  }
779
806
  // 条件请求:带上上次的 ETag,没变化时 GitHub 回 304,且**不计入**速率限制
@@ -788,6 +815,7 @@ async function pollOnce(ctx, entry, baseMs) {
788
815
  if (wait > 0) {
789
816
  entry.nextAt = new Date(Date.now() + wait).toISOString()
790
817
  entry.lastDeferred = '被 GitHub 限流,按 Retry-After 等 ' + Math.round(wait / 1000) + ' 秒'
818
+ noteEvent(entry, 'ratelimit', entry.lastDeferred)
791
819
  entry.lastError = null
792
820
  return
793
821
  }
@@ -814,6 +842,7 @@ async function pollOnce(ctx, entry, baseMs) {
814
842
  entry.consecutiveFailures = 0
815
843
  entry.nextAt = null
816
844
  entry.lastDeferred = '未变化(304,不计入速率限制)'
845
+ noteEvent(entry, 'unchanged', entry.lastDeferred)
817
846
  return
818
847
  }
819
848
  if (parsed.etag) entry.etag = parsed.etag
@@ -865,6 +894,7 @@ async function pollOnce(ctx, entry, baseMs) {
865
894
  // 仅观察模式(对标官方 observe):照常判定,但只记录「本会唤醒哪几条」,不真唤醒
866
895
  if (entry.observe === true) {
867
896
  entry.lastDeferred = '仅观察:本轮本会唤醒 ' + fresh.length + ' 条(' + fresh.slice(0, 5).map((i) => '#' + i.number).join(' ') + ')'
897
+ noteEvent(entry, 'observe', entry.lastDeferred)
868
898
  entry.history = pushHistory(entry.history, {
869
899
  at: new Date().toISOString(),
870
900
  numbers: fresh.slice(0, 5).map((i) => i.number),
@@ -881,6 +911,7 @@ async function pollOnce(ctx, entry, baseMs) {
881
911
  const sessionUsed = sessionWakesLastHour(Object.values(readState().watchers || {}), entry.sessionId)
882
912
  if (sessionUsed >= sessionCap) {
883
913
  entry.lastDeferred = '这条会话一小时内已被唤醒 ' + sessionUsed + ' 次(上限 ' + sessionCap + '),已攒 ' + fresh.length + ' 条待处理'
914
+ noteEvent(entry, 'cap-session', entry.lastDeferred)
884
915
  return
885
916
  }
886
917
 
@@ -892,6 +923,7 @@ async function pollOnce(ctx, entry, baseMs) {
892
923
  const freeAt = nextWaketimeAt(entry.wakeTimes, cap)
893
924
  const waitMin = Math.max(1, Math.round((freeAt - Date.now()) / 60000))
894
925
  entry.lastDeferred = `每小时最多唤醒 ${cap} 次,已攒 ${fresh.length} 条待处理(约 ${waitMin} 分钟后可再唤醒)`
926
+ noteEvent(entry, 'cap-watcher', entry.lastDeferred)
895
927
  return
896
928
  }
897
929
 
@@ -971,12 +1003,14 @@ async function pollOnce(ctx, entry, baseMs) {
971
1003
  if (result.ok) {
972
1004
  entry.wakeTimes.push(Date.now())
973
1005
  entry.lastDeferred = null
1006
+ noteEvent(entry, 'wake', '唤醒了 ' + (entry.lastBatch || []).length + ' 条:' + (entry.lastBatch || []).map((n) => '#' + n).join(' '))
974
1007
  entry.seen = advanceSeen(entry.seen, fresh)
975
1008
  entry.lastReported = recordReported(entry, fresh)
976
1009
  entry.cursor = newestUpdatedAt(fresh)
977
1010
  } else {
978
1011
  // 保留水位,下一轮重试这次事件
979
1012
  entry.lastError = 'wake failed: ' + String(result.reason || '')
1013
+ noteEvent(entry, 'wake-failed', entry.lastError)
980
1014
  // 会话正忙是暂时的:下一轮直接重试;退避反而会越拖越久
981
1015
  if (/busy|running|idle/i.test(String(result.reason || ''))) {
982
1016
  entry.lastDeferred = '会话正忙,下一轮重试'
@@ -1174,6 +1208,7 @@ export function apply(ctx) {
1174
1208
  isolateKeepDays: w.isolateKeepDays ?? 3,
1175
1209
  maxIsolated: w.maxIsolated ?? 5,
1176
1210
  history: (w.history ?? []).slice(-5),
1211
+ events: (w.events ?? []).slice(-20),
1177
1212
  note: w.goal ?? '',
1178
1213
  title: sessionTitle(w.sessionId),
1179
1214
  }))
package/lib/watch.js CHANGED
@@ -601,3 +601,42 @@ export function mergeWakeTexts(parts) {
601
601
  const body = trimmed.map((text, i) => String.fromCharCode(10, 10) + '—— 第 ' + (i + 1) + ' 处 ——' + String.fromCharCode(10) + text).join('')
602
602
  return head + body
603
603
  }
604
+
605
+ /**
606
+ * 该不该现在回收隔离区。
607
+ *
608
+ * 现状:每次唤醒都跑一遍回收 —— 里面是 `git worktree remove` / `branch -D` / `prune`
609
+ * (本机实测 `worktree add` 0.19s,remove 同级;5 个过期副本就是 1 秒级),
610
+ * 而绝大多数时候根本没有过期副本。
611
+ *
612
+ * 节流规则:
613
+ * - 数量**超上限**时必须立刻回收(不能等,否则会堆);
614
+ * - 没超额时,距上次回收不足 `intervalMs`(默认 10 分钟)就跳过。
615
+ */
616
+ export function shouldRunCleanup({ count = 0, keepCount = 5, lastRunAt = 0, now = Date.now(), intervalMs = 10 * 60 * 1000 } = {}) {
617
+ const total = Number(count) || 0
618
+ const cap = Math.max(1, Number(keepCount) || 5)
619
+ if (total > cap) return { run: true, reason: 'over-cap' }
620
+ const last = Number(lastRunAt) || 0
621
+ if (last > 0 && now - last < Number(intervalMs)) return { run: false, reason: 'throttled' }
622
+ return { run: true, reason: 'interval' }
623
+ }
624
+
625
+ /**
626
+ * 迷你时间线:最近 N 条事件(唤醒 / 攒着 / 限流 / 回收 / 报错 / ack)。
627
+ *
628
+ * 为什么不用 `history`:那个只记"成功唤醒过哪几条",回答不了"为什么没叫醒"。
629
+ * 事件流按 OTel 的语义组织:一条事件 = 时间 + 类型 + 一句人话 + 可选属性,
630
+ * 有界(只留最近 N 条),所以即使跑一整夜也不会把状态文件撑大。
631
+ * 出处:https://opentelemetry.io/docs/concepts/signals/logs/
632
+ */
633
+ export function pushEvent(events, event, max = 20) {
634
+ const list = Array.isArray(events) ? events.slice() : []
635
+ if (!event || typeof event !== 'object' || !event.kind) return list.slice(-max)
636
+ list.push({
637
+ at: event.at || new Date().toISOString(),
638
+ kind: String(event.kind).slice(0, 24),
639
+ text: String(event.text || '').slice(0, 160),
640
+ })
641
+ return list.slice(-Math.max(1, Number(max) || 20))
642
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-session-superagent",
3
- "version": "0.9.6",
3
+ "version": "0.9.8",
4
4
  "description": "Session-level superagent for DeepSeek Harness: watch a GitHub repository and wake a session when something needs doing. Credentials never reach the model.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",