@sanqianx/project-knowledge 5.0.32 → 5.0.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +6 -0
- package/_site/_test/automatic-context-test.js +19 -0
- package/_site/_test/context-session-index-test.js +244 -0
- package/_site/_test/fixtures/retrieval-gold-queries.json +4 -0
- package/_site/scripts/ab-rank-v2-v3.js +142 -0
- package/_site/scripts/run-retrieval-gold-isolated.js +221 -0
- package/_site/scripts/verify-retrieval-gold.js +57 -10
- package/module-runtime-manifest.json +12 -12
- package/package.json +2 -2
- package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
- package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
- package/plugins/project-knowledge/.mcp.json +1 -1
- package/plugins/project-knowledge/scripts/context-hook.cjs +9 -5
- package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +39 -28
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [5.0.33] - 2026-11-11
|
|
4
|
+
|
|
5
|
+
- 知识注入改为会话一次索引(对齐 ZCode memory 的"索引+懒加载"模式):会话首条用户消息注入一次紧凑索引(适用已确认记忆全文 + 知识条目标题清单 + 仲裁声明),正文摘录不再进入注入层;后续消息默认静默,新增/变更的记忆全文重注入一次,删除的记忆发一行移除提示,相关问题对强命中条目(实词/身份/已校准向量命中,仅 bigram 撞词不触发)给一行面包屑并在 10 轮内冷却,超过 30 轮重发仅标题索引对冲上下文压缩。30 轮会话累计注入从旧设计的 ~90KB+ 降至 ≤10KB。
|
|
6
|
+
- 引擎升级至 `@sanqianx/ai-coding-knowledge-engine@0.2.8`(ranking-v3:词锚/字节对锚分离、listTitles、注入预算进 retrieval-policy);`context-hook` 空结果完全静默、降级提示只走 systemMessage,receipt 日志新增 `injectionKind`/`sessionIndexedCount`;响应契约向后兼容(status 枚举与必选字段不变)。
|
|
7
|
+
- 检索质量金标准新增 breadcrumb-gating 用例(正例强匹配出面包屑并冷却、负例零注入)与隔离运行器 `run-retrieval-gold-isolated.js`(自起真实 vector-hub 与引擎、语料只读副本、独立 VECTOR_HUB_CONFIG 防止继承用户全局 watcher);新增 `context-session-index-test.js` 端到端回归(跨项目诱饵零面包屑、30 轮累计注入量化断言)。
|
|
8
|
+
|
|
3
9
|
## [5.0.32] - 2026-11-10
|
|
4
10
|
|
|
5
11
|
- 将 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 }), {});
|
|
@@ -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":"意图"},
|
|
@@ -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,221 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Isolated runner for the retrieval gold gate. Spins its own vector-hub (real
|
|
3
|
+
// remote embeddings via MINIMAX_API_KEY) and the real knowledge engine from
|
|
4
|
+
// node_modules, copies the three corpus project knowledge directories into a
|
|
5
|
+
// throwaway fixture (the source knowledge roots are only ever read), indexes
|
|
6
|
+
// them, then runs verify-retrieval-gold.js against the engine.
|
|
7
|
+
//
|
|
8
|
+
// Nothing here touches the running product instance: the corpus source roots
|
|
9
|
+
// are read-only inputs, all servers use fresh data directories and free ports,
|
|
10
|
+
// and the driver isolation helper rebuilds the environment before any product
|
|
11
|
+
// module is required.
|
|
12
|
+
//
|
|
13
|
+
// Usage:
|
|
14
|
+
// node _site/scripts/run-retrieval-gold-isolated.js <reportPath>
|
|
15
|
+
// Env:
|
|
16
|
+
// MINIMAX_API_KEY (or PKB_GOLD_MINIMAX_API_KEY) required - embedding API key
|
|
17
|
+
// PKB_GOLD_CORPUS_PRODUCT / _WORKBENCH / _ENGINE optional corpus overrides
|
|
18
|
+
// PKB_GOLD_INDEX_TIMEOUT_MS default 20 min
|
|
19
|
+
|
|
20
|
+
const fs = require('node:fs');
|
|
21
|
+
const os = require('node:os');
|
|
22
|
+
const path = require('node:path');
|
|
23
|
+
const crypto = require('node:crypto');
|
|
24
|
+
const { spawn } = require('node:child_process');
|
|
25
|
+
const http = require('node:http');
|
|
26
|
+
// Remote embedding of a full corpus keeps the import response open far past
|
|
27
|
+
// undici's default 5-minute headers timeout; plain http has no such default.
|
|
28
|
+
const postJson = (baseUrl, route, body, timeoutMs) => new Promise((resolve, reject) => {
|
|
29
|
+
const target = new URL(baseUrl);
|
|
30
|
+
const payload = Buffer.from(JSON.stringify(body));
|
|
31
|
+
const request = http.request({ hostname: target.hostname, port: target.port, path: route, method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': payload.length } }, response => {
|
|
32
|
+
let text = '';
|
|
33
|
+
response.on('data', chunk => { text += chunk; });
|
|
34
|
+
response.on('end', () => {
|
|
35
|
+
if (response.statusCode < 200 || response.statusCode >= 300) return reject(new Error(`POST ${route} -> ${response.statusCode}: ${text.slice(0, 300)}`));
|
|
36
|
+
try { resolve(JSON.parse(text)); } catch (error) { reject(error); }
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
request.setTimeout(timeoutMs, () => request.destroy(new Error(`POST ${route} timed out after ${timeoutMs}ms`)));
|
|
40
|
+
request.on('error', reject);
|
|
41
|
+
request.end(payload);
|
|
42
|
+
});
|
|
43
|
+
const { applyDriverIsolation } = require('../_test/helpers/parallel-qa-engine-endpoint-isolate');
|
|
44
|
+
const { guardedCreateEngineServer } = require('../_test/helpers/parallel-qa-engine-endpoint-guard');
|
|
45
|
+
const { createUpstreamProxy, createModuleFixture } = require('../_test/helpers/module-fixture');
|
|
46
|
+
const freePort = require('../_test/helpers/free-port');
|
|
47
|
+
const { verify } = require('./verify-retrieval-gold');
|
|
48
|
+
|
|
49
|
+
const ROOT = path.resolve(__dirname, '../..');
|
|
50
|
+
const DEFAULT_CORPUS = {
|
|
51
|
+
product: 'D:\\SanQian.Xu\\knowledge\\project-knowledge-base-f8eb65',
|
|
52
|
+
workbench: 'D:\\SanQian.Xu\\knowledge\\claude-ai-workbench-a40cb2',
|
|
53
|
+
engine: 'D:\\SanQian.Xu\\knowledge\\knowledge-engine-8ce6c0',
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
async function waitFor(url, check, label, timeoutMs = 20000) {
|
|
57
|
+
const deadline = Date.now() + timeoutMs;
|
|
58
|
+
while (Date.now() < deadline) {
|
|
59
|
+
try {
|
|
60
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(2000) });
|
|
61
|
+
if (response.ok && (await check(response))) return;
|
|
62
|
+
} catch {}
|
|
63
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
64
|
+
}
|
|
65
|
+
throw new Error('Timed out waiting for ' + label);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function main() {
|
|
69
|
+
const reportPath = path.resolve(process.argv[2] || 'retrieval-gold-report.json');
|
|
70
|
+
const apiKey = process.env.PKB_GOLD_MINIMAX_API_KEY || process.env.MINIMAX_API_KEY;
|
|
71
|
+
if (!apiKey) throw new Error('Set MINIMAX_API_KEY (embedding key) before running the gold gate.');
|
|
72
|
+
const corpus = {
|
|
73
|
+
product: process.env.PKB_GOLD_CORPUS_PRODUCT || DEFAULT_CORPUS.product,
|
|
74
|
+
workbench: process.env.PKB_GOLD_CORPUS_WORKBENCH || DEFAULT_CORPUS.workbench,
|
|
75
|
+
engine: process.env.PKB_GOLD_CORPUS_ENGINE || DEFAULT_CORPUS.engine,
|
|
76
|
+
};
|
|
77
|
+
for (const [name, source] of Object.entries(corpus)) if (!fs.existsSync(source)) throw new Error(`Corpus directory for "${name}" is missing: ${source}`);
|
|
78
|
+
|
|
79
|
+
const applied = applyDriverIsolation({ prefix: 'pk-qa-gold' });
|
|
80
|
+
const fixture = fs.mkdtempSync(path.join(applied.layout.temp, 'pk-gold-'));
|
|
81
|
+
const corpusRoot = path.join(fixture, 'corpus');
|
|
82
|
+
fs.mkdirSync(corpusRoot, { recursive: true });
|
|
83
|
+
// The gold queries are calibrated against the corpus state of their last
|
|
84
|
+
// evidenced run (2026-10-23). Later knowledge entries ABOUT the gate itself
|
|
85
|
+
// quote the queries and their expectations verbatim, so including them makes
|
|
86
|
+
// a PostgreSQL "unsupported" question match the entry documenting that very
|
|
87
|
+
// gate. Snapshot the corpus with a mtime cutoff instead of copying it live.
|
|
88
|
+
const cutoffEnv = process.env.PKB_GOLD_CORPUS_CUTOFF;
|
|
89
|
+
const cutoff = cutoffEnv ? Date.parse(cutoffEnv) : Date.parse('2026-10-24T00:00:00+08:00');
|
|
90
|
+
if (!Number.isFinite(cutoff)) throw new Error(`PKB_GOLD_CORPUS_CUTOFF is not a valid date: ${cutoffEnv}`);
|
|
91
|
+
const copySnapshot = (from, to) => {
|
|
92
|
+
fs.mkdirSync(to, { recursive: true });
|
|
93
|
+
for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
|
|
94
|
+
const sourceFile = path.join(from, entry.name), targetFile = path.join(to, entry.name);
|
|
95
|
+
if (entry.isDirectory()) copySnapshot(sourceFile, targetFile);
|
|
96
|
+
else if (entry.isFile() && fs.statSync(sourceFile).mtimeMs < cutoff) fs.copyFileSync(sourceFile, targetFile);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
const projects = {};
|
|
100
|
+
for (const [name, source] of Object.entries(corpus)) {
|
|
101
|
+
const target = path.join(corpusRoot, name);
|
|
102
|
+
copySnapshot(source, target);
|
|
103
|
+
const repo = path.join(fixture, 'repos', name);
|
|
104
|
+
fs.mkdirSync(repo, { recursive: true });
|
|
105
|
+
const projectId = `gold-${name}-${crypto.randomBytes(3).toString('hex')}`;
|
|
106
|
+
projects[name] = { projectId, knowledgePath: target, repoPath: repo, files: fs.readdirSync(target).length };
|
|
107
|
+
}
|
|
108
|
+
console.log('corpus snapshot cutoff:', new Date(cutoff).toISOString(), '| files:', Object.fromEntries(Object.entries(projects).map(([name, p]) => [name, p.files])));
|
|
109
|
+
const shared = path.join(corpusRoot, '_shared');
|
|
110
|
+
fs.mkdirSync(path.join(shared, 'brain'), { recursive: true }); fs.mkdirSync(path.join(shared, 'domain'), { recursive: true });
|
|
111
|
+
|
|
112
|
+
const vectorPort = await freePort();
|
|
113
|
+
const vectorUrl = `http://127.0.0.1:${vectorPort}`;
|
|
114
|
+
// A fresh VECTOR_HUB_CONFIG is isolation-critical: the default is the user's
|
|
115
|
+
// global ~/.vector-hub/config.json, whose project watchers point at the LIVE
|
|
116
|
+
// knowledge directories - an isolated gate instance must never resume them.
|
|
117
|
+
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')], {
|
|
118
|
+
env: { ...process.env, MINIMAX_API_KEY: apiKey, VECTOR_HUB_ROOT: path.join(fixture, 'vector'), VECTOR_HUB_CONFIG: path.join(fixture, 'vector-config.json') },
|
|
119
|
+
stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
|
|
120
|
+
});
|
|
121
|
+
vector.stdout.on('data', chunk => process.stdout.write('[vector] ' + chunk));
|
|
122
|
+
vector.stderr.on('data', chunk => process.stderr.write('[vector] ' + chunk));
|
|
123
|
+
|
|
124
|
+
const engineToken = crypto.randomBytes(24).toString('hex');
|
|
125
|
+
const bridge = createModuleFixture({ kind: 'eventBridge' });
|
|
126
|
+
await bridge.start(); bridge.setOnline(false);
|
|
127
|
+
const engine = guardedCreateEngineServer({ dataDir: path.join(fixture, 'engine'), runtimeToken: engineToken, debug: true, consume: false, vectorUrl, bridgeUrl: bridge.url });
|
|
128
|
+
await engine.ready;
|
|
129
|
+
await new Promise(resolve => engine.server.listen(0, '127.0.0.1', resolve));
|
|
130
|
+
const engineUrl = `http://127.0.0.1:${engine.server.address().port}`;
|
|
131
|
+
const proxy = createUpstreamProxy({ target: engineUrl, token: engineToken, tag: 'gold-engine' });
|
|
132
|
+
await proxy.start();
|
|
133
|
+
|
|
134
|
+
const engineApi = async (method, route, body) => {
|
|
135
|
+
// Registration routes are shell-only: the runtime token authorizes this
|
|
136
|
+
// harness exactly like the product shell (same loopback + timing-safe
|
|
137
|
+
// Bearer check the engine enforces).
|
|
138
|
+
const headers = { Authorization: `Bearer ${engineToken}` };
|
|
139
|
+
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
140
|
+
const response = await fetch(engineUrl + route, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(30000) });
|
|
141
|
+
const payload = await response.json().catch(() => ({}));
|
|
142
|
+
if (!response.ok) throw new Error(`${method} ${route} -> ${response.status}: ${JSON.stringify(payload).slice(0, 300)}`);
|
|
143
|
+
return payload;
|
|
144
|
+
};
|
|
145
|
+
try {
|
|
146
|
+
await waitFor(`${vectorUrl}/api/health`, async () => true, 'vector-hub health');
|
|
147
|
+
const initialProjects = await (await fetch(`${vectorUrl}/api/projects`)).json();
|
|
148
|
+
if ((initialProjects.projects || []).length) throw new Error(`isolated vector-hub must start empty, found: ${(initialProjects.projects || []).map(p => p.name).join(', ')}`);
|
|
149
|
+
const brainId = 'brain-gold', domainId = 'domain-gold';
|
|
150
|
+
await engineApi('POST', '/api/scopes', { scopes: [
|
|
151
|
+
{ id: brainId, kind: 'brain', brainId, name: 'Gold Brain', knowledgePath: path.join(shared, 'brain') },
|
|
152
|
+
{ id: domainId, kind: 'domain', brainId, domainId, name: 'Gold Domain', knowledgePath: path.join(shared, 'domain') },
|
|
153
|
+
] });
|
|
154
|
+
for (const project of Object.values(projects)) {
|
|
155
|
+
await engineApi('POST', '/api/projects', { projectId: project.projectId, repoPath: project.repoPath, knowledgePath: project.knowledgePath, domainId });
|
|
156
|
+
// The remote embedding API rate-limits full-corpus imports (RPM). The
|
|
157
|
+
// import is incremental per file hash, so retrying after a cool-down
|
|
158
|
+
// only embeds what the previous attempt did not reach.
|
|
159
|
+
let imported = null;
|
|
160
|
+
for (let attempt = 1; attempt <= 20; attempt++) {
|
|
161
|
+
try { imported = await postJson(vectorUrl, '/api/import', { projectName: project.projectId, sourceDir: project.knowledgePath, watch: false }, 30 * 60 * 1000); break; }
|
|
162
|
+
catch (error) {
|
|
163
|
+
if (attempt === 20 || !/rate limit|429|1002/i.test(String(error.message))) throw error;
|
|
164
|
+
console.log(`rate-limited on ${project.projectId} (attempt ${attempt}); cooling down 75s`);
|
|
165
|
+
await new Promise(resolve => setTimeout(resolve, 75 * 1000));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
console.log(`indexed-import accepted: ${project.projectId}`, JSON.stringify(imported).slice(0, 120));
|
|
169
|
+
}
|
|
170
|
+
const indexTimeout = Number(process.env.PKB_GOLD_INDEX_TIMEOUT_MS || 20 * 60 * 1000);
|
|
171
|
+
await waitFor(`${vectorUrl}/api/projects`, async response => {
|
|
172
|
+
const payload = await response.clone().json();
|
|
173
|
+
return Object.values(projects).every(project => payload.projects?.some(p => p.name === project.projectId && p.hasIndex));
|
|
174
|
+
}, 'all three corpus indexes', indexTimeout);
|
|
175
|
+
// Rate-limited incremental imports can leave a file tracked but not fully
|
|
176
|
+
// embedded. Every gold target must answer a probe built from its own
|
|
177
|
+
// distinctive text before the cases run; re-import until they all do.
|
|
178
|
+
const queries = JSON.parse(fs.readFileSync(path.join(ROOT, '_site/_test/fixtures/retrieval-gold-queries.json'), 'utf8'));
|
|
179
|
+
const targets = queries.filter(q => q.entry).map(q => ({ id: q.id, project: q.project, entry: q.entry }));
|
|
180
|
+
const needle = file => fs.readFileSync(file, 'utf8').split(/\r?\n/).map(line => line.trim()).filter(line => line.length >= 12 && !line.startsWith('#')).sort((a, b) => b.length - a.length)[0];
|
|
181
|
+
const probeTarget = async target => {
|
|
182
|
+
const file = path.join(projects[target.project].knowledgePath, target.entry);
|
|
183
|
+
if (!fs.existsSync(file)) return 'file-missing-in-snapshot';
|
|
184
|
+
const phrase = needle(file);
|
|
185
|
+
if (!phrase) return 'no-distinctive-line';
|
|
186
|
+
const probe = await fetch(`${vectorUrl}/api/search?q=${encodeURIComponent(phrase)}&projects=${projects[target.project].projectId}&maxResults=5&resultLevel=chunk`, { signal: AbortSignal.timeout(30000) });
|
|
187
|
+
const payload = await probe.json();
|
|
188
|
+
return (payload.results || []).some(row => String(row.uri || row.documentUri || '').replace(/\\/g, '/').endsWith(target.entry)) ? null : 'not-in-vector-top5';
|
|
189
|
+
};
|
|
190
|
+
let missing = [];
|
|
191
|
+
for (let round = 1; round <= 10; round++) {
|
|
192
|
+
missing = [];
|
|
193
|
+
for (const target of targets) { const verdict = await probeTarget(target); if (verdict) missing.push({ ...target, verdict }); }
|
|
194
|
+
if (!missing.length) break;
|
|
195
|
+
console.log('vector completeness round', round, '- missing:', missing.map(m => `${m.id}(${m.verdict})`).join(','));
|
|
196
|
+
if (missing.some(m => m.verdict === 'file-missing-in-snapshot')) throw new Error('a gold target file is absent from the corpus snapshot: ' + JSON.stringify(missing));
|
|
197
|
+
for (const project of Object.values(projects)) await postJson(vectorUrl, '/api/import', { projectName: project.projectId, sourceDir: project.knowledgePath, watch: false }, 30 * 60 * 1000);
|
|
198
|
+
}
|
|
199
|
+
if (missing.length) throw new Error('vector index incomplete after re-imports: ' + JSON.stringify(missing));
|
|
200
|
+
console.log('corpus indexed and all gold targets probe clean; running the gold cases');
|
|
201
|
+
|
|
202
|
+
const report = await verify({
|
|
203
|
+
url: proxy.url,
|
|
204
|
+
basePath: '/api',
|
|
205
|
+
recallAt: Number(process.env.PKB_GOLD_RECALL_AT || 15),
|
|
206
|
+
projects: Object.fromEntries(Object.entries(projects).map(([name, project]) => [name, { projectId: project.projectId, knowledgePath: project.knowledgePath }])),
|
|
207
|
+
fixtureRoot: corpusRoot,
|
|
208
|
+
queries,
|
|
209
|
+
reportPath,
|
|
210
|
+
});
|
|
211
|
+
process.exitCode = report.passed ? 0 : 1;
|
|
212
|
+
} finally {
|
|
213
|
+
vector.kill();
|
|
214
|
+
await engine.close().catch(() => {});
|
|
215
|
+
await proxy.close();
|
|
216
|
+
await bridge.close();
|
|
217
|
+
fs.rmSync(fixture, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
main().catch(error => { console.error(error.stack || error.message); if (error.cause) console.error('cause:', String(error.cause).slice(0, 400)); process.exitCode = 1; });
|
|
@@ -3,10 +3,10 @@ const fs = require('node:fs');
|
|
|
3
3
|
const path = require('node:path');
|
|
4
4
|
const crypto = require('node:crypto');
|
|
5
5
|
|
|
6
|
-
async function verify({ url, projects, fixtureRoot, queries, reportPath }) {
|
|
6
|
+
async function verify({ url, projects, fixtureRoot, queries, reportPath, basePath = '/api/engine', recallAt = 15 }) {
|
|
7
7
|
const root = path.resolve(fixtureRoot);
|
|
8
8
|
const inside = file => { const relative = path.relative(root, path.resolve(file)); return relative && !relative.startsWith('..') && !path.isAbsolute(relative); };
|
|
9
|
-
const report = { passed: false, source: 'real engine and configured remote embeddings', startedAt: new Date().toISOString(), cases: [], metrics: {} };
|
|
9
|
+
const report = { passed: false, source: 'real engine and configured remote embeddings', startedAt: new Date().toISOString(), recallAt, cases: [], metrics: {} };
|
|
10
10
|
const save = () => fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
|
|
11
11
|
let semanticHits = 0, vectorCases = 0, checkedCitations = 0, badCitations = 0, scopeLeaks = 0, deepReads = 0, snippetFactHits = 0;
|
|
12
12
|
for (const q of queries) {
|
|
@@ -22,8 +22,8 @@ async function verify({ url, projects, fixtureRoot, queries, reportPath }) {
|
|
|
22
22
|
if (fs.existsSync(hidden)) throw new Error('prior interrupted stale test needs recovery');
|
|
23
23
|
fs.renameSync(target, hidden);
|
|
24
24
|
}
|
|
25
|
-
const response = await fetch(new URL('/
|
|
26
|
-
body: JSON.stringify({ projectId: project.projectId, scope: 'project', query: q.query, limit: 5 }), signal: AbortSignal.timeout(20000) });
|
|
25
|
+
const response = await fetch(new URL(basePath + '/search', url), { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
26
|
+
body: JSON.stringify({ projectId: project.projectId, scope: 'project', query: q.query, limit: Math.max(5, recallAt) }), signal: AbortSignal.timeout(20000) });
|
|
27
27
|
const result = await response.json();
|
|
28
28
|
if (!response.ok) throw new Error(`search failed with HTTP ${response.status}`);
|
|
29
29
|
const rows = result.results || [];
|
|
@@ -42,13 +42,54 @@ async function verify({ url, projects, fixtureRoot, queries, reportPath }) {
|
|
|
42
42
|
if (!snippet.trim() || !body.includes(snippet) || hash !== row.content_hash) citationErrors++;
|
|
43
43
|
}
|
|
44
44
|
badCitations += citationErrors; scopeLeaks += leaks;
|
|
45
|
-
const documentHit = rows.some(row => row.entry_id === q.entry);
|
|
45
|
+
const documentHit = rows.slice(0, recallAt).some(row => row.entry_id === q.entry);
|
|
46
|
+
const documentRank = q.entry ? rows.findIndex(row => row.entry_id === q.entry) + 1 : null;
|
|
47
|
+
if (q.kind === 'breadcrumb') {
|
|
48
|
+
// The session-injection gate: same engine, same corpus, real channels.
|
|
49
|
+
// Positive cases assert BEHAVIOUR (a strong query earns one-line
|
|
50
|
+
// pointers with no body text, and an immediate repeat cools down);
|
|
51
|
+
// which specific entry tops the ranking is the search gate's job, not
|
|
52
|
+
// this one. Negative cases must stay completely silent.
|
|
53
|
+
const sessionId = `gold-${q.id}`;
|
|
54
|
+
const contextCall = async query => {
|
|
55
|
+
// scope: 'project' keeps the injection gate on the same corpus the
|
|
56
|
+
// search gate uses; the domain default would let a sibling project's
|
|
57
|
+
// entry about the very technology being asked about answer an
|
|
58
|
+
// "unsupported topic" question.
|
|
59
|
+
const response = await fetch(new URL(basePath + '/context', url), { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
60
|
+
body: JSON.stringify({ projectId: project.projectId, query, client: 'gold', sessionId, scope: 'project' }), signal: AbortSignal.timeout(20000) });
|
|
61
|
+
const result = await response.json();
|
|
62
|
+
if (!response.ok || result.ok !== true) throw new Error(`context failed with HTTP ${response.status}`);
|
|
63
|
+
return result;
|
|
64
|
+
};
|
|
65
|
+
await contextCall(q.query);
|
|
66
|
+
const turn = await contextCall(q.query);
|
|
67
|
+
const entries = (turn.facts || []).map(item => item.entryId);
|
|
68
|
+
item.injectionKind = turn.injectionKind || null; item.injectedEntries = entries;
|
|
69
|
+
const bodyLeak = (turn.facts || []).some(item => typeof item.text === 'string' && item.text.length > 0);
|
|
70
|
+
if (q.expect) {
|
|
71
|
+
item.passed = turn.injectionKind === 'breadcrumb' && entries.length > 0 && entries.length <= 3 && !bodyLeak;
|
|
72
|
+
// Cooldown is per ENTRY (10 turns): an immediate repeat may surface
|
|
73
|
+
// the next strong entries, but the ones just sent must not repeat.
|
|
74
|
+
const repeat = await contextCall(q.query);
|
|
75
|
+
const repeatEntries = (repeat.facts || []).map(entry => entry.entryId);
|
|
76
|
+
item.cooldownRespected = entries.every(entry => !repeatEntries.includes(entry));
|
|
77
|
+
item.passed = item.passed && item.cooldownRespected;
|
|
78
|
+
item.expectedEntryWithinInjected = entries.includes(q.expect);
|
|
79
|
+
} else {
|
|
80
|
+
item.passed = !turn.prompt && entries.length === 0 && !turn.injectionKind;
|
|
81
|
+
}
|
|
82
|
+
item.bodyLeak = bodyLeak;
|
|
83
|
+
report.cases.push(item); save();
|
|
84
|
+
console.log(`${item.passed ? 'PASS' : 'FAIL'} ${q.id} ${q.kind}`);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
46
87
|
const snippetFactHit = rows.some(row => row.entry_id === q.entry && (!q.fact || String(row.chunk_text).toLowerCase().includes(q.fact.toLowerCase())));
|
|
47
88
|
let factRetrieved = snippetFactHit;
|
|
48
89
|
if (q.fact && documentHit && !snippetFactHit) {
|
|
49
90
|
// Search locates documents; an agent may then get the selected entry.
|
|
50
91
|
// Record this separately rather than claiming a snippet contained it.
|
|
51
|
-
const detail = await fetch(new URL('/
|
|
92
|
+
const detail = await fetch(new URL(basePath + '/get', url), { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
52
93
|
body: JSON.stringify({ projectId: project.projectId, entryId: q.entry, scope: 'project' }), signal: AbortSignal.timeout(10000) });
|
|
53
94
|
const full = await detail.json();
|
|
54
95
|
const text = full.chunks?.map(chunk => chunk.chunk_text).join('\n') || '';
|
|
@@ -57,10 +98,15 @@ async function verify({ url, projects, fixtureRoot, queries, reportPath }) {
|
|
|
57
98
|
item.followupRead = { entry: q.entry, passed: factRetrieved, sha256: crypto.createHash('sha256').update(text).digest('hex') };
|
|
58
99
|
deepReads++;
|
|
59
100
|
}
|
|
60
|
-
item.documentHit = documentHit; item.snippetFactHit = snippetFactHit;
|
|
101
|
+
item.documentHit = documentHit; item.documentRank = documentRank; item.snippetFactHit = snippetFactHit;
|
|
61
102
|
const vector = rows.some(row => row.match_channels?.includes('index:vector-hub')) && result.health?.vectorMode === 'verified-chunks';
|
|
62
103
|
if (q.kind === 'semantic') { if (documentHit) semanticHits++; if (vector) vectorCases++; if (snippetFactHit) snippetFactHits++; }
|
|
63
|
-
|
|
104
|
+
// Empty-result expectations are enforced for "unsupported topic" cases
|
|
105
|
+
// (named technologies absent from the corpus). For isolation cases the
|
|
106
|
+
// guarantee under test is scope integrity - zero leaks and zero citation
|
|
107
|
+
// errors - not row counts, because unrelated same-scope entries may
|
|
108
|
+
// legitimately match a cross-project question lexically.
|
|
109
|
+
item.passed = !citationErrors && !leaks && (q.empty && q.kind === 'unsupported' ? rows.length === 0
|
|
64
110
|
: q.kind === 'stale' ? rows.every(row => row.entry_id !== q.entry)
|
|
65
111
|
: q.kind === 'isolation' ? true : documentHit && factRetrieved && (q.kind !== 'semantic' || vector));
|
|
66
112
|
item.citationErrors = citationErrors; item.scopeLeaks = leaks;
|
|
@@ -69,8 +115,9 @@ async function verify({ url, projects, fixtureRoot, queries, reportPath }) {
|
|
|
69
115
|
report.cases.push(item); save();
|
|
70
116
|
console.log(`${item.passed ? 'PASS' : 'FAIL'} ${q.id} ${q.kind}`);
|
|
71
117
|
}
|
|
72
|
-
|
|
73
|
-
report.
|
|
118
|
+
const semanticCount = queries.filter(q => q.kind === 'semantic').length;
|
|
119
|
+
report.metrics = { [`semanticRecallAt${recallAt}`]: semanticHits / semanticCount, semanticSnippetFactCoverage: snippetFactHits / 10, followupEntryReads: deepReads, semanticVectorCases: vectorCases, checkedCitations, badCitations, scopeLeaks };
|
|
120
|
+
report.passed = report.cases.every(c => c.passed) && report.metrics[`semanticRecallAt${recallAt}`] >= 0.9 && vectorCases === 10 && !badCitations && !scopeLeaks;
|
|
74
121
|
report.finishedAt = new Date().toISOString(); save();
|
|
75
122
|
return report;
|
|
76
123
|
}
|
|
@@ -9,11 +9,11 @@
|
|
|
9
9
|
"ui/favicon.svg": "c48be946b224112ebb0238b44263f7a61bda31e531afa895c2e9801c0ff24f32",
|
|
10
10
|
"plugins/project-knowledge/hooks/claude.json": "d61510327e3e1facbb4c645228e9f50cad05a88b33d80c4c22e5ba9f8b9f5359",
|
|
11
11
|
"plugins/project-knowledge/hooks/codex.json": "216e03c07295606ef6ebb2c4f669ad0d790b5e7c4f3f34600488033db75e4239",
|
|
12
|
-
"plugins/project-knowledge/scripts/context-hook.cjs": "
|
|
12
|
+
"plugins/project-knowledge/scripts/context-hook.cjs": "ddc1f6f5638c662adbbf4391557bbeb7196af2fb869e7ecfeefba76b9bab5760",
|
|
13
13
|
"plugins/project-knowledge/scripts/mcp-launcher.cjs": "7c68830b5c73eb53ef030756a4de33987f7eab6b1a6cc15602835aac3f954893",
|
|
14
|
-
"plugins/project-knowledge/.claude-plugin/plugin.json": "
|
|
15
|
-
"plugins/project-knowledge/.codex-plugin/plugin.json": "
|
|
16
|
-
"plugins/project-knowledge/.mcp.json": "
|
|
14
|
+
"plugins/project-knowledge/.claude-plugin/plugin.json": "d0f026321ed7abf03d88e2780d61d95defa912a6ed64b55c2408de37e9ad356e",
|
|
15
|
+
"plugins/project-knowledge/.codex-plugin/plugin.json": "0bb11b88f2f39d5aef49e8586e13457a175bf5690713a3427a7665eafa765a0d",
|
|
16
|
+
"plugins/project-knowledge/.mcp.json": "06311aedc5fce8cc6d03a68c1d0a123feb31e02d2a1882a750d7e21caccbccb2",
|
|
17
17
|
"ui/version-info.js": "01a82217b031de54b80d6c7974da9c70888c4c90a046bd4248a808f7989ddce7",
|
|
18
18
|
"ui/version-info.css": "209fad8e42b661f72d2aba3280e1ca47768b5cefb776fe5459538d34fbad120f"
|
|
19
19
|
},
|
|
@@ -267,28 +267,28 @@
|
|
|
267
267
|
"engine": {
|
|
268
268
|
"name": "@sanqianx/ai-coding-knowledge-engine",
|
|
269
269
|
"installName": "@sanqianx/ai-coding-knowledge-engine",
|
|
270
|
-
"version": "0.2.
|
|
270
|
+
"version": "0.2.8",
|
|
271
271
|
"files": {
|
|
272
272
|
"LICENSE": "c1b9df1275e769f3dbab000d1e457a2d4b0f28eb5da6c77e48dc37eeba202ed7",
|
|
273
273
|
"README.md": "4d99cf4b19a4b07533dc86bb63015255364016fad76c1306bea69db0a9ff8743",
|
|
274
|
-
"package.json": "
|
|
274
|
+
"package.json": "ae0178fbf2a7b5da8d4181380e36f98b56b32337f4f9106d1ea2b2f7006705c8",
|
|
275
275
|
"src/analysis-contract.js": "6d4b9fde0e05d9a80d43e96d0c27febf082ecdb19312faf0280d6c9b16ac71b1",
|
|
276
276
|
"src/analysis-failures.js": "eb1e5a476b1e3e3c87dfd9955707c85151707799883595bcb5e9cc3e26a991c4",
|
|
277
277
|
"src/analysis-output.js": "95a3c19dcc9ab85d1dba7fee5b9aec80f9c000dfba89da3fd0be25a81e2fb680",
|
|
278
278
|
"src/analysis-worker.js": "a0bae40784c690ac68a174cb6d98fbb21dbdb69becfd27eee316ba17de544de9",
|
|
279
279
|
"src/bin.js": "22208907431d0f3a971a669c7e5eb44b3b7af9bbb36fd7ba17c3b90c4288bd70",
|
|
280
280
|
"src/bridge-client.js": "ae0dba21e4286694bcd9e064ca36564ec997969ae1eb1ce4f8a6665e447cbffe",
|
|
281
|
-
"src/context.js": "
|
|
282
|
-
"src/coordinator.js": "
|
|
281
|
+
"src/context.js": "0f5b685210807bef36628bf6522c3a4a22ac5b8136aa7608cb61fc33fa1b646d",
|
|
282
|
+
"src/coordinator.js": "dc6fb98ba3a593007fa873797844b39888861258dc58afe93f14f0db6f79da55",
|
|
283
283
|
"src/diagnostics.js": "f7b516ace61a1e9faaa6876930b9e2e258499a25857d1203f4e53d28bfd0fa1a",
|
|
284
284
|
"src/headless-analyzer.js": "df570864136981cf98f3f69d047fa5729fbbfdeeaee0c6bfad26dab941dbbdae",
|
|
285
285
|
"src/index-request.js": "78f26b872299005499fff4f2d1f9e8f986784f2ff36a5cf2be2b1e7b7c7d9378",
|
|
286
286
|
"src/knowledge-targets.js": "aa44ec285d16d7b1c0b63bf084058a1d6f867fa9929c753b6b0cbb24f7b20ee2",
|
|
287
287
|
"src/memories.js": "b661474b51688a7ec9bc9d79bdc628070f7e128effbf7b86be9520398ead00a5",
|
|
288
288
|
"src/memory-eligibility.js": "48af31f23f81140dbc706ff83a39ba9f411314d87d01e5accfaf419c7a74e0ea",
|
|
289
|
-
"src/retrieval-policy.json": "
|
|
290
|
-
"src/retrieval-ranking.js": "
|
|
291
|
-
"src/retrieval.js": "
|
|
289
|
+
"src/retrieval-policy.json": "8c8f997ddde851a17a307d36b9aa7b01aac37861efe9196eadb4778218d4530b",
|
|
290
|
+
"src/retrieval-ranking.js": "43f61504bca5e5fd9fdaf7234e775b25dd97d2777ef4615394e8069c7371e75e",
|
|
291
|
+
"src/retrieval.js": "1486efcbb8d050eeca38d39720df451e6d559584ea9602d7aa6b16df7ebe5c07",
|
|
292
292
|
"src/runtime/atomic-file.js": "9846b4b69db5ded811acf19a1181ef93615d93efaa542b858e552a7f3124ad23",
|
|
293
293
|
"src/runtime/automation-config.js": "2794aea67e3604db9b69dcaef6d303d0b5163b7e998a9730b93797f306c679cc",
|
|
294
294
|
"src/runtime/commit-conversation-binder.js": "5dd4b65d153918ecf491acf68db81dfbdd78156fc5a2a4f9b962b4dcfdd50135",
|
|
@@ -304,7 +304,7 @@
|
|
|
304
304
|
"src/runtime/knowledge-promotion.js": "c1d29e8eca3708f8841f1a697e8bb51ed7a977f4fea649b8ae98be2d7195c06e",
|
|
305
305
|
"src/runtime/knowledge-retrieval-service.js": "a4dcd09d34185f196814ff37821666e43ed0839126eab63b234bd53c4513ef1a",
|
|
306
306
|
"src/runtime/layout.js": "e47fe54c605218493ce46f6289798d9db2a3ecec95089d288ed03d3b75cf871a",
|
|
307
|
-
"src/runtime/markdown-knowledge-indexer.js": "
|
|
307
|
+
"src/runtime/markdown-knowledge-indexer.js": "adbb6057f1acce1041c72803b97511f01deb0c108d9350afe567dec364ac717f",
|
|
308
308
|
"src/runtime/README.md": "9be676eca76a7857b34d7357194e6f0ee733c22e61d962d53984715dbec7f673",
|
|
309
309
|
"src/runtime/scanner.js": "2b5443a1b782b4b73458de907a06a34e6bb6bfa9ba45d20c443ef8272ada97e6",
|
|
310
310
|
"src/server.js": "1d89378d889d563082e7ca0ade198ba312332288d5d253a9379c24b542f39b75",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanqianx/project-knowledge",
|
|
3
|
-
"version": "5.0.
|
|
3
|
+
"version": "5.0.33",
|
|
4
4
|
"description": "Knowledge base manager with Git integration, AI-driven analysis, and bilingual (zh-CN/en-US) knowledge output",
|
|
5
5
|
"main": "_site/server.js",
|
|
6
6
|
"scripts": {
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
"@lancedb/lancedb": "0.31.0",
|
|
88
88
|
"@modelcontextprotocol/sdk": "1.29.0",
|
|
89
89
|
"@sanqianx/ai-coding-event-bridge-console": "0.7.4",
|
|
90
|
-
"@sanqianx/ai-coding-knowledge-engine": "0.2.
|
|
90
|
+
"@sanqianx/ai-coding-knowledge-engine": "0.2.8",
|
|
91
91
|
"@sanqianx/vector-hub": "1.0.8-rc.8",
|
|
92
92
|
"buffer": "^6.0.3",
|
|
93
93
|
"cheerio": "^1.2.0",
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
|
|
3
3
|
"name": "project-knowledge",
|
|
4
4
|
"hooks": "./hooks/claude.json",
|
|
5
|
-
"version": "5.0.
|
|
5
|
+
"version": "5.0.33",
|
|
6
6
|
"description": "Read durable project decisions and implementation history from Project Knowledge.",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "SanQianX",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"const fs=require('fs'),path=require('path'),os=require('os');const PKG='@sanqianx/project-knowledge',SC='project-knowledge/integration-runtime/v1';let f='';const root=process.env.CLAUDE_PLUGIN_ROOT||process.env.PLUGIN_ROOT;if(root){f=path.join(root,'scripts','mcp-launcher.cjs');if(!fs.existsSync(f))f=''}if(!f){const dd=process.env.KB_DATA_DIR||path.join(os.homedir(),'.project-knowledge-v5');try{const bp=path.join(dd,'integration-runtime.json');const st=fs.statSync(bp);if(st.isFile()&&st.size<=32768){const b=JSON.parse(fs.readFileSync(bp,'utf8'));if(b&&b.schema===SC&&b.packageName===PKG&&typeof b.packageRoot==='string'&&path.isAbsolute(b.packageRoot)){const c=path.join(b.packageRoot,'plugins','project-knowledge','scripts','mcp-launcher.cjs');const rr=fs.realpathSync(b.packageRoot),cr=fs.realpathSync(c);const rel=path.relative(rr,cr);if(rel&&rel!=='..'&&!rel.startsWith('..'+path.sep)&&!path.isAbsolute(rel)&&fs.statSync(cr).isFile())f=cr}}}catch(e){}}if(!f){console.error('[project-knowledge-mcp] 未能通过受信任插件根或已验证的安装绑定定位启动器,已停止;不访问网络,也不加载工作目录源码。');process.exit(127)}require(f);"
|
|
9
9
|
],
|
|
10
10
|
"env": {
|
|
11
|
-
"KB_PLUGIN_VERSION": "5.0.
|
|
11
|
+
"KB_PLUGIN_VERSION": "5.0.33"
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
14
|
}
|
|
@@ -22,7 +22,7 @@ async function boundedJson(response) {
|
|
|
22
22
|
function log(dataDir, event, input) {
|
|
23
23
|
// Only metadata: never log the prompt, context body, headers or CLI environment.
|
|
24
24
|
const projectId = /^project-[A-Za-z0-9._-]+$/.test(input.projectId || '') ? input.projectId : '';
|
|
25
|
-
const record = { schema: 'log/v2', id: `log-${crypto.randomUUID()}`, ts: new Date().toISOString(), level: input.code ? 'warn' : 'info', component: 'agent-context', event, message: input.code ? '开发前知识读取未完成,已提示后继续。' : '知识上下文已输出给客户端;模型实际送达需原生运行证据。', projectId, operationId: input.requestId, phase: 'context', context: { client: input.client, code: input.code || null, status: input.status, factCount: input.factCount, memoryCount: input.memoryCount, durationMs: input.durationMs } };
|
|
25
|
+
const record = { schema: 'log/v2', id: `log-${crypto.randomUUID()}`, ts: new Date().toISOString(), level: input.code ? 'warn' : 'info', component: 'agent-context', event, message: input.code ? '开发前知识读取未完成,已提示后继续。' : '知识上下文已输出给客户端;模型实际送达需原生运行证据。', projectId, operationId: input.requestId, phase: 'context', context: { client: input.client, code: input.code || null, status: input.status, injectionKind: input.injectionKind || null, sessionIndexedCount: input.sessionIndexedCount ?? null, factCount: input.factCount, memoryCount: input.memoryCount, durationMs: input.durationMs } };
|
|
26
26
|
try { const directory = path.join(dataDir, 'logs', projectId ? 'projects' : 'system', ...(projectId ? [projectId] : [])); fs.mkdirSync(directory, { recursive: true }); const now = new Date(), date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`; fs.appendFileSync(path.join(directory, `${date}.jsonl`), JSON.stringify(record) + '\n', { encoding: 'utf8', mode: 0o600 }); } catch { /* Diagnostic disk failures must not block the IDE. */ }
|
|
27
27
|
}
|
|
28
28
|
|
|
@@ -51,10 +51,14 @@ async function run(payload, { env = process.env, argv = process.argv.slice(2), f
|
|
|
51
51
|
}
|
|
52
52
|
if (!response.ok || result.ok !== true) throw new Error(/^[A-Z][A-Z0-9_]{0,79}$/.test(code || '') ? code : 'CONTEXT_UNAVAILABLE');
|
|
53
53
|
if (result.requestId !== requestId || !Array.isArray(result.references) || !Array.isArray(result.memories) || !Array.isArray(result.facts) || typeof result.prompt !== 'string' || result.prompt.length > 8000 || !['ready', 'empty', 'file-fallback'].includes(result.status)) throw new Error('CONTEXT_INVALID_RESPONSE');
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
// Empty and silent turns inject nothing at all: a per-turn "no match" note
|
|
55
|
+
// is fixed overhead that repeats in the conversation history forever.
|
|
56
|
+
// Degraded-index and pending-memory notices stay user-facing system
|
|
57
|
+
// messages and never enter the model context.
|
|
58
|
+
const notice = [result.status === 'file-fallback' ? '知识向量检索暂不可用,本次使用当前文件事实。' : '', result.memoryStatus === 'pending' ? '部分已确认记忆文件待同步,本次未注入失效内容。' : ''].filter(Boolean).join(' ');
|
|
59
|
+
const output = { ...(notice ? { systemMessage: notice } : {}), ...(result.prompt ? { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: result.prompt } } : {}) };
|
|
60
|
+
const injectionKind = /^(index|memory-delta|breadcrumb|refresh)$/.test(result.injectionKind || '') ? result.injectionKind : null;
|
|
61
|
+
Object.defineProperty(output, 'receipt', { value: { dataDir, requestId, client, projectId: result.projectId, status: result.status, injectionKind, sessionIndexedCount: Number.isInteger(result.sessionIndexedCount) ? result.sessionIndexedCount : null, factCount: result.facts.length, memoryCount: result.memories.length, durationMs: Date.now() - started } });
|
|
58
62
|
return output;
|
|
59
63
|
} catch (error) {
|
|
60
64
|
const code = controller.signal.aborted ? 'CONTEXT_TIMEOUT' : /^[A-Z][A-Z0-9_]{0,79}$/.test(error.message || '') ? error.message : 'CONTEXT_UNAVAILABLE';
|
|
@@ -1,28 +1,39 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: project-knowledge
|
|
3
|
-
description: Query durable Project Knowledge records for prior decisions, implementation history, known constraints, and related-project context. Use when starting non-trivial work in a registered repository, investigating why code was designed a certain way, checking whether a problem was solved before, or answering questions about earlier commits and project history.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# Project Knowledge
|
|
7
|
-
|
|
8
|
-
Use Project Knowledge as a read-only source of durable project context. Automatic client capture is the primary conversation truth. Its one write-capable tool only supplements that truth with an explicit user Prompt event and never starts knowledge analysis. Verify returned knowledge against the current source whenever the repository may have changed since the knowledge entry was produced.
|
|
9
|
-
|
|
10
|
-
##
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
##
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
1
|
+
---
|
|
2
|
+
name: project-knowledge
|
|
3
|
+
description: Query durable Project Knowledge records for prior decisions, implementation history, known constraints, and related-project context. Use when starting non-trivial work in a registered repository, investigating why code was designed a certain way, checking whether a problem was solved before, or answering questions about earlier commits and project history.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Project Knowledge
|
|
7
|
+
|
|
8
|
+
Use Project Knowledge as a read-only source of durable project context. Automatic client capture is the primary conversation truth. Its one write-capable tool only supplements that truth with an explicit user Prompt event and never starts knowledge analysis. Verify returned knowledge against the current source whenever the repository may have changed since the knowledge entry was produced.
|
|
9
|
+
|
|
10
|
+
## Automatic session injection (read this first)
|
|
11
|
+
|
|
12
|
+
Clients with the UserPromptSubmit hook receive knowledge automatically, once per session:
|
|
13
|
+
|
|
14
|
+
- The first message of a session injects one compact block: applicable confirmed memories in full, plus a **title-only index** of knowledge entries (with their entry ids). Body text is never auto-injected.
|
|
15
|
+
- When a later message strongly matches an indexed entry, a one-line breadcrumb `- 相关知识:title (entryId)` points back at it; the same entry cools down for several turns.
|
|
16
|
+
- Edited or newly confirmed memories are re-sent in full exactly once; removed memories get a one-line notice.
|
|
17
|
+
- Everything else is silent by design - silence means "nothing new", not "no knowledge".
|
|
18
|
+
|
|
19
|
+
Therefore: when a task touches an indexed entry, read its body with `project_knowledge_get` instead of assuming the index line is the whole story, and do not re-ask for knowledge that is already in the session index above.
|
|
20
|
+
|
|
21
|
+
## Workflow
|
|
22
|
+
|
|
23
|
+
1. Call `project_knowledge_resolve` with the current Git root before substantial implementation, diagnosis, or design work. Do not guess the project slug.
|
|
24
|
+
2. Call `project_knowledge_search` for focused matching records, or `project_knowledge_ask` when a compact cited synthesis is more useful.
|
|
25
|
+
3. Review titles and summaries before loading complete entries.
|
|
26
|
+
4. Call `project_knowledge_get` only for the most relevant entries. Call `project_knowledge_history` when sequence or recent change history matters.
|
|
27
|
+
5. Cite the returned project, entry, and commit information when it materially supports an answer or decision.
|
|
28
|
+
6. Call `project_knowledge_record_requirement` only when the user explicitly requests supplemental capture or automatic client capture is known to be unavailable. Supply the exact user request, resolved project, client, and stable session identifier; never record assistant output, system prompts, credentials, or tool transcripts.
|
|
29
|
+
|
|
30
|
+
Client integrations may prefix MCP tool names with the server name. Match the tools by their final names: `project_knowledge_resolve`, `project_knowledge_record_requirement`, `project_knowledge_search`, `project_knowledge_ask`, `project_knowledge_get`, and `project_knowledge_history`.
|
|
31
|
+
|
|
32
|
+
## Boundaries
|
|
33
|
+
|
|
34
|
+
- Treat knowledge search/get/history results as read-only. The explicit adapter may only append a user Prompt event to ConversationStore.
|
|
35
|
+
- Do not write directly to the knowledge database or knowledge files.
|
|
36
|
+
- Recording a requirement must not be used as a signal that analysis already ran or succeeded.
|
|
37
|
+
- Do not substitute remembered conversation context for a knowledge lookup when prior project work is relevant.
|
|
38
|
+
- Do not treat old knowledge as stronger evidence than current code, tests, or explicit user direction.
|
|
39
|
+
- If the repository is not registered, continue using the source tree and tell the user that no matching Project Knowledge project was found.
|