focus-guard 3.5.3 → 3.5.4

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 (84) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +1 -1
  3. package/assets/NOTICE.md +1 -1
  4. package/docs/ARCH-MAP.md +298 -83
  5. package/docs/BENCH.md +10 -4
  6. package/docs/RELEASE-POLICY.md +25 -12
  7. package/docs/RULES.md +34 -16
  8. package/docs/THREAT-MODEL.md +3 -3
  9. package/docs/WRITING-STYLE.md +40 -2
  10. package/package.json +1 -1
  11. package/skills/focus-rules/SKILL.md +9 -9
  12. package/skills/focus-thinking/SKILL.md +3 -3
  13. package/src/adapters/dsh/eligibility-gate.mjs +32 -12
  14. package/src/{dsh → adapters/dsh}/toolName.mjs +6 -0
  15. package/src/core/auditActions.mjs +214 -0
  16. package/src/core/checkEligibility.mjs +3 -1
  17. package/src/core/constants.mjs +8 -4
  18. package/src/core/env.mjs +21 -4
  19. package/src/core/profileLoader.mjs +96 -3
  20. package/src/core/scratch.mjs +288 -0
  21. package/src/core/state.mjs +3 -3
  22. package/src/dsh/audit.mjs +24 -163
  23. package/src/dsh/cost-ledger.mjs +174 -0
  24. package/src/dsh/guard/authz.mjs +1 -1
  25. package/src/dsh/guard/evidence.mjs +19 -0
  26. package/src/dsh/guard/tooling.mjs +15 -4
  27. package/src/dsh/{value-gate.mjs → guard/value-gate.mjs} +6 -0
  28. package/src/dsh/index.js +1 -1
  29. package/src/dsh/pipeline.mjs +6 -3
  30. package/src/dsh/postProgress.mjs +81 -40
  31. package/src/dsh/preGuard.mjs +1 -1
  32. package/src/dsh/seams/pre-step.mjs +74 -23
  33. package/src/dsh/seams/prompt-rules.mjs +91 -5
  34. package/src/dsh/{guard → seams}/runtime.mjs +12 -6
  35. package/src/dsh/seams/session-start.mjs +14 -0
  36. package/src/dsh/tools.mjs +1 -1
  37. package/src/memory/index.mjs +3 -1
  38. package/src/profiles/deepseek-flash.mjs +10 -8
  39. package/src/profiles/deepseek-pro.mjs +9 -8
  40. package/src/profiles/default.mjs +14 -8
  41. package/src/profiles/glm.mjs +9 -8
  42. package/src/profiles/gpt-astra.mjs +11 -9
  43. package/tools/audit-chain.mjs +29 -4
  44. package/tools/docs-drift.mjs +7 -29
  45. package/tools/docs-lint.mjs +54 -11
  46. package/tools/docs-refs.mjs +343 -0
  47. package/tools/handoff.mjs +1 -1
  48. package/tools/index-stale.mjs +124 -0
  49. package/tools/knowledge.mjs +53 -4
  50. package/tools/lib/book-style.mjs +42 -1
  51. package/tools/lib/case-tool.mjs +1 -1
  52. package/tools/lib/cli.mjs +35 -0
  53. package/tools/lib/docs-ack.mjs +4 -2
  54. package/tools/lib/docs-core.mjs +46 -23
  55. package/tools/lib/docs-scope.mjs +46 -0
  56. package/tools/lib/docs-status.mjs +8 -3
  57. package/tools/lib/docs-typography.mjs +91 -0
  58. package/tools/lib/docs-version.mjs +8 -5
  59. package/tools/lib/dup-block.mjs +117 -0
  60. package/tools/lib/index-io.mjs +4 -4
  61. package/tools/lib/index-registry.mjs +101 -0
  62. package/tools/lib/modules-doc.mjs +8 -1
  63. package/tools/lib/modules-list.mjs +22 -8
  64. package/tools/lib/modules.mjs +57 -9
  65. package/tools/lib/mutation-ops.mjs +63 -0
  66. package/tools/lib/parse-block.mjs +58 -0
  67. package/tools/lib/ratchet.mjs +22 -8
  68. package/tools/lib/release-faces.mjs +144 -0
  69. package/tools/lib/repo-copy.mjs +34 -0
  70. package/tools/lib/survey-report.mjs +57 -0
  71. package/tools/lib/where.mjs +139 -0
  72. package/tools/library-build.mjs +15 -3
  73. package/tools/lint.mjs +19 -13
  74. package/tools/log-audit.mjs +76 -0
  75. package/tools/memory-distill.mjs +14 -1
  76. package/tools/modules-audit.mjs +11 -9
  77. package/tools/mutate.mjs +120 -74
  78. package/tools/prefix-drift.mjs +1 -1
  79. package/tools/registry-check.mjs +16 -10
  80. package/tools/release.mjs +54 -106
  81. package/tools/smells.mjs +97 -139
  82. package/src/core/staleCleanup.mjs +0 -224
  83. package/src/dsh/workspace.mjs +0 -5
  84. package/tools/library-index.mjs +0 -91
@@ -80,6 +80,7 @@ export const MODULES = [
80
80
  'packages/core/src/dsh/guard/hardCheck.mjs',
81
81
  'packages/core/src/dsh/guard/writing-gate.mjs',
82
82
  'packages/core/src/dsh/guard/retryGuard.mjs',
83
+ 'packages/core/src/dsh/guard/value-gate.mjs',
83
84
  ],
84
85
  },
85
86
  {
@@ -92,7 +93,7 @@ export const MODULES = [
92
93
  id: 'evidence',
93
94
  name: '取证与闸运行时',
94
95
  note: '拦之前先把证据抓实,以及闸的加载、版本、注册',
95
- paths: ['packages/core/src/dsh/guard/evidence.mjs', 'packages/core/src/dsh/guard/runtime.mjs'],
96
+ paths: ['packages/core/src/dsh/guard/evidence.mjs'],
96
97
  },
97
98
  {
98
99
  id: 'audit',
@@ -101,7 +102,9 @@ export const MODULES = [
101
102
  paths: [
102
103
  'packages/core/src/core/audit-writer.mjs',
103
104
  'packages/core/src/core/audit.mjs',
105
+ 'packages/core/src/core/auditActions.mjs',
104
106
  'packages/core/src/dsh/audit.mjs',
107
+ 'packages/core/src/dsh/cost-ledger.mjs',
105
108
  'packages/core/src/dsh/policy-audit.mjs',
106
109
  'packages/core/tools/lib/case-tool.mjs',
107
110
  'packages/core/tools/case-audit.mjs',
@@ -151,7 +154,6 @@ export const MODULES = [
151
154
  paths: [
152
155
  'packages/core/src/memory',
153
156
  'packages/core/src/core/sessionScratch.mjs',
154
- 'packages/core/src/dsh/workspace.mjs',
155
157
  'packages/core/tools/memory-audit.mjs',
156
158
  'packages/core/tools/memory-distill.mjs',
157
159
  'packages/core/tools/memory-recall-eval.mjs',
@@ -161,7 +163,7 @@ export const MODULES = [
161
163
  id: 'cleanup',
162
164
  name: '清理与备份',
163
165
  note: '陈旧产物清理、备份、首跑清扫——不显眼,脏了才发现',
164
- paths: ['packages/core/src/core/staleCleanup.mjs', 'packages/core/src/core/backup.mjs', 'packages/core/tools/first-run-sweep.mjs'],
166
+ paths: ['packages/core/src/core/scratch.mjs', 'packages/core/src/core/backup.mjs', 'packages/core/tools/first-run-sweep.mjs'],
165
167
  },
166
168
  {
167
169
  id: 'prefix',
@@ -202,12 +204,11 @@ export const MODULES = [
202
204
  {
203
205
  id: 'guards',
204
206
  name: '守卫入口',
205
- note: 'pre / stop / repeat 三道入口守卫与价值判定',
207
+ note: 'pre / stop / repeat 三道入口守卫:自注册监听器、活在流水线段之外',
206
208
  paths: [
207
209
  'packages/core/src/dsh/preGuard.mjs',
208
210
  'packages/core/src/dsh/stopGuard.mjs',
209
211
  'packages/core/src/dsh/repeatGuard.mjs',
210
- 'packages/core/src/dsh/value-gate.mjs',
211
212
  ],
212
213
  },
213
214
  {
@@ -228,7 +229,7 @@ export const MODULES = [
228
229
  id: 'adapters',
229
230
  name: '适配层(工具面)',
230
231
  note: '宿主工具名/参数 → 母版语义的翻译;宿主改名先炸这里',
231
- paths: ['packages/core/src/adapters/dsh/tool-kinds.mjs', 'packages/core/src/dsh/toolName.mjs'],
232
+ paths: ['packages/core/src/adapters/dsh/tool-kinds.mjs', 'packages/core/src/adapters/dsh/toolName.mjs'],
232
233
  },
233
234
  {
234
235
  id: 'brain',
@@ -268,13 +269,19 @@ export const MODULES = [
268
269
  {
269
270
  id: 'selfcheck',
270
271
  name: '自检与变异',
271
- note: '尺子本身:lint / 退役惯用法 / smells / selftest / mutate / 指纹 / 结构图',
272
+ note: '尺子本身:lint / 退役惯用法 / smells / selftest / mutate / 指纹 / 结构图 / 报点定位 / 入口事实',
272
273
  paths: [
273
274
  'packages/core/tools/lint.mjs',
274
275
  'packages/core/tools/lib/idioms.mjs',
276
+ 'packages/core/tools/lib/where.mjs',
277
+ 'packages/core/tools/lib/cli.mjs',
278
+ 'packages/core/tools/lib/dup-block.mjs',
275
279
  'packages/core/tools/smells.mjs',
276
280
  'packages/core/tools/selftest.mjs',
277
281
  'packages/core/tools/mutate.mjs',
282
+ 'packages/core/tools/lib/mutation-ops.mjs',
283
+ 'packages/core/tools/lib/repo-copy.mjs',
284
+ 'packages/core/tools/lib/survey-report.mjs',
278
285
  'packages/core/tools/health.mjs',
279
286
  'packages/core/tools/quality-audit.mjs',
280
287
  'packages/core/tools/capture-fixtures.mjs',
@@ -317,20 +324,25 @@ export const MODULES = [
317
324
  paths: [
318
325
  'packages/core/tools/docs-lint.mjs',
319
326
  'packages/core/tools/docs-drift.mjs',
327
+ 'packages/core/tools/docs-refs.mjs',
320
328
  'packages/core/tools/legacy-audit.mjs',
321
329
  'packages/core/tools/lib/legacy-core.mjs',
322
330
  'packages/core/tools/docs-book.mjs',
323
331
  'packages/core/tools/lib/docs-core.mjs',
332
+ 'packages/core/tools/lib/docs-scope.mjs',
324
333
  'packages/core/tools/lib/docs-files.mjs',
325
334
  'packages/core/tools/lib/docs-status.mjs',
326
335
  'packages/core/tools/lib/docs-version.mjs',
327
336
  'packages/core/tools/lib/docs-ack.mjs',
337
+ 'packages/core/tools/lib/docs-typography.mjs',
328
338
  'packages/core/tools/lib/markdown.mjs',
329
339
  'packages/core/tools/lib/book-style.mjs',
330
340
  'packages/core/tools/library-build.mjs',
331
- 'packages/core/tools/library-index.mjs',
341
+ 'packages/core/tools/lib/parse-block.mjs',
332
342
  'packages/core/tools/library-book.mjs',
333
343
  'packages/core/tools/knowledge.mjs',
344
+ 'packages/core/tools/lib/index-registry.mjs',
345
+ 'packages/core/tools/index-stale.mjs',
334
346
  'packages/core/tools/lib/open.mjs',
335
347
  ],
336
348
  },
@@ -357,6 +369,8 @@ export const MODULES = [
357
369
  'packages/core/tools/release.mjs',
358
370
  // 发布确认:与 release.mjs 同一件事的两端(发出去 / 发成功没),放一起才会一起变。
359
371
  'packages/core/tools/registry-check.mjs',
372
+ // 产物面四真值(tag / Release / registry / workflow):从 release.mjs 拆出,同一件事。
373
+ 'packages/core/tools/lib/release-faces.mjs',
360
374
  'packages/core/tools/focusguard.mjs',
361
375
  'packages/core/src/dsh/cordis.patch.yml',
362
376
  ],
@@ -3,6 +3,7 @@ import { existsSync, readFileSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import { MODULES, META_FILES } from './modules-list.mjs'
5
5
  import { MODULES_DOC, renderModules } from './modules-doc.mjs'
6
+ import { lineOf, linesOf } from './where.mjs'
6
7
 
7
8
  // 渲染器住在 modules-doc.mjs,清单住在 modules-list.mjs,这里只管「怎么算」。
8
9
  export { MODULES, META_FILES, MODULES_DOC, renderModules }
@@ -52,6 +53,50 @@ export { MODULES, META_FILES, MODULES_DOC, renderModules }
52
53
  /** 等级由高到低。排序用它,`无法定位` 排最前——路径在 git 里找不到任何提交,本身就要看。 */
53
54
  export const LEVEL_RANK = { 无法定位: 4, 久未动: 3, 临期: 2, 偏冷: 1, 活跃: 0 }
54
55
 
56
+ /**
57
+ * 病灶位置:`modules-*` 的每一类错都出在这份清单里,所以报点必须指到清单的某一行。
58
+ *
59
+ * 此前这里写的是 `line: 1`——那不是"位置",是"文件第一行"。一条命令跳到文件开头,
60
+ * 然后你还得自己在 350 行里找那个 id,等于没有定位。
61
+ * 现按病灶类型分别取真行号:id 重复取**第二次**出现的 `id:`,路径重叠取**后登记**的那条字面量。
62
+ */
63
+ export const LIST_FILE = 'packages/core/tools/lib/modules-list.mjs'
64
+
65
+ /** 一次运行里清单会被四道判据各读一遍,缓存按 repo 分桶(测试会指到夹具目录)。 */
66
+ const listCache = new Map()
67
+ function listSource(repo) {
68
+ if (!listCache.has(repo)) {
69
+ let text = ''
70
+ try {
71
+ text = readFileSync(join(repo, LIST_FILE), 'utf8')
72
+ } catch {
73
+ text = ''
74
+ }
75
+ listCache.set(repo, text)
76
+ }
77
+ return listCache.get(repo)
78
+ }
79
+
80
+ /** `id: 'xxx'` 的行号;`nth` 取第几次出现(重复 id 要报后来那条)。 */
81
+ function idLine(repo, id, nth = 0) {
82
+ const hits = linesOf(listSource(repo), new RegExp(`id:\\s*['"]${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`))
83
+ return hits.length ? hits[Math.min(nth, hits.length - 1)] : 0
84
+ }
85
+
86
+ /** 路径字面量的行号;`nth` 取第几次出现(重叠要报后登记的那张)。 */
87
+ function pathLine(repo, p, nth = 0) {
88
+ for (const q of [`'${p}'`, `"${p}"`]) {
89
+ const hits = linesOf(listSource(repo), q)
90
+ if (hits.length) return hits[Math.min(nth, hits.length - 1)]
91
+ }
92
+ return 0
93
+ }
94
+
95
+ /** 数组声明行:有文件谁都不认领时,病灶就是"这里少了一条",指回清单开头是对的。 */
96
+ function modulesHeadLine(repo) {
97
+ return lineOf(listSource(repo), /export const MODULES\s*=\s*\[/)
98
+ }
99
+
55
100
  /**
56
101
  * 阈值:**中位文件「其后全仓提交」的次数**。
57
102
  *
@@ -230,7 +275,7 @@ export function checkModulePaths(repo, modules = MODULES) {
230
275
  for (const p of m.paths) {
231
276
  if (EXCLUDE.test(p)) continue // 排除项不是路径,别拿它去 existsSync
232
277
  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}` })
278
+ findings.push({ rule: 'modules-path-missing', file: LIST_FILE, line: pathLine(repo, p), detail: `${m.id} 的路径不存在:${p}` })
234
279
  }
235
280
  }
236
281
  }
@@ -238,12 +283,12 @@ export function checkModulePaths(repo, modules = MODULES) {
238
283
  }
239
284
 
240
285
  /** 判据②:模块 `id` 不许重复——重复会让 `--json` 的消费方拿到两条同 id 的记录。 */
241
- export function checkModuleIds(modules = MODULES) {
286
+ export function checkModuleIds(repo, modules = MODULES) {
242
287
  const seen = new Map()
243
288
  const findings = []
244
289
  for (const m of modules) {
245
290
  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})` })
291
+ findings.push({ rule: 'modules-id-duplicate', file: LIST_FILE, line: idLine(repo, m.id, 1), detail: `id \`${m.id}\` 重复(${seen.get(m.id)} 与 ${m.name})` })
247
292
  } else {
248
293
  seen.set(m.id, m.name)
249
294
  }
@@ -265,7 +310,7 @@ export function checkModuleOverlap(repo, modules = MODULES) {
265
310
  for (const f of tracked) {
266
311
  if (!matches(m.paths, f)) continue
267
312
  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}` })
313
+ findings.push({ rule: 'modules-path-overlap', file: LIST_FILE, line: pathLine(repo, f, 1), detail: `${f} 同时属于 ${owner.get(f)} 与 ${m.id}` })
269
314
  } else {
270
315
  owner.set(f, m.id)
271
316
  }
@@ -281,8 +326,8 @@ export function checkModuleCoverage(repo, modules = MODULES) {
281
326
  return [
282
327
  {
283
328
  rule: 'modules-unowned-path',
284
- file: 'packages/core/tools/lib/modules-list.mjs',
285
- line: 1,
329
+ file: LIST_FILE,
330
+ line: modulesHeadLine(repo),
286
331
  detail: `${unowned} 个文件不属于任何模块:${sample.join('、')}${unowned > sample.length ? ' 等' : ''}`,
287
332
  },
288
333
  ]
@@ -301,12 +346,15 @@ export function checkModulesDoc(repo) {
301
346
  try {
302
347
  got = readFileSync(join(repo, MODULES_DOC), 'utf8')
303
348
  } catch {
304
- return [{ rule: 'modules-doc-stale', file: MODULES_DOC, line: 1, detail: '台账不存在,跑 `npm run modules:sync` 生成' }]
349
+ // 文件都不存在,没有行号可给——`line: 0` 会被渲染成只有文件名,不会退化成"第 1 行"。
350
+ return [{ rule: 'modules-doc-stale', file: MODULES_DOC, line: 0, detail: '台账不存在,跑 `npm run modules:sync` 生成' }]
305
351
  }
306
352
  // 只比结构指纹,不比逐字:表里全是会随「现在」变的量,逐字比对会让开发中途的 check 无故变红。
307
- const keyOf = (t) => (t.match(/<!-- modules-key[^\n]*\n([\s\S]*?)\n-->/) || [, ''])[1]
353
+ // **换行先归一**:Windows runner 检出时 `core.autocrlf` 会把 LF 变 CRLF,而 `renderModules` 现算的是 LF——
354
+ // 指纹里混进一个 `\r` 就整块不等,2026-11-30 的发布闸正是这么红的(本地绿、CI 红,同一条判据两份答案)。
355
+ const keyOf = (t) => (t.replace(/\r\n/g, '\n').match(/<!-- modules-key[^\n]*\n([\s\S]*?)\n-->/) || [, ''])[1]
308
356
  if (keyOf(got) !== keyOf(want)) {
309
- return [{ rule: 'modules-doc-stale', file: MODULES_DOC, line: 1, detail: '台账与模块清单不一致(清单改了没重生成),跑 `npm run modules:sync`' }]
357
+ return [{ rule: 'modules-doc-stale', file: MODULES_DOC, line: lineOf(got, '<!-- modules-key'), detail: '台账与模块清单不一致(清单改了没重生成),跑 `npm run modules:sync`' }]
310
358
  }
311
359
  return []
312
360
  }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * 变异算子与生成/应用(2026-11-27,3.5.4 从 tools/mutate.mjs 抽出)。
3
+ *
4
+ * 抽出的理由:`tools/mutate.mjs` 到 484 行,撞上结构异味阈值 400。
5
+ * 而这一段的边界是干净的——**纯函数,只依赖 `stripLiterals`**,不碰文件系统、不碰进程。
6
+ * 编排(副本、跑测试、报分)留在 mutate.mjs,算子在这里。
7
+ */
8
+ import { stripLiterals } from './source-text.mjs'
9
+
10
+ /**
11
+ * 变异算子。每个算子:正则 + 替换规则。
12
+ *
13
+ * 全部作用在 `stripLiterals` 之后的文本上——否则 `'== 分布 =='` 这种字符串里的运算符
14
+ * 会被当成代码变异,跑出来的"存活"全是假的。去字面量保留长度与换行,
15
+ * 所以 `plain` 里的下标可以直接映射回原文件(下面有长度断言兜底)。
16
+ */
17
+ const OPERATORS = [
18
+ { id: 'comparison', re: /(?<![<>=!])(<=|>=|<|>)(?![=<>])/g, flip: { '<': '<=', '<=': '<', '>': '>=', '>=': '>' } },
19
+ { id: 'equality', re: /(?<![=!<>])(===|!==)(?!=)/g, flip: { '===': '!==', '!==': '===' } },
20
+ { id: 'boolean', re: /(?<![\w$.])(&&|\|\|)(?![\w$])/g, flip: { '&&': '||', '||': '&&' } },
21
+ { id: 'literal-bool', re: /(?<![\w$.])(true|false)(?![\w$])/g, flip: { true: 'false', false: 'true' } },
22
+ { id: 'nullish', re: /(?<![\w$.])\?\?(?![\w$])/g, flip: { '??': '||' } },
23
+ // 去掉一个 `!`:`if (!reason)` → `if (reason)`。闸门类代码里这条最能暴露"没人断言"。
24
+ // 捕获组不能省:`m[1]` 取的是 token,没有捕获组时是 undefined,整条算子会**静默失效**
25
+ // (这个 bug 是 `mutate.test.mjs` 抓出来的——自己写的算子也会犯"看起来跑了"的错)。
26
+ { id: 'negation', re: /(?<![!=<>])(!)(?!=)/g, flip: { '!': '' } },
27
+ ]
28
+
29
+ /** 生成变异体:{ op, index, token, replacement, line } */
30
+ export function generateMutants(src) {
31
+ const plain = stripLiterals(src)
32
+ if (plain.length !== src.length) {
33
+ throw new Error(`stripLiterals 改变了长度(${src.length} → ${plain.length}),下标无法映射,拒绝变异`)
34
+ }
35
+ const lineStarts = [0]
36
+ for (let i = 0; i < src.length; i += 1) if (src[i] === '\n') lineStarts.push(i + 1)
37
+ const lineOf = (idx) => {
38
+ let lo = 0
39
+ let hi = lineStarts.length - 1
40
+ while (lo < hi) {
41
+ const mid = (lo + hi + 1) >> 1
42
+ if (lineStarts[mid] <= idx) lo = mid
43
+ else hi = mid - 1
44
+ }
45
+ return lo + 1
46
+ }
47
+
48
+ const out = []
49
+ for (const op of OPERATORS) {
50
+ for (const m of plain.matchAll(op.re)) {
51
+ const token = m[1]
52
+ const replacement = op.flip[token]
53
+ if (replacement === undefined) continue
54
+ out.push({ op: op.id, index: m.index, token, replacement, line: lineOf(m.index) })
55
+ }
56
+ }
57
+ return out.sort((a, b) => a.index - b.index)
58
+ }
59
+
60
+ /** 把第 i 个变异体应用到源码上,返回新源码。 */
61
+ export function applyMutant(src, mutant) {
62
+ return src.slice(0, mutant.index) + mutant.replacement + src.slice(mutant.index + mutant.token.length)
63
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * 积木文件名解析(tools/lib/parse-block.mjs,2026-10-31 建,2026-11-29 降级)
3
+ *
4
+ * 这是**纯函数库**,不写盘、不产索引。调用方只有 `knowledge.mjs`。
5
+ *
6
+ * ## 为什么从「索引工具」降成「解析库」
7
+ *
8
+ * 原文件(`tools/library-index.mjs`)会扫 `.ai/output/library` 落一份 `index.json`。
9
+ * 2026-11-29 实测:`knowledge.json` 里 `block:*` 条目的字段是
10
+ * `{ ns, id, file, grade, topic, source, chars, path }`,而 `index.json` 的条目是
11
+ * `{ id, file, grade, topic, source, chars }`——**知识索引是它的严格超集**,
12
+ * 后者不再被任何代码读取。
13
+ *
14
+ * 而 `library-index.mjs` 的首版注释里自己写着:「两套索引源 = 两个真相源,那是 3.3 修过的病」。
15
+ * 它防住了「内容索引 vs 文件名索引」,却没防住自己与 `knowledge` 撞车——因为两个工具
16
+ * 扫的是同一个目录。所以不是再抽一层,是把其中一个的职责收窄到它唯一还被需要的那一半:
17
+ * `parseBlock`——`knowledge` 复用它的解析,不另写一套。
18
+ *
19
+ * 目录 `INDEX.md`(人读的清单)仍由 `library-build.mjs` 生成,与本文件无关。
20
+ *
21
+ * ## 命名规律(实测 28 块)
22
+ *
23
+ * B001-s-级-改改措辞就能进-rules-注入前缀.md 分级结论:s/a/b 级
24
+ * B006-核心机制-anthropic.md 主题 + 来源
25
+ *
26
+ * 认不出的写法不猜:整段原样进 `topic`,`grade`/`source` 留 null。
27
+ */
28
+
29
+ const SOURCES = ['anthropic', 'google', 'misc', 'openai', 'others', 'xai']
30
+
31
+ /**
32
+ * 「什么算一块积木」:`B001-….md`。
33
+ *
34
+ * `knowledge.mjs` 的源过滤与 `lib/index-registry.mjs` 的落后检查都用这一条,
35
+ * 不各写一份——2026-11-29 之前那里是 `/^B\d{3}-.+\.md$/` 的副本,
36
+ * 改命名规则时必有一处漏改。
37
+ */
38
+ export const BLOCK_RE = /^B(\d{3})-(.+)\.md$/
39
+
40
+ /** 文件名 → 索引项。认不出的一律不猜,整段当 topic。 */
41
+ export function parseBlock(file, chars) {
42
+ const m = BLOCK_RE.exec(file)
43
+ if (!m) return null
44
+ const [, num, rest] = m
45
+ const item = { id: `B${num}`, file, grade: null, topic: rest, source: null, chars }
46
+ const graded = /^([sab])-级-(.+)$/.exec(rest)
47
+ if (graded) {
48
+ item.grade = graded[1]
49
+ item.topic = graded[2]
50
+ return item
51
+ }
52
+ const tail = new RegExp(`^(.+)-(${SOURCES.join('|')})$`).exec(rest)
53
+ if (tail) {
54
+ item.topic = tail[1]
55
+ item.source = tail[2]
56
+ }
57
+ return item
58
+ }
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs'
2
2
  import { execFileSync } from 'node:child_process'
3
3
  import { join } from 'node:path'
4
+ import { lineOf } from './where.mjs'
4
5
 
5
6
  /**
6
7
  * 存量棘轮台账(3.3 B,2026-10-30)
@@ -19,9 +20,9 @@ import { join } from 'node:path'
19
20
  * ① 实测 ≤ 本版记账值 —— 防反弹(台账写完又被改坏)
20
21
  * ② 本版总和 < 上一版总和 —— 每版至少还 1 条
21
22
  * ③ 首版免 ② —— 总得有个起点
22
- * ④ 自上次记账起 ≥10 次提交仍未降 —— 还款期限(2026-10-30 人类要求:
23
- * 「每 N 次提交必须降 1」。按版本记账的问题是:版本可以很久不发,
24
- * 于是 8/8 能一直挂着不动。改成按提交数催,才管得住「不发版就不还债」)
23
+ * ④ 自上次记账起 ≥10 次提交仍未降 —— 还款期限(2026-10-30 定:每 N 次提交必须降 1)。
24
+ * 按版本记账的问题是:版本可以很久不发,于是 8/8 能一直挂着不动。
25
+ * 改成按提交数催,才管得住「不发版就不还债」。
25
26
  *
26
27
  * ## 为什么不塞进 smells.mjs
27
28
  *
@@ -32,6 +33,9 @@ import { join } from 'node:path'
32
33
  /** 还款期限:自上次记账 commit 起,多少提交内必须还 1 条 */
33
34
  export const COMMITS_PER_PAYBACK = 10
34
35
 
36
+ /** 台账文件(报点用):四条规则红的时候,人要改的都是这张表里的某一行。 */
37
+ export const LEDGER_FILE = 'packages/core/docs/RATCHET.json'
38
+
35
39
  /**
36
40
  * 自某 commit 起的提交数。取不到就返回 null(浅克隆 / 非 git 仓库 / 无该 sha)。
37
41
  * 返回 null 时规则④跳过——**缺数据允许粗判,但必须在输出里写明**,不能假装查过。
@@ -147,26 +151,36 @@ export function paybackNote(check) {
147
151
  */
148
152
  export function loadRatchet(repo, actual) {
149
153
  const pkgPath = join(repo, 'package.json')
150
- const ledgerPath = join(repo, 'packages/core/docs/RATCHET.json')
154
+ const ledgerPath = join(repo, LEDGER_FILE)
151
155
  if (!existsSync(pkgPath)) return { findings: [], entry: null, total: null, skipped: '无 package.json(夹具仓库)' }
152
156
  if (!existsSync(ledgerPath)) {
153
- return { findings: [{ rule: 'no-ledger', detail: '台账 RATCHET.json 缺失' }], entry: null, total: null }
157
+ return { findings: [{ rule: 'no-ledger', file: LEDGER_FILE, line: 0, detail: '台账 RATCHET.json 缺失' }], entry: null, total: null }
154
158
  }
155
159
  try {
156
160
  const version = JSON.parse(readFileSync(pkgPath, 'utf8')).version
157
- const ledger = JSON.parse(readFileSync(ledgerPath, 'utf8'))
161
+ const text = readFileSync(ledgerPath, 'utf8')
162
+ const ledger = JSON.parse(text)
158
163
  const history = Array.isArray(ledger.history) ? ledger.history : []
159
164
  const last = history.length ? history[history.length - 1] : null
160
165
  const n = commitsSince(repo, last && last.commit)
166
+ const result = checkRatchet(ledger, version, actual, { commitsSinceLast: n })
167
+ // 报点:红的是「本版那一行」还是「整张表缺一条」——前者能直接跳过去改数字,后者只能指回 history 开头。
168
+ // checkRatchet 本身保持纯函数(测试直接喂对象),定位只在这一层做。
169
+ const versionLine = lineOf(text, `"version": "${version}"`)
170
+ const historyLine = lineOf(text, '"history"')
171
+ for (const f of result.findings) {
172
+ f.file = LEDGER_FILE
173
+ f.line = f.rule === 'no-ledger-entry' ? historyLine : versionLine || historyLine
174
+ }
161
175
  return {
162
- ...checkRatchet(ledger, version, actual, { commitsSinceLast: n }),
176
+ ...result,
163
177
  version,
164
178
  // 取不到提交数时明说「只能粗判」——假装精确比承认不确定更糟
165
179
  commitsKnown: n !== null,
166
180
  }
167
181
  } catch (error) {
168
182
  return {
169
- findings: [{ rule: 'ledger-unreadable', detail: String(error && error.message) }],
183
+ findings: [{ rule: 'ledger-unreadable', file: LEDGER_FILE, line: 0, detail: String(error && error.message) }],
170
184
  entry: null,
171
185
  total: null,
172
186
  }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * 产物面:`npm run release:status` 要问的四个独立真值。
3
+ *
4
+ * 为什么单列一个文件:这四面的探测各有各的坑(gh 的字段名、jq 输出为空、一次发布横跨多个运行),
5
+ * 注释比代码长,塞在 `release.mjs` 里把它顶到 402 行、越了 400 的行数阈值。
6
+ * 按仓库规矩**只许拆不许抬**,于是拆出来。
7
+ *
8
+ * 从 `release.mjs` 拆出的原因记录在 CHANGELOG(`refactor(tools)`),这里只保留机制说明。
9
+ */
10
+
11
+ import { execFileSync } from 'node:child_process'
12
+ import { readFileSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+ import { probeVersion, registryBase } from '../registry-check.mjs'
15
+
16
+ const git = (root, args) => (execFileSync('git', args, { cwd: root, encoding: 'utf8' }) || '').trim()
17
+
18
+ /** 包名:探 registry 用,与版本同源(`packages/core/package.json`)。 */
19
+ export function packageName(root) {
20
+ return JSON.parse(readFileSync(join(root, 'packages/core/package.json'), 'utf8')).name
21
+ }
22
+
23
+ /**
24
+ * 最近一次 publish 运行;没装 gh / 未登录 / 从没跑过都返回 null。
25
+ *
26
+ * 2026-11-26 修两处,都是「认领哪一次运行」的坑:
27
+ * 1. `gh workflow run --ref main` 手动补发时 displayTitle 只有「publish」、headBranch 是 main,
28
+ * 按 tag 名怎么都认不出来——旧实现于是退到上一次历史运行,`--status` 永远指着那条失败报红。
29
+ * 2. 一次版本发布可能横跨多个 run(先跑失败 → 重跑成功 → 补 Release 又一条),
30
+ * 按 tag 名 `find` 拿到的是**最早**那条。现在取时间最新的一条,另给 `related` 标明它是否与
31
+ * 这个 tag 精确对应;不对应就只是线索,不当判据。
32
+ */
33
+ export function publishRun(root, tag, sinceMs = 0, commit = null) {
34
+ try {
35
+ const out = execFileSync('gh', ['run', 'list', '--workflow=publish.yml', '--limit', '20', '--json', 'displayTitle,headBranch,headSha,status,conclusion,url,createdAt'], {
36
+ cwd: root,
37
+ encoding: 'utf8',
38
+ })
39
+ // gh 按时间倒序;`sinceMs` 用来排除同一 tag 的历史运行(失败重跑时最容易被误当成「刚触发的」)。
40
+ const fresh = (r) => !sinceMs || Date.now() - new Date(r.createdAt).getTime() <= sinceMs
41
+ const runs = JSON.parse(out).filter(fresh)
42
+ const latest = runs[0]
43
+ if (!latest) return null
44
+ const related = (r) => (r.displayTitle || '').includes(tag) || r.headBranch === tag || Boolean(commit && r.headSha === commit)
45
+ return { ...latest, related: related(latest), everRelated: runs.some(related) }
46
+ } catch {
47
+ return null
48
+ }
49
+ }
50
+
51
+ /** tag 的本地 / 远端 / Release / 是否 Latest 四个值,各自独立取,缺哪个说哪个。 */
52
+ export function githubFace(root, tag) {
53
+ const tryGit = (args) => {
54
+ try {
55
+ return git(root, args)
56
+ } catch {
57
+ return null
58
+ }
59
+ }
60
+ const head = tryGit(['rev-parse', 'HEAD'])
61
+ const local = tryGit(['rev-parse', `refs/tags/${tag}`])
62
+ const commit = tryGit(['rev-parse', `refs/tags/${tag}^{commit}`])
63
+ const remote = (() => {
64
+ const all = tryGit(['ls-remote', '--tags', 'origin'])
65
+ if (!all) return null
66
+ const line = all.split('\n').find((l) => l.endsWith(`refs/tags/${tag}`))
67
+ return line ? line.split(/\s+/)[0] : null
68
+ })()
69
+ let release = null
70
+ try {
71
+ // 不用 `--json isLatest`:gh 的字段随版本增减,2.6x 上根本没有它(实测报 Unknown JSON field)。
72
+ // 「是不是 Latest」另走一个权威口:`releases/latest`,那是 GitHub 自己认的那一个。
73
+ release = JSON.parse(execFileSync('gh', ['release', 'view', tag, '--json', 'tagName,createdAt,isDraft,isPrerelease'], { cwd: root, encoding: 'utf8' }))
74
+ // `gh api` 返回的是**原始** API 字段(snake_case),与 `gh release view --json` 的驼峰不同;
75
+ // 且本机 gh 的 `--jq` 输出为空(实测只有换行),所以自己解析、认 `tag_name`。
76
+ const latest = JSON.parse(execFileSync('gh', ['api', 'repos/{owner}/{repo}/releases/latest'], { cwd: root, encoding: 'utf8' }))
77
+ release.isLatest = latest?.tag_name === tag
78
+ } catch {
79
+ release = null
80
+ }
81
+ return { head, local, commit, remote, atHead: Boolean(commit && head && commit === head), release }
82
+ }
83
+
84
+ const mark = (ok) => (ok ? '✅' : '❌')
85
+
86
+ /**
87
+ * 四个真值各取一次,返回可直接打印的行与结论。
88
+ * 结论只看 **tag / Release / registry** 三面——workflow 面只作线索(它能红在发布之后的确认步骤上,
89
+ * 也可能一次发布横跨多个 run,拿它判红会每发一版留一条假红)。
90
+ */
91
+ export async function productStatus({ root, version, tag }) {
92
+ // 先把 registry 探测发出去(异步),再跑几个 execFileSync 的活——它们的等待正好被 fetch 用掉。
93
+ // `elapsed` 只算探测本身(从发出到拿回),不含被 gh 那几条命令占用的时间。
94
+ const t0 = Date.now()
95
+ const registryProbe = probeVersion(registryBase(), packageName(root), version)
96
+ .then((r) => ({ ...r, elapsed: Date.now() - t0 }))
97
+ .catch((err) => ({ state: 'error', detail: err.message, elapsed: Date.now() - t0 }))
98
+ const gh = githubFace(root, tag)
99
+ const run = publishRun(root, tag, 0, gh.commit)
100
+ const registry = await registryProbe
101
+ const published = registry.state === 'present'
102
+ // 「tag 合格」只要求**本地与远端是同一个对象**。是否指向 HEAD 单独说:
103
+ // 发完之后必然还要回填 README / `PUBLISHED_MAX` 那几处(政策 §四 第 8 步),
104
+ // 于是 tag 正常会落后 HEAD 一两个提交——把它算成 ❌,等于每发一版就留一条假红。
105
+ const tagOk = Boolean(gh.local && gh.remote && gh.local === gh.remote)
106
+ const lines = []
107
+ lines.push(` tag ${mark(tagOk)} ${tag}${tagOk ? '(本地=远端)' : ''}`)
108
+ if (!tagOk) {
109
+ if (!gh.local) lines.push(' 本地没有这个 tag')
110
+ else if (!gh.remote) lines.push(` 远端没有这个 tag——\`git push origin ${tag}\``)
111
+ else lines.push(' 远端与本地不是同一个对象——同版本不重打,先确认该保留哪个')
112
+ } else if (gh.commit && !gh.atHead) {
113
+ lines.push(` ℹ tag 指向 ${String(gh.commit).slice(0, 7)},HEAD 是 ${String(gh.head).slice(0, 7)}(发布后回填文档属正常)`)
114
+ }
115
+ lines.push(` Release ${mark(Boolean(gh.release))} ${gh.release ? `${gh.release.tagName}${gh.release.isLatest ? '(Latest)' : ''}` : '没有'}`)
116
+ lines.push(
117
+ ` registry ${mark(published)} ${
118
+ published ? `${version} 已发布(${(registry.elapsed / 1000).toFixed(1)}s 读到版本文档)` : registry.state === 'error' ? `查不了(${registry.detail})` : `未见 ${version}`
119
+ }`,
120
+ )
121
+ // workflow 面只作线索,不参与结论。理由:它能红在「发布之后」的确认步骤上(3.5.3 那次就是
122
+ // ——npm 已收下、Release 已建,红在 Verify 的判据),而一次版本发布又可能横跨多个 run
123
+ // (失败 → 重跑成功 → 补 Release)。所以这一行说清「哪条运行、跟这个 tag 对不对应」,
124
+ // 让结论由前三面给,不拿运行记录去覆盖产物事实。
125
+ let workflowLine
126
+ if (!run) workflowLine = ' workflow ℹ (没有 gh 或没跑过——跳过)'
127
+ else {
128
+ const state = run.status === 'completed' ? run.conclusion : run.status
129
+ const icon = run.status !== 'completed' ? '⏳' : 'ℹ'
130
+ const how = run.related ? '与 tag 精确对应' : run.everRelated ? '最新一条;同版本另有更早的运行' : '最新一条;与 tag 无对应关系'
131
+ workflowLine = ` workflow ${icon} ${state} · ${run.url}\n ${how}:${run.displayTitle || '(无标题)'} @ ${String(run.headSha || '').slice(0, 7)}`
132
+ }
133
+ lines.push(workflowLine)
134
+ let verdict
135
+ // 「查不了」与「没有」必须分开说。合并成一句「未发布」是最坏的一种——2026-11-26 本机一次
136
+ // 网络瞬断就让它报了「还没有 publish 运行」,而三面其实齐平。查不了不等于没发过。
137
+ if (published && gh.release && tagOk) verdict = '已发布:tag / Release / npm 三面齐平'
138
+ else if (published) verdict = 'npm 上有了,但 GitHub 面不齐——按上面 ❌ 补'
139
+ else if (registry.state === 'error') verdict = `查不了:registry 不可达(${registry.detail})——这不等于没发布,联网后重跑本命令`
140
+ else if (run && run.status !== 'completed') verdict = `发布中(${run.status}),不用守着:稍后重跑本命令`
141
+ else if (run && run.conclusion === 'failure') verdict = '未发布:工作流失败,先看日志再重跑'
142
+ else verdict = '未发布:还没有 publish 运行'
143
+ return { lines, verdict, published, tagOk }
144
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * 仓根副本(2026-11-27,3.5.4 从 tools/mutate.mjs 抽出)。
3
+ *
4
+ * 抽出的理由:mutate.mjs 撞 400 行阈值;这段只做「复制」,与变异逻辑无关。
5
+ */
6
+ import { cpSync, readdirSync } from "node:fs"
7
+ import { join } from "node:path"
8
+
9
+ /**
10
+ * 副本黑名单(2026-11-27,3.5.4)。
11
+ *
12
+ * 原先是白名单:只复制 `packages/` 与 `package.json`。代价是**每新增一个顶层目录就静默漏一次**。
13
+ * 测试一旦引用仓根的东西(`docs/` 下的法典、`CHANGELOG.md`、`.git` 历史),基线就红,
14
+ * 而红的原因只报「基线测试未通过」——看不出是副本缺文件。实测 `core/risk.mjs` 因此 30 条用例失败。
15
+ *
16
+ * 改黑名单:除下列目录外全复制。新增顶层目录自动进副本,不需要回来改这里。
17
+ * 排除的都是「本机状态」或「体积大且与判定无关」:`node_modules` 可由包自身解析,
18
+ * `.focus-guard` / `.ai` 是运行时会写的东西,复制进去只会让隔离测试互相污染。
19
+ */
20
+ const COPY_SKIP = new Set(['node_modules', '.focus-guard', '.ai', '.archify', 'coverage', 'dist', '.vs'])
21
+
22
+ /**
23
+ * 把仓根复制成临时副本。逐顶层条目复制而不是 `cpSync(REPO, work)`——
24
+ * 后者在目标目录已存在时的落点规则依赖实现细节,不如显式列出来得可靠。
25
+ *
26
+ * `repo` 可传:用例要拿一个受控夹具证明「新增顶层目录自动进副本」,
27
+ * 而模块级的 `REPO` 是常量,不参数化就只能去改真实仓库来测。**能指到别处才测得了。**
28
+ */
29
+ export function copyRepo(repo, dest) {
30
+ for (const entry of readdirSync(repo, { withFileTypes: true })) {
31
+ if (COPY_SKIP.has(entry.name)) continue
32
+ cpSync(join(repo, entry.name), join(dest, entry.name), { recursive: true })
33
+ }
34
+ }