dsh-plugin-memory 0.19.4 → 0.20.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/index.js CHANGED
@@ -100,6 +100,7 @@ import {
100
100
  import { ensureMemoryScaffold } from './scaffold.js'
101
101
  import { collectInsights } from './insights.js'
102
102
  import { buildMemoryGraph } from './graph.js'
103
+ import { buildTimeline } from './timeline.js'
103
104
  import { MemoryConfigStore } from './config-store.js'
104
105
  import { SettingsSchema } from './schema.js'
105
106
  import { DigestGuard } from './digest-guard.js'
@@ -128,6 +129,9 @@ export const INSIGHTS_ROUTE_PATH = '/api/memory/insights'
128
129
 
129
130
  /** Read-only HTTP route serving the memory graph (nodes + edges). */
130
131
  export const GRAPH_ROUTE_PATH = '/api/memory/graph'
132
+
133
+ /** Read-only HTTP route serving the memory timeline (events derived from log.md). */
134
+ export const TIMELINE_ROUTE_PATH = '/api/memory/timeline'
131
135
  export const CONTROL_ROUTE_PATH = '/api/memory/control'
132
136
 
133
137
  /** Per-session memory gate: GET the state, POST a toggle. */
@@ -586,26 +590,36 @@ export function apply(ctx, config = {}) {
586
590
  if (!isRootAgent(agent)) return
587
591
  agent.ctx.effect(() => {
588
592
  const stopInserted = ctx.on('agent/inbox/inserted', ({ agent: target, message }) => {
589
- if (target?.id !== agent.id) return
590
- if (message?.source?.kind !== 'user') return
591
- if (stamped.has(agent.id)) return
592
- const resolved = store.get()
593
- if (!sessionEnabled(agent, resolved)) return
594
- if (!tracker.shouldInject(agent.id, resolved)) return
595
- stamped.add(agent.id)
593
+ // Never let bookkeeping throw inside the host's event dispatch.
596
594
  try {
597
- const memoryDir = currentMemoryDir
598
- const block = renderBootBlock(memoryDir, { bootFiles, bootMaxChars, bootFileBudgets })
599
- const referenced = extractReferencedPages(block, memoryDir)
600
- const touched = touchPages(memoryDir, [...bootFiles, ...referenced])
601
- if (touched.length > 0) {
602
- ctx.logger?.info?.(`memory: last_access stamped on ${touched.length} page(s)`)
595
+ if (target?.id !== agent.id) return
596
+ if (message?.source?.kind !== 'user') return
597
+ if (stamped.has(agent.id)) return
598
+ const resolved = store.get()
599
+ if (!sessionEnabled(agent, resolved)) return
600
+ if (!tracker.shouldInject(agent.id, resolved)) return
601
+ stamped.add(agent.id)
602
+ try {
603
+ const memoryDir = currentMemoryDir
604
+ const block = renderBootBlock(memoryDir, { bootFiles, bootMaxChars, bootFileBudgets })
605
+ const referenced = extractReferencedPages(block, memoryDir)
606
+ const touched = touchPages(memoryDir, [...bootFiles, ...referenced])
607
+ if (touched.length > 0) {
608
+ ctx.logger?.info?.(`memory: last_access stamped on ${touched.length} page(s)`)
609
+ }
610
+ } catch (error) {
611
+ ctx.logger?.warn?.(`memory: last_access stamp failed: ${error instanceof Error ? error.message : String(error)}`)
603
612
  }
604
613
  } catch (error) {
605
- ctx.logger?.warn?.(`memory: last_access stamp failed: ${error instanceof Error ? error.message : String(error)}`)
614
+ ctx.logger?.warn?.(`memory: page-access listener failed: ${error instanceof Error ? error.message : String(error)}`)
606
615
  }
607
616
  })
608
- return () => stopInserted?.()
617
+ return () => {
618
+ // The session id is unique, so forgetting it on teardown only
619
+ // releases memory; it can never cause a re-stamp of a live session.
620
+ stamped.delete(agent.id)
621
+ stopInserted?.()
622
+ }
609
623
  })
610
624
 
611
625
  } catch (error) {
@@ -1096,6 +1110,31 @@ export function apply(ctx, config = {}) {
1096
1110
  })
1097
1111
  webCtx.effect(() => disposeGraphRoute, 'memory.graph-route()')
1098
1112
  ctx.logger?.info(`memory: graph route at ${GRAPH_ROUTE_PATH}`)
1113
+
1114
+ // Read-only memory timeline: the same store projected onto a time axis.
1115
+ // Never fails the request — a missing/corrupt log yields an empty payload.
1116
+ const disposeTimelineRoute = webCtx.webServer.register({
1117
+ kind: 'exact',
1118
+ path: TIMELINE_ROUTE_PATH,
1119
+ handler: (req, res) => {
1120
+ try {
1121
+ if (req.method !== 'GET') {
1122
+ res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' })
1123
+ res.end(JSON.stringify({ error: 'method not allowed' }))
1124
+ return
1125
+ }
1126
+ const payload = buildTimeline(currentMemoryDir)
1127
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
1128
+ res.end(JSON.stringify(payload))
1129
+ } catch (error) {
1130
+ ctx.logger?.warn?.(`memory: timeline route failed: ${error instanceof Error ? error.message : String(error)}`)
1131
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
1132
+ res.end(JSON.stringify({ events: [], stats: { events: 0, pages: 0 } }))
1133
+ }
1134
+ },
1135
+ })
1136
+ webCtx.effect(() => disposeTimelineRoute, 'memory.timeline-route()')
1137
+ ctx.logger?.info(`memory: timeline route at ${TIMELINE_ROUTE_PATH}`)
1099
1138
  })
1100
1139
 
1101
1140
  return () => {
@@ -1122,6 +1161,7 @@ export { renderBootBlock, ensureMemoryScaffold, SettingsSchema, MemoryConfigStor
1122
1161
  export { touchPages, touchPageFile, extractReferencedPages, listPagePaths, accessSummary, today }
1123
1162
  export { collectInsights, readRecentLog } from './insights.js'
1124
1163
  export { buildMemoryGraph, EDGE_KINDS } from './graph.js'
1164
+ export { buildTimeline } from './timeline.js'
1125
1165
  export { buildToneGuide, TONE_INTENSITIES, TONE_GUIDE_MAX_LINES } from './tone.js'
1126
1166
  export { claimProactiveLock, readProactiveLock, defaultProactiveCooldownPath } from './proactive-lock.js'
1127
1167
  export { collectGrowth, renderGrowthRecap, growthRecapDue } from './growth.js'
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Memory timeline projection.
3
+ *
4
+ * The timeline is derived entirely from the files the memory library already
5
+ * owns: `log.md` supplies the events (one `## [YYYY-MM-DD] kind | title`
6
+ * heading each), and page frontmatter supplies the title/file names used to
7
+ * attach an event to a page so the client can open it. Nothing is cached and
8
+ * nothing is written: a missing or unreadable log yields an empty timeline,
9
+ * never an error.
10
+ *
11
+ * @module timeline
12
+ */
13
+
14
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
15
+ import { join, relative, sep } from 'node:path'
16
+
17
+ /** Log kinds folded into the five timeline groups. */
18
+ export const GROUP_OF = {
19
+ fix: 'fix',
20
+ bugfix: 'fix',
21
+ repair: 'fix',
22
+ feat: 'feat',
23
+ feature: 'feat',
24
+ implement: 'feat',
25
+ impl: 'feat',
26
+ publish: 'publish',
27
+ release: 'publish',
28
+ deliverable: 'publish',
29
+ decision: 'decision',
30
+ design: 'decision',
31
+ }
32
+
33
+ /**
34
+ * Process-noise kinds hidden by default on the timeline. Everything else is a
35
+ * key memory event and is shown without opting in.
36
+ */
37
+ export const NOISE_KINDS = new Set([
38
+ 'note',
39
+ 'digest',
40
+ 'install',
41
+ 'uninstall',
42
+ 'setup',
43
+ 'bootstrap',
44
+ 'task',
45
+ 'probe',
46
+ 'recall',
47
+ 'consolidate',
48
+ 'ops',
49
+ 'schedule',
50
+ 'export',
51
+ ])
52
+
53
+ const LOG_LINE = /^## \[(\d{4}-\d{2}-\d{2})\] (\w+) \| (.+)$/
54
+ const PAGE_SKIP = new Set(['SOUL.md', 'MEMORY.md', 'index.md', 'log.md', 'BOOTSTRAP.md'])
55
+
56
+ /** @param {string} kind @returns {'fix'|'feat'|'publish'|'decision'|'other'} */
57
+ export function groupOf(kind) {
58
+ return GROUP_OF[kind] ?? 'other'
59
+ }
60
+
61
+ /** @param {string} kind @returns {boolean} */
62
+ export function isNoiseKind(kind) {
63
+ return NOISE_KINDS.has(kind)
64
+ }
65
+
66
+ /**
67
+ * Index memory pages (outside `raw/`) with their frontmatter title, relative
68
+ * path and file stem, so log events can be matched back to a file.
69
+ *
70
+ * @param {string} memoryDir
71
+ * @returns {{ path: string, title: string | undefined, name: string }[]}
72
+ */
73
+ function readPageIndex(memoryDir) {
74
+ const pages = []
75
+ const walk = (dir) => {
76
+ let entries
77
+ try {
78
+ entries = readdirSync(dir, { withFileTypes: true })
79
+ } catch {
80
+ return
81
+ }
82
+ for (const entry of entries) {
83
+ const absolute = join(dir, entry.name)
84
+ if (entry.isDirectory()) {
85
+ if (entry.name !== 'raw') walk(absolute)
86
+ continue
87
+ }
88
+ if (!entry.name.endsWith('.md') || PAGE_SKIP.has(entry.name)) continue
89
+ try {
90
+ const text = readFileSync(absolute, 'utf8')
91
+ const heading = /^title:\s*(.+)$/m.exec(text)
92
+ const title = heading?.[1]?.trim().replace(/^["']|["']$/g, '')
93
+ pages.push({
94
+ path: relative(memoryDir, absolute).split(sep).join('/'),
95
+ title,
96
+ name: entry.name.replace(/\.md$/, ''),
97
+ })
98
+ } catch {
99
+ // unreadable page: skip it, keep the rest of the timeline
100
+ }
101
+ }
102
+ }
103
+ walk(memoryDir)
104
+ return pages
105
+ }
106
+
107
+ /**
108
+ * The most specific page whose title or file stem appears in the event title.
109
+ * Free-text headings cannot always be resolved; an undefined result is fine.
110
+ *
111
+ * @param {string} title
112
+ * @param {{ path: string, title: string | undefined, name: string }[]} pages
113
+ * @returns {string | undefined}
114
+ */
115
+ function matchPath(title, pages) {
116
+ let best
117
+ for (const page of pages) {
118
+ for (const needle of [page.title, page.name]) {
119
+ if (typeof needle !== 'string' || needle.length === 0) continue
120
+ if (!title.includes(needle)) continue
121
+ if (best === undefined || needle.length > best.length) best = { path: page.path, length: needle.length }
122
+ }
123
+ }
124
+ return best?.path
125
+ }
126
+
127
+ /**
128
+ * Build the timeline payload served by `GET /api/memory/timeline`.
129
+ *
130
+ * @param {string} memoryDir
131
+ * @returns {{ events: object[], stats: { events: number, first?: string, last?: string, pages: number } }}
132
+ */
133
+ export function buildTimeline(memoryDir) {
134
+ const pages = typeof memoryDir === 'string' && existsSync(memoryDir) ? readPageIndex(memoryDir) : []
135
+ let text = ''
136
+ try {
137
+ const logPath = join(memoryDir, 'log.md')
138
+ if (existsSync(logPath)) text = readFileSync(logPath, 'utf8')
139
+ } catch {
140
+ // unreadable log: empty timeline
141
+ }
142
+
143
+ const events = []
144
+ for (const line of text.split(/\r?\n/)) {
145
+ const match = LOG_LINE.exec(line)
146
+ if (!match) continue
147
+ const [, date, kind, rawTitle] = match
148
+ const title = rawTitle.trim()
149
+ /** @type {{ date: string, kind: string, group: string, title: string, path?: string }} */
150
+ const event = { date, kind, group: groupOf(kind), title }
151
+ const path = matchPath(title, pages)
152
+ if (path !== undefined) event.path = path
153
+ events.push(event)
154
+ }
155
+ events.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0))
156
+
157
+ /** @type {{ events: number, first?: string, last?: string, pages: number }} */
158
+ const stats = { events: events.length, pages: pages.length }
159
+ if (events.length > 0) {
160
+ stats.first = events[0].date
161
+ stats.last = events[events.length - 1].date
162
+ }
163
+ return { events, stats }
164
+ }
@@ -310,3 +310,26 @@ export function readProactiveLock(path: string):
310
310
 
311
311
  /** Default lock path: `${DSH_HOME||~/.dsh}/proactive-cooldown.json`. */
312
312
  export function defaultProactiveCooldownPath(): string
313
+
314
+ /** One memory timeline event derived from `log.md`. */
315
+ export interface TimelineEvent {
316
+ /** Calendar date, `YYYY-MM-DD`. */
317
+ date: string
318
+ /** Raw log kind (fix, feat, publish, decision, note, task, …). */
319
+ kind: string
320
+ /** Five-group classification used by the timeline colours. */
321
+ group: 'fix' | 'feat' | 'publish' | 'decision' | 'other'
322
+ /** Event headline (text after `|`). */
323
+ title: string
324
+ /** Relative page path when the title matches a page (for opening it). */
325
+ path?: string
326
+ }
327
+
328
+ /** Payload of `GET /api/memory/timeline`. */
329
+ export interface TimelinePayload {
330
+ events: TimelineEvent[]
331
+ stats: { events: number; first?: string; last?: string; pages: number }
332
+ }
333
+
334
+ /** Build the timeline payload from a memory directory (read-only). */
335
+ export function buildTimeline(memoryDir: string): TimelinePayload
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.19.4",
4
+ "version": "0.20.0",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",