dsh-sixlayer-memory 0.0.0-stage → 2.0.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 (92) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/README.md +292 -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/push-via-api.mjs +187 -0
  83. package/tools/quarterly.mjs +129 -0
  84. package/tools/refresh-catalog.mjs +60 -0
  85. package/tools/register-bundle.mjs +38 -0
  86. package/tools/review.mjs +156 -0
  87. package/tools/selfcheck.mjs +80 -0
  88. package/tools/smoke.mjs +112 -0
  89. package/tools/testset-v1.json +70 -0
  90. package/tools/validate-tools.mjs +150 -0
  91. package/tools/verify-all.mjs +39 -0
  92. 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,187 @@
1
+ /**
2
+ * push-via-api.mjs —— 用 GitHub REST API 把本地仓库推到 GitHub。
3
+ *
4
+ * 为什么要这个:这台机器上 github.com:443 不通(git push / GCM 登录都会卡死),
5
+ * 但 api.github.com:443 通。所以走 Git Data API 建库 + 提交树,不依赖 git 传输。
6
+ *
7
+ * 用法:
8
+ * $env:GITHUB_TOKEN='ghp_xxx' # classic PAT,勾 repo 权限
9
+ * node tools/push-via-api.mjs
10
+ *
11
+ * 只读本地 git 索引(git ls-files),不会把 .gitignore 排除的东西传上去。
12
+ */
13
+ import fs from 'node:fs'
14
+ import path from 'node:path'
15
+ import { execFileSync } from 'node:child_process'
16
+
17
+ const OWNER = 'z9134'
18
+ const REPO = 'dsh-sixlayer-memory'
19
+ const ROOT = process.env.REPO_ROOT ?? 'D:/001/CH002/dsh-memory-core'
20
+ const TOKEN = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? ''
21
+
22
+ if (!TOKEN) {
23
+ console.error('缺少 GITHUB_TOKEN。先在 https://github.com/settings/tokens 建一个勾了 repo 的 token,然后:')
24
+ console.error(" $env:GITHUB_TOKEN='ghp_...'")
25
+ console.error(' node tools/push-via-api.mjs')
26
+ process.exit(2)
27
+ }
28
+
29
+ const API = 'https://api.github.com'
30
+
31
+ async function callOnce(method, url, body) {
32
+ const res = await fetch(API + url, {
33
+ method,
34
+ headers: {
35
+ authorization: `Bearer ${TOKEN}`,
36
+ accept: 'application/vnd.github+json',
37
+ 'x-github-api-version': '2022-11-28',
38
+ 'user-agent': 'dsh-sixlayer-memory-release',
39
+ ...(body ? { 'content-type': 'application/json' } : {}),
40
+ },
41
+ body: body ? JSON.stringify(body) : undefined,
42
+ })
43
+ const text = await res.text()
44
+ let json = null
45
+ try {
46
+ json = text ? JSON.parse(text) : null
47
+ } catch {
48
+ /* 非 JSON 响应 */
49
+ }
50
+ if (!res.ok) {
51
+ const msg = json?.message ?? text.slice(0, 300)
52
+ throw new Error(`${method} ${url} -> ${res.status} ${msg}`)
53
+ }
54
+ return json
55
+ }
56
+
57
+ /** 网络抖动重试:断线/超时重来 3 次,4xx 直接抛。 */
58
+ async function call(method, url, body) {
59
+ let last
60
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
61
+ try {
62
+ return await callOnce(method, url, body)
63
+ } catch (error) {
64
+ last = error
65
+ const msg = String(error?.message ?? '')
66
+ const retriable = /fetch failed|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|network|-> 5\d\d/.test(msg)
67
+ if (!retriable) throw error
68
+ if (attempt < 3) await new Promise((r) => setTimeout(r, 600 * attempt))
69
+ }
70
+ }
71
+ throw last
72
+ }
73
+
74
+ async function ensureRepo() {
75
+ try {
76
+ const repo = await call('GET', `/repos/${OWNER}/${REPO}`)
77
+ console.log(`仓库已存在:${repo.html_url}`)
78
+ return repo
79
+ } catch (error) {
80
+ if (!/-> 404/.test(error.message)) throw error
81
+ }
82
+ const repo = await call('POST', '/user/repos', {
83
+ name: REPO,
84
+ description: '会先审后记、还带审计链的本地记忆 · DSH 六层记忆底座',
85
+ homepage: '',
86
+ private: false,
87
+ has_issues: true,
88
+ has_wiki: false,
89
+ auto_init: false,
90
+ })
91
+ console.log(`已创建仓库:${repo.html_url}`)
92
+ return repo
93
+ }
94
+
95
+ /**
96
+ * 空仓库连 git/trees 都返回 409「Git Repository is empty」,
97
+ * 唯一可靠的办法是先用 Contents API 写一个文件把仓库"点亮",
98
+ * 再用 blobs/tree/commit 覆盖上去。这里直接写真实 README。
99
+ */
100
+ async function bootstrapIfEmpty() {
101
+ try {
102
+ await call('GET', `/repos/${OWNER}/${REPO}/git/ref/heads/main`)
103
+ return false
104
+ } catch (error) {
105
+ if (!/-> 404|-> 409/.test(error.message)) throw error
106
+ }
107
+ const readme = fs.readFileSync(path.join(ROOT, 'README.md'))
108
+ await call('PUT', `/repos/${OWNER}/${REPO}/contents/README.md`, {
109
+ message: 'init: README',
110
+ content: readme.toString('base64'),
111
+ })
112
+ console.log('已用 README 初始化 main 分支(空仓库不能直接传 blob/tree)')
113
+ return true
114
+ }
115
+
116
+ function trackedFiles() {
117
+ const out = execFileSync('git', ['-C', ROOT, 'ls-files', '-z'], { encoding: 'utf8' })
118
+ return out.split('\0').filter(Boolean)
119
+ }
120
+
121
+ async function uploadBlob(rel) {
122
+ const abs = path.join(ROOT, rel)
123
+ const content = fs.readFileSync(abs)
124
+ const blob = await call('POST', `/repos/${OWNER}/${REPO}/git/blobs`, {
125
+ content: content.toString('base64'),
126
+ encoding: 'base64',
127
+ })
128
+ return blob.sha
129
+ }
130
+
131
+ async function main() {
132
+ const me = await call('GET', '/user')
133
+ if (me.login !== OWNER) throw new Error(`token 属于 ${me.login},不是 ${OWNER}`)
134
+ console.log(`身份:${me.login}`)
135
+
136
+ await ensureRepo()
137
+ await bootstrapIfEmpty()
138
+
139
+ const files = trackedFiles()
140
+ console.log(`本地文件:${files.length} 个`)
141
+
142
+ const entries = []
143
+ let done = 0
144
+ const concurrency = 4
145
+ let cursor = 0
146
+ async function worker() {
147
+ while (cursor < files.length) {
148
+ const rel = files[cursor++]
149
+ const sha = await uploadBlob(rel)
150
+ entries.push({ path: rel.split(path.sep).join('/'), mode: '100644', type: 'blob', sha })
151
+ done += 1
152
+ if (done % 20 === 0) console.log(` 已上传 ${done}/${files.length}`)
153
+ }
154
+ }
155
+ await Promise.all(Array.from({ length: concurrency }, worker))
156
+ console.log(` 已上传 ${done}/${files.length}`)
157
+
158
+ const tree = await call('POST', `/repos/${OWNER}/${REPO}/git/trees`, { tree: entries })
159
+ const message = execFileSync('git', ['-C', ROOT, 'log', '-1', '--pretty=%s'], { encoding: 'utf8' }).trim()
160
+ const commit = await call('POST', `/repos/${OWNER}/${REPO}/git/commits`, {
161
+ message: `${message}\n\n(经 GitHub API 推送)`,
162
+ tree: tree.sha,
163
+ parents: [],
164
+ })
165
+
166
+ let hasMain = true
167
+ try {
168
+ await call('GET', `/repos/${OWNER}/${REPO}/git/ref/heads/main`)
169
+ } catch (error) {
170
+ if (!/-> 404|-> 409/.test(error.message)) throw error
171
+ hasMain = false
172
+ }
173
+ if (hasMain) {
174
+ await call('PATCH', `/repos/${OWNER}/${REPO}/git/refs/heads/main`, { sha: commit.sha, force: true })
175
+ } else {
176
+ await call('POST', `/repos/${OWNER}/${REPO}/git/refs`, { ref: 'refs/heads/main', sha: commit.sha })
177
+ }
178
+
179
+ console.log('')
180
+ console.log(`完成:https://github.com/${OWNER}/${REPO}/tree/main`)
181
+ console.log(`commit ${commit.sha.slice(0, 10)} · ${entries.length} 个文件`)
182
+ }
183
+
184
+ main().catch((error) => {
185
+ console.error('失败:' + (error?.message ?? String(error)))
186
+ process.exit(1)
187
+ })
@@ -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}`)