dsh-plugin-memory 0.6.0 → 0.7.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.
@@ -22,10 +22,37 @@
22
22
  import { randomUUID } from 'node:crypto'
23
23
  import { existsSync, statSync } from 'node:fs'
24
24
  import { join } from 'node:path'
25
+ import { planIndex } from './index-page.js'
25
26
 
26
27
  /** A digest must touch these files; their mtime is the freshness signal. */
27
28
  export const DIGEST_MARKER_FILES = ['log.md', 'index.md']
28
29
 
30
+ /**
31
+ * One line telling the agent how far the routing table has drifted, or '' when
32
+ * it is in sync. Runs the same planner as `dsh-memory index --check`, so the
33
+ * reminder and the CLI can never disagree about what "drifted" means.
34
+ *
35
+ * Never throws: a broken or unreadable store degrades to "no hint", because a
36
+ * reminder must still be delivered.
37
+ *
38
+ * @param {string} memoryDir absolute path of the memory store
39
+ * @returns {string} hint sentence, or ''
40
+ */
41
+ export function buildIndexDriftHint(memoryDir) {
42
+ try {
43
+ const plan = planIndex(memoryDir)
44
+ const stale = plan.lines.filter((line) => line.changed).length
45
+ const parts = []
46
+ if (stale > 0) parts.push(`${stale} 行与页面不一致(\`dsh-memory index --write\` 可修)`)
47
+ if (plan.missing.length > 0) parts.push(`${plan.missing.length} 个新页面未收录(分节与顺序需你自己决定)`)
48
+ if (plan.removed.length > 0) parts.push(`${plan.removed.length} 个索引链接已失效(决定是否删行)`)
49
+ if (parts.length === 0) return ''
50
+ return `另外,记忆 index 有漂移:${parts.join(';')}。`
51
+ } catch {
52
+ return ''
53
+ }
54
+ }
55
+
29
56
  /**
30
57
  * Latest mtime (ms epoch) across the digest marker files.
31
58
  * @param {string} memoryDir
@@ -49,9 +76,12 @@ export function lastStoreWriteMs(memoryDir) {
49
76
  * Build the nudge message in the exact shape `dsh-agent-loop` expects for
50
77
  * `followup()` (role 'user', content array, plugin source).
51
78
  * @param {number} staleMinutes how long the store has been unwritten
79
+ * @param {{ indexHint?: string }} [options] optional routing-table drift line,
80
+ * rendered on its own so the message stays a checklist, not a paragraph
52
81
  * @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin', plugin:string} }}
53
82
  */
54
- export function buildDigestNudgeMessage(staleMinutes) {
83
+ export function buildDigestNudgeMessage(staleMinutes, options = {}) {
84
+ const indexHint = typeof options.indexHint === 'string' ? options.indexHint.trim() : ''
55
85
  return {
56
86
  id: `memory-digest-${randomUUID()}`,
57
87
  role: 'user',
@@ -61,6 +91,7 @@ export function buildDigestNudgeMessage(staleMinutes) {
61
91
  `【记忆 digest 提醒】距上次记忆写入已超过 ${staleMinutes} 分钟。`,
62
92
  '请现在执行 remember 沉淀:把本次会话值得持久化的关键事实、偏好、决策写回记忆库(更新对应页面与 index.md,并追加 log.md 条目)。',
63
93
  '若本会话确实没有值得持久化的内容,也在 log.md 记一条「## [日期] digest | 无新增」并说明原因——这同样会解除提醒。',
94
+ ...(indexHint.length > 0 ? [indexHint] : []),
64
95
  '完成后继续手头的事即可,不要开启新任务。',
65
96
  ].join('\n'),
66
97
  }],
@@ -143,9 +174,13 @@ export class DigestGuard {
143
174
  if (now - lastWrite < afterMs) return
144
175
 
145
176
  const staleMinutes = Math.max(1, Math.round((now - lastWrite) / 60000))
146
- this.agent.followup(buildDigestNudgeMessage(staleMinutes))
177
+ // Only computed once a reminder is actually being delivered: scanning the
178
+ // store on every idle turn would be pure overhead.
179
+ const indexHint = buildIndexDriftHint(this.getMemoryDir())
180
+ this.agent.followup(buildDigestNudgeMessage(staleMinutes, { indexHint }))
147
181
  this.lastNudgeAt = now
148
182
  this.nudges += 1
149
- this.logger?.info?.(`memory: digest nudge #${this.nudges} for agent "${this.agent.id}" (store idle ${staleMinutes}min)`)
183
+ this.logger?.info?.(`memory: digest nudge #${this.nudges} for agent "${this.agent.id}" `
184
+ + `(store idle ${staleMinutes}min${indexHint.length > 0 ? ', index drift reported' : ''})`)
150
185
  }
151
186
  }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Drag maths for the memory graph.
3
+ *
4
+ * Kept pure and dependency-free so it can be unit-tested in Node: the browser
5
+ * half cannot import local modules, and the drag behaviour is exactly the part
6
+ * that is impossible to verify by reading it.
7
+ *
8
+ * The model is deliberately simple — the dragged node follows the pointer, its
9
+ * direct neighbours lean toward it a little, everything else stays put. A full
10
+ * force simulation per frame would be O(n²) and stutter on large stores; this
11
+ * reads as "alive" while staying O(degree).
12
+ *
13
+ * @module dsh-plugin-memory/graph-drag
14
+ */
15
+
16
+ /**
17
+ * Clamp into `[min, max]`. `NaN` means "no usable input" and falls back to
18
+ * `min`; the infinities are real directions, so they clamp to the edge.
19
+ * @param {number} value @param {number} min @param {number} max
20
+ */
21
+ export function clampToBox(value, min, max) {
22
+ if (Number.isNaN(value)) return min
23
+ return Math.min(Math.max(value, min), max)
24
+ }
25
+
26
+ /**
27
+ * How far a neighbour leans toward the dragged node.
28
+ * @param {number} distance current distance between the two nodes
29
+ * @param {number} pull 0..1 strength (scaled down as the drag gets far away)
30
+ * @param {number} [strength] global multiplier
31
+ * @returns {number} offset in px, along the drag direction
32
+ */
33
+ export function neighbourLean(distance, pull, strength = 6) {
34
+ const d = Number.isFinite(distance) ? Math.max(1, distance) : 1
35
+ const p = Number.isFinite(pull) ? Math.min(Math.max(pull, 0), 1) : 0
36
+ return (p * strength * 12) / (12 + d)
37
+ }
38
+
39
+ /**
40
+ * Positions for one drag frame.
41
+ *
42
+ * @param {Map<string, {x: number, y: number}> | Record<string, {x: number, y: number}>} positions base layout
43
+ * @param {string} draggedId node under the pointer
44
+ * @param {{x: number, y: number}} target pointer position
45
+ * @param {Array<{source: string, target: string}>} edges
46
+ * @param {{width?: number, height?: number, minPull?: number, strength?: number}} [options]
47
+ * @returns {Map<string, {x: number, y: number}>} new positions (input untouched)
48
+ */
49
+ export function applyDrag(positions, draggedId, target, edges, options = {}) {
50
+ const width = options.width ?? 560
51
+ const height = options.height ?? 340
52
+ const minPull = options.minPull ?? 0.3
53
+ const strength = options.strength ?? 6
54
+ const current = positions instanceof Map ? positions : new Map(Object.entries(positions ?? {}))
55
+ const at = (id) => current.get(id)
56
+ const start = at(draggedId)
57
+ const next = new Map(current)
58
+
59
+ if (start === undefined) return next
60
+
61
+ const x = clampToBox(target?.x, 0, width)
62
+ const y = clampToBox(target?.y, 0, height)
63
+ next.set(draggedId, { x, y })
64
+
65
+ // Neighbour set in one pass over the edges.
66
+ const neighbours = new Set()
67
+ for (const edge of edges ?? []) {
68
+ if (edge?.source === draggedId) neighbours.add(edge.target)
69
+ else if (edge?.target === draggedId) neighbours.add(edge.source)
70
+ }
71
+
72
+ const dx = x - start.x
73
+ const dy = y - start.y
74
+ const distance = Math.max(1, Math.hypot(dx, dy))
75
+ const ux = dx / distance
76
+ const uy = dy / distance
77
+ const pull = Math.max(minPull, Math.min(1, 1 / (1 + distance / 80)))
78
+
79
+ for (const id of neighbours) {
80
+ const base = at(id)
81
+ if (base === undefined) continue
82
+ const lean = neighbourLean(distance, pull, strength)
83
+ next.set(id, {
84
+ x: clampToBox(base.x + ux * lean, 0, width),
85
+ y: clampToBox(base.y + uy * lean, 0, height),
86
+ })
87
+ }
88
+ return next
89
+ }
90
+
91
+ /**
92
+ * Positions after releasing, i.e. the untouched base layout — the client pairs
93
+ * this with a CSS transition so nodes glide back instead of snapping.
94
+ *
95
+ * @param {Map<string, {x: number, y: number}> | Record<string, {x: number, y: number}>} base
96
+ * @returns {Map<string, {x: number, y: number}>}
97
+ */
98
+ export function releasePositions(base) {
99
+ return base instanceof Map ? new Map(base) : new Map(Object.entries(base ?? {}))
100
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Deterministic force-directed layout for the memory graph.
3
+ *
4
+ * Split out of the browser half so the maths can be unit-tested in Node and
5
+ * reused by the standalone report/preview without duplicating it. No
6
+ * randomness, no dependency: same input, same coordinates, every time.
7
+ *
8
+ * @module dsh-plugin-memory/graph-layout
9
+ */
10
+
11
+ /** Canvas the renderer draws into. Shared so the panel and any static report
12
+ * (or preview) agree on the picture's proportions. */
13
+ export const GRAPH_CANVAS = { width: 560, height: 340 }
14
+
15
+ /** Colour per memory type, shared by the SVG renderer and any static report. */
16
+ export const TYPE_COLORS = {
17
+ project: '#4c8bf5',
18
+ skill: '#8b7bf5',
19
+ decision: '#f5a623',
20
+ concept: '#30a46c',
21
+ user: '#e5484d',
22
+ 'user-preference': '#e5484d',
23
+ identity: '#e0712f',
24
+ fact: '#8b8f96',
25
+ meta: '#5b6068',
26
+ unknown: '#8b8f96',
27
+ }
28
+
29
+ /** @param {string} type */
30
+ export function typeColor(type) {
31
+ return TYPE_COLORS[type] ?? TYPE_COLORS.unknown
32
+ }
33
+
34
+ /**
35
+ * Place nodes inside a width x height box.
36
+ *
37
+ * @param {Array<{ id: string, degree?: number, hub?: boolean }>} nodes
38
+ * @param {Array<{ source: string, target: string, kind?: string }>} edges
39
+ * @param {{ width?: number, height?: number, iterations?: number }} [options]
40
+ * @returns {{ positions: Map<string, {x: number, y: number}>, radius: (id: string) => number }}
41
+ */
42
+ export function layoutGraph(nodes, edges, options = {}) {
43
+ const width = options.width ?? 560
44
+ const height = options.height ?? 340
45
+ const iterations = options.iterations ?? 220
46
+ const positions = new Map()
47
+ if (nodes.length === 0) {
48
+ return { positions, radius: () => 5 }
49
+ }
50
+
51
+ const cx = width / 2
52
+ const cy = height / 2
53
+ nodes.forEach((node, index) => {
54
+ const angle = (index / nodes.length) * Math.PI * 2
55
+ positions.set(node.id, { x: cx + Math.cos(angle) * 110, y: cy + Math.sin(angle) * 80 })
56
+ })
57
+
58
+ const degrees = new Map(nodes.map((node) => [node.id, node.degree ?? 0]))
59
+ const radius = (id) => 4.5 + Math.min(7.5, Math.sqrt(degrees.get(id) ?? 0) * 2.4)
60
+ const springs = []
61
+ for (const edge of edges) {
62
+ if (!positions.has(edge.source) || !positions.has(edge.target)) continue
63
+ springs.push({ a: edge.source, b: edge.target, w: edge.kind === 'link' ? 1.6 : 0.5 })
64
+ }
65
+
66
+ for (let iter = 0; iter < iterations; iter += 1) {
67
+ const cool = 1 - iter / (iterations * 1.18)
68
+
69
+ // pairwise repulsion
70
+ for (let i = 0; i < nodes.length; i += 1) {
71
+ const pi = positions.get(nodes[i].id)
72
+ for (let j = i + 1; j < nodes.length; j += 1) {
73
+ const pj = positions.get(nodes[j].id)
74
+ let dx = pi.x - pj.x
75
+ let dy = pi.y - pj.y
76
+ let d2 = dx * dx + dy * dy
77
+ if (d2 < 1) {
78
+ // Coincident nodes: nudge them apart deterministically.
79
+ dx = (i - j) * 0.7 + 0.3
80
+ dy = 0.4 * (j - i) + 0.2
81
+ d2 = dx * dx + dy * dy
82
+ }
83
+ const d = Math.sqrt(d2)
84
+ const push = (46 * cool) / d2
85
+ const ux = (dx / d) * push
86
+ const uy = (dy / d) * push
87
+ pi.x += ux
88
+ pi.y += uy
89
+ pj.x -= ux
90
+ pj.y -= uy
91
+ }
92
+ }
93
+
94
+ // spring attraction along edges
95
+ for (const spring of springs) {
96
+ const pa = positions.get(spring.a)
97
+ const pb = positions.get(spring.b)
98
+ const dx = pb.x - pa.x
99
+ const dy = pb.y - pa.y
100
+ const d = Math.max(1, Math.sqrt(dx * dx + dy * dy))
101
+ const pull = (d - 78) * 0.016 * spring.w * cool
102
+ const ux = (dx / d) * pull
103
+ const uy = (dy / d) * pull
104
+ pa.x += ux
105
+ pa.y += uy
106
+ pb.x -= ux
107
+ pb.y -= uy
108
+ }
109
+
110
+ // centring, with hubs pulled a little harder so they read as hubs
111
+ for (const node of nodes) {
112
+ const p = positions.get(node.id)
113
+ const strength = node.hub ? 0.022 : 0.0035
114
+ p.x += (cx - p.x) * strength * cool
115
+ p.y += (cy - p.y) * strength * cool
116
+ }
117
+ }
118
+
119
+ // normalise into the box, preserving aspect ratio
120
+ const pad = 30
121
+ const xs = [...positions.values()].map((p) => p.x)
122
+ const ys = [...positions.values()].map((p) => p.y)
123
+ const minX = Math.min(...xs)
124
+ const maxX = Math.max(...xs)
125
+ const minY = Math.min(...ys)
126
+ const maxY = Math.max(...ys)
127
+ const scale = Math.min(
128
+ (width - pad * 2) / Math.max(1, maxX - minX),
129
+ (height - pad * 2) / Math.max(1, maxY - minY),
130
+ )
131
+ for (const p of positions.values()) {
132
+ p.x = pad + (p.x - minX) * scale
133
+ p.y = pad + (p.y - minY) * scale
134
+ }
135
+
136
+ return { positions, radius }
137
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * View maths for the memory graph: wheel zoom and canvas panning.
3
+ *
4
+ * Pure and dependency-free, for the same reason as `graph-drag`: the browser
5
+ * half cannot import local modules, so the maths is mirrored there and a test
6
+ * asserts the two agree. Zoom-about-a-point is exactly the kind of arithmetic
7
+ * that looks right and drifts under the cursor.
8
+ *
9
+ * @module dsh-plugin-memory/graph-view
10
+ */
11
+
12
+ /** @type {{x: number, y: number, w: number, h: number}} */
13
+ export const DEFAULT_VIEW = { x: 0, y: 0, w: 560, h: 340 }
14
+
15
+ /**
16
+ * Viewport width is expressed as a fraction of the base width:
17
+ * `minScale` = tightest zoom (2.5x in), `maxScale` = widest (0.4x out).
18
+ */
19
+ export const MIN_VIEW_SCALE = 0.4
20
+ export const MAX_VIEW_SCALE = 2.5
21
+
22
+ /** @param {{x: number, y: number, w: number, h: number}} view */
23
+ export function isZoomed(view, base = DEFAULT_VIEW) {
24
+ return view.w < base.w - 1 || Math.abs(view.x - base.x) > 1 || Math.abs(view.y - base.y) > 1
25
+ }
26
+
27
+ /**
28
+ * Zoom about a graph-space point, keeping that point under the cursor.
29
+ *
30
+ * @param {{x: number, y: number, w: number, h: number}} view current view
31
+ * @param {number} fx focus x in graph coordinates
32
+ * @param {number} fy focus y in graph coordinates
33
+ * @param {number} factor >1 zooms out, <1 zooms in
34
+ * @param {{width?: number, height?: number, minScale?: number, maxScale?: number}} [options]
35
+ * @returns {{x: number, y: number, w: number, h: number}} next view
36
+ */
37
+ export function zoomAt(view, fx, fy, factor, options = {}) {
38
+ const width = options.width ?? DEFAULT_VIEW.w
39
+ const height = options.height ?? DEFAULT_VIEW.h
40
+ const minScale = options.minScale ?? MIN_VIEW_SCALE
41
+ const maxScale = options.maxScale ?? MAX_VIEW_SCALE
42
+ const safeFactor = Number.isFinite(factor) && factor > 0 ? factor : 1
43
+ const nextW = Math.min(width * maxScale, Math.max(width * minScale, view.w * safeFactor))
44
+ const k = nextW / view.w
45
+ return {
46
+ x: fx - (fx - view.x) * k,
47
+ y: fy - (fy - view.y) * k,
48
+ w: nextW,
49
+ h: height * (nextW / width),
50
+ }
51
+ }
52
+
53
+ /** @param {{width?: number, height?: number}} [options] */
54
+ export function resetView(options = {}) {
55
+ return {
56
+ x: 0,
57
+ y: 0,
58
+ w: options.width ?? DEFAULT_VIEW.w,
59
+ h: options.height ?? DEFAULT_VIEW.h,
60
+ }
61
+ }
62
+
63
+ /**
64
+ * One pan step: move the view by the pointer delta, converted from screen
65
+ * pixels to graph units.
66
+ *
67
+ * @param {{x: number, y: number, w: number, h: number}} start view when the drag began
68
+ * @param {number} dxPx pointer delta in screen pixels
69
+ * @param {number} dyPx pointer delta in screen pixels
70
+ * @param {{scaleX: number, scaleY: number}} scale graph-units per screen pixel
71
+ * @returns {{x: number, y: number, w: number, h: number}}
72
+ */
73
+ export function panBy(start, dxPx, dyPx, scale) {
74
+ return {
75
+ x: start.x - (Number.isFinite(dxPx) ? dxPx : 0) * (scale?.scaleX ?? 1),
76
+ y: start.y - (Number.isFinite(dyPx) ? dyPx : 0) * (scale?.scaleY ?? 1),
77
+ w: start.w,
78
+ h: start.h,
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Screen point -> graph point for the current view. Node dragging needs this,
84
+ * otherwise a drag lands somewhere else as soon as the user zooms.
85
+ *
86
+ * @param {{x: number, y: number, w: number, h: number}} view
87
+ * @param {{left: number, top: number, width: number, height: number}} rect element box
88
+ * @param {number} clientX
89
+ * @param {number} clientY
90
+ * @returns {{x: number, y: number}}
91
+ */
92
+ export function toGraphPoint(view, rect, clientX, clientY) {
93
+ if (rect === undefined || rect.width === 0 || rect.height === 0) return { x: clientX, y: clientY }
94
+ return {
95
+ x: view.x + ((clientX - rect.left) / rect.width) * view.w,
96
+ y: view.y + ((clientY - rect.top) / rect.height) * view.h,
97
+ }
98
+ }
package/lib/graph.js ADDED
@@ -0,0 +1,249 @@
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
+ /** Stable-ish id for a node: the store-relative path. */
43
+ const nodeId = (path) => path.replace(/^\.\//, '')
44
+
45
+ /**
46
+ * Resolve a markdown link target to a node id. Links in a memory page are
47
+ * usually *relative to that page* (`../skills/foo.md`), so anchor them before
48
+ * normalising — otherwise every cross-folder link silently disappears.
49
+ * @param {string} fromId the linking page's id
50
+ * @param {string} target the raw href
51
+ * @returns {string} candidate node id
52
+ */
53
+ function resolveLink(fromId, target) {
54
+ const clean = target.trim().replace(/^<|>$/g, '')
55
+ if (clean.startsWith('/')) return nodeId(clean)
56
+ return normalize(join(dirname(fromId), clean)).split('\\').join('/')
57
+ }
58
+
59
+ /** Parse `tags: [a, b]` (frontmatter is flat in this store by convention). */
60
+ function parseTags(frontmatter) {
61
+ const raw = frontmatter.tags
62
+ if (typeof raw !== 'string') return []
63
+ const inner = /^\[(.*)\]$/.exec(raw.trim())
64
+ const body = inner ? inner[1] : raw
65
+ return body
66
+ .split(',')
67
+ .map((tag) => tag.trim().replace(/^#/, ''))
68
+ .filter((tag) => tag.length > 0)
69
+ }
70
+
71
+ /** The first sentence of the body, used as hover text when nothing else fits. */
72
+ function bodyPreview(text) {
73
+ const body = text.replace(/^---[\s\S]*?\n---\n?/, '')
74
+ for (const line of body.split('\n')) {
75
+ const clean = line.trim()
76
+ if (clean.length === 0 || clean.startsWith('#') || clean.startsWith('>')) continue
77
+ return clean.replace(/[*`[\]]/g, '').slice(0, 120)
78
+ }
79
+ return ''
80
+ }
81
+
82
+ /**
83
+ * Build the memory graph.
84
+ *
85
+ * @param {string} memoryDir absolute path of the memory store
86
+ * @param {{ includeMeta?: boolean, includeTypeEdges?: boolean, stopTags?: Set<string> }} [options]
87
+ * @returns {{
88
+ * nodes: Array<{ id: string, label: string, kind: string, type: string, tags: string[],
89
+ * degree: number, salience?: number, lastAccess?: string, preview: string, hub: boolean }>,
90
+ * edges: Array<{ source: string, target: string, kind: string, weight: number, label?: string }>,
91
+ * stats: { pages: number, links: number, tagEdges: number, typeEdges: number, isolated: string[] },
92
+ * }}
93
+ */
94
+ export function buildMemoryGraph(memoryDir, options = {}) {
95
+ const stopTags = options.stopTags ?? STOP_TAGS
96
+ const paths = listPagePaths(memoryDir)
97
+ const nodes = []
98
+ const edges = []
99
+ const byId = new Map()
100
+
101
+ for (const rel of paths) {
102
+ const id = nodeId(rel)
103
+ let text = ''
104
+ try {
105
+ text = readFileSync(join(memoryDir, rel), 'utf8')
106
+ } catch {
107
+ continue
108
+ }
109
+ const fm = parseFrontmatter(text)
110
+ const salience = Number(fm.salience)
111
+ const node = {
112
+ id,
113
+ label: fm.title || basename(rel, '.md'),
114
+ kind: 'page',
115
+ type: fm.type || 'unknown',
116
+ tags: parseTags(fm),
117
+ salience: [1, 2, 3].includes(salience) ? salience : undefined,
118
+ lastAccess: typeof fm.last_access === 'string' ? fm.last_access : undefined,
119
+ preview: bodyPreview(text),
120
+ degree: 0,
121
+ hub: false,
122
+ }
123
+ nodes.push(node)
124
+ byId.set(id, node)
125
+ }
126
+
127
+ if (options.includeMeta !== false) {
128
+ for (const name of META_FILES) {
129
+ if (!existsSync(join(memoryDir, name))) continue
130
+ const node = {
131
+ id: name,
132
+ label: name.replace(/\.md$/, ''),
133
+ kind: 'meta',
134
+ type: 'meta',
135
+ tags: [],
136
+ preview: '',
137
+ degree: 0,
138
+ hub: true,
139
+ }
140
+ nodes.push(node)
141
+ byId.set(name, node)
142
+ }
143
+ }
144
+
145
+ const seen = new Set()
146
+ const addEdge = (source, target, kind, weight, label) => {
147
+ if (!byId.has(source) || !byId.has(target) || source === target) return
148
+ const [a, b] = source < target ? [source, target] : [target, source]
149
+ const key = `${kind}:${a}|${b}`
150
+ if (seen.has(key)) return
151
+ seen.add(key)
152
+ edges.push({ source: a, target: b, kind, weight, ...(label ? { label } : {}) })
153
+ byId.get(a).degree += 1
154
+ byId.get(b).degree += 1
155
+ }
156
+
157
+ // 1. explicit links, from every node — root meta files included. index.md is
158
+ // the routing table: 33 links to every page in the store. A previous
159
+ // version skipped meta files entirely, which left the index node floating
160
+ // alone in the picture while it is in fact the busiest node in the store.
161
+ let links = 0
162
+ let indexLinks = 0
163
+ for (const node of [...nodes]) {
164
+ let text = ''
165
+ try {
166
+ text = readFileSync(join(memoryDir, node.id), 'utf8')
167
+ } catch {
168
+ continue
169
+ }
170
+ for (const match of text.matchAll(/\]\(([^)]+\.md)\)/g)) {
171
+ const target = resolveLink(node.id, match[1])
172
+ if (target === node.id || !byId.has(target)) continue
173
+ // The routing table's own rows are their own kind of relationship: an
174
+ // index→page edge means "listed here", not "these two belong together".
175
+ const fromMeta = node.kind === 'meta'
176
+ addEdge(node.id, target, fromMeta ? 'index' : 'link', fromMeta ? 0.4 : 1)
177
+ if (fromMeta) indexLinks += 1
178
+ else links += 1
179
+ }
180
+ }
181
+
182
+ // 2. shared tags — one edge per tag, labelled with it, weight = how many pages
183
+ const tagGroups = new Map()
184
+ for (const node of nodes) {
185
+ if (node.kind !== 'page') continue
186
+ for (const tag of node.tags) {
187
+ if (stopTags.has(tag)) continue
188
+ if (!tagGroups.has(tag)) tagGroups.set(tag, [])
189
+ tagGroups.get(tag).push(node.id)
190
+ }
191
+ }
192
+ let tagEdges = 0
193
+ for (const [tag, members] of tagGroups) {
194
+ if (members.length < 2) continue
195
+ // Keep dense tags readable: a tag shared by 20 pages becomes a chain through
196
+ // the first member rather than 190 edges.
197
+ const anchor = members[0]
198
+ for (const member of members.slice(1)) {
199
+ addEdge(anchor, member, 'tag', 1, tag)
200
+ tagEdges += 1
201
+ }
202
+ }
203
+
204
+ // 3. same-type edges (off by default: weak, and can overwhelm the picture)
205
+ let typeEdges = 0
206
+ if (options.includeTypeEdges) {
207
+ const typeGroups = new Map()
208
+ for (const node of nodes) {
209
+ if (node.kind !== 'page') continue
210
+ const key = node.type
211
+ if (!typeGroups.has(key)) typeGroups.set(key, [])
212
+ typeGroups.get(key).push(node.id)
213
+ }
214
+ for (const [type, members] of typeGroups) {
215
+ for (let i = 1; i < members.length; i += 1) {
216
+ addEdge(members[i - 1], members[i], 'type', 0.5, type)
217
+ typeEdges += 1
218
+ }
219
+ }
220
+ }
221
+
222
+ // Layout is computed here (once, server-side) rather than in the browser half:
223
+ // the client bundle cannot import local modules, and shipping coordinates keeps
224
+ // both sides from drifting apart.
225
+ const { positions, radius } = layoutGraph(nodes, edges)
226
+ for (const node of nodes) {
227
+ const p = positions.get(node.id)
228
+ if (p !== undefined) {
229
+ node.x = Math.round(p.x * 10) / 10
230
+ node.y = Math.round(p.y * 10) / 10
231
+ }
232
+ node.r = Math.round(radius(node.id) * 10) / 10 + (node.hub ? 4 : 0)
233
+ node.color = typeColor(node.type)
234
+ }
235
+
236
+ const isolated = nodes.filter((node) => node.degree === 0 && node.kind === 'page').map((node) => node.id)
237
+ return {
238
+ nodes,
239
+ edges,
240
+ stats: {
241
+ pages: nodes.filter((node) => node.kind === 'page').length,
242
+ links,
243
+ indexLinks,
244
+ tagEdges,
245
+ typeEdges,
246
+ isolated,
247
+ },
248
+ }
249
+ }