dsh-memory-metabolism 0.2.0 → 0.2.1

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/service.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { resolveProjectKey } from './project.js'
2
- import { metaFor, syncMeta, statusOf, feedback as applyFeedback, archive as markArchived, saveMeta } from './meta.js'
2
+ import { metaFor, syncMeta, statusOf, isPinned, feedback as applyFeedback, archive as markArchived, recordUse, saveMeta } from './meta.js'
3
3
  import { loadMeta } from './meta.js'
4
4
  import { retrievability } from './shared/fsrs.js'
5
5
  import { stableId, countChars } from './shared/text.js'
@@ -8,6 +8,10 @@ import { scoreCandidate } from './engines/write-gate.js'
8
8
  import { rank } from './engines/retrieve.js'
9
9
  import { planConsolidation } from './engines/consolidate.js'
10
10
  import { migrateFromMemoryPalace } from './migrate.js'
11
+ import { existsSync } from 'node:fs'
12
+ import { homedir } from 'node:os'
13
+ import { dirname, join } from 'node:path'
14
+ import { existingTarget, revealPath } from './open.js'
11
15
 
12
16
  function normalize(text) {
13
17
  return String(text ?? '').replace(/\s+/g, ' ').trim().toLowerCase()
@@ -37,7 +41,11 @@ export function createService({ store, config }) {
37
41
  let lastSessionId = null
38
42
 
39
43
  function projectKey(cwd) {
40
- return resolveProjectKey(cwd, config).key
44
+ const info = resolveProjectKey(cwd, config)
45
+ if (cwd && config.projectStorage !== 'central' && info.root) {
46
+ return store.registerProject({ key: info.key, root: info.root, displayName: info.root ? undefined : info.key }) || info.key
47
+ }
48
+ return info.key
41
49
  }
42
50
 
43
51
  function setPlanMode(sessionId, active) {
@@ -107,7 +115,7 @@ export function createService({ store, config }) {
107
115
  useCount: Number(item.useCount) || 0,
108
116
  lastUsed: item.lastUsed ?? null,
109
117
  created: item.created ?? null,
110
- pinned: item.pinned === true,
118
+ pinned: isPinned(entry, item, config),
111
119
  excluded: item.excluded === true,
112
120
  }
113
121
  }
@@ -151,6 +159,7 @@ export function createService({ store, config }) {
151
159
  item.source = input.source ?? 'user'
152
160
  item.importance = Number.isFinite(Number(input.importance)) ? Math.min(1, Math.max(0, Number(input.importance))) : 0.5
153
161
  item.status = gate.decision === 'candidate' ? 'candidate' : 'active'
162
+ if (scope === 'global') item.pinned = input.pinned !== false
154
163
  item.writeScore = Number(gate.probability.toFixed(3))
155
164
  saveMeta(store, meta)
156
165
  return {
@@ -181,6 +190,8 @@ export function createService({ store, config }) {
181
190
  const entries = allEntries()
182
191
  const ranked = rank(query, entries, meta, { ...config, retrieveTopK: limit })
183
192
  const ids = ranked.map((item) => item.entry.id)
193
+ recordUse(meta, ids)
194
+ saveMeta(store, meta)
184
195
  const trace = store.readTrace()
185
196
  trace.push({
186
197
  time: new Date().toISOString(),
@@ -253,6 +264,66 @@ export function createService({ store, config }) {
253
264
  return { ok: true, entry: view({ ...entry, text, section }) }
254
265
  }
255
266
 
267
+ async function reclassify(input = {}) {
268
+ if (isPlanMode(input.sessionId)) return { ok: false, error: 'plan mode: memory writes are disabled' }
269
+ const id = String(input.id ?? '')
270
+ const target = input.scope === 'global' ? 'global' : input.scope === 'project' ? 'project' : ''
271
+ if (!target) return { ok: false, error: 'target scope must be global or project' }
272
+ const entry = locate(id)
273
+ if (!entry) return { ok: false, error: 'memory not found: ' + id }
274
+ if (entry.scope !== 'global' && entry.scope !== 'project') {
275
+ return { ok: false, error: 'only global/project entries can be reclassified' }
276
+ }
277
+ if (entry.scope === target) return { ok: true, entry: view(entry), message: 'Already in target scope.' }
278
+ const traceProject = [...store.readTrace()].reverse().find((row) => row.project)?.project
279
+ const sourceKey = entry.scope === 'project' ? entry.key : null
280
+ const targetKey = target === 'project' ? String(input.project || sourceKey || traceProject || store.listProjectKeys()[0] || '') : null
281
+ if (target === 'project' && targetKey === '') return { ok: false, error: 'project key is required' }
282
+ const destination = store.read(target, targetKey)
283
+ if (destination.entries.some((item) => item.id === id)) {
284
+ return { ok: false, error: 'target scope already contains this id' }
285
+ }
286
+ const taken = await store.takeEntry(entry.scope, entry.scope === 'global' ? null : entry.key, id)
287
+ if (!taken) return { ok: false, error: 'memory changed; reload and retry' }
288
+ await store.appendEntry(target, targetKey, { id: taken.id, text: taken.text, section: taken.section })
289
+ const item = metaFor(meta, { ...entry, scope: target, key: targetKey })
290
+ item.scope = target
291
+ item.section = taken.section
292
+ item.pinned = target === 'global'
293
+ item.updated = new Date().toISOString()
294
+ saveMeta(store, meta)
295
+ return { ok: true, entry: view({ ...entry, scope: target, key: targetKey, text: taken.text, section: taken.section, pinned: item.pinned }) }
296
+ }
297
+
298
+ function pathEntries(project) {
299
+ const traceProject = [...store.readTrace()].reverse().find((row) => row.project)?.project
300
+ const key = String(project || traceProject || store.listProjectKeys()[0] || '')
301
+ const projectFile = key ? store.fileFor('project', key) : null
302
+ const entries = {
303
+ data: { path: store.dirs.root, type: 'dir' },
304
+ global: { path: store.fileFor('global', null), type: 'file' },
305
+ project: projectFile ? { path: projectFile, type: 'file', project: key } : null,
306
+ persona: { path: join(store.dirs.root, 'persona.md'), type: 'file' },
307
+ conventions: { path: join(store.dirs.root, 'conventions.md'), type: 'file' },
308
+ hostPersona: { path: join(homedir(), '.agents', 'AGENTS.md'), type: 'file' },
309
+ references: { path: store.dirs.reference, type: 'dir' },
310
+ chats: { path: store.dirs.chats, type: 'dir' },
311
+ archive: { path: store.dirs.archive, type: 'dir' },
312
+ }
313
+ return Object.fromEntries(Object.entries(entries).filter(([, value]) => value))
314
+ }
315
+
316
+ function openPath(kind, project) {
317
+ const paths = pathEntries(project)
318
+ const entry = paths[String(kind || '')]
319
+ if (!entry) return { ok: false, error: 'unknown file entry: ' + kind }
320
+ const target = existingTarget(entry.path)
321
+ if (!target) return { ok: false, error: 'path does not exist: ' + entry.path }
322
+ const opened = revealPath(target, { reveal: entry.type === 'file' && existsSync(entry.path) })
323
+ if (!opened.ok) return { ...opened, kind, requested: entry.path }
324
+ return { ...opened, kind, requested: entry.path, missing: target !== entry.path }
325
+ }
326
+
256
327
  function status() {
257
328
  const entries = allEntries()
258
329
  const counts = { total: entries.length, active: 0, candidate: 0, fading: 0, archived: 0, disputed: 0, excluded: 0 }
@@ -286,11 +357,17 @@ export function createService({ store, config }) {
286
357
  retrieveTopK: config.retrieveTopK,
287
358
  staleDays: config.staleDays,
288
359
  archiveRetrievability: config.archiveRetrievability,
360
+ globalNoForget: config.globalNoForget !== false,
361
+ projectStorage: config.projectStorage,
362
+ autoOrganize: config.autoOrganize !== false,
363
+ autoOrganizeModel: config.autoOrganizeModel || '',
364
+ autoOrganizeDelayMs: config.autoOrganizeDelayMs,
289
365
  assistantModel: config.assistantModel || '',
290
366
  assistantMaxInputChars: config.assistantMaxInputChars,
291
367
  chatHistoryChars: config.chatHistoryChars,
292
368
  chatMaxRounds: config.chatMaxRounds,
293
369
  },
370
+ paths: pathEntries(),
294
371
  }
295
372
  }
296
373
 
@@ -338,7 +415,10 @@ export function createService({ store, config }) {
338
415
  approve,
339
416
  archive,
340
417
  update,
418
+ reclassify,
341
419
  status,
420
+ paths: pathEntries,
421
+ openPath,
342
422
  consolidate,
343
423
  importLegacy,
344
424
  reference,
package/lib/store.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs'
2
- import { basename, dirname, join } from 'node:path'
2
+ import { basename, dirname, join, resolve } from 'node:path'
3
+ import { createHash } from 'node:crypto'
3
4
  import { entryBlock, parseMemory, serializeMemory, removeEntry, upsertEntry } from './shared/markdown.js'
4
5
  import { nowISO, todayISO } from './shared/text.js'
5
6
 
@@ -55,18 +56,120 @@ export function createStore(dataDir) {
55
56
  projects: join(dataDir, 'projects'),
56
57
  reference: join(dataDir, 'reference'),
57
58
  working: join(dataDir, 'working'),
59
+ chats: join(dataDir, 'chats'),
58
60
  archive: join(dataDir, 'archive'),
59
61
  meta: join(dataDir, 'meta'),
60
62
  backups: join(dataDir, 'backups'),
61
63
  }
62
64
 
65
+ const registryFile = join(dirs.meta, 'projects.json')
66
+ const projectRoots = new Map()
67
+ let registryLoaded = false
68
+
69
+ function shortHash(value) {
70
+ return createHash('sha1').update(String(value).toLowerCase()).digest('hex').slice(0, 8)
71
+ }
72
+
73
+ function loadProjects() {
74
+ if (registryLoaded) return
75
+ registryLoaded = true
76
+ try {
77
+ const doc = JSON.parse(readText(registryFile) || '{}')
78
+ for (const [key, value] of Object.entries(doc.projects || {})) {
79
+ if (value && typeof value.root === 'string' && value.root !== '') projectRoots.set(key, { ...value, key })
80
+ }
81
+ } catch {
82
+ // A malformed registry must not prevent memory access; central fallback remains.
83
+ }
84
+ }
85
+
86
+ function saveProjects() {
87
+ mkdirSync(dirs.meta, { recursive: true })
88
+ const projects = Object.fromEntries([...projectRoots.entries()].sort(([a], [b]) => a.localeCompare(b)))
89
+ atomicWrite(registryFile, JSON.stringify({ version: 1, projects }, null, 2) + '\n')
90
+ }
91
+
92
+ function projectInfo(key) {
93
+ loadProjects()
94
+ return projectRoots.get(key) || null
95
+ }
96
+
97
+ function projectLocalFile(key, root) {
98
+ return join(root, '.deepseek-harness', 'MEMORY.md')
99
+ }
100
+
101
+ function mergeLegacyProject(key, root) {
102
+ const localFile = projectLocalFile(key, root)
103
+ const legacyFile = join(dirs.projects, key, 'MEMORY.md')
104
+ if (!existsSync(legacyFile)) return false
105
+ const legacy = parseMemory(readText(legacyFile), { scope: 'project:' + key })
106
+ const localText = readText(localFile)
107
+ const local = parseMemory(localText, { scope: 'project:' + key })
108
+ const seen = new Set(local.entries.map((entry) => entry.text.trim().toLowerCase()))
109
+ let added = 0
110
+ for (const entry of legacy.entries) {
111
+ const signature = entry.text.trim().toLowerCase()
112
+ if (signature === '' || seen.has(signature)) continue
113
+ seen.add(signature)
114
+ upsertEntry(local.sections, { id: entry.id, text: entry.text, section: entry.section })
115
+ added++
116
+ }
117
+ if (added === 0 && localText !== '') return true
118
+ if (localText !== '') backup(localFile)
119
+ atomicWrite(localFile, serializeMemory(local.sections))
120
+ return true
121
+ }
122
+
123
+ function registerProject(input = {}) {
124
+ loadProjects()
125
+ const rawRoot = String(input.root || '')
126
+ if (rawRoot === '') return null
127
+ const root = resolve(rawRoot)
128
+ let key = String(input.key || basename(root)).trim() || basename(root)
129
+ const existing = projectRoots.get(key)
130
+ if (existing && resolve(existing.root).toLowerCase() !== root.toLowerCase()) {
131
+ const base = key
132
+ key = base + '-' + shortHash(root)
133
+ let suffix = 1
134
+ while (projectRoots.has(key) && resolve(projectRoots.get(key).root).toLowerCase() !== root.toLowerCase()) {
135
+ key = base + '-' + shortHash(root) + '-' + suffix++
136
+ }
137
+ }
138
+ const current = projectRoots.get(key)
139
+ if (current) {
140
+ const seen = Date.parse(current.lastSeen || '')
141
+ if (Number.isFinite(seen) && Date.now() - seen < 300_000) return key
142
+ current.lastSeen = nowISO()
143
+ current.displayName = input.displayName || current.displayName || basename(root)
144
+ current.remote = input.remote || current.remote || null
145
+ } else {
146
+ projectRoots.set(key, {
147
+ key,
148
+ id: 'p_' + shortHash(key + ':' + root),
149
+ root,
150
+ displayName: input.displayName || basename(root),
151
+ remote: input.remote || null,
152
+ createdAt: nowISO(),
153
+ lastSeen: nowISO(),
154
+ })
155
+ mkdirSync(join(root, '.deepseek-harness'), { recursive: true })
156
+ writeFileSync(join(root, '.deepseek-harness', 'project.json'), JSON.stringify(projectRoots.get(key), null, 2) + '\n', 'utf8')
157
+ mergeLegacyProject(key, root)
158
+ }
159
+ saveProjects()
160
+ return key
161
+ }
162
+
63
163
  function ensure() {
64
164
  for (const dir of Object.values(dirs)) mkdirSync(dir, { recursive: true })
65
165
  }
66
166
 
67
167
  function fileFor(scope, key, name) {
68
168
  if (scope === 'global') return join(dirs.global, 'MEMORY.md')
69
- if (scope === 'project') return join(dirs.projects, key || 'default', 'MEMORY.md')
169
+ if (scope === 'project') {
170
+ const info = projectInfo(key || 'default')
171
+ return info ? projectLocalFile(info.key, info.root) : join(dirs.projects, key || 'default', 'MEMORY.md')
172
+ }
70
173
  if (scope === 'reference') return join(dirs.reference, (name || 'reference') + '.md')
71
174
  if (scope === 'working') return join(dirs.working, (key || 'session') + '.md')
72
175
  throw new Error('unknown scope: ' + scope)
@@ -145,6 +248,15 @@ export function createStore(dataDir) {
145
248
  })
146
249
  }
147
250
 
251
+ async function takeEntry(scope, key, id) {
252
+ return mutate(scope, key, (current) => {
253
+ const entry = current.entries.find((item) => item.id === id)
254
+ if (!entry) return null
255
+ removeEntry(current.sections, id)
256
+ return entry
257
+ })
258
+ }
259
+
148
260
  async function archiveEntry(scope, key, id) {
149
261
  const found = await mutate(scope, key, (current) => {
150
262
  const entry = current.entries.find((item) => item.id === id)
@@ -161,14 +273,14 @@ export function createStore(dataDir) {
161
273
  }
162
274
 
163
275
  function listProjectKeys() {
276
+ loadProjects()
277
+ const keys = new Set(projectRoots.keys())
164
278
  try {
165
- return readdirSync(dirs.projects, { withFileTypes: true })
166
- .filter((entry) => entry.isDirectory())
167
- .map((entry) => entry.name)
168
- .sort()
169
- } catch {
170
- return []
171
- }
279
+ for (const entry of readdirSync(dirs.projects, { withFileTypes: true })) {
280
+ if (entry.isDirectory()) keys.add(entry.name)
281
+ }
282
+ } catch { /* central legacy directory is optional */ }
283
+ return [...keys].sort()
172
284
  }
173
285
 
174
286
  function listReferenceNames() {
@@ -201,6 +313,55 @@ export function createStore(dataDir) {
201
313
  return { file, text: readText(file) }
202
314
  }
203
315
 
316
+ function dailyLogFile(projectKey) {
317
+ const key = String(projectKey || 'default')
318
+ const info = projectInfo(key)
319
+ const root = info ? info.root : join(dirs.projects, key)
320
+ return join(root, '.deepseek-harness', 'memory', todayISO() + '.md')
321
+ }
322
+
323
+ function appendDailyLog(projectKey, text) {
324
+ const body = String(text || '').trim()
325
+ if (body === '') return null
326
+ const file = dailyLogFile(projectKey)
327
+ const existing = readText(file)
328
+ const header = '# ' + todayISO() + '\n\n'
329
+ const next = (existing === '' ? header : existing.endsWith('\n') ? existing : existing + '\n') + body + '\n'
330
+ atomicWrite(file, next)
331
+ return file
332
+ }
333
+
334
+ function readOrganizer() {
335
+ try { return JSON.parse(readText(join(dirs.meta, 'organizer.json')) || '{}') } catch { return {} }
336
+ }
337
+
338
+ function writeOrganizer(state) {
339
+ mkdirSync(dirs.meta, { recursive: true })
340
+ atomicWrite(join(dirs.meta, 'organizer.json'), JSON.stringify(state, null, 2) + '\n')
341
+ }
342
+
343
+ function readErrors() {
344
+ try {
345
+ return readText(join(dirs.meta, 'errors.jsonl'))
346
+ .split(/\r?\n/)
347
+ .filter(Boolean)
348
+ .map((line) => { try { return JSON.parse(line) } catch { return null } })
349
+ .filter(Boolean)
350
+ .slice(-50)
351
+ } catch {
352
+ return []
353
+ }
354
+ }
355
+
356
+ function appendError(event) {
357
+ mkdirSync(dirs.meta, { recursive: true })
358
+ const errors = readErrors()
359
+ errors.push({ time: nowISO(), ...event })
360
+ const file = join(dirs.meta, 'errors.jsonl')
361
+ atomicWrite(file, errors.slice(-50).map((item) => JSON.stringify(item)).join('\n') + '\n')
362
+ return errors[errors.length - 1]
363
+ }
364
+
204
365
  function readMeta() {
205
366
  const file = join(dirs.meta, 'index.json')
206
367
  try {
@@ -244,14 +405,23 @@ export function createStore(dataDir) {
244
405
  appendEntry,
245
406
  updateEntry,
246
407
  archiveEntry,
408
+ takeEntry,
247
409
  backup,
248
410
  listProjectKeys,
411
+ projectInfo,
412
+ registerProject,
249
413
  listReferenceNames,
250
414
  readReference,
251
415
  listArchiveFiles,
252
416
  readArchive,
253
417
  readMeta,
254
418
  writeMeta,
419
+ appendDailyLog,
420
+ dailyLogFile,
421
+ readOrganizer,
422
+ writeOrganizer,
423
+ readErrors,
424
+ appendError,
255
425
  appendFeedback,
256
426
  readTrace,
257
427
  writeTrace,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-memory-metabolism",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
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",
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",
54
54
  "pack:check": "npm pack --dry-run"
55
55
  },
56
56
  "dsh": {
package/screenshots.json CHANGED
@@ -1,8 +1,9 @@
1
- [
2
- "assets/screenshots/01-dashboard.png",
3
- "assets/screenshots/02-memory-detail.png",
4
- "assets/screenshots/03-candidates.png",
5
- "assets/screenshots/04-settings.png",
6
- "assets/screenshots/05-memory-workbench.png",
7
- "assets/screenshots/06-organizer.png"
8
- ]
1
+ [
2
+ "assets/screenshots/01-dashboard.png",
3
+ "assets/screenshots/02-memory-detail.png",
4
+ "assets/screenshots/03-candidates.png",
5
+ "assets/screenshots/04-settings.png",
6
+ "assets/screenshots/05-memory-workbench.png",
7
+ "assets/screenshots/06-organizer.png",
8
+ "assets/screenshots/07-diagnostics.png"
9
+ ]