@restregular/dsh-memory 0.11.0 → 0.12.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.
@@ -16,8 +16,10 @@
16
16
 
17
17
  import { MemoryStore, scopeFileName, } from './store.js'
18
18
  import {
19
+ canonicalWorkspacePath,
19
20
  isCustomScope,
20
21
  normalizeScopeInput,
22
+ projectScopeIdentity,
21
23
  resolveCurrentScopes,
22
24
  scopeKind,
23
25
  scopeTier,
@@ -490,12 +492,20 @@ export class LocalMemoryService {
490
492
  projectScope
491
493
  /** 上次发现磁盘 scope 的时间(限流用;0 = 还没发现过)。 */
492
494
  discoveredAt = 0
495
+ /** "同一目录不同写法"的项目作用域是否已经合并过(每个进程只做一次)。 */
496
+ scopesReconciled = false
493
497
  /** 作用域别名(project:<路径> → 显示名),落盘 <storeDir>/scopes.json。 */
494
498
  names
495
499
  /** 注入设置(面板「设置」标签页可改;落盘在 <storeDir>/settings.json)。 */
496
500
  inject
497
501
  /** 注入半边的审计收集器(可选;没有注入半边时保持 null)。 */
498
- injectAuditSink = null
502
+ injectAuditSink
503
+
504
+
505
+
506
+
507
+
508
+ = null
499
509
 
500
510
  constructor(config = {}) {
501
511
  this.cfg = resolveConfig(config)
@@ -541,13 +551,65 @@ export class LocalMemoryService {
541
551
  }
542
552
 
543
553
  /** 注入半边注册审计收集器。重复注册时后一个覆盖前一个(激活重载)。 */
544
- attachInjectAudit(sink ) {
554
+ attachInjectAudit(sink
555
+
556
+
557
+
558
+
559
+
560
+ ) {
561
+ // 显式解绑:插件半边 dispose 时必须清掉,否则面板会继续读到已停止更新的旧 store。
562
+ if (sink === null) {
563
+ try { this.injectAuditSink?.dispose?.() } catch { /* 审计清理失败不影响 provider */ }
564
+ } else if (this.injectAuditSink !== null && this.injectAuditSink !== sink) {
565
+ // 多激活实例不应悄悄覆盖:保留诊断日志,查询边界仍以最后注册者为准。
566
+ console.warn('[dsh-memory-local] audit sink replaced by another activation')
567
+ }
545
568
  this.injectAuditSink = sink
546
569
  }
547
570
 
548
- /** 面板 /memory/api/audit 用:返回注入评估记录(最新在前);没有注入半边时为空。 */
571
+ /** 显式解绑:只有当前 sink 或未指定 sink 时才清理,避免旧实例卸载误清新实例。 */
572
+ detachInjectAudit(sink ) {
573
+ if (sink !== undefined && this.injectAuditSink !== null && sink !== this.injectAuditSink) return
574
+ try { this.injectAuditSink?.dispose?.() } catch { /* 审计清理失败不影响 provider */ }
575
+ this.injectAuditSink = null
576
+ }
577
+
578
+ /** 兼容旧调用:返回审计条目数组(最新在前);没有注入半边时为空。 */
549
579
  injectAudit(sessionId ) {
550
- try { return this.injectAuditSink?.list(sessionId) ?? [] } catch { return [] }
580
+ try { return this.injectAuditSink?.list?.(sessionId) ?? [] } catch { return [] }
581
+ }
582
+
583
+ /** v2 查询:优先用类型化 sink;旧 sink 只有 list 时降级包装成单页。 */
584
+ injectAuditPage(query ) {
585
+ try {
586
+ const sink = this.injectAuditSink
587
+ if (sink?.query !== undefined) return sink.query(query)
588
+ const q = (query && typeof query === 'object' ? query : {})
589
+ const entries = sink?.list?.(q.sessionId) ?? []
590
+ return {
591
+ entries,
592
+ total: Array.isArray(entries) ? entries.length : 0,
593
+ stats: this.injectAuditStats(),
594
+ }
595
+ } catch {
596
+ return { entries: [], total: 0, stats: this.injectAuditStats() }
597
+ }
598
+ }
599
+
600
+ /** 审计容量/丢弃/写入错误等健康状态。 */
601
+ injectAuditStats() {
602
+ try {
603
+ return this.injectAuditSink?.stats?.() ?? {
604
+ entries: 0, capacity: 0, perSessionCapacity: 0, dropped: 0,
605
+ writeErrors: 0, persistence: 'memory',
606
+ }
607
+ } catch {
608
+ return {
609
+ entries: 0, capacity: 0, perSessionCapacity: 0, dropped: 0,
610
+ writeErrors: 0, persistence: 'degraded',
611
+ }
612
+ }
551
613
  }
552
614
 
553
615
  /** 面板改设置:合并补丁 → 落盘 → 返回新值。写盘失败只告警,不影响运行中的设置。 */
@@ -608,15 +670,16 @@ export class LocalMemoryService {
608
670
  * 默认排除已被 supersede 的旧记录;需要历史/审计时显式 includeSuperseded。
609
671
  */
610
672
  listSync(input = {}) {
673
+ const wanted = (input.scopes ?? []).map((scope) => this.canonicalScope(scope))
611
674
  const seen = new Set ()
612
675
  const stores = []
613
- for (const scope of input.scopes ?? []) {
676
+ for (const scope of wanted) {
614
677
  if (seen.has(scope)) continue
615
678
  seen.add(scope)
616
679
  const s = this.store.peek(scope)
617
680
  if (s) stores.push(s)
618
681
  }
619
- const retired = input.includeSuperseded ? new Set () : new Set(this.supersededIds(input.scopes))
682
+ const retired = input.includeSuperseded ? new Set () : new Set(this.supersededIds(wanted))
620
683
  const out = []
621
684
  for (const s of stores) {
622
685
  for (const rec of s.records.values()) {
@@ -1738,9 +1801,21 @@ export class LocalMemoryService {
1738
1801
  return this.names.scopeOf(name)
1739
1802
  }
1740
1803
 
1741
- /** 自定义名可能是别名:统一转回真实键,读写口径共用。 */
1804
+ /**
1805
+ * 作用域键归一:自定义名可能是别名 → 转回真实键;`project:<路径>` 统一路径写法。
1806
+ *
1807
+ * 项目键必须过 `canonicalWorkspacePath`:工具层的 `path`、模型显式给的
1808
+ * `project:D:/x`、面板 HTTP 写入都从这里落盘,同一个目录不能因为 `/` 与 `\` 的差别
1809
+ * 变成两个 scope(0.11.1;读路径的键来自 resolveCurrentScopes,也走同一套规范化)。
1810
+ */
1742
1811
  canonicalScope(scope ) {
1743
- if (scope === 'global' || scope.startsWith('project:') || scope.startsWith('session:')) return scope
1812
+ if (scope === 'global' || scope.startsWith('session:')) return scope
1813
+ if (scope.startsWith('project:')) {
1814
+ const path = scope.slice('project:'.length)
1815
+ if (path === '') return scope
1816
+ const canonical = canonicalWorkspacePath(path)
1817
+ return (canonical === path ? scope : `project:${canonical}`)
1818
+ }
1744
1819
  return (this.names.scopeOf(scope) ) ?? scope
1745
1820
  }
1746
1821
 
@@ -1790,12 +1865,110 @@ export class LocalMemoryService {
1790
1865
  } catch {
1791
1866
  // 发现失败不影响读写,清单里少几个而已
1792
1867
  }
1868
+ try {
1869
+ this.reconcileScopes()
1870
+ } catch {
1871
+ // 合并失败同样不影响读写:留着两个 scope 也比丢数据强
1872
+ }
1793
1873
  }
1794
1874
  return this.knownScopes()
1795
1875
  }
1796
1876
 
1877
+ /**
1878
+ * 把"同一个目录的不同写法"合并成一个项目作用域(0.11.1,每个进程只跑一次)。
1879
+ *
1880
+ * 0.7.0 引入 `memory_save({ path })` 之后, `D:/repositories/x` 与 `D:\repositories\x`
1881
+ * 会落成两个 scope 文件;工作区里的会话用宿主给的 `header.cwd`,于是另一份里的记忆
1882
+ * 永远读不到(面板里还会看到两个同名作用域)。写入侧已在 `canonicalScope` 统一写法,
1883
+ * 这里负责把**历史数据**并到规范键上:
1884
+ * - 同组的判定走 `projectScopeIdentity`(Windows 盘符路径再折叠大小写,POSIX 不动);
1885
+ * - 目标键优先选"写法已经规范"的那一个,其次记录多的(稳定时按键名);**只有变体存在时
1886
+ * 改名**到规范键(否则会话读规范键、永远看不到这份记忆);
1887
+ * - 记录按 id 并入目标(目标已有同 id 就跳过);向量长度与当前配置一致时一起搬;
1888
+ * - 别名跟着走(目标没有别名时才接管),迁空的 scope 由 flush 顺手删掉文件。
1889
+ * 多进程并发时,flush 的"锁内重新读盘 + 只合并本进程增量"兜底:这里只发 upsert/delete,
1890
+ * 不会把别的进程刚写的内容覆盖掉。
1891
+ */
1892
+ reconcileScopes() {
1893
+ if (this.scopesReconciled) return { merged: 0 }
1894
+ this.scopesReconciled = true
1895
+ // 直接调用(装配期)时还没有发现过磁盘 scope:先发现,否则只能看到已加载的那两个,
1896
+ // 合并会漏、而且这唯一一次机会被浪费掉。
1897
+ if (this.discoveredAt === 0) {
1898
+ this.discoveredAt = Date.now()
1899
+ try {
1900
+ this.store.loadDiscovered()
1901
+ } catch {
1902
+ // 发现失败:清单少几个,不影响读写
1903
+ }
1904
+ }
1905
+ const groups = new Map ()
1906
+ for (const store of this.store.allScopes()) {
1907
+ if (!store.scope.startsWith('project:')) continue
1908
+ const path = store.scope.slice('project:'.length)
1909
+ if (path === '') continue
1910
+ const identity = projectScopeIdentity(path)
1911
+ const list = groups.get(identity)
1912
+ const entry = { scope: store.scope, store, records: store.records.size }
1913
+ if (list === undefined) groups.set(identity, [entry])
1914
+ else list.push(entry)
1915
+ }
1916
+ let merged = 0
1917
+ for (const list of groups.values()) {
1918
+ const canonicalOf = (scope ) =>
1919
+ `project:${canonicalWorkspacePath(scope.slice('project:'.length))}`
1920
+ // 1) 写法已经规范的优先 2) 记录多的 3) 键名字典序(稳定,避免每次合并目标漂移)
1921
+ list.sort((a, b) =>
1922
+ Number(canonicalOf(b.scope) === b.scope) - Number(canonicalOf(a.scope) === a.scope)
1923
+ || b.records - a.records
1924
+ || a.scope.localeCompare(b.scope))
1925
+ const targetScope = list[0] .scope
1926
+ // 只有变体存在时(用 path 参数写进来的记忆,会话还没写过那个目录)也要**改名**:
1927
+ // 会话读的是规范键,不改名等于这份记忆永远看不见。改名后 records 一条不少。
1928
+ const canonicalTarget = canonicalOf(targetScope)
1929
+ const finalTarget = canonicalTarget === targetScope ? targetScope : canonicalTarget
1930
+ const sources = list.filter((entry) => entry.scope !== finalTarget)
1931
+ if (sources.length === 0) continue
1932
+ const targetStore = this.store.scope(finalTarget)
1933
+ for (const source of sources) {
1934
+ for (const record of [...source.store.records.values()]) {
1935
+ if (!targetStore.records.has(record.id)) {
1936
+ targetStore.insert({ ...record, scope: finalTarget })
1937
+ const vector = source.store.vectors.get(record.id)
1938
+ // 向量只有在维度与当前配置一致时才可信(换过模型/池化的边车已被 loadScope 校验过,
1939
+ // 这里再按维度兜一层);搬不动的留给回填/重启后重新嵌入。
1940
+ if (vector !== undefined && vector.length === this.cfg.vector.dims) {
1941
+ targetStore.setVector(record.id, vector)
1942
+ }
1943
+ }
1944
+ source.store.remove(record.id)
1945
+ }
1946
+ const alias = this.names.nameOf(source.scope)
1947
+ if (alias !== undefined) {
1948
+ this.names.release(source.scope)
1949
+ if (this.names.nameOf(finalTarget) === undefined) {
1950
+ try {
1951
+ this.names.claim(finalTarget, alias)
1952
+ } catch {
1953
+ // 名字已被别的 scope 占用 → 放弃别名(路径本身仍可引用)
1954
+ }
1955
+ }
1956
+ }
1957
+ merged += 1
1958
+ }
1959
+ }
1960
+ if (merged > 0) {
1961
+ this.store.flush()
1962
+ console.warn(`[dsh-memory-local] 已合并 ${merged} 个"同一目录不同写法"的项目作用域`)
1963
+ }
1964
+ return { merged }
1965
+ }
1966
+
1797
1967
  /** Force a synchronous flush (dispose/HMR path). */
1798
1968
  flushSync() {
1969
+ // 审计 sink 属于注入半边:provider 退出时解绑并释放,避免面板继续读旧 store。
1970
+ try { this.injectAuditSink?.dispose?.() } catch { /* 审计清理失败不影响 provider */ }
1971
+ this.injectAuditSink = null
1799
1972
  if (this.maintenanceTimer) {
1800
1973
  clearInterval(this.maintenanceTimer)
1801
1974
  this.maintenanceTimer = null
@@ -19,6 +19,7 @@
19
19
  * `foo:bar` 会与保留前缀撞成同一个键空间,用户也能靠它伪造 `project:` 键。
20
20
  */
21
21
  import { createHash } from 'node:crypto'
22
+ import { posix, win32 } from 'node:path'
22
23
  import { isCustomScopeKey } from './store.js'
23
24
 
24
25
  /** 作用域键:除 'global' 外的形态由 resolveCurrentScopes / normalizeScopeInput 产生。 */
@@ -185,6 +186,62 @@ export function scopeTier(scope ) {
185
186
  /** 写路径遇到只读 scope 时的错误码('all' 不能写)。 */
186
187
  export const SCOPE_NOT_WRITABLE = 'SCOPE_NOT_WRITABLE'
187
188
 
189
+ // ------------------------------------------------------------------ 项目键的路径写法
190
+
191
+ /** `D:\x` / `D:/x` / `\\server\share` —— 只有这些才按 Windows 语义处理。 */
192
+ const WINDOWS_ABSOLUTE = /^(?:[A-Za-z]:[\\/]|\\\\)/u
193
+ /** Windows 盘符路径(`D:` 后跟分隔符);UNC 没有盘符,单独判。 */
194
+ const DRIVE_PATH = /^[A-Za-z]:[\\/]/u
195
+ const POSIX_ABSOLUTE = /^\//u
196
+
197
+ /**
198
+ * 项目作用域里的**路径规范形**:同一个目录只允许一种写法。
199
+ *
200
+ * 为什么需要:Windows 上 `D:/repositories/dsh-memory` 与 `D:\repositories\dsh-memory`
201
+ * 是同一个目录,但 `project:<路径>` 是字符串键、落盘文件名是它的 SHA-1 —— 两种写法会
202
+ * 变成两个 scope 文件。用 `memory_save({ path })` 写进去的记忆,同一个工作区里的会话
203
+ * (键来自宿主 `session.header.cwd`,反斜杠形式)再也读不到,而且注入 / 面板里会看到
204
+ * 两个"同名"作用域绝对路径。
205
+ *
206
+ * 只做**绝不可能指向另一个目录**的改写:
207
+ * - Windows 绝对路径走 `win32.resolve`:分隔符统一成 `\`、消掉 `.`/`..` 与末尾分隔符,
208
+ * 盘符统一大写(`d:\x` → `D:\x`);
209
+ * - POSIX 绝对路径走 `posix.resolve`(同样消掉 `.`/`..` 与末尾分隔符);
210
+ * - 非绝对路径**原样返回**(不能拿 process.cwd() 去猜:那是 DSH 的 profile 目录);
211
+ * - 大小写除盘符外**不动** —— 既有 scope 文件是按原始大小写做 SHA-1 的,擅自小写会让
212
+ * 旧数据"消失"。只是大小写不同的重复键由 `projectScopeIdentity` 识别、由 provider
213
+ * 在发现作用域时合并。
214
+ */
215
+ export function canonicalWorkspacePath(value ) {
216
+ const trimmed = value.trim()
217
+ if (WINDOWS_ABSOLUTE.test(trimmed)) {
218
+ const resolved = win32.resolve(trimmed)
219
+ const driveFixed = DRIVE_PATH.test(resolved)
220
+ ? resolved.replace(/^([a-z]):/u, (_, drive ) => `${drive.toUpperCase()}:`)
221
+ : resolved
222
+ return stripTrailingSeparators(driveFixed, win32)
223
+ }
224
+ if (POSIX_ABSOLUTE.test(trimmed)) return stripTrailingSeparators(posix.resolve(trimmed), posix)
225
+ return trimmed.replace(/[\\/]+$/u, '') || trimmed
226
+ }
227
+
228
+ function stripTrailingSeparators(path , impl ) {
229
+ // 根(`D:\` / `/`)本身就是一个合法的 scope 路径,不能剥成 `D:`。
230
+ if (path === impl.parse(path).root) return path
231
+ const stripped = path.replace(/[\\/]+$/u, '')
232
+ return stripped === '' ? path : stripped
233
+ }
234
+
235
+ /**
236
+ * 判断两个项目键是否指向"同一个目录":规范形之后,Windows 盘符路径再折叠大小写
237
+ * (Windows 文件系统不区分大小写)。POSIX 路径保留大小写 —— 在 Linux 上
238
+ * `/Users/a` 与 `/users/a` 是两个不同的目录。
239
+ */
240
+ export function projectScopeIdentity(path ) {
241
+ const canonical = canonicalWorkspacePath(path)
242
+ return WINDOWS_ABSOLUTE.test(canonical) ? canonical.toLowerCase() : canonical
243
+ }
244
+
188
245
  // ------------------------------------------------------------------ 当前会话 / 当前项目
189
246
 
190
247
  /** 宿主 agent 上我们真正会碰到的那几个字段(其余一律不碰)。 */
@@ -235,7 +292,10 @@ export function resolveCurrentScopes(agent , opts
235
292
  // 而 DSH 服务进程的 process.cwd() 是**profile 目录**(~/.dsh/profiles/<name>),
236
293
  // 与工作区无关 —— 0.5.5 及以前把 `project:${process.cwd()}` 当成"配置"先传进来,
237
294
  // 结果所有项目的项目级记忆都挤进同一个桶,`project:` 这个作用域等于失效。
238
- const project = `project:${cwd ?? stripProjectPrefix(opts.projectScope) ?? process.cwd()}`
295
+ // 路径再过一遍 canonicalWorkspacePath:宿主若给出 `D:/x` / 带尾部分隔符的写法,
296
+ // 与 path 参数、显式 project:<路径> 落到同一个 scope(0.11.1)。
297
+ const projectPath = cwd ?? stripProjectPrefix(opts.projectScope) ?? process.cwd()
298
+ const project = `project:${canonicalWorkspacePath(projectPath)}`
239
299
  return sessionId !== undefined ? { session: `session:${sessionId}`, project } : { project }
240
300
  }
241
301
 
@@ -12,7 +12,7 @@
12
12
  */
13
13
 
14
14
  import { isAbsolute, resolve } from 'node:path'
15
- import { normalizeScopeInput, resolveScopeRef } from '../provider/scope.js'
15
+ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '../provider/scope.js'
16
16
 
17
17
  /** Shape each tool shares: JSON-schema parameters + canonical output value. */
18
18
 
@@ -163,15 +163,15 @@ function resolveScope(
163
163
 
164
164
  /**
165
165
  * `path` → 绝对工作区路径。相对路径按会话 cwd 解析(拿不到就按进程 cwd),
166
- * 去掉末尾分隔符 —— 同一个目录必须只有一种写法,否则 project:<路径> 会分叉。
166
+ * 再走 `canonicalWorkspacePath` 统一写法 —— 同一个目录必须只有一种 scope 键,
167
+ * 否则 `project:<路径>` 会分叉(`D:/x` 与 `D:\x` 曾是两个 scope,见 0.11.1)。
167
168
  */
168
169
  function resolveWorkspacePath(raw , agent ) {
169
170
  const value = raw.trim()
170
171
  if (value === '') throw new MemoryToolError('PATH_INVALID', 'path 不能为空')
171
172
  const cwd = (agent )?.session?.header?.cwd
172
173
  const base = typeof cwd === 'string' && cwd.length > 0 ? cwd : process.cwd()
173
- const full = isAbsolute(value) ? value : resolve(base, value)
174
- return full.replace(/[\\/]+$/u, '') || full
174
+ return canonicalWorkspacePath(isAbsolute(value) ? value : resolve(base, value))
175
175
  }
176
176
 
177
177
  export function memorySaveTool(opts ) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "DeepSeek Harness 记忆系统(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",