@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
@@ -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; });
@@ -0,0 +1,258 @@
1
+ // Run: node _site/_test/legacy-relocation-recovery-test.js
2
+ // Legacy 执行路径的数据目录迁移恢复:旧版在目录 A 冻结的 claim(v1 快照携带
3
+ // A 的绝对路径)在目录改名后,经 processCommitEvent 重试入口从当前目录 B 读取
4
+ // 同一份证据完成维护;证据缺失以可定位类别失败,不写知识、不推进状态。
5
+
6
+ const assert = require('assert');
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+ const { execFileSync } = require('child_process');
11
+ const { StorageLayout } = require('../lib/storage-layout');
12
+ const { ProjectRegistryStore } = require('../lib/project-registry-store');
13
+ const { ProjectStore } = require('../lib/project-store');
14
+ const { CommitReconciler, SNAPSHOT_SCHEMA_V1 } = require('../lib/commit-reconciler');
15
+ const { KnowledgePromotionService, MANIFEST_SCHEMA, hashBuffer } = require('../lib/knowledge-promotion');
16
+ const AtomicFile = require('../lib/atomic-file');
17
+
18
+ const git = (cwd, args) => execFileSync('git', args, { cwd, windowsHide: true, encoding: 'utf8' }).trim();
19
+
20
+ function makeRepo(root, name, { bigPatch = false } = {}) {
21
+ const repoPath = path.join(root, `代码 ${name}`);
22
+ fs.mkdirSync(repoPath, { recursive: true });
23
+ git(repoPath, ['init', '-q']);
24
+ git(repoPath, ['config', 'user.email', 'legacy-relocation@local.invalid']);
25
+ git(repoPath, ['config', 'user.name', 'Legacy Relocation Test']);
26
+ fs.writeFileSync(path.join(repoPath, 'README.md'), '# Initial\n');
27
+ git(repoPath, ['add', '.']);
28
+ git(repoPath, ['commit', '-qm', 'initial']);
29
+ const baseline = git(repoPath, ['rev-parse', 'HEAD']);
30
+ const payload = bigPatch ? `line ${'x'.repeat(96)} ${Date.now()}\n`.repeat(30000) : 'small feature change\n';
31
+ fs.writeFileSync(path.join(repoPath, 'feature.txt'), payload);
32
+ git(repoPath, ['add', '.']);
33
+ git(repoPath, ['commit', '-qm', 'feature']);
34
+ return { repoPath, baseline, commitSha: git(repoPath, ['rev-parse', 'HEAD']) };
35
+ }
36
+
37
+ function analyzerFor({ events = [] } = {}) {
38
+ return {
39
+ async runClaim(input) {
40
+ events.push({ evidenceRoot: input.evidenceRoot, runId: input.claim.runId, chunked: Boolean(input.evidence.patchChunked) });
41
+ fs.readFileSync(path.join(input.evidenceRoot, 'patch-manifest.json'), 'utf8');
42
+ const relative = `changes/${input.claim.commitSha.slice(0, 12)}.md`;
43
+ const content = `# Verified maintenance\n\nCommit ${input.claim.commitSha} analyzed from relocated legacy evidence.\n`;
44
+ const target = path.join(input.stagingPath, 'files', relative);
45
+ fs.mkdirSync(path.dirname(target), { recursive: true });
46
+ fs.writeFileSync(target, content, 'utf8');
47
+ AtomicFile.writeJsonAtomic(input.manifestPath, {
48
+ schema: MANIFEST_SCHEMA,
49
+ projectId: input.projectId,
50
+ runId: input.claim.runId,
51
+ commitSha: input.claim.commitSha,
52
+ operations: [{
53
+ path: relative,
54
+ operation: 'create',
55
+ sha256: hashBuffer(Buffer.from(content)),
56
+ reason: 'Relocated frozen evidence',
57
+ evidenceReferences: [
58
+ `commit:${input.claim.commitSha}`,
59
+ `patch:${input.claim.patchHash}`,
60
+ `conversation:${input.claim.conversationSnapshotHash}`,
61
+ `retrieval:${input.claim.retrievalManifestHash}`,
62
+ ].filter(reference => !reference.endsWith(':')),
63
+ }],
64
+ });
65
+ return { ok: true };
66
+ },
67
+ };
68
+ }
69
+
70
+ async function buildStores(layout) {
71
+ const registry = new ProjectRegistryStore({ layout });
72
+ const projects = new ProjectStore({ layout });
73
+ await registry.initialize();
74
+ return { registry, projects };
75
+ }
76
+
77
+ // Rewrite the on-disk snapshot into the exact v1 shape an older version wrote:
78
+ // absolute evidence/retrieval locations under `dataDir`, no runId field.
79
+ function downgradeSnapshotToV1(dataDir, projectId, commitSha, runId) {
80
+ const file = path.join(dataDir, 'runtime', 'claims', projectId, `${commitSha}.json`);
81
+ const snapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
82
+ const evidenceRoot = path.join(dataDir, 'runtime', 'runs', projectId, runId, 'input', 'evidence');
83
+ const legacy = {
84
+ schema: SNAPSHOT_SCHEMA_V1,
85
+ projectId,
86
+ commitSha,
87
+ claimFingerprint: snapshot.claimFingerprint,
88
+ evidence: {
89
+ ...snapshot.evidence,
90
+ evidenceBundle: {
91
+ ...snapshot.evidence.evidenceBundle,
92
+ root: evidenceRoot,
93
+ commitPath: path.join(evidenceRoot, 'commit.json'),
94
+ manifestPath: path.join(evidenceRoot, 'patch-manifest.json'),
95
+ },
96
+ },
97
+ prompt: snapshot.prompt,
98
+ requirements: snapshot.requirements || [],
99
+ conversationSnapshot: snapshot.conversationSnapshot || null,
100
+ existingKnowledge: {
101
+ ...snapshot.existingKnowledge,
102
+ manifestPath: path.join(dataDir, 'runtime', 'runs', projectId, runId, 'input', 'retrieval', 'manifest.json'),
103
+ },
104
+ createdAt: snapshot.createdAt,
105
+ };
106
+ AtomicFile.writeJsonAtomic(file, legacy);
107
+ return legacy;
108
+ }
109
+
110
+ async function relocateAndRetry(t, { root, name, bigPatch, tamper = null }) {
111
+ const projectId = `project-${name.replace(/\s+/g, '-')}`;
112
+ const knowledgePath = path.join(root, `知识 ${name}`);
113
+ fs.mkdirSync(knowledgePath, { recursive: true });
114
+ const repo = makeRepo(root, name, { bigPatch });
115
+ const dataA = path.join(root, `数据 A ${name}`);
116
+ const layoutA = new StorageLayout({ dataDir: dataA });
117
+ const storesA = await buildStores(layoutA);
118
+ await storesA.registry.add(projectId, { displayName: projectId });
119
+ await storesA.projects.create(projectId, { repoPath: repo.repoPath, knowledgePath }, { trackingStartCommit: repo.baseline });
120
+
121
+ const failingProcessor = { processClaim: async () => { throw Object.assign(new Error('知识分析超时。'), { code: 'MODEL_TIMEOUT', retryable: true, phase: 'analyzing' }); } };
122
+ const reconcilerA = new CommitReconciler({ layout: layoutA, registryStore: storesA.registry, projectStore: storesA.projects, claimProcessor: failingProcessor, requireAiProfile: false });
123
+ const first = await reconcilerA.processCommitEvent({ projectId, commitSha: repo.commitSha, branch: 'main' });
124
+ assert.strictEqual(first.ok, false);
125
+ assert.strictEqual(first.error.code, 'MODEL_TIMEOUT');
126
+ const stateA = storesA.projects.readState(projectId);
127
+ const runId = stateA.analysis.activeClaim.runId;
128
+ assert.ok(runId, 'the failed attempt keeps its frozen claim');
129
+ const legacy = downgradeSnapshotToV1(dataA, projectId, repo.commitSha, runId);
130
+ assert.ok(legacy.evidence.evidenceBundle.root.startsWith(dataA), 'the v1 snapshot carries absolute A paths');
131
+ const staleEvidenceRoot = legacy.evidence.evidenceBundle.root;
132
+
133
+ const dataB = path.join(root, `数据 B ${name}`);
134
+ fs.renameSync(dataA, dataB);
135
+ assert.strictEqual(fs.existsSync(dataA), false, 'directory A no longer exists');
136
+
137
+ const layoutB = new StorageLayout({ dataDir: dataB });
138
+ const storesB = await buildStores(layoutB);
139
+ const events = [];
140
+ const promotion = new KnowledgePromotionService({ layout: layoutB, projectStore: storesB.projects, analyzer: analyzerFor({ events }) });
141
+ const reconcilerB = new CommitReconciler({ layout: layoutB, registryStore: storesB.registry, projectStore: storesB.projects, claimProcessor: promotion, requireAiProfile: false });
142
+
143
+ const currentEvidenceRoot = path.join(dataB, 'runtime', 'runs', projectId, runId, 'input', 'evidence');
144
+ if (tamper) tamper({ evidenceRoot: currentEvidenceRoot, retrievalDir: path.join(dataB, 'runtime', 'runs', projectId, runId, 'input', 'retrieval') });
145
+ const second = await reconcilerB.processCommitEvent({ projectId, commitSha: repo.commitSha, branch: 'main' });
146
+ return { second, events, storesB, knowledgePath, repo, dataB, projectId, runId, staleEvidenceRoot };
147
+ }
148
+
149
+ (async () => {
150
+ // 1) Happy path: v1 claim + chunked patch retries from directory B and the
151
+ // queue continues to the next commit.
152
+ {
153
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-legacy-reloc happy-'));
154
+ try {
155
+ const result = await relocateAndRetry(null, { root, name: 'chunked', bigPatch: true });
156
+ assert.strictEqual(result.second.ok, true, JSON.stringify(result.second.error));
157
+ assert.strictEqual((result.second.processed && result.second.processed[0] || {}).runId, result.runId, 'the retry reuses the SAME analysis run');
158
+ assert.ok(result.events.length >= 1 && result.events[0].evidenceRoot.includes(`数据 B chunked`), 'the analyzer read from directory B');
159
+ assert.strictEqual(result.events[0].chunked, true, 'the big patch stayed chunked');
160
+ const state = result.storesB.projects.readState(result.projectId);
161
+ assert.strictEqual(state.lastAnalyzedCommit, result.repo.commitSha, 'state advanced after relocated retry');
162
+ assert.strictEqual(state.analysis.activeClaim, null);
163
+ assert.ok(fs.existsSync(path.join(result.knowledgePath, 'changes', `${result.repo.commitSha.slice(0, 12)}.md`)), 'knowledge promoted from relocated evidence');
164
+ assert.strictEqual(fs.existsSync(path.join(result.dataB, 'runtime', 'claims', result.projectId, `${result.repo.commitSha}.json`)), false, 'claim snapshot released');
165
+ // A second, queued commit continues in order after recovery.
166
+ const repoPath = result.repo.repoPath;
167
+ fs.writeFileSync(path.join(repoPath, 'second.txt'), 'second\n');
168
+ git(repoPath, ['add', '.']);
169
+ git(repoPath, ['commit', '-qm', 'second']);
170
+ const secondSha = git(repoPath, ['rev-parse', 'HEAD']);
171
+ const events = [];
172
+ const promotion = new KnowledgePromotionService({
173
+ layout: new StorageLayout({ dataDir: result.dataB }),
174
+ projectStore: result.storesB.projects,
175
+ analyzer: analyzerFor({ events }),
176
+ });
177
+ const reconciler = new CommitReconciler({ layout: new StorageLayout({ dataDir: result.dataB }), registryStore: result.storesB.registry || {}, projectStore: result.storesB.projects, claimProcessor: promotion, requireAiProfile: false });
178
+ const next = await reconciler.processCommitEvent({ projectId: result.projectId, commitSha: secondSha, branch: 'main' });
179
+ assert.strictEqual(next.ok, true, JSON.stringify(next.error));
180
+ assert.ok(fs.existsSync(path.join(result.knowledgePath, 'changes', `${secondSha.slice(0, 12)}.md`)), 'the queued commit continued after recovery');
181
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
182
+ }
183
+
184
+ // 2) Stale old directory with different content never satisfies the retry.
185
+ {
186
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-legacy-reloc stale-'));
187
+ try {
188
+ // Keep a poisoned copy at the old location to prove reads come from B.
189
+ const result = await relocateAndRetry(null, { root, name: 'stale', bigPatch: false });
190
+ fs.mkdirSync(result.staleEvidenceRoot, { recursive: true });
191
+ AtomicFile.writeJsonAtomic(path.join(result.staleEvidenceRoot, 'patch-manifest.json'), { schema: 'tampered', chunks: [] });
192
+ assert.strictEqual(result.second.ok, true, JSON.stringify(result.second.error));
193
+ assert.ok(result.events[0].evidenceRoot.includes('数据 B stale'), 'reads came from directory B');
194
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
195
+ }
196
+
197
+ // 3) Missing evidence fails with a locatable category and no fake success.
198
+ {
199
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-legacy-reloc missing-'));
200
+ try {
201
+ const result = await relocateAndRetry(null, {
202
+ root, name: 'missing', bigPatch: false,
203
+ tamper: ({ retrievalDir }) => fs.unlinkSync(path.join(retrievalDir, 'manifest.json')),
204
+ });
205
+ assert.strictEqual(result.second.ok, false);
206
+ assert.strictEqual(result.second.error.code, 'EVIDENCE_MISSING', JSON.stringify(result.second.error));
207
+ assert.strictEqual(result.second.error.details.resource, 'input/retrieval/manifest.json', 'the failure names the concrete resource');
208
+ assert.strictEqual(result.second.error.retryable, false);
209
+ const state = result.storesB.projects.readState(result.projectId);
210
+ assert.strictEqual(state.lastAnalyzedCommit, null, 'analysis head not advanced');
211
+ assert.strictEqual(fs.existsSync(path.join(result.knowledgePath, 'changes')), false, 'no knowledge was written');
212
+ assert.strictEqual(state.analysis.activeClaim.phase, 'failed', 'the failed claim is preserved for diagnostics');
213
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
214
+ }
215
+
216
+ // 4) A v2 snapshot survives a second relocation without any rewrite.
217
+ {
218
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'kb-legacy-reloc twice-'));
219
+ try {
220
+ // Produce the failed state on A, move A->B without downgrading (v2 stays).
221
+ const projectId = 'project-twice';
222
+ const knowledgePath = path.join(root, '知识 twice');
223
+ fs.mkdirSync(knowledgePath, { recursive: true });
224
+ const repo = makeRepo(root, 'twice', { bigPatch: false });
225
+ const dataA = path.join(root, '数据 A twice');
226
+ const layoutA = new StorageLayout({ dataDir: dataA });
227
+ const storesA = await buildStores(layoutA);
228
+ await storesA.registry.add(projectId, { displayName: projectId });
229
+ await storesA.projects.create(projectId, { repoPath: repo.repoPath, knowledgePath }, { trackingStartCommit: repo.baseline });
230
+ const failing = { processClaim: async () => { throw Object.assign(new Error('知识分析超时。'), { code: 'MODEL_TIMEOUT', retryable: true, phase: 'analyzing' }); } };
231
+ const reconcilerA = new CommitReconciler({ layout: layoutA, registryStore: storesA.registry, projectStore: storesA.projects, claimProcessor: failing, requireAiProfile: false });
232
+ await reconcilerA.processCommitEvent({ projectId, commitSha: repo.commitSha, branch: 'main' });
233
+ const runId = storesA.projects.readState(projectId).analysis.activeClaim.runId;
234
+ const dataB = path.join(root, '数据 B twice');
235
+ fs.renameSync(dataA, dataB);
236
+ const snapshot = JSON.parse(fs.readFileSync(path.join(dataB, 'runtime', 'claims', projectId, `${repo.commitSha}.json`), 'utf8'));
237
+ assert.strictEqual(snapshot.schema, 'commit-claim-snapshot/v2');
238
+ assert.strictEqual(snapshot.evidence.evidenceBundle.root, undefined, 'v2 stores no absolute evidence path');
239
+ const dataC = path.join(root, '数据 C twice');
240
+ fs.renameSync(dataB, dataC);
241
+ const layoutC = new StorageLayout({ dataDir: dataC });
242
+ const storesC = await buildStores(layoutC);
243
+ const events = [];
244
+ const promotion = new KnowledgePromotionService({ layout: layoutC, projectStore: storesC.projects, analyzer: analyzerFor({ events }) });
245
+ const reconcilerC = new CommitReconciler({ layout: layoutC, registryStore: storesC.registry, projectStore: storesC.projects, claimProcessor: promotion, requireAiProfile: false });
246
+ const retried = await reconcilerC.processCommitEvent({ projectId, commitSha: repo.commitSha, branch: 'main' });
247
+ assert.strictEqual(retried.ok, true, JSON.stringify(retried.error));
248
+ assert.strictEqual((retried.processed && retried.processed[0] || {}).runId, runId, 'same analysis run across both relocations');
249
+ assert.ok(events[0].evidenceRoot.includes('数据 C twice'));
250
+ assert.ok(fs.existsSync(path.join(knowledgePath, 'changes', `${repo.commitSha.slice(0, 12)}.md`)));
251
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
252
+ }
253
+
254
+ console.log('legacy-relocation-recovery-test PASS');
255
+ })().catch(error => {
256
+ console.error(error.stack || error.message);
257
+ process.exitCode = 1;
258
+ });
@@ -11,8 +11,8 @@
11
11
  // 3) the engine and the PINNED vector-hub package agree on the body hash,
12
12
  // which is the precondition the engine needs before it may merge a
13
13
  // vector-hub chunk row into a retrieved fact;
14
- // 4) the PINNED package still has the identity the comparison was made
15
- // against, and its query cache still BEHAVES the way the comparison
14
+ // 4) the installed package matches the shell's version pin,
15
+ // and its query cache still BEHAVES the way the comparison
16
16
  // assumed: an identical query is served from the cache, a failed query
17
17
  // is evicted, and a late failure of an evicted owner cannot destroy the
18
18
  // replacement cached for the same text. The behaviour is observed
@@ -186,11 +186,13 @@ async function waitUntil(predicate, timeoutMs = 5000, intervalMs = 20) {
186
186
  // implementation is not a behaviour.
187
187
  const pinnedPackage = path.join(shell.REPO_ROOT, 'node_modules', '@sanqianx', 'vector-hub');
188
188
  const pinnedManifest = JSON.parse(fs.readFileSync(path.join(pinnedPackage, 'package.json'), 'utf8'));
189
+ const shellManifest = JSON.parse(fs.readFileSync(path.join(shell.REPO_ROOT, 'package.json'), 'utf8'));
190
+ const expectedVersion = shellManifest.dependencies['@sanqianx/vector-hub'];
189
191
  assert.equal(pinnedManifest.name, '@sanqianx/vector-hub', 'the pinned package identity changed');
190
192
  assert.equal(
191
193
  pinnedManifest.version,
192
- '1.0.8-rc.8',
193
- `the pinned @sanqianx/vector-hub is ${pinnedManifest.version} instead of 1.0.8-rc.8; re-run qa-autopilot/tools/product-probes/parallel-retrieval-followup-ret008.js`,
194
+ expectedVersion,
195
+ 'the installed vector-hub must match the shell version pin',
194
196
  );
195
197
  record('RET-008-PINNED-PACKAGE', 'PASS', { pinnedName: pinnedManifest.name, pinnedVersion: pinnedManifest.version });
196
198
 
@@ -0,0 +1,124 @@
1
+ 'use strict';
2
+
3
+ // Run with the pinned workflow package by default. PK_TEST_WORKFLOW_ENTRY
4
+ // and PK_TEST_PRODUCT_ROOT support testing a staged package.
5
+ const assert = require('node:assert/strict');
6
+ const path = require('node:path');
7
+ // The harness launches a separate browser via helpers/cdp-browser.
8
+ const { ROOT, startHarness, makeRepo } = require('./helpers/parallel-memory-shell');
9
+
10
+ const productRoot = path.resolve(process.env.PK_TEST_PRODUCT_ROOT || ROOT);
11
+ const candidateEntry = process.env.PK_TEST_WORKFLOW_ENTRY;
12
+ const workflowEntry = candidateEntry ? path.resolve(candidateEntry) : require.resolve('@sanqianx/ai-coding-workflow', { paths: [productRoot] });
13
+ const workflowApi = '/api/workflow';
14
+ const teamName = '工具链团队';
15
+
16
+ async function createWithWizard(harness, projectId, group) {
17
+ const inFrame = (fn, ...args) => harness.run(`(${fn})(document.getElementById('workflowFrame').contentDocument, ...${JSON.stringify(args)})`);
18
+ const click = async selector => assert.ok(await inFrame((doc, target) => {
19
+ const node = doc.querySelector(target);
20
+ if (!node || node.disabled || !node.getClientRects().length) return false;
21
+ node.click();
22
+ return true;
23
+ }, selector), `available workflow control: ${selector}`);
24
+ const change = (selector, value, eventType) => inFrame((doc, target, next, type) => {
25
+ const node = doc.querySelector(target);
26
+ node.value = next;
27
+ node.dispatchEvent(new Event(type, { bubbles: true }));
28
+ }, selector, value, eventType);
29
+
30
+ await harness.nativeClick('nav [data-view="projects"]');
31
+ const createTeam = `[data-project-team="${projectId}"] [data-go="team"]`;
32
+ await harness.waitFor(() => harness.run(`Boolean(document.querySelector(${JSON.stringify(createTeam)}))`), 'create-team entry in the project list');
33
+ await harness.nativeClick(createTeam);
34
+ await harness.waitFor(() => inFrame(doc => Boolean(doc?.querySelector('#createTeamBtn'))), 'empty team page');
35
+ await click('#createTeamBtn');
36
+ await harness.waitFor(() => inFrame(doc => Boolean(doc?.querySelector('#wzAddMember'))), 'team wizard');
37
+ await change('#wzTeamName', teamName, 'input');
38
+ await click('[data-wizard-member="0"] [data-remove-member]');
39
+ await click('#wzAddMember');
40
+ await change('[data-wizard-member="1"] [data-member-field="role"]', 'release-docs', 'change');
41
+ await click('#wzNext');
42
+ const memory = `[data-wizard-memory="1"] input[value="${group.id}"]`;
43
+ await harness.waitFor(() => inFrame((doc, selector) => Boolean(doc.querySelector(selector)), memory), 'member memory choices');
44
+ await click(memory);
45
+ await click('#wzNext');
46
+ await harness.waitFor(() => inFrame(doc => Array.from(doc.querySelectorAll('[data-wiz="project"]')).length === 2), 'two projects with choices');
47
+ const projectLabels = await inFrame(doc => Array.from(doc.querySelectorAll('[data-wiz="project"]'), input => {
48
+ const label = input.closest('label');
49
+ return { name: label.textContent.trim(), layout: doc.defaultView.getComputedStyle(label).flexDirection };
50
+ }));
51
+ assert.deepEqual(new Set(projectLabels.map(p => p.name)), new Set(['项目甲', '项目乙']));
52
+ assert.ok(projectLabels.every(p => p.layout === 'row'));
53
+ const projectCheck = `[data-wiz="project"][value="${projectId}"]`;
54
+ await click(projectCheck);
55
+ await click('#wzBack');
56
+ assert.equal(await inFrame((doc, selector) => doc.querySelector(selector).checked, memory), true);
57
+ await click('#wzNext');
58
+ assert.equal(await inFrame((doc, selector) => doc.querySelector(selector).checked, projectCheck), true);
59
+ await click('#wzCreate');
60
+ await harness.waitFor(() => inFrame(doc => Boolean(doc.querySelector('#panel-members:not(.hidden) #addMember'))), 'persisted roster');
61
+ const members = await harness.productApi('GET', workflowApi + '/members');
62
+ assert.deepEqual(members.body.members.map(m => m.role), ['reviewer', 'release-docs']);
63
+ assert.deepEqual(members.body.members[1].memoryGroupIds, [group.id]);
64
+ assert.match(await inFrame(doc => doc.getElementById('panel-members').textContent), /自动维护待接入/);
65
+
66
+ await click('#addMember');
67
+ await change('#memberForm [data-member-field="name"]', 'C++ Review', 'input');
68
+ await change('#memberForm [data-member-field="instructions"]', '检查 clang-tidy 收据', 'input');
69
+ await click('#memberForm button[type="submit"]');
70
+ await harness.waitFor(() => inFrame(doc => doc.querySelectorAll('.member-card[data-member]').length === 3), 'third member on the roster');
71
+ const updated = await harness.productApi('GET', workflowApi + '/members');
72
+ assert.equal(updated.body.members[2].instructions, '检查 clang-tidy 收据');
73
+ }
74
+
75
+ async function main() {
76
+ const harness = await startHarness({ tag: 'project-team', productRoot, workflowEntry });
77
+ const { productApi } = harness;
78
+ try {
79
+ const { projectId: alpha } = await harness.importProject(makeRepo(harness.fixture, 'alpha'), '项目甲');
80
+ const { projectId: beta } = await harness.importProject(makeRepo(harness.fixture, 'beta'), '项目乙');
81
+ const newGroup = await harness.engineApi('POST', '/api/memory-groups', { name: '团队规范' });
82
+ assert.equal(newGroup.status, 200);
83
+ const group = newGroup.body.group;
84
+ const bind = await harness.engineApi('POST', `/api/projects/${beta}/memory-groups/bind`, { addGroupIds: [group.id] });
85
+ assert.equal(bind.status, 200);
86
+ await createWithWizard(harness, alpha, group);
87
+
88
+ const betaSettings = workflowApi + `/projects/${beta}/settings`;
89
+ const custom = { autoRecord: false, deliveryChecks: false, reminders: false, checkConfig: { source: 'project' } };
90
+ const saved = await productApi('PUT', betaSettings, { requestId: 'configure-beta', enabled: false, ...custom });
91
+ assert.equal(saved.status, 200);
92
+ const teamControl = `[data-project-team="${beta}"]`;
93
+ const teamTag = `${teamControl} .team-tag`;
94
+ const attach = `${teamControl} [data-action="project-team"]`;
95
+ const openProjects = async () => {
96
+ await harness.nativeClick('nav [data-view="projects"]');
97
+ await harness.waitFor(() => harness.run(`Boolean(document.querySelector(${JSON.stringify(attach)}))`), 'project team controls');
98
+ };
99
+ const assertSettings = async enabled => {
100
+ const { body: { settings } } = await productApi('GET', betaSettings);
101
+ assert.equal(settings.enabled, enabled);
102
+ for (const [key, value] of Object.entries(custom)) assert.deepEqual(settings[key], value, key);
103
+ const separate = await productApi('GET', workflowApi + `/projects/${alpha}/settings`);
104
+ assert.equal(separate.body.settings.enabled, true);
105
+ const groups = await harness.engineApi('GET', `/api/projects/${beta}/memory-groups`);
106
+ assert.ok(groups.body.groups.some(g => g.id === group.id));
107
+ };
108
+
109
+ await openProjects();
110
+ await harness.nativeClick(attach);
111
+ await harness.nativeClick('#appDialogActions button.primary');
112
+ await harness.waitFor(() => harness.run(`document.querySelector(${JSON.stringify(teamTag)})?.textContent.includes(${JSON.stringify(teamName)})`), 'mounted team chip');
113
+ await assertSettings(true);
114
+ await harness.reload();
115
+ await openProjects();
116
+ await harness.nativeClick(`${teamTag} button`);
117
+ await harness.nativeClick('#appDialogActions button.primary');
118
+ await harness.waitFor(() => harness.run(`Boolean(document.querySelector(${JSON.stringify(attach)})) && !document.querySelector(${JSON.stringify(teamTag)})`), 'detached team control');
119
+ await assertSettings(false);
120
+ console.log('project-team-ui-test PASS (wizard, roster, and project mount)');
121
+ } finally { await harness.cleanup(); }
122
+ }
123
+
124
+ main().catch(error => { console.error(error); process.exitCode = 1; });
@@ -0,0 +1,45 @@
1
+ // Run: node _site/_test/recovery-label-contract-test.js
2
+ // 与 retry-scheduler 的调度状态对齐:只有已有下一次自动恢复安排的运行才显示
3
+ // 「自动恢复中」;data-failed(从不安排 nextRetryAt)、无恢复计划、暂停或预算
4
+ // 耗尽显示「需要处理」;配置问题显示「等待配置」。
5
+
6
+ const assert = require('assert');
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+
10
+ const ROOT = path.resolve(__dirname, '..', '..');
11
+ const app = fs.readFileSync(path.join(ROOT, 'ui', 'product.js'), 'utf8');
12
+
13
+ const match = app.match(/const recoveryLabel = (run => \{[\s\S]*?\n \});/);
14
+ assert(match, 'product.js must still define recoveryLabel');
15
+ const recoveryLabel = eval(`(${match[1]})`);
16
+
17
+ const cases = [
18
+ ['data-failed without nextRetryAt reads as needing attention', { state: 'failed', recovery: { kind: 'data-failed', attempts: 1, nextRetryAt: null } }, '需要处理'],
19
+ ['data-failed with explicit budget exhaustion still needs attention', { state: 'failed', recovery: { kind: 'data-failed', attempts: 4, budgetExhaustedAt: '2026-11-13T00:00:00.000Z' } }, '需要处理'],
20
+ ['transient failure with a scheduled retry is auto-recovering', { state: 'failed', recovery: { kind: 'transient', attempts: 1, nextRetryAt: '2026-11-20T00:00:10.000Z' } }, '自动恢复中'],
21
+ ['rate-limit failure with a scheduled retry is auto-recovering', { state: 'failed', recovery: { kind: 'rate-limit', attempts: 2, nextRetryAt: '2026-11-20T00:01:00.000Z' } }, '自动恢复中'],
22
+ ['config-blocked waits for configuration', { state: 'failed', recovery: { kind: 'config-blocked', attempts: 1 } }, '等待配置'],
23
+ ['exhausted budget needs attention even for transient failures', { state: 'failed', recovery: { kind: 'transient', attempts: 3, budgetExhaustedAt: '2026-11-19T00:00:00.000Z' } }, '需要处理'],
24
+ ['paused recovery needs attention', { state: 'failed', recovery: { kind: 'transient', attempts: 1, paused: true } }, '需要处理'],
25
+ ['a failed run with no recovery plan has nothing scheduled', { state: 'failed' }, '需要处理'],
26
+ ['index-pending without a recovery plan is not silently auto-recovering', { state: 'index-pending' }, '需要处理'],
27
+ ['index-pending with a scheduled retry is auto-recovering', { state: 'index-pending', recovery: { kind: 'transient', attempts: 1, nextRetryAt: '2026-11-20T00:00:10.000Z' } }, '自动恢复中'],
28
+ ['succeeded runs carry no recovery label', { state: 'succeeded', recovery: null }, ''],
29
+ ];
30
+ for (const [label, run, expected] of cases) {
31
+ assert.strictEqual(recoveryLabel(run), expected, label);
32
+ }
33
+
34
+ // The needs/recovering filters key off the same label, so a data-failed run
35
+ // must now surface under「需要处理」instead of hiding inside auto-recovery.
36
+ assert(app.includes("state.activityFilter === 'needs' && ['failed', 'index-pending'].includes(r.state) && recoveryLabel(r) !== '自动恢复中'"), 'needs filter still uses recoveryLabel');
37
+ assert(app.includes("state.activityFilter === 'recovering' && recoveryLabel(r) === '自动恢复中'"), 'recovering filter still uses recoveryLabel');
38
+ // attempts are a per-round counter: manual retry resets them.
39
+ assert(app.includes('本轮已尝试'), 'attempt count must be labeled as the current round');
40
+ // The retry entry only acknowledges acceptance; the run state reports outcome.
41
+ assert(app.includes('已提交重试'), 'retry button toast must acknowledge submission, not completion');
42
+ // Evidence failures render their concrete resource.
43
+ assert(app.includes('失败资源:'), 'evidence failures must show the concrete resource');
44
+
45
+ console.log('recovery-label-contract-test PASS');