dsh-memory-huixiang 0.1.3 → 0.1.5
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 +2 -2
- package/index.js +33 -12
- package/lib/dream.js +8 -0
- package/lib/lock.js +34 -0
- package/lib/recall.js +5 -13
- package/lib/store.js +69 -66
- package/lib/stream.js +9 -4
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -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 # 246 个测试全过
|
|
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
|
+
- 246 个测试覆盖的是核心路径,不是全覆盖。
|
|
177
177
|
|
|
178
178
|
## 隐私
|
|
179
179
|
|
package/index.js
CHANGED
|
@@ -570,7 +570,7 @@ const catalogLimit = countOr(config.catalogLimit, 130)
|
|
|
570
570
|
ids: { type: 'array', items: { type: 'string' }, maxItems: 10, description: '按短 id 直接取全文(便签行里 [xxxx] 那个;也认完整 id 或尾 4 位)。给 ids 时 cue 可以不传,比猜自然语言准。' },
|
|
571
571
|
cues: { type: 'array', items: { type: 'string' }, maxItems: 10, description: '换几种说法一次查(可选):命中任一种就算捞到,取最高分。' },
|
|
572
572
|
includeSuperseded: { type: 'boolean', description: '连已被接替/过期的旧卡一起翻(审计用,默认 false)。' },
|
|
573
|
-
limit: { type: 'number', minimum: 1, maximum: 10, description: '最多几条,默认
|
|
573
|
+
limit: { type: 'number', minimum: 1, maximum: 10, description: '最多几条,默认 5。跨事件的问题(谁先/一共/比较/两次)给到 6~8。' },
|
|
574
574
|
},
|
|
575
575
|
},
|
|
576
576
|
output: TEXT({ type: 'object' }),
|
|
@@ -642,7 +642,9 @@ const catalogLimit = countOr(config.catalogLimit, 130)
|
|
|
642
642
|
// 原来单字线索(猫/雨/酒)一律被拦,等于查不了。门控只留给自动检索那条路。
|
|
643
643
|
|
|
644
644
|
// limit 传字符串/NaN 时 Math.trunc 得 NaN → slice(0,NaN)=[] → 命中被吞成 not_found(2026-11-21 B9)。
|
|
645
|
-
|
|
645
|
+
// 默认给 5 条(2026-11-21 全量 500 题实验:top3→top6 让 4~6 段题从 10/33 涨到 21/33,
|
|
646
|
+
// 总分 80.8%→83.0%,逼近「全给原文」上限 83.8%;卡都很短,多两条比答错划算)。
|
|
647
|
+
const limit = Math.min(Math.max(Math.trunc(Number(args.limit) || 5), 1), 10)
|
|
646
648
|
const opts = { limit, includeSuperseded: args.includeSuperseded === true }
|
|
647
649
|
const runs = cues.map((c) => ({ cue: c, r: recallByCue(store, c, opts) }))
|
|
648
650
|
// 合并:同一张卡只留分数最高那次,并记住是哪句说法捞到的(记账要用真的那句)。
|
|
@@ -708,10 +710,17 @@ const catalogLimit = countOr(config.catalogLimit, 130)
|
|
|
708
710
|
gateNote = `实体槽未命中:${g.missing.join('/')}`
|
|
709
711
|
}
|
|
710
712
|
}
|
|
713
|
+
// 被 limit 截断时说一句:让模型知道库里还有更多,值得把 limit 调大再查一次,
|
|
714
|
+
// 而不是以为「库里就这几条」直接作答(2026-11-21 全量 500 题:多段题就吃亏在这)。
|
|
715
|
+
const 候选总数 = Number(topRun?.r.候选总数 || 0)
|
|
716
|
+
if (status === 'matched' && 候选总数 > items.length) {
|
|
717
|
+
reason = (reason ? `${reason};` : '') + `库里还有 ${候选总数 - items.length} 条相关,要看得更全就把 limit 调大再查一次`
|
|
718
|
+
}
|
|
711
719
|
const result = {
|
|
712
720
|
status,
|
|
713
721
|
items,
|
|
714
722
|
reason,
|
|
723
|
+
...(候选总数 ? { 候选总数 } : {}),
|
|
715
724
|
兜底,
|
|
716
725
|
拆解: topRun?.r.拆解 || '',
|
|
717
726
|
...(gateNote ? { 出口闸: gateNote } : {}),
|
|
@@ -854,32 +863,44 @@ const catalogLimit = countOr(config.catalogLimit, 130)
|
|
|
854
863
|
for (const def of definitions) ctx.effect(() => ctx.tools.register(def), `cyber-hippocampus: ${def.name}`)
|
|
855
864
|
|
|
856
865
|
// 一轮压缩会被拆成好多条 prune,先攒着,等 end/summary 时记成一笔。
|
|
857
|
-
|
|
866
|
+
// 按会话分开:两个窗口可能同时在压自己的历史,共用一个变量会串账、丢账(2026-11-21 #6)。
|
|
867
|
+
const foldings = new Map()
|
|
868
|
+
const FOLD_TTL_MS = 60 * 60 * 1000 // 只见 start 不见 end 的僵尸账,1 小时后自清,别越攒越多
|
|
869
|
+
const foldOf = (key, now = Date.now()) => {
|
|
870
|
+
for (const [k, v] of foldings) if (now - v.at > FOLD_TTL_MS) foldings.delete(k)
|
|
871
|
+
let f = foldings.get(key)
|
|
872
|
+
if (!f) {
|
|
873
|
+
f = { tokens: 0, seqStart: null, seqEnd: null, at: now }
|
|
874
|
+
foldings.set(key, f)
|
|
875
|
+
}
|
|
876
|
+
return f
|
|
877
|
+
}
|
|
858
878
|
|
|
859
879
|
ctx.on('session/event', (session, event) => {
|
|
860
880
|
try {
|
|
861
881
|
if (session?.id) lastSessionId = session.id
|
|
862
882
|
const type = event?.type || event?.kind
|
|
863
883
|
const data = event?.data ?? event ?? {}
|
|
884
|
+
const foldKey = String(session?.id || '')
|
|
864
885
|
|
|
865
886
|
if (type === 'compaction/start') {
|
|
866
|
-
|
|
887
|
+
foldings.set(foldKey, { tokens: 0, seqStart: null, seqEnd: null, at: Date.now() })
|
|
867
888
|
return
|
|
868
889
|
}
|
|
869
890
|
if (type === 'compaction/prune') {
|
|
870
|
-
|
|
871
|
-
|
|
891
|
+
const f = foldOf(foldKey)
|
|
892
|
+
f.at = Date.now()
|
|
893
|
+
f.tokens += Number(data.shadowedTokenCount) || 0
|
|
872
894
|
const start = data?.shadowedRange?.start
|
|
873
895
|
const end = data?.shadowedRange?.end
|
|
874
|
-
if (Number.isFinite(start))
|
|
875
|
-
if (Number.isFinite(end))
|
|
896
|
+
if (Number.isFinite(start)) f.seqStart = f.seqStart === null ? start : Math.min(f.seqStart, start)
|
|
897
|
+
if (Number.isFinite(end)) f.seqEnd = f.seqEnd === null ? end : Math.max(f.seqEnd, end)
|
|
876
898
|
return
|
|
877
899
|
}
|
|
878
900
|
if (type === 'compaction/summary' || type === 'compaction/end') {
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
}
|
|
901
|
+
const f = foldings.get(foldKey)
|
|
902
|
+
if (f && f.tokens > 0) store.recordCompaction(f)
|
|
903
|
+
foldings.delete(foldKey)
|
|
883
904
|
return
|
|
884
905
|
}
|
|
885
906
|
|
package/lib/dream.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// 梦游整理(BV1dDxC67Ep3):闲下来时按主题把散的事件归成一句话,
|
|
2
2
|
// 但**保留来源、保留矛盾**,不把两条冲突的记忆强行合成一个说法。
|
|
3
3
|
// 这里故意不调模型:先把结构跑通,谁来写「概括」以后可以换成本鲸自己。
|
|
4
|
+
import { join } from 'node:path'
|
|
4
5
|
import { tokenize, isDead } from './recall.js'
|
|
6
|
+
import { withLock } from './lock.js'
|
|
5
7
|
|
|
6
8
|
const DAY = 86_400_000
|
|
7
9
|
|
|
@@ -94,6 +96,12 @@ export function buildInsightBody(tag, list, conflicts, budget) {
|
|
|
94
96
|
}
|
|
95
97
|
|
|
96
98
|
export function dreamPass(store, opts = {}) {
|
|
99
|
+
// 整趟做梦互斥:两个窗口同时触发时,各自读到同一份「这个主题还没有归纳卡」的快照,
|
|
100
|
+
// 会为同一主题各写一张同质卡(2026-11-21 实测两进程同时做梦归出 2 张)。
|
|
101
|
+
return withLock(join(store.dir, 'dream'), () => dreamPassLocked(store, opts))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function dreamPassLocked(store, opts = {}) {
|
|
97
105
|
const now = opts.now ?? Date.now()
|
|
98
106
|
const lookbackDays = opts.lookbackDays ?? 14
|
|
99
107
|
const minGroup = opts.minGroup ?? 2
|
package/lib/lock.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// 文件写锁:同一份库可能被工具调用与夜间整理同时写(BV14qxL6WEGZ 评论区那条「两个进程抢写」的坑)。
|
|
2
|
+
// 用 O_EXCL 建锁文件,拿不到就短暂自旋;超过 10 秒的锁视为前任崩了,直接清掉。
|
|
3
|
+
// 原来长在 store.js 里,2026-11-21 抽出来给 stream.js 的 appendStream 也用(#29 多进程重号)。
|
|
4
|
+
import { rmSync, statSync, writeFileSync } from 'node:fs'
|
|
5
|
+
|
|
6
|
+
export const LOCK_WAIT_MS = 3000
|
|
7
|
+
export const LOCK_STALE_MS = 10_000
|
|
8
|
+
|
|
9
|
+
export function withLock(path, fn) {
|
|
10
|
+
const lock = `${path}.lock`
|
|
11
|
+
const start = Date.now()
|
|
12
|
+
for (;;) {
|
|
13
|
+
try {
|
|
14
|
+
writeFileSync(lock, String(process.pid), { flag: 'wx' })
|
|
15
|
+
break
|
|
16
|
+
} catch (err) {
|
|
17
|
+
if (err.code !== 'EEXIST') throw err
|
|
18
|
+
try {
|
|
19
|
+
if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
|
|
20
|
+
rmSync(lock, { force: true })
|
|
21
|
+
continue
|
|
22
|
+
}
|
|
23
|
+
} catch {}
|
|
24
|
+
if (Date.now() - start > LOCK_WAIT_MS) throw new Error(`写锁超时:${lock}`)
|
|
25
|
+
// 原来的同步空转会把整个 agent 循环卡住;用 Atomics.wait 真睡 20ms。
|
|
26
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
return fn()
|
|
31
|
+
} finally {
|
|
32
|
+
rmSync(lock, { force: true })
|
|
33
|
+
}
|
|
34
|
+
}
|
package/lib/recall.js
CHANGED
|
@@ -376,7 +376,6 @@ export function recallByCue(store, cue, opts = {}) {
|
|
|
376
376
|
return { status: 'not_found', items: [], reason: '库里没有对得上的记录', 拆解: parseLine }
|
|
377
377
|
}
|
|
378
378
|
const top = scored[0]
|
|
379
|
-
const second = scored[1]
|
|
380
379
|
// 实体槽闸(11-14 复核第二名缺点的补丁):问「公司/学校/小区/型号…」这类具体实体时,
|
|
381
380
|
// 命中的卡里必须真的出现过这个词,否则还是拿「名字」「生日」凑答案。
|
|
382
381
|
// 11-14 二审:地址/角色/专业是多义词(备份包地址、本鲸算什么角色),会误伤正常问句——
|
|
@@ -387,18 +386,8 @@ export function recallByCue(store, cue, opts = {}) {
|
|
|
387
386
|
// 且命中的词里至少一个出现在这张卡的标题/标签里——防「表弟」刚好出现在生日卡正文里那种误命中。
|
|
388
387
|
// 例外:线索里有强证据词(编号 / 长数字串 / 书名号引号点名的串)时,直接放行头名。
|
|
389
388
|
// 短问句不放宽:句长/词数跟负样本几乎一样,按句长放行等于把负样本一起放回来(11-15 二审,别再做)。
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
const cardTitleOrTag = (c) => {
|
|
393
|
-
const s = new Set(tokenize(c.title || ''))
|
|
394
|
-
for (const raw of c.tags || []) {
|
|
395
|
-
const t = String(raw).toLowerCase()
|
|
396
|
-
s.add(t)
|
|
397
|
-
const i = t.indexOf(':')
|
|
398
|
-
if (i >= 0 && i < t.length - 1) s.add(t.slice(i + 1))
|
|
399
|
-
}
|
|
400
|
-
return s
|
|
401
|
-
}
|
|
389
|
+
// 下一版窄路要用的判据函数(hasStrongEvidence / gateWords)留在模块里,别在这里白算一遍——
|
|
390
|
+
// 2026-11-21 外部复核 B17:这三行算完没人读,纯粹每次召回多耗一遍 CPU。
|
|
402
391
|
// 命中门槛(coverage===1)实验版 2026-11-15:全量闸与「单字/别名/改述/时间窗」等产品语义天然冲突
|
|
403
392
|
// (主意识 22:58 判:不过,回退)。只留 gateWords() 函数给下一版窄路用,选卡恢复成直接选头名。
|
|
404
393
|
const chosen = top
|
|
@@ -438,6 +427,9 @@ export function recallByCue(store, cue, opts = {}) {
|
|
|
438
427
|
return {
|
|
439
428
|
status: ambiguous ? 'ambiguous' : 'matched',
|
|
440
429
|
items: picked,
|
|
430
|
+
// 候选总数:调用方据此判断「是不是被 limit 截断了」,好提示模型把 limit 调大再查一次。
|
|
431
|
+
// 2026-11-21 全量 500 题实验:4~6 段题吃亏在只给 3 张卡,多给几张立刻涨 11 题。
|
|
432
|
+
候选总数: scored.length,
|
|
441
433
|
reason: ambiguous ? '命中相近,请补一句是哪件事' : '',
|
|
442
434
|
拆解: parseLine,
|
|
443
435
|
parsed: { when: parsed.when, who: parsed.who, wantLatest: parsed.wantLatest, keywords: parsed.keywords },
|
package/lib/store.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
// 外文库:一条记忆 = 磁盘上一个纯文本 .md,索引只是一份 JSON。
|
|
2
2
|
// 不依赖向量库,打包走人就能带走(BV121xg6kEqx 的第一层)。
|
|
3
|
-
import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs'
|
|
3
|
+
import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, readSync, 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
8
|
import { appendStream, localDay, searchStream, streamSize, streamFirstAt, streamFirstKey } from './stream.js'
|
|
9
9
|
import { isDead, tokenize, tokenWeight } from './recall.js'
|
|
10
|
+
import { withLock } from './lock.js'
|
|
10
11
|
|
|
11
12
|
// 数据目录(2026-11-20 改名 dsh-memory-huixiang):新目录叫 huixiang。老用户的库在 cyber-hippocampus/ 下,
|
|
12
13
|
// 不能因为改名就「记忆消失」——新目录还没有、旧目录里已经有卡,就继续用旧目录。
|
|
@@ -86,38 +87,8 @@ const readJson = (path, fallback) => {
|
|
|
86
87
|
return fallback
|
|
87
88
|
}
|
|
88
89
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const LOCK_WAIT_MS = 3000
|
|
92
|
-
const LOCK_STALE_MS = 10_000
|
|
93
|
-
const withLock = (path, fn) => {
|
|
94
|
-
const lock = `${path}.lock`
|
|
95
|
-
const start = Date.now()
|
|
96
|
-
for (;;) {
|
|
97
|
-
try {
|
|
98
|
-
writeFileSync(lock, String(process.pid), { flag: 'wx' })
|
|
99
|
-
break
|
|
100
|
-
} catch (err) {
|
|
101
|
-
if (err.code !== 'EEXIST') throw err
|
|
102
|
-
try {
|
|
103
|
-
if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
|
|
104
|
-
rmSync(lock, { force: true })
|
|
105
|
-
continue
|
|
106
|
-
}
|
|
107
|
-
} catch {}
|
|
108
|
-
if (Date.now() - start > LOCK_WAIT_MS) throw new Error(`写锁超时:${lock}`)
|
|
109
|
-
// 原来的同步空转会把整个 agent 循环卡住;用 Atomics.wait 真睡 20ms。
|
|
110
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20)
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
try {
|
|
114
|
-
return fn()
|
|
115
|
-
} finally {
|
|
116
|
-
rmSync(lock, { force: true })
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
const writeAtomic = (path, text) => withLock(path, () => {
|
|
90
|
+
/** 无锁的原子写:调用方必须已经持有 path 的锁(put 要把「读 prev + 合并」也包进同一把锁)。 */
|
|
91
|
+
const writeFileUnlocked = (path, text) => {
|
|
121
92
|
const tmp = `${path}.tmp-${process.pid}`
|
|
122
93
|
// 先 fsync 再 rename:否则断电/掉电时 rename 可能指向一个还没落盘的空文件(2026-11-21 B12)。
|
|
123
94
|
const fd = openSync(tmp, 'w', 0o600)
|
|
@@ -128,7 +99,8 @@ const writeAtomic = (path, text) => withLock(path, () => {
|
|
|
128
99
|
closeSync(fd)
|
|
129
100
|
}
|
|
130
101
|
renameSync(tmp, path)
|
|
131
|
-
}
|
|
102
|
+
}
|
|
103
|
+
const writeAtomic = (path, text) => withLock(path, () => writeFileUnlocked(path, text))
|
|
132
104
|
|
|
133
105
|
/** 极简 frontmatter 解析:只认 key: value 一行一个,够用。 */
|
|
134
106
|
function parseCard(id, raw, mtimeMs = 0) {
|
|
@@ -410,23 +382,29 @@ export class HippocampusStore {
|
|
|
410
382
|
if (!card.id) throw new Error('card.id 必填')
|
|
411
383
|
card = { ...card, id: assertSafeId(card.id) }
|
|
412
384
|
const path = join(this.notesDir, `${card.id}.md`)
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
385
|
+
// 「读 prev → 合并 → 写」必须在同一把锁里:原来 get 在锁外、写才进锁,
|
|
386
|
+
// 两个进程各读到旧卡,后写的那个会把先写那个刚加的字段覆盖掉(2026-11-21 #17 实测 40/40 次丢 tags)。
|
|
387
|
+
return withLock(path, () => {
|
|
388
|
+
const prev = this.get(card.id)
|
|
389
|
+
const merged = {
|
|
390
|
+
...prev,
|
|
391
|
+
...card,
|
|
392
|
+
// tags/sourceIds/links 是数组字段;模型偶尔会传字符串,归一成数组,别让 renderCard 的 .map 崩掉。
|
|
393
|
+
tags: Array.isArray(card.tags) ? card.tags : (card.tags == null ? (prev?.tags || []) : [String(card.tags)]),
|
|
394
|
+
// ?? 只跳过 null/undefined,NaN 会原样穿透(写进 frontmatter 变成 "weight: NaN"):
|
|
395
|
+
// 缓存了一路的 NaN 最后会让这张卡既不算热也不算冷(2026-11-21 #25)。
|
|
396
|
+
weight: Number.isFinite(card.weight) ? card.weight : (Number.isFinite(prev?.weight) ? prev.weight : this.heat.initialWeight),
|
|
397
|
+
last_hit: Number.isFinite(card.last_hit) ? card.last_hit : (Number.isFinite(prev?.last_hit) ? prev.last_hit : Date.now()),
|
|
398
|
+
created: prev?.created || nowIso(),
|
|
399
|
+
// 只有明确传了 last_write 才算「写过」;touch/召回路径不传,窗口不会被召回延长。
|
|
400
|
+
last_write: card.last_write ?? prev?.last_write ?? Date.now(),
|
|
401
|
+
}
|
|
402
|
+
// 覆盖前留旧版(2026-11-11 抄自「事件流水」思路):只比内容字段,
|
|
403
|
+
// touch 改的 weight/last_hit 不算改写,不会把 history 刷满。
|
|
404
|
+
if (prev && contentChanged(prev, merged)) this.saveHistory(prev)
|
|
405
|
+
writeFileUnlocked(path, renderCard(merged))
|
|
406
|
+
return merged
|
|
407
|
+
})
|
|
430
408
|
}
|
|
431
409
|
|
|
432
410
|
/** 把旧版落进 history/<id>/<时间>.md,误合并/误覆盖时能翻回去(trash 只救删除,救不了覆盖)。 */
|
|
@@ -627,6 +605,25 @@ export class HippocampusStore {
|
|
|
627
605
|
// 传 -5 原本返回除前 5 行外的全部,注入会撑爆(2026-11-21 #34)。
|
|
628
606
|
const n = Number.isFinite(Number(lines)) ? Math.max(0, Math.trunc(Number(lines))) : 20
|
|
629
607
|
if (n === 0) return []
|
|
608
|
+
// 每轮注入都要取一次因果链尾;长跑几年这台文件会到几 MB,只拿最后 20 行却读全文件
|
|
609
|
+
// 会随年月线性变慢(2026-11-21 #23)。先读尾部 64KB,行数不够再退回全读。
|
|
610
|
+
const TAIL = 64 * 1024
|
|
611
|
+
try {
|
|
612
|
+
const size = statSync(this.chainPath).size
|
|
613
|
+
if (size > TAIL) {
|
|
614
|
+
const fd = openSync(this.chainPath, 'r')
|
|
615
|
+
let rows
|
|
616
|
+
try {
|
|
617
|
+
const buf = Buffer.alloc(TAIL)
|
|
618
|
+
readSync(fd, buf, 0, TAIL, size - TAIL)
|
|
619
|
+
rows = buf.toString('utf8').split('\n').filter(Boolean)
|
|
620
|
+
} finally {
|
|
621
|
+
closeSync(fd)
|
|
622
|
+
}
|
|
623
|
+
// 第一行多半是从字节中间切开的半截,丢掉;够 n 行就不回头读全文。
|
|
624
|
+
if (rows.length - 1 >= n) return rows.slice(-n)
|
|
625
|
+
}
|
|
626
|
+
} catch { /* 读尾部失败(权限/竞态)就退回全读 */ }
|
|
630
627
|
const all = readFileSync(this.chainPath, 'utf8').split('\n').filter(Boolean)
|
|
631
628
|
return all.slice(-n)
|
|
632
629
|
}
|
|
@@ -639,12 +636,15 @@ export class HippocampusStore {
|
|
|
639
636
|
// ── 自我笔记(限 40 条,满了挤掉最旧的)──────────────────────────────────
|
|
640
637
|
addSelfNote(text, at = nowIso()) {
|
|
641
638
|
this.ensure()
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
639
|
+
// 读全文件 → 追加 → 整文件重写,必须整体在锁里:两个进程各读到旧文件时会互相覆盖(2026-11-21 #20)。
|
|
640
|
+
return withLock(this.selfNotePath, () => {
|
|
641
|
+
const all = this.selfNotes()
|
|
642
|
+
all.push({ at, text: String(text).trim() })
|
|
643
|
+
const kept = all.slice(-SELF_NOTE_CAP)
|
|
644
|
+
// 整文件重写必须原子:写一半被杀,下次 selfNotes() 解析就炸,而它每轮都会被注入。
|
|
645
|
+
writeFileUnlocked(this.selfNotePath, kept.map((n) => JSON.stringify(n)).join('\n') + '\n')
|
|
646
|
+
return { kept: kept.length, cap: SELF_NOTE_CAP }
|
|
647
|
+
})
|
|
648
648
|
}
|
|
649
649
|
|
|
650
650
|
selfNotes() {
|
|
@@ -682,14 +682,17 @@ export class HippocampusStore {
|
|
|
682
682
|
}
|
|
683
683
|
|
|
684
684
|
setPersona({ base, state, note = '' } = {}) {
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
if (
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
685
|
+
// 读 → 改 → 写整体加锁:两个窗口同时改人格时,后写的会把前一次的状态连同它的历史一起盖掉(2026-11-21 #21)。
|
|
686
|
+
return withLock(this.personaPath, () => {
|
|
687
|
+
const p = this.persona()
|
|
688
|
+
if (typeof base === 'string' && base.trim()) p.base = base.trim()
|
|
689
|
+
if (typeof state === 'string' && state.trim() && state.trim() !== p.state) {
|
|
690
|
+
if (p.state) p.history.push({ at: nowIso(), state: p.state, note: String(note).slice(0, 200) })
|
|
691
|
+
p.state = state.trim()
|
|
692
|
+
}
|
|
693
|
+
p.history = (p.history || []).slice(-30)
|
|
694
|
+
writeFileUnlocked(this.personaPath, JSON.stringify(p, null, 1))
|
|
695
|
+
return p
|
|
696
|
+
})
|
|
694
697
|
}
|
|
695
698
|
}
|
package/lib/stream.js
CHANGED
|
@@ -4,6 +4,7 @@ import { appendFileSync, closeSync, openSync, readFileSync, readSync, statSync,
|
|
|
4
4
|
import { createHash } from 'node:crypto'
|
|
5
5
|
import { join } from 'node:path'
|
|
6
6
|
import { tokenize, truncate, tokenWeight, containsToken } from './recall.js'
|
|
7
|
+
import { withLock } from './lock.js'
|
|
7
8
|
|
|
8
9
|
export const STREAM_FILE = 'stream.jsonl'
|
|
9
10
|
const COUNT_FILE = 'stream.count'
|
|
@@ -47,10 +48,14 @@ export function appendStream(store, { role = 'owner', text = '', sessionId = '',
|
|
|
47
48
|
const clean = String(text || '').replace(/\r/g, '').trim()
|
|
48
49
|
if (!clean) return 0
|
|
49
50
|
const body = clean.length > MAX_CHARS ? `${clean.slice(0, MAX_CHARS)}…(截断)` : clean
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
51
|
+
// 「读尾部算下一个号 + 追加」必须是一个原子动作:几个进程同时写时,各自读到的最后一个号一样,
|
|
52
|
+
// 落盘就会重号(2026-11-21 #29 实测 8 进程 200 行只用了 88 个号,hc_evidence 按号回查会指错行)。
|
|
53
|
+
return withLock(pathOf(store), () => {
|
|
54
|
+
const n = nextNo(store)
|
|
55
|
+
const line = JSON.stringify({ n, at: new Date(at).toISOString(), role, sid: String(sessionId || ''), text: body })
|
|
56
|
+
appendFileSync(pathOf(store), `${line}\n`, { mode: 0o600 })
|
|
57
|
+
return n
|
|
58
|
+
})
|
|
54
59
|
}
|
|
55
60
|
|
|
56
61
|
export function streamLines(store) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-memory-huixiang",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.5",
|
|
4
|
+
"description": "回响 HuiXiang:给 AI 一个记得住人的本地记忆库。纯文本外文库 + 记忆重量 + 因果链 + 触发词召回,零依赖、不上云。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|