dsh-memory-domains 0.2.5 → 0.2.7
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 +139 -159
- package/index.js +42 -34
- package/lib/github.js +5 -5
- package/lib/review.js +2 -1
- package/lib/store.js +28 -25
- package/package.json +1 -1
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
|
-
|
|
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; dropTopForms(); 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
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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,23 +238,38 @@ window.__ModuleLoader__.load({
|
|
|
244
238
|
barEl.appendChild(bRevWrap);
|
|
245
239
|
}
|
|
246
240
|
if (view.name === 'domain' || view.name === 'global') {
|
|
247
|
-
|
|
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
|
|
|
256
245
|
/* ------------------------------------------------------------ 渲染 */
|
|
257
246
|
|
|
258
247
|
function renderBody() {
|
|
248
|
+
// 【取舍】表单里是用户输入,任何重渲染都不许杀:先摘出顶层 .dshmb-form,
|
|
249
|
+
// 渲染完倒序插回最前(保持原有上下顺序)。卡片内嵌的候选编辑表单不保留——
|
|
250
|
+
// 它绑定的卡片本身会被重建,摘出来反而错位。hasTransientUI 守卫仍保留,
|
|
251
|
+
// 但它只是"防抖动"优化(避免打字时卡片重排),不再是正确性依赖。
|
|
252
|
+
var keep = [];
|
|
253
|
+
if (bodyEl) {
|
|
254
|
+
bodyEl.querySelectorAll('.dshmb-form').forEach(function (f) {
|
|
255
|
+
if (f.parentNode === bodyEl) keep.push(f);
|
|
256
|
+
});
|
|
257
|
+
}
|
|
259
258
|
bodyEl.innerHTML = '';
|
|
260
|
-
if (view.name === 'wall') { renderWall();
|
|
261
|
-
if (view.name === 'global') { renderMemories({ scope: 'global' });
|
|
262
|
-
if (view.name === 'domain') { renderMemories({ scope: 'domain', domain: view.slug });
|
|
263
|
-
renderSessionView();
|
|
259
|
+
if (view.name === 'wall') { renderWall(); }
|
|
260
|
+
else if (view.name === 'global') { renderMemories({ scope: 'global' }); }
|
|
261
|
+
else if (view.name === 'domain') { renderMemories({ scope: 'domain', domain: view.slug }); }
|
|
262
|
+
else { renderSessionView(); }
|
|
263
|
+
for (var i = keep.length - 1; i >= 0; i--) bodyEl.insertBefore(keep[i], bodyEl.firstChild);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// 显式导航离开上下文时丢弃顶层表单——表单属于创建它的视图,
|
|
267
|
+
// 留着会在别的视图里"错位提交"(数据不错但用户会困惑)。
|
|
268
|
+
function dropTopForms() {
|
|
269
|
+
if (!bodyEl) return;
|
|
270
|
+
bodyEl.querySelectorAll('.dshmb-form').forEach(function (f) {
|
|
271
|
+
if (f.parentNode === bodyEl) f.remove();
|
|
272
|
+
});
|
|
264
273
|
}
|
|
265
274
|
|
|
266
275
|
/* ---- 卡片墙 ---- */
|
|
@@ -326,25 +335,35 @@ window.__ModuleLoader__.load({
|
|
|
326
335
|
|
|
327
336
|
/* ---- 领域 / 全局 / 会话来源 详情 ---- */
|
|
328
337
|
|
|
329
|
-
//
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
338
|
+
// 统一"loading tip → fetch → 替换为内容/错误"的异步渲染。
|
|
339
|
+
// 只 replaceWith tip 节点,绝不重写 container.innerHTML——瞬态 UI
|
|
340
|
+
// (新建/编辑表单、发现结果卡)天然存活,不需要摘节点再插回的补丁;
|
|
341
|
+
// tip 若已被清掉(视图切换),replaceWith 是 no-op,旧请求静默失效。
|
|
342
|
+
function fetchInto(container, url, okHtml, failMsg) {
|
|
343
|
+
var tip = document.createElement('div');
|
|
344
|
+
tip.className = 'dshmb-tip';
|
|
345
|
+
tip.textContent = '加载中…';
|
|
346
|
+
container.appendChild(tip);
|
|
347
|
+
api(url).then(function (j) {
|
|
348
|
+
var box = document.createElement('div');
|
|
349
|
+
box.innerHTML = (j && j.ok) ? okHtml(j)
|
|
350
|
+
: '<div class="dshmb-tip">加载失败:' + esc((j && j.error) || '接口无响应') + '</div>';
|
|
351
|
+
tip.replaceWith(box);
|
|
352
|
+
}).catch(function () { tip.textContent = failMsg || '无法连接插件后端。'; });
|
|
334
353
|
}
|
|
335
354
|
|
|
336
355
|
function renderMemories(loc) {
|
|
337
356
|
var isGlobal = loc.scope === 'global';
|
|
338
|
-
bodyEl.innerHTML = '
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
357
|
+
bodyEl.innerHTML = '';
|
|
358
|
+
fetchInto(bodyEl, API + '/memories?scope=' + loc.scope + (loc.domain ? '&domain=' + encodeURIComponent(loc.domain) : '') + '&archived=1',
|
|
359
|
+
function (j) {
|
|
360
|
+
var entries = j.entries || [];
|
|
361
|
+
return entries.length ? entries.map(function (e) { return memCardHtml(e, loc); }).join('')
|
|
362
|
+
: '<div class="dshmb-tip">' + (isGlobal
|
|
363
|
+
? '全局记忆库是空的——领域记忆里跨领域通用的条目,点「升级全局」进来;或点「+添加」手动记。'
|
|
364
|
+
: '这个领域还没有记忆。点「+添加」手动记,或从会话「整理」后入库到这里。') + '</div>';
|
|
365
|
+
},
|
|
366
|
+
'无法连接插件后端——确认 dsh-memory-domains 已启用。');
|
|
348
367
|
}
|
|
349
368
|
|
|
350
369
|
function memCardHtml(e, loc) {
|
|
@@ -357,14 +376,13 @@ window.__ModuleLoader__.load({
|
|
|
357
376
|
if (e.scope === 'domain' && e.status !== 'archived') {
|
|
358
377
|
ops += '<button class="dshmb-mini" data-op="promote" data-id="' + esc(e.id) + '" data-domain="' + esc(e.domain) + '">升级全局</button>';
|
|
359
378
|
}
|
|
360
|
-
|
|
361
|
-
|
|
379
|
+
// scope/domain 定位属性四个操作按钮共用,拼一次复用
|
|
380
|
+
var sd = ' data-scope="' + esc(e.scope || loc.scope) + '" data-domain="' + esc(e.domain || loc.domain || '') + '"';
|
|
381
|
+
ops += '<button class="dshmb-mini" data-op="' + (e.status === 'archived' ? 'unarchive' : 'archive') + '" data-id="' + esc(e.id) + '"' + sd + '">' +
|
|
362
382
|
(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 || '') + '">' +
|
|
383
|
+
ops += '<button class="dshmb-mini" data-op="prio" data-id="' + esc(e.id) + '" data-priority="' + (e.priority === 'high' ? 'high' : 'normal') + '"' + sd + '">' +
|
|
365
384
|
(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>';
|
|
385
|
+
ops += '<button class="dshmb-mini" data-op="del" data-id="' + esc(e.id) + '"' + sd + '">删除</button>';
|
|
368
386
|
return '<div class="dshmb-card' + (e.status === 'archived' ? ' arch' : '') + '">' +
|
|
369
387
|
'<div class="dshmb-card-top">' + badge + '<span class="dshmb-ctitle">' + esc(e.title) + '</span></div>' +
|
|
370
388
|
'<div class="dshmb-content">' + esc(e.content) + '</div>' +
|
|
@@ -385,25 +403,19 @@ window.__ModuleLoader__.load({
|
|
|
385
403
|
renderCandidatesInto(bodyEl);
|
|
386
404
|
return;
|
|
387
405
|
}
|
|
388
|
-
bodyEl.innerHTML = tabs
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
var box = document.createElement('div');
|
|
392
|
-
if (!j.ok) { box.innerHTML = '<div class="dshmb-tip">加载失败:' + esc(j.error || '') + '</div>'; }
|
|
393
|
-
else {
|
|
406
|
+
bodyEl.innerHTML = tabs;
|
|
407
|
+
fetchInto(bodyEl, API + '/memories?scope=all&session=' + encodeURIComponent(view.id) + '&archived=1',
|
|
408
|
+
function (j) {
|
|
394
409
|
var entries = j.entries || [];
|
|
395
|
-
|
|
410
|
+
return entries.length ? entries.map(function (e) { return memCardHtml(e, { scope: e.scope, domain: e.domain }); }).join('')
|
|
396
411
|
: '<div class="dshmb-tip">这个会话还没有沉淀的记忆。点上方「整理记忆」让 AI 回顾起草,审过后进领域或全局。</div>';
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
}).catch(function () {
|
|
400
|
-
var tip = bodyEl.querySelector('.dshmb-tip');
|
|
401
|
-
if (tip) tip.textContent = '无法连接插件后端——确认 dsh-memory-domains 已启用。';
|
|
402
|
-
});
|
|
412
|
+
},
|
|
413
|
+
'无法连接插件后端——确认 dsh-memory-domains 已启用。');
|
|
403
414
|
}
|
|
404
415
|
|
|
405
416
|
function candCardHtml(e) {
|
|
406
|
-
var
|
|
417
|
+
var dd = e.domain ? domainBySlug(e.domain) : null;
|
|
418
|
+
var sug = dd ? dd.name : '';
|
|
407
419
|
var badge = '<span class="dshmb-badge' + (e.type === 'mistake' ? ' m' : '') + '">' + (TYPE_LABEL[e.type] || e.type) + '·草稿</span>';
|
|
408
420
|
if (e.domain) badge += '<span class="dshmb-badge d">建议:' + esc(sug || e.domain) + '</span>';
|
|
409
421
|
if (e.priority === 'high') badge += '<span class="dshmb-badge p">★高</span>';
|
|
@@ -436,23 +448,21 @@ window.__ModuleLoader__.load({
|
|
|
436
448
|
|
|
437
449
|
function renderCandidatesInto(container) {
|
|
438
450
|
candCache = {};
|
|
439
|
-
container
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
if (tip) tip.replaceWith(box); else container.appendChild(box);
|
|
448
|
-
}).catch(function () { if (tip) tip.textContent = '无法连接插件后端。'; });
|
|
451
|
+
fetchInto(container, API + '/candidates?session=' + encodeURIComponent(view.id),
|
|
452
|
+
function (j) {
|
|
453
|
+
var entries = (j && j.entries) || [];
|
|
454
|
+
entries.forEach(function (e) { candCache[e.id] = e; });
|
|
455
|
+
return entries.length ? entries.map(candCardHtml).join('')
|
|
456
|
+
: '<div class="dshmb-tip">没有待审草稿。点「整理记忆」让 AI 回顾这个会话。</div>';
|
|
457
|
+
},
|
|
458
|
+
'无法连接插件后端。');
|
|
449
459
|
}
|
|
450
460
|
|
|
451
461
|
/* ------------------------------------------------------------ 动作 */
|
|
452
462
|
|
|
453
|
-
// 面板上有"瞬态 UI"
|
|
454
|
-
// renderBody
|
|
455
|
-
//
|
|
463
|
+
// 面板上有"瞬态 UI"(新建/编辑表单、发现结果卡)时,自动轮询不重渲染——
|
|
464
|
+
// renderBody 虽已能保住顶层表单,但卡片墙重建仍会造成滚动/焦点抖动。
|
|
465
|
+
// 数据照常进内存,表单关闭或用户下一次交互自然带上新数据。
|
|
456
466
|
function hasTransientUI() {
|
|
457
467
|
return !!(bodyEl && bodyEl.querySelector('.dshmb-form, .dshmb-disc'));
|
|
458
468
|
}
|
|
@@ -500,17 +510,22 @@ window.__ModuleLoader__.load({
|
|
|
500
510
|
}).catch(function () { toast('请求失败'); });
|
|
501
511
|
}
|
|
502
512
|
|
|
513
|
+
// 轮询失败的统一出口:!ok 与 catch 同权(0.2.1/0.2.5 修过的坑——放弃时必须
|
|
514
|
+
// syncBar+renderBody,否则按钮永远卡「整理中」)。返回 true=已安排重试。
|
|
515
|
+
function pollFail(job) {
|
|
516
|
+
pollReview.fails = (pollReview.fails || 0) + 1;
|
|
517
|
+
if (pollReview.fails < 5) { reviewTimer = setTimeout(function () { pollReview(job); }, 2000); return true; }
|
|
518
|
+
pollReview.fails = 0;
|
|
519
|
+
reviewJob = null; reviewSessionId = null;
|
|
520
|
+
syncBar(); renderBody();
|
|
521
|
+
return false;
|
|
522
|
+
}
|
|
523
|
+
|
|
503
524
|
function pollReview(job) {
|
|
504
525
|
clearTimeout(reviewTimer);
|
|
505
526
|
api(API + '/review/status?job=' + encodeURIComponent(job)).then(function (j) {
|
|
506
527
|
if (!j || !j.ok) {
|
|
507
|
-
|
|
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();
|
|
528
|
+
if (pollFail(job)) return;
|
|
514
529
|
toast('整理状态丢失(可能宿主重启过)——草稿若已生成请查看待审区');
|
|
515
530
|
return;
|
|
516
531
|
}
|
|
@@ -526,14 +541,7 @@ window.__ModuleLoader__.load({
|
|
|
526
541
|
toast('整理失败:' + (j.error || ''));
|
|
527
542
|
syncBar(); renderBody();
|
|
528
543
|
}
|
|
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
|
-
});
|
|
544
|
+
}).catch(function () { pollFail(job); }); // fetch 抛错与 !ok 同权
|
|
537
545
|
}
|
|
538
546
|
|
|
539
547
|
function cardOp(op, id, el) {
|
|
@@ -572,8 +580,6 @@ window.__ModuleLoader__.load({
|
|
|
572
580
|
archive: post(API + '/archive', { scope: scope, domain: dom, id: id, archived: true }),
|
|
573
581
|
unarchive: post(API + '/archive', { scope: scope, domain: dom, id: id, archived: false }),
|
|
574
582
|
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
583
|
};
|
|
578
584
|
var p = calls[op];
|
|
579
585
|
if (!p) return;
|
|
@@ -671,9 +677,26 @@ window.__ModuleLoader__.load({
|
|
|
671
677
|
};
|
|
672
678
|
}
|
|
673
679
|
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
680
|
+
// 类型/优先级 chip 组:showCreateForm 与 showCandidateForm 共用。
|
|
681
|
+
// sel = { t, pri } 由调用方持有,wireChips 负责点击互斥高亮。
|
|
682
|
+
function chipsHtml(sel) {
|
|
683
|
+
return '<div class="dshmb-types">' +
|
|
684
|
+
['mistake', 'fact', 'skill', 'pref'].map(function (t) {
|
|
685
|
+
return '<span class="dshmb-tchip' + (t === sel.t ? ' on' : '') + '" data-t="' + t + '">' + (TYPE_LABEL[t] || t) + '</span>';
|
|
686
|
+
}).join('') + '</div>' +
|
|
687
|
+
'<div class="dshmb-types" style="margin-top:0"><span style="font-size:11px;align-self:center">优先级</span>' +
|
|
688
|
+
'<span class="dshmb-tchip' + (sel.pri === 'high' ? ' on' : '') + '" data-pri="high">★高</span>' +
|
|
689
|
+
'<span class="dshmb-tchip' + (sel.pri !== 'high' ? ' on' : '') + '" data-pri="normal">普通</span></div>';
|
|
690
|
+
}
|
|
691
|
+
function wireChips(div, sel) {
|
|
692
|
+
div.querySelectorAll('.dshmb-tchip').forEach(function (chip) {
|
|
693
|
+
chip.addEventListener('click', function () {
|
|
694
|
+
var k = chip.dataset.t ? 't' : chip.dataset.pri ? 'pri' : null;
|
|
695
|
+
if (!k) return;
|
|
696
|
+
sel[k] = chip.dataset[k];
|
|
697
|
+
div.querySelectorAll('[data-' + k + ']').forEach(function (c) { c.classList.toggle('on', c === chip); });
|
|
698
|
+
});
|
|
699
|
+
});
|
|
677
700
|
}
|
|
678
701
|
|
|
679
702
|
/* ---- 手动添加记忆 ---- */
|
|
@@ -683,32 +706,15 @@ window.__ModuleLoader__.load({
|
|
|
683
706
|
if (!loc) { toast('先打开一个领域或全局库'); return; }
|
|
684
707
|
var div = document.createElement('div');
|
|
685
708
|
div.className = 'dshmb-form';
|
|
686
|
-
var
|
|
687
|
-
var priVal = 'normal';
|
|
709
|
+
var sel = { t: 'mistake', pri: 'normal' };
|
|
688
710
|
div.innerHTML =
|
|
689
|
-
|
|
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>' +
|
|
711
|
+
chipsHtml(sel) +
|
|
696
712
|
'<input class="dshmb-f-title" placeholder="标题(一句话)">' +
|
|
697
713
|
'<textarea class="dshmb-f-content" placeholder="内容(自包含,脱离会话也能看懂)"></textarea>' +
|
|
698
714
|
'<input class="dshmb-f-ev" placeholder="来源/证据(可选)">' +
|
|
699
715
|
'<div style="display:flex;gap:8px"><button class="dshmb-act primary dshmb-f-ok">保存</button>' +
|
|
700
716
|
'<button class="dshmb-act dshmb-f-no">取消</button></div>';
|
|
701
|
-
div
|
|
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
|
-
});
|
|
717
|
+
wireChips(div, sel);
|
|
712
718
|
bodyEl.insertBefore(div, bodyEl.firstChild);
|
|
713
719
|
div.querySelector('.dshmb-f-no').onclick = function () { div.remove(); };
|
|
714
720
|
div.querySelector('.dshmb-f-ok').onclick = function () {
|
|
@@ -716,31 +722,22 @@ window.__ModuleLoader__.load({
|
|
|
716
722
|
var content = div.querySelector('.dshmb-f-content').value.trim();
|
|
717
723
|
var evidence = div.querySelector('.dshmb-f-ev').value.trim();
|
|
718
724
|
if (!title || !content) { toast('标题和内容都要填'); return; }
|
|
719
|
-
post(API + '/create', { scope: loc.scope, domain: loc.domain, type:
|
|
725
|
+
post(API + '/create', { scope: loc.scope, domain: loc.domain, type: sel.t, title: title, content: content, evidence: evidence, priority: sel.pri })
|
|
720
726
|
.then(function (j) { if (j.ok) { div.remove(); renderBody(); toast('已记下'); } else toast('失败:' + (j.error || '')); })
|
|
721
727
|
.catch(function () { toast('请求失败'); });
|
|
722
728
|
};
|
|
723
729
|
}
|
|
724
730
|
|
|
725
731
|
function showCandidateForm(entry) {
|
|
726
|
-
|
|
727
|
-
bodyEl.
|
|
728
|
-
|
|
729
|
-
if (b) card = c;
|
|
730
|
-
});
|
|
732
|
+
// 直接定位编辑按钮再取最近的卡片,不用遍历全部卡片逐个找
|
|
733
|
+
var btn = bodyEl.querySelector('[data-op="editcand"][data-id="' + entry.id + '"]');
|
|
734
|
+
var card = btn && btn.closest('.dshmb-card');
|
|
731
735
|
if (!card) return;
|
|
732
736
|
var div = document.createElement('div');
|
|
733
737
|
div.className = 'dshmb-form';
|
|
734
|
-
var
|
|
735
|
-
var priVal = entry.priority === 'high' ? 'high' : 'normal';
|
|
738
|
+
var sel = { t: entry.type || 'mistake', pri: entry.priority === 'high' ? 'high' : 'normal' };
|
|
736
739
|
div.innerHTML =
|
|
737
|
-
|
|
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>' +
|
|
740
|
+
chipsHtml(sel) +
|
|
744
741
|
'<input class="dshmb-f-title" placeholder="标题(一句话)" value="' + esc(entry.title || '') + '">' +
|
|
745
742
|
'<div class="dshmb-meta" style="margin:0">建议领域(slug,可改;留空=入库时再选)</div>' +
|
|
746
743
|
'<input class="dshmb-f-domain" placeholder="领域 slug(可选)" value="' + esc(entry.domain || '') + '">' +
|
|
@@ -748,17 +745,7 @@ window.__ModuleLoader__.load({
|
|
|
748
745
|
'<input class="dshmb-f-ev" placeholder="来源/证据(可选,msg#N 或说明)" value="' + esc(entry.evidence || '') + '">' +
|
|
749
746
|
'<div style="display:flex;gap:8px"><button class="dshmb-act primary dshmb-f-ok">保存修改</button>' +
|
|
750
747
|
'<button class="dshmb-act dshmb-f-no">取消</button></div>';
|
|
751
|
-
div
|
|
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
|
-
});
|
|
748
|
+
wireChips(div, sel);
|
|
762
749
|
card.appendChild(div);
|
|
763
750
|
div.querySelector('.dshmb-f-no').onclick = function () { div.remove(); };
|
|
764
751
|
div.querySelector('.dshmb-f-ok').onclick = function () {
|
|
@@ -767,7 +754,7 @@ window.__ModuleLoader__.load({
|
|
|
767
754
|
var content = div.querySelector('.dshmb-f-content').value.trim();
|
|
768
755
|
var evidence = div.querySelector('.dshmb-f-ev').value.trim();
|
|
769
756
|
if (!title || !content) { toast('标题和内容都要填'); return; }
|
|
770
|
-
post(API + '/candidates/update', { session: view.id, id: entry.id, type:
|
|
757
|
+
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
758
|
.then(function (j) { if (j.ok) { renderBody(); toast('已更新'); } else toast('失败:' + (j.error || '')); })
|
|
772
759
|
.catch(function () { toast('请求失败'); });
|
|
773
760
|
};
|
|
@@ -826,7 +813,7 @@ window.__ModuleLoader__.load({
|
|
|
826
813
|
return;
|
|
827
814
|
}
|
|
828
815
|
var stab = e.target.closest ? e.target.closest('[data-stab]') : null;
|
|
829
|
-
if (stab) { sessTab = stab.dataset.stab; renderBody(); return; }
|
|
816
|
+
if (stab) { sessTab = stab.dataset.stab; dropTopForms(); renderBody(); return; }
|
|
830
817
|
var more = e.target.closest ? e.target.closest('[data-more]') : null;
|
|
831
818
|
if (more) { showAllSessions = !showAllSessions; renderBody(); return; }
|
|
832
819
|
var addd = e.target.closest ? e.target.closest('[data-adddomain]') : null;
|
|
@@ -835,6 +822,7 @@ window.__ModuleLoader__.load({
|
|
|
835
822
|
if (dcard) {
|
|
836
823
|
view = { name: 'domain', slug: dcard.dataset.domain };
|
|
837
824
|
pickState = null;
|
|
825
|
+
dropTopForms();
|
|
838
826
|
syncBar(); renderBody();
|
|
839
827
|
return;
|
|
840
828
|
}
|
|
@@ -843,6 +831,7 @@ window.__ModuleLoader__.load({
|
|
|
843
831
|
view = scard.dataset.g ? { name: 'global' } : { name: 'session', id: scard.dataset.sid };
|
|
844
832
|
if (view.name === 'session') sessTab = 'mem';
|
|
845
833
|
pickState = null;
|
|
834
|
+
dropTopForms();
|
|
846
835
|
syncBar(); renderBody();
|
|
847
836
|
}
|
|
848
837
|
});
|
|
@@ -867,6 +856,7 @@ window.__ModuleLoader__.load({
|
|
|
867
856
|
showAllSessions = false;
|
|
868
857
|
warmTries = 0;
|
|
869
858
|
pickState = null;
|
|
859
|
+
dropTopForms(); // 上次会话残留的表单不带进新会话
|
|
870
860
|
syncBar();
|
|
871
861
|
refreshDomains();
|
|
872
862
|
refreshSessions();
|
|
@@ -877,22 +867,12 @@ window.__ModuleLoader__.load({
|
|
|
877
867
|
}
|
|
878
868
|
}
|
|
879
869
|
|
|
880
|
-
|
|
881
|
-
|
|
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
|
-
|
|
870
|
+
// 面板开关状态存在模块级 openFlag;按钮文案静态,不需要 React state——
|
|
871
|
+
// useOpen/subs 那套同步机制是死代码(effect 只在挂载时跑一次,subs 无人读取)。
|
|
891
872
|
function Trigger() {
|
|
892
|
-
var open = useOpen();
|
|
893
873
|
return h('button', {
|
|
894
874
|
className: 'dshmb-btn', type: 'button', title: '记忆库:领域知识库,人审策展',
|
|
895
|
-
onClick: function (e) { e.preventDefault(); setOpen(!
|
|
875
|
+
onClick: function (e) { e.preventDefault(); setOpen(!openFlag); },
|
|
896
876
|
}, '🧠 记忆库');
|
|
897
877
|
}
|
|
898
878
|
|
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.
|
|
24
|
+
export const version = '0.2.7'
|
|
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
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
|
|
@@ -154,6 +158,8 @@ function readBody(req) {
|
|
|
154
158
|
req.on('data', c => { data += c; if (data.length > 1_000_000) req.destroy() })
|
|
155
159
|
req.on('end', () => { try { resolve(data ? JSON.parse(data) : {}) } catch (e) { reject(e) } })
|
|
156
160
|
req.on('error', reject)
|
|
161
|
+
// 超限 destroy 后 end/error 都可能不再触发——close 兜底,否则 Promise 永不 settle、请求挂死
|
|
162
|
+
req.on('close', () => reject(new Error('request aborted')))
|
|
157
163
|
})
|
|
158
164
|
}
|
|
159
165
|
|
|
@@ -166,11 +172,13 @@ function domainList() {
|
|
|
166
172
|
const api = {
|
|
167
173
|
// GET /api/sessions — 会话清单(秒回:标题走缓存,pending>0 表示后台还在预热)
|
|
168
174
|
'GET /api/sessions': async () => {
|
|
169
|
-
// 预热只在 apply 跑一次;运行期新会话靠这里自愈(pending>0
|
|
170
|
-
|
|
175
|
+
// 预热只在 apply 跑一次;运行期新会话靠这里自愈(pending>0 时补一轮,幂等+防重入)。
|
|
176
|
+
// sessionsPending 内部要全量 stat 会话目录——算一次存变量,别重复调。
|
|
177
|
+
const pending = sessionsPending()
|
|
178
|
+
if (pending > 0) warmSessionMeta().catch(() => {})
|
|
171
179
|
return {
|
|
172
180
|
ok: true,
|
|
173
|
-
pending
|
|
181
|
+
pending,
|
|
174
182
|
sessions: listSessions(CURRENT.sessionsDir, { parseTitles: false }).map(s => ({
|
|
175
183
|
id: s.id, title: s.title || s.id,
|
|
176
184
|
cwd: s.cwd ? String(s.cwd).split(/[\\/]/).pop() : '', // 只回 basename,不泄整机路径
|
|
@@ -221,7 +229,8 @@ const api = {
|
|
|
221
229
|
|
|
222
230
|
// GET /api/memories?scope=domain&domain=<slug> | scope=global | scope=all&session=<sid>&archived=1
|
|
223
231
|
'GET /api/memories': async (req, url) => {
|
|
224
|
-
const
|
|
232
|
+
const scopeParam = url.searchParams.get('scope')
|
|
233
|
+
const scope = ['domain', 'global', 'all'].includes(scopeParam) ? scopeParam : 'all'
|
|
225
234
|
const includeArchived = url.searchParams.get('archived') === '1'
|
|
226
235
|
const session = url.searchParams.get('session') || ''
|
|
227
236
|
let entries
|
|
@@ -237,10 +246,10 @@ const api = {
|
|
|
237
246
|
},
|
|
238
247
|
|
|
239
248
|
// GET /api/candidates?session=<id>
|
|
240
|
-
'GET /api/candidates': async (req, url) =>
|
|
241
|
-
|
|
242
|
-
entries: store.listCandidates(CURRENT.memoryDir,
|
|
243
|
-
}
|
|
249
|
+
'GET /api/candidates': async (req, url) => {
|
|
250
|
+
const session = url.searchParams.get('session') || ''
|
|
251
|
+
return { ok: true, session, entries: store.listCandidates(CURRENT.memoryDir, session) }
|
|
252
|
+
},
|
|
244
253
|
|
|
245
254
|
// POST /api/review {session} — 异步整理:解轨迹→AI起草→候选区
|
|
246
255
|
'POST /api/review': async (req) => {
|
|
@@ -323,8 +332,7 @@ const api = {
|
|
|
323
332
|
// POST /api/archive {scope, domain?, id, archived}
|
|
324
333
|
'POST /api/archive': async (req) => {
|
|
325
334
|
const b = await readBody(req)
|
|
326
|
-
const
|
|
327
|
-
const e = store.updateMemory(CURRENT.memoryDir, scope, b.domain, String(b.id || ''),
|
|
335
|
+
const e = store.updateMemory(CURRENT.memoryDir, scopeOf(b), b.domain, String(b.id || ''),
|
|
328
336
|
{ status: b.archived === false ? 'active' : 'archived' })
|
|
329
337
|
return e ? { ok: true, entry: e } : jsonErr(404, '条目不存在')
|
|
330
338
|
},
|
|
@@ -332,8 +340,7 @@ const api = {
|
|
|
332
340
|
// POST /api/priority {scope, domain?, id, priority:'high'|'normal'} — 入库后调优先级
|
|
333
341
|
'POST /api/priority': async (req) => {
|
|
334
342
|
const b = await readBody(req)
|
|
335
|
-
const
|
|
336
|
-
const e = store.updateMemory(CURRENT.memoryDir, scope, b.domain, String(b.id || ''),
|
|
343
|
+
const e = store.updateMemory(CURRENT.memoryDir, scopeOf(b), b.domain, String(b.id || ''),
|
|
337
344
|
{ priority: b.priority === 'high' ? 'high' : 'normal' })
|
|
338
345
|
return e ? { ok: true, entry: e } : jsonErr(404, '条目不存在')
|
|
339
346
|
},
|
|
@@ -341,8 +348,7 @@ const api = {
|
|
|
341
348
|
// POST /api/delete {scope, domain?, id}
|
|
342
349
|
'POST /api/delete': async (req) => {
|
|
343
350
|
const b = await readBody(req)
|
|
344
|
-
|
|
345
|
-
return store.deleteMemory(CURRENT.memoryDir, scope, b.domain, String(b.id || ''))
|
|
351
|
+
return store.deleteMemory(CURRENT.memoryDir, scopeOf(b), b.domain, String(b.id || ''))
|
|
346
352
|
? { ok: true } : jsonErr(404, '条目不存在')
|
|
347
353
|
},
|
|
348
354
|
|
|
@@ -350,7 +356,7 @@ const api = {
|
|
|
350
356
|
'POST /api/create': async (req) => {
|
|
351
357
|
const b = await readBody(req)
|
|
352
358
|
if (!b.title || !b.content) return jsonErr(400, 'title/content required')
|
|
353
|
-
const scope = b
|
|
359
|
+
const scope = scopeOf(b)
|
|
354
360
|
try {
|
|
355
361
|
const e = store.addMemory(CURRENT.memoryDir, {
|
|
356
362
|
scope, domain: b.domain, type: b.type, title: b.title, content: b.content,
|
|
@@ -362,6 +368,8 @@ const api = {
|
|
|
362
368
|
}
|
|
363
369
|
|
|
364
370
|
function jsonErr(code, error) { return { ok: false, error, _code: code } }
|
|
371
|
+
// scope 参数归一:只认 'global',其余一律按 'domain' 处理(与前端 data-scope 约定一致)
|
|
372
|
+
const scopeOf = b => (b.scope === 'global' ? 'global' : 'domain')
|
|
365
373
|
|
|
366
374
|
/* ---- 本机 API 防浏览器跨站调用(记忆投毒/删除是核心威胁)----
|
|
367
375
|
* 浏览器跨域请求必带 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'
|
|
40
|
-
//
|
|
41
|
-
const m = String(text || '').match(/\[[^\[\]]*\]/)
|
|
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 ||
|
|
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
|
-
|
|
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,
|
|
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
|
-
|
|
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
|
}
|
|
@@ -93,9 +96,9 @@ export function addDomain(dir, { name, desc }) {
|
|
|
93
96
|
if (!name) throw new Error('领域名称必填')
|
|
94
97
|
if (!desc) throw new Error('领域描述必填——它是 agent 检索时的路标')
|
|
95
98
|
const domains = listDomains(dir)
|
|
96
|
-
|
|
97
|
-
let i = 2
|
|
98
|
-
while (domains.some(d => d.slug === slug)) slug =
|
|
99
|
+
const base = slugify(name)
|
|
100
|
+
let slug = base, i = 2
|
|
101
|
+
while (domains.some(d => d.slug === slug)) slug = `${base}-${i++}`
|
|
99
102
|
const d = { slug, name, desc, created_at: new Date().toISOString() }
|
|
100
103
|
domains.push(d)
|
|
101
104
|
saveDomains(dir, domains)
|
|
@@ -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:
|
|
186
|
-
title:
|
|
187
|
-
content:
|
|
188
|
-
...(entry.evidence ? { evidence:
|
|
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 =
|
|
219
|
-
if (clean.content !== undefined) clean.content =
|
|
220
|
-
if (clean.evidence !== undefined) clean.evidence =
|
|
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:
|
|
283
|
+
...(draft.domain ? { domain: clip(draft.domain, 50) } : {}), // AI 建议的领域 slug(可能为空)
|
|
281
284
|
...(draft.priority === 'high' ? { priority: 'high' } : {}), // AI 建议的优先级(normal 缺省不存)
|
|
282
|
-
title:
|
|
283
|
-
content:
|
|
284
|
-
...(draft.evidence ? { evidence:
|
|
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:
|
|
338
|
-
...(patch.content != null ? { content:
|
|
339
|
-
...(patch.evidence != null ? { evidence:
|
|
340
|
-
...(patch.domain != null ? { domain:
|
|
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
|