dsh-agent-soul 0.9.4 → 0.9.6

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
@@ -7,6 +7,33 @@
7
7
 
8
8
  ---
9
9
 
10
+ ## 0.9.6 · 2026-11-07
11
+
12
+ ### 工程化
13
+
14
+ - **单个测试文件加超时**(P2-29):`tools/run-tests.mjs` 原来没有超时,一个挂死的用例(未 settle 的 await)能把 CI 拖到 GitHub 的 6 小时上限。现在默认 180 秒、`--timeout=<秒>` 可覆盖,超时按失败计并点名。
15
+ - **CI 加 `timeout-minutes` 与 `concurrency`**(P2-30):前者防止一次挂死烧光额度,后者让同一分支的旧 run 自动取消。
16
+ - **Linux job 跑 Node 22 + 24 矩阵**:`engines` 要求 ≥22.19,而 24 是当前主力版本,之前从没在 24 上跑过 CI。
17
+ - **新增 `npm run lint`(`tools/lint.mjs`)**:不引入 eslint(本项目零依赖),只查两条真出过问题的:未使用的 import、以及测试里的恒真断言 `ok(true, …)`。
18
+ - **清掉 9 处恒真断言**:`ok(true, '临时目录已清理')` 这类直接删除(清理动作仍在,只是不再假报一条绿);`r1-maintain-persist` 那条「没产生归档就跳过」改成**前置条件失败即红**;`smoke` 的 `disposer 可调用` 改成真断言「调用没抛错」。
19
+ - **修掉 1 处未使用导入**:`core/api-token.js` 的 `serviceOf`。
20
+
21
+ ---
22
+
23
+ ## 0.9.5 · 2026-11-07
24
+
25
+ ### 修复
26
+
27
+ - **清理对话记录可能早删一天**(P2-20):`dateKeyOf` 用的是 UTC,而引擎其它所有日期键都是本地时间。东八区晚上 8 点后本地已是第二天、UTC 还是当天 —— 清理时算错「今天」,把还该留的那天删掉。现在统一本地口径。
28
+ - **项目卡损坏在设置页看不见**(P2-21):`memoryHealth` 原来只查全局卡。现在把全局卡与所有项目卡一起汇总(含已被改名的 `.corrupt-*`),并指出是哪一张。
29
+ - **`soul_diary` 正文没有字数上限**(P2-32):一次写几万字会持续撑爆每轮注入预算。现在与 `notes` 同量级卡在 20000 字,并明确告诉她原因。
30
+ - **看门狗间隔改配置不生效**(P2-22):原来启动时读一次就固定。现在 1 分钟滴答、每次现读配置。
31
+ - **维护失败当天不再重试**(P2-24):`dailyHour` 模式下 `maintainClock.day` 原来在维护**执行前**就置位,抛错当天就再也不跑。现在置位挪到成功之后。
32
+ - **日记启动流程双层预算嵌套**(P2-23):两次 `runDiaryOnce` 原来各吃满 12 分钟,追补最长 ~24 分钟;现在共用一份预算。
33
+ - **「错误边界」其实不是错误边界**(P2-27):它只监听 `window.error`,接不住未处理的 Promise 拒绝(而设置页最多的就是 fetch 失败)。现在补上 `unhandledrejection`。**渲染期抛错仍会白屏** —— 真正的 React 边界需要 `Component` 基类,这段 bundle 的作用域里没有,不假装已解决。
34
+
35
+ ---
36
+
10
37
  ## 0.9.4 · 2026-11-07
11
38
 
12
39
  ### 安全
package/lib/client/app.js CHANGED
@@ -90,13 +90,32 @@
90
90
  )
91
91
  }
92
92
 
93
- /** 错误边界:设置页崩了要看得见原因,而不是整块白屏。 */
93
+ /**
94
+ * 错误边界:设置页崩了要看得见原因,而不是整块白屏。
95
+ *
96
+ * 2026-11-07 R11 / P2-27 的诚实说明:
97
+ * **这不是 React 的 error boundary。** 真正的边界需要 `getDerivedStateFromError`
98
+ * 的 class 组件,而这段 bundle 的作用域里只有 `h` 与几个 hook,没有 React 基类 ——
99
+ * 拿不到 `Component`,就做不出真正的边界。
100
+ *
101
+ * 所以它能接住的是「冒泡到 window 的异常」:同步未捕获异常 + **未处理的 Promise 拒绝**
102
+ * (后者原来完全没接,而设置页最多的恰恰是 fetch 失败)。
103
+ * 渲染期抛错仍然会白屏 —— 这一条只能等宿主暴露 React 之后再做,不在这里假装解决。
104
+ */
94
105
  function ErrorBoundary(props) {
95
106
  var [err, setErr] = useState(null)
96
107
  useEffect(function () {
97
108
  function onError(e) { setErr(e && e.message ? e.message : String(e)) }
109
+ function onRejection(e) {
110
+ var reason = e && e.reason
111
+ setErr(reason && reason.message ? reason.message : String(reason))
112
+ }
98
113
  window.addEventListener('error', onError)
99
- return function () { window.removeEventListener('error', onError) }
114
+ window.addEventListener('unhandledrejection', onRejection)
115
+ return function () {
116
+ window.removeEventListener('error', onError)
117
+ window.removeEventListener('unhandledrejection', onRejection)
118
+ }
100
119
  }, [])
101
120
  if (err !== null) {
102
121
  return h('div', { className: 'soul-app' },
package/lib/client.js CHANGED
@@ -2399,13 +2399,32 @@ window.__ModuleLoader__.load({
2399
2399
  )
2400
2400
  }
2401
2401
 
2402
- /** 错误边界:设置页崩了要看得见原因,而不是整块白屏。 */
2402
+ /**
2403
+ * 错误边界:设置页崩了要看得见原因,而不是整块白屏。
2404
+ *
2405
+ * 2026-11-07 R11 / P2-27 的诚实说明:
2406
+ * **这不是 React 的 error boundary。** 真正的边界需要 `getDerivedStateFromError`
2407
+ * 的 class 组件,而这段 bundle 的作用域里只有 `h` 与几个 hook,没有 React 基类 ——
2408
+ * 拿不到 `Component`,就做不出真正的边界。
2409
+ *
2410
+ * 所以它能接住的是「冒泡到 window 的异常」:同步未捕获异常 + **未处理的 Promise 拒绝**
2411
+ * (后者原来完全没接,而设置页最多的恰恰是 fetch 失败)。
2412
+ * 渲染期抛错仍然会白屏 —— 这一条只能等宿主暴露 React 之后再做,不在这里假装解决。
2413
+ */
2403
2414
  function ErrorBoundary(props) {
2404
2415
  var [err, setErr] = useState(null)
2405
2416
  useEffect(function () {
2406
2417
  function onError(e) { setErr(e && e.message ? e.message : String(e)) }
2418
+ function onRejection(e) {
2419
+ var reason = e && e.reason
2420
+ setErr(reason && reason.message ? reason.message : String(reason))
2421
+ }
2407
2422
  window.addEventListener('error', onError)
2408
- return function () { window.removeEventListener('error', onError) }
2423
+ window.addEventListener('unhandledrejection', onRejection)
2424
+ return function () {
2425
+ window.removeEventListener('error', onError)
2426
+ window.removeEventListener('unhandledrejection', onRejection)
2427
+ }
2409
2428
  }, [])
2410
2429
  if (err !== null) {
2411
2430
  return h('div', { className: 'soul-app' },
@@ -17,7 +17,7 @@
17
17
  * 校验用 sha256 摘要 + timingSafeEqual 定长比较,避免长度与时序侧信道。
18
18
  */
19
19
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
20
- import { note, serviceOf } from '../env.js'
20
+ import { note } from '../env.js'
21
21
 
22
22
  export const TOKEN_HEADER = 'x-soul-token'
23
23
  export const SESSION_ROUTE = '/session'
@@ -166,15 +166,21 @@ export function startDiaryTimer(ctx, { budgetMs = DIARY_TOTAL_BUDGET_MS } = {})
166
166
  note('diary', `${dateStr} 有旧版但写于窗口闭合前(只写了半天),重写`)
167
167
  }
168
168
 
169
+ // 2026-11-07 R11 / P2-23:整条启动流程共用**一份**总预算。
170
+ // 原来两次 runDiaryOnce 各自吃满 budget(外层 12 分钟装两次),追补最长能拖到 ~24 分钟。
171
+ // 现在记下起点,第二次只用剩下的。
172
+ const flowStartedAt = Date.now()
173
+ const remainingBudget = () => Math.max(MIN_DIARY_BUDGET_MS, budget - (Date.now() - flowStartedAt))
174
+
169
175
  note('diary', `开始写 ${dateStr}(昨天)`)
170
- const ok = await runDiaryOnce(ctx, dateStr, undefined, { budgetMs: budget, since })
176
+ const ok = await runDiaryOnce(ctx, dateStr, undefined, { budgetMs: remainingBudget(), since })
171
177
  // 写完再顺手看看更早的日子有没有漏的(一次只补最近的一天,避免流水账)
172
178
  if (ok) {
173
179
  try {
174
180
  const older = findMissingDay(todayKey(Date.now()), Number(config.diaryBackfillDays) || 4)
175
181
  if (older !== null && older !== dateStr) {
176
- note('diary', `发现更早的缺失日 ${older},接着补`)
177
- await runDiaryOnce(ctx, older, undefined, { budgetMs: budget })
182
+ note('diary', `发现更早的缺失日 ${older},接着补(剩余预算 ${Math.round(remainingBudget() / 1000)}s)`)
183
+ await runDiaryOnce(ctx, older, undefined, { budgetMs: remainingBudget() })
178
184
  }
179
185
  } catch (error) {
180
186
  note('diary', `往前追补失败:${error instanceof Error ? error.message : error}`)
@@ -222,16 +228,26 @@ export function startDiaryTimer(ctx, { budgetMs = DIARY_TOTAL_BUDGET_MS } = {})
222
228
  //
223
229
  // 它不是定点闹钟:不绑 22:00,只要「今天缺了」就补,所以不在乎机器几点开、几点关。
224
230
  // 检查本身只是两次文件存在性判断,几乎不花钱;真正烧钱的生成一天最多一次。
225
- const watchdogMs = Math.max(Number(loadConfig().diaryWatchdogMinutes || 30) * 60 * 1000, 60 * 1000)
231
+ //
232
+ // 2026-11-07 R11 / P2-22:间隔原来是**启动时读一次配置就固定下来**的,
233
+ // 用户把 diaryWatchdogMinutes 从 30 改成 180 之后要重启才生效(而且没有任何提示)。
234
+ // 现在定时器按 1 分钟滴答,每次现读配置、自己算够没够间隔。
235
+ const WATCHDOG_TICK_MS = 60 * 1000
236
+ let lastWatchdogAt = 0
226
237
  const watchdogTimer = setInterval(() => {
238
+ const minutes = Number(loadConfig().diaryWatchdogMinutes || 30)
239
+ const intervalMs = Math.max(minutes * 60 * 1000, 60 * 1000)
240
+ const nowMs = Date.now()
241
+ if (lastWatchdogAt > 0 && nowMs - lastWatchdogAt < intervalMs) return
242
+ lastWatchdogAt = nowMs
227
243
  // 2026-11-06 审计 P2-7:原来 `.catch(() => {})` 把整条流程的异常吞成空函数,
228
244
  // 看门狗死了也看不出来。至少留一行日志。
229
245
  void runStartupFlow().catch((error) => {
230
246
  note('diary', `看门狗执行失败:${error instanceof Error ? error.message : error}`)
231
247
  })
232
- }, watchdogMs)
248
+ }, WATCHDOG_TICK_MS)
233
249
  if (watchdogTimer !== null && typeof watchdogTimer.unref === 'function') watchdogTimer.unref()
234
- note('diary', `看门狗已启动(每 ${Math.round(watchdogMs / 60000)} 分钟检查一次今天缺不缺)`)
250
+ note('diary', `看门狗已启动(每 ${Math.max(Number(loadConfig().diaryWatchdogMinutes || 30), 1)} 分钟检查一次今天缺不缺;改配置立即生效)`)
235
251
 
236
252
  return () => {
237
253
  stopped = true
package/lib/diary-tool.js CHANGED
@@ -24,6 +24,8 @@ import { todayKey, writeDiaryFile, yesterdayKey } from './diary.js'
24
24
  const DAY_MS = 86_400_000
25
25
  /** 能往回补多少天。流水现在不再定期清理,所以往回补多少天只受这个上限约束。 */
26
26
  const MAX_BACK_DAYS = 14
27
+ /** 单篇日记的字数上限(2026-11-07 P2-32):与 notes 的 20000 同量级。 */
28
+ const MAX_DIARY_CHARS = 20_000
27
29
  const KINDS = ['public', 'private']
28
30
 
29
31
  const pad2 = (n) => String(n).padStart(2, '0')
@@ -148,6 +150,15 @@ export function registerDiaryTool(ctx) {
148
150
  if (checked.ok !== true) return { ok: false, message: checked.reason }
149
151
  const body = String(args?.content ?? '').trim()
150
152
  if (body === '') return { ok: false, message: '正文不能空' }
153
+ // 2026-11-07 R11 / P2-32:正文没有上限 —— 她一次写几万字进来,
154
+ // 这篇会进「最近日记」的历史段,**每回合都撑一次注入预算**(notes 早就有 20000 上限,
155
+ // 日记没有)。这里按同一个量级卡住,并且明确告诉她为什么,而不是静默截断。
156
+ if (body.length > MAX_DIARY_CHARS) {
157
+ return {
158
+ ok: false,
159
+ message: `日记太长(${body.length} 字,上限 ${MAX_DIARY_CHARS})—— 超出的部分会一直挤占每轮注入的预算。请精简后再写。`
160
+ }
161
+ }
151
162
 
152
163
  const label = kind === 'private' ? '私密' : '公开'
153
164
  // 2026-11-04 修 B2:已存在时必须显式 overwrite。
@@ -22,16 +22,21 @@ export function tick(agent, cwd, config, { allowMaintain = true, llm = null } =
22
22
  // dailyHour > 0 → 当天过了这个点才跑,且**一天只跑一次**
23
23
  const dailyHour = Math.max(0, Math.min(23, Math.trunc(Number(config.dailyHour) || 0)))
24
24
  let maintainAllowed = allowMaintain && now - maintainClock.at > MAINTAIN_INTERVAL_MS
25
+ let dailyDayKey = ''
25
26
  if (maintainAllowed && dailyHour > 0) {
26
27
  const d = new Date(now)
27
28
  const dayKey = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
28
29
  if (d.getHours() < dailyHour || maintainClock.day === dayKey) maintainAllowed = false
29
- else maintainClock.day = dayKey
30
+ // 2026-11-07 R11 / P2-24:原来在**这里**就把 maintainClock.day 置位了。
31
+ // 一旦 maintain 抛错(或写盘失败),当天就再也不会重试 —— 表现是「那天记忆没衰减」,
32
+ // 而且日志里只有一行「维护失败」。现在置位挪到维护真正跑完之后。
33
+ else dailyDayKey = dayKey
30
34
  }
31
35
  if (maintainAllowed) {
32
36
  maintainClock.at = now
33
37
  try {
34
38
  const report = maintain(cwd, config)
39
+ if (dailyDayKey !== '') maintainClock.day = dailyDayKey
35
40
  if (report.decayed.length > 0 || report.compacted.length > 0) {
36
41
  note('tick', `维护完成:衰减 ${report.decayed.join('/') || '无'},压缩 ${report.compacted.length} 处`)
37
42
  }
@@ -40,7 +45,8 @@ export function tick(agent, cwd, config, { allowMaintain = true, llm = null } =
40
45
  note('tick', `维护写盘失败 ${report.errors.length} 处:${report.errors.map((item) => `${item.scope}/${item.stage}`).join('、')}`)
41
46
  }
42
47
  } catch (error) {
43
- note('tick', `维护失败:${error instanceof Error ? error.message : error}`)
48
+ // 失败不置位:下一轮(10 分钟后)还会再试一次
49
+ note('tick', `维护失败(当天稍后重试):${error instanceof Error ? error.message : error}`)
44
50
  }
45
51
  }
46
52
 
package/lib/retention.js CHANGED
@@ -27,9 +27,18 @@ import { diaryConversationsDir } from './paths.js'
27
27
  export const DAY_MS = 24 * 60 * 60 * 1000
28
28
  const DATE_FILE_RE = /^(\d{4}-\d{2}-\d{2})\.jsonl$/
29
29
 
30
- /** 本地日期键,避免为了一个函数把整个 diary.js 拖成循环依赖。 */
30
+ /**
31
+ * 本地日期键,避免为了一个函数把整个 diary.js 拖成循环依赖。
32
+ *
33
+ * 2026-11-07 R11 / P2-20:原来是 `toISOString().slice(0,10)` —— 那是 **UTC**。
34
+ * 引擎里其它所有 dateKey(completion 的 todayKey、日记文件名、归档日期)都是本地时间。
35
+ * 两套口径混用的后果很具体:东八区晚上 8 点之后本地已经是第二天、UTC 还是当天,
36
+ * 清理对话记录时算出来的「今天是哪天」差一天 —— **可能把还该留的那天删掉**。
37
+ */
31
38
  export function dateKeyOf(ms) {
32
- return new Date(ms).toISOString().slice(0, 10)
39
+ const d = new Date(Number(ms) || Date.now())
40
+ const pad = (n) => String(n).padStart(2, '0')
41
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
33
42
  }
34
43
 
35
44
  /**
@@ -5,7 +5,9 @@
5
5
  import { addRecord, classifyScope, corruptInfoOf, createCard, isCardReadonly, loadCard, mergeCards, normalizeConfig, readCardQuietly, saveCard } from '../memory.js'
6
6
  import { cardCache, loadCached, mtimeOf } from './cache.js'
7
7
  import { invalidate } from './file-cache.js'
8
- import { globalMemoryPath, projectMemoryPath } from '../paths.js'
8
+ import { globalMemoryPath, memoryProjectsDir, projectMemoryPath } from '../paths.js'
9
+ import { existsSync, readdirSync } from 'node:fs'
10
+ import { join } from 'node:path'
9
11
  import { note } from '../env.js'
10
12
 
11
13
  /**
@@ -119,8 +121,39 @@ export function saveProjectCard(cwd, card) {
119
121
 
120
122
 
121
123
  /** 记忆卡健康状态(设置页亮红用):没坏过返回 null。 */
124
+ /**
125
+ * 记忆文件健康状态(设置页亮红用)。
126
+ *
127
+ * 2026-11-07 R11 / P2-21:原来只查全局卡 —— 项目卡损坏时设置页**完全看不见**,
128
+ * 用户只会觉得「这个项目的记忆怎么不对」。现在把全局卡与所有项目卡一起汇总:
129
+ * 任何一张坏了都报出来,并说清是哪一张。
130
+ */
122
131
  export function memoryHealth() {
123
- return corruptInfoOf(globalMemoryPath())
132
+ const out = []
133
+ const globalInfo = corruptInfoOf(globalMemoryPath())
134
+ if (globalInfo !== null && globalInfo !== undefined) out.push({ scope: 'global', ...globalInfo })
135
+
136
+ // 项目卡:目录里有多少张就查多少张(数量很少,直接 readdir)
137
+ try {
138
+ const dir = memoryProjectsDir()
139
+ if (existsSync(dir)) {
140
+ for (const name of readdirSync(dir)) {
141
+ // 坏文件会被 parkCorrupt 改名成 `X.json.corrupt-<时间戳>`,而 corruptState 是以
142
+ // **原路径**为键记的 —— 所以命中改名文件时要把原名字还原出来再去查,
143
+ // 否则「坏掉的那张」恰恰被漏掉(旧实现只查全局卡,漏得更彻底)。
144
+ const corruptAt = name.indexOf('.corrupt-')
145
+ const originalName = corruptAt === -1 ? name : name.slice(0, corruptAt)
146
+ if (!originalName.endsWith('.json')) continue
147
+ const info = corruptInfoOf(join(dir, originalName))
148
+ if (info !== null && info !== undefined) out.push({ scope: 'project', file: originalName, ...info })
149
+ }
150
+ }
151
+ } catch {
152
+ /* 目录读不到就算了,别让健康检查本身抛错 */
153
+ }
154
+ if (out.length === 0) return null
155
+ // 保持旧返回形状(单个对象)的兼容性:多张时用 list 暴露全部,最新的一张也照旧展开在顶层
156
+ return out.length === 1 ? out[0] : { ...out[0], list: out, count: out.length }
124
157
  }
125
158
 
126
159
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agent-soul",
3
- "version": "0.9.4",
3
+ "version": "0.9.6",
4
4
  "type": "module",
5
5
  "description": "给 DSH 的 agent 一套会忘事的记忆、一份会变的人格和一份会起伏的心情:人格按小节合并(项目覆盖全局但不吃掉全局),记忆按人的规律衰减(清晰→模糊→只剩印象→遗忘),「心里惦记的事」让她的主动有连续性,心情跟着每轮对话自己判断、自己平复(不注入、无挂饰)。",
6
6
  "keywords": [
@@ -37,6 +37,7 @@
37
37
  "build:client": "node tools/build-client.mjs",
38
38
  "sync:host": "node tools/build-client.mjs && node tools/sync.mjs",
39
39
  "test": "node tools/build-client.mjs && node tools/run-tests.mjs",
40
+ "lint": "node tools/lint.mjs",
40
41
  "test:contracts": "node tools/run-tests.mjs --only=tests/contract/",
41
42
  "test:s1": "node tests/s1-hotfix.test.js",
42
43
  "test:s2": "node tests/s2-hardening.test.js",
package/tools/lint.mjs ADDED
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 轻量静态检查(2026-11-07 R12 / P2-30)。
4
+ *
5
+ * 为什么不用 eslint:这个项目**零运行时依赖**,为了一个 lint 装一棵 200 包的依赖树
6
+ * 不划算,而且 esbuild/TS 那套配置对纯 ESM 脚本过重。
7
+ * 这里只做两条「不需要解析器也能查、且真出过问题」的检查:
8
+ *
9
+ * ① 未使用的 import 名字 —— 报告里就有一条:`segment-memory.js` 导入了 `name` 从没用过。
10
+ * 死导入不会报错,只会在读代码时误导人(以为这里用到了)。
11
+ * ② 测试里的恒真断言 `ok(true, …)` —— 它们看起来像断言,实际什么都没验。
12
+ * 允许带 `// lint-allow:ok-true` 的行(真需要「到这里没抛异常就算过」时用)。
13
+ *
14
+ * 两条都是**保守**的:宁可漏报,也不要因为字符串里恰好出现某个词就误报。
15
+ */
16
+ import { readFileSync, readdirSync } from 'node:fs'
17
+ import { dirname, join, relative } from 'node:path'
18
+ import { fileURLToPath } from 'node:url'
19
+
20
+ const projectRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
21
+
22
+ function walk(dir, ext = '.js') {
23
+ const out = []
24
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
25
+ const full = join(dir, entry.name)
26
+ if (entry.isDirectory()) out.push(...walk(full, ext))
27
+ else if (entry.name.endsWith(ext)) out.push(full)
28
+ }
29
+ return out
30
+ }
31
+
32
+ /** 从 `import { a, b as c } from '…'` 里抠出本地名字 */
33
+ function importedNames(text) {
34
+ const names = []
35
+ const re = /import\s*\{([^}]*)\}\s*from\s*['"][^'"]+['"]/g
36
+ let m
37
+ while ((m = re.exec(text)) !== null) {
38
+ for (const part of m[1].split(',')) {
39
+ const piece = part.trim()
40
+ if (piece === '') continue
41
+ const asMatch = /\bas\s+([A-Za-z_$][\w$]*)$/.exec(piece)
42
+ const local = asMatch ? asMatch[1] : piece
43
+ if (/^[A-Za-z_$][\w$]*$/.test(local)) names.push({ local, index: m.index })
44
+ }
45
+ }
46
+ return names
47
+ }
48
+
49
+ /** 这个标识符在文件里除了 import 语句之外还出现过吗 */
50
+ function usedElsewhere(text, local, importIndex) {
51
+ const escaped = local.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
52
+ const re = new RegExp(`\\b${escaped}\\b`, 'g')
53
+ let m
54
+ while ((m = re.exec(text)) !== null) {
55
+ // 跳过 import 语句所在的那一段(从 import 到该语句结尾的分号)
56
+ if (m.index >= importIndex) {
57
+ const tail = text.slice(importIndex)
58
+ const end = tail.indexOf('\n')
59
+ const lineEnd = end === -1 ? text.length : importIndex + end
60
+ if (m.index < lineEnd) continue
61
+ }
62
+ return true
63
+ }
64
+ return false
65
+ }
66
+
67
+ const problems = []
68
+
69
+ for (const file of walk(join(projectRoot, 'lib'))) {
70
+ const rel = relative(projectRoot, file).replace(/\\/g, '/')
71
+ const text = readFileSync(file, 'utf8')
72
+ for (const { local, index } of importedNames(text)) {
73
+ if (local === 'default') continue
74
+ if (!usedElsewhere(text, local, index)) {
75
+ problems.push({ file: rel, kind: 'unused-import', name: local })
76
+ }
77
+ }
78
+ }
79
+
80
+ for (const file of walk(join(projectRoot, 'tests'))) {
81
+ const rel = relative(projectRoot, file).replace(/\\/g, '/')
82
+ const lines = readFileSync(file, 'utf8').split('\n')
83
+ lines.forEach((line, i) => {
84
+ // 注释里提到 ok(true, …) 不算问题(那是解释,不是断言)
85
+ if (/^\s*(\/\/|\*)/.test(line)) return
86
+ if (!/\bok\(\s*true\b/.test(line)) return
87
+ if (line.includes('lint-allow:ok-true')) return
88
+ problems.push({ file: rel, kind: 'ok-true', line: i + 1, text: line.trim() })
89
+ })
90
+ }
91
+
92
+ if (problems.length === 0) {
93
+ console.log('lint: 没有发现问题(未使用导入 / 恒真断言)')
94
+ process.exit(0)
95
+ }
96
+
97
+ for (const p of problems) {
98
+ if (p.kind === 'unused-import') console.error(`✗ ${p.file}: 导入了 ${p.name} 但没用过`)
99
+ else console.error(`✗ ${p.file}:${p.line}: 恒真断言 ok(true, …) —— ${p.text.slice(0, 80)}`)
100
+ }
101
+ console.error(`\nlint: ${problems.length} 个问题`)
102
+ process.exit(1)
@@ -51,16 +51,26 @@ function main() {
51
51
  // 2026-11-06 审计 Q12:失败即 break 的话,第一个红就把后面 40 多个文件全挡住,
52
52
  // 一次只能修一个问题。改成跑完全部再汇总(--stop-on-first-failure 保留旧行为)。
53
53
  const stopEarly = process.argv.includes('--stop-on-first-failure')
54
+ // 2026-11-07 R12 / P2-29:单个测试文件原来**没有超时** —— 一个挂死的用例
55
+ // (未 settle 的 await、等不到的 Promise)会把整个 CI 拖到 GitHub 的 6 小时上限。
56
+ // 默认 180 秒,可用 --timeout=<秒> 覆盖;超时按失败计,并在汇总里点名。
57
+ const timeoutArg = (process.argv.find((a) => a.startsWith('--timeout=')) ?? '').slice('--timeout='.length)
58
+ const timeoutMs = Math.max(10_000, Math.trunc(Number(timeoutArg) || 180) * 1000)
54
59
  for (const rel of files) {
55
60
  executed += 1
56
61
  console.log(`\n===== [${executed}/${files.length}] ${rel} =====`)
57
62
  const result = spawnSync(process.execPath, [join(projectRoot, rel)], {
58
63
  cwd: projectRoot,
59
64
  env: process.env,
60
- stdio: 'inherit'
65
+ stdio: 'inherit',
66
+ timeout: timeoutMs,
67
+ killSignal: 'SIGKILL'
61
68
  })
62
69
  if (result.error) {
63
- console.error(`✗ ${rel} 启动失败:${result.error.message}`)
70
+ const timedOut = result.error.code === 'ETIMEDOUT' || result.signal === 'SIGKILL'
71
+ console.error(timedOut
72
+ ? `✗ ${rel} 超时(>${Math.round(timeoutMs / 1000)}s)—— 视为失败,不让它拖死整个 CI`
73
+ : `✗ ${rel} 启动失败:${result.error.message}`)
64
74
  failed += 1
65
75
  failures.push(rel)
66
76
  if (stopEarly) break