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
@@ -0,0 +1,101 @@
1
+ /**
2
+ * 钩子顺序自检(2026-10-29)
3
+ *
4
+ * 背景:Cordis 的 waterfall 按**注册顺序**派发监听器,而注册顺序由 `inject` 的激活时机
5
+ * 决定——互不相关的插件之间是不确定的。FG 的 `tools/pre-execute` 因此可能被别的护栏
6
+ * 插件抢先或插队。
7
+ *
8
+ * 为什么不用 `@zfdx123/dsh-hooks-ordering` 的 participant 接口来解决:**它不消费返回值**。
9
+ * 协调器的 `runPhase` 是 `for (const e of topoSort(entries)) await e.run(...payload)`,
10
+ * 返回值被丢弃,而 FG 的拦截正是靠 `return {kind:'deny'}`。接上去的后果是
11
+ * 「plan() 显示排第一,实际一次都没拦住」——比不装更糟。完整核查(四条路与各自的代价)见
12
+ * `packages/core/docs/HOOK-ORDERING.md`;实测数据(真包 1.0.15 + 最小 ctx:FG 排第一、
13
+ * run 返回 deny,派发结果仍是 HOST-DEFAULT)见 CHANGELOG 里「FG 自己做定序者」那条。
14
+ *
15
+ * 所以这里只做**观测**:探测协调器在不在、FG 在不在参与者列表里,如实报出去。
16
+ * 与 `policy-audit.mjs` 同纪律:只报不改,不改任何判定。
17
+ */
18
+
19
+ /** 值得盯的钩子:FG 在这些钩子上有监听器,顺序影响可观测性 */
20
+ export const WATCHED = ['tools/pre-execute', 'system-prompt/assemble', 'tools/post-execute']
21
+
22
+ /** FG 在协调器里注册时应该用的名字(如果将来真的接入) */
23
+ export const SELF_NAME = 'focus-guard'
24
+
25
+ /**
26
+ * 三态判定(纯函数,可测)。
27
+ *
28
+ * @param {object} input
29
+ * @param {boolean} input.hasService 协调器服务是否存在
30
+ * @param {Record<string, {front: string[], back: string[]} | null>} [input.plans]
31
+ * `plan(hook, phase)` 的结果;拿不到时为 `null`
32
+ * @returns {{state: 'uncontrolled'|'controlled-not-participant'|'participant', hooks: string[], message: string}}
33
+ */
34
+ export function judgeOrdering({ hasService, plans = {} }) {
35
+ if (!hasService) {
36
+ return {
37
+ state: 'uncontrolled',
38
+ hooks: [],
39
+ message:
40
+ '未检测到 hooks-ordering:pre-execute 顺序由插件注册时机决定(Cordis 按数组位置派发)。' +
41
+ 'FG 的拦截不依赖先后(拦截单调),但「谁先拦 / 谁记的账」不可控。',
42
+ }
43
+ }
44
+
45
+ const where = []
46
+ for (const hook of WATCHED) {
47
+ const plan = plans[hook]
48
+ if (!plan) continue
49
+ const front = Array.isArray(plan.front) ? plan.front : []
50
+ const back = Array.isArray(plan.back) ? plan.back : []
51
+ if (front.includes(SELF_NAME)) where.push(`${hook}:front#${front.indexOf(SELF_NAME) + 1}`)
52
+ if (back.includes(SELF_NAME)) where.push(`${hook}:back#${back.indexOf(SELF_NAME) + 1}`)
53
+ }
54
+
55
+ if (where.length) {
56
+ return {
57
+ state: 'participant',
58
+ hooks: where,
59
+ // 正常情况下不该出现:waterfall 参与者无法承载 deny,FG 若出现在这里说明有人接错了
60
+ message:
61
+ `FG 出现在 hooks-ordering 的参与者列表(${where.join('、')})——` +
62
+ 'waterfall 参与者的返回值会被协调器丢弃,FG 的 deny 不会生效(实测:runPhase 的 for-of 丢弃返回值,只有 serial 那条有 isBailed)。',
63
+ }
64
+ }
65
+
66
+ return {
67
+ state: 'controlled-not-participant',
68
+ hooks: [],
69
+ message:
70
+ 'hooks-ordering 已接管但 FG 未接入参与者(这是预期状态:waterfall 参与者承载不了 deny)。' +
71
+ '其他插件的先后由协调器拓扑排序决定,FG 仍在原生链上按注册位置派发。',
72
+ }
73
+ }
74
+
75
+ /**
76
+ * 从 Cordis ctx 上探测。任何异常都降级为 `uncontrolled`——自检失败不能影响执法缝。
77
+ *
78
+ * @param {object} ctx Cordis 上下文
79
+ * @returns {ReturnType<typeof judgeOrdering>}
80
+ */
81
+ export function probeHookOrdering(ctx) {
82
+ let service = null
83
+ try {
84
+ service = ctx && typeof ctx.get === 'function' ? ctx.get('hooksOrdering') : null
85
+ } catch {
86
+ service = null
87
+ }
88
+ if (!service || typeof service.plan !== 'function') return judgeOrdering({ hasService: false })
89
+
90
+ /** @type {Record<string, {front: string[], back: string[]} | null>} */
91
+ const plans = {}
92
+ for (const hook of WATCHED) {
93
+ try {
94
+ plans[hook] = { front: service.plan(hook, 'front'), back: service.plan(hook, 'back') }
95
+ } catch {
96
+ // 未被该协调器控制的钩子会抛 HookControlError;那是正常情况,不是失败
97
+ plans[hook] = null
98
+ }
99
+ }
100
+ return judgeOrdering({ hasService: true, plans })
101
+ }
package/src/dsh/index.js CHANGED
@@ -16,10 +16,135 @@ import { postProgressListener } from './postProgress.mjs'
16
16
  import { stopGuardListener } from './stopGuard.mjs'
17
17
  import { preGuardListener } from './preGuard.mjs'
18
18
  import { announceWatchReady, compactionEventListener, contextOverflowListener } from './compactionWatch.mjs'
19
- import { startHeartbeat } from './heartbeat.mjs'
20
- import { degradedModules, livenessNote, markModule } from './heartbeat.mjs'
21
- import { readWorkspace, recordWorkspaceTurn, renderWorkspaceSection } from './workspace.mjs'
19
+ // 2026-10-27:两行 import 同一模块(ESLint no-duplicate-imports 命中),已合并。
20
+ import { startHeartbeat, degradedModules, livenessBadge, markModule } from './heartbeat.mjs'
21
+ import { readWorkspace, recordWorkspaceTurn, renderWorkspaceSectionOnce } from './workspace.mjs'
22
+ import { augmentDeny } from './repeatGuard.mjs'
22
23
  import { registerGateTools } from './tools.mjs'
24
+ import { setProjectDirProvider } from '../core/audit.mjs'
25
+ // 熔断告知(2026-10-27):文案在母版,宿主缝只决定"何时注入"。
26
+ import { FUSE_NOTICE } from '../core/constants.mjs'
27
+ import { loadState, statePath } from '../core/state.mjs'
28
+ import { createPrefixTracker, describeShift, isFgSection } from '../core/prefixStability.mjs'
29
+ import { appendAudit, buildAuditRow } from '../core/audit-writer.mjs'
30
+
31
+ // 分层纪律(2026-10-22):项目目录由宿主层注入;DSH 侧用中立变量 FG_PROJECT_DIR,
32
+ // 母版 `core/audit.mjs` 不再读 ZCODE_/CLAUDE_(那是替别的宿主代言)。
33
+ setProjectDirProvider(() => process.env.FG_PROJECT_DIR || '')
34
+ import { installTraceMeta, recordFuseWaste } from './traceMeta.mjs'
35
+
36
+ /**
37
+ * 前缀抖动跟踪(2026-10-29)
38
+ *
39
+ * 缓存命中要前缀逐字节相同。实测(`tools/prefix-drift.mjs`)四个真实会话里
40
+ * `tools` / `user` 段全程 1 个版本,`system` 段却 2 个版本、分歧点恒定落在 FG 自己的
41
+ * `[FG-WORKSPACE]` 段。修内容是一半,**能测出来**是另一半——
42
+ * 否则下次谁再往注入里塞易变内容,还是没人知道。
43
+ *
44
+ * 只比 `focus-guard-*` 段,且只比同一会话内:换会话本来就会变,拿它报警等于报假阳性。
45
+ */
46
+
47
+ /**
48
+ * 已知会**合法**翻转的段:`focus-guard-fuse` 随熔断开/关每回合切换一次。
49
+ * 只由它引起的抖动不写审计——否则长会话里每回合一条噪音,真正该看的抖动会被淹掉。
50
+ *
51
+ * 2026-10-30:白名单从"免检"改成"限次免检",逻辑落在 `createPrefixTracker`
52
+ * (`expectedSections` / `churnLimit`)。正常熔断是"拨一下",连拨第四次说明它在抖。
53
+ *
54
+ * 2026-11-11:**`focus-guard-cost` 明确不进白名单**,尽管它也随时钟合法翻转
55
+ * (`PEAK_WINDOWS` 09:00–12:00 / 14:00–18:00,工作日最多 4 次)。三条理由:
56
+ * ① 它是「观测点能看到最终装配」的唯一探针——`prefix-stability.test.mjs` 用
57
+ * 「cost 段变了必须写一条审计」来锁住那个盲区修复,静音等于把靶子拆了;
58
+ * ② 白名单的语义是「由**会话状态**驱动的开关式翻转」(fuse 是开/关),
59
+ * cost 是**时钟**驱动——时钟不是状态,把它塞进来会让判据变糊;
60
+ * ③ 静音写在**写侧**,副作用是"以后谁把 cost 行改成带时间戳"这种真故障
61
+ * 也一起静音。噪音真成问题时该在**读审计**时按段名过滤,而不是在写侧闭眼。
62
+ */
63
+ const EXPECTED_SHIFT_SECTIONS = new Set(['focus-guard-fuse'])
64
+ const FUSE_CHURN_LIMIT = 3
65
+
66
+ const prefixTracker = createPrefixTracker({
67
+ expectedSections: EXPECTED_SHIFT_SECTIONS,
68
+ churnLimit: FUSE_CHURN_LIMIT,
69
+ audit: ({ sid, diff }) => {
70
+ appendAudit(
71
+ buildAuditRow(sid, 'prompt-prefix-shift', {
72
+ trigger: 'system-prompt/assemble',
73
+ evidence:
74
+ diff.kind === 'churn'
75
+ ? `fuse-churn(>${FUSE_CHURN_LIMIT} 次) | ${describeShift(diff)}`
76
+ : describeShift(diff),
77
+ }),
78
+ )
79
+ },
80
+ })
81
+
82
+ function notePrefixShift(context, downstream, extra) {
83
+ const header = context && context.agent && context.agent.session ? context.agent.session.header : null
84
+ const sid = header ? header.id : null
85
+ if (!sid) return null
86
+ return prefixTracker.note(sid, [...((downstream && downstream.sections) || []), ...(extra || [])])
87
+ }
88
+
89
+ /**
90
+ * 宿主段漂移(2026-10-29,只读诊断):FG 段之外的部分(宿主工具表 / 系统提示 / 技能目录)
91
+ * 一变前缀也会断,但它不归 FG 管,不该混进 `prompt-prefix-shift` 的告警里。
92
+ * 单独记一条 `prompt-prefix-host`,**每会话最多一次**——用来区分"FG 又抖了"与"宿主变了",
93
+ * 免得修完 FG 还在怀疑自己。
94
+ */
95
+ const HOST_REPORT_SEEN = new Set()
96
+ const HOST_SEEN_MAX = 64
97
+
98
+ const hostTracker = createPrefixTracker({
99
+ // 宿主段 = 非 FG 段;默认 filter 只认 focus-guard-*,这里反向取。
100
+ filter: (s) => !isFgSection(s && s.name),
101
+ audit: ({ sid, diff }) => {
102
+ if (HOST_REPORT_SEEN.has(sid)) return
103
+ if (HOST_REPORT_SEEN.size >= HOST_SEEN_MAX) HOST_REPORT_SEEN.delete(HOST_REPORT_SEEN.values().next().value)
104
+ HOST_REPORT_SEEN.add(sid)
105
+ appendAudit(
106
+ buildAuditRow(sid, 'prompt-prefix-host', {
107
+ trigger: 'system-prompt/assemble',
108
+ evidence: describeShift(diff),
109
+ }),
110
+ )
111
+ },
112
+ })
113
+
114
+ function noteHostShift(context, downstream) {
115
+ const header = context && context.agent && context.agent.session ? context.agent.session.header : null
116
+ const sid = header ? header.id : null
117
+ if (!sid) return null
118
+ const sections = ((downstream && downstream.sections) || []).filter((s) => !isFgSection(s && s.name))
119
+ return hostTracker.note(sid, sections)
120
+ }
121
+
122
+ /**
123
+ * 观测器:必须是 `system-prompt/assemble` 上**最先注册**的监听器。
124
+ * Cordis waterfall 按注册顺序 outermost-first(`cbs[0]` 最先跑,`next()` 继续),
125
+ * 先注册才能看到 `next()` 返回的**最终装配**——否则像 cost 段那样由别的监听器
126
+ * 在 `next()` 之后追加,观测点只能看到半截(2026-10-29 修)。
127
+ */
128
+ export function prefixObserverListener() {
129
+ return async (assembly, context, next) => {
130
+ const downstream = await next()
131
+ try {
132
+ notePrefixShift(context, downstream, [])
133
+ } catch {
134
+ /* 指纹失败不影响装配 */
135
+ }
136
+ try {
137
+ noteHostShift(context, downstream)
138
+ } catch {
139
+ /* 宿主段诊断失败不影响装配 */
140
+ }
141
+ return downstream
142
+ }
143
+ }
144
+
145
+ // 导出给测试:接线本身(观测监听器 + 跟踪器)必须能被单独验证,
146
+ // 否则"审计会不会真的写"只能靠跑真宿主才知道。
147
+ export { notePrefixShift, prefixTracker }
23
148
 
24
149
  export const name = 'focus-guard'
25
150
  // 2026-10-18:`ctx.tools` 是 Cordis 服务,未声明 inject 就访问会抛
@@ -45,9 +170,45 @@ export function apply(ctx) {
45
170
  }
46
171
  }
47
172
 
48
- register('tools/pre-execute', preExecuteListener, 'tools/pre-execute')
173
+ // 按需自证(Lazy Liveness,2026-10-19):存活状态只在这一刻对模型可见——
174
+ // 判定返回 deny/ask 时,给理由补一个 `[FG 存活 n/m]` 徽标(异常时带降级模块名)。
175
+ // 其余时候(放行、正常回合)零注入:心跳只写 status.json。
176
+ // 2026-10-22(人类反馈"工作流没做好"):再叠一层「重复被拦」改写——同一条调用第 2 次被拒时,
177
+ // 理由改成"重试无效 + 该换哪条路",抑制实测中"拦了还重试"多出来的 step。
178
+ const withLivenessBadge = (factory) => (opts) => {
179
+ const base = factory(opts)
180
+ return async (exec, next) => {
181
+ let decision = await base(exec, next)
182
+ if (decision && decision.kind === 'deny') {
183
+ try {
184
+ decision = augmentDeny(exec, decision, warn)
185
+ } catch (error) {
186
+ warn('重复被拦改写失败(不影响判定):', (error && error.message) || error)
187
+ }
188
+ }
189
+ if (decision && (decision.kind === 'deny' || decision.kind === 'ask')) {
190
+ const reason = String(decision.reason || '')
191
+ if (!reason.includes('[FG 存活')) return { ...decision, reason: `${reason} ${livenessBadge()}` }
192
+ }
193
+ return decision
194
+ }
195
+ }
196
+
197
+ // 2026-10-19 人类批示:AUDIT.log 补 turn/step 元数据(熔断浪费按会话独立计数)。
198
+ // 位置只有 `agent/pre-step` 拿得到,注册 provider 后所有审计行自动带 turn/step;
199
+ // 回合结束时由 recordFuseWaste 结算"熔断后步数"。失败只降级可观测性,不影响执法缝。
200
+ try {
201
+ installTraceMeta()
202
+ } catch (error) {
203
+ warn('位置元数据装配失败(审计仍写,只是没有 turn/step):', (error && error.message) || error)
204
+ }
205
+
206
+ register('tools/pre-execute', withLivenessBadge(preExecuteListener), 'tools/pre-execute')
49
207
  // 3.0.8 移植批 5:结构性执法(图书馆隔离/环境规则/大小写冲突/子代理闸/熔断白名单/L2·L5)
50
- register('tools/pre-execute', preGuardListener, 'tools/pre-execute(structural)')
208
+ register('tools/pre-execute', withLivenessBadge(preGuardListener), 'tools/pre-execute(structural)')
209
+ // 前缀抖动观测:必须最先注册(waterfall outermost-first)——它的 next() 才返回最终装配,
210
+ // 能看到 cost / rules / workspace / fuse 全部 FG 段。
211
+ register('system-prompt/assemble', prefixObserverListener, 'system-prompt/assemble(prefix-observer)')
51
212
  register('system-prompt/assemble', systemPromptListener, 'system-prompt/assemble')
52
213
  // 3.0.8 移植批 4:常驻规则注入(guard.mjs 的 SESSION_RULES,原文走 stdout,原生改走注入缝)
53
214
  // 2026-10-18:再包一层——启动自检缺模块时追加 `focus-guard-degraded` 段,让模型自己也看得见。
@@ -60,20 +221,30 @@ export function apply(ctx) {
60
221
  if (!downstream || !Array.isArray(downstream.sections)) return downstream
61
222
  /** @type {{name: string, text: string}[]} */
62
223
  const extra = []
63
- const note = livenessNote()
64
- if (note) extra.push({ name: 'focus-guard-degraded', text: note })
65
- // L4 跨会话卷宗(2026-10-18):只有 workspace_hash 与当前路径一致才注入;
224
+ // 2026-10-19 按需自证:存活状态不再进系统提示(原 focus-guard-degraded 段已移除)。
225
+ // 需要知道 FG 是否在场时,看拦截理由 / fg_apply 返回里的 `[FG 存活 n/m]` 徽标。
226
+ // L4 跨会话卷宗(2026-10-18)+ 快速交接(2026-10-22):只有 workspace_hash 与当前路径一致才注入;
66
227
  // 路径改变 → readWorkspace 返回 null → 一条都不加(DCR 的病根就是没这条)。
228
+ // 交接快照行只在"换会话"时出现(同一会话里重复自己的快照是噪音)。
67
229
  try {
68
- const cwd =
69
- context && context.agent && context.agent.session && context.agent.session.header
70
- ? context.agent.session.header.cwd
71
- : null
72
- const section = renderWorkspaceSection(readWorkspace(cwd))
230
+ const header =
231
+ context && context.agent && context.agent.session ? context.agent.session.header : null
232
+ const cwd = header ? header.cwd : null
233
+ const sid = header ? header.id : null
234
+ const section = renderWorkspaceSectionOnce(readWorkspace(cwd), { sid })
73
235
  if (section) extra.push({ name: 'focus-guard-workspace', text: section })
236
+ // 熔断告知(2026-10-27):熔断此前只写 warn(日志),模型完全看不见——
237
+ // 实测 turn 128 熔断后仍白走 16 步只读探索。这里在熔断期间追加固定文案,
238
+ // 让模型在下一次请求就知道该收尾。文案固定 → 前缀只变一次,不会每步抖动。
239
+ if (sid) {
240
+ const st = loadState(statePath(sid))
241
+ if (st && st.fused) extra.push({ name: 'focus-guard-fuse', text: FUSE_NOTICE })
242
+ }
74
243
  } catch {
75
244
  /* fail-open:卷宗读取失败不影响系统提示 */
76
245
  }
246
+ // 前缀稳定性(2026-10-29):观测已移到最外层 prefixObserverListener——
247
+ // 这里不再自算,否则内层看不到 cost 段会每步误报。
77
248
  if (!extra.length) return downstream
78
249
  return { ...downstream, sections: [...downstream.sections, ...extra] }
79
250
  }
@@ -86,6 +257,59 @@ export function apply(ctx) {
86
257
  // 3.0.8:补上 guard.mjs 六缝中 DSH 侧缺失的三条。映射照官方桥
87
258
  //(@deepseek-ai/dsh-hooks-claude-code)的实测代码,不是猜测。
88
259
  register('agent/created', sessionStartListener, 'agent/created')
260
+ // 「只报不改」自检缝模板(2026-11-08):策略可达性 / 钩子顺序 / 工具类别三段此前各抄一遍
261
+ // 同样的 try/catch + `next` 透传(三处 11 行重复块),差异只有「跑什么」和「失败怎么措辞」。
262
+ // 纪律不变:只 warn、不改任何判定、只跑一次。
263
+ const selfCheck = (name, label, run) =>
264
+ register(
265
+ 'agent/created',
266
+ () => async (payload, next) => {
267
+ try {
268
+ await run()
269
+ } catch (error) {
270
+ warn(`${label}失败(不影响执法):`, (error && error.message) || error)
271
+ }
272
+ return typeof next === 'function' ? next(payload) : undefined
273
+ },
274
+ `agent/created(${name})`,
275
+ )
276
+ // 策略可达性自检(2026-10-24):用当前会话真实工具 schema 校验判定里引用的参数键,
277
+ // 报警式(warn + 审计),不改变任何判定。只跑一次,失败 sink 到 warn。
278
+ selfCheck('policy-audit', '策略可达性自检', async () => {
279
+ const tools = ctx.tools && typeof ctx.tools.schemas === 'function' ? ctx.tools.schemas() : []
280
+ const { runPolicyAudit } = await import('./policy-audit.mjs')
281
+ const { ghost, reachable, scanned } = runPolicyAudit({
282
+ schemas: tools,
283
+ files: [new URL('./pipeline.mjs', import.meta.url).pathname, new URL('./preGuard.mjs', import.meta.url).pathname],
284
+ ignore: ['cmd', 'script', 'pages', 'head_limit', 'output_mode'],
285
+ })
286
+ if (ghost.length) {
287
+ warn(`策略可达性自检:${ghost.length}/${scanned} 个参数键在真实 schema 里不存在(规则可能永不触发)——` +
288
+ ghost.map((g) => g.key).join('、'))
289
+ } else if (scanned > 0) {
290
+ warn(`策略可达性自检:${scanned} 个参数键全部可达(工具 ${tools.length} 个)`)
291
+ }
292
+ void reachable
293
+ })
294
+ // 钩子顺序自检(2026-10-29):Cordis 的 waterfall 按注册顺序派发,互不相关的插件之间
295
+ // 顺序不确定。**不能**用 @zfdx123/dsh-hooks-ordering 的 participant 接口解决——它的
296
+ // runPhase 丢弃返回值,而 FG 的拦截正是靠 `return {kind:'deny'}`(核查全文见
297
+ // `packages/core/docs/HOOK-ORDERING.md`;实测数据见 CHANGELOG「FG 自己做定序者」条目)。
298
+ // 这里只观测:协调器在不在、FG 在不在参与者列表里。只报不改,与 policy-audit 同纪律。
299
+ selfCheck('hook-order', '钩子顺序自检', async () => {
300
+ const { probeHookOrdering } = await import('./hookOrder.mjs')
301
+ const verdict = probeHookOrdering(ctx)
302
+ warn(`钩子顺序[${verdict.state}]:${verdict.message}`)
303
+ })
304
+ // 工具类别覆盖自检(2026-10-29):装了插件却没在适配层登记语义类别 → 熔断期被误拒、
305
+ // 且调用算执行池而不是侦查池。只报 MCP 前缀(内置工具的欠账由 tool-kinds.mjs 自己补),
306
+ // 只 warn 不改判定,与 policy-audit / hook-order 同纪律。
307
+ selfCheck('tool-kinds', '工具类别自检', async () => {
308
+ const tools = ctx.tools && typeof ctx.tools.schemas === 'function' ? ctx.tools.schemas() : []
309
+ const { auditToolKinds, renderToolKindNotice } = await import('./toolKindAudit.mjs')
310
+ const notice = renderToolKindNotice(auditToolKinds({ schemas: tools }))
311
+ if (notice) warn(notice)
312
+ })
89
313
  register('agent/pre-step', preStepListener, 'agent/pre-step')
90
314
  // 回合结束自动落账(L4,2026-10-18):只记 FG 亲眼看到的事实(人类指令 / 被人否决的命令),
91
315
  // 不推断、不编造;写失败只 warn。与 DCR 不同:这里不 cancel、不 reject、不碰 surface。
@@ -100,6 +324,13 @@ export function apply(ctx) {
100
324
  } catch (error) {
101
325
  warn('工作区卷宗写入失败(不阻断回合):', (error && error.message) || error)
102
326
  }
327
+ // 熔断浪费结算(2026-10-19 人类批示,按会话独立计数):
328
+ // 只在本回合真熔断过时写一行 fuse-waste,正常回合零写入。
329
+ try {
330
+ recordFuseWaste(payload && payload.agent)
331
+ } catch (error) {
332
+ warn('熔断浪费结算失败(不阻断回合):', (error && error.message) || error)
333
+ }
103
334
  return decision
104
335
  }
105
336
  },
@@ -133,10 +364,11 @@ export function apply(ctx) {
133
364
  warn('心跳启动失败(不影响执法缝):', (error && error.message) || error)
134
365
  }
135
366
 
136
- // 启动自检汇总(2026-10-18):缺模块就在宿主日志喊一次;模型侧由上面那条注入缝负责。
367
+ // 启动自检汇总(2026-10-19 按需自证):缺模块只在宿主日志喊一次。
368
+ // 模型侧**不再常驻注入** FG-DEGRADED 段——改为在"拦截 / fg_apply / 压缩事件"三处附 `livenessBadge()`。
137
369
  const missing = degradedModules()
138
370
  if (missing.length > 0) {
139
- warn(`启动自检:${missing.length} 个模块未报到 —— ${missing.join('、')}(模型侧会收到 FG-DEGRADED 段)`)
371
+ warn(`启动自检:${missing.length} 个模块未报到 —— ${missing.join('、')}(不注入 Prompt;将在拦截/申请时附带徽标)`)
140
372
  }
141
373
 
142
374
  // 启动自证(2026-10-18):无条件往 AUDIT.log 写一条 compaction-watch-ready / -degraded。