dsh-memory-domains 0.2.5 → 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
  /* ------------------------------------------------------------ 动作 */
@@ -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,14 +521,7 @@ window.__ModuleLoader__.load({
526
521
  toast('整理失败:' + (j.error || ''));
527
522
  syncBar(); renderBody();
528
523
  }
529
- }).catch(function () {
530
- // fetch 抛错(断网/宿主卡)与 !ok 同权:走同一套重试,别一次抖动就放弃追踪
531
- pollReview.fails = (pollReview.fails || 0) + 1;
532
- if (pollReview.fails < 5) { reviewTimer = setTimeout(function () { pollReview(job); }, 2000); return; }
533
- pollReview.fails = 0;
534
- reviewJob = null; reviewSessionId = null;
535
- syncBar(); renderBody();
536
- });
524
+ }).catch(function () { pollFail(job); }); // fetch 抛错与 !ok 同权
537
525
  }
538
526
 
539
527
  function cardOp(op, id, el) {
@@ -572,8 +560,6 @@ window.__ModuleLoader__.load({
572
560
  archive: post(API + '/archive', { scope: scope, domain: dom, id: id, archived: true }),
573
561
  unarchive: post(API + '/archive', { scope: scope, domain: dom, id: id, archived: false }),
574
562
  del: post(API + '/delete', { scope: scope, domain: dom, id: id }),
575
- accept: null,
576
- reject: post(API + '/candidates/reject', { session: view.id, id: id }),
577
563
  };
578
564
  var p = calls[op];
579
565
  if (!p) return;
@@ -671,9 +657,26 @@ window.__ModuleLoader__.load({
671
657
  };
672
658
  }
673
659
 
674
- function showDomainEdit(slug) {
675
- var d = domainBySlug(slug);
676
- 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
+ });
677
680
  }
678
681
 
679
682
  /* ---- 手动添加记忆 ---- */
@@ -683,32 +686,15 @@ window.__ModuleLoader__.load({
683
686
  if (!loc) { toast('先打开一个领域或全局库'); return; }
684
687
  var div = document.createElement('div');
685
688
  div.className = 'dshmb-form';
686
- var typeVal = 'mistake';
687
- var priVal = 'normal';
689
+ var sel = { t: 'mistake', pri: 'normal' };
688
690
  div.innerHTML =
689
- '<div class="dshmb-types">' +
690
- ['mistake', 'fact', 'skill', 'pref'].map(function (t, i) {
691
- return '<span class="dshmb-tchip' + (i === 0 ? ' on' : '') + '" data-t="' + t + '">' + (TYPE_LABEL[t] || t) + '</span>';
692
- }).join('') + '</div>' +
693
- '<div class="dshmb-types" style="margin-top:0"><span style="font-size:11px;align-self:center">优先级</span>' +
694
- '<span class="dshmb-tchip' + (priVal === 'high' ? ' on' : '') + '" data-pri="high">★高</span>' +
695
- '<span class="dshmb-tchip on" data-pri="normal">普通</span></div>' +
691
+ chipsHtml(sel) +
696
692
  '<input class="dshmb-f-title" placeholder="标题(一句话)">' +
697
693
  '<textarea class="dshmb-f-content" placeholder="内容(自包含,脱离会话也能看懂)"></textarea>' +
698
694
  '<input class="dshmb-f-ev" placeholder="来源/证据(可选)">' +
699
695
  '<div style="display:flex;gap:8px"><button class="dshmb-act primary dshmb-f-ok">保存</button>' +
700
696
  '<button class="dshmb-act dshmb-f-no">取消</button></div>';
701
- div.querySelectorAll('.dshmb-tchip').forEach(function (chip) {
702
- chip.addEventListener('click', function () {
703
- if (chip.dataset.t) {
704
- typeVal = chip.dataset.t;
705
- div.querySelectorAll('[data-t]').forEach(function (c) { c.classList.toggle('on', c === chip); });
706
- } else if (chip.dataset.pri) {
707
- priVal = chip.dataset.pri;
708
- div.querySelectorAll('[data-pri]').forEach(function (c) { c.classList.toggle('on', c === chip); });
709
- }
710
- });
711
- });
697
+ wireChips(div, sel);
712
698
  bodyEl.insertBefore(div, bodyEl.firstChild);
713
699
  div.querySelector('.dshmb-f-no').onclick = function () { div.remove(); };
714
700
  div.querySelector('.dshmb-f-ok').onclick = function () {
@@ -716,7 +702,7 @@ window.__ModuleLoader__.load({
716
702
  var content = div.querySelector('.dshmb-f-content').value.trim();
717
703
  var evidence = div.querySelector('.dshmb-f-ev').value.trim();
718
704
  if (!title || !content) { toast('标题和内容都要填'); return; }
719
- 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 })
720
706
  .then(function (j) { if (j.ok) { div.remove(); renderBody(); toast('已记下'); } else toast('失败:' + (j.error || '')); })
721
707
  .catch(function () { toast('请求失败'); });
722
708
  };
@@ -731,16 +717,9 @@ window.__ModuleLoader__.load({
731
717
  if (!card) return;
732
718
  var div = document.createElement('div');
733
719
  div.className = 'dshmb-form';
734
- var typeVal = entry.type || 'mistake';
735
- var priVal = entry.priority === 'high' ? 'high' : 'normal';
720
+ var sel = { t: entry.type || 'mistake', pri: entry.priority === 'high' ? 'high' : 'normal' };
736
721
  div.innerHTML =
737
- '<div class="dshmb-types">' +
738
- ['mistake', 'fact', 'skill', 'pref'].map(function (t) {
739
- return '<span class="dshmb-tchip' + (t === typeVal ? ' on' : '') + '" data-t="' + t + '">' + (TYPE_LABEL[t] || t) + '</span>';
740
- }).join('') + '</div>' +
741
- '<div class="dshmb-types" style="margin-top:0"><span style="font-size:11px;align-self:center">优先级</span>' +
742
- '<span class="dshmb-tchip' + (priVal === 'high' ? ' on' : '') + '" data-pri="high">★高</span>' +
743
- '<span class="dshmb-tchip' + (priVal !== 'high' ? ' on' : '') + '" data-pri="normal">普通</span></div>' +
722
+ chipsHtml(sel) +
744
723
  '<input class="dshmb-f-title" placeholder="标题(一句话)" value="' + esc(entry.title || '') + '">' +
745
724
  '<div class="dshmb-meta" style="margin:0">建议领域(slug,可改;留空=入库时再选)</div>' +
746
725
  '<input class="dshmb-f-domain" placeholder="领域 slug(可选)" value="' + esc(entry.domain || '') + '">' +
@@ -748,17 +727,7 @@ window.__ModuleLoader__.load({
748
727
  '<input class="dshmb-f-ev" placeholder="来源/证据(可选,msg#N 或说明)" value="' + esc(entry.evidence || '') + '">' +
749
728
  '<div style="display:flex;gap:8px"><button class="dshmb-act primary dshmb-f-ok">保存修改</button>' +
750
729
  '<button class="dshmb-act dshmb-f-no">取消</button></div>';
751
- div.querySelectorAll('.dshmb-tchip').forEach(function (chip) {
752
- chip.addEventListener('click', function () {
753
- if (chip.dataset.t) {
754
- typeVal = chip.dataset.t;
755
- div.querySelectorAll('[data-t]').forEach(function (c) { c.classList.toggle('on', c === chip); });
756
- } else if (chip.dataset.pri) {
757
- priVal = chip.dataset.pri;
758
- div.querySelectorAll('[data-pri]').forEach(function (c) { c.classList.toggle('on', c === chip); });
759
- }
760
- });
761
- });
730
+ wireChips(div, sel);
762
731
  card.appendChild(div);
763
732
  div.querySelector('.dshmb-f-no').onclick = function () { div.remove(); };
764
733
  div.querySelector('.dshmb-f-ok').onclick = function () {
@@ -767,7 +736,7 @@ window.__ModuleLoader__.load({
767
736
  var content = div.querySelector('.dshmb-f-content').value.trim();
768
737
  var evidence = div.querySelector('.dshmb-f-ev').value.trim();
769
738
  if (!title || !content) { toast('标题和内容都要填'); return; }
770
- 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 })
771
740
  .then(function (j) { if (j.ok) { renderBody(); toast('已更新'); } else toast('失败:' + (j.error || '')); })
772
741
  .catch(function () { toast('请求失败'); });
773
742
  };
@@ -877,22 +846,12 @@ window.__ModuleLoader__.load({
877
846
  }
878
847
  }
879
848
 
880
- var subs = new Set();
881
- function useOpen() {
882
- var st = React.useState(openFlag);
883
- React.useEffect(function () {
884
- subs.add(st[1]);
885
- st[1](openFlag);
886
- return function () { subs.delete(st[1]); };
887
- }, []);
888
- return st[0];
889
- }
890
-
849
+ // 面板开关状态存在模块级 openFlag;按钮文案静态,不需要 React state——
850
+ // useOpen/subs 那套同步机制是死代码(effect 只在挂载时跑一次,subs 无人读取)。
891
851
  function Trigger() {
892
- var open = useOpen();
893
852
  return h('button', {
894
853
  className: 'dshmb-btn', type: 'button', title: '记忆库:领域知识库,人审策展',
895
- onClick: function (e) { e.preventDefault(); setOpen(!open); },
854
+ onClick: function (e) { e.preventDefault(); setOpen(!openFlag); },
896
855
  }, '🧠 记忆库');
897
856
  }
898
857
 
package/index.js CHANGED
@@ -21,7 +21,7 @@ import { discover } from './lib/github.js'
21
21
 
22
22
  export const name = 'memory-book'
23
23
  // 与 package.json version 保持同步(cordis 展示用;改版本时两边都要动)
24
- export const version = '0.2.5'
24
+ export const version = '0.2.6'
25
25
  export const inject = ['tools', 'webServer', 'systemPrompt']
26
26
 
27
27
  const NEW_MEMORY_DIR = path.join(os.homedir(), '.dsh', 'memory-domains')
@@ -62,7 +62,6 @@ function loadLocalSettings(memoryDir) {
62
62
  function mergeConfig(raw = {}) {
63
63
  const cfg = { ...DEFAULTS, ...raw }
64
64
  cfg.memoryDir = expandHome(cfg.memoryDir) || NEW_MEMORY_DIR
65
- cfg.sessionsDir = expandHome(cfg.sessionsDir) || sessionsRoot()
66
65
  // 一次性目录迁移:用默认新路径且旧目录还在、数据未搬过 → 整体 rename(settings.json 一起走)
67
66
  if (cfg.memoryDir === NEW_MEMORY_DIR && !fs.existsSync(NEW_MEMORY_DIR) && fs.existsSync(OLD_MEMORY_DIR)) {
68
67
  try { fs.renameSync(OLD_MEMORY_DIR, NEW_MEMORY_DIR); log(`memoryDir 迁移: ${OLD_MEMORY_DIR} → ${NEW_MEMORY_DIR}`) } catch (e) { log('memoryDir 迁移失败: ' + e.message) }
@@ -71,7 +70,7 @@ function mergeConfig(raw = {}) {
71
70
  for (const k of ['enabled', 'baseUrl', 'apiKeyFile', 'apiKey', 'reviewModel', 'reviewTimeoutMs', 'memoryDir', 'sessionsDir', 'githubToken']) {
72
71
  if (local[k] !== undefined) cfg[k] = local[k]
73
72
  }
74
- // settings.json 覆盖后同样要展开 ~
73
+ // settings.json 覆盖后统一归一化(~ 展开 + 默认值兜底)
75
74
  cfg.memoryDir = expandHome(cfg.memoryDir) || NEW_MEMORY_DIR
76
75
  cfg.sessionsDir = expandHome(cfg.sessionsDir) || sessionsRoot()
77
76
  cfg.apiKeyFile = expandHome(cfg.apiKeyFile)
@@ -113,22 +112,27 @@ async function warmSessionMeta() {
113
112
  try {
114
113
  // 最近的会话优先预热;每 25 个落盘一次,进程中途死掉不丢已完成的进度
115
114
  const files = listSessionFiles(CURRENT.sessionsDir).sort((a, b) => b.mtime - a.mtime)
116
- let dirty = false, sinceFlush = 0
117
- for (const f of files) {
118
- const cur = metaCache.get(f.id)
119
- if (cur && cur.size === f.size && cur.mtime === f.mtime) continue
120
- try {
121
- const data = parseSession(decodeZstdFrames(fs.readFileSync(f.file)))
122
- metaCache.set(f.id, { size: f.size, mtime: f.mtime, title: data.title, cwd: data.cwd, msgs: data.msgs.length })
123
- dirty = true
124
- } catch { /* 解不出跳过 */ }
125
- if (++sinceFlush >= 25) { flushMeta(); sinceFlush = 0 }
126
- await new Promise(r => setImmediate(r)) // 让出事件循环,不阻塞 API
127
- }
128
- // 清理已删除会话的缓存条目——metaCache 只增不删会让 session-meta.json 慢性膨胀
129
- const live = new Set(files.map(f => f.id))
130
- for (const k of metaCache.keys()) if (!live.has(k)) metaCache.delete(k)
131
- 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()
132
136
  } finally { warming = false }
133
137
  }
134
138
 
@@ -166,11 +170,13 @@ function domainList() {
166
170
  const api = {
167
171
  // GET /api/sessions — 会话清单(秒回:标题走缓存,pending>0 表示后台还在预热)
168
172
  'GET /api/sessions': async () => {
169
- // 预热只在 apply 跑一次;运行期新会话靠这里自愈(pending>0 时补一轮,幂等+防重入)
170
- if (sessionsPending() > 0) warmSessionMeta().catch(() => {})
173
+ // 预热只在 apply 跑一次;运行期新会话靠这里自愈(pending>0 时补一轮,幂等+防重入)。
174
+ // sessionsPending 内部要全量 stat 会话目录——算一次存变量,别重复调。
175
+ const pending = sessionsPending()
176
+ if (pending > 0) warmSessionMeta().catch(() => {})
171
177
  return {
172
178
  ok: true,
173
- pending: sessionsPending(),
179
+ pending,
174
180
  sessions: listSessions(CURRENT.sessionsDir, { parseTitles: false }).map(s => ({
175
181
  id: s.id, title: s.title || s.id,
176
182
  cwd: s.cwd ? String(s.cwd).split(/[\\/]/).pop() : '', // 只回 basename,不泄整机路径
@@ -221,7 +227,8 @@ const api = {
221
227
 
222
228
  // GET /api/memories?scope=domain&domain=<slug> | scope=global | scope=all&session=<sid>&archived=1
223
229
  'GET /api/memories': async (req, url) => {
224
- 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'
225
232
  const includeArchived = url.searchParams.get('archived') === '1'
226
233
  const session = url.searchParams.get('session') || ''
227
234
  let entries
@@ -323,8 +330,7 @@ const api = {
323
330
  // POST /api/archive {scope, domain?, id, archived}
324
331
  'POST /api/archive': async (req) => {
325
332
  const b = await readBody(req)
326
- const scope = b.scope === 'global' ? 'global' : 'domain'
327
- 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 || ''),
328
334
  { status: b.archived === false ? 'active' : 'archived' })
329
335
  return e ? { ok: true, entry: e } : jsonErr(404, '条目不存在')
330
336
  },
@@ -332,8 +338,7 @@ const api = {
332
338
  // POST /api/priority {scope, domain?, id, priority:'high'|'normal'} — 入库后调优先级
333
339
  'POST /api/priority': async (req) => {
334
340
  const b = await readBody(req)
335
- const scope = b.scope === 'global' ? 'global' : 'domain'
336
- 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 || ''),
337
342
  { priority: b.priority === 'high' ? 'high' : 'normal' })
338
343
  return e ? { ok: true, entry: e } : jsonErr(404, '条目不存在')
339
344
  },
@@ -341,8 +346,7 @@ const api = {
341
346
  // POST /api/delete {scope, domain?, id}
342
347
  'POST /api/delete': async (req) => {
343
348
  const b = await readBody(req)
344
- const scope = b.scope === 'global' ? 'global' : 'domain'
345
- return store.deleteMemory(CURRENT.memoryDir, scope, b.domain, String(b.id || ''))
349
+ return store.deleteMemory(CURRENT.memoryDir, scopeOf(b), b.domain, String(b.id || ''))
346
350
  ? { ok: true } : jsonErr(404, '条目不存在')
347
351
  },
348
352
 
@@ -350,7 +354,7 @@ const api = {
350
354
  'POST /api/create': async (req) => {
351
355
  const b = await readBody(req)
352
356
  if (!b.title || !b.content) return jsonErr(400, 'title/content required')
353
- const scope = b.scope === 'global' ? 'global' : 'domain'
357
+ const scope = scopeOf(b)
354
358
  try {
355
359
  const e = store.addMemory(CURRENT.memoryDir, {
356
360
  scope, domain: b.domain, type: b.type, title: b.title, content: b.content,
@@ -362,6 +366,8 @@ const api = {
362
366
  }
363
367
 
364
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')
365
371
 
366
372
  /* ---- 本机 API 防浏览器跨站调用(记忆投毒/删除是核心威胁)----
367
373
  * 浏览器跨域请求必带 Origin 且伪造不了;非浏览器本机客户端不带 Origin(本机已可信)。
package/lib/github.js CHANGED
@@ -34,11 +34,11 @@ export async function distillQueries(cfg, domain, { chat } = {}) {
34
34
  }
35
35
  const clean = s => String(s || '').trim().replace(/^`+|`+$/g, '').slice(0, 80)
36
36
  const ok = s => s.length >= 2 && !/[。!?;:]/.test(s) // 全角句读是解释性文字的特征;ASCII ':' 保留(language:python 限定符)
37
- // 【取舍】prompt 要 JSON 数组但模型经常不守格式,所以双保险:先试 JSON,
38
- // 失败退回行解析再过滤解释行。过滤器只认"全角句读"——太激进的过滤会误杀
39
- // 'ros2, humble' 这类合法 query;漏进来的垃圾 query 最多浪费一次 GitHub 调用。
40
- // 优先 JSON 数组解析;失败退回逐行解析(容忍模型不守格式)
41
- 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(/\[[^\[\]]*\]/)
42
42
  if (m) {
43
43
  try {
44
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
@@ -48,20 +48,23 @@ function readJson(p, fallback) {
48
48
  return fallback
49
49
  }
50
50
  }
51
- function writeJsonl(p, entries) {
51
+ // writeJsonl/writeJson 共用的原子写:同目录随机临时文件 + rename——
52
+ // 崩溃/断电不留半截,多进程也不撞名
53
+ function atomicWrite(p, content) {
52
54
  fs.mkdirSync(path.dirname(p), { recursive: true })
53
- // 原子写:同目录随机临时文件 + rename——崩溃/断电不留半截,多进程也不撞名
54
55
  const tmp = `${p}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
55
- fs.writeFileSync(tmp, entries.map(e => JSON.stringify(e)).join('\n') + (entries.length ? '\n' : ''))
56
+ fs.writeFileSync(tmp, content)
56
57
  try { fs.renameSync(tmp, p) } catch (err) { try { fs.rmSync(tmp, { force: true }) } catch { /* ok */ } throw err }
57
58
  }
59
+ function writeJsonl(p, entries) {
60
+ atomicWrite(p, entries.map(e => JSON.stringify(e)).join('\n') + (entries.length ? '\n' : ''))
61
+ }
58
62
  function writeJson(p, obj) {
59
- fs.mkdirSync(path.dirname(p), { recursive: true })
60
- const tmp = `${p}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
61
- fs.writeFileSync(tmp, JSON.stringify(obj, null, 2))
62
- 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))
63
64
  }
64
65
 
66
+ const clip = (s, n) => String(s || '').slice(0, n)
67
+
65
68
  export function newId() {
66
69
  return 'm-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
67
70
  }
@@ -182,10 +185,10 @@ export function addMemory(dir, entry) {
182
185
  type: TYPES.includes(entry.type) ? entry.type : 'fact',
183
186
  scope,
184
187
  ...(scope === 'domain' ? { domain } : {}),
185
- ...(entry.source_session ? { source_session: String(entry.source_session).slice(0, 80) } : {}),
186
- title: String(entry.title || '').slice(0, 200),
187
- content: String(entry.content || '').slice(0, 8000),
188
- ...(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) } : {}),
189
192
  source: entry.source || 'manual',
190
193
  status: entry.status === 'archived' ? 'archived' : 'active',
191
194
  created_at: entry.created_at || new Date().toISOString(),
@@ -215,9 +218,9 @@ export function updateMemory(dir, scope, key, id, patch) {
215
218
  for (const k of Object.keys(patch || {})) if (PATCHABLE.has(k)) clean[k] = patch[k]
216
219
  // 与 addMemory 同规格:type 校验枚举、字符串截断
217
220
  if (clean.type !== undefined && !TYPES.includes(clean.type)) delete clean.type
218
- if (clean.title !== undefined) clean.title = String(clean.title).slice(0, 200)
219
- if (clean.content !== undefined) clean.content = String(clean.content).slice(0, 8000)
220
- 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)
221
224
  if (clean.status !== undefined) clean.status = clean.status === 'archived' ? 'archived' : 'active'
222
225
  const touched = CONTENT_FIELDS.some(f => clean[f] !== undefined && clean[f] !== prev[f])
223
226
  const next = { ...prev, ...clean, id: prev.id, updated_at: new Date().toISOString() }
@@ -277,11 +280,11 @@ export function addCandidate(dir, session, draft) {
277
280
  id: draft.id || newId(),
278
281
  type: TYPES.includes(draft.type) ? draft.type : 'fact',
279
282
  session,
280
- ...(draft.domain ? { domain: String(draft.domain).slice(0, 50) } : {}), // AI 建议的领域 slug(可能为空)
283
+ ...(draft.domain ? { domain: clip(draft.domain, 50) } : {}), // AI 建议的领域 slug(可能为空)
281
284
  ...(draft.priority === 'high' ? { priority: 'high' } : {}), // AI 建议的优先级(normal 缺省不存)
282
- title: String(draft.title || '').slice(0, 200),
283
- content: String(draft.content || '').slice(0, 8000),
284
- ...(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) } : {}),
285
288
  source: draft.source || `review:${session}`,
286
289
  status: 'candidate',
287
290
  created_at: new Date().toISOString(),
@@ -334,10 +337,10 @@ export function updateCandidate(dir, session, id, patch) {
334
337
  cands[i] = {
335
338
  ...d,
336
339
  ...(patch.type && TYPES.includes(patch.type) ? { type: patch.type } : {}),
337
- ...(patch.title != null ? { title: String(patch.title).slice(0, 200) } : {}),
338
- ...(patch.content != null ? { content: String(patch.content).slice(0, 8000) } : {}),
339
- ...(patch.evidence != null ? { evidence: String(patch.evidence).slice(0, 500) } : {}),
340
- ...(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) } : {}),
341
344
  }
342
345
  if (patch.priority === 'high') cands[i].priority = 'high'
343
346
  else if (patch.priority === 'normal') delete cands[i].priority
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-memory-domains",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "main": "./index.js",
6
6
  "exports": {