@sanqianx/project-knowledge 4.7.0 → 5.0.0
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/.agents/plugins/marketplace.json +17 -17
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +836 -799
- package/README.md +58 -41
- package/_modules/knowledge-engine/README.md +91 -0
- package/_modules/knowledge-engine/package.json +38 -0
- package/_modules/knowledge-engine/src/analysis-contract.js +25 -0
- package/_modules/knowledge-engine/src/analysis-worker.js +54 -0
- package/_modules/knowledge-engine/src/bin.js +52 -0
- package/_modules/knowledge-engine/src/bridge-client.js +24 -0
- package/_modules/knowledge-engine/src/coordinator.js +263 -0
- package/_modules/knowledge-engine/src/headless-analyzer.js +75 -0
- package/_modules/knowledge-engine/src/memories.js +85 -0
- package/_modules/knowledge-engine/src/retrieval.js +116 -0
- package/_modules/knowledge-engine/src/runtime/README.md +7 -0
- package/_modules/knowledge-engine/src/runtime/atomic-file.js +204 -0
- package/_modules/knowledge-engine/src/runtime/automation-config.js +140 -0
- package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +249 -0
- package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +26 -0
- package/_modules/knowledge-engine/src/runtime/commit-prompt.js +202 -0
- package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +432 -0
- package/_modules/knowledge-engine/src/runtime/content-hash.js +4 -0
- package/_modules/knowledge-engine/src/runtime/contracts.js +279 -0
- package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +204 -0
- package/_modules/knowledge-engine/src/runtime/conversation-store.js +387 -0
- package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +228 -0
- package/_modules/knowledge-engine/src/runtime/git-runner.js +62 -0
- package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +444 -0
- package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +402 -0
- package/_modules/knowledge-engine/src/runtime/layout.js +44 -0
- package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +230 -0
- package/_modules/knowledge-engine/src/runtime/scanner.js +298 -0
- package/_modules/knowledge-engine/src/server.js +154 -0
- package/_modules/knowledge-engine/src/store.js +236 -0
- package/_modules/knowledge-engine/ui/app.css +172 -0
- package/_modules/knowledge-engine/ui/app.js +297 -0
- package/_modules/knowledge-engine/ui/index.html +95 -0
- package/_site/README.md +30 -30
- package/_site/_test/ai-profile-resolver-test.js +137 -137
- package/_site/_test/automation-queue-test.js +14 -14
- package/_site/_test/automation-ui-test.js +40 -40
- package/_site/_test/background-task-registry-test.js +43 -43
- package/_site/_test/baseline-schema-test.js +91 -91
- package/_site/_test/chat-claudecodeui-match-test.js +92 -92
- package/_site/_test/claude-executable-discovery-test.js +62 -62
- package/_site/_test/claude-workbench-test.js +170 -170
- package/_site/_test/codex-conversation-projection-test.js +2 -1
- package/_site/_test/commit-conversation-binding-test.js +95 -95
- package/_site/_test/commit-evidence-test.js +110 -110
- package/_site/_test/conversation-api-test.js +109 -109
- package/_site/_test/conversation-store-test.js +136 -136
- package/_site/_test/desktop-browser-compat-test.js +28 -28
- package/_site/_test/desktop-hook-runtime-regression-test.js +204 -204
- package/_site/_test/explicit-commit-processor-test.js +37 -37
- package/_site/_test/fixtures/make-git-repos.js +12 -1
- package/_site/_test/folder-picker-output-test.js +19 -19
- package/_site/_test/fresh-hook-reimport-test.js +53 -0
- package/_site/_test/fresh-product-data-test.js +42 -0
- package/_site/_test/full-integration-e2e-test.js +165 -165
- package/_site/_test/git-validation-test.js +2 -2
- package/_site/_test/hook-runtime-endpoint-test.js +88 -88
- package/_site/_test/hook-status-repair-api-test.js +152 -152
- package/_site/_test/hook-trigger-test.js +85 -85
- package/_site/_test/import-preflight-api-test.js +234 -233
- package/_site/_test/index-writer-concurrency-test.js +135 -135
- package/_site/_test/integration-adapters-test.js +171 -171
- package/_site/_test/integration-surface-coverage-test.js +164 -164
- package/_site/_test/knowledge-language-control-test.js +170 -170
- package/_site/_test/knowledge-promotion-recovery-test.js +260 -260
- package/_site/_test/knowledge-query-test.js +54 -54
- package/_site/_test/knowledge-retrieval-service-test.js +77 -77
- package/_site/_test/knowledge-storage-startup-test.js +52 -52
- package/_site/_test/knowledge-store-logs-supervision-test.js +89 -89
- package/_site/_test/logging-api-test.js +89 -89
- package/_site/_test/logging-sse-no-gap-test.js +88 -88
- package/_site/_test/logging-ui-test.js +106 -104
- package/_site/_test/markdown-delta-overlay-test.js +85 -85
- package/_site/_test/markdown-maintenance-api-test.js +75 -75
- package/_site/_test/mcp-server-test.js +149 -149
- package/_site/_test/module-artifact-integrity-test.js +27 -0
- package/_site/_test/module-boundary-test.js +30 -0
- package/_site/_test/module-bridge-eventbridge-test.js +7 -0
- package/_site/_test/module-model-configuration-test.js +44 -0
- package/_site/_test/module-process-lifecycle-test.js +24 -0
- package/_site/_test/module-stream-proxy-test.js +34 -0
- package/_site/_test/non-release-ci-test.js +34 -34
- package/_site/_test/offline-boundary-isolation-test.js +32 -32
- package/_site/_test/packaged-ui-smoke-test.js +11 -9
- package/_site/_test/path-consistency-test.js +151 -151
- package/_site/_test/pending-sweep-test.js +9 -9
- package/_site/_test/post-commit-automation-test.js +87 -87
- package/_site/_test/product-diagnostics-ui-test.js +75 -0
- package/_site/_test/product-import-ui-test.js +92 -0
- package/_site/_test/project-delete-recovery-test.js +64 -64
- package/_site/_test/project-goal-editor-test.js +144 -144
- package/_site/_test/project-lifecycle-transaction-test.js +106 -106
- package/_site/_test/prompt-settings-test.js +115 -115
- package/_site/_test/protected-architecture-gate-test.js +122 -122
- package/_site/_test/refactor-characterization-test.js +36 -36
- package/_site/_test/release-version-sync-test.js +1 -1
- package/_site/_test/requirement-recorder-test.js +173 -173
- package/_site/_test/run-all-tests.js +159 -156
- package/_site/_test/shared-contracts-test.js +58 -58
- package/_site/_test/startup-analysis-disabled-test.js +10 -10
- package/_site/_test/storage-foundation-test.js +78 -78
- package/_site/_test/structured-logger-test.js +101 -101
- package/_site/_test/tracking-start-test.js +109 -108
- package/_site/_test/workbench-permission-test.js +117 -117
- package/_site/_test/workspace-ui-contract-test.js +28 -43
- package/_site/lib/ai-profile-resolver.js +78 -78
- package/_site/lib/ai-workspace.js +101 -101
- package/_site/lib/automation-config.js +140 -140
- package/_site/lib/bridge-adapter.js +1 -0
- package/_site/lib/bridge-consumer-service.js +402 -402
- package/_site/lib/claude-cli-runner.js +1510 -1510
- package/_site/lib/commit-conversation-binder.js +234 -234
- package/_site/lib/commit-processing-ledger.js +27 -27
- package/_site/lib/commit-prompt.js +202 -202
- package/_site/lib/commit-reconciler.js +406 -406
- package/_site/lib/contracts.js +284 -279
- package/_site/lib/conversation-query-service.js +144 -144
- package/_site/lib/conversation-store.js +385 -385
- package/_site/lib/data-dir.js +6 -74
- package/_site/lib/engine-connection.js +67 -0
- package/_site/lib/evidence-bundle.js +228 -228
- package/_site/lib/folder-picker-output.js +21 -21
- package/_site/lib/git-runner.js +62 -62
- package/_site/lib/github-team-store.js +1172 -1172
- package/_site/lib/hook-manager.js +203 -202
- package/_site/lib/index-service.js +173 -173
- package/_site/lib/integration-installer.js +908 -907
- package/_site/lib/kb-framework.js +176 -176
- package/_site/lib/kb-validator.js +124 -124
- package/_site/lib/knowledge-promotion.js +435 -435
- package/_site/lib/knowledge-retrieval-service.js +401 -401
- package/_site/lib/knowledge-tool-runtime.js +359 -359
- package/_site/lib/llm-client.js +161 -161
- package/_site/lib/markdown-knowledge-indexer.js +230 -230
- package/_site/lib/module-bridge.js +191 -36
- package/_site/lib/post-commit-automation.js +87 -87
- package/_site/lib/product-data.js +24 -0
- package/_site/lib/project-lifecycle-service.js +535 -497
- package/_site/lib/project-store.js +268 -262
- package/_site/lib/requirement-recorder.js +278 -278
- package/_site/lib/runtime-endpoint.js +155 -155
- package/_site/lib/scanner.js +298 -298
- package/_site/lib/server-app.js +1579 -1520
- package/_site/lib/settings-store.js +133 -113
- package/_site/lib/storage-layout.js +162 -162
- package/_site/lib/structured-logger.js +574 -574
- package/_site/scripts/folder-picker.ps1 +156 -156
- package/_site/scripts/hook-trigger.js +157 -156
- package/_site/scripts/install-module-candidates.js +69 -0
- package/_site/scripts/pack-module-candidates.js +72 -0
- package/_site/scripts/sync-release-version.js +2 -2
- package/_site/scripts/vendor-modules.js +47 -0
- package/_site/scripts/verify-module-runtime.js +45 -0
- package/_site/scripts/verify-product-runtime.js +34 -0
- package/bin/project-knowledge-mcp.js +194 -194
- package/docs/README.zh-CN.md +42 -29
- package/docs/fresh-v5-start.md +28 -0
- package/docs/project-registry-schema.md +22 -22
- package/docs/testing-strategy.md +33 -33
- package/module-runtime-manifest.json +220 -0
- package/package.json +14 -9
- 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/opencode/project-knowledge.md +3 -3
- package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
- package/templates/project-readme.md +34 -34
- package/ui/favicon.svg +38 -38
- package/ui/index.html +52 -149
- package/ui/product.css +9 -0
- package/ui/product.js +412 -0
- package/vendor-manifest.json +45 -0
- package/_site/_test/data-dir-migration-test.js +0 -77
- package/_site/_test/import-ui-flow-test.js +0 -171
- package/_site/_test/knowledge-migration-test.js +0 -75
- package/_site/_test/legacy-forward-compat-test.js +0 -257
- package/_site/_test/legacy-project-upgrade-e2e-test.js +0 -363
- package/_site/_test/p0-data-migration-characterization-test.js +0 -37
- package/_site/_test/p0-e2e-gate-test.js +0 -347
- package/_site/_test/project-control-panel-task14-test.js +0 -63
- package/_site/_test/project-layout-v2-migration-test.js +0 -127
- package/_site/_test/server-runtime-migration-safety-test.js +0 -27
- package/_site/_test/task15-20-ui-flow-test.js +0 -148
- package/_site/_test/ui-i18n-toggle-test.js +0 -114
- package/_site/_test/ui-smoke-test.js +0 -73
- package/_site/_test/v4122-upgrade-data-contract-test.js +0 -56
- package/_site/lib/data-state-classifier.js +0 -40
- package/_site/lib/legacy-data-manifest.js +0 -26
- package/_site/lib/migration-service.js +0 -442
- package/ui/app.css +0 -58
- package/ui/app.js +0 -607
- package/ui/i18n.js +0 -146
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
const assert = require('assert/strict');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const os = require('os');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const { initializeProductData, DATA_SCHEMA } = require('../lib/product-data');
|
|
6
|
+
const { resolveDataDirPath } = require('../lib/data-dir');
|
|
7
|
+
const { connectEngine } = require('../lib/engine-connection');
|
|
8
|
+
|
|
9
|
+
(async () => {
|
|
10
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-fresh-product-'));
|
|
11
|
+
assert.equal(resolveDataDirPath({ dataDir: '', homeDir: root }), path.join(root, '.project-knowledge-v5'));
|
|
12
|
+
const old = path.join(root, 'old'); fs.mkdirSync(old);
|
|
13
|
+
const bytes = JSON.stringify({ projects: ['old-project'], activeClaim: 'old-claim' });
|
|
14
|
+
fs.writeFileSync(path.join(old, 'projects.json'), bytes);
|
|
15
|
+
assert.throws(() => initializeProductData(old), { code: 'SCHEMA_UNSUPPORTED' });
|
|
16
|
+
assert.equal(fs.readFileSync(path.join(old, 'projects.json'), 'utf8'), bytes);
|
|
17
|
+
const fresh = path.join(root, 'fresh'); initializeProductData(fresh); initializeProductData(fresh);
|
|
18
|
+
assert.equal(JSON.parse(fs.readFileSync(path.join(fresh, 'product-data.json'))).schema, DATA_SCHEMA);
|
|
19
|
+
const paths = [];
|
|
20
|
+
let activationStatus = 403;
|
|
21
|
+
const logs = [];
|
|
22
|
+
const runtime = {
|
|
23
|
+
analysisOwner: 'engine', registryStore: { listIds: () => [] }, logger: { warn: async (...args) => logs.push(args) },
|
|
24
|
+
moduleBridge: { engineUrl: 'http://engine.invalid', runtimeToken: 'private-local-token', syncEngineConfiguration: async () => {}, _fetch: async url => {
|
|
25
|
+
paths.push(url);
|
|
26
|
+
if (url.endsWith('/api/health')) return { ok: true, status: 200, json: async () => ({ name: 'knowledge-engine', version: '0.2.0', dataSchemaVersion: 3 }) };
|
|
27
|
+
if (url.endsWith('/api/runtime-auth')) return { ok: true, status: 200 };
|
|
28
|
+
return { ok: activationStatus === 200, status: activationStatus };
|
|
29
|
+
} },
|
|
30
|
+
};
|
|
31
|
+
await connectEngine(runtime);
|
|
32
|
+
assert.equal(runtime.ownership.ready, false);
|
|
33
|
+
assert.equal(runtime.ownership.error.code, 'RUNTIME_AUTH_REQUIRED');
|
|
34
|
+
assert.equal(runtime.ownership.error.step, 'engine-activation');
|
|
35
|
+
assert.ok(!JSON.stringify(logs).includes('private-local-token'));
|
|
36
|
+
assert.ok(paths.every(url => !url.includes('migrate')));
|
|
37
|
+
await connectEngine(runtime);
|
|
38
|
+
assert.equal(logs.length, 1, 'identical connection failures are not repeatedly logged');
|
|
39
|
+
activationStatus = 200; await connectEngine(runtime);
|
|
40
|
+
assert.deepEqual(runtime.ownership, { owner: 'engine', ready: true });
|
|
41
|
+
console.log('PASS fresh data isolation, legacy rejection, precise connection failure, recovery without migration');
|
|
42
|
+
})().catch(error => { console.error(error); process.exitCode = 1; });
|
|
@@ -1,165 +1,165 @@
|
|
|
1
|
-
const assert = require('assert');
|
|
2
|
-
const fs = require('fs');
|
|
3
|
-
const os = require('os');
|
|
4
|
-
const path = require('path');
|
|
5
|
-
const { spawnSync } = require('child_process');
|
|
6
|
-
const { spawnServer } = require('./helpers/spawn-server');
|
|
7
|
-
const { StorageLayout } = require('../lib/storage-layout');
|
|
8
|
-
const { ProjectRegistryStore } = require('../lib/project-registry-store');
|
|
9
|
-
const { ProjectStore } = require('../lib/project-store');
|
|
10
|
-
const { RequirementRecorder } = require('../lib/requirement-recorder');
|
|
11
|
-
|
|
12
|
-
const ROOT = path.resolve(__dirname, '..', '..');
|
|
13
|
-
const PORT = Number(process.env.KB_FULL_E2E_PORT || 7942);
|
|
14
|
-
const BASE_URL = `http://127.0.0.1:${PORT}`;
|
|
15
|
-
const TEMP = fs.mkdtempSync(path.join(os.tmpdir(), `project-knowledge-e2e-${process.pid}-`));
|
|
16
|
-
const DATA_DIR = path.join(TEMP, 'data');
|
|
17
|
-
const REPO = path.join(TEMP, 'repo with 空格');
|
|
18
|
-
const PROJECT_ID = 'project-full-e2e';
|
|
19
|
-
// Git commits fire the managed hook -> hook-trigger -> Bridge journal.
|
|
20
|
-
// Keep that journal inside the test sandbox, never the developer's home.
|
|
21
|
-
const BRIDGE_HOME = path.join(TEMP, 'bridge-home');
|
|
22
|
-
|
|
23
|
-
function git(args, allowFailure = false) {
|
|
24
|
-
const result = spawnSync('git', ['-C', REPO, ...args], {
|
|
25
|
-
encoding: 'utf8', windowsHide: true,
|
|
26
|
-
env: { ...process.env, KB_DATA_DIR: DATA_DIR, KB_SITE_PORT: String(PORT), AI_CODING_EVENT_BRIDGE_HOME: BRIDGE_HOME },
|
|
27
|
-
});
|
|
28
|
-
if (!allowFailure) assert.strictEqual(result.status, 0, result.stderr || result.stdout);
|
|
29
|
-
return { status: result.status, stdout: String(result.stdout || '').trim(), stderr: String(result.stderr || '').trim() };
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function commit(name, content) {
|
|
33
|
-
fs.writeFileSync(path.join(REPO, `${name}.txt`), `${content}\n`, 'utf8');
|
|
34
|
-
git(['add', `${name}.txt`]);
|
|
35
|
-
git(['commit', '-m', name]);
|
|
36
|
-
return git(['rev-parse', 'HEAD']).stdout;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
async function json(method, route, body) {
|
|
40
|
-
const response = await fetch(`${BASE_URL}${route}`, {
|
|
41
|
-
method,
|
|
42
|
-
headers: body ? { 'Content-Type': 'application/json' } : undefined,
|
|
43
|
-
body: body ? JSON.stringify(body) : undefined,
|
|
44
|
-
});
|
|
45
|
-
const text = await response.text();
|
|
46
|
-
return { response, body: text ? JSON.parse(text) : {} };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
async function start() {
|
|
50
|
-
const spawned = spawnServer({
|
|
51
|
-
root: ROOT, port: PORT, dataDir: DATA_DIR, tag: 'full-e2e',
|
|
52
|
-
extraEnv: {
|
|
53
|
-
KB_AUTOMATION_FAKE_CLAUDE: '1', KB_EMBEDDING_FAKE: '1', KB_MAINTENANCE_INTERVAL_MS: '600000',
|
|
54
|
-
AI_CODING_EVENT_BRIDGE_HOME: BRIDGE_HOME,
|
|
55
|
-
},
|
|
56
|
-
});
|
|
57
|
-
let output = '';
|
|
58
|
-
spawned.child.stdout.on('data', chunk => { output += chunk; });
|
|
59
|
-
spawned.child.stderr.on('data', chunk => { output += chunk; });
|
|
60
|
-
for (let attempt = 0; attempt < 150; attempt += 1) {
|
|
61
|
-
try { if ((await fetch(`${BASE_URL}/api/health`)).ok) return { ...spawned, output: () => output }; } catch {}
|
|
62
|
-
if (spawned.child.exitCode != null) throw new Error(`server exited during startup (${spawned.child.exitCode})\n${output}`);
|
|
63
|
-
await new Promise(resolve => setTimeout(resolve, 100));
|
|
64
|
-
}
|
|
65
|
-
throw new Error(`server did not start\n${output}`);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
async function stop(spawned) {
|
|
69
|
-
if (!spawned || spawned.child.exitCode != null) return;
|
|
70
|
-
const exited = new Promise(resolve => spawned.child.once('exit', resolve));
|
|
71
|
-
spawned.child.kill();
|
|
72
|
-
await Promise.race([exited, new Promise(resolve => setTimeout(resolve, 5000))]);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
async function waitForState(predicate, label) {
|
|
76
|
-
let last;
|
|
77
|
-
for (let attempt = 0; attempt < 250; attempt += 1) {
|
|
78
|
-
const result = await json('GET', `/api/projects/${PROJECT_ID}`);
|
|
79
|
-
if (result.response.ok) {
|
|
80
|
-
last = result.body.project.state;
|
|
81
|
-
if (predicate(last)) return last;
|
|
82
|
-
}
|
|
83
|
-
await new Promise(resolve => setTimeout(resolve, 100));
|
|
84
|
-
}
|
|
85
|
-
throw new Error(`${label} timed out: ${JSON.stringify(last)}`);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
(async () => {
|
|
89
|
-
let server;
|
|
90
|
-
fs.mkdirSync(REPO, { recursive: true });
|
|
91
|
-
git(['init', '--initial-branch=main']);
|
|
92
|
-
git(['config', 'user.name', 'Full E2E']);
|
|
93
|
-
git(['config', 'user.email', 'e2e@example.test']);
|
|
94
|
-
commit('baseline', 'baseline before import');
|
|
95
|
-
try {
|
|
96
|
-
server = await start();
|
|
97
|
-
let result = await json('PATCH', '/api/settings', { knowledge: { rootPath: path.join(TEMP, '用户知识') } });
|
|
98
|
-
assert(result.response.ok, JSON.stringify(result.body));
|
|
99
|
-
result = await json('PUT', '/api/ai-profiles', {
|
|
100
|
-
schema: 'ai-profiles/v1',
|
|
101
|
-
defaultProfileId: 'fake-profile',
|
|
102
|
-
profiles: [{ id: 'fake-profile', name: 'Fake', enabled: true, vendor: 'anthropic', model: 'fake', apiKeyUpdate: { mode: 'replace', value: 'fake-key-for-test' } }],
|
|
103
|
-
});
|
|
104
|
-
assert(result.response.ok, JSON.stringify(result.body));
|
|
105
|
-
result = await json('POST', '/api/projects/import', {
|
|
106
|
-
projectId: PROJECT_ID, localPath: REPO, displayName: 'Full E2E', aiProfileId: 'fake-profile', knowledgeLanguage: 'en-US',
|
|
107
|
-
});
|
|
108
|
-
assert.strictEqual(result.response.status, 201, `${JSON.stringify(result.body)}\n${server.output()}`);
|
|
109
|
-
const knowledgePath = result.body.config.knowledgePath;
|
|
110
|
-
assert.deepStrictEqual(fs.readdirSync(knowledgePath), [], 'import must not run AI or generate knowledge');
|
|
111
|
-
assert.strictEqual(result.body.state.lastAnalyzedCommit, null);
|
|
112
|
-
assert.strictEqual(result.body.project.state.hook.managedVersion, 2);
|
|
113
|
-
|
|
114
|
-
const layout = new StorageLayout({ dataDir: DATA_DIR });
|
|
115
|
-
const recorder = new RequirementRecorder({
|
|
116
|
-
layout,
|
|
117
|
-
registryStore: new ProjectRegistryStore({ layout }),
|
|
118
|
-
projectStore: new ProjectStore({ layout }),
|
|
119
|
-
});
|
|
120
|
-
const requirement = await recorder.recordRequirement({
|
|
121
|
-
projectId: PROJECT_ID, repoPath: REPO, client: 'codex', sessionId: 'full-e2e-session',
|
|
122
|
-
text: 'Record the actual post-commit behavior and keep Markdown as the source of truth.',
|
|
123
|
-
});
|
|
124
|
-
assert(requirement.id && fs.existsSync(layout.getProjectConversationEventsPath(PROJECT_ID)));
|
|
125
|
-
assert.strictEqual(fs.existsSync(layout.getProjectRequirementsPath(PROJECT_ID)), false);
|
|
126
|
-
|
|
127
|
-
const onlineCommit = commit('online-change', 'online hook evidence');
|
|
128
|
-
let state = await waitForState(current => current.lastAnalyzedCommit === onlineCommit && current.index.dirty === false, 'online Hook reconciliation');
|
|
129
|
-
assert.strictEqual(state.analysis.activeClaim, null);
|
|
130
|
-
assert(fs.existsSync(path.join(knowledgePath, 'changes', `${onlineCommit.slice(0, 12)}.md`)));
|
|
131
|
-
result = await json('POST', '/api/knowledge/search', { projectId: PROJECT_ID, query: onlineCommit.slice(0, 12), limit: 5 });
|
|
132
|
-
assert(result.response.ok && result.body.results.length > 0, JSON.stringify(result.body));
|
|
133
|
-
|
|
134
|
-
result = await json('GET', `/api/logs?projectId=${PROJECT_ID}&pageSize=500`);
|
|
135
|
-
const onlineEvents = result.body.entries.map(entry => entry.event);
|
|
136
|
-
for (const event of ['reconcile.claim_prepared', 'knowledge.promotion_completed', 'reconcile.commit_completed', 'index.project_applied']) {
|
|
137
|
-
assert(onlineEvents.includes(event), `missing online operation event: ${event}`);
|
|
138
|
-
}
|
|
139
|
-
assert.strictEqual(result.body.entries.filter(entry => entry.event === 'reconcile.claim_prepared' && entry.commitSha === onlineCommit).length, 1, 'Hook/startup overlap must not duplicate one Commit');
|
|
140
|
-
|
|
141
|
-
await stop(server);
|
|
142
|
-
server = null;
|
|
143
|
-
const offlineOne = commit('offline-one', 'first offline change');
|
|
144
|
-
const offlineTwo = commit('offline-two', 'second offline change');
|
|
145
|
-
assert.notStrictEqual(offlineOne, offlineTwo);
|
|
146
|
-
server = await start();
|
|
147
|
-
await new Promise(resolve => setTimeout(resolve, 500));
|
|
148
|
-
result = await json('GET', `/api/projects/${PROJECT_ID}`);
|
|
149
|
-
state = result.body.project.state;
|
|
150
|
-
assert.strictEqual(state.lastAnalyzedCommit, onlineCommit, 'restart must not analyze offline commits');
|
|
151
|
-
assert.strictEqual(fs.existsSync(path.join(knowledgePath, 'changes', `${offlineOne.slice(0, 12)}.md`)), false);
|
|
152
|
-
assert.strictEqual(fs.existsSync(path.join(knowledgePath, 'changes', `${offlineTwo.slice(0, 12)}.md`)), false);
|
|
153
|
-
const onlineAfterRestart = commit('online-after-restart', 'explicit hook after offline commits');
|
|
154
|
-
state = await waitForState(current => current.lastAnalyzedCommit === onlineAfterRestart && current.index.dirty === false, 'explicit online Hook after restart');
|
|
155
|
-
assert.strictEqual(state.analysis.activeClaim, null);
|
|
156
|
-
assert(fs.existsSync(path.join(knowledgePath, 'changes', `${onlineAfterRestart.slice(0, 12)}.md`)));
|
|
157
|
-
result = await json('GET', `/api/logs?projectId=${PROJECT_ID}&pageSize=500`);
|
|
158
|
-
assert.strictEqual(result.body.entries.filter(entry => entry.event === 'reconcile.commit_completed' && entry.commitSha === offlineOne).length, 0);
|
|
159
|
-
assert.strictEqual(result.body.entries.filter(entry => entry.event === 'reconcile.commit_completed' && entry.commitSha === offlineTwo).length, 0);
|
|
160
|
-
assert.strictEqual(result.body.entries.filter(entry => entry.event === 'reconcile.commit_completed' && entry.commitSha === onlineAfterRestart).length, 1);
|
|
161
|
-
console.log('full-integration-e2e-test PASS');
|
|
162
|
-
} finally {
|
|
163
|
-
await stop(server);
|
|
164
|
-
}
|
|
165
|
-
})().catch(error => { console.error(error.stack || error); process.exitCode = 1; });
|
|
1
|
+
const assert = require('assert');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const os = require('os');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const { spawnSync } = require('child_process');
|
|
6
|
+
const { spawnServer } = require('./helpers/spawn-server');
|
|
7
|
+
const { StorageLayout } = require('../lib/storage-layout');
|
|
8
|
+
const { ProjectRegistryStore } = require('../lib/project-registry-store');
|
|
9
|
+
const { ProjectStore } = require('../lib/project-store');
|
|
10
|
+
const { RequirementRecorder } = require('../lib/requirement-recorder');
|
|
11
|
+
|
|
12
|
+
const ROOT = path.resolve(__dirname, '..', '..');
|
|
13
|
+
const PORT = Number(process.env.KB_FULL_E2E_PORT || 7942);
|
|
14
|
+
const BASE_URL = `http://127.0.0.1:${PORT}`;
|
|
15
|
+
const TEMP = fs.mkdtempSync(path.join(os.tmpdir(), `project-knowledge-e2e-${process.pid}-`));
|
|
16
|
+
const DATA_DIR = path.join(TEMP, 'data');
|
|
17
|
+
const REPO = path.join(TEMP, 'repo with 空格');
|
|
18
|
+
const PROJECT_ID = 'project-full-e2e';
|
|
19
|
+
// Git commits fire the managed hook -> hook-trigger -> Bridge journal.
|
|
20
|
+
// Keep that journal inside the test sandbox, never the developer's home.
|
|
21
|
+
const BRIDGE_HOME = path.join(TEMP, 'bridge-home');
|
|
22
|
+
|
|
23
|
+
function git(args, allowFailure = false) {
|
|
24
|
+
const result = spawnSync('git', ['-C', REPO, ...args], {
|
|
25
|
+
encoding: 'utf8', windowsHide: true,
|
|
26
|
+
env: { ...process.env, KB_DATA_DIR: DATA_DIR, KB_SITE_PORT: String(PORT), AI_CODING_EVENT_BRIDGE_HOME: BRIDGE_HOME },
|
|
27
|
+
});
|
|
28
|
+
if (!allowFailure) assert.strictEqual(result.status, 0, result.stderr || result.stdout);
|
|
29
|
+
return { status: result.status, stdout: String(result.stdout || '').trim(), stderr: String(result.stderr || '').trim() };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function commit(name, content) {
|
|
33
|
+
fs.writeFileSync(path.join(REPO, `${name}.txt`), `${content}\n`, 'utf8');
|
|
34
|
+
git(['add', `${name}.txt`]);
|
|
35
|
+
git(['commit', '-m', name]);
|
|
36
|
+
return git(['rev-parse', 'HEAD']).stdout;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function json(method, route, body) {
|
|
40
|
+
const response = await fetch(`${BASE_URL}${route}`, {
|
|
41
|
+
method,
|
|
42
|
+
headers: body ? { 'Content-Type': 'application/json' } : undefined,
|
|
43
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
44
|
+
});
|
|
45
|
+
const text = await response.text();
|
|
46
|
+
return { response, body: text ? JSON.parse(text) : {} };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function start() {
|
|
50
|
+
const spawned = spawnServer({
|
|
51
|
+
root: ROOT, port: PORT, dataDir: DATA_DIR, tag: 'full-e2e',
|
|
52
|
+
extraEnv: {
|
|
53
|
+
KB_AUTOMATION_FAKE_CLAUDE: '1', KB_EMBEDDING_FAKE: '1', KB_MAINTENANCE_INTERVAL_MS: '600000',
|
|
54
|
+
AI_CODING_EVENT_BRIDGE_HOME: BRIDGE_HOME,
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
let output = '';
|
|
58
|
+
spawned.child.stdout.on('data', chunk => { output += chunk; });
|
|
59
|
+
spawned.child.stderr.on('data', chunk => { output += chunk; });
|
|
60
|
+
for (let attempt = 0; attempt < 150; attempt += 1) {
|
|
61
|
+
try { if ((await fetch(`${BASE_URL}/api/health`)).ok) return { ...spawned, output: () => output }; } catch {}
|
|
62
|
+
if (spawned.child.exitCode != null) throw new Error(`server exited during startup (${spawned.child.exitCode})\n${output}`);
|
|
63
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
64
|
+
}
|
|
65
|
+
throw new Error(`server did not start\n${output}`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function stop(spawned) {
|
|
69
|
+
if (!spawned || spawned.child.exitCode != null) return;
|
|
70
|
+
const exited = new Promise(resolve => spawned.child.once('exit', resolve));
|
|
71
|
+
spawned.child.kill();
|
|
72
|
+
await Promise.race([exited, new Promise(resolve => setTimeout(resolve, 5000))]);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function waitForState(predicate, label) {
|
|
76
|
+
let last;
|
|
77
|
+
for (let attempt = 0; attempt < 250; attempt += 1) {
|
|
78
|
+
const result = await json('GET', `/api/projects/${PROJECT_ID}`);
|
|
79
|
+
if (result.response.ok) {
|
|
80
|
+
last = result.body.project.state;
|
|
81
|
+
if (predicate(last)) return last;
|
|
82
|
+
}
|
|
83
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
84
|
+
}
|
|
85
|
+
throw new Error(`${label} timed out: ${JSON.stringify(last)}`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
(async () => {
|
|
89
|
+
let server;
|
|
90
|
+
fs.mkdirSync(REPO, { recursive: true });
|
|
91
|
+
git(['init', '--initial-branch=main']);
|
|
92
|
+
git(['config', 'user.name', 'Full E2E']);
|
|
93
|
+
git(['config', 'user.email', 'e2e@example.test']);
|
|
94
|
+
commit('baseline', 'baseline before import');
|
|
95
|
+
try {
|
|
96
|
+
server = await start();
|
|
97
|
+
let result = await json('PATCH', '/api/settings', { knowledge: { rootPath: path.join(TEMP, '用户知识') } });
|
|
98
|
+
assert(result.response.ok, JSON.stringify(result.body));
|
|
99
|
+
result = await json('PUT', '/api/ai-profiles', {
|
|
100
|
+
schema: 'ai-profiles/v1',
|
|
101
|
+
defaultProfileId: 'fake-profile',
|
|
102
|
+
profiles: [{ id: 'fake-profile', name: 'Fake', enabled: true, vendor: 'anthropic', model: 'fake', apiKeyUpdate: { mode: 'replace', value: 'fake-key-for-test' } }],
|
|
103
|
+
});
|
|
104
|
+
assert(result.response.ok, JSON.stringify(result.body));
|
|
105
|
+
result = await json('POST', '/api/projects/import', {
|
|
106
|
+
projectId: PROJECT_ID, localPath: REPO, displayName: 'Full E2E', aiProfileId: 'fake-profile', knowledgeLanguage: 'en-US',
|
|
107
|
+
});
|
|
108
|
+
assert.strictEqual(result.response.status, 201, `${JSON.stringify(result.body)}\n${server.output()}`);
|
|
109
|
+
const knowledgePath = result.body.config.knowledgePath;
|
|
110
|
+
assert.deepStrictEqual(fs.readdirSync(knowledgePath), [], 'import must not run AI or generate knowledge');
|
|
111
|
+
assert.strictEqual(result.body.state.lastAnalyzedCommit, null);
|
|
112
|
+
assert.strictEqual(result.body.project.state.hook.managedVersion, 2);
|
|
113
|
+
|
|
114
|
+
const layout = new StorageLayout({ dataDir: DATA_DIR });
|
|
115
|
+
const recorder = new RequirementRecorder({
|
|
116
|
+
layout,
|
|
117
|
+
registryStore: new ProjectRegistryStore({ layout }),
|
|
118
|
+
projectStore: new ProjectStore({ layout }),
|
|
119
|
+
});
|
|
120
|
+
const requirement = await recorder.recordRequirement({
|
|
121
|
+
projectId: PROJECT_ID, repoPath: REPO, client: 'codex', sessionId: 'full-e2e-session',
|
|
122
|
+
text: 'Record the actual post-commit behavior and keep Markdown as the source of truth.',
|
|
123
|
+
});
|
|
124
|
+
assert(requirement.id && fs.existsSync(layout.getProjectConversationEventsPath(PROJECT_ID)));
|
|
125
|
+
assert.strictEqual(fs.existsSync(layout.getProjectRequirementsPath(PROJECT_ID)), false);
|
|
126
|
+
|
|
127
|
+
const onlineCommit = commit('online-change', 'online hook evidence');
|
|
128
|
+
let state = await waitForState(current => current.lastAnalyzedCommit === onlineCommit && current.index.dirty === false, 'online Hook reconciliation');
|
|
129
|
+
assert.strictEqual(state.analysis.activeClaim, null);
|
|
130
|
+
assert(fs.existsSync(path.join(knowledgePath, 'changes', `${onlineCommit.slice(0, 12)}.md`)));
|
|
131
|
+
result = await json('POST', '/api/knowledge/search', { projectId: PROJECT_ID, query: onlineCommit.slice(0, 12), limit: 5 });
|
|
132
|
+
assert(result.response.ok && result.body.results.length > 0, JSON.stringify(result.body));
|
|
133
|
+
|
|
134
|
+
result = await json('GET', `/api/logs?projectId=${PROJECT_ID}&pageSize=500`);
|
|
135
|
+
const onlineEvents = result.body.entries.map(entry => entry.event);
|
|
136
|
+
for (const event of ['reconcile.claim_prepared', 'knowledge.promotion_completed', 'reconcile.commit_completed', 'index.project_applied']) {
|
|
137
|
+
assert(onlineEvents.includes(event), `missing online operation event: ${event}`);
|
|
138
|
+
}
|
|
139
|
+
assert.strictEqual(result.body.entries.filter(entry => entry.event === 'reconcile.claim_prepared' && entry.commitSha === onlineCommit).length, 1, 'Hook/startup overlap must not duplicate one Commit');
|
|
140
|
+
|
|
141
|
+
await stop(server);
|
|
142
|
+
server = null;
|
|
143
|
+
const offlineOne = commit('offline-one', 'first offline change');
|
|
144
|
+
const offlineTwo = commit('offline-two', 'second offline change');
|
|
145
|
+
assert.notStrictEqual(offlineOne, offlineTwo);
|
|
146
|
+
server = await start();
|
|
147
|
+
await new Promise(resolve => setTimeout(resolve, 500));
|
|
148
|
+
result = await json('GET', `/api/projects/${PROJECT_ID}`);
|
|
149
|
+
state = result.body.project.state;
|
|
150
|
+
assert.strictEqual(state.lastAnalyzedCommit, onlineCommit, 'restart must not analyze offline commits');
|
|
151
|
+
assert.strictEqual(fs.existsSync(path.join(knowledgePath, 'changes', `${offlineOne.slice(0, 12)}.md`)), false);
|
|
152
|
+
assert.strictEqual(fs.existsSync(path.join(knowledgePath, 'changes', `${offlineTwo.slice(0, 12)}.md`)), false);
|
|
153
|
+
const onlineAfterRestart = commit('online-after-restart', 'explicit hook after offline commits');
|
|
154
|
+
state = await waitForState(current => current.lastAnalyzedCommit === onlineAfterRestart && current.index.dirty === false, 'explicit online Hook after restart');
|
|
155
|
+
assert.strictEqual(state.analysis.activeClaim, null);
|
|
156
|
+
assert(fs.existsSync(path.join(knowledgePath, 'changes', `${onlineAfterRestart.slice(0, 12)}.md`)));
|
|
157
|
+
result = await json('GET', `/api/logs?projectId=${PROJECT_ID}&pageSize=500`);
|
|
158
|
+
assert.strictEqual(result.body.entries.filter(entry => entry.event === 'reconcile.commit_completed' && entry.commitSha === offlineOne).length, 0);
|
|
159
|
+
assert.strictEqual(result.body.entries.filter(entry => entry.event === 'reconcile.commit_completed' && entry.commitSha === offlineTwo).length, 0);
|
|
160
|
+
assert.strictEqual(result.body.entries.filter(entry => entry.event === 'reconcile.commit_completed' && entry.commitSha === onlineAfterRestart).length, 1);
|
|
161
|
+
console.log('full-integration-e2e-test PASS');
|
|
162
|
+
} finally {
|
|
163
|
+
await stop(server);
|
|
164
|
+
}
|
|
165
|
+
})().catch(error => { console.error(error.stack || error); process.exitCode = 1; });
|
|
@@ -32,7 +32,7 @@ async function json(method, route, body) {
|
|
|
32
32
|
|
|
33
33
|
(async () => {
|
|
34
34
|
const repo = makeRepo({ kind: 'one-commit' });
|
|
35
|
-
const spawned = spawnServer({ root: ROOT, port: PORT, dataDir: DATA_DIR, tag: 'git-validation' });
|
|
35
|
+
const spawned = spawnServer({ root: ROOT, port: PORT, dataDir: DATA_DIR, tag: 'git-validation', extraEnv: { KB_AUTOMATION_FAKE_CLAUDE: '1' } });
|
|
36
36
|
let output = '';
|
|
37
37
|
spawned.child.stdout.on('data', chunk => { output += chunk; });
|
|
38
38
|
spawned.child.stderr.on('data', chunk => { output += chunk; });
|
|
@@ -75,7 +75,7 @@ async function json(method, route, body) {
|
|
|
75
75
|
if (output) process.stderr.write(output);
|
|
76
76
|
throw error;
|
|
77
77
|
} finally {
|
|
78
|
-
spawned.
|
|
78
|
+
await spawned.cleanup();
|
|
79
79
|
repo.cleanup();
|
|
80
80
|
}
|
|
81
81
|
})().catch(error => { console.error(error); process.exitCode = 1; });
|
|
@@ -1,88 +1,88 @@
|
|
|
1
|
-
// Run: node _site/_test/hook-runtime-endpoint-test.js
|
|
2
|
-
|
|
3
|
-
const fs = require('fs');
|
|
4
|
-
const http = require('http');
|
|
5
|
-
const os = require('os');
|
|
6
|
-
const path = require('path');
|
|
7
|
-
const { spawn, spawnSync } = require('child_process');
|
|
8
|
-
const { writeEndpoint } = require('../lib/runtime-endpoint');
|
|
9
|
-
|
|
10
|
-
const ROOT = path.resolve(__dirname, '..', '..');
|
|
11
|
-
const TRIGGER = path.join(ROOT, '_site', 'scripts', 'hook-trigger.js');
|
|
12
|
-
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), `kb-hook-runtime-${process.pid}-`));
|
|
13
|
-
const repo = fs.mkdtempSync(path.join(os.tmpdir(), `kb-hook-runtime-repo-${process.pid}-`));
|
|
14
|
-
|
|
15
|
-
function assert(condition, message) {
|
|
16
|
-
if (!condition) throw new Error(message);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function git(args) {
|
|
20
|
-
return spawnSync('git', ['-C', repo, ...args], { encoding: 'utf-8', windowsHide: true });
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
(async () => {
|
|
24
|
-
git(['init']);
|
|
25
|
-
fs.writeFileSync(path.join(repo, 'README.md'), '# runtime endpoint\n', 'utf-8');
|
|
26
|
-
git(['config', 'user.email', 'runtime@example.test']);
|
|
27
|
-
git(['config', 'user.name', 'Runtime Test']);
|
|
28
|
-
git(['add', 'README.md']);
|
|
29
|
-
git(['commit', '-m', 'test']);
|
|
30
|
-
|
|
31
|
-
let received = null;
|
|
32
|
-
const server = http.createServer((req, res) => {
|
|
33
|
-
let body = '';
|
|
34
|
-
req.setEncoding('utf-8');
|
|
35
|
-
req.on('data', chunk => { body += chunk; });
|
|
36
|
-
req.on('end', () => {
|
|
37
|
-
received = { method: req.method, url: req.url, body: JSON.parse(body) };
|
|
38
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
39
|
-
res.end('{}');
|
|
40
|
-
});
|
|
41
|
-
});
|
|
42
|
-
await new Promise((resolve, reject) => {
|
|
43
|
-
server.once('error', reject);
|
|
44
|
-
server.listen(0, '127.0.0.1', resolve);
|
|
45
|
-
});
|
|
46
|
-
const port = server.address().port;
|
|
47
|
-
writeEndpoint(dataDir, { pid: process.pid, host: '127.0.0.1', port, mode: 'desktop' });
|
|
48
|
-
const bridgeJournal = path.join(dataDir, 'bridge-journal.jsonl');
|
|
49
|
-
const bridgeModule = path.join(dataDir, 'bridge-fixture.cjs');
|
|
50
|
-
fs.writeFileSync(bridgeModule, `const fs = require('fs');\nmodule.exports = {\n appendCommitBoundary(input) {\n fs.appendFileSync(process.env.BRIDGE_TEST_JOURNAL, JSON.stringify(input) + '\\n');\n return { sequence: 17, bridgeCursorAtCommit: 17, openTurnIdsAtCommit: ['turn-runtime'] };\n }\n};\n`);
|
|
51
|
-
|
|
52
|
-
const child = spawn(process.execPath, [
|
|
53
|
-
TRIGGER,
|
|
54
|
-
'--project-id', 'project-runtime',
|
|
55
|
-
'--repo-root', repo,
|
|
56
|
-
'--host', '127.0.0.1',
|
|
57
|
-
'--port', '1',
|
|
58
|
-
], {
|
|
59
|
-
cwd: ROOT,
|
|
60
|
-
windowsHide: true,
|
|
61
|
-
stdio: 'pipe',
|
|
62
|
-
env: { ...process.env, KB_DATA_DIR: dataDir, AI_CODING_EVENT_BRIDGE_MODULE: bridgeModule, BRIDGE_TEST_JOURNAL: bridgeJournal },
|
|
63
|
-
});
|
|
64
|
-
const exitCode = await new Promise(resolve => child.once('exit', resolve));
|
|
65
|
-
assert(exitCode === 0, `hook trigger should exit 0, got ${exitCode}`);
|
|
66
|
-
assert(received, 'hook trigger should use the live runtime endpoint instead of fallback port 1');
|
|
67
|
-
assert(received.method === 'POST' && received.url === '/api/hooks/post-commit', 'unexpected hook request');
|
|
68
|
-
assert(received.body.schema === 'hook-event/v2', 'hook request should use the v2 event schema');
|
|
69
|
-
assert(received.body.projectId === 'project-runtime', 'hook request should contain the stable project id');
|
|
70
|
-
assert(path.resolve(received.body.repoRoot) === path.resolve(repo), 'hook request should contain the runtime repo root');
|
|
71
|
-
assert(received.body.head, 'hook request should contain the current head');
|
|
72
|
-
assert(received.body.branch, 'hook request should contain the current branch');
|
|
73
|
-
assert(received.body.operationId && received.body.operationId.startsWith('op-'), 'Hook boundary operation id should propagate to notification');
|
|
74
|
-
assert(received.body.boundary && received.body.boundary.status === 'captured', 'Hook must append the Bridge boundary before notifying the server');
|
|
75
|
-
assert(received.body.boundary.boundary.bridgeCursorAtCommit === 17, 'Hook must forward the atomic Bridge cursor receipt');
|
|
76
|
-
const durableBoundary = JSON.parse(fs.readFileSync(bridgeJournal, 'utf8').trim());
|
|
77
|
-
assert(durableBoundary.commitSha === received.body.head, 'durable Bridge boundary and Hook payload must reference the same commit');
|
|
78
|
-
|
|
79
|
-
await new Promise(resolve => server.close(resolve));
|
|
80
|
-
fs.rmSync(dataDir, { recursive: true, force: true });
|
|
81
|
-
fs.rmSync(repo, { recursive: true, force: true });
|
|
82
|
-
console.log('hook-runtime-endpoint-test PASS');
|
|
83
|
-
})().catch(error => {
|
|
84
|
-
console.error(error && error.stack || error);
|
|
85
|
-
fs.rmSync(dataDir, { recursive: true, force: true });
|
|
86
|
-
fs.rmSync(repo, { recursive: true, force: true });
|
|
87
|
-
process.exit(1);
|
|
88
|
-
});
|
|
1
|
+
// Run: node _site/_test/hook-runtime-endpoint-test.js
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const http = require('http');
|
|
5
|
+
const os = require('os');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { spawn, spawnSync } = require('child_process');
|
|
8
|
+
const { writeEndpoint } = require('../lib/runtime-endpoint');
|
|
9
|
+
|
|
10
|
+
const ROOT = path.resolve(__dirname, '..', '..');
|
|
11
|
+
const TRIGGER = path.join(ROOT, '_site', 'scripts', 'hook-trigger.js');
|
|
12
|
+
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), `kb-hook-runtime-${process.pid}-`));
|
|
13
|
+
const repo = fs.mkdtempSync(path.join(os.tmpdir(), `kb-hook-runtime-repo-${process.pid}-`));
|
|
14
|
+
|
|
15
|
+
function assert(condition, message) {
|
|
16
|
+
if (!condition) throw new Error(message);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function git(args) {
|
|
20
|
+
return spawnSync('git', ['-C', repo, ...args], { encoding: 'utf-8', windowsHide: true });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
(async () => {
|
|
24
|
+
git(['init']);
|
|
25
|
+
fs.writeFileSync(path.join(repo, 'README.md'), '# runtime endpoint\n', 'utf-8');
|
|
26
|
+
git(['config', 'user.email', 'runtime@example.test']);
|
|
27
|
+
git(['config', 'user.name', 'Runtime Test']);
|
|
28
|
+
git(['add', 'README.md']);
|
|
29
|
+
git(['commit', '-m', 'test']);
|
|
30
|
+
|
|
31
|
+
let received = null;
|
|
32
|
+
const server = http.createServer((req, res) => {
|
|
33
|
+
let body = '';
|
|
34
|
+
req.setEncoding('utf-8');
|
|
35
|
+
req.on('data', chunk => { body += chunk; });
|
|
36
|
+
req.on('end', () => {
|
|
37
|
+
received = { method: req.method, url: req.url, body: JSON.parse(body) };
|
|
38
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
39
|
+
res.end('{}');
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
await new Promise((resolve, reject) => {
|
|
43
|
+
server.once('error', reject);
|
|
44
|
+
server.listen(0, '127.0.0.1', resolve);
|
|
45
|
+
});
|
|
46
|
+
const port = server.address().port;
|
|
47
|
+
writeEndpoint(dataDir, { pid: process.pid, host: '127.0.0.1', port, mode: 'desktop' });
|
|
48
|
+
const bridgeJournal = path.join(dataDir, 'bridge-journal.jsonl');
|
|
49
|
+
const bridgeModule = path.join(dataDir, 'bridge-fixture.cjs');
|
|
50
|
+
fs.writeFileSync(bridgeModule, `const fs = require('fs');\nmodule.exports = {\n appendCommitBoundary(input) {\n fs.appendFileSync(process.env.BRIDGE_TEST_JOURNAL, JSON.stringify(input) + '\\n');\n return { sequence: 17, bridgeCursorAtCommit: 17, openTurnIdsAtCommit: ['turn-runtime'] };\n }\n};\n`);
|
|
51
|
+
|
|
52
|
+
const child = spawn(process.execPath, [
|
|
53
|
+
TRIGGER,
|
|
54
|
+
'--project-id', 'project-runtime',
|
|
55
|
+
'--repo-root', repo,
|
|
56
|
+
'--host', '127.0.0.1',
|
|
57
|
+
'--port', '1',
|
|
58
|
+
], {
|
|
59
|
+
cwd: ROOT,
|
|
60
|
+
windowsHide: true,
|
|
61
|
+
stdio: 'pipe',
|
|
62
|
+
env: { ...process.env, KB_DATA_DIR: dataDir, AI_CODING_EVENT_BRIDGE_MODULE: bridgeModule, BRIDGE_TEST_JOURNAL: bridgeJournal },
|
|
63
|
+
});
|
|
64
|
+
const exitCode = await new Promise(resolve => child.once('exit', resolve));
|
|
65
|
+
assert(exitCode === 0, `hook trigger should exit 0, got ${exitCode}`);
|
|
66
|
+
assert(received, 'hook trigger should use the live runtime endpoint instead of fallback port 1');
|
|
67
|
+
assert(received.method === 'POST' && received.url === '/api/hooks/post-commit', 'unexpected hook request');
|
|
68
|
+
assert(received.body.schema === 'hook-event/v2', 'hook request should use the v2 event schema');
|
|
69
|
+
assert(received.body.projectId === 'project-runtime', 'hook request should contain the stable project id');
|
|
70
|
+
assert(path.resolve(received.body.repoRoot) === path.resolve(repo), 'hook request should contain the runtime repo root');
|
|
71
|
+
assert(received.body.head, 'hook request should contain the current head');
|
|
72
|
+
assert(received.body.branch, 'hook request should contain the current branch');
|
|
73
|
+
assert(received.body.operationId && received.body.operationId.startsWith('op-'), 'Hook boundary operation id should propagate to notification');
|
|
74
|
+
assert(received.body.boundary && received.body.boundary.status === 'captured', 'Hook must append the Bridge boundary before notifying the server');
|
|
75
|
+
assert(received.body.boundary.boundary.bridgeCursorAtCommit === 17, 'Hook must forward the atomic Bridge cursor receipt');
|
|
76
|
+
const durableBoundary = JSON.parse(fs.readFileSync(bridgeJournal, 'utf8').trim());
|
|
77
|
+
assert(durableBoundary.commitSha === received.body.head, 'durable Bridge boundary and Hook payload must reference the same commit');
|
|
78
|
+
|
|
79
|
+
await new Promise(resolve => server.close(resolve));
|
|
80
|
+
fs.rmSync(dataDir, { recursive: true, force: true });
|
|
81
|
+
fs.rmSync(repo, { recursive: true, force: true });
|
|
82
|
+
console.log('hook-runtime-endpoint-test PASS');
|
|
83
|
+
})().catch(error => {
|
|
84
|
+
console.error(error && error.stack || error);
|
|
85
|
+
fs.rmSync(dataDir, { recursive: true, force: true });
|
|
86
|
+
fs.rmSync(repo, { recursive: true, force: true });
|
|
87
|
+
process.exit(1);
|
|
88
|
+
});
|