@linjz/opencode-qqbot 0.3.16 → 0.3.18

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 (45) hide show
  1. package/README.md +316 -266
  2. package/README.zh-CN.md +326 -0
  3. package/dist/notify-cli.js +64 -12
  4. package/dist/opencode-qqbot-plugin.js +591 -92
  5. package/dist/openqq-bot.js +1172 -303
  6. package/dist/openqq-cli.js +253 -64
  7. package/dist/openqq-watchdog.js +373 -110
  8. package/package.json +4 -3
  9. package/src/bridge.ts +448 -32
  10. package/src/cli/notify.ts +4 -1
  11. package/src/cli/watchdog-main.ts +22 -7
  12. package/src/commands.ts +74 -58
  13. package/src/config.ts +39 -5
  14. package/src/core/bot-config.ts +66 -0
  15. package/src/core/bot-control.ts +21 -3
  16. package/src/core/bot-launcher.ts +4 -2
  17. package/src/core/cron-reminders.ts +84 -0
  18. package/src/core/delivery.ts +24 -1
  19. package/src/core/discovery.ts +207 -169
  20. package/src/core/error-rescue.ts +1 -1
  21. package/src/core/file-log.ts +16 -7
  22. package/src/core/inflight-journal.ts +1 -0
  23. package/src/core/instance-lock.ts +32 -1
  24. package/src/core/log-rotate.ts +91 -0
  25. package/src/core/mirror.ts +13 -4
  26. package/src/core/notices.ts +62 -0
  27. package/src/core/outbound-sanitize.ts +29 -0
  28. package/src/core/permission.ts +16 -0
  29. package/src/core/qq-instructions.ts +122 -0
  30. package/src/core/queue-view.ts +1 -0
  31. package/src/core/send-media.ts +29 -2
  32. package/src/core/send-requests.ts +227 -0
  33. package/src/core/start-error.ts +26 -0
  34. package/src/core/stt.ts +55 -0
  35. package/src/core/supervisor-election.ts +53 -0
  36. package/src/core/turn-correction.ts +68 -0
  37. package/src/core/watchdog.ts +171 -14
  38. package/src/index.ts +262 -250
  39. package/src/opencode/client.ts +32 -1
  40. package/src/opencode/mirror.ts +17 -4
  41. package/src/opencode/sessions.ts +20 -1
  42. package/src/plugin-entry.ts +67 -2
  43. package/src/qq/gateway.ts +35 -0
  44. package/src/qq/media.ts +21 -0
  45. package/src/qq/sender.ts +50 -1
@@ -0,0 +1,53 @@
1
+ // @input: fs、时钟
2
+ // @output: electSupervisor(channel, opts?)
3
+ // @pos: core - 监督通道选主租约(2026-11-20 owner 批「双触发器归一」)
4
+ //
5
+ // 背景:superviseOnce 的监督矩阵已是杀/拉唯一权威,但触发器有两个——
6
+ // service(计划任务 openqq-watchdog --once)与 plugin(引擎内嵌引导器巡检)。
7
+ // 双触发器相位不一,监督者认领互斥(90s claim)只能逐 tick 串行,历史上造成
8
+ // 排程撞车(11-20 激活亲历 restart 与巡检互相踩相位)。
9
+ // 归一:本租约选出一个独占监督通道——赢家每 tick 续租并照常 superviseOnce,
10
+ // 输家整轮让贤(连 superviseOnce 都不进:不抢认领、不写强度账、零干扰);
11
+ // 租约过期(赢家死亡/停排,TTL 10 分钟)后另一通道自动接管,双向自愈。
12
+ // 同通道不同 pid(多引擎并发加载插件)同样互斥。
13
+ // fail-open:租约文件不可写时放行监督——监督缺失比双触发更糟。
14
+ import { readFileSync, writeFileSync } from "fs"
15
+ import { join } from "path"
16
+ import { homedir } from "os"
17
+
18
+ export type SupervisorChannel = "service" | "plugin"
19
+
20
+ export interface SupervisorLease {
21
+ channel: SupervisorChannel
22
+ pid: number
23
+ until: number
24
+ }
25
+
26
+ const LEASE_PATH = join(homedir(), ".openqq", "supervisor-lease.json")
27
+ const LEASE_TTL_MS = 10 * 60_000
28
+
29
+ /** 选主:持有/夺得租约返回 true(可监督);他通道(或他 pid)持新鲜租约返回 false(让贤)。 */
30
+ export function electSupervisor(
31
+ channel: SupervisorChannel,
32
+ opts?: { ttlMs?: number; now?: number; path?: string },
33
+ ): boolean {
34
+ const ttlMs = opts?.ttlMs ?? LEASE_TTL_MS
35
+ const now = opts?.now ?? Date.now()
36
+ const path = opts?.path ?? LEASE_PATH
37
+ try {
38
+ let cur: Partial<SupervisorLease> | null = null
39
+ try {
40
+ cur = JSON.parse(readFileSync(path, "utf-8")) as Partial<SupervisorLease>
41
+ } catch {
42
+ /* 无租约或损坏 → 视为可夺 */
43
+ }
44
+ if (cur && typeof cur.until === "number" && cur.until > now) {
45
+ const mine = cur.channel === channel && cur.pid === process.pid
46
+ if (!mine) return false
47
+ }
48
+ writeFileSync(path, JSON.stringify({ channel, pid: process.pid, until: now + ttlMs }))
49
+ return true
50
+ } catch {
51
+ return true // fail-open:租约不可写不阻断监督
52
+ }
53
+ }
@@ -0,0 +1,68 @@
1
+ // @input: 纯数据(无依赖)
2
+ // @output: buildAmendPrompt/selectAmendEntry/lastUserMessageId/messageTextOf/resolveBusyMode/parseGoalState
3
+ // @pos: core - 回合修正域纯决策(2026-11-23 bridge 拆分切片:原散于 bridge.ts 顶部的
4
+ // 纯函数收敛于此,bridge 再导出保测试导入路径兼容——测试纪律「保持导入路径兼容」)
5
+ //
6
+ // 归属:undo/amend/steer 的判定与构造——无副作用、可单测、bridge 闭包函数只做编排。
7
+
8
+ /** 并入 prompt 构造:原 prompt + 补充指令块,模型读历史接着做。 */
9
+ export function buildAmendPrompt(original: string, amendment: string): string {
10
+ return `${original}\n\n【补充指令】${amendment.trim()}`
11
+ }
12
+
13
+ /** 并入目标选择:本用户该会话最新一条已落 promptId 且有原文的在途回合。 */
14
+ export function selectAmendEntry(
15
+ entries: Array<Pick<import("./inflight-journal.js").InflightEntry, "userId" | "sessionId" | "promptId" | "text" | "at" | "msgId" | "attemptId">>,
16
+ userId: string,
17
+ sessionId: string,
18
+ ): (typeof entries)[number] | undefined {
19
+ return entries
20
+ .filter((e) => e.userId === userId && e.sessionId === sessionId && e.promptId && e.text)
21
+ .sort((a, b) => b.at - a.at)[0]
22
+ }
23
+
24
+ /** 取会话消息列表中最后一条 user 消息的 id(回滚边界)。 */
25
+ export function lastUserMessageId(msgs: Array<{ id?: string; type?: string }>): string | null {
26
+ for (let i = msgs.length - 1; i >= 0; i--) {
27
+ if (msgs[i].type === "user" && msgs[i].id) return msgs[i].id as string
28
+ }
29
+ return null
30
+ }
31
+
32
+ /** 从消息体提取可读文本(user 消息 content 可能为字符串或 text 块数组)。 */
33
+ export function messageTextOf(m: { content?: unknown }): string {
34
+ const c = m.content
35
+ if (typeof c === "string") return c
36
+ if (Array.isArray(c)) {
37
+ return c.map((p) => (typeof p === "object" && p !== null && "text" in p ? String((p as { text?: unknown }).text ?? "") : "")).join("")
38
+ }
39
+ return ""
40
+ }
41
+
42
+ /** 忙时投递默认:owner 2026-11-23 裁定对齐官方(忙时 Enter steers)——steer 缺省;显式 queue 切回。 */
43
+ export function resolveBusyMode(envValue: string | undefined): "steer" | "queue" {
44
+ return envValue?.trim().toLowerCase() === "queue" ? "queue" : "steer"
45
+ }
46
+
47
+ /** goal 状态报文解析(纯函数):引擎把 goal 状态走 500 CommandExecutionError 通道返回,
48
+ * body 为 { _tag, command:"goal", message }——提取 message 供状态呈现与状态机通知。 */
49
+ export function parseGoalState(
50
+ raw: string,
51
+ ): { state: "active" | "paused" | "done" | "unknown"; message: string } | null {
52
+ const text = raw.trim()
53
+ const jsonText = text.startsWith("{") ? text : ""
54
+ if (!jsonText) return null
55
+ try {
56
+ const j = JSON.parse(jsonText) as { message?: string }
57
+ const msg = j.message ?? ""
58
+ if (!msg) return null
59
+ const head = msg.slice(0, 60)
60
+ const state = /goal active|^\s*active/i.test(head) ? "active"
61
+ : /paused/i.test(head) ? "paused"
62
+ : /\bdone\b|complete/i.test(head) ? "done"
63
+ : "unknown"
64
+ return { state, message: msg }
65
+ } catch {
66
+ return null
67
+ }
68
+ }
@@ -7,9 +7,11 @@
7
7
  // 锁文件 pid(单实例仲裁的唯一真相)+ process.kill(pid,0) + 心跳文件新鲜度。
8
8
  // 约定:锁 mtime 由 bot 每 10s 刷新(instance-lock);心跳文件由 bot 每 60s 刷新,
9
9
  // 且 2026-11-09 起「抢锁后立即写」,因此「进程活但心跳陈旧」= 真僵死,不是启动中。
10
- import { readFileSync, statSync, unlinkSync, writeFileSync } from "fs"
11
- import { join } from "path"
10
+ import { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from "fs"
11
+ import { dirname, join } from "path"
12
12
  import { homedir } from "os"
13
+ import { enforceLogBudget, logLimitsFromEnv, rotateLogIfNeeded } from "./log-rotate.js"
14
+ import { releaseLocksOfPid } from "./instance-lock.js"
13
15
 
14
16
  /** 心跳超过 5 分钟未刷新 = 事件循环僵死(与既有看门狗阈值一致) */
15
17
  export const HEARTBEAT_STALE_MS = 5 * 60_000
@@ -202,16 +204,80 @@ export function readEnvField(envPath: string, key: string): string | null {
202
204
  }
203
205
  }
204
206
 
205
- /** 追加一行巡检日志到 ~/.openqq/watchdog.log(数据目录,不是代码) */
207
+ /** bot 是否失能(无锁 / 持锁进程已死)——选主让贤的破格判据:bot 失能时任何通道都不许礼貌让贤。 */
208
+ export function isBotDown(health: BotHealth): boolean {
209
+ return health.lockPid === null || health.pidAlive === false
210
+ }
211
+
212
+ /** 追加一行巡检日志到统一日志 ~/.openqq/openqq.log(数据目录,不是代码;
213
+ * 2026-11-20 合并批:bot 与看门狗同文件,一眼归因全链路) */
206
214
  export function appendWatchdogLog(line: string): void {
207
215
  try {
208
- const dir = join(homedir(), ".openqq")
209
- writeFileSync(join(dir, "watchdog.log"), `${new Date().toISOString()} ${line}\n`, { flag: "a" })
216
+ const logPath = join(homedir(), ".openqq", "openqq.log")
217
+ const limits = logLimitsFromEnv()
218
+ if (existsSync(logPath) && statSync(logPath).size > limits.maxBytes) {
219
+ if (rotateLogIfNeeded(logPath, limits)) enforceLogBudget(logPath, limits)
220
+ }
221
+ writeFileSync(logPath, `${new Date().toISOString()} ${line}\n`, { flag: "a" })
210
222
  } catch {
211
223
  /* 日志失败不阻断巡检 */
212
224
  }
213
225
  }
214
226
 
227
+ /**
228
+ * 诛杀审计日志(DEF-20261120 墙 owner 当轮令「决策可审计」):独立文件 ~/.openqq/kills.log。
229
+ *
230
+ * 设计判据(审计三问)——每条诛杀记录必须可回答:
231
+ * ①判据是什么(为何判死:心跳陈旧 N 分钟/锁死/进程退出,附当时健康度快照)
232
+ * ②动作是什么(杀谁:pid;怎么杀:TERM→KILL 升级链;结果:确认死亡/无法终止)
233
+ * ③后果是什么(拉起了谁:新 pid;强度账现状:窗口内第几次)
234
+ *
235
+ * 与统一日志(openqq.log)的分工:openqq.log=全链路时间线(bot 输出+巡检混排,事后按时间归因);
236
+ * kills.log=诛杀决策专线(只有杀戮级动作,事后审计免捞沙)。两处都写不冗余——
237
+ * 审计场景下 openqq.log 会被 bot 高频输出冲刷稀释(11-20 实证:30 分钟卡死现场被
238
+ * 后续日志淹没,诛杀归因只能靠 supervisor 片段倒推),kills.log 保证决策记录永不被稀释。
239
+ */
240
+ export function appendKillLog(entry: KillAuditEntry, logPath = join(homedir(), ".openqq", "kills.log")): void {
241
+ try {
242
+ // 单行 JSONL:机器可解析(工具审计)+人类可读(字段名自释)。
243
+ // 轮转归 log-rotate 统一管辖(与 openqq.log 同口径 20MB×4 代/100MB 总预算;
244
+ // 量级=决策级事件每天数条,statSync 每次诛杀一次可忽略)。
245
+ writeFileSync(logPath, `${JSON.stringify(entry)}\n`, { flag: "a" })
246
+ const limits = logLimitsFromEnv()
247
+ if (existsSync(logPath) && statSync(logPath).size > limits.maxBytes) {
248
+ if (rotateLogIfNeeded(logPath, limits)) enforceLogBudget(logPath, limits)
249
+ }
250
+ } catch {
251
+ /* 审计日志失败不阻断监督主流程——监督本身即最后防线 */
252
+ }
253
+ }
254
+
255
+ /** 诛杀审计记录(字段=审计三问的机器形态;@ts 这里的时间一律 epoch ms) */
256
+ export interface KillAuditEntry {
257
+ /** 记录类型:decision=完整决策审计;liveness-check=拉起后存活确认 */
258
+ kind: "decision" | "liveness-check"
259
+ /** ①判据:触发动作的原始原因(如「心跳陈旧 30 分钟」) */
260
+ reason: string
261
+ /** ①判据附证:动刀时刻的健康度快照(判死依据的原始数据,审计不复算) */
262
+ health: {
263
+ lockPid: number | null
264
+ pidAlive: boolean | null
265
+ heartbeatAgeMs: number | null
266
+ lockAgeMs: number | null
267
+ }
268
+ /** ②动作:杀掉的 pid(null=本次为纯拉起/复核类记录) */
269
+ killedPid: number | null
270
+ /** ②动作:升级链终点(TERM 快速退出 / KILL 强杀 / 无法终止) */
271
+ killEscalation: "TERM" | "KILL" | "unterminated" | "n/a"
272
+ /** ③后果:拉起的新 pid */
273
+ spawnedPid: number | null
274
+ /** ③后果:强度账(窗口内重启次数/上限) */
275
+ restartIntensity: string
276
+ /** ③后果:拉起后存活复核结论(liveness-check 专用;decision 记录取证时为 null) */
277
+ livenessVerdict: string | null
278
+ at: number
279
+ }
280
+
215
281
  // ===== 监督层(2026-11-09 重构,替代裸 healOnce 的「无脑杀旧拉新」)=====
216
282
  // 设计对标(当日检索实证):
217
283
  // - Erlang OTP supervisor:maximum restart intensity——窗口内重启超限 → 放弃并上报,
@@ -310,6 +376,12 @@ export interface SuperviseDeps {
310
376
  claimPath?: string
311
377
  /** 监督动作审计日志路径(测试注入临时文件,避免污染真实 watchdog.log) */
312
378
  auditLogPath?: string
379
+ /**
380
+ * 拉起后存活确认(DEF-20261120 墙二次追击层)注入点:
381
+ * 缺省=生产行为(10s 后复核进程+锁,失败二次拉起);测试注入 false=整层跳过
382
+ *(fake spawn 返回假 pid、锁不落盘,生产复核在测试环境必判死,旧用例语义不变)。
383
+ */
384
+ livenessCheck?: boolean
313
385
  }
314
386
 
315
387
  export interface SuperviseResult {
@@ -419,9 +491,9 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
419
491
  return { action: "yield", detail: action.reason, killedPid: null, spawnedPid: null }
420
492
  }
421
493
  if (action.kind === "give-up") {
422
- const message = `⚠️ QQBot 看门狗已放弃:${action.restarts} 次重启/${Math.round(policy.windowMs / 60_000)} 分钟仍不健康。继续自动重启没有意义(同因反复死亡),请人工检查 %TEMP%\\opencode 下 bot.out.log 与 ~/.openqq/watchdog.log。`
494
+ const message = `⚠️ QQBot 看门狗已达重启强度上限:${action.restarts} 次/${Math.round(policy.windowMs / 60_000)} 分钟仍不健康(同因反复死亡)。降频重试继续——巡检不会停,强度窗口滑动后自动恢复,引擎/环境自愈即自行好转;若持续收到此告警,请检查 ~/.openqq/openqq.log(bot 与看门狗统一日志)。`
423
495
  audit(`give-up:${message}`)
424
- log(`[supervisor] give-up:${action.restarts} 次重启仍异常,停止循环并上报`)
496
+ log(`[supervisor] give-up:${action.restarts} 次重启仍异常,降频重试继续并上报(不再永动猛拉)`)
425
497
  // 告警去抖:30 分钟内只报一次(计划任务每 10 分钟一轮,防止轰炸)
426
498
  const lastAlert = state.alertedAt ?? 0
427
499
  if (now - lastAlert > 30 * 60_000) {
@@ -485,14 +557,30 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
485
557
  // design §3.9.1 监督矩阵行 2「无锁 / 锁 pid 已死 → 清锁 → 拉起」:
486
558
  // 死 bot 的锁文件由监督者在拉起前清理。否则刚死(锁 mtime<30s)时
487
559
  // 新实例 try 模式判锁新鲜而拒绝接管,本轮拉起空转,须再等一个巡检周期。
488
- // 仅当锁 pid 已死/无锁才删(grace-kill 路径已确认死亡,killedPid 非空)。
560
+ // 甲乙统一(2026-11-20 owner 批「修甲乙」):单进程多角色持多把锁——
561
+ // 杀进程即按 pid 清扫其持有的全部实例锁(锁即进程,调用方不再记角色名单;
562
+ // 多角色改造前只清单把,残留锁曾把 restart 的新实例弹飞——ceshi 僵尸锁
563
+ // 挡道 11-20 激活亲历)。已知锁路径兜底直删,兼容非 openqq-* 命名与
564
+ // pid 读不到的边角。
489
565
  try {
490
- if (killedPid !== null || health.lockPid === null || health.pidAlive === false) {
491
- unlinkSync(deps.paths.lockPath)
492
- audit(`清锁:${deps.paths.lockPath}(${action.reason})`)
566
+ const locksDir = dirname(deps.paths.lockPath)
567
+ let cleared: string[] = []
568
+ if (killedPid !== null) {
569
+ cleared = releaseLocksOfPid(killedPid, locksDir)
570
+ } else if (health.pidAlive === false && health.lockPid !== null) {
571
+ cleared = releaseLocksOfPid(health.lockPid, locksDir)
572
+ }
573
+ if (existsSync(deps.paths.lockPath)) {
574
+ try {
575
+ unlinkSync(deps.paths.lockPath)
576
+ if (!cleared.includes(deps.paths.lockPath)) cleared.push(deps.paths.lockPath)
577
+ } catch {
578
+ /* 锁不存在或删除失败:新实例 try 模式仍按 mtime 仲裁,不阻断拉起 */
579
+ }
493
580
  }
581
+ if (cleared.length > 0) audit(`清锁:${cleared.join("、")}(${action.reason})`)
494
582
  } catch {
495
- /* 锁不存在或删除失败:新实例 try 模式仍按 mtime 仲裁,不阻断拉起 */
583
+ /* 清锁失败不阻断拉起 */
496
584
  }
497
585
  const spawnedPid = deps.spawn()
498
586
  state.restartLog.push(Date.now())
@@ -502,11 +590,80 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
502
590
  } catch {
503
591
  log("[supervisor] 强度账落盘失败(不影响本次拉起)")
504
592
  }
505
- const detail = `${action.reason};${killedPid ? `已优雅停 pid=${killedPid};` : ""}已拉起 pid=${spawnedPid}`
593
+
594
+ // ===== 拉起后存活确认(DEF-20261120 墙二次追击层)=====
595
+ // 背景(2026-11-20 修订时更正注记):立项时引用的「11-20 15:17 主杀后拉起 7001
596
+ // 秒死」实系 lock-sweep 测试泄漏的假审计行(假 pid 7001,已在测试补 auditLogPath
597
+ // 隔离后根治)——该时刻真实 bot 存活。本层保留立项,因为「拉起后秒死」这一失败类
598
+ // 当日真实存在(早晨 8ms 速死群,根因未钉、仪器已埋):监督者要等下轮巡检
599
+ //(计划任务 3min/常驻 10min)才能再拉,期间 bot 继续失能;若死因未消(dist
600
+ // 混合态等),将进入「杀-拉-死-等-杀」的慢循环,每轮空转一个巡检周期直至 give-up。
601
+ // 修复:拉起后立即做 10s 存活确认(进程在 + 锁建立),失败=立刻二次拉起(仅一次,
602
+ // 防递归爆炸——二次拉起交由下轮巡检接力,与强度账协同防永动)。
603
+ // 强度账语义不变:本函数每进场只记 1 次重启(上方 restartLog.push),存活确认
604
+ // 的二次拉起不另记账——它是「本次重启的完整性收尾」而非新重启。
605
+ // 测试注入:livenessCheck=false 跳过整层(fake 环境判死恒真)。
606
+ let livenessVerdict = "alive"
607
+ let respawnPid: number | null = null
608
+ if (deps.livenessCheck !== false) {
609
+ const graceWaitMs = 10_000
610
+ await sleep(graceWaitMs)
611
+ const liveness = readBotHealth(deps.paths, Date.now())
612
+ if (!isPidAlive(spawnedPid) || liveness.lockPid === null) {
613
+ // 拉起失败两种形态:进程即死(spawn 竞态/依赖缺失)或进程在但 10s 内锁未建立
614
+ //(启动路径卡死——等价于「生而无魂」)。先清残留锁再二次拉起,防 try 锁挡道。
615
+ livenessVerdict = `dead-after-spawn(10s 复核:进程${isPidAlive(spawnedPid) ? "在但锁未建立" : "已退出"})`
616
+ audit(`二次追击:拉起 pid=${spawnedPid} 失败(${livenessVerdict}),立即重拉`)
617
+ try {
618
+ const locksDir2 = dirname(deps.paths.lockPath)
619
+ let cleared2: string[] = []
620
+ if (!isPidAlive(spawnedPid) && existsSync(deps.paths.lockPath)) {
621
+ cleared2 = releaseLocksOfPid(spawnedPid, locksDir2)
622
+ }
623
+ if (existsSync(deps.paths.lockPath)) {
624
+ try {
625
+ unlinkSync(deps.paths.lockPath)
626
+ if (!cleared2.includes(deps.paths.lockPath)) cleared2.push(deps.paths.lockPath)
627
+ } catch { /* mtime 仲裁兜底 */ }
628
+ }
629
+ if (cleared2.length > 0) audit(`清锁:${cleared2.join("、")}(二次追击前清场)`)
630
+ } catch { /* 清锁失败不阻断二次拉起 */ }
631
+ respawnPid = deps.spawn()
632
+ // 二次拉起同样确认(但不再追击——三次交下轮巡检,防递归)
633
+ await sleep(graceWaitMs)
634
+ const liveness2 = readBotHealth(deps.paths, Date.now())
635
+ if (!isPidAlive(respawnPid) || liveness2.lockPid === null) {
636
+ livenessVerdict += `;二次拉起 pid=${respawnPid} 仍失败——交下轮巡检接力(强度账 ${state.restartLog.length}/${policy.maxRestarts})`
637
+ } else {
638
+ livenessVerdict += `;二次拉起 pid=${respawnPid} 成功`
639
+ }
640
+ }
641
+ }
642
+ // 诛杀审计(决策可审计三问全要素):杀戮级动作落 kills.log 专线
643
+ if (killedPid !== null || livenessVerdict !== "alive") {
644
+ appendKillLog({
645
+ kind: "decision",
646
+ reason: action.reason,
647
+ health: {
648
+ lockPid: health.lockPid,
649
+ pidAlive: health.pidAlive,
650
+ heartbeatAgeMs: health.heartbeatAgeMs,
651
+ lockAgeMs: health.lockAgeMs,
652
+ },
653
+ killedPid,
654
+ killEscalation: killedPid !== null ? "TERM" : "n/a",
655
+ spawnedPid: respawnPid ?? spawnedPid,
656
+ restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
657
+ livenessVerdict: livenessVerdict !== "alive" ? livenessVerdict : "alive",
658
+ at: Date.now(),
659
+ })
660
+ }
661
+
662
+ const detail = `${action.reason};${killedPid ? `已优雅停 pid=${killedPid};` : ""}已拉起 pid=${respawnPid ?? spawnedPid}${livenessVerdict !== "alive" ? `;${livenessVerdict}` : ""}`
506
663
  // 审计分家(2026-11-09 加固红线):「主动杀」与「验尸拉新」必须在日志里一眼可辨——
507
664
  // 历史上两者同文案导致无声死亡无法归因(2026-11-09 他杀排查实证:审计缺陷遮蔽真凶)。
508
665
  audit(killedPid ? `主动杀:${detail}` : `验尸拉新:${detail}`)
509
- return { action: "restart", detail, killedPid, spawnedPid }
666
+ return { action: "restart", detail, killedPid, spawnedPid: respawnPid ?? spawnedPid }
510
667
  } finally {
511
668
  release()
512
669
  }