dsh-memory-domains 0.2.4 → 0.2.6

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/client.js CHANGED
@@ -181,6 +181,14 @@ window.__ModuleLoader__.load({
181
181
 
182
182
  /* ------------------------------------------------------------ 工具栏 */
183
183
 
184
+ function mkBtn(cls, text, title, fn) {
185
+ var b = document.createElement('button');
186
+ b.className = cls; b.type = 'button'; b.textContent = text;
187
+ if (title) b.title = title;
188
+ b.addEventListener('click', fn);
189
+ return b;
190
+ }
191
+
184
192
  function syncBar() {
185
193
  barEl.innerHTML = '';
186
194
  if (view.name === 'wall') {
@@ -196,12 +204,7 @@ window.__ModuleLoader__.load({
196
204
  barEl.appendChild(cnt);
197
205
  return;
198
206
  }
199
- var back = document.createElement('button');
200
- back.className = 'dshmb-act';
201
- back.type = 'button';
202
- back.textContent = '← 返回';
203
- back.addEventListener('click', function () { view = { name: 'wall' }; pickState = null; syncBar(); renderBody(); });
204
- barEl.appendChild(back);
207
+ barEl.appendChild(mkBtn('dshmb-act', '← 返回', '', function () { view = { name: 'wall' }; pickState = null; syncBar(); renderBody(); }));
205
208
 
206
209
  var ttl = document.createElement('span');
207
210
  ttl.className = 'dshmb-vtitle';
@@ -218,20 +221,11 @@ window.__ModuleLoader__.load({
218
221
  barEl.appendChild(ttl);
219
222
 
220
223
  if (view.name === 'domain') {
221
- var bEdit = document.createElement('button');
222
- bEdit.className = 'dshmb-act';
223
- bEdit.type = 'button';
224
- bEdit.textContent = '✎ 领域';
225
- bEdit.title = '编辑领域名称/描述';
226
- bEdit.addEventListener('click', function () { showDomainEdit(view.slug); });
227
- barEl.appendChild(bEdit);
228
- var bDisc = document.createElement('button');
229
- bDisc.className = 'dshmb-act';
230
- bDisc.type = 'button';
231
- bDisc.textContent = '🔍 发现';
232
- bDisc.title = '按领域画像搜 GitHub 相关项目(AI 蒸馏检索词 → GitHub 搜索,约 10-30 秒)';
233
- bDisc.addEventListener('click', function () { runDiscover(view.slug); });
234
- barEl.appendChild(bDisc);
224
+ barEl.appendChild(mkBtn('dshmb-act', '✎ 领域', '编辑领域名称/描述', function () {
225
+ var dd = domainBySlug(view.slug);
226
+ if (dd) showDomainForm(dd); // 领域可能已被删——null 会误开成"新建"表单
227
+ }));
228
+ barEl.appendChild(mkBtn('dshmb-act', '🔍 发现', '按领域画像搜 GitHub 相关项目(AI 蒸馏检索词 → GitHub 搜索,约 10-30 秒)', function () { runDiscover(view.slug); }));
235
229
  }
236
230
  if (view.name === 'session') {
237
231
  var bRevWrap = document.createElement('span');
@@ -244,12 +238,7 @@ window.__ModuleLoader__.load({
244
238
  barEl.appendChild(bRevWrap);
245
239
  }
246
240
  if (view.name === 'domain' || view.name === 'global') {
247
- var bAdd = document.createElement('button');
248
- bAdd.className = 'dshmb-act';
249
- bAdd.type = 'button';
250
- bAdd.textContent = '+ 添加';
251
- bAdd.addEventListener('click', function () { showCreateForm(); });
252
- barEl.appendChild(bAdd);
241
+ barEl.appendChild(mkBtn('dshmb-act', '+ 添加', '', function () { showCreateForm(); }));
253
242
  }
254
243
  }
255
244
 
@@ -326,25 +315,35 @@ window.__ModuleLoader__.load({
326
315
 
327
316
  /* ---- 领域 / 全局 / 会话来源 详情 ---- */
328
317
 
329
- // innerHTML 重写会杀掉表单/发现卡——先摘出瞬态节点,写完插回最前
330
- function setBodyHtml(html) {
331
- var transient = bodyEl.querySelector('.dshmb-form, .dshmb-disc');
332
- bodyEl.innerHTML = html;
333
- if (transient) bodyEl.insertBefore(transient, bodyEl.firstChild);
318
+ // 统一"loading tip → fetch → 替换为内容/错误"的异步渲染。
319
+ // 只 replaceWith tip 节点,绝不重写 container.innerHTML——瞬态 UI
320
+ // (新建/编辑表单、发现结果卡)天然存活,不需要摘节点再插回的补丁;
321
+ // tip 若已被清掉(视图切换),replaceWith 是 no-op,旧请求静默失效。
322
+ function fetchInto(container, url, okHtml, failMsg) {
323
+ var tip = document.createElement('div');
324
+ tip.className = 'dshmb-tip';
325
+ tip.textContent = '加载中…';
326
+ container.appendChild(tip);
327
+ api(url).then(function (j) {
328
+ var box = document.createElement('div');
329
+ box.innerHTML = (j && j.ok) ? okHtml(j)
330
+ : '<div class="dshmb-tip">加载失败:' + esc((j && j.error) || '接口无响应') + '</div>';
331
+ tip.replaceWith(box);
332
+ }).catch(function () { tip.textContent = failMsg || '无法连接插件后端。'; });
334
333
  }
335
334
 
336
335
  function renderMemories(loc) {
337
336
  var isGlobal = loc.scope === 'global';
338
- bodyEl.innerHTML = '<div class="dshmb-tip">加载中…</div>';
339
- var url = API + '/memories?scope=' + loc.scope + (loc.domain ? '&domain=' + encodeURIComponent(loc.domain) : '') + '&archived=1';
340
- api(url).then(function (j) {
341
- if (!j.ok) { setBodyHtml('<div class="dshmb-tip">加载失败:' + esc(j.error || '') + '</div>'); return; }
342
- var entries = j.entries || [];
343
- setBodyHtml(entries.length ? entries.map(function (e) { return memCardHtml(e, loc); }).join('')
344
- : '<div class="dshmb-tip">' + (isGlobal
345
- ? '全局记忆库是空的——领域记忆里跨领域通用的条目,点「升级全局」进来;或点「+添加」手动记。'
346
- : '这个领域还没有记忆。点「+添加」手动记,或从会话「整理」后入库到这里。') + '</div>');
347
- }).catch(function () { setBodyHtml('<div class="dshmb-tip">无法连接插件后端——确认 dsh-memory-domains 已启用。</div>'); });
337
+ bodyEl.innerHTML = '';
338
+ fetchInto(bodyEl, API + '/memories?scope=' + loc.scope + (loc.domain ? '&domain=' + encodeURIComponent(loc.domain) : '') + '&archived=1',
339
+ function (j) {
340
+ var entries = j.entries || [];
341
+ return entries.length ? entries.map(function (e) { return memCardHtml(e, loc); }).join('')
342
+ : '<div class="dshmb-tip">' + (isGlobal
343
+ ? '全局记忆库是空的——领域记忆里跨领域通用的条目,点「升级全局」进来;或点「+添加」手动记。'
344
+ : '这个领域还没有记忆。点「+添加」手动记,或从会话「整理」后入库到这里。') + '</div>';
345
+ },
346
+ '无法连接插件后端——确认 dsh-memory-domains 已启用。');
348
347
  }
349
348
 
350
349
  function memCardHtml(e, loc) {
@@ -357,14 +356,13 @@ window.__ModuleLoader__.load({
357
356
  if (e.scope === 'domain' && e.status !== 'archived') {
358
357
  ops += '<button class="dshmb-mini" data-op="promote" data-id="' + esc(e.id) + '" data-domain="' + esc(e.domain) + '">升级全局</button>';
359
358
  }
360
- ops += '<button class="dshmb-mini" data-op="' + (e.status === 'archived' ? 'unarchive' : 'archive') + '" data-id="' + esc(e.id) +
361
- '" data-scope="' + esc(e.scope || loc.scope) + '" data-domain="' + esc(e.domain || loc.domain || '') + '">' +
359
+ // scope/domain 定位属性四个操作按钮共用,拼一次复用
360
+ var sd = ' data-scope="' + esc(e.scope || loc.scope) + '" data-domain="' + esc(e.domain || loc.domain || '') + '"';
361
+ ops += '<button class="dshmb-mini" data-op="' + (e.status === 'archived' ? 'unarchive' : 'archive') + '" data-id="' + esc(e.id) + '"' + sd + '">' +
362
362
  (e.status === 'archived' ? '恢复' : '归档') + '</button>';
363
- ops += '<button class="dshmb-mini" data-op="prio" data-id="' + esc(e.id) + '" data-priority="' + (e.priority === 'high' ? 'high' : 'normal') +
364
- '" data-scope="' + esc(e.scope || loc.scope) + '" data-domain="' + esc(e.domain || loc.domain || '') + '">' +
363
+ ops += '<button class="dshmb-mini" data-op="prio" data-id="' + esc(e.id) + '" data-priority="' + (e.priority === 'high' ? 'high' : 'normal') + '"' + sd + '">' +
365
364
  (e.priority === 'high' ? '★高→普通' : '普通→★高') + '</button>';
366
- ops += '<button class="dshmb-mini" data-op="del" data-id="' + esc(e.id) +
367
- '" data-scope="' + esc(e.scope || loc.scope) + '" data-domain="' + esc(e.domain || loc.domain || '') + '">删除</button>';
365
+ ops += '<button class="dshmb-mini" data-op="del" data-id="' + esc(e.id) + '"' + sd + '">删除</button>';
368
366
  return '<div class="dshmb-card' + (e.status === 'archived' ? ' arch' : '') + '">' +
369
367
  '<div class="dshmb-card-top">' + badge + '<span class="dshmb-ctitle">' + esc(e.title) + '</span></div>' +
370
368
  '<div class="dshmb-content">' + esc(e.content) + '</div>' +
@@ -385,25 +383,19 @@ window.__ModuleLoader__.load({
385
383
  renderCandidatesInto(bodyEl);
386
384
  return;
387
385
  }
388
- bodyEl.innerHTML = tabs + '<div class="dshmb-tip">加载中…</div>';
389
- api(API + '/memories?scope=all&session=' + encodeURIComponent(view.id) + '&archived=1').then(function (j) {
390
- var tip = bodyEl.querySelector('.dshmb-tip');
391
- var box = document.createElement('div');
392
- if (!j.ok) { box.innerHTML = '<div class="dshmb-tip">加载失败:' + esc(j.error || '') + '</div>'; }
393
- else {
386
+ bodyEl.innerHTML = tabs;
387
+ fetchInto(bodyEl, API + '/memories?scope=all&session=' + encodeURIComponent(view.id) + '&archived=1',
388
+ function (j) {
394
389
  var entries = j.entries || [];
395
- box.innerHTML = entries.length ? entries.map(function (e) { return memCardHtml(e, { scope: e.scope, domain: e.domain }); }).join('')
390
+ return entries.length ? entries.map(function (e) { return memCardHtml(e, { scope: e.scope, domain: e.domain }); }).join('')
396
391
  : '<div class="dshmb-tip">这个会话还没有沉淀的记忆。点上方「整理记忆」让 AI 回顾起草,审过后进领域或全局。</div>';
397
- }
398
- if (tip) tip.replaceWith(box); else bodyEl.appendChild(box);
399
- }).catch(function () {
400
- var tip = bodyEl.querySelector('.dshmb-tip');
401
- if (tip) tip.textContent = '无法连接插件后端——确认 dsh-memory-domains 已启用。';
402
- });
392
+ },
393
+ '无法连接插件后端——确认 dsh-memory-domains 已启用。');
403
394
  }
404
395
 
405
396
  function candCardHtml(e) {
406
- var sug = e.domain && domainBySlug(e.domain) ? domainBySlug(e.domain).name : '';
397
+ var dd = e.domain ? domainBySlug(e.domain) : null;
398
+ var sug = dd ? dd.name : '';
407
399
  var badge = '<span class="dshmb-badge' + (e.type === 'mistake' ? ' m' : '') + '">' + (TYPE_LABEL[e.type] || e.type) + '·草稿</span>';
408
400
  if (e.domain) badge += '<span class="dshmb-badge d">建议:' + esc(sug || e.domain) + '</span>';
409
401
  if (e.priority === 'high') badge += '<span class="dshmb-badge p">★高</span>';
@@ -436,16 +428,14 @@ window.__ModuleLoader__.load({
436
428
 
437
429
  function renderCandidatesInto(container) {
438
430
  candCache = {};
439
- container.innerHTML += '<div class="dshmb-tip">加载中…</div>';
440
- var tip = container.querySelector('.dshmb-tip');
441
- api(API + '/candidates?session=' + encodeURIComponent(view.id)).then(function (j) {
442
- var box = document.createElement('div');
443
- var entries = (j && j.entries) || [];
444
- entries.forEach(function (e) { candCache[e.id] = e; });
445
- box.innerHTML = entries.length ? entries.map(candCardHtml).join('')
446
- : '<div class="dshmb-tip">没有待审草稿。点「整理记忆」让 AI 回顾这个会话。</div>';
447
- if (tip) tip.replaceWith(box); else container.appendChild(box);
448
- }).catch(function () { if (tip) tip.textContent = '无法连接插件后端。'; });
431
+ fetchInto(container, API + '/candidates?session=' + encodeURIComponent(view.id),
432
+ function (j) {
433
+ var entries = (j && j.entries) || [];
434
+ entries.forEach(function (e) { candCache[e.id] = e; });
435
+ return entries.length ? entries.map(candCardHtml).join('')
436
+ : '<div class="dshmb-tip">没有待审草稿。点「整理记忆」让 AI 回顾这个会话。</div>';
437
+ },
438
+ '无法连接插件后端。');
449
439
  }
450
440
 
451
441
  /* ------------------------------------------------------------ 动作 */
@@ -475,7 +465,7 @@ window.__ModuleLoader__.load({
475
465
  }
476
466
  }).catch(function () {
477
467
  toast('无法连接插件后端——确认 dsh-memory-domains 已启用。');
478
- if (view.name === 'wall') bodyEl.innerHTML = '<div class="dshmb-tip">无法连接插件后端(/memory/api 无响应)。确认 dsh-memory-domains 已启用并重启 DSH。</div>';
468
+ if (view.name === 'wall' && !hasTransientUI()) bodyEl.innerHTML = '<div class="dshmb-tip">无法连接插件后端(/memory/api 无响应)。确认 dsh-memory-domains 已启用并重启 DSH。</div>';
479
469
  });
480
470
  }
481
471
 
@@ -500,17 +490,22 @@ window.__ModuleLoader__.load({
500
490
  }).catch(function () { toast('请求失败'); });
501
491
  }
502
492
 
493
+ // 轮询失败的统一出口:!ok 与 catch 同权(0.2.1/0.2.5 修过的坑——放弃时必须
494
+ // syncBar+renderBody,否则按钮永远卡「整理中」)。返回 true=已安排重试。
495
+ function pollFail(job) {
496
+ pollReview.fails = (pollReview.fails || 0) + 1;
497
+ if (pollReview.fails < 5) { reviewTimer = setTimeout(function () { pollReview(job); }, 2000); return true; }
498
+ pollReview.fails = 0;
499
+ reviewJob = null; reviewSessionId = null;
500
+ syncBar(); renderBody();
501
+ return false;
502
+ }
503
+
503
504
  function pollReview(job) {
504
505
  clearTimeout(reviewTimer);
505
506
  api(API + '/review/status?job=' + encodeURIComponent(job)).then(function (j) {
506
507
  if (!j || !j.ok) {
507
- // job 可能被 TTL 清掉/宿主重启/瞬时抖动——重试 5 次(~10s)再放弃,
508
- // 且放弃时必须 syncBar+renderBody,否则按钮永远卡「整理中」(0.2.1 修过的坑)
509
- pollReview.fails = (pollReview.fails || 0) + 1;
510
- if (pollReview.fails < 5) { reviewTimer = setTimeout(function () { pollReview(job); }, 2000); return; }
511
- pollReview.fails = 0;
512
- reviewJob = null; reviewSessionId = null;
513
- syncBar(); renderBody();
508
+ if (pollFail(job)) return;
514
509
  toast('整理状态丢失(可能宿主重启过)——草稿若已生成请查看待审区');
515
510
  return;
516
511
  }
@@ -526,7 +521,7 @@ window.__ModuleLoader__.load({
526
521
  toast('整理失败:' + (j.error || ''));
527
522
  syncBar(); renderBody();
528
523
  }
529
- }).catch(function () { reviewJob = null; reviewSessionId = null; syncBar(); renderBody(); });
524
+ }).catch(function () { pollFail(job); }); // fetch 抛错与 !ok 同权
530
525
  }
531
526
 
532
527
  function cardOp(op, id, el) {
@@ -565,8 +560,6 @@ window.__ModuleLoader__.load({
565
560
  archive: post(API + '/archive', { scope: scope, domain: dom, id: id, archived: true }),
566
561
  unarchive: post(API + '/archive', { scope: scope, domain: dom, id: id, archived: false }),
567
562
  del: post(API + '/delete', { scope: scope, domain: dom, id: id }),
568
- accept: null,
569
- reject: post(API + '/candidates/reject', { session: view.id, id: id }),
570
563
  };
571
564
  var p = calls[op];
572
565
  if (!p) return;
@@ -581,17 +574,21 @@ window.__ModuleLoader__.load({
581
574
  * 不做持久化——发现结果时效性强(star 数、repo 状态会变),存下来只会误导;
582
575
  * 想留的项目让用户自己 star/clone,插件不做"收藏"功能(那是另一个产品的事)。 */
583
576
 
577
+ var discBusy = false; // 防连点:一次发现 = 一次 LLM 调用 + 5 次 GitHub 搜索
584
578
  function runDiscover(slug) {
585
- if (!slug) return;
579
+ if (!slug || discBusy) return;
580
+ discBusy = true;
586
581
  var box = document.createElement('div');
587
582
  box.className = 'dshmb-card dshmb-disc';
588
583
  box.innerHTML = '<div class="dshmb-tip" style="padding:8px">🔍 AI 正在蒸馏检索词并搜索 GitHub…(约 10-30 秒)</div>';
589
584
  bodyEl.insertBefore(box, bodyEl.firstChild);
590
585
  post(API + '/discover', { domain: slug }).then(function (j) {
586
+ discBusy = false;
591
587
  if (view.name !== 'domain' || view.slug !== slug) { box.remove(); return; }
592
588
  if (!j.ok) { box.innerHTML = '<div class="dshmb-tip" style="padding:8px">发现失败:' + esc(j.error || '') + '</div>'; return; }
593
589
  box.innerHTML = discoverHtml(j);
594
590
  }).catch(function () {
591
+ discBusy = false;
595
592
  if (box.parentNode) box.innerHTML = '<div class="dshmb-tip" style="padding:8px">请求失败</div>';
596
593
  });
597
594
  }
@@ -660,9 +657,26 @@ window.__ModuleLoader__.load({
660
657
  };
661
658
  }
662
659
 
663
- function showDomainEdit(slug) {
664
- var d = domainBySlug(slug);
665
- if (d) showDomainForm(d);
660
+ // 类型/优先级 chip 组:showCreateForm 与 showCandidateForm 共用。
661
+ // sel = { t, pri } 由调用方持有,wireChips 负责点击互斥高亮。
662
+ function chipsHtml(sel) {
663
+ return '<div class="dshmb-types">' +
664
+ ['mistake', 'fact', 'skill', 'pref'].map(function (t) {
665
+ return '<span class="dshmb-tchip' + (t === sel.t ? ' on' : '') + '" data-t="' + t + '">' + (TYPE_LABEL[t] || t) + '</span>';
666
+ }).join('') + '</div>' +
667
+ '<div class="dshmb-types" style="margin-top:0"><span style="font-size:11px;align-self:center">优先级</span>' +
668
+ '<span class="dshmb-tchip' + (sel.pri === 'high' ? ' on' : '') + '" data-pri="high">★高</span>' +
669
+ '<span class="dshmb-tchip' + (sel.pri !== 'high' ? ' on' : '') + '" data-pri="normal">普通</span></div>';
670
+ }
671
+ function wireChips(div, sel) {
672
+ div.querySelectorAll('.dshmb-tchip').forEach(function (chip) {
673
+ chip.addEventListener('click', function () {
674
+ var k = chip.dataset.t ? 't' : chip.dataset.pri ? 'pri' : null;
675
+ if (!k) return;
676
+ sel[k] = chip.dataset[k];
677
+ div.querySelectorAll('[data-' + k + ']').forEach(function (c) { c.classList.toggle('on', c === chip); });
678
+ });
679
+ });
666
680
  }
667
681
 
668
682
  /* ---- 手动添加记忆 ---- */
@@ -672,32 +686,15 @@ window.__ModuleLoader__.load({
672
686
  if (!loc) { toast('先打开一个领域或全局库'); return; }
673
687
  var div = document.createElement('div');
674
688
  div.className = 'dshmb-form';
675
- var typeVal = 'mistake';
676
- var priVal = 'normal';
689
+ var sel = { t: 'mistake', pri: 'normal' };
677
690
  div.innerHTML =
678
- '<div class="dshmb-types">' +
679
- ['mistake', 'fact', 'skill', 'pref'].map(function (t, i) {
680
- return '<span class="dshmb-tchip' + (i === 0 ? ' on' : '') + '" data-t="' + t + '">' + (TYPE_LABEL[t] || t) + '</span>';
681
- }).join('') + '</div>' +
682
- '<div class="dshmb-types" style="margin-top:0"><span style="font-size:11px;align-self:center">优先级</span>' +
683
- '<span class="dshmb-tchip' + (priVal === 'high' ? ' on' : '') + '" data-pri="high">★高</span>' +
684
- '<span class="dshmb-tchip on" data-pri="normal">普通</span></div>' +
691
+ chipsHtml(sel) +
685
692
  '<input class="dshmb-f-title" placeholder="标题(一句话)">' +
686
693
  '<textarea class="dshmb-f-content" placeholder="内容(自包含,脱离会话也能看懂)"></textarea>' +
687
694
  '<input class="dshmb-f-ev" placeholder="来源/证据(可选)">' +
688
695
  '<div style="display:flex;gap:8px"><button class="dshmb-act primary dshmb-f-ok">保存</button>' +
689
696
  '<button class="dshmb-act dshmb-f-no">取消</button></div>';
690
- div.querySelectorAll('.dshmb-tchip').forEach(function (chip) {
691
- chip.addEventListener('click', function () {
692
- if (chip.dataset.t) {
693
- typeVal = chip.dataset.t;
694
- div.querySelectorAll('[data-t]').forEach(function (c) { c.classList.toggle('on', c === chip); });
695
- } else if (chip.dataset.pri) {
696
- priVal = chip.dataset.pri;
697
- div.querySelectorAll('[data-pri]').forEach(function (c) { c.classList.toggle('on', c === chip); });
698
- }
699
- });
700
- });
697
+ wireChips(div, sel);
701
698
  bodyEl.insertBefore(div, bodyEl.firstChild);
702
699
  div.querySelector('.dshmb-f-no').onclick = function () { div.remove(); };
703
700
  div.querySelector('.dshmb-f-ok').onclick = function () {
@@ -705,7 +702,7 @@ window.__ModuleLoader__.load({
705
702
  var content = div.querySelector('.dshmb-f-content').value.trim();
706
703
  var evidence = div.querySelector('.dshmb-f-ev').value.trim();
707
704
  if (!title || !content) { toast('标题和内容都要填'); return; }
708
- post(API + '/create', { scope: loc.scope, domain: loc.domain, type: typeVal, title: title, content: content, evidence: evidence, priority: priVal })
705
+ post(API + '/create', { scope: loc.scope, domain: loc.domain, type: sel.t, title: title, content: content, evidence: evidence, priority: sel.pri })
709
706
  .then(function (j) { if (j.ok) { div.remove(); renderBody(); toast('已记下'); } else toast('失败:' + (j.error || '')); })
710
707
  .catch(function () { toast('请求失败'); });
711
708
  };
@@ -720,16 +717,9 @@ window.__ModuleLoader__.load({
720
717
  if (!card) return;
721
718
  var div = document.createElement('div');
722
719
  div.className = 'dshmb-form';
723
- var typeVal = entry.type || 'mistake';
724
- var priVal = entry.priority === 'high' ? 'high' : 'normal';
720
+ var sel = { t: entry.type || 'mistake', pri: entry.priority === 'high' ? 'high' : 'normal' };
725
721
  div.innerHTML =
726
- '<div class="dshmb-types">' +
727
- ['mistake', 'fact', 'skill', 'pref'].map(function (t) {
728
- return '<span class="dshmb-tchip' + (t === typeVal ? ' on' : '') + '" data-t="' + t + '">' + (TYPE_LABEL[t] || t) + '</span>';
729
- }).join('') + '</div>' +
730
- '<div class="dshmb-types" style="margin-top:0"><span style="font-size:11px;align-self:center">优先级</span>' +
731
- '<span class="dshmb-tchip' + (priVal === 'high' ? ' on' : '') + '" data-pri="high">★高</span>' +
732
- '<span class="dshmb-tchip' + (priVal !== 'high' ? ' on' : '') + '" data-pri="normal">普通</span></div>' +
722
+ chipsHtml(sel) +
733
723
  '<input class="dshmb-f-title" placeholder="标题(一句话)" value="' + esc(entry.title || '') + '">' +
734
724
  '<div class="dshmb-meta" style="margin:0">建议领域(slug,可改;留空=入库时再选)</div>' +
735
725
  '<input class="dshmb-f-domain" placeholder="领域 slug(可选)" value="' + esc(entry.domain || '') + '">' +
@@ -737,17 +727,7 @@ window.__ModuleLoader__.load({
737
727
  '<input class="dshmb-f-ev" placeholder="来源/证据(可选,msg#N 或说明)" value="' + esc(entry.evidence || '') + '">' +
738
728
  '<div style="display:flex;gap:8px"><button class="dshmb-act primary dshmb-f-ok">保存修改</button>' +
739
729
  '<button class="dshmb-act dshmb-f-no">取消</button></div>';
740
- div.querySelectorAll('.dshmb-tchip').forEach(function (chip) {
741
- chip.addEventListener('click', function () {
742
- if (chip.dataset.t) {
743
- typeVal = chip.dataset.t;
744
- div.querySelectorAll('[data-t]').forEach(function (c) { c.classList.toggle('on', c === chip); });
745
- } else if (chip.dataset.pri) {
746
- priVal = chip.dataset.pri;
747
- div.querySelectorAll('[data-pri]').forEach(function (c) { c.classList.toggle('on', c === chip); });
748
- }
749
- });
750
- });
730
+ wireChips(div, sel);
751
731
  card.appendChild(div);
752
732
  div.querySelector('.dshmb-f-no').onclick = function () { div.remove(); };
753
733
  div.querySelector('.dshmb-f-ok').onclick = function () {
@@ -756,7 +736,7 @@ window.__ModuleLoader__.load({
756
736
  var content = div.querySelector('.dshmb-f-content').value.trim();
757
737
  var evidence = div.querySelector('.dshmb-f-ev').value.trim();
758
738
  if (!title || !content) { toast('标题和内容都要填'); return; }
759
- post(API + '/candidates/update', { session: view.id, id: entry.id, type: typeVal, title: title, content: content, evidence: evidence, domain: domain, priority: priVal })
739
+ post(API + '/candidates/update', { session: view.id, id: entry.id, type: sel.t, title: title, content: content, evidence: evidence, domain: domain, priority: sel.pri })
760
740
  .then(function (j) { if (j.ok) { renderBody(); toast('已更新'); } else toast('失败:' + (j.error || '')); })
761
741
  .catch(function () { toast('请求失败'); });
762
742
  };
@@ -866,22 +846,12 @@ window.__ModuleLoader__.load({
866
846
  }
867
847
  }
868
848
 
869
- var subs = new Set();
870
- function useOpen() {
871
- var st = React.useState(openFlag);
872
- React.useEffect(function () {
873
- subs.add(st[1]);
874
- st[1](openFlag);
875
- return function () { subs.delete(st[1]); };
876
- }, []);
877
- return st[0];
878
- }
879
-
849
+ // 面板开关状态存在模块级 openFlag;按钮文案静态,不需要 React state——
850
+ // useOpen/subs 那套同步机制是死代码(effect 只在挂载时跑一次,subs 无人读取)。
880
851
  function Trigger() {
881
- var open = useOpen();
882
852
  return h('button', {
883
853
  className: 'dshmb-btn', type: 'button', title: '记忆库:领域知识库,人审策展',
884
- onClick: function (e) { e.preventDefault(); setOpen(!open); },
854
+ onClick: function (e) { e.preventDefault(); setOpen(!openFlag); },
885
855
  }, '🧠 记忆库');
886
856
  }
887
857
 
package/index.js CHANGED
@@ -20,7 +20,8 @@ import { chat as llmChat } from './lib/llm.js'
20
20
  import { discover } from './lib/github.js'
21
21
 
22
22
  export const name = 'memory-book'
23
- export const version = '0.1.0'
23
+ // 与 package.json version 保持同步(cordis 展示用;改版本时两边都要动)
24
+ export const version = '0.2.6'
24
25
  export const inject = ['tools', 'webServer', 'systemPrompt']
25
26
 
26
27
  const NEW_MEMORY_DIR = path.join(os.homedir(), '.dsh', 'memory-domains')
@@ -61,7 +62,6 @@ function loadLocalSettings(memoryDir) {
61
62
  function mergeConfig(raw = {}) {
62
63
  const cfg = { ...DEFAULTS, ...raw }
63
64
  cfg.memoryDir = expandHome(cfg.memoryDir) || NEW_MEMORY_DIR
64
- cfg.sessionsDir = expandHome(cfg.sessionsDir) || sessionsRoot()
65
65
  // 一次性目录迁移:用默认新路径且旧目录还在、数据未搬过 → 整体 rename(settings.json 一起走)
66
66
  if (cfg.memoryDir === NEW_MEMORY_DIR && !fs.existsSync(NEW_MEMORY_DIR) && fs.existsSync(OLD_MEMORY_DIR)) {
67
67
  try { fs.renameSync(OLD_MEMORY_DIR, NEW_MEMORY_DIR); log(`memoryDir 迁移: ${OLD_MEMORY_DIR} → ${NEW_MEMORY_DIR}`) } catch (e) { log('memoryDir 迁移失败: ' + e.message) }
@@ -70,7 +70,7 @@ function mergeConfig(raw = {}) {
70
70
  for (const k of ['enabled', 'baseUrl', 'apiKeyFile', 'apiKey', 'reviewModel', 'reviewTimeoutMs', 'memoryDir', 'sessionsDir', 'githubToken']) {
71
71
  if (local[k] !== undefined) cfg[k] = local[k]
72
72
  }
73
- // settings.json 覆盖后同样要展开 ~
73
+ // settings.json 覆盖后统一归一化(~ 展开 + 默认值兜底)
74
74
  cfg.memoryDir = expandHome(cfg.memoryDir) || NEW_MEMORY_DIR
75
75
  cfg.sessionsDir = expandHome(cfg.sessionsDir) || sessionsRoot()
76
76
  cfg.apiKeyFile = expandHome(cfg.apiKeyFile)
@@ -112,19 +112,27 @@ async function warmSessionMeta() {
112
112
  try {
113
113
  // 最近的会话优先预热;每 25 个落盘一次,进程中途死掉不丢已完成的进度
114
114
  const files = listSessionFiles(CURRENT.sessionsDir).sort((a, b) => b.mtime - a.mtime)
115
- let dirty = false, sinceFlush = 0
116
- for (const f of files) {
117
- const cur = metaCache.get(f.id)
118
- if (cur && cur.size === f.size && cur.mtime === f.mtime) continue
119
- try {
120
- const data = parseSession(decodeZstdFrames(fs.readFileSync(f.file)))
121
- metaCache.set(f.id, { size: f.size, mtime: f.mtime, title: data.title, cwd: data.cwd, msgs: data.msgs.length })
122
- dirty = true
123
- } catch { /* 解不出跳过 */ }
124
- if (++sinceFlush >= 25) { flushMeta(); sinceFlush = 0 }
125
- await new Promise(r => setImmediate(r)) // 让出事件循环,不阻塞 API
126
- }
127
- if (dirty) flushMeta()
115
+ let dirty = false, sinceFlush = 0
116
+ for (const f of files) {
117
+ const cur = metaCache.get(f.id)
118
+ if (cur && cur.size === f.size && cur.mtime === f.mtime) continue
119
+ try {
120
+ const data = parseSession(decodeZstdFrames(fs.readFileSync(f.file)))
121
+ metaCache.set(f.id, { size: f.size, mtime: f.mtime, title: data.title, cwd: data.cwd, msgs: data.msgs.length })
122
+ dirty = true
123
+ } catch { /* 解不出跳过 */ }
124
+ if (++sinceFlush >= 25) { flushMeta(); sinceFlush = 0 }
125
+ await new Promise(r => setImmediate(r)) // 让出事件循环,不阻塞 API
126
+ }
127
+ // 清理已删除会话的缓存条目——metaCache 只增不删会让 session-meta.json 慢性膨胀。
128
+ // files 为空时跳过:readdir 瞬时失败也返回 [],不能把整个缓存误清。
129
+ if (files.length) {
130
+ const live = new Set(files.map(f => f.id))
131
+ for (const k of metaCache.keys()) {
132
+ if (!live.has(k)) { metaCache.delete(k); dirty = true }
133
+ }
134
+ }
135
+ if (dirty) flushMeta()
128
136
  } finally { warming = false }
129
137
  }
130
138
 
@@ -162,11 +170,13 @@ function domainList() {
162
170
  const api = {
163
171
  // GET /api/sessions — 会话清单(秒回:标题走缓存,pending>0 表示后台还在预热)
164
172
  'GET /api/sessions': async () => {
165
- // 预热只在 apply 跑一次;运行期新会话靠这里自愈(pending>0 时补一轮,幂等+防重入)
166
- if (sessionsPending() > 0) warmSessionMeta().catch(() => {})
173
+ // 预热只在 apply 跑一次;运行期新会话靠这里自愈(pending>0 时补一轮,幂等+防重入)。
174
+ // sessionsPending 内部要全量 stat 会话目录——算一次存变量,别重复调。
175
+ const pending = sessionsPending()
176
+ if (pending > 0) warmSessionMeta().catch(() => {})
167
177
  return {
168
178
  ok: true,
169
- pending: sessionsPending(),
179
+ pending,
170
180
  sessions: listSessions(CURRENT.sessionsDir, { parseTitles: false }).map(s => ({
171
181
  id: s.id, title: s.title || s.id,
172
182
  cwd: s.cwd ? String(s.cwd).split(/[\\/]/).pop() : '', // 只回 basename,不泄整机路径
@@ -217,7 +227,8 @@ const api = {
217
227
 
218
228
  // GET /api/memories?scope=domain&domain=<slug> | scope=global | scope=all&session=<sid>&archived=1
219
229
  'GET /api/memories': async (req, url) => {
220
- const scope = ['domain', 'global', 'all'].includes(url.searchParams.get('scope')) ? url.searchParams.get('scope') : 'all'
230
+ const scopeParam = url.searchParams.get('scope')
231
+ const scope = ['domain', 'global', 'all'].includes(scopeParam) ? scopeParam : 'all'
221
232
  const includeArchived = url.searchParams.get('archived') === '1'
222
233
  const session = url.searchParams.get('session') || ''
223
234
  let entries
@@ -319,8 +330,7 @@ const api = {
319
330
  // POST /api/archive {scope, domain?, id, archived}
320
331
  'POST /api/archive': async (req) => {
321
332
  const b = await readBody(req)
322
- const scope = b.scope === 'global' ? 'global' : 'domain'
323
- const e = store.updateMemory(CURRENT.memoryDir, scope, b.domain, String(b.id || ''),
333
+ const e = store.updateMemory(CURRENT.memoryDir, scopeOf(b), b.domain, String(b.id || ''),
324
334
  { status: b.archived === false ? 'active' : 'archived' })
325
335
  return e ? { ok: true, entry: e } : jsonErr(404, '条目不存在')
326
336
  },
@@ -328,8 +338,7 @@ const api = {
328
338
  // POST /api/priority {scope, domain?, id, priority:'high'|'normal'} — 入库后调优先级
329
339
  'POST /api/priority': async (req) => {
330
340
  const b = await readBody(req)
331
- const scope = b.scope === 'global' ? 'global' : 'domain'
332
- const e = store.updateMemory(CURRENT.memoryDir, scope, b.domain, String(b.id || ''),
341
+ const e = store.updateMemory(CURRENT.memoryDir, scopeOf(b), b.domain, String(b.id || ''),
333
342
  { priority: b.priority === 'high' ? 'high' : 'normal' })
334
343
  return e ? { ok: true, entry: e } : jsonErr(404, '条目不存在')
335
344
  },
@@ -337,8 +346,7 @@ const api = {
337
346
  // POST /api/delete {scope, domain?, id}
338
347
  'POST /api/delete': async (req) => {
339
348
  const b = await readBody(req)
340
- const scope = b.scope === 'global' ? 'global' : 'domain'
341
- return store.deleteMemory(CURRENT.memoryDir, scope, b.domain, String(b.id || ''))
349
+ return store.deleteMemory(CURRENT.memoryDir, scopeOf(b), b.domain, String(b.id || ''))
342
350
  ? { ok: true } : jsonErr(404, '条目不存在')
343
351
  },
344
352
 
@@ -346,7 +354,7 @@ const api = {
346
354
  'POST /api/create': async (req) => {
347
355
  const b = await readBody(req)
348
356
  if (!b.title || !b.content) return jsonErr(400, 'title/content required')
349
- const scope = b.scope === 'global' ? 'global' : 'domain'
357
+ const scope = scopeOf(b)
350
358
  try {
351
359
  const e = store.addMemory(CURRENT.memoryDir, {
352
360
  scope, domain: b.domain, type: b.type, title: b.title, content: b.content,
@@ -358,6 +366,8 @@ const api = {
358
366
  }
359
367
 
360
368
  function jsonErr(code, error) { return { ok: false, error, _code: code } }
369
+ // scope 参数归一:只认 'global',其余一律按 'domain' 处理(与前端 data-scope 约定一致)
370
+ const scopeOf = b => (b.scope === 'global' ? 'global' : 'domain')
361
371
 
362
372
  /* ---- 本机 API 防浏览器跨站调用(记忆投毒/删除是核心威胁)----
363
373
  * 浏览器跨域请求必带 Origin 且伪造不了;非浏览器本机客户端不带 Origin(本机已可信)。
@@ -508,8 +518,11 @@ export function apply(ctx, config) {
508
518
  if (!cfg.enabled) { log('disabled by config'); return }
509
519
  log(`apply: memoryDir=${cfg.memoryDir} sessionsDir=${cfg.sessionsDir}`)
510
520
  fs.mkdirSync(cfg.memoryDir, { recursive: true })
511
- const mig = store.migrateLegacy(cfg.memoryDir)
512
- if (mig.migrated) log(`migrateLegacy: ${mig.migrated} 条存量记忆已迁移`)
521
+ // 迁移失败不能拖垮插件加载——坏数据降级为"不迁移",用户仍能进面板手动处理
522
+ try {
523
+ const mig = store.migrateLegacy(cfg.memoryDir)
524
+ if (mig.migrated) log(`migrateLegacy: ${mig.migrated} 条存量记忆已迁移`)
525
+ } catch (e) { log('migrateLegacy 失败(已跳过): ' + String(e?.message || e).slice(0, 200)) }
513
526
  primeMeta()
514
527
  warmSessionMeta().then(() => log('warmSessionMeta done')).catch(e => log('warmSessionMeta error ' + String(e).slice(0, 200)))
515
528
  ctx.effect(() => {
package/lib/github.js CHANGED
@@ -15,23 +15,30 @@ const GH_HEADERS = {
15
15
  /** 领域画像 → GitHub 检索关键词(3~5 个,英文优先)。 */
16
16
  export async function distillQueries(cfg, domain, { chat } = {}) {
17
17
  const _chat = chat || llmChat
18
- const text = await _chat(cfg, cfg.reviewModel, [{
19
- role: 'user',
20
- content: [
21
- '你是 GitHub 项目发现助手。根据下面这个技术领域,输出 3~5 个适合在 GitHub 搜索的关键词 query。',
22
- '要求:优先 repo name/description/topics 里常见的英文术语(可中英混合);简短精准,避免过长。',
23
- '只输出一个 JSON 数组,如 ["ros robotics", "embedded stm32 control"],不要解释。',
24
- `领域名称:${domain.name}`,
25
- `领域描述:${domain.desc}`,
26
- ].join('\n'),
27
- }], Math.min(cfg.reviewTimeoutMs || 180_000, 60_000))
18
+ let text
19
+ try {
20
+ text = await _chat(cfg, cfg.reviewModel, [{
21
+ role: 'user',
22
+ content: [
23
+ '你是 GitHub 项目发现助手。根据下面这个技术领域,输出 3~5 个适合在 GitHub 搜索的关键词 query。',
24
+ '要求:优先 repo name/description/topics 里常见的英文术语(可中英混合);简短精准,避免过长。',
25
+ '只输出一个 JSON 数组,如 ["ros robotics", "embedded stm32 control"],不要解释。',
26
+ `领域名称:${domain.name}`,
27
+ `领域描述:${domain.desc}`,
28
+ ].join('\n'),
29
+ }], Math.min(cfg.reviewTimeoutMs || 180_000, 60_000))
30
+ } catch {
31
+ // 【取舍】LLM 蒸馏挂了不等于发现功能全灭——降级用领域名本身当检索词,
32
+ // 中文 query 在 GitHub 上召回差但非零;比直接 502 强。
33
+ return [domain.name].filter(s => s && s.length >= 2)
34
+ }
28
35
  const clean = s => String(s || '').trim().replace(/^`+|`+$/g, '').slice(0, 80)
29
36
  const ok = s => s.length >= 2 && !/[。!?;:]/.test(s) // 全角句读是解释性文字的特征;ASCII ':' 保留(language:python 限定符)
30
- // 【取舍】prompt 要 JSON 数组但模型经常不守格式,所以双保险:先试 JSON,
31
- // 失败退回行解析再过滤解释行。过滤器只认"全角句读"——太激进的过滤会误杀
32
- // 'ros2, humble' 这类合法 query;漏进来的垃圾 query 最多浪费一次 GitHub 调用。
33
- // 优先 JSON 数组解析;失败退回逐行解析(容忍模型不守格式)
34
- const m = String(text || '').match(/\[[^\[\]]*\]/) // 首个无嵌套括号组,防 '["a"] 说明 [b]' 贪婪误配
37
+ // 【取舍】prompt 要 JSON 数组但模型经常不守格式,所以双保险:先试 JSON
38
+ // (取首个无嵌套括号组,防 '["a"] 说明 [b]' 贪婪误配),失败退回逐行解析。
39
+ // 行解析的过滤器只认"全角句读"——太激进的过滤会误杀 'ros2, humble' 这类
40
+ // 合法 query;漏进来的垃圾 query 最多浪费一次 GitHub 调用。
41
+ const m = String(text || '').match(/\[[^\[\]]*\]/)
35
42
  if (m) {
36
43
  try {
37
44
  const arr = JSON.parse(m[0])
package/lib/review.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * 教训信号要从对话里推断(用户纠偏/AI 自我修正/明确的失败与重来)。
6
6
  * 输出 JSON 数组草稿,由人审后 accept 进会话记忆库。
7
7
  */
8
+ import { chat as llmChat } from './llm.js'
8
9
 
9
10
  const TYPE_DESC = {
10
11
  mistake: '教训(content 写 症状→修法 两段)',
@@ -99,7 +100,7 @@ export function parseDrafts(text) {
99
100
  * deps.chat 可注入(离线测试);默认走 llm.chat。
100
101
  */
101
102
  export async function reviewSession(cfg, sessionData, { chat, model, domains } = {}) {
102
- const _chat = chat || (await import('./llm.js')).chat
103
+ const _chat = chat || llmChat
103
104
  const trajectory = buildTrajectory(sessionData.msgs || [])
104
105
  if (!trajectory.trim()) return { drafts: [], error: '会话没有可读消息' }
105
106
  const prompt = buildReviewPrompt(trajectory, sessionData.title, domains || [])
package/lib/store.js CHANGED
@@ -39,22 +39,32 @@ function readJsonl(p) {
39
39
  } catch { return [] }
40
40
  }
41
41
  function readJson(p, fallback) {
42
- try { return JSON.parse(fs.readFileSync(p, 'utf8')) } catch { return fallback }
42
+ try { return JSON.parse(fs.readFileSync(p, 'utf8')) } catch (e) {
43
+ // 解析失败不能静默——否则下次 writeJson 会把损坏文件"覆盖修复"成空注册表,
44
+ // 用户所有领域名存实亡。先把坏文件挪成 .corrupt 留证,再返回 fallback。
45
+ if (e instanceof SyntaxError) {
46
+ try { fs.renameSync(p, `${p}.corrupt-${Date.now().toString(36)}`) } catch { /* ok */ }
47
+ }
48
+ return fallback
49
+ }
43
50
  }
44
- function writeJsonl(p, entries) {
51
+ // writeJsonl/writeJson 共用的原子写:同目录随机临时文件 + rename——
52
+ // 崩溃/断电不留半截,多进程也不撞名
53
+ function atomicWrite(p, content) {
45
54
  fs.mkdirSync(path.dirname(p), { recursive: true })
46
- // 原子写:同目录随机临时文件 + rename——崩溃/断电不留半截,多进程也不撞名
47
55
  const tmp = `${p}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
48
- fs.writeFileSync(tmp, entries.map(e => JSON.stringify(e)).join('\n') + (entries.length ? '\n' : ''))
56
+ fs.writeFileSync(tmp, content)
49
57
  try { fs.renameSync(tmp, p) } catch (err) { try { fs.rmSync(tmp, { force: true }) } catch { /* ok */ } throw err }
50
58
  }
59
+ function writeJsonl(p, entries) {
60
+ atomicWrite(p, entries.map(e => JSON.stringify(e)).join('\n') + (entries.length ? '\n' : ''))
61
+ }
51
62
  function writeJson(p, obj) {
52
- fs.mkdirSync(path.dirname(p), { recursive: true })
53
- const tmp = `${p}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
54
- fs.writeFileSync(tmp, JSON.stringify(obj, null, 2))
55
- try { fs.renameSync(tmp, p) } catch (err) { try { fs.rmSync(tmp, { force: true }) } catch { /* ok */ } throw err }
63
+ atomicWrite(p, JSON.stringify(obj, null, 2))
56
64
  }
57
65
 
66
+ const clip = (s, n) => String(s || '').slice(0, n)
67
+
58
68
  export function newId() {
59
69
  return 'm-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
60
70
  }
@@ -175,10 +185,10 @@ export function addMemory(dir, entry) {
175
185
  type: TYPES.includes(entry.type) ? entry.type : 'fact',
176
186
  scope,
177
187
  ...(scope === 'domain' ? { domain } : {}),
178
- ...(entry.source_session ? { source_session: String(entry.source_session).slice(0, 80) } : {}),
179
- title: String(entry.title || '').slice(0, 200),
180
- content: String(entry.content || '').slice(0, 8000),
181
- ...(entry.evidence ? { evidence: String(entry.evidence).slice(0, 500) } : {}),
188
+ ...(entry.source_session ? { source_session: clip(entry.source_session, 80) } : {}),
189
+ title: clip(entry.title, 200),
190
+ content: clip(entry.content, 8000),
191
+ ...(entry.evidence ? { evidence: clip(entry.evidence, 500) } : {}),
182
192
  source: entry.source || 'manual',
183
193
  status: entry.status === 'archived' ? 'archived' : 'active',
184
194
  created_at: entry.created_at || new Date().toISOString(),
@@ -208,9 +218,9 @@ export function updateMemory(dir, scope, key, id, patch) {
208
218
  for (const k of Object.keys(patch || {})) if (PATCHABLE.has(k)) clean[k] = patch[k]
209
219
  // 与 addMemory 同规格:type 校验枚举、字符串截断
210
220
  if (clean.type !== undefined && !TYPES.includes(clean.type)) delete clean.type
211
- if (clean.title !== undefined) clean.title = String(clean.title).slice(0, 200)
212
- if (clean.content !== undefined) clean.content = String(clean.content).slice(0, 8000)
213
- if (clean.evidence !== undefined) clean.evidence = String(clean.evidence).slice(0, 500)
221
+ if (clean.title !== undefined) clean.title = clip(clean.title, 200)
222
+ if (clean.content !== undefined) clean.content = clip(clean.content, 8000)
223
+ if (clean.evidence !== undefined) clean.evidence = clip(clean.evidence, 500)
214
224
  if (clean.status !== undefined) clean.status = clean.status === 'archived' ? 'archived' : 'active'
215
225
  const touched = CONTENT_FIELDS.some(f => clean[f] !== undefined && clean[f] !== prev[f])
216
226
  const next = { ...prev, ...clean, id: prev.id, updated_at: new Date().toISOString() }
@@ -270,11 +280,11 @@ export function addCandidate(dir, session, draft) {
270
280
  id: draft.id || newId(),
271
281
  type: TYPES.includes(draft.type) ? draft.type : 'fact',
272
282
  session,
273
- ...(draft.domain ? { domain: String(draft.domain).slice(0, 50) } : {}), // AI 建议的领域 slug(可能为空)
283
+ ...(draft.domain ? { domain: clip(draft.domain, 50) } : {}), // AI 建议的领域 slug(可能为空)
274
284
  ...(draft.priority === 'high' ? { priority: 'high' } : {}), // AI 建议的优先级(normal 缺省不存)
275
- title: String(draft.title || '').slice(0, 200),
276
- content: String(draft.content || '').slice(0, 8000),
277
- ...(draft.evidence ? { evidence: String(draft.evidence).slice(0, 500) } : {}),
285
+ title: clip(draft.title, 200),
286
+ content: clip(draft.content, 8000),
287
+ ...(draft.evidence ? { evidence: clip(draft.evidence, 500) } : {}),
278
288
  source: draft.source || `review:${session}`,
279
289
  status: 'candidate',
280
290
  created_at: new Date().toISOString(),
@@ -327,10 +337,10 @@ export function updateCandidate(dir, session, id, patch) {
327
337
  cands[i] = {
328
338
  ...d,
329
339
  ...(patch.type && TYPES.includes(patch.type) ? { type: patch.type } : {}),
330
- ...(patch.title != null ? { title: String(patch.title).slice(0, 200) } : {}),
331
- ...(patch.content != null ? { content: String(patch.content).slice(0, 8000) } : {}),
332
- ...(patch.evidence != null ? { evidence: String(patch.evidence).slice(0, 500) } : {}),
333
- ...(patch.domain != null ? { domain: String(patch.domain).slice(0, 50) } : {}),
340
+ ...(patch.title != null ? { title: clip(patch.title, 200) } : {}),
341
+ ...(patch.content != null ? { content: clip(patch.content, 8000) } : {}),
342
+ ...(patch.evidence != null ? { evidence: clip(patch.evidence, 500) } : {}),
343
+ ...(patch.domain != null ? { domain: clip(patch.domain, 50) } : {}),
334
344
  }
335
345
  if (patch.priority === 'high') cands[i].priority = 'high'
336
346
  else if (patch.priority === 'normal') delete cands[i].priority
@@ -453,10 +463,12 @@ export function searchMemories(dir, { query = '', scope = 'all', domain = '', se
453
463
  for (const d of listDomains(dir)) files.push([domainFileFor(dir, d.slug), false])
454
464
  files.push([globalFile(dir), true])
455
465
  }
456
- // all 模式去重:已被全局版引用(promoted_from_id)的领域原件不再单独命中
466
+ // all 模式去重:已被全局版引用(promoted_from_id)的领域原件不再单独命中。
467
+ // 【取舍】只统计 active 的全局副本——若全局副本被归档,领域原件应在 all 检索里
468
+ // 重新浮现,否则这条记忆在两边都不可见(原件被隐藏+副本被归档过滤)。
457
469
  const promotedIds = new Set()
458
470
  if (files.length > 1) {
459
- for (const e of readJsonl(globalFile(dir))) if (e.promoted_from_id) promotedIds.add(e.promoted_from_id)
471
+ for (const e of readJsonl(globalFile(dir))) if (e.promoted_from_id && e.status !== 'archived') promotedIds.add(e.promoted_from_id)
460
472
  }
461
473
  // 过滤 + 预处理:小写字段文本与长度(每条一次,供 df/avgdl/打分共用)
462
474
  const docs = []
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-memory-domains",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "main": "./index.js",
6
6
  "exports": {