返回 CodeWhale
scheduler.js
根目录 / crates / plugins / assets / agent-teams / lib / scheduler.js
1 /**
2 * Event-driven shared task scheduler.
3 *
4 * Claude Code teammates keep polling the shared task list after a turn. DSH
5 * continuable agents instead expose explicit idle/running edges, so this
6 * scheduler closes the same loop without keeping a polling turn alive: every
7 * idle edge and every task-graph mutation attempts one atomic claim and wakes
8 * the selected durable member. A resident member that becomes idle while it
9 * still owns an open attempt is parked: only an explicit captain reassignment
10 * may rotate that capability. Automatic retry is reserved for cold recovery,
11 * when this process has not observed the durable owner settle its open attempt.
12 * @module dsh-agent-teams/scheduler
13 */
14 import { join } from 'node:path';
15 import { deliverToMember } from "./members.js";
16 import { isCurrentMail, mailboxPrompt } from "./mailbox.js";
17 import { markMailboxDelivered, discardMailboxMessages, beginTaskAttempt, CAPTAIN_KEY, claimMailboxDelivery, findTeamByParticipant, invalidateTaskAttempt, readTeam, readPendingMailbox, releaseMailboxDelivery, unsatisfiedDependencies, withTeamLock, writeTeam, } from "./state.js";
18 import { contractStaleness, isVerdictKind, taskKindOf, verdictScopePatterns } from "./quality-gates.js";
19 import { digestWorkspacePaths, snapshotWorkspacePaths } from "./artifacts.js";
20 /** Per-dependency output cap in the assignment prompt. */
21 export const DEPENDENCY_OUTPUT_MAX_CHARS = 2_000;
22 /** Combined dependency-output budget in the assignment prompt. */
23 export const DEPENDENCY_OUTPUTS_TOTAL_MAX_CHARS = 12_000;
24 function taskProfileSeedId(task) {
25 const seed = task.profileSeedId?.trim();
26 return seed === undefined || seed === '' ? undefined : seed;
27 }
28 function teamProfileProtocol(team) {
29 return team.profile?.protocol;
30 }
31 /**
32 * Recursively collect `status=completed` ancestors of `taskId` in topological
33 * order (dependencies before dependents). Cycles stop that branch only.
34 */
35 export function collectCompletedDependencyOutputs(tasks, taskId, warn) {
36 const byId = new Map(tasks.map(task => [task.id, task]));
37 const visiting = new Set();
38 const visited = new Set();
39 const ordered = [];
40 const walk = (id) => {
41 if (visiting.has(id)) {
42 warn?.(`agent-teams: dependency cycle involving "${id}" while collecting outputs; stopping this branch`);
43 return;
44 }
45 if (visited.has(id))
46 return;
47 visiting.add(id);
48 const task = byId.get(id);
49 if (task !== undefined) {
50 for (const dependency of task.dependencies)
51 walk(dependency);
52 if (id !== taskId)
53 ordered.push(task);
54 }
55 visiting.delete(id);
56 visited.add(id);
57 };
58 walk(taskId);
59 return ordered
60 .filter(task => task.status === 'completed')
61 .map((task) => {
62 const profileSeedId = taskProfileSeedId(task);
63 return {
64 id: task.id,
65 subject: task.subject,
66 ...profileSeedId === undefined ? {} : { profileSeedId },
67 ...task.output === undefined ? {} : { output: task.output },
68 };
69 });
70 }
71 /** Format completed-dependency outputs with per-item and total truncation. */
72 export function formatDependencyOutputs(items) {
73 if (items.length === 0)
74 return '(none)';
75 const formatted = items.map((item) => {
76 const seed = item.profileSeedId === undefined ? '' : ` [${item.profileSeedId}]`;
77 const raw = item.output === undefined || item.output === ''
78 ? '(no output recorded)'
79 : item.output;
80 const truncated = raw.length > DEPENDENCY_OUTPUT_MAX_CHARS;
81 const body = truncated ? `${raw.slice(0, DEPENDENCY_OUTPUT_MAX_CHARS)} [truncated]` : raw;
82 return `- ${item.id}${seed} ${item.subject}:\n ${body}`;
83 });
84 let selected = formatted;
85 while (selected.length > 1 && selected.join('\n').length > DEPENDENCY_OUTPUTS_TOTAL_MAX_CHARS) {
86 selected = selected.slice(1);
87 }
88 const last = selected[0];
89 if (selected.length === 1 && last !== undefined && last.length > DEPENDENCY_OUTPUTS_TOTAL_MAX_CHARS) {
90 selected = [`${last.slice(0, DEPENDENCY_OUTPUTS_TOTAL_MAX_CHARS)} [truncated]`];
91 }
92 return selected.join('\n');
93 }
94 function stateRootOf(workspace, config) {
95 return join(workspace, config.stateDir);
96 }
97 function teamLockKey(stateRoot, teamId) {
98 return `team:${stateRoot}:${teamId}`;
99 }
100 function liveCaptain(ctx, captainSessionId, supplied) {
101 if (supplied !== undefined && supplied.id === captainSessionId)
102 return supplied;
103 return ctx.agents.get(captainSessionId);
104 }
105 function liveMember(ctx, member) {
106 return ctx.agents.get(member.id);
107 }
108 function isMemberAvailable(ctx, member) {
109 if (member.stopping === true)
110 return false;
111 const live = liveMember(ctx, member);
112 return live === undefined || live.status === 'idle';
113 }
114 function ownedOpenTask(tasks, memberName) {
115 return tasks.find(task => task.assignee === memberName
116 && (task.status === 'claimed' || task.status === 'in_progress'));
117 }
118 function nextReadyTask(tasks, memberName) {
119 const ready = tasks.filter(task => task.status === 'pending'
120 && task.reassigning !== true
121 && unsatisfiedDependencies([...tasks], task.dependencies).length === 0);
122 return ready.find(task => task.assignee === memberName)
123 ?? ready.find(task => task.assignee === undefined);
124 }
125 export function assignmentPrompt(ticket, stateDir, teamId, workOrderWarnings = []) {
126 const description = ticket.description === undefined ? '' : `\n\n${ticket.description}`;
127 const seed = ticket.profileSeedId === undefined ? '' : ` [${ticket.profileSeedId}]`;
128 const goal = ticket.teamDescription?.trim() || '(not provided)';
129 const protocol = ticket.profileProtocol?.trim() || '(none)';
130 const executionPrompt = ticket.executionPrompt?.trim();
131 const kind = ticket.kind?.trim() || 'work';
132 const staleWorkOrder = workOrderWarnings.length === 0
133 ? ''
134 : `\nBefore you edit anything: this auto-generated work order was derived from a workspace that has since changed.\n${workOrderWarnings.map((warning) => `- ${warning}`).join('\n')}\nRe-read the cited files first, locate the code by content anchor rather than by any position, and report a blocker instead of editing a target that no longer exists.\n`;
135 const contract = [
136 `Kind: ${kind}${ticket.round === undefined ? '' : ` (round ${ticket.round})`}`,
137 ticket.objective === undefined || ticket.objective === '' ? '' : `Objective: ${ticket.objective}`,
138 ticket.inScope === undefined || ticket.inScope.length === 0 ? '' : `In scope: ${ticket.inScope.join(', ')}`,
139 ticket.outOfScope === undefined || ticket.outOfScope.length === 0 ? '' : `Out of scope: ${ticket.outOfScope.join(', ')}`,
140 ticket.acceptance === undefined || ticket.acceptance.length === 0 ? '' : `Acceptance: ${ticket.acceptance.join('; ')}`,
141 ticket.verify === undefined || ticket.verify.length === 0 ? '' : `Verify: ${ticket.verify.join('; ')}`,
142 ticket.reviewedTaskId === undefined ? '' : `Reviewed task: ${ticket.reviewedTaskId}`,
143 ticket.findingSourceTaskIds === undefined || ticket.findingSourceTaskIds.length === 0 ? '' : `Fixes findings of: ${ticket.findingSourceTaskIds.join(', ')}`,
144 ].filter((line) => line !== '').join('\n');
145 const structuredCompletion = ['implementation', 'repair', 'verification', 'integration'].includes(kind)
146 ? `
147 Structured completion payload (keep these arrays in contract order):
148 acceptanceResults: ${JSON.stringify((ticket.acceptance ?? []).map((criterion) => ({ criterion, status: 'passed', evidence: '<what proved it>' })))}
149 commandsRun: ${JSON.stringify((ticket.verify ?? []).map((command) => ({ command, status: 'passed', exitCode: 0, evidence: '<observed result>' })))}
150 ${kind === 'implementation' || kind === 'repair' ? 'changedPaths: list the actual workspace-relative POSIX paths you changed.\n' : ''}`
151 : '';
152 return `AgentTeams automatic task assignment from the shared task list.
153
154 You are executing as configured member "${ticket.memberName}".
155 Do not start a teammate's assigned task.
156
157 Team goal:
158 ${goal}
159
160 Profile protocol:
161 ${protocol}
162 ${executionPrompt === undefined || executionPrompt === '' ? '' : `
163 Execution guidance:
164 ${executionPrompt}
165 `}
166 Completed dependency results:
167 ${formatDependencyOutputs(ticket.dependencyOutputs)}
168
169 Task: ${ticket.taskId}${seed} — ${ticket.subject}${description}
170 ${staleWorkOrder}${contract === '' ? '' : `\nContract:\n${contract}\n`}
171 ${structuredCompletion}
172 Attempt: ${ticket.attempt}
173 Attempt id: ${ticket.attemptId}
174
175 Call agent_teams_claim_task for ${ticket.taskId}; it will return this same attempt_id. Include attempt_id=${ticket.attemptId} in every agent_teams_update_task call. If it is rejected as stale, stop work because the task was reassigned. claimed cannot jump to completed. Mark in_progress first, then completed or failed. Include attempt_id on every update. Then send_message to captain with source_task_id and source_attempt_id and become idle.
176 When finishing: use status=completed only when the task's success criteria are satisfied; use status=failed when blocking findings or validation failures mean downstream work must not proceed; include a concise output in either case. Quality kinds must submit structured fields: review/requirements need verdict=pass to complete (needs_revision/reject must fail with findings); implementation/repair/verification/integration need acceptanceResults and commandsRun, while implementation/repair also need in-scope changedPaths. Use status values "passed" or "failed" inside those arrays. After the work and verification finish, call agent_teams_update_task immediately; do not wait for captain confirmation and do not continue exploring. Do not approve your own implementation. Mail is not a formal next review. Completed work must not be repeated to attach late evidence: call update_task on the original task with its attempt_id and acceptanceResults/commandsRun/evidence_note; supplements are append-only and cannot change its verdict. Treat the dependency results above as source material. Do not ignore them. Work only this task and only its in-scope paths in this turn.
177
178 State policy: ${stateDir}/${teamId}/ is read-only diagnostics; mutate team state only through agent_teams_* tools.`;
179 }
180 /** Install one scheduler and its member activity observer. */
181 export function installTeamScheduler(ctx, config) {
182 const memberQueues = new Map();
183 // An idle edge in this process proves that the resident member ended its
184 // turn while the current attempt was still open. Remember that capability
185 // even after Harness disposes the continuable AgentHandle: later status or
186 // graph kicks must keep it parked. A cold process starts with an empty map,
187 // so durable open attempts are still recovered after restart.
188 const parkedAttempts = new Map();
189 const memberQueueKey = (stateRoot, teamId, memberName) => (`${stateRoot}\u0000${teamId}\u0000${memberName}`);
190 const serializeMember = async (key, operation) => {
191 const previous = memberQueues.get(key) ?? Promise.resolve();
192 let release;
193 const gate = new Promise((resolve) => { release = resolve; });
194 const tail = previous.then(() => gate);
195 memberQueues.set(key, tail);
196 await previous;
197 try {
198 return await operation();
199 }
200 finally {
201 release();
202 if (memberQueues.get(key) === tail)
203 memberQueues.delete(key);
204 }
205 };
206 const runtime = {
207 async kickTeam(workspace, teamId, suppliedCaptain) {
208 const stateRoot = stateRootOf(workspace, config);
209 const team = await readTeam(stateRoot, teamId);
210 if (team === undefined || team.halted === true || team.phase === 'staged')
211 return;
212 const captain = liveCaptain(ctx, team.captainSessionId, suppliedCaptain);
213 if (captain === undefined)
214 return;
215 for (const member of team.members) {
216 if (member.status === 'removed')
217 continue;
218 await runtime.kickMember(workspace, teamId, member.name, captain);
219 }
220 },
221 async kickMember(workspace, teamId, memberName, suppliedCaptain) {
222 const stateRoot = stateRootOf(workspace, config);
223 const queueKey = memberQueueKey(stateRoot, teamId, memberName);
224 await serializeMember(queueKey, async () => {
225 let team = await readTeam(stateRoot, teamId);
226 if (team === undefined || team.halted === true || team.phase === 'staged')
227 return;
228 const captain = liveCaptain(ctx, team.captainSessionId, suppliedCaptain);
229 if (captain === undefined)
230 return;
231 let member = team.members.find(candidate => candidate.name === memberName && candidate.status !== 'removed');
232 if (member === undefined || !isMemberAvailable(ctx, member))
233 return;
234 // A mailbox-only fallback is real pending work. Deliver it before a
235 // fresh task and acknowledge only after Harness accepts the follow-up.
236 const unread = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
237 const fresh = await readTeam(stateRoot, team.id);
238 if (fresh === undefined)
239 return [];
240 const pending = await readPendingMailbox(stateRoot, fresh.id, member.name);
241 await discardMailboxMessages(stateRoot, fresh.id, member.name, pending.filter(message => !isCurrentMail(fresh, message)).map(message => message.id));
242 const current = pending.filter(message => isCurrentMail(fresh, message));
243 await claimMailboxDelivery(stateRoot, fresh.id, member.name, current.map(message => message.id));
244 return current;
245 });
246 if (unread.length > 0) {
247 const prompt = mailboxPrompt(team.id, member.name, unread);
248 const signal = new AbortController().signal;
249 const accepted = config.dispatch === undefined
250 ? await deliverToMember(ctx, captain, member.id, prompt, signal, 'steer')
251 : await config.dispatch(captain, team.id, member.name, prompt, signal, 'steer');
252 if (accepted) {
253 await withTeamLock(teamLockKey(stateRoot, team.id), () => (markMailboxDelivered(stateRoot, team.id, member.name, unread.map(message => message.id))));
254 }
255 else {
256 await withTeamLock(teamLockKey(stateRoot, team.id), () => (releaseMailboxDelivery(stateRoot, team.id, member.name, unread.map(message => message.id))));
257 }
258 return;
259 }
260 const ticket = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
261 const fresh = await readTeam(stateRoot, team.id);
262 if (fresh === undefined || fresh.halted === true || fresh.phase === 'staged')
263 return undefined;
264 const currentMember = fresh.members.find(candidate => candidate.name === memberName && candidate.status !== 'removed');
265 if (currentMember === undefined || !isMemberAvailable(ctx, currentMember))
266 return undefined;
267 const owned = ownedOpenTask(fresh.tasks, currentMember.name);
268 // An idle edge observed by this scheduler parks the exact open
269 // capability. Harness may dispose its AgentHandle after settlement,
270 // so registry absence is not evidence that the owner was lost. Keep
271 // the marker sticky across later kicks; only a durable attempt that
272 // this process has not observed is eligible for one cold recovery.
273 const parkedAttemptId = parkedAttempts.get(currentMember.id);
274 const recoverOwned = owned !== undefined
275 && (owned.attemptId === undefined || owned.attemptId !== parkedAttemptId);
276 const task = recoverOwned ? owned : owned === undefined
277 ? nextReadyTask(fresh.tasks, currentMember.name)
278 : undefined;
279 if (task === undefined) {
280 if (currentMember.status !== 'idle') {
281 currentMember.status = 'idle';
282 await writeTeam(stateRoot, fresh);
283 }
284 return undefined;
285 }
286 const previousAssignee = task.assignee;
287 const previousStatus = recoverOwned ? task.status : undefined;
288 const previousAttempt = recoverOwned ? task.attempt : undefined;
289 const previousAttemptId = recoverOwned ? task.attemptId : undefined;
290 const previousResult = recoverOwned ? {
291 output: task.output, verdict: task.verdict, findings: task.findings,
292 changedPaths: task.changedPaths, acceptanceResults: task.acceptanceResults, commandsRun: task.commandsRun,
293 } : undefined;
294 const attemptId = beginTaskAttempt(task, currentMember.name);
295 // A verdict must be able to say which revision was on disk when it
296 // started, so a review that runs while someone else edits the tree
297 // cannot later claim to have judged stable bytes (issue #161).
298 if (isVerdictKind(taskKindOf(task))) {
299 const scope = verdictScopePatterns(fresh, task);
300 if (scope.length > 0)
301 task.verdictStartSnapshot = snapshotWorkspacePaths(workspace, scope);
302 }
303 // A recovered generation is parked before delivery. This makes each
304 // (member, attempt) recovery idempotent even if every status poll
305 // sees a disposed handle. Fresh pending work remains unparked so a
306 // genuinely lost first delivery can be recovered once.
307 if (recoverOwned)
308 parkedAttempts.set(currentMember.id, attemptId);
309 else
310 parkedAttempts.delete(currentMember.id);
311 currentMember.status = 'working';
312 await writeTeam(stateRoot, fresh);
313 const profileSeedId = taskProfileSeedId(task);
314 const protocol = teamProfileProtocol(fresh);
315 return {
316 taskId: task.id,
317 memberName: currentMember.name,
318 memberId: currentMember.id,
319 attempt: task.attempt ?? 1,
320 attemptId,
321 previousAssignee,
322 recoveredOwned: recoverOwned,
323 ...previousResult === undefined ? {} : { previousResult },
324 ...previousStatus === undefined ? {} : { previousStatus },
325 ...previousAttempt === undefined ? {} : { previousAttempt },
326 ...previousAttemptId === undefined ? {} : { previousAttemptId },
327 subject: task.subject,
328 description: task.description,
329 teamDescription: fresh.description,
330 ...protocol === undefined ? {} : { profileProtocol: protocol },
331 ...profileSeedId === undefined ? {} : { profileSeedId },
332 ...fresh.profile?.executionPrompt === undefined && config.executionPrompt === undefined
333 ? {}
334 : { executionPrompt: fresh.profile?.executionPrompt ?? config.executionPrompt },
335 kind: task.kind ?? 'work',
336 ...task.round === undefined ? {} : { round: task.round },
337 ...task.objective === undefined ? {} : { objective: task.objective },
338 ...task.inScope === undefined ? {} : { inScope: task.inScope },
339 ...task.outOfScope === undefined ? {} : { outOfScope: task.outOfScope },
340 ...task.acceptance === undefined ? {} : { acceptance: task.acceptance },
341 ...task.verify === undefined ? {} : { verify: task.verify },
342 ...task.reviewedTaskId === undefined ? {} : { reviewedTaskId: task.reviewedTaskId },
343 ...task.findingSourceTaskIds === undefined ? {} : { findingSourceTaskIds: task.findingSourceTaskIds },
344 dependencyOutputs: collectCompletedDependencyOutputs(fresh.tasks, task.id, (message) => ctx.logger.warn(message)),
345 };
346 });
347 if (ticket === undefined)
348 return;
349 const taskForWarning = team.tasks.find((item) => item.id === ticket.taskId);
350 const workOrderStale = taskForWarning?.contractSnapshot === undefined
351 ? []
352 : contractStaleness(taskForWarning, digestWorkspacePaths(workspace, taskForWarning.contractSnapshot.artifacts.map((artifact) => artifact.path)));
353 const prompt = assignmentPrompt(ticket, config.stateDir, team.id, workOrderStale);
354 const signal = new AbortController().signal;
355 const accepted = config.dispatch === undefined
356 ? await deliverToMember(ctx, captain, ticket.memberId, prompt, signal)
357 : await config.dispatch(captain, team.id, ticket.memberName, prompt, signal, 'queue', ticket.attemptId);
358 if (accepted)
359 return;
360 // Roll back only our exact failed dispatch. A concurrent captain
361 // handoff has already changed the capability and wins.
362 await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
363 const fresh = await readTeam(stateRoot, team.id);
364 if (fresh === undefined)
365 return;
366 const task = fresh.tasks.find(candidate => candidate.id === ticket.taskId);
367 if (task?.attemptId !== ticket.attemptId)
368 return;
369 if (ticket.recoveredOwned && ticket.previousStatus !== undefined && ticket.previousAttemptId !== undefined) {
370 // Recovery delivery failed. Restore the durable generation instead
371 // of returning it to pending, then keep it parked so later status
372 // kicks cannot spend an unbounded sequence of fresh attempts.
373 task.status = ticket.previousStatus;
374 task.assignee = ticket.previousAssignee;
375 task.attempt = ticket.previousAttempt;
376 task.attemptId = ticket.previousAttemptId;
377 Object.assign(task, ticket.previousResult);
378 parkedAttempts.set(ticket.memberId, ticket.previousAttemptId);
379 }
380 else {
381 task.status = 'pending';
382 task.assignee = ticket.previousAssignee;
383 task.attemptId = undefined;
384 parkedAttempts.delete(ticket.memberId);
385 }
386 task.handoffId = undefined;
387 task.reassigning = false;
388 task.updatedAt = Date.now();
389 const currentMember = fresh.members.find(candidate => candidate.name === ticket.memberName);
390 if (currentMember !== undefined && currentMember.status !== 'removed')
391 currentMember.status = 'idle';
392 await writeTeam(stateRoot, fresh);
393 });
394 });
395 },
396 };
397 const syncMemberStatus = async (agent, status) => {
398 const workspace = agent.session.header.cwd ?? process.cwd();
399 const stateRoot = stateRootOf(workspace, config);
400 const located = await findTeamByParticipant(stateRoot, agent.id);
401 if (located === undefined) {
402 parkedAttempts.delete(agent.id);
403 return;
404 }
405 if (located.captainSessionId === agent.id) {
406 // Captain takeover is scoped to the captain's current turn. Unlike a
407 // durable member, the captain has no scheduler lane that can resume an
408 // abandoned attempt later. Returning unfinished captain-owned work to
409 // the shared pool on the idle edge prevents it from becoming a
410 // permanently parked `claimed` task after the captain answers, is
411 // interrupted, or the user switches conversations.
412 if (status === 'running')
413 return;
414 let requeued = false;
415 await withTeamLock(teamLockKey(stateRoot, located.id), async () => {
416 const fresh = await readTeam(stateRoot, located.id);
417 if (fresh === undefined || fresh.captainSessionId !== agent.id)
418 return;
419 for (const task of fresh.tasks) {
420 if (task.assignee !== CAPTAIN_KEY
421 || task.status === 'completed'
422 || task.status === 'failed'
423 || task.status === 'cancelled')
424 continue;
425 invalidateTaskAttempt(task);
426 task.reassigning = false;
427 requeued = true;
428 }
429 if (requeued)
430 await writeTeam(stateRoot, fresh);
431 });
432 if (requeued)
433 await runtime.kickTeam(workspace, located.id, agent);
434 return;
435 }
436 const member = located.members.find(candidate => candidate.id === agent.id && candidate.status !== 'removed');
437 if (member === undefined) {
438 parkedAttempts.delete(agent.id);
439 return;
440 }
441 await withTeamLock(teamLockKey(stateRoot, located.id), async () => {
442 const fresh = await readTeam(stateRoot, located.id);
443 const current = fresh?.members.find(candidate => candidate.id === agent.id && candidate.status !== 'removed');
444 if (fresh === undefined || current === undefined)
445 return;
446 const next = status === 'running' ? 'working' : 'idle';
447 if (next === 'idle') {
448 const owned = ownedOpenTask(fresh.tasks, current.name);
449 if (owned?.attemptId === undefined)
450 parkedAttempts.delete(agent.id);
451 else
452 parkedAttempts.set(agent.id, owned.attemptId);
453 }
454 else {
455 parkedAttempts.delete(agent.id);
456 }
457 if (current.status === next)
458 return;
459 current.status = next;
460 await writeTeam(stateRoot, fresh);
461 });
462 if (status === 'idle')
463 await runtime.kickMember(workspace, located.id, member.name);
464 };
465 ctx.on('agent/status', ({ agent, status }) => {
466 void syncMemberStatus(agent, status).catch((error) => {
467 ctx.logger.warn(`agent-teams: member status scheduling failed for ${agent.id}: ${String(error)}`);
468 });
469 });
470 return runtime;
471 }
472
472 lines JAVASCRIPT