@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
@@ -69,6 +69,7 @@ const ERROR_CODES = Object.freeze([
69
69
  'LOGGER_UNAVAILABLE',
70
70
  'LOG_CURSOR_EXPIRED',
71
71
  'EVIDENCE_INTEGRITY_FAILED',
72
+ 'EVIDENCE_MISSING',
72
73
  'AI_PROFILE_REQUIRED',
73
74
  'KNOWLEDGE_WRITE_MOVED',
74
75
  'MODEL_CONFIG_MOVED',
@@ -74,6 +74,16 @@ function readManifestStrict(manifestPath, atomic = AtomicFile) {
74
74
  });
75
75
  }
76
76
 
77
+ // A missing file is a distinct, non-retryable category: after a data-directory
78
+ // relocation the frozen evidence must be re-derived from the current layout,
79
+ // never re-read from a stale absolute path, and never auto-retried in a loop.
80
+ function missingEvidence(resource, evidenceRoot) {
81
+ return new DomainError('EVIDENCE_MISSING', `Frozen patch evidence is missing: ${resource}.`, {
82
+ status: 500,
83
+ details: { resource, evidenceRoot },
84
+ });
85
+ }
86
+
77
87
  function safeChunkPath(evidenceRoot, relativePath) {
78
88
  if (!/^patches\/\d{6}\.patch$/.test(String(relativePath || ''))) {
79
89
  throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Patch evidence chunk path is invalid.', { status: 500 });
@@ -151,7 +161,7 @@ class ExactPatchEvidenceBundle {
151
161
  try {
152
162
  return this.verifyUnchecked(evidenceRoot, expected);
153
163
  } catch (error) {
154
- if (error && error.code === 'EVIDENCE_INTEGRITY_FAILED') throw error;
164
+ if (error && ['EVIDENCE_INTEGRITY_FAILED', 'EVIDENCE_MISSING', 'PATH_OUTSIDE_ROOT'].includes(error.code)) throw error;
155
165
  throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Patch evidence bundle could not be read or verified.', {
156
166
  status: 500,
157
167
  cause: error,
@@ -162,8 +172,12 @@ class ExactPatchEvidenceBundle {
162
172
 
163
173
  verifyUnchecked(evidenceRoot, expected = {}) {
164
174
  const root = path.resolve(evidenceRoot);
165
- const manifest = readManifestStrict(path.join(root, 'patch-manifest.json'), this.atomic);
166
- const commitEvidence = this.atomic.readJsonStrict(path.join(root, 'commit.json'), {
175
+ const manifestPath = path.join(root, 'patch-manifest.json');
176
+ if (!fs.existsSync(manifestPath)) throw missingEvidence('patch-manifest.json', root);
177
+ const manifest = readManifestStrict(manifestPath, this.atomic);
178
+ const commitPath = path.join(root, 'commit.json');
179
+ if (!fs.existsSync(commitPath)) throw missingEvidence('commit.json', root);
180
+ const commitEvidence = this.atomic.readJsonStrict(commitPath, {
167
181
  category: 'commit-evidence-bundle',
168
182
  validate: value => {
169
183
  if (!value || value.schema !== COMMIT_EVIDENCE_SCHEMA || value.fullPatchHash !== manifest.fullPatchHash
@@ -180,6 +194,15 @@ class ExactPatchEvidenceBundle {
180
194
  if (expected.expectedBytes != null && manifest.totalBytes !== expected.expectedBytes) {
181
195
  throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Frozen patch evidence byte count does not match the claim.', { status: 500 });
182
196
  }
197
+ if (expected.expectedManifestHash && manifest.manifestHash !== expected.expectedManifestHash) {
198
+ throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Frozen patch manifest hash does not match the claim.', { status: 500 });
199
+ }
200
+ if (expected.expectedCommitSha && String(commitEvidence.commit.commitSha || '').toLowerCase() !== String(expected.expectedCommitSha).toLowerCase()) {
201
+ throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Frozen commit evidence belongs to a different commit than the claim.', {
202
+ status: 500,
203
+ details: { resource: 'commit.json', expectedCommitSha: expected.expectedCommitSha, actualCommitSha: commitEvidence.commit.commitSha || null },
204
+ });
205
+ }
183
206
  const aggregate = crypto.createHash('sha256');
184
207
  let bytes = 0;
185
208
  manifest.chunks.forEach((chunk, index) => {
@@ -187,12 +210,16 @@ class ExactPatchEvidenceBundle {
187
210
  throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Patch evidence chunk order or metadata is invalid.', { status: 500 });
188
211
  }
189
212
  const filePath = safeChunkPath(root, chunk.path);
190
- if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile() || fs.lstatSync(filePath).isSymbolicLink()) {
213
+ if (!fs.existsSync(filePath)) throw missingEvidence(chunk.path, root);
214
+ if (!fs.statSync(filePath).isFile() || fs.lstatSync(filePath).isSymbolicLink()) {
191
215
  throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Patch evidence chunk is missing or unsafe.', { status: 500 });
192
216
  }
193
217
  const value = fs.readFileSync(filePath);
194
218
  if (value.length !== chunk.bytes || hashBuffer(value) !== chunk.sha256) {
195
- throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Patch evidence chunk failed integrity validation.', { status: 500 });
219
+ throw new DomainError('EVIDENCE_INTEGRITY_FAILED', 'Patch evidence chunk failed integrity validation.', {
220
+ status: 500,
221
+ details: { resource: chunk.path },
222
+ });
196
223
  }
197
224
  aggregate.update(value);
198
225
  bytes += value.length;
@@ -46,10 +46,11 @@ class IntegrationAutoRepair {
46
46
  if (!intent) return this.status();
47
47
  const clients = Object.entries(intent.clients).filter(([, state]) => state === 'connected').map(([client]) => client);
48
48
  if (!clients.length) return this.status();
49
- const status = await this.createManager().statusAll({ clients });
49
+ const status = await this.createManager().statusAll({ clients, captureOnly: true, includeShared: false });
50
50
  for (const entry of status?.clients || []) {
51
51
  if (readIntent(this.dataDir)?.clients[entry.client] !== 'connected') continue;
52
- if (entry.developmentCapture?.installed !== false) continue;
52
+ const capture = entry.developmentCapture;
53
+ if (capture?.installed !== false || capture.ok === false || ['checking', 'check-failed', 'failed', 'conflict'].includes(capture.state)) continue;
53
54
  if (this.attempted.has(entry.client)) continue;
54
55
  await this._attempt(entry.client);
55
56
  }
@@ -10,6 +10,7 @@ const packageInfo = require('../../package.json');
10
10
  const { resolveDataDirPath } = require('./data-dir');
11
11
  const { planNotify, writeNotify } = require('./codex-notify-config');
12
12
  const { planCaptureHooks, repairCaptureHooks, removeCaptureHooks } = require('./capture-hook-config');
13
+ const { readClaudePluginStatus } = require('./claude-plugin-status');
13
14
  const { writeJsonAtomic } = require('./atomic-file');
14
15
 
15
16
  // Fail-open module resolution: a missing/unloadable Bridge package must
@@ -23,6 +24,7 @@ try {
23
24
 
24
25
  const INTEGRATION_NAME = 'project-knowledge';
25
26
  const MARKETPLACE_NAME = 'project-knowledge';
27
+ const PLUGIN_ID = `${INTEGRATION_NAME}@${MARKETPLACE_NAME}`;
26
28
  const DEFAULT_MARKETPLACE_SOURCE = 'SanQianX/project-knowledge-base';
27
29
  const INTEGRATION_RUNTIME_SCHEMA = 'project-knowledge/integration-runtime/v1';
28
30
  const MCP_LAUNCHER_ERROR_SCHEMA = 'project-knowledge/mcp-launcher-error/v1';
@@ -103,13 +105,38 @@ function defaultCommandResolver(name, env = process.env) {
103
105
  return candidates[0] || '';
104
106
  }
105
107
 
108
+ function statusCommandResolver(name, env) {
109
+ const windows = process.platform === 'win32';
110
+ const envValue = key => windows ? env[Object.keys(env).find(name => name.toUpperCase() === key)] : env[key];
111
+ const extensions = windows
112
+ ? (envValue('PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';').filter(ext => /^\.[a-z0-9]+$/i.test(ext))
113
+ : [''];
114
+ let lookupError;
115
+ for (const entry of (envValue('PATH') || '').split(path.delimiter)) {
116
+ const directory = windows ? entry.trim().replace(/^"(.*)"$/, '$1') : entry;
117
+ if (!directory) continue;
118
+ for (const extension of extensions) {
119
+ const candidate = path.resolve(directory, name + extension);
120
+ try {
121
+ if (!fs.statSync(candidate).isFile()) continue;
122
+ if (!windows) fs.accessSync(candidate, fs.constants.X_OK);
123
+ return candidate;
124
+ } catch (error) {
125
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) lookupError = error;
126
+ }
127
+ }
128
+ }
129
+ if (lookupError) throw lookupError;
130
+ return '';
131
+ }
132
+
106
133
  function defaultRunner(command, args, options = {}) {
107
134
  return crossSpawn.sync(command, args, {
108
135
  encoding: 'utf8',
109
136
  windowsHide: true,
110
137
  env: options.env || process.env,
111
138
  cwd: options.cwd,
112
- timeout: options.timeout || (process.env.KB_INTEGRATION_STATUS_WORKER === '1' ? 5000 : 120_000),
139
+ timeout: options.timeout || (process.env.KB_INTEGRATION_STATUS_WORKER === '1' ? 12_000 : 120_000),
113
140
  });
114
141
  }
115
142
 
@@ -227,7 +254,9 @@ class IntegrationManager {
227
254
  this.codexMarketplaceAddSource = options.codexMarketplaceSource || options.marketplaceSource || this.rootDir;
228
255
  this.explicitCodexMarketplace = Boolean(options.codexMarketplaceSource || options.marketplaceSource);
229
256
  this.runner = options.runner || defaultRunner;
230
- this.commandResolver = options.commandResolver || defaultCommandResolver;
257
+ this.localStatus = options.localStatus === true;
258
+ this.commandResolver = options.commandResolver || (this.localStatus ? statusCommandResolver : defaultCommandResolver);
259
+ this.statusCommands = this.localStatus ? new Map() : null;
231
260
  this.codexHookProbe = options.codexHookProbe || require('./codex-context-status').readCodexHooks;
232
261
  this.mcpProbe = options.mcpProbe || null;
233
262
  this.dryRun = Boolean(options.dryRun);
@@ -239,7 +268,8 @@ class IntegrationManager {
239
268
  this.bridgeHomeDir = options.bridgeHomeDir
240
269
  || this.env.AI_CODING_EVENT_BRIDGE_HOME
241
270
  || path.join(resolveDataDirPath({ dataDir: this.env.KB_DATA_DIR || '', homeDir: this.homeDir }), 'events');
242
- this.claudeSettingsFile = options.claudeSettingsFile || path.join(this.homeDir, '.claude', 'settings.json');
271
+ this.claudeConfigDir = this.env.CLAUDE_CONFIG_DIR || path.join(this.homeDir, '.claude');
272
+ this.claudeSettingsFile = options.claudeSettingsFile || path.join(this.claudeConfigDir, 'settings.json');
243
273
  this.codexConfigFile = options.codexConfigFile || path.join(this.homeDir, '.codex', 'config.toml');
244
274
  this.openCodePluginsDir = options.openCodePluginsDir || path.join(openCodeConfigDir(this.homeDir, this.env), 'plugin');
245
275
  this.zcodeConfigFile = options.zcodeConfigFile || path.join(this.homeDir, '.zcode', 'cli', 'config.json');
@@ -304,6 +334,10 @@ class IntegrationManager {
304
334
  return { ok, ...result, ...(!ok ? { error: { code: 'CAPTURE_CONFLICT', message: result.detail } } : {}) };
305
335
  } catch (error) {
306
336
  this.log('error', 'integration.capture.failed', 'Agent 采集接线操作失败。', { operationId: this.operationId, durationMs: Date.now() - startedAt, error, context });
337
+ if (operation === 'status' && error.code === 'AGENT_CONFIG_INVALID') {
338
+ return { ok: false, state: 'conflict', conflict: true, detail: error.message, error: { code: error.code } };
339
+ }
340
+ if (operation === 'status') return { ok: false, state: 'check-failed', detail: '无法核实会话采集配置。', error: { code: error.code || 'CAPTURE_STATUS_FAILED' } };
307
341
  return { ok: false, state: 'failed', installed: false, detail: error.message, error: { code: error.code || 'CAPTURE_FAILED', message: error.message } };
308
342
  }
309
343
  }
@@ -322,8 +356,8 @@ class IntegrationManager {
322
356
  }
323
357
 
324
358
  async statusCaptureZCode() {
325
- const status = await this.bridge.installers.zcode.statusZcodeHook(this._captureInstallerOptions('zcode'));
326
359
  const plan = planCaptureHooks(this.zcodeConfigFile, 'zcode', this);
360
+ const status = await this.bridge.installers.zcode.statusZcodeHook(this._captureInstallerOptions('zcode'));
327
361
  if (plan.repairNeeded || status.installed && !fs.existsSync(path.join(this.bridgeHomeDir, 'bin', 'bridge-hook.cjs'))) return { state: 'needs-repair', installed: false, conflict: false, repairNeeded: true, detail: '检测到重复、旧接线或缺失的 Bridge 入口,请执行接入/修复。' };
328
362
  return { state: status.installed ? 'installed' : 'not-installed', installed: status.installed, conflict: false, detail: status.installed ? '已配置用户输入与回答采集;请重新打开 ZCode 会话。' : 'ZCode 会话采集尚未接入。' };
329
363
  }
@@ -348,8 +382,8 @@ class IntegrationManager {
348
382
  }
349
383
 
350
384
  async statusCaptureClaude() {
351
- const status = await this.bridge.installers.claudeCode.statusClaudeCodeHook(this._captureInstallerOptions());
352
385
  const plan = planCaptureHooks(this.claudeSettingsFile, 'claude', this);
386
+ const status = await this.bridge.installers.claudeCode.statusClaudeCodeHook(this._captureInstallerOptions());
353
387
  if (plan.repairNeeded || status.installed && !fs.existsSync(path.join(this.bridgeHomeDir, 'bin', 'bridge-hook.cjs'))) return { state: 'needs-repair', installed: false, conflict: false, repairNeeded: true, detail: '检测到重复、旧接线或缺失的 Bridge 入口,请执行接入/修复。' };
354
388
  return {
355
389
  state: status.installed ? 'installed' : 'not-installed',
@@ -446,9 +480,13 @@ class IntegrationManager {
446
480
  executable(client) {
447
481
  const name = client === 'claude' ? 'claude' : client;
448
482
  if (this.dryRun) return process.platform === 'win32' ? `${name}.cmd` : name;
449
- const command = this.commandResolver(name, this.env);
450
- if (command || client !== 'zcode' || this.commandResolver !== defaultCommandResolver) return command;
451
- try { return require('claude-ai-workbench/packages/server/lib/drivers/zcode-driver').discoverZCodeCli({ env: this.env })?.path || ''; } catch { return ''; }
483
+ if (this.statusCommands?.has(client)) return this.statusCommands.get(client);
484
+ let command = this.commandResolver(name, this.env);
485
+ if (!command && client === 'zcode' && [defaultCommandResolver, statusCommandResolver].includes(this.commandResolver)) {
486
+ try { command = require('claude-ai-workbench/packages/server/lib/drivers/zcode-driver').discoverZCodeCli({ env: this.env })?.path || ''; } catch { /* keep the PATH result */ }
487
+ }
488
+ this.statusCommands?.set(client, command);
489
+ return command;
452
490
  }
453
491
 
454
492
  detectClients() {
@@ -629,7 +667,9 @@ class IntegrationManager {
629
667
  const command = this.executable(client);
630
668
  this.planned.push({ command: command || client, args: [...args] });
631
669
  const argsHash = `sha256:${crypto.createHash('sha256').update(JSON.stringify(args), 'utf8').digest('hex')}`;
632
- this.log('info', 'integration.command_started', 'Integration CLI command started.', { context: { client, argumentCount: args.length, argsHash, dryRun: this.dryRun } });
670
+ const resolvedAt = Date.now();
671
+ const resolveMs = resolvedAt - startedAt;
672
+ this.log('info', 'integration.command_started', 'Integration CLI command started.', { context: { client, argumentCount: args.length, argsHash, dryRun: this.dryRun, resolveMs } });
633
673
  if (this.dryRun) {
634
674
  this.log('info', 'integration.command_completed', 'Integration CLI command completed.', { durationMs: Date.now() - startedAt, context: { client, status: 0, argsHash, dryRun: true } });
635
675
  return { status: 0, stdout: '', stderr: '' };
@@ -643,8 +683,9 @@ class IntegrationManager {
643
683
  cwd: options.cwd || this.rootDir,
644
684
  timeout: options.timeout,
645
685
  });
686
+ const commandMs = Date.now() - resolvedAt;
646
687
  if (result.error) {
647
- this.log('error', 'integration.command_failed', 'Integration CLI command failed.', { durationMs: Date.now() - startedAt, error: Object.assign(new Error('Integration CLI command failed.'), { code: result.error.code || 'INTEGRATION_COMMAND_FAILED' }), context: { client, argsHash } });
688
+ this.log('error', 'integration.command_failed', 'Integration CLI command failed.', { durationMs: Date.now() - startedAt, error: Object.assign(new Error('Integration CLI command failed.'), { code: result.error.code || 'INTEGRATION_COMMAND_FAILED' }), context: { client, argsHash, resolveMs, commandMs } });
648
689
  throw result.error;
649
690
  }
650
691
  const localRefFailure = client === 'codex' && String(result.stderr || '').trim() === 'Error: --ref is only supported for git marketplace sources';
@@ -661,7 +702,7 @@ class IntegrationManager {
661
702
  });
662
703
  this.log(completed ? 'info' : 'warn', completed ? 'integration.command_completed' : 'integration.command_failed', completed ? 'Integration CLI command completed.' : 'Integration CLI command returned a failure.', {
663
704
  durationMs: Date.now() - startedAt, error: safeError,
664
- context: { client, status: result.status, argsHash },
705
+ context: { client, status: result.status, argsHash, resolveMs, commandMs },
665
706
  });
666
707
  return result;
667
708
  }
@@ -680,9 +721,12 @@ class IntegrationManager {
680
721
  return Array.isArray(marketplaces) && marketplaces.some(item => item.name === MARKETPLACE_NAME);
681
722
  }
682
723
 
683
- codexPlugin() {
724
+ codexPlugin(strict = false) {
684
725
  const result = this.execute('codex', ['plugin', 'list', '--json'], { allowFailure: true });
685
726
  const data = parseJson(result.stdout, {});
727
+ if (strict && (result.status !== 0 || !Array.isArray(data?.installed))) {
728
+ throw Object.assign(new Error('Could not verify the Codex plugin inventory.'), { code: 'CODEX_PLUGIN_LIST_FAILED' });
729
+ }
686
730
  return Array.isArray(data?.installed)
687
731
  ? data.installed.find(item => item.pluginId === `${INTEGRATION_NAME}@${MARKETPLACE_NAME}`)
688
732
  : undefined;
@@ -720,7 +764,7 @@ class IntegrationManager {
720
764
  if (!this.dryRun && this.claudeMarketplaceExists()) {
721
765
  if (this.explicitMarketplace) return;
722
766
  let source;
723
- try { source = JSON.parse(fs.readFileSync(path.join(this.homeDir, '.claude/plugins/known_marketplaces.json'), 'utf8'))[MARKETPLACE_NAME]?.source; } catch {}
767
+ try { source = JSON.parse(fs.readFileSync(path.join(this.claudeConfigDir, 'plugins', 'known_marketplaces.json'), 'utf8'))[MARKETPLACE_NAME]?.source; } catch {}
724
768
  const directory = source?.path || source?.directory;
725
769
  if (directory && path.resolve(directory).toLowerCase() === path.resolve(this.rootDir).toLowerCase()) return;
726
770
  const remote = source?.repo === DEFAULT_MARKETPLACE_SOURCE || /^https:\/\/github\.com\/SanQianX\/project-knowledge-base(?:\.git)?\/?$/i.test(source?.url || '');
@@ -827,7 +871,10 @@ class IntegrationManager {
827
871
  statusClaude() {
828
872
  const command = this.executable('claude');
829
873
  if (!command) return { state: 'unavailable', installed: false, detail: 'Claude Code CLI not found' };
830
- const plugin = this.claudePlugin();
874
+ return this.claudeKnowledgeStatus(this.claudePlugin());
875
+ }
876
+
877
+ claudeKnowledgeStatus(plugin) {
831
878
  return {
832
879
  state: plugin?.enabled === false ? 'disabled' : plugin && plugin.version !== this.version ? 'needs-update' : plugin ? 'installed' : 'not-installed',
833
880
  installed: Boolean(plugin),
@@ -908,7 +955,7 @@ class IntegrationManager {
908
955
  statusCodex() {
909
956
  const command = this.executable('codex');
910
957
  if (!command) return { state: 'unavailable', installed: false, detail: 'Codex CLI not found' };
911
- const plugin = this.codexPlugin();
958
+ const plugin = this.codexPlugin(this.localStatus);
912
959
  return {
913
960
  state: plugin?.enabled === false ? 'disabled' : plugin && plugin.version !== this.version ? 'needs-update' : plugin ? 'installed' : 'not-installed',
914
961
  installed: Boolean(plugin),
@@ -1106,7 +1153,7 @@ class IntegrationManager {
1106
1153
  return summary;
1107
1154
  }
1108
1155
 
1109
- installedMcpLauncherPaths(client) {
1156
+ installedMcpLauncherPaths(client, knowledge, claudeInventory) {
1110
1157
  const launchers = [];
1111
1158
  const seen = new Set();
1112
1159
  const consider = directory => {
@@ -1117,70 +1164,99 @@ class IntegrationManager {
1117
1164
  seen.add(launcher);
1118
1165
  launchers.push(launcher);
1119
1166
  };
1120
- if (client === 'claude') {
1167
+ if (client === 'claude' && this.localStatus) {
1168
+ const plugin = claudeInventory?.plugin;
1169
+ if (plugin?.enabled && plugin.version === this.version) consider(plugin.installPath);
1170
+ } else if (client === 'claude') {
1121
1171
  try {
1122
- const index = JSON.parse(fs.readFileSync(path.join(this.homeDir, '.claude', 'plugins', 'installed_plugins.json'), 'utf8'));
1172
+ const index = JSON.parse(fs.readFileSync(path.join(this.claudeConfigDir, 'plugins', 'installed_plugins.json'), 'utf8'));
1123
1173
  for (const record of (index.plugins?.[`${INTEGRATION_NAME}@${MARKETPLACE_NAME}`] || [])) {
1124
1174
  if (record && record.version === this.version) consider(record.installPath);
1125
1175
  }
1126
1176
  } catch { /* no native install index yet */ }
1127
- consider(path.join(this.homeDir, '.claude', 'plugins', 'cache', MARKETPLACE_NAME, INTEGRATION_NAME, this.version));
1128
- }
1129
- if (client === 'codex' && this.executable('codex')) {
1130
- try { consider(this.codexPlugin()?.source?.path); } catch { /* the client CLI failed to list plugins; there is no installed entry to probe */ }
1177
+ consider(path.join(this.claudeConfigDir, 'plugins', 'cache', MARKETPLACE_NAME, INTEGRATION_NAME, this.version));
1131
1178
  }
1179
+ if (client === 'codex') consider(knowledge?.source?.path);
1132
1180
  return launchers;
1133
1181
  }
1134
1182
 
1135
- async statusAll(options = {}) {
1136
- const clients = options.clients && options.clients.length ? options.clients.map(normalizeClient) : SUPPORTED_CLIENTS;
1137
- const summary = { clients: [], bridge: null };
1183
+ async statusClient(client, options, runProbe) {
1184
+ const entry = { client, label: CLIENT_LABELS[client], configFound: this.captureConfigFound(client) };
1185
+ try { entry.available = Boolean(this.executable(client)); }
1186
+ catch (error) { entry.commandCheck = { code: error.code || 'COMMAND_LOOKUP_FAILED' }; }
1187
+ entry.developmentCapture = await this.captureOperation('status', client);
1188
+ if (options.captureOnly) return entry;
1189
+ options.onClientStatus?.({ ...entry });
1190
+
1191
+ let claudeInventory;
1138
1192
  try {
1139
- summary.bridge = { ok: true, ...(await this.bridgeStatus()) };
1193
+ let knowledge;
1194
+ if (client === 'claude' && this.localStatus) {
1195
+ claudeInventory = readClaudePluginStatus({ configDir: this.claudeConfigDir, settingsFile: this.claudeSettingsFile, pluginId: PLUGIN_ID, cwd: options.cwd });
1196
+ knowledge = this.claudeKnowledgeStatus(claudeInventory.plugin);
1197
+ } else {
1198
+ if (entry.commandCheck) throw Object.assign(new Error('Command lookup failed.'), entry.commandCheck);
1199
+ knowledge = await this[`status${CLIENT_METHOD_SUFFIX[client]}`]();
1200
+ }
1201
+ entry.knowledgeIntegration = { ok: true, ...knowledge };
1140
1202
  } catch (error) {
1141
- summary.bridge = { ok: false, state: 'failed', bridgeHealthy: false, detail: error.message };
1203
+ const code = error.code || 'KNOWLEDGE_INTEGRATION_CHECK_FAILED';
1204
+ entry.knowledgeIntegration = { ok: false, state: 'check-failed', error: { code },
1205
+ detail: code === 'ETIMEDOUT' ? '知识插件检查超时。' : '无法核实知识插件状态。' };
1142
1206
  }
1143
- // Probes start in parallel so one hung launcher costs a single timeout.
1144
- // Client probes exercise the entry that client would actually launch
1145
- // (never the host source tree); identical entries share one host check,
1146
- // and the shared product-runtime probe covers the shipping runtime.
1147
- const runProbe = info => (this.mcpProbe ? this.mcpProbe(info) : this.probeMcpStartup(info)).catch(() => ({ state: 'failed', checkedAt: new Date().toISOString(), code: 'PROBE_CRASH', expectedVersion: this.version, detail: MCP_PROBE_FAILURE_DETAILS.PROBE_CRASH }));
1148
- const clientProbes = new Map();
1149
- const hostProbe = options.captureOnly ? null : runProbe({ client: 'host', scope: 'product-runtime', version: this.version });
1150
- if (!options.captureOnly) {
1151
- const sharedByLauncher = new Map();
1152
- for (const client of clients) {
1153
- if (client !== 'claude' && client !== 'codex') continue;
1154
- const launcherPath = this.installedMcpLauncherPaths(client)[0];
1155
- if (!launcherPath) continue;
1156
- if (!sharedByLauncher.has(launcherPath)) sharedByLauncher.set(launcherPath, runProbe({ client, scope: `client:${client}`, launcherPath, version: this.version }));
1157
- clientProbes.set(client, sharedByLauncher.get(launcherPath).then(result => ({ ...result, scope: `client:${client}` })));
1207
+ options.onClientStatus?.({ ...entry });
1208
+
1209
+ const knowledge = entry.knowledgeIntegration;
1210
+ let mcpProbe;
1211
+ const scope = `client:${client}`;
1212
+ if (client === 'claude' || client === 'codex') {
1213
+ const launcherPath = this.installedMcpLauncherPaths(client, knowledge, claudeInventory)[0];
1214
+ if (launcherPath) {
1215
+ mcpProbe = runProbe({ client, scope, launcherPath, version: this.version });
1216
+ } else {
1217
+ const code = knowledge.error?.code || (knowledge.state === 'disabled' ? 'CLIENT_PLUGIN_DISABLED' : 'CLIENT_PLUGIN_ENTRY_MISSING');
1218
+ const detail = knowledge.error ? '知识插件状态尚未核实。' : knowledge.state === 'disabled'
1219
+ ? '客户端知识插件已被禁用。' : '没有找到该客户端的知识插件启动文件。';
1220
+ entry.mcpStartup = { state: 'failed', checkedAt: new Date().toISOString(), scope, code, expectedVersion: this.version, detail };
1158
1221
  }
1159
1222
  }
1160
- for (const client of clients) {
1161
- const suffix = CLIENT_METHOD_SUFFIX[client];
1162
- const entry = { client, label: CLIENT_LABELS[client], available: Boolean(this.executable(client)), configFound: this.captureConfigFound(client) };
1163
- if (!options.captureOnly) {
1164
- try {
1165
- entry.knowledgeIntegration = { ok: true, ...(await this[`status${suffix}`]()) };
1166
- } catch (error) {
1167
- entry.knowledgeIntegration = { ok: false, state: 'failed', detail: error.message };
1168
- }
1169
- entry.automaticContext = client === 'codex' ? await this.automaticCodexContextStatus(entry.knowledgeIntegration, options.cwd) : this.automaticContextStatus(client, entry.knowledgeIntegration);
1170
- if (client === 'claude' || client === 'codex') {
1171
- entry.mcpStartup = clientProbes.has(client)
1172
- ? await clientProbes.get(client)
1173
- : { state: 'failed', checkedAt: new Date().toISOString(), scope: `client:${client}`, code: 'CLIENT_PLUGIN_ENTRY_MISSING', expectedVersion: this.version, detail: '该客户端没有已安装的知识插件入口;未用宿主源码入口代替客户端实际启动入口做健康判定。' };
1174
- }
1223
+ entry.automaticContext = client === 'codex'
1224
+ ? await this.automaticCodexContextStatus(knowledge, options.cwd)
1225
+ : this.automaticContextStatus(client, knowledge, claudeInventory);
1226
+ if (mcpProbe) entry.mcpStartup = { ...(await mcpProbe), scope };
1227
+ return entry;
1228
+ }
1229
+
1230
+ async statusShared(options, runProbe) {
1231
+ const bridgeCheck = this.bridgeStatus().then(
1232
+ bridge => ({ ok: true, ...bridge }),
1233
+ error => ({ ok: false, state: 'failed', bridgeHealthy: false, detail: error.message }),
1234
+ );
1235
+ const hostProbe = options.captureOnly ? undefined : runProbe({ client: 'host', scope: 'product-runtime', version: this.version });
1236
+ const [bridge, mcpRuntime] = await Promise.all([bridgeCheck, hostProbe]);
1237
+ return { bridge, ...(mcpRuntime ? { mcpRuntime } : {}) };
1238
+ }
1239
+
1240
+ async statusAll(options = {}) {
1241
+ const clients = options.sharedOnly ? [] : options.clients?.length ? options.clients.map(normalizeClient) : SUPPORTED_CLIENTS;
1242
+ const probes = new Map();
1243
+ const runProbe = info => {
1244
+ const key = info.launcherPath || info.scope;
1245
+ if (!probes.has(key)) {
1246
+ const probe = Promise.resolve().then(() => this.mcpProbe ? this.mcpProbe(info) : this.probeMcpStartup(info))
1247
+ .catch(() => ({ state: 'failed', checkedAt: new Date().toISOString(), code: 'PROBE_CRASH', expectedVersion: this.version, detail: MCP_PROBE_FAILURE_DETAILS.PROBE_CRASH }));
1248
+ probes.set(key, probe);
1175
1249
  }
1176
- entry.developmentCapture = await this.captureOperation('status', client);
1177
- summary.clients.push(entry);
1178
- }
1179
- if (hostProbe) summary.mcpRuntime = await hostProbe;
1180
- return summary;
1250
+ return probes.get(key);
1251
+ };
1252
+ const [shared, results] = await Promise.all([
1253
+ options.includeShared === false ? {} : this.statusShared(options, runProbe),
1254
+ Promise.all(clients.map(client => this.statusClient(client, options, runProbe))),
1255
+ ]);
1256
+ return { ...shared, clients: results };
1181
1257
  }
1182
1258
 
1183
- automaticContextStatus(client, knowledge) {
1259
+ automaticContextStatus(client, knowledge, claudeInventory) {
1184
1260
  if (client === 'zcode') { const available = Boolean(this.executable('zcode')); return { supported: true, configured: available && knowledge?.state === 'installed', state: available ? knowledge?.state || 'not-installed' : 'unavailable', detail: available ? knowledge?.detail || '前置读取尚未接入。' : '未找到可运行的 ZCode;配置存在不等于原生入口可用。' }; }
1185
1261
  if (client === 'codex') {
1186
1262
  const filesVerified = knowledge?.state === 'installed' && this.codexContextFilesMatch({ source: knowledge.source });
@@ -1188,15 +1264,21 @@ class IntegrationManager {
1188
1264
  }
1189
1265
  if (client !== 'claude') return { supported: false, state: 'not-supported', configured: false, detail: '当前版本尚未验收此客户端的自动前置读取;知识工具与采集状态单独显示。' };
1190
1266
  const state = knowledge?.state || 'not-installed';
1191
- try { if (JSON.parse(fs.readFileSync(this.claudeSettingsFile, 'utf8')).disableAllHooks === true) return { supported: true, state: 'disabled', configured: false, detail: 'Claude Code 的 Hook 已被用户禁用,未擅自修改。' }; } catch {}
1192
- if (state !== 'installed') return { supported: true, state, configured: false, expectedVersion: this.version, detail: state === 'needs-update' ? '知识插件版本不匹配,请接入/修复后重新打开 Claude Code。' : state === 'disabled' ? '插件已被禁用;请在客户端明确启用。' : '前置知识读取尚未接入。' };
1267
+ let hooksDisabled = claudeInventory?.hooksDisabled;
1268
+ if (!claudeInventory) {
1269
+ try { hooksDisabled = JSON.parse(fs.readFileSync(this.claudeSettingsFile, 'utf8')).disableAllHooks === true; } catch {}
1270
+ }
1271
+ if (hooksDisabled) return { supported: true, state: 'disabled', configured: false, detail: 'Claude Code 的 Hook 已被用户禁用,未擅自修改。' };
1272
+ if (state !== 'installed') return { supported: true, state, configured: false, expectedVersion: this.version, detail: state === 'check-failed' ? '前置知识读取尚未核实。' : state === 'needs-update' ? '知识插件版本不匹配,请接入/修复后重新打开 Claude Code。' : state === 'disabled' ? '插件已被禁用;请在客户端明确启用。' : '前置知识读取尚未接入。' };
1193
1273
  if (!/^[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?$/.test(knowledge.version || '')) return { supported: true, state: 'needs-update', configured: false, detail: '无法验证插件版本。' };
1194
- let locations = [];
1195
- try {
1196
- const index = JSON.parse(fs.readFileSync(path.join(this.homeDir, '.claude/plugins/installed_plugins.json'), 'utf8'));
1197
- locations = (index.plugins?.[`${INTEGRATION_NAME}@${MARKETPLACE_NAME}`] || []).filter(p => p.version === knowledge.version).map(p => p.installPath);
1198
- } catch {}
1199
- if (!locations.length) locations.push(path.join(this.homeDir, '.claude/plugins/cache', MARKETPLACE_NAME, INTEGRATION_NAME, knowledge.version));
1274
+ let locations = claudeInventory?.plugin ? [claudeInventory.plugin.installPath] : [];
1275
+ if (!claudeInventory) {
1276
+ try {
1277
+ const index = JSON.parse(fs.readFileSync(path.join(this.claudeConfigDir, 'plugins', 'installed_plugins.json'), 'utf8'));
1278
+ locations = (index.plugins?.[PLUGIN_ID] || []).filter(p => p.version === knowledge.version).map(p => p.installPath);
1279
+ } catch {}
1280
+ if (!locations.length) locations.push(path.join(this.claudeConfigDir, 'plugins', 'cache', MARKETPLACE_NAME, INTEGRATION_NAME, knowledge.version));
1281
+ }
1200
1282
  const files = ['hooks/claude.json', 'scripts/context-hook.cjs', '.mcp.json', '.claude-plugin/plugin.json'];
1201
1283
  const configured = locations.some(directory => typeof directory === 'string' && files.every(file => {
1202
1284
  // Native marketplaces use Git checkout newline rules; npm integrity
@@ -68,7 +68,9 @@ function bootstrapIntent(dataDir, clientsStatus) {
68
68
  let changed = false;
69
69
  for (const entry of clientsStatus || []) {
70
70
  if (!entry || !entry.client || entry.client in clients) continue;
71
- if (entry.developmentCapture?.state === 'checking' || entry.developmentCapture?.installed === undefined) continue;
71
+ const capture = entry.developmentCapture;
72
+ if (entry.scan?.stale || capture?.ok === false || ['checking', 'check-failed', 'failed', 'conflict'].includes(capture?.state)
73
+ || typeof capture?.installed !== 'boolean') continue;
72
74
  clients[entry.client] = entry.developmentCapture?.installed === true ? 'connected' : 'disconnected';
73
75
  changed = true;
74
76
  }
@@ -78,11 +80,16 @@ function bootstrapIntent(dataDir, clientsStatus) {
78
80
 
79
81
  // Aggregate badge state for the single-switch UI.
80
82
  function summarizeClient(entry, repair) {
81
- if (entry.developmentCapture?.state === 'checking' || entry.knowledgeIntegration?.state === 'checking') return 'checking';
82
- if (!(entry.available || entry.configFound)) return 'not-detected';
83
- if (entry.developmentCapture?.installed === true) return 'connected';
83
+ const capture = entry.developmentCapture;
84
+ if (capture?.installed === true) return 'connected';
85
+ if (capture?.state === 'conflict') return 'error';
86
+ if (capture?.state === 'checking' || (capture?.installed === undefined && entry.knowledgeIntegration?.state === 'checking')) return 'checking';
87
+ if (capture?.ok === false || capture?.state === 'check-failed' || capture?.state === 'failed'
88
+ || (entry.scan?.stale && entry.scan?.error)) return 'check-failed';
84
89
  if (repair?.[entry.client]?.state === 'failed') return 'error';
85
- return 'disconnected';
90
+ if (entry.available || entry.configFound) return 'disconnected';
91
+ if (entry.available === false && entry.configFound === false && !entry.scan?.stale) return 'not-detected';
92
+ return 'check-failed';
86
93
  }
87
94
 
88
95
  module.exports = { SCHEMA, FILENAME, intentPath, readIntent, markIntent, bootstrapIntent, summarizeClient };