dsh-sixlayer-memory 0.0.0-stage → 2.0.2

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 (91) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +286 -3
  3. package/catalog/.index.json +111704 -0
  4. package/catalog/parts.json +8808 -0
  5. package/cordis.patch.yml +8 -0
  6. package/docs/DETAIL.md +1 -0
  7. package/docs/DETAIL.zh.md +1 -0
  8. package/docs/preview.svg +51 -0
  9. package/docs//347/224/237/345/221/275/345/221/250/346/234/237-/350/207/252/345/212/250/345/217/254/345/233/236/344/270/216/345/200/231/351/200/211.md +103 -0
  10. package/icon.svg +8 -0
  11. package/lib/client.js +1209 -0
  12. package/lib/index.js +741 -0
  13. package/lib/memory/affect-alert.js +60 -0
  14. package/lib/memory/affect-events.js +201 -0
  15. package/lib/memory/affect-report.js +61 -0
  16. package/lib/memory/api.js +194 -0
  17. package/lib/memory/crypto.js +68 -0
  18. package/lib/memory/detail.js +43 -0
  19. package/lib/memory/embed.js +394 -0
  20. package/lib/memory/emotion.js +99 -0
  21. package/lib/memory/explain.js +207 -0
  22. package/lib/memory/importer.js +215 -0
  23. package/lib/memory/inject.js +193 -0
  24. package/lib/memory/ledger.js +101 -0
  25. package/lib/memory/lifecycle.js +491 -0
  26. package/lib/memory/notify.js +164 -0
  27. package/lib/memory/policy.js +182 -0
  28. package/lib/memory/qq-official.js +196 -0
  29. package/lib/memory/qq.js +326 -0
  30. package/lib/memory/recorder.js +241 -0
  31. package/lib/memory/redact.js +120 -0
  32. package/lib/memory/scanners.js +142 -0
  33. package/lib/memory/schema.js +205 -0
  34. package/lib/memory/service-plugin.js +69 -0
  35. package/lib/memory/service.js +123 -0
  36. package/lib/memory/shadow.js +133 -0
  37. package/lib/memory/store.js +1138 -0
  38. package/lib/memory/timeline.js +74 -0
  39. package/lib/memory/tokenize.js +66 -0
  40. package/lib/memory/tools.js +1371 -0
  41. package/lib/memory/util.js +129 -0
  42. package/lib/parts/index.js +154 -0
  43. package/lib/parts/installer.js +294 -0
  44. package/lib/parts/jobs.js +91 -0
  45. package/lib/parts/library.js +91 -0
  46. package/lib/probe-plugin.js +38 -0
  47. package/lib/voice/board-asr.js +31 -0
  48. package/locale/en.json +7 -0
  49. package/locale/zh.json +7 -0
  50. package/package.json +114 -3
  51. package/tools/backfill-affect.mjs +82 -0
  52. package/tools/eval.mjs +88 -0
  53. package/tools/p1.mjs +108 -0
  54. package/tools/p10.mjs +36 -0
  55. package/tools/p11.mjs +51 -0
  56. package/tools/p12.mjs +53 -0
  57. package/tools/p13.mjs +65 -0
  58. package/tools/p14.mjs +66 -0
  59. package/tools/p15.mjs +43 -0
  60. package/tools/p16.mjs +42 -0
  61. package/tools/p17.mjs +29 -0
  62. package/tools/p18.mjs +48 -0
  63. package/tools/p19.mjs +50 -0
  64. package/tools/p2.mjs +59 -0
  65. package/tools/p20.mjs +54 -0
  66. package/tools/p21.mjs +42 -0
  67. package/tools/p22.mjs +32 -0
  68. package/tools/p23.mjs +43 -0
  69. package/tools/p24.mjs +40 -0
  70. package/tools/p25.mjs +151 -0
  71. package/tools/p26.mjs +113 -0
  72. package/tools/p27.mjs +89 -0
  73. package/tools/p28.mjs +60 -0
  74. package/tools/p3.mjs +54 -0
  75. package/tools/p4.mjs +73 -0
  76. package/tools/p5.mjs +117 -0
  77. package/tools/p6.mjs +122 -0
  78. package/tools/p8.mjs +50 -0
  79. package/tools/p9.mjs +35 -0
  80. package/tools/phase2.mjs +159 -0
  81. package/tools/preflight.mjs +320 -0
  82. package/tools/quarterly.mjs +129 -0
  83. package/tools/refresh-catalog.mjs +60 -0
  84. package/tools/register-bundle.mjs +38 -0
  85. package/tools/review.mjs +156 -0
  86. package/tools/selfcheck.mjs +80 -0
  87. package/tools/smoke.mjs +112 -0
  88. package/tools/testset-v1.json +70 -0
  89. package/tools/validate-tools.mjs +150 -0
  90. package/tools/verify-all.mjs +39 -0
  91. package/tools/write-chain.mjs +139 -0
@@ -0,0 +1,320 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * preflight.mjs — 插件发布/重启前的硬性检查。
4
+ *
5
+ * 为什么要它:这个项目已经因为「BOM」「import 路径」「重复联接」各崩过一次,
6
+ * 每次都是同样几类错误。把教训固化成检查项,改完先跑它,过了再重启。
7
+ *
8
+ * 用法:
9
+ * node tools/preflight.mjs # 检查当前插件
10
+ * node tools/preflight.mjs --profile <profiledir> # 额外检查 profile 一致性
11
+ *
12
+ * 退出码:0=全过,1=有失败项。
13
+ */
14
+ import fs from 'node:fs'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
18
+
19
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
20
+ const ROOT = path.resolve(HERE, '..')
21
+ const args = process.argv.slice(2)
22
+ const profileArg = args.includes('--profile') ? args[args.indexOf('--profile') + 1] : null
23
+ const PROFILE = profileArg ? path.resolve(profileArg) : path.join(os.homedir(), '.dsh', 'profiles', 'desktop')
24
+
25
+ const results = []
26
+ function check(id, title, fn) {
27
+ try {
28
+ const detail = fn()
29
+ results.push({ id, title, ok: true, detail: typeof detail === 'string' ? detail : '' })
30
+ } catch (error) {
31
+ results.push({ id, title, ok: false, detail: error?.message ?? String(error) })
32
+ }
33
+ }
34
+
35
+ function walk(dir, out = []) {
36
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
37
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'backup') continue
38
+ const full = path.join(dir, entry.name)
39
+ if (entry.isDirectory()) walk(full, out)
40
+ else out.push(full)
41
+ }
42
+ return out
43
+ }
44
+
45
+ function hasBom(file) {
46
+ const fd = fs.openSync(file, 'r')
47
+ const buf = Buffer.alloc(3)
48
+ const n = fs.readSync(fd, buf, 0, 3, 0)
49
+ fs.closeSync(fd)
50
+ return n >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf
51
+ }
52
+
53
+ function readJson(file) {
54
+ return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
55
+ }
56
+
57
+ const pkg = readJson(path.join(ROOT, 'package.json'))
58
+
59
+ // ---------- G1 编码 ----------
60
+ check('G1', '文件无 BOM(JSON/YAML/JS/MD)', () => {
61
+ const files = walk(ROOT).filter((f) => /\.(json|ya?ml|js|mjs|md)$/.test(f))
62
+ const bad = files.filter(hasBom)
63
+ if (bad.length) throw new Error('带 BOM 的文件:\n ' + bad.map((f) => path.relative(ROOT, f)).join('\n '))
64
+ return `${files.length} 个文件`
65
+ })
66
+
67
+ // ---------- G2 JSON 可解析 ----------
68
+ check('G2', 'JSON 文件可解析(package.json 等)', () => {
69
+ const files = walk(ROOT).filter((f) => f.endsWith('.json'))
70
+ const bad = []
71
+ for (const f of files) {
72
+ try {
73
+ readJson(f)
74
+ } catch (e) {
75
+ bad.push(path.relative(ROOT, f) + ': ' + e.message)
76
+ }
77
+ }
78
+ if (bad.length) throw new Error(bad.join('\n '))
79
+ return `${files.length} 个 JSON`
80
+ })
81
+
82
+ // ---------- G3 包清单 ----------
83
+ check('G3', 'package.json 的 exports/main 指向真实文件', () => {
84
+ const targets = []
85
+ if (typeof pkg.main === 'string') targets.push(pkg.main)
86
+ for (const v of Object.values(pkg.exports ?? {})) {
87
+ if (typeof v === 'string') targets.push(v)
88
+ else if (v && typeof v === 'object') for (const x of Object.values(v)) if (typeof x === 'string') targets.push(x)
89
+ }
90
+ // 支持 exports 里的通配(如 ./locale/*.json):目录存在且至少有一个匹配文件即可
91
+ const targetExists = (t) => {
92
+ if (!t.includes('*')) return fs.existsSync(path.join(ROOT, t))
93
+ const dir = path.dirname(t)
94
+ const suffix = t.slice(t.lastIndexOf('*') + 1)
95
+ try {
96
+ return fs.readdirSync(path.join(ROOT, dir)).some((f) => f.endsWith(suffix))
97
+ } catch {
98
+ return false
99
+ }
100
+ }
101
+ const missing = targets.filter((t) => !targetExists(t))
102
+ if (missing.length) throw new Error('指向不存在的文件:' + missing.join(', '))
103
+ if (!pkg.dsh?.bundle?.patch) throw new Error('缺少 dsh.bundle.patch')
104
+ const patch = path.join(ROOT, pkg.dsh.bundle.patch)
105
+ if (!fs.existsSync(patch)) throw new Error('bundle patch 不存在:' + pkg.dsh.bundle.patch)
106
+ return `${targets.length} 个入口`
107
+ })
108
+
109
+ // ---------- G4 客户端 bundle ----------
110
+ check('G4', '客户端 bundle 自包含且 id 与包名一致', () => {
111
+ const clientPath = path.join(ROOT, 'lib', 'client.js')
112
+ if (!fs.existsSync(clientPath)) return '无客户端 bundle(跳过)'
113
+ const src = fs.readFileSync(clientPath, 'utf8')
114
+ if (/^\s*import\s+/m.test(src)) throw new Error('client.js 含 import 语句(必须自包含)')
115
+ const m = src.match(/__ModuleLoader__\.load\(\{\s*id:\s*'([^']+)'/)
116
+ if (!m) throw new Error('找不到 __ModuleLoader__.load 的 id')
117
+ const expected = pkg.name
118
+ if (m[1] !== expected) throw new Error(`注册 id=${m[1]} 与包名 ${expected} 不一致(会触发 duplicate factory)`)
119
+ return `id=${m[1]}`
120
+ })
121
+
122
+ // ---------- G5 宿主可导入 ----------
123
+ check('G5', '宿主模块可导入(import 全部入口)', () => {
124
+ const entries = ['lib/index.js', 'lib/memory/tools.js', 'lib/memory/store.js', 'lib/parts/index.js', 'lib/memory/service-plugin.js']
125
+ const bad = []
126
+ for (const rel of entries) {
127
+ const file = path.join(ROOT, rel)
128
+ if (!fs.existsSync(file)) {
129
+ bad.push(rel + ': 不存在')
130
+ continue
131
+ }
132
+ try {
133
+ // 同步检查无法 await,这里用子进程语义:只做路径存在性 + 静态 import 解析
134
+ const src = fs.readFileSync(file, 'utf8')
135
+ const imports = [...src.matchAll(/from\s+'(\.[^']+)'/g)].map((x) => x[1])
136
+ for (const spec of imports) {
137
+ const target = path.resolve(path.dirname(file), spec)
138
+ if (!fs.existsSync(target)) bad.push(`${rel} → ${spec} 不存在`)
139
+ }
140
+ } catch (e) {
141
+ bad.push(rel + ': ' + e.message)
142
+ }
143
+ }
144
+ if (bad.length) throw new Error(bad.join('\n '))
145
+ return `${entries.length} 个入口的相对导入全部可解析`
146
+ })
147
+
148
+ // ---------- G6 工具注册表 ----------
149
+ check('G6', '工具注册表可构建且字段完整', () => {
150
+ const { execFileSync } = process.getBuiltinModule('node:child_process')
151
+ const script = `
152
+ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'
153
+ import MemoryStore from ${JSON.stringify(pathToFileUrl(path.join(ROOT, 'lib/memory/store.js')))}
154
+ import { buildRegistry } from ${JSON.stringify(pathToFileUrl(path.join(ROOT, 'lib/memory/tools.js')))}
155
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'preflight-'))
156
+ const store = new MemoryStore({ dataDir: dir }).open()
157
+ const reg = buildRegistry(store, {})
158
+ const bad = []
159
+ for (const [name, item] of reg) {
160
+ const d = item.definition
161
+ if (!d.name || !d.description || !d.parameters || !d.output || typeof d.execute !== 'function') bad.push(name)
162
+ }
163
+ console.log(JSON.stringify({ count: reg.size, bad }))
164
+ store.close()
165
+ `
166
+ const out = execFileSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8' }).trim()
167
+ const parsed = JSON.parse(out.split('\n').pop())
168
+ if (parsed.bad.length) throw new Error('字段不完整的工具:' + parsed.bad.join(', '))
169
+ const declared = (pkg.dshx?.contributes?.tools ?? []).length
170
+ const msg = `${parsed.count} 个工具`
171
+ if (declared && declared !== parsed.count) throw new Error(`package.json 声明 ${declared} 个,实际 ${parsed.count} 个`)
172
+ return msg
173
+ })
174
+
175
+ function pathToFileUrl(p) {
176
+ return 'file:///' + p.replace(/\\/g, '/')
177
+ }
178
+
179
+ // ---------- G7 profile 一致性 ----------
180
+ check('G7', 'profile 联接唯一(只认包名)、bundles 含本包、patch 无重复 id', () => {
181
+ if (!fs.existsSync(PROFILE)) return 'profile 不存在(跳过)'
182
+ const nm = path.join(PROFILE, 'node_modules')
183
+ const real = (p) => {
184
+ try {
185
+ return fs.realpathSync(p).replace(/\\/g, '/').toLowerCase()
186
+ } catch {
187
+ return null
188
+ }
189
+ }
190
+ const self = real(ROOT)
191
+ const links = fs
192
+ .readdirSync(nm, { withFileTypes: true })
193
+ .filter((e) => real(path.join(nm, e.name)) === self)
194
+ .map((e) => e.name)
195
+ if (links.length === 0) throw new Error(`node_modules 里没有指向本包的联接(应有 ${pkg.name})`)
196
+ if (links.length > 1) throw new Error('有多个联接指向同一个包,会重复加载:' + links.join(', '))
197
+ if (links[0] !== pkg.name) throw new Error(`联接名 ${links[0]} 与包名 ${pkg.name} 不一致`)
198
+ const profilePkg = readJson(path.join(PROFILE, 'package.json'))
199
+ const bundles = profilePkg.dsh?.profile?.bundles ?? []
200
+ if (!bundles.includes(pkg.name)) throw new Error(`bundles 里没有 ${pkg.name}`)
201
+ const patchFile = path.join(PROFILE, 'cordis.patch.yml')
202
+ if (fs.existsSync(patchFile)) {
203
+ const text = fs.readFileSync(patchFile, 'utf8').replace(/^\uFEFF/, '')
204
+ const ids = [...text.matchAll(/^\s*- id:\s*(\S+)/gm)].map((m) => m[1])
205
+ const seen = new Map()
206
+ const dupIds = []
207
+ for (const id of ids) {
208
+ if (seen.has(id)) dupIds.push(id)
209
+ seen.set(id, true)
210
+ }
211
+ if (dupIds.length) throw new Error('patch 里 id 重复:' + [...new Set(dupIds)].join(', '))
212
+ }
213
+ return `links=${links.join(',')}`
214
+ })
215
+
216
+ // ---------- G8 数据库版本 ----------
217
+ check('G8', '库版本不高于代码版本', () => {
218
+ const dataDir = process.env.DSH_MEMORY_DATA_DIR || path.resolve(ROOT, '..', 'dsh-memory-data')
219
+ const dbFile = path.join(dataDir, 'db', 'memory.db')
220
+ if (!fs.existsSync(dbFile)) return '未找到库(跳过)'
221
+ const { SCHEMA_VERSION } = { SCHEMA_VERSION: readSchemaVersion() }
222
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'preflight-db-'))
223
+ fs.mkdirSync(path.join(tmp, 'db'), { recursive: true })
224
+ fs.copyFileSync(dbFile, path.join(tmp, 'db', 'memory.db'))
225
+ const { execFileSync } = process.getBuiltinModule('node:child_process')
226
+ const script = `
227
+ import MemoryStore from ${JSON.stringify(pathToFileUrl(path.join(ROOT, 'lib/memory/store.js')))}
228
+ const store = new MemoryStore({ dataDir: ${JSON.stringify(tmp)} }).open()
229
+ console.log(store.getMeta('schema_version') ?? '0')
230
+ store.close()
231
+ `
232
+ const out = execFileSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8' }).trim()
233
+ const dbVersion = Number(out.split('\n').pop())
234
+ if (dbVersion > SCHEMA_VERSION) throw new Error(`库 v${dbVersion} 高于代码 v${SCHEMA_VERSION}(回退代码会导致降级)`)
235
+ return `库 v${dbVersion} ≤ 代码 v${SCHEMA_VERSION}`
236
+ })
237
+
238
+ // ---------- G9 profile 三处一致 ----------
239
+ check('G9', 'profile 三处一致:bundles 含包名 / 联接存在 / patch 行 name 匹配', () => {
240
+ if (!fs.existsSync(PROFILE)) return 'profile 不存在(跳过)'
241
+ const profilePkg = readJson(path.join(PROFILE, 'package.json'))
242
+ const bundles = profilePkg.dsh?.profile?.bundles ?? []
243
+ if (!bundles.includes(pkg.name)) {
244
+ throw new Error(`bundles 里没有 ${pkg.name}(加载器会跳过整个插件,设置里看不到入口)`)
245
+ }
246
+ const link = path.join(PROFILE, 'node_modules', pkg.name)
247
+ if (!fs.existsSync(link)) throw new Error(`缺少联接 node_modules/${pkg.name}`)
248
+ const patchFile = path.join(PROFILE, 'cordis.patch.yml')
249
+ const hasRow = (text, name) => {
250
+ const rows = [...text.replace(/^\uFEFF/, '').matchAll(/- id:\s*(\S+)\s*\n\s*name:\s*'?([^'\n]+)'?/g)]
251
+ return rows.some((r) => r[2].trim() === name)
252
+ }
253
+ if (fs.existsSync(patchFile)) {
254
+ const text = fs.readFileSync(patchFile, 'utf8')
255
+ if (hasRow(text, pkg.name)) return 'bundles✓ link✓ patch✓'
256
+ }
257
+ // bundle 自带 patch(package.json 的 dsh.bundle.patch)也算数:
258
+ // 现代安装路径只登记 bundles,行由 bundle 自己的 patch 插入,不再写 profile patch。
259
+ const ownPatch = pkg.dsh?.bundle?.patch ? path.join(ROOT, String(pkg.dsh.bundle.patch)) : null
260
+ if (ownPatch && fs.existsSync(ownPatch) && hasRow(fs.readFileSync(ownPatch, 'utf8'), pkg.name)) {
261
+ return 'bundles✓ link✓ bundle-patch✓'
262
+ }
263
+ throw new Error(`profile patch 和 bundle 自带 patch 里都没有 name: ${pkg.name} 的插入行`)
264
+ })
265
+
266
+ // ---------- G10 客户端 bundle 可注册 ----------
267
+ check('G10', '客户端 bundle 在模拟环境可注册(id 正确、apply 存在)', () => {
268
+ const clientPath = path.join(ROOT, 'lib', 'client.js')
269
+ if (!fs.existsSync(clientPath)) return '无客户端 bundle(跳过)'
270
+ const { execFileSync } = process.getBuiltinModule('node:child_process')
271
+ const script = `
272
+ const React = {
273
+ createElement: (...args) => ({ type: 'el', args }),
274
+ useState: (v) => [v, () => {}],
275
+ useEffect: () => {},
276
+ useCallback: (fn) => fn,
277
+ useMemo: (fn) => fn(),
278
+ useRef: (v) => ({ current: v }),
279
+ Fragment: 'fragment',
280
+ }
281
+ let captured = null
282
+ globalThis.window = {
283
+ __ModuleLoader__: {
284
+ load: (cfg) => {
285
+ const mod = cfg.factory((name) => (name === 'react' ? React : {}))
286
+ captured = { id: cfg.id, name: mod?.name, hasApply: typeof mod?.apply === 'function' }
287
+ },
288
+ },
289
+ }
290
+ await import(${JSON.stringify(pathToFileUrl(clientPath))})
291
+ console.log(JSON.stringify(captured))
292
+ `
293
+ const out = execFileSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8' }).trim()
294
+ const parsed = JSON.parse(out.split('\n').pop())
295
+ if (parsed.id !== pkg.name) throw new Error(`注册 id=${parsed.id} 与包名 ${pkg.name} 不一致`)
296
+ if (!parsed.hasApply) throw new Error('客户端模块没有导出 apply')
297
+ return `id=${parsed.id} apply✓`
298
+ })
299
+
300
+ function readSchemaVersion() {
301
+ const src = fs.readFileSync(path.join(ROOT, 'lib/memory/schema.js'), 'utf8')
302
+ const m = src.match(/SCHEMA_VERSION\s*=\s*(\d+)/)
303
+ return m ? Number(m[1]) : 0
304
+ }
305
+
306
+ // ---------- 输出 ----------
307
+ let failed = 0
308
+ for (const r of results) {
309
+ const mark = r.ok ? 'PASS' : 'FAIL'
310
+ if (!r.ok) failed += 1
311
+ console.log(`[${r.id}] ${mark} ${r.title}${r.detail ? ' — ' + r.detail : ''}`)
312
+ }
313
+
314
+ console.log('')
315
+ if (failed === 0) {
316
+ console.log('PREFLIGHT OK — 可以重启/发布。')
317
+ process.exit(0)
318
+ }
319
+ console.log(`PREFLIGHT FAILED(${failed} 项)— 修完再重启,规则见 docs/插件规范.md`)
320
+ process.exit(1)
@@ -0,0 +1,129 @@
1
+ // quarterly.mjs — 季度优化单(P3):读最近 3 份月报,出参数建议。
2
+ // 红线:只提参数调整建议,不自动改任何配置。
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+
7
+ const DATA_DIR = 'D:/001/CH002/dsh-memory-data'
8
+ const MONTHLY_DIR = path.join(DATA_DIR, 'reports', 'monthly')
9
+ const OUT_DIR = path.join(DATA_DIR, 'reports', 'quarterly')
10
+
11
+ function quarterOf(month) {
12
+ const [y, m] = month.split('-').map(Number)
13
+ return `${y}-Q${Math.floor((m - 1) / 3) + 1}`
14
+ }
15
+
16
+ function pct(x) {
17
+ return `${(x * 100).toFixed(1)}%`
18
+ }
19
+
20
+ const files = fs.existsSync(MONTHLY_DIR)
21
+ ? fs.readdirSync(MONTHLY_DIR).filter((f) => f.endsWith('.json')).sort()
22
+ : []
23
+
24
+ if (files.length === 0) {
25
+ console.error('没有月报可读:先跑 tools/review.mjs --month YYYY-MM')
26
+ process.exit(1)
27
+ }
28
+
29
+ const reports = files.slice(-3).map((f) => JSON.parse(fs.readFileSync(path.join(MONTHLY_DIR, f), 'utf8')))
30
+ const latest = reports[reports.length - 1]
31
+ const quarter = quarterOf(latest.month)
32
+
33
+ function metric(r, key) {
34
+ switch (key) {
35
+ case 'records': return r.total
36
+ case 'new': return r.monthNew
37
+ case 'hitRate': return r.search?.total ? r.search.hit / r.search.total : 0
38
+ case 'pending': return r.pending
39
+ case 'conflicts': return r.conflicts
40
+ case 'dedupRate': return r.dedupRate
41
+ case 'chainBreaks': return r.chainBreaks
42
+ case 'fpr': return r.eval?.normal?.fpr ?? 0
43
+ case 'l1': return r.eval?.levels?.L1?.rate ?? 0
44
+ case 'l2': return r.eval?.levels?.L2?.rate ?? 0
45
+ case 'l3': return r.eval?.levels?.L3?.rate ?? 0
46
+ default: return null
47
+ }
48
+ }
49
+
50
+ const METRICS = [
51
+ ['records', '记录总数', 'int'],
52
+ ['new', '本月新增', 'int'],
53
+ ['hitRate', '检索命中率', 'pct'],
54
+ ['pending', '待审积压', 'int'],
55
+ ['conflicts', '冲突数', 'int'],
56
+ ['dedupRate', '去重率', 'pct'],
57
+ ['chainBreaks', '断链数', 'int'],
58
+ ['fpr', '误报率', 'pct'],
59
+ ['l1', 'L1 检出率', 'pct'],
60
+ ['l2', 'L2 检出率', 'pct'],
61
+ ['l3', 'L3 检出率', 'pct'],
62
+ ]
63
+
64
+ function fmt(value, kind) {
65
+ if (value === null || value === undefined) return '—'
66
+ return kind === 'pct' ? pct(value) : String(value)
67
+ }
68
+
69
+ // ---------- 建议 ----------
70
+ const advice = []
71
+ const last = reports[reports.length - 1]
72
+ if ((last.chainBreaks ?? 0) > 0) advice.push({ level: 'P0', item: '审计链断裂', action: '立即跑 mem_audit --deep,修复前不要继续写入。', param: '—' })
73
+ if ((last.pending ?? 0) > 20) advice.push({ level: 'P1', item: `待审积压 ${last.pending} 条`, action: '集中审核一次;若持续积压,考虑把「未验证来源」的写入频率降下来。', param: '—' })
74
+ if ((last.eval?.normal?.fpr ?? 0) > 0.1) advice.push({ level: 'P1', item: `误报率 ${pct(last.eval.normal.fpr)}`, action: '逐条看命中的 scanner,关掉或收紧误伤的那条(scanner 可单独禁用)。', param: 'FPR 目标 ≤10%' })
75
+ if ((last.eval?.levels?.L1?.rate ?? 0) < 0.9) advice.push({ level: 'P1', item: 'L1 检出率下降', action: '检查 scanner 是否被误改;用固定测试集回归。', param: 'L1 目标 ≥90%' })
76
+ if ((last.eval?.levels?.L2?.rate ?? 0) === 0 || (last.eval?.levels?.L3?.rate ?? 0) === 0) advice.push({ level: 'P2', item: 'L2/L3 仍为结构性盲区', action: '不要靠加规则硬扛;继续靠注入侧组合检查(同批最多 1 条)兜底。', param: '—' })
77
+ if ((last.dedupRate ?? 0) > 0.3) advice.push({ level: 'P2', item: `去重率 ${pct(last.dedupRate)}`, action: '可能有重复写入源,检查是否有脚本在反复导入同一份内容。', param: '—' })
78
+ if (reports.length >= 2) {
79
+ const prev = reports[reports.length - 2]
80
+ if ((last.search?.total ?? 0) > 0 && (prev.search?.total ?? 0) > 0) {
81
+ const before = prev.search.hit / prev.search.total
82
+ const now = last.search.hit / last.search.total
83
+ if (now < before - 0.2) advice.push({ level: 'P2', item: '命中率明显下降', action: '检查分词器与索引是否一致(mem_audit 会报 FTS 差异)。', param: '—' })
84
+ }
85
+ }
86
+
87
+ // ---------- 产物 ----------
88
+ const lines = []
89
+ lines.push(`# 季度优化单 · ${quarter}`)
90
+ lines.push('')
91
+ lines.push(`- 生成时间:${new Date().toISOString()}`)
92
+ lines.push(`- 依据月报:${reports.map((r) => r.month).join(' / ')}`)
93
+ lines.push('- 口径:只给参数建议,**不自动修改任何配置**;每条建议都需人工确认。')
94
+ lines.push('')
95
+ lines.push('## 一、趋势')
96
+ lines.push('')
97
+ lines.push(`| 指标 | ${reports.map((r) => r.month).join(' | ')} |`)
98
+ lines.push(`|---|${reports.map(() => '---').join('|')}|`)
99
+ for (const [key, label, kind] of METRICS) {
100
+ lines.push(`| ${label} | ${reports.map((r) => fmt(metric(r, key), kind)).join(' | ')} |`)
101
+ }
102
+ lines.push('')
103
+ lines.push('## 二、优化建议')
104
+ lines.push('')
105
+ if (advice.length === 0) {
106
+ lines.push('本期没有需要调整的项:指标在阈值内,保持现状。')
107
+ } else {
108
+ lines.push('| 级别 | 问题 | 建议动作 | 参数目标 |')
109
+ lines.push('|---|---|---|---|')
110
+ for (const a of advice) lines.push(`| ${a.level} | ${a.item} | ${a.action} | ${a.param} |`)
111
+ }
112
+ lines.push('')
113
+ lines.push('## 三、执行纪律')
114
+ lines.push('')
115
+ lines.push('- 只调参数,不改结构;结构变更另立方案。')
116
+ lines.push('- 任何阈值调整先跑固定测试集,报出 FPR 与检出率再定。')
117
+ lines.push('- 调完记录到本单的「执行记录」里,并保留回滚值。')
118
+ lines.push('')
119
+
120
+ fs.mkdirSync(OUT_DIR, { recursive: true })
121
+ const mdPath = path.join(OUT_DIR, `${quarter}.md`)
122
+ const jsonPath = path.join(OUT_DIR, `${quarter}.json`)
123
+ fs.writeFileSync(mdPath, lines.join('\n'), 'utf8')
124
+ fs.writeFileSync(jsonPath, JSON.stringify({ quarter, months: reports.map((r) => r.month), advice, generatedAt: new Date().toISOString() }, null, 2), 'utf8')
125
+
126
+ console.log(`已生成:${mdPath}`)
127
+ console.log(`已生成:${jsonPath}`)
128
+ console.log(`建议 ${advice.length} 条:`)
129
+ for (const a of advice) console.log(` [${a.level}] ${a.item} -> ${a.action}`)
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * refresh-catalog.mjs — 从集市索引生成工作台的「零件库」快照。
4
+ *
5
+ * 数据源:https://www.mydsh.xyz/market/index.json(9300+ 条)
6
+ * 输出:catalog/parts.json(精简字段,无 BOM)
7
+ *
8
+ * 用法:node tools/refresh-catalog.mjs [--min-stars 50] [--limit 800]
9
+ */
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+
13
+ const args = process.argv.slice(2)
14
+ const minStars = Number(args[args.indexOf('--min-stars') + 1]) || 50
15
+ const limit = Number(args[args.indexOf('--limit') + 1]) || 800
16
+ const INDEX_URL = 'https://www.mydsh.xyz/market/index.json'
17
+
18
+ const outDir = path.resolve('catalog')
19
+ fs.mkdirSync(outDir, { recursive: true })
20
+ const outFile = path.join(outDir, 'parts.json')
21
+
22
+ let raw
23
+ try {
24
+ raw = JSON.parse(fs.readFileSync(path.join(outDir, '.index.json'), 'utf8'))
25
+ } catch {
26
+ const res = await fetch(INDEX_URL, { headers: { 'user-agent': 'dsh-workbench-catalog' } })
27
+ raw = await res.json()
28
+ fs.writeFileSync(path.join(outDir, '.index.json'), JSON.stringify(raw), 'utf8')
29
+ }
30
+
31
+ const plugins = raw.plugins ?? []
32
+ const picked = plugins
33
+ .filter((p) => Boolean(p.audited) || Number(p.stars ?? 0) >= minStars)
34
+ .sort((a, b) => {
35
+ const auditedDiff = Number(Boolean(b.audited)) - Number(Boolean(a.audited))
36
+ if (auditedDiff !== 0) return auditedDiff
37
+ return Number(b.stars ?? 0) - Number(a.stars ?? 0)
38
+ })
39
+ .slice(0, limit)
40
+ .map((p) => ({
41
+ id: p.id,
42
+ name: p.name,
43
+ author: p.author,
44
+ category: p.category,
45
+ stars: Number(p.stars ?? 0),
46
+ summary: p.summary ?? '',
47
+ repo: p.repo,
48
+ install: p.install ?? '',
49
+ audited: Boolean(p.audited),
50
+ }))
51
+
52
+ const payload = {
53
+ source: INDEX_URL,
54
+ fetchedAt: new Date().toISOString(),
55
+ total: plugins.length,
56
+ count: picked.length,
57
+ parts: picked,
58
+ }
59
+ fs.writeFileSync(outFile, JSON.stringify(payload, null, 2) + '\n', 'utf8')
60
+ console.log(`catalog: ${picked.length}/${plugins.length} 条 → ${outFile}`)
@@ -0,0 +1,38 @@
1
+ /**
2
+ * register-bundle.mjs — 把 dsh-workbench 重新挂回 desktop profile 的 bundles。
3
+ *
4
+ * 只做一件事:在 dsh.profile.bundles 里补回包名(联接已经存在)。
5
+ * 不用 PowerShell 写 JSON(会带 BOM,DSH 启动直接崩),写完立刻重新解析校验。
6
+ */
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+
10
+ const profile = process.env.DSH_PROFILE_DIR ?? path.join(process.env.USERPROFILE ?? '', '.dsh', 'profiles', 'desktop')
11
+ const file = path.join(profile, 'package.json')
12
+ const pkgName = 'dsh-workbench'
13
+
14
+ const raw = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
15
+ const json = JSON.parse(raw)
16
+ const bundles = json?.dsh?.profile?.bundles
17
+ if (!Array.isArray(bundles)) throw new Error('dsh.profile.bundles 不是数组')
18
+
19
+ if (bundles.includes(pkgName)) {
20
+ console.log(JSON.stringify({ changed: false, message: '已经在 bundles 里', total: bundles.length }))
21
+ process.exit(0)
22
+ }
23
+
24
+ const backup = `${file}.bak-add-${Date.now()}`
25
+ fs.copyFileSync(file, backup)
26
+ bundles.push(pkgName)
27
+
28
+ const text = JSON.stringify(json, null, 2)
29
+ JSON.parse(text) // 先自证:能解析
30
+ fs.writeFileSync(file, text, 'utf8')
31
+
32
+ // 回读校验:无 BOM、能解析、含包名
33
+ const back = fs.readFileSync(file)
34
+ if (back[0] === 0xef && back[1] === 0xbb && back[2] === 0xbf) throw new Error('写出的文件带 BOM')
35
+ const parsed = JSON.parse(back.toString('utf8'))
36
+ if (!parsed.dsh.profile.bundles.includes(pkgName)) throw new Error('回读没看到包名')
37
+
38
+ console.log(JSON.stringify({ changed: true, backup: path.basename(backup), total: parsed.dsh.profile.bundles.length }))