@shgroup/dsh-serenity-hooks 1.137.6 → 1.137.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/dsh.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-serenity-hooks",
3
- "version": "1.137.6",
3
+ "version": "1.137.8",
4
4
  "main": "lib/index.js",
5
5
  "description": "宁静号 ACC harness(Native Cordis 插件):给 DSH 装一个「AI 工作区」——14 个工具(container_fs/cognitive_trajectory/dashboard/container_git/msm/praxis/ontology/serenity-skill-creator/localstore/container_admin/browser_slot;另三个 im-bridge/diagram/reconstruct 按条件出现)+ 机械约束(安全模式/工作区围墙/密钥守卫)+ 认知轨迹日志与原地重建 + 网页登录入口/IM 桥/认知轨迹唤醒注册表 + 浏览器槽位管理(≤20 个独立 profile 的 Chrome 槽位,带占用归属与异常时向所属会话反向注入提醒)。轨迹声明 = 轨迹目录下的 trajectory.json(约束面 + 旧标识 uid + CRO 机器绑定 cro.host;旧名 trajectory-constraint.json / skiff.json 仍在读取族里);轨迹提示词 = 轨迹目录下的 PROMPT.md(一条轨迹「是谁、按什么章程工作」,所有轨迹通用,追加在容器层与质量层之后,不替换它们)。适配 DSH 0.1.7-rc.1 / 0.2.0-rc.1 / 0.2.1-rc.1(三档,deepseek-ai/deepseek-harness)。",
6
6
  "engines": {
@@ -0,0 +1,119 @@
1
+ /**
2
+ * browser/platform.ts — **macOS 差异的唯一归集处**(2026-11-18,owner 令「需要兼容 mac」)
3
+ *
4
+ * ## 为什么要有这个文件
5
+ *
6
+ * 槽位实现原本**整个建立在 `/proc` 之上**(2026-11-09 那次耗电事故逼出来的设计)。
7
+ * macOS 上这些**一个都不存在**:
8
+ *
9
+ * | 能力 | Linux 实现 | macOS |
10
+ * |---|---|---|
11
+ * | Chrome 可执行文件 | `/usr/bin/google-chrome` 等 6 条路径 | **一条都没有**(在 `.app/Contents/MacOS/` 下) |
12
+ * | 显示后端 | Wayland / X11 socket | **都不要**(走 Cocoa) |
13
+ * | 按 profile 认领进程 | 读 `/proc/<pid>/cmdline` | **无 `/proc`** |
14
+ * | 端口占用反查 | `/proc/net/tcp` + `/proc/<pid>/fd` | **无 `/proc`** |
15
+ * | CPU/RSS 采样 | `/proc/<pid>/stat` + `/status` | **无 `/proc`** |
16
+ *
17
+ * ## 🔴 设计约束:**Linux 实现零搬迁**
18
+ *
19
+ * `process.ts` 那 850 行里,Linux 与 macOS **只在四个入口分岔**,其余(启动参数、
20
+ * 杀进程三档、身份写盘、CDP 等待)**完全共用**。
21
+ * ⇒ 本模块**只提供 macOS 那四件事**,`process.ts` 在原函数第一行做一次分派:
22
+ *
23
+ * ```ts
24
+ * if (isMac()) return macFindPidsByProfile(profileDir) // ← 新增
25
+ * // ……原 Linux 实现,一行不改(本机测试跑的仍是它)
26
+ * ```
27
+ *
28
+ * ⛔ **刻意不做的两件事**(都付过代价):
29
+ * 1. **不把 Linux 改成 `ps`**。「零依赖、不调 `ps`」是用事故换来的纪律
30
+ * (`ps` 的输出格式随版本/平台变,而 `/proc` 的字段是内核契约)。
31
+ * 2. **不引入可变全局策略**。策略选择是**纯函数**(`isMac()` 读一次 `process.platform`),
32
+ * ⛔ 没有"注册/安装"那一层 —— 那会让测试之间互相污染(本仓已踩过此类)。
33
+ *
34
+ * ## macOS 侧为什么用子进程(如实登记,不粉饰)
35
+ *
36
+ * Darwin **没有**等价于 `/proc` 的内核接口:进程命令行要 `sysctl KERN_PROCARGS2`
37
+ * (需原生模块),端口反查只能 `lsof`。⇒ **这是全项目唯一引入子进程的一处**。
38
+ * 失败方向统一为**返回空集合**:不让"查不到"变成"槽位起不来"。
39
+ *
40
+ * ⚠️ **一处能力降级(不假装等同)**:`lsof` 对别人的端口可能因权限看不见 ⇒ 返回空,
41
+ * 而空在调用方等价于"没人占" ⇒ macOS 上这条判据**比 Linux 弱**。
42
+ * 真正的兜底是 CDP 探活那一步(连错实例会由 `webSocketDebuggerUrl` 判出来)。
43
+ */
44
+ /** 当前是否 macOS(**纯函数**,测试可注入) */
45
+ export declare function isMac(platform?: string): boolean;
46
+ /** 采样结果(与 `process.ts` 的 `ProcSample` 同形;独立声明以避免循环依赖) */
47
+ export interface MacProcSample {
48
+ alive: boolean;
49
+ cpuPct: number;
50
+ rssMb: number;
51
+ at: number;
52
+ /** 累计 CPU 时间(**秒 × 1000** 的整数,避免浮点漂移);Linux 侧同名字段是 ticks */
53
+ ticks?: number;
54
+ }
55
+ /**
56
+ * macOS 上 Chrome 的位置(按优先级)。
57
+ *
58
+ * 🔴 顺序有意义:① 系统级 `/Applications` → ② 用户级 `~/Applications`(无管理员权限时装这里)
59
+ * → ③ Canary/Beta/Dev(开发者机器可能只有这些)→ ④ Chromium。
60
+ *
61
+ * ⚠️ **刻意不列 Playwright/Puppeteer 下载的那份**(`~/.cache/ms-playwright/…`):
62
+ * 它随工具升级换路径,且**不是用户的浏览器** —— 拿它冒充"找到 Chrome"会让人误判
63
+ * (以为自己登着用户的浏览器,实际是一个空 profile 的自动化副本)。
64
+ */
65
+ export declare function macChromeCandidates(env?: Record<string, string | undefined>): string[];
66
+ /** 供错误回执印出"试过哪些路径"(`HOME` 无关的稳定版) */
67
+ export declare const MAC_CHROME_CANDIDATES: readonly string[];
68
+ /** macOS 上找 Chrome;找不到 ⇒ `null`(⛔ 不猜、不降级到 headless 假路径) */
69
+ export declare function macFindChrome(env?: Record<string, string | undefined>): string | null;
70
+ /**
71
+ * macOS 显示后端参数:**空**(Chrome 走 Cocoa,不需要 Wayland/X11 参数)。
72
+ *
73
+ * ⚠️ 刻意**不加 `--headless`**:槽位的价值在于"人能在屏幕上看见它",
74
+ * macOS 默认有窗口服务器 ⇒ 与 Linux 的 wayland/x11 分支**同语义**,
75
+ * ⛔ 不因为"没有 socket"就静默退化成 headless(那会改变取证条件)。
76
+ */
77
+ export declare function macDisplayDetail(): string;
78
+ /**
79
+ * 按 profile 目录找 Chrome pid。
80
+ *
81
+ * 🔴 判据与 Linux 侧**完全相同**:命令行里必须出现**本槽位专属的** `--user-data-dir` 路径。
82
+ * ⛔ 绝不用 `pgrep chrome` —— 那会连**用户自己的浏览器**一起杀掉(2026-11-09 事故差点犯的第二个错)。
83
+ *
84
+ * ⚠️ **`ps -ww` 的 `-ww` 不可省**:不加它 `ps` 按终端宽度**截断**命令行,
85
+ * 而 `--user-data-dir=<长路径>` 往往正好在被截掉的尾部 ⇒ 认领**静默失败**,
86
+ * 且表现与"进程真的没了"在读数上同形。
87
+ */
88
+ export declare function macFindPidsByProfile(profileDir: string): number[];
89
+ /**
90
+ * 某端口的监听者 pid(`lsof`)。
91
+ *
92
+ * ⚠️ 降级已在上方文件头登记:`lsof` 可能因权限看不见别人的端口 ⇒ 返回空。
93
+ * `lsof` 非 0 退出同时代表「没有匹配」与「没权限」,两者此处不可分。
94
+ */
95
+ export declare function macPortHolders(port: number): number[];
96
+ /**
97
+ * 解析 `ps -o time=` 的输出:`[[dd-]hh:]mm:ss[.cc]` → 秒。
98
+ * 例:`00:01.23` / `12:34` / `01:02:03` / `2-03:04:05`。
99
+ *
100
+ * 🔴 **解析不出 ⇒ `null`,⛔ 不返回 0**:返回 0 会让"读不到"伪装成"CPU 很低",
101
+ * 而后者正是 2026-11-09 事故里我们**没能及时发现**的那个读数。
102
+ */
103
+ export declare function parsePsTime(s: string): number | null;
104
+ /**
105
+ * 采样(`ps -o time=,rss=`)。
106
+ *
107
+ * 🔴 与 Linux 侧**同一口径**:`time` 是**累计** CPU 时间(不是瞬时占比)⇒
108
+ * 用两次采样的增量算占比。⛔ 不直接报 `%cpu`(那是"累计 ÷ 存活时长":
109
+ * 本仓事故里它给出 35.2%,而实际累计 12 小时 57 分 —— 判据量错了东西)。
110
+ */
111
+ export declare function macSample(pids: number[], prev: MacProcSample | null, now?: number): MacProcSample;
112
+ /**
113
+ * 该 pid 是否活着(`kill(pid, 0)` 语义)。
114
+ *
115
+ * 🔴 **不是"进程名存在"、也不是"目录存在"**(Linux 侧为此付过代价:僵尸进程会让
116
+ * `/proc/<pid>` 恒在,导致「杀掉了」被误判成「杀不动」)。
117
+ * `EPERM` = 进程存在但无权发信号 ⇒ **仍算活着**(与 Linux 侧同口径)。
118
+ */
119
+ export declare function macIsAlive(pid: number): boolean;
@@ -85,7 +85,39 @@ export declare function readSlotIdentity(n: number, homeDir?: string): SlotIdent
85
85
  export declare function writeSlotIdentity(ident: SlotIdentity, homeDir?: string): void;
86
86
  /** 释放时清掉身份(⛔ 保留 profile 本身 —— 登录态是槽位的资产) */
87
87
  export declare function clearSlotIdentity(n: number, homeDir?: string): void;
88
+ /**
89
+ * 找 Chrome。
90
+ *
91
+ * 🔴 **2026-11-18(owner 令「需要兼容 mac」)**:macOS 分派到 `platform.ts` ——
92
+ * 那边的路径在 `.app/Contents/MacOS/` 下,与上面六条**一条都不重合**
93
+ * (原实现在 mac 上必然"未找到 Chrome",而回执照样印 Linux 路径,把人指错方向)。
94
+ * ⚠️ Linux 分支**逐字未改**。
95
+ */
88
96
  export declare function findChrome(): string | null;
97
+ /**
98
+ * 按平台找 Chrome(**平台可注入**,理由见 {@link chromeCandidatesFor})。
99
+ *
100
+ * ⚠️ 这里的 `platform` 参数不只是为了测试:它是**让"mac 分支存在"这件事在 Linux 上可判**的唯一办法。
101
+ * 否则删掉 mac 分支,Linux 上的测试**一条都不会红**。
102
+ *
103
+ * @param exists 可选存在性探针(测试用;生产是 `existsSync`)
104
+ */
105
+ export declare function findChromeFor(platform: string, exists?: (p: string) => boolean, env?: Record<string, string | undefined>): string | null;
106
+ /** 错误回执要印出的候选路径(**按平台给**,⛔ 别在 mac 上印 Linux 路径) */
107
+ /**
108
+ * 按平台选候选路径清单(**纯函数,平台可注入**)。
109
+ *
110
+ * 🔴🔴 **为什么要抽成纯函数**(2026-11-18,我在这里踩了一次):
111
+ * 第一版写成 `isMac() ? MAC : LINUX`,然后写测试断言"Linux 上不得印 .app 路径"——
112
+ * **变异把 `isMac()` 删掉后测试照样全绿**,因为本机是 Linux,两条分支**结果相同**。
113
+ * ⇒ 这正是本仓反复踩的「判据没有判别力」:`process.platform` 在测试里改不了,
114
+ * 于是"平台分派"这件事**在 Linux 上永远读不出对错**。
115
+ * ⇒ 修法:把平台作为**参数**传进来,测试即可构造 `'darwin'` 走真分派。
116
+ * ⚠️ 生产调用点仍走默认参数(`process.platform`),行为零变化。
117
+ */
118
+ export declare function chromeCandidatesFor(platform?: string): readonly string[];
119
+ /** 生产包装(默认当前平台) */
120
+ export declare function chromeCandidatesForMessage(): readonly string[];
89
121
  /**
90
122
  * 给子进程挑一个**能真的打开**的显示后端。
91
123
  *
@@ -111,8 +143,8 @@ export declare function findChrome(): string | null;
111
143
  export interface DisplayChoice {
112
144
  args: string[];
113
145
  env: Record<string, string | undefined>;
114
- /** 选中的后端(诊断用) */
115
- backend: 'wayland' | 'x11' | 'headless';
146
+ /** 选中的后端(诊断用;macOS 上是 `cocoa`) */
147
+ backend: 'wayland' | 'x11' | 'cocoa' | 'headless';
116
148
  /** 人话说明(进日志/回执,别让下一个我重查一遍) */
117
149
  detail: string;
118
150
  }
@@ -134,7 +166,7 @@ export interface DisplayProbe {
134
166
  /** 路径是否存在(默认 `existsSync`;仅测试替换) */
135
167
  exists?: (p: string) => boolean;
136
168
  }
137
- export declare function resolveDisplay(env?: Record<string, string | undefined>, probe?: DisplayProbe): DisplayChoice;
169
+ export declare function resolveDisplay(env?: Record<string, string | undefined>, probe?: DisplayProbe, platform?: string): DisplayChoice;
138
170
  /**
139
171
  * 启动参数。
140
172
  *
package/lib/index.js CHANGED
@@ -13,7 +13,7 @@ import { i as hostAliveProbe, n as readSimpleSettings, r as registerSettingsSect
13
13
  import { a as readFeishuCredential, c as readWeixinSettings, d as weixinInboundDir, f as weixinSessionIdForTrajectory, i as matchWeixinRoute, n as extractWeixinText, r as hasVoiceItem, s as readWeixinCredential, t as extractWeixinMedia, u as sanitizeFileName$1 } from "./route-DcUo9alz.js";
14
14
  import { i as runImBridge, n as isImWiredTrajectory, r as registerImChannel, t as imChannelIds } from "./channels-Covd8vLQ.js";
15
15
  import { a as loadOpencodeSkill, c as summarizeHostContract, f as forgetNonCccToolVisibility, g as forgetToolVisibility, h as syncToolVisibility, i as listOpencodeSkillDirs, m as registerGuards, n as readDshVersion, o as compareSemver, r as setSafeMode, s as hostContractReport, t as getStatus } from "./status-BwfDsakn.js";
16
- import { a as ACK_PREFIX, c as eventToken, i as resolveSessionMdPath, l as DEFAULT_FAKE_INITIAL_MESSAGES, o as ASSISTANT_PREFIX, r as registerRebuildTurnHook, s as LOG_FILE_REL, t as buildRebuildAnchor, u as registerBootstrap } from "./rebuild-BjOT8IDK.js";
16
+ import { a as ACK_PREFIX, c as eventToken, i as resolveSessionMdPath, l as DEFAULT_FAKE_INITIAL_MESSAGES, o as ASSISTANT_PREFIX, r as registerRebuildTurnHook, s as LOG_FILE_REL, t as buildRebuildAnchor, u as registerBootstrap } from "./rebuild-CPB8k14k.js";
17
17
  import { i as subscriptionStats, n as registerTrajectorySubscriptions, r as subscriptionEval, t as defaultSubscriptionDeps } from "./subscriptions-DBoO0GSO.js";
18
18
  import { c as sendTextMessage, i as getUpdates, l as sendTyping, n as downloadMedia, o as markdownToPlainText, r as getConfig, s as sendFileMessage, t as TypingStatus, u as sniffImageExt } from "./ilink-CsZ-f64q.js";
19
19
  import { a as registerImAccountImpl, i as normalizeAccountChannel, n as getImAccountImpl, r as imAccountChannels } from "./accounts-BHQbakUh.js";
@@ -6668,7 +6668,7 @@ function createCognitiveTrajectoryTool(ctx) {
6668
6668
  };
6669
6669
  }
6670
6670
  } catch {}
6671
- const { queueRebuild } = await import("./rebuild-BjOT8IDK.js").then((n) => n.n);
6671
+ const { queueRebuild } = await import("./rebuild-CPB8k14k.js").then((n) => n.n);
6672
6672
  const result = await queueRebuild(ctx, {
6673
6673
  root,
6674
6674
  note: args.note,
@@ -18350,6 +18350,210 @@ function listLeases(ledger) {
18350
18350
  return Object.values(ledger.leases).sort((a, b) => a.slot - b.slot);
18351
18351
  }
18352
18352
  //#endregion
18353
+ //#region src/browser/platform.ts
18354
+ /** 当前是否 macOS(**纯函数**,测试可注入) */
18355
+ function isMac(platform = process.platform) {
18356
+ return platform === "darwin";
18357
+ }
18358
+ /**
18359
+ * macOS 上 Chrome 的位置(按优先级)。
18360
+ *
18361
+ * 🔴 顺序有意义:① 系统级 `/Applications` → ② 用户级 `~/Applications`(无管理员权限时装这里)
18362
+ * → ③ Canary/Beta/Dev(开发者机器可能只有这些)→ ④ Chromium。
18363
+ *
18364
+ * ⚠️ **刻意不列 Playwright/Puppeteer 下载的那份**(`~/.cache/ms-playwright/…`):
18365
+ * 它随工具升级换路径,且**不是用户的浏览器** —— 拿它冒充"找到 Chrome"会让人误判
18366
+ * (以为自己登着用户的浏览器,实际是一个空 profile 的自动化副本)。
18367
+ */
18368
+ function macChromeCandidates(env = process.env) {
18369
+ const home = env.HOME ?? "";
18370
+ return [
18371
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
18372
+ home !== "" ? join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome") : "",
18373
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
18374
+ "/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta",
18375
+ "/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev",
18376
+ "/Applications/Chromium.app/Contents/MacOS/Chromium"
18377
+ ].filter((p) => p !== "");
18378
+ }
18379
+ /** 供错误回执印出"试过哪些路径"(`HOME` 无关的稳定版) */
18380
+ const MAC_CHROME_CANDIDATES = macChromeCandidates({ HOME: "" });
18381
+ /**
18382
+ * macOS 显示后端参数:**空**(Chrome 走 Cocoa,不需要 Wayland/X11 参数)。
18383
+ *
18384
+ * ⚠️ 刻意**不加 `--headless`**:槽位的价值在于"人能在屏幕上看见它",
18385
+ * macOS 默认有窗口服务器 ⇒ 与 Linux 的 wayland/x11 分支**同语义**,
18386
+ * ⛔ 不因为"没有 socket"就静默退化成 headless(那会改变取证条件)。
18387
+ */
18388
+ function macDisplayDetail() {
18389
+ return "macOS 原生窗口(Cocoa;不需要 Wayland/X11 参数)";
18390
+ }
18391
+ /**
18392
+ * 按 profile 目录找 Chrome pid。
18393
+ *
18394
+ * 🔴 判据与 Linux 侧**完全相同**:命令行里必须出现**本槽位专属的** `--user-data-dir` 路径。
18395
+ * ⛔ 绝不用 `pgrep chrome` —— 那会连**用户自己的浏览器**一起杀掉(2026-11-09 事故差点犯的第二个错)。
18396
+ *
18397
+ * ⚠️ **`ps -ww` 的 `-ww` 不可省**:不加它 `ps` 按终端宽度**截断**命令行,
18398
+ * 而 `--user-data-dir=<长路径>` 往往正好在被截掉的尾部 ⇒ 认领**静默失败**,
18399
+ * 且表现与"进程真的没了"在读数上同形。
18400
+ */
18401
+ function macFindPidsByProfile(profileDir) {
18402
+ if (profileDir === "") return [];
18403
+ let out;
18404
+ try {
18405
+ out = execFileSync("ps", [
18406
+ "-ww",
18407
+ "-Ao",
18408
+ "pid=,command="
18409
+ ], {
18410
+ encoding: "utf8",
18411
+ stdio: [
18412
+ "ignore",
18413
+ "pipe",
18414
+ "ignore"
18415
+ ],
18416
+ timeout: 5e3,
18417
+ maxBuffer: 16777216
18418
+ });
18419
+ } catch {
18420
+ return [];
18421
+ }
18422
+ const pids = [];
18423
+ for (const line of out.split("\n")) {
18424
+ if (!line.includes(profileDir)) continue;
18425
+ const m = /^\s*(\d+)\s/.exec(line);
18426
+ if (!m) continue;
18427
+ const pid = Number(m[1]);
18428
+ if (pid === process.pid) continue;
18429
+ pids.push(pid);
18430
+ }
18431
+ return pids;
18432
+ }
18433
+ /**
18434
+ * 某端口的监听者 pid(`lsof`)。
18435
+ *
18436
+ * ⚠️ 降级已在上方文件头登记:`lsof` 可能因权限看不见别人的端口 ⇒ 返回空。
18437
+ * `lsof` 非 0 退出同时代表「没有匹配」与「没权限」,两者此处不可分。
18438
+ */
18439
+ function macPortHolders(port) {
18440
+ try {
18441
+ return execFileSync("lsof", [
18442
+ "-nP",
18443
+ `-iTCP:${port}`,
18444
+ "-sTCP:LISTEN",
18445
+ "-t"
18446
+ ], {
18447
+ encoding: "utf8",
18448
+ stdio: [
18449
+ "ignore",
18450
+ "pipe",
18451
+ "ignore"
18452
+ ],
18453
+ timeout: 3e3
18454
+ }).split("\n").map((l) => Number(l.trim())).filter((n) => Number.isInteger(n) && n > 0 && n !== process.pid);
18455
+ } catch {
18456
+ return [];
18457
+ }
18458
+ }
18459
+ /**
18460
+ * 解析 `ps -o time=` 的输出:`[[dd-]hh:]mm:ss[.cc]` → 秒。
18461
+ * 例:`00:01.23` / `12:34` / `01:02:03` / `2-03:04:05`。
18462
+ *
18463
+ * 🔴 **解析不出 ⇒ `null`,⛔ 不返回 0**:返回 0 会让"读不到"伪装成"CPU 很低",
18464
+ * 而后者正是 2026-11-09 事故里我们**没能及时发现**的那个读数。
18465
+ */
18466
+ function parsePsTime(s) {
18467
+ if (s === "") return null;
18468
+ const m = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)(?:\.(\d+))?$/.exec(s.trim());
18469
+ if (!m) return null;
18470
+ const days = m[1] !== void 0 ? Number(m[1]) : 0;
18471
+ const hours = m[2] !== void 0 ? Number(m[2]) : 0;
18472
+ const mins = Number(m[3]);
18473
+ const secs = Number(m[4]);
18474
+ const frac = m[5] !== void 0 ? Number(`0.${m[5]}`) : 0;
18475
+ if (![
18476
+ days,
18477
+ hours,
18478
+ mins,
18479
+ secs,
18480
+ frac
18481
+ ].every(Number.isFinite)) return null;
18482
+ return days * 86400 + hours * 3600 + mins * 60 + secs + frac;
18483
+ }
18484
+ /**
18485
+ * 采样(`ps -o time=,rss=`)。
18486
+ *
18487
+ * 🔴 与 Linux 侧**同一口径**:`time` 是**累计** CPU 时间(不是瞬时占比)⇒
18488
+ * 用两次采样的增量算占比。⛔ 不直接报 `%cpu`(那是"累计 ÷ 存活时长":
18489
+ * 本仓事故里它给出 35.2%,而实际累计 12 小时 57 分 —— 判据量错了东西)。
18490
+ */
18491
+ function macSample(pids, prev, now = Date.now()) {
18492
+ let cpuSec = 0;
18493
+ let rssKb = 0;
18494
+ let anyAlive = false;
18495
+ for (const pid of pids) {
18496
+ let out;
18497
+ try {
18498
+ out = execFileSync("ps", [
18499
+ "-o",
18500
+ "time=,rss=",
18501
+ "-p",
18502
+ String(pid)
18503
+ ], {
18504
+ encoding: "utf8",
18505
+ stdio: [
18506
+ "ignore",
18507
+ "pipe",
18508
+ "ignore"
18509
+ ],
18510
+ timeout: 2e3
18511
+ });
18512
+ } catch {
18513
+ continue;
18514
+ }
18515
+ const line = out.trim();
18516
+ if (line === "") continue;
18517
+ const parts = line.split(/\s+/);
18518
+ const sec = parsePsTime(parts[0] ?? "");
18519
+ if (sec === null) continue;
18520
+ cpuSec += sec;
18521
+ const rss = Number(parts[1] ?? "");
18522
+ if (Number.isFinite(rss)) rssKb += rss;
18523
+ anyAlive = true;
18524
+ }
18525
+ const ticks = Math.round(cpuSec * 1e3);
18526
+ let cpuPct = 0;
18527
+ if (prev && prev.alive && anyAlive && now > prev.at && prev.ticks !== void 0) {
18528
+ const dtSec = (now - prev.at) / 1e3;
18529
+ const dCpuSec = (ticks - prev.ticks) / 1e3;
18530
+ if (dtSec > 0 && dCpuSec >= 0) cpuPct = dCpuSec / dtSec * 100;
18531
+ }
18532
+ return {
18533
+ alive: anyAlive,
18534
+ cpuPct,
18535
+ rssMb: rssKb / 1024,
18536
+ at: now,
18537
+ ticks
18538
+ };
18539
+ }
18540
+ /**
18541
+ * 该 pid 是否活着(`kill(pid, 0)` 语义)。
18542
+ *
18543
+ * 🔴 **不是"进程名存在"、也不是"目录存在"**(Linux 侧为此付过代价:僵尸进程会让
18544
+ * `/proc/<pid>` 恒在,导致「杀掉了」被误判成「杀不动」)。
18545
+ * `EPERM` = 进程存在但无权发信号 ⇒ **仍算活着**(与 Linux 侧同口径)。
18546
+ */
18547
+ function macIsAlive(pid) {
18548
+ if (!Number.isInteger(pid) || pid <= 0) return false;
18549
+ try {
18550
+ process.kill(pid, 0);
18551
+ return true;
18552
+ } catch (e) {
18553
+ return e.code === "EPERM";
18554
+ }
18555
+ }
18556
+ //#endregion
18353
18557
  //#region src/browser/process.ts
18354
18558
  /**
18355
18559
  * browser/process.ts — 槽位 Chrome 进程的启动、探活、回收
@@ -18432,11 +18636,59 @@ const CHROME_CANDIDATES = [
18432
18636
  "/opt/google/chrome/chrome",
18433
18637
  "/snap/bin/chromium"
18434
18638
  ];
18639
+ /**
18640
+ * 找 Chrome。
18641
+ *
18642
+ * 🔴 **2026-11-18(owner 令「需要兼容 mac」)**:macOS 分派到 `platform.ts` ——
18643
+ * 那边的路径在 `.app/Contents/MacOS/` 下,与上面六条**一条都不重合**
18644
+ * (原实现在 mac 上必然"未找到 Chrome",而回执照样印 Linux 路径,把人指错方向)。
18645
+ * ⚠️ Linux 分支**逐字未改**。
18646
+ */
18435
18647
  function findChrome() {
18436
- for (const p of CHROME_CANDIDATES) if (existsSync(p)) return p;
18648
+ return findChromeFor(process.platform);
18649
+ }
18650
+ /**
18651
+ * 按平台找 Chrome(**平台可注入**,理由见 {@link chromeCandidatesFor})。
18652
+ *
18653
+ * ⚠️ 这里的 `platform` 参数不只是为了测试:它是**让"mac 分支存在"这件事在 Linux 上可判**的唯一办法。
18654
+ * 否则删掉 mac 分支,Linux 上的测试**一条都不会红**。
18655
+ *
18656
+ * @param exists 可选存在性探针(测试用;生产是 `existsSync`)
18657
+ */
18658
+ function findChromeFor(platform, exists = existsSync, env = process.env) {
18659
+ if (platform === "darwin") {
18660
+ for (const p of macChromeCandidates(env)) if (exists(p)) return p;
18661
+ return null;
18662
+ }
18663
+ for (const p of CHROME_CANDIDATES) if (exists(p)) return p;
18437
18664
  return null;
18438
18665
  }
18439
- function resolveDisplay(env = process.env, probe = {}) {
18666
+ /** 错误回执要印出的候选路径(**按平台给**,⛔ 别在 mac 上印 Linux 路径) */
18667
+ /**
18668
+ * 按平台选候选路径清单(**纯函数,平台可注入**)。
18669
+ *
18670
+ * 🔴🔴 **为什么要抽成纯函数**(2026-11-18,我在这里踩了一次):
18671
+ * 第一版写成 `isMac() ? MAC : LINUX`,然后写测试断言"Linux 上不得印 .app 路径"——
18672
+ * **变异把 `isMac()` 删掉后测试照样全绿**,因为本机是 Linux,两条分支**结果相同**。
18673
+ * ⇒ 这正是本仓反复踩的「判据没有判别力」:`process.platform` 在测试里改不了,
18674
+ * 于是"平台分派"这件事**在 Linux 上永远读不出对错**。
18675
+ * ⇒ 修法:把平台作为**参数**传进来,测试即可构造 `'darwin'` 走真分派。
18676
+ * ⚠️ 生产调用点仍走默认参数(`process.platform`),行为零变化。
18677
+ */
18678
+ function chromeCandidatesFor(platform = process.platform) {
18679
+ return platform === "darwin" ? MAC_CHROME_CANDIDATES : CHROME_CANDIDATES;
18680
+ }
18681
+ /** 生产包装(默认当前平台) */
18682
+ function chromeCandidatesForMessage() {
18683
+ return chromeCandidatesFor();
18684
+ }
18685
+ function resolveDisplay(env = process.env, probe = {}, platform = process.platform) {
18686
+ if (platform === "darwin") return {
18687
+ args: [],
18688
+ env: { ...env },
18689
+ backend: "cocoa",
18690
+ detail: macDisplayDetail()
18691
+ };
18440
18692
  const exists = probe.exists ?? existsSync;
18441
18693
  const uid = process.getuid?.() ?? 1e3;
18442
18694
  const runtimeDir = env.XDG_RUNTIME_DIR ?? `/run/user/${uid}`;
@@ -18533,7 +18785,7 @@ function launchSlot(n) {
18533
18785
  if (!chrome) return {
18534
18786
  ok: false,
18535
18787
  pid: 0,
18536
- detail: "未找到 Chrome/Chromium。候选路径:" + CHROME_CANDIDATES.join(" / ") + "\n ⇒ 装一个或用 `browser_slot` 的 --chrome 指定路径(该选项尚未实现)。"
18788
+ detail: "未找到 Chrome/Chromium(平台:" + (isMac() ? "macOS" : process.platform) + ")。候选路径:" + chromeCandidatesForMessage().join(" / ") + "\n ⇒ 装一个 Chrome,或把路径加入上面任一位置。"
18537
18789
  };
18538
18790
  const paths = slotPaths(n);
18539
18791
  if (!existsSync(paths.home)) mkdirSync(paths.home, { recursive: true });
@@ -18586,6 +18838,7 @@ function launchSlot(n) {
18586
18838
  * 本实现返回**全部**。
18587
18839
  */
18588
18840
  function portHolders(port) {
18841
+ if (isMac()) return macPortHolders(port);
18589
18842
  const inodes = /* @__PURE__ */ new Set();
18590
18843
  for (const f of ["/proc/net/tcp", "/proc/net/tcp6"]) {
18591
18844
  let text;
@@ -18652,6 +18905,7 @@ function require_readlink(p) {
18652
18905
  */
18653
18906
  function findPidsByProfile(profileDir) {
18654
18907
  if (!profileDir) return [];
18908
+ if (isMac()) return macFindPidsByProfile(profileDir);
18655
18909
  const pids = [];
18656
18910
  let names;
18657
18911
  try {
@@ -18680,6 +18934,7 @@ function findPidsByProfile(profileDir) {
18680
18934
  * 故 {@link sampleProcTree} 接受 `prev` 并返回本次样本供下次用。
18681
18935
  */
18682
18936
  function sampleProcTree(pids, prev, now = Date.now()) {
18937
+ if (isMac()) return macSample(pids, prev ?? null, now);
18683
18938
  let ticks = 0;
18684
18939
  let rssKb = 0;
18685
18940
  let anyAlive = false;
@@ -18748,6 +19003,7 @@ function killPidOutcome(pid, waitMs = 1500) {
18748
19003
  * 与 D253 同族:一个恒真的读数(`existsSync` 对僵尸为 true)会让相邻的两档同形。
18749
19004
  */
18750
19005
  function pidIsAlive(pid) {
19006
+ if (isMac()) return macIsAlive(pid);
18751
19007
  try {
18752
19008
  const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
18753
19009
  const state = stat.slice(stat.lastIndexOf(")") + 2).charAt(0);
@@ -592,29 +592,45 @@ function listFrozen(dir) {
592
592
  return names.filter((n) => n.startsWith("LOG-") && n.endsWith(".md")).sort();
593
593
  }
594
594
  /**
595
- * 从一份 LOG 正文里抽出 `## Handover note` 整节(含标题,到下一个同级或更高级标题为止)。
595
+ * 抽出**全部** `## Handover note` 节(保持原序)。
596
596
  *
597
- * 🔴 **为什么不抽就轮转 = 交接断开**:轮转把整份 `LOG.md` `mv` 成冻结代,新代是空白的。
598
- * 若在办状态写在旧代里,新会话读新代 ⇒ **读不到** ⇒ 交接失败,且**没有任何报错**。
599
- * 这与"便签必须被交接后的会话完整读到"是同一条判据(2026-11-16 owner 裁定)。
597
+ * 🔴🔴 **2026-11-17 真机缺陷(管家报「74 秒连出 7 代,手写交接详节从 gen 6 起整段消失」)**:
600
598
  *
601
- * @returns 该节全文(含标题、去掉尾部空行);没有该节 ⇒ `null`
599
+ * 旧实现是 `lines.findIndex(...)` —— **只取第一条**。而真实文件里出现过**两个**交接节:
600
+ * 模板短节在前(由上一次轮转搬运而来)、人写详节在后(本轮真正想交代的内容)。
601
+ * ⇒ 搬运只取第一条 ⇒ **人写的那一节被静默丢弃**,而它恰好是**模板没覆盖、只有人写得出来**的增量
602
+ * (该现场丢的是四条「别重做」+一条容器级发现)。
603
+ *
604
+ * ⚠️ **为什么当时没有报错**:轮转的 `verified` 只校验**字节数**(rename 搬全了没有),
605
+ * **从不校验"该搬的搬全了没有"**。⇒ 这是「判据量错了对象」的形态(D252 同族)。
606
+ *
607
+ * ⇒ 判据:**搬运必须取全部,不允许"取第一条就够了"**。多节并存本身合法
608
+ * (人可能续写、模板可能先占位),所以正确做法是**全搬**,不是"规定只能有一个"。
602
609
  */
603
- function extractHandoverNote(text) {
610
+ function extractAllHandoverNotes(text) {
604
611
  const lines = text.split("\n");
605
- const head = lines.findIndex((l) => l.trim() === HANDOVER_NOTE_HEADING);
606
- if (head < 0) return null;
607
- let end = lines.length;
608
- for (let i = head + 1; i < lines.length; i++) {
609
- const t = lines[i].trim();
610
- if (t.startsWith("## ") || t.startsWith("# ")) {
611
- end = i;
612
- break;
612
+ const out = [];
613
+ let i = 0;
614
+ while (i < lines.length) {
615
+ if (lines[i].trim() !== "## Handover note") {
616
+ i++;
617
+ continue;
618
+ }
619
+ const head = i;
620
+ let end = lines.length;
621
+ for (let j = head + 1; j < lines.length; j++) {
622
+ const t = lines[j].trim();
623
+ if (t.startsWith("## ") || t.startsWith("# ")) {
624
+ end = j;
625
+ break;
626
+ }
613
627
  }
628
+ const section = lines.slice(head, end);
629
+ while (section.length > 0 && section[section.length - 1].trim() === "") section.pop();
630
+ out.push(section.join("\n"));
631
+ i = end;
614
632
  }
615
- const section = lines.slice(head, end);
616
- while (section.length > 0 && section[section.length - 1].trim() === "") section.pop();
617
- return section.join("\n");
633
+ return out;
618
634
  }
619
635
  /**
620
636
  * 生成新一代 `LOG.md` 的出生头。
@@ -682,8 +698,8 @@ function rotateCarrierLog(trajectoryDir, now = /* @__PURE__ */ new Date()) {
682
698
  const verified = existsSync(dst) && statSync(dst).size === bytesBefore;
683
699
  if (!existsSync(live)) {
684
700
  let header = birthHeader(listFrozen(dir).length + 1, now, target);
685
- const note = extractHandoverNote(readFileSync(dst, "utf-8"));
686
- if (note !== null) header += `${note}\n\n`;
701
+ const notes = extractAllHandoverNotes(readFileSync(dst, "utf-8"));
702
+ if (notes.length > 0) header += `${notes.join("\n\n")}\n\n`;
687
703
  writeFileSync(live, header, "utf-8");
688
704
  }
689
705
  return {
@@ -819,7 +835,8 @@ let diagState = {
819
835
  queueCount: 0,
820
836
  rebuiltCount: 0,
821
837
  droppedCount: 0,
822
- failedCount: 0
838
+ failedCount: 0,
839
+ supersededCount: 0
823
840
  };
824
841
  function writeRebuildDiag(root, entry) {
825
842
  try {
@@ -831,6 +848,7 @@ function writeRebuildDiag(root, entry) {
831
848
  if (entry.event === "rebuilt") s.rebuiltCount += 1;
832
849
  if (entry.event === "ttl-dropped") s.droppedCount += 1;
833
850
  if (entry.event === "failed") s.failedCount += 1;
851
+ if (entry.event === "superseded") s.supersededCount += 1;
834
852
  s.lastTs = isoLocal();
835
853
  s.lastSessionId = entry.sessionId;
836
854
  s.lastEvent = entry.event;
@@ -860,15 +878,11 @@ async function queueRebuild(ctx, opts) {
860
878
  note: "rebuild queued"
861
879
  };
862
880
  appendBound(session, "rebuild", boundRec);
863
- try {
864
- const rot = rotateCarrierLog(dirname(mdPath));
865
- if (rot.rotated) {
866
- if (!rot.verified) console.warn(`[serenity-hooks] ⚠️ LOG 轮转回读校验失败:${rot.frozenAs} 的字节数不等于轮转前的 ${rot.bytesBefore} B。 rebuild 照常进行;请人工核对 LOG/ 目录。`);
867
- else console.log(`[serenity-hooks] ✓ LOG 轮转:${rot.bytesBefore} B → LOG/${rot.frozenAs}(回读校验通过)` + (rot.renamedFrom !== null ? `;原定名 ${rot.renamedFrom} 已存在 ⇒ 改名避让(⛔ 未覆盖)` : ""));
868
- }
869
- } catch (e) {
870
- console.warn(`[serenity-hooks] ⚠️ LOG 轮转未执行(${e.message})—— rebuild 不受影响`);
871
- }
881
+ if (pendingRebuilds.has(dshSessionId)) writeRebuildDiag(root, {
882
+ sessionId: dshSessionId,
883
+ event: "superseded",
884
+ detail: "same session queued again before turn end — the earlier queue entry was REPLACED (its rebuild will never run; with LOG rotation this used to cost one whole generation per replacement)"
885
+ });
872
886
  pendingRebuilds.set(dshSessionId, {
873
887
  anchor,
874
888
  summary,
@@ -977,6 +991,33 @@ function performRebuild(session, pending, meter) {
977
991
  }
978
992
  const REBUILD_ANCHOR_SOURCE = { kind: "user" };
979
993
  /**
994
+ * 交接**确实发生之后**的 LOG 轮转(2026-11-17 从 `queueRebuild` 迁来)。
995
+ *
996
+ * ## 为什么迁移(真机缺陷,管家报,逐字坐标)
997
+ * 旧实现挂在**排队**路径上 ⇒ 同一会话连续调 N 次 `rebuild` 会产生 N 次轮转,
998
+ * 而 `pendingRebuilds` 是覆盖写 ⇒ **只执行 1 次**。
999
+ * 实测现场:74 秒内连出 **7 代**(3,131 B → 26,739 B → 2,787 → 2,786 → 3,748 → 2,189 → 1,229 B)。
1000
+ * 每一次多余的轮转都在**切碎日志并搬运交接节**,把人的手写增量一代一代磨没。
1001
+ *
1002
+ * ## 失败方向(刻意保留原语义)
1003
+ * 轮转失败 **不** 回滚重建、**不** 让重建失败 —— rebuild 是"把上下文救回来"的动作,
1004
+ * 归档是次要的;让归档挡住重建 = 用秩序换可用性,方向反了。
1005
+ * 但失败**必须被说出来**(⛔ 不静默)。
1006
+ */
1007
+ function rotateLogAfterRebuild(mdPath) {
1008
+ try {
1009
+ const rot = rotateCarrierLog(dirname(mdPath));
1010
+ if (!rot.rotated) return;
1011
+ if (!rot.verified) {
1012
+ console.warn(`[serenity-hooks] ⚠️ LOG 轮转回读校验失败:${rot.frozenAs} 的字节数不等于轮转前的 ${rot.bytesBefore} B。 重建已完成;请人工核对 LOG/ 目录。`);
1013
+ return;
1014
+ }
1015
+ console.log(`[serenity-hooks] ✓ LOG 轮转:${rot.bytesBefore} B → LOG/${rot.frozenAs}(回读校验通过)` + (rot.renamedFrom !== null ? `;原定名 ${rot.renamedFrom} 已存在 ⇒ 改名避让(⛔ 未覆盖)` : ""));
1016
+ } catch (e) {
1017
+ console.warn(`[serenity-hooks] ⚠️ LOG 轮转未执行(${e.message})—— 重建不受影响`);
1018
+ }
1019
+ }
1020
+ /**
980
1021
  * 重建后重命名 dsh 会话标题(需求② S142 用户拍板:rebuild 后标题带新阶段概括)。
981
1022
  * 标题 = S###-YYYY-MM-DD-<summary>——S### 与日期从持久轨迹目录名派生(不信任 LLM),
982
1023
  * 概括来自 queueRebuild 的 summary 参数(服务端清洗截断)。
@@ -1031,6 +1072,7 @@ function registerRebuildTurnHook(ctx) {
1031
1072
  const tokenMeter = hostService(ctx, "tokenMeter");
1032
1073
  const meter = tokenMeter && typeof tokenMeter.estimateMessage === "function" ? { estimateMessage: (m) => tokenMeter.estimateMessage(m) } : void 0;
1033
1074
  if (performRebuild(agent.session, pending, meter)) {
1075
+ rotateLogAfterRebuild(pending.mdPath);
1034
1076
  renameAfterRebuild(ctx, agent, pending);
1035
1077
  deliver(makeInjection({
1036
1078
  origin: "acc",
@@ -86,6 +86,23 @@ export declare function isEffectivelyEmpty(text: string): boolean;
86
86
  * @returns 该节全文(含标题、去掉尾部空行);没有该节 ⇒ `null`
87
87
  */
88
88
  export declare function extractHandoverNote(text: string): string | null;
89
+ /**
90
+ * 抽出**全部** `## Handover note` 节(保持原序)。
91
+ *
92
+ * 🔴🔴 **2026-11-17 真机缺陷(管家报「74 秒连出 7 代,手写交接详节从 gen 6 起整段消失」)**:
93
+ *
94
+ * 旧实现是 `lines.findIndex(...)` —— **只取第一条**。而真实文件里出现过**两个**交接节:
95
+ * 模板短节在前(由上一次轮转搬运而来)、人写详节在后(本轮真正想交代的内容)。
96
+ * ⇒ 搬运只取第一条 ⇒ **人写的那一节被静默丢弃**,而它恰好是**模板没覆盖、只有人写得出来**的增量
97
+ * (该现场丢的是四条「别重做」+一条容器级发现)。
98
+ *
99
+ * ⚠️ **为什么当时没有报错**:轮转的 `verified` 只校验**字节数**(rename 搬全了没有),
100
+ * **从不校验"该搬的搬全了没有"**。⇒ 这是「判据量错了对象」的形态(D252 同族)。
101
+ *
102
+ * ⇒ 判据:**搬运必须取全部,不允许"取第一条就够了"**。多节并存本身合法
103
+ * (人可能续写、模板可能先占位),所以正确做法是**全搬**,不是"规定只能有一个"。
104
+ */
105
+ export declare function extractAllHandoverNotes(text: string): string[];
89
106
  /** 读一个轨迹目录的日志状态(只读,不改任何东西)。 */
90
107
  export declare function readCarrierLogState(trajectoryDir: string): CarrierLogState;
91
108
  /** 轮转结果(**回执只说明"我做了什么",不说明"效果达成了"**)。 */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shgroup/dsh-serenity-hooks",
3
- "version": "1.137.6",
3
+ "version": "1.137.8",
4
4
  "description": "宁静号 ACC harness(Native Cordis 插件)——给 DeepSeek Harness 装一个「AI 工作区」:14 个工具(container_fs/cognitive_trajectory/dashboard/container_git/msm/praxis/ontology/serenity-skill-creator/localstore/container_admin/browser_slot;另三个 im-bridge/diagram/reconstruct 按条件出现)+ 机械约束(安全模式/工作区围墙/密钥守卫/对外输出守卫)+ 认知轨迹日志与原地重建 + 网页登录入口/IM 桥/认知轨迹唤醒注册表 + 浏览器槽位管理(≤20 个独立 profile 的 Chrome 槽位,带占用归属与异常时向所属会话反向注入提醒)。轨迹声明 = 轨迹目录下的 trajectory.json(约束面 + 旧标识 uid + CRO 机器绑定 cro.host;旧名 trajectory-constraint.json / skiff.json 仍在读取族里);轨迹提示词 = 轨迹目录下的 PROMPT.md(一条轨迹「是谁、按什么章程工作」,所有轨迹通用,追加在容器层与质量层之后,不替换它们)。适配 DSH 0.1.7-rc.1 / 0.2.0-rc.1 / 0.2.1-rc.1(三档)。",
5
5
  "license": "MIT",
6
6
  "repository": {