@sanqianx/project-knowledge 5.0.32 → 5.0.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +15 -0
  3. package/_site/_test/automatic-context-test.js +19 -0
  4. package/_site/_test/chat-claudecodeui-match-test.js +22 -3
  5. package/_site/_test/context-session-index-test.js +244 -0
  6. package/_site/_test/fixtures/retrieval-gold-queries.json +4 -0
  7. package/_site/_test/fresh-product-data-test.js +1 -1
  8. package/_site/_test/glm-ui-refresh-review-test.js +1 -1
  9. package/_site/_test/harness-isolation-test.js +1 -1
  10. package/_site/_test/home-overview-test.js +64 -0
  11. package/_site/_test/index-error-display-contract-test.js +23 -1
  12. package/_site/_test/knowledge-engine-client-test.js +1 -1
  13. package/_site/_test/memory-groups-ui-test.js +149 -0
  14. package/_site/_test/module-terminal-restart-test.js +1 -1
  15. package/_site/_test/packaged-ui-smoke-test.js +40 -2
  16. package/_site/_test/parallel-capture-safety-r5-mem005-health-test.js +94 -33
  17. package/_site/_test/parallel-knowledge-client-error-code-test.js +11 -1
  18. package/_site/_test/parallel-logging-acceptance-log008-test.js +23 -11
  19. package/_site/_test/parallel-memory-candidate-test.js +134 -84
  20. package/_site/_test/parallel-memory-capture-r3-mem005-persistence-test.js +100 -38
  21. package/_site/_test/parallel-memory-capture-r4-mem005-health-test.js +92 -32
  22. package/_site/_test/parallel-memory-manual-test.js +140 -34
  23. package/_site/_test/parallel-memory-scope-test.js +91 -23
  24. package/_site/_test/parallel-memory-source-test.js +54 -25
  25. package/_site/_test/parallel-memory-sync-test.js +102 -75
  26. package/_site/_test/parallel-nav-failure-test.js +36 -16
  27. package/_site/_test/parallel-nav-offline-test.js +37 -9
  28. package/_site/_test/parallel-nav-operability-test.js +12 -1
  29. package/_site/_test/parallel-nav-switch-test.js +65 -19
  30. package/_site/_test/parallel-nav-theme-test.js +52 -7
  31. package/_site/_test/parallel-nav-viewport-test.js +13 -4
  32. package/_site/_test/product-diagnostics-ui-test.js +15 -3
  33. package/_site/_test/product-empty-state-test.js +81 -15
  34. package/_site/_test/product-import-ui-test.js +35 -9
  35. package/_site/_test/product-navigation-test.js +78 -17
  36. package/_site/_test/product-progress-status-test.js +21 -5
  37. package/_site/_test/project-module-partial-recovery-test.js +22 -7
  38. package/_site/_test/project-unbind-late-read-ui-test.js +45 -14
  39. package/_site/_test/workspace-ui-contract-test.js +38 -5
  40. package/_site/lib/engine-connection.js +1 -1
  41. package/_site/lib/engine-knowledge-client.js +1 -1
  42. package/_site/lib/server-app.js +23 -0
  43. package/_site/scripts/ab-rank-v2-v3.js +142 -0
  44. package/_site/scripts/refresh-runtime-manifest.js +108 -0
  45. package/_site/scripts/run-retrieval-gold-isolated.js +221 -0
  46. package/_site/scripts/verify-retrieval-gold.js +57 -10
  47. package/module-runtime-manifest.json +22 -20
  48. package/package.json +2 -2
  49. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  50. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  51. package/plugins/project-knowledge/.mcp.json +1 -1
  52. package/plugins/project-knowledge/scripts/context-hook.cjs +9 -5
  53. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +39 -28
  54. package/ui/index.html +14 -11
  55. package/ui/product.css +42 -0
  56. package/ui/product.js +830 -212
@@ -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('/api/engine/search', url), { method: 'POST', headers: { 'Content-Type': 'application/json' },
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('/api/engine/get', url), { method: 'POST', headers: { 'Content-Type': 'application/json' },
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
- item.passed = !citationErrors && !leaks && (q.empty ? rows.length === 0
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
- report.metrics = { semanticRecallAt5: semanticHits / queries.filter(q => q.kind === 'semantic').length, semanticSnippetFactCoverage: snippetFactHits / 10, followupEntryReads: deepReads, semanticVectorCases: vectorCases, checkedCitations, badCitations, scopeLeaks };
73
- report.passed = report.cases.every(c => c.passed) && report.metrics.semanticRecallAt5 >= 0.9 && vectorCases === 10 && !badCitations && !scopeLeaks;
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
  }
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "schema": "project-knowledge/module-content/v1",
3
3
  "productFiles": {
4
- "ui/index.html": "cdeddfeeb73866a270472414d39bf58ffd2bed960a2e9b79fb02e8f2539dc414",
4
+ "ui/index.html": "2e89f6fc40b9c01098a536433aae62e9dbe4c72da0678ab1219d65c79e7a666c",
5
5
  "ui/knowledge-panel.html": "dfd85f15759472252d797853263e9da0054b251c56bb9ccdc8a75e6301334ca8",
6
- "ui/product.js": "e82131bcb22cfd7b7ca3b0e32d3bd1bc924f59b2c1c44110388e5b9086e40157",
6
+ "ui/product.js": "f2b34c60e22e205f2430789b69c584c5e791f723debbf80f6decae0d3d04e1fa",
7
7
  "ui/live-client.js": "0d81fa894c629bb839e1931fc3c5ebad4d831aae8232d6ce8c0f542e9e3559e8",
8
- "ui/product.css": "0fa06692949636fabea589a4b093969bc36ca49c48dcfb4ba0b2415d6ec7f3b5",
8
+ "ui/product.css": "b7e2e6b1c1429078109e7742111f03a01a61f54895cf8ac733b83672cf31dca7",
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": "da666153ad5723592cce42d25337ae649f7d93e43fab76b3c6d1263933de063f",
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": "c61795c80b52c1ed79f94e60ca7ca25e27f9da7eecf36e575a73e4d8d684e94b",
15
- "plugins/project-knowledge/.codex-plugin/plugin.json": "c6b453fc3c0ce29a47d7e37151af0a3c37fbe41e56c5c296d87c6c4ef989106b",
16
- "plugins/project-knowledge/.mcp.json": "e932748a4dfa97e9aac73e3da5dfdbdcee1b28a0bb87ba750408a1ea64255664",
14
+ "plugins/project-knowledge/.claude-plugin/plugin.json": "a1fc2f0112e8f51997c59f42d3ac0ec397b8091336679dc264bfe4d9c2ce74a6",
15
+ "plugins/project-knowledge/.codex-plugin/plugin.json": "c0617c296b70c631377f2c9038e1d9757e6375473cecd912e4b1efc9ade15ff7",
16
+ "plugins/project-knowledge/.mcp.json": "2bf57a42c37a9a230eb4439f19cbf673c8c6b8b5531b56780380546dfad4909c",
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.7-rc.12",
270
+ "version": "0.2.9",
271
271
  "files": {
272
272
  "LICENSE": "c1b9df1275e769f3dbab000d1e457a2d4b0f28eb5da6c77e48dc37eeba202ed7",
273
273
  "README.md": "4d99cf4b19a4b07533dc86bb63015255364016fad76c1306bea69db0a9ff8743",
274
- "package.json": "95a37f9329b8f805512c35c44471da147a23dea7baf5d4092af0a6189f969dc5",
274
+ "package.json": "858f2530bf87a76894b78f32084134770614b01850b736379432b83bc5e93693",
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": "edd9d4942f6039dd4aaadec88533042ae130f1b80d935d87f61b071904a6688c",
282
- "src/coordinator.js": "fb0ef2fe2cdc35c0a99e3095c6abc94c6cf7c0b9c722c16a1c1a46b6efce6b83",
281
+ "src/context.js": "1785a52c22427ab8e41dacfca91ae872d81c68081940bc114f7176edb46aabc8",
282
+ "src/coordinator.js": "0a6b285fd8cd2bdb19a90b0b63ed7bc948789570cff7372128a2d6fcbbab43e1",
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
- "src/memories.js": "b661474b51688a7ec9bc9d79bdc628070f7e128effbf7b86be9520398ead00a5",
287
+ "src/memories.js": "943186467cd9929566dc0e887d04dbc03a8a2101c9285ca8c81508881fcdad4e",
288
288
  "src/memory-eligibility.js": "48af31f23f81140dbc706ff83a39ba9f411314d87d01e5accfaf419c7a74e0ea",
289
- "src/retrieval-policy.json": "3205fb4eb114a839a74f902e6fae6a61e1460958e5a9d7e29add32b60ba4e05a",
290
- "src/retrieval-ranking.js": "061b64f5bffec3269851830b30ab51abc3260274e5207ea4864ae33d9cb22809",
291
- "src/retrieval.js": "32f17494eb838cc6b209df35dbe33a155c1728420c9e501a4974c4f2a1b33ceb",
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",
@@ -296,7 +296,7 @@
296
296
  "src/runtime/commit-prompt.js": "3382cfa8f3476dfb5255ffae2189f91b03e8c795103f1ae7af04d92deaa90f8d",
297
297
  "src/runtime/commit-reconciler.js": "64ede337ce3734560df0425c539f084fe58a6ec073c227c34f83c69c414c191e",
298
298
  "src/runtime/content-hash.js": "201ee7dcc054310f14097a00058cf9b28fa913367eef616e0fdd8facbf3c6c41",
299
- "src/runtime/contracts.js": "68cff2d6007330ad11637f717c368ed67cefd5ee9532e5ea8f27ded3b93e0301",
299
+ "src/runtime/contracts.js": "8aa965141e88aa5d98dce74a979ef5da56edc4c7544f7f51aea27d816ed05eb5",
300
300
  "src/runtime/conversation-exclusions.js": "ef8545034b862d384fb460140490bb531b58d94992f5e2222ebaaa079b44fa63",
301
301
  "src/runtime/conversation-store.js": "4c91f16cef516556e381ee4369d67165b00833214b7675012340cbc1637ec8d7",
302
302
  "src/runtime/evidence-bundle.js": "d8e74774c2860a869f62e8adbe54d1c80818ea3da09436eff94037536ba559bf",
@@ -304,14 +304,16 @@
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": "ac094e947e52cbaeb781c0e1a9437b52b4e46bda9ae92fdd5c626ee13eb0b8be",
307
+ "src/runtime/markdown-knowledge-indexer.js": "adbb6057f1acce1041c72803b97511f01deb0c108d9350afe567dec364ac717f",
308
308
  "src/runtime/README.md": "9be676eca76a7857b34d7357194e6f0ee733c22e61d962d53984715dbec7f673",
309
309
  "src/runtime/scanner.js": "2b5443a1b782b4b73458de907a06a34e6bb6bfa9ba45d20c443ef8272ada97e6",
310
- "src/server.js": "1d89378d889d563082e7ca0ade198ba312332288d5d253a9379c24b542f39b75",
311
- "src/store.js": "66f573a58662f0a726c2ef62ccc1697616e9d93066af9f65a87c2c1f6b16829d",
310
+ "src/server.js": "4ad8a037f86f3fa8d6f688750485898c02d4dbc47aa32502f2f98c89f65e9a28",
311
+ "src/store.js": "91864c976e6da9a3dadf7441247a956ccc62e957789e5cb7c40df1925bcabb5d",
312
312
  "ui/app.css": "7ad370c269e60a7b5ec907d81a607b2d16bd07b2d7c22a81f102dab51eeb2889",
313
313
  "ui/app.js": "e9ecb0125d5f2a8bb30a58c4d278fe0737ee2540ecfb065f97f453495cfc792d",
314
- "ui/index.html": "ce3565cfefd4838b11d37a91a906ef26ca5a1834844fe3f7c897b56851a3c418"
314
+ "ui/index.html": "ce3565cfefd4838b11d37a91a906ef26ca5a1834844fe3f7c897b56851a3c418",
315
+ "src/memory-groups.js": "92b5edbd0ec7c9a3cf505d4683a053ea71d7ceeb7cfbe049bc65342a39c0c8f2",
316
+ "src/retry-scheduler.js": "048c11b767617e0c621c231e91029b4e5e834ae3e7ebc3c84b5168ea9f92ec57"
315
317
  }
316
318
  }
317
319
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanqianx/project-knowledge",
3
- "version": "5.0.32",
3
+ "version": "5.0.34",
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.7-rc.12",
90
+ "@sanqianx/ai-coding-knowledge-engine": "0.2.9",
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.32",
5
+ "version": "5.0.34",
6
6
  "description": "Read durable project decisions and implementation history from Project Knowledge.",
7
7
  "author": {
8
8
  "name": "SanQianX",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "project-knowledge",
3
- "version": "5.0.32",
3
+ "version": "5.0.34",
4
4
  "description": "Read durable project decisions and implementation history from Project Knowledge.",
5
5
  "author": {
6
6
  "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.32"
11
+ "KB_PLUGIN_VERSION": "5.0.34"
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
- const note = result.status === 'file-fallback' ? '知识向量检索暂不可用,本次使用当前文件事实。' : result.status === 'empty' ? '已查询当前知识范围,没有匹配知识或适用的已确认记忆。' : '';
55
- const warning = result.memoryStatus === 'pending' ? '部分已确认记忆文件待同步,本次未注入失效内容。' : '';
56
- const output = { ...(note || warning ? { systemMessage: [note, warning].filter(Boolean).join(' ') } : {}), hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: result.prompt || note } };
57
- Object.defineProperty(output, 'receipt', { value: { dataDir, requestId, client, projectId: result.projectId, status: result.status, factCount: result.facts.length, memoryCount: result.memories.length, durationMs: Date.now() - started } });
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
- ## Workflow
11
-
12
- 1. Call `project_knowledge_resolve` with the current Git root before substantial implementation, diagnosis, or design work. Do not guess the project slug.
13
- 2. Call `project_knowledge_search` for focused matching records, or `project_knowledge_ask` when a compact cited synthesis is more useful.
14
- 3. Review titles and summaries before loading complete entries.
15
- 4. Call `project_knowledge_get` only for the most relevant entries. Call `project_knowledge_history` when sequence or recent change history matters.
16
- 5. Cite the returned project, entry, and commit information when it materially supports an answer or decision.
17
- 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.
18
-
19
- 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`.
20
-
21
- ## Boundaries
22
-
23
- - Treat knowledge search/get/history results as read-only. The explicit adapter may only append a user Prompt event to ConversationStore.
24
- - Do not write directly to the knowledge database or knowledge files.
25
- - Recording a requirement must not be used as a signal that analysis already ran or succeeded.
26
- - Do not substitute remembered conversation context for a knowledge lookup when prior project work is relevant.
27
- - Do not treat old knowledge as stronger evidence than current code, tests, or explicit user direction.
28
- - If the repository is not registered, continue using the source tree and tell the user that no matching Project Knowledge project was found.
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.