dsh-memory-huixiang 0.1.1 → 0.1.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.
- package/README.md +3 -3
- package/index.js +57 -18
- package/lib/autodream.js +9 -2
- package/lib/dream.js +9 -5
- package/lib/prompt.js +3 -1
- package/lib/recall.js +4 -1
- package/lib/store.js +78 -30
- package/lib/stream.js +42 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -44,7 +44,7 @@ DSH 里你可以开很多窗口、叫很多分身干活。普通对话的上下
|
|
|
44
44
|
问一件库里没有的事,它会说「我这边没记录」,而不是编一个听起来对的答案。宁可弃权也不猜,这条有单独的测试守着。
|
|
45
45
|
|
|
46
46
|
**它记得住「为什么」。**
|
|
47
|
-
|
|
47
|
+
不只记「你住在哪里」,还记这条是打哪来的(你亲口说的 / 它自己推的)、什么条件下会变、哪天失效。两条说法打架就并排放着,标一个冲突,不硬圆。
|
|
48
48
|
|
|
49
49
|
**换个聊天软件,它也认得你。**
|
|
50
50
|
同一份记忆库,飞书、QQ、B站私信、网页聊天、手机 App 都读它。你在飞书随口提过的事,换到 QQ 里再问,它照样答得上来——记忆只存一份,不在每个渠道各记一遍。
|
|
@@ -155,7 +155,7 @@ dsh plugin --profile web add link:~/.dsh/plugin-src/dsh-memory-huixiang
|
|
|
155
155
|
以下命令**只在源码树里跑**——npm 包不带 `test/`、`demo/`、`eval/`(包只含 `index.js`、`lib/`、`cordis.patch.yml`、`README.md`、`NOTICE`、`LICENSE`)。
|
|
156
156
|
|
|
157
157
|
```bash
|
|
158
|
-
node --test #
|
|
158
|
+
node --test # 231 个测试全过
|
|
159
159
|
node demo/simulate.mjs # 10 项演示,用临时库,不碰真库
|
|
160
160
|
node eval/run.mjs --golden <你的题库.jsonl> --dir <你的库目录>
|
|
161
161
|
```
|
|
@@ -173,7 +173,7 @@ node eval/run.mjs --golden <你的题库.jsonl> --dir <你的库目录>
|
|
|
173
173
|
- 召回是词面驱动的:换个说法(「家在何方」对「住哪」)可能翻不到。
|
|
174
174
|
- 单机单进程假设:多进程靠 `O_EXCL` 文件锁,不是分布式锁。
|
|
175
175
|
- `stream.jsonl` 会存每一轮原话(单条截断 4000 字)。这是特性也是风险,见「隐私」。
|
|
176
|
-
-
|
|
176
|
+
- 231 个测试覆盖的是核心路径,不是全覆盖。
|
|
177
177
|
|
|
178
178
|
## 隐私
|
|
179
179
|
|
package/index.js
CHANGED
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
* ⑥ 人格连续(BV1dDxC67Ep3):底色 + 当前状态分开存,状态变更留史
|
|
11
11
|
* ⑦ 关系细节(BV1dDxC67Ep3):知识/经历分开,矛盾保留,来源与有效期都标
|
|
12
12
|
*/
|
|
13
|
-
import { HippocampusStore, DEFAULT_DATA_DIR } from './lib/store.js'
|
|
14
|
-
import { hotForInjection, injectionBriefs, recallByCue, shouldRecall, keywordFallback, firstLine, tokenize, answerable, entityGate, hopNeighbors } from './lib/recall.js'
|
|
15
|
-
import { occasionDays, streamLeads } from './lib/stream.js'
|
|
13
|
+
import { HippocampusStore, DEFAULT_DATA_DIR, isSafeId } from './lib/store.js'
|
|
14
|
+
import { hotForInjection, injectionBriefs, recallByCue, shouldRecall, keywordFallback, firstLine, tokenize, answerable, entityGate, hopNeighbors, isDead } from './lib/recall.js'
|
|
15
|
+
import { localDay, occasionDays, streamLeads } from './lib/stream.js'
|
|
16
16
|
import { dreamPass } from './lib/dream.js'
|
|
17
17
|
import { maybeDream } from './lib/autodream.js'
|
|
18
18
|
import { CONTEXT_NAME, CONTEXT_ORDER, POLICY_NAME, POLICY_TEXT, SECTION_ORDER, renderSnapshot } from './lib/prompt.js'
|
|
@@ -37,7 +37,7 @@ const SOURCE_TYPES = new Set(['owner-said', 'evidence-found', 'no-evidence'])
|
|
|
37
37
|
const boundaryDefaults = (src, condition, validUntil) => {
|
|
38
38
|
if (condition || validUntil) return { condition, validUntil, note: '' }
|
|
39
39
|
if (src === 'owner') return { condition: '主人改口或情况变化前一直算数', validUntil, note: '没写边界:已按「主人亲口、改口前有效」记下' }
|
|
40
|
-
const until =
|
|
40
|
+
const until = localDay(Date.now() + 30 * 86_400_000)
|
|
41
41
|
return { condition, validUntil: until, note: `没写边界:已按临时情报处理(${until} 到期)` }
|
|
42
42
|
}
|
|
43
43
|
|
|
@@ -110,22 +110,53 @@ function extractText(payload, depth = 0) {
|
|
|
110
110
|
return ''
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
+
/**
|
|
114
|
+
* heat 配置归一(2026-11-21 B8 修正):
|
|
115
|
+
* - 只认有限数字;
|
|
116
|
+
* - 少数键的 0 有明确语义(禁加成 / 立即冷 / 禁地板 / 不去重),其余键必须 > 0;
|
|
117
|
+
* - 不认识的键打一行 warn —— 拼错 halfLifeDayz 不该静默无效。
|
|
118
|
+
*/
|
|
119
|
+
export function normalizeHeat(input) {
|
|
120
|
+
const heat = { ...DEFAULT_HEAT }
|
|
121
|
+
if (!input || typeof input !== 'object') return heat
|
|
122
|
+
const ZERO_OK = new Set(['rehearseBoost', 'coldAfterDays', 'floorWeight', 'dedupeWindowMs'])
|
|
123
|
+
for (const [k, v] of Object.entries(input)) {
|
|
124
|
+
if (!Object.prototype.hasOwnProperty.call(DEFAULT_HEAT, k)) {
|
|
125
|
+
console.warn(`[cyber-hippocampus] 不认识的 heat 配置键:${k}(可用:${Object.keys(DEFAULT_HEAT).join(', ')})`)
|
|
126
|
+
continue
|
|
127
|
+
}
|
|
128
|
+
if (typeof v !== 'number' || !Number.isFinite(v)) {
|
|
129
|
+
console.warn(`[cyber-hippocampus] heat.${k} 不是有限数字,已忽略`)
|
|
130
|
+
continue
|
|
131
|
+
}
|
|
132
|
+
if (v < 0 || (v === 0 && !ZERO_OK.has(k))) {
|
|
133
|
+
console.warn(`[cyber-hippocampus] heat.${k}=${v} 不合法,已忽略`)
|
|
134
|
+
continue
|
|
135
|
+
}
|
|
136
|
+
heat[k] = v
|
|
137
|
+
}
|
|
138
|
+
return heat
|
|
139
|
+
}
|
|
140
|
+
|
|
113
141
|
export async function apply(ctx, config = {}) {
|
|
114
142
|
const dataDir = clean(config.dataDir) || DEFAULT_DATA_DIR
|
|
115
|
-
const heat =
|
|
116
|
-
|
|
117
|
-
const
|
|
143
|
+
const heat = normalizeHeat(config.heat)
|
|
144
|
+
// 这几个键的 0 有语义(0 行、0 条、不冷却),负数与 NaN 一律回退默认(2026-11-21 #11/#34)。
|
|
145
|
+
const countOr = (v, dflt) => (Number.isSafeInteger(v) && v >= 0 ? v : dflt)
|
|
146
|
+
const chainTailLines = countOr(config.chainTailLines, 12)
|
|
147
|
+
const hotLimit = countOr(config.hotLimit, 3)
|
|
118
148
|
// 折叠日志路径:config.compressionLog 优先;留空则走 lib/prompt.js 的 env/默认值。
|
|
119
149
|
const compressionLog = clean(config.compressionLog) || ''
|
|
120
150
|
// 便签条数(「大概记得」区):主人 2026-11-14 允许适当多带,默认 20 条。
|
|
121
|
-
const briefLimit =
|
|
151
|
+
const briefLimit = countOr(config.briefLimit, 20)
|
|
122
152
|
// 目录那一层的条数上限(2026-11-19 主人定 A 案):原来写死 200,179 张就把 9000 字符预算吃到 98.7%;默认收到 130,余量回到 ~900。
|
|
123
|
-
const catalogLimit =
|
|
153
|
+
const catalogLimit = countOr(config.catalogLimit, 130)
|
|
124
154
|
// 按量做梦(2026-11-12):不等定时器,stream 攒够行数就整理一次。可在配置里关。
|
|
125
155
|
const autoDream = {
|
|
126
156
|
enabled: config?.autoDream?.enabled !== false,
|
|
127
|
-
|
|
128
|
-
|
|
157
|
+
// everyLines 不能是 0:那样每轮都梦、每轮扫全库。cooldownMs=0 合法(测试与调试用)。
|
|
158
|
+
everyLines: Number.isSafeInteger(config?.autoDream?.everyLines) && config.autoDream.everyLines > 0 ? config.autoDream.everyLines : 20,
|
|
159
|
+
cooldownMs: countOr(config?.autoDream?.cooldownMs, 3_600_000),
|
|
129
160
|
dryRun: config?.autoDream?.dryRun === true,
|
|
130
161
|
}
|
|
131
162
|
const store = new HippocampusStore(dataDir, heat)
|
|
@@ -151,6 +182,11 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
|
|
|
151
182
|
if (lines.length) { try { lastAt = String(JSON.parse(lines[lines.length - 1]).at || '') } catch { /* 坏行就当没记录 */ } }
|
|
152
183
|
if (lastAt.startsWith(todayStamp)) return
|
|
153
184
|
execFile('bash', [HEALTH_SCRIPT], { timeout: 180_000 }, (err, stdout) => {
|
|
185
|
+
if (err && (err.code === 'ENOENT' || err.code === 'EACCES')) {
|
|
186
|
+
// Windows 默认没有 bash:这不是「体检失败」,是这台机器上根本没这条命令(2026-11-21 #9)。
|
|
187
|
+
console.log('[cyber-hippocampus] 体检跳过:找不到可执行的 bash。Windows 用户可把 config.healthScript 指向一个 node 脚本。', err.message)
|
|
188
|
+
return
|
|
189
|
+
}
|
|
154
190
|
const head = String(stdout || '').trim().split('\n')[0]
|
|
155
191
|
console.log('[cyber-hippocampus] 体检补跑:', err ? `失败 ${err.message}` : head)
|
|
156
192
|
})
|
|
@@ -213,8 +249,8 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
|
|
|
213
249
|
const 本次sourceType = SOURCE_TYPES.has(args.source_type) ? args.source_type : undefined
|
|
214
250
|
// id 直接进文件名,别让它穿出 notes 目录。
|
|
215
251
|
const wantId = clean(args.id)
|
|
216
|
-
|
|
217
|
-
if (wantId
|
|
252
|
+
// 与 store 层同口径(含 Unicode,归纳卡 id 形如 ins-体检-abc123)。两层白名单打架会让归纳卡永远续写不了(2026-11-21 B7)。
|
|
253
|
+
if (wantId && !isSafeId(wantId)) return { ok: false, error: 'id 只能用汉字、字母、数字和 . _ -,且不能包含 ..' }
|
|
218
254
|
// 幂等键:只认「同一调用方同一份输入」。正文不做归一化——归一化会把「差一个标点」也算同一句,
|
|
219
255
|
// 那是去重该管的边界,不是重试该管的。
|
|
220
256
|
// 幂等键=「同一次请求」的指纹:所有会改变写入结果的入参都进去。
|
|
@@ -362,7 +398,7 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
|
|
|
362
398
|
if (增量来源) body = `补:${增量来源.title || 增量来源.id}(${增量来源.id})\n${body}`
|
|
363
399
|
// 2026-11-14 审查(严重):按 id 续写会把旧卡的 superseded_by 原样带回来 —— 返回 ok,卡却永远查不到、也不注入。
|
|
364
400
|
// 续写的意思就是「这张卡还活着」:显式清死因;旧的有效期已经过期、这次又没给新的,也一并清掉,并在返回里说明。
|
|
365
|
-
const todayStr =
|
|
401
|
+
const todayStr = localDay(Date.now())
|
|
366
402
|
const 旧死因 = prev?.superseded_by ? `已被 ${prev.superseded_by} 接替` : ''
|
|
367
403
|
const 旧已过期 = prev?.valid_until && prev.valid_until < todayStr ? `旧有效期 ${prev.valid_until} 已过` : ''
|
|
368
404
|
const 复活 = Boolean(旧死因 || 旧已过期)
|
|
@@ -388,7 +424,7 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
|
|
|
388
424
|
// 泛标题会在 occasionDays 里被 df 过滤掉(结果=0 个场合 → 降级,这是正确方向)。
|
|
389
425
|
const { days } = occasionDays(store, clean(args.title) || firstLine(body))
|
|
390
426
|
if (days.length < 3) {
|
|
391
|
-
nextValidUntil =
|
|
427
|
+
nextValidUntil = localDay(Date.now() + 30 * 86_400_000)
|
|
392
428
|
场合说明 = `样本不足(原话里只见过 ${days.length} 个场合 < 3),先当临时情报,${nextValidUntil} 到期;多碰到几次再升成长期`
|
|
393
429
|
}
|
|
394
430
|
}
|
|
@@ -542,7 +578,8 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
|
|
|
542
578
|
if (!tail4.has(t)) tail4.set(t, [])
|
|
543
579
|
tail4.get(t).push(id)
|
|
544
580
|
}
|
|
545
|
-
|
|
581
|
+
// 判死跟 cue 路径同口径:valid_until 写纯日期时按本地日界算,别拿 Date.parse 当 UTC 零点(2026-11-21 B3)。
|
|
582
|
+
const isDeadCard = (c) => isDead(c, Date.now())
|
|
546
583
|
const picked = []
|
|
547
584
|
const missed = []
|
|
548
585
|
const ambiguous = []
|
|
@@ -591,7 +628,8 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
|
|
|
591
628
|
// 这是手动翻库(本鲸自己决定要查),不该被「像不像在翻旧事」的门控挡住:
|
|
592
629
|
// 原来单字线索(猫/雨/酒)一律被拦,等于查不了。门控只留给自动检索那条路。
|
|
593
630
|
|
|
594
|
-
|
|
631
|
+
// limit 传字符串/NaN 时 Math.trunc 得 NaN → slice(0,NaN)=[] → 命中被吞成 not_found(2026-11-21 B9)。
|
|
632
|
+
const limit = Math.min(Math.max(Math.trunc(Number(args.limit) || 3), 1), 10)
|
|
595
633
|
const opts = { limit, includeSuperseded: args.includeSuperseded === true }
|
|
596
634
|
const runs = cues.map((c) => ({ cue: c, r: recallByCue(store, c, opts) }))
|
|
597
635
|
// 合并:同一张卡只留分数最高那次,并记住是哪句说法捞到的(记账要用真的那句)。
|
|
@@ -647,7 +685,8 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
|
|
|
647
685
|
let gateNote = ''
|
|
648
686
|
if (status !== 'not_found' && items.length) {
|
|
649
687
|
const fullTop = store.get(items[0].id) || items[0]
|
|
650
|
-
|
|
688
|
+
// 多说法时闸要核「真正捞到头名的那句」,核 cues[0] 会把第二句捞到的卡误弃权(2026-11-21 B10)。
|
|
689
|
+
const g = answerable(String(topRun?.cue ?? args.cue ?? cues[0] ?? ''), [fullTop])
|
|
651
690
|
if (!g.ok) {
|
|
652
691
|
status = 'not_found'
|
|
653
692
|
items.length = 0
|
package/lib/autodream.js
CHANGED
|
@@ -18,7 +18,14 @@ export function maybeDream(store, opts = {}, now = Date.now()) {
|
|
|
18
18
|
try {
|
|
19
19
|
const total = store.streamSize()
|
|
20
20
|
const st = store.dreamState()
|
|
21
|
-
|
|
21
|
+
// stream.jsonl 被删/重建(README 教用户删原话的隐私操作)后行数水位失效。
|
|
22
|
+
// 判据两条,任一成立就基线归零,否则自动做梦会停摆(2026-11-21 B6):
|
|
23
|
+
// ① 现在比上次梦时还少;② 第一行不是上次梦时那一行了(比首行摘要,不看时钟先后)。
|
|
24
|
+
// 为什么不用「首行时间比上次梦新」:同毫秒重建会漏判,首行时间戳落在未来会永久误判,两种都会
|
|
25
|
+
// 让水位失效、自动做梦停摆或空转(2026-11-21 千问第二轮 B6R/N2)。
|
|
26
|
+
const firstKey = store.streamFirstKey?.() || ''
|
|
27
|
+
const reset = total < (Number(st?.line) || 0) || Boolean(st?.firstKey && firstKey && st.firstKey !== firstKey)
|
|
28
|
+
const last = reset ? 0 : (Number(st?.line) || 0)
|
|
22
29
|
const fresh = total - last
|
|
23
30
|
if (fresh < cfg.everyLines) return { ran: false, reason: 'below-threshold', fresh, total, last }
|
|
24
31
|
const lastAt = st?.at ? Date.parse(st.at) : 0
|
|
@@ -27,7 +34,7 @@ export function maybeDream(store, opts = {}, now = Date.now()) {
|
|
|
27
34
|
}
|
|
28
35
|
const result = dreamPass(store, { dryRun: cfg.dryRun })
|
|
29
36
|
// 先梦再记账:梦崩了就把记忆点留着,下次还会重来,不会「以为梦过了」。
|
|
30
|
-
store.setDreamState({ line: total, at: new Date(now).toISOString(), wrote: result.wrote })
|
|
37
|
+
store.setDreamState({ line: total, at: new Date(now).toISOString(), wrote: result.wrote, firstKey })
|
|
31
38
|
return { ran: true, fresh, total, ...result }
|
|
32
39
|
} catch (err) {
|
|
33
40
|
return { ran: false, reason: 'error', error: String(err?.message || err) }
|
package/lib/dream.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// 梦游整理(BV1dDxC67Ep3):闲下来时按主题把散的事件归成一句话,
|
|
2
2
|
// 但**保留来源、保留矛盾**,不把两条冲突的记忆强行合成一个说法。
|
|
3
3
|
// 这里故意不调模型:先把结构跑通,谁来写「概括」以后可以换成本鲸自己。
|
|
4
|
-
import { tokenize } from './recall.js'
|
|
4
|
+
import { tokenize, isDead } from './recall.js'
|
|
5
5
|
|
|
6
6
|
const DAY = 86_400_000
|
|
7
7
|
|
|
@@ -101,7 +101,8 @@ export function dreamPass(store, opts = {}) {
|
|
|
101
101
|
// 全库只扫一次(11-14 审查:以前每个 tag 组都 store.all(),真库 17 次全库扫、阻塞 1.9–5.9 秒)。
|
|
102
102
|
const allCards = store.all()
|
|
103
103
|
const insightsAll = allCards.filter((c) => c.kind === 'insight')
|
|
104
|
-
|
|
104
|
+
// 死卡不进归纳:被接替/已过期的旧说法若经 insight 复活,等于绕过全部死卡闸门(2026-11-21 B2)。
|
|
105
|
+
const cards = allCards.filter((c) => c.kind === 'experience' && !isDead(c, now) && c.created && now - Date.parse(c.created) <= lookbackDays * DAY)
|
|
105
106
|
|
|
106
107
|
const groups = new Map()
|
|
107
108
|
for (const card of cards) {
|
|
@@ -179,9 +180,12 @@ export function dreamPass(store, opts = {}) {
|
|
|
179
180
|
skipped.push({ tag, sim: Number(twin.sim.toFixed(2)), idOverlap: Number(twin.idOverlap.toFixed(2)), twin: twin.c.id })
|
|
180
181
|
continue
|
|
181
182
|
}
|
|
182
|
-
if (!dryRun)
|
|
183
|
-
|
|
184
|
-
|
|
183
|
+
if (!dryRun) {
|
|
184
|
+
store.put(insight)
|
|
185
|
+
// 这一趟新写的也要进快照,否则同一趟里后面的标签组撞不出孪生,会再写一张同质卡(13:20 复核实测 0.951)。
|
|
186
|
+
// dryRun 下没落盘,就不该进快照(2026-11-21 #37)。
|
|
187
|
+
insightsAll.push(insight)
|
|
188
|
+
}
|
|
185
189
|
insights.push({ tag, from: ids, id: insight.id, conflicts })
|
|
186
190
|
}
|
|
187
191
|
return { wrote: insights.length, insights, skipped }
|
package/lib/prompt.js
CHANGED
|
@@ -21,7 +21,9 @@ export function lastCompression(logPath = COMPRESSION_LOG) {
|
|
|
21
21
|
const last = lines[lines.length - 1]
|
|
22
22
|
const stamp = last.match(/(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2})/)
|
|
23
23
|
if (stamp) {
|
|
24
|
-
|
|
24
|
+
// 按本机本地时区解析:压缩日志里的时间戳是写日志那台机器的本地时间。
|
|
25
|
+
// 原来硬编码 +08:00,人不在东八区就会偏 8 小时,把「刚折叠过」判成好几天前(2026-11-21 B15)。
|
|
26
|
+
const t = Date.parse(`${stamp[1]}T${stamp[2]}:00`)
|
|
25
27
|
if (Number.isFinite(t) && Date.now() - t > 24 * 3600 * 1000) return ''
|
|
26
28
|
}
|
|
27
29
|
return last.replace(/^- /, '').trim()
|
package/lib/recall.js
CHANGED
|
@@ -678,7 +678,10 @@ export function injectionBriefs(store, opts = {}) {
|
|
|
678
678
|
const shownIds = new Set([...(opts.excludeIds || []), ...pinnedIds])
|
|
679
679
|
const dynamic = live.filter((c) => !shownIds.has(c.id))
|
|
680
680
|
const lastHit = (c) => {
|
|
681
|
-
|
|
681
|
+
// last_hit 读回来是毫秒数字(store 的 parse),Date.parse(数字) 恒 NaN,
|
|
682
|
+
// 排序会退化成纯重量序、轮换公平性失效(2026-11-21 B5)。老卡偶尔是 ISO 串,两种都认。
|
|
683
|
+
const raw = c.last_hit
|
|
684
|
+
const t = typeof raw === 'number' ? raw : Date.parse(raw || '')
|
|
682
685
|
return Number.isFinite(t) ? t : 0
|
|
683
686
|
}
|
|
684
687
|
const ordered = dynamic
|
package/lib/store.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// 外文库:一条记忆 = 磁盘上一个纯文本 .md,索引只是一份 JSON。
|
|
2
2
|
// 不依赖向量库,打包走人就能带走(BV121xg6kEqx 的第一层)。
|
|
3
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs'
|
|
4
4
|
import { join } from 'node:path'
|
|
5
5
|
import { homedir } from 'node:os'
|
|
6
6
|
import { execFileSync } from 'node:child_process'
|
|
7
7
|
import { DEFAULT_HEAT, liveWeightOf, rehearse } from './heat.js'
|
|
8
|
-
import { appendStream, searchStream, streamSize } from './stream.js'
|
|
8
|
+
import { appendStream, localDay, searchStream, streamSize, streamFirstAt, streamFirstKey } from './stream.js'
|
|
9
9
|
import { isDead, tokenize, tokenWeight } from './recall.js'
|
|
10
10
|
|
|
11
11
|
// 数据目录(2026-11-20 改名 dsh-memory-huixiang):新目录叫 huixiang。老用户的库在 cyber-hippocampus/ 下,
|
|
@@ -26,9 +26,12 @@ export const DEFAULT_DATA_DIR = resolveDefaultDataDir()
|
|
|
26
26
|
// 2026-11-20 复核:原来只在校验工具入参那一层净化,store 层的 get/put 还能被 `../x` 带出 notes/。
|
|
27
27
|
// 允许 Unicode 字母数字:归纳卡 id 形如 `ins-云州-mwp5qm0r`(2026-11-20 实测),不能只放行 ASCII。
|
|
28
28
|
const ID_RE = /^[\p{L}\p{N}._-]+$/u
|
|
29
|
+
// Windows 上这些是设备名:`CON.md` 也是设备,写完读不回来,文件会静默丢失(2026-11-21 #8)。
|
|
30
|
+
// 尾随的点在 Windows 上会被系统裁掉,`foo.` → `foo.md` 与别的卡撞名。
|
|
31
|
+
const WIN_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i
|
|
29
32
|
export function isSafeId(id) {
|
|
30
33
|
const s = String(id ?? '')
|
|
31
|
-
return Boolean(s) && ID_RE.test(s) && !s.includes('..')
|
|
34
|
+
return Boolean(s) && ID_RE.test(s) && !s.includes('..') && !WIN_RESERVED.test(s) && !/[. ]$/.test(s)
|
|
32
35
|
}
|
|
33
36
|
function assertSafeId(id) {
|
|
34
37
|
if (!isSafeId(id)) throw new Error(`非法卡 id:${String(id)}(只允许字母数字与 . _ -,且不能含 ..)`)
|
|
@@ -116,12 +119,22 @@ const withLock = (path, fn) => {
|
|
|
116
119
|
|
|
117
120
|
const writeAtomic = (path, text) => withLock(path, () => {
|
|
118
121
|
const tmp = `${path}.tmp-${process.pid}`
|
|
119
|
-
|
|
122
|
+
// 先 fsync 再 rename:否则断电/掉电时 rename 可能指向一个还没落盘的空文件(2026-11-21 B12)。
|
|
123
|
+
const fd = openSync(tmp, 'w', 0o600)
|
|
124
|
+
try {
|
|
125
|
+
writeSync(fd, text)
|
|
126
|
+
fsyncSync(fd)
|
|
127
|
+
} finally {
|
|
128
|
+
closeSync(fd)
|
|
129
|
+
}
|
|
120
130
|
renameSync(tmp, path)
|
|
121
131
|
})
|
|
122
132
|
|
|
123
133
|
/** 极简 frontmatter 解析:只认 key: value 一行一个,够用。 */
|
|
124
134
|
function parseCard(id, raw, mtimeMs = 0) {
|
|
135
|
+
// Windows 编辑器(记事本 / VS Code 另存)会给整份文件换成 CRLF。不归一的话正则匹配不上,
|
|
136
|
+
// 整张卡静默退化成默认值(weight 重置、tags/pinned/valid_until 全丢),不报错(2026-11-21 B16)。
|
|
137
|
+
raw = String(raw).replace(/\r\n?/g, '\n')
|
|
125
138
|
const m = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/)
|
|
126
139
|
if (!m) return { id, kind: 'experience', source: 'self', tags: [], weight: 1, last_hit: Date.now(), body: raw.trim() }
|
|
127
140
|
const meta = {}
|
|
@@ -165,6 +178,10 @@ function parseCard(id, raw, mtimeMs = 0) {
|
|
|
165
178
|
}
|
|
166
179
|
}
|
|
167
180
|
|
|
181
|
+
// frontmatter 是行式格式:提交进来的换行能伪造一整行(title: "正常\nsuperseded_by: hacked"),
|
|
182
|
+
// 落盘前把单行字段统一压平(2026-11-21 千问复核 B1)。
|
|
183
|
+
const flat = (v) => String(v ?? '').replace(/\s*\n\s*/g, ' ⏎ ').trim()
|
|
184
|
+
|
|
168
185
|
function renderCard(card) {
|
|
169
186
|
const lines = [
|
|
170
187
|
'---',
|
|
@@ -172,26 +189,26 @@ function renderCard(card) {
|
|
|
172
189
|
`source: ${card.source}`,
|
|
173
190
|
// 只在有值时才写:老卡重新落盘不该凭空多出一行(2026-11-19)。
|
|
174
191
|
...(card.source_type ? [`source_type: ${card.source_type}`] : []),
|
|
175
|
-
`tags: ${(card.tags || []).join(', ')}`,
|
|
192
|
+
`tags: ${(card.tags || []).map(flat).join(', ')}`,
|
|
176
193
|
`weight: ${Number(card.weight).toFixed(3)}`,
|
|
177
194
|
`last_hit: ${new Date(card.last_hit).toISOString()}`,
|
|
178
195
|
`created: ${card.created || nowIso()}`,
|
|
179
|
-
`valid_until: ${card.valid_until
|
|
180
|
-
`condition: ${
|
|
181
|
-
`source_date: ${card.source_date
|
|
182
|
-
`supersedes: ${card.supersedes
|
|
183
|
-
`superseded_by: ${card.superseded_by
|
|
184
|
-
`quote: ${
|
|
196
|
+
`valid_until: ${flat(card.valid_until)}`,
|
|
197
|
+
`condition: ${flat(card.condition)}`,
|
|
198
|
+
`source_date: ${flat(card.source_date)}`,
|
|
199
|
+
`supersedes: ${flat(card.supersedes)}`,
|
|
200
|
+
`superseded_by: ${flat(card.superseded_by)}`,
|
|
201
|
+
`quote: ${flat(card.quote)}`,
|
|
185
202
|
`conflict: ${card.conflict === true}`,
|
|
186
203
|
// 只在有值时才写这行:旧卡重新落盘不该凭空多出一行空字段。
|
|
187
204
|
...(Array.isArray(card.sourceIds) && card.sourceIds.length
|
|
188
|
-
? [`sourceIds: ${card.sourceIds.map(String).join(', ')}`]
|
|
205
|
+
? [`sourceIds: ${card.sourceIds.map((x) => flat(String(x))).join(', ')}`]
|
|
189
206
|
: []),
|
|
190
207
|
...(Array.isArray(card.links) && card.links.length
|
|
191
|
-
? [`links: ${card.links.map(String).join(', ')}`]
|
|
208
|
+
? [`links: ${card.links.map((x) => flat(String(x))).join(', ')}`]
|
|
192
209
|
: []),
|
|
193
|
-
`title: ${card.title
|
|
194
|
-
`aka: ${(card.aka || []).join(', ')}`,
|
|
210
|
+
`title: ${flat(card.title)}`,
|
|
211
|
+
`aka: ${(card.aka || []).map(flat).join(', ')}`,
|
|
195
212
|
`pinned: ${card.pinned === true}`,
|
|
196
213
|
`last_write: ${Number.isFinite(card.last_write) && card.last_write > 0 ? new Date(card.last_write).toISOString() : (card.created || nowIso())}`,
|
|
197
214
|
'---',
|
|
@@ -278,10 +295,16 @@ export class HippocampusStore {
|
|
|
278
295
|
|
|
279
296
|
get(id) {
|
|
280
297
|
// 读路径不抛:非法 id 当成「没这张卡」,别让一个坏 id 把整轮注入打掉。
|
|
298
|
+
// existsSync 之后文件可能被另一个进程删掉(Syncthing / 手工清理),readFileSync 会抛 ENOENT,
|
|
299
|
+
// 所以这里整段 try/catch,不靠先探测(2026-11-21 #24)。
|
|
281
300
|
if (!isSafeId(id)) return undefined
|
|
282
301
|
const path = join(this.notesDir, `${id}.md`)
|
|
283
|
-
|
|
284
|
-
|
|
302
|
+
try {
|
|
303
|
+
const raw = readFileSync(path, 'utf8')
|
|
304
|
+
return parseCard(id, raw, statSync(path).mtimeMs)
|
|
305
|
+
} catch {
|
|
306
|
+
return undefined
|
|
307
|
+
}
|
|
285
308
|
}
|
|
286
309
|
|
|
287
310
|
/**
|
|
@@ -391,8 +414,10 @@ export class HippocampusStore {
|
|
|
391
414
|
const merged = {
|
|
392
415
|
...prev,
|
|
393
416
|
...card,
|
|
394
|
-
|
|
395
|
-
|
|
417
|
+
// ?? 只跳过 null/undefined,NaN 会原样穿透(写进 frontmatter 变成 "weight: NaN"):
|
|
418
|
+
// 缓存了一路的 NaN 最后会让这张卡既不算热也不算冷(2026-11-21 #25)。
|
|
419
|
+
weight: Number.isFinite(card.weight) ? card.weight : (Number.isFinite(prev?.weight) ? prev.weight : this.heat.initialWeight),
|
|
420
|
+
last_hit: Number.isFinite(card.last_hit) ? card.last_hit : (Number.isFinite(prev?.last_hit) ? prev.last_hit : Date.now()),
|
|
396
421
|
created: prev?.created || nowIso(),
|
|
397
422
|
// 只有明确传了 last_write 才算「写过」;touch/召回路径不传,窗口不会被召回延长。
|
|
398
423
|
last_write: card.last_write ?? prev?.last_write ?? Date.now(),
|
|
@@ -421,10 +446,13 @@ export class HippocampusStore {
|
|
|
421
446
|
}
|
|
422
447
|
|
|
423
448
|
remove(id) {
|
|
449
|
+
// id 直接拼路径:与 get/put 同口径校验,别让 ../ 把 notes 外的文件挪进 trash(2026-11-21 B4)。
|
|
450
|
+
id = assertSafeId(id)
|
|
424
451
|
const path = join(this.notesDir, `${id}.md`)
|
|
425
452
|
if (!existsSync(path)) return true
|
|
426
453
|
// 不直接 rm:先挪进 trash/<日期>/,留一条退路(主人 2026-11-06 定的规矩,这里落成代码)。
|
|
427
|
-
|
|
454
|
+
// 本地日期:UTC 日期在东八区会让「今天删的」跑进昨天/明天的桶(2026-11-21 #1)。
|
|
455
|
+
const day = localDay(Date.now())
|
|
428
456
|
const trashDir = join(this.dir, 'trash', day)
|
|
429
457
|
mkdirSync(trashDir, { recursive: true })
|
|
430
458
|
renameSync(path, join(trashDir, `${id}.md`))
|
|
@@ -478,15 +506,21 @@ export class HippocampusStore {
|
|
|
478
506
|
|
|
479
507
|
// ── 用进废退的账本 ──────────────────────────────────────────────────────
|
|
480
508
|
logRehearsal({ id, from = 0, to = 0, cue = '', at = Date.now() }) {
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
509
|
+
// 记账是旁路:磁盘满 / 目录只读 / 权限错都不该把这一轮召回整条打掉(2026-11-21 #27)。
|
|
510
|
+
try {
|
|
511
|
+
this.ensure()
|
|
512
|
+
const line = JSON.stringify({
|
|
513
|
+
at: new Date(at).toISOString(),
|
|
514
|
+
id,
|
|
515
|
+
from: Number(Number(from).toFixed(3)),
|
|
516
|
+
to: Number(Number(to).toFixed(3)),
|
|
517
|
+
cue: String(cue || '').slice(0, 60),
|
|
518
|
+
})
|
|
519
|
+
appendFileSync(this.rehearsalPath, `${line}\n`, { mode: 0o600 })
|
|
520
|
+
return true
|
|
521
|
+
} catch {
|
|
522
|
+
return false
|
|
523
|
+
}
|
|
490
524
|
}
|
|
491
525
|
|
|
492
526
|
/** id → 被想起过几次。 */
|
|
@@ -519,6 +553,16 @@ export class HippocampusStore {
|
|
|
519
553
|
return streamSize(this)
|
|
520
554
|
}
|
|
521
555
|
|
|
556
|
+
streamFirstAt() {
|
|
557
|
+
this.ensure()
|
|
558
|
+
return streamFirstAt(this)
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
streamFirstKey() {
|
|
562
|
+
this.ensure()
|
|
563
|
+
return streamFirstKey(this)
|
|
564
|
+
}
|
|
565
|
+
|
|
522
566
|
// ── 按量做梦的记忆点:上次梦到 stream 第几行、什么时候(2026-11-12)──────
|
|
523
567
|
dreamState() {
|
|
524
568
|
this.ensure()
|
|
@@ -574,8 +618,12 @@ export class HippocampusStore {
|
|
|
574
618
|
|
|
575
619
|
chainTail(lines = 20) {
|
|
576
620
|
this.ensure()
|
|
621
|
+
// 负数会被 slice 当成「从尾部倒数」的反面(slice(-5) 是 slice(5)?不,slice(5) 是去掉前 5 行),
|
|
622
|
+
// 传 -5 原本返回除前 5 行外的全部,注入会撑爆(2026-11-21 #34)。
|
|
623
|
+
const n = Number.isFinite(Number(lines)) ? Math.max(0, Math.trunc(Number(lines))) : 20
|
|
624
|
+
if (n === 0) return []
|
|
577
625
|
const all = readFileSync(this.chainPath, 'utf8').split('\n').filter(Boolean)
|
|
578
|
-
return all.slice(-
|
|
626
|
+
return all.slice(-n)
|
|
579
627
|
}
|
|
580
628
|
|
|
581
629
|
chainSize() {
|
package/lib/stream.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// 原话流水:一句一句落盘,只增不改。
|
|
2
2
|
// 摘要会骗人,原话不会 —— 记不清当时怎么说的,就来这里按行号回查(借 dsh-hippocampus 0.2.40 的思路)。
|
|
3
|
-
import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { appendFileSync, closeSync, openSync, readFileSync, readSync, statSync, writeFileSync } from 'node:fs'
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
4
5
|
import { join } from 'node:path'
|
|
5
6
|
import { tokenize, truncate, tokenWeight, containsToken } from './recall.js'
|
|
6
7
|
|
|
@@ -11,9 +12,28 @@ const MAX_CHARS = 4000 // 单条上限:整段视频转写那种不塞,只留
|
|
|
11
12
|
const pathOf = (store) => join(store.dir, STREAM_FILE)
|
|
12
13
|
const countPathOf = (store) => join(store.dir, COUNT_FILE)
|
|
13
14
|
|
|
15
|
+
const TAIL_BYTES = 65536
|
|
16
|
+
|
|
14
17
|
function nextNo(store) {
|
|
15
18
|
// 原来先写计数文件再 append:两步之间被杀 → 计数虚高、行号跳号;计数文件被截断 → 归零重号。
|
|
16
|
-
//
|
|
19
|
+
// 之后改成「整读全文件数行数」:每落一句 O(n),几千行后每条消息要读几百 KB,平方级增长(2026-11-21 B11)。
|
|
20
|
+
// 现在只看尾部 64KB:最后一行里记着 n,+1 就是新行号;读不出来再退回整读兜底。
|
|
21
|
+
try {
|
|
22
|
+
const path = pathOf(store)
|
|
23
|
+
const size = statSync(path).size
|
|
24
|
+
if (size === 0) return 1
|
|
25
|
+
const len = Math.min(size, TAIL_BYTES)
|
|
26
|
+
const buf = Buffer.alloc(len)
|
|
27
|
+
const fd = openSync(path, 'r')
|
|
28
|
+
try {
|
|
29
|
+
readSync(fd, buf, 0, len, size - len)
|
|
30
|
+
} finally {
|
|
31
|
+
closeSync(fd)
|
|
32
|
+
}
|
|
33
|
+
const last = buf.toString('utf8').split('\n').filter(Boolean).pop()
|
|
34
|
+
const n = Number(JSON.parse(last).n)
|
|
35
|
+
if (Number.isSafeInteger(n) && n > 0) return n + 1
|
|
36
|
+
} catch { /* 尾部不可用就退回整读 */ }
|
|
17
37
|
try {
|
|
18
38
|
const all = readFileSync(pathOf(store), 'utf8')
|
|
19
39
|
return all ? all.split('\n').filter(Boolean).length + 1 : 1
|
|
@@ -45,6 +65,26 @@ export function streamSize(store) {
|
|
|
45
65
|
return streamLines(store).length
|
|
46
66
|
}
|
|
47
67
|
|
|
68
|
+
/** 第一行的落盘时间(毫秒)。判「流水被删/重建」用:正常追加时第一行永远是最早那句。 */
|
|
69
|
+
export function streamFirstAt(store) {
|
|
70
|
+
const line = streamLines(store)[0]
|
|
71
|
+
if (!line) return 0
|
|
72
|
+
try {
|
|
73
|
+
const at = Date.parse(JSON.parse(line).at || '')
|
|
74
|
+
return Number.isFinite(at) ? at : 0
|
|
75
|
+
} catch {
|
|
76
|
+
return 0
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 首行身份(首行原文的短摘要)。判「流水被删/重建」用:只比「第一行还是不是原来那一行」,
|
|
81
|
+
* 不看时钟先后 —— 同毫秒重建、或首行时间戳落在未来,都不会让水位判错(2026-11-21 千问第二轮 N1/B6R/N2)。 */
|
|
82
|
+
export function streamFirstKey(store) {
|
|
83
|
+
const line = streamLines(store)[0]
|
|
84
|
+
if (!line) return ''
|
|
85
|
+
return createHash('sha1').update(line).digest('hex').slice(0, 16)
|
|
86
|
+
}
|
|
87
|
+
|
|
48
88
|
/** 按线索回查原话;命中按「词重合度 + 越新越靠前」排。 */
|
|
49
89
|
export function searchStream(store, cue, opts = {}) {
|
|
50
90
|
const limit = opts.limit ?? 3
|