@sanqianx/project-knowledge 5.1.7 → 5.2.1

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.
@@ -1,97 +1,243 @@
1
1
  'use strict';
2
2
  // project_workflow_* MCP tool contract: the tools are a thin adapter over the
3
- // shell proxy into the workflow module. This suite runs a REAL workflow
4
- // module instance as upstream and verifies start/resume/status/checkpoint and
5
- // the truthful UNSUPPORTED answers for the review pipeline, plus the
6
- // structured degradation when no service is reachable.
3
+ // shell proxy into the workflow module. This suite runs a REAL workflow module
4
+ // instance (installed pinned package by default, an explicit local candidate
5
+ // via KB_WORKFLOW_TEST_SOURCE) and drives a REAL stdio MCP child through
6
+ // initialize → tools/list → tools/call for all six tools, plus the review-job
7
+ // flow and the structured degradation when no service is reachable. Missing
8
+ // module sources FAIL the suite — they are never a silent pass.
7
9
  const assert = require('node:assert/strict');
8
10
  const fs = require('node:fs');
9
11
  const os = require('node:os');
10
12
  const path = require('node:path');
13
+ const { spawn, spawnSync } = require('node:child_process');
11
14
  const { WorkflowToolRuntime } = require('../lib/workflow-tool-runtime');
12
15
 
13
- // Development-machine suite: the upstream is the real workflow module from
14
- // its private source checkout. CI without that checkout gets an explicit,
15
- // logged skip (never a silent pass); once the package publishes (W8) this
16
- // switches to installing the tarball and the suite becomes mandatory.
17
- let createWorkflowServer = null;
18
- try {
19
- createWorkflowServer = require('D:/SanQian.Xu/ai-coding-workflow/src/server').createWorkflowServer;
20
- } catch { /* not present on this machine */ }
21
- if (!createWorkflowServer) {
22
- console.log('workflow-tools-test SKIP: workflow module source not present (dev-machine suite; becomes mandatory after the package publishes in W8)');
23
- process.exit(0);
16
+ const REPO_ROOT = path.resolve(__dirname, '..', '..');
17
+ const CANDIDATE_SOURCE = process.env.KB_WORKFLOW_TEST_SOURCE || '';
18
+
19
+ function resolveWorkflowModule() {
20
+ if (CANDIDATE_SOURCE) {
21
+ const entry = path.resolve(CANDIDATE_SOURCE);
22
+ if (!fs.existsSync(entry)) throw new Error(`workflow-tools-test FAIL: KB_WORKFLOW_TEST_SOURCE points at a missing file: ${entry}`);
23
+ return { createWorkflowServer: require(entry).createWorkflowServer, source: entry };
24
+ }
25
+ try {
26
+ const entry = require.resolve('@sanqianx/ai-coding-workflow/src/server', { paths: [REPO_ROOT] });
27
+ return { createWorkflowServer: require(entry).createWorkflowServer, source: entry };
28
+ } catch (error) {
29
+ throw new Error(`workflow-tools-test FAIL: the pinned @sanqianx/ai-coding-workflow package is not installed and KB_WORKFLOW_TEST_SOURCE is not set (${error.message}).`);
30
+ }
24
31
  }
25
32
 
26
33
  function tempDataDir() { return fs.mkdtempSync(path.join(os.tmpdir(), 'ai-workflow-mcp-')); }
27
34
 
28
- async function withUpstream(fn) {
29
- const runtime = createWorkflowServer({ dataDir: tempDataDir() });
35
+ /**
36
+ * Real workflow module upstream: the resolved module's createWorkflowServer
37
+ * binds an ephemeral loopback port in THIS process (the real-CLI lifecycle
38
+ * gate lives in the workflow repo's own integration suite — that keeps this
39
+ * suite working against the currently pinned installed package too).
40
+ */
41
+ async function startWorkflowModule({ createWorkflowServer, runtimeToken }) {
42
+ const runtime = createWorkflowServer({ dataDir: tempDataDir(), runtimeToken });
30
43
  const bound = await runtime.listen(0);
31
44
  const base = `http://127.0.0.1:${bound.port}`;
32
- // Seed the default team so task creation is allowed.
33
45
  await fetch(`${base}/api/workflow/v1/team`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ requestId: 'mcp-seed' }) });
34
- try { await fn(base); } finally { await runtime.close(); }
46
+ let hasProjectRoots = false;
47
+ try {
48
+ const probe = await fetch(`${base}/api/health`);
49
+ const health = await probe.json();
50
+ hasProjectRoots = Boolean(health.capabilities && health.capabilities.projectRepoBinding);
51
+ } catch { hasProjectRoots = false; }
52
+ return { runtime, base, hasProjectRoots, close: () => runtime.close() };
53
+ }
54
+
55
+ function makeGitRepo(files) {
56
+ const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'wf-mcp-review-'));
57
+ const git = args => { const r = spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8' }); if (r.status !== 0) throw new Error(r.stderr); };
58
+ git(['init', '-b', 'main']); git(['config', 'user.email', 't@t']); git(['config', 'user.name', 't']);
59
+ for (const [name, content] of Object.entries(files)) fs.writeFileSync(path.join(repo, name), content);
60
+ git(['add', '.']); git(['commit', '-m', 'init']);
61
+ return repo;
62
+ }
63
+
64
+ /** Minimal MCP stdio client: newline-delimited JSON-RPC over the child. */
65
+ class McpClient {
66
+ constructor(env) {
67
+ this.child = spawn(process.execPath, [path.join(REPO_ROOT, 'bin', 'project-knowledge-mcp.js')], {
68
+ cwd: REPO_ROOT,
69
+ env: { ...process.env, ...env },
70
+ stdio: ['pipe', 'pipe', 'pipe'],
71
+ windowsHide: true,
72
+ });
73
+ this.nextId = 1;
74
+ this.pending = new Map();
75
+ this.buffer = '';
76
+ this.child.stdout.on('data', data => {
77
+ this.buffer += data.toString('utf8');
78
+ for (;;) {
79
+ const newline = this.buffer.indexOf('\n');
80
+ if (newline < 0) break;
81
+ const line = this.buffer.slice(0, newline).trim();
82
+ this.buffer = this.buffer.slice(newline + 1);
83
+ if (!line) continue;
84
+ let message; try { message = JSON.parse(line); } catch { continue; }
85
+ const pending = this.pending.get(message.id);
86
+ if (pending) { this.pending.delete(message.id); pending(message); }
87
+ }
88
+ });
89
+ this.child.stderr.on('data', () => { /* diagnostics only */ });
90
+ }
91
+ request(method, params) {
92
+ const id = this.nextId++;
93
+ const payload = JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n';
94
+ return new Promise((resolve, reject) => {
95
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`MCP ${method} timed out`)); }, 60_000);
96
+ this.pending.set(id, message => { clearTimeout(timer); resolve(message); });
97
+ this.child.stdin.write(payload);
98
+ });
99
+ }
100
+ async initialize() {
101
+ const reply = await this.request('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'workflow-tools-test', version: '0.0.1' } });
102
+ assert.equal(reply.result.serverInfo.name, 'project-knowledge');
103
+ await this.request('notifications/initialized', {});
104
+ return reply.result;
105
+ }
106
+ async listTools() { return (await this.request('tools/list', {})).result.tools; }
107
+ async callTool(name, args) { return (await this.request('tools/call', { name, arguments: args })).result; }
108
+ close() { try { this.child.kill(); } catch { /* already gone */ } }
35
109
  }
36
110
 
37
111
  (async () => {
38
- await withUpstream(async base => {
39
- const tools = new WorkflowToolRuntime({ workflowUrl: base });
40
-
41
- // start creates a task, binds the declared session, returns the contract.
42
- const started = await tools.start({ title: '修复重复重试', goal: '超时后不得重复提交', acceptance: [{ title: '重试幂等', kind: 'automated' }], client: 'claude', sessionId: 'sess-mcp-1', projectId: 'p1' });
43
- assert.ok(started.taskId.startsWith('task_'));
44
- assert.equal(started.sessionBinding.basis, 'declared');
45
- assert.ok(started.nextStep.includes('checkpoint'));
46
-
47
- // resume answers the short contract with acceptance and remaining.
48
- const resumed = await tools.resume({ taskId: started.taskId });
49
- assert.equal(resumed.title, '修复重复重试');
50
- assert.equal(resumed.acceptance.length, 1);
51
- assert.equal(resumed.remaining[0], '重试幂等');
52
- assert.ok(resumed.acceptanceRevision >= 1);
53
-
54
- // status lists and reads.
55
- const list = await tools.status({ projectId: 'p1' });
56
- assert.equal(list.total, 1);
57
- const one = await tools.status({ taskId: started.taskId });
58
- assert.equal(one.task.taskId, started.taskId);
59
-
60
- // checkpoint candidate does not move nextAction; fact does.
61
- await tools.checkpoint({ taskId: started.taskId, kind: 'candidate', summary: '可能完成', nextAction: '不该出现' });
62
- let task = await tools.status({ taskId: started.taskId });
63
- assert.notEqual(task.task.nextAction, '不该出现');
64
- await tools.checkpoint({ taskId: started.taskId, kind: 'fact', summary: '修复完成', verifiedResults: ['单测通过'], nextAction: '提交审查' });
65
- task = await tools.status({ taskId: started.taskId });
66
- assert.equal(task.task.nextAction, '提交审查');
67
- const resumed2 = await tools.resume({ taskId: started.taskId });
68
- assert.deepEqual(resumed2.verifiedResults, ['单测通过']);
69
-
70
- // request_review now runs the real check pipeline: use a synthetic repo
71
- // with a real eslint violation so the receipt path is exercised (the
72
- // verdict depends only on the synthetic files, never on this machine's
73
- // other state).
74
- const { spawnSync } = require('node:child_process');
75
- const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'wf-mcp-review-'));
76
- const git = args => { const r = spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8' }); if (r.status !== 0) throw new Error(r.stderr); };
77
- git(['init', '-b', 'main']); git(['config', 'user.email', 't@t']); git(['config', 'user.name', 't']);
78
- fs.writeFileSync(path.join(repo, 'package.json'), '{"name":"x","private":true}');
79
- fs.writeFileSync(path.join(repo, 'eslint.config.mjs'), 'export default [{ rules: { complexity: ["error", { max: 1 }] } }];\n');
80
- fs.writeFileSync(path.join(repo, 'violation.js'), 'export function b(x){if(x===1){return 1;}if(x===2){return 2;}if(x===3){return 3;}return 0;}\n');
81
- git(['add', '.']); git(['commit', '-m', 'init']);
82
- const review = await tools.requestReview({ taskId: started.taskId, repoPath: repo, tools: ['eslint'] });
83
- assert.ok(review.receipts.some(r => r.toolId === 'eslint'));
84
- assert.ok(['fail', 'warn', 'error'].includes(review.receipts[0].verdict), `real violation must not pass: ${JSON.stringify(review.receipts[0])}`);
85
- assert.equal(review.decision.delivered, false);
86
- assert.equal(review.modelReview, 'pending-model-review');
87
- const resultRead = await tools.reviewResult({ taskId: started.taskId });
88
- assert.ok(Array.isArray(resultRead.checks) && resultRead.checks.length >= 1, 'review_result reads the recorded checks');
89
- console.log('workflow-tools-test PASS (start/resume/status/checkpoint + real check receipts over a real module instance)');
90
- });
112
+ const { createWorkflowServer, source } = resolveWorkflowModule();
113
+ const runtimeToken = 'test-runtime-token';
114
+ const upstream = await startWorkflowModule({ createWorkflowServer, runtimeToken });
115
+ let repo = null;
116
+ try {
117
+ repo = makeGitRepo({
118
+ 'package.json': '{"name":"x","private":true}',
119
+ 'eslint.config.mjs': 'export default [{ rules: { complexity: ["error", { max: 1 }] } }];\n',
120
+ 'violation.js': 'export function b(x){if(x===1){return 1;}if(x===2){return 2;}if(x===3){return 3;}return 0;}\n',
121
+ });
122
+ // Capability branch: a NEW module exposes the trusted project-roots
123
+ // registry; the pinned installed package may predate it and keeps its
124
+ // own (unbound) behavior — both are real, honestly asserted.
125
+ let boundMode = false;
126
+ if (upstream.hasProjectRoots) {
127
+ const reg = await fetch(`${upstream.base}/api/internal/project-roots`, {
128
+ method: 'POST',
129
+ headers: { 'Content-Type': 'application/json', 'X-KB-Runtime-Token': runtimeToken },
130
+ body: JSON.stringify({ requestId: 'reg-p1', projectId: 'p1', canonicalGitRoot: repo }),
131
+ });
132
+ assert.equal(reg.status, 201, `trusted project-roots registration must succeed: ${JSON.stringify(await reg.json().catch(() => ({})))}`);
133
+ boundMode = true;
134
+ }
135
+
136
+ // ---- Real stdio MCP: initialize → tools/list → tools/call × 6 ----
137
+ const mcp = new McpClient({ KB_WORKFLOW_URL: upstream.base, KB_DATA_DIR: tempDataDir() });
138
+ try {
139
+ await mcp.initialize();
140
+ const tools = await mcp.listTools();
141
+ const workflowTools = tools.filter(t => t.name.startsWith('project_workflow_'));
142
+ assert.equal(workflowTools.length, 6, 'the six workflow tools are exposed');
143
+ const byName = Object.fromEntries(workflowTools.map(t => [t.name, t]));
144
+ assert.ok(byName.project_workflow_request_review.inputSchema.properties.tools, 'request_review declares the tools parameter');
145
+ assert.ok(byName.project_workflow_review_result.inputSchema.properties.reviewJobId, 'review_result declares the optional reviewJobId');
146
+ assert.ok(byName.project_workflow_review_result.inputSchema.properties.waitMs.maximum <= 8000, 'the wait ceiling stays inside the runtime timeout');
147
+
148
+ const started = JSON.parse((await mcp.callTool('project_workflow_start', { title: '修复重复重试', goal: '超时后不得重复提交', acceptance: [{ title: '无违规', kind: 'automated', requiredEvidence: [{ toolId: 'eslint' }] }], client: 'claude', sessionId: 'sess-mcp-1', projectId: 'p1' })).content[0].text);
149
+ assert.ok(started.taskId.startsWith('task_'));
150
+ if (boundMode) assert.equal(started.repoBinding.status, 'bound', 'the task binds the trusted root at creation');
151
+ assert.equal(started.sessionBinding.basis, 'declared');
152
+
153
+ const resumed = JSON.parse((await mcp.callTool('project_workflow_resume', { taskId: started.taskId })).content[0].text);
154
+ assert.equal(resumed.title, '修复重复重试');
155
+ assert.equal(resumed.acceptance.length, 1);
156
+
157
+ const listed = JSON.parse((await mcp.callTool('project_workflow_status', { projectId: 'p1' })).content[0].text);
158
+ assert.equal(listed.total, 1);
159
+
160
+ const checkpointed = JSON.parse((await mcp.callTool('project_workflow_checkpoint', { taskId: started.taskId, kind: 'fact', summary: '修复完成', verifiedResults: ['单测通过'], nextAction: '提交审查' })).content[0].text);
161
+ assert.ok(checkpointed.checkpoint.checkpointId);
162
+
163
+ // request_review: a NEW module reserves a job and answers with the
164
+ // reviewJobId; the pinned old module answers with legacy receipts.
165
+ // Over the installed package eslint is absent — 'missing' never passes.
166
+ const review = JSON.parse((await mcp.callTool('project_workflow_request_review', { taskId: started.taskId, repoPath: repo, tools: ['eslint'], note: '第一轮检查' })).content[0].text);
167
+ assert.ok(['completed', 'running', 'legacy-sync'].includes(review.reviewStatus), `honest review status: ${JSON.stringify(review).slice(0, 300)}`);
168
+ if (review.reviewStatus === 'legacy-sync') {
169
+ assert.ok(Array.isArray(review.receipts) && review.receipts.length >= 1, 'the old module still answers with receipts');
170
+ assert.notEqual(review.receipts[0].verdict, 'pass');
171
+ } else {
172
+ assert.ok(review.reviewJobId, 'the review answer carries the job id');
173
+ if (review.reviewStatus === 'completed') {
174
+ assert.equal(review.receipts[0].toolId, 'eslint');
175
+ assert.notEqual(review.receipts[0].verdict, 'pass', 'missing tool never passes');
176
+ } else {
177
+ assert.equal(review.pending, true);
178
+ }
179
+ const resultRead = JSON.parse((await mcp.callTool('project_workflow_review_result', { taskId: started.taskId, reviewJobId: review.reviewJobId, waitMs: 8000 })).content[0].text);
180
+ assert.equal(resultRead.reviewJobId, review.reviewJobId);
181
+ assert.ok(['completed', 'running', 'failed', 'stale'].includes(resultRead.reviewStatus));
182
+ assert.ok(Array.isArray(resultRead.acceptance));
183
+ }
184
+ } finally { mcp.close(); }
185
+
186
+ // ---------- P1b: real model-phase projection + job/task attribution ----------
187
+ if (upstream.hasProjectRoots) {
188
+ const runtime = new (require('../lib/workflow-tool-runtime').WorkflowToolRuntime)({ workflowUrl: upstream.base });
189
+ // A model-required task with no reviewer config must answer the honest
190
+ // blocked projection, never 'pending-model-review'.
191
+ const modelTask = (await runtime.request('workflow-tasks', { method: 'POST', body: {
192
+ requestId: 'p1b-t1', projectId: 'p1', title: 'P1b 模型审查任务',
193
+ acceptance: [{ title: '独立 Review', kind: 'model_review' }],
194
+ } })).task;
195
+ const otherTask = (await runtime.request('workflow-tasks', { method: 'POST', body: {
196
+ requestId: 'p1b-t2', projectId: 'p1', title: 'P1b 另一任务',
197
+ acceptance: [{ title: '独立 Review', kind: 'model_review' }],
198
+ } })).task;
199
+ const reviewA = await runtime.requestReview({ taskId: modelTask.taskId, repoPath: repo, tools: ['eslint'], requestId: 'p1b-rv1' });
200
+ if (reviewA.reviewJobId) {
201
+ const deadline = Date.now() + 60_000;
202
+ let answer = reviewA;
203
+ while (Date.now() < deadline && answer.pending) {
204
+ await new Promise(r => setTimeout(r, 500));
205
+ answer = await runtime.reviewResult({ taskId: modelTask.taskId, reviewJobId: reviewA.reviewJobId, waitMs: 0 });
206
+ }
207
+ assert.equal(answer.overallStatus, 'blocked-missing-config', `P1b: honest projection, got ${answer.overallStatus}`);
208
+ assert.equal(answer.modelReview.status, 'blocked-missing-config');
209
+ assert.equal(answer.pending, false);
210
+ // An explicit job of ANOTHER task must be rejected, never served.
211
+ let mismatch = null;
212
+ try { await runtime.reviewResult({ taskId: otherTask.taskId, reviewJobId: reviewA.reviewJobId, waitMs: 0 }); }
213
+ catch (error) { mismatch = error; }
214
+ assert.ok(mismatch && /属于任务/.test(mismatch.message), 'P1b: cross-task job rejected');
215
+ // A second round makes the first job historical; review_result marks it.
216
+ const reviewB = await runtime.requestReview({ taskId: modelTask.taskId, repoPath: repo, tools: ['eslint'], requestId: 'p1b-rv2' });
217
+ if (reviewB.reviewJobId) {
218
+ const hist = await runtime.reviewResult({ taskId: modelTask.taskId, reviewJobId: reviewA.reviewJobId, waitMs: 0 });
219
+ assert.equal(hist.historical, true, 'P1b: superseded job reads as history');
220
+ assert.match(hist.note || '', /历史/);
221
+ }
222
+ }
223
+ console.log('workflow-tools-test PASS (P1b: model-phase projection, cross-task job rejection, historical marking)');
224
+ }
225
+
226
+ console.log(`workflow-tools-test PASS (real stdio MCP over a real workflow module [${boundMode ? 'job+binding' : 'legacy'} mode]: 6 tools, review flow)`);
227
+ } finally {
228
+ await upstream.close();
229
+ }
91
230
 
92
231
  // Degradation: no live shell, no explicit URL -> structured WORKFLOW_UNAVAILABLE.
93
232
  const offline = new WorkflowToolRuntime({ workflowUrl: 'http://127.0.0.1:9' });
94
233
  try { await offline.status({}); throw new Error('offline status should fail'); }
95
234
  catch (error) { assert.equal(error.code, 'WORKFLOW_UNAVAILABLE'); }
235
+ const offlineMcp = new McpClient({ KB_DATA_DIR: tempDataDir() });
236
+ try {
237
+ await offlineMcp.initialize();
238
+ const offlineCall = await offlineMcp.callTool('project_workflow_status', {});
239
+ assert.equal(offlineCall.isError, true, 'an unreachable module is a structured tool error');
240
+ assert.match(offlineCall.content[0].text, /WORKFLOW_UNAVAILABLE/);
241
+ } finally { offlineMcp.close(); }
96
242
  console.log('workflow-tools-test PASS (structured degradation when unreachable)');
97
243
  })().catch(error => { console.error(error); process.exitCode = 1; });
@@ -79,6 +79,9 @@ const ERROR_CODES = Object.freeze([
79
79
  'ENGINE_INVALID_RESPONSE',
80
80
  'ENGINE_REQUEST_FAILED',
81
81
  'ENGINE_URL_INVALID',
82
+ // Workflow module (fifth module) tool surface — additive M0-C.
83
+ 'WORKFLOW_UNAVAILABLE',
84
+ 'WORKFLOW_HTTP_ERROR',
82
85
  ]);
83
86
 
84
87
  const IMMUTABLE_PROJECT_FIELDS = Object.freeze([
@@ -148,6 +148,10 @@ class ModuleBridge {
148
148
  };
149
149
  this.moduleUrlSources = { terminal: 'pending', vectorHub: 'pending', eventBridge: 'pending', engine: 'pending', workflow: 'pending' };
150
150
  this.runtimeToken = options.runtimeToken || crypto.randomBytes(32).toString('hex');
151
+ // M0-C: read-only registration resolver (knowledge runtime) — the shell
152
+ // uses it AFTER its own safety checks to attach the canonical Git root
153
+ // to trusted review forwards. Client tokens never become module trust.
154
+ this.workflowProjectResolver = typeof options.workflowProjectResolver === 'function' ? options.workflowProjectResolver : null;
151
155
  this.registryStore = options.registryStore || null;
152
156
  this.projectStore = options.projectStore || null;
153
157
  this.projectWiringQueue = new Map();
@@ -191,10 +195,15 @@ class ModuleBridge {
191
195
  }
192
196
 
193
197
  /** Same-origin proxy. SSE has a headers deadline, never a whole-turn deadline. */
194
- async proxy(req, res, target) {
198
+ async proxy(req, res, target, { bodyOverride, extraHeaders } = {}) {
195
199
  const chunks = [];
196
- for await (const chunk of req) chunks.push(chunk);
197
- const body = chunks.length ? Buffer.concat(chunks) : undefined;
200
+ if (bodyOverride !== undefined) {
201
+ // A prepared body (trusted review forward): the incoming request was
202
+ // already read; forward the rewritten payload instead of the raw one.
203
+ } else {
204
+ for await (const chunk of req) chunks.push(chunk);
205
+ }
206
+ const body = bodyOverride !== undefined ? bodyOverride : (chunks.length ? Buffer.concat(chunks) : undefined);
198
207
  // The native folder pickers hold the request open until the user closes
199
208
  // the dialog — they need a human-scale budget, not the API budget.
200
209
  const isPicker = /\/(system\/)?pick-folder/.test(target);
@@ -213,7 +222,11 @@ class ModuleBridge {
213
222
  upstream = await fetch(target, {
214
223
  method: req.method,
215
224
  signal: controller.signal,
216
- headers: { ...(body ? { 'Content-Type': req.headers['content-type'] || 'application/json' } : {}), ...(req.headers['last-event-id'] ? { 'Last-Event-ID': req.headers['last-event-id'] } : {}) },
225
+ headers: {
226
+ ...(body ? { 'Content-Type': req.headers['content-type'] || 'application/json' } : {}),
227
+ ...(req.headers['last-event-id'] ? { 'Last-Event-ID': req.headers['last-event-id'] } : {}),
228
+ ...(extraHeaders || {}),
229
+ },
217
230
  body: ['GET', 'HEAD'].includes(req.method) ? undefined : body,
218
231
  });
219
232
  } catch (error) {
@@ -264,9 +277,77 @@ class ModuleBridge {
264
277
  }
265
278
 
266
279
  proxyWorkflow(req, res, pathname, search) {
280
+ // M0-C: the reviews subroute is forwarded as a TRUSTED internal call —
281
+ // the shell resolves the registered project after its own safety checks
282
+ // and attaches its private runtime token plus the canonical Git root.
283
+ // A client's own token header is never forwarded as module trust; the
284
+ // generic proxy shape (headers passthrough) stays untouched otherwise.
285
+ if (req.method === 'POST' && /^\/api\/workflow\/workflow-tasks\/[^/]+\/reviews\/?$/.test(pathname)) {
286
+ return this._proxyWorkflowReviewTrusted(req, res, pathname, search);
287
+ }
288
+ // P2b: a team-mode task creation is trusted-forwarded the same way — the
289
+ // shell injects its runtime token ONLY when the body's project/repoPath
290
+ // resolves to a REGISTERED project; the workflow module strips
291
+ // executionMode from anything arriving without the token, so browsers
292
+ // cannot arm team execution no matter what they POST.
293
+ if (req.method === 'POST' && /^\/api\/workflow\/workflow-tasks\/?$/.test(pathname)) {
294
+ return this._proxyWorkflowTeamCreateTrusted(req, res, pathname, search);
295
+ }
267
296
  return this.proxy(req, res, this._workflowApi(pathname) + (search || ''));
268
297
  }
269
298
 
299
+ async _proxyWorkflowTeamCreateTrusted(req, res, pathname, search) {
300
+ const chunks = [];
301
+ for await (const chunk of req) chunks.push(chunk);
302
+ let body = {};
303
+ try { body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}; } catch {
304
+ throw new DomainError('VALIDATION', '请求体必须是合法 JSON。', { status: 400 });
305
+ }
306
+ let forward = { ...body };
307
+ let token = null;
308
+ // Trust is earned by RESOLUTION: only a body whose project/repoPath maps
309
+ // to a registered project gets the runtime token attached. Everything
310
+ // else is proxied verbatim WITHOUT the token (the module degrades it).
311
+ if (body.executionMode === 'team' && this.workflowProjectResolver) {
312
+ try {
313
+ const project = this.workflowProjectResolver({ projectId: body.projectId, repoPath: body.repoPath });
314
+ if (project && project.projectId) {
315
+ forward.projectId = project.projectId;
316
+ forward.canonicalGitRoot = project.repoPath;
317
+ if (this.runtimeToken) token = this.runtimeToken;
318
+ }
319
+ } catch { /* unresolved: forward as-is, module degrades to plain task */ }
320
+ }
321
+ return this.proxy(req, res, this._workflowApi(pathname) + (search || ''), {
322
+ bodyOverride: Buffer.from(JSON.stringify(forward), 'utf8'),
323
+ extraHeaders: token ? { 'X-KB-Runtime-Token': token } : {},
324
+ });
325
+ }
326
+
327
+ async _proxyWorkflowReviewTrusted(req, res, pathname, search) {
328
+ const chunks = [];
329
+ for await (const chunk of req) chunks.push(chunk);
330
+ let body = {};
331
+ try { body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}; } catch {
332
+ throw new DomainError('VALIDATION', 'Review 请求体必须是合法 JSON。', { status: 400 });
333
+ }
334
+ const forward = { ...body };
335
+ if (this.workflowProjectResolver && (forward.projectId || forward.repoPath)) {
336
+ try {
337
+ const project = this.workflowProjectResolver({ projectId: forward.projectId, repoPath: forward.repoPath });
338
+ if (project && project.projectId) {
339
+ forward.projectId = project.projectId;
340
+ forward.canonicalGitRoot = project.repoPath;
341
+ }
342
+ } catch { /* an unresolvable project forwards as-is; the workflow module keeps its own binding gate */ }
343
+ }
344
+ const extraHeaders = forward.canonicalGitRoot && this.runtimeToken ? { 'X-KB-Runtime-Token': this.runtimeToken } : {};
345
+ return this.proxy(req, res, this._workflowApi(pathname) + (search || ''), {
346
+ bodyOverride: Buffer.from(JSON.stringify(forward), 'utf8'),
347
+ extraHeaders,
348
+ });
349
+ }
350
+
270
351
  proxyEngine(req, res, pathname, search) {
271
352
  if (this.engineCompatible === false) throw new DomainError('ENGINE_CONNECTION_PENDING', '知识引擎连接尚未确认,请查看系统状态;不会读取旧服务中的知识。', { status: 503 });
272
353
  return this.proxy(req, res, `${this.engineUrl}/api/${pathname.replace(/^\/api\/engine\/?/, '')}${search || ''}`);
@@ -827,7 +908,7 @@ class ModuleBridge {
827
908
  name: 'workflow',
828
909
  command: process.env.KB_WORKFLOW_COMMAND || `node ${JSON.stringify(workflowEntry)} serve --port ${urlPort(this.workflowUrl, 5810)} --host ${urlHost(this.workflowUrl)} --data ${JSON.stringify(this.dataDir || require('./data-dir').getDataDir())}`,
829
910
  url: this.workflowUrl,
830
- env: { KB_WORKFLOW_MANAGED: '1', KB_WORKFLOW_RUNTIME_TOKEN: this.runtimeToken },
911
+ env: { KB_WORKFLOW_MANAGED: '1', KB_WORKFLOW_RUNTIME_TOKEN: this.runtimeToken, KB_EVENT_BRIDGE_URL: this.eventBridgeUrl },
831
912
  });
832
913
  } else {
833
914
  this.logger.warn('modules.supervisor', '@sanqianx/ai-coding-workflow runtime not installed; team features report "not installed".', {});
@@ -514,7 +514,12 @@ function createRuntime(options = {}) {
514
514
  isProjectBusy: projectId => isProjectBusy(projectId, projectStore, activeTasks),
515
515
  bridgeAdapter,
516
516
  });
517
- const moduleBridge = options.moduleBridge || new ModuleBridge({ registryStore, projectStore, settingsStore, logger, dataDir: dataPath });
517
+ const moduleBridge = options.moduleBridge || new ModuleBridge({
518
+ registryStore, projectStore, settingsStore, logger, dataDir: dataPath,
519
+ // M0-C: trusted review forwards resolve the registered project through
520
+ // the same read-only resolution the knowledge tools use.
521
+ workflowProjectResolver: input => knowledgeRuntime.resolveProject(input),
522
+ });
518
523
  return {
519
524
  analysisOwner: options.analysisOwner || 'legacy', ownership: { owner: options.analysisOwner || 'legacy', ready: false },
520
525
  rootDir, dataPath, layout, settingsStore, registryStore, projectStore, logger, logRepository,