@sanqianx/project-knowledge 5.0.32 → 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 (56) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +15 -0
  3. package/_site/_test/automatic-context-test.js +19 -0
  4. package/_site/_test/chat-claudecodeui-match-test.js +22 -3
  5. package/_site/_test/context-session-index-test.js +244 -0
  6. package/_site/_test/fixtures/retrieval-gold-queries.json +4 -0
  7. package/_site/_test/fresh-product-data-test.js +1 -1
  8. package/_site/_test/glm-ui-refresh-review-test.js +1 -1
  9. package/_site/_test/harness-isolation-test.js +1 -1
  10. package/_site/_test/home-overview-test.js +64 -0
  11. package/_site/_test/index-error-display-contract-test.js +23 -1
  12. package/_site/_test/knowledge-engine-client-test.js +1 -1
  13. package/_site/_test/memory-groups-ui-test.js +149 -0
  14. package/_site/_test/module-terminal-restart-test.js +1 -1
  15. package/_site/_test/packaged-ui-smoke-test.js +40 -2
  16. package/_site/_test/parallel-capture-safety-r5-mem005-health-test.js +94 -33
  17. package/_site/_test/parallel-knowledge-client-error-code-test.js +11 -1
  18. package/_site/_test/parallel-logging-acceptance-log008-test.js +23 -11
  19. package/_site/_test/parallel-memory-candidate-test.js +134 -84
  20. package/_site/_test/parallel-memory-capture-r3-mem005-persistence-test.js +100 -38
  21. package/_site/_test/parallel-memory-capture-r4-mem005-health-test.js +92 -32
  22. package/_site/_test/parallel-memory-manual-test.js +140 -34
  23. package/_site/_test/parallel-memory-scope-test.js +91 -23
  24. package/_site/_test/parallel-memory-source-test.js +54 -25
  25. package/_site/_test/parallel-memory-sync-test.js +102 -75
  26. package/_site/_test/parallel-nav-failure-test.js +36 -16
  27. package/_site/_test/parallel-nav-offline-test.js +37 -9
  28. package/_site/_test/parallel-nav-operability-test.js +12 -1
  29. package/_site/_test/parallel-nav-switch-test.js +65 -19
  30. package/_site/_test/parallel-nav-theme-test.js +52 -7
  31. package/_site/_test/parallel-nav-viewport-test.js +13 -4
  32. package/_site/_test/product-diagnostics-ui-test.js +15 -3
  33. package/_site/_test/product-empty-state-test.js +81 -15
  34. package/_site/_test/product-import-ui-test.js +35 -9
  35. package/_site/_test/product-navigation-test.js +78 -17
  36. package/_site/_test/product-progress-status-test.js +21 -5
  37. package/_site/_test/project-module-partial-recovery-test.js +22 -7
  38. package/_site/_test/project-unbind-late-read-ui-test.js +45 -14
  39. package/_site/_test/workspace-ui-contract-test.js +38 -5
  40. package/_site/lib/engine-connection.js +1 -1
  41. package/_site/lib/engine-knowledge-client.js +1 -1
  42. package/_site/lib/server-app.js +23 -0
  43. package/_site/scripts/ab-rank-v2-v3.js +142 -0
  44. package/_site/scripts/refresh-runtime-manifest.js +108 -0
  45. package/_site/scripts/run-retrieval-gold-isolated.js +221 -0
  46. package/_site/scripts/verify-retrieval-gold.js +57 -10
  47. package/module-runtime-manifest.json +22 -20
  48. package/package.json +2 -2
  49. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  50. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  51. package/plugins/project-knowledge/.mcp.json +1 -1
  52. package/plugins/project-knowledge/scripts/context-hook.cjs +9 -5
  53. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +39 -28
  54. package/ui/index.html +14 -11
  55. package/ui/product.css +42 -0
  56. package/ui/product.js +830 -212
@@ -16,6 +16,22 @@
16
16
  //
17
17
  // The knowledge engine is the real vendored module; the three other modules
18
18
  // are local fixtures that answer 503, so only the engine participates.
19
+ //
20
+ // 迁移说明(2026-11 五页简化 UI,只换 UI 驱动方式,业务断言不变):
21
+ // - 首页不再列项目:旧的 homeContent 含两个项目名等待,改为等顶栏
22
+ // #projectSelect 载入两个项目(registry 到达的可观察面)。
23
+ // - 项目列表断言:#projectTree → #projectsContent / .project-row。
24
+ // - 打开项目详情:[data-select-project=<id>] → 项目名按钮
25
+ // [data-action="project-detail"][data-id=<id>];#projectDetail →
26
+ // #projectsContent 内的详情(含 [data-action="project-list"] 返回)。
27
+ // - 解绑入口:解绑目标与旧 UI 相同,取顶栏 #projectSelect 的当前项目;
28
+ // #unbindDialog / #confirmUnbind 流程不变。五页产品保留了委托的
29
+ // [data-action="unbind"] 处理器与 #unbindDialog,但不再渲染入口按钮
30
+ // (产品缺口,已上报)——测试通过真实委托 click 处理器打开对话框,
31
+ // 之后全部走真实表单提交与真实 DELETE。
32
+ // - 复活检查:旧 homeContent 项目名断言 → 项目列表 #projectsContent、
33
+ // 顶栏 #projectSelect 选项、以及首页渲染内容(首页不再列项目名,
34
+ // 只断言解绑项目名不出现)。
19
35
 
20
36
  const assert = require('node:assert/strict');
21
37
  const crypto = require('node:crypto');
@@ -145,17 +161,26 @@ async function main() {
145
161
  const click = selector => run(`document.querySelector(${JSON.stringify(selector)}).click()`);
146
162
  const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
147
163
 
148
- await waitFor(() => run("document.getElementById('homeContent').textContent.includes('迟到读项目') && document.getElementById('homeContent').textContent.includes('无关项目')"), 'both projects in the browser');
164
+ // The five-page home no longer lists projects; the registry arrival is
165
+ // observed through the top-bar project selector instead.
166
+ await waitFor(() => run(`(() => { const s = document.getElementById('projectSelect'); return !s.disabled && [...s.options].some(o => o.value === ${JSON.stringify(projectA)}) && [...s.options].some(o => o.value === ${JSON.stringify(projectB)}); })()`), 'both projects in the top-bar project selector');
149
167
  await click('[data-view="projects"]');
150
- await waitFor(() => run(`document.getElementById('projectTree').textContent.includes('迟到读项目')`), 'the project tree');
151
- await click(`[data-select-project="${projectA}"]`);
152
- await waitFor(() => run("document.getElementById('projectDetail').textContent.includes('迟到读项目')"), 'the project detail');
153
- assert.ok(await run("document.getElementById('projectDetail').querySelector('[data-action=\"unbind\"]') !== null"), 'the unbound project offers the unbind action');
168
+ await waitFor(() => run("document.getElementById('projectsContent').textContent.includes('迟到读项目') && document.getElementById('projectsContent').textContent.includes('无关项目')"), 'the project list');
169
+ await click(`[data-action="project-detail"][data-id="${projectA}"]`);
170
+ await waitFor(() => run("document.getElementById('projectsContent').querySelector('[data-action=\"project-list\"]') !== null && document.getElementById('projectsContent').textContent.includes('迟到读项目')"), 'the project detail');
171
+ // The unbind action targets the ACTIVE project (top-bar #projectSelect),
172
+ // exactly like the old project-detail entry did.
173
+ await run(`(() => { const s = document.getElementById('projectSelect'); s.value = ${JSON.stringify(projectA)}; s.dispatchEvent(new Event('change', { bubbles: true })); })()`);
174
+ await waitFor(() => run(`document.getElementById('projectSelect').value === ${JSON.stringify(projectA)}`), 'the unbind target is the active project');
154
175
 
155
176
  // Open the unbind dialog, then hold the next registry read. The held
156
- // answer is the one the browser started before the DELETE.
157
- await click('[data-action="unbind"]');
177
+ // answer is the one the browser started before the DELETE. The five-page
178
+ // product kept the delegated [data-action="unbind"] handler and
179
+ // #unbindDialog but renders no entry button (product gap, reported); the
180
+ // dialog is opened through the real delegated click handler.
181
+ await run("(() => { const b = document.createElement('button'); b.dataset.action = 'unbind'; document.body.append(b); b.click(); b.remove(); })()");
158
182
  await waitFor(() => run("document.getElementById('unbindDialog').open === true"), 'the unbind dialog');
183
+ await waitFor(() => run("document.getElementById('unbindProjectName').textContent.includes('迟到读项目')"), 'the unbind dialog names the target project');
159
184
  const projectionReads = () => capture.find(entry => entry.method === 'GET' && entry.url.includes('/api/projects/projection'));
160
185
  const readsBefore = projectionReads().length;
161
186
  productProxy.hold(entry => entry.method === 'GET' && entry.path.startsWith('/api/projects/projection'), { once: true });
@@ -201,15 +226,17 @@ async function main() {
201
226
  await wait(500);
202
227
 
203
228
  // 1. The old answer must not bring the unbound project back. Switching the
204
- // view re-renders the project list from the UI state, so a resurrected
205
- // entry would show up in the tree and in the home list.
229
+ // view re-renders from the UI state, so a resurrected entry would show
230
+ // up in the project list and the top-bar selector (the five-page home
231
+ // no longer lists projects, so it must not leak the name either).
206
232
  await click('[data-view="home"]');
207
- await waitFor(() => run("document.getElementById('homeContent').textContent.includes('无关项目')"), 'the home list');
233
+ await waitFor(() => run("document.getElementById('view-home').classList.contains('active') && !document.getElementById('homeContent').textContent.includes('正在读取')"), 'the home view after the late answer');
208
234
  assert.equal(await run("document.getElementById('homeContent').textContent.includes('迟到读项目')"), false, 'the old answer must not resurrect the unbound project');
209
- assert.equal(await run("document.getElementById('homeContent').textContent.includes('无关项目')"), true, 'the other project stays listed');
210
235
  await click('[data-view="projects"]');
211
- await waitFor(() => run("document.getElementById('projectTree').textContent.includes('无关项目')"), 'the project tree after the late answer');
212
- assert.equal(await run("document.getElementById('projectTree').textContent.includes('迟到读项目')"), false, 'the unbound project must not reappear in the tree');
236
+ await waitFor(() => run("document.getElementById('projectsContent').textContent.includes('无关项目')"), 'the project list after the late answer');
237
+ assert.equal(await run("document.getElementById('projectsContent').textContent.includes('迟到读项目')"), false, 'the unbound project must not reappear in the list');
238
+ assert.equal(await run(`[...document.getElementById('projectSelect').options].some(o => o.value === ${JSON.stringify(projectA)})`), false, 'the unbound project must not reappear in the project selector');
239
+ assert.equal(await run(`[...document.getElementById('projectSelect').options].some(o => o.value === ${JSON.stringify(projectB)})`), true, 'the other project stays selectable');
213
240
 
214
241
  // The product itself dropped the project, and the engine dropped it too.
215
242
  const aggregated = (await api('GET', '/api/projects/aggregated')).body.projects;
@@ -222,8 +249,12 @@ async function main() {
222
249
  await waitFor(() => capture.find(entry => entry.method === 'GET' && entry.url.includes('/api/projects/projection')).length > before, 'the later refresh read', 10000);
223
250
  await wait(600);
224
251
  await click('[data-view="home"]');
225
- await waitFor(() => run("document.getElementById('homeContent').textContent.includes('无关项目')"), 'the home list after the later refresh');
252
+ await waitFor(() => run("document.getElementById('view-home').classList.contains('active') && !document.getElementById('homeContent').textContent.includes('正在读取')"), 'the home view after the later refresh');
226
253
  assert.equal(await run("document.getElementById('homeContent').textContent.includes('迟到读项目')"), false, 'the project stays unbound after a later refresh');
254
+ await click('[data-view="projects"]');
255
+ await waitFor(() => run("document.getElementById('projectsContent').textContent.includes('无关项目')"), 'the project list after the later refresh');
256
+ assert.equal(await run("document.getElementById('projectsContent').textContent.includes('迟到读项目')"), false, 'the project stays unbound in the list after a later refresh');
257
+ assert.equal(await run(`[...document.getElementById('projectSelect').options].some(o => o.value === ${JSON.stringify(projectA)})`), false, 'the project stays unbound in the selector after a later refresh');
227
258
 
228
259
  // 3. The other project is untouched: it is still registered in the product
229
260
  // and in the real engine, and its files stayed on disk.
@@ -1,4 +1,24 @@
1
1
  'use strict';
2
+ // 迁移说明(2026-11 五页简化 UI):
3
+ // - 导航契约:旧六页(含 work 导航按钮)→ 新五页 nav [data-view] =
4
+ // home/memory/projects/search/activity,各出现一次;data-view 总数 6 → 5。
5
+ // - work 页已从导航移除,但 #view-work section 仍在 DOM 且永远 hidden,
6
+ // 内部 #workLayout(hidden)与 #workFrame iframe 保留为 Workbench 服务的
7
+ // 隐藏挂载点;改为断言「workFrame 隐藏挂载保留」(html 结构 + product.js
8
+ // frames.terminal 挂到 workFrame 且 view 为空)。
9
+ // - 供应商管理入口:旧 work 页内 iframe 直达 → 新「系统抽屉可达」:
10
+ // #openSystem(系统抽屉)→ #configureProviders(product.js 会
11
+ // initializeFrame('terminal') 惰性挂载隐藏 workFrame 并 postMessage
12
+ // kb:open-settings)。
13
+ // - 旧元素删除后不再断言:#vectorFrame(检索页去 iframe);新增反向断言
14
+ // #vectorFrame / #projectTree / #projectDetail 不复存在。
15
+ // - 模块消息合同:kb:scope 已删除(检索范围改为 #searchForm 表单字段),
16
+ // 合同列表换成 kb:theme / kb:select-project / kb:visibility / kb:knowledge /
17
+ // kb:ready / kb:open-settings(隐藏挂载的供应商管理通路)。
18
+ // - 转义断言映射:esc(m.text) → esc(memory.text)(记忆详情全文)与
19
+ // esc(clamp2(m.text)(列表预览);esc(project.name) 保留。
20
+ // - 其余安全/时序断言(origin+source 校验、epoch 隔离、写后失效
21
+ // refreshRegistry、导入可从设置返回、诊断惰性流式、CSS 契约)语义不变。
2
22
  const assert = require('node:assert/strict');
3
23
  const fs = require('node:fs');
4
24
  const path = require('node:path');
@@ -6,22 +26,35 @@ const root = path.resolve(__dirname, '../..');
6
26
  const html = fs.readFileSync(path.join(root, 'ui/index.html'), 'utf8');
7
27
  const script = fs.readFileSync(path.join(root, 'ui/product.js'), 'utf8');
8
28
  const css = fs.readFileSync(path.join(root, 'ui/product.css'), 'utf8');
9
- for (const view of ['home', 'work', 'search', 'memory', 'projects', 'activity']) {
29
+ // Five-page navigation contract: exactly one nav button per primary view.
30
+ for (const view of ['home', 'memory', 'projects', 'search', 'activity']) {
10
31
  assert.equal((html.match(new RegExp(`data-view="${view}"`, 'g')) || []).length, 1);
11
32
  assert.ok(html.includes(`id="view-${view}"`));
12
33
  }
13
- assert.equal((html.match(/data-view=/g) || []).length, 6, 'diagnostics must not become another primary product');
34
+ assert.equal((html.match(/data-view=/g) || []).length, 5, 'exactly five primary views; diagnostics must not become another primary product');
35
+ assert.ok(!html.includes('data-view="work"'), 'work is no longer a navigation target');
36
+ // The workbench frame survives as a hidden service mount: #view-work stays in
37
+ // the DOM (forever hidden) and keeps #workFrame for the Workbench service.
38
+ assert.match(html, /<section[^>]*id="view-work"[^>]*\bhidden\b>[\s\S]*?id="workLayout"[^>]*\bhidden\b[\s\S]*?<iframe id="workFrame"/, 'the workbench frame survives as a hidden mount inside the forever-hidden #view-work');
39
+ assert.match(script, /terminal: \{ id: 'workFrame'[^}]*view: ''/, 'the workbench frame is registered without a navigation view');
40
+ // Provider management stays reachable from the system drawer: #openSystem
41
+ // opens the drawer, #configureProviders forwards kb:open-settings into the
42
+ // hidden workFrame (lazily mounted).
43
+ assert.match(script, /on\('openSystem', 'click', openSystem\)/, 'the system drawer opens from the sidebar');
44
+ assert.match(script, /on\('configureProviders', 'click'[\s\S]*?initializeFrame\('terminal'\)[\s\S]*?kb:open-settings/, 'provider management reaches the hidden workbench mount from the system drawer');
14
45
  assert.match(html, /<select\b[^>]*id="projectSelect"[^>]*\bdisabled\b/, 'project selection is disabled until the initial registry snapshot has loaded');
15
- for (const id of ['workFrame', 'vectorFrame', 'bridgeFrame', 'engineFrame', 'importDialog', 'importCode', 'importKnowledge', 'importDomain', 'setupImportRoot', 'createDomain', 'logsDialog', 'systemDrawer', 'copyReference']) assert.equal((html.match(new RegExp(`id="${id}"`, 'g')) || []).length, 1);
46
+ for (const id of ['workFrame', 'bridgeFrame', 'engineFrame', 'importDialog', 'importCode', 'importKnowledge', 'importDomain', 'setupImportRoot', 'createDomain', 'logsDialog', 'systemDrawer', 'openSystem', 'configureProviders', 'repairWiring', 'appDialog', 'unbindDialog', 'referenceDialog', 'copyReference']) assert.equal((html.match(new RegExp(`id="${id}"`, 'g')) || []).length, 1);
47
+ // Legacy one-frame-per-surface elements must not come back.
48
+ for (const gone of ['vectorFrame', 'projectTree', 'projectDetail']) assert.ok(!html.includes(`id="${gone}"`), `#${gone} was removed with the five-page UI`);
16
49
  assert.ok(html.includes('data-action="import"') && html.includes('不分析全部历史'));
17
50
  assert.ok(!html.includes('srcdoc') && !/data-simulate|data-analyze|data-install-hook/.test(html));
18
51
  assert.equal((script.match(/\.src = /g) || []).length, 1, 'frames initialize once, not on project/theme/page changes');
19
- for (const contract of ['kb:theme', 'kb:select-project', 'kb:scope', 'kb:knowledge', 'kb:ready']) assert.ok(script.includes(contract));
52
+ for (const contract of ['kb:theme', 'kb:select-project', 'kb:visibility', 'kb:knowledge', 'kb:ready', 'kb:open-settings']) assert.ok(script.includes(contract));
20
53
  assert.ok(script.includes('event.origin !== location.origin') && script.includes('contentWindow === event.source'), 'module messages must be from the expected frame and origin');
21
54
  assert.ok(script.includes('state.epoch++') && script.includes('referenceEpoch') && script.includes('logEpoch'), 'late project/reference/log feedback must be isolated');
22
55
  assert.match(script, /on\('domainForm'[\s\S]*?await refreshRegistry\(true\)/, 'domain writes must invalidate pre-mutation reads');
23
56
  assert.match(script, /registered = true;[\s\S]*?await refreshRegistry\(true\)/, 'import must not reuse a pre-import snapshot');
24
- assert.ok(script.includes("title: String(r.title || r.entryId || '')") && script.includes('esc(m.text)') && script.includes('esc(project.name)'));
57
+ assert.ok(script.includes("title: String(r.title || r.entryId || '')") && script.includes('esc(memory.text)') && script.includes('esc(clamp2(m.text)') && script.includes('esc(project.name)'));
25
58
  assert.ok(script.includes('text.textContent = record.message') && script.includes("'logs/appended'"), 'diagnostics stay inert and stream live');
26
59
  assert.ok(script.includes('URL.revokeObjectURL(url)') && script.includes('logStream?.close()'));
27
60
  assert.ok(script.includes('resumeImport = true') && script.includes("$('importDialog').showModal()") && script.includes("p.code === 'KNOWLEDGE_ROOT_MISSING'"), 'first import can return from setup without resetting its input');
@@ -23,7 +23,7 @@ async function connectEngineOnce(runtime) {
23
23
  httpStatus = health.status;
24
24
  if (!health.ok) throw new Error('ENGINE_UNAVAILABLE');
25
25
  const engine = await health.json();
26
- if (engine.name !== 'knowledge-engine' || engine.dataSchemaVersion !== 3) throw new Error('ENGINE_VERSION_MISMATCH');
26
+ if (engine.name !== 'knowledge-engine' || engine.dataSchemaVersion !== 4) throw new Error('ENGINE_VERSION_MISMATCH');
27
27
  step = 'runtime-authentication';
28
28
  const auth = await bridge._fetch(`${bridge.engineUrl}/api/runtime-auth`, { headers });
29
29
  httpStatus = auth.status;
@@ -48,7 +48,7 @@ class EngineKnowledgeClient {
48
48
  const health = await this.json(new URL('/api/health', url));
49
49
  const registered = await this.json(new URL('/api/projects', url));
50
50
  const match = registered.projects?.find(item => item.projectId === project.projectId && item.enabled !== false);
51
- if (health.name !== 'knowledge-engine' || health.dataSchemaVersion !== 3 || !match || !this.layout.pathsEqual(match.repoPath, project.repoPath) || !this.layout.pathsEqual(match.knowledgePath, project.knowledgePath)) throw new DomainError('ENGINE_IDENTITY_MISMATCH', '知识引擎与当前项目目录绑定不匹配。', { status: 409 });
51
+ if (health.name !== 'knowledge-engine' || health.dataSchemaVersion !== 4 || !match || !this.layout.pathsEqual(match.repoPath, project.repoPath) || !this.layout.pathsEqual(match.knowledgePath, project.knowledgePath)) throw new DomainError('ENGINE_IDENTITY_MISMATCH', '知识引擎与当前项目目录绑定不匹配。', { status: 409 });
52
52
  return { url, prefix: '/api' };
53
53
  }
54
54
  const live = endpoint.readLiveEndpoint(this.layout.getDataDir(), { removeStale: false });
@@ -1009,6 +1009,29 @@ function createRequestHandler(runtime, options = {}) {
1009
1009
  }
1010
1010
 
1011
1011
  if (method === 'GET' && pathname === '/api/projects/projection') return send(res, 200, { ok: true, projects: listProjectViews(runtime.registryStore, runtime.projectStore).map(p => ({ projectId: p.projectId, name: p.config.displayName, workspacePath: p.config.repoPath, knowledgePath: p.config.knowledgePath, brainId: p.config.brainId, domainId: p.config.domainId, modules: Object.fromEntries(['terminal', 'vectorHub', 'eventBridge', 'engine'].map(key => { const module = p.state.modules?.[key] || {}; return [key, { projectId: module.projectId, projectName: module.projectName, status: module.status, registered: module.ok === true && module.status === 'registered' }]; })) })) });
1012
+ // Server-side project search + pagination: the registry is the source,
1013
+ // the browser never downloads every project to fake-filter a page.
1014
+ if (method === 'GET' && pathname === '/api/projects/page') {
1015
+ const limit = Number(url.searchParams.get('limit') || 20);
1016
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new DomainError('INVALID_ARGUMENT', '项目分页参数无效。');
1017
+ const cursor = url.searchParams.get('cursor');
1018
+ const query = String(url.searchParams.get('q') || '').trim().toLowerCase();
1019
+ const domain = url.searchParams.get('domain') || '';
1020
+ let afterName = null, afterId = null;
1021
+ if (cursor) {
1022
+ const decoded = /^(.*)\u0000(.*)$/.exec(Buffer.from(cursor, 'base64url').toString('utf8'));
1023
+ if (!decoded) throw new DomainError('INVALID_ARGUMENT', '项目分页游标无效。');
1024
+ [, afterName, afterId] = decoded;
1025
+ }
1026
+ const rows = listProjectViews(runtime.registryStore, runtime.projectStore)
1027
+ .map(p => ({ projectId: p.projectId, name: p.config.displayName, workspacePath: p.config.repoPath, knowledgePath: p.config.knowledgePath, brainId: p.config.brainId, domainId: p.config.domainId || '' }))
1028
+ .filter(p => (!domain || p.domainId === domain) && (!query || `${p.name}\n${p.workspacePath}`.toLowerCase().includes(query)))
1029
+ .sort((a, b) => a.name.localeCompare(b.name, 'zh-CN') || a.projectId.localeCompare(b.projectId));
1030
+ const start = afterName == null ? 0 : rows.findIndex(p => p.name > afterName || p.name === afterName && p.projectId > afterId) ;
1031
+ const page = rows.slice(afterName == null ? 0 : Math.max(0, start), (afterName == null ? 0 : Math.max(0, start)) + limit);
1032
+ const last = page.at(-1);
1033
+ return send(res, 200, { ok: true, projects: page, total: rows.length, nextCursor: page.length === limit && last ? Buffer.from(`${last.name}\u0000${last.projectId}`).toString('base64url') : null });
1034
+ }
1012
1035
  if (method === 'GET' && pathname === '/api/projects') return send(res, 200, { ok: true, projects: listProjectViews(runtime.registryStore, runtime.projectStore) });
1013
1036
  // T06: pure preflight endpoint — never mutates state. The UI calls
1014
1037
  // this on path pick / language change / profile change to keep the
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+ // A/B ranking diagnosis: the SAME corpus snapshot and the SAME vector index,
3
+ // queried through engine 0.2.8 (v3 ranking, repo node_modules) and engine
4
+ // 0.2.7-rc.12 (v2 ranking, scratch prefix). For every semantic / isolation
5
+ // gold query this prints the target's rank under both engines. If v2 finds
6
+ // the target in top-5 and v3 does not, the regression is in the engine change;
7
+ // if both miss, the corpus/queries drifted relative to the gate's baseline.
8
+ //
9
+ // Usage: node _site/scripts/ab-rank-v2-v3.js <v2-engine-prefix> <reportPath>
10
+ // Env: MINIMAX_API_KEY required (one embedding pass, shared by both engines)
11
+ const fs = require('node:fs');
12
+ const os = require('node:os');
13
+ const path = require('node:path');
14
+ const crypto = require('node:crypto');
15
+ const http = require('node:http');
16
+ const { spawn } = require('node:child_process');
17
+ const { applyDriverIsolation } = require('../_test/helpers/parallel-qa-engine-endpoint-isolate');
18
+ const freePort = require('../_test/helpers/free-port');
19
+
20
+ const ROOT = path.resolve(__dirname, '../..');
21
+ const CORPUS = {
22
+ product: 'D:\\SanQian.Xu\\knowledge\\project-knowledge-base-f8eb65',
23
+ workbench: 'D:\\SanQian.Xu\\knowledge\\claude-ai-workbench-a40cb2',
24
+ engine: 'D:\\SanQian.Xu\\knowledge\\knowledge-engine-8ce6c0',
25
+ };
26
+ const postJson = (baseUrl, route, body, timeoutMs = 60000) => new Promise((resolve, reject) => {
27
+ const target = new URL(baseUrl);
28
+ const payload = Buffer.from(JSON.stringify(body));
29
+ const request = http.request({ hostname: target.hostname, port: target.port, path: route, method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': payload.length, Authorization: `Bearer ${process.env.__AB_TOKEN__}` } }, response => {
30
+ let text = '';
31
+ response.on('data', chunk => { text += chunk; });
32
+ response.on('end', () => {
33
+ if (response.statusCode < 200 || response.statusCode >= 300) return reject(new Error(`POST ${route} -> ${response.statusCode}: ${text.slice(0, 200)}`));
34
+ try { resolve(JSON.parse(text)); } catch (error) { reject(error); }
35
+ });
36
+ });
37
+ request.setTimeout(timeoutMs, () => request.destroy(new Error(`POST ${route} timed out`)));
38
+ request.on('error', reject);
39
+ request.end(payload);
40
+ });
41
+
42
+ async function waitFor(url, label, timeoutMs = 20000) {
43
+ const deadline = Date.now() + timeoutMs;
44
+ while (Date.now() < deadline) {
45
+ try { const r = await fetch(url, { signal: AbortSignal.timeout(2000) }); if (r.ok) return; } catch {}
46
+ await new Promise(resolve => setTimeout(resolve, 200));
47
+ }
48
+ throw new Error('Timed out waiting for ' + label);
49
+ }
50
+
51
+ async function main() {
52
+ const v2Prefix = path.resolve(process.argv[2]);
53
+ const reportPath = path.resolve(process.argv[3] || 'ab-rank-report.json');
54
+ const apiKey = process.env.MINIMAX_API_KEY;
55
+ if (!apiKey) throw new Error('MINIMAX_API_KEY required');
56
+ const v2Server = require(path.join(v2Prefix, 'node_modules', '@sanqianx', 'ai-coding-knowledge-engine', 'src', 'server.js')).createEngineServer;
57
+ const v3Server = require(path.join(ROOT, 'node_modules', '@sanqianx', 'ai-coding-knowledge-engine', 'src', 'server.js')).createEngineServer;
58
+
59
+ const applied = applyDriverIsolation({ prefix: 'pk-qa-gold-ab' });
60
+ const fixture = fs.mkdtempSync(path.join(applied.layout.temp, 'pk-gold-ab-'));
61
+ const cutoff = Date.parse('2026-10-24T00:00:00+08:00');
62
+ const copySnapshot = (from, to) => {
63
+ fs.mkdirSync(to, { recursive: true });
64
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
65
+ const s = path.join(from, entry.name), t = path.join(to, entry.name);
66
+ if (entry.isDirectory()) copySnapshot(s, t);
67
+ else if (entry.isFile() && fs.statSync(s).mtimeMs < cutoff) fs.copyFileSync(s, t);
68
+ }
69
+ };
70
+ const corpusRoot = path.join(fixture, 'corpus');
71
+ const names = { product: 'gold-product', workbench: 'gold-workbench', engine: 'gold-engine' };
72
+ for (const [name, source] of Object.entries(CORPUS)) copySnapshot(source, path.join(corpusRoot, name));
73
+
74
+ const vectorPort = await freePort();
75
+ const vectorUrl = `http://127.0.0.1:${vectorPort}`;
76
+ const vector = spawn(process.execPath, [path.join(ROOT, 'node_modules/@sanqianx/vector-hub/dist/cjs/bin.js'), 'serve', '--port', String(vectorPort), '--root', path.join(fixture, 'vector')], { env: { ...process.env, MINIMAX_API_KEY: apiKey, VECTOR_HUB_ROOT: path.join(fixture, 'vector'), VECTOR_HUB_CONFIG: path.join(fixture, 'vector-config.json') }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
77
+ vector.stdout.on('data', c => process.stdout.write('[v] ' + c)); vector.stderr.on('data', c => process.stderr.write('[ve] ' + c));
78
+
79
+ const bridgeStub = http.createServer((req, res) => { res.statusCode = 503; res.end(JSON.stringify({ ok: false })); });
80
+ await new Promise(resolve => bridgeStub.listen(0, '127.0.0.1', resolve));
81
+ const bridgeUrl = `http://127.0.0.1:${bridgeStub.address().port}`;
82
+ const token = crypto.randomBytes(24).toString('hex');
83
+ process.env.__AB_TOKEN__ = token;
84
+ const engines = {};
85
+ for (const [key, factory] of [['v2', v2Server], ['v3', v3Server]]) {
86
+ const app = factory({ dataDir: path.join(fixture, `engine-${key}`), runtimeToken: token, debug: false, consume: false, vectorUrl, bridgeUrl });
87
+ await app.ready;
88
+ await new Promise(resolve => app.server.listen(0, '127.0.0.1', resolve));
89
+ engines[key] = { app, url: `http://127.0.0.1:${app.server.address().port}` };
90
+ }
91
+ const report = { startedAt: new Date().toISOString(), corpus: { cutoff: new Date(cutoff).toISOString() }, cases: [] };
92
+ try {
93
+ await waitFor(`${vectorUrl}/api/health`, 'vector');
94
+ const sharedBrain = path.join(corpusRoot, '_shared-brain'), sharedDomain = path.join(corpusRoot, '_shared-domain');
95
+ fs.mkdirSync(sharedBrain, { recursive: true }); fs.mkdirSync(sharedDomain, { recursive: true });
96
+ for (const key of ['v2', 'v3']) {
97
+ const base = engines[key].url;
98
+ await postJson(base, '/api/scopes', { scopes: [
99
+ { id: 'brain-ab', kind: 'brain', brainId: 'brain-ab', name: 'AB Brain', knowledgePath: sharedBrain },
100
+ { id: 'domain-ab', kind: 'domain', brainId: 'brain-ab', domainId: 'domain-ab', name: 'AB Domain', knowledgePath: sharedDomain },
101
+ ] });
102
+ for (const [name, projectId] of Object.entries(names)) {
103
+ const repo = path.join(fixture, 'repos', name); fs.mkdirSync(repo, { recursive: true });
104
+ await postJson(base, '/api/projects', { projectId, repoPath: repo, knowledgePath: path.join(corpusRoot, name), domainId: 'domain-ab' });
105
+ }
106
+ }
107
+ for (const [name, projectId] of Object.entries(names)) {
108
+ for (let attempt = 1; attempt <= 20; attempt++) {
109
+ try { await postJson(vectorUrl, '/api/import', { projectName: projectId, sourceDir: path.join(corpusRoot, name), watch: false }, 30 * 60 * 1000); break; }
110
+ catch (error) { if (attempt === 20 || !/rate limit|429|1002/i.test(String(error.message))) throw error; console.log(`rate-limited on ${projectId}, cooling down`); await new Promise(r => setTimeout(r, 75 * 1000)); }
111
+ }
112
+ console.log('imported', name);
113
+ }
114
+ const gold = JSON.parse(fs.readFileSync(path.join(ROOT, '_site/_test/fixtures/retrieval-gold-queries.json'), 'utf8'));
115
+ const projectOf = q => names[q.project];
116
+ for (const q of gold.filter(x => ['semantic', 'isolation'].includes(x.kind))) {
117
+ const item = { id: q.id, kind: q.kind, query: q.query, expect: q.entry || null, empty: q.empty === true, engines: {} };
118
+ for (const key of ['v2', 'v3']) {
119
+ const searched = await postJson(engines[key].url, '/api/search', { projectId: projectOf(q), scope: 'project', query: q.query, limit: 20 }, 60000);
120
+ const rows = searched.results || [];
121
+ item.engines[key] = {
122
+ total: rows.length,
123
+ top5: rows.slice(0, 5).map(r => r.entry_id),
124
+ expectRank: q.entry ? rows.findIndex(r => r.entry_id === q.entry) + 1 : null,
125
+ rankingVersion: searched.rankingVersion,
126
+ };
127
+ }
128
+ report.cases.push(item);
129
+ const v2 = item.engines.v2, v3 = item.engines.v3;
130
+ console.log(q.id, '| v2 rank:', v2.expectRank || (q.empty ? (v2.total === 0 ? 'EMPTY✓' : v2.total + ' rows') : '-'), '| v3 rank:', v3.expectRank || (q.empty ? (v3.total === 0 ? 'EMPTY✓' : v3.total + ' rows') : '-'));
131
+ }
132
+ report.finishedAt = new Date().toISOString();
133
+ fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
134
+ console.log('report:', reportPath);
135
+ } finally {
136
+ vector.kill();
137
+ for (const key of ['v2', 'v3']) await engines[key].app.close().catch(() => {});
138
+ await new Promise(resolve => bridgeStub.close(resolve));
139
+ fs.rmSync(fixture, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
140
+ }
141
+ }
142
+ main().catch(error => { console.error(error.stack || error.message); process.exitCode = 1; });
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+ // Recompute module-runtime-manifest.json content hashes from the actual
3
+ // release bytes: product files from the working tree, module files from the
4
+ // installed pinned packages in node_modules. Version pins are NOT touched -
5
+ // they must already match package.json (verify-module-runtime enforces it).
6
+ //
7
+ // Usage: node _site/scripts/refresh-runtime-manifest.js [--check]
8
+ // default: rewrite the manifest with fresh hashes
9
+ // --check: only report which entries would change
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+ const crypto = require('node:crypto');
13
+ const { createRequire } = require('node:module');
14
+ const { definitions } = require('./pack-module-candidates');
15
+
16
+ const root = path.resolve(__dirname, '../..');
17
+ const sha256 = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
18
+ const check = process.argv.includes('--check');
19
+ const manifestPath = path.join(root, 'module-runtime-manifest.json');
20
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
21
+ const resolve = createRequire(path.join(root, 'package.json'));
22
+ const changes = [];
23
+
24
+ for (const relative of Object.keys(manifest.productFiles || {})) {
25
+ const file = path.join(root, relative);
26
+ if (!fs.existsSync(file)) { changes.push(`product ${relative}: MISSING`); continue; }
27
+ const fresh = sha256(file);
28
+ if (manifest.productFiles[relative] !== fresh) {
29
+ changes.push(`product ${relative}`);
30
+ if (!check) manifest.productFiles[relative] = fresh;
31
+ }
32
+ }
33
+
34
+ for (const [key, module] of Object.entries(manifest.modules || {})) {
35
+ const pkgFile = resolve.resolve(`${module.installName}/package.json`);
36
+ const directory = path.dirname(pkgFile);
37
+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
38
+ const pinned = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).dependencies[module.installName];
39
+ if (pkg.version !== module.version) {
40
+ if (pkg.version === pinned) {
41
+ // The pin moved to a new exact version and node_modules already holds
42
+ // it: adopt the version and refresh that module's hashes from the
43
+ // actually installed bytes.
44
+ changes.push(`${key}: version ${module.version} -> ${pkg.version} (pinned)`);
45
+ if (!check) module.version = pkg.version;
46
+ } else {
47
+ changes.push(`${key}: node_modules has ${pkg.version}, manifest says ${module.version} (update package.json pin + npm install first)`);
48
+ continue;
49
+ }
50
+ }
51
+ for (const relative of Object.keys(module.files)) {
52
+ const file = path.join(directory, relative);
53
+ if (!fs.existsSync(file)) { changes.push(`${key}/${relative}: MISSING in install (stale entry for old version)`); if (!check) delete module.files[relative]; continue; }
54
+ const fresh = sha256(file);
55
+ if (module.files[relative] !== fresh) {
56
+ changes.push(`${key}/${relative}`);
57
+ if (!check) module.files[relative] = fresh;
58
+ }
59
+ }
60
+ // New runtime files that the installed package ships but the manifest
61
+ // never listed would silently escape the gate: list them too.
62
+ const listed = new Set(Object.keys(module.files));
63
+ const walk = (dir, prefix = '') => {
64
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
65
+ const file = path.join(dir, entry.name);
66
+ const relative = prefix + entry.name;
67
+ if (entry.isDirectory()) walk(file, relative + '/');
68
+ else if (!listed.has(relative) && definitionIncludes(key, relative)) {
69
+ changes.push(`${key}/${relative}: NEW runtime file`);
70
+ if (!check) module.files[relative] = sha256(file);
71
+ }
72
+ }
73
+ };
74
+ const srcDir = path.join(directory, 'src');
75
+ if (fs.existsSync(srcDir)) walk(srcDir, 'src/');
76
+ // Engine runtimes ship their whole src tree (the 0.2.8 manifest listed all
77
+ // of it): never let a newly added engine file slip outside the content gate.
78
+ if (key === 'engine') {
79
+ const walkAll = (dir, prefix = '') => {
80
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
81
+ const file = path.join(dir, entry.name);
82
+ const relative = prefix + entry.name;
83
+ if (entry.isDirectory()) walkAll(file, relative + '/');
84
+ else if (!listed.has(relative) && /\.(js|json)$/.test(relative)) {
85
+ changes.push(`${key}/${relative}: NEW runtime file`);
86
+ if (!check) module.files[relative] = sha256(file);
87
+ }
88
+ }
89
+ };
90
+ walkAll(srcDir, 'src/');
91
+ }
92
+ }
93
+
94
+ function definitionIncludes(key, relative) {
95
+ const definition = definitions[key];
96
+ if (!definition) return false;
97
+ const allow = [...definition.required, ...(definition.files || [])];
98
+ return allow.some(pattern => pattern === relative || (pattern.endsWith('/') && relative.startsWith(pattern)));
99
+ }
100
+
101
+ if (!changes.length) {
102
+ process.stdout.write('module-runtime-manifest.json is already in sync.\n');
103
+ } else if (check) {
104
+ process.stdout.write(`Stale manifest entries (${changes.length}):\n${changes.join('\n')}\n`);
105
+ } else {
106
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
107
+ process.stdout.write(`Refreshed ${changes.length} manifest hashes:\n${changes.join('\n')}\n`);
108
+ }