focus-guard 3.5.1 → 3.5.3

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 (102) hide show
  1. package/README.md +17 -5
  2. package/README.zh-CN.md +15 -5
  3. package/assets/NOTICE.md +2 -0
  4. package/docs/ARCH-MAP.md +33 -20
  5. package/docs/BENCH.md +21 -12
  6. package/docs/RELEASE-POLICY.md +84 -19
  7. package/docs/RULES.md +75 -55
  8. package/docs/THREAT-MODEL.md +1 -1
  9. package/docs/WRITING-STYLE.md +1 -1
  10. package/package.json +11 -6
  11. package/skills/focus-plan/SKILL.md +77 -0
  12. package/skills/focus-rules/SKILL.md +267 -0
  13. package/skills/focus-thinking/SKILL.md +8 -255
  14. package/src/adapters/dsh/eligibility-gate.mjs +43 -23
  15. package/src/adapters/dsh/session.mjs +22 -0
  16. package/src/core/approvals.mjs +10 -4
  17. package/src/core/audit-writer.mjs +5 -2
  18. package/src/core/checkEligibility.mjs +190 -129
  19. package/src/core/constants.mjs +1 -1
  20. package/src/core/decisionEngine.mjs +16 -13
  21. package/src/core/env.mjs +18 -0
  22. package/src/core/patterns.mjs +3 -1
  23. package/src/core/prefixStability.mjs +27 -3
  24. package/src/core/session.mjs +23 -0
  25. package/src/dsh/audit.mjs +21 -7
  26. package/src/dsh/bridgeCheck.mjs +81 -0
  27. package/src/dsh/compactionWatch/announce.mjs +2 -1
  28. package/src/dsh/compactionWatch.mjs +2 -1
  29. package/src/dsh/guard/authz.mjs +2 -2
  30. package/src/dsh/guard/retryGuard.mjs +96 -0
  31. package/src/dsh/guard/risk.mjs +61 -16
  32. package/src/dsh/guard/runtime.mjs +30 -5
  33. package/src/dsh/guard/tooling.mjs +5 -9
  34. package/src/dsh/guard/writing-gate.mjs +117 -0
  35. package/src/dsh/index.js +4 -7
  36. package/src/dsh/pipeline.mjs +66 -5
  37. package/src/dsh/preGuard.mjs +11 -2
  38. package/src/dsh/repeatGuard.mjs +5 -4
  39. package/src/dsh/seams/session-start.mjs +49 -10
  40. package/src/dsh/seams/shared.mjs +8 -5
  41. package/src/dsh/search-hints.mjs +15 -1
  42. package/src/dsh/sessionScope.mjs +11 -11
  43. package/src/dsh/stopGuard.mjs +2 -7
  44. package/src/dsh/tools.mjs +39 -1
  45. package/src/dsh/traceMeta.mjs +5 -11
  46. package/src/memory/index.mjs +4 -4
  47. package/src/memory/workspace.mjs +41 -19
  48. package/tools/capture-fixtures.mjs +3 -24
  49. package/tools/collect-panel.mjs +3 -24
  50. package/tools/dead-export.mjs +2 -17
  51. package/tools/docs-book.mjs +234 -0
  52. package/tools/docs-drift.mjs +165 -0
  53. package/tools/docs-lint.mjs +24 -0
  54. package/tools/first-run-sweep.mjs +13 -2
  55. package/tools/gate-audit.mjs +3 -24
  56. package/tools/handoff.mjs +3 -1
  57. package/tools/install-check.mjs +294 -0
  58. package/tools/layering-audit.mjs +7 -1
  59. package/tools/legacy-audit.mjs +83 -0
  60. package/tools/lib/case-tool.mjs +8 -2
  61. package/tools/lib/docs-ack.mjs +95 -0
  62. package/tools/lib/docs-core.mjs +38 -22
  63. package/tools/lib/docs-files.mjs +73 -0
  64. package/tools/lib/docs-status.mjs +143 -0
  65. package/tools/lib/idioms.mjs +149 -0
  66. package/tools/lib/import-graph.mjs +8 -3
  67. package/tools/lib/legacy-core.mjs +178 -0
  68. package/tools/lib/markdown.mjs +202 -0
  69. package/tools/lib/modules-doc.mjs +96 -0
  70. package/tools/lib/modules-list.mjs +382 -0
  71. package/tools/lib/modules.mjs +312 -0
  72. package/tools/lib/prefix-cost.mjs +5 -3
  73. package/tools/library-book.mjs +7 -92
  74. package/tools/lint.mjs +5 -0
  75. package/tools/memory-audit.mjs +32 -6
  76. package/tools/memory-recall-eval.mjs +408 -0
  77. package/tools/module-audit.mjs +2 -17
  78. package/tools/modules-audit.mjs +108 -0
  79. package/tools/panel-baseline.mjs +172 -0
  80. package/tools/prefix-audit.mjs +10 -2
  81. package/tools/prefix-drift.mjs +9 -4
  82. package/tools/registry-check.mjs +194 -0
  83. package/tools/release.mjs +374 -0
  84. package/tools/schema-fingerprint.mjs +3 -24
  85. package/tools/version.mjs +12 -8
  86. package/docs/AB-PROMPTS.md +0 -123
  87. package/docs/AB-SESSION.md +0 -161
  88. package/docs/BENCH-BASELINE.json +0 -95
  89. package/docs/BRAIN-VIZ.md +0 -94
  90. package/docs/GATE-INPUTS.json +0 -10
  91. package/docs/HANDOFF-2026-10-27.md +0 -736
  92. package/docs/HOOK-ORDERING.md +0 -139
  93. package/docs/LEGISLATION-LAW.md +0 -104
  94. package/docs/MCP-4.0-PLAN.md +0 -184
  95. package/docs/MEMORY-4.5-PLAN.md +0 -415
  96. package/docs/PROFILE-TUNING.md +0 -147
  97. package/docs/RATCHET.json +0 -72
  98. package/docs/TOOL-SCHEMA.json +0 -6
  99. package/docs/VERSION-PLAN.md +0 -604
  100. package/docs/architecture-map.mermaid +0 -186
  101. package/docs/deepseek-pricing-audit.md +0 -65
  102. package/src/dsh/guard/superpowers.mjs +0 -70
@@ -0,0 +1,408 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * memory:recall(2026-11-24)—— 结构化记忆 vs 向量检索 的离线召回评测
4
+ *
5
+ * 目的:回答「FG 的结构化记忆注入」与「按查询检索记忆」哪个更准、哪个更省 token。
6
+ *
7
+ * 语料(memory units,两种方法用同一份):
8
+ * - `.focus-guard/workspace.json` 的 decisions / constraints / next_action(每条一个 unit)
9
+ * - `.ai/CASE_FILE.md` 按 `##`/`###` 切段(每段一个 unit)
10
+ *
11
+ * 语料口径(2026-11-26 收紧):`decisions` 里**只收带标签的条目**(`[goal]` / `[done]` / `[note]`,
12
+ * 复用 `src/memory/tags.mjs` 的 `parseTag`/`stripTag`)。无标签的一律**排除并只计数**——
13
+ * 自动落账已于 2026-11-26 下架(`memory/workspace.mjs` 头部有下架声明),存量那些是
14
+ * 「本轮人类指令原文」,拿它们当语料等于用垃圾测垃圾:测出来的 100% 只能证明「全量注入包含全量」。
15
+ *
16
+ * 空语料不算通过:`units` 或可标注查询为 0 时**不打印召回率**,直接报「结论无效」并 exit 2。
17
+ * 理由同上——这张表会被断章取义成「检索方案已验证」。
18
+ *
19
+ * 查询(queries):本工作区历史会话里的用户消息(每条 ≥ 12 字、去重),来自 session.v4 日志。
20
+ *
21
+ * 相关性标注(qrels,判定与两种检索都独立):
22
+ * 查询与 unit 的**词项 Jaccard** ≥ `--jaccard`(默认 0.12);没有命中的查询跳过并计数。
23
+ * 这是启发式标注,不是人工 qrels——报告里必须写明,结论只能看相对差。
24
+ *
25
+ * 两种方法:
26
+ * S 结构化:把**全部** memory units 注入(模拟当前 FG 行为),token = 全量单位字数/3;
27
+ * V 向量:TF-IDF 稀疏向量(离线、零依赖;不是神经语义向量),按余弦取 top-k,token = 命中单位字数/3。
28
+ *
29
+ * 指标:Recall@k、MRR、平均注入 token;另报检索耗时。
30
+ *
31
+ * 用法:
32
+ * node packages/core/tools/memory-recall-eval.mjs
33
+ * node packages/core/tools/memory-recall-eval.mjs --k 5 --jaccard 0.1 --json
34
+ */
35
+ import { readFileSync, existsSync } from 'node:fs'
36
+ import { dirname, join, resolve } from 'node:path'
37
+ import { fileURLToPath } from 'node:url'
38
+ import { decodeSession, walkSessionFiles } from './lib/sessionDump.mjs'
39
+ import { parseTag, stripTag } from '../src/memory/tags.mjs'
40
+
41
+ const HERE = dirname(fileURLToPath(import.meta.url))
42
+ const ROOT = resolve(HERE, '..', '..', '..')
43
+ const args = process.argv.slice(2)
44
+ const pick = (f) => {
45
+ const i = args.indexOf(f)
46
+ return i >= 0 ? args[i + 1] : null
47
+ }
48
+ const K = Number(pick('--k') || 3)
49
+ const JACCARD = Number(pick('--jaccard') || 0.12)
50
+ const asJson = args.includes('--json')
51
+
52
+ const STOP = new Set(
53
+ ('the a an and or of to in for on with is are was were be been it this that these those i you we they he she ' +
54
+ '我 你 他 她 它 我们 你们 他们 这 那 这个 那个 的 了 是 在 和 与 或 就 都 也 还 把 被 对 从 到 向 给 让 一个 一些 什么 怎么 为什么 不 没 有 要 能 会 可以 已经 需要 应该 现在 然后 但是 因为 所以')
55
+ .split(/\s+/)
56
+ .filter(Boolean),
57
+ )
58
+
59
+ function terms(text) {
60
+ const t = String(text || '')
61
+ .toLowerCase()
62
+ .replace(/```[\s\S]*?```/g, ' ')
63
+ .replace(/[^\p{L}\p{N}_$-]+/gu, ' ')
64
+ return t
65
+ .split(/\s+/)
66
+ .filter((w) => w.length >= 2 && !STOP.has(w))
67
+ }
68
+
69
+ function jaccard(a, b) {
70
+ const A = new Set(a)
71
+ const B = new Set(b)
72
+ if (!A.size || !B.size) return 0
73
+ let inter = 0
74
+ for (const w of A) if (B.has(w)) inter += 1
75
+ return inter / (A.size + B.size - inter)
76
+ }
77
+
78
+ // ── 1) memory units ──
79
+ const units = []
80
+ function addUnit(kind, text) {
81
+ const body = String(text || '').trim()
82
+ if (!body) return
83
+ units.push({ id: `${kind}#${units.length}`, kind, text: body, terms: terms(body) })
84
+ }
85
+ // 下架前的存量:无标签的 decisions 一律不进语料,只计数(见文件头「语料口径」)。
86
+ let legacyPrompts = 0
87
+ const wsFile = process.env.FG_WORKSPACE_FILE || join(ROOT, '.focus-guard', 'workspace.json')
88
+ if (existsSync(wsFile)) {
89
+ const ws = JSON.parse(readFileSync(wsFile, 'utf8'))
90
+ for (const x of ws.decisions || []) {
91
+ const s = String(x ?? '').trim()
92
+ if (!s) continue
93
+ if (parseTag(s)) addUnit('decision', stripTag(s))
94
+ else legacyPrompts += 1
95
+ }
96
+ for (const x of ws.constraints || []) addUnit('constraint', x)
97
+ for (const x of ws.next_action || []) addUnit('next_action', x)
98
+ }
99
+ const caseFile = process.env.FG_CASE_FILE || join(ROOT, '.ai', 'CASE_FILE.md')
100
+ if (existsSync(caseFile)) {
101
+ const sections = readFileSync(caseFile, 'utf8').split(/^#{2,3} /m).slice(1)
102
+ for (const sec of sections) addUnit('case', sec.slice(0, 1200))
103
+ }
104
+
105
+ // ── 2) queries ──
106
+ const queries = []
107
+ const seen = new Set()
108
+ for (const { f } of walkSessionFiles(join(ROOT, '..', '.dsh', 'sessions'))) {
109
+ let lines
110
+ try {
111
+ lines = decodeSession(f)
112
+ } catch {
113
+ continue
114
+ }
115
+ for (const j of lines) {
116
+ if (j.type !== 'user/message') continue
117
+ const msg = j.data && (j.data.message || j.data)
118
+ const content = msg && msg.content
119
+ const text =
120
+ typeof content === 'string'
121
+ ? content
122
+ : Array.isArray(content)
123
+ ? content
124
+ .filter((b) => b && b.type === 'text')
125
+ .map((b) => b.text || '')
126
+ .join(' ')
127
+ : ''
128
+ const q = String(text || '').trim()
129
+ if ([...q].length < 12) continue
130
+ if (seen.has(q)) continue
131
+ seen.add(q)
132
+ const sid = f.replace(/\\/g, '/').split('/').slice(-2, -1)[0] || ''
133
+ queries.push({ q, sid, terms: terms(q) })
134
+ }
135
+ }
136
+
137
+ // ── 3) qrels ──
138
+ const labelled = []
139
+ for (const q of queries) {
140
+ const rel = units.filter((u) => jaccard(q.terms, u.terms) >= JACCARD).map((u) => u.id)
141
+ if (rel.length) labelled.push({ ...q, rel })
142
+ }
143
+
144
+ // ── 4) 结构化基线:全量注入 ──
145
+ const allTokens = Math.round(units.reduce((a, u) => a + u.text.length, 0) / 3)
146
+ const structured = { name: 'S 结构化全量', recallAtK: null, mrr: null, tokensPerQuery: allTokens, latencyMs: 0 }
147
+ {
148
+ let hit = 0
149
+ for (const q of labelled) {
150
+ // 全量注入:所有 relevant 都在上下文里 → Recall 恒为 100%;
151
+ // MRR 对"全量"无意义(没有排序),留空而不是写 1.0 假装。
152
+ hit += 1
153
+ }
154
+ structured.recallAtK = labelled.length ? hit / labelled.length : null
155
+ structured.mrr = null
156
+ }
157
+
158
+ // ── 5) 向量检索:TF-IDF 稀疏向量 + 余弦 ──
159
+ const df = new Map()
160
+ for (const u of units) for (const w of new Set(u.terms)) df.set(w, (df.get(w) || 0) + 1)
161
+ const N = units.length || 1
162
+ const idf = (w) => Math.log((N + 1) / ((df.get(w) || 0) + 1)) + 1
163
+ function embed(t) {
164
+ const m = new Map()
165
+ for (const w of t) m.set(w, (m.get(w) || 0) + idf(w))
166
+ let norm = 0
167
+ for (const v of m.values()) norm += v * v
168
+ norm = Math.sqrt(norm) || 1
169
+ for (const [w, v] of m) m.set(w, v / norm)
170
+ return m
171
+ }
172
+ const unitVec = new Map(units.map((u) => [u.id, embed(u.terms)]))
173
+ function cosine(a, b) {
174
+ let s = 0
175
+ for (const [w, v] of a) {
176
+ const o = b.get(w)
177
+ if (o) s += v * o
178
+ }
179
+ return s
180
+ }
181
+
182
+ const t0 = process.hrtime.bigint()
183
+ const vectorHits = []
184
+ for (const q of labelled) {
185
+ const qv = embed(q.terms)
186
+ const ranked = units
187
+ .map((u) => ({ id: u.id, score: cosine(qv, unitVec.get(u.id)), len: u.text.length }))
188
+ .sort((a, b) => b.score - a.score)
189
+ .slice(0, K)
190
+ const relSet = new Set(q.rel)
191
+ const hit = ranked.filter((r) => relSet.has(r.id))
192
+ vectorHits.push({
193
+ hit: hit.length ? 1 : 0,
194
+ rr: hit.length ? 1 / (ranked.findIndex((r) => relSet.has(r.id)) + 1) : 0,
195
+ tokens: Math.round(ranked.reduce((a, r) => a + r.len, 0) / 3),
196
+ })
197
+ }
198
+ const elapsed = Number(process.hrtime.bigint() - t0) / 1e6
199
+ const vector = {
200
+ name: `V 向量 top-${K}`,
201
+ recallAtK: vectorHits.length ? vectorHits.reduce((a, r) => a + r.hit, 0) / vectorHits.length : null,
202
+ mrr: vectorHits.length ? vectorHits.reduce((a, r) => a + r.rr, 0) / vectorHits.length : null,
203
+ tokensPerQuery: vectorHits.length ? Math.round(vectorHits.reduce((a, r) => a + r.tokens, 0) / vectorHits.length) : null,
204
+ latencyMs: Number((elapsed / Math.max(1, vectorHits.length)).toFixed(3)),
205
+ }
206
+
207
+ // ── 5.5) 混合:常驻「必须保证」的条目 + 其余走向量 top-k ──
208
+ const PIN_RE = /红线|禁止|不得|必须|不要|不能|约束|goal|目标/i
209
+ const decisionUnits = units.filter((u) => u.kind === 'decision')
210
+ // 钉选策略(可调):约束/下一步 + **最近 3 条决策**。理由是近期决定比远期更可能被引用。
211
+ const recentDecisions = new Set(decisionUnits.slice(-3).map((u) => u.id))
212
+ const pinned = units.filter(
213
+ (u) => u.kind === 'constraint' || u.kind === 'next_action' || recentDecisions.has(u.id) || PIN_RE.test(u.text),
214
+ )
215
+ const pinnedIds = new Set(pinned.map((u) => u.id))
216
+ const retrievable = units.filter((u) => !pinnedIds.has(u.id))
217
+ const pinnedTokens = Math.round(pinned.reduce((a, u) => a + u.text.length, 0) / 3)
218
+ const rVec = new Map(retrievable.map((u) => [u.id, embed(u.terms)]))
219
+ const hybridHits = []
220
+ const th0 = process.hrtime.bigint()
221
+ for (const q of labelled) {
222
+ const qv = embed(q.terms)
223
+ const ranked = retrievable
224
+ .map((u) => ({ id: u.id, score: cosine(qv, rVec.get(u.id)), len: u.text.length }))
225
+ .sort((a, b) => b.score - a.score)
226
+ .slice(0, K)
227
+ const relSet = new Set(q.rel)
228
+ const pinnedHit = q.rel.some((id) => pinnedIds.has(id))
229
+ const vectorHit = ranked.some((r) => relSet.has(r.id))
230
+ hybridHits.push({
231
+ hit: pinnedHit || vectorHit ? 1 : 0,
232
+ tokens: pinnedTokens + Math.round(ranked.reduce((a, r) => a + r.len, 0) / 3),
233
+ })
234
+ }
235
+ const hybridElapsed = Number(process.hrtime.bigint() - th0) / 1e6
236
+ const hybrid = {
237
+ name: `H 混合(钉 ${pinned.length} 条 + top-${K})`,
238
+ recallAtK: hybridHits.length ? hybridHits.reduce((a, r) => a + r.hit, 0) / hybridHits.length : null,
239
+ mrr: null,
240
+ tokensPerQuery: hybridHits.length ? Math.round(hybridHits.reduce((a, r) => a + r.tokens, 0) / hybridHits.length) : null,
241
+ latencyMs: Number((hybridElapsed / Math.max(1, hybridHits.length)).toFixed(3)),
242
+ pinned: pinned.map((u) => u.kind),
243
+ }
244
+
245
+ const byKind = {}
246
+ for (const u of units) byKind[u.kind] = (byKind[u.kind] || 0) + 1
247
+ // 结论无效的两种情形:语料空 / 标注空。都不打印召回率——空集上的 100% 是假象。
248
+ const invalidReason =
249
+ units.length === 0
250
+ ? '语料为空(无带标签结论、无约束、无 CASE 段)'
251
+ : labelled.length === 0
252
+ ? `语料 ${units.length} 条,但没有一条与查询相关(标注 0 条)`
253
+ : null
254
+
255
+ const report = {
256
+ generatedAt: new Date().toISOString(),
257
+ units: units.length,
258
+ byKind,
259
+ legacyPrompts,
260
+ queries: queries.length,
261
+ labelled: labelled.length,
262
+ k: K,
263
+ jaccardThreshold: JACCARD,
264
+ note: '向量=TF-IDF 稀疏向量(离线),不是神经语义向量;qrels 为词项 Jaccard 启发式,结论只看相对差',
265
+ conclusionInvalid: invalidReason,
266
+ methods: [structured, vector, hybrid],
267
+ }
268
+
269
+ // ── 6) 可选:会话级语料(更大、更像真实跨会话召回)──
270
+ if (args.includes('--sessions')) {
271
+ const chunks = []
272
+ for (const { f } of walkSessionFiles(join(ROOT, '..', '.dsh', 'sessions'))) {
273
+ let lines
274
+ try {
275
+ lines = decodeSession(f)
276
+ } catch {
277
+ continue
278
+ }
279
+ const sid = f.replace(/\\/g, '/').split('/').slice(-2, -1)[0] || ''
280
+ let buf = ''
281
+ let lastTurn = null
282
+ const flush = () => {
283
+ const text = buf.trim()
284
+ if ([...text].length >= 40) chunks.push({ id: `chunk#${chunks.length}`, sid, text: text.slice(0, 800), terms: terms(text) })
285
+ buf = ''
286
+ }
287
+ for (const j of lines) {
288
+ if (j.type !== 'user/message' && j.type !== 'assistant/message') continue
289
+ const msg = j.data && (j.data.message || j.data)
290
+ const content = msg && msg.content
291
+ const text =
292
+ typeof content === 'string'
293
+ ? content
294
+ : Array.isArray(content)
295
+ ? content.filter((b) => b && b.type === 'text').map((b) => b.text || '').join(' ')
296
+ : ''
297
+ if (!text) continue
298
+ const turn = j.data && j.data.turn
299
+ if (lastTurn !== null && turn !== lastTurn) {
300
+ flush()
301
+ }
302
+ lastTurn = turn
303
+ buf += ' ' + text
304
+ if ([...buf].length > 800) flush()
305
+ }
306
+ flush()
307
+ }
308
+ const cdf = new Map()
309
+ for (const c of chunks) for (const w of new Set(c.terms)) cdf.set(w, (cdf.get(w) || 0) + 1)
310
+ const CN = chunks.length || 1
311
+ const cidf = (w) => Math.log((CN + 1) / ((cdf.get(w) || 0) + 1)) + 1
312
+ const cvec = (t) => {
313
+ const m = new Map()
314
+ for (const w of t) m.set(w, (m.get(w) || 0) + cidf(w))
315
+ let n = 0
316
+ for (const v of m.values()) n += v * v
317
+ n = Math.sqrt(n) || 1
318
+ for (const [w, v] of m) m.set(w, v / n)
319
+ return m
320
+ }
321
+ const chunkVec = new Map(chunks.map((c) => [c.id, cvec(c.terms)]))
322
+ const relabel = []
323
+ for (const q of queries) {
324
+ const rel = chunks.filter((c) => c.sid !== q.sid && jaccard(q.terms, c.terms) >= JACCARD).map((c) => c.id)
325
+ if (rel.length) relabel.push({ ...q, rel })
326
+ }
327
+ const hits = []
328
+ let tokens = 0
329
+ let structHits = 0
330
+ const hybHits = []
331
+ let hybTokens = 0
332
+ const t1 = process.hrtime.bigint()
333
+ for (const q of relabel) {
334
+ // 结构化基线在同一任务上的"召回归属":qrel 命中的会话片段,其词项是否被 FG 记忆覆盖
335
+ // (记忆全是短条目,命中按 0.3 Jaccard 算覆盖;这是摘要保真度代理,不是逐字包含)。
336
+ const chunkById = new Map(chunks.map((c) => [c.id, c]))
337
+ const covered = q.rel.some((id) => {
338
+ const c = chunkById.get(id)
339
+ if (!c) return false
340
+ return units.some((u) => jaccard(c.terms, u.terms) >= 0.3)
341
+ })
342
+ structHits += covered ? 1 : 0
343
+ const qv = cvec(q.terms)
344
+ const ranked = chunks
345
+ .map((c) => ({ id: c.id, score: cosine(qv, chunkVec.get(c.id)), len: c.text.length }))
346
+ .sort((a, b) => b.score - a.score)
347
+ .slice(0, K)
348
+ const relSet = new Set(q.rel)
349
+ const idx = ranked.findIndex((r) => relSet.has(r.id))
350
+ const vhit = idx >= 0 ? 1 : 0
351
+ hits.push(vhit)
352
+ const chunkTokens = ranked.reduce((a, r) => a + r.len, 0) / 3
353
+ tokens += chunkTokens
354
+ hybHits.push(covered || vhit ? 1 : 0)
355
+ hybTokens += pinnedTokens + chunkTokens
356
+ }
357
+ const el = Number(process.hrtime.bigint() - t1) / 1e6
358
+ report.sessionCorpus = {
359
+ chunks: chunks.length,
360
+ labelled: relabel.length,
361
+ recallAtK: relabel.length ? hits.reduce((a, b) => a + b, 0) / relabel.length : null,
362
+ structuredCoverage: relabel.length ? structHits / relabel.length : null,
363
+ hybridRecall: relabel.length ? hybHits.reduce((a, b) => a + b, 0) / relabel.length : null,
364
+ hybridTokensPerQuery: relabel.length ? Math.round(hybTokens / relabel.length) : null,
365
+ tokensPerQuery: relabel.length ? Math.round(tokens / relabel.length) : null,
366
+ latencyMs: Number((el / Math.max(1, relabel.length)).toFixed(3)),
367
+ }
368
+ }
369
+
370
+ if (asJson) console.log(JSON.stringify(report, null, 2))
371
+ else {
372
+ console.log(`[memory:recall] units=${units.length} queries=${queries.length} labelled=${labelled.length} k=${K} jaccard=${JACCARD}`)
373
+ console.log(
374
+ ` 语料构成:带标签结论 ${byKind.decision || 0} · 被否命令 ${byKind.constraint || 0} · ` +
375
+ `下一步 ${byKind.next_action || 0} · CASE 段 ${byKind.case || 0}`,
376
+ )
377
+ if (legacyPrompts) {
378
+ console.log(
379
+ ` 已排除:无标签 decisions ${legacyPrompts} 条(自动落账已于 2026-11-26 下架,指令原文不再算语料)`,
380
+ )
381
+ }
382
+ if (invalidReason) {
383
+ console.log(`\n ⚠ 结论无效:${invalidReason}。`)
384
+ console.log(' 不打印召回率——空语料上的 100% 会被读成「检索已验证」。')
385
+ console.log(' 要有可用语料,先等 `fg_memory_note` 写出带标签的结论(VERSION-PLAN §1.8 步 1)。')
386
+ } else {
387
+ for (const m of report.methods) {
388
+ console.log(
389
+ ` ${m.name.padEnd(14)} Recall@${K}=${m.recallAtK == null ? '-' : (m.recallAtK * 100).toFixed(1) + '%'} ` +
390
+ `MRR=${m.mrr == null ? '-' : m.mrr.toFixed(3)} tokens/query=${m.tokensPerQuery} latency=${m.latencyMs}ms`,
391
+ )
392
+ }
393
+ console.log(` 注:${report.note}`)
394
+ }
395
+ if (report.sessionCorpus) {
396
+ const s = report.sessionCorpus
397
+ console.log(
398
+ ` [会话语料] chunks=${s.chunks} labelled=${s.labelled} ` +
399
+ `V Recall@${K}=${s.recallAtK == null ? '-' : (s.recallAtK * 100).toFixed(1) + '%'} ` +
400
+ `H Recall=${s.hybridRecall == null ? '-' : (s.hybridRecall * 100).toFixed(1) + '%'} ` +
401
+ `S 覆盖=${s.structuredCoverage == null ? '-' : (s.structuredCoverage * 100).toFixed(1) + '%'} ` +
402
+ `V tokens=${s.tokensPerQuery} H tokens=${s.hybridTokensPerQuery} latency=${s.latencyMs}ms`,
403
+ )
404
+ }
405
+ }
406
+
407
+ // exit 2 专指「没测出东西」,与 1(脚本自身出错)区分开:方便外面一眼分辨是缺语料还是坏了。
408
+ if (invalidReason) process.exitCode = 2
@@ -4,30 +4,15 @@
4
4
  * 输出:每个模块的行数/导出符号/TODO/空 catch/console 调用;测试覆盖线索。
5
5
  * 只读,不改代码。
6
6
  */
7
- import { readdirSync, readFileSync, statSync } from 'node:fs'
7
+ import { readFileSync } from 'node:fs'
8
8
  import { dirname, join, relative } from 'node:path'
9
9
  import { fileURLToPath } from 'node:url'
10
+ import { walk } from './lib/import-graph.mjs'
10
11
 
11
12
  const HERE = dirname(fileURLToPath(import.meta.url))
12
13
  const CORE = join(HERE, '..')
13
14
  const ROOTS = ['src/core', 'src/adapters/dsh', 'src/dsh', 'hooks', 'tools', 'tests']
14
15
 
15
- function walk(dir, out = []) {
16
- let entries = []
17
- try {
18
- entries = readdirSync(dir)
19
- } catch {
20
- return out
21
- }
22
- for (const e of entries) {
23
- const p = join(dir, e)
24
- const st = statSync(p)
25
- if (st.isDirectory()) walk(p, out)
26
- else if (/\.(mjs|js)$/.test(e)) out.push(p)
27
- }
28
- return out
29
- }
30
-
31
16
  const files = ROOTS.flatMap((r) => walk(join(CORE, r)))
32
17
  const rows = []
33
18
  for (const f of files) {
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 模块修订审计(tools/modules-audit.mjs,2026-11-19)
4
+ *
5
+ * 回答一个问题:**哪块地方很久没人看了?**
6
+ *
7
+ * 数据全部现算自 git,清单在 `lib/modules-list.mjs`,算法在 `lib/modules.mjs`。
8
+ * 为什么判据用「其后全仓提交」、为什么看中位文件而不是最新文件——见那两个文件的文件头。
9
+ *
10
+ * 用法:
11
+ * node packages/core/tools/modules-audit.mjs # 一行摘要(供 check 链)
12
+ * node packages/core/tools/modules-audit.mjs --table # 完整表
13
+ * node packages/core/tools/modules-audit.mjs --json # 机器读
14
+ * node packages/core/tools/modules-audit.mjs --sync # 写 docs/MODULES.md
15
+ * node packages/core/tools/modules-audit.mjs --check-doc # 台账是否落后
16
+ * node packages/core/tools/modules-audit.mjs --strict # 清单有缺陷时 exit 1
17
+ *
18
+ * 退出码:默认只在 `--strict` 下因清单缺陷(路径缺失/重叠/未归属/id 重复)非零;
19
+ * 「久未动」本身**永不**导致非零——那是信息,不是错误。
20
+ */
21
+ import { writeFileSync } from 'node:fs'
22
+ import { dirname, join, resolve } from 'node:path'
23
+ import { fileURLToPath } from 'node:url'
24
+ import {
25
+ MODULES,
26
+ MODULES_DOC,
27
+ collectModules,
28
+ collectCoverage,
29
+ renderModules,
30
+ checkModulePaths,
31
+ checkModuleIds,
32
+ checkModuleOverlap,
33
+ checkModuleCoverage,
34
+ checkModulesDoc,
35
+ } from './lib/modules.mjs'
36
+
37
+ const HERE = dirname(fileURLToPath(import.meta.url))
38
+ const ROOT = resolve(HERE, '..', '..', '..')
39
+ const argv = process.argv.slice(2)
40
+ const has = (k) => argv.includes(k)
41
+
42
+ const data = collectModules(ROOT, MODULES)
43
+ const coverage = collectCoverage(ROOT, MODULES)
44
+ const problems = [
45
+ ...checkModulePaths(ROOT, MODULES),
46
+ ...checkModuleIds(MODULES),
47
+ ...checkModuleOverlap(ROOT, MODULES),
48
+ ...checkModuleCoverage(ROOT, MODULES),
49
+ ]
50
+
51
+ if (has('--sync')) {
52
+ writeFileSync(join(ROOT, MODULES_DOC), renderModules(data, coverage))
53
+ process.stdout.write(`[modules] 已生成 ${MODULES_DOC}:${data.rows.length} 个模块\n`)
54
+ process.exit(0)
55
+ }
56
+
57
+ if (has('--json')) {
58
+ process.stdout.write(`${JSON.stringify({ head: data.head, age: data.age, total: data.total, rows: data.rows, coverage, problems }, null, 2)}\n`)
59
+ process.exit(has('--strict') && problems.length ? 1 : 0)
60
+ }
61
+
62
+ const byLevel = (lv) => data.rows.filter((r) => r.level === lv)
63
+ const dirty = data.rows.filter((r) => r.dirty)
64
+
65
+ if (has('--check-doc')) {
66
+ const docFindings = checkModulesDoc(ROOT)
67
+ process.stdout.write(docFindings.length ? `[modules] ${docFindings[0].detail}\n` : '[modules] 台账与现算一致\n')
68
+ process.exit(docFindings.length ? 1 : 0)
69
+ }
70
+
71
+ if (has('--table')) {
72
+ process.stdout.write(`模块修订(HEAD ${data.head ? data.head.slice(0, 7) : '—'} · 仓龄 ${data.age} 天 · ${data.total} 次提交)\n\n`)
73
+ process.stdout.write(' 距今:最新 = 最勤快的文件;中位 = 一半文件比它旧(判定看它);最久 = 最沉的文件\n\n')
74
+ const icon = { 久未动: '✗', 临期: '!', 偏冷: '·', 活跃: '·', 无法定位: '?' }
75
+ for (const r of data.rows) {
76
+ const flags = []
77
+ if (r.touches < 3) flags.push('历史浅')
78
+ if (r.dirty) flags.push('有未提交改动')
79
+ const tail = flags.length ? ` · ${flags.join(' · ')}` : ''
80
+ const span = `${r.latestDays}/${r.medianDays}/${r.oldestDays}`.padStart(11)
81
+ process.stdout.write(
82
+ ` ${icon[r.level]} ${r.name.padEnd(20, ' ')} 距今 ${span} 天 · 中位其后 ${String(r.median ?? '—').padStart(3)} 次 · ${String(r.files).padStart(2)} 文件 · ${r.level}${tail}\n`,
83
+ )
84
+ }
85
+ process.stdout.write(
86
+ '\n图例:✗ 久未动 ! 临期 · 偏冷/活跃 ? 无法定位\n' +
87
+ '判定看「中位文件其后全仓提交数」:该文件最后修订之后,仓库又走了多少步。≥30 偏冷 / ≥80 临期 / ≥150 久未动。\n' +
88
+ `覆盖:受管 ${coverage.total} 个文件,仓根元数据 ${coverage.meta} 个,未归属功能文件 ${coverage.unowned} 个\n`,
89
+ )
90
+ } else {
91
+ // 摘要行:进 check 链,每次跑都提一句。**不红**——久未动不等于坏。
92
+ // 不逐条列 id:三十几个模块列出来没人读,只报计数与前三个最陈旧的。
93
+ const n = (lv) => byLevel(lv).length
94
+ const worst = data.rows
95
+ .filter((r) => r.level === '久未动')
96
+ .slice(0, 3)
97
+ .map((r) => `${r.id} ${r.median} 次`)
98
+ const rest = []
99
+ if (n('无法定位')) rest.push(`无法定位 ${n('无法定位')}`)
100
+ if (dirty.length) rest.push(`有未提交改动 ${dirty.length}`)
101
+ process.stdout.write(
102
+ `模块修订:${data.rows.length} 个模块,久未动 ${n('久未动')} / 临期 ${n('临期')} / 偏冷 ${n('偏冷')} / 活跃 ${n('活跃')}` +
103
+ `${worst.length ? `;最陈旧 ${worst.join(' · ')}` : ''}${rest.length ? `;${rest.join(';')}` : ''}\n`,
104
+ )
105
+ }
106
+
107
+ for (const p of problems) process.stdout.write(` ✗ [${p.rule}] ${p.detail}\n`)
108
+ process.exit(has('--strict') && problems.length ? 1 : 0)