dsh-plugin-memory 0.16.0 → 0.17.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
@@ -110,9 +110,9 @@ window.__ModuleLoader__.load({
110
110
  soulFromChat: '已铸魂(对话生成):下面是 SOUL.md 里的当前值,保存后由面板接管',
111
111
  soulManaged: '已设置 · 保存后下一次会话生效',
112
112
  soulAgentName: '我的名字',
113
- soulAgentPlaceholder: '例如:小蓝',
113
+ soulAgentPlaceholder: '例如:小助手',
114
114
  soulUserName: '你的称呼',
115
- soulUserPlaceholder: '例如:阿周',
115
+ soulUserPlaceholder: '例如:小明',
116
116
  soulSummary: '基础人格描述',
117
117
  soulSummaryPlaceholder: '例如:直接、诚实、先结论后细节;不确定时明说,不编造。',
118
118
  soulSave: '保存人格',
@@ -165,8 +165,16 @@ window.__ModuleLoader__.load({
165
165
  graphTitle: '记忆图谱',
166
166
  graphResetView: '重置视图',
167
167
  graph3dSpin: '自动旋转',
168
- graph3dHint: '拖空白旋转 · 滚轮缩放 · 拖节点整理布局 · 悬停/点击节点高亮邻居 · 双击空白重置;只读、实时。',
168
+ graph3dHint: '拖空白旋转 · 滚轮缩放 · 拖节点整理布局 · 悬停/点击节点高亮邻居 · 双击节点打开文件 · 双击空白重置;只读、实时。',
169
169
  graph3dNeighbours: '邻居 {count} 个',
170
+ graphSearchPlaceholder: '搜索记忆节点…',
171
+ graphSearchNone: '没有匹配的节点',
172
+ graphRevealFailed: '打开文件失败:',
173
+ graphRevealButton: '在 Finder 中显示',
174
+ graphCopyPath: '复制路径',
175
+ graphCopied: '路径已复制',
176
+ graphCopyFailed: '复制路径失败',
177
+ graphRevealFallback: '打开失败,已复制路径;在 Finder 里按 ⌘⇧G 粘贴路径即可跳转',
170
178
  graphStats: '{pages} 页 · {links} 条页间互链 · {tagEdges} 条共享 tag',
171
179
  graphIndexRoutes: '{count} 条索引路由(虚线)',
172
180
  graphIsolated: '{count} 页暂时孤立',
@@ -257,9 +265,9 @@ window.__ModuleLoader__.load({
257
265
  soulFromChat: 'Soul forged in chat: values below are parsed from SOUL.md; saving hands it to the panel',
258
266
  soulManaged: 'Set · saving applies from the next session',
259
267
  soulAgentName: 'My name',
260
- soulAgentPlaceholder: 'e.g. 小蓝',
268
+ soulAgentPlaceholder: 'e.g. Assistant',
261
269
  soulUserName: 'What I call you',
262
- soulUserPlaceholder: 'e.g. 阿周',
270
+ soulUserPlaceholder: 'e.g. Alex',
263
271
  soulSummary: 'Baseline persona',
264
272
  soulSummaryPlaceholder: 'e.g. Direct, honest, conclusion first; say when unsure, never fabricate.',
265
273
  soulSave: 'Save soul',
@@ -312,8 +320,16 @@ window.__ModuleLoader__.load({
312
320
  graphTitle: 'Memory graph',
313
321
  graphResetView: 'Reset view',
314
322
  graph3dSpin: 'Auto-spin',
315
- graph3dHint: 'Drag empty space to rotate · wheel to zoom · drag nodes to tidy the layout · hover or click a node to light up its neighbours · double-click empty space to reset; read-only, live.',
323
+ graph3dHint: 'Drag empty space to rotate · wheel to zoom · drag nodes to tidy the layout · hover or click a node to light up its neighbours · double-click a node to reveal its file · double-click empty space to reset; read-only, live.',
316
324
  graph3dNeighbours: 'Neighbours: {count}',
325
+ graphSearchPlaceholder: 'Search memory nodes…',
326
+ graphSearchNone: 'No matching nodes',
327
+ graphRevealFailed: 'Could not open the file: ',
328
+ graphRevealButton: 'Reveal in Finder',
329
+ graphCopyPath: 'Copy path',
330
+ graphCopied: 'Path copied',
331
+ graphCopyFailed: 'Could not copy the path',
332
+ graphRevealFallback: 'Reveal failed; the path was copied — paste it in your file manager to jump there',
317
333
  graphStats: '{pages} pages · {links} page links · {tagEdges} shared tags',
318
334
  graphIndexRoutes: '{count} index routes (dashed)',
319
335
  graphIsolated: '{count} pages isolated',
@@ -1839,6 +1855,41 @@ window.__ModuleLoader__.load({
1839
1855
  return false
1840
1856
  }
1841
1857
 
1858
+ // 内联自 lib/graph-search.js(客户端只能 require 平台种子)。
1859
+ const GRAPH_REVEAL_URL = '/api/memory/reveal'
1860
+ const GRAPH_PATH_URL = '/api/memory/path'
1861
+
1862
+ function graph3dMatch(nodes, query, limit = 8) {
1863
+ const needle = String(query ?? '').trim().toLowerCase()
1864
+ if (needle.length === 0) return []
1865
+ const scored = []
1866
+ for (const node of nodes) {
1867
+ const label = String(node.label ?? '').toLowerCase()
1868
+ const id = String(node.id ?? '').toLowerCase()
1869
+ const type = String(node.type ?? '').toLowerCase()
1870
+ const tags = Array.isArray(node.tags) ? node.tags.map((tag) => String(tag).toLowerCase()) : []
1871
+ let score = 0
1872
+ if (label === needle) score = 100
1873
+ else if (label.startsWith(needle)) score = 80
1874
+ else if (label.includes(needle)) score = 60
1875
+ else if (id.includes(needle)) score = 40
1876
+ else if (type === needle) score = 30
1877
+ else if (tags.includes(needle)) score = 20
1878
+ else if (tags.some((tag) => tag.includes(needle))) score = 10
1879
+ if (score > 0) scored.push({ node, score })
1880
+ }
1881
+ scored.sort((a, b) => b.score - a.score || String(a.node.label ?? '').localeCompare(String(b.node.label ?? '')))
1882
+ return scored.slice(0, limit).map((entry) => entry.node)
1883
+ }
1884
+
1885
+ function graph3dFocusAngles(node) {
1886
+ const x = Number(node?.x ?? 0)
1887
+ const y = Number(node?.y ?? 0)
1888
+ const z = Number(node?.z ?? 0)
1889
+ const ring = Math.hypot(x, z)
1890
+ return { yaw: Math.atan2(x, z), pitch: Math.atan2(y, ring) }
1891
+ }
1892
+
1842
1893
  const GraphView = React.memo(function GraphView(props) {
1843
1894
  const { graph, fetchedAt } = props
1844
1895
  const t = useT(props)
@@ -1900,6 +1951,58 @@ window.__ModuleLoader__.load({
1900
1951
  }
1901
1952
  return { nodes: list, byId, edges: edgeList, adjacency }
1902
1953
  }, [graph])
1954
+ const [query, setQuery] = React.useState('')
1955
+ const [notice, setNotice] = React.useState(undefined)
1956
+ const matches = React.useMemo(() => graph3dMatch(model.nodes, query), [model, query])
1957
+
1958
+ /** 搜索命中:把目标节点转到屏幕正中并选中(邻居自动高亮)。 */
1959
+ const focusNode = (node) => {
1960
+ const angles = graph3dFocusAngles(node)
1961
+ stateRef.current.view.yaw = angles.yaw
1962
+ stateRef.current.view.pitch = angles.pitch
1963
+ stateRef.current.selected = node.id
1964
+ setSelected(node.id)
1965
+ setQuery('')
1966
+ }
1967
+
1968
+ /** 让 host 解析节点的绝对路径并写进剪贴板(E 兜底的核心)。 */
1969
+ const copyPathToClipboard = async (id) => {
1970
+ try {
1971
+ const response = await fetch(`${GRAPH_PATH_URL}?id=${encodeURIComponent(id)}`)
1972
+ const body = await response.json().catch(() => ({}))
1973
+ if (!response.ok || typeof body.path !== 'string') throw new Error(body.error ?? `GET ${response.status}`)
1974
+ if (typeof navigator === 'undefined' || !navigator.clipboard?.writeText) throw new Error('clipboard unavailable')
1975
+ await navigator.clipboard.writeText(body.path)
1976
+ return true
1977
+ } catch {
1978
+ return false
1979
+ }
1980
+ }
1981
+
1982
+ /** 「复制路径」按钮。 */
1983
+ const copyNodePath = async (id) => {
1984
+ setNotice((await copyPathToClipboard(id)) ? t('graphCopied') : t('graphCopyFailed'))
1985
+ }
1986
+
1987
+ /** 「在 Finder 中显示」按钮 + 双击节点;失败时自动复制路径兜底。 */
1988
+ const revealNode = (id) => {
1989
+ fetch(GRAPH_REVEAL_URL, {
1990
+ method: 'POST',
1991
+ headers: { 'content-type': 'application/json' },
1992
+ body: JSON.stringify({ id }),
1993
+ })
1994
+ .then(async (response) => {
1995
+ const body = await response.json().catch(() => ({}))
1996
+ if (!response.ok) throw new Error(body.error ?? `POST ${response.status}`)
1997
+ return body
1998
+ })
1999
+ .then(() => setNotice(undefined))
2000
+ .catch(async (error) => {
2001
+ const message = error instanceof Error ? error.message : String(error)
2002
+ const copied = await copyPathToClipboard(id)
2003
+ setNotice(copied ? t('graphRevealFallback') : `${t('graphRevealFailed')}${message}`)
2004
+ })
2005
+ }
1903
2006
 
1904
2007
  React.useEffect(() => { stateRef.current.selected = selected }, [selected])
1905
2008
  React.useEffect(() => { stateRef.current.spin = spin }, [spin])
@@ -2035,7 +2138,12 @@ window.__ModuleLoader__.load({
2035
2138
  const onDouble = (event) => {
2036
2139
  const point = localPoint(event)
2037
2140
  const hit = graph3dHit(projectedNow(), point.x, point.y, radiusOf)
2038
- if (hit !== null) return
2141
+ if (hit !== null) {
2142
+ stateRef.current.selected = hit.id
2143
+ setSelected(hit.id)
2144
+ revealNode(hit.id)
2145
+ return
2146
+ }
2039
2147
  stateRef.current.view = { yaw: 0.55, pitch: -0.2, zoom: 1 }
2040
2148
  stateRef.current.selected = undefined
2041
2149
  setSelected(undefined)
@@ -2114,6 +2222,59 @@ window.__ModuleLoader__.load({
2114
2222
  + (isolated.length > 0 ? ` · ${fill(t('graphIsolated'), { count: isolated.length })}` : '')
2115
2223
  + (fetchedAt instanceof Date ? ` · ${fill(t('graphUpdatedAt'), { time: fetchedAt.toLocaleTimeString() })}` : ''),
2116
2224
  ),
2225
+ React.createElement('div', { style: { position: 'relative', marginBottom: '8px' } },
2226
+ React.createElement('input', {
2227
+ type: 'search',
2228
+ value: query,
2229
+ placeholder: t('graphSearchPlaceholder'),
2230
+ 'aria-label': t('graphSearchPlaceholder'),
2231
+ onChange: (event) => setQuery(event.target.value),
2232
+ onKeyDown: (event) => {
2233
+ if (event.key === 'Enter' && matches.length > 0) {
2234
+ event.preventDefault?.()
2235
+ focusNode(matches[0])
2236
+ }
2237
+ if (event.key === 'Escape') setQuery('')
2238
+ },
2239
+ style: { ...inputStyle, width: '100%', boxSizing: 'border-box' },
2240
+ }),
2241
+ query.trim().length > 0 && matches.length === 0
2242
+ ? React.createElement('div', { role: 'status', style: { marginTop: '4px', fontSize: '11px', color: 'var(--dsw-alias-label-secondary, #888)' } }, t('graphSearchNone'))
2243
+ : null,
2244
+ query.trim().length > 0 && matches.length > 0
2245
+ ? React.createElement('div', {
2246
+ style: {
2247
+ position: 'absolute',
2248
+ zIndex: 20,
2249
+ left: 0,
2250
+ right: 0,
2251
+ top: '100%',
2252
+ marginTop: '2px',
2253
+ maxHeight: '190px',
2254
+ overflowY: 'auto',
2255
+ borderRadius: '8px',
2256
+ border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.3))',
2257
+ background: 'var(--dsw-alias-bg-layer-2, #1b1e24)',
2258
+ boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
2259
+ },
2260
+ }, ...matches.map((node) => React.createElement('button', {
2261
+ key: node.id,
2262
+ type: 'button',
2263
+ onClick: () => focusNode(node),
2264
+ style: {
2265
+ display: 'block',
2266
+ width: '100%',
2267
+ textAlign: 'left',
2268
+ padding: '7px 10px',
2269
+ border: 'none',
2270
+ background: 'transparent',
2271
+ color: 'var(--dsw-alias-label-primary, #e8ecf7)',
2272
+ fontSize: '12px',
2273
+ cursor: 'pointer',
2274
+ },
2275
+ }, `${node.label} · ${typeLabel(node.type, t)}`)))
2276
+ : null,
2277
+ ),
2117
2278
  React.createElement('canvas', {
2118
2279
  ref: canvasRef,
2119
2280
  'aria-label': t('graphTitle'),
@@ -2147,8 +2308,23 @@ window.__ModuleLoader__.load({
2147
2308
  ` · ${typeLabel(selectedNode.type, t)} · degree ${selectedNode.degree} · `,
2148
2309
  fill(t('graph3dNeighbours'), { count: selectedNeighbours }),
2149
2310
  React.createElement('div', { style: { color: 'var(--dsw-alias-label-secondary, #888)' } }, selectedNode.id),
2311
+ React.createElement('div', { style: { display: 'flex', gap: '6px', marginTop: '6px' } },
2312
+ React.createElement('button', {
2313
+ type: 'button',
2314
+ onClick: () => revealNode(selectedNode.id),
2315
+ style: smallButtonStyle,
2316
+ }, t('graphRevealButton')),
2317
+ React.createElement('button', {
2318
+ type: 'button',
2319
+ onClick: () => copyNodePath(selectedNode.id),
2320
+ style: smallButtonStyle,
2321
+ }, t('graphCopyPath')),
2322
+ ),
2150
2323
  )
2151
2324
  : null,
2325
+ notice !== undefined
2326
+ ? React.createElement('div', { role: 'alert', style: { marginTop: '8px', fontSize: '11px', color: 'var(--dsw-alias-state-error-primary, #e5484d)' } }, notice)
2327
+ : null,
2152
2328
  React.createElement('div', { style: { marginTop: '8px' } }, ...chips),
2153
2329
  ((stats.links ?? 0) === 0 || isolated.length > 0)
2154
2330
  ? React.createElement('div', { style: { fontSize: '11px', lineHeight: '17px', color: 'var(--dsw-alias-label-secondary, #888)', marginTop: '6px' } },
@@ -2381,6 +2557,10 @@ window.__ModuleLoader__.load({
2381
2557
  graph3dUnrotate,
2382
2558
  graph3dProject,
2383
2559
  graph3dHit,
2560
+ graph3dMatch,
2561
+ graph3dFocusAngles,
2562
+ GRAPH_REVEAL_URL,
2563
+ GRAPH_PATH_URL,
2384
2564
  isLightColor,
2385
2565
  }
2386
2566
  return module.exports
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Graph search + camera focus maths (pure, deterministic).
3
+ *
4
+ * Kept out of the browser half so Node tests can pin both behaviours; the
5
+ * client inlines the same functions (the client can only require platform
6
+ * seeds) and a consistency test keeps the copies from drifting.
7
+ *
8
+ * @module dsh-plugin-memory/graph-search
9
+ */
10
+
11
+ /** Default number of suggestions the panel shows while typing. */
12
+ export const GRAPH_SEARCH_LIMIT = 8
13
+
14
+ /**
15
+ * Match nodes against a free-text query.
16
+ *
17
+ * Ranking: exact label > label prefix > label substring > id substring >
18
+ * exact type > exact tag > tag substring. Empty query returns no suggestions.
19
+ *
20
+ * @param {Array<{ id: string, label?: string, type?: string, tags?: string[] }>} nodes
21
+ * @param {string} query
22
+ * @param {{ limit?: number }} [options]
23
+ * @returns {Array<{ id: string, label?: string, type?: string, tags?: string[] }>}
24
+ */
25
+ export function matchGraphNodes(nodes, query, options = {}) {
26
+ const needle = String(query ?? '').trim().toLowerCase()
27
+ if (needle.length === 0) return []
28
+ const limit = options.limit ?? GRAPH_SEARCH_LIMIT
29
+ const scored = []
30
+ for (const node of nodes) {
31
+ const label = String(node.label ?? '').toLowerCase()
32
+ const id = String(node.id ?? '').toLowerCase()
33
+ const type = String(node.type ?? '').toLowerCase()
34
+ const tags = Array.isArray(node.tags) ? node.tags.map((tag) => String(tag).toLowerCase()) : []
35
+ let score = 0
36
+ if (label === needle) score = 100
37
+ else if (label.startsWith(needle)) score = 80
38
+ else if (label.includes(needle)) score = 60
39
+ else if (id.includes(needle)) score = 40
40
+ else if (type === needle) score = 30
41
+ else if (tags.includes(needle)) score = 20
42
+ else if (tags.some((tag) => tag.includes(needle))) score = 10
43
+ if (score > 0) scored.push({ node, score })
44
+ }
45
+ scored.sort((a, b) => b.score - a.score || String(a.node.label ?? '').localeCompare(String(b.node.label ?? '')))
46
+ return scored.slice(0, limit).map((entry) => entry.node)
47
+ }
48
+
49
+ /**
50
+ * Camera angles that bring a node to the screen centre.
51
+ *
52
+ * `projectPoint` maps a world point through yaw (around Y) then pitch (around
53
+ * X). With `yaw = atan2(x, z)` the rotated x becomes 0; with
54
+ * `pitch = atan2(y, hypot(x, z))` the rotated y becomes 0. Both zeros mean the
55
+ * node projects to the canvas centre exactly.
56
+ *
57
+ * @param {{ x: number, y: number, z: number }} node
58
+ * @returns {{ yaw: number, pitch: number }}
59
+ */
60
+ export function focusAngles(node) {
61
+ const x = Number(node?.x ?? 0)
62
+ const y = Number(node?.y ?? 0)
63
+ const z = Number(node?.z ?? 0)
64
+ const ring = Math.hypot(x, z)
65
+ return {
66
+ yaw: Math.atan2(x, z),
67
+ pitch: Math.atan2(y, ring),
68
+ }
69
+ }
package/lib/graph.js CHANGED
@@ -22,6 +22,7 @@
22
22
 
23
23
  import { existsSync, readFileSync } from 'node:fs'
24
24
  import { basename, dirname, join, normalize } from 'node:path'
25
+ import { normalizeNewlines } from './paths.js'
25
26
  import { listPagePaths } from './pages.js'
26
27
  import { parseFrontmatter } from './insights.js'
27
28
  import { layoutGraph, typeColor } from './graph-layout.js'
@@ -114,7 +115,7 @@ export function buildMemoryGraph(memoryDir, options = {}) {
114
115
  const id = nodeId(rel)
115
116
  let text = ''
116
117
  try {
117
- text = readFileSync(join(memoryDir, rel), 'utf8')
118
+ text = normalizeNewlines(readFileSync(join(memoryDir, rel), 'utf8'))
118
119
  } catch {
119
120
  continue
120
121
  }
@@ -175,7 +176,7 @@ export function buildMemoryGraph(memoryDir, options = {}) {
175
176
  for (const node of [...nodes]) {
176
177
  let text = ''
177
178
  try {
178
- text = readFileSync(join(memoryDir, node.id), 'utf8')
179
+ text = normalizeNewlines(readFileSync(join(memoryDir, node.id), 'utf8'))
179
180
  } catch {
180
181
  continue
181
182
  }
package/lib/index-page.js CHANGED
@@ -26,6 +26,7 @@
26
26
  */
27
27
 
28
28
  import { existsSync, readFileSync, writeFileSync } from 'node:fs'
29
+ import { normalizeNewlines } from './paths.js'
29
30
  import { join } from 'node:path'
30
31
  import { collectInsights, parseFrontmatter } from './insights.js'
31
32
 
@@ -227,7 +228,7 @@ const normalise = (value) => value.replace(/\s+/g, ' ').trim()
227
228
  */
228
229
  export function planIndex(memoryDir) {
229
230
  const indexPath = join(memoryDir, 'index.md')
230
- const text = existsSync(indexPath) ? readFileSync(indexPath, 'utf8') : ''
231
+ const text = existsSync(indexPath) ? normalizeNewlines(readFileSync(indexPath, 'utf8')) : ''
231
232
  const parsed = parseIndexPage(text)
232
233
  const insights = collectInsights(memoryDir)
233
234
  const pageByPath = new Map((insights.pages ?? []).map((page) => [page.path, page]))
@@ -243,7 +244,7 @@ export function planIndex(memoryDir) {
243
244
  if (page === undefined) continue
244
245
  let pageText = ''
245
246
  try {
246
- pageText = readFileSync(join(memoryDir, item.target), 'utf8')
247
+ pageText = normalizeNewlines(readFileSync(join(memoryDir, item.target), 'utf8'))
247
248
  } catch {
248
249
  continue
249
250
  }
@@ -295,7 +296,7 @@ export function planIndex(memoryDir) {
295
296
  */
296
297
  export function applyIndex(memoryDir, plan) {
297
298
  const indexPath = join(memoryDir, 'index.md')
298
- const before = existsSync(indexPath) ? readFileSync(indexPath, 'utf8') : ''
299
+ const before = existsSync(indexPath) ? normalizeNewlines(readFileSync(indexPath, 'utf8')) : ''
299
300
  const replacement = new Map()
300
301
  for (const line of plan.lines) {
301
302
  if (line.changed) replacement.set(normalise(line.current), line.next)
@@ -334,7 +335,7 @@ export function syncDeclaredSummaries(memoryDir, plan) {
334
335
  const abs = join(memoryDir, line.target)
335
336
  let text = ''
336
337
  try {
337
- text = readFileSync(abs, 'utf8')
338
+ text = normalizeNewlines(readFileSync(abs, 'utf8'))
338
339
  } catch {
339
340
  skipped.push(line.target)
340
341
  continue
package/lib/index.js CHANGED
@@ -108,8 +108,9 @@ import { buildToneGuide } from './tone.js'
108
108
  import { claimProactiveLock, defaultProactiveCooldownPath } from './proactive-lock.js'
109
109
  import { AutoCommitter } from './autocommit.js'
110
110
  import { ActivityTracker } from './activity-tracker.js'
111
- import { SessionGate, matchesWorkspace } from './session-gate.js'
111
+ import { SessionGate, expandHome, matchesWorkspace } from './session-gate.js'
112
112
  import { markBootstrapComplete, readSoulProfile, writeSoulProfile } from './soul.js'
113
+ import { resolveMemoryFile, revealFile } from './reveal.js'
113
114
  import {
114
115
  MEMORY_SKILL_NAME,
115
116
  MEMORY_SKILL_DESCRIPTION,
@@ -135,6 +136,12 @@ export const SESSION_ROUTE_PATH = '/api/memory/session'
135
136
  /** Basic soul profile (managed SOUL.md block): GET the fields, POST a save. */
136
137
  export const SOUL_ROUTE_PATH = '/api/memory/soul'
137
138
 
139
+ /** Reveal one memory page in the OS file manager (Finder/Explorer/xdg). */
140
+ export const REVEAL_ROUTE_PATH = '/api/memory/reveal'
141
+
142
+ /** Resolve one memory page to its absolute path (copy-path fallback). */
143
+ export const PATH_ROUTE_PATH = '/api/memory/path'
144
+
138
145
  export const inject = ['systemPrompt', 'skills', 'agents']
139
146
 
140
147
  /** Schemastery schema applied to the plugin config before startup. */
@@ -201,9 +208,8 @@ export const Config = z.object({
201
208
  * @returns {string}
202
209
  */
203
210
  export function resolveMemoryDir(dir) {
204
- if (dir === '~') return homedir()
205
- if (dir.startsWith('~/')) return join(homedir(), dir.slice(2))
206
- return resolve(dir)
211
+ const expanded = expandHome(dir)
212
+ return resolve(expanded ?? dir)
207
213
  }
208
214
 
209
215
  /**
@@ -838,6 +844,67 @@ export function apply(ctx, config = {}) {
838
844
  webCtx.effect(() => disposeSoulRoute, 'memory.soul-route()')
839
845
  ctx.logger?.info(`memory: soul route at ${SOUL_ROUTE_PATH}`)
840
846
 
847
+ // 双击图谱节点 → 在系统文件管理器里定位这份记忆页。路径在 reveal.js 里
848
+ // 做 realpath 边界校验,越界或非文件一律拒绝。
849
+ const disposeRevealRoute = webCtx.webServer.register({
850
+ kind: 'exact',
851
+ path: REVEAL_ROUTE_PATH,
852
+ handler: async (req, res) => {
853
+ const sendJson = (status, payload) => {
854
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
855
+ res.end(JSON.stringify(payload))
856
+ }
857
+ try {
858
+ if (req.method !== 'POST') {
859
+ sendJson(405, { error: 'method not allowed' })
860
+ return
861
+ }
862
+ const chunks = []
863
+ for await (const chunk of req) chunks.push(chunk)
864
+ let body
865
+ try {
866
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
867
+ } catch {
868
+ sendJson(400, { error: 'body must be JSON' })
869
+ return
870
+ }
871
+ const result = await revealFile(currentMemoryDir, body?.id)
872
+ sendJson(200, { ok: true, path: result.path })
873
+ } catch (error) {
874
+ const status = error?.code === 'invalid-id' ? 400 : 500
875
+ sendJson(status, { error: error instanceof Error ? error.message : String(error) })
876
+ }
877
+ },
878
+ })
879
+ webCtx.effect(() => disposeRevealRoute, 'memory.reveal-route()')
880
+ ctx.logger?.info(`memory: reveal route at ${REVEAL_ROUTE_PATH}`)
881
+
882
+ // 复制路径兜底:只解析绝对路径,不执行任何命令。reveal 失败时客户端
883
+ // 用它把路径写进剪贴板,用户自己在文件管理器里跳过去。
884
+ const disposePathRoute = webCtx.webServer.register({
885
+ kind: 'exact',
886
+ path: PATH_ROUTE_PATH,
887
+ handler: async (req, res) => {
888
+ const sendJson = (status, payload) => {
889
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
890
+ res.end(JSON.stringify(payload))
891
+ }
892
+ try {
893
+ if (req.method !== 'GET') {
894
+ sendJson(405, { error: 'method not allowed' })
895
+ return
896
+ }
897
+ const url = new URL(req.url ?? PATH_ROUTE_PATH, 'http://localhost')
898
+ const path = resolveMemoryFile(currentMemoryDir, url.searchParams.get('id'))
899
+ sendJson(200, { ok: true, path })
900
+ } catch (error) {
901
+ sendJson(400, { error: error instanceof Error ? error.message : String(error) })
902
+ }
903
+ },
904
+ })
905
+ webCtx.effect(() => disposePathRoute, 'memory.path-route()')
906
+ ctx.logger?.info(`memory: path route at ${PATH_ROUTE_PATH}`)
907
+
841
908
  // Read-only health dashboard payload. Built fresh on every request from the
842
909
  // store on disk, so the panel always reflects the newest state and the
843
910
  // plugin never caches a stale view of the user's memory.
package/lib/pages.js CHANGED
@@ -19,6 +19,7 @@
19
19
  */
20
20
 
21
21
  import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
22
+ import { normalizeNewlines } from './paths.js'
22
23
  import { join, relative, sep } from 'node:path'
23
24
 
24
25
  /** Category directories a memory page may live under. */
@@ -102,12 +103,14 @@ export function extractReferencedPages(text, memoryDir, dirs = PAGE_DIRS) {
102
103
  */
103
104
  export function touchPageFile(filePath, date = today()) {
104
105
  if (!existsSync(filePath)) return false
105
- let text
106
+ let raw
106
107
  try {
107
- text = readFileSync(filePath, 'utf8')
108
+ raw = readFileSync(filePath, 'utf8')
108
109
  } catch {
109
110
  return false
110
111
  }
112
+ const crlf = raw.includes('\r\n')
113
+ const text = normalizeNewlines(raw)
111
114
  const match = /^last_access:.*$/m.exec(text)
112
115
  // No `last_access` line: leave the page alone rather than inventing
113
116
  // frontmatter the author did not write.
@@ -115,7 +118,7 @@ export function touchPageFile(filePath, date = today()) {
115
118
  if (match[0] === `last_access: ${date}`) return false
116
119
  const next = text.slice(0, match.index) + `last_access: ${date}` + text.slice(match.index + match[0].length)
117
120
  try {
118
- writeFileSync(filePath, next, 'utf8')
121
+ writeFileSync(filePath, crlf ? next.replace(/\n/g, '\r\n') : next, 'utf8')
119
122
  } catch {
120
123
  return false
121
124
  }
@@ -170,7 +173,7 @@ export function accessSummary(memoryDir, options = {}) {
170
173
  const stale = []
171
174
  for (const path of paths) {
172
175
  const abs = join(memoryDir, path)
173
- const lastAccess = readLastAccess(readFileSync(abs, 'utf8'))
176
+ const lastAccess = readLastAccess(normalizeNewlines(readFileSync(abs, 'utf8')))
174
177
  if (!lastAccess) {
175
178
  missing += 1
176
179
  stale.push(path)
@@ -211,7 +214,7 @@ export function listPagesWithMeta(memoryDir) {
211
214
  for (const rel of listPagePaths(memoryDir)) {
212
215
  let text = ''
213
216
  try {
214
- text = readFileSync(join(memoryDir, rel), 'utf8')
217
+ text = normalizeNewlines(readFileSync(join(memoryDir, rel), 'utf8'))
215
218
  } catch {
216
219
  continue
217
220
  }
package/lib/paths.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Cross-platform path helpers: home expansion, Windows-style variables and
3
+ * newline normalisation.
4
+ *
5
+ * The plugin runs on macOS, Windows and Linux. Two things differ enough to
6
+ * hurt: `~` is POSIX-only (Windows users write `%USERPROFILE%` / `$HOME`),
7
+ * and Windows editors save markdown with CRLF — frontmatter regexes anchored
8
+ * with `^...$` silently stop matching on `\r`-suffixed lines.
9
+ *
10
+ * @module dsh-plugin-memory/paths
11
+ */
12
+
13
+ import { homedir } from 'node:os'
14
+ import { join } from 'node:path'
15
+
16
+ /**
17
+ * Normalise CRLF / lone CR to LF.
18
+ *
19
+ * Used on **read** paths only: files written back keep their own newline
20
+ * style (see the callers that detect `\r\n` before writing).
21
+ *
22
+ * @param {unknown} text
23
+ * @returns {string}
24
+ */
25
+ export function normalizeNewlines(text) {
26
+ if (typeof text !== 'string') return ''
27
+ return text.replace(/\r\n?/g, '\n')
28
+ }
29
+
30
+ /**
31
+ * Expand a user-supplied path value:
32
+ * - `~`, `~/x`, `~\x` → the user's home directory
33
+ * - `%USERPROFILE%` / `%APPDATA%` (Windows style)
34
+ * - `$HOME` / `${HOME}` (POSIX style)
35
+ * Unknown variables are left verbatim; non-strings return `undefined`.
36
+ *
37
+ * @param {unknown} value
38
+ * @param {{ home?: string, env?: Record<string, string | undefined> }} [options]
39
+ * @returns {string | undefined}
40
+ */
41
+ export function expandPath(value, options = {}) {
42
+ if (typeof value !== 'string') return undefined
43
+ const home = options.home ?? homedir()
44
+ const env = options.env ?? process.env
45
+ let text = value.trim()
46
+ if (text.length === 0) return undefined
47
+ text = text.replace(/%([A-Za-z0-9_]+)%/g, (match, name) => (
48
+ typeof env[name] === 'string' ? env[name] : match
49
+ ))
50
+ text = text.replace(/\$\{([A-Za-z0-9_]+)\}|\$([A-Za-z0-9_]+)/g, (match, braced, plain) => {
51
+ const name = braced ?? plain
52
+ return typeof env[name] === 'string' ? env[name] : match
53
+ })
54
+ if (text === '~') return home
55
+ if (text.startsWith('~/') || text.startsWith('~\\')) return join(home, text.slice(2))
56
+ return text
57
+ }