@sanqianx/project-knowledge 5.1.4 → 5.1.6

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 (37) 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 +57 -7
  4. package/_site/_test/agent-capture-ui-test.js +6 -4
  5. package/_site/_test/fixtures/integration-busy-worker.cjs +11 -3
  6. package/_site/_test/helpers/parallel-memory-shell.js +13 -2
  7. package/_site/_test/hook-relocation-rebind-test.js +120 -0
  8. package/_site/_test/integration-auto-repair-test.js +3 -1
  9. package/_site/_test/integration-intent-test.js +6 -2
  10. package/_site/_test/integration-runtime-binding-test.js +4 -4
  11. package/_site/_test/integration-status-scan-test.js +138 -7
  12. package/_site/_test/legacy-relocation-recovery-test.js +258 -0
  13. package/_site/_test/parallel-retrieval-followup-corpus-test.js +6 -4
  14. package/_site/_test/project-team-ui-test.js +124 -0
  15. package/_site/_test/recovery-label-contract-test.js +45 -0
  16. package/_site/lib/capture-hook-config.js +16 -7
  17. package/_site/lib/claude-plugin-status.js +60 -0
  18. package/_site/lib/commit-prompt.js +205 -202
  19. package/_site/lib/commit-reconciler.js +551 -444
  20. package/_site/lib/contracts.js +1 -0
  21. package/_site/lib/evidence-bundle.js +32 -5
  22. package/_site/lib/integration-auto-repair.js +3 -2
  23. package/_site/lib/integration-installer.js +153 -71
  24. package/_site/lib/integration-intent.js +12 -5
  25. package/_site/lib/integration-status-scan.js +101 -41
  26. package/_site/lib/integration-status-worker.js +4 -2
  27. package/_site/lib/knowledge-promotion.js +547 -435
  28. package/_site/lib/scanner.js +5 -3
  29. package/_site/lib/server-app.js +34 -7
  30. package/_site/scripts/refresh-runtime-manifest.js +1 -1
  31. package/module-runtime-manifest.json +85 -85
  32. package/package.json +6 -6
  33. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  34. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  35. package/plugins/project-knowledge/.mcp.json +1 -1
  36. package/ui/product.css +1 -0
  37. package/ui/product.js +239 -49
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "project-knowledge",
12
- "version": "5.1.4",
12
+ "version": "5.1.6",
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.6] - 2026-11-20
4
+
5
+ - 知识引擎升级至 `0.3.3`。提交取证合并文件变更统计、限制重命名搜索,并流式生成可校验的补丁证据。60 秒内未生成补丁时,用 180 秒再尝试一次。活动详情显示 Git 失败原因、限时和已读取的字节数。
6
+ - 外部 Agent 面板复用缓存状态和已有卡片。缓存过期时只在后台检查基础采集;展开详情才检测该客户端的知识接入与 MCP,手动重新检测也只选择相应客户端。
7
+
8
+ ## [5.1.5] - 2026-11-20
9
+
10
+ - 外部 Agent 接入页并行检查 Claude Code、OpenCode、Codex 和 ZCode,逐项显示采集和开发前知识状态。Claude Code 的插件状态直接读取本地安装记录,避免反复启动原生 CLI。单个客户端的检查失败可单独刷新,自动修复只处理已确认损坏的采集配置。
11
+ - 维护任务从当前数据目录定位提交证据和检索快照,兼容旧格式任务及知识晋升恢复记录。移动数据目录后自动校正托管 Git Hook。活动记录区分证据缺失与完整性错误,并显示实际调度的重试状态。
12
+ - Workbench 重新定位旧会话的托管知识目录,Event Bridge 按当前托管目录解析默认事件账本,vector-hub 在知识目录迁移后更新项目的索引来源并拒绝冲突地址。
13
+ - 项目页可以创建、挂载和解除 AI 团队。建队向导支持选择成员、自定义职责和引用记忆组合,建队后可继续添加成员;解除挂载保留该项目的团队设置。
14
+ - 模块版本统一更新为 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`。
15
+
3
16
  ## [5.1.4] - 2026-11-19
4
17
 
5
18
  - 默认数据目录改为 `~/.project-knowledge`,仍可显式选择数据目录。重新接入 ZCode、Claude Code 或 Codex 时会清理指向旧默认目录 `~/.project-knowledge-v5` 的采集入口,避免旧脚本路径报错或重复采集。
@@ -34,29 +34,79 @@ 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(`(${function mockAgentStatus(fixture) {
58
+ const original = window.fetch;
59
+ window.__integrationRequests = [];
60
+ window.fetch = (input, init) => {
61
+ const url = new URL(String(input?.url || input), location.href);
62
+ if (url.pathname !== '/api/integrations/status') return original(input, init);
63
+ window.__integrationRequests.push([url.href, init?.method || 'GET']);
64
+ const client = url.searchParams.get('clients');
65
+ const clients = fixture.clients.filter(row => !client || row.client === client).map(row => {
66
+ if (url.searchParams.get('captureOnly') !== '1') return row;
67
+ const { knowledgeIntegration, automaticContext, mcpStartup, ...capture } = row;
68
+ return capture;
69
+ });
70
+ return Promise.resolve({ ok: true, json: async () => ({ ...fixture, clients }) });
71
+ };
72
+ }})(${payload})`);
49
73
  await click('#openSystem');
50
74
  await waitFor(() => run("document.querySelectorAll('#agentCaptureList .agent-capture-row').length === 4"), 'capture rows render');
75
+ assert.equal(await run("window.__integrationRequests.length"), 1);
76
+ assert.equal(await run("window.__integrationRequests[0][0].includes('captureOnly=1')"), true, 'opening the overview only checks capture');
77
+ assert.equal(await run("document.getElementById('agentCaptureList').textContent.includes('PROBE_TIMEOUT')"), false);
78
+ await run("window.__openCodeRow = document.querySelector('.agent-capture-row[data-agent-client=opencode]')");
79
+ await click('#closeSystem');
80
+ await click('#openSystem');
81
+ assert.equal(await run("window.__integrationRequests.length"), 1, 'a fresh reopen uses the snapshot without fetching');
82
+ assert.equal(await run("window.__openCodeRow === document.querySelector('.agent-capture-row[data-agent-client=opencode]')"), true);
83
+ await click('.agent-capture-row[data-agent-client=codex] summary');
84
+ await waitFor(() => run("document.getElementById('agentCaptureList').textContent.includes('PROBE_TIMEOUT')"), 'Codex details load on demand');
85
+ assert.equal(await run("window.__integrationRequests.length"), 2);
86
+ assert.equal(await run("window.__integrationRequests[1][0].includes('clients=codex') && !window.__integrationRequests[1][0].includes('captureOnly')"), true);
87
+ assert.equal(await run("document.querySelector('.agent-capture-row[data-agent-client=codex] details').open"), true);
88
+ assert.equal(await run("window.__openCodeRow === document.querySelector('.agent-capture-row[data-agent-client=opencode]')"), true, 'a targeted update keeps other cards');
51
89
  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');
90
+ const codexRowHtml = await run("document.querySelector('.agent-capture-row[data-agent-client=codex]').innerHTML");
91
+ assert(codexRowHtml.includes('&lt;img'), 'hostile mcpStartup detail must be HTML-escaped, got: ' + codexRowHtml.slice(0, 300));
92
+ assert(!codexRowHtml.includes('<img'), 'no raw hostile markup may reach the DOM');
55
93
  assert.equal(await run('window.__kbXssProbe'), undefined, 'the hostile onerror must never execute');
56
94
  const smalls = await run("[...document.querySelectorAll('#agentCaptureList small')].map(el => el.textContent).join('|')");
57
95
  assert(smalls.split('|').some(text => text.startsWith('MCP')), 'the MCP diagnostic is its own line item, got: ' + smalls);
96
+ const badges = await run("Object.fromEntries(Array.from(document.querySelectorAll('.agent-capture-row'), row => [row.dataset.agentClient, row.querySelector('.status').textContent]))");
97
+ assert.deepEqual(badges, { claude: '检测超时', codex: '已接入', zcode: '已接入', opencode: '未检测到' });
98
+ await run("(() => { const originalNow = Date.now; Date.now = () => originalNow() + 31_000; })()");
99
+ await click('#closeSystem');
100
+ await click('#openSystem');
101
+ await waitFor(() => run("window.__integrationRequests.length === 3"), 'an expired overview rechecks capture');
102
+ assert.equal(await run("window.__integrationRequests[2][0].includes('captureOnly=1')"), true);
103
+ assert.equal(await run("window.__openCodeRow === document.querySelector('.agent-capture-row[data-agent-client=opencode]')"), true, 'an unchanged card stays on the same DOM node');
104
+ await click('[data-agent-check="claude"]');
105
+ await waitFor(() => run("window.__integrationRequests.some(([url]) => url.includes('clients=claude') && url.includes('refresh=1'))"), 'single-client refresh request');
106
+ assert.equal(await run("window.__integrationRequests.length"), 4, 'manual recheck issues no follow-up request for all agents');
107
+ assert.equal(await run("window.__integrationRequests.every(([,method]) => method === 'GET')"), true, 'rechecking a timeout never installs or repairs an agent');
58
108
  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)');
109
+ console.log('agent-capture-mcp-ui-test PASS (cached reopen, stable rows, lazy MCP and targeted retry)');
60
110
  } finally {
61
111
  runtime.integrationStatusScan?.close();
62
112
  await browser?.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
@@ -70,17 +70,19 @@ 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 click('.agent-capture-row[data-agent-client=zcode] summary');
77
+ 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
78
  await click('[data-agent-client=zcode][data-agent-switch=install]');
78
79
  await waitFor(() => run("document.getElementById('agentCaptureFeedback').textContent.includes('操作未完成')"), 'partial failure rendered');
79
80
  assert(await run("document.getElementById('agentCaptureFeedback').classList.contains('issue')"));
80
81
  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'));
82
+ assert(logs.some(entry => entry.error?.code === 'AGENT_CONFIG_INVALID'));
83
+ assert.equal(fs.readFileSync(configFile, 'utf8'), '{invalid JSON');
82
84
  fs.writeFileSync(configFile, JSON.stringify(config));
83
- await click('#closeSystem'); await click('#openSystem');
85
+ await click('[data-agent-check=zcode]');
84
86
  await waitFor(() => run("document.querySelector('[data-agent-client=zcode][data-agent-switch=uninstall]') !== null"), 'switch repair succeeds');
85
87
  // Switch OFF: removal keeps third-party config and prior evidence.
86
88
  await click('[data-agent-client=zcode][data-agent-switch=uninstall]');
@@ -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
 
@@ -1,29 +1,160 @@
1
1
  'use strict';
2
2
  const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
3
5
  const path = require('node:path');
6
+ const { IntegrationManager } = require('../lib/integration-installer');
4
7
  const { IntegrationStatusScan } = require('../lib/integration-status-scan');
8
+ const { summarizeClient } = require('../lib/integration-intent');
9
+
10
+ async function testClaudeInventory() {
11
+ const rootDir = path.resolve(__dirname, '../..');
12
+ const { version } = require('../../package.json');
13
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-claude-status-'));
14
+ const configDir = path.join(temp, 'Claude config');
15
+ const commandDir = path.join(temp, 'test bin');
16
+ const userInstall = path.join(temp, 'installed-user');
17
+ const projectInstall = path.join(temp, 'installed-project');
18
+ const project = path.join(temp, 'project');
19
+ const registry = path.join(configDir, 'plugins', 'installed_plugins.json');
20
+ const settings = path.join(configDir, 'settings.json');
21
+ const pluginId = 'project-knowledge@project-knowledge';
22
+ const windows = process.platform === 'win32';
23
+ const command = path.join(commandDir, windows ? 'claude.cmd' : 'claude');
24
+ const cliMarker = path.join(commandDir, 'cli-invoked.txt');
25
+ const env = {
26
+ CLAUDE_CONFIG_DIR: configDir,
27
+ KB_DATA_DIR: path.join(temp, 'data'),
28
+ ...(windows ? { Path: '"' + commandDir + '"', PATHEXT: '.CMD' } : { PATH: commandDir }),
29
+ };
30
+ const write = (file, json) => {
31
+ fs.mkdirSync(path.dirname(file), { recursive: true });
32
+ fs.writeFileSync(file, JSON.stringify(json));
33
+ };
34
+ try {
35
+ fs.mkdirSync(commandDir, { recursive: true });
36
+ const fakeCli = windows ? '@echo attempted>"%~dp0cli-invoked.txt"\r\n@exit /b 1\r\n'
37
+ : '#!/bin/sh\nprintf attempted > ' + "'" + cliMarker.replace(/'/g, "'\\''") + "'\nexit 1\n";
38
+ fs.writeFileSync(command, fakeCli, { mode: 0o755 });
39
+ for (const installDir of [userInstall, projectInstall]) {
40
+ for (const file of ['hooks/claude.json', 'scripts/context-hook.cjs', 'scripts/mcp-launcher.cjs', '.mcp.json', '.claude-plugin/plugin.json']) {
41
+ const target = path.join(installDir, file);
42
+ fs.mkdirSync(path.dirname(target), { recursive: true });
43
+ fs.copyFileSync(path.join(rootDir, 'plugins', 'project-knowledge', file), target);
44
+ }
45
+ }
46
+ write(registry, { version: 2, plugins: { [pluginId]: [
47
+ { scope: 'user', version, installPath: userInstall },
48
+ { scope: 'project', projectPath: project, version, installPath: projectInstall },
49
+ ] } });
50
+ write(settings, { enabledPlugins: { [pluginId]: true } });
51
+ const launchers = [];
52
+ let nativeCalls = 0;
53
+ const manager = new IntegrationManager({
54
+ rootDir, homeDir: temp, localStatus: true,
55
+ env,
56
+ runner: () => { nativeCalls++; throw new Error('Native CLI must be idle during this status check.'); },
57
+ bridgeModule: { installers: { claudeCode: { statusClaudeCodeHook: async () => ({ installed: false }) } } },
58
+ mcpProbe: async info => { launchers.push(info.launcherPath); return { state: 'ready' }; },
59
+ });
60
+ const status = async cwd => (await manager.statusAll({ clients: ['claude'], cwd, includeShared: false })).clients[0];
61
+ const user = await status();
62
+ assert.equal(user.available, true, 'the background check locates the executable on PATH');
63
+ assert.equal(user.configFound, true, 'the configured Claude home supplies both the inventory and settings');
64
+ assert.equal(user.knowledgeIntegration.state, 'installed');
65
+ assert.equal(user.automaticContext.configured, true, 'local inventory still verifies the actual installed context files');
66
+ assert.equal(user.mcpStartup.state, 'ready');
67
+ assert.equal(launchers.at(-1), path.join(userInstall, 'scripts', 'mcp-launcher.cjs'));
68
+
69
+ const productionWorker = new IntegrationStatusScan();
70
+ try {
71
+ const summary = await productionWorker.read({ rootDir, homeDir: temp, env, bridgeHomeDir: path.join(temp, 'events') }, { clients: ['claude'] }, { waitMs: 5000 });
72
+ assert.equal(summary.clients[0].scan.state, 'ready', 'the production worker must return the installed plugin');
73
+ assert.equal(summary.clients[0].knowledgeIntegration.state, 'installed');
74
+ assert.equal(summary.clients[0].automaticContext.configured, true);
75
+ assert.equal(fs.existsSync(cliMarker), false, 'even the production worker never starts the native Claude CLI');
76
+ } finally { productionWorker.close(); }
77
+
78
+ await status(project);
79
+ assert.equal(launchers.at(-1), path.join(projectInstall, 'scripts', 'mcp-launcher.cjs'), 'the current project registration takes precedence');
80
+ write(path.join(project, '.claude', 'settings.local.json'), { enabledPlugins: { [pluginId]: false } });
81
+ const disabled = await status(project);
82
+ assert.equal(disabled.knowledgeIntegration.state, 'disabled');
83
+ assert.equal(disabled.automaticContext.configured, false);
84
+ assert.equal(launchers.length, 2, 'disabled plugins are not launched');
85
+ write(registry, { version: 999, plugins: {} });
86
+ const unknown = await status(project);
87
+ assert.equal(unknown.knowledgeIntegration.state, 'check-failed');
88
+ assert.equal(unknown.knowledgeIntegration.error.code, 'CLAUDE_PLUGIN_INDEX_UNSUPPORTED');
89
+ assert.equal(nativeCalls, 0, 'healthy and unreadable inventories never cold-start Claude for web status');
90
+ } finally {
91
+ const resolved = fs.realpathSync(temp);
92
+ assert.equal(path.dirname(resolved), fs.realpathSync(os.tmpdir()));
93
+ assert.ok(path.basename(resolved).startsWith('kb-claude-status-'));
94
+ fs.rmSync(resolved, { recursive: true, force: true });
95
+ }
96
+ }
97
+
5
98
  async function main() {
6
- const scan = new IntegrationStatusScan({ workerFile: path.join(__dirname, 'fixtures/integration-busy-worker.cjs'), timeoutMs: 5000 });
99
+ await testClaudeInventory();
100
+ const workerFile = path.join(__dirname, 'fixtures/integration-busy-worker.cjs');
101
+ const managerOptions = { rootDir: path.resolve(__dirname, '../..') };
102
+ const scan = new IntegrationStatusScan({ workerFile, timeoutMs: 5000 });
7
103
  try {
8
104
  const before = Date.now();
9
105
  const first = await scan.read({ rootDir: path.resolve(__dirname, '../..') }, { clients: ['claude'] }, { waitMs: 50 });
10
106
  assert.equal(first.scan.state, 'checking'); assert.ok(Date.now() - before < 500);
11
107
  const again = await scan.read({ rootDir: path.resolve(__dirname, '../..') }, { clients: ['claude'] }, { waitMs: 10 });
12
- assert.equal(first.scan.generation, again.scan.generation); assert.equal(scan.children.size, 1);
108
+ assert.equal(first.scan.generation, again.scan.generation);
109
+ assert.equal(scan.entries.size, 2, 'client and shared status have separate cached jobs');
13
110
  let ticked = false; await new Promise(resolve => setTimeout(() => { ticked = true; resolve(); }, 20));
14
111
  assert.equal(ticked, true, 'a blocked probe cannot freeze the HTTP event loop');
15
- await new Promise(resolve => setTimeout(resolve, 1500));
16
- const ready = await scan.read({ rootDir: path.resolve(__dirname, '../..') }, { clients: ['claude'] });
112
+ const ready = await scan.read(managerOptions, { clients: ['claude'] }, { waitMs: 4500 });
17
113
  assert.equal(ready.scan.state, 'ready'); assert.equal(ready.clients[0].available, true);
114
+ const stale = await scan.read(managerOptions, { clients: ['claude'], fixtureError: true }, { force: true, waitMs: 2000 });
115
+ assert.equal(stale.clients[0].scan.error.code, 'INTEGRATION_STATUS_EXITED');
116
+ assert.equal(stale.clients[0].scan.stale, true);
117
+ assert.equal(stale.clients[0].scan.checkedAt, ready.clients[0].scan.checkedAt);
118
+ assert.equal(summarizeClient(stale.clients[0]), 'connected');
119
+ scan.invalidate(['claude']);
120
+ const invalidated = await scan.read(managerOptions, { clients: ['claude'], fixtureError: true }, { waitMs: 2000 });
121
+ assert.equal(summarizeClient(invalidated.clients[0]), 'check-failed', 'a superseded configuration cannot pass a later status check');
18
122
  console.log('Isolated status scan, coalescing and nonblocking snapshot passed.');
19
123
  } finally { scan.close(); }
20
- const logs = [], timed = new IntegrationStatusScan({ workerFile: path.join(__dirname, 'fixtures/integration-busy-worker.cjs'), timeoutMs: 100 });
124
+ const logs = [], timed = new IntegrationStatusScan({ workerFile, timeoutMs: 100 });
21
125
  try {
22
126
  const result = await timed.read({ rootDir: path.resolve(__dirname, '../..'), operationId: 'status-timeout-test', logger: { warn: (...args) => logs.push(args) } }, { clients: ['claude'] }, { waitMs: 500 });
23
127
  assert.equal(result.error.code, 'INTEGRATION_STATUS_TIMEOUT');
24
128
  assert.equal(result.clients[0].automaticContext.state, 'check-failed');
25
- assert.equal(logs[0][0], 'integration.status.timeout');
26
- assert.equal(logs[0][2].operationId, 'status-timeout-test');
129
+ assert.equal(summarizeClient(result.clients[0]), 'check-failed');
130
+ const timeout = logs.find(event => event[2].context.clients.includes('claude'));
131
+ assert.equal(timeout[0], 'integration.status.timeout');
132
+ assert.equal(timeout[2].operationId, 'status-timeout-test');
27
133
  } finally { timed.close(); }
134
+
135
+ const independent = new IntegrationStatusScan({ workerFile, timeoutMs: 2500 });
136
+ try {
137
+ const options = { fixtureDelay: 5000, fixturePartial: true };
138
+ let partial;
139
+ for (let attempt = 0; attempt < 4; attempt++) {
140
+ partial = await independent.read(managerOptions, options, { waitMs: 500 });
141
+ if (partial.clients.filter(row => row.client !== 'claude' && row.scan.state === 'ready').length === 3
142
+ && partial.clients.find(row => row.client === 'claude').developmentCapture.installed === true) break;
143
+ }
144
+ assert.equal(partial.scan.state, 'refreshing');
145
+ assert.equal(partial.clients.find(row => row.client === 'claude').scan.state, 'refreshing');
146
+ assert.equal(partial.clients.filter(row => row.client !== 'claude' && row.scan.state === 'ready').length, 3);
147
+ const done = await independent.read(managerOptions, options, { waitMs: 3000 });
148
+ const claude = done.clients.find(row => row.client === 'claude');
149
+ assert.equal(claude.scan.error.code, 'INTEGRATION_STATUS_TIMEOUT');
150
+ assert.equal(claude.developmentCapture.installed, true, 'the verified capture result survives a detailed probe timing out');
151
+ assert.equal(claude.knowledgeIntegration.state, 'check-failed');
152
+ assert.ok(done.clients.filter(row => row.client !== 'claude').every(row => row.scan.state === 'ready' && !row.scan.error));
153
+ const sharedGeneration = done.scan.generation;
154
+ const recheck = await independent.read(managerOptions, { clients: ['claude'], fixtureDelay: 0 }, { force: true, waitMs: 2000 });
155
+ assert.ok(recheck.scan.generation > sharedGeneration);
156
+ assert.equal(recheck.clients[0].knowledgeIntegration.state, 'installed');
157
+ console.log('Isolated client timeout, preserved partial capture and single-client refresh passed.');
158
+ } finally { independent.close(); }
28
159
  }
29
160
  main().catch(error => { console.error(error); process.exitCode = 1; });