dsh-memory-huixiang 0.1.1 → 0.1.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.
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 # 206 个测试全过
158
+ node --test # 238 个测试全过
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
- - 206 个测试覆盖的是核心路径,不是全覆盖。
176
+ - 238 个测试覆盖的是核心路径,不是全覆盖。
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 = new Date(Date.now() + 30 * 86_400_000).toISOString().slice(0, 10)
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 = { ...DEFAULT_HEAT, ...(config.heat || {}) }
116
- const chainTailLines = Number.isSafeInteger(config.chainTailLines) ? config.chainTailLines : 12
117
- const hotLimit = Number.isSafeInteger(config.hotLimit) ? config.hotLimit : 3
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 = Number.isSafeInteger(config.briefLimit) ? config.briefLimit : 20
151
+ const briefLimit = countOr(config.briefLimit, 20)
122
152
  // 目录那一层的条数上限(2026-11-19 主人定 A 案):原来写死 200,179 张就把 9000 字符预算吃到 98.7%;默认收到 130,余量回到 ~900。
123
- const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogLimit : 130
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
- everyLines: Number.isSafeInteger(config?.autoDream?.everyLines) ? config.autoDream.everyLines : 20,
128
- cooldownMs: Number.isSafeInteger(config?.autoDream?.cooldownMs) ? config.autoDream.cooldownMs : 3_600_000,
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)
@@ -133,7 +164,7 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
133
164
  // 加载标记(抄 dsh-hippocampus 0.3.1 的 load.log,2026-11-16):重启后 tail 一下就知道
134
165
  // 跑的是哪版、读的是哪份库、卡片几张;写不进去不拦插件——标记是给自己看的,不是功能。
135
166
  try {
136
- appendFileSync(`${dataDir}/load.log`, `${new Date().toISOString()} loaded v${PKG_VERSION} cards=${store.all().length} dataDir=${dataDir} pid=${process.pid}\n`)
167
+ appendFileSync(join(dataDir, 'load.log'), `${new Date().toISOString()} loaded v${PKG_VERSION} cards=${store.all().length} dataDir=${dataDir} pid=${process.pid}\n`)
137
168
  } catch { /* 标记失败不拦插件 */ }
138
169
  // 每日体检补偿(2026-11-14 审查:04:30 定时任务的投递记录在,脚本却没留下记录——手机那时多半不在线)。
139
170
  // 启动后补跑一次:只认真库、只认「今天还没有记录」,测试进程一概不碰。
@@ -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
  })
@@ -162,8 +198,19 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
162
198
  timer.unref?.()
163
199
  return () => clearTimeout(timer)
164
200
  }, 'cyber-hippocampus: health catch-up')
201
+ // 卸载/热重载后,setImmediate 里排队的做梦不该再去碰已经放开的 store(2026-11-21 #12)。
202
+ let disposed = false
203
+ ctx.effect(() => () => { disposed = true }, 'cyber-hippocampus: dispose flag')
165
204
  // trace 使用侧:每个会话最近几次注入各记一条(各自带 iid 和被引用集合),别整体覆盖。
166
205
  const injectedBySid = new Map() // sid -> [{ iid, ids, used: Set }]
206
+ // 这几个 Map 只增不删,长跑会随会话数一直涨(2026-11-21 #7):超过 200 个就丢最旧的一批。
207
+ function trimSidMap(map, max = 200) {
208
+ if (map.size <= max) return
209
+ for (const k of map.keys()) {
210
+ if (map.size <= Math.floor(max * 0.8)) break
211
+ map.delete(k)
212
+ }
213
+ }
167
214
  const INJECT_HISTORY = 5
168
215
  let injectSeq = 0
169
216
  let lastSessionId = '' // 事件里最后一次见到的会话;工具执行拿得到 session 时只用它兜底
@@ -213,8 +260,8 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
213
260
  const 本次sourceType = SOURCE_TYPES.has(args.source_type) ? args.source_type : undefined
214
261
  // id 直接进文件名,别让它穿出 notes 目录。
215
262
  const wantId = clean(args.id)
216
- if (wantId && !/^[A-Za-z0-9._-]+$/.test(wantId)) return { ok: false, error: 'id 只能用字母数字和 . _ -' }
217
- if (wantId.includes('..')) return { ok: false, error: 'id 不能包含 ..' }
263
+ // 与 store 层同口径(含 Unicode,归纳卡 id 形如 ins-体检-abc123)。两层白名单打架会让归纳卡永远续写不了(2026-11-21 B7)。
264
+ if (wantId && !isSafeId(wantId)) return { ok: false, error: 'id 只能用汉字、字母、数字和 . _ -,且不能包含 ..' }
218
265
  // 幂等键:只认「同一调用方同一份输入」。正文不做归一化——归一化会把「差一个标点」也算同一句,
219
266
  // 那是去重该管的边界,不是重试该管的。
220
267
  // 幂等键=「同一次请求」的指纹:所有会改变写入结果的入参都进去。
@@ -362,7 +409,7 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
362
409
  if (增量来源) body = `补:${增量来源.title || 增量来源.id}(${增量来源.id})\n${body}`
363
410
  // 2026-11-14 审查(严重):按 id 续写会把旧卡的 superseded_by 原样带回来 —— 返回 ok,卡却永远查不到、也不注入。
364
411
  // 续写的意思就是「这张卡还活着」:显式清死因;旧的有效期已经过期、这次又没给新的,也一并清掉,并在返回里说明。
365
- const todayStr = new Date().toISOString().slice(0, 10)
412
+ const todayStr = localDay(Date.now())
366
413
  const 旧死因 = prev?.superseded_by ? `已被 ${prev.superseded_by} 接替` : ''
367
414
  const 旧已过期 = prev?.valid_until && prev.valid_until < todayStr ? `旧有效期 ${prev.valid_until} 已过` : ''
368
415
  const 复活 = Boolean(旧死因 || 旧已过期)
@@ -388,7 +435,7 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
388
435
  // 泛标题会在 occasionDays 里被 df 过滤掉(结果=0 个场合 → 降级,这是正确方向)。
389
436
  const { days } = occasionDays(store, clean(args.title) || firstLine(body))
390
437
  if (days.length < 3) {
391
- nextValidUntil = new Date(Date.now() + 30 * 86_400_000).toISOString().slice(0, 10)
438
+ nextValidUntil = localDay(Date.now() + 30 * 86_400_000)
392
439
  场合说明 = `样本不足(原话里只见过 ${days.length} 个场合 < 3),先当临时情报,${nextValidUntil} 到期;多碰到几次再升成长期`
393
440
  }
394
441
  }
@@ -542,8 +589,10 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
542
589
  if (!tail4.has(t)) tail4.set(t, [])
543
590
  tail4.get(t).push(id)
544
591
  }
545
- const isDeadCard = (c) => Boolean(c.superseded_by) || Boolean(c.valid_until && Date.parse(c.valid_until) < Date.now())
592
+ // 判死跟 cue 路径同口径:valid_until 写纯日期时按本地日界算,别拿 Date.parse 当 UTC 零点(2026-11-21 B3)。
593
+ const isDeadCard = (c) => isDead(c, Date.now())
546
594
  const picked = []
595
+ const seenIds = new Set()
547
596
  const missed = []
548
597
  const ambiguous = []
549
598
  const cueOf = new Map()
@@ -554,7 +603,8 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
554
603
  const hit = allIds.includes(w) ? [w] : (tail4.get(w) || [])
555
604
  if (hit.length === 1) {
556
605
  const card = store.get(hit[0])
557
- if (card) { picked.push(card); cueOf.set(card.id, raw) }
606
+ // 同一张卡在 ids 里出现两次时只取一次(否则重复 touch、返回值也重复,2026-11-21 #2)。
607
+ if (card && !seenIds.has(card.id)) { seenIds.add(card.id); picked.push(card); cueOf.set(card.id, raw) }
558
608
  else missed.push(w)
559
609
  } else if (hit.length > 1) {
560
610
  ambiguous.push({ 短id: w, 候选: hit.slice(0, 4) })
@@ -591,7 +641,8 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
591
641
  // 这是手动翻库(本鲸自己决定要查),不该被「像不像在翻旧事」的门控挡住:
592
642
  // 原来单字线索(猫/雨/酒)一律被拦,等于查不了。门控只留给自动检索那条路。
593
643
 
594
- const limit = Math.min(Math.max(Math.trunc(args.limit ?? 3), 1), 10)
644
+ // limit 传字符串/NaN 时 Math.trunc 得 NaN → slice(0,NaN)=[] → 命中被吞成 not_found(2026-11-21 B9)。
645
+ const limit = Math.min(Math.max(Math.trunc(Number(args.limit) || 3), 1), 10)
595
646
  const opts = { limit, includeSuperseded: args.includeSuperseded === true }
596
647
  const runs = cues.map((c) => ({ cue: c, r: recallByCue(store, c, opts) }))
597
648
  // 合并:同一张卡只留分数最高那次,并记住是哪句说法捞到的(记账要用真的那句)。
@@ -647,7 +698,8 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
647
698
  let gateNote = ''
648
699
  if (status !== 'not_found' && items.length) {
649
700
  const fullTop = store.get(items[0].id) || items[0]
650
- const g = answerable(String(args.cue ?? cues[0] ?? ''), [fullTop])
701
+ // 多说法时闸要核「真正捞到头名的那句」,核 cues[0] 会把第二句捞到的卡误弃权(2026-11-21 B10)。
702
+ const g = answerable(String(topRun?.cue ?? args.cue ?? cues[0] ?? ''), [fullTop])
651
703
  if (!g.ok) {
652
704
  status = 'not_found'
653
705
  items.length = 0
@@ -719,8 +771,10 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
719
771
  const r = store.addSelfNote(args.write)
720
772
  return { ok: true, ...r }
721
773
  }
722
- const notes = store.selfNotes().slice(-(args.last || 3))
723
- return { ok: true, count: store.selfNotes().length, notes }
774
+ // 传负数/0/怪值时别让 slice 跑偏,也别为读一次笔记扫两遍盘(2026-11-21 #4)。
775
+ const last = Math.min(40, Math.max(1, Math.trunc(Number(args.last) || 3)))
776
+ const all = store.selfNotes()
777
+ return { ok: true, count: all.length, notes: all.slice(-last) }
724
778
  },
725
779
  },
726
780
  {
@@ -755,7 +809,11 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
755
809
  },
756
810
  output: TEXT({ type: 'object' }),
757
811
  isConcurrencySafe: () => false,
758
- execute: async (args) => ({ ok: true, ...dreamPass(store, { dryRun: args.dryRun !== false, lookbackDays: args.lookbackDays || 14 }) }),
812
+ execute: async (args) => {
813
+ // 0 会被 || 改写成 14,负数会让窗口取反(2026-11-21 #5)。
814
+ const days = Math.min(365, Math.max(1, Math.trunc(Number(args.lookbackDays) || 14)))
815
+ return { ok: true, ...dreamPass(store, { dryRun: args.dryRun !== false, lookbackDays: days }) }
816
+ },
759
817
  },
760
818
  {
761
819
  name: 'hc_status',
@@ -835,11 +893,13 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
835
893
  const who = type === 'user/message' ? 'owner' : 'self'
836
894
  // B 级「用上了」证据先记:写链/写流失败不该连带把 use 行也丢了。
837
895
  if (type === 'assistant/message') recordTextUse(session?.id || '', body)
838
- store.appendChain(who, body)
839
- store.appendStream({ role: who, text: body, sessionId: session?.id || '' })
896
+ // 两条流水各写各的:一条失败不该把另一条也带走,也别静默吞掉(2026-11-21 #13)。
897
+ try { store.appendChain(who, body) } catch (err) { console.warn('[cyber-hippocampus] 因果链写失败:', err?.message || err) }
898
+ try { store.appendStream({ role: who, text: body, sessionId: session?.id || '' }) } catch (err) { console.warn('[cyber-hippocampus] 原话流水写失败:', err?.message || err) }
840
899
  // 按量做梦:攒够就后台归一次,别在事件钩子里同步跑(做梦要读全库、写盘)。
841
900
  if (autoDream.enabled) {
842
901
  setImmediate(() => {
902
+ if (disposed) return
843
903
  try {
844
904
  const r = maybeDream(store, autoDream)
845
905
  if (r.ran) console.log('[cyber-hippocampus] 按量做梦:整理了', r.wrote, '条,stream 到第', r.total, '行')
@@ -902,10 +962,12 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
902
962
  const ok = store.trace({ at: new Date(now).toISOString(), ev: 'inject', sid, ids, n: ids.length, iid })
903
963
  if (ok) {
904
964
  lastInject.set(sid, { key, at: now })
965
+ trimSidMap(lastInject)
905
966
  const hist = injectedBySid.get(sid) || []
906
967
  hist.push({ iid, ids, used: new Set() })
907
968
  if (hist.length > INJECT_HISTORY) hist.shift()
908
969
  injectedBySid.set(sid, hist)
970
+ trimSidMap(injectedBySid)
909
971
  }
910
972
  else console.warn('[cyber-hippocampus] trace 写入失败,这一条注入流水漏记')
911
973
  } catch {
@@ -925,7 +987,7 @@ const catalogLimit = Number.isSafeInteger(config.catalogLimit) ? config.catalogL
925
987
  const now = Date.now()
926
988
  const prev = lastBrief.get(sid)
927
989
  if (prev && prev.key === key && now - prev.at < INJECT_DEDUPE_MS) return
928
- if (store.trace({ at: new Date(now).toISOString(), ev: 'brief', sid, ids, n: ids.length })) lastBrief.set(sid, { key, at: now })
990
+ if (store.trace({ at: new Date(now).toISOString(), ev: 'brief', sid, ids, n: ids.length })) { lastBrief.set(sid, { key, at: now }); trimSidMap(lastBrief) }
929
991
  } catch {
930
992
  // 记不上不能影响对话。
931
993
  }
package/lib/autodream.js CHANGED
@@ -18,16 +18,25 @@ export function maybeDream(store, opts = {}, now = Date.now()) {
18
18
  try {
19
19
  const total = store.streamSize()
20
20
  const st = store.dreamState()
21
- const last = Number(st?.line) || 0
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
25
- if (Number.isFinite(lastAt) && lastAt > 0 && now - lastAt < cfg.cooldownMs) {
32
+ // 时间戳落在未来(手动改时间/NTP 回拨)时不进冷却:否则要一直等到那个「未来」才肯再梦(2026-11-21 #32)。
33
+ const lastAtUsable = Number.isFinite(lastAt) && lastAt > 0 && lastAt <= now + 60_000
34
+ if (lastAtUsable && now - lastAt < cfg.cooldownMs) {
26
35
  return { ran: false, reason: 'cooldown', fresh, total, last, waitMs: cfg.cooldownMs - (now - lastAt) }
27
36
  }
28
37
  const result = dreamPass(store, { dryRun: cfg.dryRun })
29
38
  // 先梦再记账:梦崩了就把记忆点留着,下次还会重来,不会「以为梦过了」。
30
- store.setDreamState({ line: total, at: new Date(now).toISOString(), wrote: result.wrote })
39
+ store.setDreamState({ line: total, at: new Date(now).toISOString(), wrote: result.wrote, firstKey })
31
40
  return { ran: true, fresh, total, ...result }
32
41
  } catch (err) {
33
42
  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,13 @@ 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
- const cards = allCards.filter((c) => c.kind === 'experience' && c.created && now - Date.parse(c.created) <= lookbackDays * DAY)
104
+ // 死卡不进归纳:被接替/已过期的旧说法若经 insight 复活,等于绕过全部死卡闸门(2026-11-21 B2)。
105
+ const cards = allCards.filter((c) => {
106
+ if (c.kind !== 'experience' || isDead(c, now) || !c.created) return false
107
+ // created 坏掉的卡(手改、旧版写坏)永远算不进窗口,别让一张坏卡把整趟做梦拖死(2026-11-21 #40)。
108
+ const t = Date.parse(c.created)
109
+ return Number.isFinite(t) && now - t <= lookbackDays * DAY
110
+ })
105
111
 
106
112
  const groups = new Map()
107
113
  for (const card of cards) {
@@ -142,7 +148,8 @@ export function dreamPass(store, opts = {}) {
142
148
  continue
143
149
  }
144
150
  const insight = {
145
- id: `ins-${tag.replace(/[^\w\u4e00-\u9fff]+/g, '')}-${Date.now().toString(36)}`,
151
+ // 同一毫秒对同一 tag 梦两次会撞 id(后写覆盖前写),加 4 位随机尾巴(2026-11-21 #41)。
152
+ id: `ins-${tag.replace(/[^\w\u4e00-\u9fff]+/g, '')}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
146
153
  kind: 'insight',
147
154
  source: 'self',
148
155
  tags: [tag, '梦游整理'],
@@ -179,9 +186,18 @@ export function dreamPass(store, opts = {}) {
179
186
  skipped.push({ tag, sim: Number(twin.sim.toFixed(2)), idOverlap: Number(twin.idOverlap.toFixed(2)), twin: twin.c.id })
180
187
  continue
181
188
  }
182
- if (!dryRun) store.put(insight)
183
- // 这一趟新写的也要进快照,否则同一趟里后面的标签组撞不出孪生,会再写一张同质卡(13:20 复核实测 0.951)。
184
- insightsAll.push(insight)
189
+ if (!dryRun) {
190
+ try {
191
+ store.put(insight)
192
+ } catch (err) {
193
+ // 一张卡写不进(磁盘满/权限/坏 id)不能把整趟做梦带走,记进 skipped 让调用方看得见(2026-11-21 #38)。
194
+ skipped.push({ tag, reason: `落盘失败:${err?.message || err}`, from: ids })
195
+ continue
196
+ }
197
+ // 这一趟新写的也要进快照,否则同一趟里后面的标签组撞不出孪生,会再写一张同质卡(13:20 复核实测 0.951)。
198
+ // dryRun 下没落盘,就不该进快照(2026-11-21 #37)。
199
+ insightsAll.push(insight)
200
+ }
185
201
  insights.push({ tag, from: ids, id: insight.id, conflicts })
186
202
  }
187
203
  return { wrote: insights.length, insights, skipped }
package/lib/heat.js CHANGED
@@ -95,6 +95,9 @@ export function expiryMs(validUntil) {
95
95
  if (day) {
96
96
  // 按本机时区算「那天 23:59:59.999」,别用 Date.parse(它把纯日期当 UTC 零点)。
97
97
  const d = new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3]), 23, 59, 59, 999)
98
+ // 2 月 30 日这种不存在的日期,Date 会悄悄滚到 3 月 2 日,卡就比声明的多活几天(2026-11-21 #15)。
99
+ const rolled = d.getFullYear() !== Number(day[1]) || d.getMonth() !== Number(day[2]) - 1 || d.getDate() !== Number(day[3])
100
+ if (rolled) return 0
98
101
  return Number.isFinite(d.getTime()) ? d.getTime() : 0
99
102
  }
100
103
  const t = Date.parse(s)
package/lib/parse.js CHANGED
@@ -46,9 +46,12 @@ export function parseCue(cue, now = Date.now()) {
46
46
  const d = new Date(now)
47
47
  d.setMonth(Number(m[1]) - 1, Number(m[2]))
48
48
  d.setHours(0, 0, 0, 0)
49
- out.since = d.getTime()
50
- out.until = out.since + DAY_MS
51
- out.when = `${m[1]}月${m[2]}日`
49
+ // 2 月 30 日会滚成 3 月 2 日:不存在的日期就当没说,别拿错的一天去搜(2026-11-21 #31)。
50
+ if (d.getMonth() === Number(m[1]) - 1 && d.getDate() === Number(m[2])) {
51
+ out.since = d.getTime()
52
+ out.until = out.since + DAY_MS
53
+ out.when = `${m[1]}月${m[2]}日`
54
+ }
52
55
  }
53
56
  }
54
57
 
package/lib/prompt.js CHANGED
@@ -11,6 +11,17 @@ import { expiryMs } from './heat.js'
11
11
  const DEFAULT_COMPRESSION_LOG = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'notes', 'compression.log')
12
12
  const COMPRESSION_LOG = process.env.HC_COMPRESSION_LOG || DEFAULT_COMPRESSION_LOG
13
13
 
14
+ /** 按码点截断:text.slice 可能正好切在 emoji 的代理对中间,吐半个字符(2026-11-21 #35)。 */
15
+ export function safeCut(text, n) {
16
+ const s = String(text ?? '')
17
+ const k = Math.max(0, Math.trunc(Number(n) || 0))
18
+ if (k <= 0) return ''
19
+ if (k >= s.length) return s
20
+ const code = s.charCodeAt(k - 1)
21
+ // 落点前一个是「高代理」=正切在一个字符的中间,退一位
22
+ return s.slice(0, code >= 0xd800 && code <= 0xdbff ? k - 1 : k)
23
+ }
24
+
14
25
  /** 上一次被折叠的记录:让本鲸知道自己刚被压过,好去自检。 */
15
26
  export function lastCompression(logPath = COMPRESSION_LOG) {
16
27
  try {
@@ -21,7 +32,9 @@ export function lastCompression(logPath = COMPRESSION_LOG) {
21
32
  const last = lines[lines.length - 1]
22
33
  const stamp = last.match(/(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2})/)
23
34
  if (stamp) {
24
- const t = Date.parse(`${stamp[1]}T${stamp[2]}:00+08:00`)
35
+ // 按本机本地时区解析:压缩日志里的时间戳是写日志那台机器的本地时间。
36
+ // 原来硬编码 +08:00,人不在东八区就会偏 8 小时,把「刚折叠过」判成好几天前(2026-11-21 B15)。
37
+ const t = Date.parse(`${stamp[1]}T${stamp[2]}:00`)
25
38
  if (Number.isFinite(t) && Date.now() - t > 24 * 3600 * 1000) return ''
26
39
  }
27
40
  return last.replace(/^- /, '').trim()
@@ -61,8 +74,11 @@ export function renderSnapshot({ store, hot = [], briefs = [], catalog = [], cat
61
74
  const lines = hot.map((c) => {
62
75
  const 来源 = c.source === 'owner' ? '主人亲口' : '本鲸推的'
63
76
  const 价 = c.conflict ? ' ⚠与旧说法冲突' : ''
77
+ // 0 = 「没写有效期 / 日期读不懂」(heat.js:93/100 的既有约定),不能当「1970 年就过期了」:
78
+ // 否则同一张卡 isDead 放行、这里却标「已过期」,两处口径打架(2026-11-21 只读复核 #15)。
79
+ const 期终点 = expiryMs(c.valid_until)
64
80
  const 期 = c.valid_until
65
- ? expiryMs(c.valid_until) < Date.now()
81
+ ? 期终点 > 0 && 期终点 < Date.now()
66
82
  ? '(已过期,别再当现在的事实用)'
67
83
  : `(有效期到 ${c.valid_until})`
68
84
  : ''
@@ -93,7 +109,7 @@ export function renderSnapshot({ store, hot = [], briefs = [], catalog = [], cat
93
109
  const 无证据 = c.source_type === 'no-evidence' ? '〔无证据〕' : ''
94
110
  let line = `- ${短id}${truncate(c.title || c.body, cap)}(重量 ${c.live_weight?.toFixed(2) ?? '?'}${期}${价})${无证据}`
95
111
  // 只有截短阶段才允许硬切;正常渲染一个字节都不动(老卡/现有输出不变)。
96
- if (cut && line.length > 60) line = `${line.slice(0, 59)}…`
112
+ if (cut && line.length > 60) line = `${safeCut(line, 59)}…`
97
113
  return line
98
114
  }
99
115
  const renderCatalogItem = (x) => `${x.pinned ? '★' : ''}${x.id ? String(x.id).slice(-4) + '· ' : ''}${x.title}`
@@ -197,7 +213,7 @@ export function renderSnapshot({ store, hot = [], briefs = [], catalog = [], cat
197
213
  if (budget <= marker.length) {
198
214
  text = ''
199
215
  } else {
200
- text = `${text.slice(0, budget - marker.length).trimEnd()}${marker}`
216
+ text = `${safeCut(text, budget - marker.length).trimEnd()}${marker}`
201
217
  }
202
218
  degraded = 'truncate'
203
219
  }
@@ -210,12 +226,12 @@ export function renderSnapshot({ store, hot = [], briefs = [], catalog = [], cat
210
226
  const allowed = MAX_CHARS - GUARD_NOTE.length - SEP.length - warn.length - SEP.length
211
227
  if (allowed >= 0 && text.length > allowed) {
212
228
  const marker = tail.length > kept.length ? '…(超长截断,因果链已让位)' : '…(超长截断)'
213
- text = allowed > marker.length ? `${text.slice(0, allowed - marker.length).trimEnd()}${marker}` : ''
229
+ text = allowed > marker.length ? `${safeCut(text, allowed - marker.length).trimEnd()}${marker}` : ''
214
230
  degraded = 'truncate'
215
231
  }
216
232
  }
217
233
 
218
- const out = `${text.slice(0, Math.max(0, budget))}${SEP}${GUARD_NOTE}${warn ? SEP + warn : ''}`
234
+ const out = `${safeCut(text, Math.max(0, budget))}${SEP}${GUARD_NOTE}${warn ? SEP + warn : ''}`
219
235
  if (st) {
220
236
  st.briefsWanted = briefs.length
221
237
  st.briefsRendered = briefState.length
package/lib/recall.js CHANGED
@@ -593,7 +593,8 @@ export function keywordFallback(store, cue, opts = {}) {
593
593
  excerpt: excerptAround(c.body, hit[0]),
594
594
  coverage: Number((hit.length / rare.length).toFixed(2)),
595
595
  matched: hit.slice(0, 6),
596
- expired: Boolean(c.valid_until && expiryMs(c.valid_until) < now) || Boolean(c.superseded_by),
596
+ // 同 isDead / 上面 :359 的口径:0 是「没写 / 读不懂」,不是「过期了」(2026-11-21 只读复核 #15)。
597
+ expired: Boolean(c.valid_until && expiryMs(c.valid_until) > 0 && expiryMs(c.valid_until) < now) || Boolean(c.superseded_by),
597
598
  lowConfidence: true,
598
599
  })
599
600
  }
@@ -678,7 +679,10 @@ export function injectionBriefs(store, opts = {}) {
678
679
  const shownIds = new Set([...(opts.excludeIds || []), ...pinnedIds])
679
680
  const dynamic = live.filter((c) => !shownIds.has(c.id))
680
681
  const lastHit = (c) => {
681
- const t = Date.parse(c.last_hit || '')
682
+ // last_hit 读回来是毫秒数字(store 的 parse),Date.parse(数字) 恒 NaN,
683
+ // 排序会退化成纯重量序、轮换公平性失效(2026-11-21 B5)。老卡偶尔是 ISO 串,两种都认。
684
+ const raw = c.last_hit
685
+ const t = typeof raw === 'number' ? raw : Date.parse(raw || '')
682
686
  return Number.isFinite(t) ? t : 0
683
687
  }
684
688
  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
- writeFileSync(tmp, text, { mode: 0o600 })
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: ${String(card.condition || '').replace(/\s*\n\s*/g, ' ⏎ ').trim()}`,
181
- `source_date: ${card.source_date || ''}`,
182
- `supersedes: ${card.supersedes || ''}`,
183
- `superseded_by: ${card.superseded_by || ''}`,
184
- `quote: ${String(card.quote || '').replace(/\s*\n\s*/g, ' ⏎ ').trim()}`,
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
- if (!existsSync(path)) return undefined
284
- return parseCard(id, readFileSync(path, 'utf8'), statSync(path).mtimeMs)
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
- weight: card.weight ?? prev?.weight ?? this.heat.initialWeight,
395
- last_hit: card.last_hit ?? prev?.last_hit ?? Date.now(),
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(),
@@ -409,8 +434,9 @@ export class HippocampusStore {
409
434
  try {
410
435
  const dir = join(this.dir, 'history', String(card.id))
411
436
  mkdirSync(dir, { recursive: true })
412
- const stamp = new Date().toISOString().replace(/[:.]/g, '-')
413
- writeFileSync(join(dir, `${stamp}.md`), renderCard(card))
437
+ // 同一毫秒存两次会撞名、后一份把前一份盖掉(2026-11-21 #26):加 3 位随机尾巴,顺手 0600。
438
+ const stamp = `${new Date().toISOString().replace(/[:.]/g, '-')}-${Math.random().toString(36).slice(2, 5)}`
439
+ writeFileSync(join(dir, `${stamp}.md`), renderCard(card), { mode: 0o600 })
414
440
  // 每张卡最多留 20 个旧版,超了从最老的开始删。
415
441
  const files = readdirSync(dir).filter((f) => f.endsWith('.md')).sort()
416
442
  for (const f of files.slice(0, Math.max(0, files.length - 20))) rmSync(join(dir, f), { force: true })
@@ -421,10 +447,13 @@ export class HippocampusStore {
421
447
  }
422
448
 
423
449
  remove(id) {
450
+ // id 直接拼路径:与 get/put 同口径校验,别让 ../ 把 notes 外的文件挪进 trash(2026-11-21 B4)。
451
+ id = assertSafeId(id)
424
452
  const path = join(this.notesDir, `${id}.md`)
425
453
  if (!existsSync(path)) return true
426
454
  // 不直接 rm:先挪进 trash/<日期>/,留一条退路(主人 2026-11-06 定的规矩,这里落成代码)。
427
- const day = new Date().toISOString().slice(0, 10)
455
+ // 本地日期:UTC 日期在东八区会让「今天删的」跑进昨天/明天的桶(2026-11-21 #1)。
456
+ const day = localDay(Date.now())
428
457
  const trashDir = join(this.dir, 'trash', day)
429
458
  mkdirSync(trashDir, { recursive: true })
430
459
  renameSync(path, join(trashDir, `${id}.md`))
@@ -460,6 +489,10 @@ export class HippocampusStore {
460
489
  // 窗口内不重复加成、也不重复记账。直接调 touch 不带参数时行为不变。
461
490
  if (dedupeMs > 0) {
462
491
  this._lastTouch ||= new Map()
492
+ // 只增不删会随「碰过的卡数」一直涨;超过 512 条时清掉 24 小时前的(2026-11-21 #22)。
493
+ if (this._lastTouch.size > 512) {
494
+ for (const [k, at] of this._lastTouch) if (now - at > 86_400_000) this._lastTouch.delete(k)
495
+ }
463
496
  const prev = this._lastTouch.get(id) || 0
464
497
  if (now - prev < dedupeMs) return card
465
498
  this._lastTouch.set(id, now)
@@ -478,15 +511,21 @@ export class HippocampusStore {
478
511
 
479
512
  // ── 用进废退的账本 ──────────────────────────────────────────────────────
480
513
  logRehearsal({ id, from = 0, to = 0, cue = '', at = Date.now() }) {
481
- this.ensure()
482
- const line = JSON.stringify({
483
- at: new Date(at).toISOString(),
484
- id,
485
- from: Number(Number(from).toFixed(3)),
486
- to: Number(Number(to).toFixed(3)),
487
- cue: String(cue || '').slice(0, 60),
488
- })
489
- appendFileSync(this.rehearsalPath, `${line}\n`)
514
+ // 记账是旁路:磁盘满 / 目录只读 / 权限错都不该把这一轮召回整条打掉(2026-11-21 #27)。
515
+ try {
516
+ this.ensure()
517
+ const line = JSON.stringify({
518
+ at: new Date(at).toISOString(),
519
+ id,
520
+ from: Number(Number(from).toFixed(3)),
521
+ to: Number(Number(to).toFixed(3)),
522
+ cue: String(cue || '').slice(0, 60),
523
+ })
524
+ appendFileSync(this.rehearsalPath, `${line}\n`, { mode: 0o600 })
525
+ return true
526
+ } catch {
527
+ return false
528
+ }
490
529
  }
491
530
 
492
531
  /** id → 被想起过几次。 */
@@ -519,6 +558,16 @@ export class HippocampusStore {
519
558
  return streamSize(this)
520
559
  }
521
560
 
561
+ streamFirstAt() {
562
+ this.ensure()
563
+ return streamFirstAt(this)
564
+ }
565
+
566
+ streamFirstKey() {
567
+ this.ensure()
568
+ return streamFirstKey(this)
569
+ }
570
+
522
571
  // ── 按量做梦的记忆点:上次梦到 stream 第几行、什么时候(2026-11-12)──────
523
572
  dreamState() {
524
573
  this.ensure()
@@ -574,8 +623,12 @@ export class HippocampusStore {
574
623
 
575
624
  chainTail(lines = 20) {
576
625
  this.ensure()
626
+ // 负数会被 slice 当成「从尾部倒数」的反面(slice(-5) 是 slice(5)?不,slice(5) 是去掉前 5 行),
627
+ // 传 -5 原本返回除前 5 行外的全部,注入会撑爆(2026-11-21 #34)。
628
+ const n = Number.isFinite(Number(lines)) ? Math.max(0, Math.trunc(Number(lines))) : 20
629
+ if (n === 0) return []
577
630
  const all = readFileSync(this.chainPath, 'utf8').split('\n').filter(Boolean)
578
- return all.slice(-lines)
631
+ return all.slice(-n)
579
632
  }
580
633
 
581
634
  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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-memory-huixiang",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "你的 AI 是不是每次开新对话就忘了你是谁?回响给它一块记得住你的记忆——存在你自己电脑里,不经过任何云端。基于 cyber-hippocampus(赛博海马体)改造。",
5
5
  "license": "MIT",
6
6
  "repository": {