dsh-plugin-memory 0.11.0 → 0.13.0

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/lib/client.js CHANGED
@@ -18,6 +18,7 @@ window.__ModuleLoader__.load({
18
18
 
19
19
  const React = react
20
20
  const CONFIG_URL = '/api/memory/config'
21
+ const CONTROL_URL = '/api/memory/control'
21
22
  const INSIGHTS_URL = '/api/memory/insights'
22
23
  const GRAPH_URL = '/api/memory/graph'
23
24
  /** Poll while the panel is open, so memory edits show up without a reload. */
@@ -60,6 +61,23 @@ window.__ModuleLoader__.load({
60
61
  recallIntervalHint: '每次随机在最短 ~ 最长之间取一个间隔,避免固定节奏',
61
62
  recallMaxPerSession: '每会话追忆次数',
62
63
  recallMaxPerSessionHint: '一个会话内最多主动追忆几次,避免打扰',
64
+ toneGuide: '语气引导',
65
+ toneGuideHint: '按语境微调说话方式(赶工、深夜、坏消息、里程碑),不改变事实、不越 SOUL 边界',
66
+ toneIntensity: '语气强度',
67
+ toneIntensityHint: 'low 仅调味 / medium 更明显 / off 纯工程口吻;任何档位都以事实优先',
68
+ toneLow: 'low(仅调味)',
69
+ toneMedium: 'medium(更明显)',
70
+ toneOff: 'off(纯工程口吻)',
71
+ growthRecap: '每周成长回顾',
72
+ growthRecapHint: '每周在追忆通道里说一次「这周我记住了什么」(第一人称,最多五句,可随时关闭)',
73
+ growthNow: '立即回顾',
74
+ growthNowHint: '手动触发一次成长回顾(尊重发言权仲裁;没有新内容时不发)',
75
+ growthNowRunning: '回顾中…',
76
+ growthNowOk: '已发送成长回顾',
77
+ growthNowDeferred: '另一插件正在说话,稍后再试',
78
+ growthNowEmpty: '这一周没有可回顾的新内容',
79
+ growthNowDisabled: '成长回顾已关闭',
80
+ growthNowFailed: '回顾失败:',
63
81
  minutesPlaceholder: '30',
64
82
  maxMinutesPlaceholder: '240',
65
83
  maxPerSessionPlaceholder: '3',
@@ -148,6 +166,23 @@ window.__ModuleLoader__.load({
148
166
  recallIntervalHint: 'A random interval between min and max each time, so the rhythm never feels fixed',
149
167
  recallMaxPerSession: 'Recalls per session',
150
168
  recallMaxPerSessionHint: 'Maximum proactive recalls in one session, to stay unobtrusive',
169
+ toneGuide: 'Tone guidance',
170
+ toneGuideHint: 'Shift register by context (crunch, late night, bad news, milestones) without changing facts or crossing the SOUL boundary',
171
+ toneIntensity: 'Tone intensity',
172
+ toneIntensityHint: 'low = light seasoning / medium = more visible / off = pure engineering voice; facts always win',
173
+ toneLow: 'low (light seasoning)',
174
+ toneMedium: 'medium (more visible)',
175
+ toneOff: 'off (pure engineering voice)',
176
+ growthRecap: 'Weekly growth recap',
177
+ growthRecapHint: 'Once a week, on the recall channel, say what I kept this week (first person, at most five sentences; can be turned off)',
178
+ growthNow: 'Review now',
179
+ growthNowHint: 'Send one growth recap right away (still respects the speech floor; no new material = no message)',
180
+ growthNowRunning: 'Reviewing…',
181
+ growthNowOk: 'Growth recap sent',
182
+ growthNowDeferred: 'Another plugin holds the floor; try again later',
183
+ growthNowEmpty: 'Nothing new to recap this week',
184
+ growthNowDisabled: 'Weekly recap is off',
185
+ growthNowFailed: 'Recap failed: ',
151
186
  minutesPlaceholder: '30',
152
187
  maxMinutesPlaceholder: '240',
153
188
  maxPerSessionPlaceholder: '3',
@@ -341,11 +376,12 @@ window.__ModuleLoader__.load({
341
376
  color: 'var(--dsw-alias-label-primary, inherit)',
342
377
  }
343
378
 
344
- function Toggle({ checked, disabled, onChange }) {
379
+ function Toggle({ checked, disabled, onChange, label }) {
345
380
  return React.createElement('button', {
346
381
  type: 'button',
347
382
  role: 'switch',
348
383
  'aria-checked': checked,
384
+ 'aria-label': label,
349
385
  disabled,
350
386
  onClick: () => onChange(!checked),
351
387
  style: {
@@ -376,7 +412,7 @@ window.__ModuleLoader__.load({
376
412
 
377
413
  function ErrorText({ message }) {
378
414
  const t = useT()
379
- return React.createElement('div', { style: { padding: '14px 16px', fontSize: '13px', lineHeight: '20px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' } },
415
+ return React.createElement('div', { role: 'alert', style: { padding: '14px 16px', fontSize: '13px', lineHeight: '20px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' } },
380
416
  t('loadFailed'), message)
381
417
  }
382
418
 
@@ -575,7 +611,7 @@ window.__ModuleLoader__.load({
575
611
  }
576
612
 
577
613
  /** 目录输入:草稿态编辑,blur / Enter 才写回,避免每次按键触发 Host 重排。 */
578
- function DirInput({ value, disabled, onCommit }) {
614
+ function DirInput({ value, disabled, onCommit, label }) {
579
615
  const t = useT()
580
616
  const [draft, setDraft] = React.useState(undefined)
581
617
  const shown = draft !== undefined ? draft : (value ?? '')
@@ -588,6 +624,7 @@ window.__ModuleLoader__.load({
588
624
  return React.createElement('input', {
589
625
  type: 'text',
590
626
  placeholder: t('dirPlaceholder'),
627
+ 'aria-label': label,
591
628
  disabled,
592
629
  value: shown,
593
630
  onChange: (event) => setDraft(event.target.value),
@@ -601,7 +638,7 @@ window.__ModuleLoader__.load({
601
638
  }
602
639
 
603
640
  /** 数字输入:草稿态编辑,blur / Enter 才写回(分钟/次数)。 */
604
- function NumberInput({ value, disabled, onCommit, placeholder }) {
641
+ function NumberInput({ value, disabled, onCommit, placeholder, label }) {
605
642
  const [draft, setDraft] = React.useState(undefined)
606
643
  const shown = draft !== undefined ? draft : (value ?? '')
607
644
  const commit = () => {
@@ -613,6 +650,7 @@ window.__ModuleLoader__.load({
613
650
  return React.createElement('input', {
614
651
  type: 'number',
615
652
  placeholder,
653
+ 'aria-label': label,
616
654
  disabled,
617
655
  value: shown,
618
656
  onChange: (event) => setDraft(event.target.value),
@@ -625,6 +663,18 @@ window.__ModuleLoader__.load({
625
663
  })
626
664
  }
627
665
 
666
+ /** 下拉选择:语气强度这类枚举配置,改动立即写回。 */
667
+ function SelectInput({ value, disabled, options, onChange, label }) {
668
+ return React.createElement('select', {
669
+ 'aria-label': label,
670
+ disabled,
671
+ value: value ?? '',
672
+ onChange: (event) => onChange(event.target.value),
673
+ style: { ...inputStyle, width: '190px', cursor: 'pointer' },
674
+ }, (options ?? []).map((option) =>
675
+ React.createElement('option', { key: option.value, value: option.value }, option.label)))
676
+ }
677
+
628
678
  function MemoryForm(props) {
629
679
  const t = useT(props)
630
680
  const { onSaved } = props
@@ -632,6 +682,43 @@ window.__ModuleLoader__.load({
632
682
  const [status, setStatus] = React.useState('loading')
633
683
  const [error, setError] = React.useState(undefined)
634
684
  const [saving, setSaving] = React.useState(false)
685
+ const [growthBusy, setGrowthBusy] = React.useState(false)
686
+ const [growthNotice, setGrowthNotice] = React.useState(undefined)
687
+
688
+ // Visible keyboard focus for every control in this panel (inline styles
689
+ // cannot express :focus-visible). The tag is removed with the panel.
690
+ React.useEffect(() => {
691
+ if (typeof document === 'undefined') return undefined
692
+ const tag = document.createElement('style')
693
+ tag.setAttribute('data-dsh-memory-focus', '')
694
+ tag.textContent = 'section [role="switch"]:focus-visible, section input:focus-visible, section select:focus-visible, section button:focus-visible, section a:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary, #4c8bf5); outline-offset: 2px; }'
695
+ document.head.appendChild(tag)
696
+ return () => tag.remove()
697
+ }, [])
698
+
699
+ const reviewNow = () => {
700
+ setGrowthBusy(true)
701
+ setGrowthNotice(undefined)
702
+ fetch(CONTROL_URL, {
703
+ method: 'POST',
704
+ headers: { 'content-type': 'application/json' },
705
+ body: JSON.stringify({ action: 'growth-now' }),
706
+ })
707
+ .then(async (response) => {
708
+ const body = await response.json().catch(() => ({}))
709
+ if (!response.ok) throw new Error(body.error ?? `POST ${response.status}`)
710
+ if (body.delivered === true) { setGrowthNotice(t('growthNowOk')); return }
711
+ const reason = body.reason
712
+ if (reason === 'deferred') { setGrowthNotice(t('growthNowDeferred')); return }
713
+ if (reason === 'empty') { setGrowthNotice(t('growthNowEmpty')); return }
714
+ if (reason === 'growth-disabled') { setGrowthNotice(t('growthNowDisabled')); return }
715
+ setGrowthNotice(t('growthNowEmpty'))
716
+ })
717
+ .catch((err) => {
718
+ setGrowthNotice(`${t('growthNowFailed')}${err instanceof Error ? err.message : String(err)}`)
719
+ })
720
+ .finally(() => setGrowthBusy(false))
721
+ }
635
722
 
636
723
  React.useEffect(() => {
637
724
  let alive = true
@@ -690,6 +777,7 @@ window.__ModuleLoader__.load({
690
777
  React.createElement('div', { style: subStyle }, t('enabledHint')),
691
778
  ),
692
779
  React.createElement(Toggle, {
780
+ label: t('enabled'),
693
781
  checked: value.enabled !== false,
694
782
  disabled,
695
783
  onChange: (next) => apply({ enabled: next }),
@@ -701,6 +789,7 @@ window.__ModuleLoader__.load({
701
789
  React.createElement('div', { style: subStyle }, t('memoryDirHint')),
702
790
  ),
703
791
  React.createElement(DirInput, {
792
+ label: t('memoryDir'),
704
793
  value: value.memoryDir,
705
794
  disabled,
706
795
  onCommit: (next) => apply({ memoryDir: next }),
@@ -712,6 +801,7 @@ window.__ModuleLoader__.load({
712
801
  React.createElement('div', { style: subStyle }, t('autoInjectHint')),
713
802
  ),
714
803
  React.createElement(Toggle, {
804
+ label: t('autoInject'),
715
805
  checked: value.autoInject !== false,
716
806
  disabled,
717
807
  onChange: (next) => apply({ autoInject: next }),
@@ -723,6 +813,7 @@ window.__ModuleLoader__.load({
723
813
  React.createElement('div', { style: subStyle }, t('deferUntilUserSpeaksHint')),
724
814
  ),
725
815
  React.createElement(Toggle, {
816
+ label: t('deferUntilUserSpeaks'),
726
817
  checked: value.deferUntilUserSpeaks !== false,
727
818
  disabled,
728
819
  onChange: (next) => apply({ deferUntilUserSpeaks: next }),
@@ -734,6 +825,7 @@ window.__ModuleLoader__.load({
734
825
  React.createElement('div', { style: subStyle }, t('activeSessionOnlyHint')),
735
826
  ),
736
827
  React.createElement(Toggle, {
828
+ label: t('activeSessionOnly'),
737
829
  checked: value.activeSessionOnly !== false,
738
830
  disabled,
739
831
  onChange: (next) => apply({ activeSessionOnly: next }),
@@ -745,6 +837,7 @@ window.__ModuleLoader__.load({
745
837
  React.createElement('div', { style: subStyle }, t('registerSkillHint')),
746
838
  ),
747
839
  React.createElement(Toggle, {
840
+ label: t('registerSkill'),
748
841
  checked: value.registerSkill !== false,
749
842
  disabled,
750
843
  onChange: (next) => apply({ registerSkill: next }),
@@ -756,6 +849,7 @@ window.__ModuleLoader__.load({
756
849
  React.createElement('div', { style: subStyle }, t('recallHint')),
757
850
  ),
758
851
  React.createElement(Toggle, {
852
+ label: t('recall'),
759
853
  checked: value.recallEnabled !== false,
760
854
  disabled,
761
855
  onChange: (next) => apply({ recallEnabled: next }),
@@ -788,13 +882,83 @@ window.__ModuleLoader__.load({
788
882
  React.createElement('div', { style: subStyle }, t('recallMaxPerSessionHint')),
789
883
  ),
790
884
  React.createElement(NumberInput, {
885
+ label: t('recallMaxPerSession'),
791
886
  value: value.recallMaxPerSession,
792
887
  disabled,
793
888
  placeholder: t('maxPerSessionPlaceholder'),
794
889
  onCommit: (next) => apply({ recallMaxPerSession: next }),
795
890
  }),
796
891
  ),
797
- error !== undefined ? React.createElement('div', { style: errorStyle }, t('saveFailed'), error) : null,
892
+ React.createElement('div', { style: rowStyle },
893
+ React.createElement('div', null,
894
+ React.createElement('div', { style: labelStyle }, t('toneGuide')),
895
+ React.createElement('div', { style: subStyle }, t('toneGuideHint')),
896
+ ),
897
+ React.createElement(Toggle, {
898
+ label: t('toneGuide'),
899
+ checked: value.toneGuideEnabled !== false,
900
+ disabled,
901
+ onChange: (next) => apply({ toneGuideEnabled: next }),
902
+ }),
903
+ ),
904
+ React.createElement('div', { style: rowStyle },
905
+ React.createElement('div', null,
906
+ React.createElement('div', { style: labelStyle }, t('toneIntensity')),
907
+ React.createElement('div', { style: subStyle }, t('toneIntensityHint')),
908
+ ),
909
+ React.createElement(SelectInput, {
910
+ value: value.toneIntensity ?? 'low',
911
+ disabled: disabled || value.toneGuideEnabled === false,
912
+ options: [
913
+ { value: 'low', label: t('toneLow') },
914
+ { value: 'medium', label: t('toneMedium') },
915
+ { value: 'off', label: t('toneOff') },
916
+ ],
917
+ onChange: (next) => apply({ toneIntensity: next }),
918
+ }),
919
+ ),
920
+ React.createElement('div', { style: rowStyle },
921
+ React.createElement('div', null,
922
+ React.createElement('div', { style: labelStyle }, t('growthRecap')),
923
+ React.createElement('div', { style: subStyle }, t('growthRecapHint')),
924
+ ),
925
+ React.createElement(Toggle, {
926
+ label: t('growthRecap'),
927
+ checked: value.growthRecapEnabled !== false,
928
+ disabled,
929
+ onChange: (next) => apply({ growthRecapEnabled: next }),
930
+ }),
931
+ ),
932
+ React.createElement('div', { style: rowStyle },
933
+ React.createElement('div', null,
934
+ React.createElement('div', { style: labelStyle }, t('growthNow')),
935
+ React.createElement('div', { style: subStyle }, t('growthNowHint')),
936
+ ),
937
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '10px' } },
938
+ growthNotice !== undefined
939
+ ? React.createElement('span', { role: 'status', style: subStyle }, growthNotice)
940
+ : null,
941
+ React.createElement('button', {
942
+ type: 'button',
943
+ role: 'button',
944
+ 'aria-label': t('growthNow'),
945
+ disabled: disabled || growthBusy,
946
+ onClick: reviewNow,
947
+ style: {
948
+ padding: '7px 14px',
949
+ fontSize: '13px',
950
+ lineHeight: '18px',
951
+ borderRadius: '6px',
952
+ border: '1px solid var(--dsw-alias-border-l2, #d4d4d8)',
953
+ background: 'var(--dsw-alias-bg-layer-1, #f4f4f5)',
954
+ color: 'var(--dsw-alias-label-primary, #18181b)',
955
+ cursor: disabled || growthBusy ? 'not-allowed' : 'pointer',
956
+ opacity: disabled || growthBusy ? 0.6 : 1,
957
+ },
958
+ }, growthBusy ? t('growthNowRunning') : t('growthNow')),
959
+ ),
960
+ ),
961
+ error !== undefined ? React.createElement('div', { role: 'alert', style: errorStyle }, t('saveFailed'), error) : null,
798
962
  React.createElement('div', { style: { padding: '14px 16px', fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #888)' } },
799
963
  value.enabled === false
800
964
  ? t('footerDisabled')
@@ -23,7 +23,10 @@ export function defaultConfigPath() {
23
23
  return join(process.env.DSH_HOME || join(homedir(), '.dsh'), MEMORY_CONFIG_FILENAME)
24
24
  }
25
25
 
26
- const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill', 'deferUntilUserSpeaks', 'activeSessionOnly', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession']
26
+ const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill', 'deferUntilUserSpeaks', 'activeSessionOnly', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession', 'proactiveCooldownSeconds', 'toneGuideEnabled', 'toneIntensity', 'growthRecapEnabled', 'growthRecapIntervalDays']
27
+
28
+ /** Tone intensity values the schema accepts; invalid composition input falls back to low. */
29
+ const TONE_INTENSITIES = ['low', 'medium', 'off']
27
30
 
28
31
  function pickFields(input) {
29
32
  const picked = {}
@@ -63,6 +66,11 @@ export class MemoryConfigStore {
63
66
  recallIntervalMinMinutes: options.base?.recallIntervalMinMinutes ?? 30,
64
67
  recallIntervalMaxMinutes: options.base?.recallIntervalMaxMinutes ?? 240,
65
68
  recallMaxPerSession: options.base?.recallMaxPerSession ?? 3,
69
+ proactiveCooldownSeconds: options.base?.proactiveCooldownSeconds ?? 180,
70
+ toneGuideEnabled: options.base?.toneGuideEnabled !== false,
71
+ toneIntensity: TONE_INTENSITIES.includes(options.base?.toneIntensity) ? options.base.toneIntensity : 'low',
72
+ growthRecapEnabled: options.base?.growthRecapEnabled !== false,
73
+ growthRecapIntervalDays: options.base?.growthRecapIntervalDays ?? 7,
66
74
  }
67
75
  this.config = { ...this.base }
68
76
  this.watchers = new Set()
@@ -94,6 +102,11 @@ export class MemoryConfigStore {
94
102
  recallIntervalMinMinutes: resolved.recallIntervalMinMinutes,
95
103
  recallIntervalMaxMinutes: resolved.recallIntervalMaxMinutes,
96
104
  recallMaxPerSession: resolved.recallMaxPerSession,
105
+ proactiveCooldownSeconds: resolved.proactiveCooldownSeconds,
106
+ toneGuideEnabled: resolved.toneGuideEnabled,
107
+ toneIntensity: resolved.toneIntensity,
108
+ growthRecapEnabled: resolved.growthRecapEnabled,
109
+ growthRecapIntervalDays: resolved.growthRecapIntervalDays,
97
110
  }
98
111
  } catch {
99
112
  // schema validation failed: keep last good config
@@ -133,6 +146,11 @@ export class MemoryConfigStore {
133
146
  recallIntervalMinMinutes: next.recallIntervalMinMinutes,
134
147
  recallIntervalMaxMinutes: next.recallIntervalMaxMinutes,
135
148
  recallMaxPerSession: next.recallMaxPerSession,
149
+ proactiveCooldownSeconds: next.proactiveCooldownSeconds,
150
+ toneGuideEnabled: next.toneGuideEnabled,
151
+ toneIntensity: next.toneIntensity,
152
+ growthRecapEnabled: next.growthRecapEnabled,
153
+ growthRecapIntervalDays: next.growthRecapIntervalDays,
136
154
  }
137
155
  this.persist()
138
156
  for (const watcher of this.watchers) {
@@ -109,7 +109,8 @@ export function buildDigestNudgeMessage(staleMinutes, options = {}) {
109
109
 
110
110
  /**
111
111
  * @typedef {object} DigestGuardOptions
112
- * @property {() => { enabled: boolean, afterMinutes: number, cooldownMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean }} readConfig
112
+ * @property {() => { enabled: boolean, afterMinutes: number, cooldownMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean, proactiveCooldownSeconds?: number }} readConfig
113
+ * @property {(options: { now: number, cooldownSeconds: number }) => { ok: boolean, deferredBy?: string }} [claimLock] shared proactive lock (see proactive-lock.js)
113
114
  * @property {() => string} getMemoryDir resolve the current store dir on every check
114
115
  * @property {unknown} [agents] optional live-agent registry for liveness checks
115
116
  * @property {import('./activity-tracker.js').ActivityTracker} [tracker] gate source: has-user-spoken + active-session
@@ -131,6 +132,7 @@ export class DigestGuard {
131
132
  this.agents = options.agents
132
133
  this.tracker = options.tracker
133
134
  this.logger = options.logger
135
+ this.claimLock = options.claimLock
134
136
  this.disposed = false
135
137
  this.stopTurnStopping = undefined
136
138
  this.nudges = 0
@@ -181,6 +183,16 @@ export class DigestGuard {
181
183
  const lastWrite = lastStoreWriteMs(this.getMemoryDir())
182
184
  if (now - lastWrite < afterMs) return
183
185
 
186
+ // Proactive-speech arbitration: dsh-plugin-heartbeat may have just spoken,
187
+ // and two synthetic followups in one quiet window is exactly the noise the
188
+ // shared cooldown file exists to prevent. Refused = skip this round; the
189
+ // next idle boundary retries and this guard's own cooldown is not consumed.
190
+ const claim = this.claimProactive(now, config)
191
+ if (!claim.ok) {
192
+ this.logger?.info?.(`memory: digest reminder deferred for agent "${this.agent.id}" (${claim.deferredBy} holds the lock)`)
193
+ return
194
+ }
195
+
184
196
  const staleMinutes = Math.max(1, Math.round((now - lastWrite) / 60000))
185
197
  // Only computed once a reminder is actually being delivered: scanning the
186
198
  // store on every idle turn would be pure overhead.
@@ -191,4 +203,26 @@ export class DigestGuard {
191
203
  this.logger?.info?.(`memory: digest nudge #${this.nudges} for agent "${this.agent.id}" `
192
204
  + `(store idle ${staleMinutes}min${indexHint.length > 0 ? ', index drift reported' : ''})`)
193
205
  }
206
+
207
+ /**
208
+ * Ask the shared proactive lock for permission to speak. Missing lock (no
209
+ * other proactive plugin) or a broken lock never blocks the reminder:
210
+ * arbitration is best-effort.
211
+ * @param {number} now epoch ms
212
+ * @param {{ proactiveCooldownSeconds?: number }} config
213
+ * @returns {{ ok: boolean, deferredBy?: string }}
214
+ */
215
+ claimProactive(now, config) {
216
+ if (typeof this.claimLock !== 'function') return { ok: true }
217
+ try {
218
+ const result = this.claimLock({
219
+ now,
220
+ cooldownSeconds: Math.max(0, Number(config.proactiveCooldownSeconds ?? 180)),
221
+ })
222
+ return result ?? { ok: true }
223
+ } catch (error) {
224
+ this.logger?.warn?.(`memory: proactive lock failed: ${error instanceof Error ? error.message : String(error)}`)
225
+ return { ok: true }
226
+ }
227
+ }
194
228
  }
package/lib/growth.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Growth recap: the "look how far we've come" half of the persona.
3
+ *
4
+ * A long-term companion should occasionally *notice* its own growth instead of
5
+ * only reacting — "this week I kept these things, and touched those pages".
6
+ * Everything here is derived from what the memory store already proves: the
7
+ * recent `log.md` headlines and page mtimes. No new bookkeeping, no invented
8
+ * progress.
9
+ *
10
+ * The recap is delivered on the recall-nudge channel at most once every
11
+ * `growthRecapIntervalDays`; `<store>/.growth-recap.json` records the last
12
+ * delivery so a restart does not repeat the same week.
13
+ *
14
+ * This module depends only on `node:*` builtins plus {@link ./pages.js}.
15
+ *
16
+ * @module dsh-plugin-memory/growth
17
+ */
18
+
19
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
20
+ import { dirname, join } from 'node:path'
21
+ import { listPagePaths } from './pages.js'
22
+
23
+ /** State file recording the last delivered recap (store-relative). */
24
+ export const GROWTH_STATE_FILENAME = '.growth-recap.json'
25
+
26
+ const DAY_MS = 24 * 60 * 60 * 1000
27
+
28
+ /** Start of the local day containing `epochMs`. */
29
+ function dayStart(epochMs) {
30
+ const date = new Date(epochMs)
31
+ date.setHours(0, 0, 0, 0)
32
+ return date.getTime()
33
+ }
34
+
35
+ /**
36
+ * Parse one `log.md` headline: `## [2026-10-30] release | 标题`.
37
+ * @param {string} line
38
+ * @returns {{title: string, date: string, kind: string} | undefined}
39
+ */
40
+ export function parseGrowthLogEntry(line) {
41
+ const match = /^##\s+\[(\d{4}-\d{2}-\d{2})\]\s*(.*)$/.exec(line)
42
+ if (match === null) return undefined
43
+ const rest = match[2].trim()
44
+ if (rest.length === 0) return undefined
45
+ const pipe = rest.indexOf('|')
46
+ const kind = pipe >= 0 ? (rest.slice(0, pipe).trim() || 'note') : 'note'
47
+ const title = pipe >= 0 ? rest.slice(pipe + 1).trim() : rest
48
+ if (title.length === 0) return undefined
49
+ return { title, date: match[1], kind }
50
+ }
51
+
52
+ /**
53
+ * Collect this week's growth from the store.
54
+ *
55
+ * - `entries`: `log.md` headlines dated inside the window, newest first, at
56
+ * most `max`.
57
+ * - `pagesChanged`: memory pages whose mtime falls inside the window.
58
+ * - `newPages`: pages that were also *created* inside the window (birthtime),
59
+ * i.e. genuinely new memories rather than edits to old ones.
60
+ *
61
+ * Never throws: a missing/corrupt store yields an empty recap.
62
+ *
63
+ * @param {object} options
64
+ * @param {string} options.storeDir absolute memory-store path
65
+ * @param {number} [options.sinceDays] window size in days (default 7)
66
+ * @param {number} [options.max] headline cap (default 5)
67
+ * @param {number} [options.now] epoch ms (injectable for tests)
68
+ * @returns {{ entries: Array<{title: string, date: string, kind: string}>, pagesChanged: number, newPages: number }}
69
+ */
70
+ export function collectGrowth({ storeDir, sinceDays = 7, max = 5, now = Date.now() } = {}) {
71
+ const days = Number.isFinite(Number(sinceDays)) ? Math.max(0, Number(sinceDays)) : 7
72
+ const limit = Number.isFinite(Number(max)) ? Math.max(0, Number(max)) : 5
73
+ const windowStartMs = dayStart(now) - days * DAY_MS
74
+
75
+ // 1. Recent log headlines (the durable proof of what happened).
76
+ const entries = []
77
+ const logPath = join(storeDir, 'log.md')
78
+ if (existsSync(logPath)) {
79
+ try {
80
+ for (const line of readFileSync(logPath, 'utf8').split('\n')) {
81
+ const entry = parseGrowthLogEntry(line)
82
+ if (entry === undefined) continue
83
+ const entryMs = Date.parse(`${entry.date}T00:00:00`)
84
+ if (!Number.isFinite(entryMs) || entryMs < windowStartMs) continue
85
+ entries.push(entry)
86
+ }
87
+ } catch {
88
+ // unreadable log: still report page activity
89
+ }
90
+ }
91
+ entries.reverse()
92
+ entries.splice(limit)
93
+
94
+ // 2. Page activity from mtimes (birthtime separates new pages from edits).
95
+ let pagesChanged = 0
96
+ let newPages = 0
97
+ try {
98
+ for (const rel of listPagePaths(storeDir)) {
99
+ let stat
100
+ try {
101
+ stat = statSync(join(storeDir, rel))
102
+ } catch {
103
+ continue
104
+ }
105
+ if (stat.mtimeMs < windowStartMs) continue
106
+ pagesChanged += 1
107
+ if (stat.birthtimeMs > 0 && stat.birthtimeMs >= windowStartMs) newPages += 1
108
+ }
109
+ } catch {
110
+ // store vanished mid-scan: keep the log half
111
+ }
112
+
113
+ return { entries, pagesChanged, newPages }
114
+ }
115
+
116
+ /**
117
+ * Render the first-person recap. At most two sentences (well under the
118
+ * "≤5 sentences" contract), each half omitted when there is nothing to say.
119
+ *
120
+ * @param {object} options
121
+ * @param {Array<{title: string}>} [options.entries]
122
+ * @param {number} [options.pagesChanged]
123
+ * @param {number} [options.newPages]
124
+ * @param {'zh'|'en'} [options.language]
125
+ * @returns {string} recap text, '' when there is no growth to report
126
+ */
127
+ export function renderGrowthRecap({ entries, pagesChanged = 0, newPages = 0, language = 'zh' } = {}) {
128
+ const titles = (Array.isArray(entries) ? entries : [])
129
+ .filter((entry) => entry && typeof entry.title === 'string' && entry.title.trim().length > 0)
130
+ .slice(0, 5)
131
+ .map((entry) => entry.title.trim())
132
+ const changed = Math.max(0, Number(pagesChanged) || 0)
133
+ const fresh = Math.max(0, Math.min(changed, Number(newPages) || 0))
134
+ const sentences = []
135
+
136
+ if (language === 'en') {
137
+ if (titles.length > 0) {
138
+ sentences.push(`This week I remembered ${titles.length} thing${titles.length === 1 ? '' : 's'}: ${titles.join('; ')}.`)
139
+ }
140
+ if (changed > 0) {
141
+ sentences.push(`I also touched ${changed} memory page${changed === 1 ? '' : 's'}${fresh > 0 ? ` (${fresh} new)` : ''}.`)
142
+ }
143
+ } else {
144
+ if (titles.length > 0) {
145
+ sentences.push(`这周我记住了 ${titles.length} 件:${titles.join(';')}。`)
146
+ }
147
+ if (changed > 0) {
148
+ sentences.push(`另外改了 ${changed} 页记忆${fresh > 0 ? `(其中 ${fresh} 页是新写的)` : ''}。`)
149
+ }
150
+ }
151
+ return sentences.join('')
152
+ }
153
+
154
+ /**
155
+ * Read the last-delivered state; anything unreadable means "never recapped".
156
+ * @param {string} statePath absolute `.growth-recap.json` path
157
+ * @returns {{ version: number, lastAt: number } | undefined}
158
+ */
159
+ export function readGrowthState(statePath) {
160
+ if (typeof statePath !== 'string' || statePath.length === 0 || !existsSync(statePath)) return undefined
161
+ let raw
162
+ try {
163
+ raw = JSON.parse(readFileSync(statePath, 'utf8'))
164
+ } catch {
165
+ return undefined
166
+ }
167
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
168
+ const lastAt = Number(raw.lastAt)
169
+ if (!Number.isFinite(lastAt) || lastAt <= 0) return undefined
170
+ return { version: Number.isFinite(Number(raw.version)) ? Number(raw.version) : 1, lastAt }
171
+ }
172
+
173
+ /**
174
+ * Whether a recap is due now.
175
+ * @param {object} options
176
+ * @param {string} options.statePath absolute state-file path
177
+ * @param {number} [options.intervalDays] default 7
178
+ * @param {number} [options.now]
179
+ * @returns {boolean}
180
+ */
181
+ export function growthRecapDue({ statePath, intervalDays = 7, now = Date.now() } = {}) {
182
+ const state = readGrowthState(statePath)
183
+ if (state === undefined) return true
184
+ const days = Number.isFinite(Number(intervalDays)) ? Math.max(0, Number(intervalDays)) : 7
185
+ return now - state.lastAt >= days * DAY_MS
186
+ }
187
+
188
+ /**
189
+ * Persist the delivery time atomically.
190
+ * @param {string} statePath absolute state-file path
191
+ * @param {number} [lastAt] epoch ms (default now)
192
+ * @returns {{ version: number, lastAt: number }}
193
+ */
194
+ export function writeGrowthState(statePath, lastAt = Date.now()) {
195
+ const state = { version: 1, lastAt }
196
+ mkdirSync(dirname(statePath), { recursive: true })
197
+ const tmp = `${statePath}.tmp`
198
+ writeFileSync(tmp, `${JSON.stringify(state)}\n`, 'utf8')
199
+ renameSync(tmp, statePath)
200
+ return state
201
+ }