@restregular/dsh-memory 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -320,6 +320,14 @@ tools/build-single-package.mjs 构建(产物契约检查 + 可选加载验证)
320
320
 
321
321
  ## 版本
322
322
 
323
+ - **0.8.0** —— 「服务 → 维护」新增**重建全部向量**:
324
+ - 一键把所有记录的向量(内存 + 磁盘)作废、重新排队并按当前模型重嵌,用于换过模型或怀疑向量与内容对不上时修复;只显示在两个条件都满足时(配置了后端且启用),两步确认,后台执行、不阻塞请求。
325
+ - 进度看「待嵌入向量」:面板在有待嵌入时每 **1.5s** 自动刷新列表徽标与计数(上限 300 次);从其它标签切回「记录」也会立即刷新一次。
326
+ - 重建期间向量检索暂时只用词法,完成一条恢复一条。
327
+ - **0.7.3** —— 修复「编辑一条记忆后一直显示待嵌入」:
328
+ - 面板 `/update` 改内容时只删了内存里的向量、**没有把 `.vec` 标脏**,重启后旧向量仍在磁盘上,会被当成“已嵌入”继续用(而且内容已经变了)。现在旧向量在内存与磁盘上一并作废。
329
+ - 编辑后**立即重建这一条**的向量(不再等 60s 的定时回填);重建失败才留在队列里由重试兜底。
330
+ - 面板在有「待嵌入」时每 2s 自动刷新列表与统计(最多 30 次),徽标与计数会自己归零,不用切标签/重进面板。
323
331
  - **0.7.2** —— Star / issue 那行改为居中展示。
324
332
  - **0.7.1** —— 「服务」页底部加了 Star / issue 入口:「觉得好用?⭐ 去 GitHub 点个 Star · 💬 反馈建议 / 提 issue」,两段都是外链(仓库主页 / 新建 issue)。
325
333
  - **0.7.0** —— 作用域语义:**`path` 指定工作区,`scope` 用作作用域显示名(别名)**。
package/lib/client.js CHANGED
@@ -898,6 +898,9 @@ window.__ModuleLoader__.load({
898
898
  )
899
899
  }
900
900
 
901
+ /** 待嵌入自动刷新:最多 300 次 × 1.5s(后端挂着时不无限轮询)。 */
902
+ const PENDING_POLL_LIMIT = 300
903
+
901
904
  function MemoryPanel() {
902
905
  const [records, setRecords] = React.useState([])
903
906
  const [scopes, setScopes] = React.useState([])
@@ -911,6 +914,7 @@ window.__ModuleLoader__.load({
911
914
  const [loading, setLoading] = React.useState(true)
912
915
  const [error, setError] = React.useState('')
913
916
  const [tab, setTab] = React.useState('data')
917
+ const [pendingTick, setPendingTick] = React.useState(0)
914
918
  const [creating, setCreating] = React.useState(false)
915
919
 
916
920
  const load = async (query, scopeF) => {
@@ -970,8 +974,8 @@ window.__ModuleLoader__.load({
970
974
  }
971
975
 
972
976
  /**
973
- * 维护动作:卸载向量服务 / 清空记忆数据。两者都不可撤销,所以都走两步确认
974
- * (dangerAsk 记住当前等确认的那一项,第二次点击才真的发请求)。
977
+ * 维护动作:卸载向量服务 / 清空记忆数据 / 重建全部向量。前两者不可撤销,重建代价高,
978
+ * 都走两步确认(dangerAsk 记住当前等确认的那一项,第二次点击才真的发请求)。
975
979
  */
976
980
  const maintenanceAction = async (which) => {
977
981
  if (dangerAsk !== which) { setDangerAsk(which); setEmbedNotice(''); return }
@@ -980,8 +984,10 @@ window.__ModuleLoader__.load({
980
984
  try {
981
985
  const value = which === 'uninstall'
982
986
  ? await api('embed/uninstall', {})
983
- // 服务端要求显式 confirm:"delete",避免任何一次误触就清库
984
- : await api('data/wipe', { confirm: 'delete' })
987
+ : which === 'reindex'
988
+ ? await api('embed/reindex', {})
989
+ // 服务端要求显式 confirm:"delete",避免任何一次误触就清库
990
+ : await api('data/wipe', { confirm: 'delete' })
985
991
  setEmbedServer(value.embedServer ? { ...value.embedServer } : value)
986
992
  if (which === 'uninstall') {
987
993
  setEmbedNotice(value.removed
@@ -989,6 +995,9 @@ window.__ModuleLoader__.load({
989
995
  : value.reason === 'EXTERNAL_BACKEND'
990
996
  ? '当前后端不在本插件管理的目录里(是你自己装的),没有删除任何东西。'
991
997
  : '没有找到本插件安装的向量服务文件。')
998
+ } else if (which === 'reindex') {
999
+ setPendingTick(0)
1000
+ setEmbedNotice(`已开始重建 ${value.records ?? 0} 条的向量;「待嵌入向量」会逐步下降,期间检索暂时只用词法。`)
992
1001
  } else {
993
1002
  setEmbedNotice(`已清空 ${value.removed ?? 0} 条记忆(${(value.scopes ?? []).length} 个作用域)。`)
994
1003
  }
@@ -1021,6 +1030,17 @@ window.__ModuleLoader__.load({
1021
1030
 
1022
1031
  const total = scopes.reduce((n, s) => n + s.records, 0)
1023
1032
  const pending = scopes.reduce((n, s) => n + s.pendingEmbeds, 0)
1033
+ // 有"待嵌入"时自动刷新:编辑后向量重建需要一两秒,列表与统计不能一直停在旧状态,
1034
+ // 等用户切标签/重进面板才知道好了。(有上限,后端挂着时不会无限轮询。)
1035
+ React.useEffect(() => {
1036
+ if (pending === 0 || pendingTick >= PENDING_POLL_LIMIT) return undefined
1037
+ if (!configured || !vectorEnabled) return undefined
1038
+ const timer = setTimeout(() => {
1039
+ setPendingTick((n) => n + 1)
1040
+ load()
1041
+ }, 1500)
1042
+ return () => clearTimeout(timer)
1043
+ }, [pendingTick, pending])
1024
1044
  // 服务端 /status 给的 scope → label 映射(会话标题、project 的 cwd 只有服务端知道)
1025
1045
  const labels = {}
1026
1046
  for (const s of scopes) if (s && s.scope && typeof s.label === 'string') labels[s.scope] = s.label
@@ -1136,6 +1156,8 @@ window.__ModuleLoader__.load({
1136
1156
  onInstall: (override) => embedAction('install', override),
1137
1157
  }),
1138
1158
  )
1159
+ // 重建向量只在"配置了后端且启用"时有意义(maintenanceCard 在 configured 声明之前构建)。
1160
+ const canReindex = Boolean(embedServer && embedServer.enabled && (embedServer.configured === undefined ? Boolean(embedServer.baseUrl) : embedServer.configured))
1139
1161
  // 维护区:DSH 卸载插件时不会给插件任何提问机会(就是 pnpm remove + 去掉
1140
1162
  // bundles),所以"要不要留向量服务 / 要不要留记忆数据"只能在这里、卸载之前问。
1141
1163
  const maintenanceCard = maintenance
@@ -1153,6 +1175,17 @@ window.__ModuleLoader__.load({
1153
1175
  : h('button', { key: 'ask', disabled: embedBusy, onClick: () => maintenanceAction('uninstall') }, '卸载向量服务'))
1154
1176
  : h('span', { className: 'muted' }, '未安装'),
1155
1177
  ),
1178
+ h('div', { className: 'maint-row' },
1179
+ h('span', { className: 'grow' }, `向量索引:${maintenance.records} 条`),
1180
+ canReindex
1181
+ ? (maintenance.records > 0
1182
+ ? (dangerAsk === 'reindex'
1183
+ ? [h('button', { key: 'ok', className: 'danger', disabled: embedBusy, onClick: () => maintenanceAction('reindex') }, `确认重建 ${maintenance.records} 条的向量`),
1184
+ h('button', { key: 'no', disabled: embedBusy, onClick: () => setDangerAsk('') }, '取消')]
1185
+ : h('button', { key: 'ask', disabled: embedBusy, onClick: () => maintenanceAction('reindex') }, '重建全部向量'))
1186
+ : h('span', { className: 'muted' }, '无'))
1187
+ : h('span', { className: 'muted' }, '向量未启用'),
1188
+ ),
1156
1189
  h('div', { className: 'maint-row' },
1157
1190
  h('span', { className: 'grow' }, `记忆数据:${maintenance.records} 条`),
1158
1191
  maintenance.storeDir ? h('span', { className: 'muted path', title: maintenance.storeDir }, maintenance.storeDir) : null,
@@ -1190,13 +1223,13 @@ window.__ModuleLoader__.load({
1190
1223
  ? h(CreateForm, {
1191
1224
  scopes,
1192
1225
  onCancel: () => setCreating(false),
1193
- onCreated: () => { setCreating(false); load('', '') },
1226
+ onCreated: () => { setCreating(false); setPendingTick(0); load('', '') },
1194
1227
  })
1195
1228
  : null
1196
1229
  const listBody = !loading && !error && records.length === 0
1197
1230
  ? h('div', { className: 'empty' }, filtering ? '没有匹配的记忆' : '还没有记忆')
1198
1231
  : h('div', { className: 'list' },
1199
- records.map((rec) => h(RecordCard, { key: rec.id, rec, vectorOn: configured && vectorEnabled, labels: labels, onSaved: () => load(), onDeleted: () => load() })))
1232
+ records.map((rec) => h(RecordCard, { key: rec.id, rec, vectorOn: configured && vectorEnabled, labels: labels, onSaved: () => { setPendingTick(0); load() }, onDeleted: () => { setPendingTick(0); load() } })))
1200
1233
 
1201
1234
  // 服务页底部:一句号召 + 两个外链(Star / issue)。放在内容最后,不打扰上面的状态卡。
1202
1235
  const footer = h('div', { className: 'footer' },
@@ -1218,7 +1251,7 @@ window.__ModuleLoader__.load({
1218
1251
  return h('div', { className: 'memp' },
1219
1252
  h('div', { className: 'tabs' },
1220
1253
  h('button', { className: 'tab' + (tab === 'records' ? ' on' : ''), onClick: () => setTab('records') }, '服务'),
1221
- h('button', { className: 'tab' + (tab === 'data' ? ' on' : ''), onClick: () => setTab('data') }, '记录'),
1254
+ h('button', { className: 'tab' + (tab === 'data' ? ' on' : ''), onClick: () => { if (tab !== 'data') load(); setTab('data') } }, '记录'),
1222
1255
  h('button', { className: 'tab' + (tab === 'settings' ? ' on' : ''), onClick: () => setTab('settings') }, '设置'),
1223
1256
  ),
1224
1257
  tab === 'settings' ? h(SettingsTab, {}) : tab === 'data' ? dataBody : overviewBody,
package/lib/panel.js CHANGED
@@ -363,6 +363,15 @@ async function handle(ctx, routePath, req, res) {
363
363
  writeJson(res, { ok: true, value: { ...out, ...(await memory.embedServerStatus()) } })
364
364
  return
365
365
  }
366
+ if (method === 'POST' && path === '/embed/reindex') {
367
+ if (typeof memory.reindexAll !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供向量重建接口(请升级 @restregular/dsh-memory)')
368
+ // 同步部分只作废旧向量 + 排队,真正的重嵌在后台跑,不阻塞请求;进度看 /status 的待嵌入计数。
369
+ const result = memory.reindexAll() ?? {}
370
+ const total = typeof result.total === 'number' ? result.total : 0
371
+ console.log(`[dsh-memory-panel] 开始重建全部向量:${total} 条`)
372
+ writeJson(res, { ok: true, value: { scheduled: true, records: total } })
373
+ return
374
+ }
366
375
  if (method === 'POST' && path === '/data/wipe') {
367
376
  if (typeof memory.wipeAllRecords !== 'function') throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供数据清理接口(请升级 @restregular/dsh-memory)')
368
377
  const body = await readJsonBody(req)
@@ -422,14 +431,18 @@ async function handle(ctx, routePath, req, res) {
422
431
  }
423
432
  if (!target) throw new ApiError(404, 'RECORD_NOT_FOUND', `no record ${id}`)
424
433
  const { s, rec } = target
434
+ let reindex = false
425
435
  if (body.content !== undefined) {
426
436
  const content = String(body.content)
427
437
  if (!content.trim()) throw new ApiError(400, 'CONTENT_EMPTY', 'content 不能为空')
428
438
  if (content !== rec.content) {
429
439
  rec.content = content
430
- // 旧向量作废,排队重新嵌入(provider 的维护循环负责回填)
440
+ // 旧向量作废:内存 + 磁盘一起丢掉(vectorsDirty),再排队重建。
441
+ // 只删内存不标 dirty 的话,重启后 load 会看到旧向量、把它当成"已嵌入"。
431
442
  s.vectors.delete(id)
443
+ s.vectorsDirty = true
432
444
  s.embedPending.add(id)
445
+ reindex = true
433
446
  }
434
447
  }
435
448
  if (body.kind !== undefined) rec.kind = String(body.kind)
@@ -439,6 +452,10 @@ async function handle(ctx, routePath, req, res) {
439
452
  rec.updatedAt = Date.now()
440
453
  s.dirty = true
441
454
  store.scheduleFlush()
455
+ // 立即重建向量(不等 60s 的定时回填);失败就留在 pending 里由重试兜底。
456
+ if (reindex && typeof memory.reindexRecord === 'function') {
457
+ void memory.reindexRecord(rec.scope, id).catch(() => {})
458
+ }
442
459
  writeJson(res, { ok: true, value: { record: wireRecord(rec, s) } })
443
460
  return
444
461
  }
@@ -150,6 +150,26 @@ export class CordisMemoryService extends Service {
150
150
  return this.impl.listSync(input)
151
151
  }
152
152
 
153
+ /** 面板编辑后立即重建这一条的向量。 */
154
+ reindexRecord(scope , id ) {
155
+ return this.impl.reindexRecord(scope, id)
156
+ }
157
+
158
+ /** 维护:重建全部向量(作废旧向量并重新嵌入)。 */
159
+ reindexAll() {
160
+ return this.impl.reindexAll()
161
+ }
162
+
163
+ /** 维护:作废全部向量并按当前模型后台重嵌。 */
164
+ reindexAll() {
165
+ return this.impl.reindexAll()
166
+ }
167
+
168
+ /** 作用域别名(没有则 undefined)。 */
169
+ scopeName(scope ) {
170
+ return this.impl.scopeName(scope)
171
+ }
172
+
153
173
  /** 注入设置(面板「设置」标签页读它)。 */
154
174
  injectSettings() {
155
175
  return this.impl.injectSettings()
@@ -1274,6 +1274,51 @@ export class LocalMemoryService {
1274
1274
  return done
1275
1275
  }
1276
1276
 
1277
+ /**
1278
+ * 编辑之后立即重建**这一条**的向量,不等 60s 的回填窗口。
1279
+ * 旧向量同时从内存与磁盘作废(vectorsDirty),失败则留在 pending 里由重试兜底 ——
1280
+ * 绝不能让"新内容 + 旧向量"在重启后被当成已嵌入。
1281
+ */
1282
+ async reindexRecord(scope , id ) {
1283
+ if (!this.cfg.vector.enabled || !this.cfg.vector.configured) return false
1284
+ const s = this.store.peek(scope)
1285
+ const record = s?.records.get(id)
1286
+ if (!s || !record) return false
1287
+ s.vectors.delete(id)
1288
+ s.vectorsDirty = true
1289
+ s.embedPending.add(id)
1290
+ try {
1291
+ await this.embedRecord(record)
1292
+ } catch { /* 失败留给重试定时器 */ }
1293
+ if (!s.vectors.has(id)) return false
1294
+ s.embedPending.delete(id)
1295
+ this.store.scheduleFlush()
1296
+ return true
1297
+ }
1298
+
1299
+ /**
1300
+ * 作废全部向量并按当前模型重新嵌入。给"换模型残留了旧向量 / 怀疑向量有问题"用:
1301
+ * 同步部分只清空 + 排队,真正的重嵌在后台跑(别让 HTTP 等几分钟)。
1302
+ * 返回排队条数;进度由面板的「待嵌入」计数与自动刷新体现。
1303
+ */
1304
+ reindexAll() {
1305
+ if (!this.cfg.vector.enabled || !this.cfg.vector.configured) return { total: 0, queued: this.pendingEmbedCount }
1306
+ this.discoverScopes()
1307
+ let total = 0
1308
+ for (const s of this.store.allScopes()) {
1309
+ for (const id of s.records.keys()) {
1310
+ s.vectors.delete(id)
1311
+ s.embedPending.add(id)
1312
+ total += 1
1313
+ }
1314
+ s.vectorsDirty = true
1315
+ s.dirty = true
1316
+ }
1317
+ this.store.scheduleFlush()
1318
+ void this.backfillAll({ throttleMs: 50 }).catch(() => { /* 失败留给 60s 重试 */ })
1319
+ return { total, queued: this.pendingEmbedCount }
1320
+ }
1321
+
1277
1322
  /**
1278
1323
  * First-fill: embed the ENTIRE backlog (unlike backfillEmbeddings' single
1279
1324
  * batch per scope), in throttled batches so a big import does not hammer
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.7.2",
3
+ "version": "0.8.0",
4
4
  "description": "DeepSeek Harness 本地长期记忆(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 四个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",