@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.
Files changed (200) hide show
  1. package/.agents/plugins/marketplace.json +3 -3
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/CHANGELOG.md +5 -0
  4. package/LICENSE +201 -201
  5. package/NOTICE +5 -5
  6. package/README.md +349 -349
  7. package/_modules/knowledge-engine/README.md +4 -0
  8. package/_modules/knowledge-engine/src/analysis-failures.js +39 -0
  9. package/_modules/knowledge-engine/src/analysis-worker.js +6 -2
  10. package/_modules/knowledge-engine/src/coordinator.js +7 -0
  11. package/_modules/knowledge-engine/src/headless-analyzer.js +2 -1
  12. package/_modules/knowledge-engine/src/server.js +1 -1
  13. package/_site/_test/agent-capture-mcp-ui-test.js +67 -67
  14. package/_site/_test/ai-profile-test.js +75 -75
  15. package/_site/_test/ai-vendor-presets-test.js +91 -91
  16. package/_site/_test/automatic-context-test.js +70 -70
  17. package/_site/_test/bin-cli-test.js +230 -230
  18. package/_site/_test/bridge-adapter-test.js +95 -95
  19. package/_site/_test/bridge-consumer-service-test.js +310 -310
  20. package/_site/_test/candidate-bin-content-test.js +35 -35
  21. package/_site/_test/candidate-product-assets-test.js +13 -13
  22. package/_site/_test/candidate-release-contract-test.js +14 -14
  23. package/_site/_test/capture-hook-dedup-test.js +158 -158
  24. package/_site/_test/claude-executable-discovery-test.js +28 -28
  25. package/_site/_test/claude-session-lifecycle-sweep-test.js +252 -252
  26. package/_site/_test/cli-instance-management-test.js +62 -62
  27. package/_site/_test/client-capture-restart-e2e-test.js +189 -189
  28. package/_site/_test/codex-conversation-projection-test.js +60 -60
  29. package/_site/_test/codex-marketplace-scoped-path-test.js +186 -186
  30. package/_site/_test/codex-notify-capture-e2e-test.js +101 -101
  31. package/_site/_test/codex-notify-fanout-test.js +134 -134
  32. package/_site/_test/codex-notify-upgrade-test.js +253 -253
  33. package/_site/_test/commit-boundary-freeze-test.js +147 -147
  34. package/_site/_test/commit-conversation-binding-test.js +4 -4
  35. package/_site/_test/configuration-generation-test.js +22 -22
  36. package/_site/_test/context-pack-test.js +200 -200
  37. package/_site/_test/conversation-api-test.js +10 -10
  38. package/_site/_test/conversation-origin-test.js +15 -15
  39. package/_site/_test/cross-repo-isolation-e2e-test.js +187 -187
  40. package/_site/_test/embedding-config-test.js +32 -32
  41. package/_site/_test/fixtures/fake-browser-exit.js +10 -10
  42. package/_site/_test/fixtures/fake-browser-hang.js +10 -10
  43. package/_site/_test/fixtures/integration-busy-worker.cjs +6 -6
  44. package/_site/_test/fixtures/make-git-repos.js +92 -92
  45. package/_site/_test/fixtures/retrieval-gold-queries.json +32 -32
  46. package/_site/_test/fresh-hook-reimport-test.js +53 -53
  47. package/_site/_test/fresh-product-data-test.js +56 -56
  48. package/_site/_test/git-path-compatibility-test.js +80 -80
  49. package/_site/_test/git-validation-test.js +81 -81
  50. package/_site/_test/hook-worktree-test.js +42 -42
  51. package/_site/_test/index-builder-test.js +41 -41
  52. package/_site/_test/index-error-display-contract-test.js +10 -10
  53. package/_site/_test/integration-adapters-test.js +67 -67
  54. package/_site/_test/integration-capture-setup-test.js +118 -118
  55. package/_site/_test/integration-runtime-binding-a2-test.js +566 -566
  56. package/_site/_test/integration-runtime-binding-a3-test.js +227 -227
  57. package/_site/_test/integration-runtime-binding-test.js +473 -473
  58. package/_site/_test/integration-status-scan-test.js +29 -29
  59. package/_site/_test/kb-framework-test.js +57 -57
  60. package/_site/_test/kbpath-follow-test.js +63 -63
  61. package/_site/_test/knowledge-db-test.js +144 -144
  62. package/_site/_test/knowledge-engine-client-test.js +109 -109
  63. package/_site/_test/knowledge-maintenance-test.js +40 -40
  64. package/_site/_test/knowledge-panel-ui-contract-test.js +112 -0
  65. package/_site/_test/knowledge-scopes-test.js +37 -37
  66. package/_site/_test/knowledge-storage-location-test.js +28 -28
  67. package/_site/_test/launcher-readiness-test.js +80 -80
  68. package/_site/_test/legacy-claude-session-alias-test.js +106 -106
  69. package/_site/_test/legacy-routes-removed-test.js +47 -47
  70. package/_site/_test/legacy-workbench-exclusion-test.js +92 -92
  71. package/_site/_test/live-gateway-test.js +48 -48
  72. package/_site/_test/local-marketplace-test.js +16 -16
  73. package/_site/_test/log-redaction-test.js +58 -58
  74. package/_site/_test/markdown-maintenance-test.js +11 -11
  75. package/_site/_test/model-context-windows-test.js +89 -89
  76. package/_site/_test/module-agent-start-proxy-test.js +65 -65
  77. package/_site/_test/module-artifact-integrity-test.js +27 -27
  78. package/_site/_test/module-boundary-test.js +30 -30
  79. package/_site/_test/module-bridge-eventbridge-test.js +202 -202
  80. package/_site/_test/module-dynamic-port-test.js +118 -118
  81. package/_site/_test/module-index-proxy-test.js +33 -33
  82. package/_site/_test/module-model-configuration-test.js +44 -44
  83. package/_site/_test/module-process-lifecycle-test.js +35 -35
  84. package/_site/_test/module-stream-proxy-test.js +34 -34
  85. package/_site/_test/module-terminal-restart-test.js +63 -63
  86. package/_site/_test/module-wiring-unbind-race-test.js +59 -59
  87. package/_site/_test/native-context-integrations-test.js +86 -86
  88. package/_site/_test/orphaned-claim-recovery-test.js +80 -80
  89. package/_site/_test/package-boundary-test.js +43 -42
  90. package/_site/_test/package-startup-test.js +56 -56
  91. package/_site/_test/packaged-ui-smoke-test.js +88 -88
  92. package/_site/_test/pr-consumer-contract-test.js +55 -55
  93. package/_site/_test/product-brand-contract-test.js +25 -25
  94. package/_site/_test/product-diagnostics-ui-test.js +93 -93
  95. package/_site/_test/product-import-ui-test.js +104 -104
  96. package/_site/_test/product-progress-status-test.js +12 -1
  97. package/_site/_test/project-remove-running-guard-test.js +79 -79
  98. package/_site/_test/project-store-test.js +90 -90
  99. package/_site/_test/registry-events-test.js +38 -38
  100. package/_site/_test/release-version-sync-test.js +115 -115
  101. package/_site/_test/requirement-binding-test.js +113 -113
  102. package/_site/_test/runtime-endpoint-test.js +64 -64
  103. package/_site/_test/scanner-test.js +83 -83
  104. package/_site/_test/server-security-test.js +96 -96
  105. package/_site/_test/sessions-stream-test.js +93 -93
  106. package/_site/_test/shared-scope-root-binding-test.js +67 -67
  107. package/_site/_test/simple-import-test.js +98 -98
  108. package/_site/_test/startup-analysis-disabled-test.js +6 -6
  109. package/_site/_test/team-knowledge-store-sparse-checkout-test.js +196 -196
  110. package/_site/_test/team-knowledge-store-test.js +132 -132
  111. package/_site/_test/test-server-cleanup-test.js +35 -35
  112. package/_site/_test/test-server-module-isolation-test.js +37 -37
  113. package/_site/_test/tracking-start-test.js +35 -35
  114. package/_site/_test/workbench-context-receipts-test.js +22 -22
  115. package/_site/_test/workspace-ui-contract-test.js +31 -31
  116. package/_site/_test/zcode-capture-integration-test.js +108 -108
  117. package/_site/lib/ai-vendor-presets.js +83 -83
  118. package/_site/lib/ai-workspace.js +3 -3
  119. package/_site/lib/atomic-file.js +204 -204
  120. package/_site/lib/bridge-adapter.js +260 -260
  121. package/_site/lib/capture-hook-config.js +108 -108
  122. package/_site/lib/claude-cli-runner.js +89 -89
  123. package/_site/lib/cli-instances.js +43 -43
  124. package/_site/lib/codex-context-status.js +17 -17
  125. package/_site/lib/codex-notify-config.js +193 -193
  126. package/_site/lib/commit-conversation-binder.js +12 -12
  127. package/_site/lib/commit-reconciler.js +38 -38
  128. package/_site/lib/context-pack-builder.js +299 -299
  129. package/_site/lib/conversation-exclusions.js +204 -204
  130. package/_site/lib/conversation-query-service.js +17 -17
  131. package/_site/lib/data-dir.js +13 -13
  132. package/_site/lib/embedding-service.js +85 -85
  133. package/_site/lib/engine-connection.js +93 -93
  134. package/_site/lib/engine-knowledge-client.js +72 -72
  135. package/_site/lib/folder-picker-output.js +3 -3
  136. package/_site/lib/git-path.js +14 -14
  137. package/_site/lib/github-team-store.js +3 -3
  138. package/_site/lib/index-builder.js +157 -157
  139. package/_site/lib/integration-status-scan.js +99 -99
  140. package/_site/lib/integration-status-worker.js +14 -14
  141. package/_site/lib/kb-framework.js +15 -15
  142. package/_site/lib/knowledge-db.js +363 -363
  143. package/_site/lib/knowledge-schema.js +121 -121
  144. package/_site/lib/live-gateway.js +78 -78
  145. package/_site/lib/llm-client.js +12 -12
  146. package/_site/lib/model-context-windows.js +82 -82
  147. package/_site/lib/module-bridge.js +874 -874
  148. package/_site/lib/module-port-resolver.js +57 -57
  149. package/_site/lib/post-commit-automation.js +54 -54
  150. package/_site/lib/product-data.js +35 -35
  151. package/_site/lib/project-lifecycle-service.js +14 -14
  152. package/_site/lib/project-registry-store.js +129 -129
  153. package/_site/lib/prompt-registry.js +148 -148
  154. package/_site/lib/registry-events.js +16 -16
  155. package/_site/lib/requirement-adapters.js +10 -10
  156. package/_site/lib/requirement-binder.js +112 -112
  157. package/_site/lib/runtime-control.js +89 -89
  158. package/_site/lib/runtime-endpoint.js +5 -5
  159. package/_site/lib/zcode-context-integration.js +60 -60
  160. package/_site/scripts/codex-notify-fanout.cjs +95 -95
  161. package/_site/scripts/install-module-candidates.js +69 -69
  162. package/_site/scripts/pack-module-candidates.js +89 -89
  163. package/_site/scripts/sync-product-content.js +28 -28
  164. package/_site/scripts/sync-release-version.js +164 -164
  165. package/_site/scripts/vendor-modules.js +49 -49
  166. package/_site/scripts/verify-module-runtime.js +50 -50
  167. package/_site/scripts/verify-product-runtime.js +36 -36
  168. package/_site/scripts/verify-retrieval-gold.js +83 -83
  169. package/_site/server.js +15 -15
  170. package/_site/start.bat +26 -26
  171. package/_site/stop.bat +11 -11
  172. package/bin/project-knowledge-integrations.js +254 -254
  173. package/bin/project-knowledge-kb.js +67 -67
  174. package/bin/project-knowledge-mcp.js +8 -8
  175. package/bin/project-knowledge.js +170 -170
  176. package/claude-prompts.json +21 -21
  177. package/docs/README.zh-CN.md +205 -205
  178. package/docs/assets/architecture.svg +181 -181
  179. package/docs/assets/logo.svg +49 -49
  180. package/docs/fresh-v5-start.md +42 -42
  181. package/docs/leader-glm-workbench-playbook.md +122 -122
  182. package/docs/project-registry-schema.md +11 -11
  183. package/docs/release-5.0.16-acceptance.md +176 -176
  184. package/docs/release-5.0.17-acceptance.md +117 -117
  185. package/docs/release-5.0.19-acceptance.md +39 -25
  186. package/docs/team-knowledge-mode-a-plan.md +73 -73
  187. package/module-runtime-manifest.json +53 -33
  188. package/package.json +3 -2
  189. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  190. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  191. package/plugins/project-knowledge/.mcp.json +1 -1
  192. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
  193. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
  194. package/templates/change.md +30 -30
  195. package/templates/project-readme.md +18 -18
  196. package/ui/index.html +1 -1
  197. package/ui/knowledge-panel.html +118 -0
  198. package/ui/product.css +8 -0
  199. package/ui/product.js +146 -4
  200. package/vendor-manifest.json +55 -54
@@ -1,473 +1,473 @@
1
- // Run: node _site/_test/integration-runtime-binding-test.js
2
- //
3
- // Covers the local MCP launcher contract (no npx, no network), the durable
4
- // integration-runtime binding, installer binding writes, the mcpStartup
5
- // status probe, and the release-format contracts for the new .mcp.json.
6
-
7
- const fs = require('node:fs');
8
- const os = require('node:os');
9
- const path = require('node:path');
10
- const { spawn, spawnSync, fork } = require('node:child_process');
11
- const { IntegrationManager, INTEGRATION_NAME } = require('../lib/integration-installer');
12
- const { IntegrationStatusScan } = require('../lib/integration-status-scan');
13
- const { inspectReleaseVersion } = require('../../_site/scripts/sync-release-version');
14
-
15
- const ROOT = path.resolve(__dirname, '..', '..');
16
- const PLUGIN_ROOT = path.join(ROOT, 'plugins', 'project-knowledge');
17
- const LAUNCHER = path.join(PLUGIN_ROOT, 'scripts', 'mcp-launcher.cjs');
18
- const RUNTIME_SCHEMA = 'project-knowledge/integration-runtime/v1';
19
- const TEMP = fs.mkdtempSync(path.join(os.tmpdir(), `pk-integration-runtime-${process.pid}-`));
20
-
21
- function assert(condition, message) {
22
- if (!condition) throw new Error(message);
23
- }
24
-
25
- function readJson(filePath) {
26
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
27
- }
28
-
29
- function runLauncher({ dataDir, env = {} }) {
30
- const result = spawnSync(process.execPath, [LAUNCHER], {
31
- encoding: 'utf8',
32
- windowsHide: true,
33
- env: { ...process.env, KB_DATA_DIR: dataDir, ...env },
34
- timeout: 15000,
35
- });
36
- return result;
37
- }
38
-
39
- function parseLauncherStderr(result) {
40
- const lines = String(result.stderr || '').split(/\r?\n/).map(line => line.trim()).filter(Boolean);
41
- assert(lines.length === 1, 'launcher diagnostics must be exactly one stderr line for failures');
42
- return JSON.parse(lines[0]);
43
- }
44
-
45
- function writeBinding(dataDir, binding) {
46
- fs.mkdirSync(dataDir, { recursive: true });
47
- fs.writeFileSync(path.join(dataDir, 'integration-runtime.json'), JSON.stringify(binding, null, 2));
48
- }
49
-
50
- function fakePackage(dir, { name = '@sanqianx/project-knowledge', version = '9.9.9', withEntry = true }) {
51
- fs.mkdirSync(path.join(dir, 'bin'), { recursive: true });
52
- fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name, version, bin: { 'project-knowledge-mcp': 'bin/project-knowledge-mcp.js' } }));
53
- if (withEntry) fs.writeFileSync(path.join(dir, 'bin', 'project-knowledge-mcp.js'), '#!/usr/bin/env node\nprocess.exit(0);\n');
54
- }
55
-
56
- async function mcpHandshake({ dataDir, env = {} }) {
57
- // Line-delimited JSON-RPC handshake against the launcher, asserting every
58
- // stdout line parses as JSON (no stdio pollution). Resolves when the
59
- // initialize response arrives: a healthy server keeps running to serve
60
- // requests, so waiting for process exit would only hit the timeout.
61
- return await new Promise((resolve, reject) => {
62
- const child = spawn(process.execPath, [LAUNCHER], {
63
- windowsHide: true,
64
- env: { ...process.env, KB_DATA_DIR: dataDir, ...env },
65
- });
66
- const killTree = () => {
67
- if (!child.pid) return;
68
- try { process.platform === 'win32' ? spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, timeout: 5000 }) : child.kill(); } catch {}
69
- };
70
- const timer = setTimeout(() => { killTree(); reject(new Error('launcher handshake timeout')); }, 20000);
71
- let settled = false;
72
- const settle = result => {
73
- if (settled) return;
74
- settled = true;
75
- clearTimeout(timer);
76
- killTree();
77
- resolve(result);
78
- };
79
- let buffer = '';
80
- const responses = [];
81
- child.stdout.setEncoding('utf8');
82
- child.stdout.on('data', chunk => {
83
- buffer += chunk;
84
- let index;
85
- while ((index = buffer.indexOf('\n')) >= 0) {
86
- const line = buffer.slice(0, index).trim();
87
- buffer = buffer.slice(index + 1);
88
- if (!line) continue;
89
- responses.push(JSON.parse(line));
90
- }
91
- if (responses.some(message => message.id === 1)) settle({ responses, stderr: '' });
92
- });
93
- const stderr = [];
94
- child.stderr.setEncoding('utf8');
95
- child.stderr.on('data', chunk => stderr.push(chunk));
96
- child.on('close', code => {
97
- settle({ code, responses, stderr: stderr.join('') });
98
- });
99
- child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'pk-binding-test', version: '1' } } }) + '\n');
100
- });
101
- }
102
-
103
- async function expectFailureCode(name, { dataDir, env, binding, fakePkg, fakePkgOptions }) {
104
- const dir = path.join(TEMP, name);
105
- if (binding) writeBinding(dir, binding);
106
- else fs.mkdirSync(dir, { recursive: true });
107
- if (fakePkg) fakePackage(fakePkg, fakePkgOptions || {});
108
- const result = runLauncher({ dataDir: dir, env });
109
- assert(result.status !== 0, `${name}: launcher must exit non-zero`);
110
- const payload = parseLauncherStderr(result);
111
- assert(payload.schema === 'project-knowledge/mcp-launcher-error/v1', `${name}: error payload must carry the launcher error schema`);
112
- assert(payload.code === bindingCode(name), `${name}: unexpected code ${payload.code}`);
113
- assert(String(result.stdout || '').trim() === '', `${name}: launcher must not write diagnostics to stdout`);
114
- }
115
-
116
- function bindingCode(name) {
117
- return {
118
- missing: 'BINDING_MISSING',
119
- corrupt: 'BINDING_CORRUPT',
120
- schema: 'BINDING_SCHEMA_MISMATCH',
121
- package: 'BINDING_PACKAGE_MISMATCH',
122
- version: 'BINDING_VERSION_MISMATCH',
123
- root: 'BINDING_INVALID_ROOT',
124
- entry: 'BINDING_ENTRY_MISSING',
125
- }[name];
126
- }
127
-
128
- async function testMcpManifestContract() {
129
- const manifest = readJson(path.join(PLUGIN_ROOT, '.mcp.json'));
130
- const server = manifest.mcpServers['project-knowledge'];
131
- assert(server, '.mcp.json must keep the project-knowledge server');
132
- assert(server.type === 'stdio', 'server must stay stdio');
133
- assert(server.command === 'node', 'the default MCP entry must use the local Node, not npx');
134
- assert(!JSON.stringify(server).includes('npx'), 'the plugin MCP chain must not depend on npx anymore');
135
- assert(!/@sanqianx\/project-knowledge@/.test(JSON.stringify(server)), 'the plugin MCP chain must not pin an npx package argument');
136
- assert(Array.isArray(server.args) && server.args[0] === '-e', 'the launcher bootstrap must run through node -e');
137
- const bootstrap = server.args[1];
138
- assert(typeof bootstrap === 'string' && bootstrap.includes('mcp-launcher.cjs'), 'the bootstrap must locate the plugin launcher script');
139
- assert(bootstrap.includes('CLAUDE_PLUGIN_ROOT') && bootstrap.includes('PLUGIN_ROOT'), 'the bootstrap must honor both native plugin-root variables');
140
- assert(server.cwd === undefined, 'A2: no cwd pin; the bootstrap must not resolve relative to a working directory');
141
- assert(server.env && server.env.KB_PLUGIN_VERSION === readJson(path.join(ROOT, 'package.json')).version, 'A2: env.KB_PLUGIN_VERSION must carry the shipping version');
142
- assert(!bootstrap.includes('process.cwd'), 'A2: the bootstrap must never consult process.cwd');
143
- assert(fs.existsSync(LAUNCHER), 'the launcher script must ship inside the plugin');
144
- }
145
-
146
- async function testLauncherFailureMatrix() {
147
- const goodPkg = path.join(TEMP, 'good-pkg');
148
- fakePackage(goodPkg, { version: '9.9.9' });
149
-
150
- await expectFailureCode('missing', {});
151
- fs.mkdirSync(path.join(TEMP, 'corrupt'), { recursive: true });
152
- fs.writeFileSync(path.join(TEMP, 'corrupt', 'integration-runtime.json'), '{ not json');
153
- await expectFailureCode('corrupt', { binding: null });
154
- const dir = name => path.join(TEMP, name);
155
- writeBinding(dir('schema'), { schema: 'other/v2' });
156
- await expectFailureCode('schema', { binding: readJson(path.join(dir('schema'), 'integration-runtime.json')) });
157
- writeBinding(dir('package'), { schema: RUNTIME_SCHEMA, packageName: '@other/pkg', packageRoot: goodPkg, version: '9.9.9' });
158
- await expectFailureCode('package', { binding: readJson(path.join(dir('package'), 'integration-runtime.json')) });
159
- writeBinding(dir('version'), { schema: RUNTIME_SCHEMA, packageName: '@sanqianx/project-knowledge', packageRoot: goodPkg, version: '1.2.3' });
160
- await expectFailureCode('version', { binding: readJson(path.join(dir('version'), 'integration-runtime.json')) });
161
- writeBinding(dir('root'), { schema: RUNTIME_SCHEMA, packageName: '@sanqianx/project-knowledge', packageRoot: 'relative/pkg/root', version: '9.9.9' });
162
- await expectFailureCode('root', { binding: readJson(path.join(dir('root'), 'integration-runtime.json')) });
163
- const noEntry = path.join(TEMP, 'no-entry-pkg');
164
- fakePackage(noEntry, { version: '9.9.9', withEntry: false });
165
- writeBinding(dir('entry'), { schema: RUNTIME_SCHEMA, packageName: '@sanqianx/project-knowledge', packageRoot: noEntry, version: '9.9.9' });
166
- await expectFailureCode('entry', { binding: readJson(path.join(dir('entry'), 'integration-runtime.json')) });
167
- }
168
-
169
- async function testRealHandshakeIgnoresBrokenNpxCache() {
170
- // A corrupted _npx entry (missing package.json) must not affect the local
171
- // launcher chain at all — that is the regression this whole feature fixes.
172
- const dataDir = path.join(TEMP, '用户 空格 知识库', 'data');
173
- fs.mkdirSync(dataDir, { recursive: true });
174
- const packageInfo = readJson(path.join(ROOT, 'package.json'));
175
- writeBinding(dataDir, { schema: RUNTIME_SCHEMA, packageName: packageInfo.name, packageRoot: ROOT, version: packageInfo.version, updatedAt: new Date().toISOString() });
176
- const brokenCache = path.join(TEMP, '用户 空格 知识库', 'npm-cache');
177
- fs.mkdirSync(path.join(brokenCache, '_npx', '7581c64052dde81c'), { recursive: true });
178
- fs.mkdirSync(path.join(brokenCache, '_npx', '7581c64052dde81c', 'node_modules'), { recursive: true });
179
- const result = await mcpHandshake({ dataDir, env: { npm_config_cache: brokenCache } });
180
- assert(result.code === 0 || result.responses.length, 'the local chain must initialize despite a broken npx cache');
181
- const init = result.responses.find(message => message.id === 1);
182
- assert(init && !init.error, 'initialize must succeed');
183
- assert(init.result.serverInfo.name === 'project-knowledge', 'serverInfo must identify project-knowledge');
184
- assert(init.result.serverInfo.version === packageInfo.version, 'the bound local package version must be reported');
185
- assert(String(result.stderr || '').trim() === '', 'a healthy launch writes nothing to stderr');
186
- }
187
-
188
- async function testBootstrapResolvesForBothNativeForms() {
189
- const manifest = readJson(path.join(PLUGIN_ROOT, '.mcp.json'));
190
- const bootstrap = manifest.mcpServers['project-knowledge'].args[1];
191
- const dataDir = path.join(TEMP, 'bootstrap-forms');
192
- fs.mkdirSync(dataDir, { recursive: true });
193
- // Test isolation: the host session may itself run inside a native plugin
194
- // (CLAUDE_PLUGIN_ROOT pointing at claude-mem, etc.); the bootstrap under
195
- // test must not silently prefer that unrelated root.
196
- const baseEnv = { ...process.env };
197
- delete baseEnv.CLAUDE_PLUGIN_ROOT;
198
- delete baseEnv.PLUGIN_ROOT;
199
- const run = env => spawnSync(process.execPath, ['-e', bootstrap], {
200
- encoding: 'utf8', windowsHide: true, timeout: 15000,
201
- env: { ...baseEnv, KB_DATA_DIR: dataDir, ...env },
202
- cwd: env.PLUGIN_ROOT || env.CLAUDE_PLUGIN_ROOT || PLUGIN_ROOT,
203
- });
204
- // A2: without a plugin-root env the bootstrap must NOT fall back to cwd.
205
- const decoyDir = path.join(TEMP, 'bootstrap-decoy');
206
- fs.mkdirSync(path.join(decoyDir, 'scripts'), { recursive: true });
207
- fs.writeFileSync(path.join(decoyDir, 'scripts', 'mcp-launcher.cjs'), 'process.exit(7);\n');
208
- const codex = spawnSync(process.execPath, ['-e', bootstrap], {
209
- encoding: 'utf8', windowsHide: true, timeout: 15000,
210
- env: { ...baseEnv, KB_DATA_DIR: dataDir }, cwd: decoyDir,
211
- });
212
- assert(codex.status === 127, 'A2: without a trusted root or usable binding the bootstrap exits 127, got ' + codex.status);
213
- // Claude form: CLAUDE_PLUGIN_ROOT is exported to MCP stdio servers.
214
- const claude = run({ CLAUDE_PLUGIN_ROOT: PLUGIN_ROOT, cwd: undefined });
215
- assert(claude.status === 1 && /BINDING_MISSING/.test(String(claude.stderr || '')), 'the CLAUDE_PLUGIN_ROOT form must reach the launcher');
216
- const codexCompat = run({ PLUGIN_ROOT: PLUGIN_ROOT });
217
- assert(codexCompat.status === 1 && /BINDING_MISSING/.test(String(codexCompat.stderr || '')), 'the PLUGIN_ROOT form must reach the launcher');
218
- // A2: the verified binding fallback loads the in-package launcher with no env root.
219
- const fakePkg = path.join(TEMP, 'bootstrap-fake-pkg');
220
- const fakeLauncher = path.join(fakePkg, 'plugins', 'project-knowledge', 'scripts', 'mcp-launcher.cjs');
221
- fs.mkdirSync(path.dirname(fakeLauncher), { recursive: true });
222
- fs.writeFileSync(fakeLauncher, 'process.stderr.write(\'BINDING_FALLBACK_REACHED\'); process.exit(5);\n');
223
- writeBinding(dataDir, { schema: RUNTIME_SCHEMA, packageName: '@sanqianx/project-knowledge', packageRoot: fakePkg, version: '0.0.0' });
224
- const bound = spawnSync(process.execPath, ['-e', bootstrap], {
225
- encoding: 'utf8', windowsHide: true, timeout: 15000,
226
- env: { ...baseEnv, KB_DATA_DIR: dataDir }, cwd: decoyDir,
227
- });
228
- assert(bound.status === 5 && /BINDING_FALLBACK_REACHED/.test(String(bound.stderr || '')), 'the verified binding fallback must load the in-package launcher');
229
- }
230
-
231
- async function testInstallerBindingLifecycle() {
232
- const home = path.join(TEMP, 'installer-home');
233
- const dataDir = path.join(home, '.project-knowledge-v5');
234
- const bindingPath = path.join(dataDir, 'integration-runtime.json');
235
- const manager = new IntegrationManager({
236
- rootDir: ROOT,
237
- homeDir: home,
238
- env: { KB_DATA_DIR: dataDir },
239
- commandResolver: name => name,
240
- runner: () => ({ status: 0, stdout: '', stderr: '' }),
241
- });
242
- assert(typeof manager.ensureIntegrationRuntimeBinding === 'function', 'the installer must expose the binding writer');
243
- const packageInfo = readJson(path.join(ROOT, 'package.json'));
244
- manager.ensureIntegrationRuntimeBinding();
245
- const first = readJson(bindingPath);
246
- assert(first.schema === RUNTIME_SCHEMA, 'binding must carry the integration-runtime schema');
247
- assert(first.packageName === packageInfo.name, 'binding must pin the package name');
248
- assert(first.packageRoot === ROOT, 'binding must pin the absolute package root');
249
- assert(first.version === packageInfo.version, 'binding must pin the package version');
250
- assert(!JSON.stringify(first).match(/token|secret|key/i), 'binding must not carry credentials');
251
- // Idempotent repair: a second explicit install keeps the binding valid.
252
- manager.ensureIntegrationRuntimeBinding();
253
- const second = readJson(bindingPath);
254
- assert(second.packageRoot === first.packageRoot && second.version === first.version && second.packageName === first.packageName, 'repeated installs must keep the binding stable');
255
-
256
- // A failed atomic write keeps the previous binding byte-for-byte.
257
- const before = fs.readFileSync(bindingPath);
258
- let failed = false;
259
- try {
260
- manager.ensureIntegrationRuntimeBinding({ beforeRename: () => { throw new Error('disk full'); } });
261
- } catch (error) {
262
- failed = true;
263
- assert(/disk full/.test(error.message), 'write failures must surface, not be swallowed');
264
- }
265
- assert(failed, 'an injected rename failure must throw');
266
- assert(fs.readFileSync(bindingPath).equals(before), 'a failed atomic write must preserve the old binding');
267
- assert(!fs.readdirSync(dataDir).some(name => name.endsWith('.tmp')), 'no temp residue may survive a failed write');
268
-
269
- // dry-run never writes a binding.
270
- const dryHome = path.join(TEMP, 'installer-dry-home');
271
- new IntegrationManager({ rootDir: ROOT, homeDir: dryHome, env: { KB_DATA_DIR: path.join(dryHome, 'data') }, dryRun: true }).ensureIntegrationRuntimeBinding();
272
- assert(!fs.existsSync(path.join(dryHome, 'data', 'integration-runtime.json')), 'dry-run must not write the binding');
273
- }
274
-
275
- async function testInstallAllCaptureOnlySkipsBinding() {
276
- const home = path.join(TEMP, 'install-all-home');
277
- const dataDir = path.join(home, '.project-knowledge-v5');
278
- const bridgeStub = {
279
- createBridge: () => ({
280
- registerConsumer: async () => ({}),
281
- getConsumer: async () => ({}),
282
- getHealth: async () => ({}),
283
- ensureRuntimeHome: async () => ({}),
284
- installers: {
285
- claudeCode: { installClaudeCodeHook: async () => ({ added: [] }), statusClaudeCodeHook: async () => ({ installed: false }), uninstallClaudeCodeHook: async () => ({}) },
286
- codex: { statusCodexHook: async () => ({ installed: false }) },
287
- openCode: { installOpenCodePlugin: async () => ({}), statusOpenCodePlugin: async () => ({ installed: false }), uninstallOpenCodePlugin: async () => ({}) },
288
- zcode: { installZcodeHook: async () => ({}), statusZcodeHook: async () => ({ installed: false }), uninstallZcodeHook: async () => ({}) },
289
- },
290
- }),
291
- };
292
- const manager = new IntegrationManager({
293
- rootDir: ROOT,
294
- homeDir: home,
295
- env: { KB_DATA_DIR: dataDir },
296
- commandResolver: name => name,
297
- runner: () => ({ status: 0, stdout: '[]', stderr: '' }),
298
- bridgeModule: bridgeStub,
299
- });
300
- await manager.installAll({ clients: ['claude'], captureOnly: true });
301
- assert(!fs.existsSync(path.join(dataDir, 'integration-runtime.json')), 'A2: captureOnly must not write the knowledge runtime binding');
302
- }
303
-
304
- async function testMcpStartupProbe() {
305
- const home = path.join(TEMP, 'probe-home');
306
- const dataDir = path.join(home, '.project-knowledge-v5');
307
- const packageInfo = readJson(path.join(ROOT, 'package.json'));
308
- writeBinding(dataDir, { schema: RUNTIME_SCHEMA, packageName: packageInfo.name, packageRoot: ROOT, version: packageInfo.version, updatedAt: new Date().toISOString() });
309
- const manager = new IntegrationManager({
310
- rootDir: ROOT,
311
- homeDir: home,
312
- env: { KB_DATA_DIR: dataDir },
313
- commandResolver: name => name,
314
- runner: () => ({ status: 0, stdout: '[]', stderr: '' }),
315
- bridgeModule: {
316
- createBridge: () => ({
317
- getConsumer: async () => ({}),
318
- getHealth: async () => ({}),
319
- installers: {
320
- claudeCode: { statusClaudeCodeHook: async () => ({ installed: false }) },
321
- codex: { statusCodexHook: async () => ({ installed: false }) },
322
- },
323
- }),
324
- },
325
- });
326
- assert(typeof manager.probeMcpStartup === 'function', 'the installer must expose the MCP startup probe');
327
- const ready = await manager.probeMcpStartup();
328
- assert(ready.state === 'ready', `a healthy binding must probe ready, got ${JSON.stringify(ready)}`);
329
- assert(ready.actualVersion === packageInfo.version && ready.expectedVersion === packageInfo.version, 'the probe must report both versions');
330
- assert(ready.scope === 'product-runtime' && ready.serverName === 'project-knowledge', 'A2: the probe reports its scope and the verified server identity');
331
- assert(Array.isArray(ready.tools) && ready.tools.length === 6, 'A2: the probe verifies the six knowledge tools');
332
- assert(typeof ready.checkedAt === 'string', 'the probe must record checkedAt');
333
-
334
- // A broken binding must surface a failed probe with a machine code.
335
- fs.writeFileSync(path.join(dataDir, 'integration-runtime.json'), '{ broken');
336
- const failed = await manager.probeMcpStartup();
337
- assert(failed.state === 'failed', `a corrupted binding must probe failed, got ${JSON.stringify(failed)}`);
338
- assert(typeof failed.code === 'string' && failed.code, 'failed probes must carry a code');
339
- assert(typeof failed.detail === 'string', 'failed probes must carry a bounded detail');
340
-
341
- // Probe details must be sanitized: a launcher that prints a token must not
342
- // leak it into status output.
343
- const leaky = path.join(TEMP, 'leaky-launcher.cjs');
344
- fs.writeFileSync(leaky, 'process.stderr.write("boom sk-abcdef123456 token\\n"); process.exit(3);\n');
345
- const leakyProbe = await manager.probeMcpStartup({ launcherPath: leaky });
346
- assert(leakyProbe.state === 'failed', 'the leaky launcher must count as failed');
347
- assert(!JSON.stringify(leakyProbe).includes('sk-abcdef123456'), 'probe details must redact credential-shaped strings');
348
- assert(JSON.stringify(leakyProbe).length < 2000, 'probe details must stay bounded');
349
-
350
- // statusAll must attach mcpStartup for MCP-capable clients and honor the
351
- // injected probe (so UI refreshes reuse the cached scan instead of spawning).
352
- let probeCalls = 0;
353
- const counting = new IntegrationManager({
354
- rootDir: ROOT,
355
- homeDir: home,
356
- env: { KB_DATA_DIR: dataDir },
357
- commandResolver: name => name,
358
- runner: () => ({ status: 0, stdout: '[]', stderr: '' }),
359
- mcpProbe: async () => { probeCalls += 1; return { state: 'ready', checkedAt: new Date().toISOString(), actualVersion: packageInfo.version, expectedVersion: packageInfo.version }; },
360
- bridgeModule: manager.bridge,
361
- });
362
- const summary = await counting.statusAll({ clients: ['claude', 'codex', 'zcode'] });
363
- const claude = summary.clients.find(entry => entry.client === 'claude');
364
- const codex = summary.clients.find(entry => entry.client === 'codex');
365
- assert(claude.mcpStartup?.code === 'CLIENT_PLUGIN_ENTRY_MISSING', 'A2: claude without an installed plugin entry reports the explicit miss');
366
- assert(codex.mcpStartup?.code === 'CLIENT_PLUGIN_ENTRY_MISSING', 'A2: codex without an installed plugin entry reports the explicit miss');
367
- assert(summary.mcpRuntime?.state === 'ready', 'A2: the shared product-runtime probe lands in the summary');
368
- assert(probeCalls === 1, 'A2: only the host product-runtime probe runs when no installed entries exist');
369
- }
370
-
371
- async function testStatusScanDoesNotRespawn() {
372
- // UI refreshes funnel through the cached scan; identical reads within the
373
- // TTL must not fork another probe worker.
374
- const counter = path.join(TEMP, 'scan-count.txt');
375
- const worker = path.join(TEMP, 'scan-worker.js');
376
- fs.writeFileSync(worker, `${'const fs = require(\'node:fs\');'}
377
- process.once('message', async input => {
378
- const counter = ${JSON.stringify(counter)};
379
- const count = fs.existsSync(counter) ? Number(fs.readFileSync(counter, 'utf8')) + 1 : 1;
380
- fs.writeFileSync(counter, String(count));
381
- process.send({ ok: true, summary: { bridge: { ok: true }, clients: [{ client: input.statusOptions.clients?.[0] || 'claude', mcpStartup: { state: 'ready' } }] } }, () => process.disconnect());
382
- });
383
- `);
384
- const scan = new IntegrationStatusScan({ workerFile: worker, timeoutMs: 20000 });
385
- const options = { rootDir: ROOT, homeDir: TEMP, bridgeHomeDir: TEMP };
386
- await scan.read(options, { clients: ['claude'] }, { waitMs: 5000 });
387
- await scan.read(options, { clients: ['claude'] }, { waitMs: 5000 });
388
- assert(Number(fs.readFileSync(counter, 'utf8')) === 1, 'a cached scan must not fork another worker for the same key');
389
- await scan.read(options, { clients: ['claude'] }, { force: true, waitMs: 5000 });
390
- assert(Number(fs.readFileSync(counter, 'utf8')) === 2, 'force refresh must re-run the scan');
391
- scan.close();
392
- }
393
-
394
- async function testCodexTrustSeparatedFromWaitingTrust() {
395
- // The same already-trusted definition must not be reported as waiting-trust.
396
- const home = path.join(TEMP, 'codex-trust-home');
397
- const manager = new IntegrationManager({
398
- rootDir: ROOT,
399
- homeDir: home,
400
- env: {},
401
- commandResolver: name => name,
402
- runner: () => ({ status: 0, stdout: JSON.stringify({ installed: [{ pluginId: 'project-knowledge@project-knowledge', version: readJson(path.join(ROOT, 'package.json')).version, enabled: true, source: { path: path.join(ROOT, 'plugins', 'project-knowledge') } }] }), stderr: '' }),
403
- codexHookProbe: async () => ({ data: [{ cwd: home, hooks: [{ pluginId: 'project-knowledge@project-knowledge', eventName: 'userPromptSubmit', command: 'node "…/scripts/context-hook.cjs" --client codex', enabled: true, trustStatus: 'trusted' }] }] }),
404
- bridgeModule: {
405
- createBridge: () => ({ getConsumer: async () => ({}), getHealth: async () => ({}), installers: { codex: { statusCodexHook: async () => ({ installed: false }) } } }),
406
- },
407
- });
408
- const status = await manager.automaticCodexContextStatus(manager.statusCodex(), home);
409
- assert(status.state === 'configured', `an already-trusted matching definition must be configured, not waiting-trust (got ${status.state})`);
410
- assert(status.trustStatus === 'trusted', 'the native trust status must be surfaced');
411
- }
412
-
413
- async function testReleaseContracts() {
414
- const { drift } = inspectReleaseVersion(ROOT, { webOnly: true });
415
- assert(!drift.includes('plugins/project-knowledge/.mcp.json'), `the shipped launcher .mcp.json must satisfy the release contract (drift: ${drift.join(', ')})`);
416
-
417
- const mini = path.join(TEMP, 'release-mini');
418
- fs.mkdirSync(path.join(mini, 'plugins', 'project-knowledge', '.claude-plugin'), { recursive: true });
419
- fs.mkdirSync(path.join(mini, 'plugins', 'project-knowledge', '.codex-plugin'), { recursive: true });
420
- fs.mkdirSync(path.join(mini, '.claude-plugin'), { recursive: true });
421
- fs.writeFileSync(path.join(mini, 'package.json'), JSON.stringify({ name: '@sanqianx/project-knowledge', version: '1.0.0' }));
422
- fs.writeFileSync(path.join(mini, 'package-lock.json'), JSON.stringify({ name: '@sanqianx/project-knowledge', version: '1.0.0', packages: { '': { version: '1.0.0' } } }));
423
- fs.writeFileSync(path.join(mini, 'plugins', 'project-knowledge', '.claude-plugin', 'plugin.json'), JSON.stringify({ version: '1.0.0' }));
424
- fs.writeFileSync(path.join(mini, 'plugins', 'project-knowledge', '.codex-plugin', 'plugin.json'), JSON.stringify({ version: '1.0.0' }));
425
- fs.writeFileSync(path.join(mini, '.claude-plugin', 'marketplace.json'), JSON.stringify({ plugins: [{ version: '1.0.0' }] }));
426
- fs.writeFileSync(path.join(mini, 'plugins', 'project-knowledge', '.mcp.json'), JSON.stringify({
427
- mcpServers: { 'project-knowledge': { type: 'stdio', command: 'npx', args: ['-y', '--package', '@sanqianx/project-knowledge@1.0.0', 'project-knowledge-mcp'] } },
428
- }, null, 2));
429
- let rejected = false;
430
- try { inspectReleaseVersion(mini, { webOnly: true }); } catch (error) { rejected = /pinned|npx|launcher/i.test(error.message); }
431
- assert(rejected, 'the release check must reject a resurrected npx-pinned .mcp.json');
432
-
433
- const staleEnv = path.join(TEMP, 'release-stale-env');
434
- fs.mkdirSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.claude-plugin'), { recursive: true });
435
- fs.mkdirSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.codex-plugin'), { recursive: true });
436
- fs.mkdirSync(path.join(staleEnv, '.claude-plugin'), { recursive: true });
437
- fs.writeFileSync(path.join(staleEnv, 'package.json'), JSON.stringify({ name: '@sanqianx/project-knowledge', version: '1.0.0' }));
438
- fs.writeFileSync(path.join(staleEnv, 'package-lock.json'), JSON.stringify({ name: '@sanqianx/project-knowledge', version: '1.0.0', packages: { '': { version: '1.0.0' } } }));
439
- fs.writeFileSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.claude-plugin', 'plugin.json'), JSON.stringify({ version: '1.0.0' }));
440
- fs.writeFileSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.codex-plugin', 'plugin.json'), JSON.stringify({ version: '1.0.0' }));
441
- fs.writeFileSync(path.join(staleEnv, '.claude-plugin', 'marketplace.json'), JSON.stringify({ plugins: [{ version: '1.0.0' }] }));
442
- fs.writeFileSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.mcp.json'), JSON.stringify({
443
- mcpServers: { 'project-knowledge': { type: 'stdio', command: 'node', args: ['-e', "require('scripts/mcp-launcher.cjs')"], cwd: '.', env: { KB_PLUGIN_VERSION: '0.9.9' } } },
444
- }, null, 2));
445
- let envRejected = false;
446
- try { inspectReleaseVersion(staleEnv, { webOnly: true }); } catch (error) { envRejected = /cwd|KB_PLUGIN_VERSION|plugin version|env/i.test(error.message); }
447
- assert(envRejected, 'the release check must reject a drifted env.KB_PLUGIN_VERSION and a resurrected cwd pin');
448
-
449
- const manifest = readJson(path.join(ROOT, 'module-runtime-manifest.json'));
450
- assert(manifest.productFiles && manifest.productFiles['plugins/project-knowledge/scripts/mcp-launcher.cjs'], 'the packaged product manifest must track the launcher');
451
- for (const script of ['_site/scripts/sync-product-content.js', '_site/scripts/verify-product-runtime.js']) {
452
- assert(fs.readFileSync(path.join(ROOT, script), 'utf8').includes('mcp-launcher.cjs'), `${script} must include the launcher in the product asset checklist`);
453
- }
454
- }
455
-
456
- async function main() {
457
- await testMcpManifestContract();
458
- await testLauncherFailureMatrix();
459
- await testRealHandshakeIgnoresBrokenNpxCache();
460
- await testBootstrapResolvesForBothNativeForms();
461
- await testInstallerBindingLifecycle();
462
- await testInstallAllCaptureOnlySkipsBinding();
463
- await testMcpStartupProbe();
464
- await testStatusScanDoesNotRespawn();
465
- await testCodexTrustSeparatedFromWaitingTrust();
466
- await testReleaseContracts();
467
- console.log('INTEGRATION_RUNTIME_BINDING_TEST_PASSED');
468
- }
469
-
470
- main().catch(error => {
471
- console.error('INTEGRATION_RUNTIME_BINDING_TEST_FAILED', error.message);
472
- process.exit(1);
473
- });
1
+ // Run: node _site/_test/integration-runtime-binding-test.js
2
+ //
3
+ // Covers the local MCP launcher contract (no npx, no network), the durable
4
+ // integration-runtime binding, installer binding writes, the mcpStartup
5
+ // status probe, and the release-format contracts for the new .mcp.json.
6
+
7
+ const fs = require('node:fs');
8
+ const os = require('node:os');
9
+ const path = require('node:path');
10
+ const { spawn, spawnSync, fork } = require('node:child_process');
11
+ const { IntegrationManager, INTEGRATION_NAME } = require('../lib/integration-installer');
12
+ const { IntegrationStatusScan } = require('../lib/integration-status-scan');
13
+ const { inspectReleaseVersion } = require('../../_site/scripts/sync-release-version');
14
+
15
+ const ROOT = path.resolve(__dirname, '..', '..');
16
+ const PLUGIN_ROOT = path.join(ROOT, 'plugins', 'project-knowledge');
17
+ const LAUNCHER = path.join(PLUGIN_ROOT, 'scripts', 'mcp-launcher.cjs');
18
+ const RUNTIME_SCHEMA = 'project-knowledge/integration-runtime/v1';
19
+ const TEMP = fs.mkdtempSync(path.join(os.tmpdir(), `pk-integration-runtime-${process.pid}-`));
20
+
21
+ function assert(condition, message) {
22
+ if (!condition) throw new Error(message);
23
+ }
24
+
25
+ function readJson(filePath) {
26
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
27
+ }
28
+
29
+ function runLauncher({ dataDir, env = {} }) {
30
+ const result = spawnSync(process.execPath, [LAUNCHER], {
31
+ encoding: 'utf8',
32
+ windowsHide: true,
33
+ env: { ...process.env, KB_DATA_DIR: dataDir, ...env },
34
+ timeout: 15000,
35
+ });
36
+ return result;
37
+ }
38
+
39
+ function parseLauncherStderr(result) {
40
+ const lines = String(result.stderr || '').split(/\r?\n/).map(line => line.trim()).filter(Boolean);
41
+ assert(lines.length === 1, 'launcher diagnostics must be exactly one stderr line for failures');
42
+ return JSON.parse(lines[0]);
43
+ }
44
+
45
+ function writeBinding(dataDir, binding) {
46
+ fs.mkdirSync(dataDir, { recursive: true });
47
+ fs.writeFileSync(path.join(dataDir, 'integration-runtime.json'), JSON.stringify(binding, null, 2));
48
+ }
49
+
50
+ function fakePackage(dir, { name = '@sanqianx/project-knowledge', version = '9.9.9', withEntry = true }) {
51
+ fs.mkdirSync(path.join(dir, 'bin'), { recursive: true });
52
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name, version, bin: { 'project-knowledge-mcp': 'bin/project-knowledge-mcp.js' } }));
53
+ if (withEntry) fs.writeFileSync(path.join(dir, 'bin', 'project-knowledge-mcp.js'), '#!/usr/bin/env node\nprocess.exit(0);\n');
54
+ }
55
+
56
+ async function mcpHandshake({ dataDir, env = {} }) {
57
+ // Line-delimited JSON-RPC handshake against the launcher, asserting every
58
+ // stdout line parses as JSON (no stdio pollution). Resolves when the
59
+ // initialize response arrives: a healthy server keeps running to serve
60
+ // requests, so waiting for process exit would only hit the timeout.
61
+ return await new Promise((resolve, reject) => {
62
+ const child = spawn(process.execPath, [LAUNCHER], {
63
+ windowsHide: true,
64
+ env: { ...process.env, KB_DATA_DIR: dataDir, ...env },
65
+ });
66
+ const killTree = () => {
67
+ if (!child.pid) return;
68
+ try { process.platform === 'win32' ? spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, timeout: 5000 }) : child.kill(); } catch {}
69
+ };
70
+ const timer = setTimeout(() => { killTree(); reject(new Error('launcher handshake timeout')); }, 20000);
71
+ let settled = false;
72
+ const settle = result => {
73
+ if (settled) return;
74
+ settled = true;
75
+ clearTimeout(timer);
76
+ killTree();
77
+ resolve(result);
78
+ };
79
+ let buffer = '';
80
+ const responses = [];
81
+ child.stdout.setEncoding('utf8');
82
+ child.stdout.on('data', chunk => {
83
+ buffer += chunk;
84
+ let index;
85
+ while ((index = buffer.indexOf('\n')) >= 0) {
86
+ const line = buffer.slice(0, index).trim();
87
+ buffer = buffer.slice(index + 1);
88
+ if (!line) continue;
89
+ responses.push(JSON.parse(line));
90
+ }
91
+ if (responses.some(message => message.id === 1)) settle({ responses, stderr: '' });
92
+ });
93
+ const stderr = [];
94
+ child.stderr.setEncoding('utf8');
95
+ child.stderr.on('data', chunk => stderr.push(chunk));
96
+ child.on('close', code => {
97
+ settle({ code, responses, stderr: stderr.join('') });
98
+ });
99
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'pk-binding-test', version: '1' } } }) + '\n');
100
+ });
101
+ }
102
+
103
+ async function expectFailureCode(name, { dataDir, env, binding, fakePkg, fakePkgOptions }) {
104
+ const dir = path.join(TEMP, name);
105
+ if (binding) writeBinding(dir, binding);
106
+ else fs.mkdirSync(dir, { recursive: true });
107
+ if (fakePkg) fakePackage(fakePkg, fakePkgOptions || {});
108
+ const result = runLauncher({ dataDir: dir, env });
109
+ assert(result.status !== 0, `${name}: launcher must exit non-zero`);
110
+ const payload = parseLauncherStderr(result);
111
+ assert(payload.schema === 'project-knowledge/mcp-launcher-error/v1', `${name}: error payload must carry the launcher error schema`);
112
+ assert(payload.code === bindingCode(name), `${name}: unexpected code ${payload.code}`);
113
+ assert(String(result.stdout || '').trim() === '', `${name}: launcher must not write diagnostics to stdout`);
114
+ }
115
+
116
+ function bindingCode(name) {
117
+ return {
118
+ missing: 'BINDING_MISSING',
119
+ corrupt: 'BINDING_CORRUPT',
120
+ schema: 'BINDING_SCHEMA_MISMATCH',
121
+ package: 'BINDING_PACKAGE_MISMATCH',
122
+ version: 'BINDING_VERSION_MISMATCH',
123
+ root: 'BINDING_INVALID_ROOT',
124
+ entry: 'BINDING_ENTRY_MISSING',
125
+ }[name];
126
+ }
127
+
128
+ async function testMcpManifestContract() {
129
+ const manifest = readJson(path.join(PLUGIN_ROOT, '.mcp.json'));
130
+ const server = manifest.mcpServers['project-knowledge'];
131
+ assert(server, '.mcp.json must keep the project-knowledge server');
132
+ assert(server.type === 'stdio', 'server must stay stdio');
133
+ assert(server.command === 'node', 'the default MCP entry must use the local Node, not npx');
134
+ assert(!JSON.stringify(server).includes('npx'), 'the plugin MCP chain must not depend on npx anymore');
135
+ assert(!/@sanqianx\/project-knowledge@/.test(JSON.stringify(server)), 'the plugin MCP chain must not pin an npx package argument');
136
+ assert(Array.isArray(server.args) && server.args[0] === '-e', 'the launcher bootstrap must run through node -e');
137
+ const bootstrap = server.args[1];
138
+ assert(typeof bootstrap === 'string' && bootstrap.includes('mcp-launcher.cjs'), 'the bootstrap must locate the plugin launcher script');
139
+ assert(bootstrap.includes('CLAUDE_PLUGIN_ROOT') && bootstrap.includes('PLUGIN_ROOT'), 'the bootstrap must honor both native plugin-root variables');
140
+ assert(server.cwd === undefined, 'A2: no cwd pin; the bootstrap must not resolve relative to a working directory');
141
+ assert(server.env && server.env.KB_PLUGIN_VERSION === readJson(path.join(ROOT, 'package.json')).version, 'A2: env.KB_PLUGIN_VERSION must carry the shipping version');
142
+ assert(!bootstrap.includes('process.cwd'), 'A2: the bootstrap must never consult process.cwd');
143
+ assert(fs.existsSync(LAUNCHER), 'the launcher script must ship inside the plugin');
144
+ }
145
+
146
+ async function testLauncherFailureMatrix() {
147
+ const goodPkg = path.join(TEMP, 'good-pkg');
148
+ fakePackage(goodPkg, { version: '9.9.9' });
149
+
150
+ await expectFailureCode('missing', {});
151
+ fs.mkdirSync(path.join(TEMP, 'corrupt'), { recursive: true });
152
+ fs.writeFileSync(path.join(TEMP, 'corrupt', 'integration-runtime.json'), '{ not json');
153
+ await expectFailureCode('corrupt', { binding: null });
154
+ const dir = name => path.join(TEMP, name);
155
+ writeBinding(dir('schema'), { schema: 'other/v2' });
156
+ await expectFailureCode('schema', { binding: readJson(path.join(dir('schema'), 'integration-runtime.json')) });
157
+ writeBinding(dir('package'), { schema: RUNTIME_SCHEMA, packageName: '@other/pkg', packageRoot: goodPkg, version: '9.9.9' });
158
+ await expectFailureCode('package', { binding: readJson(path.join(dir('package'), 'integration-runtime.json')) });
159
+ writeBinding(dir('version'), { schema: RUNTIME_SCHEMA, packageName: '@sanqianx/project-knowledge', packageRoot: goodPkg, version: '1.2.3' });
160
+ await expectFailureCode('version', { binding: readJson(path.join(dir('version'), 'integration-runtime.json')) });
161
+ writeBinding(dir('root'), { schema: RUNTIME_SCHEMA, packageName: '@sanqianx/project-knowledge', packageRoot: 'relative/pkg/root', version: '9.9.9' });
162
+ await expectFailureCode('root', { binding: readJson(path.join(dir('root'), 'integration-runtime.json')) });
163
+ const noEntry = path.join(TEMP, 'no-entry-pkg');
164
+ fakePackage(noEntry, { version: '9.9.9', withEntry: false });
165
+ writeBinding(dir('entry'), { schema: RUNTIME_SCHEMA, packageName: '@sanqianx/project-knowledge', packageRoot: noEntry, version: '9.9.9' });
166
+ await expectFailureCode('entry', { binding: readJson(path.join(dir('entry'), 'integration-runtime.json')) });
167
+ }
168
+
169
+ async function testRealHandshakeIgnoresBrokenNpxCache() {
170
+ // A corrupted _npx entry (missing package.json) must not affect the local
171
+ // launcher chain at all — that is the regression this whole feature fixes.
172
+ const dataDir = path.join(TEMP, '用户 空格 知识库', 'data');
173
+ fs.mkdirSync(dataDir, { recursive: true });
174
+ const packageInfo = readJson(path.join(ROOT, 'package.json'));
175
+ writeBinding(dataDir, { schema: RUNTIME_SCHEMA, packageName: packageInfo.name, packageRoot: ROOT, version: packageInfo.version, updatedAt: new Date().toISOString() });
176
+ const brokenCache = path.join(TEMP, '用户 空格 知识库', 'npm-cache');
177
+ fs.mkdirSync(path.join(brokenCache, '_npx', '7581c64052dde81c'), { recursive: true });
178
+ fs.mkdirSync(path.join(brokenCache, '_npx', '7581c64052dde81c', 'node_modules'), { recursive: true });
179
+ const result = await mcpHandshake({ dataDir, env: { npm_config_cache: brokenCache } });
180
+ assert(result.code === 0 || result.responses.length, 'the local chain must initialize despite a broken npx cache');
181
+ const init = result.responses.find(message => message.id === 1);
182
+ assert(init && !init.error, 'initialize must succeed');
183
+ assert(init.result.serverInfo.name === 'project-knowledge', 'serverInfo must identify project-knowledge');
184
+ assert(init.result.serverInfo.version === packageInfo.version, 'the bound local package version must be reported');
185
+ assert(String(result.stderr || '').trim() === '', 'a healthy launch writes nothing to stderr');
186
+ }
187
+
188
+ async function testBootstrapResolvesForBothNativeForms() {
189
+ const manifest = readJson(path.join(PLUGIN_ROOT, '.mcp.json'));
190
+ const bootstrap = manifest.mcpServers['project-knowledge'].args[1];
191
+ const dataDir = path.join(TEMP, 'bootstrap-forms');
192
+ fs.mkdirSync(dataDir, { recursive: true });
193
+ // Test isolation: the host session may itself run inside a native plugin
194
+ // (CLAUDE_PLUGIN_ROOT pointing at claude-mem, etc.); the bootstrap under
195
+ // test must not silently prefer that unrelated root.
196
+ const baseEnv = { ...process.env };
197
+ delete baseEnv.CLAUDE_PLUGIN_ROOT;
198
+ delete baseEnv.PLUGIN_ROOT;
199
+ const run = env => spawnSync(process.execPath, ['-e', bootstrap], {
200
+ encoding: 'utf8', windowsHide: true, timeout: 15000,
201
+ env: { ...baseEnv, KB_DATA_DIR: dataDir, ...env },
202
+ cwd: env.PLUGIN_ROOT || env.CLAUDE_PLUGIN_ROOT || PLUGIN_ROOT,
203
+ });
204
+ // A2: without a plugin-root env the bootstrap must NOT fall back to cwd.
205
+ const decoyDir = path.join(TEMP, 'bootstrap-decoy');
206
+ fs.mkdirSync(path.join(decoyDir, 'scripts'), { recursive: true });
207
+ fs.writeFileSync(path.join(decoyDir, 'scripts', 'mcp-launcher.cjs'), 'process.exit(7);\n');
208
+ const codex = spawnSync(process.execPath, ['-e', bootstrap], {
209
+ encoding: 'utf8', windowsHide: true, timeout: 15000,
210
+ env: { ...baseEnv, KB_DATA_DIR: dataDir }, cwd: decoyDir,
211
+ });
212
+ assert(codex.status === 127, 'A2: without a trusted root or usable binding the bootstrap exits 127, got ' + codex.status);
213
+ // Claude form: CLAUDE_PLUGIN_ROOT is exported to MCP stdio servers.
214
+ const claude = run({ CLAUDE_PLUGIN_ROOT: PLUGIN_ROOT, cwd: undefined });
215
+ assert(claude.status === 1 && /BINDING_MISSING/.test(String(claude.stderr || '')), 'the CLAUDE_PLUGIN_ROOT form must reach the launcher');
216
+ const codexCompat = run({ PLUGIN_ROOT: PLUGIN_ROOT });
217
+ assert(codexCompat.status === 1 && /BINDING_MISSING/.test(String(codexCompat.stderr || '')), 'the PLUGIN_ROOT form must reach the launcher');
218
+ // A2: the verified binding fallback loads the in-package launcher with no env root.
219
+ const fakePkg = path.join(TEMP, 'bootstrap-fake-pkg');
220
+ const fakeLauncher = path.join(fakePkg, 'plugins', 'project-knowledge', 'scripts', 'mcp-launcher.cjs');
221
+ fs.mkdirSync(path.dirname(fakeLauncher), { recursive: true });
222
+ fs.writeFileSync(fakeLauncher, 'process.stderr.write(\'BINDING_FALLBACK_REACHED\'); process.exit(5);\n');
223
+ writeBinding(dataDir, { schema: RUNTIME_SCHEMA, packageName: '@sanqianx/project-knowledge', packageRoot: fakePkg, version: '0.0.0' });
224
+ const bound = spawnSync(process.execPath, ['-e', bootstrap], {
225
+ encoding: 'utf8', windowsHide: true, timeout: 15000,
226
+ env: { ...baseEnv, KB_DATA_DIR: dataDir }, cwd: decoyDir,
227
+ });
228
+ assert(bound.status === 5 && /BINDING_FALLBACK_REACHED/.test(String(bound.stderr || '')), 'the verified binding fallback must load the in-package launcher');
229
+ }
230
+
231
+ async function testInstallerBindingLifecycle() {
232
+ const home = path.join(TEMP, 'installer-home');
233
+ const dataDir = path.join(home, '.project-knowledge-v5');
234
+ const bindingPath = path.join(dataDir, 'integration-runtime.json');
235
+ const manager = new IntegrationManager({
236
+ rootDir: ROOT,
237
+ homeDir: home,
238
+ env: { KB_DATA_DIR: dataDir },
239
+ commandResolver: name => name,
240
+ runner: () => ({ status: 0, stdout: '', stderr: '' }),
241
+ });
242
+ assert(typeof manager.ensureIntegrationRuntimeBinding === 'function', 'the installer must expose the binding writer');
243
+ const packageInfo = readJson(path.join(ROOT, 'package.json'));
244
+ manager.ensureIntegrationRuntimeBinding();
245
+ const first = readJson(bindingPath);
246
+ assert(first.schema === RUNTIME_SCHEMA, 'binding must carry the integration-runtime schema');
247
+ assert(first.packageName === packageInfo.name, 'binding must pin the package name');
248
+ assert(first.packageRoot === ROOT, 'binding must pin the absolute package root');
249
+ assert(first.version === packageInfo.version, 'binding must pin the package version');
250
+ assert(!JSON.stringify(first).match(/token|secret|key/i), 'binding must not carry credentials');
251
+ // Idempotent repair: a second explicit install keeps the binding valid.
252
+ manager.ensureIntegrationRuntimeBinding();
253
+ const second = readJson(bindingPath);
254
+ assert(second.packageRoot === first.packageRoot && second.version === first.version && second.packageName === first.packageName, 'repeated installs must keep the binding stable');
255
+
256
+ // A failed atomic write keeps the previous binding byte-for-byte.
257
+ const before = fs.readFileSync(bindingPath);
258
+ let failed = false;
259
+ try {
260
+ manager.ensureIntegrationRuntimeBinding({ beforeRename: () => { throw new Error('disk full'); } });
261
+ } catch (error) {
262
+ failed = true;
263
+ assert(/disk full/.test(error.message), 'write failures must surface, not be swallowed');
264
+ }
265
+ assert(failed, 'an injected rename failure must throw');
266
+ assert(fs.readFileSync(bindingPath).equals(before), 'a failed atomic write must preserve the old binding');
267
+ assert(!fs.readdirSync(dataDir).some(name => name.endsWith('.tmp')), 'no temp residue may survive a failed write');
268
+
269
+ // dry-run never writes a binding.
270
+ const dryHome = path.join(TEMP, 'installer-dry-home');
271
+ new IntegrationManager({ rootDir: ROOT, homeDir: dryHome, env: { KB_DATA_DIR: path.join(dryHome, 'data') }, dryRun: true }).ensureIntegrationRuntimeBinding();
272
+ assert(!fs.existsSync(path.join(dryHome, 'data', 'integration-runtime.json')), 'dry-run must not write the binding');
273
+ }
274
+
275
+ async function testInstallAllCaptureOnlySkipsBinding() {
276
+ const home = path.join(TEMP, 'install-all-home');
277
+ const dataDir = path.join(home, '.project-knowledge-v5');
278
+ const bridgeStub = {
279
+ createBridge: () => ({
280
+ registerConsumer: async () => ({}),
281
+ getConsumer: async () => ({}),
282
+ getHealth: async () => ({}),
283
+ ensureRuntimeHome: async () => ({}),
284
+ installers: {
285
+ claudeCode: { installClaudeCodeHook: async () => ({ added: [] }), statusClaudeCodeHook: async () => ({ installed: false }), uninstallClaudeCodeHook: async () => ({}) },
286
+ codex: { statusCodexHook: async () => ({ installed: false }) },
287
+ openCode: { installOpenCodePlugin: async () => ({}), statusOpenCodePlugin: async () => ({ installed: false }), uninstallOpenCodePlugin: async () => ({}) },
288
+ zcode: { installZcodeHook: async () => ({}), statusZcodeHook: async () => ({ installed: false }), uninstallZcodeHook: async () => ({}) },
289
+ },
290
+ }),
291
+ };
292
+ const manager = new IntegrationManager({
293
+ rootDir: ROOT,
294
+ homeDir: home,
295
+ env: { KB_DATA_DIR: dataDir },
296
+ commandResolver: name => name,
297
+ runner: () => ({ status: 0, stdout: '[]', stderr: '' }),
298
+ bridgeModule: bridgeStub,
299
+ });
300
+ await manager.installAll({ clients: ['claude'], captureOnly: true });
301
+ assert(!fs.existsSync(path.join(dataDir, 'integration-runtime.json')), 'A2: captureOnly must not write the knowledge runtime binding');
302
+ }
303
+
304
+ async function testMcpStartupProbe() {
305
+ const home = path.join(TEMP, 'probe-home');
306
+ const dataDir = path.join(home, '.project-knowledge-v5');
307
+ const packageInfo = readJson(path.join(ROOT, 'package.json'));
308
+ writeBinding(dataDir, { schema: RUNTIME_SCHEMA, packageName: packageInfo.name, packageRoot: ROOT, version: packageInfo.version, updatedAt: new Date().toISOString() });
309
+ const manager = new IntegrationManager({
310
+ rootDir: ROOT,
311
+ homeDir: home,
312
+ env: { KB_DATA_DIR: dataDir },
313
+ commandResolver: name => name,
314
+ runner: () => ({ status: 0, stdout: '[]', stderr: '' }),
315
+ bridgeModule: {
316
+ createBridge: () => ({
317
+ getConsumer: async () => ({}),
318
+ getHealth: async () => ({}),
319
+ installers: {
320
+ claudeCode: { statusClaudeCodeHook: async () => ({ installed: false }) },
321
+ codex: { statusCodexHook: async () => ({ installed: false }) },
322
+ },
323
+ }),
324
+ },
325
+ });
326
+ assert(typeof manager.probeMcpStartup === 'function', 'the installer must expose the MCP startup probe');
327
+ const ready = await manager.probeMcpStartup();
328
+ assert(ready.state === 'ready', `a healthy binding must probe ready, got ${JSON.stringify(ready)}`);
329
+ assert(ready.actualVersion === packageInfo.version && ready.expectedVersion === packageInfo.version, 'the probe must report both versions');
330
+ assert(ready.scope === 'product-runtime' && ready.serverName === 'project-knowledge', 'A2: the probe reports its scope and the verified server identity');
331
+ assert(Array.isArray(ready.tools) && ready.tools.length === 6, 'A2: the probe verifies the six knowledge tools');
332
+ assert(typeof ready.checkedAt === 'string', 'the probe must record checkedAt');
333
+
334
+ // A broken binding must surface a failed probe with a machine code.
335
+ fs.writeFileSync(path.join(dataDir, 'integration-runtime.json'), '{ broken');
336
+ const failed = await manager.probeMcpStartup();
337
+ assert(failed.state === 'failed', `a corrupted binding must probe failed, got ${JSON.stringify(failed)}`);
338
+ assert(typeof failed.code === 'string' && failed.code, 'failed probes must carry a code');
339
+ assert(typeof failed.detail === 'string', 'failed probes must carry a bounded detail');
340
+
341
+ // Probe details must be sanitized: a launcher that prints a token must not
342
+ // leak it into status output.
343
+ const leaky = path.join(TEMP, 'leaky-launcher.cjs');
344
+ fs.writeFileSync(leaky, 'process.stderr.write("boom sk-abcdef123456 token\\n"); process.exit(3);\n');
345
+ const leakyProbe = await manager.probeMcpStartup({ launcherPath: leaky });
346
+ assert(leakyProbe.state === 'failed', 'the leaky launcher must count as failed');
347
+ assert(!JSON.stringify(leakyProbe).includes('sk-abcdef123456'), 'probe details must redact credential-shaped strings');
348
+ assert(JSON.stringify(leakyProbe).length < 2000, 'probe details must stay bounded');
349
+
350
+ // statusAll must attach mcpStartup for MCP-capable clients and honor the
351
+ // injected probe (so UI refreshes reuse the cached scan instead of spawning).
352
+ let probeCalls = 0;
353
+ const counting = new IntegrationManager({
354
+ rootDir: ROOT,
355
+ homeDir: home,
356
+ env: { KB_DATA_DIR: dataDir },
357
+ commandResolver: name => name,
358
+ runner: () => ({ status: 0, stdout: '[]', stderr: '' }),
359
+ mcpProbe: async () => { probeCalls += 1; return { state: 'ready', checkedAt: new Date().toISOString(), actualVersion: packageInfo.version, expectedVersion: packageInfo.version }; },
360
+ bridgeModule: manager.bridge,
361
+ });
362
+ const summary = await counting.statusAll({ clients: ['claude', 'codex', 'zcode'] });
363
+ const claude = summary.clients.find(entry => entry.client === 'claude');
364
+ const codex = summary.clients.find(entry => entry.client === 'codex');
365
+ assert(claude.mcpStartup?.code === 'CLIENT_PLUGIN_ENTRY_MISSING', 'A2: claude without an installed plugin entry reports the explicit miss');
366
+ assert(codex.mcpStartup?.code === 'CLIENT_PLUGIN_ENTRY_MISSING', 'A2: codex without an installed plugin entry reports the explicit miss');
367
+ assert(summary.mcpRuntime?.state === 'ready', 'A2: the shared product-runtime probe lands in the summary');
368
+ assert(probeCalls === 1, 'A2: only the host product-runtime probe runs when no installed entries exist');
369
+ }
370
+
371
+ async function testStatusScanDoesNotRespawn() {
372
+ // UI refreshes funnel through the cached scan; identical reads within the
373
+ // TTL must not fork another probe worker.
374
+ const counter = path.join(TEMP, 'scan-count.txt');
375
+ const worker = path.join(TEMP, 'scan-worker.js');
376
+ fs.writeFileSync(worker, `${'const fs = require(\'node:fs\');'}
377
+ process.once('message', async input => {
378
+ const counter = ${JSON.stringify(counter)};
379
+ const count = fs.existsSync(counter) ? Number(fs.readFileSync(counter, 'utf8')) + 1 : 1;
380
+ fs.writeFileSync(counter, String(count));
381
+ process.send({ ok: true, summary: { bridge: { ok: true }, clients: [{ client: input.statusOptions.clients?.[0] || 'claude', mcpStartup: { state: 'ready' } }] } }, () => process.disconnect());
382
+ });
383
+ `);
384
+ const scan = new IntegrationStatusScan({ workerFile: worker, timeoutMs: 20000 });
385
+ const options = { rootDir: ROOT, homeDir: TEMP, bridgeHomeDir: TEMP };
386
+ await scan.read(options, { clients: ['claude'] }, { waitMs: 5000 });
387
+ await scan.read(options, { clients: ['claude'] }, { waitMs: 5000 });
388
+ assert(Number(fs.readFileSync(counter, 'utf8')) === 1, 'a cached scan must not fork another worker for the same key');
389
+ await scan.read(options, { clients: ['claude'] }, { force: true, waitMs: 5000 });
390
+ assert(Number(fs.readFileSync(counter, 'utf8')) === 2, 'force refresh must re-run the scan');
391
+ scan.close();
392
+ }
393
+
394
+ async function testCodexTrustSeparatedFromWaitingTrust() {
395
+ // The same already-trusted definition must not be reported as waiting-trust.
396
+ const home = path.join(TEMP, 'codex-trust-home');
397
+ const manager = new IntegrationManager({
398
+ rootDir: ROOT,
399
+ homeDir: home,
400
+ env: {},
401
+ commandResolver: name => name,
402
+ runner: () => ({ status: 0, stdout: JSON.stringify({ installed: [{ pluginId: 'project-knowledge@project-knowledge', version: readJson(path.join(ROOT, 'package.json')).version, enabled: true, source: { path: path.join(ROOT, 'plugins', 'project-knowledge') } }] }), stderr: '' }),
403
+ codexHookProbe: async () => ({ data: [{ cwd: home, hooks: [{ pluginId: 'project-knowledge@project-knowledge', eventName: 'userPromptSubmit', command: 'node "…/scripts/context-hook.cjs" --client codex', enabled: true, trustStatus: 'trusted' }] }] }),
404
+ bridgeModule: {
405
+ createBridge: () => ({ getConsumer: async () => ({}), getHealth: async () => ({}), installers: { codex: { statusCodexHook: async () => ({ installed: false }) } } }),
406
+ },
407
+ });
408
+ const status = await manager.automaticCodexContextStatus(manager.statusCodex(), home);
409
+ assert(status.state === 'configured', `an already-trusted matching definition must be configured, not waiting-trust (got ${status.state})`);
410
+ assert(status.trustStatus === 'trusted', 'the native trust status must be surfaced');
411
+ }
412
+
413
+ async function testReleaseContracts() {
414
+ const { drift } = inspectReleaseVersion(ROOT, { webOnly: true });
415
+ assert(!drift.includes('plugins/project-knowledge/.mcp.json'), `the shipped launcher .mcp.json must satisfy the release contract (drift: ${drift.join(', ')})`);
416
+
417
+ const mini = path.join(TEMP, 'release-mini');
418
+ fs.mkdirSync(path.join(mini, 'plugins', 'project-knowledge', '.claude-plugin'), { recursive: true });
419
+ fs.mkdirSync(path.join(mini, 'plugins', 'project-knowledge', '.codex-plugin'), { recursive: true });
420
+ fs.mkdirSync(path.join(mini, '.claude-plugin'), { recursive: true });
421
+ fs.writeFileSync(path.join(mini, 'package.json'), JSON.stringify({ name: '@sanqianx/project-knowledge', version: '1.0.0' }));
422
+ fs.writeFileSync(path.join(mini, 'package-lock.json'), JSON.stringify({ name: '@sanqianx/project-knowledge', version: '1.0.0', packages: { '': { version: '1.0.0' } } }));
423
+ fs.writeFileSync(path.join(mini, 'plugins', 'project-knowledge', '.claude-plugin', 'plugin.json'), JSON.stringify({ version: '1.0.0' }));
424
+ fs.writeFileSync(path.join(mini, 'plugins', 'project-knowledge', '.codex-plugin', 'plugin.json'), JSON.stringify({ version: '1.0.0' }));
425
+ fs.writeFileSync(path.join(mini, '.claude-plugin', 'marketplace.json'), JSON.stringify({ plugins: [{ version: '1.0.0' }] }));
426
+ fs.writeFileSync(path.join(mini, 'plugins', 'project-knowledge', '.mcp.json'), JSON.stringify({
427
+ mcpServers: { 'project-knowledge': { type: 'stdio', command: 'npx', args: ['-y', '--package', '@sanqianx/project-knowledge@1.0.0', 'project-knowledge-mcp'] } },
428
+ }, null, 2));
429
+ let rejected = false;
430
+ try { inspectReleaseVersion(mini, { webOnly: true }); } catch (error) { rejected = /pinned|npx|launcher/i.test(error.message); }
431
+ assert(rejected, 'the release check must reject a resurrected npx-pinned .mcp.json');
432
+
433
+ const staleEnv = path.join(TEMP, 'release-stale-env');
434
+ fs.mkdirSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.claude-plugin'), { recursive: true });
435
+ fs.mkdirSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.codex-plugin'), { recursive: true });
436
+ fs.mkdirSync(path.join(staleEnv, '.claude-plugin'), { recursive: true });
437
+ fs.writeFileSync(path.join(staleEnv, 'package.json'), JSON.stringify({ name: '@sanqianx/project-knowledge', version: '1.0.0' }));
438
+ fs.writeFileSync(path.join(staleEnv, 'package-lock.json'), JSON.stringify({ name: '@sanqianx/project-knowledge', version: '1.0.0', packages: { '': { version: '1.0.0' } } }));
439
+ fs.writeFileSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.claude-plugin', 'plugin.json'), JSON.stringify({ version: '1.0.0' }));
440
+ fs.writeFileSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.codex-plugin', 'plugin.json'), JSON.stringify({ version: '1.0.0' }));
441
+ fs.writeFileSync(path.join(staleEnv, '.claude-plugin', 'marketplace.json'), JSON.stringify({ plugins: [{ version: '1.0.0' }] }));
442
+ fs.writeFileSync(path.join(staleEnv, 'plugins', 'project-knowledge', '.mcp.json'), JSON.stringify({
443
+ mcpServers: { 'project-knowledge': { type: 'stdio', command: 'node', args: ['-e', "require('scripts/mcp-launcher.cjs')"], cwd: '.', env: { KB_PLUGIN_VERSION: '0.9.9' } } },
444
+ }, null, 2));
445
+ let envRejected = false;
446
+ try { inspectReleaseVersion(staleEnv, { webOnly: true }); } catch (error) { envRejected = /cwd|KB_PLUGIN_VERSION|plugin version|env/i.test(error.message); }
447
+ assert(envRejected, 'the release check must reject a drifted env.KB_PLUGIN_VERSION and a resurrected cwd pin');
448
+
449
+ const manifest = readJson(path.join(ROOT, 'module-runtime-manifest.json'));
450
+ assert(manifest.productFiles && manifest.productFiles['plugins/project-knowledge/scripts/mcp-launcher.cjs'], 'the packaged product manifest must track the launcher');
451
+ for (const script of ['_site/scripts/sync-product-content.js', '_site/scripts/verify-product-runtime.js']) {
452
+ assert(fs.readFileSync(path.join(ROOT, script), 'utf8').includes('mcp-launcher.cjs'), `${script} must include the launcher in the product asset checklist`);
453
+ }
454
+ }
455
+
456
+ async function main() {
457
+ await testMcpManifestContract();
458
+ await testLauncherFailureMatrix();
459
+ await testRealHandshakeIgnoresBrokenNpxCache();
460
+ await testBootstrapResolvesForBothNativeForms();
461
+ await testInstallerBindingLifecycle();
462
+ await testInstallAllCaptureOnlySkipsBinding();
463
+ await testMcpStartupProbe();
464
+ await testStatusScanDoesNotRespawn();
465
+ await testCodexTrustSeparatedFromWaitingTrust();
466
+ await testReleaseContracts();
467
+ console.log('INTEGRATION_RUNTIME_BINDING_TEST_PASSED');
468
+ }
469
+
470
+ main().catch(error => {
471
+ console.error('INTEGRATION_RUNTIME_BINDING_TEST_FAILED', error.message);
472
+ process.exit(1);
473
+ });