@sanqianx/project-knowledge 5.0.34 → 5.1.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.
Files changed (29) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +5 -0
  3. package/_site/_test/chat-claudecodeui-match-test.js +1 -1
  4. package/_site/_test/integration-runtime-binding-test.js +1 -1
  5. package/_site/_test/mcp-server-test.js +149 -149
  6. package/_site/_test/module-supervisor-backoff-reset-test.js +64 -0
  7. package/_site/_test/packaged-ui-smoke-test.js +1 -1
  8. package/_site/_test/parallel-memory-home-review-test.js +148 -0
  9. package/_site/_test/parallel-nav-home-issues-test.js +159 -0
  10. package/_site/_test/parallel-nav-theme-test.js +5 -4
  11. package/_site/_test/parallel-nav-viewport-test.js +4 -2
  12. package/_site/_test/product-empty-state-test.js +2 -2
  13. package/_site/_test/product-navigation-test.js +2 -2
  14. package/_site/_test/workflow-module-wiring-test.js +102 -0
  15. package/_site/_test/workflow-tools-test.js +97 -0
  16. package/_site/_test/workspace-ui-contract-test.js +16 -3
  17. package/_site/lib/integration-installer.js +3 -1
  18. package/_site/lib/module-bridge.js +59 -11
  19. package/_site/lib/server-app.js +12 -0
  20. package/_site/lib/workflow-tool-runtime.js +209 -0
  21. package/bin/project-knowledge-mcp.js +282 -201
  22. package/module-runtime-manifest.json +5 -5
  23. package/package.json +1 -1
  24. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  25. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  26. package/plugins/project-knowledge/.mcp.json +1 -1
  27. package/plugins/project-knowledge/skills/pk-team/SKILL.md +35 -0
  28. package/ui/index.html +6 -0
  29. package/ui/product.js +113 -12
@@ -48,13 +48,22 @@ const REGISTER_TIMEOUT_MS = 60000;
48
48
  const INDEX_TIMEOUT_MS = 120000;
49
49
  // Native folder dialogs wait for the user without a bound.
50
50
  const PICKER_TIMEOUT_MS = 10 * 60 * 1000;
51
-
52
- // All four services resolve through the host's pinned npm dependencies.
51
+ // A supervised service that stayed up this long proved a healthy run: its next
52
+ // exit opens a fresh incident instead of accumulating toward the restart cap.
53
+ // Without this, one-off exits spread over weeks eventually abandoned a module
54
+ // while the shell kept proxying to its dead port (endless MODULE_UNREACHABLE).
55
+ const SUPERVISOR_STABLE_MS = 60_000;
56
+
57
+ // All four pinned services resolve through the host's npm dependencies. The
58
+ // workflow module is fifth and OPTIONAL until its public release is pinned
59
+ // (W8): resolveModuleEntry returning null means "not installed", which
60
+ // degrades to an external-service warning — never a startup failure.
53
61
  const MODULE_ENTRIES = {
54
62
  terminal: 'claude-ai-workbench/packages/server/bin/agent-terminal-server.js',
55
63
  'vector-hub': '@sanqianx/vector-hub/bin.js',
56
64
  'event-bridge': '@sanqianx/ai-coding-event-bridge-console/src/bin.js',
57
65
  'knowledge-engine': '@sanqianx/ai-coding-knowledge-engine/src/bin.js',
66
+ workflow: '@sanqianx/ai-coding-workflow/src/bin.js',
58
67
  };
59
68
 
60
69
  function resolveModuleEntry(name) {
@@ -82,6 +91,7 @@ function defaultEventBridgeUrl() {
82
91
  }
83
92
 
84
93
  function defaultEngineUrl() { return String(process.env.KB_KNOWLEDGE_ENGINE_URL || 'http://127.0.0.1:5790').replace(/\/+$/, ''); }
94
+ function defaultWorkflowUrl() { return String(process.env.KB_WORKFLOW_URL || 'http://127.0.0.1:5810').replace(/\/+$/, ''); }
85
95
 
86
96
  // Health identity markers: an HTTP 200 alone can come from any foreign
87
97
  // service that grabbed the port. Only a body that matches the product
@@ -92,6 +102,7 @@ const MODULE_IDENTITY = {
92
102
  vectorHub: body => body && typeof body === 'object' && Array.isArray(body.projects),
93
103
  eventBridge: body => body && typeof body === 'object' && typeof body.registeredProjects === 'number',
94
104
  engine: body => body && typeof body === 'object' && body.name === 'knowledge-engine',
105
+ workflow: body => body && typeof body === 'object' && body.name === 'ai-coding-workflow' && typeof body.apiVersion === 'string',
95
106
  };
96
107
 
97
108
  // kind -> bridge URL property, explicit env override, spawn spec name
@@ -100,6 +111,7 @@ const MODULE_URL_TARGETS = [
100
111
  { kind: 'vectorHub', prop: 'vectorHubUrl', env: 'KB_VECTORHUB_URL', specName: 'vector-hub' },
101
112
  { kind: 'eventBridge', prop: 'eventBridgeUrl', env: 'KB_EVENTBRIDGE_URL', specName: 'event-bridge' },
102
113
  { kind: 'engine', prop: 'engineUrl', env: 'KB_KNOWLEDGE_ENGINE_URL', specName: 'knowledge-engine' },
114
+ { kind: 'workflow', prop: 'workflowUrl', env: 'KB_WORKFLOW_URL', specName: 'workflow' },
103
115
  ];
104
116
 
105
117
  function specNameToKind(specName) {
@@ -124,6 +136,7 @@ class ModuleBridge {
124
136
  this.vectorHubUrl = options.vectorHubUrl || defaultVectorHubUrl();
125
137
  this.eventBridgeUrl = options.eventBridgeUrl || defaultEventBridgeUrl();
126
138
  this.engineUrl = options.engineUrl || defaultEngineUrl();
139
+ this.workflowUrl = options.workflowUrl || defaultWorkflowUrl();
127
140
  // Explicitly injected URLs (option or env) mean an external service;
128
141
  // only managed defaults participate in dynamic port resolution.
129
142
  this.explicitModuleUrls = {
@@ -131,8 +144,9 @@ class ModuleBridge {
131
144
  vectorHub: Boolean(options.vectorHubUrl || process.env.KB_VECTORHUB_URL),
132
145
  eventBridge: Boolean(options.eventBridgeUrl || process.env.KB_EVENTBRIDGE_URL),
133
146
  engine: Boolean(options.engineUrl || process.env.KB_KNOWLEDGE_ENGINE_URL),
147
+ workflow: Boolean(options.workflowUrl || process.env.KB_WORKFLOW_URL),
134
148
  };
135
- this.moduleUrlSources = { terminal: 'pending', vectorHub: 'pending', eventBridge: 'pending', engine: 'pending' };
149
+ this.moduleUrlSources = { terminal: 'pending', vectorHub: 'pending', eventBridge: 'pending', engine: 'pending', workflow: 'pending' };
136
150
  this.runtimeToken = options.runtimeToken || crypto.randomBytes(32).toString('hex');
137
151
  this.registryStore = options.registryStore || null;
138
152
  this.projectStore = options.projectStore || null;
@@ -160,6 +174,12 @@ class ModuleBridge {
160
174
  return `${this.eventBridgeUrl}/api/${rest}`;
161
175
  }
162
176
 
177
+ _workflowApi(pathname) {
178
+ // /api/workflow/<rest> -> <workflow module>/api/workflow/v1/<rest>
179
+ const rest = pathname.replace(/^\/api\/workflow\/?/, '');
180
+ return `${this.workflowUrl}/api/workflow/v1/${rest}`;
181
+ }
182
+
163
183
  async _fetch(url, init = {}) {
164
184
  const controller = new AbortController();
165
185
  const timer = setTimeout(() => controller.abort(), init.timeoutMs || PROXY_TIMEOUT_MS);
@@ -243,13 +263,17 @@ class ModuleBridge {
243
263
  return this.proxy(req, res, this._eventBridgeApi(pathname) + (search || ''));
244
264
  }
245
265
 
266
+ proxyWorkflow(req, res, pathname, search) {
267
+ return this.proxy(req, res, this._workflowApi(pathname) + (search || ''));
268
+ }
269
+
246
270
  proxyEngine(req, res, pathname, search) {
247
271
  if (this.engineCompatible === false) throw new DomainError('ENGINE_CONNECTION_PENDING', '知识引擎连接尚未确认,请查看系统状态;不会读取旧服务中的知识。', { status: 503 });
248
272
  return this.proxy(req, res, `${this.engineUrl}/api/${pathname.replace(/^\/api\/engine\/?/, '')}${search || ''}`);
249
273
  }
250
274
 
251
275
  proxyModuleUi(req, res, module, rest, search) {
252
- const base = { terminal: this.terminalUrl, vectorhub: this.vectorHubUrl, eventbridge: this.eventBridgeUrl, engine: this.engineUrl }[module];
276
+ const base = { terminal: this.terminalUrl, vectorhub: this.vectorHubUrl, eventbridge: this.eventBridgeUrl, engine: this.engineUrl, workflow: this.workflowUrl }[module];
253
277
  let decoded;
254
278
  try { decoded = decodeURIComponent(rest); } catch { decoded = null; }
255
279
  // Reject encoded separators/dot segments before URL normalization. Static
@@ -374,17 +398,22 @@ class ModuleBridge {
374
398
  }
375
399
 
376
400
  async modulesHealth() {
377
- const [terminal, vectorHub, eventBridge, engine] = await Promise.all([
401
+ const [terminal, vectorHub, eventBridge, engine, workflow] = await Promise.all([
378
402
  this._probe(this.terminalUrl, 'terminal'),
379
403
  this._probe(this.vectorHubUrl, 'vectorHub'),
380
404
  this._probe(this.eventBridgeUrl, 'eventBridge'),
381
405
  this._probe(this.engineUrl, 'engine'),
406
+ this._probe(this.workflowUrl, 'workflow'),
382
407
  ]);
383
408
  return { ok: true, modules: {
384
409
  terminal: { url: this.terminalUrl, up: terminal, source: this.moduleUrlSources.terminal },
385
410
  vectorHub: { url: this.vectorHubUrl, up: vectorHub, source: this.moduleUrlSources.vectorHub },
386
411
  eventBridge: { url: this.eventBridgeUrl, up: eventBridge, source: this.moduleUrlSources.eventBridge },
387
412
  engine: { url: this.engineUrl, up: engine, source: this.moduleUrlSources.engine },
413
+ // Optional fifth module: `installed` tells the UI "not installed" apart
414
+ // from "installed but down" so a missing package is never mistaken for
415
+ // a service failure of the four pinned runtimes.
416
+ workflow: { url: this.workflowUrl, up: workflow, source: this.moduleUrlSources.workflow, installed: Boolean(resolveModuleEntry('workflow')) },
388
417
  } };
389
418
  }
390
419
 
@@ -789,6 +818,20 @@ class ModuleBridge {
789
818
  }
790
819
  const engineEntry = resolveModuleEntry('knowledge-engine');
791
820
  if (process.env.KB_KNOWLEDGE_ENGINE_COMMAND || engineEntry) specs.push({ name: 'knowledge-engine', command: process.env.KB_KNOWLEDGE_ENGINE_COMMAND || `node ${JSON.stringify(engineEntry)} serve --port ${urlPort(this.engineUrl, 5790)} --host ${urlHost(this.engineUrl)}`, url: this.engineUrl, env: { KNOWLEDGE_ENGINE_DATA: path.join(this.dataDir || require('./data-dir').getDataDir(), 'knowledge-engine'), KB_ENGINE_MANAGED: '1', KNOWLEDGE_ENGINE_CONSUME: '0', KB_ENGINE_RUNTIME_TOKEN: this.runtimeToken, KB_EVENT_BRIDGE_URL: this.eventBridgeUrl, KB_VECTOR_HUB_URL: this.vectorHubUrl, NODE_PATH: path.resolve(__dirname, '..', '..', 'node_modules') } });
821
+ // Optional fifth module (workflow). Absent entry => warn and expect an
822
+ // external service, exactly like an unpinned optional runtime: the four
823
+ // pinned modules and the shell keep working.
824
+ const workflowEntry = resolveModuleEntry('workflow');
825
+ if (process.env.KB_WORKFLOW_COMMAND || workflowEntry) {
826
+ specs.push({
827
+ name: 'workflow',
828
+ 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
+ url: this.workflowUrl,
830
+ env: { KB_WORKFLOW_MANAGED: '1', KB_WORKFLOW_RUNTIME_TOKEN: this.runtimeToken },
831
+ });
832
+ } else {
833
+ this.logger.warn('modules.supervisor', '@sanqianx/ai-coding-workflow runtime not installed; team features report "not installed".', {});
834
+ }
792
835
  return specs;
793
836
  }
794
837
 
@@ -799,6 +842,7 @@ class ModuleBridge {
799
842
  const parts = (spec.command.match(/"[^"]+"|\S+/g) || [])
800
843
  .map(part => { if (!part.startsWith('"') || !part.endsWith('"')) return part; try { return JSON.parse(part); } catch { return part.slice(1, -1); } });
801
844
  const nodeProcess = parts[0] === 'node' || parts[0] === process.execPath;
845
+ const spawnedAt = Date.now();
802
846
  const child = spawn(nodeProcess ? process.execPath : parts[0], parts.slice(1), {
803
847
  // Module banners (ports, data roots) are diagnostics — inherit stdout
804
848
  // so they land on the console in --fg mode and in launcher.log when the
@@ -822,14 +866,18 @@ class ModuleBridge {
822
866
  child.on('exit', code => {
823
867
  this.onStateChange?.(spec.name);
824
868
  this.supervised = this.supervised.filter(existing => existing !== child);
825
- attempts += 1;
826
- if (attempts > 5 || this.stopped) {
827
- this.logger.warn('modules.supervisor', 'Module service stopped.', { context: { name: spec.name, code, attempts } });
869
+ // A stable run (see SUPERVISOR_STABLE_MS) means the prior exits belong to
870
+ // bygone incidents: count this exit as the first of a fresh one. Only a
871
+ // service that keeps dying quickly accumulates toward the give-up cap.
872
+ const stable = Date.now() - spawnedAt >= (spec._stableAfterMs ?? SUPERVISOR_STABLE_MS);
873
+ const incidentAttempts = stable ? 1 : attempts + 1;
874
+ if (incidentAttempts > 5 || this.stopped) {
875
+ this.logger.warn('modules.supervisor', 'Module service stopped.', { context: { name: spec.name, code, attempts: incidentAttempts } });
828
876
  return;
829
877
  }
830
- const delay = Math.min(1000 * 2 ** attempts, 15000);
831
- this.logger.warn('modules.supervisor', 'Module service exited; restarting.', { context: { name: spec.name, code, retryInMs: delay } });
832
- const timer = setTimeout(() => { this.restartTimers.delete(timer); this._spawnSupervised({ ...spec, _attempts: attempts }); }, delay);
878
+ const delay = Math.min(1000 * 2 ** incidentAttempts, 15000);
879
+ this.logger.warn('modules.supervisor', 'Module service exited; restarting.', { context: { name: spec.name, code, attempts: incidentAttempts, retryInMs: delay } });
880
+ const timer = setTimeout(() => { this.restartTimers.delete(timer); this._spawnSupervised({ ...spec, _attempts: incidentAttempts }); }, delay);
833
881
  this.restartTimers = this.restartTimers || new Set(); this.restartTimers.add(timer);
834
882
  });
835
883
  this.supervised.push(child);
@@ -919,6 +919,18 @@ function createRequestHandler(runtime, options = {}) {
919
919
  if (pathname.startsWith('/api/eventbridge/internal/')) throw new DomainError('FORBIDDEN', 'Internal module endpoints are not exposed to browsers.', { status: 403 });
920
920
  return runtime.moduleBridge.proxyEventBridge(req, res, pathname, url.search);
921
921
  }
922
+ // Fifth module (optional): team/workflow business API. The module's
923
+ // own base is /api/workflow/v1; the shell rewrites /api/workflow/<rest>
924
+ // to it. Internal (trusted-service) subroutes stay server-side only.
925
+ if (pathname.startsWith('/api/workflow/') || pathname === '/api/workflow') {
926
+ if (pathname.startsWith('/api/workflow/internal/')) throw new DomainError('FORBIDDEN', 'Internal module endpoints are not exposed to browsers.', { status: 403 });
927
+ return runtime.moduleBridge.proxyWorkflow(req, res, pathname, url.search);
928
+ }
929
+ // AI team page proxy: /workflow-ui/<asset> -> workflow module /<asset>.
930
+ // GET-only, encoded-segment and api/internal segments rejected inside
931
+ // proxyModuleUi; the module serves its own index.html at the root.
932
+ const workflowUi = pathname.match(/^\/workflow-ui\/?(.*)$/);
933
+ if (workflowUi && method === 'GET') return runtime.moduleBridge.proxyModuleUi(req, res, 'workflow', workflowUi[1], url.search);
922
934
  if (method === 'GET' && pathname === '/api/modules/health') {
923
935
  return send(res, 200, { ...await runtime.moduleBridge.modulesHealth(), ownership: runtime.ownership });
924
936
  }
@@ -0,0 +1,209 @@
1
+ 'use strict';
2
+
3
+ // MCP tool runtime for the six project_workflow_* tools. These tools are a
4
+ // thin adapter over the shell's /api/workflow/* proxy into the independent
5
+ // workflow module — no task state is stored here (runbook §2.3: the tools
6
+ // call the workflow master store, never a second copy).
7
+
8
+ const path = require('path');
9
+ const endpoint = require('./runtime-endpoint');
10
+ const { getDataDir } = require('./data-dir');
11
+
12
+ const DEFAULT_TIMEOUT_MS = 15000;
13
+
14
+ class WorkflowToolRuntime {
15
+ constructor(options = {}) {
16
+ this.layout = options.layout || null;
17
+ this.workflowUrl = options.workflowUrl || process.env.KB_WORKFLOW_URL || null;
18
+ this.fetchImpl = options.fetchImpl || fetch;
19
+ this.timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
20
+ }
21
+
22
+ /** Prefer an explicit module URL; else the live shell's proxy base. */
23
+ resolveBase() {
24
+ if (this.workflowUrl) return { base: this.workflowUrl.replace(/\/+$/, ''), prefix: '/api/workflow/v1' };
25
+ try {
26
+ const dataDir = this.layout ? this.layout.getDataDir() : getDataDir();
27
+ const live = endpoint.readLiveEndpoint(dataDir, { removeStale: false });
28
+ if (live && live.host && live.port) return { base: `http://${live.host}:${live.port}`, prefix: '/api/workflow' };
29
+ } catch { /* no live shell — surfaced as a structured error below */ }
30
+ return null;
31
+ }
32
+
33
+ async request(apiPath, { method = 'GET', body } = {}) {
34
+ const resolved = this.resolveBase();
35
+ if (!resolved) {
36
+ const error = new Error('WORKFLOW_UNAVAILABLE');
37
+ error.code = 'WORKFLOW_UNAVAILABLE';
38
+ error.message = '工作流服务不可达:未设置 KB_WORKFLOW_URL,且没有运行中的知识库实例。任务与知识检索不受影响。';
39
+ throw error;
40
+ }
41
+ const url = `${resolved.base}${resolved.prefix}/${apiPath.replace(/^\/+/, '')}`;
42
+ const controller = new AbortController();
43
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
44
+ try {
45
+ const response = await this.fetchImpl(url, {
46
+ method,
47
+ headers: body ? { 'Content-Type': 'application/json' } : {},
48
+ body: body ? JSON.stringify(body) : undefined,
49
+ signal: controller.signal,
50
+ });
51
+ const json = await response.json().catch(() => ({}));
52
+ 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;
58
+ }
59
+ return json;
60
+ } catch (inner) {
61
+ if (inner.code) throw inner;
62
+ const error = new Error('工作流服务不可达;原生开发可以继续,页面会显示降级状态。');
63
+ error.code = 'WORKFLOW_UNAVAILABLE';
64
+ throw error;
65
+ } finally { clearTimeout(timer); }
66
+ }
67
+
68
+ /**
69
+ * start: create the business task, bind the calling session (declared
70
+ * basis — the Bridge consumer's captured sessionId drives observation, not
71
+ * acceptance), and return the short task contract.
72
+ */
73
+ async start(args) {
74
+ const title = String(args.title || '').trim();
75
+ if (!title) { const e = new Error('title is required'); e.code = 'VALIDATION'; throw e; }
76
+ const payload = {
77
+ requestId: `mcp-start-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
78
+ projectId: args.projectId || 'unknown-project',
79
+ title,
80
+ goal: args.goal || null,
81
+ acceptance: Array.isArray(args.acceptance) ? args.acceptance : undefined,
82
+ ownerMemberId: args.memberId || null,
83
+ };
84
+ const created = await this.request('workflow-tasks', { method: 'POST', body: payload });
85
+ const taskId = created.task.taskId;
86
+ let binding = null;
87
+ if (args.client && args.sessionId) {
88
+ const bindBody = {
89
+ requestId: `mcp-bind-${payload.requestId}`,
90
+ client: String(args.client),
91
+ nativeSessionId: String(args.sessionId),
92
+ workspaceIdentity: args.workspaceIdentity || args.repoPath || process.cwd(),
93
+ memberId: args.memberId || null,
94
+ verificationBasis: 'declared',
95
+ };
96
+ try { binding = await this.request(`workflow-tasks/${encodeURIComponent(taskId)}/session-bindings`, { method: 'POST', body: bindBody }); }
97
+ catch { binding = null; /* observation still works once the hook-captured session id matches */ }
98
+ }
99
+ return {
100
+ ok: true,
101
+ taskId,
102
+ task: created.task,
103
+ sessionBinding: binding ? { bindingId: binding.binding.bindingId, basis: 'declared' } : null,
104
+ nextStep: '实现需求;完成后用 project_workflow_checkpoint 记录事实,再 request_review(交付检查在后续版本接入)。',
105
+ note: '会话绑定当前为声明级:事件观察按采集会话归因,验收始终由服务端裁决。',
106
+ };
107
+ }
108
+
109
+ async resume(args) {
110
+ if (!args.taskId) { const e = new Error('taskId is required'); e.code = 'VALIDATION'; throw e; }
111
+ const result = await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}`);
112
+ const task = result.task;
113
+ const checkpoints = task.checkpoints || [];
114
+ const latest = checkpoints[checkpoints.length - 1] || null;
115
+ return {
116
+ ok: true,
117
+ taskId: task.taskId,
118
+ title: task.title,
119
+ goal: task.goal,
120
+ status: task.status,
121
+ phase: task.phase,
122
+ acceptance: task.acceptance,
123
+ acceptanceRevision: task.acceptanceRevision,
124
+ confirmedDecisions: latest ? latest.decided : [],
125
+ verifiedResults: latest ? latest.verifiedResults : [],
126
+ remaining: latest ? latest.remaining : task.acceptance.filter(a => a.status === 'pending').map(a => a.title),
127
+ nextAction: task.nextAction,
128
+ revision: task.revision,
129
+ };
130
+ }
131
+
132
+ async status(args) {
133
+ if (args.taskId) return { ok: true, task: (await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}`)).task };
134
+ const query = new URLSearchParams();
135
+ if (args.projectId) query.set('projectId', args.projectId);
136
+ if (args.status) query.set('status', args.status);
137
+ const list = await this.request(`workflow-tasks?${query.toString()}`);
138
+ return { ok: true, total: list.total, tasks: list.tasks.map(t => ({ taskId: t.taskId, title: t.title, projectId: t.projectId, status: t.status, phase: t.phase, nextAction: t.nextAction, updatedAt: t.updatedAt })) };
139
+ }
140
+
141
+ async checkpoint(args) {
142
+ if (!args.taskId) { const e = new Error('taskId is required'); e.code = 'VALIDATION'; throw e; }
143
+ const payload = {
144
+ requestId: `mcp-ckpt-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
145
+ kind: args.kind === 'fact' ? 'fact' : 'candidate',
146
+ summary: args.summary || null,
147
+ decided: args.decided,
148
+ verifiedResults: args.verifiedResults,
149
+ remaining: args.remaining,
150
+ nextAction: args.nextAction || null,
151
+ eventRefs: args.eventRefs,
152
+ };
153
+ const result = await this.request(`workflow-tasks/${encodeURIComponent(args.taskId)}/checkpoints`, { method: 'POST', body: payload });
154
+ return { ok: true, checkpoint: result.checkpoint };
155
+ }
156
+
157
+ 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,
165
+ 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(编排交付前不虚构意见)。',
174
+ };
175
+ }
176
+
177
+ 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;
180
+ 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
+ let latestFindings = null;
184
+ const latest = checks[checks.length - 1];
185
+ if (latest && latest.executionRef) {
186
+ try {
187
+ const receipt = await this.request(`check-receipts/${encodeURIComponent(latest.executionRef)}`);
188
+ latestFindings = (receipt.receipt.findings || []).slice(0, 100).map(f => ({ ruleId: f.ruleId, file: f.file, line: f.line, severity: f.severity, message: f.message }));
189
+ } catch { latestFindings = null; /* receipt purged or unavailable — reworkItems on the task still carry the queue */ }
190
+ }
191
+ return {
192
+ ok: true,
193
+ taskId: args.taskId,
194
+ status: task.status,
195
+ phase: task.phase,
196
+ nextAction: task.nextAction,
197
+ reworkItems: task.reworkItems || [],
198
+ latestCheckFindings: latestFindings,
199
+ checks: checks.map(r => ({ runId: r.runId, summary: r.summary, status: r.status, finishedAt: r.finishedAt })),
200
+ acceptance: task.acceptance,
201
+ modelReview: 'pending-model-review',
202
+ note: task.reworkItems && task.reworkItems.length
203
+ ? `整改 ${task.reworkItems.length} 项:按 file:line[rule] 修复后重新 project_workflow_request_review。`
204
+ : '当前快照没有待整改项。',
205
+ };
206
+ }
207
+ }
208
+
209
+ module.exports = { WorkflowToolRuntime };