dsh-plugin-memory 0.6.0 → 0.8.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/graph.js ADDED
@@ -0,0 +1,395 @@
1
+ /**
2
+ * Memory graph: turn the store's *relationships* into nodes and edges.
3
+ *
4
+ * The graph DSH renders from markdown alone is a star: `index.md` links to every
5
+ * page and pages link back to almost nothing (measured on a real store: 29 pages,
6
+ * 1 page-to-page link). That shape is true but uninformative — it says "the index
7
+ * lists everything", not "these memories belong together".
8
+ *
9
+ * This module recovers the relationships the store already encodes but nobody
10
+ * drew:
11
+ *
12
+ * - `link` — an explicit markdown link between two pages (the strongest signal);
13
+ * - `tag` — pages sharing a frontmatter tag (`#dsh`, `#plugin`, …);
14
+ * - `type` — pages of the same kind (all `projects`, all `skills`), a weak
15
+ * grouping edge that is off by default.
16
+ *
17
+ * Read-only and dependency-free: it derives everything from frontmatter and
18
+ * bodies, never writes, and degrades to an empty graph instead of throwing.
19
+ *
20
+ * @module dsh-plugin-memory/graph
21
+ */
22
+
23
+ import { existsSync, readFileSync } from 'node:fs'
24
+ import { basename, dirname, join, normalize } from 'node:path'
25
+ import { listPagePaths } from './pages.js'
26
+ import { parseFrontmatter } from './insights.js'
27
+ import { layoutGraph, typeColor } from './graph-layout.js'
28
+
29
+ /** Edge kinds, strongest first; the client decides which to draw. */
30
+ export const EDGE_KINDS = ['link', 'tag', 'type']
31
+
32
+ /** Root meta files are not memory pages, but they anchor the graph visibly. */
33
+ const META_FILES = ['SOUL.md', 'MEMORY.md', 'index.md', 'log.md']
34
+
35
+ /** Tokens so generic they connect everything and therefore explain nothing. */
36
+ const STOP_TAGS = new Set([
37
+ 'project', 'projects', 'skill', 'skills', 'decision', 'decisions',
38
+ 'concept', 'concepts', 'user', 'identity', 'fact',
39
+ ])
40
+
41
+ /**
42
+ * Words that name a *bucket* rather than a topic. They are still evidence of
43
+ * shared intent (a page tagged `#skill` is a skill record), just weak evidence:
44
+ * alone they should not draw an edge, together or beside a topic tag they make
45
+ * a reasonable suggestion. `STOP_TAGS` above is the stronger form — pure type
46
+ * words that carry no intent at all.
47
+ */
48
+ const WEAK_TAGS = new Set([
49
+ 'skill', 'skills', 'project', 'projects', 'decision', 'decisions',
50
+ 'concept', 'concepts', 'fact', 'user', 'identity', 'meta',
51
+ ])
52
+
53
+
54
+ /** Stable-ish id for a node: the store-relative path. */
55
+ const nodeId = (path) => path.replace(/^\.\//, '')
56
+
57
+ /**
58
+ * Resolve a markdown link target to a node id. Links in a memory page are
59
+ * usually *relative to that page* (`../skills/foo.md`), so anchor them before
60
+ * normalising — otherwise every cross-folder link silently disappears.
61
+ * @param {string} fromId the linking page's id
62
+ * @param {string} target the raw href
63
+ * @returns {string} candidate node id
64
+ */
65
+ function resolveLink(fromId, target) {
66
+ const clean = target.trim().replace(/^<|>$/g, '')
67
+ if (clean.startsWith('/')) return nodeId(clean)
68
+ return normalize(join(dirname(fromId), clean)).split('\\').join('/')
69
+ }
70
+
71
+ /** Parse `tags: [a, b]` (frontmatter is flat in this store by convention). */
72
+ function parseTags(frontmatter) {
73
+ const raw = frontmatter.tags
74
+ if (typeof raw !== 'string') return []
75
+ const inner = /^\[(.*)\]$/.exec(raw.trim())
76
+ const body = inner ? inner[1] : raw
77
+ return body
78
+ .split(',')
79
+ .map((tag) => tag.trim().replace(/^#/, ''))
80
+ .filter((tag) => tag.length > 0)
81
+ }
82
+
83
+ /** The first sentence of the body, used as hover text when nothing else fits. */
84
+ function bodyPreview(text) {
85
+ const body = text.replace(/^---[\s\S]*?\n---\n?/, '')
86
+ for (const line of body.split('\n')) {
87
+ const clean = line.trim()
88
+ if (clean.length === 0 || clean.startsWith('#') || clean.startsWith('>')) continue
89
+ return clean.replace(/[*`[\]]/g, '').slice(0, 120)
90
+ }
91
+ return ''
92
+ }
93
+
94
+ /**
95
+ * Build the memory graph.
96
+ *
97
+ * @param {string} memoryDir absolute path of the memory store
98
+ * @param {{ includeMeta?: boolean, includeTypeEdges?: boolean, stopTags?: Set<string> }} [options]
99
+ * @returns {{
100
+ * nodes: Array<{ id: string, label: string, kind: string, type: string, tags: string[],
101
+ * degree: number, salience?: number, lastAccess?: string, preview: string, hub: boolean }>,
102
+ * edges: Array<{ source: string, target: string, kind: string, weight: number, label?: string }>,
103
+ * stats: { pages: number, links: number, tagEdges: number, typeEdges: number, isolated: string[] },
104
+ * }}
105
+ */
106
+ export function buildMemoryGraph(memoryDir, options = {}) {
107
+ const stopTags = options.stopTags ?? STOP_TAGS
108
+ const paths = listPagePaths(memoryDir)
109
+ const nodes = []
110
+ const edges = []
111
+ const byId = new Map()
112
+
113
+ for (const rel of paths) {
114
+ const id = nodeId(rel)
115
+ let text = ''
116
+ try {
117
+ text = readFileSync(join(memoryDir, rel), 'utf8')
118
+ } catch {
119
+ continue
120
+ }
121
+ const fm = parseFrontmatter(text)
122
+ const salience = Number(fm.salience)
123
+ const node = {
124
+ id,
125
+ label: fm.title || basename(rel, '.md'),
126
+ kind: 'page',
127
+ type: fm.type || 'unknown',
128
+ tags: parseTags(fm),
129
+ salience: [1, 2, 3].includes(salience) ? salience : undefined,
130
+ lastAccess: typeof fm.last_access === 'string' ? fm.last_access : undefined,
131
+ preview: bodyPreview(text),
132
+ degree: 0,
133
+ hub: false,
134
+ }
135
+ nodes.push(node)
136
+ byId.set(id, node)
137
+ }
138
+
139
+ if (options.includeMeta !== false) {
140
+ for (const name of META_FILES) {
141
+ if (!existsSync(join(memoryDir, name))) continue
142
+ const node = {
143
+ id: name,
144
+ label: name.replace(/\.md$/, ''),
145
+ kind: 'meta',
146
+ type: 'meta',
147
+ tags: [],
148
+ preview: '',
149
+ degree: 0,
150
+ hub: true,
151
+ }
152
+ nodes.push(node)
153
+ byId.set(name, node)
154
+ }
155
+ }
156
+
157
+ const seen = new Set()
158
+ const addEdge = (source, target, kind, weight, label) => {
159
+ if (!byId.has(source) || !byId.has(target) || source === target) return
160
+ const [a, b] = source < target ? [source, target] : [target, source]
161
+ const key = `${kind}:${a}|${b}`
162
+ if (seen.has(key)) return
163
+ seen.add(key)
164
+ edges.push({ source: a, target: b, kind, weight, ...(label ? { label } : {}) })
165
+ byId.get(a).degree += 1
166
+ byId.get(b).degree += 1
167
+ }
168
+
169
+ // 1. explicit links, from every node — root meta files included. index.md is
170
+ // the routing table: 33 links to every page in the store. A previous
171
+ // version skipped meta files entirely, which left the index node floating
172
+ // alone in the picture while it is in fact the busiest node in the store.
173
+ let links = 0
174
+ let indexLinks = 0
175
+ for (const node of [...nodes]) {
176
+ let text = ''
177
+ try {
178
+ text = readFileSync(join(memoryDir, node.id), 'utf8')
179
+ } catch {
180
+ continue
181
+ }
182
+ for (const match of text.matchAll(/\]\(([^)]+\.md)\)/g)) {
183
+ const target = resolveLink(node.id, match[1])
184
+ if (target === node.id || !byId.has(target)) continue
185
+ // The routing table's own rows are their own kind of relationship: an
186
+ // index→page edge means "listed here", not "these two belong together".
187
+ const fromMeta = node.kind === 'meta'
188
+ addEdge(node.id, target, fromMeta ? 'index' : 'link', fromMeta ? 0.4 : 1)
189
+ if (fromMeta) indexLinks += 1
190
+ else links += 1
191
+ }
192
+ }
193
+
194
+ // 2. shared tags — one edge per tag, labelled with it, weight = how many pages
195
+ const tagGroups = new Map()
196
+ for (const node of nodes) {
197
+ if (node.kind !== 'page') continue
198
+ for (const tag of node.tags) {
199
+ if (stopTags.has(tag)) continue
200
+ if (!tagGroups.has(tag)) tagGroups.set(tag, [])
201
+ tagGroups.get(tag).push(node.id)
202
+ }
203
+ }
204
+ let tagEdges = 0
205
+ for (const [tag, members] of tagGroups) {
206
+ if (members.length < 2) continue
207
+ // Keep dense tags readable: a tag shared by 20 pages becomes a chain through
208
+ // the first member rather than 190 edges.
209
+ const anchor = members[0]
210
+ for (const member of members.slice(1)) {
211
+ addEdge(anchor, member, 'tag', 1, tag)
212
+ tagEdges += 1
213
+ }
214
+ }
215
+
216
+ // 3. same-type edges (off by default: weak, and can overwhelm the picture)
217
+ let typeEdges = 0
218
+ if (options.includeTypeEdges) {
219
+ const typeGroups = new Map()
220
+ for (const node of nodes) {
221
+ if (node.kind !== 'page') continue
222
+ const key = node.type
223
+ if (!typeGroups.has(key)) typeGroups.set(key, [])
224
+ typeGroups.get(key).push(node.id)
225
+ }
226
+ for (const [type, members] of typeGroups) {
227
+ for (let i = 1; i < members.length; i += 1) {
228
+ addEdge(members[i - 1], members[i], 'type', 0.5, type)
229
+ typeEdges += 1
230
+ }
231
+ }
232
+ }
233
+
234
+ // Layout is computed here (once, server-side) rather than in the browser half:
235
+ // the client bundle cannot import local modules, and shipping coordinates keeps
236
+ // both sides from drifting apart.
237
+ const { positions, radius } = layoutGraph(nodes, edges)
238
+ for (const node of nodes) {
239
+ const p = positions.get(node.id)
240
+ if (p !== undefined) {
241
+ node.x = Math.round(p.x * 10) / 10
242
+ node.y = Math.round(p.y * 10) / 10
243
+ }
244
+ node.r = Math.round(radius(node.id) * 10) / 10 + (node.hub ? 4 : 0)
245
+ node.color = typeColor(node.type)
246
+ // Effective tags exclude container words (skill/project/user…): two pages
247
+ // "sharing" a type word are not related, they are just the same kind.
248
+ node.tagSet = new Set(node.tags.filter((tag) => !stopTags.has(tag)))
249
+ node.weakTags = new Set(node.tags.filter((tag) => WEAK_TAGS.has(tag)))
250
+ }
251
+
252
+ // Suggested links: inference, not fact. Only meaningful for pages that have
253
+ // no real relationship yet — a page already connected by a tag or an explicit
254
+ // link does not need to be told who its neighbours are.
255
+ const suggestions = options.includeSuggestions
256
+ ? suggestLinks({ nodes, edges })
257
+ : []
258
+
259
+ const isolated = nodes.filter((node) => node.degree === 0 && node.kind === 'page').map((node) => node.id)
260
+ return {
261
+ nodes,
262
+ edges,
263
+ suggestions,
264
+ stats: {
265
+ pages: nodes.filter((node) => node.kind === 'page').length,
266
+ links,
267
+ indexLinks,
268
+ tagEdges,
269
+ typeEdges,
270
+ isolated,
271
+ },
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Pages that have no real relationship, and who they should probably link to.
277
+ *
278
+ * A page whose only edge is its `index.md` row is connected in the routing
279
+ * sense and alone in the knowledge sense. This scores candidates by shared
280
+ * tags, same type and title overlap, and returns a short, explainable list —
281
+ * the point is to answer "who should this page cite?", which is the one thing
282
+ * the graph cannot infer from links that do not exist yet.
283
+ *
284
+ * Pure inference: nothing is written, and the caller decides whether to act.
285
+ *
286
+ * @param {{ nodes: Array<object>, edges: Array<object> }} graph from {@link buildMemoryGraph}
287
+ * @param {{ limit?: number, minScore?: number }} [options]
288
+ * @returns {Array<{ page: string, title: string, degree: number, candidates: Array<{ target: string, title: string, score: number, sharedTags: string[], sameType: boolean }> }>}
289
+ */
290
+ export function suggestLinks({ nodes, edges }, options = {}) {
291
+ const limit = Math.max(1, options.limit ?? 3)
292
+ const minScore = options.minScore ?? 3
293
+ // Default to findings only: a shared topic tag or title word.
294
+ const strengths = options.strengths ?? ['strong']
295
+ const pages = (nodes ?? []).filter((node) => node.kind === 'page')
296
+ const byId = new Map(pages.map((node) => [node.id, node]))
297
+
298
+ // Real relationships only: index rows do not count as knowing each other.
299
+ const realNeighbours = new Map()
300
+ for (const edge of edges ?? []) {
301
+ if (edge.kind === 'index') continue
302
+ if (!realNeighbours.has(edge.source)) realNeighbours.set(edge.source, new Set())
303
+ if (!realNeighbours.has(edge.target)) realNeighbours.set(edge.target, new Set())
304
+ realNeighbours.get(edge.source).add(edge.target)
305
+ realNeighbours.get(edge.target).add(edge.source)
306
+ }
307
+
308
+ const lonely = pages
309
+ .filter((node) => (realNeighbours.get(node.id)?.size ?? 0) === 0)
310
+ .sort((a, b) => (b.degree ?? 0) - (a.degree ?? 0))
311
+
312
+ const out = []
313
+ for (const page of lonely) {
314
+ const mine = page.tagSet ?? new Set(page.tags ?? [])
315
+ const myWords = new Set(
316
+ String(page.label).toLowerCase().split(/[^a-z0-9\u4e00-\u9fff]+/).filter((w) => w.length > 2),
317
+ )
318
+ const scored = []
319
+ for (const other of pages) {
320
+ if (other.id === page.id) continue
321
+ const theirs = other.tagSet ?? new Set(other.tags ?? [])
322
+ const sharedTags = [...mine].filter((tag) => theirs.has(tag))
323
+ const weakTags = [...(page.weakTags ?? [])].filter((tag) => (other.weakTags ?? new Set()).has(tag))
324
+ const sameType = page.type !== 'unknown' && page.type === other.type
325
+ const otherWords = String(other.label).toLowerCase().split(/[^a-z0-9\u4e00-\u9fff]+/).filter((w) => w.length > 2)
326
+ const sharedWords = otherWords.filter((w) => myWords.has(w))
327
+ // Weights: a shared topic tag is worth 3, a shared title word 2, a shared
328
+ // bucket tag 1, being the same kind of page 1. Crucially the last two
329
+ // cannot justify a suggestion by themselves — otherwise every skill page
330
+ // "should" link to every other skill page, which is noise, not signal.
331
+ const content = sharedTags.length * 3 + sharedWords.length * 2
332
+ // A page with no effective tags of its own has no topic to overlap on —
333
+ // and it is exactly the page most in need of a suggestion. For those,
334
+ // fall back to the weakest signals (same kind, shared title word) and let
335
+ // the explanation say so instead of staying silent.
336
+ // Two different kinds of "nothing to match on":
337
+ // - no tags at all: the page is genuinely unlabelled, so the weakest
338
+ // signal (being the same kind of page) is all we can offer — advice is
339
+ // still more useful than silence;
340
+ // - only bucket tags (`#skill`): the author did label it, they just did
341
+ // not say with what. Suggesting every other skill page would be noise,
342
+ // so this case still requires a shared title word or topic tag.
343
+ const hasContent = sharedTags.length > 0 || sharedWords.length > 0
344
+ const hasWeak = weakTags.length > 0
345
+ const sameKindOnly = sameType && !hasContent && !hasWeak
346
+ // A shared bucket tag is not a topic, but two pages of the same kind
347
+ // *and* the same bucket ("both are skill records") are still worth
348
+ // linking — that is how a `skills/` set becomes navigable. Without any
349
+ // tags at all we fall back to same-kind alone, remembering the store
350
+ // rarely has more than one distinct type per folder.
351
+ const unlabelled = mine.size === 0 && (page.weakTags?.size ?? 0) === 0 && (page.tags?.length ?? 0) === 0
352
+ const score = content + weakTags.length + (sameType ? 1 : 0)
353
+ const qualifies = hasContent
354
+ ? score >= minScore
355
+ : (hasWeak && sameType) || sameKindOnly || unlabelled
356
+ ? score >= minScore - 2
357
+ : false
358
+ if (qualifies) {
359
+ // Strength, not just score: a suggestion backed by a shared topic is
360
+ // worth writing into the page; "you are both skill pages" is a maybe.
361
+ // The CLI/dashboard filter on this so weak inferences never masquerade
362
+ // as findings.
363
+ const strength = hasContent ? 'strong' : 'weak'
364
+ scored.push({ other, score, sharedTags: [...sharedTags, ...weakTags], sameType, sharedWords, strength })
365
+ }
366
+ }
367
+ scored.sort((a, b) => b.score - a.score || String(a.other.id).localeCompare(String(b.other.id)))
368
+ out.push({
369
+ page: page.id,
370
+ title: page.label,
371
+ degree: page.degree ?? 0,
372
+ candidates: scored.slice(0, limit).map((entry) => ({
373
+ target: entry.other.id,
374
+ title: entry.other.label,
375
+ score: entry.score,
376
+ sharedTags: entry.sharedTags,
377
+ sharedWords: entry.sharedWords,
378
+ sameType: entry.sameType,
379
+ strength: entry.strength,
380
+ // Human-readable reason, so the CLI and the panel never guess.
381
+ reason: [
382
+ entry.sharedTags.length > 0 ? `共享 #${entry.sharedTags.join(' #')}` : '',
383
+ entry.sharedWords.length > 0 ? `标题词 ${entry.sharedWords.join('/')}` : '',
384
+ entry.sharedTags.length === 0 && entry.sharedWords.length === 0 && entry.sameType ? '同类型' : '',
385
+ ].filter(Boolean).join(' · ') || '弱信号',
386
+ })),
387
+ })
388
+ }
389
+ return out
390
+ .map((entry) => ({
391
+ ...entry,
392
+ candidates: entry.candidates.filter((candidate) => strengths.includes(candidate.strength)),
393
+ }))
394
+ .filter((entry) => entry.candidates.length > 0)
395
+ }