focus-guard 3.0.7 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/LICENSE +683 -21
  2. package/NOTICE +25 -0
  3. package/README.md +14 -9
  4. package/README.zh-CN.md +12 -9
  5. package/docs/AB-PROMPTS.md +123 -0
  6. package/docs/AB-SESSION.md +161 -0
  7. package/docs/ARCH-MAP.md +148 -0
  8. package/docs/BENCH-BASELINE.json +95 -0
  9. package/docs/BENCH.md +323 -0
  10. package/docs/GATE-INPUTS.json +10 -0
  11. package/docs/HANDOFF-2026-10-27.md +736 -0
  12. package/docs/HOOK-ORDERING.md +139 -0
  13. package/docs/LEGISLATION-LAW.md +4 -2
  14. package/docs/MCP-4.0-PLAN.md +184 -0
  15. package/docs/MEMORY-4.5-PLAN.md +415 -0
  16. package/docs/PROFILE-TUNING.md +147 -0
  17. package/docs/RATCHET.json +48 -0
  18. package/docs/RELEASE-POLICY.md +163 -0
  19. package/docs/RULES.md +95 -14
  20. package/docs/THREAT-MODEL.md +68 -0
  21. package/docs/TOOL-SCHEMA.json +6 -0
  22. package/docs/VERSION-PLAN.md +532 -0
  23. package/docs/WRITING-STYLE.md +109 -0
  24. package/docs/architecture-map.mermaid +186 -0
  25. package/docs/deepseek-pricing-audit.md +2 -0
  26. package/hooks/guard.mjs +92 -56
  27. package/package.json +34 -5
  28. package/skills/focus-thinking/SKILL.md +9 -7
  29. package/src/adapters/dsh/eligibility-gate.mjs +446 -23
  30. package/src/adapters/dsh/tool-kinds.mjs +81 -0
  31. package/src/core/approval.mjs +2 -8
  32. package/src/core/approvals.mjs +208 -0
  33. package/src/core/audit-writer.mjs +297 -0
  34. package/src/core/audit.mjs +46 -16
  35. package/src/core/backup.mjs +37 -11
  36. package/src/core/checkEligibility.mjs +7 -4
  37. package/src/core/constants.mjs +67 -22
  38. package/src/core/decisionEngine.mjs +12 -0
  39. package/src/core/env.mjs +147 -19
  40. package/src/core/grants.mjs +54 -13
  41. package/src/core/kpi.mjs +16 -0
  42. package/src/core/outputGate.mjs +77 -0
  43. package/src/core/patterns.mjs +129 -0
  44. package/src/core/prefixStability.mjs +143 -0
  45. package/src/core/profileLoader.mjs +40 -5
  46. package/src/core/progressPolicy.mjs +65 -0
  47. package/src/core/redlines.mjs +49 -5
  48. package/src/core/risk.mjs +94 -15
  49. package/src/core/schemaDrift.mjs +125 -0
  50. package/src/core/sessionScratch.mjs +147 -0
  51. package/src/core/stageGraph.mjs +104 -0
  52. package/src/core/staleCleanup.mjs +153 -0
  53. package/src/core/state.mjs +215 -81
  54. package/src/core/stopPolicy.mjs +97 -0
  55. package/src/core/tempPath.mjs +23 -0
  56. package/src/dsh/audit.mjs +168 -118
  57. package/src/dsh/compactionWatch/announce.mjs +117 -0
  58. package/src/dsh/compactionWatch.mjs +68 -153
  59. package/src/dsh/guard/authz.mjs +97 -0
  60. package/src/dsh/guard/evidence.mjs +308 -0
  61. package/src/dsh/guard/hardCheck.mjs +85 -0
  62. package/src/dsh/guard/redline.mjs +62 -0
  63. package/src/dsh/guard/risk.mjs +196 -0
  64. package/src/dsh/guard/runtime.mjs +162 -0
  65. package/src/dsh/guard/superpowers.mjs +70 -0
  66. package/src/dsh/guard/tooling.mjs +177 -0
  67. package/src/dsh/guard/volume.mjs +181 -0
  68. package/src/dsh/guard/wholeFile.mjs +109 -0
  69. package/src/dsh/heartbeat.mjs +76 -13
  70. package/src/dsh/hookOrder.mjs +101 -0
  71. package/src/dsh/index.js +247 -15
  72. package/src/dsh/pipeline.mjs +77 -854
  73. package/src/dsh/policy-audit.mjs +84 -0
  74. package/src/dsh/postProgress.mjs +400 -274
  75. package/src/dsh/preGuard.mjs +249 -228
  76. package/src/dsh/repeatGuard.mjs +98 -0
  77. package/src/dsh/seams/pre-step.mjs +186 -0
  78. package/src/dsh/seams/prompt-rules.mjs +59 -0
  79. package/src/dsh/seams/session-start.mjs +297 -0
  80. package/src/dsh/seams/shared.mjs +109 -0
  81. package/src/dsh/seams.mjs +95 -408
  82. package/src/dsh/search-hints.mjs +136 -0
  83. package/src/dsh/sessionScope.mjs +28 -0
  84. package/src/dsh/status.mjs +7 -0
  85. package/src/dsh/stopGuard.mjs +225 -164
  86. package/src/dsh/testRuntime.mjs +62 -0
  87. package/src/dsh/toolKindAudit.mjs +66 -0
  88. package/src/dsh/tools.mjs +81 -5
  89. package/src/dsh/traceMeta.mjs +125 -0
  90. package/src/dsh/value-gate.mjs +93 -0
  91. package/src/dsh/workspace.mjs +3 -143
  92. package/src/memory/index.mjs +15 -0
  93. package/src/memory/tags.mjs +30 -0
  94. package/src/memory/workspace.mjs +283 -0
  95. package/src/peak-cost.mjs +1 -1
  96. package/src/profiles/deepseek-flash.mjs +7 -1
  97. package/src/profiles/deepseek-pro.mjs +6 -1
  98. package/src/profiles/default.mjs +6 -1
  99. package/src/profiles/glm.mjs +6 -1
  100. package/src/profiles/gpt-astra.mjs +6 -1
  101. package/tools/bench-ab.mjs +240 -0
  102. package/tools/bench-cost.mjs +176 -0
  103. package/tools/brain-cosmic.mjs +43 -0
  104. package/tools/brain-view.html +853 -0
  105. package/tools/brain.mjs +317 -0
  106. package/tools/capture-fixtures.mjs +182 -0
  107. package/tools/case-audit.mjs +114 -0
  108. package/tools/collect-panel.mjs +218 -0
  109. package/tools/dead-export.mjs +60 -0
  110. package/tools/docs-lint.mjs +82 -0
  111. package/tools/env-fingerprint.mjs +126 -33
  112. package/tools/first-run-sweep.mjs +123 -0
  113. package/tools/focusguard.mjs +155 -0
  114. package/tools/gate-audit.mjs +140 -0
  115. package/tools/gate-inputs.mjs +115 -0
  116. package/tools/handoff.mjs +56 -0
  117. package/tools/health.mjs +182 -0
  118. package/tools/knowledge.mjs +118 -0
  119. package/tools/layering-audit.mjs +105 -0
  120. package/tools/lib/book-style.mjs +136 -0
  121. package/tools/lib/brain-core.mjs +342 -0
  122. package/tools/lib/brain-docs.mjs +293 -0
  123. package/tools/lib/brain-regions.mjs +169 -0
  124. package/tools/lib/brain-relate.mjs +235 -0
  125. package/tools/lib/brain-text.mjs +121 -0
  126. package/tools/lib/case-tool.mjs +186 -0
  127. package/tools/lib/docs-core.mjs +392 -0
  128. package/tools/lib/docs-version.mjs +66 -0
  129. package/tools/lib/envMap.mjs +31 -0
  130. package/tools/lib/health-core.mjs +94 -0
  131. package/tools/lib/import-graph.mjs +118 -0
  132. package/tools/lib/index-io.mjs +70 -0
  133. package/tools/lib/open.mjs +32 -0
  134. package/tools/lib/prefix-cost.mjs +143 -0
  135. package/tools/lib/ratchet.mjs +174 -0
  136. package/tools/lib/reach.mjs +28 -0
  137. package/tools/lib/sessionDump.mjs +80 -0
  138. package/tools/lib/source-text.mjs +112 -0
  139. package/tools/library-book.mjs +313 -0
  140. package/tools/library-build.mjs +50 -12
  141. package/tools/library-index.mjs +91 -0
  142. package/tools/lint.mjs +282 -0
  143. package/tools/log-audit.mjs +108 -0
  144. package/tools/manifest-sync.mjs +111 -0
  145. package/tools/memory-audit.mjs +67 -0
  146. package/tools/module-audit.mjs +56 -0
  147. package/tools/mutate.mjs +316 -0
  148. package/tools/prefix-audit.mjs +122 -0
  149. package/tools/prefix-drift.mjs +325 -0
  150. package/tools/privacy-guard.mjs +352 -0
  151. package/tools/quality-audit.mjs +166 -0
  152. package/tools/schema-fingerprint.mjs +191 -0
  153. package/{src/dsh → tools}/selftest.mjs +75 -22
  154. package/tools/smells.mjs +398 -0
  155. package/tools/verify-case-paths.mjs +93 -0
  156. package/tools/version.mjs +191 -0
  157. package/docs/MASTER-PLAN-2.0.0.md +0 -133
  158. package/docs/MASTER-PLAN-3.0.0.md +0 -76
  159. package/src/adapters/dsh/fg-appeal-tool.mjs +0 -47
  160. package/src/adapters/dsh/fg-apply-tool.mjs +0 -68
  161. /package/{src/adapters/dsh → hooks}/protocol.mjs +0 -0
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * FocusGuard · 成本/效果基准(读已有落盘数据,不跑模型)
4
+ *
5
+ * 它做的不是"再花一次钱跑一遍",而是把已经落盘的三份记录汇总成可比较的指标:
6
+ * ① `.ai/CASE_FILE.md` 【五】成本台账 → token 与 USD(谁在花钱)
7
+ * ② `.focus-guard/AUDIT.log` → 拦截次数 / 理由分布(拦了什么)
8
+ * ③ 同一文件里的 appeal-granted → 误伤后获准的条数(拦错了多少)
9
+ *
10
+ * 用法:
11
+ * node tools/bench-cost.mjs # 人读汇总
12
+ * node tools/bench-cost.mjs --json # 机器可读
13
+ * node tools/bench-cost.mjs --since 2026-10-18
14
+ *
15
+ * A/B 对照(回答"FG 值不值"):
16
+ * 同一批任务、同一模型,FG 开 5 次 / 关 5 次,各自跑完执行本脚本并对比输出。
17
+ * 关 FG 的那几轮不会写 AUDIT.log,所以只能比 token 与轮次——这是设计使然,不是漏采。
18
+ */
19
+
20
+ import { existsSync, readFileSync } from 'node:fs'
21
+ import { dirname, join, resolve } from 'node:path'
22
+ import { fileURLToPath } from 'node:url'
23
+
24
+ const here = dirname(fileURLToPath(import.meta.url))
25
+ const REPO = resolve(here, '..', '..', '..')
26
+ const args = process.argv.slice(2)
27
+ const jsonOut = args.includes('--json')
28
+ const sinceIdx = args.indexOf('--since')
29
+ const since = sinceIdx >= 0 ? args[sinceIdx + 1] : null
30
+
31
+ const CASE_FILE = process.env.FG_CASE_FILE || join(REPO, '.ai', 'CASE_FILE.md')
32
+ const AUDIT_FILE = process.env.FG_AUDIT_FILE || join(REPO, '.focus-guard', 'AUDIT.log')
33
+
34
+ /** 解析【五】成本台账行:| 时间 | 模型 | 时段 | 输入未缓存 | 缓存读 | 输出 | 成本USD | */
35
+ function parseCostRows(text) {
36
+ const start = text.indexOf('【五】成本台账')
37
+ if (start < 0) return []
38
+ const rows = []
39
+ for (const raw of text.slice(start).split('\n')) {
40
+ const line = raw.trim()
41
+ if (!line.startsWith('|')) {
42
+ if (rows.length > 0) break
43
+ continue
44
+ }
45
+ const cells = line.split('|').map((c) => c.trim())
46
+ const [ts, model, peak, input, cacheRead, output, usd] = cells.slice(1)
47
+ if (!ts || !/^\d{4}-\d{2}-\d{2}/.test(ts)) continue
48
+ rows.push({
49
+ ts,
50
+ model,
51
+ peak: peak === '峰',
52
+ input: Number(input) || 0,
53
+ cacheRead: Number(cacheRead) || 0,
54
+ output: Number(output) || 0,
55
+ usd: Number(usd) || 0,
56
+ })
57
+ }
58
+ return rows
59
+ }
60
+
61
+ /** 解析 AUDIT.log:按 action/trigger 统计,并可算"拦截→获准"的误伤比。 */
62
+ function parseAudit(text) {
63
+ const rows = []
64
+ for (const raw of text.split('\n')) {
65
+ const line = raw.trim()
66
+ if (!line.startsWith('{')) continue
67
+ try {
68
+ rows.push(JSON.parse(line))
69
+ } catch {
70
+ /* 损坏行跳过:审计文件可能正被并发追加 */
71
+ }
72
+ }
73
+ return rows
74
+ }
75
+
76
+ function readText(file) {
77
+ if (!existsSync(file)) return ''
78
+ try {
79
+ return readFileSync(file, 'utf8')
80
+ } catch {
81
+ return ''
82
+ }
83
+ }
84
+
85
+ const costRows = parseCostRows(readText(CASE_FILE)).filter((r) => !since || r.ts >= since)
86
+ const auditRows = parseAudit(readText(AUDIT_FILE)).filter((r) => !since || String(r.ts || '') >= since)
87
+
88
+ const tokenSum = costRows.reduce((a, r) => a + r.input + r.cacheRead + r.output, 0)
89
+ const usdSum = costRows.reduce((a, r) => a + r.usd, 0)
90
+ const byTrigger = new Map()
91
+ const byAction = new Map()
92
+ for (const r of auditRows) {
93
+ byAction.set(r.action, (byAction.get(r.action) || 0) + 1)
94
+ if (r.action === 'deny') byTrigger.set(r.trigger || 'unspecified', (byTrigger.get(r.trigger || 'unspecified') || 0) + 1)
95
+ }
96
+ const denies = byAction.get('deny') || 0
97
+ const appealsGranted = byAction.get('appeal-granted') || 0
98
+
99
+ // ── 熔断浪费(2026-10-19 人类批示"熔断步数改成每个会话独立计数")──
100
+ // 数据源:`stall-fuse` 行(现在带 turn/step)+ `fuse-waste` 行(回合结束结算,wasted 字段)。
101
+ // 口径:每个会话的 step 从 1 重新开始,**跨会话不可相加**——所以先按会话分组,再由人判断。
102
+ // 历史行没有 turn/step(2026-10-19 之前),无法回溯,明确单独计数,不假装能算。
103
+ const fuseRows = auditRows.filter((r) => r.action === 'stall-fuse')
104
+ const fuseWithMeta = fuseRows.filter((r) => Number.isInteger(r.turn) && Number.isInteger(r.step))
105
+ const wasteBySession = new Map()
106
+ for (const r of auditRows) {
107
+ if (r.action !== 'fuse-waste') continue
108
+ const key = String(r.session || 'dsh-native')
109
+ const cur = wasteBySession.get(key) || { session: key, turns: 0, wastedSteps: 0, maxWastedSingleTurn: 0 }
110
+ const wasted = Number(r.wasted) || 0
111
+ cur.turns += 1
112
+ cur.wastedSteps += wasted
113
+ cur.maxWastedSingleTurn = Math.max(cur.maxWastedSingleTurn, wasted)
114
+ wasteBySession.set(key, cur)
115
+ }
116
+
117
+ const report = {
118
+ ts: new Date().toISOString(),
119
+ since,
120
+ cost: {
121
+ rows: costRows.length,
122
+ tokens: tokenSum,
123
+ usd: Number(usdSum.toFixed(4)),
124
+ byModel: [...costRows.reduce((m, r) => m.set(r.model, (m.get(r.model) || 0) + r.input + r.cacheRead + r.output), new Map())]
125
+ .map(([model, tokens]) => ({ model, tokens }))
126
+ .sort((a, b) => b.tokens - a.tokens),
127
+ },
128
+ enforcement: {
129
+ denies,
130
+ appealsGranted,
131
+ falsePositiveRatio: denies === 0 ? 0 : Number((appealsGranted / denies).toFixed(4)),
132
+ topTriggers: [...byTrigger.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10).map(([trigger, n]) => ({ trigger, n })),
133
+ },
134
+ fuseWaste: {
135
+ stallFuse: fuseRows.length,
136
+ withMeta: fuseWithMeta.length,
137
+ bySession: [...wasteBySession.values()].sort((a, b) => b.wastedSteps - a.wastedSteps),
138
+ note: '按会话独立计数(step 每会话从 1 重新开始,跨会话不可相加);历史行无 turn/step,无法回溯',
139
+ },
140
+ files: { CASE_FILE, AUDIT_FILE },
141
+ }
142
+
143
+ if (jsonOut) {
144
+ console.log(JSON.stringify(report, null, 2))
145
+ } else {
146
+ console.log(`成本基准(${since ? `自 ${since}` : '全量'})`)
147
+ console.log(` 台账行数 ${report.cost.rows}`)
148
+ console.log(` token 合计 ${report.cost.tokens}`)
149
+ console.log(` USD 合计 ${report.cost.usd}`)
150
+ if (report.cost.byModel.length > 0) {
151
+ console.log(' 按模型:')
152
+ for (const m of report.cost.byModel) console.log(` ${m.model}: ${m.tokens}`)
153
+ }
154
+ console.log(`拦截总数 ${report.enforcement.denies}`)
155
+ console.log(` 误伤获准 ${report.enforcement.appealsGranted}(比例 ${(report.enforcement.falsePositiveRatio * 100).toFixed(2)}%)`)
156
+ if (report.enforcement.topTriggers.length > 0) {
157
+ console.log(' 拦截理由 Top:')
158
+ for (const t of report.enforcement.topTriggers) console.log(` ${t.trigger}: ${t.n}`)
159
+ }
160
+ if (report.cost.rows === 0) {
161
+ console.log(' ⚠ 台账为空:宿主可能未提供 usage(FG 会连续 5 次缺失后告警),或本机从未跑过带成本的调用')
162
+ }
163
+ console.log(
164
+ `熔断 ${report.fuseWaste.stallFuse} 次(带 turn/step 元数据 ${report.fuseWaste.withMeta} 次;旧行无元数据)`,
165
+ )
166
+ if (report.fuseWaste.bySession.length === 0) {
167
+ console.log(' ⚠ 尚无 fuse-waste 结算行:需新会话里真熔断一次(旧行无 turn/step,无法回溯)')
168
+ } else {
169
+ console.log(' 熔断后步数(按会话,跨会话不可相加):')
170
+ for (const s of report.fuseWaste.bySession) {
171
+ console.log(
172
+ ` ${s.session}: 熔断 ${s.turns} 回合 / 累计 ${s.wastedSteps} 步 / 单回合最多 ${s.maxWastedSingleTurn} 步`,
173
+ )
174
+ }
175
+ }
176
+ }
@@ -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);