@sanqianx/project-knowledge 5.0.9-rc.2 → 5.0.9-rc.3
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 +11 -0
- package/README.md +9 -0
- package/_site/_test/knowledge-engine-client-test.js +105 -0
- package/_site/_test/test-server-cleanup-test.js +31 -0
- package/_site/lib/contracts.js +5 -0
- package/_site/lib/engine-knowledge-client.js +72 -0
- package/_site/lib/knowledge-tool-runtime.js +7 -0
- package/bin/project-knowledge-kb.js +4 -2
- package/bin/project-knowledge-mcp.js +7 -1
- package/package.json +1 -1
- 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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [5.0.9-rc.3] - 2026-10-11
|
|
4
|
+
|
|
5
|
+
- Route engine-wired CLI and MCP reads through the same authoritative engine
|
|
6
|
+
as the web UI, preserving commit references and project/domain/brain scopes.
|
|
7
|
+
Verify the selected runtime identity and reject unavailable, mismatched or
|
|
8
|
+
malformed services instead of silently querying a different local index.
|
|
9
|
+
- Preserve the MCP `space` alias and expose explicit scope selection. Bound
|
|
10
|
+
responses and never forward profile or credential objects to read routes.
|
|
11
|
+
- Drain isolated regression servers before Windows fixture cleanup. Candidate
|
|
12
|
+
publication still does not promote latest or claim complete acceptance.
|
|
13
|
+
|
|
3
14
|
## [5.0.9-rc.2] - 2026-10-11
|
|
4
15
|
|
|
5
16
|
- Pin the verified Workbench 0.13.2-rc.1 and vector-hub 1.0.8-rc.1 candidates.
|
package/README.md
CHANGED
|
@@ -160,6 +160,15 @@ Queries never create or rewrite configuration. If the internal index is
|
|
|
160
160
|
unavailable, search falls back to current Markdown. Project, domain and brain
|
|
161
161
|
scopes are nested; unconfirmed memory candidates are not task preferences.
|
|
162
162
|
|
|
163
|
+
For engine-wired projects, the CLI and MCP delegate `search`, `ask`, `get` and
|
|
164
|
+
`history` to the same engine used by the web UI, including commit provenance.
|
|
165
|
+
They verify the running instance against the selected data directory; an
|
|
166
|
+
unavailable or mismatched instance is an explicit failure, not a second local
|
|
167
|
+
index with different facts. Only projects without engine wiring retain the
|
|
168
|
+
local legacy read contract. Use `--scope domain` or `--scope brain` to broaden
|
|
169
|
+
CLI searches; MCP accepts the equivalent `scope`. Shared-file reads accept
|
|
170
|
+
`--space <spaceId>` (MCP: `space` or `spaceId`).
|
|
171
|
+
|
|
163
172
|
## Storage
|
|
164
173
|
|
|
165
174
|
Version 5 is a fresh start, not a data upgrade. Stop the previous process,
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const assert = require('node:assert/strict');
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const os = require('node:os');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const http = require('node:http');
|
|
7
|
+
const { spawn } = require('node:child_process');
|
|
8
|
+
const { StorageLayout } = require('../lib/storage-layout');
|
|
9
|
+
const { SettingsStore } = require('../lib/settings-store');
|
|
10
|
+
const { ProjectRegistryStore } = require('../lib/project-registry-store');
|
|
11
|
+
const { ProjectStore } = require('../lib/project-store');
|
|
12
|
+
const { KnowledgeToolRuntime } = require('../lib/knowledge-tool-runtime');
|
|
13
|
+
const endpoint = require('../lib/runtime-endpoint');
|
|
14
|
+
const control = require('../lib/runtime-control');
|
|
15
|
+
const { EngineKnowledgeClient } = require('../lib/engine-knowledge-client');
|
|
16
|
+
|
|
17
|
+
(async () => {
|
|
18
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'knowledge-engine-client-'));
|
|
19
|
+
const layout = new StorageLayout({ dataDir: path.join(root, 'data') });
|
|
20
|
+
const settings = new SettingsStore({ layout }), registry = new ProjectRegistryStore({ layout }), projects = new ProjectStore({ layout });
|
|
21
|
+
const projectId = 'project-test', repoPath = path.join(root, 'repo'), knowledgePath = path.join(root, 'knowledge');
|
|
22
|
+
fs.mkdirSync(repoPath); fs.mkdirSync(knowledgePath);
|
|
23
|
+
fs.writeFileSync(path.join(knowledgePath, 'README.md'), '# Legacy\n\nlegacy-local-only\n');
|
|
24
|
+
await settings.initialize(); await registry.initialize();
|
|
25
|
+
await projects.create(projectId, { repoPath, knowledgePath }, { modules: { engine: { status: 'registered', projectId } } });
|
|
26
|
+
await projects.updateState(projectId, state => { state.modules = { engine: { status: 'registered', projectId } }; });
|
|
27
|
+
await registry.add(projectId, { displayNameSnapshot: 'Test' });
|
|
28
|
+
let invalidIdentity = false, malformed = false, businessError = false, oversized = false, wrongBinding = false;
|
|
29
|
+
const calls = [];
|
|
30
|
+
const reference = { scope_project_id: projectId, entry_id: 'changes/aaaaaaaaaaaa.md', commitSha: 'a'.repeat(40), chunk_text: 'Engine authoritative knowledge' };
|
|
31
|
+
const payload = { ok: true, projectId, backend: 'hybrid+markdown-truth', results: [reference], answer: reference.chunk_text, citations: [{ ...reference, entryId: reference.entry_id }], chunks: [{ chunk_text: reference.chunk_text }] };
|
|
32
|
+
const server = http.createServer(async (req, res) => {
|
|
33
|
+
res.setHeader('Content-Type', 'application/json');
|
|
34
|
+
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' })));
|
|
35
|
+
if (req.url === '/api/health') return res.end(JSON.stringify({ name: 'knowledge-engine', dataSchemaVersion: 3 }));
|
|
36
|
+
if (req.url === '/api/projects') return res.end(JSON.stringify({ projects: [{ projectId, repoPath, knowledgePath: wrongBinding ? root : knowledgePath }] }));
|
|
37
|
+
let text = ''; for await (const bytes of req) text += bytes;
|
|
38
|
+
calls.push({ route: req.url, input: JSON.parse(text || '{}') });
|
|
39
|
+
if (oversized) return res.end(JSON.stringify({ ok: true, text: 'x'.repeat(2 * 1024 * 1024) }));
|
|
40
|
+
if (businessError) { res.statusCode = 403; return res.end(JSON.stringify({ ok: false, error: { code: 'PATH_OUTSIDE_ROOT', message: 'private-test-secret' } })); }
|
|
41
|
+
res.end(malformed ? '[]' : JSON.stringify(payload));
|
|
42
|
+
});
|
|
43
|
+
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
44
|
+
endpoint.writeEndpoint(layout.getDataDir(), { pid: process.pid, port: server.address().port, host: '127.0.0.1', startedAt: 'test-start' });
|
|
45
|
+
const runtime = new KnowledgeToolRuntime({ layout, settingsStore: settings, registryStore: registry, projectStore: projects });
|
|
46
|
+
try {
|
|
47
|
+
for (const action of ['search', 'ask', 'get', 'history']) {
|
|
48
|
+
assert.deepEqual(await runtime[action]({ project: projectId, query: 'knowledge', entry: reference.entry_id, scope: 'brain', apiKey: 'must-not-forward', password: 'must-not-forward' }), payload);
|
|
49
|
+
const call = calls.at(-1);
|
|
50
|
+
assert.equal(call.route, `/api/engine/${action}`);
|
|
51
|
+
assert.equal(call.input.projectId, projectId); assert.equal(call.input.scope, 'brain');
|
|
52
|
+
assert.ok(!JSON.stringify(call.input).includes('must-not-forward'));
|
|
53
|
+
}
|
|
54
|
+
const subprocess = (file, args) => new Promise((resolve, reject) => {
|
|
55
|
+
const child = spawn(process.execPath, [file, ...args], { env: { ...process.env, KB_DATA_DIR: layout.getDataDir() }, windowsHide: true });
|
|
56
|
+
let out = '', err = ''; child.stdout.on('data', b => { out += b; }); child.stderr.on('data', b => { err += b; });
|
|
57
|
+
child.once('error', reject); child.once('close', code => resolve({ code, out, err }));
|
|
58
|
+
});
|
|
59
|
+
const cli = await subprocess(path.resolve(__dirname, '../../bin/project-knowledge-kb.js'), ['search', '--project', projectId, '--query', 'knowledge', '--scope', 'brain', '--json']);
|
|
60
|
+
assert.equal(cli.code, 0, cli.err); assert.deepEqual(JSON.parse(cli.out), payload);
|
|
61
|
+
assert.equal(calls.at(-1).input.scope, 'brain');
|
|
62
|
+
await runtime.get({ projectId, entry: reference.entry_id, space: 'brain:test' });
|
|
63
|
+
assert.equal(calls.at(-1).input.spaceId, 'brain:test', 'legacy space alias is forwarded');
|
|
64
|
+
const { createRequire } = require('node:module');
|
|
65
|
+
const sdk = createRequire(path.resolve(__dirname, '../../package.json'));
|
|
66
|
+
const { Client } = sdk('@modelcontextprotocol/sdk/client/index.js');
|
|
67
|
+
const { StdioClientTransport } = sdk('@modelcontextprotocol/sdk/client/stdio.js');
|
|
68
|
+
const transport = new StdioClientTransport({ command: process.execPath, args: [path.resolve(__dirname, '../../bin/project-knowledge-mcp.js')], env: { ...process.env, KB_DATA_DIR: layout.getDataDir() }, stderr: 'pipe' });
|
|
69
|
+
const client = new Client({ name: 'engine-regression', version: '1.0.0' });
|
|
70
|
+
try {
|
|
71
|
+
await client.connect(transport);
|
|
72
|
+
const tools = await client.listTools();
|
|
73
|
+
assert.deepEqual(tools.tools.find(t => t.name === 'project_knowledge_search').inputSchema.properties.scope.enum, ['project', 'domain', 'brain']);
|
|
74
|
+
for (const action of ['search', 'ask', 'get', 'history']) {
|
|
75
|
+
const result = await client.callTool({ name: `project_knowledge_${action}`, arguments: { projectId, scope: 'brain', ...(action === 'get' ? { entry: reference.entry_id, space: 'brain:test' } : action === 'history' ? {} : { query: 'knowledge' }) } });
|
|
76
|
+
assert.ok(!result.isError); assert.deepEqual(JSON.parse(result.content[0].text), payload);
|
|
77
|
+
assert.equal(calls.at(-1).input.scope, 'brain');
|
|
78
|
+
}
|
|
79
|
+
} finally { await client.close(); }
|
|
80
|
+
invalidIdentity = true;
|
|
81
|
+
await assert.rejects(runtime.search({ projectId, query: 'knowledge' }), e => e.code === 'ENGINE_IDENTITY_MISMATCH');
|
|
82
|
+
invalidIdentity = false; malformed = true;
|
|
83
|
+
await assert.rejects(runtime.search({ projectId, query: 'knowledge' }), e => e.code === 'ENGINE_INVALID_RESPONSE');
|
|
84
|
+
malformed = false; businessError = true;
|
|
85
|
+
await assert.rejects(runtime.get({ projectId, entry: '../outside.md' }), e => e.code === 'PATH_OUTSIDE_ROOT' && !e.message.includes('private-test-secret'));
|
|
86
|
+
businessError = false; oversized = true;
|
|
87
|
+
await assert.rejects(runtime.search({ projectId, query: 'knowledge' }), e => e.code === 'ENGINE_INVALID_RESPONSE');
|
|
88
|
+
oversized = false;
|
|
89
|
+
const direct = new EngineKnowledgeClient({ layout, engineUrl: `http://127.0.0.1:${server.address().port}` });
|
|
90
|
+
assert.deepEqual(await direct.request('search', {}, runtime.resolveProject({ projectId })), payload);
|
|
91
|
+
assert.equal(calls.at(-1).route, '/api/search');
|
|
92
|
+
wrongBinding = true;
|
|
93
|
+
await assert.rejects(direct.request('search', {}, runtime.resolveProject({ projectId })), e => e.code === 'ENGINE_IDENTITY_MISMATCH');
|
|
94
|
+
wrongBinding = false;
|
|
95
|
+
for (const engineUrl of ['http://example.com', 'http://secret@127.0.0.1', 'http://127.0.0.1/?apiKey=secret', 'file:///private']) {
|
|
96
|
+
const unsafe = new EngineKnowledgeClient({ layout, engineUrl });
|
|
97
|
+
await assert.rejects(unsafe.request('search', {}, runtime.resolveProject({ projectId })), e => e.code === 'ENGINE_URL_INVALID' && !e.message.includes('secret'));
|
|
98
|
+
}
|
|
99
|
+
await assert.rejects(direct.request('../runtime-config', {}, {}), e => e.code === 'INVALID_ARGUMENT');
|
|
100
|
+
await assert.rejects(runtime.search({ projectId, scope: 'another-brain' }), e => e.code === 'INVALID_ARGUMENT');
|
|
101
|
+
const unavailable = new EngineKnowledgeClient({ layout, fetchImpl: async () => { throw new Error('private-test-secret'); } });
|
|
102
|
+
await assert.rejects(unavailable.request('search', {}, runtime.resolveProject({ projectId })), e => e.code === 'ENGINE_UNAVAILABLE' && !e.message.includes('private-test-secret'));
|
|
103
|
+
console.log('knowledge-engine-client-test PASS (native runtime, CLI and MCP share engine facts)');
|
|
104
|
+
} finally { await runtime.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); }
|
|
105
|
+
})().catch(error => { console.error(error); process.exitCode = 1; });
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const assert = require('node:assert/strict');
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { spawnServer } = require('./helpers/spawn-server');
|
|
6
|
+
const freePort = require('./helpers/free-port');
|
|
7
|
+
const { readEndpoint } = require('../lib/runtime-endpoint');
|
|
8
|
+
|
|
9
|
+
(async () => {
|
|
10
|
+
const port = await freePort();
|
|
11
|
+
const spawned = spawnServer({ root: path.resolve(__dirname, '../..'), port, tag: 'graceful-cleanup' });
|
|
12
|
+
let stopped = false;
|
|
13
|
+
try {
|
|
14
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
15
|
+
const endpoint = readEndpoint(spawned.dataDir);
|
|
16
|
+
if (endpoint && (await fetch(`http://127.0.0.1:${port}/api/health`).catch(() => null))?.ok) break;
|
|
17
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
18
|
+
}
|
|
19
|
+
assert.equal(readEndpoint(spawned.dataDir)?.pid, spawned.child.pid);
|
|
20
|
+
let output = '';
|
|
21
|
+
spawned.child.stderr.on('data', bytes => { output += bytes; });
|
|
22
|
+
await spawned.cleanup(); stopped = true;
|
|
23
|
+
assert.notEqual(spawned.child.exitCode, null, output);
|
|
24
|
+
assert.equal(spawned.child.signalCode, null, 'normal cleanup must drain the server instead of force killing it');
|
|
25
|
+
assert.equal(spawned.child.exitCode, 0, output);
|
|
26
|
+
assert.ok(!fs.existsSync(spawned.dataDir));
|
|
27
|
+
assert.ok(!fs.existsSync(spawned.bridgeHome));
|
|
28
|
+
await assert.rejects(fetch(`http://127.0.0.1:${port}/api/health`));
|
|
29
|
+
console.log('test-server-cleanup-test PASS (verified graceful shutdown before fixture removal)');
|
|
30
|
+
} finally { if (!stopped) await spawned.cleanup(); }
|
|
31
|
+
})().catch(error => { console.error(error); process.exitCode = 1; });
|
package/_site/lib/contracts.js
CHANGED
|
@@ -71,6 +71,11 @@ const ERROR_CODES = Object.freeze([
|
|
|
71
71
|
'KNOWLEDGE_WRITE_MOVED',
|
|
72
72
|
'MODEL_CONFIG_MOVED',
|
|
73
73
|
'MODULE_UNREACHABLE',
|
|
74
|
+
'ENGINE_UNAVAILABLE',
|
|
75
|
+
'ENGINE_IDENTITY_MISMATCH',
|
|
76
|
+
'ENGINE_INVALID_RESPONSE',
|
|
77
|
+
'ENGINE_REQUEST_FAILED',
|
|
78
|
+
'ENGINE_URL_INVALID',
|
|
74
79
|
]);
|
|
75
80
|
|
|
76
81
|
const IMMUTABLE_PROJECT_FIELDS = Object.freeze([
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { DomainError } = require('./contracts');
|
|
3
|
+
const endpoint = require('./runtime-endpoint');
|
|
4
|
+
const control = require('./runtime-control');
|
|
5
|
+
|
|
6
|
+
class EngineKnowledgeClient {
|
|
7
|
+
constructor({ layout, engineUrl, fetchImpl = fetch, timeoutMs = 20000 }) {
|
|
8
|
+
this.layout = layout;
|
|
9
|
+
this.engineUrl = engineUrl || process.env.KB_KNOWLEDGE_ENGINE_URL;
|
|
10
|
+
this.fetch = fetchImpl;
|
|
11
|
+
this.timeoutMs = timeoutMs;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async json(url, options = {}) {
|
|
15
|
+
let response;
|
|
16
|
+
try { response = await this.fetch(url, { ...options, redirect: 'error', signal: AbortSignal.timeout(this.timeoutMs) }); }
|
|
17
|
+
catch { throw new DomainError('ENGINE_UNAVAILABLE', '知识引擎连接失败或超时,请在系统状态中检查服务。', { status: 503 }); }
|
|
18
|
+
let payload;
|
|
19
|
+
try {
|
|
20
|
+
const reader = response.body.getReader();
|
|
21
|
+
const chunks = []; let size = 0;
|
|
22
|
+
try {
|
|
23
|
+
while (true) {
|
|
24
|
+
const part = await reader.read(); if (part.done) break;
|
|
25
|
+
size += part.value.byteLength;
|
|
26
|
+
if (size > 2 * 1024 * 1024) { await reader.cancel(); throw new Error('response limit'); }
|
|
27
|
+
chunks.push(Buffer.from(part.value));
|
|
28
|
+
}
|
|
29
|
+
} finally { reader.releaseLock(); }
|
|
30
|
+
payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
31
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('invalid envelope');
|
|
32
|
+
} catch { throw new DomainError('ENGINE_INVALID_RESPONSE', '知识引擎返回了无效响应。', { status: 502 }); }
|
|
33
|
+
if (!response.ok || payload.ok === false) {
|
|
34
|
+
const code = /^[A-Z][A-Z0-9_]{0,79}$/.test(payload.error?.code || '') ? payload.error.code : 'ENGINE_REQUEST_FAILED';
|
|
35
|
+
throw new DomainError(code, '知识引擎未完成读取,请检查项目接线或请求参数。', { status: response.ok ? 502 : response.status });
|
|
36
|
+
}
|
|
37
|
+
return payload;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async target(project) {
|
|
41
|
+
if (this.engineUrl) {
|
|
42
|
+
let url; try { url = new URL(this.engineUrl); } catch {}
|
|
43
|
+
if (!url || !['http:', 'https:'].includes(url.protocol) || !endpoint.isLoopbackHost(url.hostname.replace(/^\[|\]$/g, '')) || url.username || url.password || url.search || url.hash || !['', '/'].includes(url.pathname)) throw new DomainError('ENGINE_URL_INVALID', '知识引擎地址必须是无凭据的本机服务地址。');
|
|
44
|
+
const health = await this.json(new URL('/api/health', url));
|
|
45
|
+
const registered = await this.json(new URL('/api/projects', url));
|
|
46
|
+
const match = registered.projects?.find(item => item.projectId === project.projectId && item.enabled !== false);
|
|
47
|
+
if (health.name !== 'knowledge-engine' || health.dataSchemaVersion !== 3 || !match || !this.layout.pathsEqual(match.repoPath, project.repoPath) || !this.layout.pathsEqual(match.knowledgePath, project.knowledgePath)) throw new DomainError('ENGINE_IDENTITY_MISMATCH', '知识引擎与当前项目目录绑定不匹配。', { status: 409 });
|
|
48
|
+
return { url, prefix: '/api' };
|
|
49
|
+
}
|
|
50
|
+
const live = endpoint.readLiveEndpoint(this.layout.getDataDir(), { removeStale: false });
|
|
51
|
+
if (!live) throw new DomainError('ENGINE_UNAVAILABLE', '知识库服务尚未运行,请先启动 project-knowledge。', { status: 503 });
|
|
52
|
+
const url = new URL(`http://${live.host.includes(':') ? `[${live.host}]` : live.host}:${live.port}`);
|
|
53
|
+
const identity = await this.json(new URL('/api/runtime/identity', url));
|
|
54
|
+
if (identity.schema !== control.SCHEMA || identity.name !== 'project-knowledge' || identity.pid !== live.pid || identity.port !== live.port || identity.startedAt !== live.startedAt || !identity.dataDir || !this.layout.pathsEqual(identity.dataDir, this.layout.getDataDir())) throw new DomainError('ENGINE_IDENTITY_MISMATCH', '知识库实例与当前数据目录不匹配,已拒绝读取。', { status: 409 });
|
|
55
|
+
return { url, prefix: '/api/engine' };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async request(action, input, project) {
|
|
59
|
+
if (!['search', 'ask', 'get', 'history'].includes(action)) throw new DomainError('INVALID_ARGUMENT', '仅支持知识读取操作。');
|
|
60
|
+
if (input.scope !== undefined && !['project', 'domain', 'brain'].includes(input.scope)) throw new DomainError('INVALID_ARGUMENT', '知识范围必须是项目、领域或智脑。');
|
|
61
|
+
const target = await this.target(project);
|
|
62
|
+
// Forward only the read contract, never profiles, credentials or context objects.
|
|
63
|
+
const body = { projectId: project.projectId };
|
|
64
|
+
for (const key of ['query', 'limit', 'entryId', 'entry', 'scope', 'spaceId']) if (input[key] !== undefined) body[key] = input[key];
|
|
65
|
+
if (body.spaceId === undefined && input.space !== undefined) body.spaceId = input.space;
|
|
66
|
+
const result = await this.json(new URL(`${target.prefix}/${action}`, target.url), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
67
|
+
const valid = action === 'get' ? Array.isArray(result.chunks) : Array.isArray(result.results);
|
|
68
|
+
if (result.ok !== true || !valid || (action === 'ask' && (typeof result.answer !== 'string' || !Array.isArray(result.citations)))) throw new DomainError('ENGINE_INVALID_RESPONSE', '知识引擎返回了无效读取结果。', { status: 502 });
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
module.exports = { EngineKnowledgeClient };
|
|
@@ -12,6 +12,7 @@ const { EMBEDDING_DIMENSIONS } = require('./knowledge-schema');
|
|
|
12
12
|
const { DomainError } = require('./contracts');
|
|
13
13
|
const { KnowledgeRetrievalService } = require('./knowledge-retrieval-service');
|
|
14
14
|
const { ConversationStore } = require('./conversation-store');
|
|
15
|
+
const { EngineKnowledgeClient } = require('./engine-knowledge-client');
|
|
15
16
|
|
|
16
17
|
function gitRoot(candidate) {
|
|
17
18
|
const resolved = path.resolve(candidate || process.cwd());
|
|
@@ -97,6 +98,7 @@ class KnowledgeToolRuntime {
|
|
|
97
98
|
this.settingsStore = options.settingsStore || new SettingsStore({ layout: this.layout });
|
|
98
99
|
this.registryStore = options.registryStore || new ProjectRegistryStore({ layout: this.layout });
|
|
99
100
|
this.projectStore = options.projectStore || new ProjectStore({ layout: this.layout });
|
|
101
|
+
this.engineClient = options.engineClient || new EngineKnowledgeClient({ layout: this.layout, engineUrl: options.engineUrl, fetchImpl: options.fetchImpl });
|
|
100
102
|
this.database = null;
|
|
101
103
|
this.embedder = null;
|
|
102
104
|
this.conversationStore = options.conversationStore || new ConversationStore({
|
|
@@ -279,10 +281,13 @@ class KnowledgeToolRuntime {
|
|
|
279
281
|
|
|
280
282
|
async search(input = {}) {
|
|
281
283
|
const project = this.resolveProject(input);
|
|
284
|
+
if (this.projectStore.readState(project.projectId).modules?.engine) return this.engineClient.request('search', input, project);
|
|
282
285
|
return this.retrievalService.search({ ...input, project });
|
|
283
286
|
}
|
|
284
287
|
|
|
285
288
|
async ask(input = {}) {
|
|
289
|
+
const project = this.resolveProject(input);
|
|
290
|
+
if (this.projectStore.readState(project.projectId).modules?.engine) return this.engineClient.request('ask', input, project);
|
|
286
291
|
const searched = await this.search(input);
|
|
287
292
|
const citations = searched.results.slice(0, 5).map((result, index) => ({
|
|
288
293
|
index: index + 1,
|
|
@@ -300,6 +305,7 @@ class KnowledgeToolRuntime {
|
|
|
300
305
|
|
|
301
306
|
async get(input = {}) {
|
|
302
307
|
const project = this.resolveProject(input);
|
|
308
|
+
if (this.projectStore.readState(project.projectId).modules?.engine) return this.engineClient.request('get', input, project);
|
|
303
309
|
const entryId = String(input.entryId || input.entry || '').trim().replace(/\\/g, '/');
|
|
304
310
|
if (!entryId) throw new DomainError('INVALID_ARGUMENT', 'entry is required.');
|
|
305
311
|
const target = path.resolve(project.knowledgePath, ...entryId.split('/'));
|
|
@@ -321,6 +327,7 @@ class KnowledgeToolRuntime {
|
|
|
321
327
|
|
|
322
328
|
async history(input = {}) {
|
|
323
329
|
const project = this.resolveProject(input);
|
|
330
|
+
if (this.projectStore.readState(project.projectId).modules?.engine) return this.engineClient.request('history', input, project);
|
|
324
331
|
const changesRoot = path.join(project.knowledgePath, 'changes');
|
|
325
332
|
const results = markdownFiles(project.knowledgePath).filter(file => this.layout.isPathInside(changesRoot, file, { realpath: true })).map(file => {
|
|
326
333
|
const text = fs.readFileSync(file, 'utf8');
|
|
@@ -25,7 +25,9 @@ Read-only local knowledge tools:
|
|
|
25
25
|
project-knowledge-kb get --project <projectId-or-legacy-slug> --entry <path>
|
|
26
26
|
project-knowledge-kb history --project <projectId-or-legacy-slug> [--limit 20]
|
|
27
27
|
|
|
28
|
-
Add --
|
|
28
|
+
Add --scope project|domain|brain for a search range, --space <id> for a cited
|
|
29
|
+
shared entry, and --json for machine-readable output. These commands never
|
|
30
|
+
modify knowledge or project configuration.\n`);
|
|
29
31
|
}
|
|
30
32
|
|
|
31
33
|
async function main(argv = process.argv.slice(2), options = {}) {
|
|
@@ -38,7 +40,7 @@ async function main(argv = process.argv.slice(2), options = {}) {
|
|
|
38
40
|
if (!args.project) throw new Error('--project is required');
|
|
39
41
|
const runtime = options.runtime || new KnowledgeToolRuntime(options);
|
|
40
42
|
try {
|
|
41
|
-
const input = { project: args.project, query: args.query, limit: args.limit, entry: args.entry };
|
|
43
|
+
const input = { project: args.project, query: args.query, limit: args.limit, entry: args.entry, scope: args.scope, spaceId: args.spaceId || args.space };
|
|
42
44
|
let result;
|
|
43
45
|
if (args.command === 'search') result = await runtime.search(input);
|
|
44
46
|
else if (args.command === 'ask') result = await runtime.ask(input);
|
|
@@ -11,6 +11,7 @@ const { KnowledgeToolRuntime } = require('../_site/lib/knowledge-tool-runtime');
|
|
|
11
11
|
const { serializeErrorEnvelope, createId } = require('../_site/lib/contracts');
|
|
12
12
|
|
|
13
13
|
const SERVER_NAME = 'project-knowledge';
|
|
14
|
+
const SCOPE = { type: 'string', enum: ['project', 'domain', 'brain'], description: 'Knowledge range: current project (default), its domain, or its brain.' };
|
|
14
15
|
const SERVER_INSTRUCTIONS = `Project Knowledge is the durable source of prior project decisions and implementation history. Knowledge content is read-only; the only write operation appends an explicit supplemental Prompt event to the shared conversation truth.
|
|
15
16
|
|
|
16
17
|
At the start of work in a registered Git repository, and before answering questions about prior work or implementing a non-trivial change:
|
|
@@ -56,7 +57,7 @@ const TOOLS = [
|
|
|
56
57
|
},
|
|
57
58
|
{
|
|
58
59
|
name: 'project_knowledge_search',
|
|
59
|
-
description: 'Search durable
|
|
60
|
+
description: 'Search the same durable knowledge and commit citations as the product UI, within the selected project, domain or brain. This tool is read-only.',
|
|
60
61
|
inputSchema: {
|
|
61
62
|
type: 'object',
|
|
62
63
|
required: ['query'],
|
|
@@ -66,6 +67,7 @@ const TOOLS = [
|
|
|
66
67
|
projectId: { type: 'string', description: 'Stable projectId returned by project_knowledge_resolve.' },
|
|
67
68
|
project: { type: 'string', description: 'Optional registered project slug.' },
|
|
68
69
|
limit: { type: 'integer', minimum: 1, maximum: 30, default: 8 },
|
|
70
|
+
scope: SCOPE,
|
|
69
71
|
},
|
|
70
72
|
additionalProperties: false,
|
|
71
73
|
},
|
|
@@ -82,6 +84,7 @@ const TOOLS = [
|
|
|
82
84
|
projectId: { type: 'string' },
|
|
83
85
|
project: { type: 'string' },
|
|
84
86
|
limit: { type: 'integer', minimum: 1, maximum: 30, default: 8 },
|
|
87
|
+
scope: SCOPE,
|
|
85
88
|
},
|
|
86
89
|
additionalProperties: false,
|
|
87
90
|
},
|
|
@@ -95,6 +98,8 @@ const TOOLS = [
|
|
|
95
98
|
properties: {
|
|
96
99
|
entry: { type: 'string', minLength: 1, description: 'Entry identifier returned by search.' },
|
|
97
100
|
space: { type: 'string', description: 'Optional scoped knowledge space identifier.' },
|
|
101
|
+
spaceId: { type: 'string', description: 'Knowledge space identifier returned by a citation; alias of space.' },
|
|
102
|
+
scope: SCOPE,
|
|
98
103
|
repoPath: { type: 'string' },
|
|
99
104
|
projectId: { type: 'string' },
|
|
100
105
|
project: { type: 'string' },
|
|
@@ -112,6 +117,7 @@ const TOOLS = [
|
|
|
112
117
|
projectId: { type: 'string' },
|
|
113
118
|
project: { type: 'string' },
|
|
114
119
|
limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
|
|
120
|
+
scope: SCOPE,
|
|
115
121
|
},
|
|
116
122
|
additionalProperties: false,
|
|
117
123
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanqianx/project-knowledge",
|
|
3
|
-
"version": "5.0.9-rc.
|
|
3
|
+
"version": "5.0.9-rc.3",
|
|
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": {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
|
|
3
3
|
"name": "project-knowledge",
|
|
4
|
-
"version": "5.0.9-rc.
|
|
4
|
+
"version": "5.0.9-rc.3",
|
|
5
5
|
"description": "Read durable project decisions and implementation history from Project Knowledge.",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "SanQianX",
|