@ran-sh/dsh-crew 0.3.6 → 0.3.7

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 (78) hide show
  1. package/.claude-plugin/plugin.json +8 -8
  2. package/.mcp.json +8 -8
  3. package/LICENSE +21 -21
  4. package/README.de.md +359 -359
  5. package/README.es.md +359 -359
  6. package/README.fr.md +359 -359
  7. package/README.hi.md +359 -359
  8. package/README.id.md +359 -359
  9. package/README.ja.md +359 -359
  10. package/README.ko.md +359 -359
  11. package/README.md +125 -180
  12. package/README.pt.md +359 -359
  13. package/README.ru.md +359 -359
  14. package/README.th.md +359 -359
  15. package/README.tr.md +359 -359
  16. package/README.vi.md +359 -359
  17. package/README.zh-TW.md +359 -359
  18. package/README.zh.md +125 -180
  19. package/agents/ds-flash.md +26 -26
  20. package/agents/ds-pro.md +32 -32
  21. package/agents/ds-reviewer.md +23 -23
  22. package/agents/ds-worker.md +22 -22
  23. package/codex/agents/ds-flash.toml +30 -30
  24. package/codex/agents/ds-pro.toml +31 -31
  25. package/codex/agents/ds-reviewer.toml +28 -28
  26. package/codex/agents/ds-worker.toml +28 -28
  27. package/codex/prompts/dsh-config.md +3 -3
  28. package/codex/prompts/dsh-status.md +1 -1
  29. package/commands/config.md +11 -11
  30. package/commands/off.md +5 -5
  31. package/commands/on.md +5 -5
  32. package/commands/status.md +5 -5
  33. package/cordis.patch.yml +4 -4
  34. package/lib/client.js +3446 -2765
  35. package/package.json +131 -131
  36. package/scripts/build-client.mjs +28 -28
  37. package/scripts/live-crew-smoke.mjs +39 -39
  38. package/scripts/live-policy-matrix.mjs +177 -177
  39. package/scripts/policy-probe.mjs +101 -101
  40. package/scripts/setup.mjs +284 -284
  41. package/scripts/smoke-real.mjs +110 -110
  42. package/scripts/smoke.mjs +78 -78
  43. package/scripts/verify-installer-fix.mjs +26 -26
  44. package/src/adaptive-routing.mjs +260 -260
  45. package/src/client/activation-summary.tsx +64 -64
  46. package/src/client/collapsible-sections.mjs +55 -0
  47. package/src/client/entry.tsx +236 -236
  48. package/src/client/index.tsx +1213 -1120
  49. package/src/config-readiness.mjs +59 -59
  50. package/src/delivery.mjs +205 -205
  51. package/src/dsh-cli-runtime.mjs +239 -239
  52. package/src/failure-classification.mjs +172 -172
  53. package/src/hub/entry.mjs +98 -98
  54. package/src/hub-client.mjs +132 -132
  55. package/src/hub-compatibility.mjs +49 -49
  56. package/src/i18n.mjs +19 -19
  57. package/src/install/cli.mjs +28 -28
  58. package/src/install/install-legacy.mjs +462 -462
  59. package/src/install/install.mjs +451 -451
  60. package/src/install/npx-lifecycle.mjs +1055 -1055
  61. package/src/mcp-runtime.mjs +257 -257
  62. package/src/model-catalog.mjs +173 -173
  63. package/src/model-routing.mjs +391 -391
  64. package/src/policy.mjs +197 -197
  65. package/src/readiness-matrix.mjs +169 -169
  66. package/src/runtime-controls.mjs +90 -90
  67. package/src/runtime-identity.mjs +108 -108
  68. package/src/server.mjs +477 -477
  69. package/src/status-shard.mjs +52 -52
  70. package/src/structured-error-code.mjs +38 -38
  71. package/src/vision-route.mjs +138 -138
  72. package/src/workflow-runtime.mjs +573 -573
  73. package/src/workflow.mjs +160 -160
  74. package/src/workspace-audit.mjs +231 -231
  75. package/src/workspace-isolation.mjs +365 -365
  76. package/statusline/statusline.sh +14 -14
  77. package/statusline/worker-segment.sh +35 -35
  78. package/worker.cordis.yml +77 -77
@@ -1,573 +1,573 @@
1
- // Workflow runtime: the single business flow for every worker dispatch, shared
2
- // by blocking (dsh_run_worker) and async (dsh_spawn_worker) and by Hub and
3
- // Standalone execution — the only difference between those transports is which
4
- // adapter executes an attempt and whether the caller awaits.
5
- //
6
- // A Workflow Job is one logical delegation; an Attempt is one actual DSH
7
- // worker/reviewer session within it. The runtime owns the state machine
8
- // (phase transitions guarded by workflow.canTransition), the attempt loop
9
- // (verify -> escalate on evidence -> reviewer pass -> finalize), candidate
10
- // capture, review mutation detection, concurrency limiting and cancellation.
11
- //
12
- // All I/O is injected through `adapters`, so this module stays testable without
13
- // DSH, a hub, git or a real filesystem. Policy decisions import the pure
14
- // modules (policy.mjs / workflow.mjs) directly; Hub/Standalone specifics never
15
- // appear here.
16
-
17
- import { resolveModelPolicy, shouldAutoReview, getRoleState } from './policy.mjs';
18
- import { buildOutcome, decideNextStep, JOB_PHASES, canTransition } from './workflow.mjs';
19
- import { parseDeliveryReport } from './delivery.mjs';
20
- import { classifyFailure } from './failure-classification.mjs';
21
-
22
- export const WORKFLOW_ERROR_CODES = {
23
- ISOLATION_UNAVAILABLE: 'ISOLATION_UNAVAILABLE',
24
- NOT_GIT_REPOSITORY: 'NOT_GIT_REPOSITORY',
25
- WORKTREE_CREATE_FAILED: 'WORKTREE_CREATE_FAILED',
26
- CANDIDATE_CAPTURE_FAILED: 'CANDIDATE_CAPTURE_FAILED',
27
- WORKFLOW_CANCELLED: 'WORKFLOW_CANCELLED',
28
- ATTEMPT_INFRA_FAILURE: 'ATTEMPT_INFRA_FAILURE',
29
- REVIEWER_MUTATED_CANDIDATE: 'REVIEWER_MUTATED_CANDIDATE',
30
- };
31
-
32
- const TERMINAL = new Set([JOB_PHASES.COMPLETED, JOB_PHASES.FAILED, JOB_PHASES.CANCELLED, JOB_PHASES.INTERRUPTED]);
33
-
34
- function lines(value) {
35
- if (typeof value !== 'string' || value.trim() === '') return [];
36
- return value.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
37
- }
38
-
39
- export function normalizeReviewVerdict(value) {
40
- const s = String(value ?? '').trim().toLowerCase();
41
- if (/^(approve|approved|pass)\b/.test(s) || s === 'pass' || s === 'approve') return 'approve';
42
- if (/request.*chang|chang.*request|reject|needs changes/i.test(s)) return 'request_changes';
43
- return 'inconclusive';
44
- }
45
-
46
- export function normalizeReview({ attemptResult, beforeCandidate, afterCandidate } = {}) {
47
- const parsed = parseDeliveryReport(attemptResult?.result ?? '');
48
- const mutation = mutationDetected(beforeCandidate, afterCandidate);
49
- const reportedVerdict = normalizeReviewVerdict(parsed.sections?.Verdict ?? attemptResult?.result ?? '');
50
- return {
51
- verdict: mutation ? 'request_changes' : reportedVerdict,
52
- reported_verdict: reportedVerdict,
53
- findings: lines(parsed.sections?.['Review Findings']),
54
- evidence: lines(parsed.sections?.Evidence),
55
- risks: lines(parsed.sections?.Risks),
56
- delivery_complete: parsed.complete ?? false,
57
- model: attemptResult?.model ?? null,
58
- provider: attemptResult?.provider ?? null,
59
- selection_trace: attemptResult?.selection_trace ?? null,
60
- status: attemptResult?.status ?? 'failed',
61
- ...(mutation ? { mutated_candidate: true, invalidated: true } : {}),
62
- };
63
- }
64
-
65
- function mutationDetected(before, after) {
66
- if (!before) return false;
67
- if (before.fingerprint == null) return false;
68
- if (!after) return true;
69
- return after.fingerprint != null && before.fingerprint !== after.fingerprint;
70
- }
71
-
72
- function deliveryClaimsChanges(outcome) {
73
- return Array.isArray(outcome?.changes) && outcome.changes.length > 0;
74
- }
75
-
76
- function workspaceEvidenceOK(outcome, candidate) {
77
- if (!candidate) return true;
78
- const hasChanges = Array.isArray(candidate.changed_files) && candidate.changed_files.length > 0;
79
- if (outcome?.execution_status !== 'completed') return true;
80
- return !deliveryClaimsChanges(outcome) || hasChanges;
81
- }
82
-
83
- function sumUsage(attempts) {
84
- const tokens = { input: 0, output: 0, reasoning: 0 };
85
- for (const a of attempts) {
86
- const u = a.usage;
87
- if (!u) continue;
88
- tokens.input += u.input ?? 0;
89
- tokens.output += u.output ?? 0;
90
- tokens.reasoning += u.reasoning ?? 0;
91
- }
92
- return tokens;
93
- }
94
-
95
- export function normalizeMaxParallel(value, fallback = 3) {
96
- const fallbackValue = Number.isInteger(Number(fallback))
97
- ? Math.max(1, Math.min(16, Number(fallback)))
98
- : 3;
99
- const parsed = Number(value);
100
- if (!Number.isInteger(parsed)) return fallbackValue;
101
- return Math.max(1, Math.min(16, parsed));
102
- }
103
-
104
- export function createWorkflowRuntime(adapters, {
105
- maxParallel = 3,
106
- idFactory = () => `wf-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
107
- clock = () => Date.now(),
108
- logger = null,
109
- } = {}) {
110
- const jobs = new Map();
111
- const queue = [];
112
- let active = 0;
113
- let maxParallelLimit = normalizeMaxParallel(maxParallel);
114
-
115
- function log(msg) { logger?.debug?.(`workflow: ${msg}`); }
116
-
117
- function runtimeState() {
118
- return {
119
- max_parallel: maxParallelLimit,
120
- active,
121
- queued: queue.length,
122
- };
123
- }
124
-
125
- function syncLiveMaxParallel() {
126
- if (typeof adapters.getRuntimeControls !== 'function') return false;
127
- const controls = adapters.getRuntimeControls() ?? {};
128
- if (controls.max_parallel === undefined) return false;
129
- const next = normalizeMaxParallel(controls.max_parallel, maxParallelLimit);
130
- if (next === maxParallelLimit) return false;
131
- maxParallelLimit = next;
132
- return true;
133
- }
134
-
135
- function transition(job, to, reason) {
136
- if (job.phase === to) return;
137
- if (!canTransition(job.phase, to)) throw new Error(`illegal workflow transition ${job.phase} -> ${to}`);
138
- job.phase = to;
139
- job.events.push({ at: clock(), phase: to, type: 'phase', reason: reason ?? to });
140
- log(`${job.id} ${to}`);
141
- }
142
-
143
- function createJob(spec) {
144
- const now = clock();
145
- return {
146
- id: idFactory(),
147
- role: spec.role ?? 'worker',
148
- delivery: spec.delivery === 'review' ? 'review' : 'coding',
149
- model_class_hint: spec.model_class_hint === 'pro' ? 'pro' : spec.model_class_hint === 'flash' ? 'flash' : null,
150
- original_task: spec.task,
151
- source: spec.source ?? 'api',
152
- requested_cwd: spec.cwd,
153
- effort: spec.effort ?? 'max',
154
- phase: JOB_PHASES.CREATED,
155
- status: 'running',
156
- cancelling: false,
157
- execution_cwd: spec.cwd,
158
- isolation: 'shared',
159
- base_revision: null,
160
- primary_workspace_dirty: false,
161
- attempts: [],
162
- current_attempt_id: null,
163
- candidate: null,
164
- decision: null,
165
- review: null,
166
- outcome: null,
167
- error: null,
168
- cleanup_warning: null,
169
- candidate_capture_failed: false,
170
- retain_workspace: false,
171
- workspace_retained: false,
172
- events: [{ at: now, phase: JOB_PHASES.CREATED, type: 'created' }],
173
- createdAt: now,
174
- startedAt: now,
175
- endedAt: null,
176
- workspaceHandle: null,
177
- waiters: [],
178
- };
179
- }
180
-
181
- function releaseSlot() {
182
- active = Math.max(0, active - 1);
183
- drain();
184
- }
185
-
186
- function handleKickoffFailure(job, err) {
187
- failJob(job, err);
188
- releaseSlot();
189
- }
190
-
191
- function drain({ sync = true } = {}) {
192
- if (sync) syncLiveMaxParallel();
193
- while (active < maxParallelLimit && queue.length > 0) {
194
- const job = queue.shift();
195
- active += 1;
196
- kickoff(job).catch((err) => handleKickoffFailure(job, err));
197
- }
198
- }
199
-
200
- function setMaxParallel(value) {
201
- maxParallelLimit = normalizeMaxParallel(value, maxParallelLimit);
202
- // Raising the limit admits queued work immediately. Lowering it never
203
- // cancels already-running work: drain simply waits until active drops below
204
- // the new limit.
205
- drain({ sync: false });
206
- return runtimeState();
207
- }
208
-
209
- function refreshRuntimeControls() {
210
- syncLiveMaxParallel();
211
- drain({ sync: false });
212
- return runtimeState();
213
- }
214
-
215
- function setTerminal(job) {
216
- if (job.status !== 'running') return;
217
- if (job.phase === JOB_PHASES.COMPLETED) job.status = 'done';
218
- else if (job.phase === JOB_PHASES.CANCELLED) job.status = 'cancelled';
219
- else job.status = 'failed';
220
- job.endedAt = clock();
221
- job.current_attempt_id = null;
222
- for (const w of job.waiters.splice(0)) w();
223
- }
224
-
225
- function failJob(job, err) {
226
- if (job.status !== 'running') return;
227
- job.error = err?.message ?? String(err);
228
- job.error_code = err?.code ?? err?.policyCode ?? job.error_code ?? null;
229
- job.phase = JOB_PHASES.FAILED;
230
- setTerminal(job);
231
- }
232
-
233
- async function releaseWorkspace(job) {
234
- if (job.retain_workspace) {
235
- job.workspace_retained = true;
236
- return;
237
- }
238
- if (!job.workspaceHandle) return;
239
- try {
240
- const r = await adapters.releaseWorkspace(job.workspaceHandle);
241
- if (!r || r.ok !== true) {
242
- // A failed cleanup leaves the isolated workspace in place; say so
243
- // truthfully instead of claiming a clean release.
244
- job.cleanup_warning = r?.error ?? 'worktree cleanup failed';
245
- job.workspace_retained = true;
246
- }
247
- } catch (err) {
248
- job.cleanup_warning = err?.message ?? String(err);
249
- job.workspace_retained = true;
250
- }
251
- job.workspaceHandle = null;
252
- }
253
-
254
- async function runWorkflow(job) {
255
- const isReviewJob = job.role === 'reviewer' || job.delivery === 'review';
256
- let config = {};
257
-
258
- try {
259
- config = adapters.getConfig?.() ?? {};
260
- const alloc = await adapters.allocateWorkspace?.(job);
261
- if (alloc && alloc.ok === false) {
262
- job.error = alloc.error ?? alloc.reason;
263
- job.phase = JOB_PHASES.FAILED;
264
- if (alloc.reason) job.error_code = alloc.reason;
265
- setTerminal(job);
266
- return;
267
- }
268
- if (alloc && alloc.ok) {
269
- job.workspaceHandle = alloc.handle ?? null;
270
- job.execution_cwd = alloc.execution_cwd ?? job.requested_cwd;
271
- job.isolation = alloc.isolation ?? 'worktree';
272
- job.base_revision = alloc.base_revision ?? null;
273
- job.primary_workspace_dirty = alloc.primary_workspace_dirty === true;
274
- }
275
- transition(job, JOB_PHASES.RUNNING, 'start');
276
-
277
- if (isReviewJob) {
278
- transition(job, JOB_PHASES.REVIEWING, 'explicit reviewer');
279
- const before = alloc?.ok && alloc.isolation === 'worktree' ? await safeCapture(adapters, job.execution_cwd, job.base_revision) : null;
280
- const reviewTask = adapters.buildReviewTask(job.original_task, null);
281
- const review = await runReviewerAttempt(job, reviewTask, config, before);
282
- job.review = review;
283
- if (job.review) transition(job, JOB_PHASES.READY, 'review complete');
284
- finalize(job);
285
- return;
286
- }
287
-
288
- let attempt = 0;
289
- let escalationReason = null;
290
- for (;;) {
291
- if (job.cancelling) { cancelWorkflow(job); return; }
292
- if (attempt > 0) transition(job, JOB_PHASES.RUNNING, `escalated attempt ${attempt}`);
293
- const policy = resolveModelPolicy(config, 'worker', { attempt });
294
- const attemptId = attemptIdFor(adapters, job.id, attempt === 0 ? '' : String(attempt));
295
- job.current_attempt_id = attemptId;
296
- job.events.push({ at: clock(), phase: job.phase, type: 'attempt/start', attempt, escalation_reason: escalationReason });
297
- const ar = await adapters.executeAttempt({
298
- id: attemptId,
299
- workflowId: job.id,
300
- role: 'worker',
301
- attempt,
302
- task: job.original_task,
303
- cwd: job.execution_cwd,
304
- effort: job.effort,
305
- policy,
306
- source: job.source,
307
- model_class_hint: job.model_class_hint,
308
- escalation_reason: escalationReason,
309
- onAttemptStarted: (actualId) => {
310
- if (typeof actualId === 'string' && actualId) job.current_attempt_id = actualId;
311
- },
312
- });
313
- job.current_attempt_id = null;
314
- if (job.cancelling) { cancelWorkflow(job); return; }
315
- const attemptView = attemptRecord(ar, attempt);
316
- job.attempts.push(attemptView);
317
- if (ar.infra === true) {
318
- failJob(job, Object.assign(new Error(ar.error ?? 'infrastructure failure'), { code: WORKFLOW_ERROR_CODES.ATTEMPT_INFRA_FAILURE }));
319
- return;
320
- }
321
- const outcome = ar.outcome ?? buildOutcome({
322
- result: ar.result ?? '',
323
- stopReason: ar.stopReason,
324
- executionStatus: ar.status === 'done' ? 'completed' : 'failed',
325
- });
326
- transition(job, JOB_PHASES.VERIFYING, `attempt ${attempt} complete`);
327
-
328
- // Capture the latest candidate after every attempt. Capture failure is
329
- // not allowed to delete the only recoverable state: retain the worktree
330
- // and preserve the worker business result, while surfacing the warning.
331
- if (alloc?.ok && alloc.isolation === 'worktree') {
332
- const candidate = await safeCapture(adapters, job.execution_cwd, job.base_revision);
333
- if (candidate === null) {
334
- job.candidate_capture_failed = true;
335
- job.retain_workspace = true;
336
- job.candidate = null;
337
- job.events.push({ at: clock(), phase: job.phase, type: 'candidate/failed', attempt, message: 'candidate capture failed; worktree retained for recovery' });
338
- } else {
339
- job.candidate = candidate;
340
- attemptView.candidate_fingerprint = candidate.fingerprint ?? null;
341
- outcome.workspace_evidence_ok = workspaceEvidenceOK(outcome, candidate);
342
- if (candidate.complete === false || candidate.replayable === false) {
343
- job.retain_workspace = true;
344
- job.events.push({ at: clock(), phase: job.phase, type: 'candidate/incomplete', attempt, message: 'candidate is not fully replayable; worktree retained' });
345
- }
346
- }
347
- }
348
- job.outcome = outcome;
349
-
350
- const reviewRequested = !isReviewJob && shouldAutoReview(config);
351
- const reviewerAuto = getRoleState(config, 'reviewer') !== 'disabled';
352
- const decision = decideNextStep({ outcome, policy, attempt, reviewRequested, reviewerAuto });
353
- job.decision = { step: decision.step, phase: decision.phase, reason: decision.reason };
354
- job.events.push({ at: clock(), phase: job.phase, type: 'attempt/complete', attempt, decision: decision.step });
355
-
356
- if (job.cancelling) { cancelWorkflow(job); return; }
357
- if (decision.step === 'fail') {
358
- const finalAttemptCode = ar.status === 'failed' ? attemptView.error_code : null;
359
- failJob(job, Object.assign(new Error(`workflow failed: ${decision.reason}`), { code: finalAttemptCode }));
360
- return;
361
- }
362
- if (decision.step === 'escalate') {
363
- transition(job, JOB_PHASES.ESCALATING, decision.reason);
364
- escalationReason = decision.reason;
365
- attempt += 1;
366
- continue;
367
- }
368
- if (decision.step === 'review') {
369
- transition(job, JOB_PHASES.REVIEWING, 'automatic review');
370
- const before = job.candidate;
371
- const reviewTask = adapters.buildReviewTask(job.original_task, { outcome, candidate: job.candidate ?? null });
372
- const review = await runReviewerAttempt(job, reviewTask, config, before, job.execution_cwd, job.base_revision);
373
- job.review = review;
374
- transition(job, JOB_PHASES.READY, decision.reason);
375
- finalize(job);
376
- return;
377
- }
378
- transition(job, JOB_PHASES.READY, decision.reason);
379
- finalize(job);
380
- return;
381
- }
382
- } catch (err) {
383
- if (job.cancelling) { cancelWorkflow(job); return; }
384
- failJob(job, err);
385
- } finally {
386
- await releaseWorkspace(job);
387
- releaseSlot();
388
- }
389
- }
390
-
391
- async function safeCapture(adapters, cwd, baseRevision) {
392
- if (typeof adapters.captureCandidate !== 'function') return null;
393
- try {
394
- const c = await adapters.captureCandidate({ cwd, baseRevision });
395
- return c && c.ok ? c : null;
396
- } catch { return null; }
397
- }
398
-
399
- async function runReviewerAttempt(job, task, config, beforeCandidate, cwd = job.execution_cwd, baseRevision = job.base_revision) {
400
- const policy = resolveModelPolicy(config, 'reviewer', { attempt: 0 });
401
- const attemptId = attemptIdFor(adapters, job.id, 'review');
402
- job.current_attempt_id = attemptId;
403
- job.events.push({ at: clock(), phase: job.phase, type: 'review/start' });
404
- const ar = await adapters.executeAttempt({
405
- id: attemptId,
406
- workflowId: job.id,
407
- role: 'reviewer',
408
- attempt: 0,
409
- task,
410
- cwd,
411
- effort: job.effort,
412
- policy,
413
- source: job.source,
414
- model_class_hint: 'pro',
415
- escalation_reason: null,
416
- onAttemptStarted: (actualId) => {
417
- if (typeof actualId === 'string' && actualId) job.current_attempt_id = actualId;
418
- },
419
- });
420
- job.current_attempt_id = null;
421
- const attemptView = { ...attemptRecord(ar, 0), phase: 'review' };
422
- job.attempts.push(attemptView);
423
- if (ar.status === 'failed' && attemptView.error_code) job.error_code = attemptView.error_code;
424
- const afterCandidate = job.isolation === 'worktree' ? await safeCapture(adapters, cwd, baseRevision) : null;
425
- return normalizeReview({ attemptResult: ar, beforeCandidate, afterCandidate });
426
- }
427
-
428
- function finalize(job) {
429
- transition(job, JOB_PHASES.COMPLETED, job.review ? 'reviewed' : 'verified');
430
- setTerminal(job);
431
- }
432
-
433
- function attemptRecord(ar, attempt) {
434
- return {
435
- id: ar.id,
436
- role: ar.role ?? 'worker',
437
- attempt,
438
- provider: ar.provider ?? null,
439
- model: ar.model ?? null,
440
- selection_source: ar.selection_source ?? null,
441
- selection_trace: ar.selection_trace ?? null,
442
- status: ar.status ?? 'failed',
443
- result: ar.result ?? null,
444
- stopReason: ar.stopReason ?? null,
445
- outcome: ar.outcome ?? null,
446
- usage: ar.usage ?? null,
447
- error: ar.error ?? null,
448
- error_code: ar.error_code ?? ar.code ?? null,
449
- timed_out: ar.timed_out === true,
450
- };
451
- }
452
-
453
- function attemptIdFor(adapters, workflowId, suffix = '') {
454
- return typeof adapters.attemptId === 'function'
455
- ? adapters.attemptId(workflowId, suffix)
456
- : `${workflowId}-a${suffix || '0'}`;
457
- }
458
-
459
- function cancelWorkflow(job) {
460
- if (job.status !== 'running') return;
461
- job.cancelling = true;
462
- job.events.push({ at: clock(), phase: job.phase, type: 'cancel' });
463
- const activeAttempt = job.current_attempt_id;
464
- if (activeAttempt) adapters.cancelAttempt?.(activeAttempt).catch(() => {});
465
- job.phase = JOB_PHASES.CANCELLED;
466
- job.status = 'cancelled';
467
- job.endedAt = clock();
468
- job.current_attempt_id = null;
469
- for (const w of job.waiters.splice(0)) w();
470
- }
471
-
472
- function workflowView(job, { withResult = false } = {}) {
473
- const failure = classifyFailure({
474
- phase: job.phase,
475
- status: job.status,
476
- errorCode: job.error_code,
477
- outcome: job.outcome,
478
- decision: job.decision,
479
- review: job.review,
480
- childAttempts: job.attempts,
481
- });
482
- const v = {
483
- id: job.id,
484
- role: job.role,
485
- phase: job.phase,
486
- status: job.status,
487
- attempt: job.attempts.length,
488
- current_model: job.attempts[job.attempts.length - 1]?.model ?? null,
489
- model_class_hint: job.model_class_hint,
490
- source: job.source,
491
- requested_cwd: job.requested_cwd,
492
- execution_cwd: job.execution_cwd,
493
- isolation: job.isolation,
494
- base_revision: job.base_revision,
495
- primary_workspace_dirty: job.primary_workspace_dirty,
496
- startedAt: job.createdAt,
497
- updatedAt: job.endedAt ?? clock(),
498
- tokens: sumUsage(job.attempts),
499
- error: job.error ?? null,
500
- error_code: job.error_code ?? null,
501
- failure,
502
- cleanup_warning: job.cleanup_warning ?? null,
503
- candidate_capture_failed: job.candidate_capture_failed === true,
504
- workspace_retained: job.workspace_retained === true,
505
- decision: job.decision,
506
- candidate_available: !!job.candidate,
507
- review_status: job.review ? job.review.status ?? null : null,
508
- };
509
- if (withResult) {
510
- v.child_attempts = job.attempts.map((a) => ({
511
- id: a.id, role: a.role, attempt: a.attempt, provider: a.provider, model: a.model,
512
- selection_source: a.selection_source, selection_trace: a.selection_trace ?? null,
513
- status: a.status, stopReason: a.stopReason,
514
- outcome_task: a.outcome?.task_status ?? null,
515
- error: a.error ?? null, error_code: a.error_code ?? null, timed_out: a.timed_out === true,
516
- candidate_fingerprint: a.candidate_fingerprint ?? null,
517
- tokens: a.usage ?? null,
518
- }));
519
- v.outcome = job.outcome;
520
- v.candidate = job.candidate;
521
- v.review = job.review;
522
- v.events = job.events;
523
- }
524
- return v;
525
- }
526
-
527
- function start(spec) {
528
- syncLiveMaxParallel();
529
- const job = createJob(spec);
530
- jobs.set(job.id, job);
531
- if (active < maxParallelLimit) {
532
- active += 1;
533
- kickoff(job).catch((err) => handleKickoffFailure(job, err));
534
- } else {
535
- transition(job, JOB_PHASES.QUEUED, 'concurrency limit');
536
- queue.push(job);
537
- }
538
- return job;
539
- }
540
-
541
- async function kickoff(job) { await runWorkflow(job); }
542
-
543
- async function wait(id, timeoutMs) {
544
- const job = jobs.get(id);
545
- if (!job) return undefined;
546
- if (job.status !== 'running') return job;
547
- await Promise.race([
548
- new Promise((res) => job.waiters.push(res)),
549
- timeoutMs > 0 ? new Promise((res) => setTimeout(res, timeoutMs)) : new Promise(() => {}),
550
- ]);
551
- return job;
552
- }
553
-
554
- function get(id, opts = {}) {
555
- const job = jobs.get(id);
556
- return job ? workflowView(job, opts) : undefined;
557
- }
558
-
559
- function list() { return [...jobs.values()].map((j) => workflowView(j)); }
560
-
561
- async function cancel(id) {
562
- const job = jobs.get(id);
563
- if (!job) return undefined;
564
- cancelWorkflow(job);
565
- const qi = queue.indexOf(job);
566
- if (qi !== -1) queue.splice(qi, 1);
567
- return workflowView(job);
568
- }
569
-
570
- return { start, wait, get, list, cancel, runtimeState, setMaxParallel, refreshRuntimeControls };
571
- }
572
-
573
- export { JOB_PHASES, TERMINAL };
1
+ // Workflow runtime: the single business flow for every worker dispatch, shared
2
+ // by blocking (dsh_run_worker) and async (dsh_spawn_worker) and by Hub and
3
+ // Standalone execution — the only difference between those transports is which
4
+ // adapter executes an attempt and whether the caller awaits.
5
+ //
6
+ // A Workflow Job is one logical delegation; an Attempt is one actual DSH
7
+ // worker/reviewer session within it. The runtime owns the state machine
8
+ // (phase transitions guarded by workflow.canTransition), the attempt loop
9
+ // (verify -> escalate on evidence -> reviewer pass -> finalize), candidate
10
+ // capture, review mutation detection, concurrency limiting and cancellation.
11
+ //
12
+ // All I/O is injected through `adapters`, so this module stays testable without
13
+ // DSH, a hub, git or a real filesystem. Policy decisions import the pure
14
+ // modules (policy.mjs / workflow.mjs) directly; Hub/Standalone specifics never
15
+ // appear here.
16
+
17
+ import { resolveModelPolicy, shouldAutoReview, getRoleState } from './policy.mjs';
18
+ import { buildOutcome, decideNextStep, JOB_PHASES, canTransition } from './workflow.mjs';
19
+ import { parseDeliveryReport } from './delivery.mjs';
20
+ import { classifyFailure } from './failure-classification.mjs';
21
+
22
+ export const WORKFLOW_ERROR_CODES = {
23
+ ISOLATION_UNAVAILABLE: 'ISOLATION_UNAVAILABLE',
24
+ NOT_GIT_REPOSITORY: 'NOT_GIT_REPOSITORY',
25
+ WORKTREE_CREATE_FAILED: 'WORKTREE_CREATE_FAILED',
26
+ CANDIDATE_CAPTURE_FAILED: 'CANDIDATE_CAPTURE_FAILED',
27
+ WORKFLOW_CANCELLED: 'WORKFLOW_CANCELLED',
28
+ ATTEMPT_INFRA_FAILURE: 'ATTEMPT_INFRA_FAILURE',
29
+ REVIEWER_MUTATED_CANDIDATE: 'REVIEWER_MUTATED_CANDIDATE',
30
+ };
31
+
32
+ const TERMINAL = new Set([JOB_PHASES.COMPLETED, JOB_PHASES.FAILED, JOB_PHASES.CANCELLED, JOB_PHASES.INTERRUPTED]);
33
+
34
+ function lines(value) {
35
+ if (typeof value !== 'string' || value.trim() === '') return [];
36
+ return value.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
37
+ }
38
+
39
+ export function normalizeReviewVerdict(value) {
40
+ const s = String(value ?? '').trim().toLowerCase();
41
+ if (/^(approve|approved|pass)\b/.test(s) || s === 'pass' || s === 'approve') return 'approve';
42
+ if (/request.*chang|chang.*request|reject|needs changes/i.test(s)) return 'request_changes';
43
+ return 'inconclusive';
44
+ }
45
+
46
+ export function normalizeReview({ attemptResult, beforeCandidate, afterCandidate } = {}) {
47
+ const parsed = parseDeliveryReport(attemptResult?.result ?? '');
48
+ const mutation = mutationDetected(beforeCandidate, afterCandidate);
49
+ const reportedVerdict = normalizeReviewVerdict(parsed.sections?.Verdict ?? attemptResult?.result ?? '');
50
+ return {
51
+ verdict: mutation ? 'request_changes' : reportedVerdict,
52
+ reported_verdict: reportedVerdict,
53
+ findings: lines(parsed.sections?.['Review Findings']),
54
+ evidence: lines(parsed.sections?.Evidence),
55
+ risks: lines(parsed.sections?.Risks),
56
+ delivery_complete: parsed.complete ?? false,
57
+ model: attemptResult?.model ?? null,
58
+ provider: attemptResult?.provider ?? null,
59
+ selection_trace: attemptResult?.selection_trace ?? null,
60
+ status: attemptResult?.status ?? 'failed',
61
+ ...(mutation ? { mutated_candidate: true, invalidated: true } : {}),
62
+ };
63
+ }
64
+
65
+ function mutationDetected(before, after) {
66
+ if (!before) return false;
67
+ if (before.fingerprint == null) return false;
68
+ if (!after) return true;
69
+ return after.fingerprint != null && before.fingerprint !== after.fingerprint;
70
+ }
71
+
72
+ function deliveryClaimsChanges(outcome) {
73
+ return Array.isArray(outcome?.changes) && outcome.changes.length > 0;
74
+ }
75
+
76
+ function workspaceEvidenceOK(outcome, candidate) {
77
+ if (!candidate) return true;
78
+ const hasChanges = Array.isArray(candidate.changed_files) && candidate.changed_files.length > 0;
79
+ if (outcome?.execution_status !== 'completed') return true;
80
+ return !deliveryClaimsChanges(outcome) || hasChanges;
81
+ }
82
+
83
+ function sumUsage(attempts) {
84
+ const tokens = { input: 0, output: 0, reasoning: 0 };
85
+ for (const a of attempts) {
86
+ const u = a.usage;
87
+ if (!u) continue;
88
+ tokens.input += u.input ?? 0;
89
+ tokens.output += u.output ?? 0;
90
+ tokens.reasoning += u.reasoning ?? 0;
91
+ }
92
+ return tokens;
93
+ }
94
+
95
+ export function normalizeMaxParallel(value, fallback = 3) {
96
+ const fallbackValue = Number.isInteger(Number(fallback))
97
+ ? Math.max(1, Math.min(16, Number(fallback)))
98
+ : 3;
99
+ const parsed = Number(value);
100
+ if (!Number.isInteger(parsed)) return fallbackValue;
101
+ return Math.max(1, Math.min(16, parsed));
102
+ }
103
+
104
+ export function createWorkflowRuntime(adapters, {
105
+ maxParallel = 3,
106
+ idFactory = () => `wf-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
107
+ clock = () => Date.now(),
108
+ logger = null,
109
+ } = {}) {
110
+ const jobs = new Map();
111
+ const queue = [];
112
+ let active = 0;
113
+ let maxParallelLimit = normalizeMaxParallel(maxParallel);
114
+
115
+ function log(msg) { logger?.debug?.(`workflow: ${msg}`); }
116
+
117
+ function runtimeState() {
118
+ return {
119
+ max_parallel: maxParallelLimit,
120
+ active,
121
+ queued: queue.length,
122
+ };
123
+ }
124
+
125
+ function syncLiveMaxParallel() {
126
+ if (typeof adapters.getRuntimeControls !== 'function') return false;
127
+ const controls = adapters.getRuntimeControls() ?? {};
128
+ if (controls.max_parallel === undefined) return false;
129
+ const next = normalizeMaxParallel(controls.max_parallel, maxParallelLimit);
130
+ if (next === maxParallelLimit) return false;
131
+ maxParallelLimit = next;
132
+ return true;
133
+ }
134
+
135
+ function transition(job, to, reason) {
136
+ if (job.phase === to) return;
137
+ if (!canTransition(job.phase, to)) throw new Error(`illegal workflow transition ${job.phase} -> ${to}`);
138
+ job.phase = to;
139
+ job.events.push({ at: clock(), phase: to, type: 'phase', reason: reason ?? to });
140
+ log(`${job.id} ${to}`);
141
+ }
142
+
143
+ function createJob(spec) {
144
+ const now = clock();
145
+ return {
146
+ id: idFactory(),
147
+ role: spec.role ?? 'worker',
148
+ delivery: spec.delivery === 'review' ? 'review' : 'coding',
149
+ model_class_hint: spec.model_class_hint === 'pro' ? 'pro' : spec.model_class_hint === 'flash' ? 'flash' : null,
150
+ original_task: spec.task,
151
+ source: spec.source ?? 'api',
152
+ requested_cwd: spec.cwd,
153
+ effort: spec.effort ?? 'max',
154
+ phase: JOB_PHASES.CREATED,
155
+ status: 'running',
156
+ cancelling: false,
157
+ execution_cwd: spec.cwd,
158
+ isolation: 'shared',
159
+ base_revision: null,
160
+ primary_workspace_dirty: false,
161
+ attempts: [],
162
+ current_attempt_id: null,
163
+ candidate: null,
164
+ decision: null,
165
+ review: null,
166
+ outcome: null,
167
+ error: null,
168
+ cleanup_warning: null,
169
+ candidate_capture_failed: false,
170
+ retain_workspace: false,
171
+ workspace_retained: false,
172
+ events: [{ at: now, phase: JOB_PHASES.CREATED, type: 'created' }],
173
+ createdAt: now,
174
+ startedAt: now,
175
+ endedAt: null,
176
+ workspaceHandle: null,
177
+ waiters: [],
178
+ };
179
+ }
180
+
181
+ function releaseSlot() {
182
+ active = Math.max(0, active - 1);
183
+ drain();
184
+ }
185
+
186
+ function handleKickoffFailure(job, err) {
187
+ failJob(job, err);
188
+ releaseSlot();
189
+ }
190
+
191
+ function drain({ sync = true } = {}) {
192
+ if (sync) syncLiveMaxParallel();
193
+ while (active < maxParallelLimit && queue.length > 0) {
194
+ const job = queue.shift();
195
+ active += 1;
196
+ kickoff(job).catch((err) => handleKickoffFailure(job, err));
197
+ }
198
+ }
199
+
200
+ function setMaxParallel(value) {
201
+ maxParallelLimit = normalizeMaxParallel(value, maxParallelLimit);
202
+ // Raising the limit admits queued work immediately. Lowering it never
203
+ // cancels already-running work: drain simply waits until active drops below
204
+ // the new limit.
205
+ drain({ sync: false });
206
+ return runtimeState();
207
+ }
208
+
209
+ function refreshRuntimeControls() {
210
+ syncLiveMaxParallel();
211
+ drain({ sync: false });
212
+ return runtimeState();
213
+ }
214
+
215
+ function setTerminal(job) {
216
+ if (job.status !== 'running') return;
217
+ if (job.phase === JOB_PHASES.COMPLETED) job.status = 'done';
218
+ else if (job.phase === JOB_PHASES.CANCELLED) job.status = 'cancelled';
219
+ else job.status = 'failed';
220
+ job.endedAt = clock();
221
+ job.current_attempt_id = null;
222
+ for (const w of job.waiters.splice(0)) w();
223
+ }
224
+
225
+ function failJob(job, err) {
226
+ if (job.status !== 'running') return;
227
+ job.error = err?.message ?? String(err);
228
+ job.error_code = err?.code ?? err?.policyCode ?? job.error_code ?? null;
229
+ job.phase = JOB_PHASES.FAILED;
230
+ setTerminal(job);
231
+ }
232
+
233
+ async function releaseWorkspace(job) {
234
+ if (job.retain_workspace) {
235
+ job.workspace_retained = true;
236
+ return;
237
+ }
238
+ if (!job.workspaceHandle) return;
239
+ try {
240
+ const r = await adapters.releaseWorkspace(job.workspaceHandle);
241
+ if (!r || r.ok !== true) {
242
+ // A failed cleanup leaves the isolated workspace in place; say so
243
+ // truthfully instead of claiming a clean release.
244
+ job.cleanup_warning = r?.error ?? 'worktree cleanup failed';
245
+ job.workspace_retained = true;
246
+ }
247
+ } catch (err) {
248
+ job.cleanup_warning = err?.message ?? String(err);
249
+ job.workspace_retained = true;
250
+ }
251
+ job.workspaceHandle = null;
252
+ }
253
+
254
+ async function runWorkflow(job) {
255
+ const isReviewJob = job.role === 'reviewer' || job.delivery === 'review';
256
+ let config = {};
257
+
258
+ try {
259
+ config = adapters.getConfig?.() ?? {};
260
+ const alloc = await adapters.allocateWorkspace?.(job);
261
+ if (alloc && alloc.ok === false) {
262
+ job.error = alloc.error ?? alloc.reason;
263
+ job.phase = JOB_PHASES.FAILED;
264
+ if (alloc.reason) job.error_code = alloc.reason;
265
+ setTerminal(job);
266
+ return;
267
+ }
268
+ if (alloc && alloc.ok) {
269
+ job.workspaceHandle = alloc.handle ?? null;
270
+ job.execution_cwd = alloc.execution_cwd ?? job.requested_cwd;
271
+ job.isolation = alloc.isolation ?? 'worktree';
272
+ job.base_revision = alloc.base_revision ?? null;
273
+ job.primary_workspace_dirty = alloc.primary_workspace_dirty === true;
274
+ }
275
+ transition(job, JOB_PHASES.RUNNING, 'start');
276
+
277
+ if (isReviewJob) {
278
+ transition(job, JOB_PHASES.REVIEWING, 'explicit reviewer');
279
+ const before = alloc?.ok && alloc.isolation === 'worktree' ? await safeCapture(adapters, job.execution_cwd, job.base_revision) : null;
280
+ const reviewTask = adapters.buildReviewTask(job.original_task, null);
281
+ const review = await runReviewerAttempt(job, reviewTask, config, before);
282
+ job.review = review;
283
+ if (job.review) transition(job, JOB_PHASES.READY, 'review complete');
284
+ finalize(job);
285
+ return;
286
+ }
287
+
288
+ let attempt = 0;
289
+ let escalationReason = null;
290
+ for (;;) {
291
+ if (job.cancelling) { cancelWorkflow(job); return; }
292
+ if (attempt > 0) transition(job, JOB_PHASES.RUNNING, `escalated attempt ${attempt}`);
293
+ const policy = resolveModelPolicy(config, 'worker', { attempt });
294
+ const attemptId = attemptIdFor(adapters, job.id, attempt === 0 ? '' : String(attempt));
295
+ job.current_attempt_id = attemptId;
296
+ job.events.push({ at: clock(), phase: job.phase, type: 'attempt/start', attempt, escalation_reason: escalationReason });
297
+ const ar = await adapters.executeAttempt({
298
+ id: attemptId,
299
+ workflowId: job.id,
300
+ role: 'worker',
301
+ attempt,
302
+ task: job.original_task,
303
+ cwd: job.execution_cwd,
304
+ effort: job.effort,
305
+ policy,
306
+ source: job.source,
307
+ model_class_hint: job.model_class_hint,
308
+ escalation_reason: escalationReason,
309
+ onAttemptStarted: (actualId) => {
310
+ if (typeof actualId === 'string' && actualId) job.current_attempt_id = actualId;
311
+ },
312
+ });
313
+ job.current_attempt_id = null;
314
+ if (job.cancelling) { cancelWorkflow(job); return; }
315
+ const attemptView = attemptRecord(ar, attempt);
316
+ job.attempts.push(attemptView);
317
+ if (ar.infra === true) {
318
+ failJob(job, Object.assign(new Error(ar.error ?? 'infrastructure failure'), { code: WORKFLOW_ERROR_CODES.ATTEMPT_INFRA_FAILURE }));
319
+ return;
320
+ }
321
+ const outcome = ar.outcome ?? buildOutcome({
322
+ result: ar.result ?? '',
323
+ stopReason: ar.stopReason,
324
+ executionStatus: ar.status === 'done' ? 'completed' : 'failed',
325
+ });
326
+ transition(job, JOB_PHASES.VERIFYING, `attempt ${attempt} complete`);
327
+
328
+ // Capture the latest candidate after every attempt. Capture failure is
329
+ // not allowed to delete the only recoverable state: retain the worktree
330
+ // and preserve the worker business result, while surfacing the warning.
331
+ if (alloc?.ok && alloc.isolation === 'worktree') {
332
+ const candidate = await safeCapture(adapters, job.execution_cwd, job.base_revision);
333
+ if (candidate === null) {
334
+ job.candidate_capture_failed = true;
335
+ job.retain_workspace = true;
336
+ job.candidate = null;
337
+ job.events.push({ at: clock(), phase: job.phase, type: 'candidate/failed', attempt, message: 'candidate capture failed; worktree retained for recovery' });
338
+ } else {
339
+ job.candidate = candidate;
340
+ attemptView.candidate_fingerprint = candidate.fingerprint ?? null;
341
+ outcome.workspace_evidence_ok = workspaceEvidenceOK(outcome, candidate);
342
+ if (candidate.complete === false || candidate.replayable === false) {
343
+ job.retain_workspace = true;
344
+ job.events.push({ at: clock(), phase: job.phase, type: 'candidate/incomplete', attempt, message: 'candidate is not fully replayable; worktree retained' });
345
+ }
346
+ }
347
+ }
348
+ job.outcome = outcome;
349
+
350
+ const reviewRequested = !isReviewJob && shouldAutoReview(config);
351
+ const reviewerAuto = getRoleState(config, 'reviewer') !== 'disabled';
352
+ const decision = decideNextStep({ outcome, policy, attempt, reviewRequested, reviewerAuto });
353
+ job.decision = { step: decision.step, phase: decision.phase, reason: decision.reason };
354
+ job.events.push({ at: clock(), phase: job.phase, type: 'attempt/complete', attempt, decision: decision.step });
355
+
356
+ if (job.cancelling) { cancelWorkflow(job); return; }
357
+ if (decision.step === 'fail') {
358
+ const finalAttemptCode = ar.status === 'failed' ? attemptView.error_code : null;
359
+ failJob(job, Object.assign(new Error(`workflow failed: ${decision.reason}`), { code: finalAttemptCode }));
360
+ return;
361
+ }
362
+ if (decision.step === 'escalate') {
363
+ transition(job, JOB_PHASES.ESCALATING, decision.reason);
364
+ escalationReason = decision.reason;
365
+ attempt += 1;
366
+ continue;
367
+ }
368
+ if (decision.step === 'review') {
369
+ transition(job, JOB_PHASES.REVIEWING, 'automatic review');
370
+ const before = job.candidate;
371
+ const reviewTask = adapters.buildReviewTask(job.original_task, { outcome, candidate: job.candidate ?? null });
372
+ const review = await runReviewerAttempt(job, reviewTask, config, before, job.execution_cwd, job.base_revision);
373
+ job.review = review;
374
+ transition(job, JOB_PHASES.READY, decision.reason);
375
+ finalize(job);
376
+ return;
377
+ }
378
+ transition(job, JOB_PHASES.READY, decision.reason);
379
+ finalize(job);
380
+ return;
381
+ }
382
+ } catch (err) {
383
+ if (job.cancelling) { cancelWorkflow(job); return; }
384
+ failJob(job, err);
385
+ } finally {
386
+ await releaseWorkspace(job);
387
+ releaseSlot();
388
+ }
389
+ }
390
+
391
+ async function safeCapture(adapters, cwd, baseRevision) {
392
+ if (typeof adapters.captureCandidate !== 'function') return null;
393
+ try {
394
+ const c = await adapters.captureCandidate({ cwd, baseRevision });
395
+ return c && c.ok ? c : null;
396
+ } catch { return null; }
397
+ }
398
+
399
+ async function runReviewerAttempt(job, task, config, beforeCandidate, cwd = job.execution_cwd, baseRevision = job.base_revision) {
400
+ const policy = resolveModelPolicy(config, 'reviewer', { attempt: 0 });
401
+ const attemptId = attemptIdFor(adapters, job.id, 'review');
402
+ job.current_attempt_id = attemptId;
403
+ job.events.push({ at: clock(), phase: job.phase, type: 'review/start' });
404
+ const ar = await adapters.executeAttempt({
405
+ id: attemptId,
406
+ workflowId: job.id,
407
+ role: 'reviewer',
408
+ attempt: 0,
409
+ task,
410
+ cwd,
411
+ effort: job.effort,
412
+ policy,
413
+ source: job.source,
414
+ model_class_hint: 'pro',
415
+ escalation_reason: null,
416
+ onAttemptStarted: (actualId) => {
417
+ if (typeof actualId === 'string' && actualId) job.current_attempt_id = actualId;
418
+ },
419
+ });
420
+ job.current_attempt_id = null;
421
+ const attemptView = { ...attemptRecord(ar, 0), phase: 'review' };
422
+ job.attempts.push(attemptView);
423
+ if (ar.status === 'failed' && attemptView.error_code) job.error_code = attemptView.error_code;
424
+ const afterCandidate = job.isolation === 'worktree' ? await safeCapture(adapters, cwd, baseRevision) : null;
425
+ return normalizeReview({ attemptResult: ar, beforeCandidate, afterCandidate });
426
+ }
427
+
428
+ function finalize(job) {
429
+ transition(job, JOB_PHASES.COMPLETED, job.review ? 'reviewed' : 'verified');
430
+ setTerminal(job);
431
+ }
432
+
433
+ function attemptRecord(ar, attempt) {
434
+ return {
435
+ id: ar.id,
436
+ role: ar.role ?? 'worker',
437
+ attempt,
438
+ provider: ar.provider ?? null,
439
+ model: ar.model ?? null,
440
+ selection_source: ar.selection_source ?? null,
441
+ selection_trace: ar.selection_trace ?? null,
442
+ status: ar.status ?? 'failed',
443
+ result: ar.result ?? null,
444
+ stopReason: ar.stopReason ?? null,
445
+ outcome: ar.outcome ?? null,
446
+ usage: ar.usage ?? null,
447
+ error: ar.error ?? null,
448
+ error_code: ar.error_code ?? ar.code ?? null,
449
+ timed_out: ar.timed_out === true,
450
+ };
451
+ }
452
+
453
+ function attemptIdFor(adapters, workflowId, suffix = '') {
454
+ return typeof adapters.attemptId === 'function'
455
+ ? adapters.attemptId(workflowId, suffix)
456
+ : `${workflowId}-a${suffix || '0'}`;
457
+ }
458
+
459
+ function cancelWorkflow(job) {
460
+ if (job.status !== 'running') return;
461
+ job.cancelling = true;
462
+ job.events.push({ at: clock(), phase: job.phase, type: 'cancel' });
463
+ const activeAttempt = job.current_attempt_id;
464
+ if (activeAttempt) adapters.cancelAttempt?.(activeAttempt).catch(() => {});
465
+ job.phase = JOB_PHASES.CANCELLED;
466
+ job.status = 'cancelled';
467
+ job.endedAt = clock();
468
+ job.current_attempt_id = null;
469
+ for (const w of job.waiters.splice(0)) w();
470
+ }
471
+
472
+ function workflowView(job, { withResult = false } = {}) {
473
+ const failure = classifyFailure({
474
+ phase: job.phase,
475
+ status: job.status,
476
+ errorCode: job.error_code,
477
+ outcome: job.outcome,
478
+ decision: job.decision,
479
+ review: job.review,
480
+ childAttempts: job.attempts,
481
+ });
482
+ const v = {
483
+ id: job.id,
484
+ role: job.role,
485
+ phase: job.phase,
486
+ status: job.status,
487
+ attempt: job.attempts.length,
488
+ current_model: job.attempts[job.attempts.length - 1]?.model ?? null,
489
+ model_class_hint: job.model_class_hint,
490
+ source: job.source,
491
+ requested_cwd: job.requested_cwd,
492
+ execution_cwd: job.execution_cwd,
493
+ isolation: job.isolation,
494
+ base_revision: job.base_revision,
495
+ primary_workspace_dirty: job.primary_workspace_dirty,
496
+ startedAt: job.createdAt,
497
+ updatedAt: job.endedAt ?? clock(),
498
+ tokens: sumUsage(job.attempts),
499
+ error: job.error ?? null,
500
+ error_code: job.error_code ?? null,
501
+ failure,
502
+ cleanup_warning: job.cleanup_warning ?? null,
503
+ candidate_capture_failed: job.candidate_capture_failed === true,
504
+ workspace_retained: job.workspace_retained === true,
505
+ decision: job.decision,
506
+ candidate_available: !!job.candidate,
507
+ review_status: job.review ? job.review.status ?? null : null,
508
+ };
509
+ if (withResult) {
510
+ v.child_attempts = job.attempts.map((a) => ({
511
+ id: a.id, role: a.role, attempt: a.attempt, provider: a.provider, model: a.model,
512
+ selection_source: a.selection_source, selection_trace: a.selection_trace ?? null,
513
+ status: a.status, stopReason: a.stopReason,
514
+ outcome_task: a.outcome?.task_status ?? null,
515
+ error: a.error ?? null, error_code: a.error_code ?? null, timed_out: a.timed_out === true,
516
+ candidate_fingerprint: a.candidate_fingerprint ?? null,
517
+ tokens: a.usage ?? null,
518
+ }));
519
+ v.outcome = job.outcome;
520
+ v.candidate = job.candidate;
521
+ v.review = job.review;
522
+ v.events = job.events;
523
+ }
524
+ return v;
525
+ }
526
+
527
+ function start(spec) {
528
+ syncLiveMaxParallel();
529
+ const job = createJob(spec);
530
+ jobs.set(job.id, job);
531
+ if (active < maxParallelLimit) {
532
+ active += 1;
533
+ kickoff(job).catch((err) => handleKickoffFailure(job, err));
534
+ } else {
535
+ transition(job, JOB_PHASES.QUEUED, 'concurrency limit');
536
+ queue.push(job);
537
+ }
538
+ return job;
539
+ }
540
+
541
+ async function kickoff(job) { await runWorkflow(job); }
542
+
543
+ async function wait(id, timeoutMs) {
544
+ const job = jobs.get(id);
545
+ if (!job) return undefined;
546
+ if (job.status !== 'running') return job;
547
+ await Promise.race([
548
+ new Promise((res) => job.waiters.push(res)),
549
+ timeoutMs > 0 ? new Promise((res) => setTimeout(res, timeoutMs)) : new Promise(() => {}),
550
+ ]);
551
+ return job;
552
+ }
553
+
554
+ function get(id, opts = {}) {
555
+ const job = jobs.get(id);
556
+ return job ? workflowView(job, opts) : undefined;
557
+ }
558
+
559
+ function list() { return [...jobs.values()].map((j) => workflowView(j)); }
560
+
561
+ async function cancel(id) {
562
+ const job = jobs.get(id);
563
+ if (!job) return undefined;
564
+ cancelWorkflow(job);
565
+ const qi = queue.indexOf(job);
566
+ if (qi !== -1) queue.splice(qi, 1);
567
+ return workflowView(job);
568
+ }
569
+
570
+ return { start, wait, get, list, cancel, runtimeState, setMaxParallel, refreshRuntimeControls };
571
+ }
572
+
573
+ export { JOB_PHASES, TERMINAL };