dsh-memory-metabolism 0.2.1 → 0.2.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
@@ -6,7 +6,7 @@ Local-first Markdown memory for DeepSeek Harness, with a full-page memory workbe
6
6
 
7
7
  *Screenshots use demo data.*
8
8
 
9
- Status: 0.2.1. The Markdown store, workbench, chat and organizer are usable; retention/write thresholds remain tunable.
9
+ Status: 0.2.3. The Markdown store, workbench, chat and organizer are usable; retention/write thresholds remain tunable.
10
10
 
11
11
  ## Why
12
12
 
@@ -22,7 +22,7 @@ This plugin keeps memory as plain Markdown. Global memory lives in the shared da
22
22
  - Streaming replies over SSE, with visible tool chips and a stop button.
23
23
  - Global and project are persistence scopes. Reference documents are a separate library; working notes are session scratch, not long-term injection.
24
24
  - Write gate, FSRS-style retention, BM25 + MMR retrieval and duplicate reports.
25
- - Background organizer on `turn/end`: writes a daily evidence log, then sends extracted proposals through the same write gate (candidate by default).
25
+ - Background organizer on `turn/end`: writes a daily evidence log, then sends extracted proposals through the same write gate (high-confidence may be active; the rest become candidates).
26
26
  - Diagnostics drawer with read-only injection preview, recent injection trace, organizer state and recent errors.
27
27
  - Settings dashboard for memory entries, candidates, injection trace, import and thresholds.
28
28
  - Theme-aware base surfaces. Progress bars and gauges use a fixed cyan/yellow/purple/green/red display palette so they stay legible on any DSH skin.
package/README.zh.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  *截图为演示数据。*
8
8
 
9
- 状态:0.2.1。记忆存储、工作台、聊天和整理已可用;写入阈值和留存参数仍可调整。
9
+ 状态:0.2.3。记忆存储、工作台、聊天和整理已可用;写入阈值和留存参数仍可调整。
10
10
 
11
11
  ## 为什么
12
12
 
package/lib/api.js CHANGED
@@ -146,10 +146,10 @@ export function registerRoutes({ ctx, hostCtx, service, store, config, chatStore
146
146
  if (request.method !== 'GET' && request.method !== 'HEAD') return sendJson(response, 405, { ok: false, error: 'GET only' })
147
147
  const status = service.status()
148
148
  const project = queryValue(request.url, 'project') || status.lastProject || ''
149
- const preview = previewProjections({ store, config, projectKey: project })
149
+ const preview = previewProjections({ store, config, projectKey: project, service })
150
150
  const trace = service.trace().filter((row) => row.kind === 'inject').slice(-8).reverse().map((row) => ({
151
151
  ...row,
152
- chars: (row.ids || []).reduce((sum, id) => sum + String(service.locate(id)?.text || '').length, 0),
152
+ chars: Number.isFinite(row.chars) ? row.chars : (row.ids || []).reduce((sum, id) => sum + String(service.locate(id)?.text || '').length, 0),
153
153
  }))
154
154
  return sendJson(response, 200, {
155
155
  ok: true,
package/lib/context.js CHANGED
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { createUserMessage } from '@deepseek-ai/dsh-llm'
4
4
  import { budgetClip, stripDeletedLines, toHomeShort } from './shared/text.js'
5
+ import { serializeMemory } from './shared/markdown.js'
5
6
 
6
7
  const PROJECTION_SOURCE = Object.freeze({
7
8
  kind: 'plugin:dsh-memory-metabolism',
@@ -9,11 +10,11 @@ const PROJECTION_SOURCE = Object.freeze({
9
10
  })
10
11
 
11
12
  const RULES = [
12
- '你有一套持久化、人类可直接编辑的 Markdown 记忆,真源在 ~/.dsh/memory-metabolism。',
13
+ '你有一套持久化、人类可直接编辑的 Markdown 记忆。全局记忆在 ~/.dsh/memory-metabolism;项目记忆在项目根 .deepseek-harness/MEMORY.md。',
13
14
  '',
14
15
  '[记忆层级]',
15
16
  '- 全局记忆:跨项目偏好、硬约束、长期事实。',
16
- '- 项目记忆:按 project key 分片,不跟对话目录绑定;换目录不会丢。',
17
+ '- 项目记忆:跟着项目目录走,项目根 .deepseek-harness/MEMORY.md;key 只是元数据,不是中央桶。',
17
18
  '- reference:长文档与手册,不参与写入门和遗忘,只做检索。',
18
19
  '- 工作记忆:会话级草稿,不长期保存。',
19
20
  '',
@@ -76,6 +77,20 @@ function projection(text, heading) {
76
77
  })
77
78
  }
78
79
 
80
+ function renderActive(service, store, scope, key) {
81
+ const entries = service.read({ scope, project: scope === 'project' ? key : undefined, status: 'active', limit: 500 })
82
+ const sections = []
83
+ for (const entry of entries) {
84
+ let section = sections.find((item) => item.title === (entry.section || '记忆'))
85
+ if (!section) {
86
+ section = { title: entry.section || '记忆', entries: [] }
87
+ sections.push(section)
88
+ }
89
+ section.entries.push({ id: entry.id, text: entry.text })
90
+ }
91
+ return { text: stripDeletedLines(serializeMemory(sections)), ids: entries.map((entry) => entry.id), file: store.fileFor(scope, scope === 'project' ? key : null) }
92
+ }
93
+
79
94
  export function buildProjections({ service, store, config, session }) {
80
95
  const cwd = session?.header?.cwd
81
96
  const projectKey = service.projectKey(cwd)
@@ -94,21 +109,21 @@ export function buildProjections({ service, store, config, session }) {
94
109
  if (message) out.push(message)
95
110
  }
96
111
 
97
- const global = store.read('global', null)
112
+ const global = renderActive(service, store, 'global', null)
98
113
  if (global.text.trim() !== '') {
99
- const message = projection(budgetClip(stripDeletedLines(global.text), config.maxInjectionChars), '# 用户级记忆 (' + toHomeShort(global.file) + ')')
114
+ const message = projection(budgetClip(global.text, config.maxInjectionChars), '# 用户级记忆 (' + toHomeShort(global.file) + ')')
100
115
  if (message) {
101
116
  out.push(message)
102
- ids.push(...global.entries.map((entry) => entry.id))
117
+ ids.push(...global.ids)
103
118
  }
104
119
  }
105
120
 
106
- const project = store.read('project', projectKey)
121
+ const project = renderActive(service, store, 'project', projectKey)
107
122
  if (project.text.trim() !== '') {
108
- const message = projection(budgetClip(stripDeletedLines(project.text), config.maxInjectionChars), '# 项目记忆 (' + projectKey + ' @ ' + toHomeShort(project.file) + ')')
123
+ const message = projection(budgetClip(project.text, config.maxInjectionChars), '# 项目记忆 (' + projectKey + ' @ ' + toHomeShort(project.file) + ')')
109
124
  if (message) {
110
125
  out.push(message)
111
- ids.push(...project.entries.map((entry) => entry.id))
126
+ ids.push(...project.ids)
112
127
  }
113
128
  }
114
129
 
@@ -124,7 +139,8 @@ export function buildProjections({ service, store, config, session }) {
124
139
  if (message) out.push(message)
125
140
  }
126
141
 
127
- return { messages: out, ids, projectKey }
142
+ const chars = out.reduce((sum, message) => sum + String(message?.content?.[0]?.text ?? '').length, 0)
143
+ return { messages: out, ids, projectKey, chars }
128
144
  }
129
145
 
130
146
  export function registerContext({ ctx, service, store, config }) {
@@ -158,7 +174,7 @@ export function registerContext({ ctx, service, store, config }) {
158
174
  ? decision.messages.toSpliced(lastClaimedIndex + 1, 0, ...pending)
159
175
  : [...decision.messages.slice(0, lastClaimedIndex + 1), ...pending, ...decision.messages.slice(lastClaimedIndex + 1)]
160
176
  try {
161
- service.recordInjected(built.ids, session?.id, built.projectKey)
177
+ service.recordInjected(built.ids, session?.id, built.projectKey, built.chars)
162
178
  } catch {
163
179
  // Trace is diagnostic only; never fail the step for it.
164
180
  }
@@ -18,6 +18,7 @@ export function rank(query, entries, metaIndex, config = {}) {
18
18
 
19
19
  for (const item of bm25) {
20
20
  const entry = item.entry
21
+ if (entry.scope === 'archive') continue
21
22
  const meta = metaIndex?.entries?.[entry.id] ?? {}
22
23
  if (meta.excluded === true || meta.status === 'archived' || meta.status === 'disputed') continue
23
24
  const relevance = item.score / max
@@ -31,6 +32,7 @@ export function rank(query, entries, metaIndex, config = {}) {
31
32
 
32
33
  if (candidates.length === 0) {
33
34
  for (const entry of entries) {
35
+ if (entry.scope === 'archive') continue
34
36
  const meta = metaIndex?.entries?.[entry.id] ?? {}
35
37
  if (meta.pinned === true && meta.excluded !== true) {
36
38
  candidates.push({ entry, score: 1, parts: { relevance: 0, retention: retrievability(meta, now), importance: Number(meta.importance) || 0.5, trust: trustOf(meta), pin: 1 } })
package/lib/meta.js CHANGED
@@ -50,6 +50,7 @@ export function isPinned(entry, item, config = {}) {
50
50
  }
51
51
 
52
52
  export function statusOf(meta, entry, config = {}) {
53
+ if (entry?.scope === 'archive') return 'archived'
53
54
  const item = metaFor(meta, entry)
54
55
  if (item.excluded === true) return 'excluded'
55
56
  if (item.status === 'archived' || item.status === 'disputed' || item.status === 'candidate') return item.status
package/lib/organizer.js CHANGED
@@ -11,13 +11,22 @@ function clip(value, length) {
11
11
  }
12
12
 
13
13
  function extractText(event) {
14
- const data = event?.data
15
- if (typeof data?.text === 'string') return data.text
16
- if (Array.isArray(data?.content)) {
17
- return data.content.filter((block) => block && block.type === 'text' && typeof block.text === 'string').map((block) => block.text).join('\n')
14
+ try {
15
+ const data = event?.data ?? {}
16
+ const content = data.message?.content ?? data.content ?? data.text
17
+ let output = ''
18
+ if (typeof content === 'string') output = content
19
+ else if (Array.isArray(content)) {
20
+ output = content.map((block) => {
21
+ if (!block || typeof block.text !== 'string') return ''
22
+ if (/^Current runtime context\./i.test(block.text)) return ''
23
+ return block.text
24
+ }).join('\n')
25
+ } else if (content && typeof content === 'object') output = JSON.stringify(content)
26
+ return output.replace(/<system-reminder[\s\S]*?<\/system-reminder>/gi, '').trim()
27
+ } catch {
28
+ return ''
18
29
  }
19
- if (typeof data?.message?.text === 'string') return data.message.text
20
- return ''
21
30
  }
22
31
 
23
32
  function stripFence(text) {
@@ -242,6 +251,7 @@ export function createAutoOrganizer({ ctx, service, store, config, host }) {
242
251
  }
243
252
 
244
253
  function register() {
254
+ if (!lastState || !lastState.time) recordState({ time: new Date().toISOString(), status: 'idle', reason: 'registered' })
245
255
  if (typeof ctx?.on !== 'function') return () => {}
246
256
  const listener = (session, event) => {
247
257
  try { handle(session, event) } catch (error) { recordError('organizer', error?.message || String(error), { sessionId: session?.id || null }) }
package/lib/preview.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { budgetClip, stripDeletedLines, toHomeShort } from './shared/text.js'
4
+ import { serializeMemory } from './shared/markdown.js'
4
5
 
5
6
  function readText(file) {
6
7
  try { return readFileSync(file, 'utf8') } catch { return '' }
@@ -18,7 +19,18 @@ function section(title, raw, limit, source) {
18
19
  }
19
20
  }
20
21
 
21
- export function previewProjections({ store, config, projectKey }) {
22
+ function activeText(service, scope, key) {
23
+ const entries = service.read({ scope, project: scope === 'project' ? key : undefined, status: 'active', limit: 500 })
24
+ const sections = []
25
+ for (const entry of entries) {
26
+ let section = sections.find((item) => item.title === (entry.section || '记忆'))
27
+ if (!section) { section = { title: entry.section || '记忆', entries: [] }; sections.push(section) }
28
+ section.entries.push({ id: entry.id, text: entry.text })
29
+ }
30
+ return { text: stripDeletedLines(serializeMemory(sections)), ids: entries.map((entry) => entry.id) }
31
+ }
32
+
33
+ export function previewProjections({ store, config, projectKey, service }) {
22
34
  const key = String(projectKey || '')
23
35
  const limit = Math.max(1, Number(config.maxInjectionChars) || 6000)
24
36
  const sections = []
@@ -27,14 +39,10 @@ export function previewProjections({ store, config, projectKey }) {
27
39
  const conventions = readText(join(store.dirs.root, 'conventions.md'))
28
40
  if (conventions.trim()) sections.push(section('协作约定', conventions, Math.min(limit, 3000), join(store.dirs.root, 'conventions.md')))
29
41
 
30
- const global = store.read('global', null)
31
- if (global.text.trim()) {
32
- sections.push({ ...section('全局记忆', stripDeletedLines(global.text), limit, toHomeShort(global.file)), ids: global.entries.map((entry) => entry.id) })
33
- }
34
- const project = key ? store.read('project', key) : { text: '', file: '', entries: [] }
35
- if (project.text.trim()) {
36
- sections.push({ ...section('项目记忆', stripDeletedLines(project.text), limit, toHomeShort(project.file)), ids: project.entries.map((entry) => entry.id), project: key })
37
- }
42
+ const globalRaw = service ? activeText(service, 'global', null) : { text: store.read('global', null).text, ids: [] }
43
+ if (globalRaw.text.trim()) sections.push({ ...section('全局记忆', globalRaw.text, limit, toHomeShort(store.fileFor('global', null))), ids: globalRaw.ids })
44
+ const projectRaw = service && key ? activeText(service, 'project', key) : (key ? { text: store.read('project', key).text, ids: [] } : { text: '', ids: [] })
45
+ if (projectRaw.text.trim()) sections.push({ ...section('项目记忆', projectRaw.text, limit, toHomeShort(key ? store.fileFor('project', key) : '')), ids: projectRaw.ids, project: key })
38
46
  if (store.listProjectKeys().length > 0 || store.listReferenceNames().length > 0) {
39
47
  const index = ['# 记忆索引', '项目:' + store.listProjectKeys().join(', '), '参考:' + store.listReferenceNames().join(', '), '当前项目:' + key].join('\n')
40
48
  sections.push(section('记忆索引', index, Math.min(limit, 2000), 'index'))
package/lib/service.js CHANGED
@@ -336,8 +336,9 @@ export function createService({ store, config }) {
336
336
  const totalChars = entries.reduce((sum, entry) => sum + countChars(entry.text), 0)
337
337
  const trace = store.readTrace()
338
338
  const lastProject = [...trace].reverse().find((row) => row.project)?.project ?? (store.listProjectKeys()[0] ?? null)
339
- const globalChars = store.read('global', null).entries.reduce((sum, entry) => sum + countChars(entry.text), 0)
340
- const projectChars = lastProject ? store.read('project', lastProject).entries.reduce((sum, entry) => sum + countChars(entry.text), 0) : 0
339
+ const activeEntries = entries.filter((entry) => statusOf(meta, entry, config) === 'active')
340
+ const globalChars = activeEntries.filter((entry) => entry.scope === 'global').reduce((sum, entry) => sum + countChars(entry.text), 0)
341
+ const projectChars = lastProject ? activeEntries.filter((entry) => entry.scope === 'project' && entry.key === lastProject).reduce((sum, entry) => sum + countChars(entry.text), 0) : 0
341
342
  const chars = Math.min(globalChars, config.maxInjectionChars) + Math.min(projectChars, config.maxInjectionChars)
342
343
  return {
343
344
  ok: true,
@@ -386,10 +387,10 @@ export function createService({ store, config }) {
386
387
  return content === '' ? { ok: false, error: 'reference not found: ' + name } : { ok: true, name, content }
387
388
  }
388
389
 
389
- function recordInjected(ids, sessionId, project) {
390
+ function recordInjected(ids, sessionId, project, chars) {
390
391
  const unique = [...new Set(ids)]
391
392
  const trace = store.readTrace()
392
- trace.push({ time: new Date().toISOString(), kind: 'inject', sessionId: sessionId ?? null, project: project ?? null, ids: unique })
393
+ trace.push({ time: new Date().toISOString(), kind: 'inject', sessionId: sessionId ?? null, project: project ?? null, ids: unique, chars: Number.isFinite(Number(chars)) ? Number(chars) : null })
393
394
  store.writeTrace(trace)
394
395
  }
395
396
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-memory-metabolism",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Local-first Markdown memory for DeepSeek Harness with a full-page memory workbench, independent chat threads, project scoping and a restricted memory assistant.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -50,7 +50,7 @@
50
50
  },
51
51
  "scripts": {
52
52
  "check": "node --check index.js && node --check client.js",
53
- "test": "node tests/core.mjs && node tests/api.mjs && node tests/chat-store.mjs && node tests/chat-tools.mjs && node tests/chat-agent.mjs && node tests/organizer.mjs",
53
+ "test": "node tests/algorithm.mjs && node tests/core.mjs && node tests/api.mjs && node tests/chat-store.mjs && node tests/chat-tools.mjs && node tests/chat-agent.mjs && node tests/organizer.mjs",
54
54
  "pack:check": "npm pack --dry-run"
55
55
  },
56
56
  "dsh": {