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.
- package/LICENSE +683 -21
- package/NOTICE +25 -0
- package/README.md +14 -9
- package/README.zh-CN.md +12 -9
- package/docs/AB-PROMPTS.md +123 -0
- package/docs/AB-SESSION.md +161 -0
- package/docs/ARCH-MAP.md +148 -0
- package/docs/BENCH-BASELINE.json +95 -0
- package/docs/BENCH.md +323 -0
- package/docs/GATE-INPUTS.json +10 -0
- package/docs/HANDOFF-2026-10-27.md +736 -0
- package/docs/HOOK-ORDERING.md +139 -0
- package/docs/LEGISLATION-LAW.md +4 -2
- package/docs/MCP-4.0-PLAN.md +184 -0
- package/docs/MEMORY-4.5-PLAN.md +415 -0
- package/docs/PROFILE-TUNING.md +147 -0
- package/docs/RATCHET.json +48 -0
- package/docs/RELEASE-POLICY.md +163 -0
- package/docs/RULES.md +95 -14
- package/docs/THREAT-MODEL.md +68 -0
- package/docs/TOOL-SCHEMA.json +6 -0
- package/docs/VERSION-PLAN.md +532 -0
- package/docs/WRITING-STYLE.md +109 -0
- package/docs/architecture-map.mermaid +186 -0
- package/docs/deepseek-pricing-audit.md +2 -0
- package/hooks/guard.mjs +92 -56
- package/package.json +34 -5
- package/skills/focus-thinking/SKILL.md +9 -7
- package/src/adapters/dsh/eligibility-gate.mjs +446 -23
- package/src/adapters/dsh/tool-kinds.mjs +81 -0
- package/src/core/approval.mjs +2 -8
- package/src/core/approvals.mjs +208 -0
- package/src/core/audit-writer.mjs +297 -0
- package/src/core/audit.mjs +46 -16
- package/src/core/backup.mjs +37 -11
- package/src/core/checkEligibility.mjs +7 -4
- package/src/core/constants.mjs +67 -22
- package/src/core/decisionEngine.mjs +12 -0
- package/src/core/env.mjs +147 -19
- package/src/core/grants.mjs +54 -13
- package/src/core/kpi.mjs +16 -0
- package/src/core/outputGate.mjs +77 -0
- package/src/core/patterns.mjs +129 -0
- package/src/core/prefixStability.mjs +143 -0
- package/src/core/profileLoader.mjs +40 -5
- package/src/core/progressPolicy.mjs +65 -0
- package/src/core/redlines.mjs +49 -5
- package/src/core/risk.mjs +94 -15
- package/src/core/schemaDrift.mjs +125 -0
- package/src/core/sessionScratch.mjs +147 -0
- package/src/core/stageGraph.mjs +104 -0
- package/src/core/staleCleanup.mjs +153 -0
- package/src/core/state.mjs +215 -81
- package/src/core/stopPolicy.mjs +97 -0
- package/src/core/tempPath.mjs +23 -0
- package/src/dsh/audit.mjs +168 -118
- package/src/dsh/compactionWatch/announce.mjs +117 -0
- package/src/dsh/compactionWatch.mjs +68 -153
- package/src/dsh/guard/authz.mjs +97 -0
- package/src/dsh/guard/evidence.mjs +308 -0
- package/src/dsh/guard/hardCheck.mjs +85 -0
- package/src/dsh/guard/redline.mjs +62 -0
- package/src/dsh/guard/risk.mjs +196 -0
- package/src/dsh/guard/runtime.mjs +162 -0
- package/src/dsh/guard/superpowers.mjs +70 -0
- package/src/dsh/guard/tooling.mjs +177 -0
- package/src/dsh/guard/volume.mjs +181 -0
- package/src/dsh/guard/wholeFile.mjs +109 -0
- package/src/dsh/heartbeat.mjs +76 -13
- package/src/dsh/hookOrder.mjs +101 -0
- package/src/dsh/index.js +247 -15
- package/src/dsh/pipeline.mjs +77 -854
- package/src/dsh/policy-audit.mjs +84 -0
- package/src/dsh/postProgress.mjs +400 -274
- package/src/dsh/preGuard.mjs +249 -228
- package/src/dsh/repeatGuard.mjs +98 -0
- package/src/dsh/seams/pre-step.mjs +186 -0
- package/src/dsh/seams/prompt-rules.mjs +59 -0
- package/src/dsh/seams/session-start.mjs +297 -0
- package/src/dsh/seams/shared.mjs +109 -0
- package/src/dsh/seams.mjs +95 -408
- package/src/dsh/search-hints.mjs +136 -0
- package/src/dsh/sessionScope.mjs +28 -0
- package/src/dsh/status.mjs +7 -0
- package/src/dsh/stopGuard.mjs +225 -164
- package/src/dsh/testRuntime.mjs +62 -0
- package/src/dsh/toolKindAudit.mjs +66 -0
- package/src/dsh/tools.mjs +81 -5
- package/src/dsh/traceMeta.mjs +125 -0
- package/src/dsh/value-gate.mjs +93 -0
- package/src/dsh/workspace.mjs +3 -143
- package/src/memory/index.mjs +15 -0
- package/src/memory/tags.mjs +30 -0
- package/src/memory/workspace.mjs +283 -0
- package/src/peak-cost.mjs +1 -1
- package/src/profiles/deepseek-flash.mjs +7 -1
- package/src/profiles/deepseek-pro.mjs +6 -1
- package/src/profiles/default.mjs +6 -1
- package/src/profiles/glm.mjs +6 -1
- package/src/profiles/gpt-astra.mjs +6 -1
- package/tools/bench-ab.mjs +240 -0
- package/tools/bench-cost.mjs +176 -0
- package/tools/brain-cosmic.mjs +43 -0
- package/tools/brain-view.html +853 -0
- package/tools/brain.mjs +317 -0
- package/tools/capture-fixtures.mjs +182 -0
- package/tools/case-audit.mjs +114 -0
- package/tools/collect-panel.mjs +218 -0
- package/tools/dead-export.mjs +60 -0
- package/tools/docs-lint.mjs +82 -0
- package/tools/env-fingerprint.mjs +126 -33
- package/tools/first-run-sweep.mjs +123 -0
- package/tools/focusguard.mjs +155 -0
- package/tools/gate-audit.mjs +140 -0
- package/tools/gate-inputs.mjs +115 -0
- package/tools/handoff.mjs +56 -0
- package/tools/health.mjs +182 -0
- package/tools/knowledge.mjs +118 -0
- package/tools/layering-audit.mjs +105 -0
- package/tools/lib/book-style.mjs +136 -0
- package/tools/lib/brain-core.mjs +342 -0
- package/tools/lib/brain-docs.mjs +293 -0
- package/tools/lib/brain-regions.mjs +169 -0
- package/tools/lib/brain-relate.mjs +235 -0
- package/tools/lib/brain-text.mjs +121 -0
- package/tools/lib/case-tool.mjs +186 -0
- package/tools/lib/docs-core.mjs +392 -0
- package/tools/lib/docs-version.mjs +66 -0
- package/tools/lib/envMap.mjs +31 -0
- package/tools/lib/health-core.mjs +94 -0
- package/tools/lib/import-graph.mjs +118 -0
- package/tools/lib/index-io.mjs +70 -0
- package/tools/lib/open.mjs +32 -0
- package/tools/lib/prefix-cost.mjs +143 -0
- package/tools/lib/ratchet.mjs +174 -0
- package/tools/lib/reach.mjs +28 -0
- package/tools/lib/sessionDump.mjs +80 -0
- package/tools/lib/source-text.mjs +112 -0
- package/tools/library-book.mjs +313 -0
- package/tools/library-build.mjs +50 -12
- package/tools/library-index.mjs +91 -0
- package/tools/lint.mjs +282 -0
- package/tools/log-audit.mjs +108 -0
- package/tools/manifest-sync.mjs +111 -0
- package/tools/memory-audit.mjs +67 -0
- package/tools/module-audit.mjs +56 -0
- package/tools/mutate.mjs +316 -0
- package/tools/prefix-audit.mjs +122 -0
- package/tools/prefix-drift.mjs +325 -0
- package/tools/privacy-guard.mjs +352 -0
- package/tools/quality-audit.mjs +166 -0
- package/tools/schema-fingerprint.mjs +191 -0
- package/{src/dsh → tools}/selftest.mjs +75 -22
- package/tools/smells.mjs +398 -0
- package/tools/verify-case-paths.mjs +93 -0
- package/tools/version.mjs +191 -0
- package/docs/MASTER-PLAN-2.0.0.md +0 -133
- package/docs/MASTER-PLAN-3.0.0.md +0 -76
- package/src/adapters/dsh/fg-appeal-tool.mjs +0 -47
- package/src/adapters/dsh/fg-apply-tool.mjs +0 -68
- /package/{src/adapters/dsh → hooks}/protocol.mjs +0 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 3.0.8 面板采集处理器(2026-10-22)
|
|
4
|
+
*
|
|
5
|
+
* 用途:把人工从宿主面板抄下来的六项数字,与**会话记录里的结构指标**(steps/denies/时长)合并,
|
|
6
|
+
* 复算命中率与成本,输出每轮表 + 中位数 + 与基线(3.0.7 / 10-18 A/B)的对照。
|
|
7
|
+
*
|
|
8
|
+
* 口径纪律:
|
|
9
|
+
* - 面板数字是唯一实证 token 来源;本脚本不估算 token,只做校验与汇总。
|
|
10
|
+
* - 命中率 = 缓存读取 /(缓存读取 + 未缓存输入),不含输出。若面板值与本式不符,告警。
|
|
11
|
+
* - 成本按官方价目复算;峰谷按时段判定(北京 09-12 / 14-18 工作日为峰,×2)。
|
|
12
|
+
* - 只认**同一 profile、同一 8 任务**的轮次;n<5 时输出「样本不足,仅方向参考」。
|
|
13
|
+
*
|
|
14
|
+
* 输入:JSON 数组(见 --init 生成模板)
|
|
15
|
+
* [{ "run":1, "sid":"002c143b", "at":"2026-10-22T21:20:00+08:00",
|
|
16
|
+
* "total":231544, "uncached":50561, "cacheRead":175360, "output":5623,
|
|
17
|
+
* "panelCost":0.011484, "elapsedSec":null }]
|
|
18
|
+
*
|
|
19
|
+
* 用法:
|
|
20
|
+
* node packages/core/tools/collect-panel.mjs --init # 生成模板文件
|
|
21
|
+
* node packages/core/tools/collect-panel.mjs panel.json # 汇总
|
|
22
|
+
* node packages/core/tools/collect-panel.mjs panel.json --json
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { decodeSession as decode } from './lib/sessionDump.mjs'
|
|
26
|
+
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
|
27
|
+
import { dirname, join } from 'node:path'
|
|
28
|
+
import { fileURLToPath } from 'node:url'
|
|
29
|
+
|
|
30
|
+
const HERE = dirname(fileURLToPath(import.meta.url))
|
|
31
|
+
const SESSIONS = process.env.FG_SESSIONS_DIR || 'E:/DSH/.dsh/sessions'
|
|
32
|
+
const TEMPLATE = join(process.cwd(), 'panel-runs.json')
|
|
33
|
+
|
|
34
|
+
// 官方价目(USD / 1M tokens):缓存命中 / 未缓存 / 输出;高峰 = 空闲 ×2
|
|
35
|
+
const PRICE_OFFPEAK = { cacheRead: 0.003, uncached: 0.15, output: 0.6 }
|
|
36
|
+
const PRICE_PEAK = { cacheRead: 0.006, uncached: 0.3, output: 1.2 }
|
|
37
|
+
|
|
38
|
+
function isPeak(at) {
|
|
39
|
+
const d = at ? new Date(at) : new Date()
|
|
40
|
+
// 转北京时间
|
|
41
|
+
const bj = new Date(d.getTime() + (d.getTimezoneOffset() + 480) * 60000)
|
|
42
|
+
const dow = bj.getDay()
|
|
43
|
+
const minutes = bj.getHours() * 60 + bj.getMinutes()
|
|
44
|
+
if (dow === 0 || dow === 6) return false
|
|
45
|
+
return (minutes >= 540 && minutes < 720) || (minutes >= 840 && minutes < 1080)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 面板成本单位(2026-10-22 人类确认):宿主用量面板显示的是**人民币 ¥**。
|
|
49
|
+
// 官方价目是 USD/1M,故按汇率换算后与面板核对;汇率可被 FG_USD_CNY 覆盖(默认 7.1)。
|
|
50
|
+
const USD_CNY = Number(process.env.FG_USD_CNY || 7.1)
|
|
51
|
+
|
|
52
|
+
function walk(dir, out = []) {
|
|
53
|
+
let entries = []
|
|
54
|
+
try {
|
|
55
|
+
entries = readdirSync(dir)
|
|
56
|
+
} catch {
|
|
57
|
+
return out
|
|
58
|
+
}
|
|
59
|
+
for (const e of entries) {
|
|
60
|
+
const p = join(dir, e)
|
|
61
|
+
let st
|
|
62
|
+
try {
|
|
63
|
+
st = statSync(p)
|
|
64
|
+
} catch {
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
if (st.isDirectory()) walk(p, out)
|
|
68
|
+
else if (e === 'session.v4.jsonl.zstd') out.push(p)
|
|
69
|
+
}
|
|
70
|
+
return out
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const FILES = walk(SESSIONS)
|
|
74
|
+
|
|
75
|
+
/** 从会话记录取结构指标:steps / denies / 工具调用 / 时长。 */
|
|
76
|
+
function structureOf(sidPrefix) {
|
|
77
|
+
if (!sidPrefix) return null
|
|
78
|
+
const file = FILES.find((f) => f.includes(String(sidPrefix).replace(/^session-/, '')))
|
|
79
|
+
if (!file) return { found: false }
|
|
80
|
+
const lines = decode(file)
|
|
81
|
+
const stepStarts = lines.filter((l) => l.type === 'step/start').length
|
|
82
|
+
const turns = lines.filter((l) => l.type === 'turn/start').length
|
|
83
|
+
const calls = lines.filter((l) => l.type === 'tool/call')
|
|
84
|
+
// 拦截计数:按 FG 的真实拒绝文案判定(2026-10-22 修:只用 deny/拦截 会漏掉
|
|
85
|
+
// 「本机环境:用 bat 替代 cat」「该工具需先调 fg_apply」「命中绝对红线」等不同措辞)。
|
|
86
|
+
const DENY_RE = /focus-guard-native|拦截|红线|fg_apply|绝对|本机环境|禁|取证记录/
|
|
87
|
+
const denies = lines.filter((l) => l.type === 'tool/result' && DENY_RE.test(JSON.stringify(l.data)))
|
|
88
|
+
const first = lines.find((l) => l.type === 'turn/start')
|
|
89
|
+
const last = lines.filter((l) => l.type === 'turn/end').pop() || lines[lines.length - 1]
|
|
90
|
+
const t0 = first && first.data && first.data.at ? Date.parse(first.data.at) : null
|
|
91
|
+
const t1 = last && last.data && last.data.at ? Date.parse(last.data.at) : null
|
|
92
|
+
return {
|
|
93
|
+
found: true,
|
|
94
|
+
file,
|
|
95
|
+
turns,
|
|
96
|
+
steps: stepStarts,
|
|
97
|
+
toolCalls: calls.length,
|
|
98
|
+
denies: denies.length,
|
|
99
|
+
elapsedSec: t0 && t1 ? Math.round((t1 - t0) / 1000) : null,
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function summarize(runs) {
|
|
104
|
+
const rows = runs.map((r) => {
|
|
105
|
+
const peak = isPeak(r.at)
|
|
106
|
+
const price = peak ? PRICE_PEAK : PRICE_OFFPEAK
|
|
107
|
+
const total = Number(r.total) || 0
|
|
108
|
+
const uncached = Number(r.uncached) || 0
|
|
109
|
+
const cacheRead = Number(r.cacheRead) || 0
|
|
110
|
+
const output = Number(r.output) || 0
|
|
111
|
+
const sum = uncached + cacheRead + output
|
|
112
|
+
const cost =
|
|
113
|
+
(cacheRead * price.cacheRead + uncached * price.uncached + output * price.output) / 1e6
|
|
114
|
+
const hit = cacheRead + uncached > 0 ? (cacheRead / (cacheRead + uncached)) * 100 : null
|
|
115
|
+
const st = structureOf(r.sid)
|
|
116
|
+
return {
|
|
117
|
+
run: r.run ?? null,
|
|
118
|
+
sid: r.sid || null,
|
|
119
|
+
at: r.at || null,
|
|
120
|
+
peak,
|
|
121
|
+
total,
|
|
122
|
+
uncached,
|
|
123
|
+
cacheRead,
|
|
124
|
+
output,
|
|
125
|
+
sum,
|
|
126
|
+
sumMatches: total ? sum === total : null,
|
|
127
|
+
hitRate: hit,
|
|
128
|
+
cost,
|
|
129
|
+
costCNY: Number((cost * USD_CNY).toFixed(6)),
|
|
130
|
+
panelCost: r.panelCost == null ? null : Number(r.panelCost),
|
|
131
|
+
// 面板成本是 ¥,故与 costCNY 比;差额 >0.002 视为口径不一致
|
|
132
|
+
costDelta: r.panelCost == null ? null : Number((cost * USD_CNY - Number(r.panelCost)).toFixed(6)),
|
|
133
|
+
steps: st && st.found ? st.steps : null,
|
|
134
|
+
denies: st && st.found ? st.denies : null,
|
|
135
|
+
elapsedSec: r.elapsedSec ?? (st && st.found ? st.elapsedSec : null),
|
|
136
|
+
structureFound: Boolean(st && st.found),
|
|
137
|
+
}
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
const med = (k) => {
|
|
141
|
+
const v = rows.map((x) => x[k]).filter((x) => typeof x === 'number' && Number.isFinite(x)).sort((a, b) => a - b)
|
|
142
|
+
if (!v.length) return null
|
|
143
|
+
const m = Math.floor(v.length / 2)
|
|
144
|
+
return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
runs: rows,
|
|
149
|
+
median: {
|
|
150
|
+
total: med('total'),
|
|
151
|
+
uncached: med('uncached'),
|
|
152
|
+
cacheRead: med('cacheRead'),
|
|
153
|
+
hitRate: med('hitRate'),
|
|
154
|
+
cost: med('cost'),
|
|
155
|
+
steps: med('steps'),
|
|
156
|
+
denies: med('denies'),
|
|
157
|
+
elapsedSec: med('elapsedSec'),
|
|
158
|
+
},
|
|
159
|
+
n: rows.length,
|
|
160
|
+
note: rows.length < 5 ? '样本不足 5 轮:仅方向参考,不得作为结论(BENCH.md A/B 协议)' : '达到 ≥5 轮,可作为 3.0.8 基线',
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function fmt(v, digits = 0) {
|
|
165
|
+
if (v == null || Number.isNaN(v)) return '—'
|
|
166
|
+
return digits ? Number(v).toFixed(digits) : String(Math.round(v))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const args = process.argv.slice(2)
|
|
170
|
+
if (args.includes('--init')) {
|
|
171
|
+
if (existsSync(TEMPLATE)) {
|
|
172
|
+
console.log(`已存在:${TEMPLATE}(不覆盖)`)
|
|
173
|
+
process.exit(0)
|
|
174
|
+
}
|
|
175
|
+
const tpl = [1, 2, 3, 4, 5].map((i) => ({
|
|
176
|
+
run: i,
|
|
177
|
+
sid: '',
|
|
178
|
+
at: '',
|
|
179
|
+
total: 0,
|
|
180
|
+
uncached: 0,
|
|
181
|
+
cacheRead: 0,
|
|
182
|
+
output: 0,
|
|
183
|
+
panelCost: null,
|
|
184
|
+
elapsedSec: null,
|
|
185
|
+
}))
|
|
186
|
+
writeFileSync(TEMPLATE, JSON.stringify(tpl, null, 2))
|
|
187
|
+
console.log(`已生成模板:${TEMPLATE}\n填写每轮的 sid(会话 id 前 8 位即可)与面板六项后运行本脚本。`)
|
|
188
|
+
process.exit(0)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const input = args.find((a) => !a.startsWith('--'))
|
|
192
|
+
if (!input || !existsSync(input)) {
|
|
193
|
+
console.error('用法:node packages/core/tools/collect-panel.mjs <panel.json> [--json](--init 生成模板)')
|
|
194
|
+
process.exit(2)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const runs = JSON.parse(readFileSync(input, 'utf8'))
|
|
198
|
+
const result = summarize(Array.isArray(runs) ? runs : [runs])
|
|
199
|
+
|
|
200
|
+
if (args.includes('--json')) {
|
|
201
|
+
console.log(JSON.stringify(result, null, 2))
|
|
202
|
+
process.exit(0)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
console.log('轮次 | sid | 峰/谷 | 总 token | 未缓存 | 缓存读取 | 输出 | 命中率 | 成本$ | 成本¥ | 面板¥ | 差额 | steps | denies | 耗时 s')
|
|
206
|
+
for (const r of result.runs) {
|
|
207
|
+
const flag = r.sumMatches === false ? ' ⚠求和不等' : ''
|
|
208
|
+
const drift = r.costDelta != null && Math.abs(r.costDelta) > 0.002 ? ' ⚠成本不符' : ''
|
|
209
|
+
console.log(
|
|
210
|
+
`${fmt(r.run)} | ${String(r.sid || '-').slice(0, 8)} | ${r.peak ? '峰' : '谷'} | ${fmt(r.total).padStart(9)} | ${fmt(r.uncached).padStart(8)} | ${fmt(r.cacheRead).padStart(9)} | ${fmt(r.output).padStart(6)} | ${fmt(r.hitRate, 2).padStart(6)}% | ${fmt(r.cost, 6).padStart(7)} | ${fmt(r.costCNY, 4).padStart(7)} | ${fmt(r.panelCost, 4).padStart(7)} | ${fmt(r.costDelta, 4).padStart(6)} | ${fmt(r.steps).padStart(5)} | ${fmt(r.denies).padStart(6)} | ${fmt(r.elapsedSec).padStart(6)}${flag}${drift}`,
|
|
211
|
+
)
|
|
212
|
+
}
|
|
213
|
+
const m = result.median
|
|
214
|
+
console.log(
|
|
215
|
+
`\n中位数:总 ${fmt(m.total)} / 未缓存 ${fmt(m.uncached)} / 缓存读取 ${fmt(m.cacheRead)} / 命中率 ${fmt(m.hitRate, 2)}% / 成本 $${fmt(m.cost, 6)} / steps ${fmt(m.steps)} / denies ${fmt(m.denies)}`,
|
|
216
|
+
)
|
|
217
|
+
console.log(`n=${result.n} · ${result.note}`)
|
|
218
|
+
process.exit(0)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 死导出检查(2026-10-25):找出"导出了但没人调用"的符号——模块活着、功能没接上的典型形态。
|
|
4
|
+
* 只读。排除:tests/ 内的引用不算使用者;同名不同文件的第二个实现会单独列出。
|
|
5
|
+
*/
|
|
6
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
|
7
|
+
import { dirname, join, relative } from 'node:path'
|
|
8
|
+
import { fileURLToPath } from 'node:url'
|
|
9
|
+
|
|
10
|
+
const HERE = dirname(fileURLToPath(import.meta.url))
|
|
11
|
+
const CORE = join(HERE, '..')
|
|
12
|
+
const ROOTS = ['src', 'hooks', 'tools']
|
|
13
|
+
|
|
14
|
+
function walk(dir, out = []) {
|
|
15
|
+
let entries = []
|
|
16
|
+
try {
|
|
17
|
+
entries = readdirSync(dir)
|
|
18
|
+
} catch {
|
|
19
|
+
return out
|
|
20
|
+
}
|
|
21
|
+
for (const e of entries) {
|
|
22
|
+
const p = join(dir, e)
|
|
23
|
+
const st = statSync(p)
|
|
24
|
+
if (st.isDirectory()) walk(p, out)
|
|
25
|
+
else if (/\.(mjs|js)$/.test(e)) out.push(p)
|
|
26
|
+
}
|
|
27
|
+
return out
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const files = ROOTS.flatMap((r) => walk(join(CORE, r)))
|
|
31
|
+
const sources = new Map()
|
|
32
|
+
for (const f of files) sources.set(f, readFileSync(f, 'utf8'))
|
|
33
|
+
const testsText = (() => {
|
|
34
|
+
const tests = walk(join(CORE, 'tests'))
|
|
35
|
+
return tests.map((f) => readFileSync(f, 'utf8')).join('\n')
|
|
36
|
+
})()
|
|
37
|
+
|
|
38
|
+
const exportRe = /export\s+(?:async\s+)?(?:function|const|let|class)\s+([A-Za-z_$][\w$]*)/g
|
|
39
|
+
const findings = []
|
|
40
|
+
for (const [file, src] of sources) {
|
|
41
|
+
const rel = relative(CORE, file).replace(/\\/g, '/')
|
|
42
|
+
for (const m of src.matchAll(exportRe)) {
|
|
43
|
+
const name = m[1]
|
|
44
|
+
let uses = 0
|
|
45
|
+
for (const [other, osrc] of sources) {
|
|
46
|
+
if (other === file) continue
|
|
47
|
+
// 粗略:出现该符号名即算一次使用(含 import 与调用);元字符全转义(CodeQL regex-injection)
|
|
48
|
+
const esc = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
49
|
+
const re = new RegExp(`\\b${esc}\\b`, 'g')
|
|
50
|
+
uses += (osrc.match(re) || []).length
|
|
51
|
+
}
|
|
52
|
+
const escName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
53
|
+
const inTests = new RegExp(`\\b${escName}\\b`).test(testsText)
|
|
54
|
+
if (uses === 0) findings.push({ rel, name, inTests })
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
findings.sort((a, b) => a.rel.localeCompare(b.rel))
|
|
59
|
+
console.log(`死导出候选 ${findings.length} 个(被 tests 引用的标注 *)`)
|
|
60
|
+
for (const f of findings) console.log(` ${f.rel.padEnd(42)} ${f.name}${f.inTests ? ' *仅测试使用' : ''}`)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 文档口径检查(3.3 D5):版本面 + 相对链接。零依赖。
|
|
3
|
+
*
|
|
4
|
+
* 用法:
|
|
5
|
+
* node packages/core/tools/docs-lint.mjs # 明细
|
|
6
|
+
* node packages/core/tools/docs-lint.mjs --brief # 一行(供 npm run check)
|
|
7
|
+
* node packages/core/tools/docs-lint.mjs --json # 机器读
|
|
8
|
+
* node packages/core/tools/docs-lint.mjs --strict # 有问题即 exit 1
|
|
9
|
+
*
|
|
10
|
+
* 闸门是棘轮:`BUDGET` 记当前存量(初始 0),只许降不许升。
|
|
11
|
+
* 这是 3.5「文档重置完成」的前置尺子(D5);README 硬指标、数字单点、状态头分别归 D1/D4/D2。
|
|
12
|
+
*/
|
|
13
|
+
import { fileURLToPath } from 'node:url'
|
|
14
|
+
import {
|
|
15
|
+
listMarkdownFiles,
|
|
16
|
+
checkVersionFace,
|
|
17
|
+
checkRelativeLinks,
|
|
18
|
+
checkCodePathRefs,
|
|
19
|
+
checkStatusHeaders,
|
|
20
|
+
checkIndexCoverage,
|
|
21
|
+
allDocFiles,
|
|
22
|
+
checkReadmeMetrics,
|
|
23
|
+
checkCitationStyle,
|
|
24
|
+
} from './lib/docs-core.mjs'
|
|
25
|
+
import { checkVersionClaims } from './lib/docs-version.mjs'
|
|
26
|
+
|
|
27
|
+
const ROOT = fileURLToPath(new URL('../../../', import.meta.url))
|
|
28
|
+
const argv = process.argv.slice(2)
|
|
29
|
+
const AS_JSON = argv.includes('--json')
|
|
30
|
+
const BRIEF = argv.includes('--brief')
|
|
31
|
+
const STRICT = argv.includes('--strict')
|
|
32
|
+
const BUDGET = 0
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 按规则的存量豁免(3.3 A)。
|
|
36
|
+
*
|
|
37
|
+
* 原为 `{ 'dead-code-path': 5 }`——那 5 条全在 CHANGELOG 的历史段里,指向当年存在、后来搬走的文件。
|
|
38
|
+
* 2026-11-07 历史段(≤3.0.7)原样移入 `docs/archive/`(不在扫描面内),存量归零,额度一并收回。
|
|
39
|
+
* 判据:豁免是**存量**的记账。存量没了还留着额度,等于给未来的死链预留藏身处。
|
|
40
|
+
*/
|
|
41
|
+
const RULE_BUDGET = { 'dead-code-path': 0 }
|
|
42
|
+
|
|
43
|
+
const files = listMarkdownFiles(ROOT)
|
|
44
|
+
const findings = [
|
|
45
|
+
...checkVersionFace(ROOT),
|
|
46
|
+
...checkRelativeLinks(ROOT, files),
|
|
47
|
+
...checkCodePathRefs(ROOT, files),
|
|
48
|
+
...checkStatusHeaders(ROOT),
|
|
49
|
+
...checkIndexCoverage(ROOT, allDocFiles(ROOT)),
|
|
50
|
+
...checkReadmeMetrics(ROOT),
|
|
51
|
+
...checkCitationStyle(ROOT),
|
|
52
|
+
...checkVersionClaims(ROOT),
|
|
53
|
+
]
|
|
54
|
+
const byRule = {}
|
|
55
|
+
for (const f of findings) byRule[f.rule] = (byRule[f.rule] || 0) + 1
|
|
56
|
+
// 超限数按规则算:某规则在自己的豁免内不算超限,别让历史存量压住新问题
|
|
57
|
+
const over = Object.entries(byRule).reduce(
|
|
58
|
+
(sum, [rule, n]) => sum + Math.max(0, n - (RULE_BUDGET[rule] || 0)),
|
|
59
|
+
0,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
if (AS_JSON) {
|
|
63
|
+
console.log(JSON.stringify({ files: files.length, findings, byRule, budget: BUDGET, ruleBudget: RULE_BUDGET, over }, null, 2))
|
|
64
|
+
} else if (BRIEF) {
|
|
65
|
+
const parts = Object.entries(byRule)
|
|
66
|
+
.sort((a, b) => b[1] - a[1])
|
|
67
|
+
.map(([r, n]) => `${r} ${n}${RULE_BUDGET[r] ? `(豁免${RULE_BUDGET[r]})` : ''}`)
|
|
68
|
+
const gate = over > BUDGET ? `❌ 超上限 ${BUDGET}` : `✅ 上限 ${BUDGET}`
|
|
69
|
+
console.log(`文档口径:${files.length} 个 md,问题 ${findings.length} 条${parts.length ? `(${parts.join(' / ')})` : ''};${gate}`)
|
|
70
|
+
} else {
|
|
71
|
+
console.log(`文档口径:${files.length} 个 md,问题 ${findings.length} 条\n`)
|
|
72
|
+
if (!findings.length) console.log('无问题(版本面一致 / 相对链接全部可达 / 行内路径全部可达)。')
|
|
73
|
+
for (const f of findings) {
|
|
74
|
+
const allow = RULE_BUDGET[f.rule] ? '(存量豁免)' : ''
|
|
75
|
+
console.log(`${f.file}:${f.line}\t[${f.rule}]${allow} ${f.detail}`)
|
|
76
|
+
}
|
|
77
|
+
console.log(`\n闸门口径:超限 ${over} 条 / 上限 ${BUDGET}(棘轮,只许降不许升)。`)
|
|
78
|
+
for (const [rule, n] of Object.entries(RULE_BUDGET)) {
|
|
79
|
+
console.log(` 豁免:${rule} 最多 ${n} 条(当前 ${byRule[rule] || 0} 条)`)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
process.exit(STRICT && over > BUDGET ? 1 : 0)
|
|
@@ -1,16 +1,26 @@
|
|
|
1
|
-
// FocusGuard
|
|
1
|
+
// FocusGuard 环境档案生成器(v2,2026-11-09)
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
3
|
+
// 探测平台、可用执行体、工具可用性,产出 <项目根>/.ai/env-fingerprint.json。
|
|
4
|
+
// 该文件同时是两件事的来源:
|
|
5
|
+
// ① 「命令硬校验」的规则表(map):key = 本机不鼓励直接用的命令,value = 替代命令;
|
|
6
|
+
// ② 环境档案(machine / shells / probe):给模型看「这台机器有什么、哪个是自带的」。
|
|
5
7
|
// 指纹缺失时硬校验 fail-open(跳过 + warn),不会阻断任何命令。
|
|
6
8
|
//
|
|
7
|
-
// 用法:node packages/core/tools/env-fingerprint.mjs [--out <路径>]
|
|
9
|
+
// 用法:node packages/core/tools/env-fingerprint.mjs [--out <路径>] [--shell <id>]
|
|
10
|
+
// --shell 本会话实际执行体(由适配层传入)。不传则记探测到的首选,并标 source=probe。
|
|
11
|
+
//
|
|
12
|
+
// TTL 不固定:连续探测结果不变则间隔翻倍(6h → 12h → 24h … 上限 30 天),一变立刻回到 6h。
|
|
13
|
+
// 判据:环境是低频变化的东西,天天重探是浪费;但一旦变了(装了新终端),必须马上看见。
|
|
8
14
|
|
|
9
|
-
import { writeFileSync, mkdirSync, existsSync } from "node:fs";
|
|
15
|
+
import { writeFileSync, mkdirSync, existsSync, readFileSync } from "node:fs";
|
|
10
16
|
import { join, dirname, delimiter } from "node:path";
|
|
11
17
|
import { execFileSync } from "node:child_process";
|
|
18
|
+
import { hostname } from "node:os";
|
|
19
|
+
import { buildEnvMap, droppedAlternatives } from "./lib/envMap.mjs";
|
|
20
|
+
import { osLabel, probeShellDetails } from "../src/core/env.mjs";
|
|
12
21
|
|
|
13
22
|
// PATH 补全:宿主进程的 PATH 可能是启动时的旧快照,补上常见安装位置后再探测(只影响本脚本)。
|
|
23
|
+
// 注意:这不是"假设装在 C 盘"——只是把 scoop/winget 的 shim 目录补进 PATH,探不到就当没有。
|
|
14
24
|
const EXTRA_PATH_DIRS = [
|
|
15
25
|
join(process.env.USERPROFILE || "", "scoop", "shims"),
|
|
16
26
|
join(process.env.LOCALAPPDATA || "", "Microsoft", "WinGet", "Links"),
|
|
@@ -22,6 +32,10 @@ const MAP = { grep: "rg", find: "fd", ls: "eza", cat: "bat", sed: "sd" };
|
|
|
22
32
|
// 探测范围:map 的 key 与 value,外加常用运行时与增强工具
|
|
23
33
|
const PROBE = ["rg", "fd", "eza", "bat", "sd", "grep", "sed", "less", "jq", "yq", "fzf", "zoxide", "node", "python", "git"];
|
|
24
34
|
|
|
35
|
+
/** TTL 自适应:首次 6 小时,连续未变逐次翻倍,上限 30 天。 */
|
|
36
|
+
const TTL_FIRST = 6 * 3600e3;
|
|
37
|
+
const TTL_CEIL = 30 * 86400e3;
|
|
38
|
+
|
|
25
39
|
function probe(tool) {
|
|
26
40
|
for (const args of [["--version"], ["-v"], ["--help"]]) {
|
|
27
41
|
try {
|
|
@@ -34,25 +48,6 @@ function probe(tool) {
|
|
|
34
48
|
return false;
|
|
35
49
|
}
|
|
36
50
|
|
|
37
|
-
function shellVersion(exe) {
|
|
38
|
-
try {
|
|
39
|
-
return execFileSync(exe, ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()"], { encoding: "utf8", timeout: 6000 }).trim();
|
|
40
|
-
} catch {
|
|
41
|
-
return "";
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function detectShell() {
|
|
46
|
-
if (process.platform !== "win32") return String(process.env.SHELL || "sh").split(/[\\/]/).pop() || "sh";
|
|
47
|
-
// Windows:ComSpec 恒指向 cmd.exe,会误判;以实际可用的现代 shell 为准,并带版本号。
|
|
48
|
-
const pwsh = shellVersion("pwsh");
|
|
49
|
-
if (pwsh) return `pwsh ${pwsh}`;
|
|
50
|
-
const ps = shellVersion("powershell");
|
|
51
|
-
if (ps) return `powershell ${ps}`;
|
|
52
|
-
const cs = String(process.env.ComSpec || "");
|
|
53
|
-
return cs.toLowerCase().includes("cmd") ? "cmd" : "unknown";
|
|
54
|
-
}
|
|
55
|
-
|
|
56
51
|
function detectEncoding() {
|
|
57
52
|
if (process.platform !== "win32") return "UTF-8";
|
|
58
53
|
try {
|
|
@@ -63,26 +58,124 @@ function detectEncoding() {
|
|
|
63
58
|
}
|
|
64
59
|
}
|
|
65
60
|
|
|
61
|
+
/**
|
|
62
|
+
* 命令工具的**语法实现**探测(2026-11-09)。
|
|
63
|
+
*
|
|
64
|
+
* 为什么需要:同一条命令在不同实现上行为不同,而且差别是**静默**的——
|
|
65
|
+
* · BSD sed 的 `-i` 必须带后缀(`sed -i '' …`),GNU sed 带了反而把后缀当文件名;
|
|
66
|
+
* · BSD grep 没有 `-P`(Perl 正则);
|
|
67
|
+
* · GNU find 有 `-printf`,BSD find 没有。
|
|
68
|
+
* 原来这套判断靠 `os === 'darwin'` 硬推——macOS 上 `brew install gnu-sed` 之后就全错了。
|
|
69
|
+
* 现在改成探**实际实现**:跑一次 `--version` 看它自报什么(BSD 工具不认这个参数,
|
|
70
|
+
* 会往 stderr 吐 "illegal option",那就判 bsd)。
|
|
71
|
+
*
|
|
72
|
+
* 只在生成器里跑(后台 spawn),会话启动只读档案——探测本身要花几百毫秒。
|
|
73
|
+
*/
|
|
74
|
+
function probeCommand(name) {
|
|
75
|
+
const run = (args) => {
|
|
76
|
+
try {
|
|
77
|
+
return String(execFileSync(name, args, { encoding: "utf8", timeout: 2500, stdio: ["ignore", "pipe", "pipe"] }) || "");
|
|
78
|
+
} catch (e) {
|
|
79
|
+
// BSD 工具把 --version 当非法参数,信息在 stderr;有输出就用它判型。
|
|
80
|
+
return String((e && (e.stdout || e.stderr)) || "");
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const v = run(["--version"]);
|
|
84
|
+
if (!v.trim()) return null;
|
|
85
|
+
let impl = "unknown";
|
|
86
|
+
if (/GNU/i.test(v)) impl = "gnu";
|
|
87
|
+
else if (/BSD/i.test(v)) impl = "bsd";
|
|
88
|
+
else if (/busybox/i.test(v)) impl = "busybox";
|
|
89
|
+
else if (/illegal option|invalid option/i.test(v)) impl = "bsd";
|
|
90
|
+
else if (/ripgrep/i.test(v)) impl = "ripgrep";
|
|
91
|
+
const ver = (v.match(/\b(\d+\.\d+(?:\.\d+)?)\b/) || [])[1] || "";
|
|
92
|
+
return { impl, version: ver };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 只探这几个有"同工具不同语法"问题的;其余工具没有跨实现的行为差异。 */
|
|
96
|
+
const SYNTAX_PROBES = ["grep", "sed", "find", "awk", "xargs", "tar"];
|
|
97
|
+
|
|
98
|
+
const argOf = (name) => {
|
|
99
|
+
const i = process.argv.indexOf(name);
|
|
100
|
+
return i >= 0 ? process.argv[i + 1] : undefined;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const out = argOf("--out") || join(process.cwd(), ".ai", "env-fingerprint.json");
|
|
104
|
+
|
|
105
|
+
/** 读旧档案:机器编号、首次见到的时刻、已有反馈都要继承,不能每次重探就重发一个新编号。 */
|
|
106
|
+
let prev = null;
|
|
107
|
+
try {
|
|
108
|
+
prev = JSON.parse(readFileSync(out, "utf8"));
|
|
109
|
+
} catch {
|
|
110
|
+
/* 首次生成,或文件损坏 —— 按新建处理 */
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const now = Date.now();
|
|
114
|
+
const shells = probeShellDetails();
|
|
115
|
+
// 命令语法实现(GNU / BSD / busybox + 版本)。只探有跨实现差异的那几个。
|
|
116
|
+
const commands = {};
|
|
117
|
+
for (const name of SYNTAX_PROBES) {
|
|
118
|
+
const p = probeCommand(name);
|
|
119
|
+
if (p) commands[name] = p;
|
|
120
|
+
}
|
|
66
121
|
const available = [];
|
|
67
122
|
const unavailable = [];
|
|
68
123
|
for (const t of PROBE) (probe(t) ? available : unavailable).push(t);
|
|
69
124
|
|
|
125
|
+
// 机器编号:首次分配 A;已有则沿用;FG_MACHINE_ID 可覆盖(多台机器时手动指定 B/C…)。
|
|
126
|
+
const machine = {
|
|
127
|
+
id: String(process.env.FG_MACHINE_ID || prev?.machine?.id || "A").trim() || "A",
|
|
128
|
+
host: hostname(),
|
|
129
|
+
arch: process.arch,
|
|
130
|
+
firstSeen: prev?.machine?.firstSeen || new Date(now).toISOString(),
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
// 「变了没有」只看平台与执行体集合——工具装了新版本不该把 TTL 重置。
|
|
134
|
+
const shellKey = shells.map((s) => s.id).join(",");
|
|
135
|
+
const changed = Boolean(prev) && (prev?.platform?.os !== process.platform || prev?.shells?.map?.((s) => s.id).join(",") !== shellKey);
|
|
136
|
+
const streak = changed ? 0 : Math.min((prev?.probe?.streak || 0) + 1, 12);
|
|
137
|
+
const ttlMs = Math.min(TTL_FIRST * 2 ** streak, TTL_CEIL);
|
|
138
|
+
|
|
139
|
+
const sessionShell = String(argOf("--shell") || "").trim();
|
|
70
140
|
const fingerprint = {
|
|
71
|
-
|
|
72
|
-
|
|
141
|
+
schema: 2,
|
|
142
|
+
machine,
|
|
143
|
+
platform: {
|
|
144
|
+
os: process.platform,
|
|
145
|
+
// win32 是 Node 的 API 名,不是"32 位系统"——对外一律给 Windows/x64。
|
|
146
|
+
osLabel: osLabel(process.platform, process.arch),
|
|
147
|
+
shell: sessionShell || shells[0]?.id || "unknown",
|
|
148
|
+
shellSource: sessionShell ? "session" : "probe",
|
|
149
|
+
encoding: detectEncoding(),
|
|
150
|
+
},
|
|
151
|
+
shells,
|
|
152
|
+
// 同一条命令在不同实现上的语法差异(BSD sed 的 -i 要后缀、BSD grep 无 -P、GNU find 有 -printf)。
|
|
153
|
+
// 报告给模型,让它写命令前就知道该用哪套写法——这比事后拦一条更省事。
|
|
154
|
+
commands,
|
|
73
155
|
tools: { available, unavailable },
|
|
74
|
-
map:
|
|
156
|
+
map: buildEnvMap(MAP, available),
|
|
157
|
+
probe: {
|
|
158
|
+
at: new Date(now).toISOString(),
|
|
159
|
+
ttlMs,
|
|
160
|
+
streak,
|
|
161
|
+
changed,
|
|
162
|
+
nextAt: new Date(now + ttlMs).toISOString(),
|
|
163
|
+
},
|
|
164
|
+
// 模型/人类回填的补充说明(fg_env 工具写入)。探测只看得到 PATH,看不到"这个 pwsh 是谁装的"。
|
|
165
|
+
notes: Array.isArray(prev?.notes) ? prev.notes : [],
|
|
75
166
|
};
|
|
76
167
|
|
|
77
|
-
const outIdx = process.argv.indexOf("--out");
|
|
78
|
-
const out = outIdx >= 0 ? process.argv[outIdx + 1] : join(process.cwd(), ".ai", "env-fingerprint.json");
|
|
79
168
|
mkdirSync(dirname(out), { recursive: true });
|
|
80
169
|
writeFileSync(out, JSON.stringify(fingerprint, null, 2) + "\n", "utf8");
|
|
81
170
|
|
|
82
|
-
const missingAlt =
|
|
171
|
+
const missingAlt = droppedAlternatives(MAP, available);
|
|
172
|
+
const shellText = shells.map((s) => `${s.id}(${s.origin === "builtin" ? "自带" : "额外"})`).join(" ");
|
|
83
173
|
console.log(`env-fingerprint:${out}`);
|
|
84
|
-
console.log(`
|
|
85
|
-
console.log(`
|
|
174
|
+
console.log(` 机器 ${machine.id} · ${machine.host} · ${fingerprint.platform.osLabel}`);
|
|
175
|
+
console.log(` 执行体 ${fingerprint.platform.shell}(来源 ${fingerprint.platform.shellSource})/ 可用 ${shellText}`);
|
|
176
|
+
console.log(` 编码 ${fingerprint.platform.encoding} / 下次重探 ${fingerprint.probe.nextAt}(${Math.round(ttlMs / 3600e3)}h,连续未变 ${streak} 次)`);
|
|
177
|
+
console.log(` 命令语法 ${Object.entries(commands).map(([k, v]) => `${k}=${v.impl}${v.version ? " " + v.version : ""}`).join(" ") || "-"}`);
|
|
178
|
+
console.log(` 可用工具 ${available.join(" ") || "-"}`);
|
|
86
179
|
console.log(` 不可用 ${unavailable.join(" ") || "-"}`);
|
|
87
180
|
console.log(` map ${Object.entries(MAP).map(([k, v]) => `${k}→${v}`).join(" ")}`);
|
|
88
|
-
if (missingAlt.length) console.log(` [
|
|
181
|
+
if (missingAlt.length) console.log(` [已剔除] 替代工具未安装:${missingAlt.join(" ")}——这些 key 不进 map,硬校验不会拒它们(否则会建议一个不存在的命令)`);
|