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,91 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 【私有工具】资料积木索引(2026-10-31)
4
+ *
5
+ * 读 `.ai/output/library/*.md` 的文件名,落一份 `index.json` 当目录。
6
+ * 产物落 `.ai/output/`——私有面,不入库、不随 npm 分发。
7
+ *
8
+ * ## 为什么只做文件名索引,不做内容索引
9
+ *
10
+ * 实测:118 份源文件 174,479 字,全量读一遍 ≈ 12 万 token,而 compaction 阈值 0.3,
11
+ * 读不完。但积木的文件名本身已经是「编号-主题-来源」——索引项早就存在,只是没人读它。
12
+ * 29 项合计 638 字符,比 118 条机器摘要(约 2,360 字)便宜四倍,且不会抽错主题。
13
+ *
14
+ * 内容级索引留到真有检索痛点再做。两套索引源 = 两个真相源,那是 3.3 修过的病。
15
+ *
16
+ * ## 命名规律(实测 28 块)
17
+ *
18
+ * B001-s-级-改改措辞就能进-rules-注入前缀.md 分级结论:s/a/b 级
19
+ * B006-核心机制-anthropic.md 主题 + 来源
20
+ *
21
+ * 认不出的写法不猜:整段原样进 `topic`,`grade`/`source` 留 null。
22
+ *
23
+ * ## 用法
24
+ *
25
+ * node tools/library-index.mjs 重建 index.json
26
+ * node tools/library-index.mjs --check 只比对,不写;漂移则退 1
27
+ */
28
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
29
+ import { join } from 'node:path'
30
+ import { diffKeys, runIndexTool } from './lib/index-io.mjs'
31
+
32
+ const DIR = '.ai/output/library'
33
+ const OUT = join(DIR, 'index.json')
34
+ const SOURCES = ['anthropic', 'google', 'misc', 'openai', 'others', 'xai']
35
+
36
+ /** 文件名 → 索引项。认不出的一律不猜,整段当 topic。 */
37
+ export function parseBlock(file, chars) {
38
+ const m = /^B(\d{3})-(.+)\.md$/.exec(file)
39
+ if (!m) return null
40
+ const [, num, rest] = m
41
+ const item = { id: `B${num}`, file, grade: null, topic: rest, source: null, chars }
42
+ const graded = /^([sab])-级-(.+)$/.exec(rest)
43
+ if (graded) {
44
+ item.grade = graded[1]
45
+ item.topic = graded[2]
46
+ return item
47
+ }
48
+ const tail = new RegExp(`^(.+)-(${SOURCES.join('|')})$`).exec(rest)
49
+ if (tail) {
50
+ item.topic = tail[1]
51
+ item.source = tail[2]
52
+ }
53
+ return item
54
+ }
55
+
56
+ /** 扫目录,出索引对象。不写盘。 */
57
+ export function buildIndex(dir = DIR) {
58
+ if (!existsSync(dir)) return { dir, blocks: [] }
59
+ const blocks = readdirSync(dir)
60
+ .filter((f) => /^B\d{3}-.+\.md$/.test(f))
61
+ .sort()
62
+ .map((f) => parseBlock(f, readFileSync(join(dir, f), 'utf8').length))
63
+ .filter(Boolean)
64
+ return { dir, blocks }
65
+ }
66
+
67
+ /** 零漂移判据:id/file/chars 三者全等。少一块、多一块、改一个字都算。 */
68
+ const KEY = (b) => `${b.id}|${b.file}|${b.chars}`
69
+ export function diffIndex(expected, actual) {
70
+ return diffKeys(expected, actual, KEY, 'blocks')
71
+ }
72
+
73
+ function main() {
74
+ runIndexTool({
75
+ argv: process.argv.slice(2),
76
+ build: buildIndex,
77
+ field: 'blocks',
78
+ out: OUT,
79
+ label: 'index.json',
80
+ keyOf: KEY,
81
+ prefix: '[library-index]',
82
+ empty: `${DIR} 下没有积木,先跑 library-build`,
83
+ summary: (i) => {
84
+ const graded = i.blocks.filter((b) => b.grade).length
85
+ const total = i.blocks.reduce((n, b) => n + b.chars, 0)
86
+ return `${i.blocks.length} 块(分级结论 ${graded})/ ${total} 字 → ${OUT}`
87
+ },
88
+ })
89
+ }
90
+
91
+ if (process.argv[1] && process.argv[1].endsWith('library-index.mjs')) main()
package/tools/lint.mjs ADDED
@@ -0,0 +1,282 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 房规检查器(tools/lint.mjs,2026-10-27)——内置化第一件,零依赖。
4
+ *
5
+ * 为什么自己写:
6
+ * 上一轮用 `dsh-code-check` 的 ESLint fallback 配置跑,得出 **775 warnings**,
7
+ * 但其中 `curly` 589 条全是本仓房规(单语句块不加大括号),不是缺陷。
8
+ * 它的评分模型 `100 − errors×8 − warnings×3` 代入后直接封底 0/100——
9
+ * **一个把房规算成缺陷的尺子,量出来的是尺子自己**。
10
+ *
11
+ * 本工具只报"确定是问题"的五类,不报风格:
12
+ * unused-import 导入了但全文没用到(死代码,会骗读者以为有依赖)
13
+ * duplicate-import 同一模块被 import 两次(合并后易读,且 no-duplicate 是硬错)
14
+ * var 应 let/const(函数作用域陷阱,非块级)
15
+ * loose-equal `==`/`!=` 且两侧都不是 null/undefined(隐式转换)
16
+ * console-in-src `console.log` 留在 `src/core/` 或 `src/adapters/`(污染输出,测试里允许)
17
+ *
18
+ * `console-in-src` 只查母版与适配层,**不查 `src/dsh/`**(2026-10-27 修注释):
19
+ * 分层纪律是"母版是逻辑,适配层只做翻译,打印属宿主职责"。宿主缝里 `status.mjs`
20
+ * 这类 CLI 本来就要往 stdout 写,算成污染是错的。原注释写成"留在 src/",与实现不符——
21
+ * **注释与实现不一致时,先信实现,再改注释**。
22
+ *
23
+ * 明确**不报**的三类(各自有理由):
24
+ * curly 房规。单语句块不加括号,全仓一致
25
+ * `== null` 惯用法,同时匹配 null 与 undefined;改 `===` 会漏掉 undefined
26
+ * 空 catch FG 的空 catch 是环境探测/清理路径的三级兜底,有意为之
27
+ *
28
+ * 用法:
29
+ * node packages/core/tools/lint.mjs # 明细
30
+ * node packages/core/tools/lint.mjs --brief # 一行(供 npm run check)
31
+ * node packages/core/tools/lint.mjs --json
32
+ * node packages/core/tools/lint.mjs --strict # 超债务上限 exit 1
33
+ * node packages/core/tools/lint.mjs <目录...> # 只扫指定目录
34
+ *
35
+ * 退出码:默认恒 0(只报不改);`--strict` 时**活跃层问题数 > BUDGET** 才 exit 1。
36
+ *
37
+ * 为什么是"债务上限"而不是"有问题就红"(2026-10-27 改):
38
+ * 首版 `--strict` = 有任何一条就 exit 1。当前 54 条全在已封存的 `hooks/`(不维护),
39
+ * 那条闸门**永远红**。永久红会训练人忽略告警——`schema:verify` 上已经踩过同一个坑。
40
+ * 所以:① 闸门只看活跃层(src/tools/tests),`hooks/` 只报不计;② 活跃层上限为 0,
41
+ * 新增一条就红;③ 修好了不许反弹(存量降下来时手工把 BUDGET 往下调)。
42
+ */
43
+
44
+ import { readFileSync, readdirSync, statSync } from 'node:fs'
45
+ import { join, dirname, relative, resolve } from 'node:path'
46
+ import { fileURLToPath } from 'node:url'
47
+ // 去字面量与注释:与 smells.mjs 共用同一实现(2026-10-27 抽到 tools/lib/)。
48
+ // 各写一份必然分叉——smells 那份就漏了正则字面量,把 398 行的函数抹成 0。
49
+ import { stripLiterals } from './lib/source-text.mjs'
50
+
51
+ const HERE = dirname(fileURLToPath(import.meta.url))
52
+ // 仓库根可覆盖:测试要造夹具目录跑真扫描,否则这个工具自己没被测量。
53
+ // 与 FG_AUDIT_FILE 同一思路——**测试必须能把被测对象指到别处**。
54
+ const REPO = process.env.FG_REPO_ROOT ? resolve(process.env.FG_REPO_ROOT) : resolve(HERE, '../../..')
55
+
56
+ const argv = process.argv.slice(2)
57
+ const BRIEF = argv.includes('--brief')
58
+ const AS_JSON = argv.includes('--json')
59
+ const STRICT = argv.includes('--strict')
60
+ const dirArgs = argv.filter((a) => !a.startsWith('--'))
61
+
62
+ const DEFAULT_ROOTS = ['packages/core/src', 'packages/core/tools', 'packages/core/tests', 'packages/core/hooks', 'packages/extended/src']
63
+ const roots = (dirArgs.length ? dirArgs : DEFAULT_ROOTS).map((d) => resolve(REPO, d))
64
+
65
+ /**
66
+ * 债务上限(棘轮)。只对**活跃层**计数:`hooks/` 已封存不维护,不计入闸门。
67
+ * 现状活跃层 0 条 —— 所以上限就是 0,新增一条即红。降存量后手工下调,不许反弹。
68
+ */
69
+ const BUDGET = 0
70
+ const GATED = /^packages\/(core\/(src|tools|tests)|extended\/src)\//
71
+
72
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.stryker-tmp', '.mutate-tmp', 'reports', '.ai'])
73
+
74
+ function walk(dir, out = []) {
75
+ let entries
76
+ try {
77
+ entries = readdirSync(dir)
78
+ } catch {
79
+ return out
80
+ }
81
+ for (const e of entries) {
82
+ if (SKIP_DIRS.has(e)) continue
83
+ const p = join(dir, e)
84
+ let st
85
+ try {
86
+ st = statSync(p)
87
+ } catch {
88
+ continue
89
+ }
90
+ if (st.isDirectory()) walk(p, out)
91
+ else if (/\.(mjs|cjs|js)$/.test(e)) out.push(p)
92
+ }
93
+ return out
94
+ }
95
+
96
+ /**
97
+ * 解析 import 语句:返回 [{ start, end, source, names: [{ local, imported }] }]。
98
+ * 手写状态机而非正则一把梭——本仓有多行具名 import(`import {\n A,\n B,\n} from 'x'`),
99
+ * 单行正则会把它们截断,进而把"已使用的符号"误报成未使用。
100
+ */
101
+ function parseImports(src) {
102
+ const lines = src.split('\n')
103
+ const out = []
104
+ let buf = null
105
+ let startLine = 0
106
+ for (let i = 0; i < lines.length; i += 1) {
107
+ const line = lines[i]
108
+ if (buf === null) {
109
+ // 排除 `import(` 动态导入与缩进的 `import.meta`
110
+ if (/^\s*import\s+[^(]/.test(line) || /^\s*import\s*['"]/.test(line)) {
111
+ buf = line
112
+ startLine = i
113
+ } else continue
114
+ } else {
115
+ buf += '\n' + line
116
+ }
117
+ if (/from\s*['"][^'"]+['"]/.test(buf) || /^\s*import\s*['"][^'"]+['"]/.test(buf)) {
118
+ const m = buf.match(/from\s*['"]([^'"]+)['"]/)
119
+ const sideEffect = buf.match(/^\s*import\s*['"]([^'"]+)['"]/)
120
+ const source = m ? m[1] : sideEffect ? sideEffect[1] : ''
121
+ out.push({ start: startLine, end: i, source, names: parseNames(buf) })
122
+ buf = null
123
+ }
124
+ }
125
+ return { list: out, lines }
126
+ }
127
+
128
+ /** 从一段 import 语句里取绑定名(本地名)。 */
129
+ function parseNames(stmt) {
130
+ const names = []
131
+ const clause = stmt.replace(/^\s*import\s*/, '').replace(/from\s*['"][^'"]+['"][\s;]*$/, '').replace(/^\s*['"][^'"]+['"][\s;]*$/, '')
132
+ // 具名部分
133
+ const brace = clause.match(/\{([\s\S]*?)\}/)
134
+ if (brace) {
135
+ for (const part of brace[1].split(',')) {
136
+ const t = part.trim()
137
+ if (!t) continue
138
+ const as = t.match(/\bas\s+([A-Za-z_$][\w$]*)/)
139
+ const imported = t.replace(/\s+as\s+[\w$]+$/, '').trim()
140
+ const local = as ? as[1] : imported
141
+ if (local) names.push({ local, imported })
142
+ }
143
+ }
144
+ // 默认导入与命名空间
145
+ const head = clause.replace(/\{[\s\S]*?\}/, '').replace(/,/g, ' ').trim()
146
+ for (const tok of head.split(/\s+/)) {
147
+ if (!tok || tok === 'import') continue
148
+ if (tok === 'as' || tok === '*') continue
149
+ if (/^[A-Za-z_$][\w$]*$/.test(tok)) names.push({ local: tok, imported: tok })
150
+ }
151
+ return names
152
+ }
153
+
154
+ const RULES = {
155
+ 'unused-import': '导入后全文未使用(死代码)',
156
+ 'duplicate-import': '同一模块被 import 多次',
157
+ var: '使用 var(应 let/const)',
158
+ 'loose-equal': '使用 == / !=(两侧均非 null/undefined)',
159
+ 'console-in-src': 'console.log 留在 src/(污染输出)',
160
+ }
161
+
162
+ const findings = []
163
+
164
+ function report(file, line, rule, detail) {
165
+ findings.push({ file: relative(REPO, file).replace(/\\/g, '/'), line, rule, detail })
166
+ }
167
+
168
+ /** 未使用 import:把 import 段从源码剔除后再数出现次数,避免把导入本身算成使用。 */
169
+ function checkImports(file, src) {
170
+ const { list, lines } = parseImports(src)
171
+ const seen = new Map()
172
+ for (const imp of list) {
173
+ if (imp.source) seen.set(imp.source, (seen.get(imp.source) || 0) + 1)
174
+ }
175
+ for (const [source, n] of seen) {
176
+ if (n > 1) report(file, list.find((i) => i.source === source).start + 1, 'duplicate-import', `${source} 被 import ${n} 次`)
177
+ }
178
+
179
+ // 剔除所有 import 语句后的剩余正文
180
+ const keep = []
181
+ const dropRanges = list.map((i) => [i.start, i.end])
182
+ for (let i = 0; i < lines.length; i += 1) {
183
+ if (dropRanges.some(([s, e]) => i >= s && i <= e)) continue
184
+ keep.push(lines[i])
185
+ }
186
+ const body = keep.join('\n')
187
+
188
+ for (const imp of list) {
189
+ for (const { local } of imp.names) {
190
+ // 只保留 ASCII 标识符边界,避免中文注释里的同名字串误判;元字符全转义(CodeQL regex-injection)
191
+ const re = new RegExp(`(?<![\\w$])${local.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w$])`)
192
+ if (!re.test(body)) report(file, imp.start + 1, 'unused-import', `${local}(来自 ${imp.source})`)
193
+ }
194
+ }
195
+ }
196
+
197
+ /** var:跑在去字面量后的文本上,避免 `var ` 出现在字符串里被误报。 */
198
+ function checkVar(file, plain) {
199
+ const lines = plain.split('\n')
200
+ for (let i = 0; i < lines.length; i += 1) {
201
+ if (/(^|[;{}]\s*)var\s+[A-Za-z_$[]/.test(lines[i])) {
202
+ report(file, i + 1, 'var', lines[i].trim().slice(0, 60))
203
+ }
204
+ }
205
+ }
206
+
207
+ /** 宽松相等:`== null` / `!= null` 是本仓惯用法(同时匹配 null 与 undefined),明确放行。 */
208
+ function checkLooseEqual(file, plain) {
209
+ const lines = plain.split('\n')
210
+ // 2026-10-27 首版踩坑两次:① `[^=!<>]!?==[^=]` 把 `!==` 吃进去(报 98 条);
211
+ // ② 改成 `(?<![=!<>])[!=]==(?!=)` 后 `[!=]` 仍能匹配 `=`,于是 `===` 又被吃进去(报 545 条)。
212
+ // **宽松相等的对手是严格相等**,必须精确锚定成 `==` 或 `!=`:第一个字符 `[!=]`,
213
+ // 第二个字符 `=`,且其后不能再接 `=`。用样本测过再上线,不靠眼读。
214
+ const RE = /(?<![=!<>])[!=]=(?!=)/g
215
+ for (let i = 0; i < lines.length; i += 1) {
216
+ const line = lines[i]
217
+ let hit
218
+ RE.lastIndex = 0
219
+ while ((hit = RE.exec(line))) {
220
+ const around = line.slice(Math.max(0, hit.index - 12), hit.index + 14)
221
+ if (/\bnull\b|\bundefined\b/.test(around)) continue // 惯用法,放行
222
+ report(file, i + 1, 'loose-equal', line.trim().slice(0, 60))
223
+ break
224
+ }
225
+ }
226
+ }
227
+
228
+ /**
229
+ * console.log 留在不该打印的层。
230
+ *
231
+ * 只查 `src/core/` 与 `src/adapters/`:母版是纯判定、适配层只做翻译,两者都不该往 stdout 写。
232
+ * `src/dsh/` 里有 CLI 入口(`status.mjs` 就是渲染命令输出的),报它没有意义。
233
+ */
234
+ function checkConsole(file, plain) {
235
+ const rel = relative(REPO, file).replace(/\\/g, '/')
236
+ if (!/^packages\/core\/src\/(core|adapters)\//.test(rel)) return
237
+ const lines = plain.split('\n')
238
+ for (let i = 0; i < lines.length; i += 1) {
239
+ if (/\bconsole\.(log|debug|info)\s*\(/.test(lines[i])) report(file, i + 1, 'console-in-src', lines[i].trim().slice(0, 60))
240
+ }
241
+ }
242
+
243
+ const files = roots.flatMap((r) => walk(r))
244
+ for (const file of files) {
245
+ let src
246
+ try {
247
+ src = readFileSync(file, 'utf8')
248
+ } catch {
249
+ continue
250
+ }
251
+ const plain = stripLiterals(src)
252
+ checkImports(file, src)
253
+ checkVar(file, plain)
254
+ checkLooseEqual(file, plain)
255
+ checkConsole(file, plain)
256
+ }
257
+
258
+ const byRule = {}
259
+ for (const f of findings) byRule[f.rule] = (byRule[f.rule] || 0) + 1
260
+
261
+ // 闸门只数活跃层;封存的 hooks/ 与 extended 之外一律不计
262
+ const gated = findings.filter((f) => GATED.test(f.file.replace(/\\/g, '/')))
263
+ const frozen = findings.length - gated.length
264
+
265
+ if (AS_JSON) {
266
+ console.log(JSON.stringify({ files: files.length, findings, byRule, gated: gated.length, budget: BUDGET }, null, 2))
267
+ } else if (BRIEF) {
268
+ const parts = Object.entries(byRule)
269
+ .sort((a, b) => b[1] - a[1])
270
+ .map(([r, n]) => `${r} ${n}`)
271
+ const gate = gated.length > BUDGET ? `活跃层 ${gated.length} 条 > 上限 ${BUDGET} ❌` : `活跃层 ${gated.length}/${BUDGET} ✅`
272
+ console.log(`房规检查:${files.length} 文件,问题 ${findings.length} 条${parts.length ? `(${parts.join(' / ')})` : ''};${gate}${frozen ? `,封存层 ${frozen} 条不计` : ''}`)
273
+ } else {
274
+ console.log(`房规检查:${files.length} 文件,问题 ${findings.length} 条\n`)
275
+ if (!findings.length) console.log('无问题。')
276
+ for (const f of findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line)) {
277
+ console.log(`${f.file}:${f.line}\t[${f.rule}] ${f.detail}`)
278
+ }
279
+ console.log('\n不报的三类(各有理由):curly 房规 / `== null` 惯用法 / 空 catch 三级兜底。')
280
+ console.log(`闸门口径:活跃层 ${gated.length} 条 / 上限 ${BUDGET};封存层 ${frozen} 条(hooks/)只报不计。`)
281
+ }
282
+ process.exit(STRICT && gated.length > BUDGET ? 1 : 0)
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 审计日志体检(2026-10-25):从 AUDIT.log 里找"模块没在工作"的证据。
4
+ * 输出:动作分布 / 重复拒绝 / 异常行 / 时间断层 / 各闸触发量 / **行契约体检**。
5
+ * 只读。
6
+ *
7
+ * 2026-10-29 增补「行契约体检」:2026-10-29 的重构就是靠这几项发现问题的——
8
+ * 当时没有任何工具能看见"同一份日志里有三种行形态",全靠临时探针脚本。
9
+ * 现在把探针固化进本工具,下次漂移能自己报出来。
10
+ */
11
+ import { existsSync, readFileSync } from 'node:fs'
12
+ import { join } from 'node:path'
13
+ import { AUDIT_REQUIRED_FIELDS } from '../src/core/audit-writer.mjs'
14
+
15
+ const ROOT = 'E:/DSH/focus-guard-main'
16
+ const LOG = process.env.FG_AUDIT_FILE || join(ROOT, '.focus-guard', 'AUDIT.log')
17
+ if (!existsSync(LOG)) {
18
+ console.log('无审计日志:', LOG)
19
+ process.exit(0)
20
+ }
21
+ const rows = readFileSync(LOG, 'utf8')
22
+ .split('\n')
23
+ .filter(Boolean)
24
+ .map((l) => {
25
+ try {
26
+ return JSON.parse(l)
27
+ } catch {
28
+ return { bad: true, raw: l.slice(0, 80) }
29
+ }
30
+ })
31
+
32
+ const bad = rows.filter((r) => r.bad)
33
+ const ok = rows.filter((r) => !r.bad)
34
+ const byAction = {}
35
+ const byTrigger = {}
36
+ for (const r of ok) {
37
+ byAction[r.action || '?'] = (byAction[r.action || '?'] || 0) + 1
38
+ if (r.trigger) byTrigger[r.trigger] = (byTrigger[r.trigger] || 0) + 1
39
+ }
40
+ console.log(`总行 ${rows.length}(坏行 ${bad.length})`)
41
+
42
+ const top = (o, n = 18) => Object.entries(o).sort((a, b) => b[1] - a[1]).slice(0, n)
43
+ console.log('\n== 动作分布(top18)==')
44
+ for (const [k, v] of top(byAction)) console.log(` ${String(v).padStart(6)} ${k}`)
45
+ console.log('\n== 触发分布(top18)==')
46
+ for (const [k, v] of top(byTrigger)) console.log(` ${String(v).padStart(6)} ${k}`)
47
+
48
+ // 可疑行:evidence 里带 error/undefined/null/NaN
49
+ const suspect = ok.filter((r) => /error|undefined|null|NaN|\[object/.test(String(r.evidence || '')))
50
+ console.log(`\n== 可疑行(evidence 含 error/undefined/NaN)${suspect.length} 条,前 6 ==`)
51
+ for (const s of suspect.slice(-6)) console.log(` ${s.action} | ${String(s.evidence).slice(0, 110)}`)
52
+
53
+ // 时间断层(>30 分钟无记录,可能是会话空闲,仅供参考)
54
+ const ts = ok.map((r) => Date.parse(r.ts)).filter((x) => Number.isFinite(x)).sort((a, b) => a - b)
55
+ let maxGap = 0
56
+ let gapAt = null
57
+ for (let i = 1; i < ts.length; i += 1) {
58
+ const g = ts[i] - ts[i - 1]
59
+ if (g > maxGap) {
60
+ maxGap = g
61
+ gapAt = new Date(ts[i]).toISOString()
62
+ }
63
+ }
64
+ if (gapAt) console.log(`\n最大时间断层 ${(maxGap / 60000).toFixed(1)} 分钟(恢复于 ${gapAt})`)
65
+
66
+ // 近 24h 动作,判断哪些模块最近没在跑
67
+ const since = Date.now() - 24 * 3600 * 1000
68
+ const recent = ok.filter((r) => Date.parse(r.ts) >= since)
69
+ const recentActions = {}
70
+ for (const r of recent) recentActions[r.action || '?'] = (recentActions[r.action || '?'] || 0) + 1
71
+ console.log(`\n== 近 24h 动作(${recent.length} 行)==`)
72
+ for (const [k, v] of top(recentActions, 22)) console.log(` ${String(v).padStart(6)} ${k}`)
73
+
74
+ // ── 行契约体检(2026-10-29)────────────────────────────────────────────────
75
+ // 三项都能在历史上真的红过:缺字段(fuse-waste 11 行)、seq 撞号(17 组)、
76
+ // 写入器形态分裂(带 chain/ref 的 vs 不带的 vs 缺字段的)。
77
+ console.log('\n== 行契约体检 ==')
78
+
79
+ const missing = new Map()
80
+ for (const r of ok) {
81
+ const lack = AUDIT_REQUIRED_FIELDS.filter((k) => !(k in r))
82
+ if (lack.length) missing.set(lack.join('+'), (missing.get(lack.join('+')) || 0) + 1)
83
+ }
84
+ if (missing.size === 0) console.log(' 七字段:全部齐备 ✅')
85
+ else {
86
+ console.log(` 七字段:${[...missing.values()].reduce((a, b) => a + b, 0)} 行缺字段 ❌`)
87
+ for (const [k, v] of [...missing].sort((a, b) => b[1] - a[1])) console.log(` ${String(v).padStart(5)} 行缺 ${k}`)
88
+ }
89
+
90
+ const seqRows = ok.filter((r) => r.seq)
91
+ const seqDup = seqRows.length - new Set(seqRows.map((r) => r.seq)).size
92
+ console.log(
93
+ ` 事件号:${seqRows.length} 行带 seq,唯一 ${new Set(seqRows.map((r) => r.seq)).size}` +
94
+ (seqDup ? ` ❌ 重复 ${seqDup} 组(因果链按 seq 建索引,撞号即丢边)` : ' ✅'),
95
+ )
96
+
97
+ // 形态分组:按"是否带 seq / 七字段是否齐"给每行归类。
98
+ // chain 不计入形态——因果链本来就只挂在任务链上的事件,缺它是正常,不是漂移。
99
+ const shapeOf = (r) =>
100
+ `${r.seq ? 'seq' : '无seq'}/${AUDIT_REQUIRED_FIELDS.every((k) => k in r) ? '7/7' : '残行'}`
101
+ const shapes = {}
102
+ for (const r of ok) shapes[shapeOf(r)] = (shapes[shapeOf(r)] || 0) + 1
103
+ console.log(` 行形态:${Object.keys(shapes).length} 种`)
104
+ for (const [k, v] of Object.entries(shapes).sort((a, b) => b[1] - a[1])) console.log(` ${String(v).padStart(6)} ${k}`)
105
+ console.log(` 因果链:${ok.filter((r) => r.chain).length} 行带 chain(可选字段,缺属正常)`)
106
+ if (Object.keys(shapes).length > 1) {
107
+ console.log(' ↑ 超过 1 种说明写入点还没收敛到同一个构造点(buildAuditRow)')
108
+ }
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 清单文案单点(2026-11-08)
4
+ *
5
+ * 为什么有这个工具:
6
+ * 同一个插件的「名字 / 简介 / 显示名」曾经在 5 份 JSON 里各手写一遍——
7
+ * `packages/core/package.json`、仓库根 `marketplace.json`、
8
+ * `.claude-plugin/marketplace.json`、`.claude-plugin/plugin.json`、`.zcode-plugin/plugin.json`。
9
+ * 它们不能合并(每个宿主生态各要一个固定文件名),但**内容该只有一份**。
10
+ * 实测代价:自适应 TTL 早已从四档阶梯改成半衰期,`.zcode-plugin/plugin.json` 的简介
11
+ * 还写着「4h~7天」;「上下文污染检测(58条)」的条号也对不上。改了代码忘改副本,
12
+ * 这类漂移不会有任何闸门报错——因为每份副本都"自洽"。
13
+ *
14
+ * 真源:`packages/core/package.json` 的 `description` / `displayName` /
15
+ * `displayNameI18n` / `descriptionI18n`。
16
+ * 不新开真源文件:那等于为了收敛再加一个 JSON,本末倒置。
17
+ *
18
+ * 边界:
19
+ * ① **只写各文件本来就有的字段**。没有 `displayName_i18n` 的清单不硬塞一个——
20
+ * 不替宿主发明 schema,也不替它删字段。
21
+ * ② **不动 version**。版本归 `tools/version.mjs --set` 管,两个工具各写一份就是新的散乱。
22
+ * ③ **保留原缩进与行尾**。清单是 CRLF,`JSON.stringify` 吐 LF,写一次就留一条假改动。
23
+ *
24
+ * 用法:
25
+ * node tools/manifest-sync.mjs # 只查,漂移即 exit 1
26
+ * node tools/manifest-sync.mjs --write # 以真源为准写回副本
27
+ */
28
+
29
+ import { readFileSync, writeFileSync } from "node:fs";
30
+ import { dirname, join, resolve } from "node:path";
31
+ import { fileURLToPath } from "node:url";
32
+
33
+ const HERE = dirname(fileURLToPath(import.meta.url));
34
+ const ROOT = resolve(HERE, "..", "..", "..");
35
+ const TRUTH = "packages/core/package.json";
36
+
37
+ /** 副本清单:`at` 指明文案落在顶层还是 `plugins[0]`(市场清单的形状)。 */
38
+ const COPIES = [
39
+ { rel: "marketplace.json", at: "plugins" },
40
+ { rel: ".claude-plugin/marketplace.json", at: "plugins" },
41
+ { rel: ".claude-plugin/plugin.json", at: "top" },
42
+ { rel: ".zcode-plugin/plugin.json", at: "top" },
43
+ ];
44
+
45
+ /** 文案字段:真源键 → 清单键。只同步目标里**已存在**的那些。 */
46
+ const FIELDS = [
47
+ ["description", "description"],
48
+ ["displayName", "displayName"],
49
+ ["displayNameI18n", "displayName_i18n"],
50
+ ["descriptionI18n", "description_i18n"],
51
+ ];
52
+
53
+ function readJson(rel) {
54
+ return JSON.parse(readFileSync(join(ROOT, rel), "utf8"));
55
+ }
56
+
57
+ function targetOf(json, at) {
58
+ return at === "plugins" ? json.plugins?.[0] : json;
59
+ }
60
+
61
+ function main() {
62
+ const write = process.argv.includes("--write");
63
+ const truth = readJson(TRUTH);
64
+ const drifts = [];
65
+
66
+ for (const { rel, at } of COPIES) {
67
+ const path = join(ROOT, rel);
68
+ const raw = readFileSync(path, "utf8");
69
+ const json = JSON.parse(raw);
70
+ const target = targetOf(json, at);
71
+ if (!target) {
72
+ drifts.push(`${rel}:找不到 plugins[0],形状不对`);
73
+ continue;
74
+ }
75
+ let touched = false;
76
+ for (const [srcKey, dstKey] of FIELDS) {
77
+ if (!(dstKey in target)) continue; // 不替宿主发明字段
78
+ const want = truth[srcKey];
79
+ if (want === undefined) continue;
80
+ if (JSON.stringify(target[dstKey]) !== JSON.stringify(want)) {
81
+ drifts.push(`${rel} ${dstKey}`);
82
+ target[dstKey] = want;
83
+ touched = true;
84
+ }
85
+ }
86
+ // 插件名必须一致;市场的 `name` 是市场标识,不在此列
87
+ if (target.name !== truth.name) {
88
+ drifts.push(`${rel} name`);
89
+ target.name = truth.name;
90
+ touched = true;
91
+ }
92
+ if (!touched) continue;
93
+ const eol = raw.includes("\r\n") ? "\r\n" : "\n";
94
+ const after = (JSON.stringify(json, null, 2) + "\n").replace(/\n/g, eol);
95
+ if (write && after !== raw) writeFileSync(path, after);
96
+ }
97
+
98
+ if (!drifts.length) {
99
+ console.log(`✓ 清单文案与真源一致(${TRUTH}):${COPIES.length} 份副本无漂移`);
100
+ return 0;
101
+ }
102
+ const lines = drifts.map((d) => ` ✗ ${d}`).join("\n");
103
+ if (write) {
104
+ console.log(`✓ 已按真源写回 ${new Set(drifts.map((d) => d.split(" ")[0])).size} 份清单:\n${lines}`);
105
+ return 0;
106
+ }
107
+ console.log(`✗ 清单文案与真源漂移 ${drifts.length} 处:\n${lines}\n\n 修法:node packages/core/tools/manifest-sync.mjs --write`);
108
+ return 1;
109
+ }
110
+
111
+ process.exit(main());
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * memory:audit(4.5 M1,2026-11-02)——列出记忆的三类载体,只读。
4
+ *
5
+ * 收益:M1 验收要求一条命令说清「记忆存在哪、多大、索引有没有」。
6
+ * 改动面:本文件 + package.json 一行 script,不跨层。
7
+ * 替代:无更小做法——验收命令需要一个真实入口。
8
+ */
9
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
10
+ import { dirname, join, resolve } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+
13
+ const HERE = dirname(fileURLToPath(import.meta.url))
14
+ const REPO = resolve(HERE, '..', '..', '..')
15
+
16
+ const carriers = [
17
+ {
18
+ key: 'workspace',
19
+ label: '跨会话卷宗',
20
+ path: join(REPO, '.focus-guard', 'workspace.json'),
21
+ describe: (p) => {
22
+ const raw = readFileSync(p, 'utf8')
23
+ const j = JSON.parse(raw)
24
+ const n = (j.decisions?.length || 0) + (j.constraints?.length || 0) + (j.next?.length || 0)
25
+ return `${raw.length} 字节 · workspace_hash=${j.workspace_hash || '—'} · 条目 ${n}`
26
+ },
27
+ },
28
+ {
29
+ key: 'case-file',
30
+ label: '四册卷宗',
31
+ path: join(REPO, '.ai', 'CASE_FILE.md'),
32
+ describe: (p) => {
33
+ const raw = readFileSync(p, 'utf8')
34
+ const sections = (raw.match(/^#{1,6}\s*【[一二三四五六七八九十]+】/gm) || []).length
35
+ return `${raw.length} 字节 · 章节 ${sections}`
36
+ },
37
+ },
38
+ {
39
+ key: 'library',
40
+ label: '静态知识库',
41
+ path: join(REPO, '.ai', 'library'),
42
+ describe: (p) => {
43
+ const idx = join(p, 'INDEX.md')
44
+ const live = readdirSync(p).filter((f) => f.endsWith('.md') && f !== 'README.md').length
45
+ const archiveRoot = join(REPO, '.ai', 'archive', 'library')
46
+ let archive = 0
47
+ if (existsSync(archiveRoot)) {
48
+ for (const d of readdirSync(archiveRoot)) {
49
+ try { archive += readdirSync(join(archiveRoot, d)).filter((f) => f.endsWith('.md')).length } catch {}
50
+ }
51
+ }
52
+ return `现行 ${live} 份 · 归档 ${archive} 份 · 索引 ${existsSync(idx) ? '有' : '无'}`
53
+ },
54
+ },
55
+ ]
56
+
57
+ let bad = 0
58
+ for (const c of carriers) {
59
+ if (!existsSync(c.path)) {
60
+ process.stdout.write(`${c.key}\t${c.label}\tMISSING\t${c.path}\n`)
61
+ bad++
62
+ continue
63
+ }
64
+ statSync(c.path)
65
+ process.stdout.write(`${c.key}\t${c.label}\tOK\t${c.describe(c.path)}\n`)
66
+ }
67
+ process.exitCode = bad ? 1 : 0