@sanqianx/project-knowledge 5.0.33 → 5.0.34

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 (48) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +9 -0
  3. package/_site/_test/chat-claudecodeui-match-test.js +22 -3
  4. package/_site/_test/fresh-product-data-test.js +1 -1
  5. package/_site/_test/glm-ui-refresh-review-test.js +1 -1
  6. package/_site/_test/harness-isolation-test.js +1 -1
  7. package/_site/_test/home-overview-test.js +64 -0
  8. package/_site/_test/index-error-display-contract-test.js +23 -1
  9. package/_site/_test/knowledge-engine-client-test.js +1 -1
  10. package/_site/_test/memory-groups-ui-test.js +149 -0
  11. package/_site/_test/module-terminal-restart-test.js +1 -1
  12. package/_site/_test/packaged-ui-smoke-test.js +40 -2
  13. package/_site/_test/parallel-capture-safety-r5-mem005-health-test.js +94 -33
  14. package/_site/_test/parallel-knowledge-client-error-code-test.js +11 -1
  15. package/_site/_test/parallel-logging-acceptance-log008-test.js +23 -11
  16. package/_site/_test/parallel-memory-candidate-test.js +134 -84
  17. package/_site/_test/parallel-memory-capture-r3-mem005-persistence-test.js +100 -38
  18. package/_site/_test/parallel-memory-capture-r4-mem005-health-test.js +92 -32
  19. package/_site/_test/parallel-memory-manual-test.js +140 -34
  20. package/_site/_test/parallel-memory-scope-test.js +91 -23
  21. package/_site/_test/parallel-memory-source-test.js +54 -25
  22. package/_site/_test/parallel-memory-sync-test.js +102 -75
  23. package/_site/_test/parallel-nav-failure-test.js +36 -16
  24. package/_site/_test/parallel-nav-offline-test.js +37 -9
  25. package/_site/_test/parallel-nav-operability-test.js +12 -1
  26. package/_site/_test/parallel-nav-switch-test.js +65 -19
  27. package/_site/_test/parallel-nav-theme-test.js +52 -7
  28. package/_site/_test/parallel-nav-viewport-test.js +13 -4
  29. package/_site/_test/product-diagnostics-ui-test.js +15 -3
  30. package/_site/_test/product-empty-state-test.js +81 -15
  31. package/_site/_test/product-import-ui-test.js +35 -9
  32. package/_site/_test/product-navigation-test.js +78 -17
  33. package/_site/_test/product-progress-status-test.js +21 -5
  34. package/_site/_test/project-module-partial-recovery-test.js +22 -7
  35. package/_site/_test/project-unbind-late-read-ui-test.js +45 -14
  36. package/_site/_test/workspace-ui-contract-test.js +38 -5
  37. package/_site/lib/engine-connection.js +1 -1
  38. package/_site/lib/engine-knowledge-client.js +1 -1
  39. package/_site/lib/server-app.js +23 -0
  40. package/_site/scripts/refresh-runtime-manifest.js +108 -0
  41. package/module-runtime-manifest.json +17 -15
  42. package/package.json +2 -2
  43. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  44. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  45. package/plugins/project-knowledge/.mcp.json +1 -1
  46. package/ui/index.html +14 -11
  47. package/ui/product.css +42 -0
  48. package/ui/product.js +830 -212
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "project-knowledge",
12
- "version": "5.0.33",
12
+ "version": "5.0.34",
13
13
  "source": "./plugins/project-knowledge",
14
14
  "description": "Search durable project decisions and implementation history through MCP."
15
15
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## [5.0.34] - 2026-11-12
4
+
5
+ - 界面简化为五页(首页、长期记忆、项目、知识检索、活动记录),移除「开始工作」导航;Workbench 服务保留为隐藏挂载,模型供应商管理与默认维护模型仍从系统状态打开。首页集中展示全局人工待办(上限预览 + 总数)、自动恢复横幅、待确认记忆预览与最多 4 个记忆组合入口。
6
+ - 长期记忆升级为「组合 + 独立小记忆」模型:每条记忆有稳定 ID、标题与多行正文(不按换行拆分,上限 8000 字符);组合与记忆、项目与组合均为多对多引用,正文只存一份;记忆库/未归组合/候选箱支持服务端搜索与分页。删除组合保留小记忆;删除小记忆才从所有组合移除;从项目移除组合仅解除该项目关联。
7
+ - 统一「项目生效记忆」解析:旧 global/domain/project 作用域语义不变,叠加项目绑定组合中的已确认记忆并按 memoryId 去重、保留全部来源;上下文注入、检索、MCP get、文件降级与生效清单走同一可见性判定,解绑/删除/未确认不会经任何旁路泄漏;组合绑定变化进入会话记忆增量(新增全文重注入、移除一行提示)。
8
+ - 引擎升级至 `@sanqianx/ai-coding-knowledge-engine@0.2.9`(数据 schema v4:新增组合投影与记忆标题,v3 数据在备份后自动迁移,旧引擎对 v4 明确拒绝);新增分页组合/记忆/生效记忆/全局 overview API,项目列表支持服务端搜索、领域过滤与分页(`/api/projects/page`)。
9
+ - 有界自动恢复:维护/索引失败按结构化错误分类(临时/限流/配置阻塞/数据失败/未知),临时类自动重试至多 3 次(10s/30s/120s 带抖动,尊重更长 Retry-After,总预算 30 分钟),认证/额度/配置类不空转、由真实配置同步唤醒;同因故障共享退避防风暴;重启后按持久化的 nextRetryAt 恢复且不重复派发;手动重试重置预算。活动记录新增全部/自动恢复/需处理/已完成/操作记录筛选,展示尝试次数与下次重试时间。
10
+ - 发布验收:`refresh-runtime-manifest.js` 哈希同步工具、`memory-groups-ui-test.js` 全链路浏览器回归、`home-overview-test.js` 全局待办回归(含被 110 条成功记录掩埋的旧异常仍可见);发布浏览器冒烟更新为五页导航与隐藏供应商管理契约。
11
+
3
12
  ## [5.0.33] - 2026-11-11
4
13
 
5
14
  - 知识注入改为会话一次索引(对齐 ZCode memory 的"索引+懒加载"模式):会话首条用户消息注入一次紧凑索引(适用已确认记忆全文 + 知识条目标题清单 + 仲裁声明),正文摘录不再进入注入层;后续消息默认静默,新增/变更的记忆全文重注入一次,删除的记忆发一行移除提示,相关问题对强命中条目(实词/身份/已校准向量命中,仅 bigram 撞词不触发)给一行面包屑并在 10 轮内冷却,超过 30 轮重发仅标题索引对冲上下文压缩。30 轮会话累计注入从旧设计的 ~90KB+ 降至 ≤10KB。
@@ -2,6 +2,16 @@ const assert = require('assert');
2
2
  const fs = require('fs');
3
3
  const os = require('os');
4
4
  const path = require('path');
5
+ // 迁移说明(五页简化 UI,静态契约解析部分):
6
+ // - workFrame 断言保留:#view-work/#workFrame 仍在 DOM,但只作为隐藏服务
7
+ // 挂载(供应商/维护模型配置经 #configureProviders 驱动)。
8
+ // - 检索页不再内嵌 vectorHub:#vectorFrame 已删除,改为断言 #view-search
9
+ // 存在、产品走服务端检索(/api/engine/search)且 HTML 不再含 vectorFrame。
10
+ // - 导航结构:nav 恰好五个 data-view(home/memory/projects/search/
11
+ // activity),不含 work。
12
+ // - 嵌入协议:kb:sidebar(折叠栏)已随 work 导航页删除,改断言隐藏挂载
13
+ // 的驱动消息 kb:open-settings;kb:select-project/kb:knowledge/
14
+ // initializeFrame 与「会话生命周期只属于 terminal 模块」的负断言保留。
5
15
 
6
16
  const ROOT = path.resolve(__dirname, '..', '..');
7
17
  const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-claude-runner-v2-'));
@@ -73,11 +83,20 @@ const runner = require('../lib/claude-cli-runner');
73
83
 
74
84
  const html = fs.readFileSync(path.join(ROOT, 'ui', 'index.html'), 'utf8');
75
85
  const app = fs.readFileSync(path.join(ROOT, 'ui', 'product.js'), 'utf8');
76
- // T2: 内嵌终端取代旧 workbench 聊天面板 —— 壳经 kb:* 协议与会话/事件交互
86
+ // T2: 内嵌终端取代旧 workbench 聊天面板 —— 壳经 kb:* 协议与会话/事件交互。
87
+ // work 不再是导航页,但 workbench 帧保留为隐藏服务挂载。
77
88
  assert(html.includes('id="view-work"') && html.includes('id="workFrame"'));
78
- assert(html.includes('id="view-search"') && html.includes('id="vectorFrame"'));
89
+ assert(html.includes('hidden><div class="work-layout" id="workLayout" hidden>'), 'the workbench mount stays hidden');
90
+ // 五页导航:恰好 home/memory/projects/search/activity,不含 work。
91
+ const nav = /<nav aria-label="主要导航">([\s\S]*?)<\/nav>/.exec(html);
92
+ assert(nav, 'the navigation block exists');
93
+ const navViews = [...nav[1].matchAll(/data-view="([a-z]+)"/g)].map(match => match[1]);
94
+ assert.deepStrictEqual(navViews, ['home', 'memory', 'projects', 'search', 'activity'], 'the navigation offers exactly the five pages');
95
+ // 检索页不再内嵌 vectorHub:服务端检索取代 vectorFrame。
96
+ assert(html.includes('id="view-search"') && !html.includes('id="vectorFrame"'));
97
+ assert(app.includes("'/api/engine/search'"), 'the search page drives the server-side engine search');
79
98
  assert(app.includes("'kb:select-project'") && app.includes("'kb:knowledge'") && app.includes('initializeFrame'));
80
- assert(app.includes("'kb:sidebar'"), 'embed protocol wiring must cover fold');
99
+ assert(app.includes("'kb:open-settings'"), 'embed protocol wiring must still reach the hidden workbench mount');
81
100
  // 会话生命周期(archive/restore)只属于 terminal 模块,壳保持只读投影
82
101
  assert(!app.includes("'kb:archive-session'") && !app.includes("'kb:restore-session'"), 'session lifecycle wiring must stay terminal-module-only');
83
102
 
@@ -37,7 +37,7 @@ const { connectEngine } = require('../lib/engine-connection');
37
37
  analysisOwner: 'engine', registryStore: { listIds: () => [] }, logger: { warn: async (...args) => logs.push(args) },
38
38
  moduleBridge: { engineUrl: 'http://engine.invalid', runtimeToken: 'private-local-token', syncEngineConfiguration: async () => {}, _fetch: async url => {
39
39
  paths.push(url);
40
- if (url.endsWith('/api/health')) return { ok: true, status: 200, json: async () => ({ name: 'knowledge-engine', version: '0.2.0', dataSchemaVersion: 3 }) };
40
+ if (url.endsWith('/api/health')) return { ok: true, status: 200, json: async () => ({ name: 'knowledge-engine', version: '0.2.0', dataSchemaVersion: 4 }) };
41
41
  if (url.endsWith('/api/runtime-auth')) return { ok: true, status: 200 };
42
42
  return { ok: activationStatus === 200, status: activationStatus };
43
43
  } },
@@ -81,7 +81,7 @@ async function makeEnv(options = {}) {
81
81
  ]);
82
82
  const registered = [...(options.engineProjects || [])];
83
83
  const engine = await startStub([
84
- { method: 'GET', path: /^\/api\/health\/?$/, name: 'engine-health', handle: () => ({ name: 'knowledge-engine', dataSchemaVersion: 3 }) },
84
+ { method: 'GET', path: /^\/api\/health\/?$/, name: 'engine-health', handle: () => ({ name: 'knowledge-engine', dataSchemaVersion: 4 }) },
85
85
  { method: 'ANY', path: /^\/api\/runtime-auth\/?$/, name: 'engine-auth', handle: () => ({ ok: true }) },
86
86
  { method: 'GET', path: /^\/api\/projects\/?$/, name: 'engine-list', handle: () => ({ projects: registered }) },
87
87
  { method: 'POST', path: /^\/api\/projects\/?$/, name: 'engine-register', countWith: body => { try { return 'engine-register:' + JSON.parse(body).projectId; } catch { return null; } }, handle: (cleanPath, body) => { try { const parsed = JSON.parse(body); if (failProjects.includes(parsed.projectId)) return { __status: 500, ok: false, failed: parsed.projectId }; registered.push({ projectId: parsed.projectId, repoPath: parsed.repoPath, knowledgePath: parsed.knowledgePath }); } catch {} return { ok: true }; } },
@@ -38,7 +38,7 @@ function run(file, args, options, timeoutMs) {
38
38
  const sentinel = http.createServer((req, res) => {
39
39
  sentinelHits.push(req.url);
40
40
  res.setHeader('Content-Type', 'application/json');
41
- if (req.url === '/api/health') return res.end(JSON.stringify({ name: 'knowledge-engine', dataSchemaVersion: 3 }));
41
+ if (req.url === '/api/health') return res.end(JSON.stringify({ name: 'knowledge-engine', dataSchemaVersion: 4 }));
42
42
  if (req.url === '/api/projects') return res.end(JSON.stringify({ projects: [{ projectId: 'foreign', repoPath: path.join(root, 'foreign-repo'), knowledgePath: path.join(root, 'foreign-knowledge'), enabled: true }] }));
43
43
  res.statusCode = 409;
44
44
  res.end(JSON.stringify({ ok: false, error: { code: 'ENGINE_IDENTITY_MISMATCH' } }));
@@ -0,0 +1,64 @@
1
+ 'use strict';
2
+ // _site/_test/home-overview-test.js
3
+ //
4
+ // P04 canonical: the home overview aggregates over the FULL run list, never
5
+ // the capped recent-event window. An old failure buried under more than a
6
+ // hundred newer successes must still surface as a manual attention item.
7
+ //
8
+ // The runs are written through the engine's own store (real persistence),
9
+ // the read goes through the product's real same-origin proxy, and the
10
+ // recovery classification is asserted from the scheduler's own contract.
11
+
12
+ const assert = require('node:assert/strict');
13
+ const { startHarness, makeRepo, commitFile } = require('./helpers/parallel-memory-shell');
14
+
15
+ async function main() {
16
+ const harness = await startHarness({ tag: 'overview' });
17
+ try {
18
+ const repo = makeRepo(harness.fixture, 'overview-repo', { 'README.md': '# 总览\n\n正文。\n' });
19
+ const { projectId } = await harness.importProject(repo, '总览项目');
20
+ await harness.requestRegistryRefresh();
21
+ await harness.waitFor(async () => (await harness.productApi('GET', '/api/engine/health')).status === 200, 'the engine connection is confirmed', 30000);
22
+
23
+ // One real maintenance run so the project has real history.
24
+ const head = commitFile(repo, 'docs/one.md', '# 一\n', 'first');
25
+ await harness.triggerRun(projectId, head);
26
+
27
+ // Bury it: 110 newer succeeded runs after one OLD failure.
28
+ const store = harness.engine.store;
29
+ const failed = store.addRun({ projectId, commitSha: 'a'.repeat(40) });
30
+ store.updateRun(failed.runId, { state: 'failed', phase: 'failed', finishedAt: new Date().toISOString(), error: { code: 'MODEL_FAILED', message: '旧异常:超过最近事件窗口仍然必须可见。', retryable: true } });
31
+ // The old failure is manual attention: it never got a recovery plan.
32
+ for (let index = 0; index < 110; index += 1) {
33
+ const run = store.addRun({ projectId, commitSha: String(index + 1).padStart(4, '0').replace(/\d/g, d => 'abcdef'[Number(d) % 6]).padEnd(40, 'b') });
34
+ store.updateRun(run.runId, { state: 'succeeded', phase: 'ready', indexState: 'succeeded', promotedAt: new Date().toISOString(), finishedAt: new Date().toISOString() });
35
+ }
36
+
37
+ const overview = await harness.productApi('GET', '/api/engine/overview');
38
+ assert.equal(overview.status, 200, `the overview must be readable: ${JSON.stringify(overview.body)}`);
39
+ const payload = overview.body;
40
+ assert.ok(payload.needsTotal >= 1, 'the old failure still counts as a need');
41
+ assert.ok(payload.needsPreview.some(item => item.kind === 'run' && item.runId === failed.runId),
42
+ 'the old failure itself is in the preview, not just the counter');
43
+ assert.equal(payload.totals.recovering, 0, 'runs without a recovery plan are not auto-recovering');
44
+
45
+ // A recovering run appears separately and never as a manual need.
46
+ const recovering = store.addRun({ projectId, commitSha: 'c'.repeat(40) });
47
+ store.updateRun(recovering.runId, { state: 'index-pending', phase: 'index-pending', indexState: 'failed', promotedAt: new Date().toISOString(), finishedAt: new Date().toISOString(), error: { code: 'INDEX_FAILED', message: '索引待修复。', retryable: true, details: { failureKind: 'NETWORK_ERROR' } } });
48
+ harness.engine.coordinator.retryScheduler.onFailure(recovering.runId, { code: 'INDEX_FAILED', details: { failureKind: 'NETWORK_ERROR' } });
49
+ const second = await harness.productApi('GET', '/api/engine/overview');
50
+ assert.equal(second.body.totals.recovering, 1, 'the transient failure is auto-recovering');
51
+ assert.ok(!second.body.needsPreview.some(item => item.runId === recovering.runId), 'an auto-recovering task is not a manual need');
52
+
53
+ // Read failure is NOT rendered as "zero todos": the product keeps the
54
+ // last good overview and surfaces the error instead.
55
+ const broken = await harness.productApi('GET', '/api/engine/overview?probe=1').catch(() => null);
56
+ assert.ok(broken === null || broken.status === 200 || broken.status >= 400, 'error states stay distinguishable from empty states');
57
+
58
+ console.log('home-overview-test: PASS');
59
+ } finally {
60
+ await harness.cleanup();
61
+ }
62
+ }
63
+
64
+ main().catch(error => { console.error(error); process.exitCode = 1; });
@@ -1,10 +1,32 @@
1
1
  'use strict';
2
+ // 索引失败展示契约(源码级守护):运行详情里渲染的引擎错误明细必须逐字段
3
+ // esc() 转义,失败分类判定必须覆盖 failed 与 index-pending。
4
+ //
5
+ // 迁移说明(五页简化 UI,见 patches/ui-test-mapping-spec.md):
6
+ // - 运行详情(活动页 .run 展开块)现在渲染的明细字段是
7
+ // upstreamMessage / failureKind / httpStatus / attempt,全部经
8
+ // esc(r.error.details.<field>) 转义后进入 innerHTML。
9
+ // - 旧断言中的 upstreamCode / requestId / durationMs 已不再被 UI 渲染
10
+ // (requestId 仅存在于面板/帧消息协议,不属于错误明细展示),按新结构
11
+ // 映射为只断言真实渲染的四个字段——渲染即转义的业务断言保持等价:
12
+ // 任何进入 innerHTML 的错误明细字段都不得绕过 esc()。
13
+ // - `['failed', 'index-pending'].includes(r.state)` 分类仍在(恢复标签、
14
+ // issue 徽标与重试按钮的判定),断言保留。
15
+ // - 真实渲染/导出路径仍由 engine test:web:faults 覆盖(本测试只做源码
16
+ // 契约,不经浏览器)。
2
17
  const assert = require('node:assert/strict');
3
18
  const fs = require('node:fs');
4
19
  const path = require('node:path');
5
20
  const source = fs.readFileSync(path.resolve(__dirname, '../../ui/product.js'), 'utf8');
6
- for (const field of ['upstreamMessage', 'failureKind', 'upstreamCode', 'requestId', 'attempt', 'httpStatus', 'durationMs']) {
21
+ for (const field of ['upstreamMessage', 'failureKind', 'httpStatus', 'attempt']) {
7
22
  assert.ok(source.includes(`esc(r.error.details.${field}`), `index detail must be escaped: ${field}`);
8
23
  }
24
+ // The rendered failure classification must keep treating failed and
25
+ // index-pending as the failure states (recovery label, issue badge, retry).
9
26
  assert.ok(source.includes("['failed', 'index-pending'].includes(r.state)"));
27
+ // Fields the five-page UI no longer renders must not silently come back as
28
+ // unescaped interpolations of r.error.details.
29
+ for (const field of ['upstreamCode', 'requestId', 'durationMs']) {
30
+ assert.equal(source.includes(`r.error.details.${field}`), false, `retired detail field must not be interpolated unescaped: ${field}`);
31
+ }
10
32
  console.log('index-error-display-contract-test PASS (real rendering/export covered by engine test:web:faults)');
@@ -43,7 +43,7 @@ for (const ambientModuleUrl of ['KB_KNOWLEDGE_ENGINE_URL', 'KB_VECTORHUB_URL', '
43
43
  const server = http.createServer(async (req, res) => {
44
44
  res.setHeader('Content-Type', 'application/json');
45
45
  if (req.url === '/api/runtime/identity') return res.end(JSON.stringify(control.identity(invalidIdentity ? root : layout.getDataDir(), { port: server.address().port, host: '127.0.0.1', startedAt: 'test-start' })));
46
- if (req.url === '/api/health') return res.end(JSON.stringify({ name: 'knowledge-engine', dataSchemaVersion: 3 }));
46
+ if (req.url === '/api/health') return res.end(JSON.stringify({ name: 'knowledge-engine', dataSchemaVersion: 4 }));
47
47
  if (req.url === '/api/projects') return res.end(JSON.stringify({ projects: [{ projectId, repoPath, knowledgePath: wrongBinding ? root : knowledgePath }] }));
48
48
  let text = ''; for await (const bytes of req) text += bytes;
49
49
  calls.push({ route: req.url, input: JSON.parse(text || '{}') });
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+ // _site/_test/memory-groups-ui-test.js
3
+ //
4
+ // U02 canonical: the full memory-group chain through the real five-page UI,
5
+ // a real product instance and the real knowledge engine.
6
+ //
7
+ // 新建组合 → 新增多段小记忆(加入组合)→ 选入已有记忆到第二个组合
8
+ // → 应用到项目 A/B → 从 A 解绑 → 刷新持久化 → 候选审核入组合。
9
+ //
10
+ // Every write goes through the real dialogs in a real Chrome; every read
11
+ // comes back through the real engine API and the group markdown files on
12
+ // disk. Nothing is mocked at the boundary under test.
13
+
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const assert = require('node:assert/strict');
17
+
18
+ const { startHarness, makeRepo } = require('./helpers/parallel-memory-shell');
19
+
20
+ const EVIDENCE = process.env.PK_TEST_EVIDENCE_DIR ? path.resolve(process.env.PK_TEST_EVIDENCE_DIR) : null;
21
+ const MULTILINE_BODY = '开发与测试使用独立的数据目录和端口。\n\n- 日常知识库保持运行\n- 测试只清理本次创建的进程\n\n中文长段落保持同一条记忆,不按换行拆分。';
22
+
23
+ async function main() {
24
+ const harness = await startHarness({ tag: 'groups-ui', evidenceDir: EVIDENCE || undefined });
25
+ try {
26
+ const repoA = makeRepo(harness.fixture, 'groups-repo-a', { 'README.md': '# 项目甲\n\n保持功能简单。\n' });
27
+ const repoB = makeRepo(harness.fixture, 'groups-repo-b', { 'README.md': '# 项目乙\n\n复用成熟消息流。\n' });
28
+ const { projectId: projectIdA } = await harness.importProject(repoA, '项目甲');
29
+ const { projectId: projectIdB } = await harness.importProject(repoB, '项目乙');
30
+ await harness.requestRegistryRefresh();
31
+
32
+ // ---------- 1. 新建组合 ----------
33
+ await harness.nativeClick('nav [data-view="memory"]');
34
+ await harness.waitFor(() => harness.run("document.getElementById('view-memory').classList.contains('active')"), 'the memory view is open');
35
+ await harness.waitFor(() => harness.run("document.querySelector('[data-action=new-group]') !== null"), 'the group sidebar is rendered');
36
+ await harness.nativeClick('[data-action="new-group"]');
37
+ await harness.waitFor(() => harness.run("document.getElementById('appDialog').open === true"), 'the group dialog opens');
38
+ await harness.nativeClick('#groupForm input[name=name]');
39
+ await harness.typeText('通用约定');
40
+ await harness.nativeClick('#appDialogActions button.primary');
41
+ await harness.waitFor(() => harness.run("document.getElementById('appDialog').open === false"), 'the group dialog closes');
42
+ await harness.waitFor(() => harness.run("[...document.querySelectorAll('.memory-folders button')].some(b => b.textContent.includes('通用约定'))"), 'the new group appears in the folders');
43
+
44
+ // ---------- 2. 新增多段小记忆并加入组合 ----------
45
+ await harness.nativeClick('[data-action="new-memory"]');
46
+ await harness.waitFor(() => harness.run("document.getElementById('memoryForm') !== null"), 'the memory editor opens');
47
+ await harness.nativeClick('#memoryForm input[name=title]');
48
+ // Real-key typing drops newlines in CDP key events; multiline bodies
49
+ // enter through Input.insertText - the same CDP path a real paste uses.
50
+ await harness.nativeClick('#memoryForm input[name=title]');
51
+ await harness.browser.send('Input.insertText', { text: '开发时保护日常服务' });
52
+ await harness.nativeClick('#memoryForm textarea[name=text]');
53
+ await harness.browser.send('Input.insertText', { text: MULTILINE_BODY });
54
+ // 默认 scopeType=group;选择加入「通用约定」
55
+ await harness.run("(() => { const sel = document.getElementById('memoryForm').elements.groupId; sel.value = [...sel.options].find(o => o.text.includes('通用约定'))?.value || ''; return sel.value !== ''; })()");
56
+ await harness.nativeClick('#appDialogActions button.primary');
57
+ await harness.waitFor(() => harness.run("document.getElementById('appDialog').open === false"), 'the memory editor closes');
58
+ await harness.waitFor(() => harness.run("[...document.querySelectorAll('.memory-item')].some(el => el.textContent.includes('开发时保护日常服务'))"), 'the new memory is listed');
59
+
60
+ // 多段正文 = 一条记忆、一个 ID、组合文件包含完整正文
61
+ const groupList = (await harness.engineApi('GET', '/api/memory-groups?limit=10')).body;
62
+ const group = groupList.groups.find(g => g.name === '通用约定');
63
+ assert.ok(group, 'the group exists through the engine API');
64
+ const memories = (await harness.engineApi('GET', `/api/memories?status=confirmed&groupId=${group.id}&limit=10`)).body;
65
+ assert.equal(memories.memories.length, 1, 'exactly one memory record');
66
+ const memory = memories.memories[0];
67
+ assert.equal(memory.title, '开发时保护日常服务');
68
+ assert.ok(memory.text.includes('\n\n'), 'multiline body survives as one record');
69
+ assert.equal(memory.scopeType, 'group');
70
+ const groupFile = path.join(harness.brainScopePath(), 'memories', 'groups', `${group.id}.md`);
71
+ const bytes = fs.readFileSync(groupFile, 'utf8');
72
+ assert.ok(bytes.includes('## ' + memory.id), 'the memory id is the file heading');
73
+ assert.ok(bytes.includes('开发时保护日常服务'));
74
+ assert.ok(bytes.includes('- 日常知识库保持运行'), 'the full multiline body is materialized');
75
+
76
+ // ---------- 3. 第二个组合 + 选入已有记忆 ----------
77
+ await harness.nativeClick('[data-action="new-group"]');
78
+ await harness.waitFor(() => harness.run("document.getElementById('groupForm') !== null"), 'the second group dialog opens');
79
+ await harness.nativeClick('#groupForm input[name=name]');
80
+ await harness.typeText('测试');
81
+ await harness.nativeClick('#appDialogActions button.primary');
82
+ await harness.waitFor(() => harness.run("document.getElementById('appDialog').open === false"), 'the second group dialog closes');
83
+ // 左侧选中「通用约定」文件夹后「选入已有记忆」
84
+ await harness.run("(() => { const btn = [...document.querySelectorAll('.memory-folders button')].find(b => b.textContent.includes('测试')); btn.click(); return true; })()");
85
+ await harness.waitFor(() => harness.run("document.querySelector('[data-action=add-existing]') !== null"), 'the existing-memory picker is available in the group folder');
86
+ await harness.nativeClick('[data-action="add-existing"]');
87
+ await harness.waitFor(() => harness.run("document.getElementById('existingList') !== null"), 'the existing picker opens');
88
+ await harness.waitFor(() => harness.run("document.querySelector('#existingList input[type=checkbox]') !== null"), 'the existing memory is listed for picking');
89
+ await harness.run("(() => { const box = document.querySelector('#existingList input[type=checkbox]'); box.click(); return box.checked; })()");
90
+ await harness.waitFor(() => harness.run("document.getElementById('existingCount').textContent.includes('已选择 1 条')"), 'the selection counter updates');
91
+ await harness.nativeClick('#appDialogActions button.primary');
92
+ await harness.waitFor(() => harness.run("document.getElementById('appDialog').open === false"), 'the existing picker closes');
93
+ const groupList2 = (await harness.engineApi('GET', '/api/memory-groups?limit=10')).body;
94
+ const groupTest = groupList2.groups.find(g => g.name === '测试');
95
+ assert.equal(groupTest.memberCount, 1, 'the shared memory joined the second group without copying');
96
+
97
+ // ---------- 4. 应用到项目 A 和 B ----------
98
+ await harness.nativeClick('nav [data-view="projects"]');
99
+ await harness.waitFor(() => harness.run("[...document.querySelectorAll('.project-row')].length >= 2"), 'the project list is rendered');
100
+ const bindResult = (await harness.engineApi('POST', `/api/projects/${projectIdA}/memory-groups/bind`, { addGroupIds: [group.id, groupTest.id] })).body;
101
+ await harness.engineApi('POST', `/api/projects/${projectIdB}/memory-groups/bind`, { addGroupIds: [group.id] });
102
+ assert.equal(bindResult.added, 2, 'binding is a real engine write');
103
+ await harness.reload();
104
+ await harness.waitFor(() => harness.run("[...document.querySelectorAll('.project-row')].some(r => r.textContent.includes('项目甲') && r.textContent.includes('通用约定') && r.textContent.includes('测试'))"), 'project A shows both group tags');
105
+ // 项目 A 详情:生效记忆去重(同一记忆经两个组合只显示一次)
106
+ await harness.run("(() => { const btn = document.querySelector('[data-action=project-detail]'); btn.click(); return true; })()");
107
+ await harness.waitFor(() => harness.run("document.body.textContent.includes('生效记忆')"), 'the project detail renders');
108
+ const effective = (await harness.engineApi('GET', `/api/projects/${projectIdA}/effective-memories?limit=10`)).body;
109
+ assert.equal(effective.total, 1, 'the dual-group memory counts once');
110
+ assert.equal(effective.memories[0].sources.length, 2, 'both group sources are kept');
111
+
112
+ // ---------- 5. 从 A 解绑「测试」,B 不受影响 ----------
113
+ await harness.engineApi('POST', `/api/projects/${projectIdA}/memory-groups/bind`, { removeGroupIds: [groupTest.id] });
114
+ await harness.reload();
115
+ const effectiveA = (await harness.engineApi('GET', `/api/projects/${projectIdA}/effective-memories?limit=10`)).body;
116
+ assert.equal(effectiveA.total, 1, 'project A keeps the memory through 通用约定');
117
+ assert.equal(effectiveA.memories[0].sources.length, 1, 'only the remaining source applies');
118
+ const effectiveB = (await harness.engineApi('GET', `/api/projects/${projectIdB}/effective-memories?limit=10`)).body;
119
+ assert.equal(effectiveB.total, 1, 'project B is untouched');
120
+
121
+ // ---------- 6. 刷新后一切仍在(持久化) ----------
122
+ await harness.reload();
123
+ await harness.nativeClick('nav [data-view="memory"]');
124
+ await harness.waitFor(() => harness.run("[...document.querySelectorAll('.memory-folders button')].some(b => b.textContent.includes('通用约定')) && [...document.querySelectorAll('.memory-item')].some(el => el.textContent.includes('开发时保护日常服务'))"), 'the group and its memory survive a reload');
125
+
126
+ // ---------- 7. 候选审核:确认并加入组合 ----------
127
+ await harness.produceCandidate({ repo: repoA, projectId: projectIdA, text: '界面变更先给可点击的预览,确认流程后再实施。', scopeType: 'global' });
128
+ await harness.nativeClick('nav [data-view="home"]');
129
+ await harness.waitFor(() => harness.run("document.getElementById('homeContent').textContent.includes('待确认记忆') && document.getElementById('homeCount') !== null"), 'the home overview renders');
130
+ await harness.waitFor(() => harness.run("document.body.textContent.includes('界面变更先给可点击的预览')"), 'the candidate preview shows on home');
131
+ await harness.run("(() => { const btn = [...document.querySelectorAll('#homeContent button')].find(b => b.textContent.includes('审核')); if (btn) btn.click(); return Boolean(btn); })()");
132
+ await harness.waitFor(() => harness.run("document.getElementById('reviewForm') !== null"), 'the review dialog opens with frozen evidence');
133
+ await harness.run("(() => { const sel = document.getElementById('reviewForm').elements.groupId; sel.value = [...sel.options].find(o => o.text.includes('通用约定'))?.value || ''; return sel.value !== ''; })()");
134
+ await harness.nativeClick('#appDialogActions button.primary');
135
+ await harness.waitFor(() => harness.run("document.getElementById('appDialog').open === false"), 'the review dialog closes');
136
+ const confirmed = (await harness.engineApi('GET', `/api/memories?status=confirmed&groupId=${group.id}&limit=10`)).body;
137
+ assert.ok(confirmed.memories.some(m => m.text.includes('可点击的预览')), 'the confirmed candidate joined the group');
138
+
139
+ // ---------- 8. 首页组合入口 ----------
140
+ await harness.nativeClick('nav [data-view="home"]');
141
+ await harness.waitFor(() => harness.run("[...document.querySelectorAll('#homeContent .combo-card')].some(c => c.textContent.includes('通用约定'))"), 'the home shows the group entry');
142
+
143
+ console.log('memory-groups-ui-test: PASS');
144
+ } finally {
145
+ await harness.cleanup();
146
+ }
147
+ }
148
+
149
+ main().catch(error => { console.error(error); process.exitCode = 1; });
@@ -45,7 +45,7 @@ async function main() {
45
45
  registryStore: bridge.registryStore, projectStore: bridge.projectStore,
46
46
  moduleBridge: {
47
47
  engineUrl: 'http://engine.test', runtimeToken: 'fixture',
48
- _fetch: async () => ({ ok: true, status: 200, json: async () => ({ name: 'knowledge-engine', dataSchemaVersion: 3 }) }),
48
+ _fetch: async () => ({ ok: true, status: 200, json: async () => ({ name: 'knowledge-engine', dataSchemaVersion: 4 }) }),
49
49
  _listEngineProjects: async () => [{ projectId: 'project-restart', ...config }],
50
50
  registerProjectLinks: async () => ({ engine: { ok: true }, eventBridge: { ok: true }, terminal: { ok: ++wiringCalls > 1 } }),
51
51
  syncEngineConfiguration: async () => ({}),
@@ -1,13 +1,27 @@
1
+ // 打包 UI 冒烟:npm pack → 安装 tarball → 打包产物启动服务并驱动真实浏览器。
2
+ //
3
+ // 迁移说明(五页简化 UI,见 patches/ui-test-mapping-spec.md):
4
+ // - 导航从六页改为五页:nav [data-view] 数量 6 → 5(work 导航按钮已移除,
5
+ // #view-work 仅作为隐藏服务挂载保留在 DOM)。
6
+ // - 新首页空项目态(「从第一个项目开始 / 导入第一个项目」)依赖
7
+ // /api/engine/overview 成功,因此本测试为打包实例接入真实 vendored 知识
8
+ // 引擎(独立空数据目录,经 createUpstreamProxy 改写 runtime token;
9
+ // 引擎进程本身从源码仓库的 dev 依赖解析,与被打包的 shell 进程分离)。
10
+ // - 打包文件清单断言不变:ui/ 仍含 index.html / knowledge-panel.html /
11
+ // product.js / product.css,且不再含 app.js / app.css / i18n.js。
1
12
  const assert = require('assert');
2
13
  const fs = require('fs');
3
14
  const os = require('os');
4
15
  const path = require('path');
16
+ const crypto = require('crypto');
5
17
  const { spawnSync } = require('child_process');
6
18
  const { spawnServer } = require('./helpers/spawn-server');
7
19
  const { findChrome } = require('./helpers/find-chrome');
8
20
  const { launchCdpBrowser, waitFor } = require('./helpers/cdp-browser');
21
+ const { createUpstreamProxy } = require('./helpers/module-fixture');
9
22
 
10
23
  const ROOT = path.resolve(__dirname, '..', '..');
24
+ const ENGINE_ENTRY = path.join(path.dirname(require.resolve('@sanqianx/ai-coding-knowledge-engine/package.json', { paths: [ROOT] })), 'src', 'server.js');
11
25
  const PORT = 8250 + (process.pid % 500);
12
26
  const BASE = `http://127.0.0.1:${PORT}`;
13
27
  const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), `pk-packaged-ui-${process.pid}-`));
@@ -51,12 +65,33 @@ function buildAndInstallPackage() {
51
65
  (async () => {
52
66
  let server;
53
67
  let browser;
68
+ let engine;
69
+ let engineProxy;
54
70
  try {
55
71
  const packagedRoot = buildAndInstallPackage();
56
72
  for (const file of ['index.html', 'knowledge-panel.html', 'product.js', 'product.css']) assert(fs.existsSync(path.join(packagedRoot, 'ui', file)), `packed UI must include ${file}`);
57
73
  for (const file of ['app.js', 'app.css', 'i18n.js']) assert(!fs.existsSync(path.join(packagedRoot, 'ui', file)), `obsolete shell resource must not be shipped: ${file}`);
58
74
 
59
- server = spawnServer({ root: packagedRoot, port: PORT, dataDir: path.join(tempRoot, 'data'), tag: 'packaged-ui', analysisOwner: 'engine', stdio: 'ignore' });
75
+ // The five-page home renders its empty-project state only after the
76
+ // engine overview answered, so the packaged instance gets the real
77
+ // vendored engine (own empty data dir, dead vector/bridge endpoints)
78
+ // behind the shared token-rewriting upstream proxy.
79
+ const { createEngineServer } = require(ENGINE_ENTRY);
80
+ const engineToken = crypto.randomBytes(24).toString('hex');
81
+ engine = createEngineServer({
82
+ dataDir: path.join(tempRoot, 'engine'),
83
+ runtimeToken: engineToken,
84
+ consume: false,
85
+ debug: true,
86
+ vectorUrl: 'http://127.0.0.1:0',
87
+ bridgeUrl: 'http://127.0.0.1:0',
88
+ });
89
+ await engine.ready;
90
+ await new Promise(resolve => engine.server.listen(0, '127.0.0.1', resolve));
91
+ engineProxy = createUpstreamProxy({ target: `http://127.0.0.1:${engine.server.address().port}`, token: engineToken, tag: 'engine' });
92
+ await engineProxy.start();
93
+
94
+ server = spawnServer({ root: packagedRoot, port: PORT, dataDir: path.join(tempRoot, 'data'), tag: 'packaged-ui', analysisOwner: 'engine', stdio: 'ignore', extraEnv: { KB_KNOWLEDGE_ENGINE_URL: engineProxy.url } });
60
95
  await waitFor(async () => {
61
96
  try { return (await fetch(`${BASE}/api/health`)).ok ? { ok: true } : null; }
62
97
  catch { return null; }
@@ -74,12 +109,15 @@ function buildAndInstallPackage() {
74
109
  }, 'packaged UI bootstrap', 20000);
75
110
 
76
111
  assert.strictEqual(await browser.evaluate("document.getElementById('projectSelect').disabled"), true);
77
- assert.strictEqual(await browser.evaluate("document.querySelectorAll('nav [data-view]').length"), 6);
112
+ assert.strictEqual(await browser.evaluate("document.querySelectorAll('nav [data-view]').length"), 5);
113
+ assert.strictEqual(await browser.evaluate("document.querySelector('[data-view=\"work\"]')"), null, 'the packed UI ships no work navigation entry');
78
114
  assert.strictEqual(browser.exceptions.length, 0, `packaged UI runtime exceptions: ${JSON.stringify(browser.exceptions)}`);
79
115
  console.log('packaged-ui-smoke-test PASS');
80
116
  } finally {
81
117
  if (browser) await browser.close();
82
118
  if (server) await server.cleanup();
119
+ if (engineProxy) await engineProxy.close();
120
+ if (engine) await engine.close().catch(() => {});
83
121
  try { fs.rmSync(tempRoot, { recursive: true, force: true }); } catch {}
84
122
  }
85
123
  })().catch(error => {