@ssamurias/dsh-fish 1.1.2 → 1.1.4

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 (77) hide show
  1. package/AGENTS.md +13 -7
  2. package/CHANGELOG.md +170 -0
  3. package/README.md +75 -4
  4. package/RELEASE-NOTES-1.1.3.md +89 -0
  5. package/RELEASE-NOTES-1.1.4.md +87 -0
  6. package/docs//350/256/244/344/272/272/345/210/244/346/215/256.md +4 -1
  7. package/lib/absence.js +1 -1
  8. package/lib/appoint.js +9 -1
  9. package/lib/ask.js +3 -3
  10. package/lib/backup.js +44 -1
  11. package/lib/basis.js +85 -0
  12. package/lib/capture.js +96 -4
  13. package/lib/claim.js +35 -0
  14. package/lib/client/01-state-load.js +41 -7
  15. package/lib/client/02-actions.js +27 -5
  16. package/lib/client/03-widgets-header.js +29 -1
  17. package/lib/client/04-pressure-lab.js +15 -0
  18. package/lib/client/09-tab-outing.js +88 -1
  19. package/lib/client/11-tab-data-frame.js +7 -3
  20. package/lib/client/12-pressure-chip-mount.js +14 -0
  21. package/lib/client.js +221 -17
  22. package/lib/comment.js +824 -823
  23. package/lib/compactionlog.js +181 -0
  24. package/lib/derive.js +290 -47
  25. package/lib/dream.js +3 -1
  26. package/lib/firstwake.js +6 -3
  27. package/lib/generator.js +4 -0
  28. package/lib/handoff.js +93 -8
  29. package/lib/health.js +4 -1
  30. package/lib/hear.js +67 -9
  31. package/lib/herpeople.js +28 -14
  32. package/lib/herperson.js +384 -0
  33. package/lib/home.js +8 -3
  34. package/lib/identity.js +100 -24
  35. package/lib/index.js +33 -2
  36. package/lib/letter.js +3 -1
  37. package/lib/mapserve.js +10 -0
  38. package/lib/match.js +3 -1
  39. package/lib/memorymap-html.js +1 -1
  40. package/lib/memorymap.js +22 -3
  41. package/lib/notice.js +60 -0
  42. package/lib/observe-bili.js +1 -1
  43. package/lib/observe-home.js +52 -7
  44. package/lib/observe-http.js +20 -1
  45. package/lib/observe-state.js +22 -3
  46. package/lib/observe-trip.js +1 -1
  47. package/lib/people.js +259 -22
  48. package/lib/peopledoc.js +1 -1
  49. package/lib/person.js +95 -0
  50. package/lib/persona.js +37 -24
  51. package/lib/proactive.js +1 -1
  52. package/lib/pronounask.js +2 -2
  53. package/lib/quota.js +34 -0
  54. package/lib/recall.js +267 -17
  55. package/lib/reset-pending.js +349 -0
  56. package/lib/reset.js +8 -4
  57. package/lib/restrict.js +1 -0
  58. package/lib/say.js +70 -10
  59. package/lib/scheduler.js +176 -28
  60. package/lib/schema.js +141 -2
  61. package/lib/selfdoc.js +13 -5
  62. package/lib/session-pressure-analysis.js +24 -4
  63. package/lib/session-pressure-data.js +5 -0
  64. package/lib/session-pressure.js +32 -6
  65. package/lib/settings.js +3 -2
  66. package/lib/sleepfact.js +9 -3
  67. package/lib/stance.js +56 -19
  68. package/lib/store.js +53 -5
  69. package/lib/talkmem.js +151 -21
  70. package/lib/turnexport.js +34 -5
  71. package/lib/turns.js +70 -9
  72. package/lib/types.d.ts +12 -2
  73. package/lib/unclaimed.js +102 -0
  74. package/lib/whatseen.js +17 -0
  75. package/lib/wiki.js +86 -1
  76. package/lib/works.js +2 -0
  77. package/package.json +1 -1
@@ -47,8 +47,15 @@ export function analyzePressureEvents(events, checkpoint = null, saveCheckpoint
47
47
  let envelope = checkpoint?.envelope ?? null
48
48
  let toolSnapshot = checkpoint?.toolSnapshot ?? null
49
49
  let requestEnvelope = checkpoint?.requestEnvelope ?? null
50
- const compaction = checkpoint?.compaction ?? { summaries: 0, reported: 0, tokens: 0, shadowed: null }
50
+ // 最近一次压缩的完整身份(1.1.4,外部报告 B8):除了「压掉多少」,还要记住是哪一次、
51
+ // 是不是手动 `/compact`、压掉几条历史、摘要事件落在哪个 seq——后面「压完剩多少」
52
+ // 只能从这次压缩之后的第一次请求反推,没有 seq 就对不上号。
53
+ const compaction = checkpoint?.compaction ?? { summaries: 0, reported: 0, tokens: 0, shadowed: null,
54
+ shadowedCount: null, id: null, seq: null, at: null, manual: false }
51
55
  const compactionEvents = checkpoint?.compactionEvents ?? { started: 0, succeeded: 0, failed: 0, summaries: 0, prunes: 0 }
56
+ // 手动 /compact 的标记落在 `compaction/start` 上,摘要事件不一定带 `sourceCommandId`;
57
+ // 按 compactionId 先记下,等摘要到了再认领,end 时清掉(失败的压缩不该改标签)。
58
+ const manualStarts = new Map(checkpoint?.manualStarts ?? [])
52
59
  const toolResults = new Map(checkpoint?.toolResults)
53
60
  let surfaceKnown = checkpoint?.surfaceKnown ?? true
54
61
  function measureRequest(turn, step, seq) {
@@ -84,8 +91,16 @@ export function analyzePressureEvents(events, checkpoint = null, saveCheckpoint
84
91
  toolTokens: toolChars == null ? null : toolChars ? Math.ceil(toolChars / 4) + 4 : 0 }
85
92
  }
86
93
  if (event.type === 'assistant/message' && usageOf(data.usage).comparable) requestEnvelope = envelope
87
- if (event.type === 'compaction/start') compactionEvents.started++
88
- if (event.type === 'compaction/end') compactionEvents[data.error ? 'failed' : 'succeeded']++
94
+ if (event.type === 'compaction/start') {
95
+ compactionEvents.started++
96
+ const cid = String(data.compactionId ?? '')
97
+ if (cid && data.sourceCommandId) manualStarts.set(cid, true)
98
+ if (manualStarts.size > 64) manualStarts.delete(manualStarts.keys().next().value)
99
+ }
100
+ if (event.type === 'compaction/end') {
101
+ compactionEvents[data.error ? 'failed' : 'succeeded']++
102
+ manualStarts.delete(String(data.compactionId ?? ''))
103
+ }
89
104
  if (event.type === 'compaction/prune') compactionEvents.prunes++
90
105
  if (event.type === 'compaction/summary') {
91
106
  compactionEvents.summaries++
@@ -93,6 +108,11 @@ export function analyzePressureEvents(events, checkpoint = null, saveCheckpoint
93
108
  compaction.summaries++
94
109
  if (usage.total != null) { compaction.reported++; compaction.tokens += usage.total }
95
110
  compaction.shadowed = count(data.shadowedTokenCount)
111
+ compaction.shadowedCount = Array.isArray(data.shadowedSeqs) ? data.shadowedSeqs.length : null
112
+ compaction.id = typeof data.compactionId === 'string' && data.compactionId ? data.compactionId : null
113
+ compaction.seq = Number.isSafeInteger(event.seq) ? event.seq : null
114
+ compaction.at = typeof event.time === 'string' ? event.time : null
115
+ compaction.manual = Boolean(data.sourceCommandId) || (compaction.id != null && manualStarts.get(compaction.id) === true)
96
116
  }
97
117
  const turnId = count(data.turn)
98
118
  if (event.type === 'assistant/chunk' && turnId != null && (dispatch?.turn !== turnId || dispatch?.step !== data.step)) {
@@ -291,6 +311,6 @@ export function analyzePressureEvents(events, checkpoint = null, saveCheckpoint
291
311
  turns: [...turns.values()].map(turn => ({ ...turn, steps: [...turn.steps], routes: [...turn.routes],
292
312
  attemptsByStep: [...turn.attemptsByStep] })),
293
313
  callNames: [...callNames], surface, activeTools: [...activeTools], surfacePrices: [...surfacePrices], surfaceTokens, dispatch,
294
- burden: [...burden], route, surfaceKnown, envelope, requestEnvelope, toolSnapshot, compaction, compactionEvents, toolResults: [...toolResults],
314
+ burden: [...burden], route, surfaceKnown, envelope, requestEnvelope, toolSnapshot, compaction, compactionEvents, manualStarts: [...manualStarts], toolResults: [...toolResults],
295
315
  } } : {}) }
296
316
  }
@@ -89,6 +89,9 @@ export function pressureDataDictionary(rounds, samples, request, details = {}, c
89
89
  row('压缩占用减少量', 'DSH tokenMeter 压缩边界采样', compactionPair,
90
90
  compactionPair ? compactionPair.before - compactionPair.after : null, 'Token',
91
91
  '最近一次有效配对', '压缩前占用 − 压缩后占用', '估算'),
92
+ row('压缩后 / 压缩前', 'DSH tokenMeter 压缩边界采样', compactionPair,
93
+ ratio(compactionPair?.after, compactionPair?.before), '%',
94
+ '最近一次有效配对', '压缩后占用 ÷ 压缩前占用', '估算'),
92
95
  ] },
93
96
  { id: 'G', title: '增长负担', rows: [
94
97
  row('逐轮净变化', '相邻轮末 tokenMeter 采样', { previous: previousSample?.tokens, current: lastSample?.tokens,
@@ -126,6 +129,8 @@ export function pressureDataDictionary(rounds, samples, request, details = {}, c
126
129
  details.compaction?.reported ? details.compaction.tokens : null, 'Token', '会话 · 已报告的压缩调用', 'Σ 已报告的压缩输入与输出 Token'),
127
130
  row('最近一次压缩替换的原文规模', 'DSH compaction/summary.shadowedTokenCount', details.compaction?.shadowed,
128
131
  details.compaction?.shadowed, 'Token', '最近一次压缩摘要', '原值', '估算'),
132
+ row('最近一次压缩收起的历史', 'DSH compaction/summary.shadowedSeqs', details.compaction?.shadowedCount,
133
+ details.compaction?.shadowedCount, '条', '最近一次压缩摘要', '原值'),
129
134
  ] },
130
135
  { id: 'A', title: '请求放大', rows: [
131
136
  row('模型请求数(含尝试)', 'assistant/message 与 assistant/attempt', { requests: last?.requests, attempts: last?.attempts }, total([last?.requests, last?.attempts]), '次', '最新完成轮', '成功请求数 + 失败尝试数'),
@@ -190,7 +190,7 @@ export function registerSessionPressure(ctx, root) {
190
190
  async function cachedAnalysis(id) {
191
191
  try {
192
192
  const value = JSON.parse(await fs.readFile(join(cacheDir, encodeURIComponent(id) + '.json'), 'utf8'))
193
- return value.version === 10 ? value : null
193
+ return value.version === 11 ? value : null
194
194
  } catch { return null }
195
195
  }
196
196
 
@@ -218,7 +218,7 @@ export function registerSessionPressure(ctx, root) {
218
218
  lastRequest: lastRecordedRequest(added, prior?.checkpoint.route, prior?.result.lastRequest) }
219
219
  await fs.mkdir(cacheDir, { recursive: true })
220
220
  await writeAtomic(join(cacheDir, encodeURIComponent(id) + '.json'), JSON.stringify({
221
- version: 10, cursor: snapshot.cursor, length: events.length, footer: footer(events.at(-1)), checkpoint, result,
221
+ version: 11, cursor: snapshot.cursor, length: events.length, footer: footer(events.at(-1)), checkpoint, result,
222
222
  }))
223
223
  return result
224
224
  } catch {
@@ -548,9 +548,10 @@ export function registerSessionPressure(ctx, root) {
548
548
  return mutateJson(file, async () => {
549
549
  if ((await readHome()).sessionId !== id) return
550
550
  const state = await read()
551
- state.compactions = { ...state.compactions, [id]: { before: before.tokens, after: point.tokens } }
551
+ const pair = { before: before.tokens, after: point.tokens, id: compactionId }
552
+ state.compactions = { ...state.compactions, [id]: pair }
552
553
  state.compactionPairs ??= {}
553
- state.compactionPairs[id] = { ...state.compactionPairs[id], [event.seq]: state.compactions[id] }
554
+ state.compactionPairs[id] = { ...state.compactionPairs[id], [event.seq]: pair }
554
555
  await fs.mkdir(dir, { recursive: true })
555
556
  await writeAtomic(file, JSON.stringify(state))
556
557
  })
@@ -688,7 +689,32 @@ export function registerSessionPressure(ctx, root) {
688
689
  const medianPoint = nearestCurve ? { turn: nearestCurve.turn, pct: nearestCurve.pct, n: nearestCurve.n } : null
689
690
  const interruptedRounds = (await readInterrupted(currentId)).length
690
691
  // 压缩记录只来自宿主事件流;别的压缩插件不共享数据(2026-11-18 用户 m03969)。
691
- const compactionCount = Object.keys(state.compactionPairs?.[currentId] ?? {}).length
692
+ // 次数用分析结果里的「成功结束」,没有分析结果才退回 tokenMeter 配对数:
693
+ // 没装 tokenMeter 时配对会漏计,压过也会显示 0 次(2026-11-29,外部报告 B8)。
694
+ const compactionCount = Number.isFinite(current.compactionEvents?.succeeded)
695
+ ? current.compactionEvents.succeeded
696
+ : Object.keys(state.compactionPairs?.[currentId] ?? {}).length
697
+ // 最近一次压缩(2026-11-29,外部报告 B8):
698
+ // · 压掉几条、多少 Token:`compaction/summary` 的原值,能直接标;
699
+ // · 压缩后剩多少:只有 tokenMeter 在同一个 compactionId 的开始/结束边界量到过,
700
+ // 才算「量到」(配对按 id 认,不拿最新一对硬凑);
701
+ // · 没有配对时,给「压缩后第一轮开头的请求输入」当代理值,并在文案里说清
702
+ // 它含了那一轮新说的话,不是净剩下的 Token。
703
+ const comp = current.compaction ?? null
704
+ const pair = comp?.id
705
+ ? Object.values(state.compactionPairs?.[currentId] ?? {}).find(item => item?.id === comp.id) ?? null
706
+ : null
707
+ const nextRow = comp?.seq != null
708
+ ? (current.rows ?? []).find(row => Number.isSafeInteger(row.metrics?.requestSeq) && row.metrics.requestSeq > comp.seq)
709
+ : null
710
+ const lastCompaction = comp && comp.summaries > 0
711
+ ? { id: comp.id ?? null, at: comp.at ?? null, manual: comp.manual === true,
712
+ count: Number.isSafeInteger(comp.shadowedCount) ? comp.shadowedCount : null,
713
+ shadowed: Number.isFinite(comp.shadowed) ? comp.shadowed : null,
714
+ before: pair?.before ?? null, after: pair?.after ?? null,
715
+ retained: pair && pair.before > 0 && Number.isFinite(pair.after) ? pair.after / pair.before : null,
716
+ nextInput: nextRow ? { turn: nextRow.turn, tokens: nextRow.metrics?.firstInput ?? null } : null }
717
+ : null
692
718
  const selectedHistory = history.filter(row => row.selected && !row.current)
693
719
  const pendingCount = history.filter(row => row.status === 'pending' || pending.get(row.id)?.titleOnly).length
694
720
  const analyzedCount = selectedHistory.filter(row => row.status === 'analyzed').length
@@ -700,7 +726,7 @@ export function registerSessionPressure(ctx, root) {
700
726
  if (comparison) {
701
727
  try { await saveDiagnostic(currentDiagnostic) } catch { comparison.saveFailed = true }
702
728
  }
703
- return { ...view, compositeAverage, updatedAt: Date.now(), availability: current.status, historyCurve, medianPoint, interruptedRounds, compactionCount, lastRequest: current.lastRequest, load: buildSessionLoad(current, partial ? [] : loadHistory, null, referenceRounds),
729
+ return { ...view, compositeAverage, updatedAt: Date.now(), availability: current.status, historyCurve, medianPoint, interruptedRounds, compactionCount, lastCompaction, lastRequest: current.lastRequest, load: buildSessionLoad(current, partial ? [] : loadHistory, null, referenceRounds),
704
730
  usage: { structurePressure: structurePressureInputs(current), requestBurden: requestBurdenInputs(current.rows ?? [], current.lastRequest?.contextWindow ?? null),
705
731
  amplificationHistory, dictionary, comparison, latest: current.latest, burden: current.burden?.slice(0, 10),
706
732
  retentionComplete: current.retentionComplete, toolResults: current.toolResults ?? [],
package/lib/settings.js CHANGED
@@ -136,7 +136,8 @@ export const DEFAULTS = {
136
136
  // 2026-11-07(用户 m00365):恢复自动刷,但换了挂法——它不再挂在「醒来」上,
137
137
  // 而是自己按时间段走一趟(见 lib/scheduler.js 的 quietBrowse):
138
138
  // 只取、只记账,不叫醒、不往这一轮的正文里塞十几条简介热评。
139
- // 下一次醒来只带一行「今天你自己翻过 N 条(标题…)」,要看细节她自己调 bili_look。
139
+ // 下一次醒来只带一行便条,照实说是后台刷到的、不是她翻的(2026-11-23,见 browseDigestLine),
140
+ // 要看细节她自己调 bili_look。
140
141
  // 关掉这一项 = 不再自动替她逛;她想看的时候仍然可以自己调工具(那由 bili.enabled 管)。
141
142
  enabled: true,
142
143
  perDay: 1, // 每天最多刷几次(0 = 从不)
@@ -928,7 +929,7 @@ export async function updateConfig(patch, root) {
928
929
  if (Number(next.growthDays) !== Number(cur.growthDays)) {
929
930
  try {
930
931
  const { events } = await readEvents(root)
931
- const before = deriveSelf(events, { growthDays: cur.growthDays })
932
+ const before = deriveSelf(events, { growthDays: cur.growthDays, owner: cur.owner })
932
933
  await appendEvent(
933
934
  { type: 'meta', text: `stage-was:${before.stage}` },
934
935
  { day: before.day, stage: before.stage, source: 'system' },
package/lib/sleepfact.js CHANGED
@@ -18,7 +18,7 @@
18
18
  * - 不写 `sleep:`;不新增事件类型;只读。
19
19
  */
20
20
 
21
- import { tsMs } from './schema.js'
21
+ import { tsMs, isContactEvent } from './schema.js'
22
22
  import { HER_WORDS, clipLine } from './dreamtable.js'
23
23
 
24
24
  const HOUR_MS = 3_600_000
@@ -29,7 +29,13 @@ function isWake(e) {
29
29
 
30
30
  function isActivity(e) {
31
31
  // 醒着时留下的事:她写下的话、他说的话、听到的、看见的。meta 记账不算。
32
- return e?.type !== 'meta'
32
+ //
33
+ // 例外是 `meta seen:`(2026-11-23):它不是记账,是「他开口了」在事件流里留下的那一笔,
34
+ // 冷落检测、身份派生认的都是它(schema.js 的 isContactEvent,这里用同一份判定)。
35
+ // 走 /say 的桥(AGENTS.md §7.1)、桥房、靠工具回话的部署,他来过、她也答了,
36
+ // 事件流里常常只剩这一行:/say 不替她写 utterance,`heard` 每几轮才记一句。
37
+ // 不认它的话,他半夜来聊过一阵,早上照样说「从昨晚到现在,屋里没有别的动静」。
38
+ return e?.type !== 'meta' || isContactEvent(e)
33
39
  }
34
40
 
35
41
  function pad(n) {
@@ -71,7 +77,7 @@ export function sleepFacts(events = [], now = Date.now()) {
71
77
 
72
78
  // 这一段空白的起点是「上一次有动静」:她/他留下的话,或者一次醒来。
73
79
  // 但跨夜的整段要从睡前那句算起——半夜醒过一次不能把起点推到那次醒。
74
- // 所以先记下「最后一次非 meta 活动」;一条都没有时才退到上一次醒来。
80
+ // 所以先记下「最后一次活动」(非 meta,或者 seen:,见 isActivity);一条都没有时才退到上一次醒来。
75
81
  if (isWake(e)) {
76
82
  if (t > lastWake) lastWake = t
77
83
  middle.push({ t, text: String(e.text ?? '') })
package/lib/stance.js CHANGED
@@ -21,6 +21,8 @@ import { dateKey, loadConfig } from './settings.js'
21
21
  import { rootDir, readEvents } from './store.js'
22
22
  import { fillOwner } from './pronoun.js'
23
23
  import { clipText } from './clip.js'
24
+ // 判断的来源(1.1.4,issue #183):只在 her_stance 的明细里跟一句,不进身份文档。
25
+ import { basisText } from './basis.js'
24
26
  import { defineTool } from './tool.js'
25
27
  import { toJsonSchema } from './toolschema.js'
26
28
 
@@ -347,6 +349,9 @@ export function buildStances(model = {}, { limit = STANCE_MAX } = {}) {
347
349
  // members 把影子也列进来:her_stance 的明细是给她核对「这条是怎么长出来的」,
348
350
  // 旧说法也是来历的一部分。
349
351
  members: [...group, ...shadows].map((x) => x.id),
352
+ // 代表句的来源(1.1.4,issue #183)。只给 her_stance 的明细看,
353
+ // 不写进身份文档——预算、以及「不摆设置」那条线都靠这个边界。
354
+ basis: Array.isArray(latest.basis) ? latest.basis.slice() : undefined,
350
355
  since: latest.since ?? null,
351
356
  ...cost,
352
357
  backed,
@@ -410,49 +415,75 @@ function sideOf(kind) {
410
415
  * 这件事你没答应」,一条是她说的态度,一条是她没做的事,少了哪条都是少一段来历。
411
416
  * 拒绝类有疤(scars > 0)时照留——那是真栽过一次,不是重复表态。
412
417
  */
418
+ function stanceTopicText(s) {
419
+ const text = String(s?.text ?? '').trim()
420
+ const act = String(s?.act ?? '').trim()
421
+ if (s?.kind === 'refused' && act && !text.startsWith(act)) return `${act}${text}`
422
+ return text
423
+ }
424
+
425
+ function sameStanceTopic(a, b) {
426
+ return sameTopic(a?.text, b?.text) || sameTopic(stanceTopicText(a), stanceTopicText(b))
427
+ }
428
+
413
429
  function dedupeSameSide(list) {
414
430
  return list.filter((s) => {
415
431
  if (s.kind !== 'refused' || s.scars > 0) return true
416
432
  const mine = String(s.quote ?? s.text ?? '').trim()
417
433
  if (!mine) return true
418
- return !list.some(
434
+ const keeper = list.find(
419
435
  (o) => o !== s
420
436
  && o.kind !== 'refused'
421
437
  && sideOf(o.kind) === sideOf(s.kind)
422
438
  && similarity(mine, String(o.text ?? '').trim()) >= 0.9,
423
439
  )
440
+ if (!keeper) return true
441
+ // 记录被吸收进判断立场的拒绝 id:若 keeper 最终排进前 STANCE_PROMPT_MAX,
442
+ // 「你拒绝过」不再重复写同一句;若 keeper 排在第 9–12 条没进文档,拒绝仍留在「你拒绝过」里。
443
+ keeper.absorbedRefusalIds = [...new Set([...(keeper.absorbedRefusalIds ?? []), ...(s.members ?? [])])]
444
+ return false
424
445
  })
425
446
  }
426
447
 
427
448
  function resolveConflicts(groups) {
428
449
  const out = []
429
450
  for (const g of groups) {
430
- const clash = out.findIndex(
431
- (o) => sideOf(o.kind) !== sideOf(g.kind) && sameTopic(o.text, g.text),
451
+ const clashes = out.filter(
452
+ (o) => sideOf(o.kind) !== sideOf(g.kind) && sameStanceTopic(o, g),
432
453
  )
433
- if (clash < 0) {
454
+ if (!clashes.length) {
434
455
  out.push(g)
435
456
  continue
436
457
  }
437
- const other = out[clash]
438
- const a = sinceOf(other)
439
458
  const b = sinceOf(g)
440
- if (a === null || b === null || a === b) {
459
+ const older = []
460
+ const newer = []
461
+ const tied = []
462
+ for (const other of clashes) {
463
+ const a = sinceOf(other)
464
+ if (a === null || b === null || a === b) tied.push(other)
465
+ else if (b > a) older.push(other)
466
+ else newer.push(other)
467
+ }
468
+ if (newer.length) {
469
+ for (const other of newer) other.changedFrom = g.text
470
+ continue
471
+ }
472
+ if (older.length) {
473
+ const drop = new Set(older)
474
+ for (let i = out.length - 1; i >= 0; i--) {
475
+ if (drop.has(out[i])) out.splice(i, 1)
476
+ }
477
+ g.changedFrom = older[older.length - 1].text
478
+ }
479
+ for (const other of tied) {
441
480
  // 判不出先后:不替她选,也不把两条一起删(2026-11-22,用户 m00360)。
442
481
  // 两条都留,互相记一个成员 id;渲染时合成一个单独的冲突块。
443
482
  // 两边都不挂 changedFrom——她没改过口,只是还没定。
444
483
  if (!other.conflictWith) other.conflictWith = String(g.members?.[0] ?? '')
445
484
  if (!g.conflictWith) g.conflictWith = String(other.members?.[0] ?? '')
446
- out.push(g)
447
- continue
448
- }
449
- if (b > a) {
450
- g.changedFrom = other.text
451
- out.splice(clash, 1)
452
- out.push(g)
453
- } else {
454
- other.changedFrom = g.text
455
485
  }
486
+ out.push(g)
456
487
  }
457
488
  // 一方被「后来的算数」挤掉时,另一方可能还留着指向它的 conflictWith。
458
489
  // 只保留互相指认的那一对;指空或单向的都清掉,免得渲染时误压「改过口」。
@@ -609,12 +640,13 @@ export function stanceDetail(model = {}, { limit = Number.MAX_SAFE_INTEGER } = {
609
640
  const byId = new Map(
610
641
  [...beliefs, ...refusals].filter((x) => x?.id).map((x) => [String(x.id), x]),
611
642
  )
612
- const shownIds = new Set(shownStances(stances).map((s) => String(s.members?.[0] ?? '')))
643
+ const shownSet = new Set(shownStances(stances))
613
644
  return stances.map((s) => ({
614
- shown: shownIds.has(String(s.members?.[0] ?? '')),
645
+ shown: shownSet.has(s),
615
646
  conflict: Boolean(s.conflictWith),
616
647
  kind: s.kind,
617
648
  text: s.text,
649
+ basis: Array.isArray(s.basis) ? s.basis.slice() : undefined,
618
650
  line: stanceLine(s).replace(/^-\s+/, ''),
619
651
  members: (Array.isArray(s.members) ? s.members : []).map((id) => {
620
652
  const ev = byId.get(String(id)) ?? {}
@@ -677,6 +709,11 @@ export function renderDetail(rows, near = []) {
677
709
  lines.push(' 这条是怎么来的:')
678
710
  for (const m of r.members) lines.push(` - ${m.at ? `${m.at} ` : ''}${m.text}(${m.id})`)
679
711
  }
712
+ // 凭据只跟一句,不展开成清单(1.1.4,issue #183)。拒绝类不是「她说的话」,不摆来源。
713
+ if (r.kind !== 'refused') {
714
+ const from = Array.isArray(r.basis) && r.basis.length ? basisText(r.basis) : '没说'
715
+ lines.push(` 来源:${from}`)
716
+ }
680
717
  }
681
718
  lines.push('')
682
719
  lines.push(
@@ -719,7 +756,7 @@ export function registerHerStance(ctx, deps = {}) {
719
756
  try {
720
757
  const { events } = await readEvents(root)
721
758
  const { config } = await loadConfig(root)
722
- const model = deriveSelf(events, { growthDays: config.growthDays })
759
+ const model = deriveSelf(events, { growthDays: config.growthDays, owner: config.owner })
723
760
  const rows = stanceDetail(model)
724
761
  // 空清单时把她记过的话原样摆出来(2026-11-20):不解释阈值,只说事实。
725
762
  const near = rows.length ? [] : uncountedRecords(model)
package/lib/store.js CHANGED
@@ -203,15 +203,54 @@ const cleanStrings = (v) => {
203
203
  return v
204
204
  }
205
205
 
206
+ /**
207
+ * 读全量事件流的进程内缓存(2026-11-29,issue #184)。
208
+ *
209
+ * 为什么要有它:设置页首屏一次打开会并发十几条请求,其中 `/state`、`/beliefs`、
210
+ * `/memory`、`/rules`、`/status`、`/templates` 每条都要一份**同一份**事件流。
211
+ * 以前每次都重读整个 events.jsonl 再逐行 JSON.parse、再过一遍 cleanStrings——
212
+ * 两千多条时一次几十毫秒,六条加起来就上百毫秒,全花在把同样的字解析六遍。
213
+ *
214
+ * 失效判据是 `(mtimeMs, size)` 而不是自己记账:写入口只有一个(appendLine),
215
+ * 但还原备份、导入、迁移、别的进程都可能换掉这个文件,只有 stat 看得见。
216
+ * 事件流只追加,所以 size 变了 mtime 一定也变了;反过来某些文件系统 mtime 粒度粗,
217
+ * 同一秒内两次追加靠 size 才分得开——两个一起比才不漏。
218
+ *
219
+ * 缓存**按 root 分开**:同一个进程里测试会开一堆临时 root,串味比慢严重得多。
220
+ * 上限 32 个 root,超了丢最久没读的那个(正常只有一两个)。
221
+ *
222
+ * @type {Map<string, { mtimeMs: number, size: number, result: { events: any[], skipped: number, legacy?: number } }>}
223
+ */
224
+ const eventsCache = new Map()
225
+ const EVENTS_CACHE_ROOTS = 32
226
+
227
+ /** 测试用:清掉缓存(改完文件又想让下一次读真的回盘)。 */
228
+ export function resetEventsCache() {
229
+ eventsCache.clear()
230
+ }
231
+
206
232
  export async function readEvents(root = rootDir()) {
207
233
  const p = paths(root).events
208
- let raw = ''
234
+ const key = String(root ?? '')
235
+ let stat = null
209
236
  try {
210
- raw = await fs.readFile(p, 'utf8')
237
+ stat = await fs.stat(p)
211
238
  } catch (err) {
212
- if (err.code === 'ENOENT') return { events: [], skipped: 0 }
213
- throw err
239
+ if (err.code !== 'ENOENT') throw err
214
240
  }
241
+ if (!stat) {
242
+ const empty = { events: [], skipped: 0 }
243
+ eventsCache.delete(key)
244
+ return empty
245
+ }
246
+ const hit = eventsCache.get(key)
247
+ if (hit && hit.mtimeMs === stat.mtimeMs && hit.size === stat.size) {
248
+ // 命中就把它挪到队尾(Map 保插入序,等于 LRU)
249
+ eventsCache.delete(key)
250
+ eventsCache.set(key, hit)
251
+ return hit.result
252
+ }
253
+ const raw = await fs.readFile(p, 'utf8')
215
254
  const events = []
216
255
  let skipped = 0
217
256
  let legacy = 0
@@ -234,7 +273,16 @@ export async function readEvents(root = rootDir()) {
234
273
  }
235
274
  }
236
275
  // legacy:这批事件里有多少条是「加版本号之前」写的。备份与自检会显示它。
237
- return { events, skipped, legacy }
276
+ const result = { events, skipped, legacy }
277
+ // 只缓「读成功」的结果。读失败照旧往上抛,不缓存错误——下一次要能重试。
278
+ eventsCache.delete(key)
279
+ eventsCache.set(key, { mtimeMs: stat.mtimeMs, size: stat.size, result })
280
+ while (eventsCache.size > EVENTS_CACHE_ROOTS) {
281
+ const oldest = eventsCache.keys().next()
282
+ if (oldest.done) break
283
+ eventsCache.delete(oldest.value)
284
+ }
285
+ return result
238
286
  }
239
287
 
240
288
  /**