openfeel 1.5.11 → 1.5.13

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.
@@ -1,11 +1,11 @@
1
1
  /**
2
- * 门禁自检状态(v1.5.11 D-126-04 / P0-4)
2
+ * 门禁自检状态(v1.5.11 D-126-04 / P0-4;v1.5.12 stage-127 / op-001 身份自证 + 自愈)
3
3
  *
4
4
  * 目的:让「门禁到底有没有生效、用哪个 cwd 判的、是不是旧进程/旧适配器」
5
5
  * 成为**可查证据**,而不是靠「工具没报错」猜。两处落点:
6
6
  *
7
7
  * 1. 工作区:`<project>/.openfeel/dev/guard-state.json`
8
- * 2. 全局:`os.tmpdir()/openfeel-guard/guard-state.json`
8
+ * 2. 全局:`os.tmpdir()/openfeel-guard/guard-state.json`(`OPENFEEL_GUARD_DIR` 可覆盖,测试隔离用)
9
9
  *
10
10
  * **cwd 解析失败时必须落全局路径**(`root = null`):绝不用 `process.cwd()`
11
11
  * (那会把宿主启动目录当成会话工作区,正是原 bug 的形态),也绝不静默丢弃——
@@ -14,13 +14,24 @@
14
14
  * 失败策略:写盘失败要**出声**(stderr),但不阻塞判定(best-effort)。
15
15
  * 读取顺序:工作区 → 全局(全局命中时 `source='global-fallback'`、`degraded=true`)。
16
16
  *
17
+ * **身份三键(stage-127 / op-001)**:`hostStartedAt` / `loaded_hash` / `pid` 只来自
18
+ * 「当前进程的注册事实」(`setGuardRuntimeIdentity`,`index.js` 启动时用当前 marker 设置),
19
+ * 或注册段的显式 patch;**旧工作区文件里的身份一律剥离、绝不继承**——那是重启后
20
+ * `stale` 恒 true 的根因(旧 `hostStartedAt` 覆盖新 seed)。
21
+ *
22
+ * **stale 只认 `pid` + `loaded_hash`**(`loaded_hash` 缺失也算不可信,`loaded-hash-missing`):
23
+ * `hostStartedAt` 仅作诊断字段(marker 每次 `apply()` 重写、多 profile/多宿主下时间比较必然误报且永不恢复)。
24
+ * HMAC 失配降级为 `hmacWarn:true`(可见、不门禁、不置 stale)。
25
+ *
17
26
  * @module openfeel-dsh/guard-state
18
27
  */
19
28
  import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
20
- import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
29
+ import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
21
30
  import { tmpdir } from 'node:os';
22
31
  import { dirname, join } from 'node:path';
23
32
 
33
+ import { defaultMarkerPath, readHostMarker } from './host-state.js';
34
+
24
35
  /** 文件 schema 版本(后续字段演进用)。 */
25
36
  export const GUARD_STATE_SCHEMA_VERSION = 1;
26
37
 
@@ -31,14 +42,72 @@ export const GUARD_STATE_SCHEMA_VERSION = 1;
31
42
  * (伪造 `pid` / `lastDecision` / `stale` 三键),让 `feel_status` 显示「门禁正常」。
32
43
  * 加一个只有**当前进程**知道的密钥签名后:
33
44
  * - 本进程写的状态 → 校验通过;
34
- * - 别的进程(含重启前的自己/被伪造的文件)写的状态 → 校验失败 → `stale: true`
35
- * (文案「门禁状态被篡改或来自旧进程」)。
45
+ * - 别的进程(含重启前的自己/被伪造的文件)写的状态 → 校验失败 → `hmacWarn: true`
46
+ * (**可见但不置 stale**:跨进程识别由 `pid` 覆盖,见 D2)。
36
47
  *
37
- * 代价:跨进程共享时必然 stale —— 这恰好是「状态是否由**正在服务的进程**写出」的
38
- * 正确语义,不是缺陷。
48
+ * 代价:跨进程共享时签名必然失配 —— 这恰好是「状态是否由**正在服务的进程**写出」的
49
+ * 证据之一,判别交给 `pid`;签名只作为**可见性**信号,不再门禁。
39
50
  */
40
51
  const STATE_HMAC_KEY = randomBytes(32);
41
52
 
53
+ /** 身份三键:只由当前进程/显式 patch 提供,旧工作区文件绝不继承(stage-127 / D1)。 */
54
+ const IDENTITY_KEYS = ['hostStartedAt', 'loaded_hash', 'pid'];
55
+
56
+ /** 当前进程的运行时身份(`setGuardRuntimeIdentity` 登记;只在内存)。 */
57
+ let runtimeIdentity = null;
58
+
59
+ /** 「本进程未登记身份」的 stderr 只警告一次。 */
60
+ let identityWarned = false;
61
+
62
+ /**
63
+ * 自动自愈的 `guard_repair` 审计:每宿主启动至多一条(防审计无界增长)。
64
+ *
65
+ * 取舍(stage-127 / op-005 P3-1):多 root 场景下只有**第一条**自动修复进审计,
66
+ * 后续自动修复仍写 state 但不追加审计;显式 `feel_verify health fix=true` 每次实际
67
+ * 变更各记一条。这样审计体积有界;需要逐 root 追溯时用显式入口。
68
+ */
69
+ let autoRepairAudited = false;
70
+
71
+ /** 自动自愈节流:同一 root 60s 内只检查一次;表带上限(LRU)防无界增长。 */
72
+ const SELF_HEAL_THROTTLE_MS = 60_000;
73
+ const SELF_HEAL_THROTTLE_LIMIT = 64;
74
+ const selfHealLastCheck = new Map();
75
+
76
+ /**
77
+ * 记录一次**成功完成**的检查(P3-2:异常路径不写节流,避免该 root 静默 60s)。
78
+ * Map 按插入序 LRU:最新在后,超过上限淘汰最旧。
79
+ * @param {string} root
80
+ * @param {number} at
81
+ */
82
+ function touchSelfHealThrottle(root, at) {
83
+ selfHealLastCheck.delete(root);
84
+ selfHealLastCheck.set(root, at);
85
+ while (selfHealLastCheck.size > SELF_HEAL_THROTTLE_LIMIT) {
86
+ const oldest = selfHealLastCheck.keys().next().value;
87
+ if (oldest === undefined) break;
88
+ selfHealLastCheck.delete(oldest);
89
+ }
90
+ }
91
+
92
+ /** marker 内容缓存:`{path, mtimeMs, size}` 未变时零内容读盘。 */
93
+ let markerCache = null;
94
+
95
+ /**
96
+ * 自愈读次数观测(op-005 P2-5 口径修正):
97
+ * - `stateReads`:读 guard-state(工作区;缺失时还会回退读全局);
98
+ * - `markerReads`:读宿主 marker(缓存命中时 0);
99
+ * - `writeReads`:修复写盘内部 `writeGuardState` 的两次读(global seed + workspace 继承)。
100
+ * 单次自动修复上限 = 1 + 1 + 2 = **4**;marker 缓存命中时 3。
101
+ */
102
+ const selfHealStats = { checks: 0, stateReads: 0, markerReads: 0, writeReads: 0 };
103
+
104
+ /**
105
+ * 自愈读次数归集器:`{phase: 'state'|'write', stateReads, writeReads}`。
106
+ * `readStateFile` 按当前 phase 记账(P2-5:写盘内部两次读也要计入,不能自证口径)。
107
+ * @type {{ phase: 'state'|'write', stateReads: number, writeReads: number } | null}
108
+ */
109
+ let readCapture = null;
110
+
42
111
  /** 递归稳定序列化(键排序),保证同一对象在写入/校验两侧得到同一字符串。 */
43
112
  function stableStringify(value) {
44
113
  if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
@@ -77,6 +146,33 @@ export function verifyGuardStateSignature(state) {
77
146
  }
78
147
  }
79
148
 
149
+ /**
150
+ * 登记当前进程的运行时身份(stage-127 / D1)。**只在内存**,绝不落盘。
151
+ *
152
+ * 缺项丢弃(`pid` 必须有限数字、其余必须非空字符串);非对象 → 清空。
153
+ * 重复调用以最后一次为准(测试用 `setGuardRuntimeIdentity(null)` 复位)。
154
+ *
155
+ * @param {{ pid?: number, hostStartedAt?: string, loaded_hash?: string } | null} identity
156
+ */
157
+ export function setGuardRuntimeIdentity(identity) {
158
+ if (identity === null || typeof identity !== 'object') {
159
+ runtimeIdentity = null;
160
+ return;
161
+ }
162
+ /** @type {Record<string, any>} */
163
+ const picked = {};
164
+ for (const key of IDENTITY_KEYS) {
165
+ const value = identity[key];
166
+ if (value === undefined || value === null) continue;
167
+ if (key === 'pid') {
168
+ if (Number.isFinite(value)) picked.pid = value;
169
+ continue;
170
+ }
171
+ if (typeof value === 'string' && value !== '') picked[key] = value;
172
+ }
173
+ runtimeIdentity = Object.keys(picked).length === 0 ? null : picked;
174
+ }
175
+
80
176
  /** 注册段字段(从全局文件播种到工作区文件时只带这些,避免把别的项目的 lastDecision 带进来)。 */
81
177
  const REGISTRATION_KEYS = [
82
178
  'schemaVersion',
@@ -98,8 +194,14 @@ export function guardStatePath(root) {
98
194
  return join(root, '.openfeel', 'dev', 'guard-state.json');
99
195
  }
100
196
 
101
- /** 全局落点目录(cwd 不可解析时用)。 @returns {string} */
197
+ /**
198
+ * 全局落点目录(cwd 不可解析时用)。
199
+ * `OPENFEEL_GUARD_DIR` 可覆盖(测试隔离用;非安全边界)。
200
+ * @returns {string}
201
+ */
102
202
  export function globalGuardDir() {
203
+ const override = process.env.OPENFEEL_GUARD_DIR;
204
+ if (typeof override === 'string' && override.trim() !== '') return override;
103
205
  return join(tmpdir(), 'openfeel-guard');
104
206
  }
105
207
 
@@ -119,12 +221,25 @@ export function globalGuardAuditPath() {
119
221
  return join(globalGuardDir(), 'guard-audit.jsonl');
120
222
  }
121
223
 
224
+ /**
225
+ * 工作区审计落点(与 guard.js 的落点同名同格式)。
226
+ * @param {string} root
227
+ * @returns {string}
228
+ */
229
+ export function guardAuditPath(root) {
230
+ return join(root, '.openfeel', 'log', 'guard-audit.jsonl');
231
+ }
232
+
122
233
  /**
123
234
  * 读一个 state 文件(缺失/损坏 → null)。
124
235
  * @param {string} file
125
236
  * @returns {Record<string, any> | null}
126
237
  */
127
238
  function readStateFile(file) {
239
+ if (readCapture !== null) {
240
+ if (readCapture.phase === 'write') readCapture.writeReads += 1;
241
+ else readCapture.stateReads += 1;
242
+ }
128
243
  try {
129
244
  const raw = JSON.parse(readFileSync(file, 'utf-8'));
130
245
  return typeof raw === 'object' && raw !== null ? raw : null;
@@ -153,8 +268,13 @@ export function readGuardState(root) {
153
268
  * 写入 guard-state(best-effort;失败出声、不阻塞)。
154
269
  *
155
270
  * `root = null` → 固定写全局路径(**绝不**用 `process.cwd()`)。
156
- * 工作区文件不存在时,用全局文件的注册段播种(registered/enforce/…),
157
- * 这样第一次判定写出的工作区文件同样带自证三键。
271
+ *
272
+ * **合并顺序(stage-127 / D1,不可颠倒)**:
273
+ * `seed`(全局注册段弱兜底,身份可能来自旧宿主 → 会 stale,属降级事实)
274
+ * → `inherited`(工作区**易变字段**:`lastDecision`/`cwd`/`cwdSource`/`resolvedAt` 等)
275
+ * → `runtimeIdentity`(当前进程注册事实,**覆盖 seed**)
276
+ * → `patch`(显式传入,优先级最高)。
277
+ * **`workspaceRaw` 的身份三键一律剥离**——旧工作区文件绝不提供身份。
158
278
  *
159
279
  * 失败时:stderr 打文件与原因;给了 `fallback`(at/tool/reason/cwdSource)时
160
280
  * 再打两行结构化的判定现场 —— 「最需要证据的时候」绝不静默(D-126-04)。
@@ -173,14 +293,27 @@ export function writeGuardState(root, patch, fallback = null) {
173
293
  const seed = globalRaw === null
174
294
  ? {}
175
295
  : Object.fromEntries(REGISTRATION_KEYS.filter((key) => globalRaw[key] !== undefined).map((key) => [key, globalRaw[key]]));
296
+ const inherited = workspaceRaw === null
297
+ ? {}
298
+ : Object.fromEntries(Object.entries(workspaceRaw).filter(([key]) => !IDENTITY_KEYS.includes(key)));
299
+ // 显式 patch 里 `undefined` 不参与覆盖(避免 `{hostStartedAt: undefined}` 意外抹掉身份)。
300
+ const patchClean = Object.fromEntries(Object.entries(patch ?? {}).filter(([, value]) => value !== undefined));
176
301
  const next = {
177
302
  ...seed,
178
- ...(workspaceRaw ?? {}),
179
- ...patch,
303
+ ...inherited,
304
+ ...(runtimeIdentity ?? {}),
305
+ ...patchClean,
180
306
  schemaVersion: GUARD_STATE_SCHEMA_VERSION,
181
- source: undefined,
182
307
  updatedAt: new Date().toISOString(),
183
308
  };
309
+ // 降级告警:合并后仍然没有任何身份事实 → 状态必然按不可信处理,必须出声(只一次)。
310
+ const identityPresent = Number.isFinite(next.pid)
311
+ && typeof next.hostStartedAt === 'string' && next.hostStartedAt !== ''
312
+ && typeof next.loaded_hash === 'string' && next.loaded_hash !== '';
313
+ if (!identityPresent && !identityWarned) {
314
+ identityWarned = true;
315
+ process.stderr.write('[guard] guard-identity-unavailable:本进程未登记身份且全局段缺失,状态将按不可信处理。\n');
316
+ }
184
317
  delete next.source;
185
318
  delete next.hmac;
186
319
  next.hmac = signState(next);
@@ -221,52 +354,62 @@ export function clearGuardState(root) {
221
354
  }
222
355
 
223
356
  /**
224
- * 可信度判定(op-005 / P1-6):返回不可信的原因,可信时返回 null。
357
+ * 可信度判定(op-005 / P1-6;stage-127 / D2 重排)。
225
358
  *
226
- * 顺序很重要 —— **先验签**:签名不过说明文件不是本进程写的(被 agent 重写、
227
- * 或来自旧进程),后面所有自证字段都不可信,没必要再看。
359
+ * 顺序很重要:
360
+ * 1. 缺 `pid` → `pid-missing`(fail-closed,状态可被整体重写,无证据不能算可信);
361
+ * 2. `pid` 与当前进程不符 → `pid`(状态来自旧进程);
362
+ * 3. 缺 `loaded_hash` → `loaded-hash-missing`(P2-4:无法证明代码版本;旧实现「空 hash 跳过
363
+ * 比对」会让「marker 不完整 → repair 写入空 hash」变成 `stale:false`,与告警相反);
364
+ * 4. `loaded_hash`(双方非空)不符 → `loaded-hash`(适配器文件已更新但宿主没重启);
365
+ * 5. 以上都过但验签失败 → `hmac` + `severity:'warn'`(**不 stale**,仅 `hmacWarn` 可见);
366
+ * 6. `hostStartedAt` **不参与判定**(P1-3:marker 每次 `apply()` 重写,时间比较必然误报)。
228
367
  *
229
368
  * @param {Record<string, any> | null} state
230
369
  * @param {Record<string, any> | null} hostMarker
231
370
  * @param {number} pid
232
- * @returns {{ reason: string, message?: string } | null}
371
+ * @returns {{ reason: string, severity: 'stale'|'warn', message?: string } | null}
233
372
  */
234
373
  export function guardStateDistrust(state, hostMarker = null, pid = process.pid) {
235
374
  if (state === null || typeof state !== 'object') return null;
236
- if (!verifyGuardStateSignature(state)) {
237
- return {
238
- reason: 'hmac',
239
- message: '门禁状态被篡改或来自旧进程(guard-state 签名校验失败):请重启宿主后确认 feel_status.guard.stale === false。',
240
- };
241
- }
242
375
  if (!Number.isFinite(state.pid)) {
243
376
  return {
244
377
  reason: 'pid-missing',
378
+ severity: 'stale',
245
379
  message: '门禁状态缺少 pid(无法证明由当前进程写入):请重启宿主后确认 feel_status.guard.stale === false。',
246
380
  };
247
381
  }
248
- if (state.pid !== pid) return { reason: 'pid' };
249
- if (hostMarker === null || typeof hostMarker !== 'object') return null;
382
+ if (state.pid !== pid) return { reason: 'pid', severity: 'stale' };
383
+ if (typeof state.loaded_hash !== 'string' || state.loaded_hash === '') {
384
+ return {
385
+ reason: 'loaded-hash-missing',
386
+ severity: 'stale',
387
+ message: '门禁状态缺少 loaded_hash(无法证明适配器版本):请重启宿主,或用 feel_verify action=health fix=true 修复。',
388
+ };
389
+ }
250
390
  if (
251
- typeof state.loaded_hash === 'string' && state.loaded_hash !== ''
391
+ hostMarker !== null && typeof hostMarker === 'object'
252
392
  && typeof hostMarker.loaded_hash === 'string' && hostMarker.loaded_hash !== ''
253
393
  && state.loaded_hash !== hostMarker.loaded_hash
254
- ) return { reason: 'loaded-hash' };
255
- const stateAt = Date.parse(state.hostStartedAt);
256
- const markerAt = Date.parse(hostMarker.started_at);
257
- if (Number.isFinite(stateAt) && Number.isFinite(markerAt) && stateAt < markerAt) return { reason: 'host-started-at' };
394
+ ) return { reason: 'loaded-hash', severity: 'stale' };
395
+ if (!verifyGuardStateSignature(state)) {
396
+ return {
397
+ reason: 'hmac',
398
+ severity: 'warn',
399
+ message: '门禁状态签名失配(可能来自旧进程或被重写):仅提示,不影响判定。如显示异常可完全重启宿主。',
400
+ };
401
+ }
258
402
  return null;
259
403
  }
260
404
 
261
405
  /**
262
- * stale 判定(P0-4 / op-005 P1-6):状态不可信 → true。
406
+ * stale 判定(P0-4 / op-005 P1-6 / stage-127 D2):只有 `severity:'stale'` 才算 stale。
263
407
  *
264
- * - **HMAC 校验失败** → 被篡改或来自旧进程(新增,防伪造);
265
- * - **缺 `pid`** → 不可信(旧实现「无证据不冤枉」,但状态文件可被整体重写,
266
- * 所以缺 pid 必须当 stale);
408
+ * - **缺 `pid`** → 不可信;
267
409
  * - `pid` 与当前进程不符 → 状态来自旧进程;
268
410
  * - `loaded_hash` 与标记不符 → 适配器文件已更新但宿主没重启;
269
- * - `hostStartedAt` 早于标记的 `started_at` → 状态来自更早的宿主启动。
411
+ * - **HMAC 失配不判 stale**(`hmacWarn` 可见);
412
+ * - **`hostStartedAt` 永不参与**(仅诊断字段)。
270
413
  *
271
414
  * @param {Record<string, any> | null} state
272
415
  * @param {Record<string, any> | null} hostMarker
@@ -274,16 +417,20 @@ export function guardStateDistrust(state, hostMarker = null, pid = process.pid)
274
417
  * @returns {boolean}
275
418
  */
276
419
  export function computeGuardStale(state, hostMarker, pid = process.pid) {
277
- return guardStateDistrust(state, hostMarker, pid) !== null;
420
+ const distrust = guardStateDistrust(state, hostMarker, pid);
421
+ return distrust !== null && distrust.severity === 'stale';
278
422
  }
279
423
 
280
424
  /**
281
425
  * 组装 `feel_status` / `feel_next` 的 `guard` 段。
282
426
  *
283
- * 两处都缺 → `{ registered:false, cwd:null, cwdSource:null, stale:false }`(计划口径:
284
- * 不再假装生效)。`live` 是调用方用**同一条 cwd 解析链**现算的结果,仅用于
427
+ * 两处都缺 → `{ registered:false, cwd:null, cwdSource:null, stale:false }`(恰 4 键;
428
+ * 计划口径:不再假装生效)。`live` 是调用方用**同一条 cwd 解析链**现算的结果,仅用于
285
429
  * 填补「还没有第一条判定」时的显示空缺(状态里已有 cwd 时以状态为准)。
286
430
  *
431
+ * 非空分支新增 `signature:'valid'|'mismatch'`;仅当三元组(pid/loaded_hash)通过且
432
+ * 验签失败时加 `hmacWarn:true`(不置 stale、不进 workflowGate)。
433
+ *
287
434
  * @param {{ root: string | null, hostMarker?: Record<string, any> | null, pid?: number, live?: { cwd: string | null, source: string, degraded: boolean } | null }} input
288
435
  * @returns {Record<string, any>}
289
436
  */
@@ -293,7 +440,8 @@ export function buildGuardSection({ root, hostMarker = null, pid = process.pid,
293
440
  return { registered: false, cwd: null, cwdSource: null, stale: false };
294
441
  }
295
442
  const distrust = guardStateDistrust(state, hostMarker, pid);
296
- const stale = distrust !== null;
443
+ const stale = distrust !== null && distrust.severity === 'stale';
444
+ const signatureValid = verifyGuardStateSignature(state);
297
445
  const section = {
298
446
  registered: state.registered === true,
299
447
  enforce: typeof state.enforce === 'string' ? state.enforce : undefined,
@@ -307,10 +455,13 @@ export function buildGuardSection({ root, hostMarker = null, pid = process.pid,
307
455
  pid: Number.isFinite(state.pid) ? state.pid : null,
308
456
  lastDecision: state.lastDecision ?? null,
309
457
  stale,
310
- // op-005 / P1-6:不可信的原因与文案(`hmac` = 被篡改或来自旧进程)。
458
+ signature: signatureValid ? 'valid' : 'mismatch',
459
+ // 不可信的原因与文案(只在 stale 时写;`hmac` 不再出现在 staleReason 枚举里)。
311
460
  ...(stale ? { staleReason: distrust.reason, staleMessage: distrust.message ?? null } : {}),
312
461
  source: state.source,
313
462
  };
463
+ // HMAC 失配:三元组通过才降级为可见告警(不置 stale、不门禁)。
464
+ if (!stale && !signatureValid) section.hmacWarn = true;
314
465
  // 只在「还没有任何判定」时用现场解析填补显示。**已有 lastDecision 时以状态为准**:
315
466
  // fail-closed 那次判定写的是 `cwd:null / unresolved`,如果这里用同类链再解析一次
316
467
  // (比如落到 process/config 环)就会把「已 fail-closed」粉饰成正常 —— 那正是
@@ -324,3 +475,248 @@ export function buildGuardSection({ root, hostMarker = null, pid = process.pid,
324
475
  }
325
476
  return section;
326
477
  }
478
+
479
+ /* ════════════════════════════════════════════════════════════════
480
+ * 受支持的自愈(stage-127 / §3-F)
481
+ *
482
+ * 为什么需要:跨进程 HMAC 与「旧工作区身份」在重启后必然让 state 不可信;
483
+ * 官方修复路径**不要求用户删文件**。修复只发生在适配器进程内(握有 marker +
484
+ * 当前 `process.pid`),身份**不接受任何工具参数**——agent 无法注入任意 pid/hash。
485
+ *
486
+ * 兼容性:`.openfeel/dev/guard-state.json` 是**受保护路径**(针对 `write`/`edit`
487
+ * 等工具写),这里用适配器进程内的 `fs` 直写,不经过 guard,因此不存在自锁;
488
+ * 安全性由「身份只能来自 marker + 当前 pid」保证。
489
+ * ════════════════════════════════════════════════════════════════ */
490
+
491
+ /**
492
+ * 追加一行门禁审计(best-effort:写失败不阻断修复)。
493
+ * @param {string} root
494
+ * @param {Record<string, any>} record
495
+ * @returns {boolean}
496
+ */
497
+ function appendGuardAudit(root, record) {
498
+ try {
499
+ const file = guardAuditPath(root);
500
+ mkdirSync(dirname(file), { recursive: true });
501
+ writeFileSync(file, `${JSON.stringify(record)}\n`, { encoding: 'utf-8', flag: 'a' });
502
+ return true;
503
+ } catch {
504
+ return false;
505
+ }
506
+ }
507
+
508
+ /**
509
+ * 修复 guard-state 的身份(显式入口 `feel_verify action=health fix=true` 与自动自愈共用)。
510
+ *
511
+ * - `hostMarker` 为空/null → `{ ok:false, reason:'marker-missing' }`,**零写盘**;
512
+ * - `hostMarker` 可解析但**不完整**(缺 `started_at` 或 `loaded_hash` 为空)→
513
+ * `{ ok:false, reason:'marker-incomplete' }`,**零写盘**(P2-4:否则会把空 hash 写进 state,
514
+ * 让「无法证明版本」伪装成可信);
515
+ * - 新身份只来自 `marker` + **当前 `process.pid`**(不接受外部传入的身份值);
516
+ * - 若旧 state 三键已与新身份一致 → `{ ok:true, changed:false }`(幂等,不写盘、不审计);
517
+ * - 写盘借助 `writeGuardState` 的合并语义**保留** `lastDecision`/`cwd`/`cwdSource`;
518
+ * `state === null` 时补 `registered:true` / `cwd:root` / `cwdSource:'repair'`;
519
+ * - 追加 `guard-audit.jsonl`:`event:'guard_repair'`,含 old/new;自动自愈每宿主启动至多 1 条。
520
+ *
521
+ * @param {string} root
522
+ * @param {{ hostMarker?: Record<string, any> | null, auto?: boolean, actor?: string, tool?: string, state?: Record<string, any> | null }} [options]
523
+ * @returns {{ ok: boolean, changed?: boolean, reason?: string, old?: Record<string, any>, next?: Record<string, any>, audited?: boolean }}
524
+ */
525
+ export function repairGuardState(root, options = {}) {
526
+ if (typeof root !== 'string' || root === '') return { ok: false, reason: 'root-missing' };
527
+ const hostMarker = options.hostMarker ?? null;
528
+ if (hostMarker === null || typeof hostMarker !== 'object') return { ok: false, reason: 'marker-missing' };
529
+ // P2-4:marker 完整性校验(可解析 ≠ 可信任)。缺键/空 hash 一律拒绝修复,零写盘。
530
+ if (
531
+ typeof hostMarker.started_at !== 'string' || hostMarker.started_at === ''
532
+ || typeof hostMarker.loaded_hash !== 'string' || hostMarker.loaded_hash === ''
533
+ ) return { ok: false, reason: 'marker-incomplete' };
534
+ const auto = options.auto === true;
535
+ const pid = process.pid; // 身份只能来自当前宿主进程,绝不接受工具参数
536
+ const nextIdentity = {
537
+ pid,
538
+ hostStartedAt: hostMarker.started_at,
539
+ loaded_hash: hostMarker.loaded_hash,
540
+ };
541
+ // 自动自愈把已读的 state 传进来,避免重复读盘。
542
+ const state = options.state !== undefined ? options.state : readGuardState(root);
543
+ const old = {
544
+ pid: Number.isFinite(state?.pid) ? state.pid : null,
545
+ loaded_hash: typeof state?.loaded_hash === 'string' ? state.loaded_hash : null,
546
+ hostStartedAt: typeof state?.hostStartedAt === 'string' ? state.hostStartedAt : null,
547
+ };
548
+ const unchanged = state !== null && state.source === 'workspace'
549
+ && old.pid === nextIdentity.pid
550
+ && old.loaded_hash === nextIdentity.loaded_hash
551
+ && old.hostStartedAt === nextIdentity.hostStartedAt;
552
+ if (unchanged) return { ok: true, changed: false, old, next: nextIdentity };
553
+
554
+ const now = new Date().toISOString();
555
+ /** @type {Record<string, any>} */
556
+ const patch = {
557
+ ...nextIdentity,
558
+ repairedAt: now,
559
+ repairSource: auto ? 'self-heal' : 'feel_verify',
560
+ };
561
+ if (state === null) {
562
+ patch.registered = true;
563
+ patch.cwd = root;
564
+ patch.cwdSource = 'repair';
565
+ }
566
+ const written = writeGuardState(root, patch);
567
+ if (!written) return { ok: false, reason: 'write-failed', old, next: nextIdentity };
568
+
569
+ const record = {
570
+ time: now,
571
+ event: 'guard_repair',
572
+ decision: 'allow',
573
+ reason: 'guard-repair',
574
+ tool: typeof options.tool === 'string' && options.tool !== '' ? options.tool : 'feel_verify',
575
+ auto,
576
+ old,
577
+ new: { ...nextIdentity },
578
+ cwdSource: typeof state?.cwdSource === 'string' && state.cwdSource !== '' ? state.cwdSource : 'repair',
579
+ };
580
+ let audited = false;
581
+ if (!auto) {
582
+ audited = appendGuardAudit(root, record);
583
+ } else if (!autoRepairAudited) {
584
+ autoRepairAudited = true;
585
+ audited = appendGuardAudit(root, record);
586
+ }
587
+ return { ok: true, changed: true, old, next: nextIdentity, audited };
588
+ }
589
+
590
+ /**
591
+ * 读 marker(带 `{path, mtimeMs, size}` 缓存):未变化时零内容读盘。
592
+ * @returns {Record<string, any> | null}
593
+ */
594
+ function readMarkerCached() {
595
+ const path = defaultMarkerPath();
596
+ let stat = null;
597
+ try {
598
+ stat = statSync(path);
599
+ } catch {
600
+ markerCache = null;
601
+ return null;
602
+ }
603
+ if (
604
+ markerCache !== null
605
+ && markerCache.path === path
606
+ && markerCache.mtimeMs === stat.mtimeMs
607
+ && markerCache.size === stat.size
608
+ ) {
609
+ return markerCache.marker;
610
+ }
611
+ selfHealStats.markerReads += 1;
612
+ const marker = readHostMarker(path);
613
+ markerCache = { path, mtimeMs: stat.mtimeMs, size: stat.size, marker };
614
+ return marker;
615
+ }
616
+
617
+ /**
618
+ * 自动自愈(`target()` 每个 `feel_*` 公共入口调用一次)。
619
+ *
620
+ * 约束(少一条就会变成多宿主 ping-pong 写):
621
+ * - `OPENFEEL_GUARD_SELF_HEAL=off` 时直接返回(测试/逃生阀);
622
+ * - 同一 root **60s 内只检查一次**;**成功完成检查后**才记节流(异常不占用窗口,P3-2),
623
+ * 节流表上限 64(LRU);
624
+ * - marker 按 mtime+size 缓存,未变时零内容读盘;
625
+ * - **只对「`pid` 缺失 / `pid` 已死(ESRCH)」自动修**:
626
+ * - 活着的异 pid(`process.kill(pid,0)` 成功或抛 `EPERM`)→ 跳过(多宿主不互相覆盖);
627
+ * - **同 pid 的 `loaded_hash` 失配绝不自动修**(P2-3):那正是「适配器已更新但宿主没重启」
628
+ * 的信号,必须在展示前保留;交由完全重启或显式 `feel_verify action=health fix=true`;
629
+ * - 每次检查 ≤4 次同步小 JSON 读(state 1 + marker 0~1 + 修复写盘内部 2,见 `selfHealStats`);
630
+ * - 异常一律吞掉(best-effort,绝不阻断 `feel_*`),且不写节流时间戳。
631
+ *
632
+ * @param {string} root
633
+ * @returns {{ checked: boolean, healed?: boolean, reason: string, result?: Record<string, any> }}
634
+ */
635
+ export function maybeSelfHealGuardState(root) {
636
+ if (process.env.OPENFEEL_GUARD_SELF_HEAL === 'off') return { checked: false, reason: 'disabled' };
637
+ if (typeof root !== 'string' || root === '') return { checked: false, reason: 'no-root' };
638
+ const last = selfHealLastCheck.get(root);
639
+ if (last !== undefined && Date.now() - last < SELF_HEAL_THROTTLE_MS) return { checked: false, reason: 'throttled' };
640
+ selfHealStats.checks += 1;
641
+ const capture = { phase: /** @type {'state'|'write'} */ ('state'), stateReads: 0, writeReads: 0 };
642
+ readCapture = capture;
643
+ let outcome;
644
+ let failed = false;
645
+ try {
646
+ outcome = selfHealCheck(root);
647
+ } catch (error) {
648
+ failed = true;
649
+ outcome = { checked: true, healed: false, reason: error instanceof Error ? error.message : 'error' };
650
+ } finally {
651
+ selfHealStats.stateReads += capture.stateReads;
652
+ selfHealStats.writeReads += capture.writeReads;
653
+ readCapture = null;
654
+ }
655
+ // P3-2:只有检查正常完成才写节流;异常下一轮可立即重试,不让该 root 静默 60s。
656
+ if (!failed) touchSelfHealThrottle(root, Date.now());
657
+ return outcome;
658
+ }
659
+
660
+ /**
661
+ * 自动自愈的单次检查(不含节流/异常兜底;读次数由调用方的 `readCapture` 归集)。
662
+ *
663
+ * @param {string} root
664
+ * @returns {{ checked: boolean, healed?: boolean, reason: string, result?: Record<string, any> }}
665
+ */
666
+ function selfHealCheck(root) {
667
+ const state = readGuardState(root);
668
+ if (state === null || state.source !== 'workspace') return { checked: true, healed: false, reason: 'no-workspace-state' };
669
+ if (Number.isFinite(state.pid) && state.pid !== process.pid) {
670
+ let alive = true;
671
+ try {
672
+ process.kill(state.pid, 0);
673
+ } catch (error) {
674
+ alive = error?.code === 'EPERM';
675
+ }
676
+ // 活着的异 pid 不自动修:两个活宿主共享同一工程会互相覆盖(显式入口才修)。
677
+ if (alive) return { checked: true, healed: false, reason: 'foreign-pid-alive' };
678
+ }
679
+ const marker = readMarkerCached();
680
+ if (marker === null || typeof marker !== 'object') return { checked: true, healed: false, reason: 'marker-missing' };
681
+ if (Number.isFinite(state.pid) && state.pid === process.pid) {
682
+ // 同 pid:pid 已自证;loaded_hash 失配**不自动修**(P2-3:保留「宿主未重启」信号)。
683
+ if (
684
+ typeof marker.loaded_hash === 'string' && marker.loaded_hash !== ''
685
+ && state.loaded_hash === marker.loaded_hash
686
+ ) {
687
+ return { checked: true, healed: false, reason: 'trusted' };
688
+ }
689
+ return { checked: true, healed: false, reason: 'loaded-hash-mismatch' };
690
+ }
691
+ // 到这里只可能是「pid 缺失」或「pid 已死(ESRCH)」→ 允许自动修复。
692
+ if (readCapture !== null) readCapture.phase = 'write';
693
+ const result = repairGuardState(root, { hostMarker: marker, auto: true, state });
694
+ return {
695
+ checked: true,
696
+ healed: result.ok === true && result.changed === true,
697
+ reason: result.ok === true ? (result.changed === true ? 'repaired' : 'unchanged') : (result.reason ?? 'repair-failed'),
698
+ result,
699
+ };
700
+ }
701
+
702
+ /**
703
+ * 复位自愈的模块级状态(测试用:节流 / marker 缓存 / 审计上限 / 读计数)。
704
+ */
705
+ export function resetGuardSelfHealState() {
706
+ selfHealLastCheck.clear();
707
+ markerCache = null;
708
+ autoRepairAudited = false;
709
+ selfHealStats.checks = 0;
710
+ selfHealStats.stateReads = 0;
711
+ selfHealStats.markerReads = 0;
712
+ selfHealStats.writeReads = 0;
713
+ readCapture = null;
714
+ }
715
+
716
+ /**
717
+ * 读自愈读计数(op-005 P2-5:含写盘内部两次读,单次自动修复上限 4)。
718
+ * @returns {{ checks: number, stateReads: number, markerReads: number, writeReads: number }}
719
+ */
720
+ export function readGuardSelfHealStats() {
721
+ return { ...selfHealStats };
722
+ }
@@ -83,3 +83,52 @@ export function computeWorkflowGate(snapshot) {
83
83
  ],
84
84
  };
85
85
  }
86
+
87
+ /**
88
+ * 门禁标题(**单句、不带 `⚠ ` 前缀**)——`feel_status` / `feel_next` 两处共用,避免再次分叉。
89
+ *
90
+ * v1.5.12 / stage-127 §3-E:旧实现两个工具各自硬编码「⚠ 无活跃阶段:非只读任务先
91
+ * feel_status→建阶段。」,于是 `guard-stale` / `guard-inactive` / `guard-cwd-unresolved`
92
+ * 时标题与真实原因矛盾(门禁自身没生效,却在催建阶段)。
93
+ *
94
+ * 口径:
95
+ * - `no-active-stage` → 保留既有短句(仅此一条 reason 才允许出现「无活跃阶段」);
96
+ * - `guard-*` 三条 → **逐字使用 `gate.message`**(门禁原因文案;同一原因只说一次,
97
+ * 与 `guardWarnings` 的 `skipGateCovered` 配合,不重复堆两句);
98
+ * - 其它/未知 reason → 回落 `gate.message`;无 message 时空串(调用方据此不加标题)。
99
+ *
100
+ * @param {{ reason?: string|null, message?: string } | null | undefined} gate
101
+ * @returns {string}
102
+ */
103
+ export function workflowGateTitle(gate) {
104
+ if (gate === null || gate === undefined || typeof gate !== 'object') return '';
105
+ switch (gate.reason) {
106
+ case 'no-active-stage':
107
+ // 唯一允许出现「无活跃阶段」的 reason
108
+ return '无活跃阶段:非只读任务先 feel_status→建阶段。';
109
+ case 'guard-inactive':
110
+ case 'guard-cwd-unresolved':
111
+ case 'guard-stale':
112
+ // 与 gate.message 逐字一致:原因 + 修复动作全部取自单源,不在标题里另写一套
113
+ break;
114
+ default:
115
+ break;
116
+ }
117
+ return typeof gate.message === 'string' ? gate.message : '';
118
+ }
119
+
120
+ /**
121
+ * 一句话门禁告警(`⚠ ` 开头的完整标题;无告警时返回空串)。
122
+ *
123
+ * 两处调用点只做「拼到 summary 前面」,选择文案的逻辑只在 `workflowGateTitle` 一处。
124
+ *
125
+ * @param {{ workflowGate?: { required?: boolean, reason?: string|null, message?: string } } | null | undefined} snapshot
126
+ * @returns {string}
127
+ */
128
+ export function headlineWarning(snapshot) {
129
+ const gate = snapshot?.workflowGate;
130
+ if (gate === null || gate === undefined || typeof gate !== 'object' || gate.required !== true) return '';
131
+ const title = workflowGateTitle(gate);
132
+ if (title === '') return '';
133
+ return `⚠ ${title}`;
134
+ }