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
@@ -9,13 +9,22 @@
9
9
  * 职责分工:pipeline 那条记成本台账;本条做进度/预算/污染/考核。
10
10
  *
11
11
  * 工具名适配(DSH 与 ZCode 命名不同):
12
- * ZCode: Read/Write/Edit/Grep/Bash/Agent → DSH: read/write/edit/grep/pwsh|bash/subagent
12
+ * ZCode: Read/Write/Edit/Grep/Bash/Agent → DSH: read/write/edit/grep|pwsh|bash/subagent
13
13
  * 故一律用大小写不敏感匹配;子代理同时认 'agent' 与 'subagent'。
14
14
  * 入参适配:DSH 的 post-execute 签名是 `(exec, result, next)`,
15
15
  * 对应 guard.mjs 的 `input.tool_response` 是这里的 result、`input.tool_name` 是 exec.name、
16
16
  * `input.tool_input` 是 exec.arguments。
17
17
  *
18
18
  * 纪律:任何异常只 warn,绝不断开 DSH 主流程;写状态走 saveState(原子落盘)。
19
+ *
20
+ * ── 2026-10-27 按段拆分(brooks-lint 判 Divergent Change)──
21
+ * 原先 `postProgressListener` 是单个 320 行闭包,按段落顺序堆放 7 个互不相干的职责
22
+ * (预算 / 上下文污染 / 巨量输出追责 / 子代理摘要 / 强制委派 KPI / 抽查A / 抽查B),
23
+ * 共用 `reason` 一个短路变量——改任一职责都要读完全部前序短路条件。
24
+ * 现抽成 9 个命名函数(7 个产出 reason,2 个只落状态),监听器退化为顺序调用 + 首个非空即短路。
25
+ *
26
+ * **如实申报:这次拆分不降行数**(320 → 约 340,多出的是每段的签名、ctx 解构与段落注释)。
27
+ * 收益是**可测性与可读性**:每段可单独喂 ctx 断言,不再需要构造一整个 exec/result 才能碰到某条判定。
19
28
  */
20
29
  import { statSync } from 'node:fs'
21
30
  import { statePath as guardStateFile, loadState, saveState, fingerprint, gitDirty, casePath, loadCaseRecords, saveCaseRecords } from '../core/state.mjs'
@@ -23,27 +32,10 @@ import { auditChainInit } from '../core/audit.mjs'
23
32
  import { collectStrings, callHash, isInvestigation } from '../core/risk.mjs'
24
33
  import { zcodeToolName } from './toolName.mjs'
25
34
  import { isDangerousCmd, SCRIPT_FILE_RE } from '../core/redlines.mjs'
26
- import { appendAudit } from './audit.mjs'
27
-
28
- /**
29
- * 本地 audit:**签名与母版一致**(sid, action, { level, evidence }),但落点走 DSH 侧统一入口。
30
- *
31
- * 为什么不直接用母版 `audit`:它按 `auditTarget()` 落盘,优先读 `ZCODE_PROJECT_DIR` /
32
- * `CLAUDE_PROJECT_DIR`——在 DSH 下后者被设置,于是**会写真实工作区的 `.focus-guard/AUDIT.log`**
33
- *(测试亦然,会重演此前修过的测试污染)。DSH 侧必须统一经 `appendAudit`:它尊重 `FG_AUDIT_FILE`
34
- * 且带体积轮转。
35
- */
36
- const audit = (sid, action, opts = {}) =>
37
- appendAudit({
38
- ts: new Date().toISOString(),
39
- session: sid,
40
- seq: Date.now().toString(36) + '.' + Math.floor(performance.now()),
41
- action,
42
- trigger: action,
43
- level: opts.level ?? null,
44
- evidence: String(opts.evidence || '').slice(0, 200),
45
- pardon: !!opts.pardon,
46
- })
35
+ import { appendAudit, buildAuditRow } from './audit.mjs'
36
+ import { normalizePath as normalize, projDirOf, sidOf } from './sessionScope.mjs'
37
+ import { gateSwitch } from './testRuntime.mjs'
38
+ import { budgetVerdict, stallVerdict, invPoolOverLimit, judgeProgress, poolOf } from '../core/progressPolicy.mjs'
47
39
  import {
48
40
  BLOCKS_RE,
49
41
  BUDGET_CAP,
@@ -53,35 +45,398 @@ import {
53
45
  INV_POOL_DEFAULT,
54
46
  OUTPUT_GATE_BYTES,
55
47
  RANDOM_AUDIT_EVERY,
48
+ RANDOM_FUSE_MAX,
49
+ RANDOM_FUSE_MIN,
56
50
  REFILL,
57
51
  STALL_FUSE,
58
52
  } from '../core/constants.mjs'
59
53
 
54
+ /**
55
+ * 本地 audit:**签名与母版一致**(sid, action, { level, evidence }),但落点走 DSH 侧统一入口。
56
+ *
57
+ * 为什么不直接用母版 `audit`:它按 `auditTarget()` 落盘,优先读 `ZCODE_PROJECT_DIR` /
58
+ * `CLAUDE_PROJECT_DIR`——在 DSH 下后者被设置,于是**会写真实工作区的 `.focus-guard/AUDIT.log`**
59
+ *(测试亦然,会重演此前修过的测试污染)。DSH 侧必须统一经 `appendAudit`:它尊重 `FG_AUDIT_FILE`
60
+ * 且带体积轮转。
61
+ */
62
+ const audit = (sid, action, opts = {}) => appendAudit(buildAuditRow(sid, action, opts))
63
+
64
+ /**
65
+ * 反规避抽查B 的间隔解析(2026-10-19 人类批示:独立参数,勿与抽查A 耦合)。
66
+ *
67
+ * - **默认开启**(2026-10-19 晚人类批示):间隔在 [2,5] 次写操作之间随机;`FG_RANDOM_FUSE=0` 关闭
68
+ * - 抽查A(`RANDOM_AUDIT_EVERY`)是"确定性每 5 次全量审计";抽查B 是"不可预测的检查点",两回事
69
+ * - `FG_RANDOM_FUSE_EVERY=N` 固定间隔,优先级高于随机(运维/测试用)
70
+ * - 返回 null = 关闭;否则给 `pick()` 与 `kind`,便于测试断言区间
71
+ */
72
+ export function randomFuseInterval() {
73
+ if (!gateSwitch('FG_RANDOM_FUSE')) return null
74
+ const fixed = Number(process.env.FG_RANDOM_FUSE_EVERY)
75
+ if (Number.isInteger(fixed) && fixed > 0) return { kind: 'fixed', n: fixed, pick: () => fixed }
76
+ const span = RANDOM_FUSE_MAX - RANDOM_FUSE_MIN + 1
77
+ return { kind: 'random', pick: () => RANDOM_FUSE_MIN + Math.floor(Math.random() * span) }
78
+ }
79
+
60
80
  const RE_WRITE = /^(?:write|edit|multiedit)$/i
61
81
  const RE_READ = /^(?:read|notebookread)$/i
62
82
  const RE_GREP = /^grep$/i
63
83
  const RE_BASH = /^(?:pwsh|bash|shell|bash-persistent|pwsh-persistent)$/i
64
84
  const RE_AGENT = /^(?:agent|subagent)$/i
65
85
 
66
- /** 会话标识与工作目录:与 seams.mjs 同口径(agent.session.header.*)。 */
67
- function sidOf(exec) {
68
- const a = exec && exec.agent
86
+ // 段 1/9 · 取证销账(只落状态,不产出 reason)
87
+
88
+ /** 取证销账:一次成功调查解除强制取证。 */
89
+ function settleForcedInvestigate(ctx) {
90
+ const { sid, tool, ti, isFail, state } = ctx
91
+ if (state.forcedInvestigate && !isFail && isInvestigation(tool, ti)) {
92
+ state.forcedInvestigate = false
93
+ audit(sid, 'L2-cleared', { level: 2, evidence: `${tool} 取证完成` })
94
+ }
95
+ }
96
+
97
+ // 段 2/9 · 本回合已读/已写集合 + 卷宗取证指纹(只落状态)
98
+
99
+ /** 本回合已读/已写集合 + 卷宗取证指纹(供 TTL 与免重读)。 */
100
+ function trackReadSet(ctx) {
101
+ const { exec, tool, ti, isFail, state } = ctx
102
+ if (isFail) return
103
+ state.readSet = state.readSet || {}
104
+ if (ti.file_path && (RE_READ.test(tool) || RE_WRITE.test(tool))) state.readSet[normalize(ti.file_path)] = 1
105
+ if (RE_WRITE.test(tool) && ti.file_path && SCRIPT_FILE_RE.test(String(ti.file_path))) {
106
+ state.scriptFiles = state.scriptFiles || {}
107
+ const body = String(ti.content ?? '') + String(ti.old_string ?? '') + String(ti.new_string ?? '')
108
+ state.scriptFiles[normalize(ti.file_path)] = isDangerousCmd(body) ? 'd' : 'c'
109
+ }
110
+ if (RE_GREP.test(tool) && typeof ti.path === 'string') state.readSet[normalize(ti.path)] = 1
111
+ // 卷宗【三】取证记录(指纹 + TTL 依据)。3.0.5:派生积木不进卷宗
112
+ if (RE_READ.test(tool) && ti.file_path && !BLOCKS_RE.test(String(ti.file_path))) {
113
+ try {
114
+ const fp = fingerprint(ti.file_path)
115
+ const key = normalize(ti.file_path)
116
+ const cc = state.caseCache || {}
117
+ const prev = cc[key]
118
+ const changedFp = !!(
119
+ prev &&
120
+ (prev.mtime !== fp.mtime || prev.size !== fp.size || (prev.sha && fp.sha && prev.sha !== fp.sha))
121
+ )
122
+ cc[key] = {
123
+ path: ti.file_path,
124
+ mtime: fp.mtime,
125
+ size: fp.size,
126
+ sha: fp.sha || '',
127
+ gitDirty: fp.sha ? null : gitDirty(projDirOf(exec), ti.file_path),
128
+ readAt: Date.now(),
129
+ changes: (prev ? prev.changes || 0 : 0) + (changedFp ? 1 : 0),
130
+ lastChange: prev ? (changedFp ? Date.now() : prev.lastChange || 0) : 0,
131
+ ttlOverride: prev ? prev.ttlOverride || '' : '',
132
+ via: fp.sha ? 'mtime+size+sha' : 'mtime+size+git',
133
+ }
134
+ state.caseCache = cc
135
+ const ccKeys = Object.keys(cc)
136
+ if (ccKeys.length > CASE_MAX_ROWS) {
137
+ ccKeys.sort((a, b) => (cc[a].readAt || 0) - (cc[b].readAt || 0))
138
+ for (const k of ccKeys.slice(0, ccKeys.length - CASE_MAX_ROWS)) delete cc[k]
139
+ }
140
+ const pDir = projDirOf(exec)
141
+ if (pDir) saveCaseRecords(pDir, { ...loadCaseRecords(casePath(pDir)), ...cc })
142
+ } catch {
143
+ /* 指纹/卷宗失败不阻断 */
144
+ }
145
+ }
146
+ }
147
+
148
+ // 段 3/9 · 动态预算:进度检测 + 三池记账 + 熔断/续杯/侦查池
149
+
150
+ /**
151
+ * 进度与三池核算。
152
+ *
153
+ * 判定全部来自母版 `core/progressPolicy.mjs`(阶段 2 第一/第二刀):本函数只算签名、落计数、
154
+ * 写审计、给提示。行为细节(刻意保留原语义):
155
+ * - 侦查池超限会**覆盖**同一次调用里已产生的续杯/熔断 reason——原实现如此,未改;
156
+ * - 工具失败(`isFail`)时 `progress` 恒为 false,走停滞分支,因此失败也计入 `ineffCalls`。
157
+ */
158
+ /** 进度判定:失败调用不算进度;签名(响应前 1500 字 + 入参哈希)变化即算。 */
159
+ function detectProgress({ tool, ti, isFail, state, respText }) {
160
+ if (isFail) return false
161
+ const contentSig = respText.slice(0, 1500)
162
+ const inputSig = callHash({ tool_name: tool, tool_input: ti })
163
+ const progress = judgeProgress({
164
+ isWrite: RE_WRITE.test(tool),
165
+ respSig: contentSig,
166
+ inputSig,
167
+ prevRespSig: state.lastSig,
168
+ prevInputSig: state.lastInput,
169
+ })
170
+ state.lastSig = contentSig
171
+ state.lastInput = inputSig
172
+ return progress
173
+ }
174
+
175
+ function judgeBudgetPools(ctx) {
176
+ const { sid, tool, ti, isFail, state, inv, respText, guardDeny } = ctx
177
+ // 2026-10-28(熔断太容易):闸门拒绝不是"模型空转"——它是**判定生效**。
178
+ // 原实现把 deny 当失败 → 无 progress → stalledStreak+1,连改 3 个被拦文件就熔断。
179
+ // 被拒调用对进度与停滞都记中性(不 += 也不清零),由 repeatGuard 的换法提示负责纠偏。
180
+ if (guardDeny) return null
181
+ const progress = detectProgress({ tool, ti, isFail, state, respText })
182
+
183
+ let reason = null
184
+ if (progress) {
185
+ // 池归属来自母版 `poolOf`(阶段 2 第二刀):三池分立的语义在母版,本文件只落计数。
186
+ const pool = poolOf({ isDelegation: RE_AGENT.test(tool), isInvestigation: inv })
187
+ state.stalledStreak = 0
188
+ if (pool === 'investigate') state.invCalls = (state.invCalls || 0) + 1
189
+ else if (pool === 'execute') state.effectiveCalls = (state.effectiveCalls || 0) + 1
190
+ // 判定来自母版 `core/progressPolicy.mjs`(阶段 2):本文件只做落状态 + 审计 + 提示。
191
+ const budget = budgetVerdict({
192
+ effectiveCalls: state.effectiveCalls || 0,
193
+ taskBudget: state.taskBudget || BUDGET_DEFAULT,
194
+ cap: BUDGET_CAP,
195
+ refill: REFILL,
196
+ })
197
+ if (budget.kind === 'fuse') {
198
+ // 2026-10-27 修(审计重复记账):`effectiveCalls >= cap` 一旦成立就永远成立,
199
+ // 原来每次调用都再写一条 `stall-fuse`——实测同一会话写了 61 条"硬上限:有效调用达 200",
200
+ // 而真实熔断只发生 1 次。日志虚高会让所有基于它的判断失真(测量工具本身没被测量)。
201
+ // 只在「从未熔断 → 熔断」的跃迁点记账;重复期间静默。
202
+ const firstFuse = !state.fused
203
+ state.fused = true
204
+ state.violations = Math.max(state.violations || 0, 3)
205
+ if (firstFuse) {
206
+ audit(sid, 'stall-fuse', { level: 3, evidence: `硬上限:有效调用达 ${BUDGET_CAP}` })
207
+ reason = `[触发④·L3]硬上限 ${BUDGET_CAP} 次,强制熔断。输出『${FUSE_PHRASE}』+三行降级方案,等批示。`
208
+ }
209
+ } else if (budget.kind === 'refill') {
210
+ state.taskBudget = budget.nextBudget
211
+ audit(sid, 'budget-extend', {
212
+ level: null,
213
+ evidence: `自动续杯 budget=${state.taskBudget} eff=${state.effectiveCalls} stall=0`,
214
+ })
215
+ reason = `[触发④]续杯:执行池 ${state.effectiveCalls} 次达阈值,预算+${REFILL}→${state.taskBudget}。任务继续,自查是否收敛。`
216
+ }
217
+ if (inv && !state.invWarned && invPoolOverLimit({ invCalls: state.invCalls || 0, invCap: state.invCap || INV_POOL_DEFAULT })) {
218
+ state.invWarned = true
219
+ audit(sid, 'inv-pool-exceeded', {
220
+ level: null,
221
+ evidence: `20条 侦查池超限 inv=${state.invCalls}/${state.invCap || INV_POOL_DEFAULT}`,
222
+ })
223
+ reason = `[20条]侦查池(${state.invCap || INV_POOL_DEFAULT}次)超限。汇总证据请示追加(『追加额度』+10),或交子代理压缩侦查成本。`
224
+ }
225
+ } else {
226
+ state.stalledStreak = (state.stalledStreak || 0) + 1
227
+ state.ineffCalls = (state.ineffCalls || 0) + 1
228
+ if (stallVerdict({ stalledStreak: state.stalledStreak || 0, threshold: STALL_FUSE }).fuse) {
229
+ // 2026-10-27 修(审计重复记账):判据是 `stalledStreak >= 3`,而熔断后 stalledStreak 不清零
230
+ // → 越线之后每一次无效调用都再写一条 stall-fuse。实测 10-18 07:58:25~07:59:01 一秒内写了
231
+ // 17 条(连续 3/4/5/…/19 次),把 1 次熔断记成 17 次。只在跃迁点记账。
232
+ const firstFuse = !state.fused
233
+ state.fused = true
234
+ state.violations = Math.max(state.violations || 0, 3)
235
+ if (firstFuse) {
236
+ audit(sid, 'stall-fuse', {
237
+ level: 3,
238
+ evidence: `连续 ${state.stalledStreak} 次无效调用 eff=${state.effectiveCalls || 0}`,
239
+ })
240
+ reason = `[触发④·L3]真失控:连续 ${state.stalledStreak} 次无效调用。停止探索,输出『${FUSE_PHRASE}』+三行降级方案,或等批示。`
241
+ }
242
+ } else if ((state.stalledStreak || 0) === STALL_FUSE - 1) {
243
+ audit(sid, 'stall-warning', {
244
+ level: null,
245
+ evidence: `停滞 ${state.stalledStreak} 次 eff=${state.effectiveCalls || 0}`,
246
+ })
247
+ reason = `[触发④]停滞预警:连续 ${state.stalledStreak} 次无效,再有一次即熔断。换有证据的方法,或结束回合发【信用延期】请批示。`
248
+ }
249
+ }
250
+ return reason
251
+ }
252
+
253
+ // 段 4/9 · 58条 上下文污染检测(批 2 的消费侧在此闭环)
254
+
255
+ /** 输出与指令矛盾:head N 行实得更多 / 清单出现不可能的重复路径。 */
256
+ function detectCtxPollution(ctx) {
257
+ const { sid, tool, ti, isFail, state, respText } = ctx
258
+ if (isFail || !RE_BASH.test(tool)) return null
259
+ let reason = null
260
+ const cmd = String(ti.command || '')
261
+ const outLines = respText.split('\n').filter((l) => l.trim() !== '')
262
+ // 2.5.3(案三):输出对账只对单条语句有意义;复合命令跳过分段对账,宁宽勿严。
263
+ const stmts = cmd.split(/[;&\n]+/).map((s) => s.trim()).filter(Boolean)
264
+ if (stmts.length === 1) {
265
+ const hm = cmd.match(/\bhead\s+(?:-n\s*(\d{1,6})|-(\d{1,6}))\b/)
266
+ if (hm) {
267
+ const n = parseInt(hm[1] || hm[2], 10)
268
+ if (n > 0 && outLines.length > n) {
269
+ state.pollutionFlagged = true
270
+ audit(sid, 'ctx-pollution', {
271
+ level: null,
272
+ evidence: `58条 行数超限 head ${n} → 实际 ${outLines.length} 行 | ${cmd.slice(0, 60)}`,
273
+ })
274
+ reason = `[38条·上下文污染]输出与指令矛盾:head ${n} 行实得 ${outLines.length}。停用本次输出,echo MARK-X 隔离核实并报告人类。`
275
+ }
276
+ }
277
+ if (!reason && /\b(find|git\s+(ls-files|ls-tree))\b/.test(cmd)) {
278
+ const seen = new Set()
279
+ let dup = ''
280
+ for (const l of outLines) {
281
+ if (seen.has(l)) {
282
+ dup = l
283
+ break
284
+ }
285
+ const tok = l.trim().split(/\s+/)[0] || ''
286
+ if (/[/\\]/.test(tok) && !/[::]$/.test(tok)) seen.add(l)
287
+ }
288
+ if (dup) {
289
+ state.pollutionFlagged = true
290
+ audit(sid, 'ctx-pollution', {
291
+ level: null,
292
+ evidence: `58条 路径重复 ${dup.slice(0, 80)} | ${cmd.slice(0, 50)}`,
293
+ })
294
+ reason = `[38条·上下文污染]清单出现不可能的重复路径(${dup.slice(0, 60)})。停用本次输出,echo MARK-X 隔离核实并报告人类。`
295
+ }
296
+ }
297
+ }
298
+ return reason
299
+ }
300
+
301
+ // 段 5/9 · 巨量输出事后追责
302
+
303
+ /** 巨量输出事后追责。注意:原实现**不看 isFail**(失败的巨量输出同样要追责),此处保持。 */
304
+ function scoldDump(ctx) {
305
+ const { sid, tool, state, respProbe } = ctx
306
+ if (!(RE_BASH.test(tool) || RE_GREP.test(tool))) return null
307
+ if (respProbe.total <= OUTPUT_GATE_BYTES) return null
308
+ state.dumpCount = (state.dumpCount || 0) + 1
309
+ audit(sid, 'scold-dump', { level: null, evidence: `${tool} 输出 ${Math.round(respProbe.total / 1024)}KB` })
310
+ return `体积刺客:${tool} 输出 ${Math.round(respProbe.total / 1024)}KB 已入上下文。下次先 head/tail/wc/grep 过滤(累计 ${state.dumpCount} 次)。`
311
+ }
312
+
313
+ // 段 6/9 · 子代理摘要格式校验
314
+
315
+ /** 只收【子代理摘要】,≤200 字,五段字段齐全;合格 +3、不合格 -3。 */
316
+ function checkDelegateSummary(ctx) {
317
+ const { sid, tool, isFail, state, respText } = ctx
318
+ if (isFail || !RE_AGENT.test(tool)) return null
319
+ const sumText = respText
320
+ const fmtOk =
321
+ /【子代理摘要】/.test(sumText) &&
322
+ /任务[::]/.test(sumText) &&
323
+ /结果[::]/.test(sumText) &&
324
+ /异常[::]/.test(sumText) &&
325
+ /文件线索[::]/.test(sumText)
326
+ if (!fmtOk || sumText.length > 200) {
327
+ state.kpi = (state.kpi || 0) - 3
328
+ audit(sid, 'delegate-summary-pollution', {
329
+ level: null,
330
+ evidence: `2.3.0 摘要污染 -3 len=${sumText.length} fmt=${fmtOk ? '有' : '无'}`,
331
+ })
332
+ return '[委派摘要拒收·KPI-3]超200字或缺字段,拒绝全量采纳。压缩为:【子代理摘要】任务:…|结果:≤5条|异常:…|文件线索:文件:行号,以此继续。'
333
+ }
334
+ state.kpi = (state.kpi || 0) + 3
335
+ audit(sid, 'kpi-summary-good', { level: null, evidence: `2.3.0 委派摘要合格 +3 len=${sumText.length}` })
336
+ return null
337
+ }
338
+
339
+ // 段 7/9 · 强制委派场景检测(该委派不委派 → KPI-5;已委派 → KPI+5 一次)
340
+
341
+ /** 识别三类强制委派场景:全库搜索 / 大文档摘要 / 批量文件处理。 */
342
+ function detectForcedDelegation(ctx) {
343
+ const { sid, tool, ti, isFail, state, respText } = ctx
344
+ if (isFail) return null
345
+ const scLines = respText.split('\n').map((l) => l.trim()).filter(Boolean)
346
+ const scPaths = scLines.filter((l) => /[/\\]/.test(l) && l.length <= 200 && !/^(total|\.\.?|d[-rwx]|-[-rwx])/.test(l))
347
+ const scDirs = new Set(scPaths.map((l) => l.replace(/[/\\][^/\\]*$/, '')))
348
+ let scenario = ''
349
+ if (RE_GREP.test(tool) || (RE_BASH.test(tool) && /\b(find|rg|grep)\b/i.test(String(ti.command || '')))) {
350
+ if (scPaths.length >= 10 || scDirs.size >= 3) scenario = '全库搜索'
351
+ } else if (RE_READ.test(tool) && ti.file_path) {
352
+ let kb = 0
353
+ try {
354
+ kb = statSync(ti.file_path).size / 1024
355
+ } catch {
356
+ kb = 0
357
+ }
358
+ if (kb > OUTPUT_GATE_BYTES / 1024 || scLines.length > 2000) scenario = '大文档摘要'
359
+ } else if (RE_WRITE.test(tool) && ti.file_path) {
360
+ state.editedFiles = state.editedFiles || {}
361
+ state.editedFiles[normalize(ti.file_path)] = 1
362
+ if (Object.keys(state.editedFiles).length >= 5) scenario = '批量文件处理'
363
+ }
364
+ if (!scenario) return null
365
+ if (state.delegated) {
366
+ if (!state.kpiDelegatedAwarded) {
367
+ state.kpiDelegatedAwarded = true
368
+ state.kpi = (state.kpi || 0) + 5
369
+ audit(sid, 'kpi-delegated', { level: null, evidence: `2.3.0 强制场景已委派 +5 ${scenario}` })
370
+ }
371
+ return null
372
+ }
373
+ state.kpiScolded = state.kpiScolded || {}
374
+ const key = scenario === '全库搜索' ? 'search' : scenario === '大文档摘要' ? 'bigdoc' : 'batch'
375
+ if (state.kpiScolded[key]) return null
376
+ state.kpiScolded[key] = true
377
+ state.kpi = (state.kpi || 0) - 5
378
+ audit(sid, 'kpi-not-delegated', { level: null, evidence: `2.3.0 强制场景未委派 -5 ${scenario}` })
69
379
  return (
70
- (a && ((a.session && a.session.header && a.session.header.id) || a.sessionId || a.id)) ||
71
- (exec && exec.sessionId) ||
72
- 'dsh-native'
380
+ `[未尽职·KPI-5]${scenario}属强制委派场景(≥3目录/≥10文件、>50KB或>2000行、≥5文件批量、并行任务),本任务未委派过。` +
381
+ `改用 Agent 委派,只回【子代理摘要】;特例需向人类说明。`
73
382
  )
74
383
  }
75
- function projDirOf(exec) {
76
- const a = exec && exec.agent
77
- return (a && a.session && a.session.header && a.session.header.cwd) || process.cwd()
384
+
385
+ // 段 8/9 · 抽查A:每 5 次写操作全量审计 1 次(确定性节奏,不是随机抽样)
386
+
387
+ /** 抽查A:确定性节奏的留痕。 */
388
+ function spotCheckA(ctx) {
389
+ const { sid, tool, ti, isFail, state } = ctx
390
+ if (isFail || !RE_WRITE.test(tool)) return null
391
+ state.writeOps = (state.writeOps || 0) + 1
392
+ if (state.writeOps % RANDOM_AUDIT_EVERY !== 0) return null
393
+ audit(sid, 'random-audit', {
394
+ level: null,
395
+ evidence: `第 ${state.writeOps} 次写操作全量审计 ${normalize(ti.file_path)}`,
396
+ })
397
+ return `抽查A:第 ${state.writeOps} 次写操作已留痕。确认有锚点([文件:行号]),无则补【假设】。`
398
+ }
399
+
400
+ // 段 9/9 · 抽查B:反规避随机检查点(只挂检查点,不产出 reason)
401
+
402
+ /**
403
+ * 抽查B(2026-10-19;与抽查A 的 RANDOM_AUDIT_EVERY **完全独立**)。
404
+ *
405
+ * 目的:让"何时被检查"不可预测,"攒着批量绕过"无法规划。
406
+ * 触发时机只能是 post-execute(那次写已经发生),所以这里只**挂检查点**:
407
+ * pre-execute 第 3 层只清 pending、**默认不打断**(2026-10-27 改;旧"拒一次"语义保留在
408
+ * `FG_RANDOM_FUSE_BLOCK=1`)。因此本段**不产出 reason**。
409
+ */
410
+ function spotCheckB(ctx) {
411
+ const { sid, tool, isFail, state } = ctx
412
+ if (isFail || !RE_WRITE.test(tool)) return
413
+ const fuseInterval = randomFuseInterval()
414
+ if (!fuseInterval) return
415
+ state.fuseOps = (state.fuseOps || 0) + 1
416
+ const nextAt = Number(state.fuseNextAt) || 0
417
+ if (nextAt <= 0) {
418
+ // 第一轮先定阈值,不在本轮就触发(否则"2-5 次"会退化成"第一次就查")
419
+ state.fuseNextAt = state.fuseOps + fuseInterval.pick()
420
+ return
421
+ }
422
+ if (state.fuseOps < nextAt) return
423
+ const gap = state.fuseOps - nextAt
424
+ state.randomFusePending = true
425
+ state.randomFuseAt = state.fuseOps
426
+ state.fuseNextAt = state.fuseOps + fuseInterval.pick()
427
+ audit(sid, 'random-fuse', {
428
+ level: null,
429
+ evidence: `反规避抽查B:第 ${state.fuseOps} 次写操作命中随机检查点(间隔 ${fuseInterval.kind === 'fixed' ? fuseInterval.n : '2-5 随机'}${gap > 0 ? `,超出阈值 ${gap} 次` : ''})`,
430
+ })
78
431
  }
79
- const normalize = (p) => String(p || '').replace(/\\/g, '/')
80
432
 
81
433
  /**
82
434
  * post-execute 进度与执法缝。
83
435
  * 对应 guard.mjs 的 `post`(工具成功后)与 `postfail`(工具失败后)两种语义——
84
436
  * DSH 侧没有独立的失败缝,故用 `result` 是否含 error 判定。
437
+ *
438
+ * 顺序即优先级:前一段产出 reason 后,后续段一律跳过(原实现的 `!reason` 短路)。
439
+ * 唯一的例外是段 9(抽查B)——它不产出 reason,故放在最后且**只在无 reason 时**执行。
85
440
  */
86
441
  export function postProgressListener({ warn } = {}) {
87
442
  return async (exec, result, next) => {
@@ -90,11 +445,12 @@ export function postProgressListener({ warn } = {}) {
90
445
  const tool = String((exec && exec.name) || '')
91
446
  const ti = (exec && exec.arguments) || {}
92
447
  const isFail = !!(result && (result.error || result.isError))
448
+ // FG 的 deny 也走 error 形状;必须与"真失败"分开,否则闸门越严越容易熔断。
449
+ const guardDeny = isFail && /focus-guard-native/.test(String((result && (result.error || result.message)) || ''))
93
450
  const file = guardStateFile(sid)
94
451
  const state = loadState(file)
95
452
  auditChainInit(state)
96
453
 
97
- let reason = null
98
454
  state.turnCount = (state.turnCount || 0) + 1
99
455
 
100
456
  // 响应内容单次采样:进度/污染/追责/摘要/强制场景五处共用
@@ -102,255 +458,25 @@ export function postProgressListener({ warn } = {}) {
102
458
  if (!isFail) collectStrings(result ?? {}, respProbe, 200000)
103
459
  const respText = respProbe.parts.join('\n')
104
460
 
105
- // 取证销账:一次成功调查解除强制取证
106
- if (state.forcedInvestigate && !isFail && isInvestigation(tool, ti)) {
107
- state.forcedInvestigate = false
108
- audit(sid, 'L2-cleared', { level: 2, evidence: `${tool} 取证完成` })
109
- }
110
-
111
- // ── 本回合已读/已写集合 + 卷宗取证指纹(供 TTL 与免重读)──
112
- if (!isFail) {
113
- state.readSet = state.readSet || {}
114
- if (ti.file_path && (RE_READ.test(tool) || RE_WRITE.test(tool))) state.readSet[normalize(ti.file_path)] = 1
115
- if (RE_WRITE.test(tool) && ti.file_path && SCRIPT_FILE_RE.test(String(ti.file_path))) {
116
- state.scriptFiles = state.scriptFiles || {}
117
- const body = String(ti.content ?? '') + String(ti.old_string ?? '') + String(ti.new_string ?? '')
118
- state.scriptFiles[normalize(ti.file_path)] = isDangerousCmd(body) ? 'd' : 'c'
119
- }
120
- if (RE_GREP.test(tool) && typeof ti.path === 'string') state.readSet[normalize(ti.path)] = 1
121
- // 卷宗【三】取证记录(指纹 + TTL 依据)。3.0.5:派生积木不进卷宗
122
- if (RE_READ.test(tool) && ti.file_path && !BLOCKS_RE.test(String(ti.file_path))) {
123
- try {
124
- const fp = fingerprint(ti.file_path)
125
- const key = normalize(ti.file_path)
126
- const cc = state.caseCache || {}
127
- const prev = cc[key]
128
- const changedFp = !!(
129
- prev &&
130
- (prev.mtime !== fp.mtime || prev.size !== fp.size || (prev.sha && fp.sha && prev.sha !== fp.sha))
131
- )
132
- cc[key] = {
133
- path: ti.file_path,
134
- mtime: fp.mtime,
135
- size: fp.size,
136
- sha: fp.sha || '',
137
- gitDirty: fp.sha ? null : gitDirty(projDirOf(exec), ti.file_path),
138
- readAt: Date.now(),
139
- changes: (prev ? prev.changes || 0 : 0) + (changedFp ? 1 : 0),
140
- lastChange: prev ? (changedFp ? Date.now() : prev.lastChange || 0) : 0,
141
- ttlOverride: prev ? prev.ttlOverride || '' : '',
142
- via: fp.sha ? 'mtime+size+sha' : 'mtime+size+git',
143
- }
144
- state.caseCache = cc
145
- const ccKeys = Object.keys(cc)
146
- if (ccKeys.length > CASE_MAX_ROWS) {
147
- ccKeys.sort((a, b) => (cc[a].readAt || 0) - (cc[b].readAt || 0))
148
- for (const k of ccKeys.slice(0, ccKeys.length - CASE_MAX_ROWS)) delete cc[k]
149
- }
150
- const pDir = projDirOf(exec)
151
- if (pDir) saveCaseRecords(pDir, { ...loadCaseRecords(casePath(pDir)), ...cc })
152
- } catch {
153
- /* 指纹/卷宗失败不阻断 */
154
- }
155
- }
156
- }
157
-
158
- // ── 动态预算:进度检测引擎 ──
159
- let progress = false
160
- if (!isFail) {
161
- const contentSig = respText.slice(0, 1500)
162
- const inputSig = callHash({ tool_name: tool, tool_input: ti })
163
- progress = RE_WRITE.test(tool) || contentSig !== (state.lastSig ?? '') || inputSig !== (state.lastInput ?? '')
164
- state.lastSig = contentSig
165
- state.lastInput = inputSig
166
- }
167
-
168
461
  // ⚠ 母版 isInvestigation 按 ZCode 命名判定(Read/Grep/Glob/Bash),DSH 传小写 → 必须归一化。
169
462
  // 未归一化时只读调用恒被判为"非侦查",于是全部计入 effectiveCalls:侦查池永不满、
170
463
  // 执行池被只读调用提前耗尽(2026-10-10 由批 5 的用例连带抓出本批缺陷)。
171
464
  const inv = isInvestigation(zcodeToolName(tool), ti)
172
- if (progress) {
173
- if (RE_AGENT.test(tool)) {
174
- state.stalledStreak = 0 // 委派不占主会话执行池(委托池在 pre 核算)
175
- } else if (inv) {
176
- state.invCalls = (state.invCalls || 0) + 1
177
- state.stalledStreak = 0
178
- } else {
179
- state.effectiveCalls = (state.effectiveCalls || 0) + 1
180
- state.stalledStreak = 0
181
- }
182
- if ((state.effectiveCalls || 0) >= BUDGET_CAP) {
183
- state.fused = true
184
- state.violations = Math.max(state.violations || 0, 3)
185
- audit(sid, 'stall-fuse', { level: 3, evidence: `硬上限:有效调用达 ${BUDGET_CAP}` })
186
- reason = `[触发④·L3]硬上限 ${BUDGET_CAP} 次,强制熔断。输出『${FUSE_PHRASE}』+三行降级方案,等批示。`
187
- } else if ((state.effectiveCalls || 0) >= (state.taskBudget || BUDGET_DEFAULT)) {
188
- state.taskBudget = Math.min((state.taskBudget || BUDGET_DEFAULT) + REFILL, BUDGET_CAP)
189
- audit(sid, 'budget-extend', {
190
- level: null,
191
- evidence: `自动续杯 budget=${state.taskBudget} eff=${state.effectiveCalls} stall=0`,
192
- })
193
- reason = `[触发④]续杯:执行池 ${state.effectiveCalls} 次达阈值,预算+${REFILL}→${state.taskBudget}。任务继续,自查是否收敛。`
194
- }
195
- if (inv && !state.invWarned && (state.invCalls || 0) > (state.invCap || INV_POOL_DEFAULT)) {
196
- state.invWarned = true
197
- audit(sid, 'inv-pool-exceeded', {
198
- level: null,
199
- evidence: `20条 侦查池超限 inv=${state.invCalls}/${state.invCap || INV_POOL_DEFAULT}`,
200
- })
201
- reason = `[20条]侦查池(${state.invCap || INV_POOL_DEFAULT}次)超限。汇总证据请示追加(『追加额度』+10),或交子代理压缩侦查成本。`
202
- }
203
- } else {
204
- state.stalledStreak = (state.stalledStreak || 0) + 1
205
- state.ineffCalls = (state.ineffCalls || 0) + 1
206
- if ((state.stalledStreak || 0) >= STALL_FUSE) {
207
- state.fused = true
208
- state.violations = Math.max(state.violations || 0, 3)
209
- audit(sid, 'stall-fuse', {
210
- level: 3,
211
- evidence: `连续 ${state.stalledStreak} 次无效调用 eff=${state.effectiveCalls || 0}`,
212
- })
213
- reason = `[触发④·L3]真失控:连续 ${state.stalledStreak} 次无效调用。停止探索,输出『${FUSE_PHRASE}』+三行降级方案,或等批示。`
214
- } else if ((state.stalledStreak || 0) === STALL_FUSE - 1) {
215
- audit(sid, 'stall-warning', {
216
- level: null,
217
- evidence: `停滞 ${state.stalledStreak} 次 eff=${state.effectiveCalls || 0}`,
218
- })
219
- reason = `[触发④]停滞预警:连续 ${state.stalledStreak} 次无效,再有一次即熔断。换有证据的方法,或结束回合发【信用延期】请批示。`
220
- }
221
- }
222
465
 
223
- // ── 58条 上下文污染检测(批 2 的消费侧在此闭环)──
224
- if (!reason && !isFail && RE_BASH.test(tool)) {
225
- const cmd = String(ti.command || '')
226
- const outLines = respText.split('\n').filter((l) => l.trim() !== '')
227
- // 2.5.3(案三):输出对账只对单条语句有意义;复合命令跳过分段对账,宁宽勿严。
228
- const stmts = cmd.split(/[;&\n]+/).map((s) => s.trim()).filter(Boolean)
229
- if (stmts.length === 1) {
230
- const hm = cmd.match(/\bhead\s+(?:-n\s*(\d{1,6})|-(\d{1,6}))\b/)
231
- if (hm) {
232
- const n = parseInt(hm[1] || hm[2], 10)
233
- if (n > 0 && outLines.length > n) {
234
- state.pollutionFlagged = true
235
- audit(sid, 'ctx-pollution', {
236
- level: null,
237
- evidence: `58条 行数超限 head ${n} → 实际 ${outLines.length} 行 | ${cmd.slice(0, 60)}`,
238
- })
239
- reason = `[38条·上下文污染]输出与指令矛盾:head ${n} 行实得 ${outLines.length}。停用本次输出,echo MARK-X 隔离核实并报告人类。`
240
- }
241
- }
242
- if (!reason && /\b(find|git\s+(ls-files|ls-tree))\b/.test(cmd)) {
243
- const seen = new Set()
244
- let dup = ''
245
- for (const l of outLines) {
246
- if (seen.has(l)) {
247
- dup = l
248
- break
249
- }
250
- const tok = l.trim().split(/\s+/)[0] || ''
251
- if (/[/\\]/.test(tok) && !/[::]$/.test(tok)) seen.add(l)
252
- }
253
- if (dup) {
254
- state.pollutionFlagged = true
255
- audit(sid, 'ctx-pollution', {
256
- level: null,
257
- evidence: `58条 路径重复 ${dup.slice(0, 80)} | ${cmd.slice(0, 50)}`,
258
- })
259
- reason = `[38条·上下文污染]清单出现不可能的重复路径(${dup.slice(0, 60)})。停用本次输出,echo MARK-X 隔离核实并报告人类。`
260
- }
261
- }
262
- }
263
- }
264
-
265
- // 巨量输出事后追责
266
- if (!reason && (RE_BASH.test(tool) || RE_GREP.test(tool))) {
267
- if (respProbe.total > OUTPUT_GATE_BYTES) {
268
- state.dumpCount = (state.dumpCount || 0) + 1
269
- audit(sid, 'scold-dump', { level: null, evidence: `${tool} 输出 ${Math.round(respProbe.total / 1024)}KB` })
270
- reason = `体积刺客:${tool} 输出 ${Math.round(respProbe.total / 1024)}KB 已入上下文。下次先 head/tail/wc/grep 过滤(累计 ${state.dumpCount} 次)。`
271
- }
272
- }
466
+ const ctx = { exec, sid, tool, ti, isFail, guardDeny, state, respText, respProbe, inv }
273
467
 
274
- // ── 子代理摘要格式校验(只收【子代理摘要】,≤200字)──
275
- if (!reason && !isFail && RE_AGENT.test(tool)) {
276
- const sumText = respText
277
- const fmtOk =
278
- /【子代理摘要】/.test(sumText) &&
279
- /任务[::]/.test(sumText) &&
280
- /结果[::]/.test(sumText) &&
281
- /异常[::]/.test(sumText) &&
282
- /文件线索[::]/.test(sumText)
283
- if (!fmtOk || sumText.length > 200) {
284
- state.kpi = (state.kpi || 0) - 3
285
- audit(sid, 'delegate-summary-pollution', {
286
- level: null,
287
- evidence: `2.3.0 摘要污染 -3 len=${sumText.length} fmt=${fmtOk ? '有' : '无'}`,
288
- })
289
- reason =
290
- '[委派摘要拒收·KPI-3]超200字或缺字段,拒绝全量采纳。压缩为:【子代理摘要】任务:…|结果:≤5条|异常:…|文件线索:文件:行号,以此继续。'
291
- } else {
292
- state.kpi = (state.kpi || 0) + 3
293
- audit(sid, 'kpi-summary-good', { level: null, evidence: `2.3.0 委派摘要合格 +3 len=${sumText.length}` })
294
- }
295
- }
468
+ settleForcedInvestigate(ctx)
469
+ trackReadSet(ctx)
296
470
 
297
- // ── 强制委派场景检测(该委派不委派 → KPI-5;已委派 → KPI+5 一次)──
298
- if (!reason && !isFail) {
299
- const scLines = respText.split('\n').map((l) => l.trim()).filter(Boolean)
300
- const scPaths = scLines.filter((l) => /[/\\]/.test(l) && l.length <= 200 && !/^(total|\.\.?|d[-rwx]|-[-rwx])/.test(l))
301
- const scDirs = new Set(scPaths.map((l) => l.replace(/[/\\][^/\\]*$/, '')))
302
- let scenario = ''
303
- if (
304
- RE_GREP.test(tool) ||
305
- (RE_BASH.test(tool) && /\b(find|rg|grep)\b/i.test(String(ti.command || '')))
306
- ) {
307
- if (scPaths.length >= 10 || scDirs.size >= 3) scenario = '全库搜索'
308
- } else if (RE_READ.test(tool) && ti.file_path) {
309
- let kb = 0
310
- try {
311
- kb = statSync(ti.file_path).size / 1024
312
- } catch {
313
- kb = 0
314
- }
315
- if (kb > OUTPUT_GATE_BYTES / 1024 || scLines.length > 2000) scenario = '大文档摘要'
316
- } else if (RE_WRITE.test(tool) && ti.file_path) {
317
- state.editedFiles = state.editedFiles || {}
318
- state.editedFiles[normalize(ti.file_path)] = 1
319
- if (Object.keys(state.editedFiles).length >= 5) scenario = '批量文件处理'
320
- }
321
- if (scenario) {
322
- if (state.delegated) {
323
- if (!state.kpiDelegatedAwarded) {
324
- state.kpiDelegatedAwarded = true
325
- state.kpi = (state.kpi || 0) + 5
326
- audit(sid, 'kpi-delegated', { level: null, evidence: `2.3.0 强制场景已委派 +5 ${scenario}` })
327
- }
328
- } else {
329
- state.kpiScolded = state.kpiScolded || {}
330
- const key = scenario === '全库搜索' ? 'search' : scenario === '大文档摘要' ? 'bigdoc' : 'batch'
331
- if (!state.kpiScolded[key]) {
332
- state.kpiScolded[key] = true
333
- state.kpi = (state.kpi || 0) - 5
334
- audit(sid, 'kpi-not-delegated', { level: null, evidence: `2.3.0 强制场景未委派 -5 ${scenario}` })
335
- reason =
336
- `[未尽职·KPI-5]${scenario}属强制委派场景(≥3目录/≥10文件、>50KB或>2000行、≥5文件批量、并行任务),本任务未委派过。` +
337
- `改用 Agent 委派,只回【子代理摘要】;特例需向人类说明。`
338
- }
339
- }
340
- }
341
- }
471
+ let reason =
472
+ judgeBudgetPools(ctx) ||
473
+ detectCtxPollution(ctx) ||
474
+ scoldDump(ctx) ||
475
+ checkDelegateSummary(ctx) ||
476
+ detectForcedDelegation(ctx) ||
477
+ spotCheckA(ctx)
342
478
 
343
- // ── 抽查A:每 5 次写操作全量审计 1 次(确定性节奏,不是随机抽样)──
344
- if (!reason && !isFail && RE_WRITE.test(tool)) {
345
- state.writeOps = (state.writeOps || 0) + 1
346
- if (state.writeOps % RANDOM_AUDIT_EVERY === 0) {
347
- audit(sid, 'random-audit', {
348
- level: null,
349
- evidence: `第 ${state.writeOps} 次写操作全量审计 ${normalize(ti.file_path)}`,
350
- })
351
- reason = `抽查A:第 ${state.writeOps} 次写操作已留痕。确认有锚点([文件:行号]),无则补【假设】。`
352
- }
353
- }
479
+ if (!reason) spotCheckB(ctx)
354
480
 
355
481
  saveState(file, state)
356
482
  if (reason && typeof warn === 'function') warn('事后执法:', reason)