@sanqianx/project-knowledge 5.0.30 → 5.0.31

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 (65) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +21 -0
  3. package/_site/_test/appearance-settings-test.js +148 -0
  4. package/_site/_test/helpers/parallel-capture-safety-r5-cap-shell.js +606 -0
  5. package/_site/_test/helpers/parallel-capture-safety-r5-memory-shell.js +464 -0
  6. package/_site/_test/helpers/parallel-dock-acceptance-env.js +301 -0
  7. package/_site/_test/helpers/parallel-dock-acceptance-r2-env.js +378 -0
  8. package/_site/_test/helpers/parallel-dock-acceptance-r2-ui.js +314 -0
  9. package/_site/_test/helpers/parallel-dock-acceptance-ui.js +195 -0
  10. package/_site/_test/helpers/parallel-dock-isolation-r3-credential-preload.js +113 -0
  11. package/_site/_test/helpers/parallel-dock-isolation-r3-env.js +307 -0
  12. package/_site/_test/helpers/parallel-dock-isolation-r3-fixture.js +373 -0
  13. package/_site/_test/helpers/parallel-dock-isolation-r3-ui.js +314 -0
  14. package/_site/_test/helpers/parallel-engine-reconcile-r4-harness.js +340 -0
  15. package/_site/_test/helpers/parallel-engine-reconcile-r4-standin-analyzer.js +82 -0
  16. package/_site/_test/helpers/parallel-memory-capture-r3-cap-shell.js +605 -0
  17. package/_site/_test/helpers/parallel-memory-capture-r3-shell.js +176 -0
  18. package/_site/_test/helpers/parallel-memory-capture-r4-cap-shell.js +577 -0
  19. package/_site/_test/helpers/parallel-memory-injection-shell.js +723 -0
  20. package/_site/_test/helpers/parallel-memory-injection-wb-host.js +81 -0
  21. package/_site/_test/helpers/parallel-workbench-drafts-r5-fixture.js +295 -0
  22. package/_site/_test/helpers/parallel-workbench-drafts-r5-harness.js +573 -0
  23. package/_site/_test/helpers/parallel-workbench-drafts-r5-host.js +69 -0
  24. package/_site/_test/helpers/parallel-workbench-runtime-harness.js +587 -0
  25. package/_site/_test/helpers/qa-r45-harness.js +94 -0
  26. package/_site/_test/helpers/qa-r48-env.js +64 -0
  27. package/_site/_test/helpers/qa-r51-env.cjs +77 -0
  28. package/_site/_test/parallel-capture-safety-r5-cap006-probe.js +524 -0
  29. package/_site/_test/parallel-capture-safety-r5-cap008e-probe.js +577 -0
  30. package/_site/_test/parallel-capture-safety-r5-mem005-health-test.js +320 -0
  31. package/_site/_test/parallel-engine-reconcile-r4-eng007-probe.js +304 -0
  32. package/_site/_test/parallel-logging-acceptance-log003-probe.js +78 -0
  33. package/_site/_test/parallel-logging-acceptance-log004-probe.js +85 -0
  34. package/_site/_test/parallel-memory-capture-r3-cap001-probe.js +238 -0
  35. package/_site/_test/parallel-memory-capture-r3-cap006-probe.js +371 -0
  36. package/_site/_test/parallel-memory-capture-r3-cap008-probe.js +439 -0
  37. package/_site/_test/parallel-memory-capture-r3-mem005-persistence-test.js +271 -0
  38. package/_site/_test/parallel-memory-capture-r4-cap006-probe.js +519 -0
  39. package/_site/_test/parallel-memory-capture-r4-cap008e-probe.js +569 -0
  40. package/_site/_test/parallel-memory-capture-r4-mem005-health-test.js +314 -0
  41. package/_site/_test/parallel-memory-injection-origin-probe.js +412 -0
  42. package/_site/_test/parallel-memory-injection-probe.js +411 -0
  43. package/_site/_test/parallel-workbench-drafts-r4-probe.js +477 -0
  44. package/_site/_test/parallel-workbench-drafts-r5-chrome-env-bisect.js +89 -0
  45. package/_site/_test/parallel-workbench-drafts-r5-probe.js +593 -0
  46. package/_site/_test/parallel-workbench-runtime-minimax-probe.js +321 -0
  47. package/_site/_test/parallel-workbench-runtime-wb004-ordering.js +307 -0
  48. package/_site/_test/parallel-workbench-runtime-wb005-drafts.js +313 -0
  49. package/_site/_test/parallel-workbench-runtime-wb008-abort.js +321 -0
  50. package/_site/_test/qa-r45-offline-backfill-test.js +279 -0
  51. package/_site/_test/qa-r48-sys003-blank-secret-test.js +258 -0
  52. package/_site/_test/t07c-cln-001-002-007-coverage-test.js +135 -0
  53. package/_site/_test/t07d-git-rel-coverage-test.js +224 -0
  54. package/_site/_test/t07e-qta-coverage-test.js +195 -0
  55. package/_site/_test/t07f-mem-008-coverage-test.js +101 -0
  56. package/_site/lib/server-app.js +11 -2
  57. package/_site/lib/settings-store.js +43 -1
  58. package/module-runtime-manifest.json +6 -6
  59. package/package.json +1 -1
  60. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  61. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  62. package/plugins/project-knowledge/.mcp.json +1 -1
  63. package/ui/index.html +18 -1
  64. package/ui/product.css +6 -2
  65. package/ui/product.js +86 -1
@@ -0,0 +1,301 @@
1
+ // _site/_test/helpers/parallel-dock-acceptance-env.js
2
+ //
3
+ // Lane-exclusive helper for batch P-DOCK-ACCEPTANCE-01 (DOCK-001/002/003).
4
+ // Boots the REAL product page against REAL module processes with full
5
+ // isolation:
6
+ // - product shell: _site/lib/server-app.js via helpers/spawn-server.js
7
+ // (isolated KB_DATA_DIR / KB_KNOWLEDGE_DATA_DIR / bridge home)
8
+ // - terminal module: the pinned claude-ai-workbench package from this
9
+ // repo's node_modules, spawned here on an exclusive port with its own
10
+ // AGENT_TERMINAL_DATA_DIR + isolated HOME. KB_TERMINAL_URL is injected
11
+ // explicitly, so the product shell treats it as an external service and
12
+ // NEVER spawns/reuses the live 5.x desktop modules (port 5760 etc.).
13
+ // - fixture workspace kept a valid Git repo; the fixture project is then
14
+ // created through the REAL onboarding API chain (settings knowledge-root
15
+ // patch -> preflight-import -> import), which registers it with the
16
+ // terminal module and persists state.modules wiring via module-bridge.
17
+ //
18
+ // Shared helpers (spawn-server, free-port) are referenced read-only.
19
+
20
+ 'use strict';
21
+
22
+ const fs = require('fs');
23
+ const os = require('os');
24
+ const path = require('path');
25
+ const http = require('http');
26
+ const crypto = require('crypto');
27
+ const { spawn, spawnSync } = require('child_process');
28
+
29
+ const { spawnServer } = require('./spawn-server');
30
+ const freePort = require('./free-port');
31
+
32
+ const PKB_ROOT = path.resolve(__dirname, '..', '..', '..');
33
+ const TERMINAL_ENTRY = path.join(
34
+ PKB_ROOT, 'node_modules', 'claude-ai-workbench', 'packages', 'server', 'bin', 'agent-terminal-server.js'
35
+ );
36
+
37
+ function sha256File(file) {
38
+ try { return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); } catch { return null; }
39
+ }
40
+
41
+ function httpJson(url, { method = 'GET', body, timeoutMs = 8000 } = {}) {
42
+ return new Promise((resolve, reject) => {
43
+ const payload = body === undefined ? null : JSON.stringify(body);
44
+ const request = http.request(url, { method, headers: payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {} }, response => {
45
+ let text = '';
46
+ response.setEncoding('utf8');
47
+ response.on('data', chunk => { text += chunk; });
48
+ response.on('end', () => {
49
+ let data = null;
50
+ try { data = text ? JSON.parse(text) : null; } catch { data = null; }
51
+ resolve({ status: response.statusCode, data });
52
+ });
53
+ });
54
+ request.setTimeout(timeoutMs, () => { request.destroy(new Error('timeout')); });
55
+ request.on('error', reject);
56
+ if (payload) request.write(payload);
57
+ request.end();
58
+ });
59
+ }
60
+
61
+ async function waitForHttpOk(url, label, timeoutMs = 60000, accept = () => true) {
62
+ const deadline = Date.now() + timeoutMs;
63
+ let lastError = 'not attempted';
64
+ while (Date.now() < deadline) {
65
+ try {
66
+ const response = await httpJson(url, { timeoutMs: 3000 });
67
+ if (response.status === 200 && accept(response.data)) return response.data;
68
+ lastError = `status ${response.status}`;
69
+ } catch (error) { lastError = error.message; }
70
+ await new Promise(resolve => setTimeout(resolve, 400));
71
+ }
72
+ throw new Error(`Timed out waiting for ${label} (${lastError}): ${url}`);
73
+ }
74
+
75
+ function writeJson(file, value) {
76
+ fs.mkdirSync(path.dirname(file), { recursive: true });
77
+ fs.writeFileSync(file, JSON.stringify(value, null, 2), 'utf8');
78
+ }
79
+
80
+ async function createDockAcceptanceEnv({ tag = 'dock-acceptance' } = {}) {
81
+ if (!fs.existsSync(TERMINAL_ENTRY)) {
82
+ throw new Error(`pinned claude-ai-workbench terminal entry missing: ${TERMINAL_ENTRY}`);
83
+ }
84
+ const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), `pk-${tag}-${process.pid}-`));
85
+ const marker = { pid: process.pid, startedAt: new Date().toISOString() };
86
+ writeJson(path.join(fixtureRoot, 'owner-marker.json'), marker);
87
+
88
+ const workspace = path.join(fixtureRoot, 'workspace');
89
+ const knowledgeDir = path.join(fixtureRoot, 'knowledge');
90
+ const homeDir = path.join(fixtureRoot, 'home');
91
+ const workbenchDir = path.join(fixtureRoot, 'agent-terminal-data');
92
+ const dataDir = path.join(fixtureRoot, 'kb-data');
93
+ for (const dir of [workspace, knowledgeDir, homeDir, workbenchDir, dataDir]) fs.mkdirSync(dir, { recursive: true });
94
+
95
+ // The workspace stays a valid rebuilt Git repo (module/project resolution
96
+ // relies on real repository shape, a lesson carried from the retrieval lane).
97
+ const git = (args) => spawnSync('git', ['-C', workspace, ...args], { encoding: 'utf8', windowsHide: true });
98
+ let gitOk = git(['init', '-q']).status === 0;
99
+ gitOk = git(['config', 'user.email', 'dock-acceptance@example.invalid']).status === 0 && gitOk;
100
+ gitOk = git(['config', 'user.name', 'dock-acceptance']).status === 0 && gitOk;
101
+ fs.writeFileSync(path.join(workspace, 'README.md'), '# dock acceptance fixture workspace\n', 'utf8');
102
+ gitOk = git(['add', 'README.md']).status === 0 && gitOk;
103
+ gitOk = git(['commit', '-q', '-m', 'fixture baseline']).status === 0 && gitOk;
104
+ if (!gitOk) throw new Error('fixture workspace could not be initialized as a Git repository');
105
+
106
+ // The data dir starts EMPTY: initializeProductData refuses a dir holding
107
+ // legacy-shaped entries (projects.json / projects/) without its own
108
+ // product-data.json marker, so the fixture project is created AFTER boot
109
+ // through the real onboarding API chain (settings -> preflight -> import).
110
+
111
+ const productPort = await freePort();
112
+ const terminalPort = await freePort();
113
+ const terminalUrl = `http://127.0.0.1:${terminalPort}`;
114
+ const productUrl = `http://127.0.0.1:${productPort}`;
115
+
116
+ // Product shell. KB_TERMINAL_URL is an explicit external URL: the shell
117
+ // proxies to our isolated terminal module and never spawns or probes the
118
+ // live desktop modules. KB_MODULES_REGISTER=1 re-enables the real
119
+ // per-project module registration the import route performs (terminal
120
+ // project creation + state.modules wiring) — autostart stays off.
121
+ const product = spawnServer({
122
+ root: PKB_ROOT, port: productPort, dataDir, tag,
123
+ analysisOwner: 'engine',
124
+ extraEnv: {
125
+ KB_TERMINAL_URL: terminalUrl,
126
+ KB_MODULES_AUTOSTART: '0',
127
+ KB_MODULES_REGISTER: '1',
128
+ HOME: homeDir, USERPROFILE: homeDir,
129
+ },
130
+ });
131
+
132
+ const env = {
133
+ fixtureRoot, workspace, knowledgeDir, homeDir, workbenchDir, dataDir,
134
+ productUrl, terminalUrl, productPort, terminalPort,
135
+ projectId: null,
136
+ terminalProjectId: null,
137
+ processes: { product: product.child, terminal: null },
138
+ };
139
+
140
+ const productLog = [];
141
+ const productTail = (chunk) => productLog.push(String(chunk));
142
+ product.child.stdout.on('data', productTail);
143
+ product.child.stderr.on('data', productTail);
144
+ const productLogText = () => productLog.join('');
145
+
146
+ try {
147
+ const deadline = Date.now() + 60000;
148
+ while (Date.now() < deadline) {
149
+ if (product.child.exitCode !== null) {
150
+ throw new Error(`product server exited early with code ${product.child.exitCode}; log tail: ${productLogText().slice(-4000)}`);
151
+ }
152
+ try {
153
+ const response = await httpJson(`${productUrl}/api/health`, { timeoutMs: 3000 });
154
+ if (response.status === 200 && response.data && typeof response.data === 'object') break;
155
+ await new Promise(resolve => setTimeout(resolve, 400));
156
+ } catch { await new Promise(resolve => setTimeout(resolve, 400)); }
157
+ }
158
+ const late = await httpJson(`${productUrl}/api/health`, { timeoutMs: 3000 }).catch(() => null);
159
+ if (!late || late.status !== 200) {
160
+ throw new Error(`product health never came up; exitCode=${product.child.exitCode}; log tail: ${productLogText().slice(-4000)}`);
161
+ }
162
+ } catch (error) {
163
+ await cleanup();
164
+ throw error;
165
+ }
166
+
167
+ // Terminal module on its own port with its own data dir and HOME.
168
+ const terminalLog = [];
169
+ const terminal = spawn(process.execPath, [TERMINAL_ENTRY], {
170
+ cwd: PKB_ROOT,
171
+ env: {
172
+ ...process.env,
173
+ AGENT_TERMINAL_PORT: String(terminalPort),
174
+ AGENT_TERMINAL_HOST: '127.0.0.1',
175
+ AGENT_TERMINAL_DATA_DIR: workbenchDir,
176
+ KB_KNOWLEDGE_DATA_DIR: dataDir,
177
+ KB_KNOWLEDGE_ENGINE_URL: 'http://127.0.0.1:0',
178
+ KB_WORKBENCH_DISABLE_PICKER: '1',
179
+ HOME: homeDir, USERPROFILE: homeDir,
180
+ },
181
+ stdio: ['ignore', 'pipe', 'pipe'],
182
+ windowsHide: true,
183
+ });
184
+ env.processes.terminal = terminal;
185
+ const tail = (chunk) => terminalLog.push(String(chunk));
186
+ terminal.stdout.on('data', tail);
187
+ terminal.stderr.on('data', tail);
188
+
189
+ try {
190
+ await waitForHttpOk(`${terminalUrl}/api/claude-workbench/v1/health`, 'terminal module health', 60000,
191
+ data => data && data.status === 'ok' && typeof data.apiVersion === 'string');
192
+ } catch (error) {
193
+ await cleanup();
194
+ throw new Error(`${error.message}; terminal log tail: ${terminalLog.join('').slice(-2000)}`);
195
+ }
196
+
197
+ // Real onboarding chain, exactly what the product UI's import wizard calls:
198
+ // 1. PATCH /api/settings — configure the knowledge root
199
+ // 2. POST /api/projects/preflight-import — validation-only gate
200
+ // 3. POST /api/projects/import — creates the project, installs the
201
+ // real git hook, and registers it with the terminal module through
202
+ // module-bridge (which also persists state.modules.terminal wiring —
203
+ // the mapping ui/product.js uses for kb:knowledge).
204
+ const patched = await httpJson(`${productUrl}/api/settings`, {
205
+ method: 'PATCH', body: { knowledge: { rootPath: knowledgeDir } },
206
+ });
207
+ if (patched.status !== 200 || !(patched.data && patched.data.ok)) {
208
+ await cleanup();
209
+ throw new Error(`settings knowledge-root patch failed: ${patched.status} ${JSON.stringify(patched.data).slice(0, 800)}`);
210
+ }
211
+ const preflight = await httpJson(`${productUrl}/api/projects/preflight-import`, {
212
+ method: 'POST', body: { localPath: workspace },
213
+ });
214
+ if (preflight.status !== 200 || !(preflight.data && preflight.data.ok) || (Array.isArray(preflight.data.problems) && preflight.data.problems.length)) {
215
+ await cleanup();
216
+ throw new Error(`import preflight failed: ${preflight.status} ${JSON.stringify(preflight.data).slice(0, 800)}`);
217
+ }
218
+ const imported = await httpJson(`${productUrl}/api/projects/import`, {
219
+ method: 'POST', body: { localPath: workspace, displayName: 'Dock Acceptance Fixture' },
220
+ });
221
+ const terminalModule = imported.data && imported.data.modules && imported.data.modules.terminal;
222
+ if (imported.status !== 201 || !(imported.data && imported.data.projectId)
223
+ || !(terminalModule && terminalModule.ok === true && terminalModule.status === 'registered' && terminalModule.projectId)) {
224
+ await cleanup();
225
+ throw new Error(`fixture project import/terminal registration failed: ${imported.status} ${JSON.stringify(imported.data).slice(0, 1200)}; product log tail: ${productLogText().slice(-1500)}`);
226
+ }
227
+ env.projectId = imported.data.projectId;
228
+ env.terminalProjectId = terminalModule.projectId;
229
+
230
+ const termApi = (pathname, init) => httpJson(`${productUrl}/api/terminal/${pathname.replace(/^\//, '')}`, init);
231
+
232
+ // Session knowledge fixture in the module's real persisted format. The
233
+ // module reads this file fresh on every GET /sessions/:id/knowledge, so
234
+ // later writes are picked up live without touching the module process.
235
+ const knowledgeFile = path.join(workbenchDir, 'knowledge-contexts.v1.json');
236
+ const seedSessionKnowledge = (sessionId, references, status = 'ready') => {
237
+ const current = fs.existsSync(knowledgeFile)
238
+ ? JSON.parse(fs.readFileSync(knowledgeFile, 'utf8'))
239
+ : { schema: 'session-knowledge-context/v1', sessions: {} };
240
+ current.sessions[sessionId] = { status, references, retrievedAt: new Date().toISOString() };
241
+ writeJson(knowledgeFile, current);
242
+ return current;
243
+ };
244
+
245
+ async function cleanup() {
246
+ const terminalChild = env.processes.terminal;
247
+ if (terminalChild && terminalChild.exitCode === null && terminalChild.pid) {
248
+ if (process.platform === 'win32') {
249
+ try { spawnSync('taskkill', ['/PID', String(terminalChild.pid), '/T', '/F'], { stdio: 'ignore', timeout: 10000, windowsHide: true }); } catch {}
250
+ } else {
251
+ try { terminalChild.kill('SIGTERM'); } catch {}
252
+ await new Promise(resolve => {
253
+ const timer = setTimeout(resolve, 5000);
254
+ terminalChild.once('exit', () => { clearTimeout(timer); resolve(); });
255
+ });
256
+ }
257
+ }
258
+ try { await product.cleanup(); } catch {}
259
+ try {
260
+ const current = JSON.parse(fs.readFileSync(path.join(fixtureRoot, 'owner-marker.json'), 'utf8'));
261
+ if (current.pid === marker.pid) fs.rmSync(fixtureRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
262
+ } catch { /* fixture root already gone or not owned */ }
263
+ }
264
+
265
+ const identity = () => ({
266
+ pkbRoot: PKB_ROOT,
267
+ productId: 'project-knowledge _site server (spawn-server bootstrap)',
268
+ productPid: product.child.pid,
269
+ productPort, terminalPort,
270
+ terminalEntry: TERMINAL_ENTRY,
271
+ terminalPid: terminal.pid,
272
+ terminalPackageVersion: (() => {
273
+ try { return require(path.join(PKB_ROOT, 'node_modules', 'claude-ai-workbench', 'package.json')).version; } catch { return null; }
274
+ })(),
275
+ servedFiles: {
276
+ 'agent-terminal/app.js': { path: path.join(PKB_ROOT, 'node_modules', 'claude-ai-workbench', 'apps', 'agent-terminal', 'app.js') },
277
+ 'agent-terminal/right-workspace-dock.js': { path: path.join(PKB_ROOT, 'node_modules', 'claude-ai-workbench', 'apps', 'agent-terminal', 'right-workspace-dock.js') },
278
+ 'ui/product.js': { path: path.join(PKB_ROOT, 'ui', 'product.js') },
279
+ },
280
+ });
281
+
282
+ const fileHashes = () => {
283
+ const out = {};
284
+ const id = identity();
285
+ for (const [name, entry] of Object.entries(id.servedFiles)) out[name] = sha256File(entry.path);
286
+ return out;
287
+ };
288
+
289
+ return {
290
+ ...env,
291
+ termApi,
292
+ seedSessionKnowledge,
293
+ identity,
294
+ fileHashes,
295
+ cleanup,
296
+ terminalLogText: () => terminalLog.join(''),
297
+ productLogText,
298
+ };
299
+ }
300
+
301
+ module.exports = { createDockAcceptanceEnv };
@@ -0,0 +1,378 @@
1
+ // _site/_test/helpers/parallel-dock-acceptance-r2-env.js
2
+ //
3
+ // Lane-exclusive helper for batch P-DOCK-ACCEPTANCE-02 (DOCK-001/002/004).
4
+ // Derived from the R1 helper (parallel-dock-acceptance-env.js, read-only
5
+ // reference). Same isolation contract, plus two R2 additions:
6
+ //
7
+ // - an optional read-only copy of a REAL model profile (default:
8
+ // 'minimax') into the isolated module data dir, so a real model turn can
9
+ // run without touching the installed desktop workbench. The credential is
10
+ // only written into the isolated temp data dir; it is never logged, never
11
+ // put into a URL, never sent to the browser and never written to a report.
12
+ // - direct access to the isolated module's own API (the product proxy is
13
+ // still available through termApi) plus the module's static app root, so
14
+ // the module's OWN shipped panel host proof page can be driven as a real
15
+ // host for the two-simultaneous-panel case.
16
+ //
17
+ // Everything else (product shell, fixture project through the real
18
+ // onboarding API chain, isolated HOME/ports/data dirs, owner-marker cleanup)
19
+ // is unchanged from R1.
20
+
21
+ 'use strict';
22
+
23
+ const fs = require('fs');
24
+ const os = require('os');
25
+ const path = require('path');
26
+ const http = require('http');
27
+ const crypto = require('crypto');
28
+ const { spawn, spawnSync } = require('child_process');
29
+
30
+ const { spawnServer } = require('./spawn-server');
31
+ const freePort = require('./free-port');
32
+
33
+ const PKB_ROOT = path.resolve(__dirname, '..', '..', '..');
34
+ const TERMINAL_ENTRY = path.join(
35
+ PKB_ROOT, 'node_modules', 'claude-ai-workbench', 'packages', 'server', 'bin', 'agent-terminal-server.js'
36
+ );
37
+ const MODULE_APP_ROOT = path.join(PKB_ROOT, 'node_modules', 'claude-ai-workbench', 'apps', 'agent-terminal');
38
+ const MODULE_API_PREFIX = '/api/claude-workbench/v1';
39
+
40
+ // Real, already-installed workbench stores. They are opened READ-ONLY and
41
+ // only to copy one profile definition + its credential into the isolated
42
+ // fixture data dir. The live desktop core 5.0.24 installation is never
43
+ // written to, restarted or replaced.
44
+ const REAL_PROFILE_STORES = [
45
+ path.join(os.homedir(), '.project-knowledge-v5', 'workbench'),
46
+ path.join(os.homedir(), '.agent-terminal'),
47
+ ];
48
+
49
+ function sha256File(file) {
50
+ try { return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); } catch { return null; }
51
+ }
52
+
53
+ function httpJson(url, { method = 'GET', body, timeoutMs = 8000 } = {}) {
54
+ return new Promise((resolve, reject) => {
55
+ const payload = body === undefined ? null : JSON.stringify(body);
56
+ const request = http.request(url, { method, headers: payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {} }, response => {
57
+ let text = '';
58
+ response.setEncoding('utf8');
59
+ response.on('data', chunk => { text += chunk; });
60
+ response.on('end', () => {
61
+ let data = null;
62
+ try { data = text ? JSON.parse(text) : null; } catch { data = null; }
63
+ resolve({ status: response.statusCode, data, text });
64
+ });
65
+ });
66
+ request.setTimeout(timeoutMs, () => { request.destroy(new Error('timeout')); });
67
+ request.on('error', reject);
68
+ if (payload) request.write(payload);
69
+ request.end();
70
+ });
71
+ }
72
+
73
+ async function waitForHttpOk(url, label, timeoutMs = 60000, accept = () => true) {
74
+ const deadline = Date.now() + timeoutMs;
75
+ let lastError = 'not attempted';
76
+ while (Date.now() < deadline) {
77
+ try {
78
+ const response = await httpJson(url, { timeoutMs: 3000 });
79
+ if (response.status === 200 && accept(response.data)) return response.data;
80
+ lastError = `status ${response.status}`;
81
+ } catch (error) { lastError = error.message; }
82
+ await new Promise(resolve => setTimeout(resolve, 400));
83
+ }
84
+ throw new Error(`Timed out waiting for ${label} (${lastError}): ${url}`);
85
+ }
86
+
87
+ function writeJson(file, value) {
88
+ fs.mkdirSync(path.dirname(file), { recursive: true });
89
+ fs.writeFileSync(file, JSON.stringify(value, null, 2), 'utf8');
90
+ }
91
+
92
+ // Copy exactly one real profile (definition + credential) into the isolated
93
+ // module data dir. The secret never leaves the fixture directory: it is not
94
+ // logged, not returned to the caller and not written into any artifact.
95
+ function seedModelProfile(workbenchDir, profileId) {
96
+ for (const store of REAL_PROFILE_STORES) {
97
+ const profilesFile = path.join(store, 'profiles.v2.json');
98
+ const credentialsFile = path.join(store, 'credentials.v1.json');
99
+ if (!fs.existsSync(profilesFile) || !fs.existsSync(credentialsFile)) continue;
100
+ let profiles;
101
+ let credentials;
102
+ try {
103
+ profiles = JSON.parse(fs.readFileSync(profilesFile, 'utf8'));
104
+ credentials = JSON.parse(fs.readFileSync(credentialsFile, 'utf8'));
105
+ } catch { continue; }
106
+ const profile = (profiles.profiles || []).find(item => item && item.id === profileId);
107
+ if (!profile) continue;
108
+ const credentialRef = profile.credentialRef || `credential:${profile.id}`;
109
+ const secret = (credentials.credentials || {})[credentialRef];
110
+ if (!secret) continue;
111
+ writeJson(path.join(workbenchDir, 'profiles.v2.json'), {
112
+ schema: 'claude-workbench-profiles/v2',
113
+ profiles: [profile],
114
+ maintenanceDefaultProfileId: null,
115
+ });
116
+ writeJson(path.join(workbenchDir, 'credentials.v1.json'), {
117
+ schema: 'claude-workbench-credentials/v1',
118
+ credentials: { [credentialRef]: secret },
119
+ });
120
+ return {
121
+ profileId: profile.id,
122
+ name: profile.name || null,
123
+ provider: profile.provider || null,
124
+ baseUrl: profile.baseUrl || null,
125
+ model: (profile.models && profile.models.default) || null,
126
+ credentialRef,
127
+ credentialConfigured: true,
128
+ sourceStore: path.basename(store),
129
+ };
130
+ }
131
+ throw new Error(`real profile "${profileId}" not found in any installed workbench store`);
132
+ }
133
+
134
+ async function createDockAcceptanceEnv({ tag = 'dock-acceptance-r2', modelProfileId = null } = {}) {
135
+ if (!fs.existsSync(TERMINAL_ENTRY)) {
136
+ throw new Error(`pinned claude-ai-workbench terminal entry missing: ${TERMINAL_ENTRY}`);
137
+ }
138
+ const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), `pk-${tag}-${process.pid}-`));
139
+ const marker = { pid: process.pid, startedAt: new Date().toISOString() };
140
+ writeJson(path.join(fixtureRoot, 'owner-marker.json'), marker);
141
+
142
+ const workspace = path.join(fixtureRoot, 'workspace');
143
+ const knowledgeDir = path.join(fixtureRoot, 'knowledge');
144
+ const homeDir = path.join(fixtureRoot, 'home');
145
+ const workbenchDir = path.join(fixtureRoot, 'agent-terminal-data');
146
+ const dataDir = path.join(fixtureRoot, 'kb-data');
147
+ // Windows roaming/local app data are per-user state directories. The
148
+ // dispatch requires them isolated per run, otherwise a spawned process could
149
+ // read or write the developer's real per-user application state.
150
+ const appDataDir = path.join(fixtureRoot, 'appdata-roaming');
151
+ const localAppDataDir = path.join(fixtureRoot, 'appdata-local');
152
+ const tempDir = path.join(fixtureRoot, 'temp');
153
+ for (const dir of [workspace, knowledgeDir, homeDir, workbenchDir, dataDir, appDataDir, localAppDataDir, tempDir]) fs.mkdirSync(dir, { recursive: true });
154
+
155
+ // The model profile (if any) is written BEFORE the module boots so the
156
+ // module reads it from its own store on first use.
157
+ let modelProfile = null;
158
+ if (modelProfileId) modelProfile = seedModelProfile(workbenchDir, modelProfileId);
159
+
160
+ const git = (args) => spawnSync('git', ['-C', workspace, ...args], { encoding: 'utf8', windowsHide: true });
161
+ let gitOk = git(['init', '-q']).status === 0;
162
+ gitOk = git(['config', 'user.email', 'dock-acceptance@example.invalid']).status === 0 && gitOk;
163
+ gitOk = git(['config', 'user.name', 'dock-acceptance']).status === 0 && gitOk;
164
+ fs.writeFileSync(path.join(workspace, 'README.md'), '# dock acceptance fixture workspace\n', 'utf8');
165
+ gitOk = git(['add', 'README.md']).status === 0 && gitOk;
166
+ gitOk = git(['commit', '-q', '-m', 'fixture baseline']).status === 0 && gitOk;
167
+ if (!gitOk) throw new Error('fixture workspace could not be initialized as a Git repository');
168
+
169
+ const productPort = await freePort();
170
+ const terminalPort = await freePort();
171
+ const terminalUrl = `http://127.0.0.1:${terminalPort}`;
172
+ const productUrl = `http://127.0.0.1:${productPort}`;
173
+
174
+ const product = spawnServer({
175
+ root: PKB_ROOT, port: productPort, dataDir, tag,
176
+ analysisOwner: 'engine',
177
+ extraEnv: {
178
+ KB_TERMINAL_URL: terminalUrl,
179
+ KB_MODULES_AUTOSTART: '0',
180
+ KB_MODULES_REGISTER: '1',
181
+ HOME: homeDir, USERPROFILE: homeDir,
182
+ APPDATA: appDataDir, LOCALAPPDATA: localAppDataDir, TEMP: tempDir, TMP: tempDir,
183
+ },
184
+ });
185
+
186
+ const env = {
187
+ fixtureRoot, workspace, knowledgeDir, homeDir, workbenchDir, dataDir,
188
+ appDataDir, localAppDataDir, tempDir,
189
+ productUrl, terminalUrl, productPort, terminalPort,
190
+ modelProfile,
191
+ projectId: null,
192
+ terminalProjectId: null,
193
+ processes: { product: product.child, terminal: null },
194
+ };
195
+
196
+ const productLog = [];
197
+ const productTail = (chunk) => productLog.push(String(chunk));
198
+ product.child.stdout.on('data', productTail);
199
+ product.child.stderr.on('data', productTail);
200
+ const productLogText = () => productLog.join('');
201
+
202
+ async function cleanup() {
203
+ const terminalChild = env.processes.terminal;
204
+ if (terminalChild && terminalChild.exitCode === null && terminalChild.pid) {
205
+ if (process.platform === 'win32') {
206
+ try { spawnSync('taskkill', ['/PID', String(terminalChild.pid), '/T', '/F'], { stdio: 'ignore', timeout: 10000, windowsHide: true }); } catch {}
207
+ } else {
208
+ try { terminalChild.kill('SIGTERM'); } catch {}
209
+ await new Promise(resolve => {
210
+ const timer = setTimeout(resolve, 5000);
211
+ terminalChild.once('exit', () => { clearTimeout(timer); resolve(); });
212
+ });
213
+ }
214
+ }
215
+ try { await product.cleanup(); } catch {}
216
+ try {
217
+ const current = JSON.parse(fs.readFileSync(path.join(fixtureRoot, 'owner-marker.json'), 'utf8'));
218
+ if (current.pid === marker.pid) fs.rmSync(fixtureRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
219
+ } catch { /* fixture root already gone or not owned */ }
220
+ }
221
+
222
+ try {
223
+ const deadline = Date.now() + 60000;
224
+ while (Date.now() < deadline) {
225
+ if (product.child.exitCode !== null) {
226
+ throw new Error(`product server exited early with code ${product.child.exitCode}; log tail: ${productLogText().slice(-4000)}`);
227
+ }
228
+ try {
229
+ const response = await httpJson(`${productUrl}/api/health`, { timeoutMs: 3000 });
230
+ if (response.status === 200 && response.data && typeof response.data === 'object') break;
231
+ await new Promise(resolve => setTimeout(resolve, 400));
232
+ } catch { await new Promise(resolve => setTimeout(resolve, 400)); }
233
+ }
234
+ const late = await httpJson(`${productUrl}/api/health`, { timeoutMs: 3000 }).catch(() => null);
235
+ if (!late || late.status !== 200) {
236
+ throw new Error(`product health never came up; exitCode=${product.child.exitCode}; log tail: ${productLogText().slice(-4000)}`);
237
+ }
238
+ } catch (error) {
239
+ await cleanup();
240
+ throw error;
241
+ }
242
+
243
+ // Terminal module on its own port with its own data dir and HOME.
244
+ const terminalLog = [];
245
+ const terminal = spawn(process.execPath, [TERMINAL_ENTRY], {
246
+ cwd: PKB_ROOT,
247
+ env: {
248
+ ...process.env,
249
+ AGENT_TERMINAL_PORT: String(terminalPort),
250
+ AGENT_TERMINAL_HOST: '127.0.0.1',
251
+ AGENT_TERMINAL_DATA_DIR: workbenchDir,
252
+ KB_KNOWLEDGE_DATA_DIR: dataDir,
253
+ KB_KNOWLEDGE_ENGINE_URL: 'http://127.0.0.1:0',
254
+ KB_WORKBENCH_DISABLE_PICKER: '1',
255
+ HOME: homeDir, USERPROFILE: homeDir,
256
+ APPDATA: appDataDir, LOCALAPPDATA: localAppDataDir, TEMP: tempDir, TMP: tempDir,
257
+ // The CLI that the Agent SDK spawns must not read or write the real
258
+ // developer's agent config directories.
259
+ CLAUDE_CONFIG_DIR: path.join(homeDir, '.claude'),
260
+ CODEX_HOME: path.join(homeDir, '.codex'),
261
+ },
262
+ stdio: ['ignore', 'pipe', 'pipe'],
263
+ windowsHide: true,
264
+ });
265
+ env.processes.terminal = terminal;
266
+ const tail = (chunk) => terminalLog.push(String(chunk));
267
+ terminal.stdout.on('data', tail);
268
+ terminal.stderr.on('data', tail);
269
+
270
+ try {
271
+ await waitForHttpOk(`${terminalUrl}${MODULE_API_PREFIX}/health`, 'terminal module health', 60000,
272
+ data => data && data.status === 'ok' && typeof data.apiVersion === 'string');
273
+ } catch (error) {
274
+ await cleanup();
275
+ throw new Error(`${error.message}; terminal log tail: ${terminalLog.join('').slice(-2000)}`);
276
+ }
277
+
278
+ // Real onboarding chain (settings -> preflight -> import). The import route
279
+ // registers the fixture project with the terminal module and persists the
280
+ // state.modules.terminal wiring the product UI depends on.
281
+ const patched = await httpJson(`${productUrl}/api/settings`, {
282
+ method: 'PATCH', body: { knowledge: { rootPath: knowledgeDir } },
283
+ });
284
+ if (patched.status !== 200 || !(patched.data && patched.data.ok)) {
285
+ await cleanup();
286
+ throw new Error(`settings knowledge-root patch failed: ${patched.status} ${JSON.stringify(patched.data).slice(0, 800)}`);
287
+ }
288
+ const preflight = await httpJson(`${productUrl}/api/projects/preflight-import`, {
289
+ method: 'POST', body: { localPath: workspace },
290
+ });
291
+ if (preflight.status !== 200 || !(preflight.data && preflight.data.ok) || (Array.isArray(preflight.data.problems) && preflight.data.problems.length)) {
292
+ await cleanup();
293
+ throw new Error(`import preflight failed: ${preflight.status} ${JSON.stringify(preflight.data).slice(0, 800)}`);
294
+ }
295
+ const imported = await httpJson(`${productUrl}/api/projects/import`, {
296
+ method: 'POST', body: { localPath: workspace, displayName: 'Dock Acceptance Fixture' },
297
+ });
298
+ const terminalModule = imported.data && imported.data.modules && imported.data.modules.terminal;
299
+ if (imported.status !== 201 || !(imported.data && imported.data.projectId)
300
+ || !(terminalModule && terminalModule.ok === true && terminalModule.status === 'registered' && terminalModule.projectId)) {
301
+ await cleanup();
302
+ throw new Error(`fixture project import/terminal registration failed: ${imported.status} ${JSON.stringify(imported.data).slice(0, 1200)}; product log tail: ${productLogText().slice(-1500)}`);
303
+ }
304
+ env.projectId = imported.data.projectId;
305
+ env.terminalProjectId = terminalModule.projectId;
306
+
307
+ // Through the PRODUCT proxy (the path the product UI actually uses).
308
+ const termApi = (pathname, init) => httpJson(`${productUrl}/api/terminal/${pathname.replace(/^\//, '')}`, init);
309
+ // Direct to the isolated module (same server, bypassing the product proxy).
310
+ const moduleApi = (pathname, init) => httpJson(`${terminalUrl}${MODULE_API_PREFIX}/${pathname.replace(/^\//, '')}`, init);
311
+
312
+ const knowledgeFile = path.join(workbenchDir, 'knowledge-contexts.v1.json');
313
+ const seedSessionKnowledge = (sessionId, references, status = 'ready') => {
314
+ const current = fs.existsSync(knowledgeFile)
315
+ ? JSON.parse(fs.readFileSync(knowledgeFile, 'utf8'))
316
+ : { schema: 'session-knowledge-context/v1', sessions: {} };
317
+ current.sessions[sessionId] = { status, references, retrievedAt: new Date().toISOString() };
318
+ writeJson(knowledgeFile, current);
319
+ return current;
320
+ };
321
+
322
+ // The isolated module's own native-task store identity (used by the
323
+ // public native-tasks read API). The module publishes it as
324
+ // { schema: 'workbench-store/v1', storeId }.
325
+ const storeScope = () => {
326
+ try {
327
+ const raw = JSON.parse(fs.readFileSync(path.join(workbenchDir, 'store-id.v1.json'), 'utf8'));
328
+ return raw.storeId || raw.storeScope || raw.scope || raw.id || null;
329
+ } catch { return null; }
330
+ };
331
+
332
+ const identity = () => ({
333
+ pkbRoot: PKB_ROOT,
334
+ productId: 'project-knowledge _site server (spawn-server bootstrap)',
335
+ productPid: product.child.pid,
336
+ productPort, terminalPort,
337
+ terminalEntry: TERMINAL_ENTRY,
338
+ terminalPid: terminal.pid,
339
+ terminalPackageVersion: (() => {
340
+ try { return require(path.join(PKB_ROOT, 'node_modules', 'claude-ai-workbench', 'package.json')).version; } catch { return null; }
341
+ })(),
342
+ modelProfile: env.modelProfile,
343
+ servedFiles: {
344
+ 'agent-terminal/app.js': { path: path.join(MODULE_APP_ROOT, 'app.js') },
345
+ 'agent-terminal/right-workspace-dock.js': { path: path.join(MODULE_APP_ROOT, 'right-workspace-dock.js') },
346
+ 'agent-terminal/right-dock-panel-registry.js': { path: path.join(MODULE_APP_ROOT, 'right-dock-panel-registry.js') },
347
+ 'agent-terminal/panel-host-proof.html': { path: path.join(MODULE_APP_ROOT, 'panel-host-proof.html') },
348
+ 'agent-terminal/panel-proof-content.html': { path: path.join(MODULE_APP_ROOT, 'panel-proof-content.html') },
349
+ 'ui/product.js': { path: path.join(PKB_ROOT, 'ui', 'product.js') },
350
+ },
351
+ });
352
+
353
+ const fileHashes = () => {
354
+ const out = {};
355
+ const id = identity();
356
+ for (const [name, entry] of Object.entries(id.servedFiles)) out[name] = sha256File(entry.path);
357
+ return out;
358
+ };
359
+
360
+ return {
361
+ ...env,
362
+ termApi,
363
+ moduleApi,
364
+ seedSessionKnowledge,
365
+ storeScope,
366
+ identity,
367
+ fileHashes,
368
+ cleanup,
369
+ // The module's own shipped panel host proof page (a real host that
370
+ // registers a multi-instance panel provider through the public panel
371
+ // protocol and drives it with real buttons).
372
+ panelProofHostUrl: () => `${terminalUrl}/agent-terminal/panel-host-proof.html`,
373
+ terminalLogText: () => terminalLog.join(''),
374
+ productLogText,
375
+ };
376
+ }
377
+
378
+ module.exports = { createDockAcceptanceEnv, MODULE_API_PREFIX, MODULE_APP_ROOT };