focus-guard 3.3.3 → 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.
@@ -9,13 +9,15 @@
9
9
  * `withRulesSection`,**判定与透传语义一字未改**。
10
10
  */
11
11
  import { SESSION_RULES } from '../../core/constants.mjs'
12
+ import { pendingPatternStubs } from '../../core/patterns.mjs'
13
+ import { projDirOf } from './shared.mjs'
12
14
 
13
15
  export function systemPromptRulesListener({ warn } = {}) {
14
16
  return async (assembly, context, next) => {
15
17
  let downstream
16
18
  try {
17
19
  downstream = await next()
18
- return withRulesSection(downstream)
20
+ return withRulesSection(downstream, patternsNotice(context))
19
21
  } catch (error) {
20
22
  if (typeof warn === 'function') warn('常驻规则注入异常(不阻塞):', (error && error.message) || error)
21
23
  return downstream
@@ -23,10 +25,35 @@ export function systemPromptRulesListener({ warn } = {}) {
23
25
  }
24
26
  }
25
27
 
28
+ /**
29
+ * 经验库「教训」待补提醒(2026-11-08)。
30
+ *
31
+ * 病根:`appendPatternStub` 在熔断时写下骨架,`- 教训:<待补…>` 那一行**没有任何机制促使回填**。
32
+ * 建库 27 天零条是第一层(写不进去),补上写入之后是第二层(写进去也永远空着)——
33
+ * 骨架不是经验,而模型看不见"还欠几笔"。
34
+ *
35
+ * 只在**真有未回填**时才追加一段:干净时零成本,清完自动消失;不写进 `SESSION_RULES`
36
+ * 常驻文本(那会变成每步都付的固定开销)。判断仍归模型,引擎只报数。
37
+ */
38
+ function patternsNotice(context) {
39
+ try {
40
+ const n = pendingPatternStubs(projDirOf(context && context.agent))
41
+ if (!n) return ''
42
+ return (
43
+ `【经验库】.ai/PATTERNS.md 有 ${n} 条「教训」未回填。` +
44
+ '收尾前把它写成「以后遇到 X 必须先做 Y」——骨架不算经验,未清不算结项。'
45
+ )
46
+ } catch {
47
+ return ''
48
+ }
49
+ }
50
+
26
51
  /** 下游是预期 assembly 形状时追加独立 section;否则原样透传(不强行改写)。 */
27
- function withRulesSection(downstream) {
52
+ function withRulesSection(downstream, extra) {
28
53
  if (downstream && typeof downstream === 'object' && Array.isArray(downstream.sections)) {
29
- return { ...downstream, sections: [...downstream.sections, { name: 'focus-guard-rules', text: SESSION_RULES }] }
54
+ const sections = [...downstream.sections, { name: 'focus-guard-rules', text: SESSION_RULES }]
55
+ if (extra) sections.push({ name: 'focus-guard-patterns', text: extra })
56
+ return { ...downstream, sections }
30
57
  }
31
58
  return downstream
32
59
  }
@@ -14,6 +14,8 @@
14
14
  */
15
15
  import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs'
16
16
  import { join } from 'node:path'
17
+ import { spawn } from 'node:child_process'
18
+ import { fileURLToPath } from 'node:url'
17
19
  import {
18
20
  statePath,
19
21
  loadState,
@@ -21,9 +23,10 @@ import {
21
23
  casePath,
22
24
  ensureCaseFile,
23
25
  loadCaseRecords,
26
+ fmtTime,
24
27
  } from '../../core/state.mjs'
25
28
  import { noteFail } from '../../core/audit.mjs'
26
- import { detectEnv, quickShellId } from '../../core/env.mjs'
29
+ import { detectEnv, probeShells, quickShellId } from '../../core/env.mjs'
27
30
  import { ENGINE_VERSION } from '../../core/constants.mjs'
28
31
  import { sidOf, projDirOf, isSubagent, auditRow } from './shared.mjs'
29
32
 
@@ -31,6 +34,9 @@ import { sidOf, projDirOf, isSubagent, auditRow } from './shared.mjs'
31
34
  const SEALED = new Set(['packages/core/hooks/guard.mjs'])
32
35
  const VERSION_CANDIDATES = ['hooks/guard.mjs', 'focus-guard/hooks/guard.mjs', 'packages/core/hooks/guard.mjs']
33
36
 
37
+ /** 指纹生成器(安装后目录结构不变:src/dsh/seams → ../../../tools)。 */
38
+ const ENV_FP_TOOL = fileURLToPath(new URL('../../../tools/env-fingerprint.mjs', import.meta.url))
39
+
34
40
  export function sessionStartListener({ warn } = {}) {
35
41
  return async ({ agent } = {}) => {
36
42
  try {
@@ -68,11 +74,23 @@ export function sessionStartListener({ warn } = {}) {
68
74
  }
69
75
 
70
76
  /**
71
- * 本宿主应当使用的执行体标识:DSH 的 shell 工具执行体由宿主固定(win32 上是 pwsh),
72
- * 不由用户 shell 会话决定——所以这里直接给出期望值,不靠 quickShellId 猜。
77
+ * 本宿主应当使用的执行体标识。
78
+ *
79
+ * 2026-11-09 修:原先 win32 恒返回 `'powershell'`,注释称「DSH 的 shell 工具执行体由宿主固定
80
+ * (win32 上是 pwsh)」。**实测不成立**——DSH Desktop 只有 `dsh-tool-bash`,执行 argv 是
81
+ * `["bash", "-c", cmd]`(`@deepseek-ai/dsh-bash-local/lib/index.js:141`),没有 pwsh 工具。
82
+ * 那条注释是 2.x 时代的遗留假定,从未核对;后果是卷宗【一】写 powershell、平台禁令按
83
+ * PowerShell 规则选,而每条命令实际跑在 bash 里。
84
+ *
85
+ * 也不能退回 `quickShellId()`:宿主进程 `SHELL` 未定义、`ComSpec` 指向 cmd.exe,它会猜成 `cmd`。
86
+ * 现在的判据是**探测**:扫 PATH,能解析到 `bash` 就认 bash(DSH 的 Bash 工具就是 `bash -c`);
87
+ * 探不到才退回宿主推断。不写死任何安装路径——装在 D 盘、scoop 目录、或压根没装,都能判对。
88
+ * `FG_SHELL` 仍可覆盖,供测试与特殊部署使用。
73
89
  */
74
90
  function expectedShellId() {
75
- return process.platform === 'win32' ? 'powershell' : quickShellId()
91
+ const forced = String(process.env.FG_SHELL || '').trim().toLowerCase()
92
+ if (forced) return forced
93
+ return probeShells().includes('bash') ? 'bash' : quickShellId()
76
94
  }
77
95
 
78
96
  /**
@@ -87,27 +105,101 @@ function expectedShellId() {
87
105
  * 后者是「缓存不能比它的输入活得久」——缓存 key 必须包含输入,否则换环境还拿旧结果。
88
106
  *
89
107
  * 关于「shell 变化重检」:`pre-step.mjs` 注释说该分支「留待后续批次」,实际从未移植。
90
- * 在 DSH 路径上它不是缺口——插件是常驻进程,执行体由宿主配置(cordis.patch.yml 的
91
- * pwshPath)在启动时固定,回合之间不会变。需要每进程重检的是封存版 `guard.mjs`
92
- * (每次调用都是新进程,SHELL 可能不同),那条路本来就有。
108
+ * 在 DSH 路径上它不是缺口——插件是常驻进程,执行体由宿主决定,回合之间不会变。
109
+ * 需要每进程重检的是封存版 `guard.mjs`(每次调用都是新进程,SHELL 可能不同),那条路本来就有。
93
110
  */
94
111
  function detectEnvInto(state, projDir) {
95
- // 2026-10-18:DSH 的 shell 工具执行体是 pwsh(cordis.patch.yml 的 pwshPath),
96
- // 但 Node 进程自身的 ComSpec 是 cmd —— 不显式声明就会把执行体记成 cmd。
112
+ // 2026-11-09:注释与实现一并更正。原写「执行体是 pwsh(cordis.patch.yml 的 pwshPath)」——
113
+ // 实测 DSH Desktop 走 `["bash","-c",cmd]`,且根本没有 pwsh 工具(详见 expectedShellId)。
114
+ // 仍要显式传参:Node 进程自身的 ComSpec 是 cmd,不传就会记成 cmd(也不是 bash)。
97
115
  // 用参数传,不写环境变量(否则会被子进程继承,污染测试)。
98
116
  const cached = state.envCache
99
117
  if (cached && cached.os === process.platform && cached.shellIdKey === expectedShellId()) return
100
118
  try {
101
- state.envCache = detectEnv(projDir, process.platform === 'win32' ? { shell: 'powershell' } : {})
119
+ // 命令语法表(grep/sed/find 是 GNU 还是 BSD)来自环境档案。生成器要跑子进程探测,
120
+ // 会话启动不该付这个钱——读一次 JSON 就够。读不到时 `platformBashViolation` 退回 OS 推断。
121
+ let commands = {}
122
+ try {
123
+ const t = JSON.parse(readFileSync(join(projDir, '.ai', 'env-fingerprint.json'), 'utf8'))
124
+ if (t && t.commands) commands = t.commands
125
+ } catch {
126
+ /* 档案缺失或损坏:按无命令语法表处理,不阻断 */
127
+ }
128
+ state.envCache = detectEnv(projDir, { shell: expectedShellId(), commands })
102
129
  } catch {
103
130
  /* 环境检测失败不阻断 */
104
131
  }
105
132
  }
106
133
 
134
+ /**
135
+ * 环境指纹自动补齐(2026-11-07)。
136
+ *
137
+ * 病根:全仓没有任何生成入口——`INSTALL.md` 没写、会话启动不做、`postinstall` 也不做。
138
+ * 于是第 1.5 层命令硬校验在**大多数机器上等于没开**(缺文件即 fail-open),
139
+ * 而作者机上恰好有一份手工生成的,造成「同一条命令这边拦、那边放」。
140
+ *
141
+ * 为什么后台 spawn 而不是同步算:探测 5 个工具正常几百毫秒,但工具挂起时最坏要 7 秒以上,
142
+ * 不该压在会话启动路径上。生成后下一回合即生效;本次仍 fail-open,与旧行为一致。
143
+ */
144
+ /**
145
+ * 环境指纹的有效期。过期即重新探测。
146
+ *
147
+ * 2026-11-08 补:`ensureEnvFingerprint` 原先只有「不存在才生成」(`if (existsSync(fp)) return`),
148
+ * 生成一次就永久冻结——作者机上那份停在 2026-10-08,31 天没动。
149
+ * 而这个文件不只是留痕:`hardCheck.mjs` 第 1.5 层的命令映射(`grep→rg` / `find→fd`)
150
+ * **直接读它**。shell 换版本、工具装了或卸了,规则表照旧用旧的 → 同一条命令
151
+ * 「这边拦、那边放」,且没有任何信号。留痕件同时是规则源,就必须有保质期。
152
+ */
153
+ export const ENV_FP_TTL_MS = 30 * 86400e3
154
+
155
+ /**
156
+ * 指纹是否过期。读不到 / 解析不了 / 没有 generated_at 一律算过期——
157
+ * 宁可多探测一次(后台、几百毫秒),也不要拿着一份坏掉的规则表继续判。
158
+ */
159
+ export function envFpStale(fp, now = Date.now()) {
160
+ try {
161
+ const t = JSON.parse(readFileSync(fp, "utf8"))
162
+ // 2026-11-09:v2 档案自带 nextAt(自适应 TTL,6h 起、连续未变翻倍、上限 30 天)。
163
+ // 旧文件没有 probe 字段 → 退回 generated_at + 30 天,保证升级期不会突然全员重探。
164
+ const nextAt = Date.parse(t?.probe?.nextAt || "")
165
+ if (Number.isFinite(nextAt)) return now >= nextAt
166
+ const at = Date.parse(t.generated_at || "")
167
+ if (!Number.isFinite(at)) return true
168
+ return now - at >= ENV_FP_TTL_MS
169
+ } catch {
170
+ return true
171
+ }
172
+ }
173
+
174
+ function ensureEnvFingerprint(projDir) {
175
+ if (process.env.FG_ENV_FP_AUTO === '0') return
176
+ try {
177
+ const fp = join(projDir, '.ai', 'env-fingerprint.json')
178
+ if (existsSync(fp) && !envFpStale(fp)) return
179
+ // 2026-11-08:**不能加 `detached: true`**。Windows 上它会为子进程新开一个控制台窗口
180
+ // (`windowsHide: true` 拦不住),而且实测那个子进程从不产出——`.ai/env-fingerprint.json`
181
+ // 等 3 秒仍不存在、目录为空。非 detached + `unref()` 既能活过父进程,又不弹窗,实测立刻落盘。
182
+ // 判据:这个子进程只是写一个 JSON,不需要独立进程组;要的是「别阻塞会话启动」,不是「脱离父进程」。
183
+ // 2026-11-09:**也不传 `cwd`**。工具只往 `--out` 写、只探 PATH,不读项目目录;而把 cwd 设成
184
+ // 项目目录等于让这个后台进程**攥住项目目录的句柄**——Windows 上期间删/改/移动该目录一律 EBUSY
185
+ // (实测:`env-cache-reuse` 用例在 after 清理时报 rmdir EBUSY)。
186
+ // 2026-11-09:`--shell` 把**本会话实际执行体**传进去。档案里的 `platform.shell` 原本由
187
+ // 生成器自己猜(优先 pwsh),于是同一台机器上卷宗写 bash、档案写 pwsh,两份记录互相打架。
188
+ const child = spawn(process.execPath, [ENV_FP_TOOL, '--out', fp, '--shell', expectedShellId()], {
189
+ stdio: 'ignore',
190
+ windowsHide: true,
191
+ })
192
+ child.unref()
193
+ } catch {
194
+ /* 生成失败不阻断:缺文件时该层仍 fail-open,与旧行为一致 */
195
+ }
196
+ }
197
+
107
198
  /** 2.0~42条:卷宗载入 + 环境声明落卷 + 交叉巡视 + 部署版本核验。 */
108
199
  function prepareProject({ sid, projDir, state }) {
109
200
  loadCaseInto(state, sid, projDir)
110
201
  writeEnvDeclaration(state, sid, projDir)
202
+ ensureEnvFingerprint(projDir)
111
203
  // 36条 异地交叉巡视:新会话接手 → 复核前任结论
112
204
  inspectHandover(sid, projDir)
113
205
  checkVersionDrift(sid, projDir)
@@ -131,8 +223,35 @@ function writeEnvDeclaration(state, sid, projDir) {
131
223
  const cp = casePath(projDir)
132
224
  let t = readFileSync(cp, 'utf8')
133
225
  const env = state.envCache || {}
134
- const envRow = `- OS=${env.os} / Shell=${env.shellIdKey} / 大小写=${env.caseSensitive === false ? '不敏感' : '敏感'} / 编码=${env.encoding || '-'} / 检测于 ${new Date().toISOString()}`
135
- t = t.replace(/### 【一】[\s\S]*?(?=\n### |\n## |$)/, () => `### 【一】环境声明(会话级检测,全程复用)\n\n${envRow}\n`)
226
+ // 「可用=」是本机扫 PATH 探到的执行体(按推荐顺序)。写进卷宗,是为了让读到这一行的人
227
+ // (模型或人类)知道**该用哪个 shell**——实测本机 pwsh7 装在 E 盘、powershell 5.1 才是自带的。
228
+ // 自带的不标(省地方),额外安装的标「(额外)」——这个区别决定模型该不该建议"去装一个"。
229
+ // OS 用 `Windows/x64` 而不是 `win32`:后者是 Node 的 API 名,模型会误读成 32 位系统。
230
+ const shells = (env.shells || []).map((s) => `${s.id}${s.origin === 'extra' ? '(额外)' : ''}`).join(',')
231
+ const envRow = `- OS=${env.osLabel || env.os} / Shell=${env.shellIdKey}${shells ? ` / 可用=${shells}` : ''} / 大小写=${env.caseSensitive === false ? '不敏感' : '敏感'} / 编码=${env.encoding || '-'} / 检测于 ${fmtTime(Date.now())}`
232
+ // 命令语法行:同一台机器上 grep/sed/find 是 GNU 还是 BSD,决定 `-P`、`-i` 能不能那样写。
233
+ // 这是"写命令前就该知道"的事,等被拦一次再说太晚——所以直接摆在【一】里给模型看。
234
+ const cmdText = Object.entries(env.commands || {})
235
+ .map(([k, v]) => `${k}=${v.impl}${v.version ? ' ' + v.version : ''}`)
236
+ .join(' / ')
237
+ const engineRows = [envRow, ...(cmdText ? [`- 命令语法:${cmdText}`] : [])]
238
+ // 只换引擎自己写的那一行,不整段重写【一】。原先是 `[\s\S]*?` 一路吃到下一个标题,
239
+ // 人类在【一】里补的注("本机 rg 在 D:\tools" 之类)每次会话启动都被抹掉——与 2026-11-01
240
+ // 红队 A3 修【三】【四】是同一类病,当时漏了【一】。判据:引擎只拥有它写的那几行。
241
+ t = t.replace(/(### 【一】[^\n]*\n)([\s\S]*?)(?=\n### |\n## |$)/, (_m, head, body) => {
242
+ const kept = body
243
+ .split('\n')
244
+ .map((line) => line.trimEnd())
245
+ .filter((line) => {
246
+ const s = line.trim()
247
+ if (!s) return false
248
+ if (/^-\s*OS=/.test(s)) return false // 上一次的检测行,由本次覆盖
249
+ if (/^-\s*命令语法[::]/.test(s)) return false // 同上:引擎自己的行,由本次覆盖
250
+ if (/^(.*)$/.test(s)) return false // 模板占位语,检测行到位后就没有意义
251
+ return true
252
+ })
253
+ return `${head}\n${[...engineRows, ...kept].join('\n')}\n`
254
+ })
136
255
  const tmp = cp + '.' + process.pid + '.tmp'
137
256
  writeFileSync(tmp, t)
138
257
  renameSync(tmp, cp)
package/src/dsh/seams.mjs CHANGED
@@ -44,9 +44,14 @@ export function turnStoppingListener({ warn } = {}) {
44
44
  return async ({ agent } = {}) => {
45
45
  try {
46
46
  const { sid, file, state } = loadOrInit(agent)
47
- // 顺序固定:ttl 回收 → 改动面报告 → KPI 结算(后两步都依赖前一步不留残留)。
47
+ // 顺序固定:ttl 回收 → 改动面报告 → 额度台账 → KPI 结算(后三步都依赖前一步不留残留)。
48
48
  await sweepTurnGrants(sid, warn)
49
49
  await reportBlastRadius(sid, state)
50
+ // 2026-11-08 修(卷宗【四】在真实会话里恒空):本行原在 settleKpi 内、且在
51
+ // `kpiNow === 0` 的提前 return **之后**——没有 KPI 增量的回合(大多数回合)永远不写,
52
+ // 于是额度台账只剩一张表头。与 reportBlastRadius 同一类病、同一类修法:搬出提前 return 的射程。
53
+ // 放在 settleKpi 之前:结算是"加分",不该因为结算异常连本回合的额度快照都丢掉。
54
+ saveLedger(projDirOf(agent), state)
50
55
  await settleKpi({ agent, sid, file, state })
51
56
  } catch (error) {
52
57
  if (typeof warn === 'function') warn('KPI 结算缝异常(不阻塞):', (error && error.message) || error)
@@ -114,7 +119,6 @@ async function settleKpi({ agent, sid, file, state }) {
114
119
  state.kpiLowReported = false
115
120
  }
116
121
  saveState(file, state)
117
- saveLedger(projDirOf(agent), state)
118
122
  await publishKpiSnapshot(state)
119
123
  auditRow(
120
124
  sid,
package/src/dsh/tools.mjs CHANGED
@@ -12,6 +12,8 @@
12
12
  * output: { schema, render }, execute }`——与 dsh-memory 的 state_checkpoint 同构。
13
13
  */
14
14
 
15
+ import { readFileSync, writeFileSync } from 'node:fs'
16
+ import { join } from 'node:path'
15
17
  import { applyEligibility, grantFromAppeal, FG_APPLY_TOOL_SPEC, FG_APPEAL_TOOL_SPEC } from '../adapters/dsh/eligibility-gate.mjs'
16
18
  import { ABSOLUTE_REDLINES } from '../core/redlines.mjs'
17
19
  import { livenessBadge } from './heartbeat.mjs'
@@ -74,6 +76,77 @@ export function buildApplyTool() {
74
76
  }
75
77
  }
76
78
 
79
+ /**
80
+ * 构造 fg_env 工具定义(2026-11-09)。
81
+ *
82
+ * 为什么需要这个工具:环境档案是**探测**出来的,而探测只看得到 PATH 与 `--version`。
83
+ * 它看不出「这个 pwsh7 是 scoop 装的」「bash 其实是 WSL」「grep 3.0 的 -P 有坑」——
84
+ * 这些只有模型(或人类)在真用过之后才知道。工具给一条**写回**的通道,探测与经验互补。
85
+ *
86
+ * 不传 note 就是只读查询:模型可以随时确认"这台机器到底有什么",不必靠猜。
87
+ */
88
+ /** fg_env 的执行体(抽出来是为了不让 buildEnvTool 的嵌套超阈值)。 */
89
+ async function runEnvArchive(args = {}, exec) {
90
+ const projDir =
91
+ (exec && exec.agent && exec.agent.session && exec.agent.session.header && exec.agent.session.header.cwd) ||
92
+ process.env.FG_PROJECT_DIR ||
93
+ process.cwd()
94
+ const fp = join(projDir, '.ai', 'env-fingerprint.json')
95
+ let data
96
+ try {
97
+ data = JSON.parse(readFileSync(fp, 'utf8'))
98
+ } catch {
99
+ return { text: `[环境档案] 尚未生成:${fp}\n会话启动会自动探测(后台);也可手动跑 packages/core/tools/env-fingerprint.mjs` }
100
+ }
101
+ const note = String(args.note || '').trim()
102
+ if (note) {
103
+ data.notes = Array.isArray(data.notes) ? data.notes : []
104
+ data.notes.push({ at: new Date().toISOString(), by: 'model', text: note.slice(0, 500) })
105
+ try {
106
+ writeFileSync(fp, JSON.stringify(data, null, 2) + '\n')
107
+ } catch (error) {
108
+ return { text: `[环境档案] 反馈写入失败(不阻塞):${(error && error.message) || error}` }
109
+ }
110
+ }
111
+ const shells = (data.shells || [])
112
+ .map((s) => `${s.id}(${s.origin === 'builtin' ? '自带' : '额外'})`)
113
+ .join(' ')
114
+ const cmds = Object.entries(data.commands || {})
115
+ .map(([k, v]) => `${k}=${v.impl}${v.version ? ' ' + v.version : ''}`)
116
+ .join(' / ')
117
+ const probe = data.probe || {}
118
+ const lines = [
119
+ `[环境档案] 机器 ${data.machine?.id || '?'} · ${data.machine?.host || '?'} · ${data.platform?.osLabel || data.platform?.os || '?'}`,
120
+ `执行体 ${data.platform?.shell || '?'}(来源 ${data.platform?.shellSource || '?'})/ 可用 ${shells || '-'}`,
121
+ `命令语法 ${cmds || '-'}`,
122
+ `探测 ${probe.at || '-'} · 下次重探 ${probe.nextAt || '-'}(${Math.round((probe.ttlMs || 0) / 3600e3)}h,连续未变 ${probe.streak ?? '-'} 次)`,
123
+ ]
124
+ const notes = Array.isArray(data.notes) ? data.notes : []
125
+ if (notes.length) {
126
+ lines.push(`反馈 ${notes.length} 条:`)
127
+ for (const n of notes.slice(-5)) lines.push(` · ${n.text}`)
128
+ }
129
+ if (note) lines.push(`已记录反馈:${note.slice(0, 120)}`)
130
+ return { text: lines.join('\n') }
131
+ }
132
+
133
+ export function buildEnvTool() {
134
+ return {
135
+ name: 'fg_env',
136
+ description:
137
+ '查看本机环境档案(机器编号 / 操作系统 / 可用终端 / 命令语法新旧 / 探测 TTL),或回填一条补充说明。' +
138
+ '探测只能看到 PATH 与版本号,看不到「这个终端是谁装的」「某个命令在本机有特殊行为」——这些用 note 写回来。',
139
+ parameters: specToJsonSchema({
140
+ note: {
141
+ type: 'string',
142
+ description: '本机环境的补充说明,例如「pwsh7 是 scoop 装的,非系统自带」「bash 实为 WSL」「grep 3.0 不支持 -P 的某些写法」',
143
+ },
144
+ }),
145
+ output: TEXT_OUTPUT,
146
+ execute: runEnvArchive,
147
+ }
148
+ }
149
+
77
150
  /** 构造 fg_appeal 工具定义。 */
78
151
  function buildAppealTool() {
79
152
  return {
@@ -105,6 +178,7 @@ export function registerGateTools(ctx, { warn } = {}) {
105
178
  for (const [label, build] of [
106
179
  ['fg_apply', buildApplyTool],
107
180
  ['fg_appeal', buildAppealTool],
181
+ ['fg_env', buildEnvTool],
108
182
  ]) {
109
183
  try {
110
184
  ctx.tools.register(build())
@@ -163,8 +163,13 @@ export function renderWorkspaceSection(record, opts = {}) {
163
163
  ? `上次会话:${s.sid ? String(s.sid).slice(0, 12) : '-'} · ${s.at || '-'} · 工具调用 ${s.toolCalls ?? '-'} · 被拦 ${s.denies ?? '-'} · KPI ${s.kpi ?? '-'} · 委托 ${s.delegateBudget ?? '-'}`
164
164
  : ''
165
165
  // 决策行同理,且理由更硬(2026-10-29):它是**历史**,而历史每回合都在长。
166
- // 实测(tools/prefix-drift.mjs)系统段每会话 2 个版本,分歧点恒定落在这一行——
167
- // 前缀一变,后面整段会话历史都要按未缓存价重付,而这些指令原文本来就在会话消息里。
166
+ // 实测(tools/prefix-drift.mjs)系统段每会话 2 个版本,分歧点恒定落在这一行。
167
+ // 代价口径(2026-11-11 更正,与 docs/ARCHITECTURE.md「前缀稳定性」一节对齐):
168
+ // 宿主是 `systemPromptUpdate: "in-history"`——系统段变了是往历史里**追加**一条,
169
+ // 不改写前缀,所以「后面整段历史按未缓存价重付」**不成立**(前缀照常命中)。
170
+ // 真实代价是每变一次多背一份完整系统提示(约 2.5k tok/次),并在历史里堆出多条 system 消息。
171
+ // 冻结它仍值得,但收益量级是 0.3% 而不是"整段重付"——别用旧口径给这条加权重。
172
+ // 而指令原文本来就在会话消息里,再抄一份既重复又抖。
168
173
  const showDecisions = opts.sid === undefined || shouldInjectHandoff(record, opts.sid)
169
174
  const head = `[FG-WORKSPACE] 本工作区跨会话卷宗(hash=${record.workspace_hash},仅当前路径可见):`
170
175
  /** 组装可见条目:`[done]` / `[note]` 不注入,`[goal]` 剥掉标记。 */
@@ -196,7 +201,9 @@ export function renderWorkspaceSection(record, opts = {}) {
196
201
  * 为什么必须冻结:`workspace.json` 是**每工作区一份**,而同一工作区常有多个并发会话。
197
202
  * 每个会话在回合结束都会写自己的快照,于是 A 会话的系统提示里会忽而出现 B 的快照、
198
203
  * 忽而变回自己的——实测两个真实会话的卷宗段都是 2 个版本,分歧点就在「上次会话」这一行。
199
- * 前缀一变,后面整段会话历史都要按未缓存价重付。
204
+ * 代价口径(2026-11-11 更正):宿主 `systemPromptUpdate: "in-history"`,系统段变了是**追加**
205
+ * 一条新 system 消息而非改写前缀,所以不是"整段历史按未缓存价重付",而是每次多背一份完整
206
+ * 系统提示(约 2.5k tok/次)并在历史里堆出多条 system 消息。冻结把 N 次压成 1 次。
200
207
  *
201
208
  * 冻结的语义:**本会话首步渲染出什么,整场会话就是什么**。换会话自然是新的一份(交接信息还在)。
202
209
  * 代价如实说:本会话内新增的约束不会出现在提示里——但约束由闸门实时执行,
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 本地皮层版脑的入口(2026-11-08)
4
+ *
5
+ * 为什么有这个文件:
6
+ * 磁盘上那个 6.3 MB 的脑(带真 PLY 皮层网格)由 `.focus-guard/viz/build-brain2.mjs` 生成,
7
+ * 而那个生成器**在隐藏目录里、被 `.git/info/exclude` 排除**——官方 `npm run brain`
8
+ * 产出的是模板版(481 KB),两者不是同一个东西。
9
+ * 结果是:看着最顺眼的那版,恰恰是唯一没有入口、也从未进过仓库的那版。
10
+ *
11
+ * 边界(硬性):
12
+ * ① **不把资产搬进版本库**。皮层数据来自 `memory-brain`,是 CC BY-SA 3.0;
13
+ * 把它请进公开仓库等于替使用者接下一份传染性授权,这个决定不该由工具悄悄做。
14
+ * ② **对没装资产的人不报错成崩溃**。文件不在就明说"这是本地实验产物",exit 1 收工。
15
+ * ③ **不改判定**。只读审计、只写自己的 HTML,与 `brain.mjs` 同一口径。
16
+ *
17
+ * 用法:
18
+ * npm run brain:cosmic # 用本地皮层版生成 → .focus-guard/brain.html,并打开
19
+ */
20
+
21
+ import { existsSync } from "node:fs";
22
+ import { dirname, join, resolve } from "node:path";
23
+ import { fileURLToPath, pathToFileURL } from "node:url";
24
+ import { openInBrowser } from "./lib/open.mjs";
25
+
26
+ const HERE = dirname(fileURLToPath(import.meta.url));
27
+ const REPO = resolve(HERE, "..", "..", "..");
28
+ const BUILDER = join(REPO, ".focus-guard", "viz", "build-brain2.mjs");
29
+ const OUT = join(REPO, ".focus-guard", "brain.html");
30
+
31
+ if (!existsSync(BUILDER)) {
32
+ process.stderr.write(
33
+ `找不到本地皮层版生成器:${BUILDER}\n` +
34
+ ` 它是本地实验产物,不入版本库(皮层数据为 CC BY-SA 3.0,不随仓库分发)。\n` +
35
+ ` 换官方模板版:npm run brain\n`,
36
+ );
37
+ process.exit(1);
38
+ }
39
+
40
+ await import(pathToFileURL(BUILDER).href);
41
+
42
+ process.stdout.write(`脑已更新:${pathToFileURL(OUT).href}\n 已请求用默认程序打开(没弹窗就点上面那个地址)\n`);
43
+ openInBrowser(OUT);
package/tools/brain.mjs CHANGED
@@ -25,20 +25,22 @@
25
25
  * ④ **不引 three.js**。本仓 `dependencies: {}` 是唯一的性格。
26
26
  *
27
27
  * 用法:
28
- * node packages/core/tools/brain.mjs # 增量 → .focus-guard/brain.html
29
- * node packages/core/tools/brain.mjs --open
28
+ * npm run brain # 增量 → .focus-guard/brain.html,并打开
29
+ * npm run brain:build # 只生成不打开
30
30
  * node packages/core/tools/brain.mjs --rebuild # 丢掉索引,从头重算
31
31
  * node packages/core/tools/brain.mjs --json # 只打图数据(供测试)
32
+ * node packages/core/tools/brain.mjs --out <path> # 换产物路径(试生成用)
32
33
  */
33
34
 
34
35
  import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from "node:fs";
35
36
  import { dirname, join, resolve } from "node:path";
36
- import { fileURLToPath } from "node:url";
37
+ import { fileURLToPath, pathToFileURL } from "node:url";
37
38
  import {
38
39
  REGIONS, applyEvent, applySeqLinks, classify, emptyIndex, entitiesOf, listSources, loadConfig,
39
40
  loadIndex, prune, readNewLines, reclassify, saveIndex, snapshot,
40
41
  } from "./lib/brain-core.mjs";
41
42
  import { syncDocs } from "./lib/brain-docs.mjs";
43
+ import { openInBrowser } from "./lib/open.mjs";
42
44
 
43
45
  const HERE = dirname(fileURLToPath(import.meta.url));
44
46
  const REPO = resolve(HERE, "..", "..", "..");
@@ -279,6 +281,7 @@ function main() {
279
281
 
280
282
  const cf = o.casefileWrite ? writeCaseFile(o.casefile, g, now, idx.seen) : 0;
281
283
  report(o, { g, idx, added, sources, moved, dropped, docs, regionCount, from, to, cf });
284
+ if (o.open) openInBrowser(o.out);
282
285
  }
283
286
 
284
287
  /* 汇总输出单独成函数:它跟"跑一遍"本来就是两件事,混在 main() 里只会让流程读不清。
@@ -288,7 +291,8 @@ function report(o, x) {
288
291
  .map(([k, v]) => `${v.label} ${x.regionCount[k] || 0}`)
289
292
  .join(" · ");
290
293
  process.stdout.write(
291
- `脑已更新:${o.out.replace(REPO, ".")}\n` +
294
+ `脑已更新:${pathToFileURL(o.out).href}\n` +
295
+ ` ${o.open ? "已请求用默认程序打开(没弹窗就点上面那个地址)" : `打开:npm run brain -- --open 或直接双击上面这个地址`}\n` +
292
296
  ` 新增 ${x.added} 条(源 ${x.sources} 个)· 累计 ${x.idx.seen} 条事件 · 遗忘 ${x.dropped} 个 · 重分区 ${x.moved} 个\n` +
293
297
  ` 记忆 ${x.docs.blocks} 块(实读 ${x.docs.sources} 份文档` +
294
298
  (x.docs.missing.length ? `,缺 ${x.docs.missing.length} 份` : "") +
@@ -14,7 +14,7 @@
14
14
  */
15
15
 
16
16
  import { decodeSession as decode } from './lib/sessionDump.mjs'
17
- import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync, rmSync } from 'node:fs'
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, rmSync } from 'node:fs'
18
18
  import { dirname, join, basename } from 'node:path'
19
19
  import { fileURLToPath } from 'node:url'
20
20
 
@@ -23,6 +23,19 @@ const CORE = join(HERE, '..')
23
23
  const SESSIONS = process.env.FG_SESSIONS_DIR || 'E:/DSH/.dsh/sessions'
24
24
  const OUT = join(CORE, 'tests', 'fixtures', 'real-calls')
25
25
 
26
+ // 本机环境闸的规则来源是 `.ai/env-fingerprint.json`——**私有面文件,不入版本库**。
27
+ // 不把 map 一起记下来,这类样本就只能在录制机上复现:干净 clone 上该闸按设计 fail-open,
28
+ // 重放必报「漏拦」。记下来,重放时用 `FG_ENV_FP_FILE` 指到临时文件即可还原现场。
29
+ const ENV_FP = join(CORE, '..', '.ai', 'env-fingerprint.json')
30
+ const ENV_MAP = (() => {
31
+ try {
32
+ const j = JSON.parse(readFileSync(ENV_FP, 'utf8'))
33
+ return j && j.map && typeof j.map === 'object' ? j.map : null
34
+ } catch {
35
+ return null
36
+ }
37
+ })()
38
+
26
39
  const argv = process.argv.slice(2)
27
40
  const LIMIT = Number(argv.includes('--limit') ? argv[argv.indexOf('--limit') + 1] : 30) || 30
28
41
  const MAX_BYTES = 3 * 1024 * 1024
@@ -124,6 +137,7 @@ for (const { f } of files) {
124
137
  args: call.args,
125
138
  verdict: denied ? 'deny' : 'pass',
126
139
  reason: denied ? text.replace(/\\n/g, ' ').slice(0, 160) : null,
140
+ ...(denied && /本机环境/.test(text) && ENV_MAP ? { envMap: ENV_MAP } : {}),
127
141
  })
128
142
  }
129
143
  }
@@ -34,11 +34,11 @@ const BUDGET = 0
34
34
  /**
35
35
  * 按规则的存量豁免(3.3 A)。
36
36
  *
37
- * `dead-code-path` 的 5 条全在 CHANGELOG 的历史段里,指向当年存在、后来搬走的文件。
38
- * 按本仓纪律「历史条目不动」(改了就等于抹掉过程记录),所以给它们一个明账:
39
- * 数字摆在这里,不是静默放过。新写进文档的引用不在豁免内,一律现算现红。
37
+ * 原为 `{ 'dead-code-path': 5 }`——那 5 条全在 CHANGELOG 的历史段里,指向当年存在、后来搬走的文件。
38
+ * 2026-11-07 历史段(≤3.0.7)原样移入 `docs/archive/`(不在扫描面内),存量归零,额度一并收回。
39
+ * 判据:豁免是**存量**的记账。存量没了还留着额度,等于给未来的死链预留藏身处。
40
40
  */
41
- const RULE_BUDGET = { 'dead-code-path': 5 }
41
+ const RULE_BUDGET = { 'dead-code-path': 0 }
42
42
 
43
43
  const files = listMarkdownFiles(ROOT)
44
44
  const findings = [