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.
package/lib/client.js CHANGED
@@ -15,6 +15,10 @@ window.__ModuleLoader__.load({
15
15
 
16
16
  const React = react
17
17
  const CONFIG_URL = '/api/memory/config'
18
+ const INSIGHTS_URL = '/api/memory/insights'
19
+ const GRAPH_URL = '/api/memory/graph'
20
+ /** Poll while the panel is open, so memory edits show up without a reload. */
21
+ const GRAPH_REFRESH_MS = 25000
18
22
 
19
23
  const rowStyle = {
20
24
  display: 'flex',
@@ -91,7 +95,176 @@ window.__ModuleLoader__.load({
91
95
  }
92
96
 
93
97
  function MemorySection() {
94
- return React.createElement(SectionBoundary, null, React.createElement(MemoryForm))
98
+ // `gen` bumps after every successful config write so the read-only health
99
+ // card re-mounts and re-reads the store (e.g. after a memoryDir switch).
100
+ const [gen, setGen] = React.useState(0)
101
+ return React.createElement(SectionBoundary, null,
102
+ React.createElement(MemoryForm, { onSaved: () => setGen((value) => value + 1) }),
103
+ React.createElement(SectionBoundary, { key: gen },
104
+ React.createElement(InsightsCard),
105
+ ),
106
+ React.createElement(SectionBoundary, { key: `graph-${gen}` },
107
+ React.createElement(GraphCard),
108
+ ),
109
+ )
110
+ }
111
+
112
+ // ---------------- 记忆健康看板 ----------------
113
+
114
+ const cardStyle = {
115
+ margin: '4px 16px 16px',
116
+ padding: '14px 16px',
117
+ border: '1px solid var(--dsw-alias-border-l1, rgba(128,128,128,0.2))',
118
+ borderRadius: '10px',
119
+ background: 'var(--dsw-alias-bg-layer-2, rgba(128,128,128,0.05))',
120
+ }
121
+ const cardTitleStyle = { fontSize: '13px', fontWeight: '600', marginBottom: '2px' }
122
+ const cardSubStyle = { fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #999)', marginBottom: '12px' }
123
+ const metricRowStyle = { display: 'flex', gap: '8px', marginBottom: '12px', flexWrap: 'wrap' }
124
+ const metricBoxStyle = {
125
+ flex: '1 1 72px',
126
+ minWidth: '72px',
127
+ padding: '8px 10px',
128
+ borderRadius: '8px',
129
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
130
+ border: '1px solid var(--dsw-alias-border-l1, rgba(128,128,128,0.15))',
131
+ }
132
+ const metricValueStyle = { fontSize: '18px', lineHeight: '24px', fontWeight: '600' }
133
+ const metricLabelStyle = { fontSize: '11px', lineHeight: '16px', color: 'var(--dsw-alias-label-secondary, #999)' }
134
+ const sectionLabelStyle = { fontSize: '12px', fontWeight: '600', margin: '12px 0 6px', color: 'var(--dsw-alias-label-secondary, #999)' }
135
+
136
+ const scoreColor = (score) =>
137
+ score >= 85 ? 'var(--dsw-alias-state-success-primary, #30a46c)'
138
+ : score >= 60 ? 'var(--dsw-alias-state-warning-primary, #f5a623)'
139
+ : 'var(--dsw-alias-state-error-primary, #e5484d)'
140
+ const checkColor = (ok) =>
141
+ ok ? 'var(--dsw-alias-state-success-primary, #30a46c)' : 'var(--dsw-alias-state-warning-primary, #f5a623)'
142
+ const barColor = (key) =>
143
+ key === 'stale' ? 'var(--dsw-alias-state-error-primary, #e5484d)'
144
+ : key === 'quarter' ? 'var(--dsw-alias-state-warning-primary, #f5a623)'
145
+ : 'var(--dsw-alias-brand-primary, #4c8bf5)'
146
+
147
+ /** 一行标签 + 细横条 + 计数。 */
148
+ function Bar({ label, count, total, color }) {
149
+ const ratio = total > 0 ? Math.max(0, Math.min(1, count / total)) : 0
150
+ return React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '5px' } },
151
+ React.createElement('div', { style: { width: '68px', flexShrink: 0, fontSize: '12px', color: 'var(--dsw-alias-label-secondary, #999)' } }, label),
152
+ React.createElement('div', { style: { flex: 1, height: '6px', borderRadius: '3px', background: 'var(--dsw-alias-border-l1, rgba(128,128,128,0.18))', overflow: 'hidden' } },
153
+ React.createElement('div', { style: { width: `${Math.round(ratio * 100)}%`, height: '100%', borderRadius: '3px', background: color } }),
154
+ ),
155
+ React.createElement('div', { style: { width: '22px', flexShrink: 0, textAlign: 'right', fontSize: '12px', fontVariantNumeric: 'tabular-nums' } }, String(count)),
156
+ )
157
+ }
158
+
159
+ /** 记忆健康看板:只读,数据来自 /api/memory/insights,打开面板时拉取一次。 */
160
+ function InsightsCard() {
161
+ const [data, setData] = React.useState(undefined)
162
+ const [status, setStatus] = React.useState('loading')
163
+
164
+ React.useEffect(() => {
165
+ let alive = true
166
+ fetch(INSIGHTS_URL)
167
+ .then(async (response) => {
168
+ if (!response.ok) throw new Error(`GET ${response.status}`)
169
+ return response.json()
170
+ })
171
+ .then((value) => {
172
+ if (!alive) return
173
+ setData(value)
174
+ setStatus('ready')
175
+ })
176
+ .catch(() => {
177
+ if (alive) setStatus('failed')
178
+ })
179
+ return () => {
180
+ alive = false
181
+ }
182
+ }, [])
183
+
184
+ if (status === 'loading') {
185
+ return React.createElement('div', { style: { ...cardStyle, fontSize: '12px', color: 'var(--dsw-alias-label-secondary, #888)' } }, '正在统计记忆库…')
186
+ }
187
+ // 看板是附加信息:拿不到就静默隐藏,绝不影响设置页可用。
188
+ if (status === 'failed' || data === undefined) return null
189
+
190
+ const overview = data.overview ?? {}
191
+ const pages = overview.pages ?? 0
192
+ const health = data.health ?? { score: 0, checks: [] }
193
+ const buckets = (data.freshness && data.freshness.buckets) || []
194
+ const stale = data.stalePages ?? []
195
+ const recent = data.recent ?? []
196
+ const formatDays = (days) => (days === null || days === undefined ? '从未戳记' : `${days} 天未访问`)
197
+
198
+ return React.createElement('div', { style: cardStyle },
199
+ React.createElement('div', { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px' } },
200
+ React.createElement('div', { style: cardTitleStyle }, '记忆健康'),
201
+ React.createElement('div', { style: { fontSize: '20px', lineHeight: '26px', fontWeight: '700', color: scoreColor(health.score) } },
202
+ `${health.score}`,
203
+ React.createElement('span', { style: { fontSize: '11px', fontWeight: '400', color: 'var(--dsw-alias-label-secondary, #999)' } }, ' / 100'),
204
+ ),
205
+ ),
206
+ React.createElement('div', { style: cardSubStyle }, '只读统计:页数、访问新鲜度、体检结论与最近动态。'),
207
+
208
+ React.createElement('div', { style: metricRowStyle },
209
+ React.createElement('div', { style: metricBoxStyle },
210
+ React.createElement('div', { style: metricValueStyle }, String(pages)),
211
+ React.createElement('div', { style: metricLabelStyle }, '记忆页'),
212
+ ),
213
+ React.createElement('div', { style: metricBoxStyle },
214
+ React.createElement('div', { style: metricValueStyle }, String(overview.indexEntries ?? 0)),
215
+ React.createElement('div', { style: metricLabelStyle }, 'index 路由'),
216
+ ),
217
+ React.createElement('div', { style: metricBoxStyle },
218
+ React.createElement('div', { style: metricValueStyle }, `~${overview.chars ?? 0}`),
219
+ React.createElement('div', { style: metricLabelStyle }, '记忆字数'),
220
+ ),
221
+ ),
222
+
223
+ React.createElement('div', { style: sectionLabelStyle }, '访问新鲜度'),
224
+ ...buckets.map((bucket) =>
225
+ React.createElement(Bar, {
226
+ key: bucket.key,
227
+ label: bucket.label,
228
+ count: bucket.count,
229
+ total: pages,
230
+ color: barColor(bucket.key),
231
+ })),
232
+ (data.freshness && data.freshness.never > 0)
233
+ ? React.createElement(Bar, { label: '从未', count: data.freshness.never, total: pages, color: 'var(--dsw-alias-label-secondary, #888)' })
234
+ : null,
235
+
236
+ React.createElement('div', { style: sectionLabelStyle }, '体检'),
237
+ ...health.checks.map((check) =>
238
+ React.createElement('div', { key: check.id, style: { display: 'flex', gap: '8px', alignItems: 'baseline', marginBottom: '4px' } },
239
+ React.createElement('span', { style: { color: checkColor(check.ok), fontSize: '12px', width: '14px', flexShrink: 0 } }, check.ok ? '✓' : '!'),
240
+ React.createElement('span', { style: { fontSize: '12px', lineHeight: '18px' } },
241
+ check.label,
242
+ React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary, #999)' } }, ` · ${check.detail}`),
243
+ ),
244
+ )),
245
+
246
+ stale.length > 0
247
+ ? React.createElement('div', null,
248
+ React.createElement('div', { style: sectionLabelStyle }, `陈旧候选(前 ${stale.length})`),
249
+ ...stale.map((page) =>
250
+ React.createElement('div', { key: page.path, style: { fontSize: '12px', lineHeight: '18px', display: 'flex', justifyContent: 'space-between', gap: '8px', marginBottom: '3px' } },
251
+ React.createElement('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, page.title || page.path),
252
+ React.createElement('span', { style: { color: 'var(--dsw-alias-state-warning-primary, #f5a623)', flexShrink: 0, fontVariantNumeric: 'tabular-nums' } }, formatDays(page.daysSinceAccess)),
253
+ )),
254
+ )
255
+ : null,
256
+
257
+ recent.length > 0
258
+ ? React.createElement('div', null,
259
+ React.createElement('div', { style: sectionLabelStyle }, '最近动态'),
260
+ ...recent.map((line, index) =>
261
+ React.createElement('div', {
262
+ key: `${index}-${line}`,
263
+ style: { fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #999)', marginBottom: '3px' },
264
+ }, `· ${line}`)),
265
+ )
266
+ : null,
267
+ )
95
268
  }
96
269
 
97
270
  /** 目录输入:草稿态编辑,blur / Enter 才写回,避免每次按键触发 Host 重排。 */
@@ -144,7 +317,7 @@ window.__ModuleLoader__.load({
144
317
  })
145
318
  }
146
319
 
147
- function MemoryForm() {
320
+ function MemoryForm({ onSaved }) {
148
321
  const [config, setConfig] = React.useState(undefined)
149
322
  const [status, setStatus] = React.useState('loading')
150
323
  const [error, setError] = React.useState(undefined)
@@ -184,6 +357,7 @@ window.__ModuleLoader__.load({
184
357
  const body = await response.json().catch(() => ({}))
185
358
  if (!response.ok) throw new Error(body.error ?? `POST ${response.status}`)
186
359
  setConfig(body)
360
+ onSaved?.()
187
361
  })
188
362
  .catch((err) => {
189
363
  setError(err instanceof Error ? err.message : String(err))
@@ -317,6 +491,453 @@ window.__ModuleLoader__.load({
317
491
  )
318
492
  }
319
493
 
494
+ // ---------------- 记忆图谱 ----------------
495
+ //
496
+ // index.md 渲染出的图是星形:它只说明"索引列了所有页",不说明"哪些记忆
497
+ // 属于一起"。这里改成画索引画不出来的关系:页间显式链接 + 共享 tag。
498
+
499
+ const GRAPH_W = 560
500
+ const GRAPH_H = 340
501
+
502
+ // Inlined from lib/graph-drag.js: the client bundle can only require platform
503
+ // seeds, so the drag maths lives here in a 12-line form. The canonical
504
+ // implementation (with its tests) is the module; this mirrors it.
505
+ const clampToBox = (value, min, max) => (Number.isNaN(value) ? min : Math.min(Math.max(value, min), max))
506
+ function applyDrag(base, draggedId, target, edges, options) {
507
+ const width = (options && options.width) || GRAPH_W
508
+ const height = (options && options.height) || GRAPH_H
509
+ const out = new Map(base)
510
+ const start = base.get(draggedId)
511
+ if (start === undefined) return out
512
+ const x = clampToBox(target?.x, 0, width)
513
+ const y = clampToBox(target?.y, 0, height)
514
+ out.set(draggedId, { x, y })
515
+ const dx = x - start.x
516
+ const dy = y - start.y
517
+ const distance = Math.max(1, Math.hypot(dx, dy))
518
+ const ux = dx / distance
519
+ const uy = dy / distance
520
+ const pull = Math.max(0.3, Math.min(1, 1 / (1 + distance / 80)))
521
+ const lean = (pull * 6 * 12) / (12 + distance)
522
+ const neighbours = new Set()
523
+ for (const edge of edges ?? []) {
524
+ if (edge?.source === draggedId) neighbours.add(edge.target)
525
+ else if (edge?.target === draggedId) neighbours.add(edge.source)
526
+ }
527
+ for (const id of neighbours) {
528
+ const base0 = base.get(id)
529
+ if (base0 === undefined) continue
530
+ out.set(id, {
531
+ x: clampToBox(base0.x + ux * lean, 0, width),
532
+ y: clampToBox(base0.y + uy * lean, 0, height),
533
+ })
534
+ }
535
+ return out
536
+ }
537
+ const releasePositions = (base) => new Map(base)
538
+
539
+ // Inlined from lib/graph-view.js for the same reason: the client bundle can
540
+ // only require platform seeds. A test asserts both copies agree.
541
+ const DEFAULT_VIEW = { x: 0, y: 0, w: GRAPH_W, h: GRAPH_H }
542
+ const MIN_VIEW_SCALE = 0.4
543
+ const MAX_VIEW_SCALE = 2.5
544
+ const isZoomedView = (v) => v.w < GRAPH_W - 1 || Math.abs(v.x) > 1 || Math.abs(v.y) > 1
545
+ function zoomAt(view, fx, fy, factor) {
546
+ const nextW = Math.min(GRAPH_W * MAX_VIEW_SCALE, Math.max(GRAPH_W * MIN_VIEW_SCALE, view.w * factor))
547
+ const k = nextW / view.w
548
+ return {
549
+ x: fx - (fx - view.x) * k,
550
+ y: fy - (fy - view.y) * k,
551
+ w: nextW,
552
+ h: GRAPH_H * (nextW / GRAPH_W),
553
+ }
554
+ }
555
+ const resetViewState = () => ({ x: 0, y: 0, w: GRAPH_W, h: GRAPH_H })
556
+ function panBy(start, dxPx, dyPx, scale) {
557
+ return {
558
+ x: start.x - dxPx * scale.scaleX,
559
+ y: start.y - dyPx * scale.scaleY,
560
+ w: start.w,
561
+ h: start.h,
562
+ }
563
+ }
564
+ function toGraphPointIn(view, rect, clientX, clientY) {
565
+ if (rect === undefined || rect.width === 0 || rect.height === 0) return { x: clientX, y: clientY }
566
+ return {
567
+ x: view.x + ((clientX - rect.left) / rect.width) * view.w,
568
+ y: view.y + ((clientY - rect.top) / rect.height) * view.h,
569
+ }
570
+ }
571
+
572
+ /** 图谱的过渡/入场样式:拖动时不要过渡,松手后要滑回去。 */
573
+ function ensureGraphStyles() {
574
+ if (typeof document === 'undefined' || document.getElementById('dsh-memory-graph-style') !== null) return
575
+ const style = document.createElement('style')
576
+ style.id = 'dsh-memory-graph-style'
577
+ style.textContent = [
578
+ '#dsh-memory-graph-style + * {}',
579
+ '.dsh-memory-graph-svg g { transition: transform .18s cubic-bezier(.2,.8,.2,1); }',
580
+ '.dsh-memory-graph-svg.anim-off g { transition: none; }',
581
+ '.dsh-memory-graph-svg.dragging g { transition: none; }',
582
+ '.dsh-memory-graph-svg.entering g { transform: scale(.08); opacity: 0; }',
583
+ '.dsh-memory-graph-svg.graph-drop g { transition: transform .32s cubic-bezier(.2,.9,.2,1.05); }',
584
+ '.dsh-memory-graph-svg circle, .dsh-memory-graph-svg text { transition: opacity .12s; }',
585
+ '.dsh-memory-graph-svg.hovering g:not(.lit) circle,' +
586
+ '.dsh-memory-graph-svg.hovering g:not(.lit) text { opacity: .18; }',
587
+ ].join('\n')
588
+ document.head.appendChild(style)
589
+ }
590
+
591
+ /**
592
+ * 图谱视图:拿到 nodes/edges 就画(纯渲染,无副作用)。拖动与悬停是它
593
+ * 自己维护的临时状态;`memo` 隔断父级重渲染带来的 hooks 调用。
594
+ */
595
+ const GraphView = React.memo(function GraphView({ graph, fetchedAt }) {
596
+ const [hover, setHover] = React.useState(undefined)
597
+ const [dragPositions, setDragPositions] = React.useState(undefined)
598
+ const [dragging, setDragging] = React.useState(false)
599
+ const [dropAnim, setDropAnim] = React.useState(false)
600
+ const svgRef = React.useRef(null)
601
+ const dragRef = React.useRef(undefined)
602
+ const [view, setView] = React.useState({ x: 0, y: 0, w: GRAPH_W, h: GRAPH_H })
603
+ const [zoomed, setZoomed] = React.useState(false)
604
+ const panRef = React.useRef(undefined)
605
+ const viewRef = React.useRef({ x: 0, y: 0, w: GRAPH_W, h: GRAPH_H })
606
+ const firstPaint = React.useRef(true)
607
+ React.useEffect(() => { viewRef.current = view }, [view])
608
+ const basePositions = React.useMemo(() => {
609
+ const map = new Map()
610
+ for (const node of graph.nodes ?? []) map.set(node.id, { x: node.x, y: node.y })
611
+ return map
612
+ }, [graph])
613
+
614
+ // Bloom in from the centre, once, unless reduced motion is asked. Graph
615
+ // refreshes must not replay it (memory edits can arrive every few seconds).
616
+ React.useEffect(() => {
617
+ const el = svgRef.current
618
+ if (el === null) return undefined
619
+ if (!firstPaint.current) return undefined
620
+ firstPaint.current = false
621
+ const reduced = typeof window !== 'undefined'
622
+ && typeof window.matchMedia === 'function'
623
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches
624
+ if (reduced) {
625
+ el.classList.remove('anim-off')
626
+ return undefined
627
+ }
628
+ el.classList.add('anim-off')
629
+ el.classList.add('entering')
630
+ const raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : (fn) => setTimeout(fn, 16)
631
+ raf(() => {
632
+ el.classList.remove('anim-off')
633
+ el.classList.remove('entering')
634
+ })
635
+ return () => { el.classList.remove('anim-off', 'entering') }
636
+ }, [graph])
637
+
638
+ const nodes = graph.nodes ?? []
639
+ const edges = graph.edges ?? []
640
+ const stats = graph.stats ?? {}
641
+ if (nodes.length === 0) return null
642
+
643
+ const byId = new Map(nodes.map((node) => [node.id, node]))
644
+ const neighbours = new Map()
645
+ for (const e of edges) {
646
+ if (!neighbours.has(e.source)) neighbours.set(e.source, new Set())
647
+ if (!neighbours.has(e.target)) neighbours.set(e.target, new Set())
648
+ neighbours.get(e.source).add(e.target)
649
+ neighbours.get(e.target).add(e.source)
650
+ }
651
+ const lit = (id) => hover === undefined || hover === id || (neighbours.get(hover)?.has(id) ?? false)
652
+ const litEdge = (e) => hover === undefined || e.source === hover || e.target === hover
653
+ const posOf = (node) => dragPositions?.get(node.id) ?? node
654
+
655
+ /** Pointer position in graph coordinates, honouring the current zoom. */
656
+ const toGraphPoint = (event) => {
657
+ const el = svgRef.current
658
+ const rect = el?.getBoundingClientRect?.()
659
+ if (rect === undefined || rect.width === 0 || rect.height === 0) {
660
+ return { x: event.clientX, y: event.clientY }
661
+ }
662
+ return toGraphPointIn(viewRef.current, rect, event.clientX, event.clientY)
663
+ }
664
+
665
+ /** Zoom about a graph point so it stays under the cursor. */
666
+ const applyView = (next) => {
667
+ viewRef.current = next
668
+ setView(next)
669
+ setZoomed(isZoomedView(next))
670
+ }
671
+ const zoomBy = (fx, fy, factor) => applyView(zoomAt(viewRef.current, fx, fy, factor))
672
+ const resetView = () => applyView(resetViewState())
673
+
674
+ // Wheel zoom is registered by hand instead of via onWheel so it can be
675
+ // non-passive: otherwise preventDefault is ignored and the settings page
676
+ // scrolls while the user is trying to zoom.
677
+ React.useEffect(() => {
678
+ const el = svgRef.current
679
+ if (el === null || typeof el.addEventListener !== 'function') return undefined
680
+ const onWheel = (event) => {
681
+ event.preventDefault()
682
+ const p = toGraphPointIn(viewRef.current, el.getBoundingClientRect(), event.clientX, event.clientY)
683
+ zoomBy(p.x, p.y, event.deltaY < 0 ? 1 / 1.15 : 1.15)
684
+ }
685
+ el.addEventListener('wheel', onWheel, { passive: false })
686
+ return () => el.removeEventListener('wheel', onWheel)
687
+ }, [])
688
+
689
+ /** Drag empty canvas to pan. */
690
+ const panStart = (event) => {
691
+ if (dragRef.current !== undefined) return
692
+ if (event.button !== undefined && event.button !== 0) return
693
+ const v = viewRef.current
694
+ const rect = event.currentTarget?.getBoundingClientRect?.()
695
+ if (rect === undefined) return
696
+ event.preventDefault?.()
697
+ panRef.current = {
698
+ clientX: event.clientX,
699
+ clientY: event.clientY,
700
+ view: v,
701
+ scaleX: v.w / rect.width,
702
+ scaleY: v.h / rect.height,
703
+ }
704
+ }
705
+ const panMove = (event) => {
706
+ const pan = panRef.current
707
+ if (pan === undefined) return
708
+ event.preventDefault?.()
709
+ applyView(panBy(pan.view, event.clientX - pan.clientX, event.clientY - pan.clientY,
710
+ { scaleX: pan.scaleX, scaleY: pan.scaleY }))
711
+ }
712
+ const panEnd = () => { panRef.current = undefined }
713
+
714
+ const endDrag = () => {
715
+ if (dragRef.current === undefined) return
716
+ dragRef.current = undefined
717
+ setDragging(false)
718
+ setDragPositions(undefined) // CSS transition glides everything back
719
+ setDropAnim(false)
720
+ }
721
+
722
+ const handlePointerDown = (event, node) => {
723
+ if (event.button !== undefined && event.button !== 0) return
724
+ event.preventDefault?.()
725
+ dragRef.current = { id: node.id, pointerId: event.pointerId }
726
+ try {
727
+ event.currentTarget?.setPointerCapture?.(event.pointerId)
728
+ } catch {
729
+ // Capture is an optimisation; without it the element's own
730
+ // pointermove events still drive the drag.
731
+ }
732
+ setDragging(true)
733
+ setDragPositions(applyDrag(basePositions, node.id, toGraphPoint(event), edges,
734
+ { width: GRAPH_W, height: GRAPH_H }))
735
+ }
736
+
737
+ const handlePointerMove = (event) => {
738
+ const drag = dragRef.current
739
+ if (drag === undefined) return
740
+ event.preventDefault?.()
741
+ setDragPositions(applyDrag(basePositions, drag.id, toGraphPoint(event), edges,
742
+ { width: GRAPH_W, height: GRAPH_H }))
743
+ }
744
+
745
+ const handlePointerUp = (event) => {
746
+ const drag = dragRef.current
747
+ if (drag === undefined) return
748
+ try {
749
+ event.currentTarget?.releasePointerCapture?.(drag.pointerId)
750
+ } catch {
751
+ // Already released, or never captured.
752
+ }
753
+ setDropAnim(true)
754
+ setTimeout(endDrag, 60)
755
+ }
756
+
757
+ /** One node = one <g>, so a drag transform moves dot and label together. */
758
+ const renderNode = (node) => {
759
+ const p = posOf(node)
760
+ const dx = p.x - node.x
761
+ const dy = p.y - node.y
762
+ const tip = `${node.label}\n${node.type}`
763
+ + `${node.salience ? ` · salience:${node.salience}` : ''}`
764
+ + `${node.tags && node.tags.length > 0 ? `\n#${node.tags.join(' #')}` : ''}`
765
+ + `\n${node.degree ?? 0} 条关系`
766
+ const showLabel = node.hub || (node.degree ?? 0) >= 2
767
+ const label = String(node.label).length > 16 ? `${String(node.label).slice(0, 15)}…` : String(node.label)
768
+ return React.createElement('g', {
769
+ key: node.id,
770
+ transform: `translate(${dx.toFixed(2)} ${dy.toFixed(2)})`,
771
+ className: lit(node.id) ? 'lit' : undefined,
772
+ style: { cursor: 'grab' },
773
+ onPointerDown: (event) => { event.stopPropagation?.(); handlePointerDown(event, node) },
774
+ onPointerMove: handlePointerMove,
775
+ onPointerUp: handlePointerUp,
776
+ onPointerCancel: handlePointerUp,
777
+ onMouseEnter: () => setHover(node.id),
778
+ onMouseLeave: () => setHover(undefined),
779
+ },
780
+ React.createElement('circle', {
781
+ cx: node.x, cy: node.y, r: node.r,
782
+ fill: node.color,
783
+ fillOpacity: lit(node.id) ? 0.95 : 0.2,
784
+ stroke: 'var(--dsw-alias-bg-layer-2, #22252a)',
785
+ strokeWidth: node.hub ? 2 : 1,
786
+ }, React.createElement('title', null, tip)),
787
+ showLabel
788
+ ? React.createElement('text', {
789
+ x: node.x + node.r + 4,
790
+ y: node.y + 3.5,
791
+ fontSize: node.hub ? 11 : 10,
792
+ fontWeight: node.hub ? 600 : 400,
793
+ fill: 'var(--dsw-alias-label-secondary, #999)',
794
+ fillOpacity: lit(node.id) ? 1 : 0.25,
795
+ style: { userSelect: 'none' },
796
+ }, label)
797
+ : null,
798
+ )
799
+ }
800
+
801
+ const svgClass = ['dsh-memory-graph-svg', dragging ? 'dragging' : '', dropAnim ? 'graph-drop' : '']
802
+ .filter(Boolean).join(' ')
803
+ const svg = React.createElement('svg', {
804
+ ref: svgRef,
805
+ viewBox: `${view.x} ${view.y} ${view.w} ${view.h}`,
806
+ width: '100%',
807
+ className: svgClass,
808
+ style: {
809
+ display: 'block',
810
+ borderRadius: '8px',
811
+ background: 'var(--dsw-alias-bg-layer-1, transparent)',
812
+ touchAction: 'none',
813
+ cursor: zoomed ? 'grab' : 'default',
814
+ },
815
+ role: 'img',
816
+ 'aria-label': '记忆图谱',
817
+ onPointerDown: panStart,
818
+ onPointerMove: panMove,
819
+ onPointerUp: panEnd,
820
+ onPointerLeave: panEnd,
821
+ },
822
+ edges.map((e, index) => {
823
+ const a = byId.get(e.source)
824
+ const b = byId.get(e.target)
825
+ if (a === undefined || b === undefined) return null
826
+ const pa = posOf(a)
827
+ const pb = posOf(b)
828
+ return React.createElement('line', {
829
+ key: `e${index}`,
830
+ x1: pa.x, y1: pa.y, x2: pb.x, y2: pb.y,
831
+ stroke: e.kind === 'link'
832
+ ? 'var(--dsw-alias-brand-primary, #4c8bf5)'
833
+ : e.kind === 'index'
834
+ ? 'var(--dsw-alias-label-secondary, #8b8f96)'
835
+ : 'var(--dsw-alias-border-l2, rgba(128,128,128,0.45))',
836
+ strokeWidth: e.kind === 'link' ? 1.4 : 0.7,
837
+ strokeDasharray: e.kind === 'index' ? '2 3' : undefined,
838
+ strokeOpacity: litEdge(e) ? (e.kind === 'index' ? 0.5 : 0.9) : (e.kind === 'index' ? 0.08 : 0.12),
839
+ })
840
+ }),
841
+ nodes.map(renderNode),
842
+ )
843
+
844
+ const colourOf = (type) => (nodes.find((n) => n.type === type)?.color) ?? '#8b8f96'
845
+ const chips = [...new Set(nodes.map((n) => n.type))]
846
+ .filter((type) => type !== 'unknown')
847
+ .map((type) => React.createElement('span', {
848
+ key: type,
849
+ style: { display: 'inline-flex', alignItems: 'center', gap: '4px', fontSize: '11px', color: 'var(--dsw-alias-label-secondary, #999)', marginRight: '10px' },
850
+ },
851
+ React.createElement('span', { style: { width: '7px', height: '7px', borderRadius: '4px', background: colourOf(type), display: 'inline-block' } }),
852
+ type,
853
+ ))
854
+
855
+ const isolated = stats.isolated ?? []
856
+ return React.createElement('div', { style: cardStyle },
857
+ React.createElement('div', { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px' } },
858
+ React.createElement('div', { style: cardTitleStyle }, '记忆图谱'),
859
+ zoomed
860
+ ? React.createElement('button', {
861
+ type: 'button',
862
+ onClick: resetView,
863
+ style: {
864
+ fontSize: '11px',
865
+ padding: '2px 8px',
866
+ borderRadius: '6px',
867
+ cursor: 'pointer',
868
+ border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))',
869
+ background: 'transparent',
870
+ color: 'var(--dsw-alias-label-secondary, #999)',
871
+ },
872
+ }, '重置视图')
873
+ : null,
874
+ ),
875
+ React.createElement('div', { style: cardSubStyle },
876
+ `${stats.pages ?? nodes.length} 页 · ${stats.links ?? 0} 条页间互链 · ${stats.tagEdges ?? 0} 条共享 tag`
877
+ + `${stats.indexLinks ? ` · ${stats.indexLinks} 条索引路由(虚线)` : ''}`
878
+ + `${isolated.length > 0 ? ` · ${isolated.length} 页暂时孤立` : ''}`
879
+ + `${fetchedAt instanceof Date ? ` · 更新于 ${fetchedAt.toLocaleTimeString()}` : ''}`,
880
+ ),
881
+ svg,
882
+ React.createElement('div', { style: { marginTop: '8px' } }, ...chips),
883
+ ((stats.links ?? 0) === 0 || isolated.length > 0)
884
+ ? React.createElement('div', { style: { fontSize: '11px', lineHeight: '17px', color: 'var(--dsw-alias-label-secondary, #888)', marginTop: '6px' } },
885
+ (stats.links ?? 0) === 0
886
+ ? '页面之间还没有互相引用——图谱目前只靠共享 tag 连接。写下"见 [某页](path)"会让关系变实。'
887
+ : `这 ${isolated.length} 页还没和别的记忆连上:${isolated.slice(0, 3).map((id) => id.replace(/\.md$/, '')).join('、')}${isolated.length > 3 ? ' 等' : ''}`,
888
+ )
889
+ : null,
890
+ React.createElement('div', { style: { fontSize: '11px', lineHeight: '17px', color: 'var(--dsw-alias-label-secondary, #888)', marginTop: '6px' } },
891
+ React.createElement('span', { style: { color: 'var(--dsw-alias-brand-primary, #4c8bf5)' } }, '━ 页间互链'),
892
+ ' · ',
893
+ React.createElement('span', { style: { color: '#8b8f96' } }, '┄ 索引路由'),
894
+ ' · ',
895
+ '细线=共享 tag。滚轮缩放 · 拖空白处平移 · 拖节点整理视图 · 悬停高亮关系;只读、实时。',
896
+ ),
897
+ )
898
+ })
899
+
900
+ /** 记忆图谱卡片:负责取数(含轮询)与生命周期,渲染交给 GraphView。 */
901
+ function GraphCard() {
902
+ const [graph, setGraph] = React.useState(undefined)
903
+ const [status, setStatus] = React.useState('loading')
904
+ const [fetchedAt, setFetchedAt] = React.useState(undefined)
905
+ ensureGraphStyles()
906
+
907
+ // First load, then keep polling while the panel is open: the graph is a
908
+ // live projection of the store, so a memory written mid-session should
909
+ // appear without closing the panel. Refresh failures are silent — the
910
+ // previous graph stays on screen rather than blanking out.
911
+ React.useEffect(() => {
912
+ let alive = true
913
+ const tick = () => {
914
+ fetch(GRAPH_URL)
915
+ .then(async (response) => {
916
+ if (!response.ok) throw new Error(`GET ${response.status}`)
917
+ return response.json()
918
+ })
919
+ .then((value) => {
920
+ if (!alive) return
921
+ setGraph(value)
922
+ setFetchedAt(new Date())
923
+ setStatus('ready')
924
+ })
925
+ .catch(() => {
926
+ if (alive && status !== 'ready') setStatus('failed')
927
+ })
928
+ }
929
+ tick()
930
+ const timer = setInterval(tick, GRAPH_REFRESH_MS)
931
+ return () => { alive = false; clearInterval(timer) }
932
+ }, [])
933
+
934
+ if (status === 'loading') {
935
+ return React.createElement('div', { style: { ...cardStyle, fontSize: '12px', color: 'var(--dsw-alias-label-secondary, #888)' } }, '正在构建记忆图谱…')
936
+ }
937
+ if (status === 'failed' || graph === undefined) return null
938
+ return React.createElement(GraphView, { graph, fetchedAt })
939
+ }
940
+
320
941
  function apply(ctx) {
321
942
  ctx.slots.inject('settings.section', () => ctx.slots.register({
322
943
  name: 'settings.section',
@@ -328,6 +949,26 @@ window.__ModuleLoader__.load({
328
949
 
329
950
  exports.apply = apply
330
951
  exports.inject = ['slots']
952
+ // Test seam: the browser half cannot be imported by Node, so the pure
953
+ // helpers and the component itself are exposed for a vm-based harness.
954
+ // Underscore-prefixed and additive: the host only reads `apply`/`inject`.
955
+ exports.__test = {
956
+ GraphCard,
957
+ GraphView,
958
+ applyDrag,
959
+ releasePositions,
960
+ clampToBox,
961
+ GRAPH_REFRESH_MS,
962
+ zoomAt,
963
+ panBy,
964
+ toGraphPointIn,
965
+ isZoomedView,
966
+ resetViewState,
967
+ MIN_VIEW_SCALE,
968
+ MAX_VIEW_SCALE,
969
+ GRAPH_W,
970
+ GRAPH_H,
971
+ }
331
972
  return module.exports
332
973
  },
333
974
  })