dsh-plugin-memory 0.5.2 → 0.6.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/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  所有记录跟随 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/) 风格;版本号与 `package.json` 保持一致。
4
4
 
5
+ ## [0.6.0] - 2026-09-09
6
+
7
+ ### Added(两道礼貌闸门:提问后才注入 + 只注入激活会话)
8
+
9
+ - **`deferUntilUserSpeaks`**(默认开):会话收到第一条真实用户消息(`source.kind === 'user'`)前,boot 块、主动追忆、digest 提醒一律不注入——杜绝「开了会话啥也没问就自动蹦提示词」。
10
+ - **`activeSessionOnly`**(默认开):只对「最近收到用户消息的 live root agent」注入,后台 / 未展开会话不再被追忆或 digest 提醒打扰。
11
+ - 新增 `lib/activity-tracker.js`:per-agent 状态表(`hasUserSpoken` + 最近用户消息次序),三个注入点共用同一 `shouldInject` 谓词,口径一致。
12
+
13
+ ### Fixed
14
+
15
+ - 主动追忆首拍立即开火:`nextRecallAt` 初始值为 0 → 第一次 idle 检查就触发。改为「首个满足条件的空闲时刻先 arm 间隔,再等一个随机间隔后才开口」。
16
+
17
+ ### Tests
18
+
19
+ - 54/54 全过(新增 activity-tracker 套件:hasUserSpoken / isActive / shouldInject / 去重 / 注册表跳过死亡 agent;recall / digest 各补 defer + active 两个闸门用例,并更新首拍 arm 语义用例)。
20
+
5
21
  ## [0.5.2] - 2026-08-31
6
22
 
7
23
  ### Changed
package/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
 
14
14
  ## 特性
15
15
 
16
- - **开机强制注入**:插件通过 `ctx.systemPrompt.context()` 把记忆 boot 块(`SOUL.md` 人格 + `MEMORY.md` 协议 + `index.md` 目录 + 最近动态)注入每个会话开头。宿主按投影去重:记忆不变就不重复注入,变化时新快照自动取代旧的——这是"新会话必先加载记忆"的**硬保障**,不需要模型碰运气调技能。
16
+ - **开机强制注入**:插件通过 `ctx.systemPrompt.context()` 把记忆 boot 块(`SOUL.md` 人格 + `MEMORY.md` 协议 + `index.md` 目录 + 最近动态)注入会话上下文。宿主按投影去重:记忆不变就不重复注入,变化时新快照自动取代旧的——这是"新会话必先加载记忆"的**硬保障**,不需要模型碰运气调技能。默认还带**两道礼貌闸门**:`deferUntilUserSpeaks`(用户开口后才注入)与 `activeSessionOnly`(只注入当前激活会话),见「配置」。
17
17
  - **SOUL.md 铸魂**:安装后首要任务是和用户对话定义灵魂(名字、性格、价值观、语气、边界)、确认身份与关系(`BOOTSTRAP.md` 清单驱动,complete 前优先于常规任务)。
18
18
  - **铸魂自动引导**:记忆库还没有灵魂(`BOOTSTRAP.md` 非 complete,或 `SOUL.md` 仍是占位模板)时,boot 块会自动前置一段第一人称引导词——「我的首要任务是确认我是谁,还有你是谁:我叫什么名字、怎么称呼你、你我是什么关系、我该是什么样的性格」——像 OpenClaw 初始化那样,**由 agent 在对话里主动发起铸魂**,逐项问、逐项写回,而不是等用户来喂。铸魂完成后引导词自动消失,零开销。
19
19
  - **复利记忆**:遵循 Karpathy 的 *LLM Wiki* 约定——记忆是"一次编译、持续保鲜"的持久产物,不是每次查询重新 RAG。remember / recall / consolidate / forget 四操作 + salience 三级衰减。
@@ -33,6 +33,7 @@
33
33
  dsh-plugin-memory(本插件)
34
34
  ├── lib/index.js # Cordis 入口:boot 注入 + 运行时技能注册 + settings 热改
35
35
  ├── lib/boot.js # boot 块渲染(SOUL/MEMORY/index + 最近 log,限额截断)
36
+ ├── lib/activity-tracker.js # 两道礼貌闸门:用户是否开口 + 当前激活会话
36
37
  ├── lib/digest-guard.js # 防懒 digest 唤醒(空闲 + 记忆库久未写 → followup 提醒)
37
38
  ├── lib/recall-nudge.js # 主动追忆(空闲 → 第一人称提起一件真实往事,纯对话不写库)
38
39
  ├── lib/scaffold.js # 记忆库脚手架(模板只建不覆盖)
@@ -75,6 +76,8 @@ dsh plugin --profile <profile> add dsh-plugin-memory
75
76
  | `bootFiles` | `[SOUL.md, MEMORY.md, index.md]` | 开机注入的文件 |
76
77
  | `bootMaxChars` | `6000` | boot 块总字符预算(防止占用过多上下文) |
77
78
  | `autoInject` | `true` | 会话开始时注入 boot 块 |
79
+ | `deferUntilUserSpeaks` | `true` | 用户发出第一条真实消息后才注入(boot 块 / 追忆 / digest 提醒都遵守);面板可热改 |
80
+ | `activeSessionOnly` | `true` | 只对「当前激活会话」(最近收到用户消息的会话)注入,后台会话不打扰;面板可热改 |
78
81
  | `registerSkill` | `true` | 注册内嵌 `memory` 技能 |
79
82
  | `scaffold` | `true` | 记忆库缺失时自动创建模板(只建不覆盖) |
80
83
  | `configFile` | `<dshHome>/memory.json` | 用户可改配置的 JSON 文件路径(设置面板读写它) |
@@ -92,7 +95,9 @@ dsh plugin --profile <profile> add dsh-plugin-memory
92
95
 
93
96
  ### 设置面板(热改)
94
97
 
95
- `enabled` / `memoryDir` / `autoInject` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` 八项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、技能注册、主动追忆(含随机间隔与次数)随修改立即生效;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
98
+ `enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks` / `activeSessionOnly` / `registerSkill` / `recallEnabled` / `recallIntervalMinMinutes` / `recallIntervalMaxMinutes` / `recallMaxPerSession` 十项在 DSH 设置页的「记忆 Memory」区块中可改,**即时生效**:boot 注入、两道礼貌闸门、技能注册、主动追忆(含随机间隔与次数)随修改立即生效;记忆目录切换时自动为新目录初始化脚手架(`scaffold: true` 时)。其余键(`bootFiles` / `bootMaxChars` / `scaffold` / `configFile` / `digestNudge*` / `autoCommit*`)只在 composition 配置层生效,改完需重启。
99
+
100
+ > **「当前激活会话」怎么判?** DSH 宿主侧没有「浏览器当前聚焦的会话」信号(激活会话是前端概念)。插件用**最近一次收到真实用户消息的 live root agent**作为激活会话的代理:你在哪个会话里说话,哪个会话就激活;切到别处但不发消息时,宿主感知不到「切换」这个动作(这是代理的已知边界)。若日后需要精确到「展开/聚焦」级别,需补一小段客户端 focus 上报。
96
101
 
97
102
  覆盖 composition 键(例如把 boot 块预算调大),在 profile 的 `cordis.patch.yml` 里写**不带 `insert` 的 id 覆盖条目**:
98
103
 
package/cordis.patch.yml CHANGED
@@ -3,8 +3,9 @@
3
3
  # Declared via the `dsh.bundle.patch` manifest in package.json, so
4
4
  # `dsh plugin add dsh-plugin-memory` (and the dsh-market install flow)
5
5
  # mounts this insert automatically. User-level overrides — including the
6
- # hot-editable `enabled` / `memoryDir` / `autoInject` / `registerSkill` —
7
- # live in <dshHome>/memory.json, managed by the settings panel.
6
+ # hot-editable `enabled` / `memoryDir` / `autoInject` / `deferUntilUserSpeaks`
7
+ # / `activeSessionOnly` / `registerSkill` — live in <dshHome>/memory.json,
8
+ # managed by the settings panel.
8
9
  - insert:
9
10
  - id: dsh-memory
10
11
  name: dsh-plugin-memory
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Per-agent activity tracker: the two gates that keep memory injection polite.
3
+ *
4
+ * 1. **`hasUserSpoken(id)`** — becomes true on the first REAL user message
5
+ * (`source.kind === 'user'`). Gates "don't inject until the user actually
6
+ * asks something".
7
+ * 2. **`isActive(id)`** — the live root agent that most recently received a
8
+ * real user message. Gates "only the currently active session injects".
9
+ *
10
+ * The host has no "focused session" signal (that is a browser-side concept),
11
+ * so "active" is proxied by the most recent user message — a session the user
12
+ * is not talking to stops being active the moment they speak elsewhere.
13
+ *
14
+ * `shouldInject(id, config)` folds both gates (plus the config toggles) into
15
+ * one predicate, shared by the boot block, the recall nudge and the digest
16
+ * guard so the three never disagree.
17
+ *
18
+ * @module dsh-plugin-memory/activity-tracker
19
+ */
20
+
21
+ /**
22
+ * @typedef {object} ActivityTrackerOptions
23
+ * @property {unknown} [agents] optional live-agent registry, used only to skip
24
+ * disposed agents when deciding the active one
25
+ * @property {{ info?: Function, warn?: Function }} [logger]
26
+ */
27
+
28
+ export class ActivityTracker {
29
+ constructor(options = {}) {
30
+ this.agents = options.agents
31
+ this.logger = options.logger
32
+ /** @type {Map<string, { agent: object, hasUserSpoken: boolean, lastUserSeq: number, stop?: Function }>} */
33
+ this.states = new Map()
34
+ this.seq = 0
35
+ this.disposed = false
36
+ }
37
+
38
+ /**
39
+ * Wire one live root agent's inbox feed into the tracker. Idempotent per
40
+ * agent identity.
41
+ * @param {object} agent live agent ({ id, ctx })
42
+ */
43
+ attach(agent) {
44
+ const existing = this.states.get(agent.id)
45
+ if (existing && existing.agent === agent) return
46
+ const entry = { agent, hasUserSpoken: false, lastUserSeq: 0, stop: undefined }
47
+ entry.stop = agent.ctx?.on?.('agent/inbox/inserted', ({ message }) => {
48
+ if (message?.source?.kind === 'user') this.noteUserMessage(agent.id)
49
+ })
50
+ this.states.set(agent.id, entry)
51
+ }
52
+
53
+ /** Record a real user message against one agent (monotonic order). */
54
+ noteUserMessage(id) {
55
+ const entry = this.states.get(id)
56
+ if (!entry) return
57
+ entry.hasUserSpoken = true
58
+ entry.lastUserSeq = ++this.seq
59
+ }
60
+
61
+ /** Unsubscribe and drop one agent's state. */
62
+ detach(id) {
63
+ const entry = this.states.get(id)
64
+ if (!entry) return
65
+ try {
66
+ entry.stop?.()
67
+ } catch (error) {
68
+ this.logger?.warn?.(`memory: detach listener failed for "${id}": ${error instanceof Error ? error.message : String(error)}`)
69
+ }
70
+ this.states.delete(id)
71
+ }
72
+
73
+ /** Whether the agent has ever received a real user message. */
74
+ hasUserSpoken(id) {
75
+ return this.states.get(id)?.hasUserSpoken === true
76
+ }
77
+
78
+ /**
79
+ * Whether `id` is the live agent that most recently received a real user
80
+ * message. A never-spoken-to agent is never active.
81
+ */
82
+ isActive(id) {
83
+ const entry = this.states.get(id)
84
+ if (!entry || !entry.hasUserSpoken) return false
85
+ let winner
86
+ let latest = 0
87
+ for (const [agentId, state] of this.states) {
88
+ if (!state.hasUserSpoken) continue
89
+ if (this.agents && this.agents.get(agentId) === undefined) continue
90
+ if (state.lastUserSeq > latest) {
91
+ latest = state.lastUserSeq
92
+ winner = agentId
93
+ }
94
+ }
95
+ return winner === id
96
+ }
97
+
98
+ /**
99
+ * Fold the two gates + config toggles into one predicate. With both toggles
100
+ * off, always inject (backward compatible).
101
+ * @param {string} id agent id
102
+ * @param {{ deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean }} config
103
+ */
104
+ shouldInject(id, config = {}) {
105
+ if (config.deferUntilUserSpeaks !== false && !this.hasUserSpoken(id)) return false
106
+ if (config.activeSessionOnly !== false && !this.isActive(id)) return false
107
+ return true
108
+ }
109
+
110
+ /** Detach every tracked agent. */
111
+ dispose() {
112
+ this.disposed = true
113
+ for (const id of [...this.states.keys()]) this.detach(id)
114
+ }
115
+ }
package/lib/client.js CHANGED
@@ -233,6 +233,28 @@ window.__ModuleLoader__.load({
233
233
  onChange: (next) => apply({ autoInject: next }),
234
234
  }),
235
235
  ),
236
+ React.createElement('div', { style: rowStyle },
237
+ React.createElement('div', null,
238
+ React.createElement('div', { style: labelStyle }, '提问后才注入'),
239
+ React.createElement('div', { style: subStyle }, '开启后,新会话在你发出第一条消息前不会注入任何记忆 / 追忆 / digest 提醒'),
240
+ ),
241
+ React.createElement(Toggle, {
242
+ checked: value.deferUntilUserSpeaks !== false,
243
+ disabled,
244
+ onChange: (next) => apply({ deferUntilUserSpeaks: next }),
245
+ }),
246
+ ),
247
+ React.createElement('div', { style: rowStyle },
248
+ React.createElement('div', null,
249
+ React.createElement('div', { style: labelStyle }, '仅当前激活会话注入'),
250
+ React.createElement('div', { style: subStyle }, '开启后,只有最近收到你消息的会话才会注入记忆(后台会话不打扰)'),
251
+ ),
252
+ React.createElement(Toggle, {
253
+ checked: value.activeSessionOnly !== false,
254
+ disabled,
255
+ onChange: (next) => apply({ activeSessionOnly: next }),
256
+ }),
257
+ ),
236
258
  React.createElement('div', { style: rowStyle },
237
259
  React.createElement('div', null,
238
260
  React.createElement('div', { style: labelStyle }, '注册 memory 技能'),
@@ -23,7 +23,7 @@ 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', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession']
26
+ const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill', 'deferUntilUserSpeaks', 'activeSessionOnly', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession']
27
27
 
28
28
  function pickFields(input) {
29
29
  const picked = {}
@@ -57,6 +57,8 @@ export class MemoryConfigStore {
57
57
  : '~/.memory',
58
58
  autoInject: options.base?.autoInject !== false,
59
59
  registerSkill: options.base?.registerSkill !== false,
60
+ deferUntilUserSpeaks: options.base?.deferUntilUserSpeaks !== false,
61
+ activeSessionOnly: options.base?.activeSessionOnly !== false,
60
62
  recallEnabled: options.base?.recallEnabled !== false,
61
63
  recallIntervalMinMinutes: options.base?.recallIntervalMinMinutes ?? 30,
62
64
  recallIntervalMaxMinutes: options.base?.recallIntervalMaxMinutes ?? 240,
@@ -86,6 +88,8 @@ export class MemoryConfigStore {
86
88
  memoryDir: resolved.memoryDir,
87
89
  autoInject: resolved.autoInject,
88
90
  registerSkill: resolved.registerSkill,
91
+ deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
92
+ activeSessionOnly: resolved.activeSessionOnly,
89
93
  recallEnabled: resolved.recallEnabled,
90
94
  recallIntervalMinMinutes: resolved.recallIntervalMinMinutes,
91
95
  recallIntervalMaxMinutes: resolved.recallIntervalMaxMinutes,
@@ -123,6 +127,8 @@ export class MemoryConfigStore {
123
127
  memoryDir: next.memoryDir,
124
128
  autoInject: next.autoInject,
125
129
  registerSkill: next.registerSkill,
130
+ deferUntilUserSpeaks: next.deferUntilUserSpeaks,
131
+ activeSessionOnly: next.activeSessionOnly,
126
132
  recallEnabled: next.recallEnabled,
127
133
  recallIntervalMinMinutes: next.recallIntervalMinMinutes,
128
134
  recallIntervalMaxMinutes: next.recallIntervalMaxMinutes,
@@ -70,9 +70,10 @@ export function buildDigestNudgeMessage(staleMinutes) {
70
70
 
71
71
  /**
72
72
  * @typedef {object} DigestGuardOptions
73
- * @property {() => { enabled: boolean, afterMinutes: number, cooldownMinutes: number, maxPerSession: number }} readConfig
73
+ * @property {() => { enabled: boolean, afterMinutes: number, cooldownMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean }} readConfig
74
74
  * @property {() => string} getMemoryDir resolve the current store dir on every check
75
75
  * @property {unknown} [agents] optional live-agent registry for liveness checks
76
+ * @property {import('./activity-tracker.js').ActivityTracker} [tracker] gate source: has-user-spoken + active-session
76
77
  * @property {{ info?: Function, warn?: Function }} [logger]
77
78
  */
78
79
 
@@ -89,6 +90,7 @@ export class DigestGuard {
89
90
  this.readConfig = options.readConfig
90
91
  this.getMemoryDir = options.getMemoryDir
91
92
  this.agents = options.agents
93
+ this.tracker = options.tracker
92
94
  this.logger = options.logger
93
95
  this.disposed = false
94
96
  this.stopTurnStopping = undefined
@@ -124,6 +126,9 @@ export class DigestGuard {
124
126
  }
125
127
  const config = this.readConfig()
126
128
  if (!config.enabled) return
129
+ // Both gates: don't remind before the user has spoken, and only for the
130
+ // currently active session (most recent user message).
131
+ if (this.tracker && !this.tracker.shouldInject(this.agent.id, config)) return
127
132
  if (this.nudges >= Math.max(1, Number(config.maxPerSession ?? 2))) return
128
133
  if (this.agent.status !== 'idle') return
129
134
  const inbox = this.agent.inbox
package/lib/index.js CHANGED
@@ -79,6 +79,7 @@ import { SettingsSchema } from './schema.js'
79
79
  import { DigestGuard } from './digest-guard.js'
80
80
  import { RecallNudge } from './recall-nudge.js'
81
81
  import { AutoCommitter } from './autocommit.js'
82
+ import { ActivityTracker } from './activity-tracker.js'
82
83
  import {
83
84
  MEMORY_SKILL_NAME,
84
85
  MEMORY_SKILL_DESCRIPTION,
@@ -103,6 +104,10 @@ export const Config = z.object({
103
104
  registerSkill: z.boolean().default(true),
104
105
  scaffold: z.boolean().default(true),
105
106
  configFile: z.union([z.string(), z.const(undefined)]),
107
+ // Gate 1: don't inject until the session's first real user message.
108
+ deferUntilUserSpeaks: z.boolean().default(true),
109
+ // Gate 2: only the currently active session (most recent user message) injects.
110
+ activeSessionOnly: z.boolean().default(true),
106
111
  // Digest guard: inject a synthetic reminder when the agent sits idle and
107
112
  // the store has not been written for a while, so the end-of-session
108
113
  // digest cannot be silently skipped.
@@ -156,6 +161,8 @@ export function apply(ctx, config = {}) {
156
161
  memoryDir: config.memoryDir ?? '~/.memory',
157
162
  autoInject: config.autoInject !== false,
158
163
  registerSkill: config.registerSkill !== false,
164
+ deferUntilUserSpeaks: config.deferUntilUserSpeaks !== false,
165
+ activeSessionOnly: config.activeSessionOnly !== false,
159
166
  recallEnabled: config.recallEnabled !== false,
160
167
  recallIntervalMinMinutes: config.recallIntervalMinMinutes ?? 30,
161
168
  recallIntervalMaxMinutes: config.recallIntervalMaxMinutes ?? 240,
@@ -163,6 +170,11 @@ export function apply(ctx, config = {}) {
163
170
  },
164
171
  })
165
172
 
173
+ // Per-agent activity tracker: the single source of truth for both gates.
174
+ // Created before `rebuild()` so the boot block's `text` closure can consult
175
+ // it, and shared with the digest guard + recall nudge so they never disagree.
176
+ const tracker = new ActivityTracker({ agents: ctx.agents, logger: ctx.logger })
177
+
166
178
  let bootDispose
167
179
  let skillDispose
168
180
  let scaffoldedDir
@@ -231,7 +243,14 @@ export function apply(ctx, config = {}) {
231
243
  bootDispose = ctx.systemPrompt.context({
232
244
  name: 'memory-boot',
233
245
  order: -200,
234
- text: () => renderBootBlock(memoryDir, { bootFiles, bootMaxChars }),
246
+ text: (context) => {
247
+ // Per-agent gate: no agent context (e.g. a global preview) injects
248
+ // unconditionally; an agent injects only once it has spoken and is
249
+ // the active session.
250
+ const agent = context?.agent
251
+ if (agent && !tracker.shouldInject(agent.id, store.get())) return ''
252
+ return renderBootBlock(memoryDir, { bootFiles, bootMaxChars })
253
+ },
235
254
  })
236
255
  } else {
237
256
  disposeBoot()
@@ -259,6 +278,21 @@ export function apply(ctx, config = {}) {
259
278
 
260
279
  rebuild()
261
280
 
281
+ // Activity tracker: attach to every live ROOT agent so the two gates
282
+ // (has-user-spoken + active-session) see real user messages as they land.
283
+ ctx.effect(() => {
284
+ const stopCreated = ctx.on('agent/created', ({ agent }) => {
285
+ if (!ctx.agents.roots().includes(agent)) return
286
+ agent.ctx.effect(() => {
287
+ tracker.attach(agent)
288
+ return () => {
289
+ tracker.detach(agent.id)
290
+ }
291
+ })
292
+ })
293
+ return () => stopCreated()
294
+ }, 'memory.activity-tracker()')
295
+
262
296
  // Digest guard: one per live ROOT agent, so a skipped end-of-session
263
297
  // digest is caught mechanically instead of relying on the agent's
264
298
  // self-discipline. Independent of dsh-plugin-heartbeat — the nudge is
@@ -275,10 +309,13 @@ export function apply(ctx, config = {}) {
275
309
  afterMinutes: config.digestNudgeAfterMinutes,
276
310
  cooldownMinutes: config.digestNudgeCooldownMinutes,
277
311
  maxPerSession: config.digestNudgeMaxPerSession,
312
+ deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
313
+ activeSessionOnly: resolved.activeSessionOnly,
278
314
  }
279
315
  },
280
316
  getMemoryDir: () => currentMemoryDir,
281
317
  agents: ctx.agents,
318
+ tracker,
282
319
  logger: ctx.logger,
283
320
  })
284
321
  agent.ctx.effect(() => {
@@ -307,10 +344,13 @@ export function apply(ctx, config = {}) {
307
344
  minMinutes: resolved.recallIntervalMinMinutes,
308
345
  maxMinutes: resolved.recallIntervalMaxMinutes,
309
346
  maxPerSession: resolved.recallMaxPerSession,
347
+ deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
348
+ activeSessionOnly: resolved.activeSessionOnly,
310
349
  }
311
350
  },
312
351
  getMemoryDir: () => currentMemoryDir,
313
352
  agents: ctx.agents,
353
+ tracker,
314
354
  logger: ctx.logger,
315
355
  })
316
356
  agent.ctx.effect(() => {
@@ -377,6 +417,7 @@ export function apply(ctx, config = {}) {
377
417
  disposeBoot()
378
418
  disposeSkill()
379
419
  disposeCommitter()
420
+ tracker.dispose()
380
421
  }
381
422
  }
382
423
 
@@ -392,4 +433,4 @@ Object.defineProperties(apply, {
392
433
 
393
434
  export default apply
394
435
 
395
- export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStore }
436
+ export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStore, ActivityTracker }
@@ -98,9 +98,10 @@ export function buildRecallNudgeMessage(candidates) {
98
98
 
99
99
  /**
100
100
  * @typedef {object} RecallNudgeOptions
101
- * @property {() => { enabled: boolean, minMinutes: number, maxMinutes: number, maxPerSession: number }} readConfig
101
+ * @property {() => { enabled: boolean, minMinutes: number, maxMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean }} readConfig
102
102
  * @property {() => string} getMemoryDir resolve the current store dir on every check
103
103
  * @property {unknown} [agents] optional live-agent registry for liveness checks
104
+ * @property {import('./activity-tracker.js').ActivityTracker} [tracker] gate source: has-user-spoken + active-session
104
105
  * @property {{ info?: Function, warn?: Function }} [logger]
105
106
  */
106
107
 
@@ -119,12 +120,15 @@ export class RecallNudge {
119
120
  this.readConfig = options.readConfig
120
121
  this.getMemoryDir = options.getMemoryDir
121
122
  this.agents = options.agents
123
+ this.tracker = options.tracker
122
124
  this.logger = options.logger
123
125
  this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS
124
126
  this.disposed = false
125
127
  this.stopTurnStopping = undefined
126
128
  this.timer = undefined
127
129
  this.recalls = 0
130
+ // 0 = "not armed yet": the first eligible idle moment arms the interval so
131
+ // the first recall never fires instantly after the user's first turn.
128
132
  this.nextRecallAt = 0
129
133
  }
130
134
 
@@ -173,12 +177,21 @@ export class RecallNudge {
173
177
  }
174
178
  const config = this.readConfig()
175
179
  if (!config.enabled) return
180
+ // Both gates: don't recall before the user has spoken, and only for the
181
+ // currently active session (most recent user message).
182
+ if (this.tracker && !this.tracker.shouldInject(this.agent.id, config)) return
176
183
  if (this.recalls >= Math.max(1, Number(config.maxPerSession ?? 3))) return
177
184
  if (this.agent.status !== 'idle') return
178
185
  const inbox = this.agent.inbox
179
186
  if (inbox && Array.isArray(inbox.nextStep) && inbox.nextStep.length > 0) return
180
187
 
181
188
  const now = Date.now()
189
+ if (this.nextRecallAt === 0) {
190
+ // First eligible idle moment: arm the interval from here instead of
191
+ // firing instantly (the pre-gate bug). Returns so the next check honors it.
192
+ this.nextRecallAt = now + randomIntervalMs(config.minMinutes, config.maxMinutes)
193
+ return
194
+ }
182
195
  if (now < this.nextRecallAt) return
183
196
 
184
197
  const candidates = listRecallCandidates(this.getMemoryDir(), 3)
package/lib/schema.js CHANGED
@@ -15,6 +15,10 @@ export const SettingsSchema = z.object({
15
15
  memoryDir: z.string().default('~/.memory'),
16
16
  autoInject: z.boolean().default(true),
17
17
  registerSkill: z.boolean().default(true),
18
+ // Gate 1: don't inject anything until the session's first real user message.
19
+ deferUntilUserSpeaks: z.boolean().default(true),
20
+ // Gate 2: only the currently active session (most recent user message) injects.
21
+ activeSessionOnly: z.boolean().default(true),
18
22
  recallEnabled: z.boolean().default(true),
19
23
  recallIntervalMinMinutes: z.number().default(30),
20
24
  recallIntervalMaxMinutes: z.number().default(240),
@@ -10,7 +10,7 @@ import type { Context } from '@deepseek-ai/cordis'
10
10
  export const name: 'memory'
11
11
 
12
12
  /** Services required by the plugin. */
13
- export const inject: ['systemPrompt', 'skills']
13
+ export const inject: ['systemPrompt', 'skills', 'agents']
14
14
 
15
15
  /** User-facing plugin configuration (all fields optional). */
16
16
  export interface MemoryConfig {
@@ -24,6 +24,10 @@ export interface MemoryConfig {
24
24
  bootMaxChars?: number
25
25
  /** Inject the boot block at session start. Default `true`. */
26
26
  autoInject?: boolean
27
+ /** Don't inject anything until the session's first real user message. Default `true`. */
28
+ deferUntilUserSpeaks?: boolean
29
+ /** Only inject for the currently active session (most recent user message). Default `true`. */
30
+ activeSessionOnly?: boolean
27
31
  /** Register the embedded `memory` skill. Default `true`. */
28
32
  registerSkill?: boolean
29
33
  /** Create the store layout and templates when missing. Default `true`. */
@@ -65,6 +69,8 @@ export interface MemorySettings {
65
69
  enabled?: boolean
66
70
  memoryDir?: string
67
71
  autoInject?: boolean
72
+ deferUntilUserSpeaks?: boolean
73
+ activeSessionOnly?: boolean
68
74
  registerSkill?: boolean
69
75
  recallEnabled?: boolean
70
76
  recallIntervalMinMinutes?: number
@@ -94,7 +100,7 @@ export function resolveMemoryDir(dir: string): string
94
100
  export interface MemoryPlugin {
95
101
  (ctx: Context, config?: MemoryConfig): () => void
96
102
  readonly name: 'memory'
97
- readonly inject: ['systemPrompt', 'skills']
103
+ readonly inject: ['systemPrompt', 'skills', 'agents']
98
104
  readonly Config: import('@deepseek-ai/schemastery').default<MemoryConfig>
99
105
  }
100
106
 
@@ -113,3 +119,18 @@ export function renderBootBlock(
113
119
 
114
120
  /** Create the memory-store layout if missing. Returns created paths. */
115
121
  export function ensureMemoryScaffold(memoryDir: string): string[]
122
+
123
+ /**
124
+ * Per-agent activity tracker behind the two polite-injection gates
125
+ * (`deferUntilUserSpeaks` + `activeSessionOnly`).
126
+ */
127
+ export class ActivityTracker {
128
+ constructor(options?: { agents?: unknown; logger?: unknown })
129
+ attach(agent: unknown): void
130
+ noteUserMessage(id: string): void
131
+ detach(id: string): void
132
+ hasUserSpoken(id: string): boolean
133
+ isActive(id: string): boolean
134
+ shouldInject(id: string, config?: { deferUntilUserSpeaks?: boolean; activeSessionOnly?: boolean }): boolean
135
+ dispose(): void
136
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-plugin-memory",
3
3
  "description": "Long-term memory plugin for DeepSeek Harness: persistent cross-session markdown memory with a soul/persona file, auto-injected at every session start, plus remember/recall/consolidate/forget workflows and portable migration tooling.",
4
- "version": "0.5.2",
4
+ "version": "0.6.0",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",