@sanqianx/project-knowledge 5.2.0 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +4 -0
  3. package/README.md +6 -0
  4. package/_site/_test/automatic-context-test.js +6 -0
  5. package/_site/_test/context-session-index-test.js +19 -9
  6. package/_site/_test/helpers/parallel-memory-shell.js +15 -7
  7. package/_site/_test/helpers/parallel-qa-engine-endpoint-isolate.js +3 -1
  8. package/_site/_test/memory-groups-ui-test.js +27 -3
  9. package/_site/_test/parallel-capture-safety-r5-mem005-health-test.js +2 -2
  10. package/_site/_test/parallel-engine-final-eng012-test.js +4 -4
  11. package/_site/_test/parallel-memory-candidate-test.js +7 -5
  12. package/_site/_test/parallel-memory-capture-r3-mem005-persistence-test.js +1 -1
  13. package/_site/_test/parallel-memory-capture-r4-mem005-health-test.js +2 -2
  14. package/_site/_test/parallel-memory-home-review-test.js +1 -1
  15. package/_site/_test/parallel-memory-manual-test.js +14 -25
  16. package/_site/_test/parallel-memory-scope-test.js +66 -264
  17. package/_site/_test/parallel-memory-source-test.js +5 -7
  18. package/_site/_test/parallel-memory-sync-test.js +8 -8
  19. package/_site/_test/parallel-qa-engine-endpoint-guard-test.js +4 -2
  20. package/_site/_test/project-team-ui-test.js +54 -46
  21. package/_site/_test/shared-scope-root-binding-test.js +7 -6
  22. package/_site/_test/t07f-mem-008-coverage-test.js +0 -1
  23. package/_site/lib/engine-connection.js +2 -2
  24. package/_site/lib/engine-knowledge-client.js +1 -1
  25. package/_site/scripts/verify-retrieval-gold.js +10 -13
  26. package/module-runtime-manifest.json +26 -25
  27. package/package.json +3 -3
  28. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  29. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  30. package/plugins/project-knowledge/.mcp.json +1 -1
  31. package/plugins/project-knowledge/scripts/context-hook.cjs +3 -3
  32. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +5 -6
  33. package/ui/product.js +147 -65
package/ui/product.js CHANGED
@@ -25,7 +25,7 @@
25
25
  overview: null, overviewError: null, overviewLoading: false, overviewEpoch: 0,
26
26
  groups: { items: [], total: 0, loading: false, epoch: 0 },
27
27
  memory: { tab: 'library', folder: 'all', q: '', items: [], total: 0, cursors: [null], page: 0, loading: false, epoch: 0 },
28
- candidates: { items: [], total: 0, cursors: [null], page: 0, loading: false, epoch: 0 },
28
+ candidates: { items: [], total: 0, cursors: [null], page: 0, projectFilter: null, loading: false, epoch: 0 },
29
29
  projects: [], projectsPage: { q: '', domain: '', items: [], total: 0, cursors: [null], page: 0, loading: false, epoch: 0, detail: null },
30
30
  detailGroups: { detail: null, epoch: 0 },
31
31
  search: { q: '', draft: '', projectId: '', scope: 'brain', type: 'all', done: false, results: [], page: 0, loading: false, epoch: 0 },
@@ -39,7 +39,6 @@
39
39
  const projectName = id => state.projects.find(p => p.projectId === id)?.name || id;
40
40
  const time = value => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : '—';
41
41
  const clamp2 = text => String(text || '').replace(/\n\s*\n/g, '\n');
42
- const SCOPE_LABEL = { project: '项目记忆', domain: '领域记忆', global: '全局记忆', group: '组合记忆' };
43
42
  const recoveryLabel = run => {
44
43
  const recovery = run.recovery;
45
44
  if (['failed', 'index-pending'].includes(run.state)) {
@@ -244,6 +243,7 @@
244
243
  function selectProject(id) {
245
244
  if (id === state.projectId && activeProject()) return;
246
245
  state.projectId = id; state.epoch++;
246
+ if (state.candidates.projectFilter === null) { state.candidates.page = 0; state.candidates.cursors = [null]; }
247
247
  state.snapshot.runs = []; state.activityProject = null; state.activityBefore = null; state.runDetails = new Map();
248
248
  void refreshSnapshot();
249
249
  referenceEpoch++; $('referenceDialog').close();
@@ -378,7 +378,7 @@
378
378
  ${overview.totals?.recovering ? `<div class="recovery-banner">${overview.totals?.recovering} 项正在自动恢复,无需操作<button data-action="activity-recovering">查看</button></div>` : ''}
379
379
  </section>
380
380
  <section class="panel"><h2>待确认记忆 ${overview.totals?.candidates ? badge(overview.totals?.candidates, '') : ''}</h2>${candidateRows}
381
- ${overview.totals?.candidates > candidates.length ? '<button data-go="memory">查看候选箱</button>' : ''}
381
+ ${overview.totals?.candidates > candidates.length ? '<button data-go="memory" data-memory-tab="candidate">查看候选箱</button>' : ''}
382
382
  </section>
383
383
  </div>
384
384
  ${teamSummaryCard()}
@@ -388,13 +388,18 @@
388
388
  async function loadGroups() {
389
389
  const epoch = ++state.groups.epoch;
390
390
  state.groups.loading = true;
391
+ let groups = state.groups.items;
391
392
  try {
392
393
  const result = await api('/api/engine/memory-groups?limit=100');
393
- if (epoch !== state.groups.epoch) return;
394
- state.groups.items = result.groups; state.groups.total = result.total;
394
+ groups = result.groups;
395
+ if (epoch === state.groups.epoch) {
396
+ state.groups.items = groups;
397
+ state.groups.total = result.total;
398
+ }
395
399
  } catch (error) { if (epoch === state.groups.epoch) toast('组合列表读取失败:' + error.message); }
396
400
  finally { if (epoch === state.groups.epoch) state.groups.loading = false; }
397
- if (state.view === 'memory') renderMemories();
401
+ if (epoch === state.groups.epoch && state.view === 'memory') renderMemories();
402
+ return groups;
398
403
  }
399
404
  const groupById = id => state.groups.items.find(g => g.id === id);
400
405
  async function loadMemoryPage() {
@@ -416,24 +421,44 @@
416
421
  finally { if (epoch === memory.epoch) memory.loading = false; }
417
422
  if (state.view === 'memory') renderMemories();
418
423
  }
424
+ const candidateProjectId = () => state.candidates.projectFilter ?? activeProject()?.projectId ?? '';
425
+ const candidateSourceProjectId = memory => memory.evidence?.projectId || null;
426
+ async function projectCandidates(projectId) {
427
+ const params = new URLSearchParams({ status: 'candidate', sourceProjectId: projectId });
428
+ const result = await api('/api/engine/memories?' + params);
429
+ return result.memories.filter(memory => candidateSourceProjectId(memory) === projectId)
430
+ .sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || '')) || a.id.localeCompare(b.id));
431
+ }
419
432
  async function loadCandidates() {
420
433
  const candidates = state.candidates;
421
434
  const epoch = ++candidates.epoch;
422
435
  candidates.loading = true;
436
+ const projectId = candidateProjectId();
437
+ if (state.view === 'memory' && state.memory.tab === 'candidate') renderMemories();
423
438
  try {
424
- const params = new URLSearchParams({ status: 'candidate', limit: '10' });
425
- const cursor = candidates.cursors[candidates.page];
426
- if (cursor) params.set('cursor', cursor);
427
- const result = await api('/api/engine/memories?' + params);
428
- if (epoch !== candidates.epoch) return;
429
- candidates.items = result.memories; candidates.total = result.total;
430
- if (result.nextCursor) candidates.cursors[candidates.page + 1] = result.nextCursor; else candidates.cursors.length = candidates.page + 1;
439
+ if (projectId) {
440
+ const items = await projectCandidates(projectId);
441
+ if (epoch !== candidates.epoch) return;
442
+ candidates.total = items.length;
443
+ candidates.page = Math.min(candidates.page, Math.max(0, Math.ceil(items.length / 10) - 1));
444
+ const start = candidates.page * 10;
445
+ candidates.items = items.slice(start, start + 10);
446
+ candidates.cursors = Array.from({ length: Math.ceil(items.length / 10) }, (_, page) => page * 10);
447
+ } else {
448
+ const params = new URLSearchParams({ status: 'candidate', limit: '10' });
449
+ const cursor = candidates.cursors[candidates.page];
450
+ if (cursor) params.set('cursor', cursor);
451
+ const result = await api('/api/engine/memories?' + params);
452
+ if (epoch !== candidates.epoch) return;
453
+ candidates.items = result.memories; candidates.total = result.total;
454
+ if (result.nextCursor) candidates.cursors[candidates.page + 1] = result.nextCursor; else candidates.cursors.length = candidates.page + 1;
455
+ }
431
456
  } catch (error) { if (epoch === candidates.epoch) toast('候选列表读取失败:' + error.message); }
432
457
  finally { if (epoch === candidates.epoch) candidates.loading = false; }
433
458
  if (state.view === 'memory') renderMemories();
434
459
  }
435
460
  function memoryCard(m) {
436
- const scopeText = m.scopeType === 'group' ? (m.groups?.length ? `组合:${m.groups.map(g => esc(g.name)).join('、')}` : '未归组合') : `${SCOPE_LABEL[m.scopeType] || ''} · ${m.scopeType === 'domain' ? esc(domainName(m.scopeId)) : m.scopeType === 'project' ? esc(projectName(m.scopeId)) : '所有项目'}`;
461
+ const scopeText = m.groups?.length ? `组合:${m.groups.map(g => esc(g.name)).join('、')}` : '未归组合';
437
462
  const statusBadge = m.targetAvailable === false ? badge('目标已失效,不会注入', 'issue') : m.syncStatus === 'pending' ? badge('写入待恢复', 'issue') : '';
438
463
  return `<article class="memory-item"><button class="reference" data-action="memory-detail" data-id="${esc(m.id)}"><b>${esc(m.title)}</b><small>${esc(clamp2(m.text).slice(0, 160))}</small><small>${scopeText}</small></button><div class="actions">${statusBadge}<button data-action="memory-edit" data-id="${esc(m.id)}">编辑</button><button data-action="memory-groups" data-id="${esc(m.id)}">组合归属</button>${m.sourceType !== 'manual' ? `<button data-action="memory-evidence" data-id="${esc(m.id)}">查看依据</button>` : ''}<button data-action="memory-delete" data-id="${esc(m.id)}">删除</button></div></article>`;
439
464
  }
@@ -446,9 +471,12 @@
446
471
  if (!state.engineAvailable) { $('memoryContent').innerHTML = '<div class="empty">知识引擎暂时不可用。未读取到的记忆不会显示为已确认。</div>'; return; }
447
472
  const memory = state.memory, candidates = state.candidates;
448
473
  if (memory.tab === 'candidate') {
474
+ const projectId = candidateProjectId();
475
+ const projectOptions = ['<option value="">全部项目</option>', ...state.projects.map(project => `<option value="${esc(project.projectId)}" ${project.projectId === projectId ? 'selected' : ''}>${esc(project.name)}</option>`)].join('');
449
476
  const rows = candidates.items.map(m => `<div class="row"><div><b>${esc(m.title)}</b><small>${esc(clamp2(m.text).slice(0, 140))}</small><small>${m.evidence ? `来源:${esc(projectName(m.evidence.projectId))} · ${esc(m.evidence.commitSha.slice(0, 8))}` : '来源:手动添加'}</small></div><button class="primary" data-action="review-candidate" data-id="${esc(m.id)}">审核</button></div>`).join('');
450
477
  $('memoryContent').innerHTML = `<div class="segmented" style="margin-bottom:20px"><button data-memory-tab="library">记忆库</button><button class="active" data-memory-tab="candidate">候选箱 ${candidates.total || ''}</button></div>
451
- ${rows || '<div class="empty small-empty">候选箱为空。维护产物中的有据偏好会进入这里,等待你的确认。</div>'}
478
+ <label>按项目查看<select id="candidateProjectFilter">${projectOptions}</select></label>
479
+ ${candidates.loading ? '<p class="small-empty">正在读取候选…</p>' : rows || '<div class="empty small-empty">这个范围内没有待确认的记忆。</div>'}
452
480
  ${pagerUi('candidate', candidates.page, candidates.total, 10)}`;
453
481
  return;
454
482
  }
@@ -584,7 +612,7 @@
584
612
  const project = state.projectsPage.items.find(p => p.projectId === detail.projectId);
585
613
  if (!project) { state.projectsPage.detail = null; return renderProjects(); }
586
614
  const effective = detail.effective;
587
- const items = effective.items.map(m => `<article class="memory-item"><button class="reference" data-action="memory-detail" data-id="${esc(m.id)}"><b>${esc(m.title)}</b><small>${esc(clamp2(m.text).slice(0, 160))}</small><small>${(m.sources || []).map(s => s.kind === 'group' ? `组合:${esc(s.groupName)}` : `${SCOPE_LABEL[s.scopeType] || '作用域'}`).join(' · ')}</small></button></article>`).join('') || '<div class="empty small-empty">为项目添加组合后,在这里查看生效记忆。</div>';
615
+ const items = effective.items.map(m => `<article class="memory-item"><button class="reference" data-action="memory-detail" data-id="${esc(m.id)}"><b>${esc(m.title)}</b><small>${esc(clamp2(m.text).slice(0, 160))}</small><small>${(m.sources || []).map(s => esc(s.groupName)).join(' · ')}</small></button></article>`).join('') || '<div class="empty small-empty">为项目添加组合后,在这里查看生效记忆。</div>';
588
616
  $('projectsContent').innerHTML = `
589
617
  <div class="section-heading"><button class="link-button" data-action="project-list">‹ 返回项目列表</button><div class="actions"><button data-action="unbind">解绑并保留数据</button><button data-action="edit-project" data-id="${esc(project.projectId)}">项目设置</button></div></div>
590
618
  <h2>${esc(project.name)}</h2><p>${esc(domainName(project.domainId))}</p>
@@ -592,10 +620,42 @@
592
620
  <section class="panel" style="margin-top:20px"><div class="section-heading" style="margin-bottom:12px"><h2>使用的组合</h2><button data-action="project-groups" data-id="${esc(project.projectId)}">+ 添加组合</button></div>
593
621
  <div class="group-tags">${detail.groups.map(g => groupTag(g, project.projectId)).join('') || '<small>尚未添加组合</small>'}</div></section>
594
622
  <section class="panel" style="margin-top:20px"><div class="section-heading"><h2>AI 团队</h2>${projectTeamControl(project.projectId)}</div></section>
595
- <section class="panel" style="margin-top:20px"><h2>生效记忆 <small>${effective.total} 条 · 已按记忆去重</small></h2>
623
+ <section class="panel" style="margin-top:20px"><div class="section-heading"><h2>生效记忆 <small>${effective.total} 条 · 已按记忆去重</small></h2>
624
+ <button data-action="export-memories" data-id="${esc(project.projectId)}" ${effective.total ? '' : 'disabled'}>导出 Markdown</button></div>
596
625
  <div class="memory-list">${items}</div>
597
626
  ${pagerUi('effective', effective.page, effective.total, 10)}</section>`;
598
627
  }
628
+ async function exportProjectMemories(projectId) {
629
+ const project = state.projectsPage.items.find(item => item.projectId === projectId);
630
+ if (!project) return;
631
+ const items = new Map(), cursors = new Set();
632
+ let cursor = null, total = null;
633
+ do {
634
+ const params = new URLSearchParams({ limit: '100' });
635
+ if (cursor) params.set('cursor', cursor);
636
+ const page = await api(`/api/engine/projects/${encodeURIComponent(projectId)}/effective-memories?${params}`);
637
+ total ??= page.total;
638
+ if (page.total !== total || (page.nextCursor && cursors.has(page.nextCursor))) throw new Error('生效记忆列表已变化,请重新导出。');
639
+ for (const memory of page.memories) items.set(memory.id, memory);
640
+ cursor = page.nextCursor;
641
+ if (cursor) cursors.add(cursor);
642
+ } while (cursor);
643
+ if (items.size !== total) throw new Error('生效记忆列表已变化,请重新导出。');
644
+ const memories = [...items.values()].filter(memory => memory.syncStatus === 'ready' && memory.targetAvailable && memory.sources.some(source => source.kind === 'group'));
645
+ if (!memories.length) return toast('当前没有已同步的生效记忆。');
646
+ const sections = memories.map(memory => {
647
+ const sources = memory.sources.map(source => source.groupName);
648
+ const provenance = memory.evidence ? [projectName(memory.evidence.projectId), memory.evidence.entryId, memory.evidence.commitSha].filter(Boolean).join(' / ') : '';
649
+ return `## ${memory.title}\n\n${memory.text}\n\n生效来源:${sources.join('、')}${provenance ? `\n\n依据:${provenance}` : ''}\n`;
650
+ });
651
+ const markdown = `# ${project.name.replace(/[\r\n]+/g, ' ')} · 生效记忆\n\n${sections.join('\n')}`;
652
+ const url = URL.createObjectURL(new Blob([markdown], { type: 'text/markdown;charset=utf-8' }));
653
+ const link = document.createElement('a');
654
+ link.href = url;
655
+ link.download = `${project.name.replace(/[<>:"/\\|?*\x00-\x1f]/g, '-').trim() || 'project'}-MEMORY.md`;
656
+ link.click();
657
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
658
+ }
599
659
  // ============ 检索:真实引擎 API ============
600
660
  function renderSearch() {
601
661
  const search = state.search;
@@ -604,7 +664,7 @@
604
664
  let resultsHtml = '<div class="empty small-empty">输入关键词,查找已保存的项目知识和长期记忆。</div>';
605
665
  if (search.done) {
606
666
  const filtered = search.results.filter(r => search.type === 'all' || (search.type === 'memory') === Boolean(r.memoryId));
607
- const pageRows = filtered.slice(search.page * 8, (search.page + 1) * 8).map((r, i) => `<article class="result-row"><button class="reference" data-action="search-detail" data-index="${search.page * 8 + i}"><b>${esc(r.title)}</b><small>${esc(clamp2(r.snippet || r.chunk_text || '').slice(0, 180))}</small></button><small>${r.memoryId ? `长期记忆${r.memoryScopeType && r.memoryScopeType !== 'group' ? ' · ' + (SCOPE_LABEL[r.memoryScopeType] || '') : ''}` : `${esc(projectName(r.scope_project_id || r.projectId))}${r.commitSha ? ` · commit ${esc(r.commitSha.slice(0, 8))}` : ''}`}</small></article>`).join('');
667
+ const pageRows = filtered.slice(search.page * 8, (search.page + 1) * 8).map((r, i) => `<article class="result-row"><button class="reference" data-action="search-detail" data-index="${search.page * 8 + i}"><b>${esc(r.title)}</b><small>${esc(clamp2(r.snippet || r.chunk_text || '').slice(0, 180))}</small></button><small>${r.memoryId ? '长期记忆' : `${esc(projectName(r.scope_project_id || r.projectId))}${r.commitSha ? ` · commit ${esc(r.commitSha.slice(0, 8))}` : ''}`}</small></article>`).join('');
608
668
  resultsHtml = `<p class="muted" style="margin:12px 0">${search.results.length} 条结果${filtered.length !== search.results.length ? `(当前筛选 ${filtered.length} 条)` : ''}</p>${pageRows || '<div class="empty small-empty">没有找到匹配内容,试试其他关键词。</div>'}${pagerUi('search', search.page, filtered.length, 8)}`;
609
669
  }
610
670
  $('searchContent').innerHTML = `
@@ -1187,58 +1247,31 @@
1187
1247
  function memoryById(id) {
1188
1248
  return state.memory.items.find(m => m.id === id) || state.candidates.items.find(m => m.id === id) || state.detailGroups.detail?.effective.items.find(m => m.id === id);
1189
1249
  }
1190
- // ---- 记忆编辑器(标题 + 多行正文 + 可选组合/作用域) ----
1191
- function memoryEditor(memory = null) {
1192
- const isLegacy = memory && memory.scopeType !== 'group';
1193
- const groupOptions = ['<option value="">暂不加入组合</option>', ...state.groups.items.map(g => `<option value="${esc(g.id)}" ${memory?.groups?.[0]?.id === g.id ? 'selected' : ''}>${esc(g.name)}</option>`)].join('');
1194
- const scopeOptions = isLegacy || !memory
1195
- ? `<label>适用范围<select name="scopeType"><option value="group" ${!isLegacy ? 'selected' : ''}>组合记忆:通过组合应用到项目</option><option value="global" ${memory?.scopeType === 'global' ? 'selected' : ''}>全局:所有领域与项目</option><option value="domain" ${memory?.scopeType === 'domain' ? 'selected' : ''}>领域:指定领域内的项目</option><option value="project" ${memory?.scopeType === 'project' ? 'selected' : ''}>项目:仅指定项目</option></select></label>
1196
- <label data-role="scope-target" hidden>适用目标<select name="scopeTarget"></select></label>`
1197
- : '';
1250
+ async function memoryEditor(memory = null) {
1251
+ const groups = memory ? state.groups.items : await loadGroups();
1252
+ const groupOptions = ['<option value="">暂不加入组合</option>', ...groups.map(g => `<option value="${esc(g.id)}" ${memory?.groups?.[0]?.id === g.id ? 'selected' : ''}>${esc(g.name)}</option>`)].join('');
1198
1253
  appDialogOpen(memory ? '编辑记忆' : '添加记忆', `
1199
1254
  <form id="memoryForm">
1200
1255
  <label>标题<input name="title" maxlength="120" required value="${esc(memory?.title || '')}" placeholder="例如:开发时保护日常服务"></label>
1201
1256
  <label>内容<textarea name="text" required rows="8" placeholder="这是一条完整记忆,可以包含多个段落和列表。">${esc(memory?.text || '')}</textarea></label>
1202
1257
  ${memory ? '' : `<label>加入组合<select name="groupId">${groupOptions}</select></label>`}
1203
- ${scopeOptions}
1204
- <p class="muted">${memory?.scopeType === 'group' ? '这条记忆通过组合应用到项目;正文只有一份,被所有引用共享。' : '多段正文保存在同一条记忆中,不会按换行拆分。'}</p>
1258
+ <p class="muted">记忆通过组合生效。各组合共享同一条正文。</p>
1205
1259
  </form>`, [
1206
1260
  { label: '取消', run: appDialogClose },
1207
1261
  { label: memory ? '保存' : '添加', class: 'primary', form: 'memoryForm' },
1208
1262
  ]);
1209
1263
  const form = $('memoryForm');
1210
- const scopeSelect = form.elements.scopeType;
1211
- const targetLabel = form.querySelector('[data-role="scope-target"]');
1212
- const fillTargets = type => {
1213
- const targets = type === 'domain' ? state.brain.domains.map(d => ({ id: d.id, name: d.name })) : type === 'project' ? state.projects.map(p => ({ id: p.projectId, name: p.name })) : [];
1214
- targetLabel.hidden = targets.length === 0;
1215
- form.elements.scopeTarget.innerHTML = targets.map(t => `<option value="${esc(t.id)}" ${memory?.scopeId === t.id ? 'selected' : ''}>${esc(t.name)}</option>`).join('');
1216
- };
1217
- if (scopeSelect) {
1218
- fillTargets(scopeSelect.value);
1219
- scopeSelect.addEventListener('change', () => fillTargets(scopeSelect.value));
1220
- }
1221
1264
  form.addEventListener('submit', async event => {
1222
1265
  event.preventDefault();
1223
1266
  const title = form.elements.title.value.trim();
1224
1267
  const text = form.elements.text.value.trim();
1225
1268
  if (!title || !text) return appDialogError('请填写标题和记忆内容。');
1226
- const scopeType = form.elements.scopeType?.value || 'group';
1227
- if (scopeType !== 'group' && scopeType !== 'global' && !form.elements.scopeTarget?.value) return appDialogError('请选择适用目标。');
1228
1269
  try {
1229
- let saved;
1230
1270
  if (memory) {
1231
- const body = { title, text };
1232
- if (form.elements.scopeType && (memory.scopeType !== scopeType || scopeType !== 'group')) {
1233
- body.scopeType = scopeType;
1234
- body.scopeId = scopeType === 'global' ? state.brain.id : form.elements.scopeTarget?.value;
1235
- }
1236
- saved = await api(`/api/engine/memories/${encodeURIComponent(memory.id)}`, { method: 'PATCH', body });
1271
+ await api(`/api/engine/memories/${encodeURIComponent(memory.id)}`, { method: 'PATCH', body: { title, text } });
1237
1272
  } else {
1238
- const body = { title, text, brainId: state.brain.id, scopeType, scopeId: scopeType === 'group' || scopeType === 'global' ? state.brain.id : form.elements.scopeTarget?.value };
1239
- saved = await api('/api/engine/memories', { method: 'POST', body });
1240
- const groupId = form.elements.groupId?.value;
1241
- if (groupId) await api(`/api/engine/memory-groups/${encodeURIComponent(groupId)}/members`, { method: 'POST', body: { addMemoryIds: [saved.memory.id] } });
1273
+ const groupId = form.elements.groupId.value;
1274
+ await api('/api/engine/memories', { method: 'POST', body: { title, text, brainId: state.brain.id, ...(groupId ? { groupId } : {}) } });
1242
1275
  }
1243
1276
  appDialogClose();
1244
1277
  toast(memory ? '记忆已保存,多行内容保持在同一条记忆中。' : '记忆已保存。');
@@ -1247,37 +1280,79 @@
1247
1280
  } catch (error) { appDialogError(error.message); }
1248
1281
  });
1249
1282
  }
1250
- // ---- 候选审核 ----
1251
- function reviewCandidate(memory) {
1252
- const groupOptions = ['<option value="">暂不加入组合</option>', ...state.groups.items.map(g => `<option value="${esc(g.id)}">${esc(g.name)}</option>`)].join('');
1283
+ function textTrigrams(text) {
1284
+ const normalized = text.normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '');
1285
+ return new Set(Array.from({ length: Math.max(0, normalized.length - 2) }, (_, i) => normalized.slice(i, i + 3)));
1286
+ }
1287
+ function nearbyCandidates(memory, candidates) {
1288
+ const base = textTrigrams(memory.text);
1289
+ return candidates.filter(candidate => candidate.id !== memory.id).map(candidate => {
1290
+ const terms = textTrigrams(candidate.text);
1291
+ let shared = 0;
1292
+ for (const term of terms) if (base.has(term)) shared++;
1293
+ return { candidate, similarity: shared ? 2 * shared / (base.size + terms.size) : 0 };
1294
+ }).filter(item => item.similarity >= 0.5)
1295
+ .sort((a, b) => b.similarity - a.similarity).slice(0, 3).map(item => item.candidate);
1296
+ }
1297
+ async function reviewCandidate(memory) {
1298
+ const sourceProjectId = candidateSourceProjectId(memory);
1299
+ const sourceGroups = sourceProjectId ? api(`/api/engine/projects/${encodeURIComponent(sourceProjectId)}/memory-groups`).catch(() => null) : null;
1300
+ const groups = await loadGroups();
1301
+ const bound = (await sourceGroups)?.groups || [];
1302
+ const preferred = bound.length === 1 ? bound[0].id : '';
1303
+ const groupOptions = ['<option value="">仅收录到记忆库(暂不生效)</option>', ...groups.map(group => `<option value="${esc(group.id)}" ${group.id === preferred ? 'selected' : ''}>${esc(group.name)}</option>`)].join('');
1253
1304
  appDialogOpen('审核候选记忆', `
1254
1305
  <form id="reviewForm">
1255
1306
  <h3>${esc(memory.title)}</h3>
1256
1307
  <p class="feedback" style="white-space:pre-wrap">${esc(memory.text)}</p>
1257
1308
  <p class="muted">${memory.evidence ? `来源:${esc(projectName(memory.evidence.projectId))} · commit ${esc(memory.evidence.commitSha.slice(0, 8))} · ${esc(memory.evidence.entryId)}` : '来源:手动添加'}</p>
1258
1309
  ${memory.evidence?.quote ? `<details class="agent-detail" style="margin:12px 0"><summary>查看原始依据(冻结原文)</summary><p class="feedback" style="white-space:pre-wrap">${esc(memory.evidence.quote)}</p></details>` : ''}
1310
+ <details class="agent-detail" data-role="similar" hidden></details>
1259
1311
  <label>确认后加入组合<select name="groupId">${groupOptions}</select></label>
1260
- <p class="muted" data-role="impact">确认后保留在记忆库;加入组合并应用到项目后生效。</p>
1312
+ <p class="muted" data-role="impact"></p>
1261
1313
  </form>`, [
1262
1314
  { label: '忽略', class: 'danger', run: async () => { await api(`/api/engine/memories/${encodeURIComponent(memory.id)}`, { method: 'PATCH', body: { status: 'ignored' } }); appDialogClose(); toast('已忽略候选。'); await Promise.all([loadCandidates(), loadOverview(true)]); } },
1263
1315
  { label: '取消', run: appDialogClose },
1264
1316
  { label: '确认收录', class: 'primary', form: 'reviewForm' },
1265
1317
  ]);
1266
1318
  const form = $('reviewForm');
1267
- form.elements.groupId.addEventListener('change', () => {
1268
- const group = groupById(form.elements.groupId.value);
1269
- $('appDialogBody').querySelector('[data-role="impact"]').textContent = group ? `加入后,使用「${group.name}」的 ${group.boundProjectCount} 个项目后续新任务会读到它。` : '确认后保留在记忆库;加入组合并应用到项目后生效。';
1270
- });
1319
+ const dialogIsOpen = () => form.isConnected && $('appDialog').open;
1320
+ const updateImpact = async () => {
1321
+ const groupId = form.elements.groupId.value;
1322
+ const group = groupById(groupId);
1323
+ const impact = form.querySelector('[data-role="impact"]');
1324
+ impact.textContent = group
1325
+ ? `加入「${group.name}」后生效于 ${group.boundProjectCount} 个项目。`
1326
+ : '确认后保存在记忆库中,应用到项目的组合才会让它生效。';
1327
+ if (!group?.boundProjectCount) return;
1328
+ const result = await api(`/api/engine/memory-groups/${encodeURIComponent(groupId)}`).catch(() => null);
1329
+ if (!dialogIsOpen() || form.elements.groupId.value !== groupId || !result?.group?.boundProjectIds) return;
1330
+ const names = result.group.boundProjectIds.slice(0, 5).map(projectName).join('、');
1331
+ impact.textContent = `加入「${group.name}」后生效于 ${names}${result.group.boundProjectIds.length > 5 ? '等 ' + result.group.boundProjectIds.length + ' 个项目' : ''}。`;
1332
+ };
1333
+ form.elements.groupId.addEventListener('change', updateImpact);
1334
+ void updateImpact();
1335
+ if (sourceProjectId) void projectCandidates(sourceProjectId).then(candidates => {
1336
+ if (!dialogIsOpen()) return;
1337
+ const related = nearbyCandidates(memory, candidates);
1338
+ if (!related.length) return;
1339
+ const details = form.querySelector('[data-role="similar"]');
1340
+ details.innerHTML = `<summary>可能重复的候选(${related.length})</summary>${related.map(item => `<p class="feedback" style="white-space:pre-wrap"><b>${esc(item.title)}</b><br>${esc(item.text)}</p>`).join('')}`;
1341
+ details.hidden = false;
1342
+ }).catch(() => {});
1343
+ let saving = false;
1271
1344
  form.addEventListener('submit', async event => {
1272
1345
  event.preventDefault();
1346
+ if (saving) return;
1347
+ saving = true;
1273
1348
  try {
1274
- await api(`/api/engine/memories/${encodeURIComponent(memory.id)}`, { method: 'PATCH', body: { status: 'confirmed' } });
1275
1349
  const groupId = form.elements.groupId.value;
1276
- if (groupId) await api(`/api/engine/memory-groups/${encodeURIComponent(groupId)}/members`, { method: 'POST', body: { addMemoryIds: [memory.id] } });
1350
+ await api(`/api/engine/memories/${encodeURIComponent(memory.id)}`, { method: 'PATCH', body: { status: 'confirmed', ...(groupId ? { groupId } : {}) } });
1277
1351
  appDialogClose();
1278
1352
  toast(groupId ? `已确认并加入「${groupById(groupId)?.name}」。` : '已确认,保留在记忆库中。');
1279
1353
  await Promise.all([loadCandidates(), loadGroups(), loadMemoryPage(), loadOverview(true)]);
1280
1354
  } catch (error) { appDialogError(error.message); }
1355
+ finally { saving = false; }
1281
1356
  });
1282
1357
  }
1283
1358
  // ---- 记忆详情 ----
@@ -1286,7 +1361,7 @@
1286
1361
  appDialogOpen(memory.title, `
1287
1362
  <p class="muted">${memory.sourceType === 'manual' ? `手动添加 · ${time(memory.createdAt)}` : memory.evidence ? `${esc(projectName(memory.evidence.projectId))} · commit ${esc(memory.evidence.commitSha.slice(0, 8))} · ${time(memory.updatedAt)}` : time(memory.updatedAt)}</p>
1288
1363
  <p class="feedback" style="white-space:pre-wrap;max-height:40vh;overflow:auto">${esc(memory.text)}</p>
1289
- <p class="muted">所在组合:${groups.map(g => esc(g.name)).join('、') || '未归组合'}${memory.scopeType !== 'group' ? ` · 原作用域:${SCOPE_LABEL[memory.scopeType]}(${memory.scopeType === 'domain' ? esc(domainName(memory.scopeId)) : memory.scopeType === 'project' ? esc(projectName(memory.scopeId)) : '所有项目'})` : ''}</p>`, [
1364
+ <p class="muted">所在组合:${groups.map(g => esc(g.name)).join('、') || '未归组合'}</p>`, [
1290
1365
  { label: '关闭', run: appDialogClose },
1291
1366
  ...(memory.status === 'confirmed' ? [
1292
1367
  { label: '组合归属', run: () => memoryGroupsDialog(memory) },
@@ -1566,11 +1641,12 @@
1566
1641
  if (button.dataset.action === 'group-settings') groupEditor(groupById(button.dataset.id));
1567
1642
  if (button.dataset.action === 'group-projects') await groupProjectsDialog(groupById(button.dataset.id));
1568
1643
  if (button.dataset.action === 'open-group') { setView('memory'); state.memory.tab = 'library'; state.memory.folder = button.dataset.id; state.memory.q = ''; state.memory.page = 0; state.memory.cursors = [null]; await loadMemoryPage(); }
1569
- if (button.dataset.action === 'new-memory') memoryEditor();
1644
+ if (button.dataset.action === 'new-memory') await memoryEditor();
1645
+ if (button.dataset.action === 'export-memories') await exportProjectMemories(button.dataset.id);
1570
1646
  if (button.dataset.action === 'memory-edit') memoryEditor(memoryById(button.dataset.id));
1571
1647
  if (button.dataset.action === 'memory-detail') { const memory = memoryById(button.dataset.id); if (memory) memoryDetail(memory); else toast('列表已刷新,请重试。'); }
1572
1648
  if (button.dataset.action === 'memory-groups') { const memory = memoryById(button.dataset.id); if (memory) await memoryGroupsDialog(memory); }
1573
- if (button.dataset.action === 'review-candidate') { const memory = state.candidates.items.find(m => m.id === button.dataset.id) || state.overview?.candidatesPreview?.find(m => m.id === button.dataset.id); if (memory) reviewCandidate(memory); else { await loadCandidates(); const fresh = state.candidates.items.find(m => m.id === button.dataset.id); if (fresh) reviewCandidate(fresh); else toast('候选不存在或已处理。'); } }
1649
+ if (button.dataset.action === 'review-candidate') { const memory = state.candidates.items.find(m => m.id === button.dataset.id) || state.overview?.candidatesPreview?.find(m => m.id === button.dataset.id); if (memory) await reviewCandidate(memory); else { await loadCandidates(); const fresh = state.candidates.items.find(m => m.id === button.dataset.id); if (fresh) await reviewCandidate(fresh); else toast('候选不存在或已处理。'); } }
1574
1650
  if (button.dataset.action === 'memory-evidence') { const memory = memoryById(button.dataset.id); if (memory?.evidence) await openReference({ ...memory.evidence, readFile: false, text: memory.evidence.quote, title: '记忆来源依据(冻结原文)' }); }
1575
1651
  if (button.dataset.action === 'memory-delete') { const memory = memoryById(button.dataset.id); if (memory) confirmDialog('删除这条记忆?', `「${memory.title}」将从所有组合中移除。其他小记忆保留。`, '删除', async () => {
1576
1652
  await api(`/api/engine/memories/${encodeURIComponent(memory.id)}`, { method: 'DELETE' });
@@ -1605,6 +1681,12 @@
1605
1681
  });
1606
1682
  document.addEventListener('change', async event => {
1607
1683
  if (event.target.id === 'projectDomainFilter') { state.projectsPage.domain = event.target.value; state.projectsPage.page = 0; state.projectsPage.cursors = [null]; await loadProjectsPage(); }
1684
+ if (event.target.id === 'candidateProjectFilter') {
1685
+ state.candidates.projectFilter = event.target.value;
1686
+ state.candidates.page = 0;
1687
+ state.candidates.cursors = [null];
1688
+ await loadCandidates();
1689
+ }
1608
1690
  });
1609
1691
  // 拖放:组合 → 项目行 = 应用;标签 → 拖回条 = 解除(键盘等价操作见各按钮/对话框)
1610
1692
  let drag = null;