@sanqianx/project-knowledge 5.1.7 → 5.2.0

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.
@@ -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,
@@ -4,12 +4,25 @@
4
4
  // thin adapter over the shell's /api/workflow/* proxy into the independent
5
5
  // workflow module — no task state is stored here (runbook §2.3: the tools
6
6
  // call the workflow master store, never a second copy).
7
+ //
8
+ // M0-C: project registration is reused from the knowledge runtime, so tasks
9
+ // resolve to a registered projectId + canonical repo path instead of a
10
+ // silent 'unknown-project'. The review pipeline is job-based: request_review
11
+ // reserves a job (202) and polls it with a bounded wait; review_result reads
12
+ // a persisted job by reviewJobId (or the task's latest) — a slow check
13
+ // answers honestly "pending" instead of blocking the MCP call.
7
14
 
8
15
  const path = require('path');
16
+ const { DomainError } = require('./contracts');
9
17
  const endpoint = require('./runtime-endpoint');
10
18
  const { getDataDir } = require('./data-dir');
11
19
 
12
20
  const DEFAULT_TIMEOUT_MS = 15000;
21
+ // A single MCP tool call must stay inside the 15s runtime timeout, so the
22
+ // bounded wait never exceeds 8s (M1-B ceiling). Slow checks keep running
23
+ // server-side; review_result picks the same reviewJobId up later.
24
+ const MAX_WAIT_MS = 8000;
25
+ const POLL_INTERVAL_MS = 250;
13
26
 
14
27
  class WorkflowToolRuntime {
15
28
  constructor(options = {}) {
@@ -17,6 +30,11 @@ class WorkflowToolRuntime {
17
30
  this.workflowUrl = options.workflowUrl || process.env.KB_WORKFLOW_URL || null;
18
31
  this.fetchImpl = options.fetchImpl || fetch;
19
32
  this.timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
33
+ // Registration resolver reused from the knowledge runtime (read-only).
34
+ // Absent (unit tests, standalone use) → explicit projectId or the
35
+ // historical 'unknown-project' fallback; present → resolution failure is
36
+ // a structured error, never a silent unknown project.
37
+ this.resolveProject = typeof options.resolveProject === 'function' ? options.resolveProject : null;
20
38
  }
21
39
 
22
40
  /** Prefer an explicit module URL; else the live shell's proxy base. */
@@ -33,10 +51,7 @@ class WorkflowToolRuntime {
33
51
  async request(apiPath, { method = 'GET', body } = {}) {
34
52
  const resolved = this.resolveBase();
35
53
  if (!resolved) {
36
- const error = new Error('WORKFLOW_UNAVAILABLE');
37
- error.code = 'WORKFLOW_UNAVAILABLE';
38
- error.message = '工作流服务不可达:未设置 KB_WORKFLOW_URL,且没有运行中的知识库实例。任务与知识检索不受影响。';
39
- throw error;
54
+ throw new DomainError('WORKFLOW_UNAVAILABLE', '工作流服务不可达:未设置 KB_WORKFLOW_URL,且没有运行中的知识库实例。任务与知识检索不受影响。', { status: 503, retryable: true });
40
55
  }
41
56
  const url = `${resolved.base}${resolved.prefix}/${apiPath.replace(/^\/+/, '')}`;
42
57
  const controller = new AbortController();
@@ -50,36 +65,52 @@ class WorkflowToolRuntime {
50
65
  });
51
66
  const json = await response.json().catch(() => ({}));
52
67
  if (!response.ok) {
53
- const error = new Error(json.message || `HTTP ${response.status}`);
54
- error.code = json.error || 'WORKFLOW_HTTP_ERROR';
55
- error.status = response.status;
56
- error.details = json.details || {};
57
- throw error;
68
+ throw new DomainError(json.error && typeof json.error === 'string' ? json.error : 'WORKFLOW_HTTP_ERROR', json.message || `HTTP ${response.status}`, { status: response.status, details: json.details || {}, retryable: response.status >= 500 });
58
69
  }
59
70
  return json;
60
71
  } catch (inner) {
61
- if (inner.code) throw inner;
62
- const error = new Error('工作流服务不可达;原生开发可以继续,页面会显示降级状态。');
63
- error.code = 'WORKFLOW_UNAVAILABLE';
64
- throw error;
72
+ if (inner instanceof DomainError) throw inner;
73
+ throw new DomainError('WORKFLOW_UNAVAILABLE', '工作流服务不可达;原生开发可以继续,页面会显示降级状态。', { status: 503, retryable: true, cause: inner });
65
74
  } finally { clearTimeout(timer); }
66
75
  }
67
76
 
77
+ /** Resolve the registered project for this call; null when no resolver. */
78
+ _resolveRegisteredProject(args, { required = false } = {}) {
79
+ if (!this.resolveProject) return null;
80
+ try {
81
+ return this.resolveProject({ projectId: args.projectId, repoPath: args.repoPath });
82
+ } catch (error) {
83
+ if (args.projectId) return null; // an explicit projectId stands as declared; the module verifies the binding
84
+ if (!required) return null; // read/forward paths proceed; the module's binding gate decides
85
+ throw new DomainError('INVALID_ARGUMENT', `PROJECT_NOT_RESOLVED:${error.message || '未找到与当前 Git 根匹配的登记项目'};请显式传 projectId 或先调用 project_knowledge_resolve。`, { details: { reason: 'project-not-resolved' } });
86
+ }
87
+ }
88
+
68
89
  /**
69
90
  * start: create the business task, bind the calling session (declared
70
91
  * basis — the Bridge consumer's captured sessionId drives observation, not
71
- * acceptance), and return the short task contract.
92
+ * acceptance), and return the short task contract. The repo binding is
93
+ * verified server-side from the trusted project mapping; repoPath here is
94
+ * only a match hint.
72
95
  */
73
96
  async start(args) {
74
97
  const title = String(args.title || '').trim();
75
- if (!title) { const e = new Error('title is required'); e.code = 'VALIDATION'; throw e; }
98
+ if (!title) throw new DomainError('INVALID_ARGUMENT', 'title is required.', { details: { tool: 'project_workflow_start' } });
99
+ const resolved = this._resolveRegisteredProject(args);
100
+ let projectId = args.projectId ? String(args.projectId) : (resolved && resolved.projectId) || null;
101
+ if (!projectId && this.resolveProject) {
102
+ throw new DomainError('INVALID_ARGUMENT', 'PROJECT_NOT_RESOLVED:未找到与当前 Git 根匹配的登记项目;请显式传 projectId 或先调用 project_knowledge_resolve。', { details: { reason: 'project-not-resolved' } });
103
+ }
104
+ if (!projectId) projectId = 'unknown-project'; // no resolver wired (standalone/test) — the module keeps the task honestly unbound
76
105
  const payload = {
77
- requestId: `mcp-start-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
78
- projectId: args.projectId || 'unknown-project',
106
+ requestId: args.requestId || `mcp-start-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
107
+ projectId,
79
108
  title,
80
109
  goal: args.goal || null,
81
110
  acceptance: Array.isArray(args.acceptance) ? args.acceptance : undefined,
82
111
  ownerMemberId: args.memberId || null,
112
+ repoPath: args.repoPath || (resolved && resolved.repoPath) || undefined,
113
+ executionMode: args.executionMode === 'team' ? 'team' : undefined,
83
114
  };
84
115
  const created = await this.request('workflow-tasks', { method: 'POST', body: payload });
85
116
  const taskId = created.task.taskId;
@@ -89,7 +120,7 @@ class WorkflowToolRuntime {
89
120
  requestId: `mcp-bind-${payload.requestId}`,
90
121
  client: String(args.client),
91
122
  nativeSessionId: String(args.sessionId),
92
- workspaceIdentity: args.workspaceIdentity || args.repoPath || process.cwd(),
123
+ workspaceIdentity: args.workspaceIdentity || payload.repoPath || process.cwd(),
93
124
  memberId: args.memberId || null,
94
125
  verificationBasis: 'declared',
95
126
  };
@@ -100,14 +131,19 @@ class WorkflowToolRuntime {
100
131
  ok: true,
101
132
  taskId,
102
133
  task: created.task,
134
+ repoBinding: created.task.repoBinding || { status: 'unbound' },
103
135
  sessionBinding: binding ? { bindingId: binding.binding.bindingId, basis: 'declared' } : null,
104
- nextStep: '实现需求;完成后用 project_workflow_checkpoint 记录事实,再 request_review(交付检查在后续版本接入)。',
136
+ nextStep: args.executionMode === 'team'
137
+ ? '团队任务已激活(taskId 已返回):服务端按项目团队配置推进计划、执行与独立审查;用 resume/status 读取进展。'
138
+ : '实现需求;完成后用 project_workflow_checkpoint 记录事实,再 request_review 并用 review_result 读取证据。',
139
+ ...(created.task.executionMode === 'team' ? { teamActivated: true, planStatus: created.task.planStatus } : {}),
140
+ ...(args.executionMode === 'team' && created.task.executionMode !== 'team' ? { degraded: true, degradedReason: '团队模式未生效:请求未通过受信通道(项目未登记/未开启 autoDispatch 的模块会降级为普通任务)。' } : {}),
105
141
  note: '会话绑定当前为声明级:事件观察按采集会话归因,验收始终由服务端裁决。',
106
142
  };
107
143
  }
108
144
 
109
145
  async resume(args) {
110
- if (!args.taskId) { const e = new Error('taskId is required'); e.code = 'VALIDATION'; throw e; }
146
+ if (!args.taskId) throw new DomainError('INVALID_ARGUMENT', 'taskId is required.', { details: { tool: 'project_workflow_*' } });
111
147
  const result = await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}`);
112
148
  const task = result.task;
113
149
  const checkpoints = task.checkpoints || [];
@@ -126,11 +162,21 @@ class WorkflowToolRuntime {
126
162
  remaining: latest ? latest.remaining : task.acceptance.filter(a => a.status === 'pending').map(a => a.title),
127
163
  nextAction: task.nextAction,
128
164
  revision: task.revision,
165
+ ...(task.teamPlan ? { team: {
166
+ planStatus: task.planStatus,
167
+ leaderMemberId: task.teamPlan.leaderMemberId,
168
+ current: (() => { const items = task.teamPlan.items || []; const ip = items.find(i => i.status === 'in_progress'); const rd = items.find(i => i.status === 'ready'); const cur = ip || rd || null; return cur ? { id: cur.id, goal: cur.goal, executorMemberId: cur.executorMemberId, status: cur.status, claimedBy: cur.claimedBy || null } : null; })(),
169
+ progress: { delivered: (task.teamPlan.items || []).filter(i => ['delivered', 'verified'].includes(i.status)).length, total: (task.teamPlan.items || []).length },
170
+ items: (task.teamPlan.items || []).map(i => ({ id: i.id, status: i.status, dependsOn: i.dependsOn })),
171
+ } } : {}),
129
172
  };
130
173
  }
131
174
 
132
175
  async status(args) {
133
- if (args.taskId) return { ok: true, task: (await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}`)).task };
176
+ if (args.taskId) {
177
+ const t = (await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}`)).task;
178
+ return { ok: true, task: t, ...(t.teamPlan ? { team: { planStatus: t.planStatus, items: (t.teamPlan.items || []).map(i => ({ id: i.id, status: i.status, executorMemberId: i.executorMemberId })) } } : {}) };
179
+ }
134
180
  const query = new URLSearchParams();
135
181
  if (args.projectId) query.set('projectId', args.projectId);
136
182
  if (args.status) query.set('status', args.status);
@@ -139,7 +185,7 @@ class WorkflowToolRuntime {
139
185
  }
140
186
 
141
187
  async checkpoint(args) {
142
- if (!args.taskId) { const e = new Error('taskId is required'); e.code = 'VALIDATION'; throw e; }
188
+ if (!args.taskId) throw new DomainError('INVALID_ARGUMENT', 'taskId is required.', { details: { tool: 'project_workflow_*' } });
143
189
  const payload = {
144
190
  requestId: `mcp-ckpt-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
145
191
  kind: args.kind === 'fact' ? 'fact' : 'candidate',
@@ -154,32 +200,174 @@ class WorkflowToolRuntime {
154
200
  return { ok: true, checkpoint: result.checkpoint };
155
201
  }
156
202
 
203
+ async _readReviewJob(reviewJobId) {
204
+ return this.request(`review-jobs/${encodeURIComponent(reviewJobId)}`);
205
+ }
206
+
207
+ /** Bounded job wait — never exceeds MAX_WAIT_MS, honest pending afterwards. */
208
+ async _awaitJob(reviewJobId, waitMs) {
209
+ const deadline = Date.now() + Math.max(0, Math.min(Number(waitMs) || 0, MAX_WAIT_MS));
210
+ let payload;
211
+ for (;;) {
212
+ payload = await this._readReviewJob(reviewJobId);
213
+ const overall = payload.job && payload.job.overallStatus;
214
+ // P1b: wait on the WHOLE review (checks + model), not just job.status —
215
+ // 'completed' with a pending model phase is still worth polling.
216
+ const settled = overall ? ['review-complete', 'failed', 'stale', 'review-blocked', 'blocked-missing-config'].includes(overall)
217
+ : ['completed', 'failed', 'stale'].includes(payload.job.status);
218
+ if (settled) return payload;
219
+ if (Date.now() >= deadline) return payload;
220
+ await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS));
221
+ }
222
+ }
223
+
224
+ _reviewAnswer(args, payload) {
225
+ const job = payload.job || {};
226
+ const overall = job.overallStatus || job.status;
227
+ const finished = ['completed', 'failed', 'stale'].includes(job.status);
228
+ const settled = ['review-complete', 'failed', 'stale', 'review-blocked', 'blocked-missing-config'].includes(overall);
229
+ const answer = {
230
+ ok: true,
231
+ taskId: args.taskId,
232
+ reviewJobId: job.reviewJobId,
233
+ reviewStatus: job.status,
234
+ overallStatus: overall || null,
235
+ modelRequired: job.modelRequired === true,
236
+ modelState: job.modelState || null,
237
+ pending: !settled,
238
+ snapshotId: job.snapshotId || null,
239
+ acceptanceRevision: job.acceptanceRevision ?? null,
240
+ };
241
+ // P1b: the REAL model phase, never a hard-coded string. Old modules
242
+ // without the projection degrade to 'pending-model-review'.
243
+ const mr = job.modelReview || null;
244
+ if (mr) {
245
+ answer.modelReview = {
246
+ status: mr.status,
247
+ identity: mr.identity || null,
248
+ identityVerified: Boolean(mr.identityVerified),
249
+ blockedReason: mr.blockedReason || null,
250
+ summary: mr.summary || null,
251
+ findings: (mr.findings || []).slice(0, 50),
252
+ };
253
+ } else {
254
+ answer.modelReview = job.modelRequired ? { status: job.modelState || 'pending', identity: null, identityVerified: false, blockedReason: null, summary: null, findings: [] } : 'not-required';
255
+ }
256
+ if (settled && overall === 'review-complete') {
257
+ answer.snapshot = { snapshotId: job.snapshotId, fileCount: job.fileCount };
258
+ answer.receipts = payload.receipts || [];
259
+ answer.decision = job.decision || null;
260
+ answer.note = '程序检查与模型审查(如要求)均完成;自动验收由服务端依据收据与已核实模型意见裁决。';
261
+ } else if (settled && overall === 'review-blocked') {
262
+ answer.error = (mr && mr.blockedReason) || job.error || null;
263
+ answer.note = `模型审查阻塞:${answer.error || '见 modelReview 详情'}。处理后重新 request_review。`;
264
+ } else if (settled && overall === 'blocked-missing-config') {
265
+ answer.error = 'REVIEWER_CONFIG_MISSING';
266
+ answer.note = '本轮要求模型审查但服务端未配置受信 Reviewer(/api/internal/reviewer-config)。程序收据已记录;配置后重新 request_review。';
267
+ } else if (finished) {
268
+ answer.error = job.error || null;
269
+ answer.note = `审查作业 ${job.status}:${job.error || '保留诊断;处理后重新 request_review。'}`;
270
+ } else {
271
+ answer.note = overall === 'awaiting-model' || overall === 'awaiting-model-config'
272
+ ? `程序检查已完成,模型审查进行中(等待上限 ${MAX_WAIT_MS}ms 已到):稍后用 project_workflow_review_result 读取同一 reviewJobId。`
273
+ : `审查仍在运行(本次等待上限 ${MAX_WAIT_MS}ms 已到):稍后用 project_workflow_review_result 读取同一 reviewJobId。`;
274
+ }
275
+ if (payload.task) {
276
+ // P1b: attribute carefully — the TASK-level rework list may be newer
277
+ // than this job; surface it read-only with the job's own phase.
278
+ answer.task = { status: payload.task.status, phase: payload.task.phase, nextAction: payload.task.nextAction, reworkItems: (payload.task.reworkItems || []).slice(0, 50) };
279
+ answer.decision = answer.decision || (job.decision || null);
280
+ }
281
+ return answer;
282
+ }
283
+
157
284
  async requestReview(args) {
158
- if (!args.taskId) { const e = new Error('taskId is required'); e.code = 'VALIDATION'; throw e; }
159
- // W5: submit the current snapshot to the deterministic check pipeline.
160
- // Receipt verdicts drive automated acceptance server-side; the model
161
- // review stage is reported honestly as pending.
162
- const result = await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}/reviews`, { method: 'POST', body: {
163
- requestId: `mcp-review-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
164
- repoPath: args.repoPath || undefined,
285
+ if (!args.taskId) throw new DomainError('INVALID_ARGUMENT', 'taskId is required.', { details: { tool: 'project_workflow_*' } });
286
+ const resolved = this._resolveRegisteredProject(args);
287
+ const body = {
288
+ requestId: args.requestId || `mcp-review-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
289
+ repoPath: args.repoPath || (resolved && resolved.repoPath) || undefined,
290
+ projectId: (resolved && resolved.projectId) || args.projectId || undefined,
165
291
  tools: Array.isArray(args.tools) ? args.tools : undefined,
166
- } });
167
- return {
168
- ok: true,
169
- snapshot: result.snapshot,
170
- receipts: result.receipts,
171
- decision: result.decision,
172
- modelReview: result.modelReview,
173
- note: '程序检查收据已记录;自动验收由服务端依据收据裁决。模型审查阶段当前为 pending(编排交付前不虚构意见)。',
292
+ included: Array.isArray(args.included) ? args.included.map(String) : undefined,
293
+ note: args.note || undefined,
174
294
  };
295
+ const submitted = await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}/reviews`, { method: 'POST', body });
296
+ if (!submitted.reviewJobId) {
297
+ // Old workflow module (pre-review-jobs): the POST answered with the
298
+ // full receipt payload — pass it through as the honest degradation.
299
+ return {
300
+ ok: true,
301
+ taskId: args.taskId,
302
+ reviewStatus: 'legacy-sync',
303
+ pending: false,
304
+ snapshot: submitted.snapshot,
305
+ receipts: submitted.receipts,
306
+ decision: submitted.decision,
307
+ modelReview: submitted.modelReview || 'pending-model-review',
308
+ note: '旧版工作流模块(无 review 作业):已按同步检查结果返回;升级后 review_result 支持 reviewJobId 与有界等待。',
309
+ };
310
+ }
311
+ const payload = await this._awaitJob(submitted.reviewJobId, args.waitMs ?? MAX_WAIT_MS);
312
+ return this._reviewAnswer(args, payload);
175
313
  }
176
314
 
177
315
  async reviewResult(args) {
178
- if (!args.taskId) { const e = new Error('taskId is required'); e.code = 'VALIDATION'; throw e; }
179
- const task = (await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}`)).task;
316
+ if (!args.taskId) throw new DomainError('INVALID_ARGUMENT', 'taskId is required.', { details: { tool: 'project_workflow_*' } });
317
+ const waitMs = Math.min(Math.max(Number(args.waitMs) || 0, 0), MAX_WAIT_MS);
318
+ let reviewJobId = args.reviewJobId ? String(args.reviewJobId) : null;
319
+ let historical = false;
320
+ if (!reviewJobId) {
321
+ const task = (await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}`)).task;
322
+ const jobIds = task.reviewJobIds || [];
323
+ if (!jobIds.length) return this._legacyReviewResult(task);
324
+ reviewJobId = jobIds[jobIds.length - 1];
325
+ }
326
+ const payload = await this._awaitJob(reviewJobId, waitMs);
327
+ const job = payload.job || {};
328
+ // P1b: an explicitly passed job must belong to the passed task — a job
329
+ // id from another task is a caller bug, never silently served.
330
+ if (args.reviewJobId && job.taskId && job.taskId !== args.taskId) {
331
+ const error = new DomainError('INVALID_ARGUMENT', `reviewJobId ${reviewJobId} 属于任务 ${job.taskId},不是 ${args.taskId}。`, { status: 400, details: { reason: 'job-task-mismatch', jobTaskId: job.taskId } });
332
+ throw error;
333
+ }
334
+ if (job.taskId && job.taskId !== args.taskId) {
335
+ // Derived-by-default should never mismatch; treat as unavailable.
336
+ const task = (await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}`)).task;
337
+ const jobIds = task.reviewJobIds || [];
338
+ if (!jobIds.length) return this._legacyReviewResult(task);
339
+ historical = true;
340
+ const fallback = await this._awaitJob(jobIds[jobIds.length - 1], 0);
341
+ return this._reviewAnswer(args, fallback);
342
+ }
343
+ // Mark historical jobs explicitly: the task's LATEST round is what the
344
+ // rework/next-step summary may speak for; older rounds are read-only.
345
+ const taskNow = payload.task || null;
346
+ if (taskNow && (taskNow.reviewJobIds || []).length && (taskNow.reviewJobIds || []).at(-1) !== reviewJobId) historical = true;
347
+ const answer = this._reviewAnswer(args, payload);
348
+ const task = taskNow || {};
349
+ const checks = (task.runs || []).filter(r => r.kind === 'check');
350
+ return {
351
+ ...answer,
352
+ historical,
353
+ status: task.status,
354
+ phase: task.phase,
355
+ nextAction: task.nextAction,
356
+ reworkItems: task.reworkItems || [],
357
+ checks: checks.map(r => ({ runId: r.runId, summary: r.summary, status: r.status, finishedAt: r.finishedAt })),
358
+ acceptance: task.acceptance,
359
+ ...(historical
360
+ ? { note: `这是历史审查作业(当前最新一轮不是它);最新整改与下一步以不带 reviewJobId 的 review_result 为准。` }
361
+ : {}),
362
+ ...(!historical && answer.pending && (task.reworkItems || []).length
363
+ ? { note: `作业仍在运行;当前整改清单 ${task.reworkItems.length} 项(来自上一轮快照)。` }
364
+ : {}),
365
+ };
366
+ }
367
+
368
+ /** Old workflow module (no review jobs): read checks from the task runs. */
369
+ async _legacyReviewResult(task) {
180
370
  const checks = (task.runs || []).filter(r => r.kind === 'check');
181
- // Full findings of the LATEST check run: the rework member works from
182
- // concrete file:line[rule] items, not from summaries.
183
371
  let latestFindings = null;
184
372
  const latest = checks[checks.length - 1];
185
373
  if (latest && latest.executionRef) {
@@ -190,7 +378,9 @@ class WorkflowToolRuntime {
190
378
  }
191
379
  return {
192
380
  ok: true,
193
- taskId: args.taskId,
381
+ taskId: task.taskId,
382
+ reviewStatus: 'legacy',
383
+ pending: false,
194
384
  status: task.status,
195
385
  phase: task.phase,
196
386
  nextAction: task.nextAction,
@@ -206,4 +396,4 @@ class WorkflowToolRuntime {
206
396
  }
207
397
  }
208
398
 
209
- module.exports = { WorkflowToolRuntime };
399
+ module.exports = { WorkflowToolRuntime, MAX_WAIT_MS };