@sanqianx/project-knowledge 5.1.3 → 5.1.5

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 (43) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +13 -0
  3. package/_site/_test/agent-capture-mcp-ui-test.js +21 -7
  4. package/_site/_test/agent-capture-ui-test.js +4 -3
  5. package/_site/_test/bin-cli-test.js +3 -2
  6. package/_site/_test/capture-hook-dedup-test.js +41 -1
  7. package/_site/_test/cli-version-report-test.js +22 -0
  8. package/_site/_test/codex-notify-upgrade-test.js +7 -0
  9. package/_site/_test/fixtures/integration-busy-worker.cjs +11 -3
  10. package/_site/_test/helpers/parallel-memory-shell.js +13 -2
  11. package/_site/_test/hook-relocation-rebind-test.js +120 -0
  12. package/_site/_test/integration-auto-repair-test.js +3 -1
  13. package/_site/_test/integration-intent-test.js +6 -2
  14. package/_site/_test/integration-runtime-binding-test.js +4 -4
  15. package/_site/_test/integration-status-scan-test.js +138 -7
  16. package/_site/_test/legacy-relocation-recovery-test.js +258 -0
  17. package/_site/_test/parallel-retrieval-followup-corpus-test.js +6 -4
  18. package/_site/_test/project-team-ui-test.js +124 -0
  19. package/_site/_test/recovery-label-contract-test.js +45 -0
  20. package/_site/lib/capture-hook-config.js +25 -9
  21. package/_site/lib/claude-plugin-status.js +60 -0
  22. package/_site/lib/commit-prompt.js +205 -202
  23. package/_site/lib/commit-reconciler.js +551 -444
  24. package/_site/lib/contracts.js +1 -0
  25. package/_site/lib/evidence-bundle.js +32 -5
  26. package/_site/lib/integration-auto-repair.js +3 -2
  27. package/_site/lib/integration-installer.js +153 -71
  28. package/_site/lib/integration-intent.js +12 -5
  29. package/_site/lib/integration-status-scan.js +101 -41
  30. package/_site/lib/integration-status-worker.js +4 -2
  31. package/_site/lib/knowledge-promotion.js +547 -435
  32. package/_site/lib/module-bridge.js +1 -1
  33. package/_site/lib/scanner.js +5 -3
  34. package/_site/lib/server-app.js +34 -7
  35. package/_site/scripts/refresh-runtime-manifest.js +1 -1
  36. package/bin/project-knowledge.js +51 -1
  37. package/module-runtime-manifest.json +84 -84
  38. package/package.json +6 -6
  39. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  40. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  41. package/plugins/project-knowledge/.mcp.json +1 -1
  42. package/ui/product.css +1 -0
  43. package/ui/product.js +125 -30
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "project-knowledge",
12
- "version": "5.1.3",
12
+ "version": "5.1.5",
13
13
  "source": "./plugins/project-knowledge",
14
14
  "description": "Search durable project decisions and implementation history through MCP."
15
15
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [5.1.5] - 2026-11-20
4
+
5
+ - 外部 Agent 接入页并行检查 Claude Code、OpenCode、Codex 和 ZCode,逐项显示采集和开发前知识状态。Claude Code 的插件状态直接读取本地安装记录,避免反复启动原生 CLI。单个客户端的检查失败可单独刷新,自动修复只处理已确认损坏的采集配置。
6
+ - 维护任务从当前数据目录定位提交证据和检索快照,兼容旧格式任务及知识晋升恢复记录。移动数据目录后自动校正托管 Git Hook。活动记录区分证据缺失与完整性错误,并显示实际调度的重试状态。
7
+ - Workbench 重新定位旧会话的托管知识目录,Event Bridge 按当前托管目录解析默认事件账本,vector-hub 在知识目录迁移后更新项目的索引来源并拒绝冲突地址。
8
+ - 项目页可以创建、挂载和解除 AI 团队。建队向导支持选择成员、自定义职责和引用记忆组合,建队后可继续添加成员;解除挂载保留该项目的团队设置。
9
+ - 模块版本统一更新为 Workbench `0.13.14`、Event Bridge `0.7.5-rc.1`、vector-hub `1.0.8-rc.9`、knowledge-engine `0.3.2` 和 ai-coding-workflow `0.1.2`。
10
+
11
+ ## [5.1.4] - 2026-11-19
12
+
13
+ - 默认数据目录改为 `~/.project-knowledge`,仍可显式选择数据目录。重新接入 ZCode、Claude Code 或 Codex 时会清理指向旧默认目录 `~/.project-knowledge-v5` 的采集入口,避免旧脚本路径报错或重复采集。
14
+ - `project-knowledge --version` 现同时显示主程序和五个模块的版本。
15
+
3
16
  ## [5.0.35] - 2026-11-13
4
17
 
5
18
  - 模块监督器退避计数在稳定运行后重置:连续健康运行 ≥60 秒的模块服务,其下一次退出按新事故计(计数归 1),只有持续快速崩溃才累计到放弃上限,快速崩溃循环的原有保护与退避节奏不变。消除「偶发退出的模块被监督器永久放弃、外壳持续向死端口反代、界面长时间 MODULE_UNREACHABLE 直到重启外壳」的故障模式(系统日志中 10-22→23、10-26→27 两波 24/20 小时级故障即此成因)。新增 `module-supervisor-backoff-reset-test.js` 回归(崩溃循环仍放弃 + 稳定退出必拉起且计数归 1)。
@@ -34,29 +34,43 @@ async function main() {
34
34
  const offline = http.createServer((req, res) => { res.writeHead(503, { 'content-type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: { message: 'offline stub' } })); });
35
35
  await new Promise(resolve => offline.listen(0, '127.0.0.1', resolve));
36
36
  const offlineUrl = 'http://127.0.0.1:' + offline.address().port;
37
- const runtime = createRuntime({ dataDir, analysisOwner: 'engine', bridgeAdapter: new BridgeAdapter({ dataDir, bridgeHomeDir: eventsHome }), moduleBridge: new ModuleBridge({ terminalUrl: offlineUrl, engineUrl: offlineUrl, eventBridgeUrl: offlineUrl, vectorHubUrl: offlineUrl }) });
37
+ const runtime = createRuntime({ dataDir, analysisOwner: 'engine', bridgeAdapter: new BridgeAdapter({ dataDir, bridgeHomeDir: eventsHome }), moduleBridge: new ModuleBridge({ terminalUrl: offlineUrl, engineUrl: offlineUrl, eventBridgeUrl: offlineUrl, vectorHubUrl: offlineUrl, workflowUrl: offlineUrl }) });
38
38
  await initializeRuntime(runtime);
39
39
  const server = http.createServer(createRequestHandler(runtime, { integrationOptions: { homeDir, env: {}, commandResolver: () => '' } }));
40
40
  await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
41
41
  const base = 'http://127.0.0.1:' + server.address().port;
42
- const payload = JSON.stringify({ bridge: { ok: true }, scan: { state: 'ready' }, clients: [clientFixture('claude', 'Claude Code'), clientFixture('codex', 'Codex'), clientFixture('zcode', 'ZCode'), clientFixture('opencode', 'OpenCode')] });
42
+ const payload = JSON.stringify({ bridge: { ok: true }, scan: { state: 'ready' }, clients: [
43
+ {
44
+ client: 'claude', label: 'Claude Code', summary: 'check-failed',
45
+ scan: { state: 'check-failed', error: { code: 'INTEGRATION_STATUS_TIMEOUT' } },
46
+ developmentCapture: { state: 'check-failed', ok: false, detail: '采集状态尚未核实。' },
47
+ },
48
+ clientFixture('codex', 'Codex'),
49
+ clientFixture('zcode', 'ZCode'),
50
+ { client: 'opencode', label: 'OpenCode', available: false, configFound: false, summary: 'not-detected', developmentCapture: { installed: false, state: 'not-installed' } },
51
+ ] });
43
52
  let browser;
44
53
  try {
45
54
  browser = await launchCdpBrowser({ chrome: findChrome(), profileDir: path.join(temp, 'browser'), url: base, width: 1440, height: 900 });
46
55
  const run = expression => browser.evaluate(expression);
47
56
  const click = selector => run('document.querySelector(' + JSON.stringify(selector) + ').click()');
48
- await run('(() => { const original = window.fetch; window.__originalFetch = original; window.fetch = (input, init) => { const url = String(input && input.url || input); if (url.includes(\'/api/integrations/status\')) { return Promise.resolve({ ok: true, json: async () => (' + payload + ') }); } return original(input, init); }; })()');
57
+ await run('(() => { const original = window.fetch; window.__integrationRequests = []; window.fetch = (input, init) => { const url = String(input && input.url || input); if (url.includes(\'/api/integrations/\')) { window.__integrationRequests.push([url, init?.method || \'GET\']); return Promise.resolve({ ok: true, json: async () => (' + payload + ') }); } return original(input, init); }; })()');
49
58
  await click('#openSystem');
50
59
  await waitFor(() => run("document.querySelectorAll('#agentCaptureList .agent-capture-row').length === 4"), 'capture rows render');
51
60
  assert(await run("document.getElementById('agentCaptureList').textContent.includes('PROBE_TIMEOUT')"), 'the MCP startup failure code must be rendered for MCP-capable clients');
52
- const claudeRowHtml = await run("document.querySelector('#agentCaptureList .agent-capture-row').innerHTML");
53
- assert(claudeRowHtml.includes('<img'), 'hostile mcpStartup detail must be HTML-escaped, got: ' + claudeRowHtml.slice(0, 300));
54
- assert(!claudeRowHtml.includes('<img'), 'no raw hostile markup may reach the DOM');
61
+ const codexRowHtml = await run("document.querySelector('.agent-capture-row[data-agent-client=codex]').innerHTML");
62
+ assert(codexRowHtml.includes('&lt;img'), 'hostile mcpStartup detail must be HTML-escaped, got: ' + codexRowHtml.slice(0, 300));
63
+ assert(!codexRowHtml.includes('<img'), 'no raw hostile markup may reach the DOM');
55
64
  assert.equal(await run('window.__kbXssProbe'), undefined, 'the hostile onerror must never execute');
56
65
  const smalls = await run("[...document.querySelectorAll('#agentCaptureList small')].map(el => el.textContent).join('|')");
57
66
  assert(smalls.split('|').some(text => text.startsWith('MCP')), 'the MCP diagnostic is its own line item, got: ' + smalls);
67
+ const badges = await run("Object.fromEntries(Array.from(document.querySelectorAll('.agent-capture-row'), row => [row.dataset.agentClient, row.querySelector('.status').textContent]))");
68
+ assert.deepEqual(badges, { claude: '检测超时', codex: '已接入', zcode: '已接入', opencode: '未检测到' });
69
+ await click('[data-agent-check="claude"]');
70
+ await waitFor(() => run("window.__integrationRequests.some(([url]) => url.includes('clients=claude') && url.includes('refresh=1'))"), 'single-client refresh request');
71
+ assert.equal(await run("window.__integrationRequests.every(([,method]) => method === 'GET')"), true, 'rechecking a timeout never installs or repairs an agent');
58
72
  assert.equal(browser.exceptions.length, 0, JSON.stringify(browser.exceptions));
59
- console.log('agent-capture-mcp-ui-test PASS (MCP line rendered separately; hostile detail escaped; no XSS execution)');
73
+ console.log('agent-capture-mcp-ui-test PASS (independent states, targeted retry and escaped MCP diagnostics)');
60
74
  } finally {
61
75
  runtime.integrationStatusScan?.close();
62
76
  await browser?.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
@@ -70,15 +70,16 @@ async function main() {
70
70
  await click('#closeSystem'); await click('#themeToggle'); await click('#openSystem');
71
71
  await waitFor(() => run("document.querySelector('[data-agent-client=zcode][data-agent-switch=uninstall]') !== null"), 'theme retains capture status');
72
72
  await browser.screenshot(path.join(artifacts, '1920-dark.png'));
73
- // Broken config: the single switch acts as the explicit repair path.
73
+ // Confirmed invalid config is actionable, and the installer preserves it.
74
74
  fs.writeFileSync(configFile, '{invalid JSON');
75
75
  await click('#closeSystem'); await click('#openSystem');
76
- await waitFor(() => run("(() => { const b = document.querySelector('[data-agent-client=zcode][data-agent-switch=install]'); return b !== null && !b.disabled; })()"), 'capture row settled before invalid config');
76
+ await waitFor(() => run("(() => { const b = document.querySelector('[data-agent-client=zcode][data-agent-switch=install]'); return b !== null && !b.disabled && b.closest('.agent-capture-row').textContent.includes('异常'); })()"), 'invalid ZCode config is shown as actionable');
77
77
  await click('[data-agent-client=zcode][data-agent-switch=install]');
78
78
  await waitFor(() => run("document.getElementById('agentCaptureFeedback').textContent.includes('操作未完成')"), 'partial failure rendered');
79
79
  assert(await run("document.getElementById('agentCaptureFeedback').classList.contains('issue')"));
80
80
  const logs = (await (await fetch(base + '/api/logs?event=integration.capture.failed')).json()).entries;
81
- assert(logs.length > 0 && logs[0].error.message.includes('valid JSON'));
81
+ assert(logs.some(entry => entry.error?.code === 'AGENT_CONFIG_INVALID'));
82
+ assert.equal(fs.readFileSync(configFile, 'utf8'), '{invalid JSON');
82
83
  fs.writeFileSync(configFile, JSON.stringify(config));
83
84
  await click('#closeSystem'); await click('#openSystem');
84
85
  await waitFor(() => run("document.querySelector('[data-agent-client=zcode][data-agent-switch=uninstall]') !== null"), 'switch repair succeeds');
@@ -104,8 +104,9 @@ function canConnect(port) {
104
104
  // --version
105
105
  const versionResult = run(['--version']);
106
106
  assert(versionResult.status === 0, `--version should exit 0, got ${versionResult.status}: ${versionResult.stderr}`);
107
- assert(versionResult.stdout.trim() === require(path.join(ROOT, 'package.json')).version,
108
- `--version output (${versionResult.stdout.trim()}) should match package.json`);
107
+ const versionFirstLine = versionResult.stdout.split('\n')[0].trim();
108
+ assert(versionFirstLine === `project-knowledge ${require(path.join(ROOT, 'package.json')).version}`,
109
+ `--version first line (${versionFirstLine}) should be "project-knowledge <package.json version>"; the remaining lines are the module inventory`);
109
110
 
110
111
  // --help mentions the new subcommands
111
112
  const helpResult = run(['--help']);
@@ -13,6 +13,7 @@ const ROOT = path.resolve(__dirname, '../..');
13
13
  const TEMP = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-capture-dedup-'));
14
14
  const HOME = path.join(TEMP, '用户 空格');
15
15
  const OLD = path.join(HOME, '.ai-coding-event-bridge');
16
+ const OLD_V5 = path.join(HOME, '.project-knowledge-v5/events');
16
17
  const CURRENT = path.join(HOME, '.project-knowledge/events');
17
18
  const options = { homeDir: HOME, bridgeHomeDir: CURRENT };
18
19
  const shim = home => path.join(home, 'bin/bridge-hook.cjs');
@@ -74,6 +75,45 @@ async function main() {
74
75
  assert.deepEqual(read(zcode).env, unrelated.env);
75
76
  assert.deepEqual(read(zcode).hooks.events.UserPromptSubmit[0].hooks, [third, zContext]);
76
77
 
78
+ // Renaming the default data directory leaves absolute hooks behind. The
79
+ // missing v5 shim must be retired even when the current hook already exists.
80
+ for (const client of ['claude', 'zcode']) {
81
+ const file = path.join(HOME, client, 'v5-migration.json');
82
+ const managed = client === 'zcode' ? processHook : cmd;
83
+ const eventMap = Object.fromEntries(events.map(event => [event, [
84
+ { matcher: '*', hooks: [managed(OLD_V5), third, managed(CURRENT), managed(customHome), lookalike] },
85
+ ]]));
86
+ write(file, { ...unrelated, hooks: client === 'zcode' ? { enabled: true, events: eventMap } : eventMap });
87
+ const migrated = manager(client === 'zcode' ? { zcodeConfigFile: file } : { claudeSettingsFile: file });
88
+ const status = () => client === 'zcode' ? migrated.statusCaptureZCode() : migrated.statusCaptureClaude();
89
+ const install = () => client === 'zcode' ? migrated.installCaptureZCode() : migrated.installCaptureClaude();
90
+ const original = fs.readFileSync(file, 'utf8');
91
+ assert(!fs.existsSync(shim(OLD_V5)), 'the retired v5 runtime is absent');
92
+ assert.equal((await status()).state, 'needs-repair', `${client}: stale v5 hooks cannot be reported healthy`);
93
+ assert.equal(fs.readFileSync(file, 'utf8'), original, 'migration status remains read-only');
94
+ const repaired = await install();
95
+ assert.equal(repaired.removedLegacy, 2);
96
+ assert.equal(repaired.removedDuplicates, 0);
97
+ const config = read(file), fixedEvents = client === 'zcode' ? config.hooks.events : config.hooks;
98
+ assert.deepEqual(config.env, unrelated.env);
99
+ for (const event of events) {
100
+ const hooks = fixedEvents[event].flatMap(group => group.hooks);
101
+ assert(!hooks.some(hook => JSON.stringify(hook) === JSON.stringify(managed(OLD_V5))));
102
+ assert.equal(hooks.filter(hook => JSON.stringify(hook) === JSON.stringify(managed(CURRENT))).length, 1);
103
+ for (const keep of [third, managed(customHome), lookalike]) assert(hooks.some(hook => JSON.stringify(hook) === JSON.stringify(keep)));
104
+ assert.equal(fixedEvents[event][0].matcher, '*');
105
+ }
106
+ assert.equal((await status()).state, 'installed');
107
+ const fixed = fs.readFileSync(file, 'utf8');
108
+ assert.equal((await install()).changed, false);
109
+ assert.equal(fs.readFileSync(file, 'utf8'), fixed, 'v5 migration is byte-idempotent');
110
+ }
111
+ assert.equal(bridgeBinding(['node', shim(OLD_V5)], options), 'legacy');
112
+ assert.equal(bridgeBinding(['node', shim(OLD_V5)], { ...options, bridgeHomeDir: OLD_V5 }), 'current', 'an explicitly selected v5 data directory remains current');
113
+ assert.equal(bridgeBinding(['node', shim(OLD_V5), '--custom-argument'], options), '');
114
+ assert.equal(bridgeBinding(['node', `${shim(OLD_V5)}.user-script`], options), '');
115
+ assert.equal(bridgeBinding(['node', shim(path.join(TEMP, 'another-user/.project-knowledge-v5/events'))], options), '', 'another account is not owned');
116
+
77
117
  write(claude, { hooks: Object.fromEntries(events.map(event => [event, [{ hooks: [cmd(OLD)] }]])) });
78
118
  const onlyLegacy = fs.readFileSync(claude, 'utf8');
79
119
  assert.throws(() => repairCaptureHooks(claude, 'claude', options), /入口未完整/);
@@ -135,7 +175,7 @@ async function main() {
135
175
  const captured = fs.readFileSync(journal, 'utf8').trim().split(/\r?\n/).map(line => JSON.parse(line));
136
176
  assert.deepEqual(captured.map(row => row.eventType), ['user_prompt', 'assistant_response']);
137
177
  assert(!fs.existsSync(obsoleteStore), 'the stale second directory is not recreated');
138
- write(zcode, { hooks: { enabled: true, events: Object.fromEntries(events.map(event => [event, [{ hooks: [processHook(OLD), processHook(CURRENT), processHook(CURRENT)] }]])) } });
178
+ write(zcode, { hooks: { enabled: true, events: Object.fromEntries(events.map(event => [event, [{ hooks: [processHook(OLD_V5), processHook(CURRENT), processHook(CURRENT)] }]])) } });
139
179
  await item.installCaptureZCode();
140
180
  for (const [event, payload] of [
141
181
  ['UserPromptSubmit', { prompt: 'isolated zcode dedup request' }],
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+ // `project-knowledge --version` is a one-shot inventory: the core version,
3
+ // the instance state, and one line per pinned runtime module with a live or
4
+ // installed version. Assertions keep the report complete even when no
5
+ // instance is running (CI).
6
+
7
+ const { spawnSync } = require('child_process');
8
+ const path = require('path');
9
+ const assert = require('assert/strict');
10
+
11
+ const result = spawnSync(process.execPath, [path.join(__dirname, '..', '..', 'bin', 'project-knowledge.js'), '--version'], { encoding: 'utf8', timeout: 30_000 });
12
+ assert.equal(result.status, 0, `--version exited ${result.status}: ${result.stderr}`);
13
+ const out = result.stdout;
14
+ assert.match(out, /^project-knowledge \d+\.\d+\.\d+/, 'core version line');
15
+ assert.match(out, /instance: (running at http|not running)/, 'instance line');
16
+ for (const label of ['Workbench (terminal)', 'vector-hub', 'event-bridge', 'knowledge-engine', 'workflow']) {
17
+ const line = out.split('\n').find(l => l.trim().startsWith(label));
18
+ assert.ok(line, `module line for ${label} present`);
19
+ assert.match(line, /\d+\.\d+\.\d+/, `${label} carries a version`);
20
+ assert.match(line, /\[(live|installed)\]/, `${label} carries a source tag`);
21
+ }
22
+ console.log('cli-version-report-test PASS');
@@ -172,6 +172,13 @@ async function main() {
172
172
  await rawLegacy.manager.uninstallCaptureCodex();
173
173
  assert.strictEqual(readNotify(rawLegacy.configFile), null, 'uninstall must not resurrect a retired Bridge home');
174
174
 
175
+ const v5Command = ['node', path.join(TEMP, 'legacy-v5-data-home', 'home', '.project-knowledge-v5', 'events', 'bin', 'bridge-hook.cjs')];
176
+ const rawV5 = fixture('legacy-v5-data-home', v5Command);
177
+ await assertInstallIdempotent(rawV5);
178
+ assert(!descendants(readNotify(rawV5.configFile)).some(command => command[1] === v5Command[1]), 'retire the old default data-directory hook rather than chaining its missing script');
179
+ await rawV5.manager.uninstallCaptureCodex();
180
+ assert.strictEqual(readNotify(rawV5.configFile), null, 'uninstall cannot resurrect the retired v5 data-directory hook');
181
+
175
182
  const nestedLegacyCommand = defaultLegacy('nested-legacy-default-home');
176
183
  const legacyRadar = [...radar, '--previous-notify', JSON.stringify(nestedLegacyCommand)];
177
184
  const nestedLegacy = fixture('nested-legacy-default-home', oldFanout('old-with-legacy-next', legacyRadar, staleBridge));
@@ -1,6 +1,14 @@
1
1
  'use strict';
2
- process.once('message', () => {
3
- const until = Date.now() + 1200;
2
+ process.once('message', ({ statusOptions }) => {
3
+ const send = summary => process.send({ ok: true, summary }, () => process.disconnect());
4
+ if (statusOptions.sharedOnly) return send({ bridge: { ok: true }, clients: [] });
5
+ const client = statusOptions.clients[0];
6
+ if (statusOptions.fixtureError) {
7
+ return process.send({ ok: false, code: 'INTEGRATION_STATUS_EXITED' }, () => process.disconnect());
8
+ }
9
+ const entry = { client, available: true, developmentCapture: { ok: true, state: 'installed', installed: true } };
10
+ if (statusOptions.fixturePartial) process.send({ kind: 'client-status', entry });
11
+ const until = Date.now() + (client === 'claude' ? (statusOptions.fixtureDelay ?? 1200) : 0);
4
12
  while (Date.now() < until) { /* Reproduce a blocking native status probe outside the HTTP process. */ }
5
- process.send({ ok: true, summary: { bridge: { ok: true }, clients: [{ client: 'claude', available: true }] } }, () => process.disconnect());
13
+ send({ clients: [{ ...entry, knowledgeIntegration: { ok: true, state: 'installed' } }] });
6
14
  });
@@ -75,7 +75,7 @@ function commitFile(repo, file, content, message = 'follow-up') {
75
75
  return repo.headCommit;
76
76
  }
77
77
 
78
- async function startHarness({ tag, evidenceDir, viewport = { width: 1600, height: 900 } } = {}) {
78
+ async function startHarness({ tag, evidenceDir, viewport = { width: 1600, height: 900 }, productRoot = ROOT, workflowEntry } = {}) {
79
79
  // Full driver isolation FIRST, before any product module load or fixture
80
80
  // directory: the environment is rebuilt from a system whitelist with every
81
81
  // product surface pointed at a per-run layout. Chrome is captured from the
@@ -125,10 +125,18 @@ async function startHarness({ tag, evidenceDir, viewport = { width: 1600, height
125
125
  const engineProxy = createUpstreamProxy({ target: engineUrl, token: engineToken, tag: 'engine' });
126
126
  await engineProxy.start();
127
127
 
128
+ let workflow;
129
+ let workflowUrl = 'http://127.0.0.1:1';
130
+ if (workflowEntry) {
131
+ const { createWorkflowServer } = require(workflowEntry);
132
+ workflow = createWorkflowServer({ dataDir: path.join(fixture, 'workflow-runtime') });
133
+ const bound = await workflow.listen(0);
134
+ workflowUrl = `http://127.0.0.1:${bound.port}`;
135
+ }
128
136
  const port = await freePort();
129
137
  const base = `http://127.0.0.1:${port}`;
130
138
  const server = spawnServer({
131
- root: ROOT,
139
+ root: productRoot,
132
140
  port,
133
141
  dataDir,
134
142
  tag: `parallel-memory-${tag}`,
@@ -140,6 +148,7 @@ async function startHarness({ tag, evidenceDir, viewport = { width: 1600, height
140
148
  KB_VECTORHUB_URL: vectorHub.url,
141
149
  KB_EVENTBRIDGE_URL: eventBridge.url,
142
150
  KB_KNOWLEDGE_ENGINE_URL: engineProxy.url,
151
+ KB_WORKFLOW_URL: workflowUrl,
143
152
  },
144
153
  });
145
154
 
@@ -192,6 +201,7 @@ async function startHarness({ tag, evidenceDir, viewport = { width: 1600, height
192
201
  await vectorHub.close();
193
202
  await eventBridge.close();
194
203
  await engine.close().catch(() => {});
204
+ await workflow?.close();
195
205
  fs.rmSync(fixture, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
196
206
  throw error;
197
207
  }
@@ -450,6 +460,7 @@ async function startHarness({ tag, evidenceDir, viewport = { width: 1600, height
450
460
  await eventBridge.close();
451
461
  await engine.close().catch(() => {});
452
462
  await engineVector.close().catch(() => {});
463
+ await workflow?.close();
453
464
  fs.rmSync(fixture, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
454
465
  };
455
466
 
@@ -0,0 +1,120 @@
1
+ // Run: node _site/_test/hook-relocation-rebind-test.js
2
+ // 数据目录迁移后的受管 Hook 重绑定:legacy 启动路径上,「已迁移」标记不再跳过
3
+ // 路径核对——Hook 实体必须绑定当前实例(--data-dir / --bridge-home / 触发脚本),
4
+ // 过期绑定被受控重写;已是当前的绑定不写文件;第三方或他人 Hook 报冲突并保留。
5
+
6
+ const assert = require('assert');
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+ const { spawnSync } = require('child_process');
11
+ const { migrateManagedHooks } = require('../lib/server-app');
12
+ const hookManager = require('../lib/hook-manager');
13
+
14
+ const ROOT = path.resolve(__dirname, '..', '..');
15
+ const TEMP = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-hook-reloc-'));
16
+ const repo = path.join(TEMP, '代码 仓库');
17
+ const TRIGGER = path.join(ROOT, '_site', 'scripts', 'hook-trigger.js');
18
+
19
+ function git(args) {
20
+ const result = spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8', windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } });
21
+ if (result.status !== 0) throw new Error(result.stderr || `git ${args.join(' ')} failed`);
22
+ return String(result.stdout || '').trim();
23
+ }
24
+
25
+ function makeRuntime(dataDir, analysisOwner = 'legacy') {
26
+ // Minimal runtime surface used by migrateManagedHooks.
27
+ const projects = new Map();
28
+ const states = new Map();
29
+ return {
30
+ analysisOwner,
31
+ registryStore: { listIds: () => [...projects.keys()] },
32
+ projectStore: {
33
+ readConfig: id => projects.get(id),
34
+ readState: id => states.get(id) || { hook: { migrationVersion: 0 } },
35
+ updateState: async (id, mutate) => {
36
+ const state = states.get(id) || { hook: { migrationVersion: 0 } };
37
+ mutate(state);
38
+ states.set(id, state);
39
+ },
40
+ register(id, config) { projects.set(id, config); },
41
+ states,
42
+ },
43
+ bridgeAdapter: {
44
+ hookBinding: () => ({ dataDir, bridgeHomeDir: path.join(dataDir, 'events'), bridgeModulePath: undefined }),
45
+ },
46
+ logger: { warn: async () => {}, info: async () => {} },
47
+ };
48
+ }
49
+
50
+ function hookText() {
51
+ const hookPath = hookManager.readHookStatus({ repoPath: repo }).hookPath;
52
+ return fs.readFileSync(hookPath, 'utf8');
53
+ }
54
+
55
+ (async () => {
56
+ fs.mkdirSync(repo, { recursive: true });
57
+ git(['init', '-q', '-b', 'main']);
58
+ git(['config', 'user.email', 'hook-reloc@example.local']);
59
+ git(['config', 'user.name', 'Hook Reloc Test']);
60
+ fs.writeFileSync(path.join(repo, 'README.md'), '# hook reloc\n');
61
+ git(['add', '.']);
62
+ git(['commit', '-q', '-m', 'initial']);
63
+ const projectId = 'project-hook-reloc';
64
+
65
+ // An older installation under data directory A already recorded migration v2.
66
+ const dataA = path.join(TEMP, '数据 A');
67
+ const dataB = path.join(TEMP, '数据 B');
68
+ hookManager.installHook({ repoPath: repo, projectId, triggerScriptPath: TRIGGER, dataDir: dataA, bridgeHomeDir: path.join(dataA, 'events') });
69
+ assert.ok(hookText().includes('数据 A'), 'the stale hook carries the old data directory');
70
+
71
+ const runtimeA = makeRuntime(dataA);
72
+ runtimeA.projectStore.register(projectId, { repoPath: repo });
73
+ runtimeA.projectStore.states.set(projectId, { hook: { migrationVersion: 2 } });
74
+
75
+ // Relocation: the current instance runs from directory B.
76
+ const runtimeB = makeRuntime(dataB);
77
+ runtimeB.projectStore.register(projectId, { repoPath: repo });
78
+ runtimeB.projectStore.states.set(projectId, { hook: { migrationVersion: 2 } });
79
+ const rebound = await migrateManagedHooks(runtimeB);
80
+ assert.strictEqual(rebound[0].ok, true, JSON.stringify(rebound[0]));
81
+ assert.strictEqual(rebound[0].reason, 'rebound-to-current-instance');
82
+ const afterRebind = hookText();
83
+ assert.ok(afterRebind.includes('数据 B'), 'the hook now binds the current data directory');
84
+ assert.ok(!afterRebind.includes('数据 A'), 'the stale binding is gone');
85
+
86
+ // A second pass with the same instance must be a no-op (no rewrite).
87
+ const again = await migrateManagedHooks(runtimeB);
88
+ assert.strictEqual(again[0].ok, true);
89
+ assert.strictEqual(again[0].reason, 'already-migrated');
90
+ assert.strictEqual(again[0].updated, false, 'an already-current binding is not rewritten');
91
+ assert.strictEqual(hookText(), afterRebind, 'the hook file is byte-identical');
92
+
93
+ // A third-party hook is reported as a conflict and preserved verbatim.
94
+ const hookPath = hookManager.readHookStatus({ repoPath: repo }).hookPath;
95
+ const thirdParty = '#!/bin/sh\necho third-party-marker\nexit 0\n';
96
+ fs.writeFileSync(hookPath, thirdParty);
97
+ const conflicted = await migrateManagedHooks(runtimeB);
98
+ assert.strictEqual(conflicted[0].ok, false);
99
+ assert.strictEqual(conflicted[0].status, 'conflict');
100
+ assert.strictEqual(fs.readFileSync(hookPath, 'utf8'), thirdParty, 'the third-party hook is preserved');
101
+ const conflictState = runtimeB.projectStore.states.get(projectId);
102
+ assert.strictEqual(conflictState.hook.lastConflict.code, 'HOOK_CONFLICT');
103
+
104
+ // A managed hook bound to ANOTHER project is likewise preserved (both the
105
+ // marker line and the command line identify the owner).
106
+ fs.writeFileSync(hookPath, afterRebind
107
+ .replace(`--project-id '${projectId}'`, `--project-id 'project-other'`)
108
+ .replace(`"projectId":"${projectId}"`, `"projectId":"project-other"`));
109
+ const wrongProject = await migrateManagedHooks(runtimeB);
110
+ assert.strictEqual(wrongProject[0].ok, false);
111
+ assert.strictEqual(wrongProject[0].status, 'conflict');
112
+ assert.ok(fs.readFileSync(hookPath, 'utf8').includes("project-other"), 'the other project\'s hook is preserved');
113
+
114
+ console.log('hook-relocation-rebind-test PASS');
115
+ })().catch(error => {
116
+ console.error(error.stack || error.message);
117
+ process.exitCode = 1;
118
+ }).finally(() => {
119
+ fs.rmSync(TEMP, { recursive: true, force: true });
120
+ });
@@ -98,7 +98,9 @@ const makeManager = ({ statusClients, onInstall }) => {
98
98
  markIntent(dir, 'codex', 'connected');
99
99
  manager.statusAll = async options => {
100
100
  assert.deepEqual(options.clients, ['codex']);
101
- return { clients: [{ client: 'codex', developmentCapture: { state: 'check-failed' } }] };
101
+ assert.equal(options.captureOnly, true, 'startup should only check the configuration it can repair');
102
+ assert.equal(options.includeShared, false, 'startup capture checks do not need a shared MCP probe');
103
+ return { clients: [{ client: 'codex', developmentCapture: { state: 'check-failed', installed: false } }] };
102
104
  };
103
105
  await repair.runOnce();
104
106
  assert.equal(manager.calls.installAll.length, 0, 'an unknown status must not be treated as an absent integration');
@@ -55,8 +55,9 @@ const intentPath = dataDir => path.join(dataDir, 'integration-intent.json');
55
55
  const midFlight = tmpDataDir();
56
56
  const unsettled = bootstrapIntent(midFlight, [
57
57
  { client: 'claude', developmentCapture: { state: 'checking', installed: undefined } },
58
- { client: 'codex', developmentCapture: {} },
58
+ { client: 'codex', developmentCapture: { state: 'check-failed', installed: false } },
59
59
  { client: 'zcode', developmentCapture: { state: 'installed', installed: true } },
60
+ { client: 'opencode', scan: { stale: true }, developmentCapture: { state: 'installed', installed: true } },
60
61
  ]);
61
62
  assert.deepEqual(unsettled, { schema: SCHEMA, clients: { zcode: 'connected' } }, 'checking/undefined entries must stay absent');
62
63
  const settled = bootstrapIntent(midFlight, [
@@ -66,7 +67,7 @@ const intentPath = dataDir => path.join(dataDir, 'integration-intent.json');
66
67
  assert.equal(settled.clients.claude, 'connected', 'later settled scan fills the skipped client correctly');
67
68
  assert.equal(settled.clients.codex, 'disconnected');
68
69
  }
69
- // C: summarizeClient covers all five states plus precedence rules.
70
+ // C: summarizeClient covers the status transitions and their precedence.
70
71
  {
71
72
  const failedRepair = { claude: { state: 'failed', at: new Date().toISOString(), error: 'boom' } };
72
73
  assert.equal(summarizeClient({ client: 'claude', available: true, developmentCapture: { state: 'checking' } }, null), 'checking');
@@ -75,6 +76,9 @@ const intentPath = dataDir => path.join(dataDir, 'integration-intent.json');
75
76
  assert.equal(summarizeClient({ client: 'claude', available: false, configFound: false, developmentCapture: {} }, null), 'not-detected');
76
77
  assert.equal(summarizeClient({ client: 'claude', available: false, configFound: true, developmentCapture: {} }, null), 'disconnected', 'configFound alone counts as detected');
77
78
  assert.equal(summarizeClient({ client: 'claude', available: true, developmentCapture: { installed: true } }, failedRepair), 'connected', 'installed outranks a failed repair');
79
+ assert.equal(summarizeClient({ client: 'claude', developmentCapture: { installed: true }, knowledgeIntegration: { state: 'checking' } }, null), 'connected', 'confirmed capture outranks a pending detailed check');
80
+ assert.equal(summarizeClient({ client: 'claude', available: false, configFound: false, developmentCapture: { state: 'check-failed' } }, null), 'check-failed', 'a failed scan cannot prove absence');
81
+ assert.equal(summarizeClient({ client: 'claude', available: true, developmentCapture: { state: 'check-failed' } }, failedRepair), 'check-failed', 'a new unknown status should offer a check, not an install');
78
82
  assert.equal(summarizeClient({ client: 'claude', available: true, developmentCapture: {} }, failedRepair), 'error');
79
83
  assert.equal(summarizeClient({ client: 'claude', available: true, developmentCapture: {} }, null), 'disconnected');
80
84
  }
@@ -376,8 +376,7 @@ async function testStatusScanDoesNotRespawn() {
376
376
  fs.writeFileSync(worker, `${'const fs = require(\'node:fs\');'}
377
377
  process.once('message', async input => {
378
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));
379
+ fs.appendFileSync(counter, (input.statusOptions.sharedOnly ? 'shared' : input.statusOptions.clients[0]) + '\\n');
381
380
  process.send({ ok: true, summary: { bridge: { ok: true }, clients: [{ client: input.statusOptions.clients?.[0] || 'claude', mcpStartup: { state: 'ready' } }] } }, () => process.disconnect());
382
381
  });
383
382
  `);
@@ -385,9 +384,10 @@ process.once('message', async input => {
385
384
  const options = { rootDir: ROOT, homeDir: TEMP, bridgeHomeDir: TEMP };
386
385
  await scan.read(options, { clients: ['claude'] }, { waitMs: 5000 });
387
386
  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');
387
+ const calls = () => fs.readFileSync(counter, 'utf8').trim().split(/\r?\n/).sort();
388
+ assert(calls().join(',') === 'claude,shared', 'cached reads reuse the client and shared results');
389
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');
390
+ assert(calls().join(',') === 'claude,claude,shared', 'a targeted refresh re-runs only the requested client');
391
391
  scan.close();
392
392
  }
393
393