@sanqianx/ai-coding-workflow 0.1.2 → 0.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.
package/src/tasks.js CHANGED
@@ -15,7 +15,12 @@
15
15
  // derived from event recency, never a progress percentage.
16
16
 
17
17
  const crypto = require('crypto');
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const { spawnSync } = require('child_process');
18
21
  const { WorkflowError } = require('./errors');
22
+ const { ADAPTERS } = require('./checks');
23
+ const { captureSnapshot } = require('./snapshots');
19
24
 
20
25
  const TASK_PHASES = ['clarify', 'plan', 'implement', 'verify', 'review', 'rework', 'deliver'];
21
26
  const TASK_STATUSES = ['draft', 'ready', 'in_progress', 'verifying', 'in_review', 'done', 'blocked', 'cancelled'];
@@ -24,13 +29,32 @@ const HEALTH_STATES = ['connected', 'stale', 'disconnected', 'partial', 'unknown
24
29
 
25
30
  function newId(prefix) { return `${prefix}_${crypto.randomBytes(10).toString('hex')}`; }
26
31
 
27
- function validateAcceptance(item, index) {
32
+ function normalizeRequiredEvidence(requiredEvidence, index) {
33
+ if (requiredEvidence === undefined || requiredEvidence === null) return null;
34
+ if (!Array.isArray(requiredEvidence) || !requiredEvidence.length) {
35
+ throw new WorkflowError('VALIDATION', `Acceptance item ${index + 1}: requiredEvidence must be a non-empty array.`);
36
+ }
37
+ return requiredEvidence.map(req => {
38
+ const toolId = req && typeof req === 'object' ? req.toolId : req;
39
+ if (!toolId || typeof toolId !== 'string' || !ADAPTERS[toolId]) {
40
+ throw new WorkflowError('VALIDATION', `Acceptance item ${index + 1}: requiredEvidence names an unknown check tool (${toolId}).`);
41
+ }
42
+ return { toolId: String(toolId) };
43
+ });
44
+ }
45
+
46
+ function validateAcceptance(item, index, { requireEvidence = false } = {}) {
28
47
  if (!item || typeof item !== 'object' || !item.title || typeof item.title !== 'string') {
29
48
  throw new WorkflowError('VALIDATION', `Acceptance item ${index + 1} needs a title.`);
30
49
  }
31
50
  if (item.kind && !['automated', 'manual', 'model_review'].includes(item.kind)) {
32
51
  throw new WorkflowError('VALIDATION', `Acceptance item ${index + 1} has an unsupported kind.`);
33
52
  }
53
+ if (requireEvidence && (item.kind || 'automated') === 'automated' && !(Array.isArray(item.requiredEvidence) && item.requiredEvidence.length)) {
54
+ // A re-submitted automated item must NAME its evidence — guessing the
55
+ // check tool from the title is how lint passes stood in for tests.
56
+ throw new WorkflowError('VALIDATION', `Acceptance item ${index + 1} (automated) re-submitted without requiredEvidence: name the check tool(s) this item requires.`);
57
+ }
34
58
  }
35
59
 
36
60
  function createTask(state, input) {
@@ -39,7 +63,7 @@ function createTask(state, input) {
39
63
  if (title.length > 200) throw new WorkflowError('VALIDATION', 'Task title too long (max 200).');
40
64
  if (!input.projectId || typeof input.projectId !== 'string') throw new WorkflowError('VALIDATION', 'projectId is required.');
41
65
  const acceptance = Array.isArray(input.acceptance) ? input.acceptance : [];
42
- acceptance.forEach(validateAcceptance);
66
+ acceptance.forEach((item, index) => validateAcceptance(item, index));
43
67
  const taskId = newId('task');
44
68
  const now = new Date().toISOString();
45
69
  state.tasks[taskId] = {
@@ -48,10 +72,24 @@ function createTask(state, input) {
48
72
  title,
49
73
  goal: input.goal ? String(input.goal).slice(0, 4000) : null,
50
74
  sourceRefs: Array.isArray(input.sourceRefs) ? input.sourceRefs.map(String) : [],
75
+ // M0-A repository binding: the canonical root is resolved by the API
76
+ // layer from a trusted source in the SAME transaction (bindTaskRepo
77
+ // below); the client's repoPath never flows through createTask.
78
+ repoPath: null,
79
+ repoPathHint: null,
80
+ repoBinding: { status: 'unbound', basis: null, boundAt: null },
81
+ // P2b team mode (trusted activation only; the server layer strips the
82
+ // field from untrusted callers): executionMode 'team' arms the task for
83
+ // a Leader plan; planStatus tracks the planning lifecycle and
84
+ // teamConfigRevision pins the project settings the activation saw.
85
+ executionMode: input.executionMode === 'team' ? 'team' : 'session',
86
+ planStatus: input.executionMode === 'team' ? 'pending-plan' : null,
87
+ teamPlan: null,
51
88
  acceptance: acceptance.map((item, i) => ({
52
89
  id: `acc-${i + 1}`,
53
90
  title: String(item.title),
54
91
  kind: item.kind || 'automated', // automated | manual | model_review
92
+ requiredEvidence: normalizeRequiredEvidence(item.requiredEvidence, i), // named evidence per item (M0-B)
55
93
  status: 'pending', // pending | satisfied | failed | waived(with expiry)
56
94
  updatedAt: now,
57
95
  })),
@@ -114,10 +152,11 @@ function patchTask(state, taskId, patch, expectedRevision) {
114
152
  }
115
153
  if (patch.acceptance !== undefined) {
116
154
  // Acceptance edits bump the acceptanceRevision: prior evidence against
117
- // the old definition is stale by contract.
155
+ // the old definition is stale by contract. A re-submission must name its
156
+ // evidence (M0-B): no more tool-guessing from item titles.
118
157
  const acceptance = Array.isArray(patch.acceptance) ? patch.acceptance : [];
119
- acceptance.forEach(validateAcceptance);
120
- task.acceptance = acceptance.map((item, i) => ({ id: `acc-${i + 1}`, title: String(item.title), kind: item.kind || 'automated', status: 'pending', updatedAt: new Date().toISOString() }));
158
+ acceptance.forEach((item, index) => validateAcceptance(item, index, { requireEvidence: true }));
159
+ task.acceptance = acceptance.map((item, i) => ({ id: `acc-${i + 1}`, title: String(item.title), kind: item.kind || 'automated', requiredEvidence: normalizeRequiredEvidence(item.requiredEvidence, i), status: 'pending', updatedAt: new Date().toISOString() }));
121
160
  task.acceptanceRevision += 1;
122
161
  appendChange(state, { kind: 'task.acceptance_redefined', taskId, acceptanceRevision: task.acceptanceRevision });
123
162
  }
@@ -211,6 +250,287 @@ function addCheckpoint(state, taskId, input) {
211
250
  return checkpoint;
212
251
  }
213
252
 
253
+ // ---------- repository binding (M0-A) ----------
254
+
255
+ /** Resolve a real, existing directory or throw a structured VALIDATION error. */
256
+ function realDir(inputPath, label) {
257
+ if (!inputPath || typeof inputPath !== 'string') throw new WorkflowError('VALIDATION', `${label} is required.`);
258
+ let resolved;
259
+ // realpathSync.native (GetFinalPathNameByHandle) also expands 8.3 short
260
+ // names (RUNNER~1) — the plain JS variant keeps them and would make the
261
+ // same directory compare unequal to its own Git top-level.
262
+ const realpath = fs.realpathSync.native || fs.realpathSync;
263
+ try { resolved = realpath(path.resolve(inputPath)); } catch {
264
+ throw new WorkflowError('VALIDATION', `${label} does not exist: ${inputPath}`, { reason: 'path-missing' });
265
+ }
266
+ if (!fs.statSync(resolved).isDirectory()) {
267
+ throw new WorkflowError('VALIDATION', `${label} is not a directory: ${inputPath}`, { reason: 'not-a-directory' });
268
+ }
269
+ return resolved;
270
+ }
271
+
272
+ /** The Git work-tree root of a directory, realpath-normalized; null when not a repo. */
273
+ function gitTopLevel(dir) {
274
+ const result = spawnSync('git', ['-C', dir, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', windowsHide: true });
275
+ if (result.status !== 0 || !result.stdout) return null;
276
+ try { return (fs.realpathSync.native || fs.realpathSync)(result.stdout.trim()); } catch { return null; }
277
+ }
278
+
279
+ /**
280
+ * True when `dir` IS a Git work-tree root. The .git presence check does the
281
+ * real work — a string comparison between git's printed path and Node's
282
+ * realpath breaks on 8.3 short names and forward/back slash variants, which
283
+ * is exactly how CI's RUNNER~1 temp dir failed the first version of this.
284
+ */
285
+ function isGitRoot(dir) {
286
+ return Boolean(gitTopLevel(dir)) && fs.existsSync(path.join(dir, '.git'));
287
+ }
288
+
289
+ function sameTree(root, candidate) {
290
+ const rel = path.relative(root, candidate);
291
+ return !(rel.startsWith('..') || path.isAbsolute(rel));
292
+ }
293
+
294
+ /**
295
+ * Bind a task to its canonical Git root (M0-A). The root comes from a trusted
296
+ * source only — the managed shell's internal forward or the server-side
297
+ * project config; the client's repoPath is a hint that must live INSIDE the
298
+ * bound root, never establish it. The real path and the Git root must agree,
299
+ * so checks can never silently run in a same-named or look-alike repository.
300
+ * Rebinding to the same root is a no-op, so a retry re-bind stays idempotent.
301
+ */
302
+ function bindTaskRepo(state, taskId, { canonicalGitRoot, hintRepoPath, basis } = {}) {
303
+ const task = requireTask(state, taskId);
304
+ const root = realDir(canonicalGitRoot, 'canonicalGitRoot');
305
+ if (!isGitRoot(root)) {
306
+ throw new WorkflowError('VALIDATION', `canonicalGitRoot is not a Git work-tree root: ${canonicalGitRoot}`, { reason: 'not-git-root' });
307
+ }
308
+ const hint = hintRepoPath ? realDir(hintRepoPath, 'repoPath') : null;
309
+ if (hint && !sameTree(root, hint)) {
310
+ throw new WorkflowError('FORBIDDEN', 'repoPath 与任务绑定的 Git 根不一致(同名仓或目录不符)。', { reason: 'repo-mismatch', repoPath: hint, canonicalGitRoot: root });
311
+ }
312
+ if (task.repoPath === root && task.repoBinding && task.repoBinding.status === 'bound') return task;
313
+ task.repoPath = root;
314
+ task.repoPathHint = hint;
315
+ task.repoBinding = { status: 'bound', basis: basis || 'trusted-config', boundAt: new Date().toISOString() };
316
+ task.revision += 1;
317
+ task.updatedAt = new Date().toISOString();
318
+ appendChange(state, { kind: 'task.repo-bound', taskId, basis: task.repoBinding.basis, repoPath: root });
319
+ return task;
320
+ }
321
+
322
+ /**
323
+ * Register the trusted projectId → canonicalGitRoot mapping (M0-A). Only the
324
+ * runtime-token holder may write it; the path must already BE a Git root so
325
+ * a mistyped config fails at registration, not mid-delivery.
326
+ */
327
+ function putProjectRoot(state, projectId, canonicalGitRoot) {
328
+ if (!projectId || typeof projectId !== 'string') throw new WorkflowError('VALIDATION', 'projectId is required.');
329
+ const root = realDir(canonicalGitRoot, 'canonicalGitRoot');
330
+ if (!isGitRoot(root)) throw new WorkflowError('VALIDATION', `canonicalGitRoot is not a Git work-tree root: ${canonicalGitRoot}`, { reason: 'not-git-root' });
331
+ state.projectRoots = state.projectRoots || {};
332
+ const existing = state.projectRoots[projectId];
333
+ if (existing && existing.canonicalGitRoot === root) return { projectId, canonicalGitRoot: root, updatedAt: existing.updatedAt };
334
+ state.projectRoots[projectId] = { projectId, canonicalGitRoot: root, source: 'trusted-internal', updatedAt: new Date().toISOString() };
335
+ appendChange(state, { kind: 'project.root-set', projectId, repoPath: root });
336
+ return { projectId, canonicalGitRoot: root, updatedAt: state.projectRoots[projectId].updatedAt };
337
+ }
338
+
339
+ // ---------- review jobs (M0-B) ----------
340
+
341
+ /**
342
+ * Atomically reserve a review job (M0-B): the job and the snapshot it pins
343
+ * persist in ONE store mutation; the quality checks then run OUTSIDE the
344
+ * transaction. `executionToken` keeps a superseded or foreign execution from
345
+ * ever writing results into someone else's job.
346
+ */
347
+ function reserveReviewJob(state, taskId, { tools, policyHash, repoPath, included } = {}) {
348
+ const task = requireTask(state, taskId);
349
+ const toolList = (Array.isArray(tools) && tools.length ? tools : ['eslint']).map(String);
350
+ const snapshot = captureSnapshot(repoPath, { included: Array.isArray(included) ? included.map(String) : undefined });
351
+ const reviewJobId = `rvj_${crypto.randomBytes(8).toString('hex')}`;
352
+ state.reviewJobs = state.reviewJobs || {};
353
+ // P1a: does THIS round require a model review? Recorded inside the job so
354
+ // readers can tell "checks done, model still pending" from "checks-only
355
+ // contract, fully complete" without guessing from task acceptance shapes.
356
+ const modelRequired = task.acceptance.some(a => a.kind === 'model_review');
357
+ const job = {
358
+ reviewJobId,
359
+ taskId,
360
+ status: 'running',
361
+ tools: toolList,
362
+ policyHash: policyHash || 'policy:none',
363
+ repoPath,
364
+ included: Array.isArray(included) ? included.map(String) : [],
365
+ snapshotId: snapshot.snapshotId,
366
+ fileCount: snapshot.fileCount,
367
+ acceptanceRevision: task.acceptanceRevision,
368
+ taskRevision: task.revision,
369
+ modelRequired,
370
+ modelState: modelRequired ? 'pending' : 'not-required',
371
+ executionToken: crypto.randomBytes(12).toString('hex'),
372
+ receiptIds: [],
373
+ requestedAt: new Date().toISOString(),
374
+ finishedAt: null,
375
+ error: null,
376
+ };
377
+ state.reviewJobs[reviewJobId] = job;
378
+ task.reviewJobIds = [...(task.reviewJobIds || []), reviewJobId].slice(-20);
379
+ task.revision += 1;
380
+ appendChange(state, { kind: 'task.review-reserved', taskId, reviewJobId, snapshotId: snapshot.snapshotId });
381
+ return { job: { ...job }, snapshot };
382
+ }
383
+
384
+ /**
385
+ * P1a projection: what a client should WAIT ON for this job. `status` keeps
386
+ * its historical meaning (program phase); overallStatus adds the model
387
+ * dimension so 'completed' no longer has to mean 'review finished'.
388
+ */
389
+ function jobOverallStatus(job) {
390
+ if (!job) return null;
391
+ if (job.status === 'running') return 'checks-running';
392
+ if (job.status === 'failed') return 'failed';
393
+ if (job.status === 'stale') return 'stale';
394
+ if (job.status !== 'completed') return job.status;
395
+ if (!job.modelRequired) return 'review-complete';
396
+ if (job.modelState === 'blocked-missing-config') return 'blocked-missing-config';
397
+ const mr = job.modelReview;
398
+ if (!mr) return job.modelState === 'pending' ? 'awaiting-model-config' : 'awaiting-model';
399
+ if (mr.status === 'running') return 'awaiting-model';
400
+ if (mr.status === 'stale') return 'stale';
401
+ if (mr.status === 'pass' && mr.identityVerified) return 'review-complete';
402
+ return 'review-blocked';
403
+ }
404
+
405
+ function failReviewJob(state, reviewJobId, { executionToken, message } = {}) {
406
+ const job = (state.reviewJobs || {})[reviewJobId];
407
+ if (!job) throw new WorkflowError('NOT_FOUND', 'Review job not found.', { reviewJobId });
408
+ if (job.executionToken !== executionToken) throw new WorkflowError('FORBIDDEN', 'Review job is owned by another execution.', { reviewJobId });
409
+ if (job.status !== 'running') return { reviewJobId, status: job.status };
410
+ job.status = 'failed';
411
+ job.error = String(message || 'review execution failed').slice(0, 1000);
412
+ job.finishedAt = new Date().toISOString();
413
+ appendChange(state, { kind: 'task.review-failed', taskId: job.taskId, reviewJobId });
414
+ return { reviewJobId, status: 'failed', error: job.error };
415
+ }
416
+
417
+ /**
418
+ * Complete a reserved review job (M0-B). Occupancy, acceptanceRevision and
419
+ * the snapshot are re-verified INSIDE the persisting mutation: a snapshot
420
+ * that moved, an acceptance redefinition or a foreign token leaves the job
421
+ * stale/failed and never applies the old results.
422
+ */
423
+ function completeReviewJob(state, reviewJobId, { snapshot, receipts, executionToken } = {}) {
424
+ const job = (state.reviewJobs || {})[reviewJobId];
425
+ if (!job) throw new WorkflowError('NOT_FOUND', 'Review job not found.', { reviewJobId });
426
+ if (job.executionToken !== executionToken) throw new WorkflowError('FORBIDDEN', 'Review job is owned by another execution.', { reviewJobId });
427
+ if (job.status !== 'running') return { reviewJobId, status: job.status, replayed: true };
428
+ const task = requireTask(state, job.taskId);
429
+ if (task.acceptanceRevision !== job.acceptanceRevision) {
430
+ job.status = 'stale';
431
+ job.error = 'acceptanceRevision changed while the review ran; re-request review.';
432
+ job.finishedAt = new Date().toISOString();
433
+ appendChange(state, { kind: 'task.review-stale', taskId: job.taskId, reviewJobId, reason: 'acceptance-revision' });
434
+ return { reviewJobId, status: 'stale', stale: true };
435
+ }
436
+ const recaptured = captureSnapshot(job.repoPath, { included: job.included });
437
+ if (recaptured.snapshotId !== job.snapshotId) {
438
+ job.status = 'stale';
439
+ job.error = 'the work tree changed while the review ran; re-request review.';
440
+ job.finishedAt = new Date().toISOString();
441
+ appendChange(state, { kind: 'task.review-stale', taskId: job.taskId, reviewJobId, reason: 'snapshot-moved' });
442
+ return { reviewJobId, status: 'stale', stale: true };
443
+ }
444
+ const applied = applyCheckReceipts(state, job.taskId, { snapshot, receipts: receipts || [], policyHash: job.policyHash, reviewJobId });
445
+ job.status = 'completed';
446
+ job.receiptIds = applied.receiptIds;
447
+ job.decision = applied.decision;
448
+ job.finishedAt = new Date().toISOString();
449
+ return { reviewJobId, status: 'completed', ...applied };
450
+ }
451
+
452
+ /**
453
+ * Complete the MODEL review stage of a review job (M1-A). The evidence comes
454
+ * from runNativeReviewer; a pass verdict ONLY counts when the run's model
455
+ * identity was verified against the trusted reviewer config — anything else
456
+ * stays blocked with its diagnostic and never satisfies an item.
457
+ */
458
+ function completeModelReview(state, reviewJobId, { executionToken, evidence } = {}) {
459
+ const job = (state.reviewJobs || {})[reviewJobId];
460
+ if (!job) throw new WorkflowError('NOT_FOUND', 'Review job not found.', { reviewJobId });
461
+ if (job.executionToken !== executionToken) throw new WorkflowError('FORBIDDEN', 'Review job is owned by another execution.', { reviewJobId });
462
+ if (!job.modelReview || job.modelReview.status !== 'running') return { reviewJobId, modelReview: job.modelReview || null, replayed: true };
463
+ const task = requireTask(state, job.taskId);
464
+ evidence = evidence || {};
465
+ // P1a: a late model result may only land on the round it belongs to. If a
466
+ // NEWER snapshot or acceptance revision already replaced this job's view of
467
+ // the work tree, the result is history for THIS job — it must not satisfy
468
+ // items, clear rework of the new round, or flip delivery.
469
+ const stillCurrent = task.acceptanceRevision === job.acceptanceRevision
470
+ && task.latestSnapshot && task.latestSnapshot.snapshotId === job.snapshotId
471
+ && (task.reviewJobIds || []).at(-1) === reviewJobId;
472
+ job.modelReview = {
473
+ status: !stillCurrent ? 'stale' : evidence.verdict === 'pass' ? 'pass' : evidence.verdict === 'findings' ? 'findings' : 'blocked',
474
+ executionRef: evidence.executionRef || null,
475
+ reviewerRuntime: evidence.reviewerRuntime || null,
476
+ identity: evidence.identity || null,
477
+ identityVerified: Boolean(evidence.identityVerified),
478
+ blockedReason: !stillCurrent ? 'a newer review round exists; this result is history only' : evidence.blockedReason || null,
479
+ findings: (evidence.findings || []).slice(0, 50),
480
+ summary: evidence.summary || null,
481
+ finishedAt: new Date().toISOString(),
482
+ };
483
+ job.modelState = job.modelReview.status;
484
+ task.runs.push({
485
+ runId: `run_model_${evidence.executionRef || crypto.randomBytes(6).toString('hex')}`,
486
+ kind: 'review', status: job.modelReview.identityVerified ? (job.modelReview.status === 'pass' ? 'succeeded' : 'failed') : 'failed',
487
+ startedAt: evidence.startedAt || job.modelReview.finishedAt, finishedAt: job.modelReview.finishedAt,
488
+ attempt: task.runs.filter(r => r.kind === 'review').length + 1,
489
+ executionRef: job.modelReview.executionRef,
490
+ summary: `model-review ${job.modelReview.status} (${job.modelReview.identity || 'identity-unverified'})`,
491
+ });
492
+ if (task.runs.length > 100) task.runs = task.runs.slice(-100);
493
+ if (job.modelReview.status === 'pass' && job.modelReview.identityVerified) {
494
+ for (const item of task.acceptance) {
495
+ if (item.kind !== 'model_review') continue;
496
+ if (!stillCurrent) break; // a newer round owns the items now
497
+ if (item.status !== 'satisfied') {
498
+ item.status = 'satisfied';
499
+ item.evidenceRef = job.modelReview.executionRef;
500
+ item.evidenceRefs = [job.modelReview.executionRef];
501
+ item.updatedAt = new Date().toISOString();
502
+ appendChange(state, { kind: 'task.acceptance', taskId: task.taskId, acceptanceId: item.id, result: 'satisfied', via: 'model-review' });
503
+ }
504
+ }
505
+ // P1a: a verified pass of the CURRENT round resolves the model-review
506
+ // findings that this round covered — old model rework items must not
507
+ // linger as fake blockers. Program-check items from the SAME green
508
+ // round are already gone; findings of other tools/rounds stay.
509
+ if (stillCurrent) {
510
+ const remaining = (task.reworkItems || []).filter(r => r.toolId !== 'model-review');
511
+ if (remaining.length !== (task.reworkItems || []).length) {
512
+ task.reworkItems = remaining;
513
+ if (!remaining.length) task.nextAction = null;
514
+ }
515
+ }
516
+ } else if (stillCurrent && (evidence.findings || []).length) {
517
+ // Only the CURRENT round's findings may (re)write the rework queue; a
518
+ // late arrival from a superseded round is recorded on its job only.
519
+ task.reworkItems = (evidence.findings || []).slice(0, 50).map(f => ({
520
+ receiptId: null, toolId: 'model-review', ruleId: 'model-review',
521
+ file: f.file, line: f.line, severity: f.severity === 'error' ? 'error' : 'warning',
522
+ message: f.reason,
523
+ }));
524
+ task.nextAction = `按 Review 意见修复 ${task.reworkItems.length} 处后重新提交审查(project_workflow_request_review)`;
525
+ }
526
+ task.revision += 1;
527
+ task.updatedAt = new Date().toISOString();
528
+ appendChange(state, { kind: 'task.model-review', taskId: task.taskId, reviewJobId, status: job.modelReview.status, identityVerified: job.modelReview.identityVerified });
529
+ const decision = evaluateDelivery(state, task);
530
+ job.decision = decision;
531
+ return { reviewJobId, modelReview: job.modelReview, decision, task: publicTask(task, state) };
532
+ }
533
+
214
534
  /**
215
535
  * Apply check receipts to a task (called by the review orchestration):
216
536
  * stores the snapshot + receipts, then drives automated acceptance items
@@ -218,14 +538,14 @@ function addCheckpoint(state, taskId, input) {
218
538
  * item; a passing receipt satisfies it WITH its evidence key, so a later
219
539
  * snapshot change invalidates the delivery (T11/U16).
220
540
  */
221
- function applyCheckReceipts(state, taskId, { snapshot, receipts, policyHash }) {
541
+ function applyCheckReceipts(state, taskId, { snapshot, receipts, policyHash, reviewJobId }) {
222
542
  const task = requireTask(state, taskId);
223
543
  task.latestSnapshot = { snapshotId: snapshot.snapshotId, fileCount: snapshot.fileCount, head: snapshot.head, capturedAt: snapshot.capturedAt };
224
544
  state.checkReceipts = state.checkReceipts || {};
225
545
  const receiptIds = [];
226
546
  for (const receipt of receipts) {
227
547
  const receiptId = `chk_${crypto.randomBytes(8).toString('hex')}`;
228
- state.checkReceipts[receiptId] = { receiptId, taskId, ...receipt };
548
+ state.checkReceipts[receiptId] = { receiptId, taskId, reviewJobId: reviewJobId || null, ...receipt };
229
549
  receiptIds.push(receiptId);
230
550
  task.runs.push({
231
551
  runId: `run_${receiptId}`, kind: 'check',
@@ -270,14 +590,36 @@ function applyCheckReceipts(state, taskId, { snapshot, receipts, policyHash }) {
270
590
  if (item.kind !== 'automated') continue;
271
591
  const was = item.status;
272
592
  if (anyBlocking) {
273
- item.status = item.status === 'satisfied' ? 'satisfied' : 'failed'; // keep old satisfied until a NEW snapshot re-verifies? No: fail now, evidence first.
593
+ // A blocking receipt re-opens every automated item: evidence comes
594
+ // from the CURRENT snapshot only, never from an older green run.
274
595
  item.status = 'failed';
275
- item.evidenceRef = receiptIds[0] || item.evidenceRef;
276
- } else if (passAll) {
277
- item.status = 'satisfied';
278
- item.evidenceRef = receiptIds[0];
596
+ item.evidenceRef = null;
597
+ } else if (item.requiredEvidence && item.requiredEvidence.length) {
598
+ // M0-B evidence matching: the item is satisfied only when EVERY named
599
+ // tool produced a passing, complete receipt for THIS task, snapshot,
600
+ // acceptance revision and policy — a receipt from another task or an
601
+ // unrequested tool can never stand in.
602
+ const matches = item.requiredEvidence.map(req => receiptIds.find(rid => {
603
+ const r = state.checkReceipts[rid];
604
+ return r && r.taskId === taskId && r.toolId === req.toolId && r.verdict === 'pass'
605
+ && r.completeness === 'complete' && r.snapshotId === snapshot.snapshotId
606
+ && Number(r.acceptanceRevision) === task.acceptanceRevision;
607
+ }));
608
+ if (matches.every(Boolean)) {
609
+ item.status = 'satisfied';
610
+ item.evidenceRef = matches[0];
611
+ item.evidenceRefs = matches;
612
+ } else {
613
+ item.status = 'pending';
614
+ item.evidenceRef = null;
615
+ item.evidenceRefs = null;
616
+ }
279
617
  } else {
618
+ // Legacy default acceptance without named evidence: a re-review can
619
+ // never satisfy it (the tool must be named on re-submission); the
620
+ // item stays pending so delivery needs an explicit redefinition.
280
621
  item.status = 'pending';
622
+ item.evidenceRef = null;
281
623
  }
282
624
  item.updatedAt = new Date().toISOString();
283
625
  if (was !== item.status) appendChange(state, { kind: 'task.acceptance', taskId, acceptanceId: item.id, result: item.status, via: 'checks' });
@@ -285,7 +627,7 @@ function applyCheckReceipts(state, taskId, { snapshot, receipts, policyHash }) {
285
627
  task.revision += 1;
286
628
  task.updatedAt = new Date().toISOString();
287
629
  if (task.status === 'verifying') task.phase = 'review';
288
- return { receiptIds, decision: evaluateDelivery(task) };
630
+ return { receiptIds, decision: evaluateDelivery(state, task) };
289
631
  }
290
632
 
291
633
  /**
@@ -300,18 +642,25 @@ function recordAcceptanceDecision(state, taskId, input) {
300
642
  const item = task.acceptance.find(a => a.id === input.acceptanceId);
301
643
  if (!item) throw new WorkflowError('NOT_FOUND', 'Acceptance item not found.', { acceptanceId: input.acceptanceId });
302
644
  if (input.result === 'satisfied') {
303
- if (item.kind === 'manual' && input.basis !== 'human') {
304
- throw new WorkflowError('FORBIDDEN', 'Manual acceptance requires a human confirmation basis.', { acceptanceId: item.id });
645
+ if (item.kind === 'manual' || item.kind === 'model_review') {
646
+ // M0-B: no auditable human-authorization entry exists yet, so a human
647
+ // "yes" cannot be recorded — the item stays pending instead of trusting
648
+ // a client-declared basis. When the authorized entry ships it goes
649
+ // through HERE with its approval reference.
650
+ throw new WorkflowError('UNSUPPORTED', '人工/模型验收的授权入口尚未建立;确认保持待确认(等待可审计入口)。', { acceptanceId: item.id, reason: 'authorization-entry-missing' });
305
651
  }
306
652
  if (item.kind === 'automated') {
307
653
  // Program items are satisfied by receipts only — a model or user claim
308
- // cannot flip them (T18/U17).
654
+ // cannot flip them (T18/U17). The receipt must belong to THIS task,
655
+ // be passing and complete, and name a tool the item requires.
309
656
  const receipt = input.evidenceRef && state.checkReceipts && state.checkReceipts[input.evidenceRef];
310
- const matches = receipt && task.latestSnapshot && receipt.snapshotId === task.latestSnapshot.snapshotId
311
- && receipt.verdict === 'pass' && Number(receipt.acceptanceRevision) === task.acceptanceRevision;
312
- if (!matches) throw new WorkflowError('FORBIDDEN', 'Automated acceptance needs a passing receipt for the current snapshot and acceptance revision.', { acceptanceId: item.id });
657
+ const toolAllowed = !item.requiredEvidence || (Array.isArray(item.requiredEvidence) && item.requiredEvidence.some(req => receipt && receipt.toolId === req.toolId));
658
+ const matches = receipt && receipt.taskId === taskId && toolAllowed && task.latestSnapshot && receipt.snapshotId === task.latestSnapshot.snapshotId
659
+ && receipt.verdict === 'pass' && receipt.completeness === 'complete' && Number(receipt.acceptanceRevision) === task.acceptanceRevision;
660
+ if (!matches) throw new WorkflowError('FORBIDDEN', 'Automated acceptance needs a passing receipt of a required tool for the current snapshot and acceptance revision (cross-task or borrowed-tool receipts are rejected).', { acceptanceId: item.id });
313
661
  }
314
662
  item.status = 'satisfied';
663
+ item.evidenceRefs = [input.evidenceRef];
315
664
  } else if (input.result === 'failed') {
316
665
  item.status = 'failed';
317
666
  if (task.status === 'verifying' || task.status === 'in_review') task.status = 'in_progress';
@@ -326,30 +675,222 @@ function recordAcceptanceDecision(state, taskId, input) {
326
675
  item.updatedAt = new Date().toISOString();
327
676
  task.revision += 1;
328
677
  appendChange(state, { kind: 'task.acceptance', taskId, acceptanceId: item.id, result: input.result });
329
- return evaluateDelivery(task);
678
+ return evaluateDelivery(state, task);
330
679
  }
331
680
 
332
- function evaluateDelivery(task) {
681
+ /**
682
+ * Server-side delivery decision (M0-B): done comes ONLY through here, and
683
+ * the same gate covers explicit pause/cancel, blockers, waivers (with
684
+ * expiry), unresolved rework items, and evidence that is still valid for the
685
+ * CURRENT snapshot + acceptance revision. Satisfied automated items whose
686
+ * receipts went stale drop out of done with a diagnostic.
687
+ */
688
+ function evaluateDelivery(state, task) {
333
689
  const now = new Date().toISOString();
334
690
  const open = task.acceptance.filter(a => a.status === 'pending' || a.status === 'failed');
335
691
  const expiredWaivers = task.acceptance.filter(a => a.status === 'waived' && a.waiver && a.waiver.expiresAt < now);
692
+ const staleEvidence = [];
693
+ for (const a of task.acceptance) {
694
+ if (a.status !== 'satisfied') continue;
695
+ if (a.kind === 'automated') {
696
+ const refs = (a.evidenceRefs && a.evidenceRefs.length ? a.evidenceRefs : (a.evidenceRef ? [a.evidenceRef] : [])).filter(Boolean);
697
+ const valid = refs.length > 0 && refs.every(rid => {
698
+ const r = (state.checkReceipts || {})[rid];
699
+ return r && r.taskId === task.taskId && r.verdict === 'pass' && r.completeness === 'complete'
700
+ && task.latestSnapshot && r.snapshotId === task.latestSnapshot.snapshotId
701
+ && Number(r.acceptanceRevision) === task.acceptanceRevision;
702
+ });
703
+ if (!valid) staleEvidence.push(a.id);
704
+ }
705
+ if (a.kind === 'model_review') {
706
+ // P1a: a satisfied model item must trace to a REAL review job whose
707
+ // verified pass belongs to the CURRENT snapshot and acceptance
708
+ // revision — an old pass never carries over a moved work tree.
709
+ const refs = (a.evidenceRefs && a.evidenceRefs.length ? a.evidenceRefs : (a.evidenceRef ? [a.evidenceRef] : [])).filter(Boolean);
710
+ const valid = refs.length > 0 && refs.some(ref => {
711
+ const jobs = state.reviewJobs || {};
712
+ return Object.values(jobs).some(j => j.taskId === task.taskId
713
+ && j.modelReview && j.modelReview.executionRef === ref
714
+ && j.modelReview.status === 'pass' && j.modelReview.identityVerified
715
+ && j.acceptanceRevision === task.acceptanceRevision
716
+ && task.latestSnapshot && j.snapshotId === task.latestSnapshot.snapshotId);
717
+ });
718
+ if (!valid) staleEvidence.push(a.id);
719
+ }
720
+ }
336
721
  const blockers = [];
337
722
  if (open.length) blockers.push(`${open.length} acceptance item(s) not satisfied`);
338
723
  for (const a of expiredWaivers) { a.status = 'pending'; blockers.push(`waiver expired on ${a.id}`); }
724
+ for (const id of staleEvidence) blockers.push(`evidence for ${id} no longer matches the current snapshot/revision`);
725
+ if ((task.reworkItems || []).length) blockers.push(`${task.reworkItems.length} rework item(s) unresolved`);
726
+ if (task.status === 'blocked') blockers.push('task is explicitly blocked');
727
+ if (task.status === 'cancelled') blockers.push('task is cancelled');
339
728
  if (blockers.length) {
340
729
  // A previously delivered task whose evidence went stale (snapshot moved,
341
730
  // receipt re-run failed) drops out of done: delivery tracks evidence.
342
- if (task.status === 'done') { task.status = 'verifying'; task.deliveryNote = '交付状态待复核:有效证据不再完整。'; appendDeliveryChange(task); }
731
+ if (task.status === 'done') { task.status = 'verifying'; task.deliveryNote = '交付状态待复核:有效证据不再完整。'; }
343
732
  return { delivered: false, reasons: blockers, status: task.status };
344
733
  }
345
734
  if (!task.acceptance.length) return { delivered: false, reasons: ['no acceptance items defined'], status: task.status };
346
- if (task.status !== 'done') { task.status = 'done'; task.phase = 'deliver'; task.doneAt = now; task.updatedAt = now; task.deliveryNote = null; appendDeliveryChange(task); }
735
+ if (task.status !== 'done') { task.status = 'done'; task.phase = 'deliver'; task.doneAt = now; task.updatedAt = now; task.deliveryNote = null; }
347
736
  return { delivered: true, reasons: [], status: 'done' };
348
737
  }
349
738
 
350
- function appendDeliveryChange(task) {
351
- // Delivered via the task's own changes entry through appendChange upstream;
352
- // minimal inline bookkeeping here (change log is state-level).
739
+ /**
740
+ * P2b: validate and persist a Leader plan for a team task, atomically
741
+ * reserving the project's leader budget. Contract: unique ids, at most 3
742
+ * items, dependsOn complete + acyclic + forward-only, executorMemberId in
743
+ * the project's developerMemberIds, goal/acceptance present. Only a valid
744
+ * plan flips planStatus to 'planned'; invalid input throws and reserves
745
+ * nothing beyond the retry budget rule below.
746
+ */
747
+ function applyTeamPlan(state, taskId, { plan, leaderMemberId, leaderRun } = {}) {
748
+ const task = requireTask(state, taskId);
749
+ if (task.executionMode !== 'team') throw new WorkflowError('VALIDATION', '任务不是团队模式。', { taskId, reason: 'not-team-mode' });
750
+ const project = (state.projects || {})[task.projectId];
751
+ if (!project) throw new WorkflowError('VALIDATION', '项目未配置。', { taskId, reason: 'project-missing' });
752
+ if (!project.enabled) throw new WorkflowError('VALIDATION', '项目未启用。', { taskId, reason: 'project-disabled' });
753
+ if (!project.autoDispatch) throw new WorkflowError('VALIDATION', '项目未开启自动派发(autoDispatch)。', { taskId, reason: 'dispatch-disabled' });
754
+ const items = Array.isArray(plan) ? plan : [];
755
+ if (!items.length || items.length > 3) throw new WorkflowError('VALIDATION', '计划须为 1-3 个工作项。', { reason: 'plan-size' });
756
+ const ids = new Set();
757
+ for (const item of items) {
758
+ if (!item || typeof item.id !== 'string' || !item.id) throw new WorkflowError('VALIDATION', '工作项缺少 id。', { reason: 'plan-item-id' });
759
+ if (ids.has(item.id)) throw new WorkflowError('VALIDATION', `工作项 id 重复:${item.id}`, { reason: 'plan-duplicate-id' });
760
+ ids.add(item.id);
761
+ if (!item.goal || typeof item.goal !== 'string') throw new WorkflowError('VALIDATION', `工作项 ${item.id} 缺少 goal。`, { reason: 'plan-item-goal' });
762
+ if (!Array.isArray(item.acceptance) || !item.acceptance.length || item.acceptance.some(a => !a || !String(a.title || a))) throw new WorkflowError('VALIDATION', `工作项 ${item.id} 缺少可检验验收。`, { reason: 'plan-item-acceptance' });
763
+ const executor = item.executorMemberId;
764
+ if (!executor || !(project.developerMemberIds || []).includes(executor)) throw new WorkflowError('VALIDATION', `工作项 ${item.id} 的执行成员不在项目允许列表。`, { reason: 'plan-executor-not-allowed', executorMemberId: executor || null });
765
+ const member = state.members[executor];
766
+ if (!member || !member.enabled) throw new WorkflowError('VALIDATION', `工作项 ${item.id} 的执行成员不可用。`, { reason: 'plan-executor-unavailable' });
767
+ }
768
+ const order = new Set();
769
+ for (const item of items) {
770
+ for (const dep of item.dependsOn || []) {
771
+ if (!ids.has(dep)) throw new WorkflowError('VALIDATION', `工作项 ${item.id} 依赖未知项 ${dep}。`, { reason: 'plan-dep-unknown' });
772
+ if (!order.has(dep)) throw new WorkflowError('VALIDATION', `工作项 ${item.id} 依赖后面的 ${dep}(须正向依赖)。`, { reason: 'plan-dep-order' });
773
+ }
774
+ order.add(item.id);
775
+ }
776
+ // Budget: maxPlanRunsPerTask counts PERSISTED plans for this task;
777
+ // maxPlansPerDay counts persisted plans project-wide today.
778
+ const budget = project.leaderBudget || { maxPlansPerDay: 5, maxPlanRunsPerTask: 2 };
779
+ const today = new Date().toISOString().slice(0, 10);
780
+ state.teamPlanRuns = state.teamPlanRuns || { perTask: {}, perDay: {} };
781
+ const perTask = state.teamPlanRuns.perTask[taskId] || 0;
782
+ if (perTask >= budget.maxPlanRunsPerTask) throw new WorkflowError('VALIDATION', `任务计划次数已达上限(${budget.maxPlanRunsPerTask})。`, { reason: 'budget-per-task' });
783
+ const perDay = state.teamPlanRuns.perDay[project.projectId] && state.teamPlanRuns.perDay[project.projectId][today] || 0;
784
+ if (perDay >= budget.maxPlansPerDay) throw new WorkflowError('VALIDATION', `项目今日计划次数已达上限(${budget.maxPlansPerDay})。`, { reason: 'budget-per-day' });
785
+ const planRevision = (task.teamPlan && task.teamPlan.planRevision || 0) + 1;
786
+ task.teamPlan = {
787
+ planRevision,
788
+ leaderMemberId: leaderMemberId || project.leaderMemberId || null,
789
+ leaderRun: leaderRun || null,
790
+ createdAt: new Date().toISOString(),
791
+ items: items.map(item => ({
792
+ id: String(item.id),
793
+ goal: String(item.goal).slice(0, 1000),
794
+ executorMemberId: String(item.executorMemberId),
795
+ dependsOn: (item.dependsOn || []).map(String),
796
+ acceptance: item.acceptance.map(a => String(a.title || a).slice(0, 300)),
797
+ status: 'ready',
798
+ attempts: 0,
799
+ })),
800
+ };
801
+ task.planStatus = 'planned';
802
+ state.teamPlanRuns.perTask[taskId] = perTask + 1;
803
+ state.teamPlanRuns.perDay[project.projectId] = state.teamPlanRuns.perDay[project.projectId] || {};
804
+ state.teamPlanRuns.perDay[project.projectId][today] = perDay + 1;
805
+ task.revision += 1;
806
+ appendChange(state, { kind: 'task.team-plan', taskId, planRevision, items: items.length, leaderRun: task.teamPlan.leaderRun });
807
+ return { planRevision, items: task.teamPlan.items.map(i => ({ id: i.id, status: i.status })) };
808
+ }
809
+
810
+ /**
811
+ * P3a: claim the next (or a named) work item for execution. In-session
812
+ * execution: the ORIGINATING conversation claims an item and does the work
813
+ * itself (the P0-blocked auto-write dispatch records the same claim shape
814
+ * when it eventually runs). Claiming is idempotent per attempt and refuses
815
+ * items whose dependencies are not delivered/verified yet.
816
+ */
817
+ function claimWorkItem(state, taskId, workItemId, { claimedBy, executionRef } = {}) {
818
+ const task = requireTask(state, taskId);
819
+ const plan = task.teamPlan;
820
+ if (!plan) throw new WorkflowError('VALIDATION', '任务没有团队计划。', { taskId, reason: 'no-plan' });
821
+ const item = plan.items.find(i => i.id === workItemId);
822
+ if (!item) throw new WorkflowError('NOT_FOUND', '工作项不存在。', { taskId, workItemId, reason: 'work-item-unknown' });
823
+ if (item.status === 'verified' || item.status === 'delivered') return { item: { ...item }, replayed: true };
824
+ if (item.status === 'in_progress' && item.claimedBy && item.claimedBy !== (claimedBy || item.claimedBy)) {
825
+ throw new WorkflowError('CONFLICT', `工作项已被 ${item.claimedBy} 认领。`, { workItemId, reason: 'work-item-claimed' });
826
+ }
827
+ for (const dep of item.dependsOn || []) {
828
+ const depItem = plan.items.find(i => i.id === dep);
829
+ if (!depItem || !['delivered', 'verified'].includes(depItem.status)) {
830
+ throw new WorkflowError('VALIDATION', `依赖 ${dep} 未交付。`, { workItemId, dep, reason: 'dependency-not-delivered' });
831
+ }
832
+ }
833
+ item.status = 'in_progress';
834
+ item.attempts += 1;
835
+ item.claimedBy = claimedBy || null;
836
+ item.claimedAt = new Date().toISOString();
837
+ item.executionRef = executionRef || item.executionRef || null;
838
+ task.revision += 1;
839
+ appendChange(state, { kind: 'task.work-item-claimed', taskId, workItemId, claimedBy: item.claimedBy, attempt: item.attempts });
840
+ return { item: { ...item } };
841
+ }
842
+
843
+ /**
844
+ * P3a: record a work item's delivery (what changed, how it was tested, the
845
+ * artifacts). Delivery NEVER marks acceptance — the review pipeline owns
846
+ * that. When every item is delivered, the task's next review round can
847
+ * verify the whole plan; the caller is told the remaining count.
848
+ */
849
+ function reportWorkItem(state, taskId, workItemId, { claimedBy, summary, testedWith, artifacts } = {}) {
850
+ const task = requireTask(state, taskId);
851
+ const plan = task.teamPlan;
852
+ if (!plan) throw new WorkflowError('VALIDATION', '任务没有团队计划。', { taskId, reason: 'no-plan' });
853
+ const item = plan.items.find(i => i.id === workItemId);
854
+ if (!item) throw new WorkflowError('NOT_FOUND', '工作项不存在。', { taskId, workItemId, reason: 'work-item-unknown' });
855
+ if (item.status === 'delivered' || item.status === 'verified') return { item: { ...item }, replayed: true };
856
+ if (item.status !== 'in_progress') throw new WorkflowError('VALIDATION', '先认领再交付报告。', { workItemId, reason: 'not-claimed' });
857
+ if (claimedBy && item.claimedBy && claimedBy !== item.claimedBy) {
858
+ throw new WorkflowError('CONFLICT', '只有认领者能提交交付报告。', { workItemId, reason: 'claim-owner-mismatch' });
859
+ }
860
+ item.status = 'delivered';
861
+ item.deliveredAt = new Date().toISOString();
862
+ item.report = {
863
+ summary: String(summary || '').slice(0, 2000),
864
+ testedWith: Array.isArray(testedWith) ? testedWith.map(x => String(x).slice(0, 300)).slice(0, 20) : [],
865
+ artifacts: Array.isArray(artifacts) ? artifacts.map(x => String(x).slice(0, 300)).slice(0, 20) : [],
866
+ };
867
+ task.revision += 1;
868
+ const remaining = plan.items.filter(i => !['delivered', 'verified'].includes(i.status)).length;
869
+ if (!remaining) task.nextAction = '全部工作项已交付:提交整任务审查(request_review)做最终验证。';
870
+ appendChange(state, { kind: 'task.work-item-delivered', taskId, workItemId, remaining });
871
+ return { item: { ...item }, remaining };
872
+ }
873
+
874
+ /**
875
+ * P3a read-side projection: what should execute NOW and what is the plan's
876
+ * overall progress. Pure derivation, no mutation — resume/status surface it.
877
+ */
878
+ function planProgress(task) {
879
+ const plan = task && task.teamPlan;
880
+ if (!plan) return null;
881
+ const items = plan.items.map(i => ({ id: i.id, status: i.status, executorMemberId: i.executorMemberId, dependsOn: i.dependsOn, claimedBy: i.claimedBy || null, report: i.report || null }));
882
+ const ready = items.find(i => i.status === 'ready');
883
+ const inProgress = items.find(i => i.status === 'in_progress');
884
+ return {
885
+ planRevision: plan.planRevision,
886
+ leaderMemberId: plan.leaderMemberId,
887
+ leaderRun: plan.leaderRun,
888
+ items,
889
+ current: inProgress || ready || null,
890
+ deliveredCount: items.filter(i => ['delivered', 'verified'].includes(i.status)).length,
891
+ remainingCount: items.filter(i => !['delivered', 'verified'].includes(i.status)).length,
892
+ waitingUser: !inProgress && !ready && items.some(i => i.status === 'delivered'),
893
+ };
353
894
  }
354
895
 
355
896
  /** Bounded change log for the overview/restore projection. */
@@ -359,13 +900,16 @@ function appendChange(state, change) {
359
900
  if (state.changes.length > 2000) state.changes = state.changes.slice(-2000);
360
901
  }
361
902
 
362
- function publicTask(task) {
903
+ function publicTask(task, state) {
363
904
  return {
364
905
  taskId: task.taskId,
365
906
  projectId: task.projectId,
366
907
  title: task.title,
367
908
  goal: task.goal,
368
909
  sourceRefs: task.sourceRefs.slice(),
910
+ repoPath: task.repoPath || null,
911
+ repoPathHint: task.repoPathHint || null,
912
+ repoBinding: task.repoBinding ? { ...task.repoBinding } : { status: 'unbound', basis: null, boundAt: null },
369
913
  acceptance: task.acceptance.map(a => ({ ...a })),
370
914
  acceptanceRevision: task.acceptanceRevision,
371
915
  scope: task.scope,
@@ -377,6 +921,15 @@ function publicTask(task) {
377
921
  status: task.status,
378
922
  nextAction: task.nextAction,
379
923
  blockers: task.blockers,
924
+ reviewJobIds: (task.reviewJobIds || []).slice(-5),
925
+ executionMode: task.executionMode || 'session',
926
+ planStatus: task.planStatus || null,
927
+ teamPlan: task.teamPlan ? { planRevision: task.teamPlan.planRevision, leaderMemberId: task.teamPlan.leaderMemberId, leaderRun: task.teamPlan.leaderRun, items: task.teamPlan.items.map(i => ({ id: i.id, goal: i.goal, executorMemberId: i.executorMemberId, dependsOn: i.dependsOn, acceptance: i.acceptance, status: i.status, claimedBy: i.claimedBy || null, report: i.report || null })) } : null,
928
+ reviewState: (() => {
929
+ const latest = (task.reviewJobIds || []).at(-1);
930
+ const job = state && state.reviewJobs && latest ? state.reviewJobs[latest] : null;
931
+ return job ? { reviewJobId: latest, status: job.status, modelState: job.modelState || null, overallStatus: jobOverallStatus(job) } : null;
932
+ })(),
380
933
  runs: task.runs.slice(-10),
381
934
  observation: { ...task.observation },
382
935
  checkpoints: (task.checkpoints || []).slice(-5),
@@ -392,4 +945,6 @@ module.exports = {
392
945
  TASK_PHASES, TASK_STATUSES, RUN_STATUSES, HEALTH_STATES,
393
946
  createTask, requireTask, patchTask, addRun, addSessionBinding, addCheckpoint,
394
947
  recordAcceptanceDecision, evaluateDelivery, applyCheckReceipts, publicTask, appendChange,
948
+ realDir, gitTopLevel, sameTree, bindTaskRepo, putProjectRoot,
949
+ reserveReviewJob, completeReviewJob, failReviewJob, completeModelReview, jobOverallStatus, applyTeamPlan, claimWorkItem, reportWorkItem, planProgress,
395
950
  };