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,312 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { MODULES, META_FILES } from './modules-list.mjs'
5
+ import { MODULES_DOC, renderModules } from './modules-doc.mjs'
6
+
7
+ // 渲染器住在 modules-doc.mjs,清单住在 modules-list.mjs,这里只管「怎么算」。
8
+ export { MODULES, META_FILES, MODULES_DOC, renderModules }
9
+
10
+ /**
11
+ * 模块修订台账(tools/lib/modules.mjs,2026-11-19)
12
+ *
13
+ * ## 它防的是什么
14
+ *
15
+ * 不是「代码坏了」,是「**某块地方很久没人看,也没人记得它存在**」。
16
+ * 这类腐化没有报错、没有红测试,只是慢慢和其余部分脱节:
17
+ * 别人重构了调用方,它还按旧契约写着;接口变了,它还在按老假设兜底。
18
+ *
19
+ * ## 为什么一个日期都不存
20
+ *
21
+ * `docs/INDEX.md` 手抄过一份「适用版本 / 最后核对」,实测 **18 处与文档自身状态头不符**,
22
+ * 分叉二十多天无人发现——手写的真值一定会腐化,且没有判据能发现。
23
+ * 所以这里全部现算 git。手写的只有一样:**哪些路径算一个模块**(`modules-list.mjs`)。
24
+ *
25
+ * ## 判据为什么用「其后全仓提交」而不是天数
26
+ *
27
+ * 初版按「距今 120 天 / 400 次提交」判定,跑出 13 个模块全绿;收紧到 30 天仍全绿。
28
+ * 因为这个仓只有 51 天(397 次提交、日均 7.6 次)——照「几年的仓」设的天数线,
29
+ * 等于永远量不到东西。第二版改用「模块自身提交间隔的中位数」,更糟:多数模块是被
30
+ * 一批连续 commit 引入的,中位数被压到 0.0x 天;而提交不足 3 次的模块算不出中位数、
31
+ * 退回宽松兜底,**越该被提醒的越绿**——方向是反的。
32
+ *
33
+ * 最终用:**该文件最后一次修订之后,全仓又提交了多少次**。
34
+ * 它随仓库节奏自伸缩(日更十次的仓里 30 次是三天,月更的仓里是半年)、单调、动一次归零,
35
+ * 而且不需要给任何模块配数字——没有第二份手写真值。
36
+ *
37
+ * ## 为什么按「中位文件」判,不按「最新文件」
38
+ *
39
+ * 2026-11-19 第二处返工。模块整体取最新,等于**只统计最勤快的那一个文件**:
40
+ * 实测 `tools` 最新文件 0 天、中位文件 16 天;`src/core` 最新 0 天、中位 21 天。
41
+ * 一个 61 文件的目录里 2 个在动,整块就显示「活跃」——正是「个别文件活跃,其余很少动」
42
+ * 被遮住的地方。所以判定看**该模块所有文件「其后提交数」的中位数**:
43
+ * 一半以上的文件多久没动,才是这块真实的陈旧程度。最新与最久照列,供人看分布。
44
+ *
45
+ * ## 判定不拦构建
46
+ *
47
+ * 「久未动」不等于「坏了」。设成硬红就是一个永远红的闸门——「永久红会训练人忽略告警」。
48
+ * 所以表里加粗提示,`--strict` 也不因它 exit 1。真正会红的是**确定是错**的三件事:
49
+ * 清单路径不存在、两个模块抢同一个文件、有功能文件没被任何模块认领。
50
+ */
51
+
52
+ /** 等级由高到低。排序用它,`无法定位` 排最前——路径在 git 里找不到任何提交,本身就要看。 */
53
+ export const LEVEL_RANK = { 无法定位: 4, 久未动: 3, 临期: 2, 偏冷: 1, 活跃: 0 }
54
+
55
+ /**
56
+ * 阈值:**中位文件「其后全仓提交」的次数**。
57
+ *
58
+ * `30` 的意思是「仓库又往前走了三十步,这块一半以上的文件一步没挪」。
59
+ * 定这个值时的仓况:51 天 / 397 次提交 / 日均 7.6 次,所以 30 次 ≈ 四天。
60
+ * 仓的节奏变了不必急着调——它是相对量,会跟着一起伸缩。
61
+ */
62
+ const SINCE = { cold: 30, due: 80, stale: 150 }
63
+
64
+ /** 累计提交少于此数视为「历史浅」:样本不足以谈节奏,本身也是遗忘风险。 */
65
+ const THIN = 3
66
+
67
+ const DAYS = 86400
68
+
69
+ /** `git` 调用统一出口:失败一律返回 null,**不抛**——没装 git 的机器不该因此炸掉。 */
70
+ function git(repo, args) {
71
+ try {
72
+ return execFileSync('git', args, { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
73
+ } catch {
74
+ return null
75
+ }
76
+ }
77
+
78
+ /**
79
+ * 一次读完整部历史:新 → 旧,每条带时间戳、短 hash、标题、触及的文件。
80
+ *
81
+ * 用 `--name-status` 而非 `--name-only`:改名会输出 `R100\t旧\t新`,只取新路径就会
82
+ * 漏掉「某文件被移出本模块」那次提交(实测 adapters 少算 1 次)。文件名那栏可能有
83
+ * 两个字段,所以 `parts.slice(1)` 全收。
84
+ */
85
+ function scanHistory(repo) {
86
+ const raw = git(repo, ['log', '--format=%x00%ct%x00%h%x00%s', '--name-status'])
87
+ if (!raw) return []
88
+ const out = []
89
+ let cur = null
90
+ for (const line of raw.split('\n')) {
91
+ if (line.startsWith('\u0000')) {
92
+ const [, ts, hash, subject] = line.split('\u0000')
93
+ cur = { ts: Number(ts), hash, subject, files: new Set() }
94
+ out.push(cur)
95
+ continue
96
+ }
97
+ if (!cur || !line) continue
98
+ for (const f of line.split('\t').slice(1)) cur.files.add(f)
99
+ }
100
+ return out
101
+ }
102
+
103
+ /**
104
+ * 排除项的两种写法:`:(exclude)path` 与 `:!path`。**必须按整段前缀切**。
105
+ *
106
+ * 2026-11-19 首版写成 `p.slice(3, -1)`,本想把 `:(exclude)foo` 切成 `foo`,
107
+ * 实际切出 `xclude)fo`——排除项从此一条都没生效:`dsh` 把 `guard`/`seams` 的提交
108
+ * 算进自己(101 次,git 的答案是 98),`core` 把 `prefixStability` 算进自己(68,实为 64)。
109
+ * 手工复刻 git 的 pathspec 就是在重写它的解析器,**任何一处差一点都会静默算错**,
110
+ * 所以 `tests/modules-attribution.test.mjs` 拿 git 自己的结果当基准比对。
111
+ */
112
+ const EXCLUDE = /^:(?:\(exclude\)|!)/
113
+
114
+ /** 路径是否落在某组 pathspec 里(含排除项)。目录按 `/` 边界匹配,防 `tools-x` 误配 `tools`。 */
115
+ function matches(paths, file) {
116
+ let hit = false
117
+ for (const p of paths) {
118
+ const neg = EXCLUDE.exec(p)
119
+ const raw = neg ? p.slice(neg[0].length) : p
120
+ const inside = file === raw || file.startsWith(`${raw}/`)
121
+ if (!inside) continue
122
+ if (neg) return false
123
+ hit = true
124
+ }
125
+ return hit
126
+ }
127
+
128
+ /** 中位数(偶数取偏上)。空数组返回 null。 */
129
+ function median(nums) {
130
+ if (!nums.length) return null
131
+ const s = [...nums].sort((a, b) => a - b)
132
+ return s[Math.floor(s.length / 2)]
133
+ }
134
+
135
+ export function collectModules(repo, modules = MODULES, now = new Date()) {
136
+ const commits = scanHistory(repo)
137
+ const head = commits[0]?.hash ?? null
138
+ const first = commits[commits.length - 1]?.ts ?? null
139
+ const age = first ? Math.floor((now.getTime() / 1000 - first) / DAYS) : null
140
+ // 每个文件最后一次被碰的**提交下标**(0 = HEAD)。下标本身就是「其后全仓提交数」。
141
+ const lastAt = new Map()
142
+ for (let i = 0; i < commits.length; i += 1) for (const f of commits[i].files) if (!lastAt.has(f)) lastAt.set(f, i)
143
+ const tracked = (git(repo, ['ls-files']) || '').split('\n').filter(Boolean)
144
+ const dirtySet = new Set(
145
+ (git(repo, ['status', '--porcelain', '-uall']) || '')
146
+ .split('\n')
147
+ .filter(Boolean)
148
+ .map((l) => l.slice(3).replace(/^.* -> /, '')),
149
+ )
150
+ // 台账的「适用版本」要填**产品版本号**,不是 commit hash——hash 进不了版本面比较,
151
+ // 在 `docs/STATUS.md` 里会被当成「无版本面」。hash 放在正文里就够定位。
152
+ let version = null
153
+ try {
154
+ version = JSON.parse(readFileSync(join(repo, 'packages/core/package.json'), 'utf8')).version
155
+ } catch {
156
+ version = null
157
+ }
158
+ const ago = (i) => (commits[i] ? Math.floor((now.getTime() / 1000 - commits[i].ts) / DAYS) : null)
159
+ const rows = []
160
+ for (const m of modules) {
161
+ const files = tracked.filter((f) => matches(m.paths, f))
162
+ const idxs = files.map((f) => lastAt.get(f)).filter((v) => v !== undefined).sort((a, b) => a - b)
163
+ // 提交归属按 pathspec 语义逐条判,不看文件是否还存在——git 的 `log -- path`
164
+ // 连已删除/改名的旧路径也算,只拿现存文件比对会让累计数比 `rev-list --count` 少。
165
+ let touches = 0
166
+ let hit = null
167
+ for (let i = 0; i < commits.length; i += 1) {
168
+ if (![...commits[i].files].some((f) => matches(m.paths, f))) continue
169
+ touches += 1
170
+ if (hit === null) hit = i
171
+ }
172
+ const mid = median(idxs)
173
+ rows.push({
174
+ id: m.id,
175
+ name: m.name,
176
+ note: m.note,
177
+ files: files.length,
178
+ latest: idxs.length ? idxs[0] : null,
179
+ median: mid,
180
+ oldest: idxs.length ? idxs[idxs.length - 1] : null,
181
+ latestDays: idxs.length ? ago(idxs[0]) : null,
182
+ medianDays: mid === null ? null : ago(mid),
183
+ oldestDays: idxs.length ? ago(idxs[idxs.length - 1]) : null,
184
+ since: hit,
185
+ touches,
186
+ hash: hit === null ? null : commits[hit].hash,
187
+ date: hit === null ? null : new Date(commits[hit].ts * 1000).toISOString(),
188
+ dirty: files.some((f) => dirtySet.has(f)),
189
+ level:
190
+ mid === null
191
+ ? '无法定位'
192
+ : mid >= SINCE.stale
193
+ ? '久未动'
194
+ : mid >= SINCE.due
195
+ ? '临期'
196
+ : mid >= SINCE.cold
197
+ ? '偏冷'
198
+ : '活跃',
199
+ })
200
+ }
201
+ // 按风险排,不按「有没有未提交改动」排——那个只该是标记。
202
+ // 首版把 dirty 排最前,结果前两行全是「有未提交改动」,后面一片绿,看着像全活跃。
203
+ rows.sort((a, b) => LEVEL_RANK[b.level] - LEVEL_RANK[a.level] || (b.median ?? -1) - (a.median ?? -1))
204
+ return { head, version, age, total: commits.length, rows }
205
+ }
206
+
207
+ /**
208
+ * 覆盖情况:有没有功能文件没被任何模块认领。
209
+ *
210
+ * 这是「全活跃」那次翻车的真正原因——清单里少了整个 `packages/extended`(外接三包),
211
+ * 而它 43 天没动、史上只有 5 次提交,**最该被提醒的那块根本不在表里**。
212
+ * 仓根那些 LICENSE / package.json / CI 配置列在 `META_FILES` 里,是「本来就不归属」,
213
+ * 不算漏;除它们之外还有文件没归属,就是清单真的漏了。
214
+ */
215
+ export function collectCoverage(repo, modules = MODULES) {
216
+ const tracked = (git(repo, ['ls-files']) || '').split('\n').filter(Boolean)
217
+ const unowned = tracked.filter((f) => !matches(META_FILES, f) && !modules.some((m) => matches(m.paths, f)))
218
+ return { total: tracked.length, meta: tracked.filter((f) => matches(META_FILES, f)).length, unowned: unowned.length, sample: unowned.slice(0, 5) }
219
+ }
220
+
221
+ /**
222
+ * 判据①:清单里的路径必须存在。
223
+ *
224
+ * 这是**真错**:目录搬走/改名而清单没跟着改,表就成了假话,而且看起来一切正常。
225
+ * 与「久未动」不同——久未动是信息,路径不存在是缺陷。
226
+ */
227
+ export function checkModulePaths(repo, modules = MODULES) {
228
+ const findings = []
229
+ for (const m of modules) {
230
+ for (const p of m.paths) {
231
+ if (EXCLUDE.test(p)) continue // 排除项不是路径,别拿它去 existsSync
232
+ if (!existsSync(join(repo, p))) {
233
+ findings.push({ rule: 'modules-path-missing', file: 'packages/core/tools/lib/modules-list.mjs', line: 1, detail: `${m.id} 的路径不存在:${p}` })
234
+ }
235
+ }
236
+ }
237
+ return findings
238
+ }
239
+
240
+ /** 判据②:模块 `id` 不许重复——重复会让 `--json` 的消费方拿到两条同 id 的记录。 */
241
+ export function checkModuleIds(modules = MODULES) {
242
+ const seen = new Map()
243
+ const findings = []
244
+ for (const m of modules) {
245
+ if (seen.has(m.id)) {
246
+ findings.push({ rule: 'modules-id-duplicate', file: 'packages/core/tools/lib/modules-list.mjs', line: 1, detail: `id \`${m.id}\` 重复(${seen.get(m.id)} 与 ${m.name})` })
247
+ } else {
248
+ seen.set(m.id, m.name)
249
+ }
250
+ }
251
+ return findings
252
+ }
253
+
254
+ /**
255
+ * 判据③:一个文件只能属于一个模块。
256
+ *
257
+ * 重叠的后果是同一份改动同时点亮两行,看着像「两块都在动」,判定就假了。
258
+ * 三十个模块全手写路径,重叠是很容易犯的错——所以由机器查。
259
+ */
260
+ export function checkModuleOverlap(repo, modules = MODULES) {
261
+ const tracked = (git(repo, ['ls-files']) || '').split('\n').filter(Boolean)
262
+ const owner = new Map()
263
+ const findings = []
264
+ for (const m of modules) {
265
+ for (const f of tracked) {
266
+ if (!matches(m.paths, f)) continue
267
+ if (owner.has(f) && owner.get(f) !== m.id) {
268
+ findings.push({ rule: 'modules-path-overlap', file: 'packages/core/tools/lib/modules-list.mjs', line: 1, detail: `${f} 同时属于 ${owner.get(f)} 与 ${m.id}` })
269
+ } else {
270
+ owner.set(f, m.id)
271
+ }
272
+ }
273
+ }
274
+ return findings
275
+ }
276
+
277
+ /** 判据④:不能有功能文件落在所有模块之外——漏掉一块,那块就永远不会被提醒。 */
278
+ export function checkModuleCoverage(repo, modules = MODULES) {
279
+ const { unowned, sample } = collectCoverage(repo, modules)
280
+ if (!unowned) return []
281
+ return [
282
+ {
283
+ rule: 'modules-unowned-path',
284
+ file: 'packages/core/tools/lib/modules-list.mjs',
285
+ line: 1,
286
+ detail: `${unowned} 个文件不属于任何模块:${sample.join('、')}${unowned > sample.length ? ' 等' : ''}`,
287
+ },
288
+ ]
289
+ }
290
+
291
+ /**
292
+ * 台账是否与现算一致。
293
+ *
294
+ * **刻意不进 `docs:lint`**:这张表的「其后提交」每次提交都会变,一旦当成硬闸,
295
+ * 每次 commit 都会红一次——那正是「永久红的闸门等于没有闸门」。
296
+ * 改为由 `.githooks/pre-commit` 自动重新生成并 `git add`,人不用记着跑。
297
+ */
298
+ export function checkModulesDoc(repo) {
299
+ const want = renderModules(collectModules(repo), collectCoverage(repo))
300
+ let got = ''
301
+ try {
302
+ got = readFileSync(join(repo, MODULES_DOC), 'utf8')
303
+ } catch {
304
+ return [{ rule: 'modules-doc-stale', file: MODULES_DOC, line: 1, detail: '台账不存在,跑 `npm run modules:sync` 生成' }]
305
+ }
306
+ // 只比结构指纹,不比逐字:表里全是会随「现在」变的量,逐字比对会让开发中途的 check 无故变红。
307
+ const keyOf = (t) => (t.match(/<!-- modules-key[^\n]*\n([\s\S]*?)\n-->/) || [, ''])[1]
308
+ if (keyOf(got) !== keyOf(want)) {
309
+ return [{ rule: 'modules-doc-stale', file: MODULES_DOC, line: 1, detail: '台账与模块清单不一致(清单改了没重生成),跑 `npm run modules:sync`' }]
310
+ }
311
+ return []
312
+ }
@@ -20,9 +20,10 @@ import { calcCost } from '../../src/peak-cost.mjs'
20
20
  export function runCost({ sessionsDir, limit = 8 } = {}) {
21
21
  const TOK = (chars) => Math.round(chars / 4)
22
22
  const rows = []
23
- for (const cand of walkSessionFiles(sessionsDir)
24
- .filter((x) => x.size < 3 * 1024 * 1024)
25
- .slice(0, limit)) {
23
+ // 2026-11-20 修选样:原先先 `slice(0, limit)` 再筛「≥5 步」,等于只在前 8 个文件里碰运气——
24
+ // 而落盘目录里靠前的是 hermes-loop-review 那批短会话,结果恒报「找不到 ≥5 步的会话」。
25
+ // 现在遍历全部、合格才计数,够 `limit` 个就停。与 `prefix-audit` 的选会话口径对齐。
26
+ for (const cand of walkSessionFiles(sessionsDir).filter((x) => x.size < 3 * 1024 * 1024)) {
26
27
  let lines
27
28
  try {
28
29
  lines = decodeSession(cand.f)
@@ -83,6 +84,7 @@ export function runCost({ sessionsDir, limit = 8 } = {}) {
83
84
  beforeTotal: before + after,
84
85
  afterTotal: after,
85
86
  })
87
+ if (rows.length >= limit) break
86
88
  }
87
89
  return rows
88
90
  }
@@ -22,6 +22,7 @@
22
22
  import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
23
23
  import { basename, join } from 'node:path'
24
24
  import { BOOK_CSS } from './lib/book-style.mjs'
25
+ import { mdToHtml } from './lib/markdown.mjs'
25
26
 
26
27
  const argv = process.argv.slice(2)
27
28
  const arg = (k, d) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : d)
@@ -30,98 +31,12 @@ const OUT = arg('--out', join(SRC, 'book.html'))
30
31
  const LABEL = arg('--label', '资料书')
31
32
  const UNIT = arg('--unit', '块')
32
33
 
33
- // ── markdown:只覆盖积木实际用到的语法 ────────────────────────────────────
34
- // 实测(28 块 5.7 万字):无序列表 728、有序列表 60、### 小标题 23、粗体 164;
35
- // 表格 0、代码块 0。所以不引依赖,写这几种就够。
36
- // 2026-10-30 补 `>` 引用与 `---` 分隔线:按文件切(章节版)会保留每份资料开头的
37
- // 来源说明,那几行正是 `>` 引用;卡片版按 `##` 切时整段被丢掉,所以以前没暴露。
38
- const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
39
-
40
- function inline(s) {
41
- return esc(s)
42
- .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
43
- .replace(/`([^`]+)`/g, '<code>$1</code>')
44
- }
45
-
46
- export function mdToHtml(md) {
47
- const out = []
48
- let list = null
49
- let quote = null
50
- const flush = () => {
51
- if (list) {
52
- out.push(`<${list.tag}>${list.items.map((i) => `<li>${i}</li>`).join('')}</${list.tag}>`)
53
- list = null
54
- }
55
- if (quote) {
56
- out.push(`<blockquote>${quote.map((i) => `<p>${i}</p>`).join('')}</blockquote>`)
57
- quote = null
58
- }
59
- }
60
- for (const raw of String(md).split('\n')) {
61
- const line = raw.trimEnd()
62
- if (!line.trim()) {
63
- flush()
64
- continue
65
- }
66
- const h = /^(#{1,6})\s+(.*)$/.exec(line)
67
- if (h) {
68
- flush()
69
- const lv = Math.min(6, h[1].length + 1)
70
- out.push(`<h${lv}>${inline(h[2])}</h${lv}>`)
71
- continue
72
- }
73
- // 分隔线:必须在列表之前判,否则 `---` 会被当成空的列表项
74
- if (/^(-{3,}|\*{3,}|_{3,})$/.test(line.trim())) {
75
- flush()
76
- out.push('<hr>')
77
- continue
78
- }
79
- const bq = /^>\s?(.*)$/.exec(line)
80
- if (bq) {
81
- if (list) {
82
- out.push(`<${list.tag}>${list.items.map((i) => `<li>${i}</li>`).join('')}</${list.tag}>`)
83
- list = null
84
- }
85
- if (!quote) quote = []
86
- quote.push(inline(bq[1]))
87
- continue
88
- }
89
- const ul = /^[-*]\s+(.*)$/.exec(line)
90
- if (ul) {
91
- if (!list || list.tag !== 'ul') {
92
- flush()
93
- list = { tag: 'ul', items: [] }
94
- }
95
- list.items.push(inline(ul[1]))
96
- continue
97
- }
98
- const ol = /^\d+\.\s+(.*)$/.exec(line)
99
- if (ol) {
100
- if (!list || list.tag !== 'ol') {
101
- flush()
102
- list = { tag: 'ol', items: [] }
103
- }
104
- list.items.push(inline(ol[1]))
105
- continue
106
- }
107
- flush()
108
- // 认笔记自己的体例(三层):整行只有一句粗体的 → 小标题;`→ 接入…` → 动作行;
109
- // `出处:…` → 出处行。不认这三层的话,每条都摊成四段同样大小的字,读起来一片平。
110
- const html = inline(line)
111
- const strongOnly =
112
- /^<strong>[\s\S]*<\/strong>$/.test(html) && (html.match(/<strong>/g) || []).length === 1
113
- const cls = strongOnly
114
- ? ' class="h"'
115
- : line.startsWith('→')
116
- ? ' class="act"'
117
- : /^出处[::]/.test(line)
118
- ? ' class="ref"'
119
- : ''
120
- out.push(`<p${cls}>${html}</p>`)
121
- }
122
- flush()
123
- return out.join('\n')
124
- }
34
+ // ── markdown ──────────────────────────────────────────────────────────────
35
+ // 2026-11-19:渲染器移到 `lib/markdown.mjs`,与「全仓文档书」(`docs-book.mjs`)共用。
36
+ // 原先这里有一份只认卡片语法的实现;做第二本书时如果再抄一份,两份迟早对同一段
37
+ // markdown 给出不同结果,而且没有任何判据会发现。卡片体例靠 `cardClasses` 选项保留。
38
+ // 顺带补上表格与代码围栏——积木里没有,但共用件必须有。
39
+ export { mdToHtml }
125
40
 
126
41
  /** frontmatter + 正文;没有 frontmatter 就整体当正文。 */
127
42
  export function parseBlock(text) {
package/tools/lint.mjs CHANGED
@@ -49,6 +49,7 @@ import { fileURLToPath } from 'node:url'
49
49
  import { stripLiterals } from './lib/source-text.mjs'
50
50
  // 目录遍历复用 lib 里那一份:带 SKIP_DIRS 的版本曾在 lint / smells 各抄一遍(2026-11-17 收成参数)。
51
51
  import { walk } from './lib/import-graph.mjs'
52
+ import { scanIdioms, IDIOMS } from './lib/idioms.mjs'
52
53
 
53
54
  const HERE = dirname(fileURLToPath(import.meta.url))
54
55
  // 仓库根可覆盖:测试要造夹具目录跑真扫描,否则这个工具自己没被测量。
@@ -137,6 +138,9 @@ const RULES = {
137
138
  var: '使用 var(应 let/const)',
138
139
  'loose-equal': '使用 == / !=(两侧均非 null/undefined)',
139
140
  'console-in-src': 'console.log 留在 src/(污染输出)',
141
+ ...Object.fromEntries(IDIOMS.map((r) => [r.id, r.why])),
142
+ 'filter-first': 'filter(...)[0] 应换 find(...)(少一次全表扫描 + 少一个数组)',
143
+ 'filter-length': 'filter(...).length 应换 some/every(命中即停)',
140
144
  }
141
145
 
142
146
  const findings = []
@@ -233,6 +237,7 @@ for (const file of files) {
233
237
  checkVar(file, plain)
234
238
  checkLooseEqual(file, plain)
235
239
  checkConsole(file, plain)
240
+ for (const hit of scanIdioms(plain, src)) report(file, hit.line, hit.rule, hit.detail)
236
241
  }
237
242
 
238
243
  const byRule = {}
@@ -5,10 +5,18 @@
5
5
  * 收益:M1 验收要求一条命令说清「记忆存在哪、多大、索引有没有」。
6
6
  * 改动面:本文件 + package.json 一行 script,不跨层。
7
7
  * 替代:无更小做法——验收命令需要一个真实入口。
8
+ *
9
+ * 状态口径(2026-11-26 收紧):`OK` 只说明**文件在**,不说明记忆健康。
10
+ * 卷宗里若还有下架前的无标签 `decisions`(自动落账已于 2026-11-26 下架,见
11
+ * `src/memory/workspace.mjs` 头部),标 `STALE` 并写明条数——那些是指令原文,不是结论。
12
+ * 早期版本把它们算进「条目 N」并盖 OK,等于让体检报告替半成品背书。
13
+ *
14
+ * 退出码:0 = 全 OK;1 = 有载体缺失;2 = 文件都在但有存量待清理(不是坏了,是脏)。
8
15
  */
9
16
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
10
17
  import { dirname, join, resolve } from 'node:path'
11
18
  import { fileURLToPath } from 'node:url'
19
+ import { parseTag } from '../src/memory/tags.mjs'
12
20
 
13
21
  const HERE = dirname(fileURLToPath(import.meta.url))
14
22
  const REPO = resolve(HERE, '..', '..', '..')
@@ -21,8 +29,17 @@ const carriers = [
21
29
  describe: (p) => {
22
30
  const raw = readFileSync(p, 'utf8')
23
31
  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}`
32
+ const decisions = (j.decisions || []).map((x) => String(x ?? '').trim()).filter(Boolean)
33
+ const conclusions = decisions.filter((x) => parseTag(x)).length
34
+ const legacy = decisions.length - conclusions
35
+ const constraints = (j.constraints || []).length
36
+ // 旧版读的是 `j.next`(字段名不存在,恒算 0),实际键是 `next_action`。
37
+ const next = (j.next_action || []).length
38
+ const detail =
39
+ `${raw.length} 字节 · workspace_hash=${j.workspace_hash || '—'} · ` +
40
+ `带标签结论 ${conclusions} · 被否命令 ${constraints} · 下一步 ${next}` +
41
+ (legacy ? ` · 存量指令原文 ${legacy}(待清理,不注入)` : '')
42
+ return { status: legacy ? 'STALE' : 'OK', detail }
26
43
  },
27
44
  },
28
45
  {
@@ -32,7 +49,7 @@ const carriers = [
32
49
  describe: (p) => {
33
50
  const raw = readFileSync(p, 'utf8')
34
51
  const sections = (raw.match(/^#{1,6}\s*【[一二三四五六七八九十]+】/gm) || []).length
35
- return `${raw.length} 字节 · 章节 ${sections}`
52
+ return { status: 'OK', detail: `${raw.length} 字节 · 章节 ${sections}` }
36
53
  },
37
54
  },
38
55
  {
@@ -49,12 +66,13 @@ const carriers = [
49
66
  try { archive += readdirSync(join(archiveRoot, d)).filter((f) => f.endsWith('.md')).length } catch {}
50
67
  }
51
68
  }
52
- return `现行 ${live} 份 · 归档 ${archive} 份 · 索引 ${existsSync(idx) ? '有' : '无'}`
69
+ return { status: 'OK', detail: `现行 ${live} 份 · 归档 ${archive} 份 · 索引 ${existsSync(idx) ? '有' : '无'}` }
53
70
  },
54
71
  },
55
72
  ]
56
73
 
57
74
  let bad = 0
75
+ let stale = 0
58
76
  for (const c of carriers) {
59
77
  if (!existsSync(c.path)) {
60
78
  process.stdout.write(`${c.key}\t${c.label}\tMISSING\t${c.path}\n`)
@@ -62,6 +80,14 @@ for (const c of carriers) {
62
80
  continue
63
81
  }
64
82
  statSync(c.path)
65
- process.stdout.write(`${c.key}\t${c.label}\tOK\t${c.describe(c.path)}\n`)
83
+ const { status, detail } = c.describe(c.path)
84
+ if (status === 'STALE') stale++
85
+ process.stdout.write(`${c.key}\t${c.label}\t${status}\t${detail}\n`)
86
+ }
87
+ if (stale) {
88
+ process.stdout.write(
89
+ `\nSTALE ≠ 文件坏了:卷宗里还留着下架前的指令原文。` +
90
+ `它们既不注入也不进评测语料;清掉用 \`fg case rm <序号>\` 逐条删,或删 \`.focus-guard/workspace.json\` 让下次落账重建。\n`,
91
+ )
66
92
  }
67
- process.exitCode = bad ? 1 : 0
93
+ process.exitCode = bad ? 1 : stale ? 2 : 0