@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
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "project-knowledge",
12
- "version": "5.0.32",
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,20 @@
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
+
12
+ ## [5.0.33] - 2026-11-11
13
+
14
+ - 知识注入改为会话一次索引(对齐 ZCode memory 的"索引+懒加载"模式):会话首条用户消息注入一次紧凑索引(适用已确认记忆全文 + 知识条目标题清单 + 仲裁声明),正文摘录不再进入注入层;后续消息默认静默,新增/变更的记忆全文重注入一次,删除的记忆发一行移除提示,相关问题对强命中条目(实词/身份/已校准向量命中,仅 bigram 撞词不触发)给一行面包屑并在 10 轮内冷却,超过 30 轮重发仅标题索引对冲上下文压缩。30 轮会话累计注入从旧设计的 ~90KB+ 降至 ≤10KB。
15
+ - 引擎升级至 `@sanqianx/ai-coding-knowledge-engine@0.2.8`(ranking-v3:词锚/字节对锚分离、listTitles、注入预算进 retrieval-policy);`context-hook` 空结果完全静默、降级提示只走 systemMessage,receipt 日志新增 `injectionKind`/`sessionIndexedCount`;响应契约向后兼容(status 枚举与必选字段不变)。
16
+ - 检索质量金标准新增 breadcrumb-gating 用例(正例强匹配出面包屑并冷却、负例零注入)与隔离运行器 `run-retrieval-gold-isolated.js`(自起真实 vector-hub 与引擎、语料只读副本、独立 VECTOR_HUB_CONFIG 防止继承用户全局 watcher);新增 `context-session-index-test.js` 端到端回归(跨项目诱饵零面包屑、30 轮累计注入量化断言)。
17
+
3
18
  ## [5.0.32] - 2026-11-10
4
19
 
5
20
  - 将 knowledge-engine 改为固定版本的公开 npm 依赖 `@sanqianx/ai-coding-knowledge-engine@0.2.7-rc.12`,从主仓库移除内置引擎源码和旧 vendoring 脚本;保留历史提交及现有 npm 版本。
@@ -27,6 +27,25 @@ async function main() {
27
27
  await writeOutput(output, { write: (text, callback) => { assert.ok(!text.includes('receipt')); callback(); } });
28
28
  const logDir = path.join(root, 'logs/projects/project-a'); const logText = fs.readFileSync(path.join(logDir, fs.readdirSync(logDir)[0]), 'utf8');
29
29
  assert.ok(!logText.includes(payload.prompt)); assert.ok(!logText.includes('revision 37')); assert.ok(logText.includes('agent.context.output'));
30
+ // Session-index contract: empty turns are fully silent, degraded notices
31
+ // stay user-facing, injectionKind rides along to the receipt log.
32
+ const engineResponse = body => async (url, options) => {
33
+ if (String(url).endsWith('/identity')) return Response.json(identity);
34
+ const input = JSON.parse(options.body);
35
+ return Response.json({ ok: true, requestId: input.requestId, projectId: 'project-a', memoryStatus: 'ready', ...body });
36
+ };
37
+ const silent = await run(payload, { env, fetchImpl: engineResponse({ status: 'empty', prompt: '', facts: [], memories: [], references: [] }) });
38
+ assert.deepEqual(silent, {}, 'empty turns inject nothing at all');
39
+ const degraded = await run(payload, { env, fetchImpl: engineResponse({ status: 'file-fallback', prompt: '', facts: [], memories: [], references: [] }) });
40
+ assert.match(degraded.systemMessage, /向量检索暂不可用/);
41
+ assert.ok(!degraded.hookSpecificOutput, 'degraded notices never enter the model context');
42
+ const indexed = await run(payload, { env, fetchImpl: engineResponse({ status: 'ready', injectionKind: 'index', sessionIndexedCount: 7, prompt: '<knowledge_context>session index</knowledge_context>', facts: [{}, {}], memories: [], references: [{}, {}] }) });
43
+ assert.match(indexed.hookSpecificOutput.additionalContext, /session index/);
44
+ assert.equal(indexed.receipt.injectionKind, 'index'); assert.equal(indexed.receipt.sessionIndexedCount, 7);
45
+ await writeOutput(indexed, { write: (text, callback) => callback() });
46
+ assert.ok(fs.readFileSync(path.join(logDir, fs.readdirSync(logDir)[0]), 'utf8').includes('"injectionKind":"index"'), 'the receipt log carries the injection kind');
47
+ const oversized = await run(payload, { env, fetchImpl: engineResponse({ status: 'ready', prompt: 'x'.repeat(8001), facts: [], memories: [], references: [] }) });
48
+ assert.match(oversized.systemMessage, /CONTEXT_INVALID_RESPONSE/);
30
49
  calls.length = 0;
31
50
  assert.deepEqual(await run(payload, { env: { ...env, KB_KNOWLEDGE_CONTEXT: '0' }, fetchImpl }), {}); assert.equal(calls.length, 0);
32
51
  assert.deepEqual(await run({ ...payload, hook_event_name: 'Stop' }, { env, fetchImpl }), {});
@@ -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
 
@@ -0,0 +1,244 @@
1
+ 'use strict';
2
+ // CTX-SI: the knowledge context injection follows the ZCode-memory session
3
+ // model instead of re-sending a full pack on every user message.
4
+ //
5
+ // The case drives the real engine through the product shell route that the
6
+ // UserPromptSubmit hook itself uses (/api/engine/context), with the vector hub
7
+ // fixture answering 503 so the lexical channel is the one under test.
8
+ //
9
+ // Expectations:
10
+ // 1. the first turn of a session injects the statement block, applicable
11
+ // memories and a TITLE-ONLY index once - never body text;
12
+ // 2. later turns stay silent unless something changed;
13
+ // 3. boundary-bigram collisions from same-domain neighbour projects (the
14
+ // "外推算法/RpcTransportSDK inside a memory-system question" class of
15
+ // false positives) never produce a breadcrumb, while a real word match
16
+ // earns a one-line pointer that then cools down;
17
+ // 4. a memory added mid-session is re-sent in full exactly once, and a
18
+ // deletion is announced exactly once;
19
+ // 5. across a simulated 30-turn session the cumulative injection stays an
20
+ // order of magnitude below the previous per-turn 8000-char design.
21
+
22
+ const assert = require('node:assert/strict');
23
+ const crypto = require('node:crypto');
24
+ const fs = require('node:fs');
25
+ const path = require('node:path');
26
+ const { spawnSync } = require('node:child_process');
27
+ const { spawnServer } = require('./helpers/spawn-server');
28
+ const { createModuleFixture, createUpstreamProxy } = require('./helpers/module-fixture');
29
+ const freePort = require('./helpers/free-port');
30
+ const { applyDriverIsolation } = require('./helpers/parallel-qa-engine-endpoint-isolate');
31
+ const { guardedCreateEngineServer } = require('./helpers/parallel-qa-engine-endpoint-guard');
32
+
33
+ const ROOT = path.resolve(__dirname, '../..');
34
+
35
+ function git(cwd, args) {
36
+ const result = spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8', windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } });
37
+ assert.equal(result.status, 0, `git ${args.join(' ')} failed: ${result.stderr}`);
38
+ return String(result.stdout || '').trim();
39
+ }
40
+
41
+ function makeRepo(root, name) {
42
+ const repo = path.join(root, name);
43
+ fs.mkdirSync(repo, { recursive: true });
44
+ git(repo, ['init', '-q', '-b', 'main']);
45
+ git(repo, ['config', 'user.email', 'session-index@local.invalid']);
46
+ git(repo, ['config', 'user.name', 'Session Index Regression']);
47
+ fs.writeFileSync(path.join(repo, 'README.md'), `# ${name}\n`);
48
+ git(repo, ['add', '.']); git(repo, ['commit', '-qm', 'baseline']);
49
+ return repo;
50
+ }
51
+
52
+ async function waitForHealth(base, timeoutMs = 20000) {
53
+ const deadline = Date.now() + timeoutMs;
54
+ while (Date.now() < deadline) {
55
+ try {
56
+ const response = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(2000) });
57
+ if (response.ok) return;
58
+ } catch {}
59
+ await new Promise(resolve => setTimeout(resolve, 100));
60
+ }
61
+ throw new Error('Timed out waiting for the isolated server on ' + base);
62
+ }
63
+
64
+ async function main() {
65
+ // Driver isolation FIRST: the environment is rebuilt from a system whitelist
66
+ // with every product surface pointed at a per-run layout, before any product
67
+ // module is required.
68
+ const applied = applyDriverIsolation({ prefix: 'pk-qa-ctx-session' });
69
+ const fixture = fs.mkdtempSync(path.join(applied.layout.temp, 'pk-ctx-session-'));
70
+ const dataDir = path.join(fixture, 'data');
71
+ const knowledgeRoot = path.join(fixture, 'knowledge');
72
+ const repoA = makeRepo(fixture, 'repo-memory-system');
73
+ const repoC = makeRepo(fixture, 'repo-rpc-transport');
74
+ const knowledgeA = path.join(knowledgeRoot, '记忆系统项目');
75
+ const knowledgeC = path.join(knowledgeRoot, '轮转调度项目');
76
+ fs.mkdirSync(knowledgeA, { recursive: true }); fs.mkdirSync(knowledgeC, { recursive: true });
77
+
78
+ const engineToken = crypto.randomBytes(24).toString('hex');
79
+ const terminal = createModuleFixture({ kind: 'terminal' });
80
+ const vectorHub = createModuleFixture({ kind: 'vectorHub' });
81
+ const eventBridge = createModuleFixture({ kind: 'eventBridge' });
82
+ for (const fixtureService of [terminal, vectorHub, eventBridge]) {
83
+ await fixtureService.start();
84
+ fixtureService.setOnline(false);
85
+ }
86
+ const engine = guardedCreateEngineServer({ dataDir: path.join(fixture, 'engine'), runtimeToken: engineToken, debug: true, consume: false, vectorUrl: vectorHub.url, bridgeUrl: eventBridge.url });
87
+ await engine.ready;
88
+ await new Promise(resolve => engine.server.listen(0, '127.0.0.1', resolve));
89
+ const engineUrl = `http://127.0.0.1:${engine.server.address().port}`;
90
+ const engineProxy = createUpstreamProxy({ target: engineUrl, token: engineToken, tag: 'engine' });
91
+ await engineProxy.start();
92
+
93
+ const port = await freePort();
94
+ const base = `http://127.0.0.1:${port}`;
95
+ const server = spawnServer({
96
+ root: ROOT,
97
+ port,
98
+ dataDir,
99
+ tag: 'context-session-index',
100
+ analysisOwner: 'engine',
101
+ extraEnv: {
102
+ KB_MODULES_REGISTER: '1',
103
+ KB_MODULES_AUTOSTART: '0',
104
+ KB_KNOWLEDGE_ENGINE_URL: engineProxy.url,
105
+ KB_TERMINAL_URL: terminal.url,
106
+ KB_VECTORHUB_URL: vectorHub.url,
107
+ KB_EVENTBRIDGE_URL: eventBridge.url,
108
+ },
109
+ });
110
+ const api = async (method, route, body) => {
111
+ const response = await fetch(base + route, {
112
+ method,
113
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
114
+ body: body === undefined ? undefined : JSON.stringify(body),
115
+ signal: AbortSignal.timeout(20000),
116
+ });
117
+ return { status: response.status, body: await response.json() };
118
+ };
119
+ const engineApi = async (method, route, body) => {
120
+ const response = await fetch(engineUrl + route, {
121
+ method,
122
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
123
+ body: body === undefined ? undefined : JSON.stringify(body),
124
+ signal: AbortSignal.timeout(20000),
125
+ });
126
+ return { status: response.status, body: await response.json() };
127
+ };
128
+ let turnSeq = 0;
129
+ const context = async (query, sessionId, repoPath = repoA) => {
130
+ turnSeq += 1;
131
+ const result = await api('POST', '/api/engine/context', { repoPath, query, client: 'zcode', sessionId, requestId: `ctx-e2e-${turnSeq}` });
132
+ assert.equal(result.status, 200, JSON.stringify(result.body));
133
+ return result.body;
134
+ };
135
+
136
+ try {
137
+ await waitForHealth(base);
138
+ assert.equal((await api('PATCH', '/api/settings', { knowledge: { rootPath: knowledgeRoot } })).status, 200);
139
+ const domain = (await api('POST', '/api/domains', { name: '会话领域' })).body.domain;
140
+ assert.ok(domain && domain.id, 'the domain exists for both projects');
141
+
142
+ const importedA = await api('POST', '/api/projects/import', { localPath: repoA, knowledgePath: knowledgeA, displayName: '记忆系统项目', domainId: domain.id });
143
+ assert.equal(importedA.status, 201, JSON.stringify(importedA.body));
144
+ const projectA = importedA.body.projectId;
145
+ const importedC = await api('POST', '/api/projects/import', { localPath: repoC, knowledgePath: knowledgeC, displayName: '轮转调度项目', domainId: domain.id });
146
+ assert.equal(importedC.status, 201, JSON.stringify(importedC.body));
147
+ const projectC = importedC.body.projectId;
148
+ assert.notEqual(projectA, projectC, 'the decoy lives in a different project of the same domain');
149
+
150
+ // The current project owns memory-system knowledge; the neighbour owns the
151
+ // two decoys from the original complaint plus a boundary-bigram trap.
152
+ fs.mkdirSync(path.join(knowledgeA, 'modules'), { recursive: true });
153
+ fs.mkdirSync(path.join(knowledgeA, 'changes'), { recursive: true });
154
+ fs.writeFileSync(path.join(knowledgeA, 'README.md'), '# 记忆系统项目说明\n\n导出需要 schemaRevision 37。KB-INDEX-SECRET-A 导出契约正文。\n');
155
+ fs.writeFileSync(path.join(knowledgeA, 'modules', 'context.md'), '# 记忆注入机制\n\n会话首条消息注入一次索引,正文经 MCP 按需读取。KB-INDEX-SECRET-B 记忆注入机制正文。\n');
156
+ fs.writeFileSync(path.join(knowledgeA, 'changes', 'change.md'), '# 最近一次注入改造\n\n已完成会话索引改造。KB-INDEX-SECRET-C\n');
157
+ fs.mkdirSync(path.join(knowledgeC, 'modules'), { recursive: true });
158
+ fs.mkdirSync(path.join(knowledgeC, 'changes'), { recursive: true });
159
+ fs.writeFileSync(path.join(knowledgeC, 'modules', 'rpc.md'), '# RpcTransportSDK lane 轮转规则\n\n恢复导出配置的九步流程与并发调度。KB-INDEX-SECRET-D\n');
160
+ fs.writeFileSync(path.join(knowledgeC, 'changes', 'extrapolation.md'), '# 外推算法九步流程\n\n外推算法按九步执行并记录证据。KB-INDEX-SECRET-E\n');
161
+
162
+ // 1. The first turn injects the index once: statement block, no body text.
163
+ const first = await context('开始设计记忆系统的注入机制', 'sess-main');
164
+ assert.equal(first.status, 'ready'); assert.equal(first.injectionKind, 'index');
165
+ assert.equal(first.rankingVersion, 'project-knowledge/ranking-v3');
166
+ assert.ok(first.facts.some(item => item.entryId === 'modules/context.md' && item.role === '本项目事实'), 'the index lists the memory-system module');
167
+ assert.ok(first.facts.every(item => !('text' in item)), 'index facts never carry body text');
168
+ assert.ok(first.prompt.includes('modules/context.md'));
169
+ assert.equal((first.prompt.match(/当前生效的已确认记忆只来自 memories/g) || []).length, 1);
170
+ assert.ok(first.prompt.length <= 3000, `index stays compact, got ${first.prompt.length}`);
171
+ assert.ok(first.sessionIndexedCount >= 2, 'the session registry counts its titles');
172
+ for (const secret of ['KB-INDEX-SECRET-A', 'KB-INDEX-SECRET-B', 'KB-INDEX-SECRET-C', 'KB-INDEX-SECRET-D', 'KB-INDEX-SECRET-E']) {
173
+ assert.ok(!first.prompt.includes(secret), 'no knowledge body ever enters the injection layer');
174
+ }
175
+
176
+ // 2. A later turn without changes or strong matches is fully silent. With
177
+ // the vector fixture offline the turn reports file-fallback (a
178
+ // user-facing notice), which must still inject nothing.
179
+ const quiet = await context('顺便聊聊天气', 'sess-main');
180
+ assert.ok(quiet.status !== 'ready', 'nothing was injected');
181
+ assert.equal(quiet.prompt, '');
182
+ assert.equal(quiet.injectionKind, undefined); assert.equal(quiet.facts.length, 0);
183
+
184
+ // 3. Boundary-bigram decoys stay silent even though search admits them.
185
+ const decoyQuery = '修复导入功能的报错';
186
+ const admitted = await api('POST', '/api/knowledge/search', { projectId: projectA, query: decoyQuery, scope: 'domain' });
187
+ assert.equal(admitted.status, 200, JSON.stringify(admitted.body));
188
+ assert.ok((admitted.body.results || []).some(row => row.path === 'modules/rpc.md'), 'the lexical channel still admits the decoy entry');
189
+ const decoyTurn = await context(decoyQuery, 'sess-main');
190
+ assert.equal(decoyTurn.prompt, '', 'a boundary-bigram collision never becomes a breadcrumb');
191
+
192
+ // 4. A real word match earns a one-line breadcrumb, then cools down.
193
+ const strongQuery = '记忆注入机制是怎么设计的';
194
+ const crumb = await context(strongQuery, 'sess-main');
195
+ assert.equal(crumb.injectionKind, 'breadcrumb');
196
+ assert.ok(crumb.facts.some(item => item.entryId === 'modules/context.md'), 'the breadcrumb points at the matching entry');
197
+ assert.ok(!crumb.facts.some(item => String(item.entryId).includes('rpc') || String(item.entryId).includes('extrapolation')), 'the decoys never appear');
198
+ assert.ok(crumb.prompt.includes('modules/context.md')); assert.ok(!crumb.prompt.includes('KB-INDEX-SECRET-B'));
199
+ assert.ok(!crumb.prompt.includes('当前生效的已确认记忆只来自'), 'deltas never repeat the statement block');
200
+ assert.equal((await context(strongQuery, 'sess-main')).prompt, '', 'the same entry is on cooldown');
201
+
202
+ // 5. A memory added mid-session is re-sent in full exactly once.
203
+ const brainScope = (await engineApi('GET', '/api/snapshot?summary=1&limit=1')).body.sharedScopes.find(scope => scope.kind === 'brain');
204
+ assert.ok(brainScope, 'the brain scope exists');
205
+ const created = await engineApi('POST', '/api/memories', { text: '本仓库必须保持中文提交信息', scopeType: 'project', scopeId: projectA, brainId: brainScope.brainId });
206
+ assert.equal(created.status, 200, JSON.stringify(created.body));
207
+ const memoryId = created.body.memory.id;
208
+ const memoryTurn = await context('继续做别的', 'sess-main');
209
+ assert.equal(memoryTurn.injectionKind, 'memory-delta'); assert.equal(memoryTurn.memories.length, 1);
210
+ assert.equal(memoryTurn.memories[0].memoryId, memoryId);
211
+ assert.ok(memoryTurn.prompt.includes('本仓库必须保持中文提交信息'));
212
+ assert.equal((await context('继续做别的', 'sess-main')).prompt, '', 'an unchanged memory never repeats');
213
+ const deleted = await engineApi('DELETE', `/api/memories/${encodeURIComponent(memoryId)}`);
214
+ assert.equal(deleted.status, 200, JSON.stringify(deleted.body));
215
+ const removalTurn = await context('继续做别的', 'sess-main');
216
+ assert.ok(removalTurn.prompt.includes('记忆已移除'), 'a deletion is announced instead of silently vanishing');
217
+ assert.equal((await context('继续做别的', 'sess-main')).prompt, '', 'the removal notice fires once');
218
+
219
+ // 6. Thirty simulated turns stay an order of magnitude below the old
220
+ // per-turn 8000-char design (which accumulated ~90KB+ over 30 turns).
221
+ let cumulative = 0;
222
+ for (let turn = 1; turn <= 30; turn++) {
223
+ const query = turn === 1 ? '开始设计记忆系统的注入机制'
224
+ : turn % 5 === 0 ? '记忆注入机制还有哪些细节'
225
+ : turn % 7 === 0 ? '修复导入功能的报错'
226
+ : `随便记录一下第${turn}轮的进展`;
227
+ const result = await context(query, 'sess-30');
228
+ cumulative += (result.prompt || '').length;
229
+ assert.ok((result.prompt || '').length <= 8000, 'the hard contract never breaks');
230
+ assert.ok(!(result.prompt || '').includes('KB-INDEX-SECRET-'), 'no turn ever leaks a body');
231
+ }
232
+ assert.ok(cumulative <= 10240, `30 turns inject at most 10KB in total, got ${cumulative}`);
233
+
234
+ console.log('context-session-index-test PASS (one index per session, silent turns, gated breadcrumbs, once-only memory deltas, 30-turn cumulative injection bounded)');
235
+ } finally {
236
+ await server.cleanup();
237
+ await engine.close().catch(() => {});
238
+ await engineProxy.close();
239
+ for (const fixtureService of [terminal, vectorHub, eventBridge]) await fixtureService.close();
240
+ fs.rmSync(fixture, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
241
+ }
242
+ }
243
+
244
+ main().catch(error => { console.error(error.stack || error.message); process.exitCode = 1; });
@@ -1,5 +1,9 @@
1
1
  [
2
2
  {"id":"S01","kind":"semantic","project":"product","query":"默认监听地址被别的程序占用后,模块如何避让并确认服务身份?","entry":"changes/c4afa63fa1ca.md","fact":"dynamic"},
3
+ {"id":"B01","kind":"breadcrumb","project":"product","query":"默认监听地址被别的程序占用后,模块如何避让并确认服务身份?","expect":"changes/c4afa63fa1ca.md"},
4
+ {"id":"B02","kind":"breadcrumb","project":"workbench","query":"相同项目的嵌入消息反复到达,为何不应作废正在创建的会话?","expect":"changes/29e2cf932e08.md"},
5
+ {"id":"B03","kind":"breadcrumb","project":"product","query":"当前项目 PostgreSQL 主从故障切换与 WAL 归档策略是什么?"},
6
+ {"id":"B04","kind":"breadcrumb","project":"workbench","query":"当前项目 ElasticSearch 搜索集群如何备份?"},
3
7
  {"id":"S02","kind":"semantic","project":"product","query":"桌面窗口怎样复用网页后台并在退出时处理自己启动的进程?","entry":"changes/6ea83d5c4e59.md","fact":"后台"},
4
8
  {"id":"S03","kind":"semantic","project":"product","query":"客户端检测尚未结束时,为什么不能记录用户已移除接入?","entry":"changes/155e3bf3bb5f.md","fact":"扫描"},
5
9
  {"id":"S04","kind":"semantic","project":"product","query":"外部开发工具的接入开关怎样记住用户选择并在启动时修复?","entry":"changes/b2da6dd5d6fd.md","fact":"意图"},
@@ -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 || '{}') });