@sanqianx/ai-coding-workflow 0.1.1 → 0.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.
package/src/server.js CHANGED
@@ -28,23 +28,62 @@ const domain = require('./domain');
28
28
  const tasksDomain = require('./tasks');
29
29
  const { WorkflowConsumer } = require('./consumer');
30
30
  const { runChecks } = require('./checks');
31
+ const { runNativeReviewer, captureReviewDiff, captureReviewTree, buildReviewMaterial } = require('./review-native');
31
32
  const { buildDailyDigest, upsertReminder, reminderAction, localDay } = require('./digests');
32
33
  const { healthBody, capabilitiesBody } = require('./identity');
33
34
 
34
- function taskRepoPath(snapshot, taskId) {
35
- const task = snapshot.tasks[taskId];
36
- return task && task.sourceRefs && task.sourceRefs.repoPath ? task.sourceRefs.repoPath : null;
35
+ // M1-D: the optional LangGraph orchestrator loads ONLY when explicitly
36
+ // configured (orchestratorDbPath) and its package is present; the core
37
+ // package itself stays zero-dependency.
38
+ let orchestrator = null;
39
+ function resolveOrchestrator(dbPath) {
40
+ if (!dbPath) return null;
41
+ if (orchestrator) return orchestrator;
42
+ try { orchestrator = require('../orchestrator'); return orchestrator; } catch { return null; }
37
43
  }
38
44
 
39
45
  const UI_ROOT = path.join(__dirname, '..', 'ui');
40
46
  const MAX_BODY_BYTES = 1024 * 1024;
41
47
  const PROXY_HOP_HEADERS = ['x-forwarded-host', 'x-forwarded-for'];
42
48
 
49
+ /**
50
+ * M0-A: the trusted projectId → canonicalGitRoot map. Sources, in priority
51
+ * order: state records written through the trusted internal endpoint
52
+ * (managed shell), the explicit options map, and `<dataDir>/workflow/
53
+ * projects.json` (standalone server-side config). A client-supplied repoPath
54
+ * can never establish trust — it only has to MATCH the resolved root.
55
+ */
56
+ function loadProjectRootsConfig(dataDir) {
57
+ if (!dataDir) return {};
58
+ try {
59
+ const raw = fs.readFileSync(path.join(dataDir, 'workflow', 'projects.json'), 'utf8');
60
+ const parsed = JSON.parse(raw);
61
+ if (!parsed || typeof parsed !== 'object') return {};
62
+ const map = {};
63
+ for (const [projectId, value] of Object.entries(parsed)) {
64
+ const root = value && typeof value === 'object' ? value.canonicalGitRoot : value;
65
+ if (typeof root === 'string' && root) map[String(projectId)] = root;
66
+ }
67
+ return map;
68
+ } catch { return {}; }
69
+ }
70
+
43
71
  function createWorkflowServer(options = {}) {
44
72
  const store = options.store || new WorkflowStore(options.dataDir);
45
73
  const runtimeToken = options.runtimeToken || process.env.KB_WORKFLOW_RUNTIME_TOKEN || null;
46
74
  const startedAt = Date.now();
47
- const state = { dataDir: options.dataDir || null, managed: Boolean(options.managed) };
75
+ const state = { dataDir: options.dataDir || null, managed: Boolean(options.managed), orchestratorDbPath: options.orchestratorDbPath || null };
76
+ resolveOrchestrator(state.orchestratorDbPath);
77
+ const projectRootsOptions = options.projectRoots && typeof options.projectRoots === 'object' ? options.projectRoots : {};
78
+ const projectRootsConfig = loadProjectRootsConfig(options.dataDir);
79
+
80
+ function resolveProjectRoot(snapshot, projectId) {
81
+ const fromState = (snapshot.projectRoots || {})[projectId];
82
+ if (fromState && fromState.canonicalGitRoot) return fromState.canonicalGitRoot;
83
+ if (projectRootsOptions[projectId]) return projectRootsOptions[projectId];
84
+ if (projectRootsConfig[projectId]) return projectRootsConfig[projectId];
85
+ return null;
86
+ }
48
87
  // Independent Bridge consumer. Registering/draining is explicit (notify or
49
88
  // admin call); constructing never starts network loops.
50
89
  const bridgeUrl = options.bridgeUrl || process.env.KB_EVENT_BRIDGE_URL || '';
@@ -158,22 +197,7 @@ function createWorkflowServer(options = {}) {
158
197
  const { replayed, result, revision } = await store.mutate({
159
198
  requestId: body.requestId,
160
199
  payload: { op: 'createMember', member: body },
161
- op: snapshot => {
162
- domain.requireTeam(snapshot);
163
- const draft = { name: body.name, role: body.role, driverId: body.driverId, profileId: body.profileId, model: body.model, memoryGroupIds: body.memoryGroupIds };
164
- const errors = domain.validateMemberInput(draft);
165
- if (errors.length) throw new WorkflowError('VALIDATION', `Invalid member: ${errors.join('; ')}`);
166
- const crypto = require('crypto');
167
- const memberId = `member_${crypto.randomBytes(10).toString('hex')}`;
168
- snapshot.members[memberId] = {
169
- memberId, teamId: snapshot.team.teamId,
170
- name: String(body.name).trim(), role: body.role,
171
- driverId: body.driverId || null, profileId: body.profileId || null, model: body.model || null,
172
- memoryGroupIds: Array.isArray(body.memoryGroupIds) ? body.memoryGroupIds.map(String) : [],
173
- enabled: true, revision: 1, createdAt: new Date().toISOString(),
174
- };
175
- return domain.publicMember(snapshot.members[memberId]);
176
- },
200
+ op: snapshot => domain.addMember(snapshot, body),
177
201
  });
178
202
  return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, member: result });
179
203
  }
@@ -271,7 +295,24 @@ function createWorkflowServer(options = {}) {
271
295
  payload: { op: 'createTask', input: body },
272
296
  op: snapshot => {
273
297
  if (!snapshot.team) throw new WorkflowError('VALIDATION', 'Create the default team before starting tasks.');
274
- return tasksDomain.createTask(snapshot, body);
298
+ // P2b: team activation is TRUSTED-ONLY. A browser POST carrying
299
+ // executionMode is silently degraded to a plain task (the field
300
+ // never arms paid/writable execution without the runtime token).
301
+ const createInput = { ...body };
302
+ if (createInput.executionMode === 'team' && !isTrustedRequest(req)) delete createInput.executionMode;
303
+ const task = tasksDomain.createTask(snapshot, createInput);
304
+ // M0-A: creation and its verifiable repo binding land in ONE
305
+ // transaction — a retry with the same requestId replays both, so
306
+ // a timeout never builds a duplicate card on a second write.
307
+ const root = resolveProjectRoot(snapshot, task.projectId);
308
+ if (root) {
309
+ tasksDomain.bindTaskRepo(snapshot, task.taskId, { canonicalGitRoot: root, hintRepoPath: body.repoPath, basis: state.managed ? 'managed-config' : 'project-config' });
310
+ } else if (body.repoPath) {
311
+ // No trusted mapping yet: keep the hint verbatim, keep the task
312
+ // honestly unbound, and let the review gate fail before spawn.
313
+ snapshot.tasks[task.taskId].repoPathHint = String(body.repoPath);
314
+ }
315
+ return tasksDomain.publicTask(snapshot.tasks[task.taskId], snapshot);
275
316
  },
276
317
  });
277
318
  return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, task: result });
@@ -279,13 +320,26 @@ function createWorkflowServer(options = {}) {
279
320
  throw new WorkflowError('NOT_FOUND', 'Unsupported method for /workflow-tasks.');
280
321
  }
281
322
 
282
- const taskMatch = pathname.match(/^\/api\/workflow\/v1\/workflow-tasks\/([^/]+)(?:\/(session-bindings|checkpoints|runs|acceptance-decisions|reviews))?$/);
323
+ const taskMatch = pathname.match(/^\/api\/workflow\/v1\/workflow-tasks\/([^/]+)(?:\/(session-bindings|checkpoints|runs|acceptance-decisions|reviews|blocking))?$/);
283
324
  if (taskMatch) {
284
325
  const taskId = taskMatch[1];
285
326
  const sub = taskMatch[2] || null;
286
327
  if (!sub && method === 'GET') {
287
328
  const snapshot = await store.read();
288
- return send(res, 200, { task: tasksDomain.publicTask(tasksDomain.requireTask(snapshot, taskId)) });
329
+ return send(res, 200, { task: tasksDomain.publicTask(tasksDomain.requireTask(snapshot, taskId), snapshot) });
330
+ }
331
+ if (sub === 'blocking' && method === 'GET') {
332
+ // M2-B (GLM plan w1): the direct-blocking view — tasks that this
333
+ // task DEPENDS ON and that are not done/cancelled. Read-only,
334
+ // derived, never a second source of truth.
335
+ const snapshot = await store.read();
336
+ const task = tasksDomain.requireTask(snapshot, taskId);
337
+ const blocking = (task.dependencies || [])
338
+ .map(depId => snapshot.tasks[depId])
339
+ .filter(Boolean)
340
+ .filter(dep => !['done', 'cancelled'].includes(dep.status))
341
+ .map(dep => ({ taskId: dep.taskId, title: dep.title, status: dep.status, phase: dep.phase }));
342
+ return send(res, 200, { taskId, blocking, count: blocking.length });
289
343
  }
290
344
  if (!sub && method === 'PATCH') {
291
345
  const body = await readJsonBody(req);
@@ -298,30 +352,211 @@ function createWorkflowServer(options = {}) {
298
352
  return send(res, 200, { ok: true, replayed, revision, task: result });
299
353
  }
300
354
  if (sub === 'reviews' && method === 'POST') {
301
- // W5: run the deterministic checks over a fresh snapshot of the
302
- // task's repository, persist receipts, and let the receipt verdicts
303
- // drive automated acceptance. Model review orchestration (Workbench
304
- // background execution) stays honestly 'pending-model-review' until
305
- // its slice ships — nothing here fakes an opinion.
355
+ // M0-B: the POST atomically reserves a review job (job + pinned
356
+ // snapshot persist in one mutation) and answers quickly with the
357
+ // reviewJobId. The deterministic checks run OUTSIDE the store
358
+ // transaction; results land through completeReviewJob, which
359
+ // re-verifies occupancy, acceptanceRevision and the snapshot before
360
+ // anything is applied. Model review stays honestly pending.
306
361
  const body = await readJsonBody(req);
307
362
  requireId(body.requestId);
308
363
  const preSnapshot = await store.read();
309
- const repoPath = body.repoPath || taskRepoPath(preSnapshot, taskId);
310
- if (!repoPath || !fs.existsSync(repoPath)) throw new WorkflowError('VALIDATION', '任务的仓库路径不可用(repoPath)。', { taskId });
364
+ const preTask = tasksDomain.requireTask(preSnapshot, taskId);
365
+ // M0-A: resolve the check repository BEFORE any subprocess starts.
366
+ // The bound root wins; the client repoPath is only a match hint. An
367
+ // unbound task fails here — an untrusted caller can never point the
368
+ // checks at an arbitrary path by supplying repoPath.
369
+ let repoPath = preTask.repoPath;
370
+ if (repoPath && body.repoPath) {
371
+ const hint = tasksDomain.realDir(body.repoPath, 'repoPath');
372
+ if (!tasksDomain.sameTree(repoPath, hint)) {
373
+ throw new WorkflowError('FORBIDDEN', 'repoPath 与任务绑定的 Git 根不一致(同名仓或目录不符)。', { taskId, reason: 'repo-mismatch', repoPath: hint, canonicalGitRoot: repoPath });
374
+ }
375
+ } else if (!repoPath) {
376
+ if (isTrustedRequest(req) && body.canonicalGitRoot) {
377
+ const bound = await store.mutate({
378
+ requestId: `${body.requestId}:bind`,
379
+ payload: { op: 'bindTaskRepo', taskId, canonicalGitRoot: body.canonicalGitRoot, hintRepoPath: body.repoPath || null },
380
+ op: snapshot => tasksDomain.bindTaskRepo(snapshot, taskId, { canonicalGitRoot: body.canonicalGitRoot, hintRepoPath: body.repoPath, basis: 'managed-forward' }),
381
+ });
382
+ repoPath = bound.result.repoPath;
383
+ } else {
384
+ throw new WorkflowError('VALIDATION', '任务未绑定 Git 根(REPO_UNBOUND):需要受信的项目映射后才能运行检查。', { taskId, reason: 'repo-unbound' });
385
+ }
386
+ }
387
+ if (!fs.existsSync(repoPath)) throw new WorkflowError('VALIDATION', '任务的仓库路径不可用(repoPath)。', { taskId });
311
388
  const tools = Array.isArray(body.tools) && body.tools.length ? body.tools : ['eslint'];
312
- const runResult = await runChecks(repoPath, { tools, policyHash: body.policyHash || 'policy:none', acceptanceRevision: preSnapshot.tasks[taskId].acceptanceRevision, config: body.config || {} });
313
- const applied = await store.mutate({
389
+ const included = Array.isArray(body.included) ? body.included : undefined;
390
+ const reserved = await store.mutate({
314
391
  requestId: body.requestId,
315
- payload: { op: 'applyChecks', taskId, receiptVerdicts: runResult.receipts.map(r => [r.toolId, r.verdict]) },
316
- op: state => tasksDomain.applyCheckReceipts(state, taskId, { snapshot: runResult.snapshot, receipts: runResult.receipts, policyHash: body.policyHash || 'policy:none' }),
392
+ payload: { op: 'reserveReviewJob', taskId, tools, policyHash: body.policyHash || 'policy:none', included: included || [] },
393
+ op: snapshot => tasksDomain.reserveReviewJob(snapshot, taskId, { tools, policyHash: body.policyHash || 'policy:none', repoPath, included }),
317
394
  });
318
- return send(res, applied.replayed ? 200 : 201, {
319
- ok: true, replayed: applied.replayed, revision: applied.revision,
320
- snapshot: { snapshotId: runResult.snapshot.snapshotId, fileCount: runResult.snapshot.fileCount },
321
- receipts: runResult.receipts.map((r, i) => ({ receiptId: (applied.result.receiptIds || [])[i] || null, toolId: r.toolId, verdict: r.verdict, findingCount: r.findingCount ?? r.findings?.length ?? 0, completeness: r.completeness, executionStatus: r.executionStatus, message: r.message })),
322
- decision: applied.result.decision,
395
+ const job = reserved.result.job;
396
+ const reviewSnapshot = reserved.result.snapshot;
397
+ // Checks outside the transaction. Whatever happens, the job records
398
+ // the outcome: completed receipts, a stale snapshot, or a failure.
399
+ runChecks(repoPath, {
400
+ tools: job.tools, policyHash: job.policyHash, acceptanceRevision: job.acceptanceRevision,
401
+ config: body.config || {}, included: job.included.length ? job.included : undefined, snapshot: reviewSnapshot,
402
+ })
403
+ .then(runResult => store.mutate({
404
+ requestId: `${body.requestId}:result`,
405
+ payload: { op: 'completeReviewJob', reviewJobId: job.reviewJobId },
406
+ op: state => tasksDomain.completeReviewJob(state, job.reviewJobId, { snapshot: runResult.snapshot, receipts: runResult.receipts, executionToken: job.executionToken }),
407
+ }))
408
+ .then(async completed => {
409
+ // M1-A/P1a: when the task carries model_review items and a trusted
410
+ // reviewer runtime is configured, dispatch the native reviewer
411
+ // with the bounded material of THIS job's verified snapshot.
412
+ const snapshot = await store.read();
413
+ const config = snapshot.reviewerConfig;
414
+ const taskNow = snapshot.tasks[taskId];
415
+ const wantsModelReview = taskNow && (taskNow.acceptance || []).some(a => a.kind === 'model_review');
416
+ // P2a: when the project pinned a reviewer member, that member's
417
+ // configured driver/model must MATCH the trusted reviewer runtime
418
+ // — a mismatch blocks visibly; the member selection is never
419
+ // silently ignored in favor of the global config.
420
+ let reviewerMismatch = null;
421
+ if (wantsModelReview && config) {
422
+ const projectSettings = (snapshot.projects || {})[taskNow.projectId];
423
+ const rid = projectSettings && projectSettings.reviewerMemberId;
424
+ if (rid) {
425
+ const reviewerMember = (snapshot.members || {})[rid];
426
+ if (!reviewerMember) reviewerMismatch = `reviewerMemberId ${rid} 不存在`;
427
+ else {
428
+ const memberModel = reviewerMember.model || null;
429
+ const memberDriver = reviewerMember.driverId || null;
430
+ const modelOk = !memberModel || !config.model || memberModel === config.model;
431
+ const driverOk = !memberDriver || String(memberDriver).toLowerCase() === String(config.provider).toLowerCase();
432
+ if (!modelOk) reviewerMismatch = `项目 Reviewer 成员的模型 ${memberModel} 与受信审查运行配置 ${config.model} 不一致`;
433
+ else if (!driverOk) reviewerMismatch = `项目 Reviewer 成员的驱动 ${memberDriver} 与受信审查提供方 ${config.provider} 不一致`;
434
+ }
435
+ }
436
+ }
437
+ if (wantsModelReview && reviewerMismatch) {
438
+ await store.mutate({
439
+ requestId: `${body.requestId}:reviewermismatch`,
440
+ payload: { op: 'markReviewerMismatch', reviewJobId: job.reviewJobId },
441
+ op: state => {
442
+ const currentJob = (state.reviewJobs || {})[job.reviewJobId];
443
+ if (currentJob) {
444
+ currentJob.modelState = 'blocked-reviewer-mismatch';
445
+ currentJob.modelReview = { status: 'blocked', identityVerified: false, blockedReason: reviewerMismatch, findings: [], finishedAt: new Date().toISOString() };
446
+ }
447
+ return { modelState: 'blocked-reviewer-mismatch' };
448
+ },
449
+ }).catch(() => {});
450
+ return completed;
451
+ }
452
+ if (wantsModelReview && !config) {
453
+ // P1a: the round REQUIRES a model review but no trusted runtime
454
+ // is configured — surface a diagnosable block on the job
455
+ // instead of silently treating 'completed' as finished.
456
+ await store.mutate({
457
+ requestId: `${body.requestId}:modelconfig`,
458
+ payload: { op: 'markModelConfigMissing', reviewJobId: job.reviewJobId },
459
+ op: state => {
460
+ const currentJob = (state.reviewJobs || {})[job.reviewJobId];
461
+ if (currentJob) currentJob.modelState = 'blocked-missing-config';
462
+ return { modelState: 'blocked-missing-config' };
463
+ },
464
+ }).catch(() => {});
465
+ return completed;
466
+ }
467
+ if (!config || !wantsModelReview) return completed;
468
+ const jobReceipts = Object.values(snapshot.checkReceipts || {}).filter(r => r.reviewJobId === job.reviewJobId);
469
+ await store.mutate({
470
+ requestId: `${body.requestId}:modelreserve`,
471
+ payload: { op: 'reserveModelReview', reviewJobId: job.reviewJobId },
472
+ op: state => {
473
+ const currentJob = (state.reviewJobs || {})[job.reviewJobId];
474
+ if (!currentJob || currentJob.status !== 'completed') throw new WorkflowError('CONFLICT', 'Review job is not in a model-reviewable state.');
475
+ currentJob.modelReview = { status: 'running', requestedAt: new Date().toISOString() };
476
+ currentJob.modelState = 'running';
477
+ tasksDomain.appendChange(state, { kind: 'task.model-review-reserved', taskId, reviewJobId: job.reviewJobId });
478
+ console.error('[ai-coding-workflow] model-review reserved', job.reviewJobId);
479
+ return { modelReview: 'running' };
480
+ },
481
+ });
482
+ console.error('[ai-coding-workflow] building review material for', job.reviewJobId);
483
+ const reviewDiff = captureReviewDiff(repoPath, job.included);
484
+ const reviewTree = captureReviewTree(repoPath, reviewSnapshot.files);
485
+ const material = buildReviewMaterial({ taskId, acceptanceRevision: job.acceptanceRevision, snapshot: reviewSnapshot, receipts: jobReceipts, contract: taskNow, policy: job.policyHash, diff: reviewDiff, tree: reviewTree });
486
+ console.error('[ai-coding-workflow] dispatching native reviewer for', job.reviewJobId, 'model:', config.model || '(default)');
487
+ // M1-D optional graph: with an explicit orchestratorDbPath AND a
488
+ // resolvable orchestrator package, the model dispatch runs on the
489
+ // checkpointed LangGraph (dispatch records survive a restart and
490
+ // an unconfirmed dispatch is reconciled, never re-sent). Without
491
+ // it the passthrough stays exactly as before.
492
+ let evidence;
493
+ if (state.orchestratorDbPath && orchestrator) {
494
+ const orchestratorResult = await orchestrator.runReviewJob({
495
+ dbPath: state.orchestratorDbPath,
496
+ reviewJobId: job.reviewJobId,
497
+ taskId,
498
+ initial: { reviewJobId: job.reviewJobId, taskId, stage: 'review', checksDone: true, modelDispatched: false, modelResult: null, decision: null, error: null },
499
+ callbacks: {
500
+ runChecksStage: async () => ({ ok: false, error: 'checks already completed by the review job chain' }),
501
+ runModelStage: async () => {
502
+ const reviewerEvidence = await runNativeReviewer({ config, material });
503
+ return { ok: true, evidence: reviewerEvidence };
504
+ },
505
+ persistCompletion: async graphState => {
506
+ const persisted = await store.mutate({
507
+ requestId: `${body.requestId}:modelresult`,
508
+ payload: { op: 'completeModelReview', reviewJobId: job.reviewJobId },
509
+ op: graphStore => tasksDomain.completeModelReview(graphStore, job.reviewJobId, { executionToken: job.executionToken, evidence: graphState.modelResult }),
510
+ });
511
+ return { ok: true, decision: persisted.result && persisted.result.modelReview ? persisted.result.modelReview.status : null };
512
+ },
513
+ },
514
+ });
515
+ if (orchestratorResult.dispatchUnknown) {
516
+ console.error('[ai-coding-workflow] orchestrator reconciled dispatch_unknown for', job.reviewJobId, '- no re-dispatch');
517
+ evidence = { verdict: 'blocked', blockedReason: 'MODEL_DISPATCH_UNKNOWN: the checkpointed dispatch could not be confirmed; reconcile before re-sending.', startedAt: new Date().toISOString(), finishedAt: new Date().toISOString() };
518
+ } else {
519
+ evidence = orchestratorResult.state.modelResult || { verdict: 'blocked', blockedReason: 'orchestrator produced no evidence' };
520
+ }
521
+ } else {
522
+ evidence = await runNativeReviewer({ config, material });
523
+ }
524
+ console.error('[ai-coding-workflow] native reviewer finished', job.reviewJobId, evidence.verdict, evidence.blockedReason || '');
525
+ return store.mutate({
526
+ requestId: `${body.requestId}:modelresult`,
527
+ payload: { op: 'completeModelReview', reviewJobId: job.reviewJobId },
528
+ op: graphStore => tasksDomain.completeModelReview(graphStore, job.reviewJobId, { executionToken: job.executionToken, evidence }),
529
+ });
530
+ })
531
+ .catch(async error => {
532
+ // Check failures fail the job; model-review failures mark the
533
+ // modelReview stage blocked with its diagnostic.
534
+ const snapshot = await store.read().catch(() => null);
535
+ const currentJob = snapshot && (snapshot.reviewJobs || {})[job.reviewJobId];
536
+ if (currentJob && currentJob.status === 'completed') {
537
+ await store.mutate({
538
+ requestId: `${body.requestId}:modelfail`,
539
+ payload: { op: 'failModelReview', reviewJobId: job.reviewJobId },
540
+ op: state => tasksDomain.completeModelReview(state, job.reviewJobId, { executionToken: job.executionToken, evidence: { verdict: 'blocked', blockedReason: `model-review-dispatch-failed: ${error.message}`.slice(0, 200) } }),
541
+ }).catch(() => {});
542
+ } else {
543
+ await store.mutate({
544
+ requestId: `${body.requestId}:fail`,
545
+ payload: { op: 'failReviewJob', reviewJobId: job.reviewJobId },
546
+ op: state => tasksDomain.failReviewJob(state, job.reviewJobId, { executionToken: job.executionToken, message: error.message }),
547
+ }).catch(() => { /* the job stays 'running' honestly; a retry re-requests */ });
548
+ }
549
+ });
550
+ return send(res, reserved.replayed ? 200 : 202, {
551
+ ok: true,
552
+ replayed: reserved.replayed,
553
+ reviewJobId: job.reviewJobId,
554
+ status: job.status,
555
+ taskId,
556
+ snapshot: { snapshotId: job.snapshotId, fileCount: job.fileCount },
557
+ acceptanceRevision: job.acceptanceRevision,
558
+ poll: `/api/workflow/v1/review-jobs/${job.reviewJobId}`,
323
559
  modelReview: 'pending-model-review',
324
- task: tasksDomain.publicTask((await store.read()).tasks[taskId]),
325
560
  });
326
561
  }
327
562
  if (sub && method === 'POST') {
@@ -336,7 +571,7 @@ function createWorkflowServer(options = {}) {
336
571
  if (sub === 'runs') return tasksDomain.addRun(snapshot, taskId, body);
337
572
  if (sub === 'acceptance-decisions') {
338
573
  const decision = tasksDomain.recordAcceptanceDecision(snapshot, taskId, body);
339
- return { decision, task: tasksDomain.publicTask(snapshot.tasks[taskId]) };
574
+ return { decision, task: tasksDomain.publicTask(snapshot.tasks[taskId], snapshot) };
340
575
  }
341
576
  throw new WorkflowError('NOT_FOUND', 'Unknown task subresource.');
342
577
  },
@@ -355,6 +590,19 @@ function createWorkflowServer(options = {}) {
355
590
  return send(res, 200, { receipt });
356
591
  }
357
592
 
593
+ // M0-B: read a persisted review job and its receipts. The execution
594
+ // token never leaves the server — results are read, not claimed.
595
+ const jobMatch = pathname.match(/^\/api\/workflow\/v1\/review-jobs\/([^/]+)$/);
596
+ if (jobMatch && method === 'GET') {
597
+ const snapshot = await store.read();
598
+ const job = (snapshot.reviewJobs || {})[jobMatch[1]];
599
+ if (!job) throw new WorkflowError('NOT_FOUND', 'Review job not found.', { reviewJobId: jobMatch[1] });
600
+ const receipts = (job.receiptIds || []).map(rid => (snapshot.checkReceipts || {})[rid]).filter(Boolean)
601
+ .map(r => ({ receiptId: r.receiptId, toolId: r.toolId, verdict: r.verdict, findingCount: r.findingCount ?? r.findings?.length ?? 0, completeness: r.completeness, executionStatus: r.executionStatus, message: r.message, snapshotId: r.snapshotId, acceptanceRevision: r.acceptanceRevision, policyHash: r.policyHash }));
602
+ const { executionToken, ...publicJob } = job;
603
+ return send(res, 200, { job: { ...publicJob, modelState: publicJob.modelState || null, overallStatus: tasksDomain.jobOverallStatus(job) }, receipts, task: tasksDomain.publicTask(tasksDomain.requireTask(snapshot, job.taskId), snapshot) });
604
+ }
605
+
358
606
  // ---------- digests + reminders (W7) ----------
359
607
 
360
608
  if (pathname === '/api/workflow/v1/daily-digests' && method === 'GET') {
@@ -418,17 +666,117 @@ function createWorkflowServer(options = {}) {
418
666
  return send(res, 200, { revision: snapshot.revision, changes, latestSeq: snapshot.changeSeq || 0, truncated: (snapshot.changes || []).filter(c => c.seq > after).length > changes.length });
419
667
  }
420
668
 
669
+ // M0-A: trusted project → canonical Git root registry. The managed shell
670
+ // (and only the runtime-token holder) writes the mapping the task repo
671
+ // binding resolves against; reads answer the same trust level.
672
+ // P2b: trusted endpoint persisting a REAL Leader plan for a team task.
673
+ // Budget reservation + contract validation live in the domain; only the
674
+ // runtime token may call this (the shell forwards it for the leader run).
675
+ if (pathname === '/api/internal/team-plan' && method === 'POST') {
676
+ if (!isTrustedRequest(req)) throw new WorkflowError('UNAUTHENTICATED', 'Internal endpoints require the runtime token.');
677
+ const body = await readJsonBody(req);
678
+ requireId(body.requestId);
679
+ const { replayed, result, revision } = await store.mutate({
680
+ requestId: body.requestId,
681
+ payload: { op: 'applyTeamPlan', taskId: body.taskId, plan: body.plan, leaderMemberId: body.leaderMemberId, leaderRun: body.leaderRun },
682
+ op: snapshot => tasksDomain.applyTeamPlan(snapshot, body.taskId, { plan: body.plan, leaderMemberId: body.leaderMemberId, leaderRun: body.leaderRun }),
683
+ });
684
+ return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, ...result });
685
+ }
686
+
687
+ // P3a: work-item claim/report subresources (team tasks). Same-origin
688
+ // writes like every task mutation — claiming records WHO executes; the
689
+ // review pipeline (not these endpoints) decides acceptance.
690
+ const workItemMatch = pathname.match(/^\/api\/workflow\/v1\/workflow-tasks\/([^/]+)\/work-items\/([^/]+)\/(claim|report)$/);
691
+ if (workItemMatch && method === 'POST') {
692
+ const [, taskId, workItemId, action] = workItemMatch;
693
+ const body = await readJsonBody(req);
694
+ requireId(body.requestId);
695
+ const { replayed, result, revision } = await store.mutate({
696
+ requestId: body.requestId,
697
+ payload: { op: 'workItem.' + action, taskId, workItemId, body },
698
+ op: snapshot => action === 'claim'
699
+ ? { workItem: tasksDomain.claimWorkItem(snapshot, taskId, workItemId, { claimedBy: body.claimedBy || null, executionRef: body.executionRef || null }) }
700
+ : { workItem: tasksDomain.reportWorkItem(snapshot, taskId, workItemId, { claimedBy: body.claimedBy || null, summary: body.summary, testedWith: body.testedWith, artifacts: body.artifacts }) },
701
+ });
702
+ return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, ...result });
703
+ }
704
+
705
+ if (pathname === '/api/internal/reviewer-config') {
706
+ if (!isTrustedRequest(req)) throw new WorkflowError('UNAUTHENTICATED', 'Internal endpoints require the runtime token.');
707
+ if (method === 'GET') {
708
+ const snapshot = await store.read();
709
+ const config = snapshot.reviewerConfig;
710
+ return send(res, 200, { configured: Boolean(config), provider: config ? config.provider : null, allowedModels: config ? config.allowedModels : [], updatedAt: config ? config.updatedAt : null });
711
+ }
712
+ if (method === 'POST') {
713
+ const body = await readJsonBody(req);
714
+ requireId(body.requestId);
715
+ const { replayed, result, revision } = await store.mutate({
716
+ requestId: body.requestId,
717
+ payload: { op: 'putReviewerConfig', provider: body.provider, entry: body.entry, allowedModels: body.allowedModels, model: body.model },
718
+ op: snapshot => {
719
+ if (!body.provider || !body.entry || !Array.isArray(body.allowedModels) || !body.allowedModels.length) {
720
+ throw new WorkflowError('VALIDATION', 'reviewer config needs provider, entry and a non-empty allowedModels list.');
721
+ }
722
+ const allowedModels = body.allowedModels.map(String);
723
+ // M1-A: the explicit reviewer model must be pre-flighted — it is
724
+ // validated here AND re-checked against the run output later.
725
+ if (body.model && !allowedModels.includes(String(body.model))) {
726
+ throw new WorkflowError('VALIDATION', 'reviewer config model must be one of allowedModels.', { reason: 'reviewer-model-not-allowed' });
727
+ }
728
+ snapshot.reviewerConfig = {
729
+ provider: String(body.provider),
730
+ entry: String(body.entry),
731
+ allowedModels,
732
+ model: body.model ? String(body.model) : undefined,
733
+ timeoutMs: Number(body.timeoutMs) || undefined,
734
+ updatedAt: new Date().toISOString(),
735
+ };
736
+ tasksDomain.appendChange(snapshot, { kind: 'reviewer.config-set', provider: snapshot.reviewerConfig.provider });
737
+ return { configured: true, provider: snapshot.reviewerConfig.provider };
738
+ },
739
+ });
740
+ return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, ...result });
741
+ }
742
+ throw new WorkflowError('NOT_FOUND', 'Unsupported method for /internal/reviewer-config.');
743
+ }
744
+
745
+ if (pathname === '/api/internal/project-roots') {
746
+ if (!isTrustedRequest(req)) throw new WorkflowError('UNAUTHENTICATED', 'Internal endpoints require the runtime token.');
747
+ if (method === 'GET') {
748
+ const snapshot = await store.read();
749
+ return send(res, 200, { roots: snapshot.projectRoots || {} });
750
+ }
751
+ if (method === 'POST') {
752
+ const body = await readJsonBody(req);
753
+ requireId(body.requestId);
754
+ const { replayed, result, revision } = await store.mutate({
755
+ requestId: body.requestId,
756
+ payload: { op: 'putProjectRoot', projectId: body.projectId, canonicalGitRoot: body.canonicalGitRoot },
757
+ op: snapshot => tasksDomain.putProjectRoot(snapshot, body.projectId, body.canonicalGitRoot),
758
+ });
759
+ return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, ...result });
760
+ }
761
+ throw new WorkflowError('NOT_FOUND', 'Unsupported method for /internal/project-roots.');
762
+ }
763
+
421
764
  if (pathname === '/api/internal/context-bindings/validate' && method === 'POST') {
422
765
  if (!isTrustedRequest(req)) throw new WorkflowError('UNAUTHENTICATED', 'Internal endpoints require the runtime token.');
423
- // W4: read-only validation for the engine. Valid requires an OPEN
424
- // session binding for (client, nativeSessionId) whose member exists,
425
- // is enabled, and — when the caller pins a memberId — matches. The
426
- // answer carries the member revision so the engine can reject stale
427
- // local projections. This never widens: any miss returns valid:false.
766
+ // W4 + M1-C: read-only validation for the engine. Valid requires an
767
+ // OPEN session binding for (client, nativeSessionId) whose member
768
+ // exists, is enabled, matches the pinned memberId and — when the
769
+ // caller pins a projectId — belongs to a task OF THAT PROJECT, with a
770
+ // VERIFIED binding basis for member-memory reads (a 'declared' basis
771
+ // only ever justifies event attribution, never memory). The answer
772
+ // carries the member revision so the engine can reject stale local
773
+ // projections. This never widens: any miss returns valid:false.
428
774
  const body = await readJsonBody(req);
429
775
  const client = String(body.client || '');
430
776
  const sessionId = String(body.sessionId || '');
431
777
  const memberId = String(body.memberId || '');
778
+ const projectId = body.projectId ? String(body.projectId) : null;
779
+ const requireVerifiedBasis = body.requireVerifiedBasis === true;
432
780
  if (!client || !sessionId || !memberId) return send(res, 200, { valid: false, reason: 'missing-identity' });
433
781
  const snapshot = await store.read();
434
782
  const open = Object.values(snapshot.sessionBindings).find(b => !b.validTo && b.client === client && b.nativeSessionId === sessionId);
@@ -436,7 +784,16 @@ function createWorkflowServer(options = {}) {
436
784
  if (open.memberId !== memberId) return send(res, 200, { valid: false, reason: 'binding-member-mismatch' });
437
785
  const member = snapshot.members[memberId];
438
786
  if (!member || !member.enabled) return send(res, 200, { valid: false, reason: 'member-missing-or-disabled' });
439
- return send(res, 200, { valid: true, memberId, memberRevision: member.revision, epoch: `rev${snapshot.revision}` });
787
+ if (requireVerifiedBasis && open.verificationBasis === 'declared') {
788
+ return send(res, 200, { valid: false, reason: 'binding-not-verified', verificationBasis: open.verificationBasis });
789
+ }
790
+ let projectMatched = null;
791
+ if (projectId) {
792
+ const task = snapshot.tasks[open.taskId];
793
+ projectMatched = Boolean(task && task.projectId === projectId);
794
+ if (!projectMatched) return send(res, 200, { valid: false, reason: 'binding-project-mismatch', projectId });
795
+ }
796
+ return send(res, 200, { valid: true, memberId, memberRevision: member.revision, epoch: `rev${snapshot.revision}`, verificationBasis: open.verificationBasis || 'declared', projectId: projectId || (snapshot.tasks[open.taskId] && snapshot.tasks[open.taskId].projectId) || null, projectMatched });
440
797
  }
441
798
 
442
799
  // Bridge wake-up callback. Body is intentionally ignored (family contract