@linjz/opencode-qqbot 0.3.15 → 0.3.17

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.
Files changed (61) hide show
  1. package/README.md +303 -229
  2. package/README.zh-CN.md +313 -0
  3. package/bin/openqq.js +13 -0
  4. package/dist/notify-cli.js +92 -26
  5. package/dist/opencode-qqbot-plugin.js +1201 -67
  6. package/dist/openqq-bot.js +3963 -893
  7. package/dist/openqq-cli.js +980 -0
  8. package/dist/openqq-watchdog.js +1326 -0
  9. package/package.json +8 -5
  10. package/src/bridge.ts +1599 -150
  11. package/src/cli/notify.ts +170 -158
  12. package/src/cli/openqq-main.ts +95 -0
  13. package/src/cli/service-main.ts +302 -0
  14. package/src/cli/watchdog-main.ts +92 -0
  15. package/src/commands.ts +670 -554
  16. package/src/config.ts +122 -3
  17. package/src/core/bot-config.ts +66 -0
  18. package/src/core/bot-control.ts +166 -0
  19. package/src/core/bot-launcher.ts +110 -15
  20. package/src/core/card-approval.ts +20 -9
  21. package/src/core/cron-reminders.ts +84 -0
  22. package/src/core/delivery.ts +145 -54
  23. package/src/core/discovery.ts +207 -151
  24. package/src/core/error-rescue.ts +1 -1
  25. package/src/core/file-log.ts +50 -9
  26. package/src/core/form-bridge.ts +14 -5
  27. package/src/core/form-journal.ts +4 -4
  28. package/src/core/gateway-state.ts +3 -3
  29. package/src/core/inflight-journal.ts +215 -36
  30. package/src/core/instance-lock.ts +42 -3
  31. package/src/core/linkwatch.ts +3 -4
  32. package/src/core/log-rotate.ts +91 -0
  33. package/src/core/markdown.ts +117 -0
  34. package/src/core/message-queue.ts +242 -91
  35. package/src/core/mirror.ts +228 -182
  36. package/src/core/notices.ts +62 -0
  37. package/src/core/notify-sink.ts +93 -96
  38. package/src/core/outbound-sanitize.ts +29 -0
  39. package/src/core/outbox.ts +10 -9
  40. package/src/core/permission.ts +634 -303
  41. package/src/core/question-form.ts +230 -0
  42. package/src/core/queue-view.ts +662 -0
  43. package/src/core/send-media.ts +61 -2
  44. package/src/core/start-error.ts +26 -0
  45. package/src/core/storage.ts +34 -0
  46. package/src/core/stt.ts +55 -0
  47. package/src/core/supervisor-election.ts +53 -0
  48. package/src/core/watchdog.ts +670 -0
  49. package/src/core/zombie-reaper.ts +127 -0
  50. package/src/index.ts +262 -162
  51. package/src/opencode/client.ts +237 -27
  52. package/src/opencode/eventstream.ts +94 -12
  53. package/src/opencode/history.ts +4 -2
  54. package/src/opencode/mirror.ts +25 -5
  55. package/src/opencode/sessions.ts +135 -37
  56. package/src/plugin-entry.ts +139 -115
  57. package/src/qq/api.ts +165 -61
  58. package/src/qq/gateway.ts +114 -16
  59. package/src/qq/media.ts +21 -0
  60. package/src/qq/sender.ts +79 -18
  61. package/src/qq/types.ts +7 -0
@@ -1,6 +1,6 @@
1
- // @input: fs/path/os(台账落盘)
1
+ // @input: fs/path/os(台账落盘)
2
2
  // @output: claimInflight, recordInflight, settleInflight, pendingInflight, classifyInflight(纯函数供测试),
3
- // pruneInflightEntries(保留策略纯函数), newInflightAttemptId,
3
+ // markInflightStage, listInflightView, pruneInflightEntries(保留策略纯函数), newInflightAttemptId,
4
4
  // resetInflightJournal(测试用),
5
5
  // INFLIGHT_MAX_AGE_MS, SETTLED_RETENTION_MS, SETTLED_RETENTION_LIMIT, redispatchMaxAgeMs
6
6
  // @pos: core - 在途台账(重启换代丢消息修复:QQ 消息派发落账、答复送达销账、启动对账)
@@ -8,9 +8,9 @@
8
8
  // 事故背景(2026-10-30,用户实证):bot 重启/网关静默死亡窗口内到达的 QQ 消息
9
9
  // 丢失无反馈——在途回合状态全在内存,进程换代即蒸发。本模块把"派发→送达"责任
10
10
  // 落盘到 ~/.openqq/inflight.json,启动时对账恢复(bridge.recoverInflightRounds)。
11
+ import { storageFile } from "./storage.js"
11
12
  import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, unlinkSync, statSync } from "fs"
12
13
  import { join } from "path"
13
- import { homedir } from "os"
14
14
  import { admissionDecision } from "./inbound-dedupe.js"
15
15
 
16
16
  export interface InflightEntry {
@@ -31,6 +31,49 @@ export interface InflightEntry {
31
31
  fingerprint?: string
32
32
  /** 本回合的 prompt 用户消息 id(修复⑧直答归属的回合边界锚点) */
33
33
  promptId?: string
34
+ /**
35
+ * 可观测细化阶段(2026-11-05 队列/台账可观测性):
36
+ * claimed=已受理未入队 | queued=已入队 | dispatched=已派发未落 promptId
37
+ * running=执行中 | background=后台等待 | settled=已结清。
38
+ * state 仍是权威二元态;stage 只做诊断,缺失时按 sessionId/promptId 推导。
39
+ */
40
+ stage?: InflightStage
41
+ /** 与内存队列 #id 对齐(重启恢复 FIFO 顺序用) */
42
+ queueId?: number
43
+ /** 入队时刻(重启按此排序重建队列) */
44
+ enqueuedAt?: number
45
+ /** 最后一次状态变更时刻 */
46
+ updatedAt?: number
47
+ /** 结清原因(诊断"为什么没答") */
48
+ settleReason?: SettleReason
49
+ /** 受理/更新所属进程(跨进程归属诊断) */
50
+ ownerPid?: number
51
+ /** 最近一次失败摘要(截 200 字) */
52
+ lastError?: string
53
+ /** 死回合自动续作已消耗次数(2026-11-19 owner 裁定:单任务续作上限 3 次,落盘防重启洗白) */
54
+ resumeCount?: number
55
+ }
56
+
57
+ export type InflightStage = "claimed" | "queued" | "dispatched" | "running" | "background" | "settled"
58
+
59
+ export type SettleReason =
60
+ | "answered"
61
+ | "error"
62
+ | "queue-full"
63
+ | "duplicate-msgid"
64
+ | "duplicate-intent"
65
+ | "cancelled"
66
+ | "dropped"
67
+ | "blocked"
68
+ | "superseded"
69
+ | "steered"
70
+ | "expired"
71
+ | "redispatch"
72
+ | "manual"
73
+
74
+ export interface InflightView {
75
+ inflight: InflightEntry[]
76
+ settled: InflightEntry[]
34
77
  }
35
78
 
36
79
  /** 生成新的投递代次 ID(bridge 显式新回合/显式重投时调用) */
@@ -71,16 +114,17 @@ export function redispatchMaxAgeMs(): number {
71
114
  return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7_200_000
72
115
  }
73
116
 
74
- // 测试可经 QQ_INFLIGHT_FILE 指向临时文件
75
- function journalPath(): string {
76
- return process.env.QQ_INFLIGHT_FILE || join(homedir(), ".openqq", "inflight.json")
117
+ // 路径解析:显式注入(多角色 createInflightJournal(file))> env 覆盖(测试)> legacy 全局。
118
+ function journalPath(file?: string): string {
119
+ return file || process.env.QQ_INFLIGHT_FILE || storageFile("inflight.json")
77
120
  }
78
121
 
79
- function load(): InflightEntry[] {
122
+ function load(file?: string): InflightEntry[] {
80
123
  let entries: InflightEntry[] = []
124
+ const path = journalPath(file)
81
125
  try {
82
- if (existsSync(journalPath())) {
83
- const raw = JSON.parse(readFileSync(journalPath(), "utf-8"))
126
+ if (existsSync(path)) {
127
+ const raw = JSON.parse(readFileSync(path, "utf-8"))
84
128
  if (Array.isArray(raw)) entries = raw
85
129
  }
86
130
  } catch {
@@ -90,8 +134,8 @@ function load(): InflightEntry[] {
90
134
  return pruneInflightEntries(entries)
91
135
  }
92
136
 
93
- function save(entries: InflightEntry[]): void {
94
- const path = journalPath()
137
+ function save(file: string | undefined, entries: InflightEntry[]): void {
138
+ const path = journalPath(file)
95
139
  mkdirSync(join(path, ".."), { recursive: true })
96
140
  const retained = pruneInflightEntries(entries)
97
141
  // 临时文件带进程与随机后缀:并发执行体不会互相覆盖对方的 tmp。
@@ -111,8 +155,8 @@ const JOURNAL_LOCK_STALE_MS = 30_000
111
155
  const JOURNAL_LOCK_WAIT_MS = 5_000
112
156
  const sleepArray = new Int32Array(new SharedArrayBuffer(4))
113
157
 
114
- function withJournalLock<T>(fn: () => T): T {
115
- const path = journalPath()
158
+ function withJournalLock<T>(file: string | undefined, fn: () => T): T {
159
+ const path = journalPath(file)
116
160
  mkdirSync(join(path, ".."), { recursive: true })
117
161
  const lockPath = `${path}.lock`
118
162
  const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`
@@ -147,11 +191,11 @@ function withJournalLock<T>(fn: () => T): T {
147
191
  }
148
192
  }
149
193
 
150
- function mutate<T>(fn: (entries: InflightEntry[]) => T): T {
151
- return withJournalLock(() => {
152
- const entries = load()
194
+ function mutate<T>(file: string | undefined, fn: (entries: InflightEntry[]) => T): T {
195
+ return withJournalLock(file, () => {
196
+ const entries = load(file)
153
197
  const result = fn(entries)
154
- save(entries)
198
+ save(file, entries)
155
199
  return result
156
200
  })
157
201
  }
@@ -169,8 +213,8 @@ export type ClaimOutcome = "ok" | "duplicate-msgid" | "duplicate-intent"
169
213
  * attemptId;未传则生成新代次);不另建去重文件。
170
214
  * 被 24h/20 条保留策略裁掉的旧 msgId 也可正常认领。
171
215
  */
172
- export function claimInflightDetailed(entry: Omit<InflightEntry, "state">, opts?: { fingerprint?: string }): ClaimOutcome {
173
- return mutate((entries) => {
216
+ export function claimInflightDetailed(entry: Omit<InflightEntry, "state">, opts?: { fingerprint?: string; file?: string }): ClaimOutcome {
217
+ return mutate(opts?.file, (entries) => {
174
218
  const fingerprint = opts?.fingerprint ?? entry.fingerprint ?? ""
175
219
  const decision = admissionDecision({
176
220
  hasSameMsgIdInflight: entries.some((e) => e.msgId === entry.msgId && e.state === "inflight"),
@@ -181,19 +225,35 @@ export function claimInflightDetailed(entry: Omit<InflightEntry, "state">, opts?
181
225
  })
182
226
  if (decision !== "ok") return decision
183
227
  const attempt = entry.attemptId ?? newInflightAttemptId()
228
+ const now = Date.now()
184
229
  const existing = entries.find((e) => e.msgId === entry.msgId)
185
230
  if (existing) {
186
- Object.assign(existing, entry, { fingerprint, attemptId: attempt, state: "inflight" as const })
231
+ Object.assign(existing, entry, {
232
+ fingerprint,
233
+ attemptId: attempt,
234
+ state: "inflight" as const,
235
+ stage: entry.stage ?? "claimed",
236
+ updatedAt: now,
237
+ ownerPid: entry.ownerPid ?? process.pid,
238
+ })
187
239
  } else {
188
- entries.push({ ...entry, fingerprint, attemptId: attempt, state: "inflight" as const })
240
+ entries.push({
241
+ ...entry,
242
+ fingerprint,
243
+ attemptId: attempt,
244
+ state: "inflight" as const,
245
+ stage: entry.stage ?? "claimed",
246
+ updatedAt: now,
247
+ ownerPid: entry.ownerPid ?? process.pid,
248
+ })
189
249
  }
190
250
  return "ok"
191
251
  })
192
252
  }
193
253
 
194
254
  /** 兼容旧布尔签名的认领(测试与既有调用方) */
195
- export function claimInflight(entry: Omit<InflightEntry, "state">): boolean {
196
- return claimInflightDetailed(entry) === "ok"
255
+ export function claimInflight(entry: Omit<InflightEntry, "state">, file?: string): boolean {
256
+ return claimInflightDetailed(entry, { file }) === "ok"
197
257
  }
198
258
 
199
259
  /**
@@ -203,22 +263,41 @@ export function claimInflight(entry: Omit<InflightEntry, "state">): boolean {
203
263
  * - 已 settled:显式重投重新激活(换新代次与新的 at/user/session/text);
204
264
  * - 无记录:新增在途。
205
265
  */
206
- export function recordInflight(entry: Omit<InflightEntry, "state">): void {
207
- mutate((entries) => {
266
+ export function recordInflight(entry: Omit<InflightEntry, "state">, file?: string): void {
267
+ mutate(file, (entries) => {
268
+ const now = Date.now()
208
269
  const existing = entries.find((e) => e.msgId === entry.msgId)
209
270
  if (existing) {
210
271
  if (existing.state === "inflight") {
211
272
  if (entry.attemptId && existing.attemptId && entry.attemptId !== existing.attemptId) return
212
273
  if (!existing.sessionId && entry.sessionId) existing.sessionId = entry.sessionId
213
274
  if (!existing.promptId && entry.promptId) existing.promptId = entry.promptId
275
+ // 派发落账 = 已进入会话;stage 只前进不回退(queued → dispatched)
276
+ if (entry.sessionId) existing.stage = existing.stage === "running" || existing.stage === "background" ? existing.stage : "dispatched"
277
+ existing.updatedAt = now
278
+ if (!existing.ownerPid) existing.ownerPid = process.pid
214
279
  return
215
280
  }
216
281
  // settled:视为显式重投,重新激活为新在途回合
217
282
  const attempt = entry.attemptId ?? newInflightAttemptId()
218
- Object.assign(existing, entry, { attemptId: attempt, state: "inflight" as const })
283
+ Object.assign(existing, entry, {
284
+ attemptId: attempt,
285
+ state: "inflight" as const,
286
+ stage: entry.stage ?? (entry.sessionId ? "dispatched" : "claimed"),
287
+ updatedAt: now,
288
+ settleReason: undefined,
289
+ ownerPid: entry.ownerPid ?? process.pid,
290
+ })
219
291
  return
220
292
  }
221
- entries.push({ ...entry, attemptId: entry.attemptId ?? newInflightAttemptId(), state: "inflight" as const })
293
+ entries.push({
294
+ ...entry,
295
+ attemptId: entry.attemptId ?? newInflightAttemptId(),
296
+ state: "inflight" as const,
297
+ stage: entry.stage ?? (entry.sessionId ? "dispatched" : "claimed"),
298
+ updatedAt: now,
299
+ ownerPid: entry.ownerPid ?? process.pid,
300
+ })
222
301
  })
223
302
  }
224
303
 
@@ -226,38 +305,104 @@ export function recordInflight(entry: Omit<InflightEntry, "state">): void {
226
305
  * 销账:答复已送达(或已转入有接管的后台等待/已给用户终态反馈)。
227
306
  * 传入 attemptId 时必须 msgId + attemptId 双匹配才销账——settled 重新认领后,
228
307
  * 旧代次的迟到 settle 不得把新在途回合误销。返回是否实际销账。
308
+ * reason 记录"为什么结束",供 /ledger 区分 answered 与 rejected。
229
309
  */
230
- export function settleInflight(msgId: string, attemptId?: string): boolean {
231
- return mutate((entries) => {
310
+ export function settleInflight(msgId: string, attemptId?: string, reason: SettleReason = "answered", file?: string): boolean {
311
+ return mutate(file, (entries) => {
232
312
  const entry = entries.find(
233
313
  (e) => e.msgId === msgId && e.state === "inflight" && (!attemptId || !e.attemptId || e.attemptId === attemptId),
234
314
  )
235
315
  if (!entry) return false
236
316
  entry.state = "settled"
317
+ entry.stage = "settled"
318
+ entry.settleReason = reason
319
+ entry.updatedAt = Date.now()
237
320
  return true
238
321
  })
239
322
  }
240
323
 
241
324
  /** 待对账清单(启动恢复用) */
242
- export function pendingInflight(): InflightEntry[] {
243
- return load().filter((e) => e.state === "inflight")
325
+ export function pendingInflight(file?: string): InflightEntry[] {
326
+ return load(file).filter((e) => e.state === "inflight")
327
+ }
328
+
329
+ /** 台账快照(/queue 与 /ledger 派生视图的数据源;不做用户过滤) */
330
+ export function listInflightView(file?: string): InflightView {
331
+ const entries = load(file)
332
+ return {
333
+ inflight: entries.filter((e) => e.state === "inflight").sort((a, b) => a.at - b.at),
334
+ settled: entries.filter((e) => e.state === "settled").sort((a, b) => b.at - a.at),
335
+ }
336
+ }
337
+
338
+ /**
339
+ * 阶段推进(可观测性):只对在途账生效,默认只前进不回退。
340
+ * patch 用于回填 queueId/enqueuedAt/sessionId/promptId/lastError。
341
+ * opts.force:重启恢复排队时允许回退到 queued(进程换代后旧 stage 不再可信)。
342
+ */
343
+ export function markInflightStage(
344
+ msgId: string,
345
+ stage: InflightStage,
346
+ patch?: Partial<Pick<InflightEntry, "queueId" | "enqueuedAt" | "sessionId" | "promptId" | "lastError">>,
347
+ opts?: { force?: boolean; file?: string },
348
+ ): boolean {
349
+ const rank: Record<InflightStage, number> = {
350
+ claimed: 0,
351
+ queued: 1,
352
+ dispatched: 2,
353
+ running: 3,
354
+ background: 4,
355
+ settled: 5,
356
+ }
357
+ return mutate(opts?.file, (entries) => {
358
+ const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight")
359
+ if (!entry) return false
360
+ if (opts?.force || !entry.stage || rank[stage] >= rank[entry.stage]) entry.stage = stage
361
+ if (patch?.queueId !== undefined) entry.queueId = patch.queueId
362
+ if (patch?.enqueuedAt !== undefined) entry.enqueuedAt = patch.enqueuedAt
363
+ if (patch?.sessionId && !entry.sessionId) entry.sessionId = patch.sessionId
364
+ if (patch?.promptId && !entry.promptId) entry.promptId = patch.promptId
365
+ if (patch?.lastError !== undefined) entry.lastError = patch.lastError.slice(0, 200)
366
+ entry.updatedAt = Date.now()
367
+ return true
368
+ })
244
369
  }
245
370
 
246
371
  /**
247
372
  * 回合 prompt 落库后回填 promptId(修复⑧):后台等待/重启重挂的直答归属
248
373
  * 需要「这是哪个回合」的边界锚点,taskId 台账是跨进程唯一可靠载体。
374
+ * 2026-11-05:同时把 stage 推进到 running(可观测性)。
249
375
  */
250
- export function markInflightPromptId(msgId: string, promptId: string): void {
376
+ export function markInflightPromptId(msgId: string, promptId: string, file?: string): void {
251
377
  if (!promptId) return
252
- mutate((entries) => {
378
+ mutate(file, (entries) => {
253
379
  const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight")
254
- if (entry && !entry.promptId) entry.promptId = promptId
380
+ if (!entry) return
381
+ if (!entry.promptId) entry.promptId = promptId
382
+ entry.stage = "running"
383
+ entry.updatedAt = Date.now()
384
+ })
385
+ }
386
+
387
+ /**
388
+ * 续作锚点更新(2026-11-19 死回合自动续作):新回合的 promptId 必须强制覆盖旧锚点
389
+ * (markPromptId/markStage 的「只补空」语义不适用——旧锚点已存在),
390
+ * resumeCount 同步落盘:bot 重启后启动对账重挂按已消耗次数续算,上限不洗白。
391
+ */
392
+ export function markInflightResume(msgId: string, promptId: string, resumeCount: number, file?: string): void {
393
+ if (!promptId) return
394
+ mutate(file, (entries) => {
395
+ const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight")
396
+ if (!entry) return
397
+ entry.promptId = promptId
398
+ entry.resumeCount = resumeCount
399
+ entry.updatedAt = Date.now()
255
400
  })
256
401
  }
257
402
 
258
403
  /** 测试用:清空台账文件状态 */
259
- export function resetInflightJournal(): void {
260
- withJournalLock(() => save([]))
404
+ export function resetInflightJournal(file?: string): void {
405
+ withJournalLock(file, () => save(file, []))
261
406
  }
262
407
 
263
408
  // —— 对账分类(纯函数)——
@@ -380,3 +525,37 @@ export function classifyInflight(
380
525
  }
381
526
  return { kind: "running" }
382
527
  }
528
+
529
+ // ── 多角色绑定实例(2026-11-17,owner 裁定单进程多 bot 身份)──
530
+ // 单进程多角色时,各角色的台账必须物理隔离(否则重启对账跨角色误补/误派)。
531
+ // createInflightJournal(file) 返回绑定到指定文件的实例;模块级具名导出 =
532
+ // 默认实例(路径解析照旧:env 覆盖 > legacy 全局),既有调用方/测试零改动。
533
+ export interface InflightJournal {
534
+ readonly file: string
535
+ claim: typeof claimInflight
536
+ claimDetailed: typeof claimInflightDetailed
537
+ record: typeof recordInflight
538
+ settle: typeof settleInflight
539
+ pending: typeof pendingInflight
540
+ view: typeof listInflightView
541
+ markStage: typeof markInflightStage
542
+ markPromptId: typeof markInflightPromptId
543
+ markResume: typeof markInflightResume
544
+ reset: typeof resetInflightJournal
545
+ }
546
+
547
+ export function createInflightJournal(file?: string): InflightJournal {
548
+ return {
549
+ file: journalPath(file),
550
+ claim: (entry) => claimInflight(entry, file),
551
+ claimDetailed: (entry, opts) => claimInflightDetailed(entry, { ...opts, file }),
552
+ record: (entry) => recordInflight(entry, file),
553
+ settle: (msgId, attemptId, reason) => settleInflight(msgId, attemptId, reason, file),
554
+ pending: () => pendingInflight(file),
555
+ view: () => listInflightView(file),
556
+ markStage: (msgId, stage, patch, opts) => markInflightStage(msgId, stage, patch, { ...opts, file }),
557
+ markPromptId: (msgId, promptId) => markInflightPromptId(msgId, promptId, file),
558
+ markResume: (msgId, promptId, resumeCount) => markInflightResume(msgId, promptId, resumeCount, file),
559
+ reset: () => resetInflightJournal(file),
560
+ }
561
+ }
@@ -9,7 +9,7 @@
9
9
  // - 抢锁失败时看 mtime:超 30s 未刷新判僵尸锁(宿主崩溃)→ 删除强抢
10
10
  // - 未抢到可进入待命循环,每 5s 重试,宿主退出/暴毙后自动接管
11
11
  // 锁文件按 appId 隔离:~/.openqq/openqq-<appId>.lock。
12
- import { openSync, readFileSync, writeFileSync, closeSync, unlinkSync, statSync, utimesSync, mkdirSync } from "fs"
12
+ import { openSync, readFileSync, readdirSync, writeFileSync, closeSync, unlinkSync, statSync, utimesSync, mkdirSync } from "fs"
13
13
  import { join } from "path"
14
14
  import { homedir } from "os"
15
15
 
@@ -22,6 +22,9 @@ const LOCK_RETRY_MS = 5_000 // 待命抢锁间隔
22
22
  // 心跳 touch 失败是静默的(锁文件被新实例接管/删除后自己并不知道),双 believer
23
23
  // 并存造成同 msgId 并发受理(主链)。自检看锁文件里的 pid:不是自己且进程存活
24
24
  // → 本实例是残留,自杀退出;锁文件消失同样说明被强抢 → 自杀。待命态无锁不检。
25
+ // P2-10(2026-11-09):自杀判定加锁 mtime 新鲜度——真 holder 每 10s 心跳 touch;
26
+ // holder pid 存活但锁已陈旧 = 高度疑似 PID 复用(Windows pid 回收快),此时不自杀,
27
+ // 交由 stale 强抢流程正常接管(误自杀比双跑代价大,宽进严出)。
25
28
  const LOCK_SELF_CHECK_MS = 60_000
26
29
 
27
30
  export interface InstanceLock {
@@ -33,6 +36,37 @@ function lockPathOf(appId: string): string {
33
36
  return join(homedir(), ".openqq", `openqq-${appId}.lock`)
34
37
  }
35
38
 
39
+ /**
40
+ * 按 pid 清扫实例锁(2026-11-20 owner 批「修甲乙」:锁即进程)。
41
+ * 单进程多角色持多把 openqq-<appId>.lock,杀进程后应清其持有的全部锁——
42
+ * 调用方不再记角色名单。锁文件内嵌 pid(acquireInstanceLockAt 写入),按 pid
43
+ * 匹配精准清扫:不误清他进程锁、不碰 supervisor.lock 等非实例锁。坏锁/占用
44
+ * 一律跳过(僵尸判定与接管仍由 mtime 机制兜底)。
45
+ */
46
+ export function releaseLocksOfPid(pid: number, dir: string): string[] {
47
+ let names: string[]
48
+ try {
49
+ names = readdirSync(dir)
50
+ } catch {
51
+ return []
52
+ }
53
+ const cleared: string[] = []
54
+ for (const name of names) {
55
+ if (!/^openqq-.+\.lock$/.test(name)) continue
56
+ const p = join(dir, name)
57
+ try {
58
+ const holder = JSON.parse(readFileSync(p, "utf-8")) as { pid?: unknown }
59
+ if (holder.pid === pid) {
60
+ unlinkSync(p)
61
+ cleared.push(p)
62
+ }
63
+ } catch {
64
+ /* 坏锁/读写竞态——跳过,mtime 僵尸机制兜底 */
65
+ }
66
+ }
67
+ return cleared
68
+ }
69
+
36
70
  function touch(path: string): void {
37
71
  const now = new Date()
38
72
  utimesSync(path, now, now)
@@ -87,8 +121,13 @@ export function acquireInstanceLockAt(
87
121
  if (holder === process.pid) return
88
122
  try {
89
123
  process.kill(holder!, 0)
90
- console.error(`[instance-lock] 自检:锁已被 pid=${holder} 持有且进程存活,本实例为残留 believer,自杀退出`)
91
- process.exit(1)
124
+ // P2-10:holder 存活时分两种情况——锁新鲜=真双 believer(自杀);锁陈旧=疑 PID 复用(不自杀)
125
+ const lockFresh = Date.now() - statSync(path).mtimeMs <= LOCK_STALE_MS
126
+ if (lockFresh) {
127
+ console.error(`[instance-lock] 自检:锁已被 pid=${holder} 持有且进程存活(锁新鲜),本实例为残留 believer,自杀退出`)
128
+ process.exit(1)
129
+ }
130
+ console.warn(`[instance-lock] 自检:holder pid=${holder} 存活但锁已陈旧(疑 PID 复用),不自杀,交由 stale 强抢接管`)
92
131
  } catch {
93
132
  /* holder 已死:等待其锁被 stale 逻辑回收,本实例继续自检 */
94
133
  }
@@ -1,4 +1,4 @@
1
- // HC2(2026-10-26):运行中链路自愈巡检。
1
+ // HC2(2026-10-26):运行中链路自愈巡检。
2
2
  // 复盘3 教训:bot 与 opencode 平时零流量 + 看门狗只验进程心跳 → 下游死亡
3
3
  // 不可观测(2026-10-26 实证:端口漂移后黑暗 3 天,直到用户消息撞上)。
4
4
  // 本模块给链路装独立心跳:
@@ -11,9 +11,8 @@
11
11
  // @input: client(healthCheck/rebase)、discoverOpencode、alarm 回调、fs
12
12
  // @output: startLinkWatch, LinkWatchDeps, IncidentRecord, incidentPath
13
13
  // @pos: core - 链路巡检(HC2)
14
+ import { storageFile } from "./storage.js"
14
15
  import { existsSync, readFileSync, writeFileSync } from "fs"
15
- import { join } from "path"
16
- import { homedir } from "os"
17
16
  import { discoverOpencode, persistDiscovery, type OpencodeDiscovery } from "./discovery.js"
18
17
  import { healthCheck, type OpencodeClient } from "../opencode/client.js"
19
18
 
@@ -40,7 +39,7 @@ export interface IncidentRecord {
40
39
  }
41
40
 
42
41
  export function incidentPath(): string {
43
- return join(homedir(), ".openqq", "incident.json")
42
+ return storageFile("incident.json")
44
43
  }
45
44
 
46
45
  function saveIncident(path: string, rec: IncidentRecord): void {
@@ -0,0 +1,91 @@
1
+ // @input: fs、环境变量(QQ_LOG_MAX_MB / QQ_LOG_KEEP / QQ_LOG_TOTAL_MB)
2
+ // @output: logLimitsFromEnv, rotateLogIfNeeded, enforceLogBudget
3
+ // @pos: core - 统一日志滚动与预算闸(2026-11-20 owner 批「openqq.log 合并批」)
4
+ //
5
+ // 背景:bot 双写日志(openqq.log/bot.out.log 同源)+ watchdog 审计(watchdog.log)
6
+ // 三路各自为政、零预算约束。合并后单文件由本模块统一管辖:
7
+ // 滚动:active 超 QQ_LOG_MAX_MB(默认 20MB)→ 依次改名 .1←active、.2←.1…,
8
+ // 超过 QQ_LOG_KEEP(默认 4)代的最旧档直接删除。
9
+ // 预算:openqq.log* 全部世代合计超 QQ_LOG_TOTAL_MB(默认 100MB)时,从最旧
10
+ // 世代起删到达标——正常滚动下结构上限 20×(4+1)=100MB 天然达标,本闸
11
+ // 兜「调参后遗留大文件 / 脏命名」异常态。
12
+ // 并发:bot 与 watchdog 双进程同写一个文件,轮转的 rename/rm 竞态全程容忍
13
+ //(try/catch,失败即本轮放弃,下个写者再试),绝不阻断日志与主流程。
14
+ import { existsSync, renameSync, rmSync, statSync } from "fs"
15
+
16
+ export interface LogLimits {
17
+ maxBytes: number
18
+ keepBackups: number
19
+ totalBudgetBytes: number
20
+ }
21
+
22
+ const MB = 1024 * 1024
23
+
24
+ const num = (v: string | undefined, d: number): number => {
25
+ const n = Number(v)
26
+ return Number.isFinite(n) && n > 0 ? n : d
27
+ }
28
+
29
+ export function logLimitsFromEnv(env: NodeJS.ProcessEnv = process.env): LogLimits {
30
+ return {
31
+ maxBytes: num(env.QQ_LOG_MAX_MB, 20) * MB,
32
+ keepBackups: Math.floor(num(env.QQ_LOG_KEEP, 4)),
33
+ totalBudgetBytes: num(env.QQ_LOG_TOTAL_MB, 100) * MB,
34
+ }
35
+ }
36
+
37
+ /** 超阈轮转:active→.1→.2…,超 keepBackups 的最旧档先删。返回本轮是否轮转过。 */
38
+ export function rotateLogIfNeeded(logPath: string, limits: LogLimits = logLimitsFromEnv()): boolean {
39
+ try {
40
+ if (!existsSync(logPath) || statSync(logPath).size <= limits.maxBytes) return false
41
+ try {
42
+ rmSync(`${logPath}.${limits.keepBackups}`, { force: true })
43
+ } catch {
44
+ /* 最旧档不存在或占用——容忍 */
45
+ }
46
+ for (let i = limits.keepBackups - 1; i >= 1; i--) {
47
+ const from = `${logPath}.${i}`
48
+ if (!existsSync(from)) continue
49
+ try {
50
+ renameSync(from, `${logPath}.${i + 1}`)
51
+ } catch {
52
+ /* 占用/竞态——容忍,下轮再移 */
53
+ }
54
+ }
55
+ try {
56
+ renameSync(logPath, `${logPath}.1`)
57
+ } catch {
58
+ return false
59
+ }
60
+ return true
61
+ } catch {
62
+ return false
63
+ }
64
+ }
65
+
66
+ /** 总预算闸:logPath* 全世代合计超总预算时从最旧世代删起,直至达标或只剩 active。 */
67
+ export function enforceLogBudget(logPath: string, limits: LogLimits = logLimitsFromEnv()): void {
68
+ try {
69
+ const sizes = new Map<number, number>()
70
+ let total = 0
71
+ for (let i = 0; i <= 64; i++) {
72
+ const p = i === 0 ? logPath : `${logPath}.${i}`
73
+ if (!existsSync(p)) break
74
+ const s = statSync(p).size
75
+ sizes.set(i, s)
76
+ total += s
77
+ }
78
+ for (let i = limits.keepBackups; i >= 1 && total > limits.totalBudgetBytes; i--) {
79
+ const s = sizes.get(i)
80
+ if (s === undefined) continue
81
+ try {
82
+ rmSync(`${logPath}.${i}`, { force: true })
83
+ total -= s
84
+ } catch {
85
+ /* 占用——容忍 */
86
+ }
87
+ }
88
+ } catch {
89
+ /* 预算闸绝不阻断 */
90
+ }
91
+ }