@ran-sh/dsh-crew 0.3.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/.claude-plugin/marketplace.json +17 -0
- package/.claude-plugin/plugin.json +8 -0
- package/.mcp.json +8 -0
- package/LICENSE +21 -0
- package/README.de.md +359 -0
- package/README.es.md +359 -0
- package/README.fr.md +359 -0
- package/README.hi.md +359 -0
- package/README.id.md +359 -0
- package/README.ja.md +359 -0
- package/README.ko.md +359 -0
- package/README.md +360 -0
- package/README.pt.md +359 -0
- package/README.ru.md +359 -0
- package/README.th.md +359 -0
- package/README.tr.md +359 -0
- package/README.vi.md +359 -0
- package/README.zh-TW.md +359 -0
- package/README.zh.md +305 -0
- package/agents/ds-flash.md +26 -0
- package/agents/ds-pro.md +32 -0
- package/agents/ds-reviewer.md +23 -0
- package/agents/ds-worker.md +22 -0
- package/codex/agents/ds-flash.toml +30 -0
- package/codex/agents/ds-pro.toml +31 -0
- package/codex/agents/ds-reviewer.toml +28 -0
- package/codex/agents/ds-worker.toml +28 -0
- package/codex/prompts/dsh-config.md +3 -0
- package/codex/prompts/dsh-status.md +1 -0
- package/commands/config.md +11 -0
- package/commands/off.md +5 -0
- package/commands/on.md +5 -0
- package/commands/status.md +5 -0
- package/cordis.patch.yml +4 -0
- package/docs/images/dsh-crew-host.png +0 -0
- package/docs/images/dsh-crew-jobs.png +0 -0
- package/docs/images/dsh-crew-logo.png +0 -0
- package/docs/images/dsh-crew-overview.png +0 -0
- package/lib/client.js +2765 -0
- package/package.json +125 -0
- package/scripts/build-client.mjs +28 -0
- package/scripts/live-crew-smoke.mjs +39 -0
- package/scripts/live-policy-matrix.mjs +177 -0
- package/scripts/policy-probe.mjs +101 -0
- package/scripts/setup.mjs +294 -0
- package/scripts/smoke-real.mjs +110 -0
- package/scripts/smoke.mjs +78 -0
- package/scripts/verify-installer-fix.mjs +26 -0
- package/src/adaptive-routing.mjs +260 -0
- package/src/client/activation-summary.tsx +64 -0
- package/src/client/entry.tsx +236 -0
- package/src/client/index.tsx +1120 -0
- package/src/config-readiness.mjs +59 -0
- package/src/delivery.mjs +205 -0
- package/src/dsh-cli-runtime.mjs +251 -0
- package/src/failure-classification.mjs +172 -0
- package/src/hub/entry.mjs +98 -0
- package/src/hub/index.mjs +757 -0
- package/src/hub-client.mjs +132 -0
- package/src/hub-compatibility.mjs +49 -0
- package/src/i18n.mjs +19 -0
- package/src/install/cli.mjs +28 -0
- package/src/install/install-legacy.mjs +460 -0
- package/src/install/install.mjs +451 -0
- package/src/jobs.mjs +275 -0
- package/src/mcp-runtime.mjs +257 -0
- package/src/model-catalog.mjs +173 -0
- package/src/model-routing.mjs +391 -0
- package/src/multimodal.mjs +0 -0
- package/src/policy-legacy.mjs +830 -0
- package/src/policy.mjs +197 -0
- package/src/readiness-matrix.mjs +169 -0
- package/src/runtime-controls.mjs +90 -0
- package/src/runtime-identity.mjs +108 -0
- package/src/server.mjs +477 -0
- package/src/status-shard.mjs +52 -0
- package/src/structured-error-code.mjs +39 -0
- package/src/vision-route.mjs +138 -0
- package/src/workflow-runtime.mjs +567 -0
- package/src/workflow.mjs +160 -0
- package/src/workspace-audit.mjs +231 -0
- package/src/workspace-isolation.mjs +306 -0
- package/statusline/statusline.sh +14 -0
- package/statusline/worker-segment.sh +35 -0
- package/worker.cordis.yml +77 -0
|
@@ -0,0 +1,567 @@
|
|
|
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) job.cleanup_warning = r?.error ?? 'worktree cleanup failed';
|
|
242
|
+
} catch (err) {
|
|
243
|
+
job.cleanup_warning = err?.message ?? String(err);
|
|
244
|
+
}
|
|
245
|
+
job.workspaceHandle = null;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function runWorkflow(job) {
|
|
249
|
+
const isReviewJob = job.role === 'reviewer' || job.delivery === 'review';
|
|
250
|
+
let config = {};
|
|
251
|
+
|
|
252
|
+
try {
|
|
253
|
+
config = adapters.getConfig?.() ?? {};
|
|
254
|
+
const alloc = await adapters.allocateWorkspace?.(job);
|
|
255
|
+
if (alloc && alloc.ok === false) {
|
|
256
|
+
job.error = alloc.error ?? alloc.reason;
|
|
257
|
+
job.phase = JOB_PHASES.FAILED;
|
|
258
|
+
if (alloc.reason) job.error_code = alloc.reason;
|
|
259
|
+
setTerminal(job);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (alloc && alloc.ok) {
|
|
263
|
+
job.workspaceHandle = alloc.handle ?? null;
|
|
264
|
+
job.execution_cwd = alloc.execution_cwd ?? job.requested_cwd;
|
|
265
|
+
job.isolation = alloc.isolation ?? 'worktree';
|
|
266
|
+
job.base_revision = alloc.base_revision ?? null;
|
|
267
|
+
job.primary_workspace_dirty = alloc.primary_workspace_dirty === true;
|
|
268
|
+
}
|
|
269
|
+
transition(job, JOB_PHASES.RUNNING, 'start');
|
|
270
|
+
|
|
271
|
+
if (isReviewJob) {
|
|
272
|
+
transition(job, JOB_PHASES.REVIEWING, 'explicit reviewer');
|
|
273
|
+
const before = alloc?.ok && alloc.isolation === 'worktree' ? await safeCapture(adapters, job.execution_cwd, job.base_revision) : null;
|
|
274
|
+
const reviewTask = adapters.buildReviewTask(job.original_task, null);
|
|
275
|
+
const review = await runReviewerAttempt(job, reviewTask, config, before);
|
|
276
|
+
job.review = review;
|
|
277
|
+
if (job.review) transition(job, JOB_PHASES.READY, 'review complete');
|
|
278
|
+
finalize(job);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
let attempt = 0;
|
|
283
|
+
let escalationReason = null;
|
|
284
|
+
for (;;) {
|
|
285
|
+
if (job.cancelling) { cancelWorkflow(job); return; }
|
|
286
|
+
if (attempt > 0) transition(job, JOB_PHASES.RUNNING, `escalated attempt ${attempt}`);
|
|
287
|
+
const policy = resolveModelPolicy(config, 'worker', { attempt });
|
|
288
|
+
const attemptId = attemptIdFor(adapters, job.id, attempt === 0 ? '' : String(attempt));
|
|
289
|
+
job.current_attempt_id = attemptId;
|
|
290
|
+
job.events.push({ at: clock(), phase: job.phase, type: 'attempt/start', attempt, escalation_reason: escalationReason });
|
|
291
|
+
const ar = await adapters.executeAttempt({
|
|
292
|
+
id: attemptId,
|
|
293
|
+
workflowId: job.id,
|
|
294
|
+
role: 'worker',
|
|
295
|
+
attempt,
|
|
296
|
+
task: job.original_task,
|
|
297
|
+
cwd: job.execution_cwd,
|
|
298
|
+
effort: job.effort,
|
|
299
|
+
policy,
|
|
300
|
+
source: job.source,
|
|
301
|
+
model_class_hint: job.model_class_hint,
|
|
302
|
+
escalation_reason: escalationReason,
|
|
303
|
+
onAttemptStarted: (actualId) => {
|
|
304
|
+
if (typeof actualId === 'string' && actualId) job.current_attempt_id = actualId;
|
|
305
|
+
},
|
|
306
|
+
});
|
|
307
|
+
job.current_attempt_id = null;
|
|
308
|
+
if (job.cancelling) { cancelWorkflow(job); return; }
|
|
309
|
+
const attemptView = attemptRecord(ar, attempt);
|
|
310
|
+
job.attempts.push(attemptView);
|
|
311
|
+
if (ar.infra === true) {
|
|
312
|
+
failJob(job, Object.assign(new Error(ar.error ?? 'infrastructure failure'), { code: WORKFLOW_ERROR_CODES.ATTEMPT_INFRA_FAILURE }));
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
const outcome = ar.outcome ?? buildOutcome({
|
|
316
|
+
result: ar.result ?? '',
|
|
317
|
+
stopReason: ar.stopReason,
|
|
318
|
+
executionStatus: ar.status === 'done' ? 'completed' : 'failed',
|
|
319
|
+
});
|
|
320
|
+
transition(job, JOB_PHASES.VERIFYING, `attempt ${attempt} complete`);
|
|
321
|
+
|
|
322
|
+
// Capture the latest candidate after every attempt. Capture failure is
|
|
323
|
+
// not allowed to delete the only recoverable state: retain the worktree
|
|
324
|
+
// and preserve the worker business result, while surfacing the warning.
|
|
325
|
+
if (alloc?.ok && alloc.isolation === 'worktree') {
|
|
326
|
+
const candidate = await safeCapture(adapters, job.execution_cwd, job.base_revision);
|
|
327
|
+
if (candidate === null) {
|
|
328
|
+
job.candidate_capture_failed = true;
|
|
329
|
+
job.retain_workspace = true;
|
|
330
|
+
job.candidate = null;
|
|
331
|
+
job.events.push({ at: clock(), phase: job.phase, type: 'candidate/failed', attempt, message: 'candidate capture failed; worktree retained for recovery' });
|
|
332
|
+
} else {
|
|
333
|
+
job.candidate = candidate;
|
|
334
|
+
attemptView.candidate_fingerprint = candidate.fingerprint ?? null;
|
|
335
|
+
outcome.workspace_evidence_ok = workspaceEvidenceOK(outcome, candidate);
|
|
336
|
+
if (candidate.complete === false || candidate.replayable === false) {
|
|
337
|
+
job.retain_workspace = true;
|
|
338
|
+
job.events.push({ at: clock(), phase: job.phase, type: 'candidate/incomplete', attempt, message: 'candidate is not fully replayable; worktree retained' });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
job.outcome = outcome;
|
|
343
|
+
|
|
344
|
+
const reviewRequested = !isReviewJob && shouldAutoReview(config);
|
|
345
|
+
const reviewerAuto = getRoleState(config, 'reviewer') !== 'disabled';
|
|
346
|
+
const decision = decideNextStep({ outcome, policy, attempt, reviewRequested, reviewerAuto });
|
|
347
|
+
job.decision = { step: decision.step, phase: decision.phase, reason: decision.reason };
|
|
348
|
+
job.events.push({ at: clock(), phase: job.phase, type: 'attempt/complete', attempt, decision: decision.step });
|
|
349
|
+
|
|
350
|
+
if (job.cancelling) { cancelWorkflow(job); return; }
|
|
351
|
+
if (decision.step === 'fail') {
|
|
352
|
+
const finalAttemptCode = ar.status === 'failed' ? attemptView.error_code : null;
|
|
353
|
+
failJob(job, Object.assign(new Error(`workflow failed: ${decision.reason}`), { code: finalAttemptCode }));
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
if (decision.step === 'escalate') {
|
|
357
|
+
transition(job, JOB_PHASES.ESCALATING, decision.reason);
|
|
358
|
+
escalationReason = decision.reason;
|
|
359
|
+
attempt += 1;
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
if (decision.step === 'review') {
|
|
363
|
+
transition(job, JOB_PHASES.REVIEWING, 'automatic review');
|
|
364
|
+
const before = job.candidate;
|
|
365
|
+
const reviewTask = adapters.buildReviewTask(job.original_task, { outcome, candidate: job.candidate ?? null });
|
|
366
|
+
const review = await runReviewerAttempt(job, reviewTask, config, before, job.execution_cwd, job.base_revision);
|
|
367
|
+
job.review = review;
|
|
368
|
+
transition(job, JOB_PHASES.READY, decision.reason);
|
|
369
|
+
finalize(job);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
transition(job, JOB_PHASES.READY, decision.reason);
|
|
373
|
+
finalize(job);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
} catch (err) {
|
|
377
|
+
if (job.cancelling) { cancelWorkflow(job); return; }
|
|
378
|
+
failJob(job, err);
|
|
379
|
+
} finally {
|
|
380
|
+
await releaseWorkspace(job);
|
|
381
|
+
releaseSlot();
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function safeCapture(adapters, cwd, baseRevision) {
|
|
386
|
+
if (typeof adapters.captureCandidate !== 'function') return null;
|
|
387
|
+
try {
|
|
388
|
+
const c = await adapters.captureCandidate({ cwd, baseRevision });
|
|
389
|
+
return c && c.ok ? c : null;
|
|
390
|
+
} catch { return null; }
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function runReviewerAttempt(job, task, config, beforeCandidate, cwd = job.execution_cwd, baseRevision = job.base_revision) {
|
|
394
|
+
const policy = resolveModelPolicy(config, 'reviewer', { attempt: 0 });
|
|
395
|
+
const attemptId = attemptIdFor(adapters, job.id, 'review');
|
|
396
|
+
job.current_attempt_id = attemptId;
|
|
397
|
+
job.events.push({ at: clock(), phase: job.phase, type: 'review/start' });
|
|
398
|
+
const ar = await adapters.executeAttempt({
|
|
399
|
+
id: attemptId,
|
|
400
|
+
workflowId: job.id,
|
|
401
|
+
role: 'reviewer',
|
|
402
|
+
attempt: 0,
|
|
403
|
+
task,
|
|
404
|
+
cwd,
|
|
405
|
+
effort: job.effort,
|
|
406
|
+
policy,
|
|
407
|
+
source: job.source,
|
|
408
|
+
model_class_hint: 'pro',
|
|
409
|
+
escalation_reason: null,
|
|
410
|
+
onAttemptStarted: (actualId) => {
|
|
411
|
+
if (typeof actualId === 'string' && actualId) job.current_attempt_id = actualId;
|
|
412
|
+
},
|
|
413
|
+
});
|
|
414
|
+
job.current_attempt_id = null;
|
|
415
|
+
const attemptView = { ...attemptRecord(ar, 0), phase: 'review' };
|
|
416
|
+
job.attempts.push(attemptView);
|
|
417
|
+
if (ar.status === 'failed' && attemptView.error_code) job.error_code = attemptView.error_code;
|
|
418
|
+
const afterCandidate = job.isolation === 'worktree' ? await safeCapture(adapters, cwd, baseRevision) : null;
|
|
419
|
+
return normalizeReview({ attemptResult: ar, beforeCandidate, afterCandidate });
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function finalize(job) {
|
|
423
|
+
transition(job, JOB_PHASES.COMPLETED, job.review ? 'reviewed' : 'verified');
|
|
424
|
+
setTerminal(job);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function attemptRecord(ar, attempt) {
|
|
428
|
+
return {
|
|
429
|
+
id: ar.id,
|
|
430
|
+
role: ar.role ?? 'worker',
|
|
431
|
+
attempt,
|
|
432
|
+
provider: ar.provider ?? null,
|
|
433
|
+
model: ar.model ?? null,
|
|
434
|
+
selection_source: ar.selection_source ?? null,
|
|
435
|
+
selection_trace: ar.selection_trace ?? null,
|
|
436
|
+
status: ar.status ?? 'failed',
|
|
437
|
+
result: ar.result ?? null,
|
|
438
|
+
stopReason: ar.stopReason ?? null,
|
|
439
|
+
outcome: ar.outcome ?? null,
|
|
440
|
+
usage: ar.usage ?? null,
|
|
441
|
+
error: ar.error ?? null,
|
|
442
|
+
error_code: ar.error_code ?? ar.code ?? null,
|
|
443
|
+
timed_out: ar.timed_out === true,
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function attemptIdFor(adapters, workflowId, suffix = '') {
|
|
448
|
+
return typeof adapters.attemptId === 'function'
|
|
449
|
+
? adapters.attemptId(workflowId, suffix)
|
|
450
|
+
: `${workflowId}-a${suffix || '0'}`;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function cancelWorkflow(job) {
|
|
454
|
+
if (job.status !== 'running') return;
|
|
455
|
+
job.cancelling = true;
|
|
456
|
+
job.events.push({ at: clock(), phase: job.phase, type: 'cancel' });
|
|
457
|
+
const activeAttempt = job.current_attempt_id;
|
|
458
|
+
if (activeAttempt) adapters.cancelAttempt?.(activeAttempt).catch(() => {});
|
|
459
|
+
job.phase = JOB_PHASES.CANCELLED;
|
|
460
|
+
job.status = 'cancelled';
|
|
461
|
+
job.endedAt = clock();
|
|
462
|
+
job.current_attempt_id = null;
|
|
463
|
+
for (const w of job.waiters.splice(0)) w();
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function workflowView(job, { withResult = false } = {}) {
|
|
467
|
+
const failure = classifyFailure({
|
|
468
|
+
phase: job.phase,
|
|
469
|
+
status: job.status,
|
|
470
|
+
errorCode: job.error_code,
|
|
471
|
+
outcome: job.outcome,
|
|
472
|
+
decision: job.decision,
|
|
473
|
+
review: job.review,
|
|
474
|
+
childAttempts: job.attempts,
|
|
475
|
+
});
|
|
476
|
+
const v = {
|
|
477
|
+
id: job.id,
|
|
478
|
+
role: job.role,
|
|
479
|
+
phase: job.phase,
|
|
480
|
+
status: job.status,
|
|
481
|
+
attempt: job.attempts.length,
|
|
482
|
+
current_model: job.attempts[job.attempts.length - 1]?.model ?? null,
|
|
483
|
+
model_class_hint: job.model_class_hint,
|
|
484
|
+
source: job.source,
|
|
485
|
+
requested_cwd: job.requested_cwd,
|
|
486
|
+
execution_cwd: job.execution_cwd,
|
|
487
|
+
isolation: job.isolation,
|
|
488
|
+
base_revision: job.base_revision,
|
|
489
|
+
primary_workspace_dirty: job.primary_workspace_dirty,
|
|
490
|
+
startedAt: job.createdAt,
|
|
491
|
+
updatedAt: job.endedAt ?? clock(),
|
|
492
|
+
tokens: sumUsage(job.attempts),
|
|
493
|
+
error: job.error ?? null,
|
|
494
|
+
error_code: job.error_code ?? null,
|
|
495
|
+
failure,
|
|
496
|
+
cleanup_warning: job.cleanup_warning ?? null,
|
|
497
|
+
candidate_capture_failed: job.candidate_capture_failed === true,
|
|
498
|
+
workspace_retained: job.workspace_retained === true,
|
|
499
|
+
decision: job.decision,
|
|
500
|
+
candidate_available: !!job.candidate,
|
|
501
|
+
review_status: job.review ? job.review.status ?? null : null,
|
|
502
|
+
};
|
|
503
|
+
if (withResult) {
|
|
504
|
+
v.child_attempts = job.attempts.map((a) => ({
|
|
505
|
+
id: a.id, role: a.role, attempt: a.attempt, provider: a.provider, model: a.model,
|
|
506
|
+
selection_source: a.selection_source, selection_trace: a.selection_trace ?? null,
|
|
507
|
+
status: a.status, stopReason: a.stopReason,
|
|
508
|
+
outcome_task: a.outcome?.task_status ?? null,
|
|
509
|
+
error: a.error ?? null, error_code: a.error_code ?? null, timed_out: a.timed_out === true,
|
|
510
|
+
candidate_fingerprint: a.candidate_fingerprint ?? null,
|
|
511
|
+
tokens: a.usage ?? null,
|
|
512
|
+
}));
|
|
513
|
+
v.outcome = job.outcome;
|
|
514
|
+
v.candidate = job.candidate;
|
|
515
|
+
v.review = job.review;
|
|
516
|
+
v.events = job.events;
|
|
517
|
+
}
|
|
518
|
+
return v;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function start(spec) {
|
|
522
|
+
syncLiveMaxParallel();
|
|
523
|
+
const job = createJob(spec);
|
|
524
|
+
jobs.set(job.id, job);
|
|
525
|
+
if (active < maxParallelLimit) {
|
|
526
|
+
active += 1;
|
|
527
|
+
kickoff(job).catch((err) => handleKickoffFailure(job, err));
|
|
528
|
+
} else {
|
|
529
|
+
transition(job, JOB_PHASES.QUEUED, 'concurrency limit');
|
|
530
|
+
queue.push(job);
|
|
531
|
+
}
|
|
532
|
+
return job;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
async function kickoff(job) { await runWorkflow(job); }
|
|
536
|
+
|
|
537
|
+
async function wait(id, timeoutMs) {
|
|
538
|
+
const job = jobs.get(id);
|
|
539
|
+
if (!job) return undefined;
|
|
540
|
+
if (job.status !== 'running') return job;
|
|
541
|
+
await Promise.race([
|
|
542
|
+
new Promise((res) => job.waiters.push(res)),
|
|
543
|
+
timeoutMs > 0 ? new Promise((res) => setTimeout(res, timeoutMs)) : new Promise(() => {}),
|
|
544
|
+
]);
|
|
545
|
+
return job;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function get(id, opts = {}) {
|
|
549
|
+
const job = jobs.get(id);
|
|
550
|
+
return job ? workflowView(job, opts) : undefined;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function list() { return [...jobs.values()].map((j) => workflowView(j)); }
|
|
554
|
+
|
|
555
|
+
async function cancel(id) {
|
|
556
|
+
const job = jobs.get(id);
|
|
557
|
+
if (!job) return undefined;
|
|
558
|
+
cancelWorkflow(job);
|
|
559
|
+
const qi = queue.indexOf(job);
|
|
560
|
+
if (qi !== -1) queue.splice(qi, 1);
|
|
561
|
+
return workflowView(job);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
return { start, wait, get, list, cancel, runtimeState, setMaxParallel, refreshRuntimeControls };
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
export { JOB_PHASES, TERMINAL };
|