@sanqianx/project-knowledge 5.0.31 → 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 +11 -0
- package/README.md +5 -2
- 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/_test/helpers/parallel-capture-safety-r5-cap-shell.js +1 -1
- package/_site/_test/helpers/parallel-capture-safety-r5-memory-shell.js +1 -1
- package/_site/_test/helpers/parallel-engine-advanced-engine-child.js +1 -1
- package/_site/_test/helpers/parallel-engine-advanced-fault-writer.js +3 -3
- package/_site/_test/helpers/parallel-engine-advanced-harness.js +1 -1
- package/_site/_test/helpers/parallel-engine-advanced-standin-analyzer.js +1 -1
- package/_site/_test/helpers/parallel-engine-final-harness.js +2 -2
- package/_site/_test/helpers/parallel-engine-final-standin-analyzer.js +1 -1
- package/_site/_test/helpers/parallel-engine-reconcile-r4-harness.js +1 -1
- package/_site/_test/helpers/parallel-engine-reconcile-r4-standin-analyzer.js +1 -1
- package/_site/_test/helpers/parallel-memory-analyzer.js +1 -1
- package/_site/_test/helpers/parallel-memory-capture-r4-cap-shell.js +1 -1
- package/_site/_test/helpers/parallel-memory-injection-shell.js +1 -1
- package/_site/_test/helpers/parallel-nav-shell.js +1 -1
- package/_site/_test/helpers/parallel-qa-engine-endpoint-guard.js +1 -1
- package/_site/_test/helpers/parallel-retrieval-followup-r2-shell.js +1 -1
- package/_site/_test/helpers/qa-r91-harness.cjs +4 -1
- package/_site/_test/package-boundary-test.js +5 -0
- package/_site/_test/parallel-capture-safety-r5-cap008e-probe.js +1 -1
- package/_site/_test/parallel-engine-advanced-eng011-ui-probe.js +1 -1
- package/_site/_test/parallel-knowledge-engine-test.js +3 -3
- package/_site/_test/parallel-knowledge-retrieval-test.js +2 -2
- package/_site/_test/parallel-memory-capture-r4-cap008e-probe.js +1 -1
- package/_site/_test/parallel-memory-injection-origin-probe.js +1 -1
- package/_site/_test/parallel-nav-isolation-test.js +1 -1
- package/_site/_test/parallel-qa-engine-endpoint-guard-test.js +1 -1
- package/_site/_test/parallel-retrieval-followup-citation-test.js +2 -2
- package/_site/_test/parallel-retrieval-followup-corpus-test.js +1 -1
- package/_site/_test/qa-r45-offline-backfill-test.js +2 -2
- package/_site/_test/t07d-git-rel-coverage-test.js +5 -3
- package/_site/_test/t07f-mem-008-coverage-test.js +1 -1
- package/_site/lib/module-bridge.js +2 -11
- package/_site/scripts/ab-rank-v2-v3.js +142 -0
- package/_site/scripts/install-module-candidates.js +1 -1
- package/_site/scripts/pack-module-candidates.js +2 -1
- package/_site/scripts/run-retrieval-gold-isolated.js +221 -0
- package/_site/scripts/verify-module-runtime.js +17 -32
- package/_site/scripts/verify-product-runtime.js +7 -3
- package/_site/scripts/verify-retrieval-gold.js +57 -10
- package/docs/README.zh-CN.md +3 -1
- package/module-runtime-manifest.json +54 -4
- package/package.json +2 -4
- 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/_modules/knowledge-engine/README.md +0 -133
- package/_modules/knowledge-engine/package.json +0 -38
- package/_modules/knowledge-engine/src/analysis-contract.js +0 -35
- package/_modules/knowledge-engine/src/analysis-failures.js +0 -39
- package/_modules/knowledge-engine/src/analysis-output.js +0 -52
- package/_modules/knowledge-engine/src/analysis-worker.js +0 -58
- package/_modules/knowledge-engine/src/bin.js +0 -52
- package/_modules/knowledge-engine/src/bridge-client.js +0 -24
- package/_modules/knowledge-engine/src/context.js +0 -140
- package/_modules/knowledge-engine/src/coordinator.js +0 -376
- package/_modules/knowledge-engine/src/diagnostics.js +0 -37
- package/_modules/knowledge-engine/src/headless-analyzer.js +0 -66
- package/_modules/knowledge-engine/src/index-request.js +0 -49
- package/_modules/knowledge-engine/src/knowledge-targets.js +0 -46
- package/_modules/knowledge-engine/src/memories.js +0 -281
- package/_modules/knowledge-engine/src/memory-eligibility.js +0 -74
- package/_modules/knowledge-engine/src/retrieval-policy.json +0 -14
- package/_modules/knowledge-engine/src/retrieval-ranking.js +0 -153
- package/_modules/knowledge-engine/src/retrieval.js +0 -367
- package/_modules/knowledge-engine/src/runtime/README.md +0 -7
- package/_modules/knowledge-engine/src/runtime/atomic-file.js +0 -204
- package/_modules/knowledge-engine/src/runtime/automation-config.js +0 -140
- package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +0 -250
- package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +0 -26
- package/_modules/knowledge-engine/src/runtime/commit-prompt.js +0 -205
- package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +0 -432
- package/_modules/knowledge-engine/src/runtime/content-hash.js +0 -4
- package/_modules/knowledge-engine/src/runtime/contracts.js +0 -282
- package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +0 -204
- package/_modules/knowledge-engine/src/runtime/conversation-store.js +0 -389
- package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +0 -228
- package/_modules/knowledge-engine/src/runtime/git-runner.js +0 -62
- package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +0 -559
- package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +0 -408
- package/_modules/knowledge-engine/src/runtime/layout.js +0 -46
- package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +0 -276
- package/_modules/knowledge-engine/src/runtime/scanner.js +0 -298
- package/_modules/knowledge-engine/src/server.js +0 -166
- package/_modules/knowledge-engine/src/store.js +0 -267
- package/_modules/knowledge-engine/ui/app.css +0 -172
- package/_modules/knowledge-engine/ui/app.js +0 -318
- package/_modules/knowledge-engine/ui/index.html +0 -95
- package/_site/scripts/vendor-modules.js +0 -49
- package/vendor-manifest.json +0 -55
|
@@ -49,7 +49,7 @@ const {
|
|
|
49
49
|
} = require('./helpers/parallel-nav-isolation-env');
|
|
50
50
|
|
|
51
51
|
const ROOT = path.resolve(__dirname, '..', '..');
|
|
52
|
-
const ENGINE_ENTRY = path.join(
|
|
52
|
+
const ENGINE_ENTRY = path.join(path.dirname(require.resolve('@sanqianx/ai-coding-knowledge-engine/package.json', { paths: [path.join(ROOT)] })), 'src', 'server.js');
|
|
53
53
|
const SHELL_FILE = path.join(ROOT, '_site', '_test', 'helpers', 'parallel-nav-shell.js');
|
|
54
54
|
const EVIDENCE = process.env.PK_R7_EVIDENCE_DIR ? path.resolve(process.env.PK_R7_EVIDENCE_DIR) : null;
|
|
55
55
|
|
|
@@ -75,7 +75,7 @@ const {
|
|
|
75
75
|
|
|
76
76
|
// ── Leg B: negative regression — the ORIGINAL defect, safely held ──
|
|
77
77
|
// Raw product constructor without vectorUrl (exactly the S1/S2/S3 shape).
|
|
78
|
-
const { createEngineServer } = require('
|
|
78
|
+
const { createEngineServer } = require('@sanqianx/ai-coding-knowledge-engine/src/server');
|
|
79
79
|
const negRoot = mkdtemp('neg');
|
|
80
80
|
const negBrainDir = path.join(negRoot, 'brain-shared');
|
|
81
81
|
fs.mkdirSync(negBrainDir, { recursive: true });
|
|
@@ -26,8 +26,8 @@ const shell = require('./helpers/parallel-retrieval-followup-shell');
|
|
|
26
26
|
// Isolate before any product module is loaded.
|
|
27
27
|
shell.isolateProcess();
|
|
28
28
|
|
|
29
|
-
const { createEngineServer } = require('
|
|
30
|
-
const AtomicFile = require('
|
|
29
|
+
const { createEngineServer } = require('@sanqianx/ai-coding-knowledge-engine/src/server');
|
|
30
|
+
const AtomicFile = require('@sanqianx/ai-coding-knowledge-engine/src/runtime/atomic-file');
|
|
31
31
|
|
|
32
32
|
const TOKEN = 'RET007OFFLINE';
|
|
33
33
|
const results = [];
|
|
@@ -38,7 +38,7 @@ const shell = require('./helpers/parallel-retrieval-followup-shell');
|
|
|
38
38
|
shell.isolateProcess();
|
|
39
39
|
|
|
40
40
|
const corpusDefinitions = require('./helpers/parallel-retrieval-followup-corpus');
|
|
41
|
-
const ranking = require('
|
|
41
|
+
const ranking = require('@sanqianx/ai-coding-knowledge-engine/src/retrieval-ranking');
|
|
42
42
|
|
|
43
43
|
const HUB_DIST = path.join(shell.REPO_ROOT, 'node_modules', '@sanqianx', 'vector-hub', 'dist', 'cjs');
|
|
44
44
|
const DIMENSIONS = 512;
|
|
@@ -83,8 +83,8 @@ async function main() {
|
|
|
83
83
|
caseId: 'ENG-007', lane: 'P-ENGINE-OFFLINE-AUDIT-R45', laneDir: lane, phases: {}, commands,
|
|
84
84
|
isolation: { tempRoot: TEMP_ROOT, evidenceRoot: EVIDENCE_ROOT, envIsolation: ENV_ISOLATION_RESOLVED },
|
|
85
85
|
identity: {
|
|
86
|
-
vendoredEngineVersion: JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', '..'
|
|
87
|
-
vendoredCoordinatorSha256: sha256(path.resolve(__dirname, '..', '..'
|
|
86
|
+
vendoredEngineVersion: JSON.parse(fs.readFileSync(path.join(path.dirname(require.resolve('@sanqianx/ai-coding-knowledge-engine/package.json', { paths: [path.resolve(__dirname, '..', '..')] })), 'package.json'), 'utf8')).version,
|
|
87
|
+
vendoredCoordinatorSha256: sha256(path.join(path.dirname(require.resolve('@sanqianx/ai-coding-knowledge-engine/package.json', { paths: [path.resolve(__dirname, '..', '..')] })), 'src', 'coordinator.js')),
|
|
88
88
|
bridge: RUNTIME_IDENTITY.bridge, vector: RUNTIME_IDENTITY.vector,
|
|
89
89
|
},
|
|
90
90
|
};
|
|
@@ -172,7 +172,7 @@ function main() {
|
|
|
172
172
|
// ---------------- REL-003 制品泄漏 ------------------------------------
|
|
173
173
|
{
|
|
174
174
|
const { validatePack } = require(path.join(REPO, 'qa-autopilot', 'lib', 'registry.cjs'));
|
|
175
|
-
const essentials = ['package.json', '_site/server.js', 'ui/index.html', 'ui/product.js', 'ui/live-client.js', 'module-runtime-manifest.json'
|
|
175
|
+
const essentials = ['package.json', '_site/server.js', 'ui/index.html', 'ui/product.js', 'ui/live-client.js', 'module-runtime-manifest.json'];
|
|
176
176
|
assert.throws(() => validatePack([...essentials, 'qa-autopilot/tools/x.cjs']), /Forbidden package file.*qa-autopilot/,
|
|
177
177
|
'QA-SPEC-REL-003: qa/ paths are refused in the pack');
|
|
178
178
|
assert.throws(() => validatePack([...essentials, 'state/runs/1.json']), /Forbidden package file.*state/,
|
|
@@ -185,8 +185,10 @@ function main() {
|
|
|
185
185
|
assert.throws(() => validatePack(essentials.filter(f => f !== required)), /Required runtime missing/,
|
|
186
186
|
`QA-SPEC-REL-003: removing the essential ${required} is refused — the engine/plugins runtime cannot be cleaned away`);
|
|
187
187
|
}
|
|
188
|
-
assert.doesNotThrow(() => validatePack([...essentials, '
|
|
189
|
-
'QA-SPEC-REL-003:
|
|
188
|
+
assert.doesNotThrow(() => validatePack([...essentials, 'plugins/project-knowledge/plugin.json']),
|
|
189
|
+
'QA-SPEC-REL-003: shell and plugin payload passes the audit with npm runtime dependencies');
|
|
190
|
+
assert.throws(() => validatePack([...essentials, '_modules/knowledge-engine/src/server.js']), /Engine source must be installed/,
|
|
191
|
+
'QA-SPEC-REL-003: engine source cannot leak back into the shell package');
|
|
190
192
|
console.log('QA-SPEC-REL-003: leak paths refused; required runtime essentials protected');
|
|
191
193
|
}
|
|
192
194
|
|
|
@@ -21,7 +21,7 @@ const path = require('node:path');
|
|
|
21
21
|
const crypto = require('node:crypto');
|
|
22
22
|
|
|
23
23
|
const REPO = path.resolve(__dirname, '..', '..');
|
|
24
|
-
const { MemoryEligibility } = require(path.join(
|
|
24
|
+
const { MemoryEligibility } = require(path.join(path.dirname(require.resolve('@sanqianx/ai-coding-knowledge-engine/package.json', { paths: [path.join(REPO)] })), 'src', 'memory-eligibility.js'));
|
|
25
25
|
|
|
26
26
|
const sha = text => crypto.createHash('sha256').update(text).digest('hex');
|
|
27
27
|
|
|
@@ -49,24 +49,15 @@ const INDEX_TIMEOUT_MS = 120000;
|
|
|
49
49
|
// Native folder dialogs wait for the user without a bound.
|
|
50
50
|
const PICKER_TIMEOUT_MS = 10 * 60 * 1000;
|
|
51
51
|
|
|
52
|
-
//
|
|
53
|
-
// spawning is gone: the services are bundled, spawned from here, and resolved
|
|
54
|
-
// through normal node_modules resolution
|
|
55
|
-
// node_modules.
|
|
56
|
-
// Module entry scripts resolve through normal node_modules dependencies
|
|
57
|
-
// (claude-ai-workbench, @sanqianx/vector-hub, @sanqianx/ai-coding-event-bridge-
|
|
58
|
-
// console) — the npm packages are the single source of these runtimes.
|
|
52
|
+
// All four services resolve through the host's pinned npm dependencies.
|
|
59
53
|
const MODULE_ENTRIES = {
|
|
60
54
|
terminal: 'claude-ai-workbench/packages/server/bin/agent-terminal-server.js',
|
|
61
55
|
'vector-hub': '@sanqianx/vector-hub/bin.js',
|
|
62
56
|
'event-bridge': '@sanqianx/ai-coding-event-bridge-console/src/bin.js',
|
|
57
|
+
'knowledge-engine': '@sanqianx/ai-coding-knowledge-engine/src/bin.js',
|
|
63
58
|
};
|
|
64
59
|
|
|
65
60
|
function resolveModuleEntry(name) {
|
|
66
|
-
if (name === 'knowledge-engine') {
|
|
67
|
-
const runtime = path.resolve(__dirname, '..', '..', '_modules', 'knowledge-engine', 'src', 'bin.js');
|
|
68
|
-
return fs.existsSync(runtime) ? runtime : null;
|
|
69
|
-
}
|
|
70
61
|
try { return require.resolve(MODULE_ENTRIES[name]); } catch { return null; }
|
|
71
62
|
}
|
|
72
63
|
|
|
@@ -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; });
|
|
@@ -56,7 +56,7 @@ function main() {
|
|
|
56
56
|
const verify = spawnSync(process.execPath, [path.join(core, '_site/scripts/verify-module-runtime.js'), '--working-tree'], { cwd: installedRoot, windowsHide: true, encoding: 'utf8' });
|
|
57
57
|
if (verify.status !== 0) throw new Error('Packaged engine integrity failed');
|
|
58
58
|
require('./verify-product-runtime').verifyProductRuntime(core);
|
|
59
|
-
for (const relative of ['
|
|
59
|
+
for (const relative of ['module-runtime-manifest.json']) {
|
|
60
60
|
if (!fs.readFileSync(path.join(core, relative)).equals(fs.readFileSync(path.join(root, relative)))) throw new Error(`Installed candidate is stale: ${relative}`);
|
|
61
61
|
}
|
|
62
62
|
const report = { schema: 'project-knowledge/installed-candidates/v1', mode: 'local npm candidate installation, not remote release', installedRoot, core, artifactManifest: manifestFile, shellVersion: candidate.version, shellSha256, shellArtifact, modules: Object.fromEntries(Object.entries(manifest.modules).map(([key, module]) => [key, { version: module.version, sha256: module.sha256 }])), integrityPassed: true, testedAt: new Date().toISOString() };
|
|
@@ -12,6 +12,7 @@ const definitions = {
|
|
|
12
12
|
terminal: { option: '--terminal-source', name: '@sanqianx/claude-ai-workbench', installName: 'claude-ai-workbench', required: ['apps/agent-terminal/app.js', 'apps/agent-terminal/app.css', 'packages/server/lib/knowledge-context.js'] },
|
|
13
13
|
vectorHub: { option: '--vector-source', name: '@sanqianx/vector-hub', installName: '@sanqianx/vector-hub', required: ['dist/cjs/bin.js', 'dist/cjs/server/manager.js', 'ui/index.html'] },
|
|
14
14
|
eventBridge: { option: '--bridge-source', name: '@sanqianx/ai-coding-event-bridge-console', installName: '@sanqianx/ai-coding-event-bridge-console', required: ['src/server.js', 'src/bridge/core/consumer-registry.js', 'console/index.html'] },
|
|
15
|
+
engine: { option: '--engine-source', name: '@sanqianx/ai-coding-knowledge-engine', installName: '@sanqianx/ai-coding-knowledge-engine', required: ['src/bin.js', 'src/server.js', 'src/coordinator.js', 'src/analysis-worker.js', 'ui/index.html', 'ui/app.js', 'ui/app.css'] },
|
|
15
16
|
};
|
|
16
17
|
function run(command, args, cwd) {
|
|
17
18
|
const result = spawnSync(command, args, { cwd, windowsHide: true, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });
|
|
@@ -86,4 +87,4 @@ if (require.main === module) {
|
|
|
86
87
|
}
|
|
87
88
|
} catch (error) { process.stderr.write(`${error.message}\n`); process.exitCode = 1; }
|
|
88
89
|
}
|
|
89
|
-
module.exports = { verifyInstalled, safeRelative, productFiles, installedFileBytes };
|
|
90
|
+
module.exports = { definitions, verifyInstalled, safeRelative, productFiles, installedFileBytes };
|
|
@@ -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; });
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
const fs = require('fs');
|
|
3
3
|
const path = require('path');
|
|
4
|
-
const crypto = require('crypto');
|
|
5
4
|
const { spawnSync } = require('child_process');
|
|
5
|
+
const { verifyProductRuntime } = require('./verify-product-runtime');
|
|
6
|
+
const { definitions } = require('./pack-module-candidates');
|
|
6
7
|
const root = path.resolve(__dirname, '../..');
|
|
7
8
|
const workingTree = process.argv.includes('--working-tree');
|
|
8
9
|
function isPinnedModuleVersion(name, value) {
|
|
@@ -10,41 +11,25 @@ function isPinnedModuleVersion(name, value) {
|
|
|
10
11
|
return /^\d+\.\d+\.\d+(?:-rc\.\d+)?$/.test(version || '');
|
|
11
12
|
}
|
|
12
13
|
function verify() {
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
if (!engine || engine.root !== '_modules/knowledge-engine') throw new Error('Missing engine runtime');
|
|
17
|
-
const packageInfo = JSON.parse(fs.readFileSync(path.join(root, 'package.json')));
|
|
18
|
-
for (const dependency of ['claude-ai-workbench', '@sanqianx/vector-hub', '@sanqianx/ai-coding-event-bridge-console']) {
|
|
19
|
-
if (!isPinnedModuleVersion(dependency, packageInfo.dependencies[dependency])) throw new Error(`Module dependency must be pinned: ${dependency}`);
|
|
14
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json')));
|
|
15
|
+
for (const { installName } of Object.values(definitions)) {
|
|
16
|
+
if (!isPinnedModuleVersion(installName, pkg.dependencies[installName])) throw new Error(`Module dependency must be pinned: ${installName}`);
|
|
20
17
|
}
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
if (entry.isDirectory()) checkTree(path.join(directory, entry.name), relative + '/');
|
|
29
|
-
else if (!Object.hasOwn(engine.files, relative)) throw new Error(`Unreviewed runtime file: ${relative}`);
|
|
30
|
-
}
|
|
18
|
+
const modules = verifyProductRuntime(root);
|
|
19
|
+
const engine = JSON.parse(fs.readFileSync(path.join(modules.engine.directory, 'package.json')));
|
|
20
|
+
if (Object.keys(engine.dependencies || {}).length || Object.keys(engine.devDependencies || {}).length) throw new Error('Engine must remain dependency-free');
|
|
21
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'module-runtime-manifest.json')));
|
|
22
|
+
for (const file of Object.keys(manifest.modules.engine.files).filter(file => file.endsWith('.js'))) {
|
|
23
|
+
const syntax = spawnSync(process.execPath, ['--check', path.join(modules.engine.directory, file)], { windowsHide: true, encoding: 'utf8' });
|
|
24
|
+
if (syntax.status !== 0) throw new Error(`Engine runtime syntax error: ${file}`);
|
|
31
25
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
if (fs.lstatSync(file).isSymbolicLink()) throw new Error('Unsafe vendored symlink');
|
|
37
|
-
if (crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex') !== expected) throw new Error(`Runtime drift: ${relative}`);
|
|
38
|
-
if (relative.endsWith('.js')) { const syntax = spawnSync(process.execPath, ['--check', file], { windowsHide: true, encoding: 'utf8' }); if (syntax.status !== 0) throw new Error(`Runtime syntax error: ${relative}`); }
|
|
39
|
-
if (hasGit && !workingTree) {
|
|
40
|
-
const indexed = spawnSync('git', ['show', `:${engine.root}/${relative}`], { cwd: root, windowsHide: true });
|
|
41
|
-
if (indexed.status !== 0) throw new Error(`Release blocked: runtime file is not Git tracked: ${relative}`);
|
|
42
|
-
if (crypto.createHash('sha256').update(indexed.stdout).digest('hex') !== expected) throw new Error(`Release blocked: Git runtime bytes differ from manifest: ${relative}`);
|
|
26
|
+
if (fs.existsSync(path.join(root, '.git')) && !workingTree) {
|
|
27
|
+
for (const file of ['package.json', 'module-runtime-manifest.json']) {
|
|
28
|
+
const indexed = spawnSync('git', ['show', `:${file}`], { cwd: root, windowsHide: true });
|
|
29
|
+
if (indexed.status !== 0 || indexed.stdout.toString().replace(/\r\n/g, '\n') !== fs.readFileSync(path.join(root, file), 'utf8').replace(/\r\n/g, '\n')) throw new Error(`Release blocked: Git bytes differ from runtime contract: ${file}`);
|
|
43
30
|
}
|
|
44
31
|
}
|
|
45
|
-
|
|
46
|
-
if (enginePackage.version !== engine.version || Object.keys(enginePackage.dependencies || {}).length || Object.keys(enginePackage.devDependencies || {}).length) throw new Error('Engine version/dependency contract failed');
|
|
47
|
-
process.stdout.write(workingTree ? 'Runtime content verified; uncommitted working tree is not release approval.\n' : 'Vendored runtime release gate passed.\n');
|
|
32
|
+
process.stdout.write(workingTree ? 'Four npm module runtimes verified; working tree is not release approval.\n' : 'Pinned npm runtime release gate passed.\n');
|
|
48
33
|
}
|
|
49
34
|
if (require.main === module) { try { verify(); } catch (error) { process.stderr.write(`${error.message}\n`); process.exitCode = 1; } }
|
|
50
35
|
module.exports = { isPinnedModuleVersion };
|
|
@@ -3,10 +3,11 @@ const fs = require('node:fs');
|
|
|
3
3
|
const path = require('node:path');
|
|
4
4
|
const crypto = require('node:crypto');
|
|
5
5
|
const { createRequire } = require('node:module');
|
|
6
|
-
const { safeRelative } = require('./pack-module-candidates');
|
|
6
|
+
const { safeRelative, definitions } = require('./pack-module-candidates');
|
|
7
7
|
function verifyProductRuntime(coreRoot, resolveFrom = path.join(coreRoot, 'package.json')) {
|
|
8
8
|
const manifest = JSON.parse(fs.readFileSync(path.join(coreRoot, 'module-runtime-manifest.json')));
|
|
9
|
-
if (manifest.schema !== 'project-knowledge/module-content/v1' || Object.keys(manifest.modules).length !==
|
|
9
|
+
if (manifest.schema !== 'project-knowledge/module-content/v1' || Object.keys(manifest.modules).length !== Object.keys(definitions).length || Object.keys(definitions).some(key => !manifest.modules[key])) throw new Error('Incomplete module content manifest');
|
|
10
|
+
const host = JSON.parse(fs.readFileSync(path.join(coreRoot, 'package.json')));
|
|
10
11
|
for (const file of ['ui/index.html', 'ui/knowledge-panel.html', 'ui/product.js', 'ui/product.css', 'ui/favicon.svg', 'plugins/project-knowledge/hooks/claude.json', 'plugins/project-knowledge/hooks/codex.json', 'plugins/project-knowledge/scripts/context-hook.cjs', 'plugins/project-knowledge/scripts/mcp-launcher.cjs', 'plugins/project-knowledge/.claude-plugin/plugin.json', 'plugins/project-knowledge/.codex-plugin/plugin.json', 'plugins/project-knowledge/.mcp.json']) if (!manifest.productFiles?.[file]) throw new Error(`Product asset missing from content manifest: ${file}`);
|
|
11
12
|
const resolve = createRequire(resolveFrom);
|
|
12
13
|
if (!manifest.productFiles['ui/live-client.js']) throw new Error('Product live transport missing from content manifest');
|
|
@@ -15,6 +16,9 @@ function verifyProductRuntime(coreRoot, resolveFrom = path.join(coreRoot, 'packa
|
|
|
15
16
|
}
|
|
16
17
|
const modules = {};
|
|
17
18
|
for (const [key, module] of Object.entries(manifest.modules)) {
|
|
19
|
+
const definition = definitions[key];
|
|
20
|
+
if (module.name !== definition.name || module.installName !== definition.installName || definition.required.some(file => !module.files[file])) throw new Error(`Incomplete module runtime: ${key}`);
|
|
21
|
+
if (![module.version, `npm:${module.name}@${module.version}`].includes(host.dependencies[module.installName])) throw new Error(`Module dependency is not pinned to manifest: ${key}`);
|
|
18
22
|
const pkgFile = resolve.resolve(`${module.installName}/package.json`);
|
|
19
23
|
const directory = path.dirname(pkgFile);
|
|
20
24
|
const pkg = JSON.parse(fs.readFileSync(pkgFile));
|
|
@@ -26,7 +30,7 @@ function verifyProductRuntime(coreRoot, resolveFrom = path.join(coreRoot, 'packa
|
|
|
26
30
|
}
|
|
27
31
|
modules[key] = { directory, version: pkg.version };
|
|
28
32
|
}
|
|
29
|
-
for (const file of ['ui/index.html', 'ui/knowledge-panel.html', 'ui/product.js', 'ui/product.css'
|
|
33
|
+
for (const file of ['ui/index.html', 'ui/knowledge-panel.html', 'ui/product.js', 'ui/product.css']) if (!fs.existsSync(path.join(coreRoot, file))) throw new Error(`Product runtime missing: ${file}`);
|
|
30
34
|
return modules;
|
|
31
35
|
}
|
|
32
36
|
if (require.main === module) {
|