@sanqianx/project-knowledge 5.0.19 → 5.0.20-rc.1
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 +3 -3
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +5 -0
- package/LICENSE +201 -201
- package/NOTICE +5 -5
- package/README.md +349 -349
- package/_modules/knowledge-engine/README.md +4 -0
- package/_modules/knowledge-engine/src/analysis-failures.js +39 -0
- package/_modules/knowledge-engine/src/analysis-worker.js +6 -2
- package/_modules/knowledge-engine/src/coordinator.js +7 -0
- package/_modules/knowledge-engine/src/headless-analyzer.js +2 -1
- package/_modules/knowledge-engine/src/server.js +1 -1
- package/_site/_test/agent-capture-mcp-ui-test.js +67 -67
- package/_site/_test/ai-profile-test.js +75 -75
- package/_site/_test/ai-vendor-presets-test.js +91 -91
- package/_site/_test/automatic-context-test.js +70 -70
- package/_site/_test/bin-cli-test.js +230 -230
- package/_site/_test/bridge-adapter-test.js +95 -95
- package/_site/_test/bridge-consumer-service-test.js +310 -310
- package/_site/_test/candidate-bin-content-test.js +35 -35
- package/_site/_test/candidate-product-assets-test.js +13 -13
- package/_site/_test/candidate-release-contract-test.js +14 -14
- package/_site/_test/capture-hook-dedup-test.js +158 -158
- package/_site/_test/claude-executable-discovery-test.js +28 -28
- package/_site/_test/claude-session-lifecycle-sweep-test.js +252 -252
- package/_site/_test/cli-instance-management-test.js +62 -62
- package/_site/_test/client-capture-restart-e2e-test.js +189 -189
- package/_site/_test/codex-conversation-projection-test.js +60 -60
- package/_site/_test/codex-marketplace-scoped-path-test.js +186 -186
- package/_site/_test/codex-notify-capture-e2e-test.js +101 -101
- package/_site/_test/codex-notify-fanout-test.js +134 -134
- package/_site/_test/codex-notify-upgrade-test.js +253 -253
- package/_site/_test/commit-boundary-freeze-test.js +147 -147
- package/_site/_test/commit-conversation-binding-test.js +4 -4
- package/_site/_test/configuration-generation-test.js +22 -22
- package/_site/_test/context-pack-test.js +200 -200
- package/_site/_test/conversation-api-test.js +10 -10
- package/_site/_test/conversation-origin-test.js +15 -15
- package/_site/_test/cross-repo-isolation-e2e-test.js +187 -187
- package/_site/_test/embedding-config-test.js +32 -32
- package/_site/_test/fixtures/fake-browser-exit.js +10 -10
- package/_site/_test/fixtures/fake-browser-hang.js +10 -10
- package/_site/_test/fixtures/integration-busy-worker.cjs +6 -6
- package/_site/_test/fixtures/make-git-repos.js +92 -92
- package/_site/_test/fixtures/retrieval-gold-queries.json +32 -32
- package/_site/_test/fresh-hook-reimport-test.js +53 -53
- package/_site/_test/fresh-product-data-test.js +56 -56
- package/_site/_test/git-path-compatibility-test.js +80 -80
- package/_site/_test/git-validation-test.js +81 -81
- package/_site/_test/hook-worktree-test.js +42 -42
- package/_site/_test/index-builder-test.js +41 -41
- package/_site/_test/index-error-display-contract-test.js +10 -10
- package/_site/_test/integration-adapters-test.js +67 -67
- package/_site/_test/integration-capture-setup-test.js +118 -118
- package/_site/_test/integration-runtime-binding-a2-test.js +566 -566
- package/_site/_test/integration-runtime-binding-a3-test.js +227 -227
- package/_site/_test/integration-runtime-binding-test.js +473 -473
- package/_site/_test/integration-status-scan-test.js +29 -29
- package/_site/_test/kb-framework-test.js +57 -57
- package/_site/_test/kbpath-follow-test.js +63 -63
- package/_site/_test/knowledge-db-test.js +144 -144
- package/_site/_test/knowledge-engine-client-test.js +109 -109
- package/_site/_test/knowledge-maintenance-test.js +40 -40
- package/_site/_test/knowledge-panel-ui-contract-test.js +112 -0
- package/_site/_test/knowledge-scopes-test.js +37 -37
- package/_site/_test/knowledge-storage-location-test.js +28 -28
- package/_site/_test/launcher-readiness-test.js +80 -80
- package/_site/_test/legacy-claude-session-alias-test.js +106 -106
- package/_site/_test/legacy-routes-removed-test.js +47 -47
- package/_site/_test/legacy-workbench-exclusion-test.js +92 -92
- package/_site/_test/live-gateway-test.js +48 -48
- package/_site/_test/local-marketplace-test.js +16 -16
- package/_site/_test/log-redaction-test.js +58 -58
- package/_site/_test/markdown-maintenance-test.js +11 -11
- package/_site/_test/model-context-windows-test.js +89 -89
- package/_site/_test/module-agent-start-proxy-test.js +65 -65
- package/_site/_test/module-artifact-integrity-test.js +27 -27
- package/_site/_test/module-boundary-test.js +30 -30
- package/_site/_test/module-bridge-eventbridge-test.js +202 -202
- package/_site/_test/module-dynamic-port-test.js +118 -118
- package/_site/_test/module-index-proxy-test.js +33 -33
- package/_site/_test/module-model-configuration-test.js +44 -44
- package/_site/_test/module-process-lifecycle-test.js +35 -35
- package/_site/_test/module-stream-proxy-test.js +34 -34
- package/_site/_test/module-terminal-restart-test.js +63 -63
- package/_site/_test/module-wiring-unbind-race-test.js +59 -59
- package/_site/_test/native-context-integrations-test.js +86 -86
- package/_site/_test/orphaned-claim-recovery-test.js +80 -80
- package/_site/_test/package-boundary-test.js +43 -42
- package/_site/_test/package-startup-test.js +56 -56
- package/_site/_test/packaged-ui-smoke-test.js +88 -88
- package/_site/_test/pr-consumer-contract-test.js +55 -55
- package/_site/_test/product-brand-contract-test.js +25 -25
- package/_site/_test/product-diagnostics-ui-test.js +93 -93
- package/_site/_test/product-import-ui-test.js +104 -104
- package/_site/_test/product-progress-status-test.js +12 -1
- package/_site/_test/project-remove-running-guard-test.js +79 -79
- package/_site/_test/project-store-test.js +90 -90
- package/_site/_test/registry-events-test.js +38 -38
- package/_site/_test/release-version-sync-test.js +115 -115
- package/_site/_test/requirement-binding-test.js +113 -113
- package/_site/_test/runtime-endpoint-test.js +64 -64
- package/_site/_test/scanner-test.js +83 -83
- package/_site/_test/server-security-test.js +96 -96
- package/_site/_test/sessions-stream-test.js +93 -93
- package/_site/_test/shared-scope-root-binding-test.js +67 -67
- package/_site/_test/simple-import-test.js +98 -98
- package/_site/_test/startup-analysis-disabled-test.js +6 -6
- package/_site/_test/team-knowledge-store-sparse-checkout-test.js +196 -196
- package/_site/_test/team-knowledge-store-test.js +132 -132
- package/_site/_test/test-server-cleanup-test.js +35 -35
- package/_site/_test/test-server-module-isolation-test.js +37 -37
- package/_site/_test/tracking-start-test.js +35 -35
- package/_site/_test/workbench-context-receipts-test.js +22 -22
- package/_site/_test/workspace-ui-contract-test.js +31 -31
- package/_site/_test/zcode-capture-integration-test.js +108 -108
- package/_site/lib/ai-vendor-presets.js +83 -83
- package/_site/lib/ai-workspace.js +3 -3
- package/_site/lib/atomic-file.js +204 -204
- package/_site/lib/bridge-adapter.js +260 -260
- package/_site/lib/capture-hook-config.js +108 -108
- package/_site/lib/claude-cli-runner.js +89 -89
- package/_site/lib/cli-instances.js +43 -43
- package/_site/lib/codex-context-status.js +17 -17
- package/_site/lib/codex-notify-config.js +193 -193
- package/_site/lib/commit-conversation-binder.js +12 -12
- package/_site/lib/commit-reconciler.js +38 -38
- package/_site/lib/context-pack-builder.js +299 -299
- package/_site/lib/conversation-exclusions.js +204 -204
- package/_site/lib/conversation-query-service.js +17 -17
- package/_site/lib/data-dir.js +13 -13
- package/_site/lib/embedding-service.js +85 -85
- package/_site/lib/engine-connection.js +93 -93
- package/_site/lib/engine-knowledge-client.js +72 -72
- package/_site/lib/folder-picker-output.js +3 -3
- package/_site/lib/git-path.js +14 -14
- package/_site/lib/github-team-store.js +3 -3
- package/_site/lib/index-builder.js +157 -157
- package/_site/lib/integration-status-scan.js +99 -99
- package/_site/lib/integration-status-worker.js +14 -14
- package/_site/lib/kb-framework.js +15 -15
- package/_site/lib/knowledge-db.js +363 -363
- package/_site/lib/knowledge-schema.js +121 -121
- package/_site/lib/live-gateway.js +78 -78
- package/_site/lib/llm-client.js +12 -12
- package/_site/lib/model-context-windows.js +82 -82
- package/_site/lib/module-bridge.js +874 -874
- package/_site/lib/module-port-resolver.js +57 -57
- package/_site/lib/post-commit-automation.js +54 -54
- package/_site/lib/product-data.js +35 -35
- package/_site/lib/project-lifecycle-service.js +14 -14
- package/_site/lib/project-registry-store.js +129 -129
- package/_site/lib/prompt-registry.js +148 -148
- package/_site/lib/registry-events.js +16 -16
- package/_site/lib/requirement-adapters.js +10 -10
- package/_site/lib/requirement-binder.js +112 -112
- package/_site/lib/runtime-control.js +89 -89
- package/_site/lib/runtime-endpoint.js +5 -5
- package/_site/lib/zcode-context-integration.js +60 -60
- package/_site/scripts/codex-notify-fanout.cjs +95 -95
- package/_site/scripts/install-module-candidates.js +69 -69
- package/_site/scripts/pack-module-candidates.js +89 -89
- package/_site/scripts/sync-product-content.js +28 -28
- package/_site/scripts/sync-release-version.js +164 -164
- package/_site/scripts/vendor-modules.js +49 -49
- package/_site/scripts/verify-module-runtime.js +50 -50
- package/_site/scripts/verify-product-runtime.js +36 -36
- package/_site/scripts/verify-retrieval-gold.js +83 -83
- package/_site/server.js +15 -15
- package/_site/start.bat +26 -26
- package/_site/stop.bat +11 -11
- package/bin/project-knowledge-integrations.js +254 -254
- package/bin/project-knowledge-kb.js +67 -67
- package/bin/project-knowledge-mcp.js +8 -8
- package/bin/project-knowledge.js +170 -170
- package/claude-prompts.json +21 -21
- package/docs/README.zh-CN.md +205 -205
- package/docs/assets/architecture.svg +181 -181
- package/docs/assets/logo.svg +49 -49
- package/docs/fresh-v5-start.md +42 -42
- package/docs/leader-glm-workbench-playbook.md +122 -122
- package/docs/project-registry-schema.md +11 -11
- package/docs/release-5.0.16-acceptance.md +176 -176
- package/docs/release-5.0.17-acceptance.md +117 -117
- package/docs/release-5.0.19-acceptance.md +39 -25
- package/docs/team-knowledge-mode-a-plan.md +73 -73
- package/module-runtime-manifest.json +53 -33
- package/package.json +3 -2
- package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
- package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
- package/plugins/project-knowledge/.mcp.json +1 -1
- package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
- package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
- package/templates/change.md +30 -30
- package/templates/project-readme.md +18 -18
- package/ui/index.html +1 -1
- package/ui/knowledge-panel.html +118 -0
- package/ui/product.css +8 -0
- package/ui/product.js +146 -4
- package/vendor-manifest.json +55 -54
|
@@ -1,70 +1,70 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
const assert = require('node:assert/strict');
|
|
3
|
-
const fs = require('node:fs');
|
|
4
|
-
const os = require('node:os');
|
|
5
|
-
const path = require('node:path');
|
|
6
|
-
const { IntegrationManager } = require('../lib/integration-installer');
|
|
7
|
-
const { run, writeOutput } = require('../../plugins/project-knowledge/scripts/context-hook.cjs');
|
|
8
|
-
|
|
9
|
-
async function main() {
|
|
10
|
-
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'automatic-context-'));
|
|
11
|
-
try {
|
|
12
|
-
const endpoint = { schema: 'project-knowledge/runtime-endpoint/v1', host: '127.0.0.1', pid: process.pid, port: 23456, startedAt: 'now' };
|
|
13
|
-
fs.writeFileSync(path.join(root, 'runtime-endpoint.json'), JSON.stringify(endpoint));
|
|
14
|
-
const payload = { cwd: root, session_id: 'session-a', hook_event_name: 'UserPromptSubmit', prompt: 'Develop export normally' };
|
|
15
|
-
const env = { KB_DATA_DIR: root }, calls = [];
|
|
16
|
-
const identity = { ...endpoint, schema: 'project-knowledge/runtime-control/v1', name: 'project-knowledge', dataDir: root };
|
|
17
|
-
const fetchImpl = async (url, options) => {
|
|
18
|
-
calls.push({ url: String(url), options });
|
|
19
|
-
if (String(url).endsWith('/identity')) return Response.json(identity);
|
|
20
|
-
const input = JSON.parse(options.body);
|
|
21
|
-
return Response.json({ ok: true, requestId: input.requestId, projectId: 'project-a', status: 'ready', memoryStatus: 'ready', prompt: '<knowledge_context>export revision 37</knowledge_context>', facts: [{}], memories: [{}], references: [{}] });
|
|
22
|
-
};
|
|
23
|
-
const output = await run(payload, { env, fetchImpl });
|
|
24
|
-
assert.match(output.hookSpecificOutput.additionalContext, /revision 37/); assert.equal(calls.length, 2);
|
|
25
|
-
assert.equal(JSON.parse(calls[1].options.body).query, payload.prompt);
|
|
26
|
-
assert.ok(!JSON.stringify(output).includes('receipt')); assert.ok(!fs.existsSync(path.join(root, 'logs')));
|
|
27
|
-
await writeOutput(output, { write: (text, callback) => { assert.ok(!text.includes('receipt')); callback(); } });
|
|
28
|
-
const logDir = path.join(root, 'logs/projects/project-a'); const logText = fs.readFileSync(path.join(logDir, fs.readdirSync(logDir)[0]), 'utf8');
|
|
29
|
-
assert.ok(!logText.includes(payload.prompt)); assert.ok(!logText.includes('revision 37')); assert.ok(logText.includes('agent.context.output'));
|
|
30
|
-
calls.length = 0;
|
|
31
|
-
assert.deepEqual(await run(payload, { env: { ...env, KB_KNOWLEDGE_CONTEXT: '0' }, fetchImpl }), {}); assert.equal(calls.length, 0);
|
|
32
|
-
assert.deepEqual(await run({ ...payload, hook_event_name: 'Stop' }, { env, fetchImpl }), {});
|
|
33
|
-
const mismatch = await run(payload, { env, fetchImpl: async () => Response.json({ ...identity, dataDir: path.join(root, 'other') }) });
|
|
34
|
-
assert.match(mismatch.systemMessage, /CONTEXT_IDENTITY_MISMATCH/);
|
|
35
|
-
const unknown = await run(payload, { env, fetchImpl: async url => String(url).endsWith('/identity') ? Response.json(identity) : Response.json({ ok: false, error: 'PROJECT_NOT_FOUND' }, { status: 404 }) });
|
|
36
|
-
assert.match(unknown.systemMessage, /未识别到当前代码目录/);
|
|
37
|
-
assert.match(unknown.hookSpecificOutput.additionalContext, /不代表知识库为空/);
|
|
38
|
-
const offline = await run(payload, { env, fetchImpl: async () => { throw new Error('sensitive untrusted upstream text'); } });
|
|
39
|
-
assert.match(offline.systemMessage, /可继续开发/); assert.ok(!JSON.stringify(offline).includes('sensitive'));
|
|
40
|
-
const slow = await run(payload, { env, timeoutMs: 30, fetchImpl: (url, options) => new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true })) });
|
|
41
|
-
assert.match(slow.systemMessage, /CONTEXT_TIMEOUT/);
|
|
42
|
-
let version = '4.2.16'; const commandCalls = [];
|
|
43
|
-
const manager = new IntegrationManager({ homeDir: root, commandResolver: name => name, runner: (command, args) => {
|
|
44
|
-
commandCalls.push(args.join(' '));
|
|
45
|
-
if (args.join(' ') === 'plugin list --json') return { status: 0, stdout: JSON.stringify([{ id: 'project-knowledge@project-knowledge', version, enabled: true }]) };
|
|
46
|
-
if (args.join(' ') === 'plugin marketplace list --json') return { status: 0, stdout: JSON.stringify([{ name: 'project-knowledge' }]) };
|
|
47
|
-
if (args.slice(0, 2).join(' ') === 'plugin update') {
|
|
48
|
-
version = manager.version;
|
|
49
|
-
const source = path.resolve(__dirname, '../../plugins/project-knowledge'), cache = path.join(root, '.claude/plugins/cache/project-knowledge/project-knowledge', version);
|
|
50
|
-
fs.mkdirSync(cache, { recursive: true }); fs.cpSync(source, cache, { recursive: true });
|
|
51
|
-
}
|
|
52
|
-
return { status: 0, stdout: '' };
|
|
53
|
-
} });
|
|
54
|
-
const knownMarketplaces = path.join(root, '.claude/plugins/known_marketplaces.json');
|
|
55
|
-
fs.mkdirSync(path.dirname(knownMarketplaces), { recursive: true });
|
|
56
|
-
fs.writeFileSync(knownMarketplaces, JSON.stringify({ 'project-knowledge': { source: { source: 'directory', path: manager.rootDir } } }));
|
|
57
|
-
assert.equal(manager.statusClaude().state, 'needs-update');
|
|
58
|
-
manager.installClaude();
|
|
59
|
-
assert.ok(commandCalls.includes('plugin marketplace update project-knowledge'));
|
|
60
|
-
assert.ok(commandCalls.includes('plugin update project-knowledge@project-knowledge --scope user'));
|
|
61
|
-
assert.equal(manager.statusClaude().state, 'installed');
|
|
62
|
-
const cacheRoot = path.join(root, '.claude/plugins/cache/project-knowledge/project-knowledge', manager.version);
|
|
63
|
-
for (const file of ['hooks/claude.json', 'scripts/context-hook.cjs']) fs.writeFileSync(path.join(cacheRoot, file), fs.readFileSync(path.join(cacheRoot, file), 'utf8').replace(/\r?\n/g, '\r\n'));
|
|
64
|
-
assert.equal(manager.automaticContextStatus('claude', manager.statusClaude()).configured, true, 'Git CRLF checkout and npm LF are the same client integration');
|
|
65
|
-
const before = commandCalls.filter(c => c.startsWith('plugin update')).length; manager.installClaude();
|
|
66
|
-
assert.equal(commandCalls.filter(c => c.startsWith('plugin update')).length, before);
|
|
67
|
-
console.log('Automatic context protocol, fail-open safety and stale-plugin upgrade passed.');
|
|
68
|
-
} finally { fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); }
|
|
69
|
-
}
|
|
70
|
-
main().catch(error => { console.error(error); process.exitCode = 1; });
|
|
1
|
+
'use strict';
|
|
2
|
+
const assert = require('node:assert/strict');
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const os = require('node:os');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { IntegrationManager } = require('../lib/integration-installer');
|
|
7
|
+
const { run, writeOutput } = require('../../plugins/project-knowledge/scripts/context-hook.cjs');
|
|
8
|
+
|
|
9
|
+
async function main() {
|
|
10
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'automatic-context-'));
|
|
11
|
+
try {
|
|
12
|
+
const endpoint = { schema: 'project-knowledge/runtime-endpoint/v1', host: '127.0.0.1', pid: process.pid, port: 23456, startedAt: 'now' };
|
|
13
|
+
fs.writeFileSync(path.join(root, 'runtime-endpoint.json'), JSON.stringify(endpoint));
|
|
14
|
+
const payload = { cwd: root, session_id: 'session-a', hook_event_name: 'UserPromptSubmit', prompt: 'Develop export normally' };
|
|
15
|
+
const env = { KB_DATA_DIR: root }, calls = [];
|
|
16
|
+
const identity = { ...endpoint, schema: 'project-knowledge/runtime-control/v1', name: 'project-knowledge', dataDir: root };
|
|
17
|
+
const fetchImpl = async (url, options) => {
|
|
18
|
+
calls.push({ url: String(url), options });
|
|
19
|
+
if (String(url).endsWith('/identity')) return Response.json(identity);
|
|
20
|
+
const input = JSON.parse(options.body);
|
|
21
|
+
return Response.json({ ok: true, requestId: input.requestId, projectId: 'project-a', status: 'ready', memoryStatus: 'ready', prompt: '<knowledge_context>export revision 37</knowledge_context>', facts: [{}], memories: [{}], references: [{}] });
|
|
22
|
+
};
|
|
23
|
+
const output = await run(payload, { env, fetchImpl });
|
|
24
|
+
assert.match(output.hookSpecificOutput.additionalContext, /revision 37/); assert.equal(calls.length, 2);
|
|
25
|
+
assert.equal(JSON.parse(calls[1].options.body).query, payload.prompt);
|
|
26
|
+
assert.ok(!JSON.stringify(output).includes('receipt')); assert.ok(!fs.existsSync(path.join(root, 'logs')));
|
|
27
|
+
await writeOutput(output, { write: (text, callback) => { assert.ok(!text.includes('receipt')); callback(); } });
|
|
28
|
+
const logDir = path.join(root, 'logs/projects/project-a'); const logText = fs.readFileSync(path.join(logDir, fs.readdirSync(logDir)[0]), 'utf8');
|
|
29
|
+
assert.ok(!logText.includes(payload.prompt)); assert.ok(!logText.includes('revision 37')); assert.ok(logText.includes('agent.context.output'));
|
|
30
|
+
calls.length = 0;
|
|
31
|
+
assert.deepEqual(await run(payload, { env: { ...env, KB_KNOWLEDGE_CONTEXT: '0' }, fetchImpl }), {}); assert.equal(calls.length, 0);
|
|
32
|
+
assert.deepEqual(await run({ ...payload, hook_event_name: 'Stop' }, { env, fetchImpl }), {});
|
|
33
|
+
const mismatch = await run(payload, { env, fetchImpl: async () => Response.json({ ...identity, dataDir: path.join(root, 'other') }) });
|
|
34
|
+
assert.match(mismatch.systemMessage, /CONTEXT_IDENTITY_MISMATCH/);
|
|
35
|
+
const unknown = await run(payload, { env, fetchImpl: async url => String(url).endsWith('/identity') ? Response.json(identity) : Response.json({ ok: false, error: 'PROJECT_NOT_FOUND' }, { status: 404 }) });
|
|
36
|
+
assert.match(unknown.systemMessage, /未识别到当前代码目录/);
|
|
37
|
+
assert.match(unknown.hookSpecificOutput.additionalContext, /不代表知识库为空/);
|
|
38
|
+
const offline = await run(payload, { env, fetchImpl: async () => { throw new Error('sensitive untrusted upstream text'); } });
|
|
39
|
+
assert.match(offline.systemMessage, /可继续开发/); assert.ok(!JSON.stringify(offline).includes('sensitive'));
|
|
40
|
+
const slow = await run(payload, { env, timeoutMs: 30, fetchImpl: (url, options) => new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true })) });
|
|
41
|
+
assert.match(slow.systemMessage, /CONTEXT_TIMEOUT/);
|
|
42
|
+
let version = '4.2.16'; const commandCalls = [];
|
|
43
|
+
const manager = new IntegrationManager({ homeDir: root, commandResolver: name => name, runner: (command, args) => {
|
|
44
|
+
commandCalls.push(args.join(' '));
|
|
45
|
+
if (args.join(' ') === 'plugin list --json') return { status: 0, stdout: JSON.stringify([{ id: 'project-knowledge@project-knowledge', version, enabled: true }]) };
|
|
46
|
+
if (args.join(' ') === 'plugin marketplace list --json') return { status: 0, stdout: JSON.stringify([{ name: 'project-knowledge' }]) };
|
|
47
|
+
if (args.slice(0, 2).join(' ') === 'plugin update') {
|
|
48
|
+
version = manager.version;
|
|
49
|
+
const source = path.resolve(__dirname, '../../plugins/project-knowledge'), cache = path.join(root, '.claude/plugins/cache/project-knowledge/project-knowledge', version);
|
|
50
|
+
fs.mkdirSync(cache, { recursive: true }); fs.cpSync(source, cache, { recursive: true });
|
|
51
|
+
}
|
|
52
|
+
return { status: 0, stdout: '' };
|
|
53
|
+
} });
|
|
54
|
+
const knownMarketplaces = path.join(root, '.claude/plugins/known_marketplaces.json');
|
|
55
|
+
fs.mkdirSync(path.dirname(knownMarketplaces), { recursive: true });
|
|
56
|
+
fs.writeFileSync(knownMarketplaces, JSON.stringify({ 'project-knowledge': { source: { source: 'directory', path: manager.rootDir } } }));
|
|
57
|
+
assert.equal(manager.statusClaude().state, 'needs-update');
|
|
58
|
+
manager.installClaude();
|
|
59
|
+
assert.ok(commandCalls.includes('plugin marketplace update project-knowledge'));
|
|
60
|
+
assert.ok(commandCalls.includes('plugin update project-knowledge@project-knowledge --scope user'));
|
|
61
|
+
assert.equal(manager.statusClaude().state, 'installed');
|
|
62
|
+
const cacheRoot = path.join(root, '.claude/plugins/cache/project-knowledge/project-knowledge', manager.version);
|
|
63
|
+
for (const file of ['hooks/claude.json', 'scripts/context-hook.cjs']) fs.writeFileSync(path.join(cacheRoot, file), fs.readFileSync(path.join(cacheRoot, file), 'utf8').replace(/\r?\n/g, '\r\n'));
|
|
64
|
+
assert.equal(manager.automaticContextStatus('claude', manager.statusClaude()).configured, true, 'Git CRLF checkout and npm LF are the same client integration');
|
|
65
|
+
const before = commandCalls.filter(c => c.startsWith('plugin update')).length; manager.installClaude();
|
|
66
|
+
assert.equal(commandCalls.filter(c => c.startsWith('plugin update')).length, before);
|
|
67
|
+
console.log('Automatic context protocol, fail-open safety and stale-plugin upgrade passed.');
|
|
68
|
+
} finally { fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); }
|
|
69
|
+
}
|
|
70
|
+
main().catch(error => { console.error(error); process.exitCode = 1; });
|
|
@@ -1,230 +1,230 @@
|
|
|
1
|
-
// Run: node _site/_test/bin-cli-test.js
|
|
2
|
-
//
|
|
3
|
-
// Covers the project-knowledge CLI:
|
|
4
|
-
// --version, --help, status (no pid), stop (no pid),
|
|
5
|
-
// --fg foreground lifecycle (PID file written + cleaned),
|
|
6
|
-
// port fallback when default port is busy.
|
|
7
|
-
|
|
8
|
-
const fs = require('fs');
|
|
9
|
-
const os = require('os');
|
|
10
|
-
const path = require('path');
|
|
11
|
-
const net = require('net');
|
|
12
|
-
const { spawn, spawnSync } = require('child_process');
|
|
13
|
-
|
|
14
|
-
const ROOT = path.resolve(__dirname, '..', '..');
|
|
15
|
-
const BIN = path.join(ROOT, 'bin', 'project-knowledge.js');
|
|
16
|
-
const KB_BIN = path.join(ROOT, 'bin', 'project-knowledge-kb.js');
|
|
17
|
-
const ISOLATED_STATUS_PORT = 19000 + (process.pid % 1000);
|
|
18
|
-
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), `kb-bin-cli-${process.pid}-`));
|
|
19
|
-
const PID_FILE = path.join(TEST_DATA_DIR, 'runtime-endpoint.json');
|
|
20
|
-
const TEST_BRIDGE_HOME = fs.mkdtempSync(path.join(os.tmpdir(), `kb-bin-cli-bridge-${process.pid}-`));
|
|
21
|
-
const TEST_ENV = { ...process.env, KB_DATA_DIR: TEST_DATA_DIR, KB_SKIP_MIGRATION: '1', AI_CODING_EVENT_BRIDGE_HOME: TEST_BRIDGE_HOME, KB_MODULES_AUTOSTART: '0' };
|
|
22
|
-
|
|
23
|
-
function assert(cond, msg) { if (!cond) throw new Error(msg); }
|
|
24
|
-
|
|
25
|
-
function run(args, opts = {}) {
|
|
26
|
-
return spawnSync(process.execPath, [BIN, ...args], {
|
|
27
|
-
cwd: ROOT,
|
|
28
|
-
encoding: 'utf-8',
|
|
29
|
-
timeout: 15_000,
|
|
30
|
-
env: TEST_ENV,
|
|
31
|
-
...opts,
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function readPidFile() {
|
|
36
|
-
try {
|
|
37
|
-
if (!fs.existsSync(PID_FILE)) return null;
|
|
38
|
-
return JSON.parse(fs.readFileSync(PID_FILE, 'utf8'));
|
|
39
|
-
} catch { return null; }
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function removePidFile() {
|
|
43
|
-
try { fs.unlinkSync(PID_FILE); } catch { /* ignore */ }
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function pickFreePort() {
|
|
47
|
-
return new Promise((resolve, reject) => {
|
|
48
|
-
const server = net.createServer();
|
|
49
|
-
server.unref();
|
|
50
|
-
server.on('error', reject);
|
|
51
|
-
server.listen(0, () => {
|
|
52
|
-
const { port } = server.address();
|
|
53
|
-
server.close(() => resolve(port));
|
|
54
|
-
});
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function isPortListening(port) {
|
|
59
|
-
// A port is "in use by someone else" iff we cannot bind it (EADDRINUSE).
|
|
60
|
-
// If our probe bind succeeds, the port is actually free.
|
|
61
|
-
return new Promise((resolve) => {
|
|
62
|
-
const tester = net.createServer();
|
|
63
|
-
tester.unref();
|
|
64
|
-
const finish = (inUse) => {
|
|
65
|
-
tester.removeAllListeners();
|
|
66
|
-
tester.close(() => resolve(inUse));
|
|
67
|
-
};
|
|
68
|
-
tester.once('error', (err) => {
|
|
69
|
-
if (err && err.code === 'EADDRINUSE') finish(true);
|
|
70
|
-
else finish(false);
|
|
71
|
-
});
|
|
72
|
-
tester.once('listening', () => finish(false));
|
|
73
|
-
tester.listen(port, '127.0.0.1');
|
|
74
|
-
setTimeout(() => finish(false), 500);
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
async function waitForListening(port, deadlineMs = 8000) {
|
|
79
|
-
const deadline = Date.now() + deadlineMs;
|
|
80
|
-
while (Date.now() < deadline) {
|
|
81
|
-
if (await canConnect(port)) return true;
|
|
82
|
-
await new Promise(resolve => setTimeout(resolve, 150));
|
|
83
|
-
}
|
|
84
|
-
return false;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function canConnect(port) {
|
|
88
|
-
// A bind probe can steal the selected port exactly as the child starts.
|
|
89
|
-
// Readiness checks must connect, never compete with the server's listener.
|
|
90
|
-
return new Promise(resolve => {
|
|
91
|
-
const socket = net.createConnection({ host: '127.0.0.1', port });
|
|
92
|
-
let settled = false;
|
|
93
|
-
const finish = result => { if (settled) return; settled = true; socket.destroy(); resolve(result); };
|
|
94
|
-
socket.setTimeout(500, () => finish(false));
|
|
95
|
-
socket.once('connect', () => finish(true));
|
|
96
|
-
socket.once('error', () => finish(false));
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
(async () => {
|
|
101
|
-
// Make sure no leftover PID file or server from a previous run.
|
|
102
|
-
removePidFile();
|
|
103
|
-
|
|
104
|
-
// --version
|
|
105
|
-
const versionResult = run(['--version']);
|
|
106
|
-
assert(versionResult.status === 0, `--version should exit 0, got ${versionResult.status}: ${versionResult.stderr}`);
|
|
107
|
-
assert(versionResult.stdout.trim() === require(path.join(ROOT, 'package.json')).version,
|
|
108
|
-
`--version output (${versionResult.stdout.trim()}) should match package.json`);
|
|
109
|
-
|
|
110
|
-
// --help mentions the new subcommands
|
|
111
|
-
const helpResult = run(['--help']);
|
|
112
|
-
assert(helpResult.status === 0, '--help should exit 0');
|
|
113
|
-
const helpText = helpResult.stdout;
|
|
114
|
-
assert(/stop/.test(helpText), '--help should mention `stop`');
|
|
115
|
-
assert(/status/.test(helpText), '--help should mention `status`');
|
|
116
|
-
assert(/--fg/.test(helpText), '--help should mention `--fg`');
|
|
117
|
-
assert(/--no-open/.test(helpText), '--help should mention `--no-open`');
|
|
118
|
-
assert(/5757/.test(helpText), '--help should mention default port 5757');
|
|
119
|
-
|
|
120
|
-
const kbHelp = spawnSync(process.execPath, [KB_BIN, '--help'], { cwd: ROOT, encoding: 'utf8', timeout: 15_000 });
|
|
121
|
-
assert(kbHelp.status === 0, `project-knowledge-kb --help should exit 0: ${kbHelp.stderr}`);
|
|
122
|
-
assert(/search/.test(kbHelp.stdout) && /history/.test(kbHelp.stdout), 'knowledge CLI help should list read-only commands');
|
|
123
|
-
|
|
124
|
-
// status when no PID file
|
|
125
|
-
removePidFile();
|
|
126
|
-
const statusResult = run(['status'], { env: { ...TEST_ENV, KB_SITE_PORT: String(ISOLATED_STATUS_PORT) } });
|
|
127
|
-
assert(statusResult.status === 0, 'status should exit 0 when not running');
|
|
128
|
-
assert(/not running/i.test(statusResult.stdout + statusResult.stderr),
|
|
129
|
-
`status output should mention "not running", got: ${statusResult.stdout} ${statusResult.stderr}`);
|
|
130
|
-
|
|
131
|
-
// stop when no PID file
|
|
132
|
-
const stopResult = run(['stop'], { env: { ...TEST_ENV, KB_SITE_PORT: String(ISOLATED_STATUS_PORT) } });
|
|
133
|
-
assert(stopResult.status === 0, 'stop should exit 0 when no PID file');
|
|
134
|
-
assert(/No background process/i.test(stopResult.stdout + stopResult.stderr),
|
|
135
|
-
`stop output should mention "No background process", got: ${stopResult.stdout} ${stopResult.stderr}`);
|
|
136
|
-
|
|
137
|
-
// Foreground lifecycle: --fg writes PID file and listens; SIGTERM cleans up.
|
|
138
|
-
const fgPort = await pickFreePort();
|
|
139
|
-
const fgChild = spawn(process.execPath, [BIN, '--fg', '--port', String(fgPort), '--no-open'], {
|
|
140
|
-
cwd: ROOT,
|
|
141
|
-
env: TEST_ENV,
|
|
142
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
143
|
-
windowsHide: true,
|
|
144
|
-
});
|
|
145
|
-
let fgOutput = '';
|
|
146
|
-
fgChild.stdout.on('data', d => { fgOutput += d.toString(); });
|
|
147
|
-
fgChild.stderr.on('data', d => { fgOutput += d.toString(); });
|
|
148
|
-
|
|
149
|
-
const listening = await waitForListening(fgPort);
|
|
150
|
-
assert(listening, `server in --fg mode should listen on port ${fgPort}; output: ${fgOutput}`);
|
|
151
|
-
|
|
152
|
-
const pidRecord = readPidFile();
|
|
153
|
-
assert(pidRecord, `PID file at ${PID_FILE} should exist after fg child bound port; output: ${fgOutput}`);
|
|
154
|
-
assert(pidRecord.pid === fgChild.pid,
|
|
155
|
-
`PID file should record the foreground child PID (file: ${JSON.stringify(pidRecord)}, child: ${fgChild.pid})`);
|
|
156
|
-
assert(pidRecord.port === fgPort,
|
|
157
|
-
`PID file should record the actual port ${fgPort}, got ${pidRecord && pidRecord.port}`);
|
|
158
|
-
|
|
159
|
-
fgChild.kill('SIGTERM');
|
|
160
|
-
await new Promise(resolve => setTimeout(resolve, 400));
|
|
161
|
-
|
|
162
|
-
// On Windows, child.kill('SIGTERM') goes through TerminateProcess and skips
|
|
163
|
-
// Node's exit/SIGTERM handlers, so we can't reliably assert PID file cleanup
|
|
164
|
-
// here. Instead, verify the bin was responsive while alive and that the
|
|
165
|
-
// child is gone; the test harness cleans up the PID file at the end.
|
|
166
|
-
assert(fgChild.killed || fgChild.exitCode !== null, 'foreground child should have exited on kill');
|
|
167
|
-
removePidFile();
|
|
168
|
-
|
|
169
|
-
// Port fallback: bind a port in 5757-5776 range, then start --fg without --port
|
|
170
|
-
// → CLI should pick the next free port in that range.
|
|
171
|
-
let busyPort = null;
|
|
172
|
-
for (let candidate = 5757; candidate < 5757 + 19; candidate++) {
|
|
173
|
-
if (!(await isPortListening(candidate)) && !(await isPortListening(candidate + 1))) {
|
|
174
|
-
busyPort = candidate;
|
|
175
|
-
break;
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
assert(busyPort, 'should find a free port in fallback range');
|
|
179
|
-
const busyServer = net.createServer();
|
|
180
|
-
await new Promise((resolve, reject) => {
|
|
181
|
-
busyServer.once('error', reject);
|
|
182
|
-
busyServer.listen(busyPort, '127.0.0.1', resolve);
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
const fallbackChild = spawn(process.execPath, [BIN, '--fg', '--no-open'], {
|
|
186
|
-
cwd: ROOT,
|
|
187
|
-
env: { ...TEST_ENV, KB_SITE_PORT: String(busyPort) },
|
|
188
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
189
|
-
windowsHide: true,
|
|
190
|
-
});
|
|
191
|
-
let fallbackOutput = '';
|
|
192
|
-
fallbackChild.stdout.on('data', d => { fallbackOutput += d.toString(); });
|
|
193
|
-
fallbackChild.stderr.on('data', d => { fallbackOutput += d.toString(); });
|
|
194
|
-
|
|
195
|
-
// Wait for server to come up on some port.
|
|
196
|
-
const deadline = Date.now() + 8000;
|
|
197
|
-
let detectedPort = null;
|
|
198
|
-
while (Date.now() < deadline && !detectedPort) {
|
|
199
|
-
const rec = readPidFile();
|
|
200
|
-
if (rec && rec.port && rec.port !== busyPort) {
|
|
201
|
-
if (await canConnect(rec.port)) {
|
|
202
|
-
detectedPort = rec.port;
|
|
203
|
-
break;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
await new Promise(resolve => setTimeout(resolve, 150));
|
|
207
|
-
}
|
|
208
|
-
assert(detectedPort, `port fallback should pick a free port (output: ${fallbackOutput})`);
|
|
209
|
-
assert(detectedPort >= 5757 && detectedPort < 5757 + 20,
|
|
210
|
-
`fallback port ${detectedPort} should be in 5757–${5757 + 19} range`);
|
|
211
|
-
|
|
212
|
-
fallbackChild.kill('SIGTERM');
|
|
213
|
-
await new Promise(resolve => setTimeout(resolve, 400));
|
|
214
|
-
await new Promise(resolve => busyServer.close(resolve));
|
|
215
|
-
|
|
216
|
-
// Unknown flag should exit non-zero
|
|
217
|
-
const unknown = run(['--bogus']);
|
|
218
|
-
assert(unknown.status !== 0, 'unknown flag should exit non-zero');
|
|
219
|
-
assert(/Unknown option/i.test(unknown.stdout + unknown.stderr),
|
|
220
|
-
`unknown flag output should mention "Unknown option", got: ${unknown.stdout} ${unknown.stderr}`);
|
|
221
|
-
|
|
222
|
-
removePidFile();
|
|
223
|
-
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
|
224
|
-
console.log('bin-cli-test PASS');
|
|
225
|
-
})().catch(err => {
|
|
226
|
-
console.error(err && err.stack || err);
|
|
227
|
-
removePidFile();
|
|
228
|
-
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
|
229
|
-
process.exit(1);
|
|
230
|
-
});
|
|
1
|
+
// Run: node _site/_test/bin-cli-test.js
|
|
2
|
+
//
|
|
3
|
+
// Covers the project-knowledge CLI:
|
|
4
|
+
// --version, --help, status (no pid), stop (no pid),
|
|
5
|
+
// --fg foreground lifecycle (PID file written + cleaned),
|
|
6
|
+
// port fallback when default port is busy.
|
|
7
|
+
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const os = require('os');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const net = require('net');
|
|
12
|
+
const { spawn, spawnSync } = require('child_process');
|
|
13
|
+
|
|
14
|
+
const ROOT = path.resolve(__dirname, '..', '..');
|
|
15
|
+
const BIN = path.join(ROOT, 'bin', 'project-knowledge.js');
|
|
16
|
+
const KB_BIN = path.join(ROOT, 'bin', 'project-knowledge-kb.js');
|
|
17
|
+
const ISOLATED_STATUS_PORT = 19000 + (process.pid % 1000);
|
|
18
|
+
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), `kb-bin-cli-${process.pid}-`));
|
|
19
|
+
const PID_FILE = path.join(TEST_DATA_DIR, 'runtime-endpoint.json');
|
|
20
|
+
const TEST_BRIDGE_HOME = fs.mkdtempSync(path.join(os.tmpdir(), `kb-bin-cli-bridge-${process.pid}-`));
|
|
21
|
+
const TEST_ENV = { ...process.env, KB_DATA_DIR: TEST_DATA_DIR, KB_SKIP_MIGRATION: '1', AI_CODING_EVENT_BRIDGE_HOME: TEST_BRIDGE_HOME, KB_MODULES_AUTOSTART: '0' };
|
|
22
|
+
|
|
23
|
+
function assert(cond, msg) { if (!cond) throw new Error(msg); }
|
|
24
|
+
|
|
25
|
+
function run(args, opts = {}) {
|
|
26
|
+
return spawnSync(process.execPath, [BIN, ...args], {
|
|
27
|
+
cwd: ROOT,
|
|
28
|
+
encoding: 'utf-8',
|
|
29
|
+
timeout: 15_000,
|
|
30
|
+
env: TEST_ENV,
|
|
31
|
+
...opts,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function readPidFile() {
|
|
36
|
+
try {
|
|
37
|
+
if (!fs.existsSync(PID_FILE)) return null;
|
|
38
|
+
return JSON.parse(fs.readFileSync(PID_FILE, 'utf8'));
|
|
39
|
+
} catch { return null; }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function removePidFile() {
|
|
43
|
+
try { fs.unlinkSync(PID_FILE); } catch { /* ignore */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function pickFreePort() {
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
const server = net.createServer();
|
|
49
|
+
server.unref();
|
|
50
|
+
server.on('error', reject);
|
|
51
|
+
server.listen(0, () => {
|
|
52
|
+
const { port } = server.address();
|
|
53
|
+
server.close(() => resolve(port));
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isPortListening(port) {
|
|
59
|
+
// A port is "in use by someone else" iff we cannot bind it (EADDRINUSE).
|
|
60
|
+
// If our probe bind succeeds, the port is actually free.
|
|
61
|
+
return new Promise((resolve) => {
|
|
62
|
+
const tester = net.createServer();
|
|
63
|
+
tester.unref();
|
|
64
|
+
const finish = (inUse) => {
|
|
65
|
+
tester.removeAllListeners();
|
|
66
|
+
tester.close(() => resolve(inUse));
|
|
67
|
+
};
|
|
68
|
+
tester.once('error', (err) => {
|
|
69
|
+
if (err && err.code === 'EADDRINUSE') finish(true);
|
|
70
|
+
else finish(false);
|
|
71
|
+
});
|
|
72
|
+
tester.once('listening', () => finish(false));
|
|
73
|
+
tester.listen(port, '127.0.0.1');
|
|
74
|
+
setTimeout(() => finish(false), 500);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function waitForListening(port, deadlineMs = 8000) {
|
|
79
|
+
const deadline = Date.now() + deadlineMs;
|
|
80
|
+
while (Date.now() < deadline) {
|
|
81
|
+
if (await canConnect(port)) return true;
|
|
82
|
+
await new Promise(resolve => setTimeout(resolve, 150));
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function canConnect(port) {
|
|
88
|
+
// A bind probe can steal the selected port exactly as the child starts.
|
|
89
|
+
// Readiness checks must connect, never compete with the server's listener.
|
|
90
|
+
return new Promise(resolve => {
|
|
91
|
+
const socket = net.createConnection({ host: '127.0.0.1', port });
|
|
92
|
+
let settled = false;
|
|
93
|
+
const finish = result => { if (settled) return; settled = true; socket.destroy(); resolve(result); };
|
|
94
|
+
socket.setTimeout(500, () => finish(false));
|
|
95
|
+
socket.once('connect', () => finish(true));
|
|
96
|
+
socket.once('error', () => finish(false));
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
(async () => {
|
|
101
|
+
// Make sure no leftover PID file or server from a previous run.
|
|
102
|
+
removePidFile();
|
|
103
|
+
|
|
104
|
+
// --version
|
|
105
|
+
const versionResult = run(['--version']);
|
|
106
|
+
assert(versionResult.status === 0, `--version should exit 0, got ${versionResult.status}: ${versionResult.stderr}`);
|
|
107
|
+
assert(versionResult.stdout.trim() === require(path.join(ROOT, 'package.json')).version,
|
|
108
|
+
`--version output (${versionResult.stdout.trim()}) should match package.json`);
|
|
109
|
+
|
|
110
|
+
// --help mentions the new subcommands
|
|
111
|
+
const helpResult = run(['--help']);
|
|
112
|
+
assert(helpResult.status === 0, '--help should exit 0');
|
|
113
|
+
const helpText = helpResult.stdout;
|
|
114
|
+
assert(/stop/.test(helpText), '--help should mention `stop`');
|
|
115
|
+
assert(/status/.test(helpText), '--help should mention `status`');
|
|
116
|
+
assert(/--fg/.test(helpText), '--help should mention `--fg`');
|
|
117
|
+
assert(/--no-open/.test(helpText), '--help should mention `--no-open`');
|
|
118
|
+
assert(/5757/.test(helpText), '--help should mention default port 5757');
|
|
119
|
+
|
|
120
|
+
const kbHelp = spawnSync(process.execPath, [KB_BIN, '--help'], { cwd: ROOT, encoding: 'utf8', timeout: 15_000 });
|
|
121
|
+
assert(kbHelp.status === 0, `project-knowledge-kb --help should exit 0: ${kbHelp.stderr}`);
|
|
122
|
+
assert(/search/.test(kbHelp.stdout) && /history/.test(kbHelp.stdout), 'knowledge CLI help should list read-only commands');
|
|
123
|
+
|
|
124
|
+
// status when no PID file
|
|
125
|
+
removePidFile();
|
|
126
|
+
const statusResult = run(['status'], { env: { ...TEST_ENV, KB_SITE_PORT: String(ISOLATED_STATUS_PORT) } });
|
|
127
|
+
assert(statusResult.status === 0, 'status should exit 0 when not running');
|
|
128
|
+
assert(/not running/i.test(statusResult.stdout + statusResult.stderr),
|
|
129
|
+
`status output should mention "not running", got: ${statusResult.stdout} ${statusResult.stderr}`);
|
|
130
|
+
|
|
131
|
+
// stop when no PID file
|
|
132
|
+
const stopResult = run(['stop'], { env: { ...TEST_ENV, KB_SITE_PORT: String(ISOLATED_STATUS_PORT) } });
|
|
133
|
+
assert(stopResult.status === 0, 'stop should exit 0 when no PID file');
|
|
134
|
+
assert(/No background process/i.test(stopResult.stdout + stopResult.stderr),
|
|
135
|
+
`stop output should mention "No background process", got: ${stopResult.stdout} ${stopResult.stderr}`);
|
|
136
|
+
|
|
137
|
+
// Foreground lifecycle: --fg writes PID file and listens; SIGTERM cleans up.
|
|
138
|
+
const fgPort = await pickFreePort();
|
|
139
|
+
const fgChild = spawn(process.execPath, [BIN, '--fg', '--port', String(fgPort), '--no-open'], {
|
|
140
|
+
cwd: ROOT,
|
|
141
|
+
env: TEST_ENV,
|
|
142
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
143
|
+
windowsHide: true,
|
|
144
|
+
});
|
|
145
|
+
let fgOutput = '';
|
|
146
|
+
fgChild.stdout.on('data', d => { fgOutput += d.toString(); });
|
|
147
|
+
fgChild.stderr.on('data', d => { fgOutput += d.toString(); });
|
|
148
|
+
|
|
149
|
+
const listening = await waitForListening(fgPort);
|
|
150
|
+
assert(listening, `server in --fg mode should listen on port ${fgPort}; output: ${fgOutput}`);
|
|
151
|
+
|
|
152
|
+
const pidRecord = readPidFile();
|
|
153
|
+
assert(pidRecord, `PID file at ${PID_FILE} should exist after fg child bound port; output: ${fgOutput}`);
|
|
154
|
+
assert(pidRecord.pid === fgChild.pid,
|
|
155
|
+
`PID file should record the foreground child PID (file: ${JSON.stringify(pidRecord)}, child: ${fgChild.pid})`);
|
|
156
|
+
assert(pidRecord.port === fgPort,
|
|
157
|
+
`PID file should record the actual port ${fgPort}, got ${pidRecord && pidRecord.port}`);
|
|
158
|
+
|
|
159
|
+
fgChild.kill('SIGTERM');
|
|
160
|
+
await new Promise(resolve => setTimeout(resolve, 400));
|
|
161
|
+
|
|
162
|
+
// On Windows, child.kill('SIGTERM') goes through TerminateProcess and skips
|
|
163
|
+
// Node's exit/SIGTERM handlers, so we can't reliably assert PID file cleanup
|
|
164
|
+
// here. Instead, verify the bin was responsive while alive and that the
|
|
165
|
+
// child is gone; the test harness cleans up the PID file at the end.
|
|
166
|
+
assert(fgChild.killed || fgChild.exitCode !== null, 'foreground child should have exited on kill');
|
|
167
|
+
removePidFile();
|
|
168
|
+
|
|
169
|
+
// Port fallback: bind a port in 5757-5776 range, then start --fg without --port
|
|
170
|
+
// → CLI should pick the next free port in that range.
|
|
171
|
+
let busyPort = null;
|
|
172
|
+
for (let candidate = 5757; candidate < 5757 + 19; candidate++) {
|
|
173
|
+
if (!(await isPortListening(candidate)) && !(await isPortListening(candidate + 1))) {
|
|
174
|
+
busyPort = candidate;
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
assert(busyPort, 'should find a free port in fallback range');
|
|
179
|
+
const busyServer = net.createServer();
|
|
180
|
+
await new Promise((resolve, reject) => {
|
|
181
|
+
busyServer.once('error', reject);
|
|
182
|
+
busyServer.listen(busyPort, '127.0.0.1', resolve);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
const fallbackChild = spawn(process.execPath, [BIN, '--fg', '--no-open'], {
|
|
186
|
+
cwd: ROOT,
|
|
187
|
+
env: { ...TEST_ENV, KB_SITE_PORT: String(busyPort) },
|
|
188
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
189
|
+
windowsHide: true,
|
|
190
|
+
});
|
|
191
|
+
let fallbackOutput = '';
|
|
192
|
+
fallbackChild.stdout.on('data', d => { fallbackOutput += d.toString(); });
|
|
193
|
+
fallbackChild.stderr.on('data', d => { fallbackOutput += d.toString(); });
|
|
194
|
+
|
|
195
|
+
// Wait for server to come up on some port.
|
|
196
|
+
const deadline = Date.now() + 8000;
|
|
197
|
+
let detectedPort = null;
|
|
198
|
+
while (Date.now() < deadline && !detectedPort) {
|
|
199
|
+
const rec = readPidFile();
|
|
200
|
+
if (rec && rec.port && rec.port !== busyPort) {
|
|
201
|
+
if (await canConnect(rec.port)) {
|
|
202
|
+
detectedPort = rec.port;
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
await new Promise(resolve => setTimeout(resolve, 150));
|
|
207
|
+
}
|
|
208
|
+
assert(detectedPort, `port fallback should pick a free port (output: ${fallbackOutput})`);
|
|
209
|
+
assert(detectedPort >= 5757 && detectedPort < 5757 + 20,
|
|
210
|
+
`fallback port ${detectedPort} should be in 5757–${5757 + 19} range`);
|
|
211
|
+
|
|
212
|
+
fallbackChild.kill('SIGTERM');
|
|
213
|
+
await new Promise(resolve => setTimeout(resolve, 400));
|
|
214
|
+
await new Promise(resolve => busyServer.close(resolve));
|
|
215
|
+
|
|
216
|
+
// Unknown flag should exit non-zero
|
|
217
|
+
const unknown = run(['--bogus']);
|
|
218
|
+
assert(unknown.status !== 0, 'unknown flag should exit non-zero');
|
|
219
|
+
assert(/Unknown option/i.test(unknown.stdout + unknown.stderr),
|
|
220
|
+
`unknown flag output should mention "Unknown option", got: ${unknown.stdout} ${unknown.stderr}`);
|
|
221
|
+
|
|
222
|
+
removePidFile();
|
|
223
|
+
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
|
224
|
+
console.log('bin-cli-test PASS');
|
|
225
|
+
})().catch(err => {
|
|
226
|
+
console.error(err && err.stack || err);
|
|
227
|
+
removePidFile();
|
|
228
|
+
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
|
229
|
+
process.exit(1);
|
|
230
|
+
});
|