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,91 @@
1
+ /**
2
+ * library.js — 零件库(集市索引的本地快照)。
3
+ *
4
+ * 数据来源:catalog/parts.json(由 tools/refresh-catalog.mjs 从集市索引生成)
5
+ * 只做只读搜索,不执行安装;安装命令原样返回,由用户复制执行。
6
+ */
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
10
+
11
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
12
+ const CATALOG_FILE = path.resolve(HERE, '..', '..', 'catalog', 'parts.json')
13
+
14
+ let cache = null
15
+
16
+ export function loadCatalog() {
17
+ if (cache) return cache
18
+ try {
19
+ cache = JSON.parse(fs.readFileSync(CATALOG_FILE, 'utf8').replace(/^\uFEFF/, ''))
20
+ } catch {
21
+ cache = { source: '', fetchedAt: null, total: 0, count: 0, parts: [] }
22
+ }
23
+ return cache
24
+ }
25
+
26
+ export function catalogMeta() {
27
+ const c = loadCatalog()
28
+ return {
29
+ source: c.source,
30
+ fetchedAt: c.fetchedAt ?? null,
31
+ total: c.total ?? 0,
32
+ count: c.count ?? 0,
33
+ categories: categoryCounts(c.parts ?? []),
34
+ }
35
+ }
36
+
37
+ function categoryCounts(parts) {
38
+ const map = {}
39
+ for (const p of parts) {
40
+ const key = p.category || '其他'
41
+ map[key] = (map[key] ?? 0) + 1
42
+ }
43
+ return map
44
+ }
45
+
46
+ function score(part, q) {
47
+ if (!q) return (part.audited ? 1000 : 0) + Math.log10((part.stars ?? 0) + 10) * 10
48
+ const name = String(part.name ?? '').toLowerCase()
49
+ const author = String(part.author ?? '').toLowerCase()
50
+ const summary = String(part.summary ?? '').toLowerCase()
51
+ let s = 0
52
+ if (name === q) s += 500
53
+ else if (name.includes(q)) s += 200
54
+ if (author.includes(q)) s += 80
55
+ if (summary.includes(q)) s += 60
56
+ if (part.audited) s += 40
57
+ s += Math.log10((part.stars ?? 0) + 10) * 5
58
+ return s
59
+ }
60
+
61
+ /**
62
+ * 搜索零件库。
63
+ * @param {{query?: string, category?: string, limit?: number}} input
64
+ */
65
+ export function searchLibrary(input = {}) {
66
+ const catalog = loadCatalog()
67
+ const q = String(input.query ?? '').trim().toLowerCase()
68
+ const category = String(input.category ?? '').trim()
69
+ const limit = Math.min(Math.max(Number(input.limit ?? 30), 1), 200)
70
+
71
+ let parts = catalog.parts ?? []
72
+ if (category) parts = parts.filter((p) => (p.category || '其他') === category)
73
+ if (q) parts = parts.filter((p) => {
74
+ const hay = `${p.name ?? ''} ${p.author ?? ''} ${p.summary ?? ''}`.toLowerCase()
75
+ return hay.includes(q)
76
+ })
77
+
78
+ const items = parts
79
+ .map((p) => ({ ...p, _score: score(p, q) }))
80
+ .sort((a, b) => b._score - a._score)
81
+ .slice(0, limit)
82
+ .map(({ _score, ...p }) => p)
83
+
84
+ return {
85
+ query: q,
86
+ category,
87
+ matched: items.length,
88
+ total: catalog.count ?? 0,
89
+ items,
90
+ }
91
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * probe-plugin.js — 临时诊断插件(问题定位后可删)。
3
+ *
4
+ * 它只做一件事:证明"这个宿主能不能加载 file:// 插件"以及
5
+ * "index.js 到底能不能被 import、apply 会不会抛错",全部写进诊断日志。
6
+ */
7
+ import fs from 'node:fs'
8
+
9
+ const LOG = 'D:/001/CH002/dsh-memory-core/docs/_rpc-diag.log'
10
+ function log(message) {
11
+ try {
12
+ fs.appendFileSync(LOG, `${new Date().toISOString()} ${message}\n`, 'utf8')
13
+ } catch {
14
+ /* 忽略 */
15
+ }
16
+ }
17
+
18
+ log('probe: module loaded')
19
+
20
+ export const name = 'memory-core-probe'
21
+
22
+ export function apply(ctx, config = {}) {
23
+ log('probe: apply called')
24
+ const dataDir = String(config?.dataDir ?? 'D:\\001\\CH002\\dsh-memory-data')
25
+ import('./index.js')
26
+ .then((mod) => {
27
+ log('probe: index.js import OK')
28
+ try {
29
+ mod.apply(ctx, { dataDir })
30
+ log('probe: index.apply OK')
31
+ } catch (error) {
32
+ log('probe: index.apply THREW: ' + (error && error.message ? error.message : String(error)))
33
+ }
34
+ })
35
+ .catch((error) => {
36
+ log('probe: index.js import FAILED: ' + (error && error.message ? error.message : String(error)))
37
+ })
38
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * board-asr.js — 调昇腾板子上的 ASR 服务(语音→文字)。
3
+ *
4
+ * 板子侧:/opt/voice-asr/asr_server.py(paraformer int8,systemd 管理,端口 8788)
5
+ * 契约:POST /asr,body = 16k 单声道 WAV 字节;返回 { ok, text, ms, dur_s }
6
+ *
7
+ * 实测(2026-11-03):5.6s 语音 → 端到端 768ms(解码 700ms + 网络 68ms)
8
+ */
9
+ export const DEFAULT_BASE = 'http://192.168.0.198:8788'
10
+
11
+ export async function boardHealth({ baseUrl = DEFAULT_BASE, timeoutMs = 3000 } = {}) {
12
+ const res = await fetch(baseUrl + '/health', { signal: AbortSignal.timeout(timeoutMs) })
13
+ if (!res.ok) throw new Error('板子 ASR 健康检查失败:HTTP ' + res.status)
14
+ return res.json()
15
+ }
16
+
17
+ /**
18
+ * @param {Buffer|Uint8Array} wav 16k 单声道 WAV
19
+ * @returns {Promise<{ok: boolean, text: string, ms: number, dur_s: number}>}
20
+ */
21
+ export async function boardAsr(wav, { baseUrl = DEFAULT_BASE, timeoutMs = 20000 } = {}) {
22
+ const res = await fetch(baseUrl + '/asr', {
23
+ method: 'POST',
24
+ headers: { 'content-type': 'audio/wav' },
25
+ body: wav,
26
+ signal: AbortSignal.timeout(timeoutMs),
27
+ })
28
+ const json = await res.json()
29
+ if (!res.ok || !json.ok) throw new Error('板子 ASR 失败:' + (json.error || ('HTTP ' + res.status)))
30
+ return json
31
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Six-layer Memory",
4
+ "description": "Local, auditable long-term memory: query-aware recall every turn, untrusted writes held for review, credential-level content never surfaced, and every action on a hash-chained audit trail. Zero external dependencies by default.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "六层记忆底座",
4
+ "description": "本地、可审计的长期记忆:每一轮按你的输入自动召回,写入先审后记,凭证级内容永不外显,全部动作留哈希链。默认零外部依赖,数据不出本机。",
5
+ "detail": "docs/DETAIL.zh.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,117 @@
1
1
  {
2
2
  "name": "dsh-sixlayer-memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.0.3",
4
+ "private": false,
5
+ "description": "DSH 工作台:六层记忆底座(每轮自动召回 + 候选沉淀 + 闸门审计)+ 零件化,支持 QQ 随身使用。",
6
+ "type": "module",
7
+ "main": "lib/index.js",
8
+ "exports": {
9
+ ".": "./lib/index.js",
10
+ "./client": "./lib/client.js",
11
+ "./service-plugin": "./lib/memory/service-plugin.js",
12
+ "./store": "./lib/memory/store.js",
13
+ "./package.json": "./package.json",
14
+ "./parts": "./lib/parts/index.js",
15
+ "./locale/*.json": "./locale/*.json",
16
+ "./icon": "./icon.svg"
17
+ },
18
+ "engines": {
19
+ "node": ">=22.5",
20
+ "dsh": ">=0.2.0-rc.1 <0.3.0-0"
21
+ },
22
+ "files": [
23
+ "lib/",
24
+ "tools/",
25
+ "cordis.patch.yml",
26
+ "README.md",
27
+ "CHANGELOG.md",
28
+ "catalog/",
29
+ "locale/*.json",
30
+ "icon.svg",
31
+ "docs/DETAIL.md",
32
+ "docs/DETAIL.zh.md",
33
+ "docs/preview.svg",
34
+ "docs/生命周期-自动召回与候选.md"
35
+ ],
36
+ "dsh": {
37
+ "bundle": {
38
+ "patch": "./cordis.patch.yml"
39
+ },
40
+ "manifestVersion": 1,
41
+ "client": {
42
+ "platform": "web",
43
+ "inject": [
44
+ "@deepseek-ai/dsh-client-connection",
45
+ "@deepseek-ai/dsh-client-ui-slots",
46
+ "@deepseek-ai/dsh-client-ui-sidebar-right"
47
+ ],
48
+ "immediately": false
49
+ }
50
+ },
51
+ "dshx": {
52
+ "contributes": {
53
+ "tools": [
54
+ "mem_admin_catalog",
55
+ "mem_admin_open",
56
+ "mem_admin_call",
57
+ "mem_write",
58
+ "mem_search",
59
+ "mem_associate",
60
+ "mem_read",
61
+ "mem_judge",
62
+ "mem_review",
63
+ "mem_pending",
64
+ "mem_resume",
65
+ "mem_handoff",
66
+ "mem_check",
67
+ "mem_dispatch",
68
+ "mem_receipt",
69
+ "mem_task",
70
+ "mem_scope",
71
+ "mem_import",
72
+ "mem_shadow",
73
+ "mem_prompt_inspector",
74
+ "mem_audit",
75
+ "mem_archive",
76
+ "mem_fetch_media",
77
+ "mem_graph_view",
78
+ "mem_graph_traverse",
79
+ "mem_parts",
80
+ "mem_compose",
81
+ "mem_affect_report",
82
+ "mem_affect_ingest",
83
+ "mem_crypto",
84
+ "mem_ledger",
85
+ "mem_health"
86
+ ]
87
+ }
88
+ },
89
+ "license": "MIT",
90
+ "scripts": {
91
+ "preflight": "node tools/preflight.mjs",
92
+ "verify": "node tools/verify-all.mjs",
93
+ "check": "node tools/preflight.mjs && node tools/verify-all.mjs",
94
+ "prepublishOnly": "node tools/preflight.mjs && node tools/verify-all.mjs"
95
+ },
96
+ "keywords": [
97
+ "deepseek-harness",
98
+ "dsh",
99
+ "dsh-plugin",
100
+ "cordis",
101
+ "memory",
102
+ "memory-layer",
103
+ "recall",
104
+ "audit"
105
+ ],
106
+ "repository": {
107
+ "type": "git",
108
+ "url": "git+https://github.com/z9134/dsh-sixlayer-memory.git"
109
+ },
110
+ "bugs": {
111
+ "url": "https://github.com/z9134/dsh-sixlayer-memory/issues"
112
+ },
113
+ "homepage": "https://github.com/z9134/dsh-sixlayer-memory#readme",
114
+ "publishConfig": {
115
+ "access": "public"
116
+ }
6
117
  }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * backfill-affect.mjs — 给存量记忆补情绪标签与重要性。
3
+ *
4
+ * 背景:情绪标注是 v7 才加的,之前的记录 affect_label 都是 NULL/neutral,
5
+ * 观测页的情绪分布和趋势因此没有历史数据。
6
+ *
7
+ * 安全:
8
+ * 1. 先 VACUUM INTO 备份整库(备份失败就中止)
9
+ * 2. 只改 affect_* 与 importance,不动 content/summary/status
10
+ * 3. 写一条 op=affect.backfill 的审计
11
+ * 4. --dry 只统计不写库
12
+ */
13
+ import fs from 'node:fs'
14
+ import path from 'node:path'
15
+ import MemoryStore from '../lib/memory/store.js'
16
+ import { analyzeAffect, initialImportance } from '../lib/memory/emotion.js'
17
+
18
+ const argv = process.argv.slice(2)
19
+ const dry = argv.includes('--dry')
20
+ const dataDir = argv.find((a) => !a.startsWith('--')) ?? 'D:/001/CH002/dsh-memory-data'
21
+
22
+ const store = new MemoryStore({ dataDir }).open()
23
+
24
+ // 1. 备份
25
+ const backupDir = path.join(dataDir, 'backup')
26
+ fs.mkdirSync(backupDir, { recursive: true })
27
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
28
+ const backupPath = path.join(backupDir, `affect-backfill-${stamp}.db`)
29
+ if (!dry) {
30
+ store.db.exec(`VACUUM INTO '${backupPath.replace(/\\/g, '/')}'`)
31
+ console.log('备份:' + backupPath + ' (' + fs.statSync(backupPath).size + ' bytes)')
32
+ }
33
+
34
+ // 2. 逐条重算
35
+ const rows = store.db
36
+ .prepare("SELECT record_id, layer, summary, content, affect_label FROM records WHERE status IN ('active','pending')")
37
+ .all()
38
+
39
+ const counts = { total: rows.length, changed: 0, neutral: 0, positive: 0, negative: 0, urgent: 0 }
40
+ const updates = []
41
+ for (const row of rows) {
42
+ const affect = analyzeAffect(`${row.summary ?? ''} ${row.content ?? ''}`)
43
+ const importance = initialImportance(affect, row.layer)
44
+ const same = row.affect_label === affect.label
45
+ if (same) {
46
+ if (affect.label === 'neutral') counts.neutral += 1
47
+ else counts[affect.label] += 1
48
+ continue
49
+ }
50
+ counts.changed += 1
51
+ counts[affect.label] = (counts[affect.label] ?? 0) + 1
52
+ updates.push({
53
+ record_id: row.record_id,
54
+ label: affect.label,
55
+ valence: affect.valence,
56
+ arousal: affect.arousal,
57
+ importance,
58
+ })
59
+ }
60
+
61
+ if (!dry && updates.length > 0) {
62
+ const stmt = store.db.prepare(
63
+ 'UPDATE records SET affect_label = ?, affect_valence = ?, affect_arousal = ?, importance = ?, updated_at = ? WHERE record_id = ?',
64
+ )
65
+ const now = new Date().toISOString()
66
+ store.db.exec('BEGIN')
67
+ try {
68
+ for (const u of updates) stmt.run(u.label, u.valence, u.arousal, u.importance, now, u.record_id)
69
+ store.db.exec('COMMIT')
70
+ } catch (error) {
71
+ store.db.exec('ROLLBACK')
72
+ throw error
73
+ }
74
+ store.record({
75
+ op: 'affect.backfill',
76
+ count: updates.length,
77
+ detail: counts,
78
+ })
79
+ }
80
+
81
+ console.log(JSON.stringify({ dry, ...counts }, null, 2))
82
+ store.close()
package/tools/eval.mjs ADDED
@@ -0,0 +1,88 @@
1
+ // eval.mjs — 固定测试集上的扫描器评测(P2)。
2
+ // 指标口径对齐 v3 方案 §6:报**工作点**上的误报率与检出率,不报 AUROC。
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { createHash } from 'node:crypto'
7
+ import { scan } from '../lib/memory/policy.js'
8
+
9
+ const TESTSET = path.join(path.dirname(fileURLToPath(import.meta.url)), 'testset-v1.json')
10
+
11
+ export function loadTestset(file = TESTSET) {
12
+ const raw = fs.readFileSync(file, 'utf8')
13
+ const data = JSON.parse(raw)
14
+ // 构造方式哈希:同一份样本集合任何时候都能对上号
15
+ const canonical = JSON.stringify(data.samples.map((s) => [s.id, s.level, s.text]))
16
+ const hash = createHash('sha256').update(canonical, 'utf8').digest('hex').slice(0, 16)
17
+ return { ...data, hash }
18
+ }
19
+
20
+ /**
21
+ * 跑评测。
22
+ * @returns {{testset:{version,hash,count}, normal:{total,flagged,fpr}, levels:object, overall:object, scanners:object}}
23
+ */
24
+ export function evaluateScanners(file = TESTSET) {
25
+ const set = loadTestset(file)
26
+ const byLevel = {}
27
+ const scannerHits = {}
28
+ let normalTotal = 0
29
+ let normalFlagged = 0
30
+
31
+ for (const sample of set.samples) {
32
+ const result = scan(sample.text)
33
+ const flagged = result.injection.length > 0
34
+ const level = sample.level || 'normal'
35
+ if (!byLevel[level]) byLevel[level] = { total: 0, caught: 0 }
36
+ byLevel[level].total += 1
37
+ if (flagged) byLevel[level].caught += 1
38
+ if (level === 'normal') {
39
+ normalTotal += 1
40
+ if (flagged) normalFlagged += 1
41
+ }
42
+ for (const hit of result.hits || []) {
43
+ scannerHits[hit.id] = (scannerHits[hit.id] || 0) + 1
44
+ }
45
+ }
46
+
47
+ const levels = {}
48
+ for (const [level, v] of Object.entries(byLevel)) {
49
+ levels[level] = { total: v.total, caught: v.caught, rate: v.total ? round(v.caught / v.total) : 0 }
50
+ }
51
+
52
+ const attacks = (levels.L1?.total || 0) + (levels.L2?.total || 0) + (levels.L3?.total || 0)
53
+ const caught = (levels.L1?.caught || 0) + (levels.L2?.caught || 0) + (levels.L3?.caught || 0)
54
+ const precisionDen = caught + normalFlagged
55
+
56
+ return {
57
+ testset: { version: set.version, hash: set.hash, count: set.samples.length },
58
+ normal: { total: normalTotal, flagged: normalFlagged, fpr: normalTotal ? round(normalFlagged / normalTotal) : 0 },
59
+ levels,
60
+ overall: {
61
+ attacks,
62
+ caught,
63
+ recall: attacks ? round(caught / attacks) : 0,
64
+ precision: precisionDen ? round(caught / precisionDen) : 0,
65
+ },
66
+ scanners: scannerHits,
67
+ }
68
+ }
69
+
70
+ function round(x) {
71
+ return Math.round(x * 1000) / 1000
72
+ }
73
+
74
+ // CLI
75
+ if (process.argv[1] && process.argv[1].endsWith('eval.mjs')) {
76
+ const r = evaluateScanners()
77
+ console.log(`测试集 ${r.testset.version} 样本 ${r.testset.count} 构造哈希 ${r.testset.hash}`)
78
+ console.log('')
79
+ console.log('级别 样本 检出 检出率')
80
+ for (const [level, v] of Object.entries(r.levels)) {
81
+ console.log(`${level.padEnd(6)} ${String(v.total).padStart(4)} ${String(v.caught).padStart(5)} ${(v.rate * 100).toFixed(1)}%`)
82
+ }
83
+ console.log('')
84
+ console.log(`误报率 FPR = ${(r.normal.fpr * 100).toFixed(1)}%(${r.normal.flagged}/${r.normal.total})`)
85
+ console.log(`整体 recall = ${(r.overall.recall * 100).toFixed(1)}% precision = ${(r.overall.precision * 100).toFixed(1)}%`)
86
+ console.log('')
87
+ console.log('各 scanner 命中次数:', JSON.stringify(r.scanners))
88
+ }
package/tools/p1.mjs ADDED
@@ -0,0 +1,108 @@
1
+ // P1 回归:schema v4 迁移 / 闸门公理 / 注入组合检查 / 未验证只给指针。
2
+ // 运行:node tools/p1.mjs (不需要 DSH;自己造临时库,不碰真实数据)
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { DatabaseSync } from 'node:sqlite'
7
+ import MemoryStore from '../lib/memory/store.js'
8
+ import { selectSnapshot, pickWithComposition, buildSnapshotText, Injector } from '../lib/memory/inject.js'
9
+
10
+ let pass = 0
11
+ let fail = 0
12
+ function check(name, ok, detail = '') {
13
+ if (ok) {
14
+ pass++
15
+ console.log(' PASS ' + name)
16
+ } else {
17
+ fail++
18
+ console.log(' FAIL ' + name + (detail ? ' ' + detail : ''))
19
+ }
20
+ }
21
+
22
+ // ---------- 1. 真实库副本:v3 → v4 迁移 ----------
23
+ const realDb = 'D:/001/CH002/dsh-memory-data/db/memory.db'
24
+ if (fs.existsSync(realDb)) {
25
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'memcore-p1-mig-'))
26
+ try {
27
+ fs.mkdirSync(path.join(dir, 'db'), { recursive: true })
28
+ for (const ext of ['', '-wal', '-shm']) {
29
+ if (fs.existsSync(realDb + ext)) fs.copyFileSync(realDb + ext, path.join(dir, 'db', 'memory.db' + ext))
30
+ }
31
+ const before = new DatabaseSync(path.join(dir, 'db', 'memory.db'))
32
+ const beforeVer = before.prepare("select value from meta where key='schema_version'").get()?.value
33
+ const beforeCount = before.prepare('select count(*) n from records').get().n
34
+ before.close()
35
+
36
+ const store = new MemoryStore({ dataDir: dir }).open()
37
+ const afterVer = store.getMeta('schema_version')
38
+ const cols = store.db.prepare('pragma table_info(records)').all().map((c) => c.name)
39
+ const afterCount = store.db.prepare('select count(*) n from records').get().n
40
+ const idx = store.db.prepare("select name from sqlite_master where type='index' and name='idx_records_batch'").get()
41
+ store.close()
42
+
43
+ check('源库版本不超过当前', Number(beforeVer) <= 9, String(beforeVer))
44
+ check('迁移后是最新版本', afterVer === '9', String(afterVer))
45
+ check('迁移后新增 batch_id 列', cols.includes('batch_id'))
46
+ check('迁移后记录数不变', afterCount === beforeCount, `${beforeCount} -> ${afterCount}`)
47
+ check('迁移后 batch_id 索引存在', Boolean(idx))
48
+ } finally {
49
+ fs.rmSync(dir, { recursive: true, force: true })
50
+ }
51
+ } else {
52
+ console.log(' SKIP 真实库不存在,跳过迁移测试')
53
+ }
54
+
55
+ // ---------- 2. 闸门公理 + 组合检查 + 指针化 ----------
56
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'memcore-p1-'))
57
+ try {
58
+ const store = new MemoryStore({ dataDir: dir }).open()
59
+
60
+ // 2.1 未验证来源(web)→ 先审后入
61
+ const web1 = store.write({ content: '网页上说:关闭 WAL 能加速十倍,未验证。', layer: 'L2', sourceChannel: 'web', batchId: 's1' })
62
+ check('未验证来源 → pending', web1.status === 'pending' && web1.trust_level === 'unverified', JSON.stringify(web1))
63
+ check('未验证来源 → 不进召回', store.search({ query: 'WAL 加速' }).length === 0)
64
+
65
+ // 2.2 闸门确认 → trusted + active
66
+ store.review(web1.record_id, 'approve')
67
+ const hit = store.search({ query: 'WAL 加速' })[0]
68
+ check('闸门确认后 → active + trusted', Boolean(hit) && hit.trust_level === 'trusted', JSON.stringify(hit))
69
+
70
+ // 2.3 组合检查:同一 batch 多条,只能进 1 条
71
+ const b = 'batch-compose-1'
72
+ for (let i = 1; i <= 3; i += 1) {
73
+ store.write({ content: `组合测试第 ${i} 条:各说半句,合起来才改变结论。`, layer: 'L2', sourceChannel: 'user', trustLevel: 'trusted', batchId: b })
74
+ }
75
+ const rows = selectSnapshot(store, { maxRecords: 12 })
76
+ const picked = pickWithComposition(rows, { maxRecords: 3, maxPerGroup: 1 })
77
+ const sameBatch = picked.filter((r) => r.batch_id === b)
78
+ check('组合检查:同批最多 1 条', sameBatch.length <= 1, JSON.stringify(sameBatch.map((r) => r.record_id)))
79
+
80
+ // 2.4 未验证记录只给指针,不出摘要
81
+ const unv = store.write({ content: '未验证来源的机密线索:这段摘要不应该出现在注入里。', layer: 'L2', sourceChannel: 'user', trustLevel: 'unverified', batchId: 'b-unv' })
82
+ const allRows = selectSnapshot(store, { maxRecords: 20 })
83
+ const unvRow = allRows.find((r) => r.record_id === unv.record_id)
84
+ const text = buildSnapshotText([unvRow], { maxChars: 500 })
85
+ check('未验证记录:出现指针行', text.includes(unv.record_id))
86
+ check('未验证记录:不出现摘要', !text.includes('这段摘要不应该出现'))
87
+ check('未验证记录:标注仅指针', text.includes('仅指针'))
88
+
89
+ // 2.5 预算:超长文本被截断
90
+ const long = buildSnapshotText(allRows, { maxChars: 300 })
91
+ check('预算:注入长度不超过上限', long.length <= 300, String(long.length))
92
+
93
+ // 2.6 Injector 端到端:无内容返回空串
94
+ const injector = new Injector({ store, maxRecords: 3, maxChars: 500 })
95
+ const t1 = injector.text()
96
+ check('注入器:有内容时返回围栏块', t1.includes('dsh-memory-core:inject:begin'))
97
+ store.db.prepare("update records set status='archived'").run()
98
+ const t2 = injector.text()
99
+ check('注入器:无内容时返回空串', t2 === '')
100
+
101
+ store.close()
102
+ } finally {
103
+ fs.rmSync(dir, { recursive: true, force: true })
104
+ }
105
+
106
+ console.log(`\nP1 ${fail === 0 ? 'OK' : 'FAILED'} pass=${pass} fail=${fail}`)
107
+ if (fail > 0) process.exitCode = 1
108
+
package/tools/p10.mjs ADDED
@@ -0,0 +1,36 @@
1
+ /** p10:B4 情绪趋势(近 14 天按天聚合) */
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import MemoryStore from '../lib/memory/store.js'
6
+
7
+ let pass = 0, fail = 0
8
+ function ok(name, cond, extra = '') {
9
+ if (cond) { pass++; console.log(' ok ' + name) } else { fail++; console.log(' FAIL ' + name + (extra ? ' :: ' + extra : '')) }
10
+ }
11
+
12
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'memcore-p10-'))
13
+ const store = new MemoryStore({ dataDir: dir }).open()
14
+ store.write({ content: '插件崩溃了,一直报错,紧急!', layer: 'L2', sourceChannel: 'user', trustLevel: 'trusted' })
15
+ store.write({ content: '修好了,测试全部通过,感谢', layer: 'L2', sourceChannel: 'user', trustLevel: 'trusted' })
16
+ store.write({ content: '今天的会议改到下午三点', layer: 'L2', sourceChannel: 'user', trustLevel: 'trusted' })
17
+
18
+ const trendDays = 14
19
+ const trendSince = new Date(Date.now() - (trendDays - 1) * 24 * 3600 * 1000).toISOString().slice(0, 10)
20
+ const raw = store.db.prepare(
21
+ `SELECT substr(created_at, 1, 10) AS day, COUNT(*) AS n,
22
+ SUM(CASE WHEN affect_label IN ('negative','urgent') THEN 1 ELSE 0 END) AS bad,
23
+ SUM(CASE WHEN affect_label = 'positive' THEN 1 ELSE 0 END) AS good
24
+ FROM records WHERE status='active' AND substr(created_at,1,10) >= ? GROUP BY day`,
25
+ ).all(trendSince)
26
+ const today = new Date().toISOString().slice(0, 10)
27
+ const row = raw.find((r) => r.day === today)
28
+ ok('今天有数据', Boolean(row), JSON.stringify(raw))
29
+ ok('今天 3 条', row?.n === 3, String(row?.n))
30
+ ok('负面 1 条', row?.bad === 1, String(row?.bad))
31
+ ok('正面 1 条', row?.good === 1, String(row?.good))
32
+ ok('趋势窗口 14 天', trendDays === 14)
33
+
34
+ store.close()
35
+ console.log(`\nP10 ${fail === 0 ? 'OK' : 'FAIL'} pass=${pass} fail=${fail}`)
36
+ process.exit(fail === 0 ? 0 : 1)
package/tools/p11.mjs ADDED
@@ -0,0 +1,51 @@
1
+ /** p11:QQ 桥(命令解析、白名单、写入闸门) */
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import MemoryStore from '../lib/memory/store.js'
6
+ import { QqBridge, parseCommand, segmentsToText } from '../lib/memory/qq.js'
7
+
8
+ let pass = 0, fail = 0
9
+ function ok(name, cond, extra = '') {
10
+ if (cond) { pass++; console.log(' ok ' + name) } else { fail++; console.log(' FAIL ' + name + (extra ? ' :: ' + extra : '')) }
11
+ }
12
+
13
+ // 0 纯函数
14
+ ok('中文记命令', JSON.stringify(parseCommand('/记 你好')) === JSON.stringify({ cmd: 'remember', arg: '你好' }))
15
+ ok('英文 search', parseCommand('/search 崩溃')?.cmd === 'search')
16
+ ok('非命令返回 null', parseCommand('你好') === null)
17
+ ok('未知命令', parseCommand('/xyz')?.cmd === 'unknown')
18
+ ok('帮助别名', parseCommand('/?')?.cmd === 'help')
19
+ const seg = segmentsToText([{ type: 'at', data: { qq: '1' } }, { type: 'text', data: { text: ' /记 你好' } }])
20
+ ok('消息段拼接', seg.includes('/记 你好'), seg)
21
+
22
+ // 1 命令处理
23
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'memcore-p11-'))
24
+ const store = new MemoryStore({ dataDir: dir }).open()
25
+ const bridge = new QqBridge({ store, config: { enabled: true, allowedUsers: ['123'] } })
26
+
27
+ const r1 = await bridge.handleCommand(parseCommand('/记 明天下午三点开会'), { userId: '123' })
28
+ ok('记命令返回已记下', r1.includes('已记下') || r1.includes('已存在'), r1)
29
+ const row = store.db.prepare("SELECT status, pending_review, source_channel FROM records ORDER BY created_at DESC LIMIT 1").get()
30
+ ok('QQ 写入走未验证闸门', row.status === 'pending' && row.pending_review === 1, JSON.stringify(row))
31
+ ok('来源记为 qq', row.source_channel === 'qq', row.source_channel)
32
+
33
+ const r2 = await bridge.handleCommand(parseCommand('/搜 开会'), { userId: '123' })
34
+ ok('搜索有回复', r2.includes('搜到') || r2.includes('没搜到'), r2)
35
+ const r3 = await bridge.handleCommand(parseCommand('/状态'), {})
36
+ ok('状态含记录数', r3.includes('记录'), r3)
37
+ const r4 = await bridge.handleCommand(parseCommand('/联想 开会'), {})
38
+ ok('联想有回复', r4.includes('联想到') || r4.includes('没想到'), r4)
39
+ const r5 = await bridge.handleCommand(parseCommand('/帮助'), {})
40
+ ok('帮助列出命令', r5.includes('/记'), r5)
41
+
42
+ // 2 白名单:未授权用户被忽略且不写库
43
+ const before = store.db.prepare('SELECT COUNT(*) n FROM records').get().n
44
+ await bridge._handleEvent({ post_type: 'message', message_type: 'private', self_id: '999', user_id: '888', message: [{ type: 'text', data: { text: '/记 不该写进去' } }] })
45
+ const after = store.db.prepare('SELECT COUNT(*) n FROM records').get().n
46
+ ok('白名单外不写库', before === after, `${before} -> ${after}`)
47
+ ok('白名单外计数 ignored', bridge.stats.ignored >= 1, String(bridge.stats.ignored))
48
+
49
+ store.close()
50
+ console.log(`\nP11 ${fail === 0 ? 'OK' : 'FAIL'} pass=${pass} fail=${fail}`)
51
+ process.exit(fail === 0 ? 0 : 1)