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
@@ -24,45 +24,24 @@ import { backupBeforeEdit } from '../core/backup.mjs'
24
24
  import { platformBashViolation } from '../core/env.mjs'
25
25
  import { isDangerousCmd } from '../core/redlines.mjs'
26
26
  import { isInvestigation, isMutating, penalize } from '../core/risk.mjs'
27
+ import '../adapters/dsh/tool-kinds.mjs' // 分层纪律:宿主工具名在适配层注册成语义类别
27
28
  import { zcodeToolName } from './toolName.mjs'
28
- import { appendAudit } from './audit.mjs'
29
+ import { appendAudit, buildAuditRow } from './audit.mjs'
30
+ import { normalizePath as normalize, projDirOf, sidOf } from './sessionScope.mjs'
29
31
  import { BLOCKS_RE, DELEGATE_DEFAULT, DOWNGRADE_MSG, LIBRARY_RE } from '../core/constants.mjs'
30
32
 
31
33
  const RE_WRITE = /^(?:write|edit|multiedit)$/i
32
34
  const RE_READ = /^(?:read|notebookread)$/i
33
- const RE_GREP = /^grep$/i
34
35
  const RE_BASH = /^(?:pwsh|bash|shell|bash-persistent|pwsh-persistent)$/i
35
- const RE_AGENT = /^(?:agent|subagent)$/i
36
+ // 委派类工具(2026-10-22 补口):此前只认 `agent|subagent`,而 DSH 原生还有
37
+ // `subagent_fork`、`spawn_teammate`(Agent Teams)、`summon_expert(s)` / `summon_expert_team`(Agency 专家团)。
38
+ // 它们全部绕过子代理闸 → 委托池(默认 20 次)从未被扣、熔断期也不拦,KPI 的奖惩因此空转。
39
+ const RE_AGENT =
40
+ /^(?:agent|task|subagent|subagent_fork|spawn_teammate|summon_expert|summon_experts|summon_expert_team)$/i
36
41
  const RE_SEARCH = /^(?:grep|glob|fs-search|search)$/i
37
42
 
38
- /** 会话标识 / 工作目录:与其余 DSH 模块同口径。 */
39
- function sidOf(exec) {
40
- const a = exec && exec.agent
41
- return (
42
- (a && ((a.session && a.session.header && a.session.header.id) || a.sessionId || a.id)) ||
43
- (exec && exec.sessionId) ||
44
- 'dsh-native'
45
- )
46
- }
47
- function projDirOf(exec) {
48
- const a = exec && exec.agent
49
- return (a && a.session && a.session.header && a.session.header.cwd) || process.cwd()
50
- }
51
- const normalize = (p) => String(p || '').replace(/\\/g, '/')
52
43
 
53
- const audit = (sid, action, opts = {}) =>
54
- appendAudit({
55
- ts: new Date().toISOString(),
56
- session: sid,
57
- seq: Date.now().toString(36) + '.' + Math.floor(performance.now()),
58
- action,
59
- trigger: opts.trigger || action,
60
- chain: opts.chain || null,
61
- ref: opts.ref || null,
62
- level: opts.level ?? null,
63
- evidence: String(opts.evidence || '').slice(0, 200),
64
- pardon: !!opts.pardon,
65
- })
44
+ const audit = (sid, action, opts = {}) => appendAudit(buildAuditRow(sid, action, opts))
66
45
 
67
46
  /** 处罚阶梯说明(原 approval.mjs 的 ladderNote:与审批单无关,是"降级阶梯"提示)。 */
68
47
  function ladderNote(level) {
@@ -73,213 +52,255 @@ function ladderNote(level) {
73
52
  return '(L2:下次改动类调用须先取证)'
74
53
  }
75
54
 
76
- /**
77
- * pre-execute 补充执法缝(`tools/pre-execute`)。
78
- * 返回 deny 决策以拦截;返回 next() 透传下游。
79
- */
80
- export function preGuardListener({ warn } = {}) {
81
- return async (exec, next) => {
82
- try {
83
- const sid = sidOf(exec)
84
- const tool = String((exec && exec.name) || '')
85
- const ti = (exec && exec.arguments) || {}
86
- const rawPath = ti.file_path || ti.path || ti.target || ''
87
- const filePath = rawPath ? normalize(rawPath) : ''
88
- const cmd = RE_BASH.test(tool) ? String(ti.command || '') : ''
89
- // ⚠ 母版判定按 ZCode 命名(Read/Write/Bash/Agent),DSH 传小写 → 必须先归一化,
90
- // 否则只读工具不被认成只读、改动类不被认成改动(静默判错,非漏拦)。
91
- const ztool = zcodeToolName(tool)
92
- const handoff = /HANDOFF\.md$/i.test(String(filePath))
93
- const search = RE_SEARCH.test(tool)
94
- const file = guardStateFile(sid)
95
- const state = loadState(file)
96
- const env = state.envCache || null
55
+ /** 透传下游哨兵:与 deny 判定区分(熔断期只读放行必须继续 next())。 */
56
+ const THROUGH = Symbol('through')
97
57
 
98
- // ===== 资料分层隔离:静态资料区与派生积木区均不得直写(防自我投毒)=====
99
- if (RE_WRITE.test(tool) && filePath && (LIBRARY_RE.test(filePath) || BLOCKS_RE.test(filePath))) {
100
- audit(sid, 'library-write-deny', { evidence: `静态资料区直写被拒 ${filePath}` })
101
- return {
102
- kind: 'deny',
103
- reason:
104
- `focus-guard-native: [图书馆·隔离]${filePath} 属静态资料区/派生积木区,不得直写。` +
105
- `外部原文走同步三步(旧版归档 → 覆盖 → 写 frontmatter),派生积木由 library-build 生成到 .ai/output/library(防自我投毒)。`,
106
- }
107
- }
58
+ /** 收集本次调用所需上下文;state 只读一份,后续段共用同一引用。 */
59
+ function collectContext(exec) {
60
+ const sid = sidOf(exec)
61
+ const tool = String((exec && exec.name) || '')
62
+ const ti = (exec && exec.arguments) || {}
63
+ const rawPath = ti.file_path || ti.path || ti.target || ''
64
+ const filePath = rawPath ? normalize(rawPath) : ''
65
+ const file = guardStateFile(sid)
66
+ const state = loadState(file)
67
+ return {
68
+ exec,
69
+ sid,
70
+ tool,
71
+ ti,
72
+ rawPath,
73
+ filePath,
74
+ cmd: RE_BASH.test(tool) ? String(ti.command || '') : '',
75
+ // ⚠ 母版判定按 ZCode 命名(Read/Write/Bash/Agent),DSH 传小写 → 必须先归一化,
76
+ // 否则只读工具不被认成只读、改动类不被认成改动(静默判错,非漏拦)。
77
+ ztool: zcodeToolName(tool),
78
+ handoff: /HANDOFF\.md$/i.test(String(filePath)),
79
+ search: RE_SEARCH.test(tool),
80
+ file,
81
+ state,
82
+ env: state.envCache || null,
83
+ }
84
+ }
108
85
 
109
- // ===== 环境规则检查(平台命令拦截)=====
110
- // 与第 1.5 层的区别:环境指纹管"本机有更好替代"(ls→eza),本层管"平台本身不兼容"。
111
- if (cmd) {
112
- const v = platformBashViolation(env, cmd)
113
- if (v) {
114
- audit(sid, 'platform-deny', {
115
- evidence: `${env ? env.os + '/' + env.shellIdKey : 'unknown'} ${v.slice(0, 100)}`,
116
- })
117
- return {
118
- kind: 'deny',
119
- reason: `focus-guard-native: [平台规则·${env ? env.os + '/' + env.shellIdKey : '?'}]${v}`,
120
- }
121
- }
122
- }
86
+ /** ===== 资料分层隔离:静态资料区与派生积木区均不得直写(防自我投毒)===== */
87
+ function checkLibraryWrite({ sid, tool, filePath }) {
88
+ if (!RE_WRITE.test(tool) || !filePath) return null
89
+ if (!LIBRARY_RE.test(filePath) && !BLOCKS_RE.test(filePath)) return null
90
+ audit(sid, 'library-write-deny', { evidence: `静态资料区直写被拒 ${filePath}` })
91
+ return {
92
+ kind: 'deny',
93
+ reason:
94
+ `focus-guard-native: [图书馆·隔离]${filePath} 属静态资料区/派生积木区,不得直写。` +
95
+ `外部原文走同步三步(旧版归档 → 覆盖 → 写 frontmatter),派生积木由 library-build 生成到 .ai/output/library(防自我投毒)。`,
96
+ }
97
+ }
123
98
 
124
- // ===== 大小写不敏感文件系统:禁仅大小写不同的重名文件 =====
125
- // 注意:不敏感 FS 上大小写变体目标的 existsSync 恒为 true,故不能以 existsSync 豁免。
126
- if (RE_WRITE.test(tool) && rawPath && env && env.caseSensitive === false) {
127
- try {
128
- const dirp = dirname(rawPath)
129
- const base = basename(rawPath)
130
- const clash = readdirSync(dirp).find((e) => e !== base && e.toLowerCase() === base.toLowerCase())
131
- if (clash) {
132
- audit(sid, 'platform-deny', { evidence: `2.0平台 大小写冲突 ${base} vs ${clash}` })
133
- return {
134
- kind: 'deny',
135
- reason:
136
- `focus-guard-native: [平台规则·大小写冲突]本文件系统大小写不敏感:${base} 与已有 ${clash} 仅大小写不同,` +
137
- `创建后会互相覆盖。改名,或改用现有文件。`,
138
- }
139
- }
140
- } catch {
141
- /* 目录不可读 → 跳过该检查 */
142
- }
143
- }
99
+ /** ===== 环境规则检查(平台命令拦截)===== */
100
+ // 与第 1.5 层的区别:环境指纹管"本机有更好替代"(ls→eza),本层管"平台本身不兼容"。
101
+ function checkPlatformCommand({ sid, cmd, env }) {
102
+ if (!cmd) return null
103
+ const v = platformBashViolation(env, cmd)
104
+ if (!v) return null
105
+ audit(sid, 'platform-deny', {
106
+ evidence: `${env ? env.os + '/' + env.shellIdKey : 'unknown'} ${v.slice(0, 100)}`,
107
+ })
108
+ return {
109
+ kind: 'deny',
110
+ reason: `focus-guard-native: [平台规则·${env ? env.os + '/' + env.shellIdKey : '?'}]${v}`,
111
+ }
112
+ }
144
113
 
145
- // ===== 子代理闸:越权绕行边界 + 48 条继承留痕 + 蜂群因果子链 + 委托池消耗 =====
146
- if (RE_AGENT.test(tool)) {
147
- // 仅熔断期启动子代理属违规(L4 记档 + L5 降权);正常委派放行且不计违规
148
- if (state.fused) {
149
- state.violations = Math.max(state.violations || 0, 4)
150
- const lvl = penalize(
151
- state,
152
- sid,
153
- 'violation-subagent-usurp',
154
- `56条 熔断期启动子代理 ${String(ti.description || ti.prompt || '').slice(0, 60)}`,
155
- )
156
- saveState(file, state)
157
- return {
158
- kind: 'deny',
159
- reason:
160
- `focus-guard-native: [越权绕行·L${lvl}]熔断期启动子代理执行被禁操作:L4 记档+L5 降权。` +
161
- `只读可亲自查,或等批示。${ladderNote(lvl)}`,
162
- }
163
- }
164
- // 48条 子代理继承留痕:父会话处分状态随派单记录(平台无注入通道,以留痕方式移交)
165
- const spawnSeq = audit(sid, 'subagent-spawn', {
166
- evidence: `48条 父状态 fused=${!!state.fused} L${state.violations || 0} eff=${state.effectiveCalls || 0} inv=${state.invCalls || 0} | ${String(ti.description || ti.prompt || '').slice(0, 60)}`,
167
- })
168
- // 3.0.0 蜂群因果链:每次委派派生子链 /dN,ref 指回派单事件
169
- state.childChainN = (state.childChainN || 0) + 1
170
- const childChain = (state.taskChain || sid) + '/d' + state.childChainN
171
- // 委托池独立核算(不占执行池;用尽须人类批示追加)
172
- if ((state.delegateBudget ?? DELEGATE_DEFAULT) <= 0) {
173
- audit(sid, 'delegate-exhausted', { evidence: `2.3.0 委托池用尽 剩余=0 累计=${state.delegateUsed || 0}` })
174
- return {
175
- kind: 'deny',
176
- reason:
177
- 'focus-guard-native: [委托池用尽]子代理额度已用完(默认20次,独立于执行池)。' +
178
- '请批示『追加额度』(执行/侦查/委托三池各+10),或主会话自行收敛。',
179
- }
180
- }
181
- state.delegateBudget = (state.delegateBudget ?? DELEGATE_DEFAULT) - 1
182
- state.delegateUsed = (state.delegateUsed || 0) + 1
183
- state.delegated = true
184
- saveState(file, state)
185
- audit(sid, 'delegate-used', {
186
- chain: childChain,
187
- ref: spawnSeq,
188
- evidence: `2.3.0 委托池消耗 剩余=${state.delegateBudget} 累计=${state.delegateUsed} | ${String(ti.description || '').slice(0, 50)}`,
189
- })
190
- }
114
+ /** ===== 大小写不敏感文件系统:禁仅大小写不同的重名文件 ===== */
115
+ // 注意:不敏感 FS 上大小写变体目标的 existsSync 恒为 true,故不能以 existsSync 豁免。
116
+ function checkCaseClash({ sid, tool, rawPath, env }) {
117
+ if (!RE_WRITE.test(tool) || !rawPath || !env || env.caseSensitive !== false) return null
118
+ try {
119
+ const dirp = dirname(rawPath)
120
+ const base = basename(rawPath)
121
+ const clash = readdirSync(dirp).find((e) => e !== base && e.toLowerCase() === base.toLowerCase())
122
+ if (!clash) return null
123
+ audit(sid, 'platform-deny', { evidence: `2.0平台 大小写冲突 ${base} vs ${clash}` })
124
+ return {
125
+ kind: 'deny',
126
+ reason:
127
+ `focus-guard-native: [平台规则·大小写冲突]本文件系统大小写不敏感:${base} 与已有 ${clash} 仅大小写不同,` +
128
+ `创建后会互相覆盖。改名,或改用现有文件。`,
129
+ }
130
+ } catch {
131
+ /* 目录不可读 → 跳过该检查 */
132
+ return null
133
+ }
134
+ }
191
135
 
192
- // ===== 熔断期白名单:只读放行、改动拒绝;熔断期不是高危命令的免检通道 =====
193
- if (state.fused) {
194
- // 旧顺序曾让白名单先放行,于是 npm publish / shutil.rmtree 等"不在 MUTATING 表里"的
195
- // 高危命令被 isInvestigation 判成只读侦查而绕过审批——本分支保证该不变量在熔断期也成立。
196
- if (cmd && isDangerousCmd(cmd)) {
197
- audit(sid, 'deny-shuanggui-highrisk', { level: 3, evidence: `熔断期高危命令被拒 ${cmd.slice(0, 120)}` })
198
- return {
199
- kind: 'deny',
200
- reason:
201
- 'focus-guard-native: [熔断期·高危命令]熔断期只读放行不含高危命令。此类命令即使解熔也须先调 fg_apply,现在一律拒绝。',
202
- }
203
- }
204
- if (search || handoff || isInvestigation(ztool, ti)) return next()
205
- audit(sid, 'deny-shuanggui', { level: 3, evidence: `${tool} 熔断期改动类被拒` })
206
- return { kind: 'deny', reason: `focus-guard-native: ${DOWNGRADE_MSG}` }
207
- }
136
+ /** ===== 子代理闸:越权绕行边界 + 48 条继承留痕 + 蜂群因果子链 + 委托池消耗 ===== */
137
+ function gateSubagent({ sid, tool, ti, file, state }) {
138
+ if (!RE_AGENT.test(tool)) return null
139
+ // 仅熔断期启动子代理属违规(L4 记档 + L5 降权);正常委派放行且不计违规
140
+ if (state.fused) {
141
+ state.violations = Math.max(state.violations || 0, 4)
142
+ const lvl = penalize(
143
+ state,
144
+ sid,
145
+ 'violation-subagent-usurp',
146
+ `56条 熔断期启动子代理 ${String(ti.description || ti.prompt || '').slice(0, 60)}`,
147
+ )
148
+ saveState(file, state)
149
+ return {
150
+ kind: 'deny',
151
+ reason:
152
+ `focus-guard-native: [越权绕行·L${lvl}]熔断期启动子代理执行被禁操作:L4 记档+L5 降权。` +
153
+ `只读可亲自查,或等批示。${ladderNote(lvl)}`,
154
+ }
155
+ }
156
+ // 48条 子代理继承留痕:父会话处分状态随派单记录(平台无注入通道,以留痕方式移交)
157
+ const spawnSeq = audit(sid, 'subagent-spawn', {
158
+ evidence: `48条 父状态 fused=${!!state.fused} L${state.violations || 0} eff=${state.effectiveCalls || 0} inv=${state.invCalls || 0} | ${String(ti.description || ti.prompt || '').slice(0, 60)}`,
159
+ })
160
+ // 3.0.0 蜂群因果链:每次委派派生子链 /dN,ref 指回派单事件
161
+ state.childChainN = (state.childChainN || 0) + 1
162
+ const childChain = (state.taskChain || sid) + '/d' + state.childChainN
163
+ // 委托池独立核算(不占执行池;用尽须人类批示追加)
164
+ if ((state.delegateBudget ?? DELEGATE_DEFAULT) <= 0) {
165
+ audit(sid, 'delegate-exhausted', { evidence: `2.3.0 委托池用尽 剩余=0 累计=${state.delegateUsed || 0}` })
166
+ return {
167
+ kind: 'deny',
168
+ reason:
169
+ 'focus-guard-native: [委托池用尽]子代理额度已用完(默认20次,独立于执行池)。' +
170
+ '请批示『追加额度』(执行/侦查/委托三池各+10),或主会话自行收敛。',
171
+ }
172
+ }
173
+ state.delegateBudget = (state.delegateBudget ?? DELEGATE_DEFAULT) - 1
174
+ state.delegateUsed = (state.delegateUsed || 0) + 1
175
+ state.delegated = true
176
+ saveState(file, state)
177
+ audit(sid, 'delegate-used', {
178
+ chain: childChain,
179
+ ref: spawnSeq,
180
+ evidence: `2.3.0 委托池消耗 剩余=${state.delegateBudget} 累计=${state.delegateUsed} | ${String(ti.description || '').slice(0, 50)}`,
181
+ })
182
+ return null
183
+ }
208
184
 
209
- // ===== L2 强制取证 / L5 降权:改动类操作一律拒绝 =====
210
- if ((state.forcedInvestigate || state.probation) && isMutating(ztool, ti, handoff)) {
211
- const lvl = state.probation ? 5 : 2
212
- audit(sid, state.probation ? 'deny-L5-probation' : 'deny-L2-forced', {
213
- level: lvl,
214
- evidence: `${tool} ${filePath}`,
215
- })
216
- return {
217
- kind: 'deny',
218
- reason: state.probation
219
- ? 'focus-guard-native: [L5 降权]只读模式,改动类全拒,等人类批示。'
220
- : 'focus-guard-native: [L2 强制取证]下一调用必须是取证类,取证后自动解除。',
221
- }
222
- }
185
+ /** ===== 熔断期白名单:只读放行、改动拒绝;熔断期不是高危命令的免检通道 ===== */
186
+ function gateFused({ sid, tool, cmd, search, handoff, ti, ztool, state }) {
187
+ if (!state.fused) return null
188
+ // 旧顺序曾让白名单先放行,于是 npm publish / shutil.rmtree 等"不在 MUTATING 表里"的
189
+ // 高危命令被 isInvestigation 判成只读侦查而绕过审批——本分支保证该不变量在熔断期也成立。
190
+ if (cmd && isDangerousCmd(cmd)) {
191
+ audit(sid, 'deny-shuanggui-highrisk', { level: 3, evidence: `熔断期高危命令被拒 ${cmd.slice(0, 120)}` })
192
+ return {
193
+ kind: 'deny',
194
+ reason:
195
+ 'focus-guard-native: [熔断期·高危命令]熔断期只读放行不含高危命令。此类命令即使解熔也须先调 fg_apply,现在一律拒绝。',
196
+ }
197
+ }
198
+ if (search || handoff || isInvestigation(ztool, ti)) return THROUGH
199
+ audit(sid, 'deny-shuanggui', { level: 3, evidence: `${tool} 熔断期改动类被拒` })
200
+ return { kind: 'deny', reason: `focus-guard-native: ${DOWNGRADE_MSG}` }
201
+ }
223
202
 
224
- // ===== 总纲四:卷宗不重复读校验(跨回合)=====
225
- // 指纹一致(mtime+size+SHA/git)且 TTL 未超 → 拦免重读,复用已有取证;
226
- // 指纹不一致 / TTL 超时 → 放开,允许真重读(post 缝会更新卷宗指纹)。
227
- // 与第 3 层取证闸**语义相反**(那座闸管"没读就改",本闸管"读了还读"),二者不冲突:
228
- // 取证闸只对改动类生效(MUTATING_TOOL),本闸只对 Read 生效。
229
- // 熔断/强制取证期豁免(降级重建证据需真重读);offset 增量读永远放行。
230
- if (
231
- RE_READ.test(tool) &&
232
- rawPath &&
233
- !ti.offset &&
234
- !state.fused &&
235
- !state.forcedInvestigate &&
236
- !BLOCKS_RE.test(rawPath)
237
- ) {
238
- try {
239
- const rec = (state.caseCache || {})[filePath]
240
- if (rec) {
241
- const fp = fingerprint(rawPath)
242
- const pDir = projDirOf(exec)
243
- const dirty = fp.sha ? null : gitDirty(pDir, rawPath)
244
- const changed =
245
- rec.mtime !== fp.mtime ||
246
- rec.size !== fp.size ||
247
- (rec.sha && fp.sha && rec.sha !== fp.sha) ||
248
- (rec.gitDirty !== null && rec.gitDirty !== undefined && dirty !== null && dirty !== rec.gitDirty)
249
- if (!changed) {
250
- const ttl = resolveTTL(pDir, rec, rawPath)
251
- if (Date.now() - (rec.readAt || 0) < ttl.ms) {
252
- if (rec.inherited) {
253
- // 卷宗继承的指纹只提示不拦——本会话从未读过,内容不在上下文,拦首读即阻断取证
254
- audit(sid, 'casefile-inherit', { evidence: `2.0卷宗 继承指纹放行首读 ${filePath} ttl=${ttl.src}` })
255
- if (typeof warn === 'function') {
256
- warn('卷宗·提示:', `${filePath} 卷宗有近期取证(${ttl.src}),但本会话尚未读过——首读放行。`)
257
- }
258
- } else {
259
- audit(sid, 'casefile-hit', { evidence: `2.0卷宗 免重读 ${filePath} ttl=${ttl.src}` })
260
- return {
261
- kind: 'deny',
262
- reason:
263
- `focus-guard-native: [卷宗·免重读]${filePath} 指纹一致(${rec.via || 'mtime+size'})且 TTL 未超(${ttl.src}),` +
264
- `勿重复整读;需新内容用 offset 增量读或请批示。`,
265
- }
266
- }
267
- }
268
- }
269
- }
270
- } catch {
271
- /* 指纹/卷宗读取失败 → 放行真重读(fail-open,与全文件口径一致) */
272
- }
273
- }
203
+ /** ===== L2 强制取证 / L5 降权:改动类操作一律拒绝 ===== */
204
+ function gateDowngrade({ sid, tool, filePath, handoff, ti, ztool, state }) {
205
+ if (!(state.forcedInvestigate || state.probation)) return null
206
+ if (!isMutating(ztool, ti, handoff)) return null
207
+ const lvl = state.probation ? 5 : 2
208
+ audit(sid, state.probation ? 'deny-L5-probation' : 'deny-L2-forced', {
209
+ level: lvl,
210
+ evidence: `${tool} ${filePath}`,
211
+ })
212
+ return {
213
+ kind: 'deny',
214
+ reason: state.probation
215
+ ? 'focus-guard-native: [L5 降权]只读模式,改动类全拒,等人类批示。'
216
+ : 'focus-guard-native: [L2 强制取证]下一调用必须是取证类,取证后自动解除。',
217
+ }
218
+ }
219
+
220
+ /** 卷宗指纹是否变了(mtime / size / sha / git 脏位任一不一致)。 */
221
+ function casefileChanged(rec, fp, dirty) {
222
+ return (
223
+ rec.mtime !== fp.mtime ||
224
+ rec.size !== fp.size ||
225
+ (rec.sha && fp.sha && rec.sha !== fp.sha) ||
226
+ (rec.gitDirty !== null && rec.gitDirty !== undefined && dirty !== null && dirty !== rec.gitDirty)
227
+ )
228
+ }
274
229
 
275
- // ===== 74条:本次调用确定执行 → 备份改动前内容到 .ai/backup/(新文件无内容可备份,自动跳过)=====
276
- if (RE_WRITE.test(tool) && !handoff && rawPath) {
277
- try {
278
- backupBeforeEdit(rawPath, projDirOf(exec))
279
- } catch {
280
- audit(sid, 'note-fail', { evidence: `74条 改动前备份失败 ${filePath}` })
281
- }
230
+ /** ===== 总纲四:卷宗不重复读校验(跨回合)===== */
231
+ // 指纹一致(mtime+size+SHA/git)且 TTL 未超 → 拦免重读,复用已有取证;
232
+ // 指纹不一致 / TTL 超时 → 放开,允许真重读(post 缝会更新卷宗指纹)。
233
+ // 与第 3 层取证闸**语义相反**(那座闸管"没读就改",本闸管"读了还读"),二者不冲突:
234
+ // 取证闸只对改动类生效(MUTATING_TOOL),本闸只对 Read 生效。
235
+ // 熔断/强制取证期豁免(降级重建证据需真重读);offset 增量读永远放行。
236
+ function checkCasefileReread({ exec, sid, tool, ti, rawPath, filePath, state }, warn) {
237
+ if (!RE_READ.test(tool) || !rawPath || ti.offset) return null
238
+ if (state.fused || state.forcedInvestigate || BLOCKS_RE.test(rawPath)) return null
239
+ try {
240
+ const rec = (state.caseCache || {})[filePath]
241
+ if (!rec) return null
242
+ const fp = fingerprint(rawPath)
243
+ const pDir = projDirOf(exec)
244
+ const dirty = fp.sha ? null : gitDirty(pDir, rawPath)
245
+ if (casefileChanged(rec, fp, dirty)) return null
246
+ const ttl = resolveTTL(pDir, rec, rawPath)
247
+ if (Date.now() - (rec.readAt || 0) >= ttl.ms) return null
248
+ if (rec.inherited) {
249
+ // 卷宗继承的指纹只提示不拦——本会话从未读过,内容不在上下文,拦首读即阻断取证
250
+ audit(sid, 'casefile-inherit', { evidence: `2.0卷宗 继承指纹放行首读 ${filePath} ttl=${ttl.src}` })
251
+ if (typeof warn === 'function') {
252
+ warn('卷宗·提示:', `${filePath} 卷宗有近期取证(${ttl.src}),但本会话尚未读过——首读放行。`)
282
253
  }
254
+ return null
255
+ }
256
+ audit(sid, 'casefile-hit', { evidence: `2.0卷宗 免重读 ${filePath} ttl=${ttl.src}` })
257
+ return {
258
+ kind: 'deny',
259
+ reason:
260
+ `focus-guard-native: [卷宗·免重读]${filePath} 指纹一致(${rec.via || 'mtime+size'})且 TTL 未超(${ttl.src}),` +
261
+ `勿重复整读;需新内容用 offset 增量读或请批示。`,
262
+ }
263
+ } catch {
264
+ /* 指纹/卷宗读取失败 → 放行真重读(fail-open,与全文件口径一致) */
265
+ return null
266
+ }
267
+ }
268
+
269
+ /** ===== 74条:本次调用确定执行 → 备份改动前内容到 .ai/backup/(新文件无内容可备份,自动跳过)===== */
270
+ function backupBeforeWrite({ exec, sid, tool, handoff, rawPath, filePath }) {
271
+ if (!RE_WRITE.test(tool) || handoff || !rawPath) return
272
+ try {
273
+ backupBeforeEdit(rawPath, projDirOf(exec))
274
+ } catch {
275
+ audit(sid, 'note-fail', { evidence: `74条 改动前备份失败 ${filePath}` })
276
+ }
277
+ }
278
+
279
+ /**
280
+ * pre-execute 补充执法缝(`tools/pre-execute`)。
281
+ * 返回 deny 决策以拦截;返回 next() 透传下游。
282
+ */
283
+ export function preGuardListener({ warn } = {}) {
284
+ return async (exec, next) => {
285
+ try {
286
+ const ctx = collectContext(exec)
287
+
288
+ let verdict = checkLibraryWrite(ctx)
289
+ if (verdict) return verdict
290
+ verdict = checkPlatformCommand(ctx)
291
+ if (verdict) return verdict
292
+ verdict = checkCaseClash(ctx)
293
+ if (verdict) return verdict
294
+ verdict = gateSubagent(ctx)
295
+ if (verdict) return verdict
296
+ verdict = gateFused(ctx)
297
+ if (verdict === THROUGH) return next()
298
+ if (verdict) return verdict
299
+ verdict = gateDowngrade(ctx)
300
+ if (verdict) return verdict
301
+ verdict = checkCasefileReread(ctx, warn)
302
+ if (verdict) return verdict
303
+ backupBeforeWrite(ctx)
283
304
  } catch (error) {
284
305
  if (typeof warn === 'function') warn('补充执法缝异常,fail-open 放行:', (error && error.message) || error)
285
306
  }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * 重复被拦 → 换策略提示(2026-10-22,人类反馈"工作流没做好")
3
+ *
4
+ * 实测浪费:8 任务那轮被拦 7 条后,模型仍**重试同一条调用**,多出 4 个 step(每 step 都重读全上下文)。
5
+ * 现有理由只写"请先读/请补 include",没告诉它"同一条重试多少次都不会放行"。
6
+ *
7
+ * 本模块只做两件事:
8
+ * ① 按「会话 + 工具 + 参数」计数被拦次数;
9
+ * ② 第 2 次起改写理由:明确"重试无效",并按闸的类型给出**换法**(不是重复原话)。
10
+ * 不改任何判定(allow/deny 不变),只改模型看到的文字。
11
+ */
12
+
13
+ const MAX_TRACK = 200
14
+ import { detectSearchBackends, retrievalHint } from './search-hints.mjs'
15
+ const counts = new Map()
16
+ // 会话级被拦总数:≥5 次时给**一次**"先停手"提示(实测被拦后越试越乱)。
17
+ // 2026-10-28:原实现随每次 deny 重复追加,等于每拒一次多付一段提示;改为每会话只一次。
18
+ const sessionDenies = new Map()
19
+ const sessionHinted = new Set()
20
+ const SESSION_HINT_AT = 5
21
+
22
+ function sidOf(exec) {
23
+ return String((exec && (exec.sessionId || (exec.agent && (exec.agent.sessionId || exec.agent.id)))) || '-')
24
+ }
25
+
26
+ function keyOf(exec) {
27
+ const tool = String((exec && exec.name) || '')
28
+ let args = ''
29
+ try {
30
+ args = JSON.stringify((exec && exec.arguments) || {})
31
+ } catch {
32
+ args = ''
33
+ }
34
+ const sid = (exec && (exec.sessionId || (exec.agent && (exec.agent.sessionId || exec.agent.id)))) || '-'
35
+ return `${sid}::${tool}::${args.length > 500 ? args.slice(0, 500) : args}`
36
+ }
37
+
38
+ /** 按闸的类型给"换法"——必须是**另一条路**,不是同一句话再说一遍。 */
39
+ export function altHint(reason) {
40
+ const r = String(reason || '')
41
+ // 整读类:提示按本机可用的检索后端给(xerj→rg→fd→无)。
42
+ if (/整文件闸|整读/.test(r)) return retrievalHint(detectSearchBackends())
43
+ if (/Grep 未收窄|体积刺客/.test(r)) return 'Grep 补 `include`(如 `**/*.mjs`)收窄,或先按文件名定位再读指定文件。'
44
+ if (/取证|未读/.test(r)) return '先用 read 读目标文件(或它所在目录的清单),再重试改动;不要连着改多个没读过的文件。'
45
+ if (/fg_apply|申请授权/.test(r)) return '调用 `fg_apply`(purpose/scope 必填)一次性申请;同一条命令直接重试只会再次被拒。'
46
+ if (/委托池用尽/.test(r)) return '委托额度已用尽:主会话自己收敛,或请人类批示『追加额度』。'
47
+ if (/不可逆|人类批准/.test(r)) return '等人类在审批卡片上点批准;或改用可逆做法(先备份/小范围)。'
48
+ if (/绝对红线/.test(r)) return '红线不接受重试:换等价的安全做法;若确认是误判(危险片段只是被引用的数据),用 `fg_appeal` 提交反例锚点。'
49
+ return '换一条路径:先取证/收窄范围,或改工具(同一条调用重复提交不会放行)。'
50
+ }
51
+
52
+ /**
53
+ * 判定返回 deny 时调用:返回改写后的 decision(或原样返回)。
54
+ * @param {object} exec 工具执行上下文
55
+ * @param {object} decision {kind, reason}
56
+ * @param {(msg: string) => void} [warn]
57
+ */
58
+ export function augmentDeny(exec, decision, warn) {
59
+ if (!decision || decision.kind !== 'deny') return decision
60
+ const key = keyOf(exec)
61
+ const n = (counts.get(key) || 0) + 1
62
+ if (counts.size > MAX_TRACK && !counts.has(key)) counts.clear()
63
+ counts.set(key, n)
64
+
65
+ const sid = sidOf(exec)
66
+ const total = (sessionDenies.get(sid) || 0) + 1
67
+ sessionDenies.set(sid, total)
68
+
69
+ let out = decision
70
+ if (n >= 2) {
71
+ const base = String(decision.reason || '')
72
+ if (!base.includes('[重复被拦')) {
73
+ const text = `[重复被拦 ×${n}] 同一条调用不会因为重试而放行。换法:${altHint(base)}\n—— 原始理由:${base}`
74
+ try {
75
+ warn?.(`重复被拦 ×${n}:${String((exec && exec.name) || '')}`)
76
+ } catch {
77
+ /* 日志失败不影响判定 */
78
+ }
79
+ out = { ...decision, reason: text, repeat: n }
80
+ } else {
81
+ out = { ...decision, repeat: n }
82
+ }
83
+ }
84
+ // 会话级:拦得多说明方向错了,给一句"先停手"(只加提示,不改变判定;每会话一次)。
85
+ if (total >= SESSION_HINT_AT && !sessionHinted.has(sid)) {
86
+ sessionHinted.add(sid)
87
+ const reason = `${String(out.reason || '')}\n[本会话已被拦 ${total} 次] 先停手:用一段话总结现状(已确认的事实 / 卡在哪 / 下一步),再继续;不要靠连续试错推进。`
88
+ out = { ...out, reason }
89
+ }
90
+ return out
91
+ }
92
+
93
+ /** 测试用:清空计数。 */
94
+ export function resetRepeatCounts() {
95
+ counts.clear()
96
+ sessionDenies.clear()
97
+ sessionHinted.clear()
98
+ }