focus-guard 3.0.7 → 3.4.0

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 (161) hide show
  1. package/LICENSE +683 -21
  2. package/NOTICE +25 -0
  3. package/README.md +14 -9
  4. package/README.zh-CN.md +12 -9
  5. package/docs/AB-PROMPTS.md +123 -0
  6. package/docs/AB-SESSION.md +161 -0
  7. package/docs/ARCH-MAP.md +148 -0
  8. package/docs/BENCH-BASELINE.json +95 -0
  9. package/docs/BENCH.md +323 -0
  10. package/docs/GATE-INPUTS.json +10 -0
  11. package/docs/HANDOFF-2026-10-27.md +736 -0
  12. package/docs/HOOK-ORDERING.md +139 -0
  13. package/docs/LEGISLATION-LAW.md +4 -2
  14. package/docs/MCP-4.0-PLAN.md +184 -0
  15. package/docs/MEMORY-4.5-PLAN.md +415 -0
  16. package/docs/PROFILE-TUNING.md +147 -0
  17. package/docs/RATCHET.json +48 -0
  18. package/docs/RELEASE-POLICY.md +163 -0
  19. package/docs/RULES.md +95 -14
  20. package/docs/THREAT-MODEL.md +68 -0
  21. package/docs/TOOL-SCHEMA.json +6 -0
  22. package/docs/VERSION-PLAN.md +532 -0
  23. package/docs/WRITING-STYLE.md +109 -0
  24. package/docs/architecture-map.mermaid +186 -0
  25. package/docs/deepseek-pricing-audit.md +2 -0
  26. package/hooks/guard.mjs +92 -56
  27. package/package.json +34 -5
  28. package/skills/focus-thinking/SKILL.md +9 -7
  29. package/src/adapters/dsh/eligibility-gate.mjs +446 -23
  30. package/src/adapters/dsh/tool-kinds.mjs +81 -0
  31. package/src/core/approval.mjs +2 -8
  32. package/src/core/approvals.mjs +208 -0
  33. package/src/core/audit-writer.mjs +297 -0
  34. package/src/core/audit.mjs +46 -16
  35. package/src/core/backup.mjs +37 -11
  36. package/src/core/checkEligibility.mjs +7 -4
  37. package/src/core/constants.mjs +67 -22
  38. package/src/core/decisionEngine.mjs +12 -0
  39. package/src/core/env.mjs +147 -19
  40. package/src/core/grants.mjs +54 -13
  41. package/src/core/kpi.mjs +16 -0
  42. package/src/core/outputGate.mjs +77 -0
  43. package/src/core/patterns.mjs +129 -0
  44. package/src/core/prefixStability.mjs +143 -0
  45. package/src/core/profileLoader.mjs +40 -5
  46. package/src/core/progressPolicy.mjs +65 -0
  47. package/src/core/redlines.mjs +49 -5
  48. package/src/core/risk.mjs +94 -15
  49. package/src/core/schemaDrift.mjs +125 -0
  50. package/src/core/sessionScratch.mjs +147 -0
  51. package/src/core/stageGraph.mjs +104 -0
  52. package/src/core/staleCleanup.mjs +153 -0
  53. package/src/core/state.mjs +215 -81
  54. package/src/core/stopPolicy.mjs +97 -0
  55. package/src/core/tempPath.mjs +23 -0
  56. package/src/dsh/audit.mjs +168 -118
  57. package/src/dsh/compactionWatch/announce.mjs +117 -0
  58. package/src/dsh/compactionWatch.mjs +68 -153
  59. package/src/dsh/guard/authz.mjs +97 -0
  60. package/src/dsh/guard/evidence.mjs +308 -0
  61. package/src/dsh/guard/hardCheck.mjs +85 -0
  62. package/src/dsh/guard/redline.mjs +62 -0
  63. package/src/dsh/guard/risk.mjs +196 -0
  64. package/src/dsh/guard/runtime.mjs +162 -0
  65. package/src/dsh/guard/superpowers.mjs +70 -0
  66. package/src/dsh/guard/tooling.mjs +177 -0
  67. package/src/dsh/guard/volume.mjs +181 -0
  68. package/src/dsh/guard/wholeFile.mjs +109 -0
  69. package/src/dsh/heartbeat.mjs +76 -13
  70. package/src/dsh/hookOrder.mjs +101 -0
  71. package/src/dsh/index.js +247 -15
  72. package/src/dsh/pipeline.mjs +77 -854
  73. package/src/dsh/policy-audit.mjs +84 -0
  74. package/src/dsh/postProgress.mjs +400 -274
  75. package/src/dsh/preGuard.mjs +249 -228
  76. package/src/dsh/repeatGuard.mjs +98 -0
  77. package/src/dsh/seams/pre-step.mjs +186 -0
  78. package/src/dsh/seams/prompt-rules.mjs +59 -0
  79. package/src/dsh/seams/session-start.mjs +297 -0
  80. package/src/dsh/seams/shared.mjs +109 -0
  81. package/src/dsh/seams.mjs +95 -408
  82. package/src/dsh/search-hints.mjs +136 -0
  83. package/src/dsh/sessionScope.mjs +28 -0
  84. package/src/dsh/status.mjs +7 -0
  85. package/src/dsh/stopGuard.mjs +225 -164
  86. package/src/dsh/testRuntime.mjs +62 -0
  87. package/src/dsh/toolKindAudit.mjs +66 -0
  88. package/src/dsh/tools.mjs +81 -5
  89. package/src/dsh/traceMeta.mjs +125 -0
  90. package/src/dsh/value-gate.mjs +93 -0
  91. package/src/dsh/workspace.mjs +3 -143
  92. package/src/memory/index.mjs +15 -0
  93. package/src/memory/tags.mjs +30 -0
  94. package/src/memory/workspace.mjs +283 -0
  95. package/src/peak-cost.mjs +1 -1
  96. package/src/profiles/deepseek-flash.mjs +7 -1
  97. package/src/profiles/deepseek-pro.mjs +6 -1
  98. package/src/profiles/default.mjs +6 -1
  99. package/src/profiles/glm.mjs +6 -1
  100. package/src/profiles/gpt-astra.mjs +6 -1
  101. package/tools/bench-ab.mjs +240 -0
  102. package/tools/bench-cost.mjs +176 -0
  103. package/tools/brain-cosmic.mjs +43 -0
  104. package/tools/brain-view.html +853 -0
  105. package/tools/brain.mjs +317 -0
  106. package/tools/capture-fixtures.mjs +182 -0
  107. package/tools/case-audit.mjs +114 -0
  108. package/tools/collect-panel.mjs +218 -0
  109. package/tools/dead-export.mjs +60 -0
  110. package/tools/docs-lint.mjs +82 -0
  111. package/tools/env-fingerprint.mjs +126 -33
  112. package/tools/first-run-sweep.mjs +123 -0
  113. package/tools/focusguard.mjs +155 -0
  114. package/tools/gate-audit.mjs +140 -0
  115. package/tools/gate-inputs.mjs +115 -0
  116. package/tools/handoff.mjs +56 -0
  117. package/tools/health.mjs +182 -0
  118. package/tools/knowledge.mjs +118 -0
  119. package/tools/layering-audit.mjs +105 -0
  120. package/tools/lib/book-style.mjs +136 -0
  121. package/tools/lib/brain-core.mjs +342 -0
  122. package/tools/lib/brain-docs.mjs +293 -0
  123. package/tools/lib/brain-regions.mjs +169 -0
  124. package/tools/lib/brain-relate.mjs +235 -0
  125. package/tools/lib/brain-text.mjs +121 -0
  126. package/tools/lib/case-tool.mjs +186 -0
  127. package/tools/lib/docs-core.mjs +392 -0
  128. package/tools/lib/docs-version.mjs +66 -0
  129. package/tools/lib/envMap.mjs +31 -0
  130. package/tools/lib/health-core.mjs +94 -0
  131. package/tools/lib/import-graph.mjs +118 -0
  132. package/tools/lib/index-io.mjs +70 -0
  133. package/tools/lib/open.mjs +32 -0
  134. package/tools/lib/prefix-cost.mjs +143 -0
  135. package/tools/lib/ratchet.mjs +174 -0
  136. package/tools/lib/reach.mjs +28 -0
  137. package/tools/lib/sessionDump.mjs +80 -0
  138. package/tools/lib/source-text.mjs +112 -0
  139. package/tools/library-book.mjs +313 -0
  140. package/tools/library-build.mjs +50 -12
  141. package/tools/library-index.mjs +91 -0
  142. package/tools/lint.mjs +282 -0
  143. package/tools/log-audit.mjs +108 -0
  144. package/tools/manifest-sync.mjs +111 -0
  145. package/tools/memory-audit.mjs +67 -0
  146. package/tools/module-audit.mjs +56 -0
  147. package/tools/mutate.mjs +316 -0
  148. package/tools/prefix-audit.mjs +122 -0
  149. package/tools/prefix-drift.mjs +325 -0
  150. package/tools/privacy-guard.mjs +352 -0
  151. package/tools/quality-audit.mjs +166 -0
  152. package/tools/schema-fingerprint.mjs +191 -0
  153. package/{src/dsh → tools}/selftest.mjs +75 -22
  154. package/tools/smells.mjs +398 -0
  155. package/tools/verify-case-paths.mjs +93 -0
  156. package/tools/version.mjs +191 -0
  157. package/docs/MASTER-PLAN-2.0.0.md +0 -133
  158. package/docs/MASTER-PLAN-3.0.0.md +0 -76
  159. package/src/adapters/dsh/fg-appeal-tool.mjs +0 -47
  160. package/src/adapters/dsh/fg-apply-tool.mjs +0 -68
  161. /package/{src/adapters/dsh → hooks}/protocol.mjs +0 -0
@@ -39,8 +39,14 @@
39
39
  * 记录一并带出(prunes_so_far / pruned_tokens),既不丢信息也不淹没有效记录。
40
40
  */
41
41
 
42
- import { appendAudit } from './audit.mjs'
43
- import { moduleSnapshot } from './heartbeat.mjs'
42
+ import { appendAudit, buildAuditRow } from './audit.mjs'
43
+ import { livenessBadge, noteLivenessEvent } from './heartbeat.mjs'
44
+ import { statePath, loadState, saveState } from '../core/state.mjs'
45
+ // 2026-10-27:启动自证拆到 compactionWatch/announce.mjs(本文件超 400 行)。
46
+ // 对外 API 不变:index.js 与测试仍从本模块取 announceWatchReady / _resetWatchAnnounce / WATCH_SEAMS。
47
+ export { WATCH_SEAMS, announceWatchReady, _resetWatchAnnounce } from './compactionWatch/announce.mjs'
48
+ import { clampText } from './compactionWatch/announce.mjs'
49
+ import { gateThreshold } from './testRuntime.mjs'
44
50
 
45
51
  const EV_START = 'compaction/start'
46
52
  const EV_END = 'compaction/end'
@@ -92,21 +98,14 @@ export function _compactionWatchState(session) {
92
98
  }
93
99
 
94
100
  function row(state, action, trigger, extra = {}) {
95
- return {
96
- ts: new Date().toISOString(),
97
- session: state.sessionId,
98
- action,
101
+ // 2026-10-29:行构造收敛到 buildAuditRow(此前这是第 5 份复制体)。
102
+ // `basis` 是本模块特有的来源标注,走 extra 带进去;`pardon` 由构造点统一为 false。
103
+ const { basis, level, ...rest } = extra
104
+ return buildAuditRow(state.sessionId, action, {
99
105
  trigger,
100
- level: null,
101
- basis: 'builtin:compaction-basic',
102
- ...extra,
103
- pardon: false,
104
- }
105
- }
106
-
107
- function clampText(value, max = 300) {
108
- const text = typeof value === 'string' ? value : String(value ?? '')
109
- return text.length > max ? text.slice(0, max) + '…' : text
106
+ level,
107
+ extra: { basis: basis === undefined ? 'builtin:compaction-basic' : basis, ...rest },
108
+ })
110
109
  }
111
110
 
112
111
  /** 压缩落定留痕。 */
@@ -118,6 +117,27 @@ function auditCompaction(state, { failed, durationMs, open, summary, error }) {
118
117
  `输入 ${state.lastInputTokens}`,
119
118
  ]
120
119
  if (failed) parts.push(`error=${clampText(error, 120)}`)
120
+ // 按需自证(2026-10-19):压缩是第三个局部点。压缩后模型的上下文被改写过,
121
+ // 这时告诉它"FG 还活着、刚才发生过压缩"才有解释价值;平时不注入。
122
+ noteLivenessEvent(failed ? 'compaction(failed)' : 'compaction')
123
+ // 结果准入额度随压缩恢复(2026-10-24):压缩后上下文变小,大结果预算理应回满;
124
+ // 恢复失败只留痕,不影响压缩监察本身。
125
+ if (!failed) {
126
+ try {
127
+ const sid = (state.session && state.session.id) || state.sessionId
128
+ if (sid) {
129
+ const file = statePath(sid)
130
+ const st = loadState(file)
131
+ if (st) {
132
+ // 与 volume.mjs 同口径:0=关闭在测试里可用,生产被 gateThreshold 兜到 1。
133
+ const def = gateThreshold('FG_RESULT_ADMIT_BUDGET', 3)
134
+ saveState(file, { ...st, resultAdmitLeft: Number.isFinite(def) ? def : 3 })
135
+ }
136
+ }
137
+ } catch {
138
+ /* 不阻断 */
139
+ }
140
+ }
121
141
  appendAudit(
122
142
  row(state, 'compaction', failed ? 'compaction/end(error)' : 'compaction/end', {
123
143
  basis: open.sourceCommandId ? 'builtin:command-compact' : 'builtin:compaction-basic',
@@ -132,6 +152,7 @@ function auditCompaction(state, { failed, durationMs, open, summary, error }) {
132
152
  // 剪枝累计:不逐条留痕,但要让它随压缩记录一起可见("释放了多少")
133
153
  prunes_so_far: state.prunes,
134
154
  pruned_tokens: state.prunedTokens,
155
+ liveness: livenessBadge({ drain: false }),
135
156
  error: failed ? clampText(error, 300) : null,
136
157
  evidence: clampText(parts.join(' | ')),
137
158
  }),
@@ -259,37 +280,7 @@ export function contextOverflowListener({ warn } = {}) {
259
280
  const emit = typeof warn === 'function' ? warn : () => {}
260
281
  return async ({ agent, failure }, next) => {
261
282
  try {
262
- if (failure && failure.code === CONTEXT_OVERFLOW_CODE) {
263
- const session = agent && agent.session
264
- if (session) {
265
- const state = stateFor(session)
266
- const dead = state.compactions === 0 && state.prunes === 0
267
- appendAudit(
268
- row(state, 'context-overflow', 'agent/request-error', {
269
- code: failure.code,
270
- input_tokens: state.lastInputTokens || null,
271
- compactions_so_far: state.compactions,
272
- failed_so_far: state.failed,
273
- prunes_so_far: state.prunes,
274
- pruned_tokens: state.prunedTokens,
275
- stack_looks_dead: dead,
276
- error: clampText(failure.message ?? failure.code, 300),
277
- evidence: clampText(
278
- `撞窗 code=${failure.code} 输入=${state.lastInputTokens || '-'} ` +
279
- `压缩=${state.compactions} 失败=${state.failed} 剪枝=${state.prunes}(${state.prunedTokens}tok)` +
280
- (dead ? ' —— 压缩栈疑似未生效' : ''),
281
- ),
282
- }),
283
- )
284
- if (dead && !state.overflowWarned) {
285
- state.overflowWarned = true
286
- emit(
287
- `压缩监察:会话 ${state.sessionId} 撞上下文窗口,但本会话 0 次压缩 / 0 次剪枝 —— ` +
288
- '内置压缩栈疑似未挂载(检查 preset 里的 compaction-basic 行)',
289
- )
290
- }
291
- }
292
- }
283
+ reportOverflow({ agent, failure, emit })
293
284
  } catch (error) {
294
285
  emit('压缩监察(撞窗)观察失败(不阻断会话):', (error && error.message) || error)
295
286
  }
@@ -298,110 +289,34 @@ export function contextOverflowListener({ warn } = {}) {
298
289
  }
299
290
  }
300
291
 
301
- // ── 启动自证(2026-10-18,人类批示「让日志真正做到自证清白」)────────────────
302
- //
303
- // 病根:上面所有记录都是**被动**的——只有会话真的压过一次,AUDIT.log 里才有 `compaction`。
304
- // 于是"监察层没挂上"和"挂上了但还没触发"在日志里长得一模一样,都表现为"什么都没有"。
305
- // 唯一旁证是 `.focus-guard/status.json`,但那是心跳文件、随时被覆写,而且它证明的是
306
- // "插件在跳",不是"这两条缝在听"。要把两者分开,只能在进程启动时无条件留一条。
307
- //
308
- // 口径:**同一状态每进程只报一次**(`announced` 闸门);ready↔degraded 真发生翻转时再报一次
309
- // ——那不是重复,是真实的状态变化,必须留痕。翻转在当前装配流程里理论上不会发生
310
- // (register() 在 apply() 内同步跑完),闸门是防御性的,不是功能。
311
-
312
- /** 本层依赖的两条宿主缝;label 必须与 index.js 里 register() 的第三参数逐字一致。 */
313
- export const WATCH_SEAMS = ['session/event(compaction-watch)', 'agent/request-error(compaction-watch)']
314
-
315
- /** 进程启动时刻:只用于让"这条记录属于哪一次启动"可核对,不参与任何判断。 */
316
- const PROCESS_STARTED_AT = new Date().toISOString()
317
-
318
- /** @type {'ready'|'degraded'|null} 上一次宣告的状态;null = 本进程尚未宣告。 */
319
- let announced = null
320
-
321
- /** 测试钩子:清空宣告闸门,使同一进程内可重复验证。生产路径不调用。 */
322
- export function _resetWatchAnnounce() {
323
- announced = null
324
- }
325
-
326
- /**
327
- * 读当前装配快照,判定本层是否真的挂上了两条缝。
328
- * 数据源是 heartbeat.mjs 的 MODULES —— register() 成功即 markModule(label, true),
329
- * 这是"注册到底成没成"的唯一权威口径,比任何自检代码更可信。
330
- * @returns {{ ready: boolean, seams: Record<string,string>, bad: string[], ok: number, total: number, degraded: string[] }}
331
- */
332
- function seamSnapshot() {
333
- const snapshot = moduleSnapshot()
334
- const seams = {}
335
- const bad = []
336
- for (const key of WATCH_SEAMS) {
337
- // 未出现在快照里 = apply() 根本没跑到那行 register(),与 FAIL 同等对待。
338
- const value = snapshot[key] === undefined ? 'MISSING: 未报到' : snapshot[key]
339
- seams[key] = value
340
- if (value !== 'OK') bad.push(`${key}=${value}`)
341
- }
342
- const keys = Object.keys(snapshot)
343
- return {
344
- ready: bad.length === 0,
345
- seams,
346
- bad,
347
- ok: keys.filter((k) => snapshot[k] === 'OK').length,
348
- total: keys.length,
349
- // 全量降级清单:自证行要能独立说明"整机几成",而不只是本层两条缝。
350
- degraded: keys.filter((k) => snapshot[k] !== 'OK'),
351
- }
352
- }
353
-
354
- /**
355
- * 启动自证:把"监察层在不在"无条件写进 AUDIT.log 一次。
356
- *
357
- * 必须在 index.js 的两条 register() **与**心跳启动**之后**调用 ——
358
- * 自证要反映的是最终装配结果,早一步调用就会漏掉心跳、报出错误的完成度。
359
- *
360
- * 永不抛:写不进去只 warn。自证失败不能变成宿主的新故障点(与本层其余部分同纪律)。
361
- * @param {{ warn?: Function }} [options]
362
- * @returns {'ready'|'degraded'|null} 本次宣告的状态;被闸门拦下时返回上次的状态
363
- */
364
- export function announceWatchReady({ warn } = {}) {
365
- const emit = typeof warn === 'function' ? warn : () => {}
366
- try {
367
- const { ready, seams, bad, ok, total, degraded } = seamSnapshot()
368
- const next = ready ? 'ready' : 'degraded'
369
- if (announced === next) return next
370
- announced = next
371
-
372
- const action = ready ? 'compaction-watch-ready' : 'compaction-watch-degraded'
373
- const evidence = ready
374
- ? `监察层就位:${WATCH_SEAMS.length} 条缝均已注册,压缩事件与撞窗告警都会进本日志` +
375
- `(模块 ${ok}/${total} 报到,pid ${process.pid})`
376
- : `监察层未就位:${bad.join(';')} —— 该缝未注册时,对应的压缩事件不会进本日志` +
377
- `(模块 ${ok}/${total} 报到,pid ${process.pid})`
378
-
379
- appendAudit({
380
- ts: new Date().toISOString(),
381
- // 进程级记录没有会话归属,用既有兜底口径 dsh-native,另以 scope 标明不是会话级留痕。
382
- session: 'dsh-native',
383
- action,
384
- trigger: 'startup',
385
- level: null,
386
- basis: 'fg:compaction-watch',
387
- scope: 'process',
388
- pid: process.pid,
389
- process_started_at: PROCESS_STARTED_AT,
390
- watching: [...WATCH_SEAMS],
391
- seams,
392
- modules_ok: `${ok}/${total}`,
393
- degraded_modules: degraded,
394
- readonly: true,
395
- evidence: clampText(evidence),
396
- pardon: false,
397
- })
398
-
399
- if (!ready) {
400
- emit(`压缩监察层未就位:${bad.join(';')} —— 这些缝未注册时,压缩事件不会进 AUDIT.log`)
401
- }
402
- return next
403
- } catch (error) {
404
- emit('压缩监察启动自证失败(不影响会话):', (error && error.message) || error)
405
- return null
406
- }
292
+ /** 撞窗上报:只在 failure 是上下文溢出且有 session 时留痕;栈疑似未生效时喊一次。 */
293
+ function reportOverflow({ agent, failure, emit }) {
294
+ if (!failure || failure.code !== CONTEXT_OVERFLOW_CODE) return
295
+ const session = agent && agent.session
296
+ if (!session) return
297
+ const state = stateFor(session)
298
+ const dead = state.compactions === 0 && state.prunes === 0
299
+ appendAudit(
300
+ row(state, 'context-overflow', 'agent/request-error', {
301
+ code: failure.code,
302
+ input_tokens: state.lastInputTokens || null,
303
+ compactions_so_far: state.compactions,
304
+ failed_so_far: state.failed,
305
+ prunes_so_far: state.prunes,
306
+ pruned_tokens: state.prunedTokens,
307
+ stack_looks_dead: dead,
308
+ error: clampText(failure.message ?? failure.code, 300),
309
+ evidence: clampText(
310
+ `撞窗 code=${failure.code} 输入=${state.lastInputTokens || '-'} ` +
311
+ `压缩=${state.compactions} 失败=${state.failed} 剪枝=${state.prunes}(${state.prunedTokens}tok)` +
312
+ (dead ? ' —— 压缩栈疑似未生效' : ''),
313
+ ),
314
+ }),
315
+ )
316
+ if (!dead || state.overflowWarned) return
317
+ state.overflowWarned = true
318
+ emit(
319
+ `压缩监察:会话 ${state.sessionId} 撞上下文窗口,但本会话 0 次压缩 / 0 次剪枝 —— ` +
320
+ '内置压缩栈疑似未挂载(检查 preset 里的 compaction-basic 行)',
321
+ )
407
322
  }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 授权/改动面两道闸(2026-10-27 从 pipeline.mjs 抽出,纯搬运)。
3
+ *
4
+ * ① 资格审核闸(3.0.5 第二步):高危工具须先调 fg_apply 取得授权;
5
+ * ② 改动面闸(2026-10-25):新建架构敏感文件 / 加依赖须先回三行(收益 / 改动面 / 替代)。
6
+ */
7
+ import { existsSync } from 'node:fs'
8
+ import { loadProfile } from '../../core/profileLoader.mjs'
9
+ import { statePath as guardStateFile, loadState, saveState } from '../../core/state.mjs'
10
+ import { shouldGate, gateReason, promptDeclaresBenefit } from '../value-gate.mjs'
11
+ import { auditDeny } from '../audit.mjs'
12
+ import { modelIdOf, pathOfTool, resolveToolPath, sessionIdOf } from './tooling.mjs'
13
+ import { gateSwitch } from '../testRuntime.mjs'
14
+
15
+ /**
16
+ * 资格审核闸 —— 高危工具须先调 fg_apply 取得授权。
17
+ * 按需加载适配层模块:本文件不在顶部静态 import,以免与适配层的注入关系形成环形依赖。
18
+ * 2026-10-18(任务测试 T39 修):原条件为 `if (cmd)`,而 Write/Edit 没有 command 参数,
19
+ * 于是"写系统路径"这类只能靠 file_path 判定的门槛**从未被执行**。改为命令或路径任一存在即过闸。
20
+ */
21
+ export async function eligibilityStage(ctx) {
22
+ const { exec, warn, cmd } = ctx
23
+ const gateFilePath = (() => {
24
+ const a = (exec && exec.arguments) || {}
25
+ const p = a.file_path ?? a.filePath ?? a.path ?? a.notebook_path
26
+ return typeof p === 'string' ? p : ''
27
+ })()
28
+ if (!cmd && !gateFilePath) return null
29
+ try {
30
+ const { gateToolCall } = await import('../../adapters/dsh/eligibility-gate.mjs')
31
+ const session =
32
+ (exec && (exec.sessionId || (exec.agent && (exec.agent.sessionId || exec.agent.id)))) || 'dsh-native'
33
+ // 最后一公里:把 exec 里的模型标识翻成画像交闸,使画像在真实 pre-execute 生效
34
+ //(此前 pipeline 不传 profile,画像只在 decide()/applyEligibility 那两条路可达)。
35
+ // 取不到模型时为 null → 闸按最严 mutating,是安全默认而非缺陷。
36
+ const modelId = modelIdOf(exec)
37
+ const gate = gateToolCall({
38
+ session,
39
+ tool: String((exec && exec.name) || ''),
40
+ command: cmd || '',
41
+ filePath: gateFilePath,
42
+ profile: modelId ? loadProfile(modelId) : null,
43
+ })
44
+ if (gate.kind === 'deny') {
45
+ warn('资格审核闸拦截:', gate.reason)
46
+ auditDeny(exec, cmd || gateFilePath, { trigger: 'gate:fg_apply', level: 6 })
47
+ return { kind: 'deny', reason: `focus-guard-native: ${gate.reason}` }
48
+ }
49
+ // 2026-10-22:人类批准走宿主 ask 缝(GUI 审批卡片),不再只发 CLI 请求。
50
+ // ask 由宿主 approval.request 处理:allowed-once → 本次执行;rejected/cancelled/unavailable → deny。
51
+ if (gate.kind === 'ask') {
52
+ warn('资格审核闸转人工审批:', gate.reason)
53
+ auditDeny(exec, cmd || gateFilePath, { trigger: 'gate:human-approval', level: 6 })
54
+ return { kind: 'ask', reason: gate.reason, displayReason: gate.displayReason || gate.reason }
55
+ }
56
+ } catch (error) {
57
+ warn('资格审核闸异常,fail-open 放行:', (error && error.message) || error)
58
+ }
59
+ return null
60
+ }
61
+
62
+ /**
63
+ * 改动面闸 —— 人类判据:"改大量文件只换来一个小彩灯"。新建架构敏感文件 / 加依赖时,
64
+ * 要求先回三行(收益 / 改动面 / 替代);**只拒一次**,重试即放行。
65
+ * 人类指令里已声明收益(≥20 字且含收益词)时不介入。
66
+ */
67
+ export async function valueGateStage(ctx) {
68
+ const { exec, warn, cmd } = ctx
69
+ try {
70
+ if (gateSwitch('FG_VALUE_GATE')) {
71
+ const fPath = resolveToolPath(pathOfTool((exec && exec.arguments) || {}), exec)
72
+ const sid5 = sessionIdOf(exec)
73
+ const sf = guardStateFile(sid5)
74
+ const st5 = existsSync(sf) ? loadState(sf) : null
75
+ const needGate =
76
+ shouldGate({ filePath: fPath, exists: existsSync, command: cmd }) &&
77
+ !(st5 && st5.valueGateSeen) &&
78
+ !promptDeclaresBenefit(st5 && (st5.turnPromptFull || st5.turnPrompt))
79
+ if (needGate) {
80
+ try {
81
+ saveState(sf, { ...(st5 || {}), valueGateSeen: true })
82
+ } catch {
83
+ /* 记账失败不阻断(宁可少拦,不做死锁) */
84
+ }
85
+ warn('改动面闸:', `新建敏感文件或加依赖 → 要求一行收益 ${fPath || cmd || ''}`)
86
+ auditDeny(exec, fPath || cmd || 'value-gate', { trigger: 'value-gate' })
87
+ return {
88
+ kind: 'deny',
89
+ reason: gateReason({ filePath: fPath, kind: fPath ? 'file' : 'dep' }),
90
+ }
91
+ }
92
+ }
93
+ } catch (error) {
94
+ warn('改动面闸异常,fail-open 放行:', (error && error.message) || error)
95
+ }
96
+ return null
97
+ }
@@ -0,0 +1,308 @@
1
+ /**
2
+ * 第 3 层·状态校验 + 取证闸(2026-10-27 从 pipeline.mjs 抽出,纯搬运)。
3
+ *
4
+ * 权威落盘点(实测 guard.mjs:255-268, 372-395):
5
+ * 会话状态 → <stateDir()>/focus-guard-<会话id>.json(2026-11-01 起;此前平铺在 os.tmpdir() 根),
6
+ * 字段 fused / forcedInvestigate / probation / readSet
7
+ * 执法留痕 → <工作区>/.focus-guard/AUDIT.log(guard.mjs:19;工作区由 ZCODE_PROJECT_DIR/CLAUDE_PROJECT_DIR 定,缺省 stateDir())
8
+ * 取证记录 → <工作区>/.ai/CASE_FILE.md 的【三】(guard.mjs 写;原生插件另有记账类【五】)
9
+ * 注意:任务书写的「熔断状态在 packages/core/.focus-guard/」不准确——该目录只有 AUDIT.log;
10
+ * 熔断标志实际落在 stateDir() 的会话状态文件里。
11
+ */
12
+ import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+ import { stateDir } from '../../core/tempPath.mjs'
15
+ import { auditDeny } from '../audit.mjs'
16
+ import { isMutatingBashCmd } from '../../core/redlines.mjs'
17
+ import { statePath as guardStateFile, loadState, saveState } from '../../core/state.mjs'
18
+ import {
19
+ READ_TOOL,
20
+ SHELL_TOOL,
21
+ commandOf,
22
+ evidenceKeyOf,
23
+ isMutatingInvocation,
24
+ pathOfTool,
25
+ resolveToolPath,
26
+ sameEvidenceKey,
27
+ sessionIdOf,
28
+ shellWriteTargets,
29
+ } from './tooling.mjs'
30
+ import { gateSwitch } from '../testRuntime.mjs'
31
+ import { sessionSet } from '../../core/sessionScratch.mjs'
32
+
33
+ export const STATE_GATE = { effective: true }
34
+ // 2026-10-29 立法:不允许关闭任何功能。`FG_EVIDENCE_GATE=0` 只在测试运行时生效,
35
+ // 生产环境 gateSwitch 恒返 true——见 testRuntime.mjs 头注释。
36
+ export const EVIDENCE_GATE = { effective: gateSwitch('FG_EVIDENCE_GATE') }
37
+ const GUARD_STATE_MAX_AGE_MS = 60 * 60 * 1000
38
+
39
+ /**
40
+ * 取最近一个真实会话状态(排除 eval 快照)。
41
+ * 入参可以是目录(默认 stateDir())或一个具体的状态文件路径(自检注入用)。
42
+ * 顺序:先按 mtime 取最新一个 focus-guard-*.json → 再判定是否在 GUARD_STATE_MAX_AGE_MS 内。
43
+ * 无可用状态(无文件 / 过旧 / 解析失败)返回 null,由调用方 fail-open + warn。
44
+ */
45
+ export function readGuardState(target = stateDir()) {
46
+ try {
47
+ const isFile = /\.json$/i.test(String(target)) && !String(target).endsWith('\\') && !String(target).endsWith('/')
48
+ if (isFile) {
49
+ const state = JSON.parse(readFileSync(target, 'utf8'))
50
+ if (state && typeof state === 'object') return { file: target, state }
51
+ return null
52
+ }
53
+
54
+ const dir = target
55
+ const latest = readdirSync(dir)
56
+ .filter((n) => n.startsWith('focus-guard-') && n.endsWith('.json') && !n.startsWith('focus-guard-eval-'))
57
+ .map((n) => join(dir, n))
58
+ .map((p) => ({ p, st: statSync(p) }))
59
+ .sort((a, b) => b.st.mtimeMs - a.st.mtimeMs)[0]
60
+ if (!latest) return null
61
+ if (Date.now() - latest.st.mtimeMs >= GUARD_STATE_MAX_AGE_MS) return null // 最新一个也已过期
62
+ const state = JSON.parse(readFileSync(latest.p, 'utf8'))
63
+ if (state && typeof state === 'object') return { file: latest.p, state }
64
+ return null
65
+ } catch {
66
+ return null
67
+ }
68
+ }
69
+
70
+ // 3.0.8:按【会话身份】分表(原为模块级单一 Set,跨会话共享)。
71
+ // DSH 单进程里多个会话共用同一份 pipeline 模块,共享 Set 会让"会话 A 读过的文件"
72
+ // 被判成"会话 B 也读过"——违反取证的本会话语义(新增用例「会话隔离」锁定了这一点)。
73
+ // 2026-10-29:两个容器改由 core/sessionScratch.mjs 托管——能按会话清空(测试可重置)、
74
+ // 有插入序上限(长驻进程不无限涨)。原来各 new 一个 Map,没有任何 API 能摆回起点。
75
+ const nativeReadSet = sessionSet('nativeReadSet')
76
+ const evidenceBlockedOnce = sessionSet('evidenceBlockedOnce')
77
+
78
+ /**
79
+ * 本会话是否"读过"该文件。先查直命(归一化键),再兼容历史/异形态键
80
+ *(postProgress 存的是相对正斜杠、老记录可能存原始相对路径)——逐个解析后比较。
81
+ */
82
+ function isReadRecorded(state, sid, absKey, exec) {
83
+ const seen = nativeReadSet.of(sid)
84
+ const rs = state && state.readSet && typeof state.readSet === 'object' ? state.readSet : {}
85
+ if (seen.has(absKey) || Object.hasOwn(rs, absKey)) return true
86
+ const candidates = [...seen, ...Object.keys(rs)]
87
+ for (const c of candidates) {
88
+ const k = evidenceKeyOf(c, exec)
89
+ if (k && sameEvidenceKey(k, absKey)) return true
90
+ }
91
+ return false
92
+ }
93
+
94
+ /**
95
+ * 记录本会话内已读过的文件(第 3 层取证判定的原生侧证据)。
96
+ *
97
+ * 3.0.8(孤儿机制审计):除内存 Set 外**同时落盘**到本会话状态文件。
98
+ * 为什么必须落盘:内存 Set 随模块重载(HMR)与进程重启清零,而 DSH 侧此前**没有 state 写入者**
99
+ * (唯一的写者 guard.mjs 在 DSH 下未挂载)——于是取证记录会凭空消失,表现为"明明读过却被判未取证"。
100
+ * 这是"原生插件自持状态"的第一处写权;KPI / 预算池等机制后续也依赖它。
101
+ * 仅在**新增**记录时落盘,避免每次 Read 都写一次盘。
102
+ */
103
+ export function rememberReads(exec) {
104
+ if (!READ_TOOL.test(String((exec && exec.name) || ''))) return
105
+ const p = pathOfTool(exec && exec.arguments)
106
+ if (!p) return
107
+ // 2026-10-19:键必须与查证侧(resolveToolPath 的绝对路径)同形态,否则"读过"永远查不到。
108
+ const key = evidenceKeyOf(p, exec) || String(p)
109
+ const sid = sessionIdOf(exec)
110
+ const seen = nativeReadSet.of(sid)
111
+ if (seen.has(key)) return
112
+ seen.add(key)
113
+ try {
114
+ const file = guardStateFile(sid)
115
+ // loadState 在文件不存在时返回默认结构(含 readSet: {}),无需先判存在
116
+ const state = loadState(file)
117
+ state.readSet = state.readSet && typeof state.readSet === 'object' ? state.readSet : {}
118
+ state.readSet[key] = Date.now()
119
+ saveState(file, state)
120
+ } catch (error) {
121
+ // 落盘失败不阻断(内存 Set 仍有效);但必须留痕——静默丢取证记录属"假留痕"
122
+ console.warn('[focus-guard-native] 取证记录落盘失败(内存记录仍有效):', (error && error.message) || error)
123
+ }
124
+ }
125
+
126
+ /**
127
+ * 本会话状态读取器(3.0.8 · 孤儿机制审计的修复)。
128
+ * 用 exec 的会话身份**精确定位** `statePath(sessionId)`,**绝不做目录扫描**。
129
+ *
130
+ * 为什么必须这样:原实现走 `readGuardState(undefined)` → 退化成"扫 os.tmpdir() 取 mtime 最新",
131
+ * 于是会读到**别的会话或测试的残留**,拿它们(往往是空的)readSet 去判你的真实改动。
132
+ * 实测 os.tmpdir() 里有 199 个 `focus-guard-eval-*`(被过滤掉)外加 acceptance/selftest 写的
133
+ * `focus-guard-<测试sid>-<RUN>.json`(**过滤不掉**),于是"拦不拦你"取决于最近跑没跑测试。
134
+ * 自检可传具体文件路径覆盖(statePathOverride)。
135
+ */
136
+ function readGuardStateExact(exec, override) {
137
+ const file =
138
+ override && /\.json$/i.test(String(override)) ? String(override) : guardStateFile(sessionIdOf(exec))
139
+ try {
140
+ if (!existsSync(file)) return null
141
+ const state = JSON.parse(readFileSync(file, 'utf8'))
142
+ return state && typeof state === 'object' ? { file, state } : null
143
+ } catch {
144
+ return null
145
+ }
146
+ }
147
+
148
+ /**
149
+ * 第 3 层判定:返回 deny 决策或 null(放行到下游);读失败一律 fail-open + warn。
150
+ *
151
+ * 反规避抽查B(2026-10-19 人类批示;**2026-10-27 改:默认只留痕,不打断**)。
152
+ *
153
+ * 原实现是「拒一次 → 重试即放行」。审计实测(2026-10-06~10-26,6230 行):
154
+ * 命中 61 次,全部集中在 1 个长会话(turn 174,第 179/183/187 次写操作…)。
155
+ * 而拒绝理由原文写着"重试即放行"——即**不检查任何内容、不要求任何声明**,
156
+ * 模型最理性的反应就是原样重试。它收不到信息,也拦不住任何东西。
157
+ *
158
+ * 代价是确定的:每拒一次 = 多一次工具往返(≥15k 前缀 + 输出,长会话里最贵)。
159
+ * 收益是 0:它没有核对任何内容。而抽查A(RANDOM_AUDIT_EVERY,同期 143 次)
160
+ * 已经在做同样"不可预测"的留痕,且零成本。抽查B 的净增量只有"打断"。
161
+ * → 往返比拦截贵,所以默认不打断。
162
+ *
163
+ * 保留:计数(fuseOps/fuseNextAt)、post 侧审计行、pending 状态(供观测)。
164
+ * 逃生口:`FG_RANDOM_FUSE_BLOCK=1` 恢复旧语义(拒一次即放行),供需要时序干扰时用。
165
+ * 安全取向不变:状态清不掉就**不拒**(宁可不拦,也不做永久死锁)。
166
+ */
167
+ function layer3Check(exec, warn, statePathOverride) {
168
+ const tool = String((exec && exec.name) || '')
169
+ // 2026-10-27:按 (工具, 动作) 判改动——`plugin_manager` 的 list_* 只读列举不写盘,
170
+ // 不能落进下面的"改动类无路径"分支;写动作仍按改动类处理。
171
+ // 参数读取必须防炸(同下段注释):DSH 允许 arguments 为惰性 getter,
172
+ // 它可能抛错;此处只是取动作名,取不到就按"非只读"(安全默认)。
173
+ let argsForAction = null
174
+ try {
175
+ argsForAction = (exec && exec.arguments) || null
176
+ } catch {
177
+ argsForAction = null
178
+ }
179
+ const isMutating = isMutatingInvocation(tool, argsForAction)
180
+ // 2026-10-18 补口:shell 重定向/写 cmdlet 与 Edit 是等效写操作,取证闸不能只认工具名;
181
+ // 变更型 shell(git commit / npm install)与写类工具同等对待,熔断期一律只读放行。
182
+ const { shellTargets, shellMutating } = shellMutationOf(exec)
183
+ if (!isMutating && shellTargets.length === 0 && !shellMutating) return null
184
+
185
+ const gs = readGuardStateExact(exec, statePathOverride)
186
+ if (gs === null) {
187
+ warn('第3层:本会话尚无状态文件(fail-open 放行;无读写记录时不做取证判定)')
188
+ return null
189
+ }
190
+ const { state } = gs
191
+ if (STATE_GATE.effective && (state.fused || state.probation)) {
192
+ const which = state.probation ? 'L5 降权' : '熔断'
193
+ return {
194
+ kind: 'deny',
195
+ reason: `focus-guard-native 第3层状态校验:guard 权威状态为「${which}」,改动类调用(${tool})被拒;只读放行,解除按 guard 流程`,
196
+ }
197
+ }
198
+
199
+ const fuse = randomFuseVerdict({ state, file: gs.file, warn })
200
+ if (fuse) return fuse
201
+
202
+ return evidenceTargetsVerdict({ exec, warn, tool, isMutating, shellTargets, state })
203
+ }
204
+
205
+ /**
206
+ * 反规避抽查B(2026-10-19 人类批示;2026-10-27 改:默认只留痕,不打断)。
207
+ * 状态清不掉就不拒(宁可不拦,也不做永久死锁);`FG_RANDOM_FUSE_BLOCK=1` 恢复"拒一次"。
208
+ */
209
+ function randomFuseVerdict({ state, file, warn }) {
210
+ if (!state.randomFusePending) return null
211
+ try {
212
+ saveState(file, { ...state, randomFusePending: false })
213
+ if (String(process.env.FG_RANDOM_FUSE_BLOCK || '') === '1') {
214
+ return {
215
+ kind: 'deny',
216
+ trigger: 'random-fuse',
217
+ reason:
218
+ `focus-guard-native 反规避抽查B:随机检查点命中(第 ${Number(state.randomFuseAt) || 0} 次写操作),本次变更被拒一次;` +
219
+ '这不是报错,是防「攒批量绕过」的不可预测抽查,重试即放行。',
220
+ }
221
+ }
222
+ } catch (error) {
223
+ warn('反规避抽查B:检查点状态回写失败 → 本次放行(不做永久死锁):', (error && error.message) || error)
224
+ }
225
+ return null
226
+ }
227
+
228
+ /** shell 类工具的写目标与"变更型"判定;参数惰性 getter 抛错时降级为"无写目标、非变更型"。 */
229
+ function shellMutationOf(exec) {
230
+ let shellTargets = []
231
+ let shellMutating = false
232
+ const tool = String((exec && exec.name) || '')
233
+ if (!SHELL_TOOL.test(tool)) return { shellTargets, shellMutating }
234
+ try {
235
+ const cmd = commandOf(exec)
236
+ shellTargets = shellWriteTargets(cmd)
237
+ shellMutating = isMutatingBashCmd(String(cmd ?? ''))
238
+ } catch {
239
+ shellTargets = []
240
+ shellMutating = false
241
+ }
242
+ return { shellTargets, shellMutating }
243
+ }
244
+
245
+ /**
246
+ * 取证闸:改动类工具 / shell 写目标必须在**本会话**读过。
247
+ *
248
+ * 2026-10-22 补口:改动类工具**解析不出路径**时(`plugin_manager`、`move_run`、`import_claude`、
249
+ * `mcp__x__build_project` 等),取证闸无法核验"是否先读过"——旧行为是直接放行,
250
+ * 等于这些工具天生免检。现改为默认要求授权(`fg_apply` 一次放行),可用
251
+ * `FG_MUTATION_UNMAPPED=allow` 退回旧行为。
252
+ */
253
+ function evidenceTargetsVerdict({ exec, warn, tool, isMutating, shellTargets, state }) {
254
+ if (!EVIDENCE_GATE.effective) return null
255
+ // 2026-10-19 修:真实调用传相对路径(`Add-Content -Path packages/core/README.md`),
256
+ // 未解析时 existsSync 按宿主 cwd 判 → 假阴性 → 取证闸放行(实测 session-002c143b 第 2 条直通)。
257
+ // 2026-10-27:`plugin_manager` 的 `target` 是包名/条目 id,不是文件路径。旧实现把它
258
+ // 当路径 → 解析出一个不存在的"新文件" → 安装类调用反而绕过了"要求授权"分支。
259
+ const toolPath =
260
+ isMutating && /^plugin_manager$/i.test(tool)
261
+ ? null
262
+ : resolveToolPath(pathOfTool(exec && exec.arguments), exec)
263
+ if (isMutating && !toolPath) {
264
+ if (String(process.env.FG_MUTATION_UNMAPPED || '').toLowerCase() === 'allow') {
265
+ warn('改动类工具无路径(FG_MUTATION_UNMAPPED=allow)→ 放行:', `tool=${tool}`)
266
+ } else {
267
+ auditDeny(exec, `改动类工具无可解析路径:${tool}`, { trigger: 'mutation:unmapped' })
268
+ return {
269
+ kind: 'deny',
270
+ reason:
271
+ `focus-guard-native: 改动类工具「${tool}」未提供可解析的文件路径,取证闸无法核验"是否先读过"。` +
272
+ `请先用 fg_apply 申请一次授权(tool="${tool}"),或改用带 file_path 的工具。`,
273
+ }
274
+ }
275
+ }
276
+ const targets = isMutating
277
+ ? (toolPath ? [toolPath] : [])
278
+ : shellTargets.map((p) => resolveToolPath(p, exec)).filter(Boolean)
279
+ for (const fp of targets) {
280
+ const key = String(fp).replace(/\\/g, '/')
281
+ const sid = sessionIdOf(exec)
282
+ const known = isReadRecorded(state, sid, key, exec)
283
+ // 3.0.7(HANDOFF §十「另:FG 自身缺陷」):取证闸只对"**已存在**目标的修改"有意义。
284
+ // 新建文件没有可读的既有内容 —— 文件不存在 → 读不了 → 永远进不了 readSet →
285
+ // 只能靠"拒一次后豁免"逃生,是死锁。故目标不存在(新建)时直接放行,不要求先读。
286
+ // existsSync 失败(权限/异常)一律视为"不存在",与取证闸其余分支的 fail-open 口径一致。
287
+ if (!known && existsSync(key) && !evidenceBlockedOnce.has(sid, key)) {
288
+ evidenceBlockedOnce.add(sid, key)
289
+ // 2026-11-09:区分两种「没读」——卷宗里**根本**没有这条,还是卷宗里有但属于上一次会话。
290
+ // 原本文案一律说「卷宗无取证记录」,跨会话继承时卷宗明明躺着那一行,模型读完卷宗发现
291
+ // 自相矛盾,只能怀疑是引擎坏了(实测)。措辞必须与卷宗对得上,否则留痕本身变成误导。
292
+ const rec = (state.caseCache || {})[key]
293
+ const why = rec && rec.inherited
294
+ ? `本会话未取证(卷宗有 ${fp} 的近期记录,但那是上一次会话读的,内容不在当前上下文)`
295
+ : `卷宗无取证记录(本会话未读 ${fp})`
296
+ return {
297
+ kind: 'deny',
298
+ reason: `focus-guard-native 第3层状态校验:${why},改动类调用被拒一次;先读取该文件再重试(避免盲写)`,
299
+ }
300
+ }
301
+ }
302
+ return null
303
+ }
304
+
305
+ /** pre-execute 阶段:取证/熔断状态判定(异常不吞,保持原语义)。 */
306
+ export async function evidenceStage(ctx) {
307
+ return layer3Check(ctx.exec, ctx.warn, ctx.statePath)
308
+ }