@sanqianx/project-knowledge 5.0.30 → 5.0.32

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 (135) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +26 -0
  3. package/README.md +5 -2
  4. package/_site/_test/appearance-settings-test.js +148 -0
  5. package/_site/_test/helpers/parallel-capture-safety-r5-cap-shell.js +606 -0
  6. package/_site/_test/helpers/parallel-capture-safety-r5-memory-shell.js +464 -0
  7. package/_site/_test/helpers/parallel-dock-acceptance-env.js +301 -0
  8. package/_site/_test/helpers/parallel-dock-acceptance-r2-env.js +378 -0
  9. package/_site/_test/helpers/parallel-dock-acceptance-r2-ui.js +314 -0
  10. package/_site/_test/helpers/parallel-dock-acceptance-ui.js +195 -0
  11. package/_site/_test/helpers/parallel-dock-isolation-r3-credential-preload.js +113 -0
  12. package/_site/_test/helpers/parallel-dock-isolation-r3-env.js +307 -0
  13. package/_site/_test/helpers/parallel-dock-isolation-r3-fixture.js +373 -0
  14. package/_site/_test/helpers/parallel-dock-isolation-r3-ui.js +314 -0
  15. package/_site/_test/helpers/parallel-engine-advanced-engine-child.js +1 -1
  16. package/_site/_test/helpers/parallel-engine-advanced-fault-writer.js +3 -3
  17. package/_site/_test/helpers/parallel-engine-advanced-harness.js +1 -1
  18. package/_site/_test/helpers/parallel-engine-advanced-standin-analyzer.js +1 -1
  19. package/_site/_test/helpers/parallel-engine-final-harness.js +2 -2
  20. package/_site/_test/helpers/parallel-engine-final-standin-analyzer.js +1 -1
  21. package/_site/_test/helpers/parallel-engine-reconcile-r4-harness.js +340 -0
  22. package/_site/_test/helpers/parallel-engine-reconcile-r4-standin-analyzer.js +82 -0
  23. package/_site/_test/helpers/parallel-memory-analyzer.js +1 -1
  24. package/_site/_test/helpers/parallel-memory-capture-r3-cap-shell.js +605 -0
  25. package/_site/_test/helpers/parallel-memory-capture-r3-shell.js +176 -0
  26. package/_site/_test/helpers/parallel-memory-capture-r4-cap-shell.js +577 -0
  27. package/_site/_test/helpers/parallel-memory-injection-shell.js +723 -0
  28. package/_site/_test/helpers/parallel-memory-injection-wb-host.js +81 -0
  29. package/_site/_test/helpers/parallel-nav-shell.js +1 -1
  30. package/_site/_test/helpers/parallel-qa-engine-endpoint-guard.js +1 -1
  31. package/_site/_test/helpers/parallel-retrieval-followup-r2-shell.js +1 -1
  32. package/_site/_test/helpers/parallel-workbench-drafts-r5-fixture.js +295 -0
  33. package/_site/_test/helpers/parallel-workbench-drafts-r5-harness.js +573 -0
  34. package/_site/_test/helpers/parallel-workbench-drafts-r5-host.js +69 -0
  35. package/_site/_test/helpers/parallel-workbench-runtime-harness.js +587 -0
  36. package/_site/_test/helpers/qa-r45-harness.js +94 -0
  37. package/_site/_test/helpers/qa-r48-env.js +64 -0
  38. package/_site/_test/helpers/qa-r51-env.cjs +77 -0
  39. package/_site/_test/helpers/qa-r91-harness.cjs +4 -1
  40. package/_site/_test/package-boundary-test.js +5 -0
  41. package/_site/_test/parallel-capture-safety-r5-cap006-probe.js +524 -0
  42. package/_site/_test/parallel-capture-safety-r5-cap008e-probe.js +577 -0
  43. package/_site/_test/parallel-capture-safety-r5-mem005-health-test.js +320 -0
  44. package/_site/_test/parallel-engine-advanced-eng011-ui-probe.js +1 -1
  45. package/_site/_test/parallel-engine-reconcile-r4-eng007-probe.js +304 -0
  46. package/_site/_test/parallel-knowledge-engine-test.js +3 -3
  47. package/_site/_test/parallel-knowledge-retrieval-test.js +2 -2
  48. package/_site/_test/parallel-logging-acceptance-log003-probe.js +78 -0
  49. package/_site/_test/parallel-logging-acceptance-log004-probe.js +85 -0
  50. package/_site/_test/parallel-memory-capture-r3-cap001-probe.js +238 -0
  51. package/_site/_test/parallel-memory-capture-r3-cap006-probe.js +371 -0
  52. package/_site/_test/parallel-memory-capture-r3-cap008-probe.js +439 -0
  53. package/_site/_test/parallel-memory-capture-r3-mem005-persistence-test.js +271 -0
  54. package/_site/_test/parallel-memory-capture-r4-cap006-probe.js +519 -0
  55. package/_site/_test/parallel-memory-capture-r4-cap008e-probe.js +569 -0
  56. package/_site/_test/parallel-memory-capture-r4-mem005-health-test.js +314 -0
  57. package/_site/_test/parallel-memory-injection-origin-probe.js +412 -0
  58. package/_site/_test/parallel-memory-injection-probe.js +411 -0
  59. package/_site/_test/parallel-nav-isolation-test.js +1 -1
  60. package/_site/_test/parallel-qa-engine-endpoint-guard-test.js +1 -1
  61. package/_site/_test/parallel-retrieval-followup-citation-test.js +2 -2
  62. package/_site/_test/parallel-retrieval-followup-corpus-test.js +1 -1
  63. package/_site/_test/parallel-workbench-drafts-r4-probe.js +477 -0
  64. package/_site/_test/parallel-workbench-drafts-r5-chrome-env-bisect.js +89 -0
  65. package/_site/_test/parallel-workbench-drafts-r5-probe.js +593 -0
  66. package/_site/_test/parallel-workbench-runtime-minimax-probe.js +321 -0
  67. package/_site/_test/parallel-workbench-runtime-wb004-ordering.js +307 -0
  68. package/_site/_test/parallel-workbench-runtime-wb005-drafts.js +313 -0
  69. package/_site/_test/parallel-workbench-runtime-wb008-abort.js +321 -0
  70. package/_site/_test/qa-r45-offline-backfill-test.js +279 -0
  71. package/_site/_test/qa-r48-sys003-blank-secret-test.js +258 -0
  72. package/_site/_test/t07c-cln-001-002-007-coverage-test.js +135 -0
  73. package/_site/_test/t07d-git-rel-coverage-test.js +226 -0
  74. package/_site/_test/t07e-qta-coverage-test.js +195 -0
  75. package/_site/_test/t07f-mem-008-coverage-test.js +101 -0
  76. package/_site/lib/module-bridge.js +2 -11
  77. package/_site/lib/server-app.js +11 -2
  78. package/_site/lib/settings-store.js +43 -1
  79. package/_site/scripts/install-module-candidates.js +1 -1
  80. package/_site/scripts/pack-module-candidates.js +2 -1
  81. package/_site/scripts/verify-module-runtime.js +17 -32
  82. package/_site/scripts/verify-product-runtime.js +7 -3
  83. package/docs/README.zh-CN.md +3 -1
  84. package/module-runtime-manifest.json +56 -6
  85. package/package.json +2 -4
  86. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  87. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  88. package/plugins/project-knowledge/.mcp.json +1 -1
  89. package/ui/index.html +18 -1
  90. package/ui/product.css +6 -2
  91. package/ui/product.js +86 -1
  92. package/_modules/knowledge-engine/README.md +0 -133
  93. package/_modules/knowledge-engine/package.json +0 -38
  94. package/_modules/knowledge-engine/src/analysis-contract.js +0 -35
  95. package/_modules/knowledge-engine/src/analysis-failures.js +0 -39
  96. package/_modules/knowledge-engine/src/analysis-output.js +0 -52
  97. package/_modules/knowledge-engine/src/analysis-worker.js +0 -58
  98. package/_modules/knowledge-engine/src/bin.js +0 -52
  99. package/_modules/knowledge-engine/src/bridge-client.js +0 -24
  100. package/_modules/knowledge-engine/src/context.js +0 -140
  101. package/_modules/knowledge-engine/src/coordinator.js +0 -376
  102. package/_modules/knowledge-engine/src/diagnostics.js +0 -37
  103. package/_modules/knowledge-engine/src/headless-analyzer.js +0 -66
  104. package/_modules/knowledge-engine/src/index-request.js +0 -49
  105. package/_modules/knowledge-engine/src/knowledge-targets.js +0 -46
  106. package/_modules/knowledge-engine/src/memories.js +0 -281
  107. package/_modules/knowledge-engine/src/memory-eligibility.js +0 -74
  108. package/_modules/knowledge-engine/src/retrieval-policy.json +0 -14
  109. package/_modules/knowledge-engine/src/retrieval-ranking.js +0 -153
  110. package/_modules/knowledge-engine/src/retrieval.js +0 -367
  111. package/_modules/knowledge-engine/src/runtime/README.md +0 -7
  112. package/_modules/knowledge-engine/src/runtime/atomic-file.js +0 -204
  113. package/_modules/knowledge-engine/src/runtime/automation-config.js +0 -140
  114. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +0 -250
  115. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +0 -26
  116. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +0 -205
  117. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +0 -432
  118. package/_modules/knowledge-engine/src/runtime/content-hash.js +0 -4
  119. package/_modules/knowledge-engine/src/runtime/contracts.js +0 -282
  120. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +0 -204
  121. package/_modules/knowledge-engine/src/runtime/conversation-store.js +0 -389
  122. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +0 -228
  123. package/_modules/knowledge-engine/src/runtime/git-runner.js +0 -62
  124. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +0 -559
  125. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +0 -408
  126. package/_modules/knowledge-engine/src/runtime/layout.js +0 -46
  127. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +0 -276
  128. package/_modules/knowledge-engine/src/runtime/scanner.js +0 -298
  129. package/_modules/knowledge-engine/src/server.js +0 -166
  130. package/_modules/knowledge-engine/src/store.js +0 -267
  131. package/_modules/knowledge-engine/ui/app.css +0 -172
  132. package/_modules/knowledge-engine/ui/app.js +0 -318
  133. package/_modules/knowledge-engine/ui/index.html +0 -95
  134. package/_site/scripts/vendor-modules.js +0 -49
  135. package/vendor-manifest.json +0 -55
@@ -0,0 +1,606 @@
1
+ 'use strict';
2
+ // _site/_test/helpers/parallel-capture-safety-r5-cap-shell.js
3
+ //
4
+ // P-CAPTURE-SAFETY-R5 copy of the accepted R4 cap shell
5
+ // (parallel-memory-capture-r4-cap-shell.js, frozen by the Leader handoff).
6
+ // The R5 dispatch requires ONE unified premise: the probe process and every
7
+ // child run under a FULLY explicit environment supplied by the R5 wrapper —
8
+ // so this copy changes exactly two things and nothing else:
9
+ // 1. the read-only real-home comparison digests no longer resolve the real
10
+ // home from os.homedir() (under the isolated env that would digest the
11
+ // ISOLATED home — a fake-HOME proof). They use the path the wrapper
12
+ // captured BEFORE switching environments (PK_CAPTURE_SAFETY_R5_REAL_HOME,
13
+ // asserted, never defaulted to a real value);
14
+ // 2. startLaneVectorHub and realHomeDir are exported for the sibling R5
15
+ // memory-shell copy, which closes the same engine-default-vectorUrl gap
16
+ // the R4 mem005 path left open (see the R5 incident investigation).
17
+ // All other logic is byte-identical to the frozen R4 shell.
18
+ //
19
+ // Lane harness for the DEFAULT-owner (engine) external-Agent integration
20
+ // cases of P-MEMORY-CAPTURE-R4 (CAP-008 engine mode).
21
+ //
22
+ // The R3 cap shell proved the legacy consumer. This harness runs the same
23
+ // real product UI against the DEFAULT production topology instead:
24
+ //
25
+ // * the REAL event-bridge console (@sanqianx/ai-coding-event-bridge-console,
26
+ // the exact pinned package the product installs) as its OWN child
27
+ // process, spawned the way module-bridge spawns it in production
28
+ // (`node src/bin.js serve --host 127.0.0.1 --port <p> --home <dir>`),
29
+ // serving the SAME journal home the installed shim, the shell's Bridge
30
+ // adapter and the engine all use;
31
+ // * the REAL vendored knowledge engine in-process, started with consume
32
+ // DISABLED — consumption is switched on by the SHELL's own
33
+ // connectEngine -> POST /api/control activation, never by the driver;
34
+ // * the engine's analysis step is the frozen P-MEMORY-01 stand-in analyzer
35
+ // with an empty plan (the case under test is capture/consumption
36
+ // identity, not model judgement);
37
+ // * the real product server in its DEFAULT mode (analysisOwner 'engine')
38
+ // wired to the console and the engine through the same env and token
39
+ // proxy the frozen memory lane proved;
40
+ // * a shared real HTTP module fixture for terminal plus a lane-local
41
+ // vector endpoint (implementing the real hub's /api/sync contract
42
+ // subset) so the ENGINE's index step never falls back to its built-in
43
+ // default vectorUrl — 127.0.0.1:8787, which is a LIVE module here.
44
+ // Neither is the module under test;
45
+ // * a real Chrome (CDP) in its own profile, an isolated home for the
46
+ // 接入 installation, and the real-home digests of the R3 cap shell.
47
+ //
48
+ // Nothing here reaches the developer's live ports, live homes or live
49
+ // journals; every path lives under the lane temp root.
50
+
51
+ const crypto = require('node:crypto');
52
+ const fs = require('node:fs');
53
+ const http = require('node:http');
54
+ const path = require('node:path');
55
+ const { spawn } = require('node:child_process');
56
+
57
+ const r3cap = require('./parallel-memory-capture-r3-cap-shell');
58
+ const { spawnServer } = require('../helpers/spawn-server');
59
+ const { findChrome } = require('../helpers/find-chrome');
60
+ const { launchCdpBrowser, waitFor } = require('../helpers/cdp-browser');
61
+ const { attachNetworkCapture } = require('../helpers/cdp-network-capture');
62
+ const { createModuleFixture, createUpstreamProxy } = require('../helpers/module-fixture');
63
+ const freePort = require('../helpers/free-port');
64
+ const { createMemoryStandinAnalyzer } = require('./parallel-memory-analyzer');
65
+
66
+ const ROOT = r3cap.ROOT;
67
+ const ENGINE_ENTRY = path.join(path.dirname(require.resolve('@sanqianx/ai-coding-knowledge-engine/package.json', { paths: [path.join(ROOT)] })), 'src', 'server.js');
68
+ const CONSOLE_ENTRY = path.join(ROOT, 'node_modules', '@sanqianx', 'ai-coding-event-bridge-console', 'src', 'bin.js');
69
+ const { resolveTempRoot, withSanitizedEnv } = r3cap;
70
+
71
+ function sha256File(file) {
72
+ try { return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); } catch { return null; }
73
+ }
74
+
75
+ /**
76
+ * The real home for the read-only comparison digests. The R5 wrapper captures
77
+ * this path BEFORE moving the probe into the isolated environment; resolving
78
+ * it from os.homedir() here would read the isolated home instead and turn the
79
+ * real-home-untouched assertions into a fake-HOME proof.
80
+ */
81
+ function realHomeDir() {
82
+ const dir = process.env.PK_CAPTURE_SAFETY_R5_REAL_HOME;
83
+ if (!dir || !fs.existsSync(dir)) {
84
+ throw new Error('PK_CAPTURE_SAFETY_R5_REAL_HOME must name the real home (set by the capture-safety-r5 wrapper before isolation)');
85
+ }
86
+ return dir;
87
+ }
88
+
89
+ /** The pinned console package identity + per-file hashes of the serving code. */
90
+ function consoleIdentity() {
91
+ const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'node_modules', '@sanqianx', 'ai-coding-event-bridge-console', 'package.json'), 'utf8'));
92
+ const files = [
93
+ 'src/bin.js',
94
+ 'src/server.js',
95
+ 'src/bridge/core/journal-router.js',
96
+ 'src/bridge/core/journal.js',
97
+ 'src/bridge/core/repo-context.js',
98
+ 'src/bridge/core/project-registry.js',
99
+ ];
100
+ return {
101
+ package: packageJson.name,
102
+ version: packageJson.version,
103
+ resolved: packageJson._resolved || null,
104
+ integrity: packageJson._integrity || null,
105
+ entry: CONSOLE_ENTRY,
106
+ files: files.map(file => ({ file, sha256: sha256File(path.join(ROOT, 'node_modules', '@sanqianx', 'ai-coding-event-bridge-console', file)) })),
107
+ };
108
+ }
109
+
110
+ /** Start the real console child process and wait until it serves its API. */
111
+ async function startConsoleChild({ bridgeHome, tag }) {
112
+ const port = await freePort();
113
+ const url = `http://127.0.0.1:${port}`;
114
+ const output = [];
115
+ const child = withSanitizedEnv(() => spawn(process.execPath, [CONSOLE_ENTRY, 'serve', '--host', '127.0.0.1', '--port', String(port), '--home', bridgeHome], {
116
+ stdio: ['ignore', 'pipe', 'pipe'],
117
+ windowsHide: true,
118
+ env: { ...process.env, AI_CODING_EVENT_BRIDGE_HOME: bridgeHome },
119
+ }));
120
+ child.stdout.on('data', chunk => output.push(String(chunk)));
121
+ child.stderr.on('data', chunk => output.push(String(chunk)));
122
+ const exited = new Promise(resolve => child.on('exit', (code, signal) => resolve({ code, signal })));
123
+ let lastError = null;
124
+ await waitFor(async () => {
125
+ try {
126
+ const response = await fetch(`${url}/api/journals`, { signal: AbortSignal.timeout(2000) });
127
+ if (response.ok) return true;
128
+ lastError = `status ${response.status}`;
129
+ return false;
130
+ } catch (error) { lastError = error.message; return false; }
131
+ }, `the real event-bridge console child (port ${port}, last error ${lastError})`, 30000);
132
+ return {
133
+ kind: 'eventBridgeConsole',
134
+ tag,
135
+ child, url, port, bridgeHome, exited,
136
+ output: () => output.join(''),
137
+ async api(method, route, body) {
138
+ const response = await fetch(url + route, {
139
+ method,
140
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
141
+ body: body === undefined ? undefined : JSON.stringify(body),
142
+ signal: AbortSignal.timeout(15000),
143
+ });
144
+ return { status: response.status, body: await response.json().catch(() => null) };
145
+ },
146
+ async close() {
147
+ if (child.exitCode !== null) return;
148
+ child.kill();
149
+ const settled = await Promise.race([exited, new Promise(resolve => setTimeout(() => resolve('timeout'), 5000))]);
150
+ if (settled === 'timeout' && child.exitCode === null) {
151
+ const { spawnSync } = require('node:child_process');
152
+ spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true });
153
+ await exited.catch(() => {});
154
+ }
155
+ },
156
+ };
157
+ }
158
+
159
+ /**
160
+ * Lane-local vector endpoint for the ENGINE's index step.
161
+ *
162
+ * The shared vector-hub fixture implements the module surface but not
163
+ * POST /api/sync — and the engine's built-in vectorUrl default is
164
+ * http://127.0.0.1:8787, which on this machine is the developer's LIVE
165
+ * desktop vector-hub. Creating the engine without an explicit vectorUrl
166
+ * leaked /api/sync calls (and their index writes) into that live module
167
+ * (CAP-008e attempts 1-4; fixed from attempt 5 on). This service mirrors
168
+ * the real hub's /api/sync contract subset so runs settle deterministically
169
+ * inside the lane, and records every request as evidence.
170
+ */
171
+ function startLaneVectorHub({ tag }) {
172
+ const state = { projects: [], requests: [] };
173
+ const sendJson = (res, status, payload) => {
174
+ const body = JSON.stringify(payload);
175
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) });
176
+ res.end(body);
177
+ };
178
+ const readBody = req => new Promise(resolve => {
179
+ let raw = Buffer.alloc(0);
180
+ req.on('data', chunk => { raw = Buffer.concat([raw, chunk]); });
181
+ req.on('end', () => resolve(raw));
182
+ req.on('error', () => resolve(raw));
183
+ });
184
+ const server = http.createServer(async (req, res) => {
185
+ const url = new URL(req.url, 'http://127.0.0.1');
186
+ const raw = await readBody(req);
187
+ let body = null;
188
+ if (raw.length) { try { body = JSON.parse(raw.toString('utf8')); } catch { body = null; } }
189
+ state.requests.push({ method: req.method, path: url.pathname + url.search, body, at: Date.now() });
190
+ if (req.method === 'GET' && url.pathname === '/api/projects') { sendJson(res, 200, { projects: state.projects }); return; }
191
+ if (req.method === 'POST' && url.pathname === '/api/sync') {
192
+ if (!body?.project || !body?.sourceDir) { sendJson(res, 400, { error: "Body must include 'project' and 'sourceDir'." }); return; }
193
+ let filesTracked = 0;
194
+ try { filesTracked = fs.readdirSync(body.sourceDir, { withFileTypes: true }).filter(entry => entry.isFile() && entry.name.endsWith('.md')).length; } catch {}
195
+ state.projects = state.projects.filter(project => project.name !== body.project);
196
+ state.projects.push({ name: body.project, sourceDir: body.sourceDir, hasIndex: true });
197
+ sendJson(res, 200, { ok: true, project: body.project, filesTracked });
198
+ return;
199
+ }
200
+ if (req.method === 'POST' && url.pathname === '/api/import') {
201
+ state.projects.push({ name: body?.projectName || '', sourceDir: body?.sourceDir || '', hasIndex: true });
202
+ sendJson(res, 200, { ok: true, project: body?.projectName || '' });
203
+ return;
204
+ }
205
+ if (req.method === 'DELETE' && url.pathname === '/api/project') {
206
+ const name = url.searchParams.get('name');
207
+ state.projects = state.projects.filter(project => project.name !== name);
208
+ sendJson(res, 200, { ok: true });
209
+ return;
210
+ }
211
+ sendJson(res, 404, { ok: false, error: { code: 'NOT_FOUND', message: '未实现的模块接口' } });
212
+ });
213
+ return {
214
+ kind: 'laneVectorHub',
215
+ tag,
216
+ state,
217
+ requests: state.requests,
218
+ url: null,
219
+ async start() {
220
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
221
+ this.url = `http://127.0.0.1:${server.address().port}`;
222
+ return this.url;
223
+ },
224
+ async close() { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); },
225
+ };
226
+ }
227
+
228
+ async function startCapHarness({ tag, evidenceDir, viewport = { width: 1600, height: 950 }, serverEnv = {} } = {}) {
229
+ const tempRoot = resolveTempRoot();
230
+ fs.mkdirSync(tempRoot, { recursive: true });
231
+ const previousTemp = { TEMP: process.env.TEMP, TMP: process.env.TMP, TMPDIR: process.env.TMPDIR };
232
+ process.env.TEMP = tempRoot;
233
+ process.env.TMP = tempRoot;
234
+ process.env.TMPDIR = tempRoot;
235
+
236
+ const fixture = fs.mkdtempSync(path.join(tempRoot, `pk-cap-r4-${tag}-`));
237
+ const homeDir = path.join(fixture, 'home');
238
+ fs.mkdirSync(homeDir, { recursive: true });
239
+ const evidence = evidenceDir || path.join(fixture, 'evidence');
240
+ fs.mkdirSync(evidence, { recursive: true });
241
+ const bridgeHome = fs.mkdtempSync(path.join(tempRoot, `pk-cap-r4-${tag}-bridge-`));
242
+ // Force every PowerShell child of this lane (the browser helper's CIM
243
+ // sweep, the product's own port probe) to keep its module analysis cache
244
+ // inside the disposable fixture — see the Microsoft/ forensics.
245
+ process.env.PSModuleAnalysisCachePath = path.join(fixture, 'ps-module-analysis-cache.bin');
246
+
247
+ const realHomeBefore = r3cap.digestRealClientConfigs(realHomeDir());
248
+ const realTreesBefore = r3cap.digestRealClientTrees(realHomeDir());
249
+
250
+ // The analysis step is the frozen stand-in with an empty plan: runs triggered
251
+ // by real commit boundaries complete, and the case says so honestly.
252
+ const plan = { document: '', memoryCandidates: [] };
253
+
254
+ const consoleChild = await startConsoleChild({ bridgeHome, tag: `${tag}-console` });
255
+
256
+ let engine = null;
257
+ let engineProxy = null;
258
+ let terminal = null;
259
+ let laneVector = null;
260
+ let server = null;
261
+ let browser = null;
262
+ let network = null;
263
+ const engineToken = crypto.randomBytes(24).toString('hex');
264
+ let base = null;
265
+ try {
266
+ // The vector plane MUST exist before the engine: the engine's index step
267
+ // calls it, and its built-in default points at the developer's live
268
+ // vector-hub (127.0.0.1:8787) — never reached from this lane.
269
+ laneVector = startLaneVectorHub({ tag: `${tag}-vector` });
270
+ await laneVector.start();
271
+
272
+ const { createEngineServer } = require(ENGINE_ENTRY);
273
+ engine = createEngineServer({
274
+ dataDir: path.join(fixture, 'engine'),
275
+ runtimeToken: engineToken,
276
+ debug: true,
277
+ consume: false,
278
+ bridgeUrl: consoleChild.url,
279
+ vectorUrl: laneVector.url,
280
+ analyzer: createMemoryStandinAnalyzer({ plan }),
281
+ });
282
+ await engine.ready;
283
+ await new Promise(resolve => engine.server.listen(0, '127.0.0.1', resolve));
284
+ const engineUrl = `http://127.0.0.1:${engine.server.address().port}`;
285
+ engineProxy = createUpstreamProxy({ target: engineUrl, token: engineToken, tag: `${tag}-engine` });
286
+ await engineProxy.start();
287
+
288
+ terminal = createModuleFixture({ kind: 'terminal', tag: `${tag}-terminal` });
289
+ await terminal.start();
290
+
291
+ const port = await freePort();
292
+ base = `http://127.0.0.1:${port}`;
293
+ server = withSanitizedEnv(() => spawnServer({
294
+ root: ROOT,
295
+ port,
296
+ dataDir: path.join(fixture, 'data'),
297
+ tag: `cap-r4-${tag}`,
298
+ analysisOwner: 'engine',
299
+ extraEnv: {
300
+ HOME: homeDir,
301
+ USERPROFILE: homeDir,
302
+ CLAUDE_CONFIG_DIR: path.join(homeDir, '.claude'),
303
+ KB_MODULES_REGISTER: '1',
304
+ KB_MODULES_AUTOSTART: '0',
305
+ KB_TERMINAL_URL: terminal.url,
306
+ KB_VECTORHUB_URL: laneVector.url,
307
+ KB_EVENTBRIDGE_URL: consoleChild.url,
308
+ KB_KNOWLEDGE_ENGINE_URL: engineProxy.url,
309
+ AI_CODING_EVENT_BRIDGE_HOME: bridgeHome,
310
+ // A lane may override or extend the server process environment (the
311
+ // CAP-006 isolation case points the server's own codex children at an
312
+ // explicit external CODEX_HOME plus independent APPDATA/LOCALAPPDATA).
313
+ ...serverEnv,
314
+ },
315
+ }));
316
+ process.env.TEMP = previousTemp.TEMP;
317
+ process.env.TMP = previousTemp.TMP;
318
+ process.env.TMPDIR = previousTemp.TMPDIR;
319
+
320
+ await waitFor(async () => {
321
+ try {
322
+ const response = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(5000) });
323
+ return response.status === 200;
324
+ } catch { return false; }
325
+ }, 'the isolated product instance (engine owner)', 30000);
326
+
327
+ browser = await launchCdpBrowser({
328
+ chrome: findChrome(),
329
+ profileDir: path.join(fixture, 'browser'),
330
+ url: `${base}/`,
331
+ width: viewport.width,
332
+ height: viewport.height,
333
+ });
334
+ await browser.setViewport(viewport.width, viewport.height);
335
+ await browser.send('Network.enable');
336
+ network = attachNetworkCapture(browser);
337
+ } catch (error) {
338
+ await browser?.close().catch(() => {});
339
+ await server?.cleanup().catch(() => {});
340
+ await engineProxy?.close().catch(() => {});
341
+ await terminal?.close().catch(() => {});
342
+ await laneVector?.close().catch(() => {});
343
+ await consoleChild?.close().catch(() => {});
344
+ await engine?.close().catch(() => {});
345
+ fs.rmSync(fixture, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
346
+ fs.rmSync(bridgeHome, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
347
+ throw error;
348
+ }
349
+
350
+ const run = expression => browser.evaluate(expression);
351
+
352
+ const productApi = async (method, route, body) => {
353
+ const response = await fetch(base + route, {
354
+ method,
355
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
356
+ body: body === undefined ? undefined : JSON.stringify(body),
357
+ signal: AbortSignal.timeout(30000),
358
+ });
359
+ return { status: response.status, body: await response.json().catch(() => null) };
360
+ };
361
+
362
+ // The engine trusts only the runtime token; the harness created it and holds it.
363
+ const engineTokenFetch = async (method, route, body) => {
364
+ const engineUrl = `http://127.0.0.1:${engine.server.address().port}`;
365
+ const response = await fetch(engineUrl + route, {
366
+ method,
367
+ headers: {
368
+ 'Content-Type': 'application/json',
369
+ Authorization: `Bearer ${engineToken}`,
370
+ },
371
+ body: body === undefined ? undefined : JSON.stringify(body),
372
+ signal: AbortSignal.timeout(20000),
373
+ });
374
+ return { status: response.status, body: await response.json().catch(() => null) };
375
+ };
376
+
377
+ /** A native pointer click: the hit test must resolve to the target. */
378
+ const nativeClick = async selector => {
379
+ const probe = await run(`(() => {
380
+ const el = document.querySelector(${JSON.stringify(selector)});
381
+ if (!el) return { missing: true };
382
+ el.scrollIntoView({ block: 'center' });
383
+ const rect = el.getBoundingClientRect();
384
+ if (rect.width <= 0 || rect.height <= 0) return { invisible: true };
385
+ const x = rect.left + rect.width / 2;
386
+ const y = rect.top + rect.height / 2;
387
+ const hit = document.elementFromPoint(x, y);
388
+ return { x, y, hitIsTarget: Boolean(hit && (hit === el || el.contains(hit))), label: (el.textContent || '').trim().slice(0, 40) };
389
+ })()`);
390
+ if (!probe || probe.missing) throw new Error(`the control ${selector} must exist in the page`);
391
+ if (probe.invisible) throw new Error(`the control ${selector} must be visible`);
392
+ if (!probe.hitIsTarget) throw new Error(`the control ${selector} must be the hit target; something else is on top`);
393
+ const common = { x: probe.x, y: probe.y, button: 'left', clickCount: 1 };
394
+ await browser.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: probe.x, y: probe.y, button: 'none', clickCount: 0 });
395
+ await browser.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...common });
396
+ await browser.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...common });
397
+ return probe;
398
+ };
399
+
400
+ /** Open the real system drawer and wait until the product's own scan settles. */
401
+ const openSystemDrawer = async () => {
402
+ await nativeClick('#openSystem');
403
+ await waitFor(() => run("document.getElementById('systemDrawer').hidden === false"), 'the system drawer is open', 15000);
404
+ await waitFor(
405
+ () => run("document.querySelectorAll('#agentCaptureList .agent-capture-row').length > 0"),
406
+ 'the external agent rows are rendered',
407
+ 60000,
408
+ );
409
+ await waitFor(
410
+ () => run("[...document.querySelectorAll('#agentCaptureList .agent-capture-row')].every(row => { const badge = row.querySelector('.status'); return badge && badge.textContent !== '检测中'; })"),
411
+ 'the external agent rows show a settled state',
412
+ 90000,
413
+ );
414
+ };
415
+
416
+ /** The last install request the real UI sent, with its real response body. */
417
+ const lastInstallCall = async () => {
418
+ const entries = network.find(entry => entry.method === 'POST' && entry.url.includes('/api/integrations/install'));
419
+ const entry = entries.length ? entries[entries.length - 1] : null;
420
+ if (!entry) return null;
421
+ return { method: entry.method, url: entry.url.replace(base, ''), request: entry.body, status: entry.status, response: await network.body(entry) };
422
+ };
423
+
424
+ /** Every install request the real UI sent so far. */
425
+ const installCallCount = () => network.find(entry => entry.method === 'POST' && entry.url.includes('/api/integrations/install')).length;
426
+
427
+ /** Close and reopen the drawer with real clicks: reopening is the product's own refresh point. */
428
+ const reopenSystemDrawer = async () => {
429
+ if (!(await run("document.getElementById('systemDrawer').hidden === false"))) throw new Error('the system drawer must be open before it can be reopened');
430
+ await nativeClick('#closeSystem');
431
+ await waitFor(() => run("document.getElementById('systemDrawer').hidden === true"), 'the system drawer is closed', 15000);
432
+ await openSystemDrawer();
433
+ };
434
+
435
+ /** The rows exactly as the UI rendered them. */
436
+ const agentRows = () => run(`[...document.querySelectorAll('#agentCaptureList .agent-capture-row')].map(row => ({
437
+ label: row.querySelector('b') ? row.querySelector('b').textContent : null,
438
+ badge: row.querySelector('.status') ? row.querySelector('.status').textContent : null,
439
+ client: row.querySelector('[data-agent-switch]') ? row.querySelector('[data-agent-switch]').dataset.agentClient : null,
440
+ details: [...row.querySelectorAll('small')].map(el => el.textContent),
441
+ switch: row.querySelector('[data-agent-switch]') ? {
442
+ action: row.querySelector('[data-agent-switch]').dataset.agentSwitch,
443
+ client: row.querySelector('[data-agent-switch]').dataset.agentClient,
444
+ text: row.querySelector('[data-agent-switch]').textContent,
445
+ disabled: row.querySelector('[data-agent-switch]').disabled,
446
+ } : null,
447
+ retry: row.querySelector('[data-agent-retry]') ? row.querySelector('[data-agent-retry]').dataset.agentClient : null,
448
+ }))`);
449
+
450
+ /** The row of one client exactly as the UI rendered it. */
451
+ const agentRow = async client => {
452
+ const rows = await agentRows();
453
+ return rows.find(row => row.client === client) || null;
454
+ };
455
+
456
+ /** The status once the product's own scan has settled (never a 'checking' placeholder). */
457
+ const settledStatus = async (timeoutMs = 90000) => {
458
+ const deadline = Date.now() + timeoutMs;
459
+ let last = null;
460
+ while (Date.now() < deadline) {
461
+ const result = await productApi('GET', '/api/integrations/status');
462
+ last = result.body;
463
+ const clients = (last && last.clients) || [];
464
+ const pending = clients.some(client => ['checking', 'refreshing'].includes(client.summary)
465
+ || client.knowledgeIntegration?.state === 'checking'
466
+ || client.automaticContext?.state === 'checking'
467
+ || client.developmentCapture?.state === 'checking');
468
+ if (!pending && last && last.scan && last.scan.state === 'ready') return last;
469
+ await new Promise(resolve => setTimeout(resolve, 400));
470
+ }
471
+ throw new Error(`the integration status never settled: ${JSON.stringify(last)}`);
472
+ };
473
+
474
+ /** One client entry of the settled status. */
475
+ const statusClient = (status, client) => (status.clients || []).find(entry => entry.client === client) || null;
476
+
477
+ const typeInto = async (selector, text) => {
478
+ await nativeClick(selector);
479
+ await run(`(() => { const el = document.querySelector(${JSON.stringify(selector)}); el.value = ''; el.focus(); })()`);
480
+ for (const character of String(text)) {
481
+ const upper = character.toUpperCase();
482
+ const isLetter = character >= 'a' && character <= 'z';
483
+ const isUpper = character >= 'A' && character <= 'Z';
484
+ const isDigit = character >= '0' && character <= '9';
485
+ const code = isLetter ? `Key${upper}` : isUpper ? `Key${character}` : isDigit ? `Digit${character}` : '';
486
+ const keyCode = isUpper ? upper.charCodeAt(0) : isLetter ? character.charCodeAt(0) : isDigit ? character.charCodeAt(0) : 0;
487
+ const base = { key: character, code, windowsVirtualKeyCode: keyCode, nativeVirtualKeyCode: keyCode };
488
+ await browser.send('Input.dispatchKeyEvent', { type: 'keyDown', ...base, text: character, unmodifiedText: character });
489
+ await browser.send('Input.dispatchKeyEvent', { type: 'keyUp', ...base });
490
+ }
491
+ };
492
+
493
+ /** The real 系统诊断记录 dialog, searched with the real input and the real 查询 button. */
494
+ const logsSearch = async operationId => {
495
+ if (await run("document.getElementById('logsDialog').open === true")) {
496
+ await nativeClick('#logsDialog [data-close="logsDialog"]');
497
+ await waitFor(() => run("document.getElementById('logsDialog').open === false"), 'the diagnostics dialog is closed', 10000);
498
+ }
499
+ if (await run("document.getElementById('systemDrawer').hidden === true")) await openSystemDrawer();
500
+ await nativeClick('#openLogs');
501
+ await waitFor(() => run("document.getElementById('logsDialog').open === true"), 'the diagnostics dialog is open', 10000);
502
+ await typeInto('#logsSearch', operationId);
503
+ await nativeClick('#loadLogs');
504
+ await waitFor(
505
+ () => run(`[...document.getElementById('logsContent').querySelectorAll('.log-entry')].some(row => row.textContent.includes(${JSON.stringify(operationId)}))`),
506
+ 'the diagnostics search returns records for the operation id',
507
+ 20000,
508
+ );
509
+ return run(`({
510
+ status: document.getElementById('logsStatus').textContent,
511
+ search: document.getElementById('logsSearch').value,
512
+ entries: [...document.getElementById('logsContent').querySelectorAll('.log-entry')].map(row => ({
513
+ level: row.dataset.level,
514
+ summary: row.querySelector('summary') ? row.querySelector('summary').textContent : '',
515
+ detail: row.querySelector('.log-detail') ? row.querySelector('.log-detail').textContent : '',
516
+ })),
517
+ })`);
518
+ };
519
+
520
+ /** The client configuration files the installer wrote into the isolated home. */
521
+ const isolatedConfigs = () => {
522
+ const claudeSettings = path.join(homeDir, '.claude', 'settings.json');
523
+ const readJson = file => {
524
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
525
+ };
526
+ const settings = readJson(claudeSettings);
527
+ const hookEvents = settings && settings.hooks ? settings.hooks : null;
528
+ const ownedHooks = {};
529
+ for (const [event, groups] of Object.entries(hookEvents || {})) {
530
+ const list = Array.isArray(groups) ? groups : [];
531
+ const entries = [];
532
+ for (const group of list) for (const hook of group?.hooks || []) {
533
+ const command = hook?.type === 'command' ? hook.command : `${hook?.command} ${(hook?.args || []).join(' ')}`;
534
+ if (/bridge-hook\.cjs/i.test(String(command))) entries.push({ command, args: hook?.args || null, type: hook?.type || null });
535
+ }
536
+ ownedHooks[event] = entries;
537
+ }
538
+ return {
539
+ homeDir,
540
+ claudeSettingsFile: claudeSettings,
541
+ claudeSettingsExists: fs.existsSync(claudeSettings),
542
+ claudeSettings: settings,
543
+ ownedHooks,
544
+ ownedHookCounts: Object.fromEntries(Object.entries(ownedHooks).map(([event, entries]) => [event, entries.length])),
545
+ };
546
+ };
547
+
548
+ /** The Bridge hook entries the product owns in the isolated home. */
549
+ const ownedHookEntries = () => {
550
+ const configs = isolatedConfigs();
551
+ const entries = [];
552
+ for (const [event, list] of Object.entries(configs.ownedHooks)) {
553
+ for (const hook of list) {
554
+ const match = String(hook.command || '').match(/bridge-hook\.cjs/i);
555
+ const target = match ? String(hook.command).match(/"([^"]*bridge-hook\.cjs)"/i) : null;
556
+ const shim = target ? target[1] : null;
557
+ entries.push({ event, command: hook.command, shimPath: shim, shimExists: Boolean(shim && fs.existsSync(shim)) });
558
+ }
559
+ }
560
+ return entries;
561
+ };
562
+
563
+ // A hung child (a slow install inside the shell, a stuck drain) must never
564
+ // zombie the whole probe: every cleanup step is raced against a deadline and
565
+ // the remaining children are force-killed by their own PIDs afterwards.
566
+ const withDeadline = (promise, ms, label) => Promise.race([
567
+ Promise.resolve(promise).catch(() => {}),
568
+ new Promise(resolve => setTimeout(() => { console.error(`cleanup step timed out: ${label}`); resolve(); }, ms)),
569
+ ]);
570
+ const forceKillTree = pid => {
571
+ if (!pid) return;
572
+ const { spawnSync } = require('node:child_process');
573
+ spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true });
574
+ };
575
+ const cleanup = async () => {
576
+ // Order follows the connection graph: chrome -> shell -> engine (its 2s
577
+ // console poll keeps opening connections) -> console -> lane fixtures.
578
+ // browser.close() includes a machine-wide CIM sweep for detached chrome
579
+ // launchers, which alone can take >15s — give it a real budget.
580
+ await withDeadline(browser?.close(), 30000, 'browser');
581
+ await withDeadline(engine?.close(), 12000, 'engine');
582
+ if (engine?.server) { try { engine.server.closeAllConnections?.(); await new Promise(resolve => engine.server.close(() => resolve())); } catch {} }
583
+ await withDeadline(server?.cleanup(), 20000, 'server');
584
+ if (server?.child?.pid && server.child.exitCode === null) forceKillTree(server.child.pid);
585
+ await withDeadline(consoleChild?.close(), 10000, 'console');
586
+ if (consoleChild && consoleChild.child.exitCode === null) forceKillTree(consoleChild.child.pid);
587
+ await withDeadline(engineProxy?.close(), 5000, 'engine proxy');
588
+ await withDeadline(terminal?.close(), 5000, 'terminal');
589
+ await withDeadline(laneVector?.close(), 5000, 'lane vector');
590
+ fs.rmSync(fixture, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
591
+ fs.rmSync(bridgeHome, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
592
+ };
593
+
594
+ return {
595
+ fixture, evidence, homeDir, bridgeHome, tempRoot, base, server, browser, network,
596
+ run, waitFor, nativeClick, openSystemDrawer, reopenSystemDrawer, agentRows, agentRow,
597
+ settledStatus, statusClient, lastInstallCall, installCallCount, logsSearch,
598
+ isolatedConfigs, ownedHookEntries,
599
+ productApi, engineApi: engineTokenFetch, consoleApi: consoleChild.api, consoleChild,
600
+ engine, engineProxy, terminal, laneVector, plan,
601
+ realHomeBefore, realTreesBefore,
602
+ cleanup,
603
+ };
604
+ }
605
+
606
+ module.exports = { ROOT, startCapHarness, consoleIdentity, sha256File, startLaneVectorHub, realHomeDir };