@fish-under-sea/dsh-agent-teams-fish 1.0.2 → 2.0.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.
Files changed (179) hide show
  1. package/NOTICE.md +13 -7
  2. package/README.en.md +20 -12
  3. package/README.md +20 -12
  4. package/compatibility.json +82 -46
  5. package/icon.png +0 -0
  6. package/lib/artifacts.js +148 -25
  7. package/lib/client/ActivityPanel.js +26 -5
  8. package/lib/client/WorkspaceActivity.js +6 -4
  9. package/lib/client/activity-monitor.js +113 -41
  10. package/lib/client/locales.js +14 -0
  11. package/lib/client.js +433 -199
  12. package/lib/client.js.map +1 -1
  13. package/lib/command.js +7 -4
  14. package/lib/git-artifact-stamp.json +2 -2
  15. package/lib/harness-compat.js +120 -62
  16. package/lib/index.js +7 -10
  17. package/lib/mailbox.js +15 -5
  18. package/lib/members.js +221 -154
  19. package/lib/snapshot.js +15 -10
  20. package/lib/state.js +41 -8
  21. package/lib/tools.js +123 -64
  22. package/lib/types/artifacts.d.ts +6 -3
  23. package/lib/types/client/activity-monitor.d.ts +13 -4
  24. package/lib/types/client/locales.d.ts +14 -0
  25. package/lib/types/harness-compat.d.ts +63 -16
  26. package/lib/types/mailbox.d.ts +2 -0
  27. package/lib/types/members.d.ts +5 -17
  28. package/lib/types/snapshot.d.ts +12 -7
  29. package/lib/types/state.d.ts +10 -3
  30. package/lib/types/types.d.ts +5 -0
  31. package/lib/types/web-routes.d.ts +2 -0
  32. package/lib/types/workspace-audit-service.d.ts +35 -0
  33. package/lib/types/workspace-audit-worker.d.ts +1 -0
  34. package/lib/web-routes.js +31 -0
  35. package/lib/workspace-audit-service.js +165 -0
  36. package/lib/workspace-audit-worker.js +11 -0
  37. package/lib/workspace-audit.js +6 -5
  38. package/locale/en.json +6 -0
  39. package/locale/zh.json +6 -0
  40. package/package.json +69 -64
  41. package/pnpm-workspace.yaml +306 -273
  42. package/release-notes/v0.1.25.md +16 -0
  43. package/release-notes/v0.1.26.md +19 -0
  44. package/release-notes/v0.1.27.md +42 -0
  45. package/release-notes/v0.1.28.md +45 -0
  46. package/release-notes/v0.1.29.md +23 -0
  47. package/release-notes/v1.1.0.md +42 -0
  48. package/release-notes/v2.0.0.md +17 -0
  49. package/scripts/artwork-role-match.test.mjs +517 -0
  50. package/scripts/capabilities.test.mjs +301 -0
  51. package/scripts/check-install-channel.mjs +55 -0
  52. package/scripts/check-install-channel.test.mjs +39 -0
  53. package/scripts/clean-build.mjs +14 -0
  54. package/scripts/client-harness-migration.test.mjs +46 -0
  55. package/scripts/compatibility.mjs +20 -0
  56. package/scripts/compatibility.test.mjs +187 -0
  57. package/scripts/corrupt-teamjson.test.mjs +180 -0
  58. package/scripts/custom-artwork.test.mjs +273 -0
  59. package/scripts/fallback-tdd.mjs +61 -0
  60. package/scripts/fixtures/harness-benchmark-scope.mjs +16 -0
  61. package/scripts/fixtures/harness-benchmark-scope.test.mjs +18 -0
  62. package/scripts/fixtures/harness-complex-case.mjs +201 -0
  63. package/scripts/fixtures/harness-complex-case.test.mjs +21 -0
  64. package/scripts/fixtures/harness-complex-oracle.mjs +63 -0
  65. package/scripts/fixtures/harness-issue-case.mjs +51 -0
  66. package/scripts/fixtures/harness-issue159-case.mjs +28 -0
  67. package/scripts/fixtures/harness-model-case.mjs +127 -0
  68. package/scripts/fixtures/harness-model-case.test.mjs +37 -0
  69. package/scripts/fixtures/harness-model-driver.mjs +100 -0
  70. package/scripts/fixtures/harness-runtime-credentials.mjs +23 -0
  71. package/scripts/fixtures/harness-runtime-entry.mjs +171 -0
  72. package/scripts/fixtures/harness-runtime-idle.mjs +42 -0
  73. package/scripts/fixtures/harness-runtime-llm.mjs +193 -0
  74. package/scripts/fixtures/harness-runtime-protocol.mjs +187 -0
  75. package/scripts/fixtures/harness-runtime-resume.mjs +24 -0
  76. package/scripts/fixtures/harness-runtime-stability.mjs +282 -0
  77. package/scripts/fixtures/harness-runtime-tools.mjs +13 -0
  78. package/scripts/fixtures/harness-runtime-web-approval.mjs +341 -0
  79. package/scripts/fixtures/issue-336-audit-worker.mjs +18 -0
  80. package/scripts/git-artifacts.mjs +64 -0
  81. package/scripts/git-artifacts.test.mjs +32 -0
  82. package/scripts/harness-compat-tdd.mjs +492 -0
  83. package/scripts/harness-issue-verify.mjs +26 -0
  84. package/scripts/harness-model-benchmark.mjs +163 -0
  85. package/scripts/harness-runtime-platform.test.mjs +31 -0
  86. package/scripts/harness-runtime-scenarios.mjs +297 -0
  87. package/scripts/harness-runtime-verify.mjs +169 -0
  88. package/scripts/harness-source-verify.mjs +211 -0
  89. package/scripts/harness-source-verify.test.mjs +97 -0
  90. package/scripts/harness-validation.mjs +68 -0
  91. package/scripts/harness-validation.test.mjs +95 -0
  92. package/scripts/http-body.test.mjs +72 -0
  93. package/scripts/import-vendor-artwork.mjs +78 -0
  94. package/scripts/inline-plan-blank-optional-tdd.mjs +121 -0
  95. package/scripts/issue-159.test.mjs +78 -0
  96. package/scripts/issue-188.test.mjs +148 -0
  97. package/scripts/issue-189.test.mjs +100 -0
  98. package/scripts/issue-203-card.test.mjs +181 -0
  99. package/scripts/issue-205.test.mjs +163 -0
  100. package/scripts/issue-234.test.mjs +424 -0
  101. package/scripts/issue-236-stale-module.test.mjs +63 -0
  102. package/scripts/issue-236.test.mjs +59 -0
  103. package/scripts/issue-262.test.mjs +98 -0
  104. package/scripts/issue-336.test.mjs +404 -0
  105. package/scripts/legacy-session-source-repair.test.mjs +201 -0
  106. package/scripts/lifecycle-verify.mjs +1573 -0
  107. package/scripts/lineage-identity.test.mjs +77 -0
  108. package/scripts/member-failure-tdd.mjs +451 -0
  109. package/scripts/member-spawn-recovery.test.mjs +92 -0
  110. package/scripts/quality-gates-amend.test.mjs +161 -0
  111. package/scripts/quality-gates-content-bound.test.mjs +572 -0
  112. package/scripts/quality-gates-cross-binding.test.mjs +184 -0
  113. package/scripts/quality-gates-excluded-scope.test.mjs +163 -0
  114. package/scripts/quality-gates-repair-scope.test.mjs +143 -0
  115. package/scripts/quality-gates-repair-wiring.test.mjs +189 -0
  116. package/scripts/quality-gates-tdd.mjs +1238 -0
  117. package/scripts/quality-gates-work-order.test.mjs +494 -0
  118. package/scripts/readme-version.mjs +89 -0
  119. package/scripts/readme-version.test.mjs +77 -0
  120. package/scripts/release-metadata.mjs +45 -0
  121. package/scripts/release-metadata.test.mjs +66 -0
  122. package/scripts/scoped-release.test.mjs +52 -0
  123. package/scripts/stability-tdd.mjs +144 -0
  124. package/scripts/stress-verify.mjs +548 -0
  125. package/scripts/symlink-support.mjs +46 -0
  126. package/scripts/sync-skill.mjs +103 -0
  127. package/scripts/tool-policies.test.mjs +280 -0
  128. package/scripts/update-skills.mjs +105 -0
  129. package/scripts/update-skills.test.mjs +79 -0
  130. package/scripts/upgrade-status.mjs +66 -0
  131. package/scripts/upgrade-status.test.mjs +83 -0
  132. package/scripts/verify-package.mjs +73 -0
  133. package/scripts/verify.mjs +2199 -0
  134. package/scripts/web-routes-verify.mjs +142 -0
  135. package/scripts/workspace-activity.test.mjs +346 -0
  136. package/scripts/workspace-summary.test.mjs +49 -0
  137. package/src/artifacts.ts +487 -0
  138. package/src/artwork-source.ts +262 -0
  139. package/src/capabilities.ts +113 -0
  140. package/src/client/ActivityPanel.module.css +2390 -0
  141. package/src/client/ActivityPanel.tsx +1507 -0
  142. package/src/client/AgentTeamsCard.module.css +148 -0
  143. package/src/client/AgentTeamsCard.tsx +155 -0
  144. package/src/client/StagingPlanEditor.tsx +829 -0
  145. package/src/client/TeamChatEntry.tsx +27 -0
  146. package/src/client/WorkspaceActivity.module.css +41 -0
  147. package/src/client/WorkspaceActivity.tsx +137 -0
  148. package/src/client/activity-model.ts +372 -0
  149. package/src/client/activity-monitor.ts +440 -0
  150. package/src/client/agent-teams-card-definition.ts +250 -0
  151. package/src/client/artwork.ts +374 -0
  152. package/src/client/icons.tsx +17 -0
  153. package/src/client/index.tsx +140 -0
  154. package/src/client/locales.ts +481 -0
  155. package/src/client/panel-geometry.ts +194 -0
  156. package/src/client/session-navigation.ts +73 -0
  157. package/src/client/workspace-state.ts +52 -0
  158. package/src/command.ts +145 -0
  159. package/src/css-modules.d.ts +4 -0
  160. package/src/event-types.ts +177 -0
  161. package/src/events.ts +78 -0
  162. package/src/harness-compat.ts +570 -0
  163. package/src/index.ts +599 -0
  164. package/src/lineage.ts +248 -0
  165. package/src/mailbox.ts +185 -0
  166. package/src/members.ts +1230 -0
  167. package/src/profiles.ts +765 -0
  168. package/src/quality-gates.ts +2124 -0
  169. package/src/scheduler.ts +554 -0
  170. package/src/snapshot.ts +333 -0
  171. package/src/state.ts +1317 -0
  172. package/src/tool-names.ts +14 -0
  173. package/src/tool-policies.ts +219 -0
  174. package/src/tools.ts +2939 -0
  175. package/src/types.ts +414 -0
  176. package/src/web-routes.ts +128 -0
  177. package/src/workspace-audit-service.ts +182 -0
  178. package/src/workspace-audit-worker.ts +12 -0
  179. package/src/workspace-audit.ts +57 -0
@@ -0,0 +1,554 @@
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
+
15
+ import type { Context } from '@deepseek-ai/cordis'
16
+ import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
17
+ import type { SessionId } from '@deepseek-ai/dsh-session'
18
+ import { join } from 'node:path'
19
+ import { deliverToMember } from './members.ts'
20
+ import { isCurrentMail, mailboxPrompt } from './mailbox.ts'
21
+ import {
22
+ markMailboxDelivered,
23
+ discardMailboxMessages,
24
+ beginTaskAttempt,
25
+ CAPTAIN_KEY,
26
+ claimMailboxDelivery,
27
+ findTeamByParticipant,
28
+ invalidateTaskAttempt,
29
+ readTeam,
30
+ readPendingMailbox,
31
+ releaseMailboxDelivery,
32
+ unsatisfiedDependencies,
33
+ withTeamLock,
34
+ writeTeam,
35
+ } from './state.ts'
36
+ import { contractStaleness, isVerdictKind, taskKindOf, verdictScopePatterns } from './quality-gates.ts'
37
+ import { digestWorkspacePaths, snapshotWorkspacePaths } from './artifacts.ts'
38
+ import type { TeamMember, TeamState, TeamTask } from './types.ts'
39
+
40
+ /** Per-dependency output cap in the assignment prompt. */
41
+ export const DEPENDENCY_OUTPUT_MAX_CHARS = 2_000
42
+ /** Combined dependency-output budget in the assignment prompt. */
43
+ export const DEPENDENCY_OUTPUTS_TOTAL_MAX_CHARS = 12_000
44
+
45
+ export interface SchedulerConfig {
46
+ readonly stateDir: string
47
+ readonly executionPrompt?: string
48
+ readonly dispatch?: (captain: Agent, teamId: string, memberName: string, text: string, signal: AbortSignal, mode: 'queue' | 'steer', attemptId?: string) => Promise<boolean>
49
+ }
50
+
51
+ export interface TeamScheduler {
52
+ /** Try to give every genuinely idle/ready member one unit of ready work. */
53
+ kickTeam(workspace: string, teamId: string, captain?: Agent): Promise<void>
54
+ /** Try to flush fallback mail or give one member one ready task. */
55
+ kickMember(workspace: string, teamId: string, memberName: string, captain?: Agent): Promise<void>
56
+ }
57
+
58
+ /** One completed recursive dependency shown to the assignee. */
59
+ export interface DependencyOutput {
60
+ readonly id: string
61
+ readonly subject: string
62
+ readonly profileSeedId?: string
63
+ readonly output?: string
64
+ }
65
+
66
+ export interface DispatchTicket {
67
+ readonly taskId: string
68
+ readonly memberName: string
69
+ readonly memberId: string
70
+ readonly attempt: number
71
+ readonly attemptId: string
72
+ readonly previousAssignee?: string
73
+ /** True when this ticket rotates an unobserved durable open attempt. */
74
+ readonly recoveredOwned: boolean
75
+ /** Original task generation, used to restore a failed automatic recovery. */
76
+ readonly previousStatus?: 'claimed' | 'in_progress'
77
+ readonly previousAttempt?: number
78
+ readonly previousAttemptId?: string
79
+ readonly previousResult?: Pick<TeamTask, 'output' | 'verdict' | 'findings' | 'changedPaths' | 'acceptanceResults' | 'commandsRun'>
80
+ readonly subject: string
81
+ readonly description?: string
82
+ readonly teamDescription?: string
83
+ readonly profileProtocol?: string
84
+ readonly profileSeedId?: string
85
+ readonly dependencyOutputs: readonly DependencyOutput[]
86
+ readonly executionPrompt?: string
87
+ readonly kind?: string
88
+ readonly round?: number
89
+ readonly objective?: string
90
+ readonly inScope?: readonly string[]
91
+ readonly outOfScope?: readonly string[]
92
+ readonly acceptance?: readonly string[]
93
+ readonly verify?: readonly string[]
94
+ readonly reviewedTaskId?: string
95
+ readonly findingSourceTaskIds?: readonly string[]
96
+ }
97
+
98
+ function taskProfileSeedId(task: TeamTask): string | undefined {
99
+ const seed = task.profileSeedId?.trim()
100
+ return seed === undefined || seed === '' ? undefined : seed
101
+ }
102
+
103
+ function teamProfileProtocol(team: TeamState): string | undefined {
104
+ return team.profile?.protocol
105
+ }
106
+
107
+ /**
108
+ * Recursively collect `status=completed` ancestors of `taskId` in topological
109
+ * order (dependencies before dependents). Cycles stop that branch only.
110
+ */
111
+ export function collectCompletedDependencyOutputs(
112
+ tasks: readonly TeamTask[],
113
+ taskId: string,
114
+ warn?: (message: string) => void,
115
+ ): DependencyOutput[] {
116
+ const byId = new Map(tasks.map(task => [task.id, task]))
117
+ const visiting = new Set<string>()
118
+ const visited = new Set<string>()
119
+ const ordered: TeamTask[] = []
120
+
121
+ const walk = (id: string): void => {
122
+ if (visiting.has(id)) {
123
+ warn?.(`agent-teams: dependency cycle involving "${id}" while collecting outputs; stopping this branch`)
124
+ return
125
+ }
126
+ if (visited.has(id)) return
127
+ visiting.add(id)
128
+ const task = byId.get(id)
129
+ if (task !== undefined) {
130
+ for (const dependency of task.dependencies) walk(dependency)
131
+ if (id !== taskId) ordered.push(task)
132
+ }
133
+ visiting.delete(id)
134
+ visited.add(id)
135
+ }
136
+
137
+ walk(taskId)
138
+ return ordered
139
+ .filter(task => task.status === 'completed')
140
+ .map((task) => {
141
+ const profileSeedId = taskProfileSeedId(task)
142
+ return {
143
+ id: task.id,
144
+ subject: task.subject,
145
+ ...profileSeedId === undefined ? {} : { profileSeedId },
146
+ ...task.output === undefined ? {} : { output: task.output },
147
+ }
148
+ })
149
+ }
150
+
151
+ /** Format completed-dependency outputs with per-item and total truncation. */
152
+ export function formatDependencyOutputs(items: readonly DependencyOutput[]): string {
153
+ if (items.length === 0) return '(none)'
154
+ const formatted = items.map((item) => {
155
+ const seed = item.profileSeedId === undefined ? '' : ` [${item.profileSeedId}]`
156
+ const raw = item.output === undefined || item.output === ''
157
+ ? '(no output recorded)'
158
+ : item.output
159
+ const truncated = raw.length > DEPENDENCY_OUTPUT_MAX_CHARS
160
+ const body = truncated ? `${raw.slice(0, DEPENDENCY_OUTPUT_MAX_CHARS)} [truncated]` : raw
161
+ return `- ${item.id}${seed} ${item.subject}:\n ${body}`
162
+ })
163
+ let selected = formatted
164
+ while (selected.length > 1 && selected.join('\n').length > DEPENDENCY_OUTPUTS_TOTAL_MAX_CHARS) {
165
+ selected = selected.slice(1)
166
+ }
167
+ const last = selected[0]
168
+ if (selected.length === 1 && last !== undefined && last.length > DEPENDENCY_OUTPUTS_TOTAL_MAX_CHARS) {
169
+ selected = [`${last.slice(0, DEPENDENCY_OUTPUTS_TOTAL_MAX_CHARS)} [truncated]`]
170
+ }
171
+ return selected.join('\n')
172
+ }
173
+
174
+ function stateRootOf(workspace: string, config: SchedulerConfig): string {
175
+ return join(workspace, config.stateDir)
176
+ }
177
+
178
+ function teamLockKey(stateRoot: string, teamId: string): string {
179
+ return `team:${stateRoot}:${teamId}`
180
+ }
181
+
182
+ function liveCaptain(ctx: Context, captainSessionId: string, supplied?: Agent): Agent | undefined {
183
+ if (supplied !== undefined && supplied.id === captainSessionId) return supplied
184
+ return ctx.agents.get(captainSessionId as SessionId)
185
+ }
186
+
187
+ function liveMember(ctx: Context, member: TeamMember): Agent | undefined {
188
+ return ctx.agents.get(member.id as SessionId)
189
+ }
190
+
191
+ function isMemberAvailable(ctx: Context, member: TeamMember): boolean {
192
+ if (member.stopping === true) return false
193
+ const live = liveMember(ctx, member)
194
+ return live === undefined || live.status === 'idle'
195
+ }
196
+
197
+ function ownedOpenTask(tasks: readonly TeamTask[], memberName: string): TeamTask | undefined {
198
+ return tasks.find(task => task.assignee === memberName
199
+ && (task.status === 'claimed' || task.status === 'in_progress'))
200
+ }
201
+
202
+ function nextReadyTask(tasks: readonly TeamTask[], memberName: string): TeamTask | undefined {
203
+ const ready = tasks.filter(task => task.status === 'pending'
204
+ && task.reassigning !== true
205
+ && unsatisfiedDependencies([...tasks], task.dependencies).length === 0)
206
+ return ready.find(task => task.assignee === memberName)
207
+ ?? ready.find(task => task.assignee === undefined)
208
+ }
209
+
210
+ export function assignmentPrompt(
211
+ ticket: DispatchTicket,
212
+ stateDir: string,
213
+ teamId: string,
214
+ workOrderWarnings: readonly string[] = [],
215
+ ): string {
216
+ const description = ticket.description === undefined ? '' : `\n\n${ticket.description}`
217
+ const seed = ticket.profileSeedId === undefined ? '' : ` [${ticket.profileSeedId}]`
218
+ const goal = ticket.teamDescription?.trim() || '(not provided)'
219
+ const protocol = ticket.profileProtocol?.trim() || '(none)'
220
+ const executionPrompt = ticket.executionPrompt?.trim()
221
+ const kind = ticket.kind?.trim() || 'work'
222
+ const staleWorkOrder = workOrderWarnings.length === 0
223
+ ? ''
224
+ : `\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`
225
+ const contract = [
226
+ `Kind: ${kind}${ticket.round === undefined ? '' : ` (round ${ticket.round})`}`,
227
+ ticket.objective === undefined || ticket.objective === '' ? '' : `Objective: ${ticket.objective}`,
228
+ ticket.inScope === undefined || ticket.inScope.length === 0 ? '' : `In scope: ${ticket.inScope.join(', ')}`,
229
+ ticket.outOfScope === undefined || ticket.outOfScope.length === 0 ? '' : `Out of scope: ${ticket.outOfScope.join(', ')}`,
230
+ ticket.acceptance === undefined || ticket.acceptance.length === 0 ? '' : `Acceptance: ${ticket.acceptance.join('; ')}`,
231
+ ticket.verify === undefined || ticket.verify.length === 0 ? '' : `Verify: ${ticket.verify.join('; ')}`,
232
+ ticket.reviewedTaskId === undefined ? '' : `Reviewed task: ${ticket.reviewedTaskId}`,
233
+ ticket.findingSourceTaskIds === undefined || ticket.findingSourceTaskIds.length === 0 ? '' : `Fixes findings of: ${ticket.findingSourceTaskIds.join(', ')}`,
234
+ ].filter((line) => line !== '').join('\n')
235
+ const structuredCompletion = ['implementation', 'repair', 'verification', 'integration'].includes(kind)
236
+ ? `
237
+ Structured completion payload (keep these arrays in contract order):
238
+ acceptanceResults: ${JSON.stringify((ticket.acceptance ?? []).map((criterion) => ({ criterion, status: 'passed', evidence: '<what proved it>' })))}
239
+ commandsRun: ${JSON.stringify((ticket.verify ?? []).map((command) => ({ command, status: 'passed', exitCode: 0, evidence: '<observed result>' })))}
240
+ ${kind === 'implementation' || kind === 'repair' ? 'changedPaths: list the actual workspace-relative POSIX paths you changed.\n' : ''}`
241
+ : ''
242
+ return `AgentTeams automatic task assignment from the shared task list.
243
+
244
+ You are executing as configured member "${ticket.memberName}".
245
+ Do not start a teammate's assigned task.
246
+
247
+ Team goal:
248
+ ${goal}
249
+
250
+ Profile protocol:
251
+ ${protocol}
252
+ ${executionPrompt === undefined || executionPrompt === '' ? '' : `
253
+ Execution guidance:
254
+ ${executionPrompt}
255
+ `}
256
+ Completed dependency results:
257
+ ${formatDependencyOutputs(ticket.dependencyOutputs)}
258
+
259
+ Task: ${ticket.taskId}${seed} — ${ticket.subject}${description}
260
+ ${staleWorkOrder}${contract === '' ? '' : `\nContract:\n${contract}\n`}
261
+ ${structuredCompletion}
262
+ Attempt: ${ticket.attempt}
263
+ Attempt id: ${ticket.attemptId}
264
+
265
+ 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.
266
+ 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.
267
+
268
+ State policy: ${stateDir}/${teamId}/ is read-only diagnostics; mutate team state only through agent_teams_* tools.`
269
+ }
270
+
271
+ /** Install one scheduler and its member activity observer. */
272
+ export function installTeamScheduler(ctx: Context, config: SchedulerConfig): TeamScheduler {
273
+ const memberQueues = new Map<string, Promise<unknown>>()
274
+ // An idle edge in this process proves that the resident member ended its
275
+ // turn while the current attempt was still open. Remember that capability
276
+ // even after Harness disposes the continuable AgentHandle: later status or
277
+ // graph kicks must keep it parked. A cold process starts with an empty map,
278
+ // so durable open attempts are still recovered after restart.
279
+ const parkedAttempts = new Map<string, string>()
280
+
281
+ const memberQueueKey = (stateRoot: string, teamId: string, memberName: string): string => (
282
+ `${stateRoot}\u0000${teamId}\u0000${memberName}`
283
+ )
284
+
285
+ const serializeMember = async <T>(key: string, operation: () => Promise<T>): Promise<T> => {
286
+ const previous = memberQueues.get(key) ?? Promise.resolve()
287
+ let release!: () => void
288
+ const gate = new Promise<void>((resolve) => { release = resolve })
289
+ const tail = previous.then(() => gate)
290
+ memberQueues.set(key, tail)
291
+ await previous
292
+ try {
293
+ return await operation()
294
+ } finally {
295
+ release()
296
+ if (memberQueues.get(key) === tail) memberQueues.delete(key)
297
+ }
298
+ }
299
+
300
+ const runtime: TeamScheduler = {
301
+ async kickTeam(workspace, teamId, suppliedCaptain) {
302
+ const stateRoot = stateRootOf(workspace, config)
303
+ const team = await readTeam(stateRoot, teamId)
304
+ if (team === undefined || team.halted === true || team.phase === 'staged') return
305
+ const captain = liveCaptain(ctx, team.captainSessionId, suppliedCaptain)
306
+ if (captain === undefined) return
307
+ for (const member of team.members) {
308
+ if (member.status === 'removed') continue
309
+ await runtime.kickMember(workspace, teamId, member.name, captain)
310
+ }
311
+ },
312
+
313
+ async kickMember(workspace, teamId, memberName, suppliedCaptain) {
314
+ const stateRoot = stateRootOf(workspace, config)
315
+ const queueKey = memberQueueKey(stateRoot, teamId, memberName)
316
+ await serializeMember(queueKey, async () => {
317
+ let team = await readTeam(stateRoot, teamId)
318
+ if (team === undefined || team.halted === true || team.phase === 'staged') return
319
+ const captain = liveCaptain(ctx, team.captainSessionId, suppliedCaptain)
320
+ if (captain === undefined) return
321
+ let member = team.members.find(candidate => candidate.name === memberName && candidate.status !== 'removed')
322
+ if (member === undefined || !isMemberAvailable(ctx, member)) return
323
+
324
+ // A mailbox-only fallback is real pending work. Deliver it before a
325
+ // fresh task and acknowledge only after Harness accepts the follow-up.
326
+ const unread = await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
327
+ const fresh = await readTeam(stateRoot, team!.id)
328
+ if (fresh === undefined) return []
329
+ const pending = await readPendingMailbox(stateRoot, fresh.id, member!.name)
330
+ await discardMailboxMessages(stateRoot, fresh.id, member!.name, pending.filter(message => !isCurrentMail(fresh, message)).map(message => message.id))
331
+ const current = pending.filter(message => isCurrentMail(fresh, message))
332
+ await claimMailboxDelivery(stateRoot, fresh.id, member!.name, current.map(message => message.id))
333
+ return current
334
+ })
335
+ if (unread.length > 0) {
336
+ const prompt = mailboxPrompt(team.id, member.name, unread)
337
+ const signal = new AbortController().signal
338
+ const accepted = config.dispatch === undefined
339
+ ? await deliverToMember(ctx, captain, member.id, prompt, signal, 'steer')
340
+ : await config.dispatch(captain, team.id, member.name, prompt, signal, 'steer')
341
+ if (accepted) {
342
+ await withTeamLock(teamLockKey(stateRoot, team.id), () => (
343
+ markMailboxDelivered(stateRoot, team!.id, member!.name, unread.map(message => message.id))
344
+ ))
345
+ } else {
346
+ await withTeamLock(teamLockKey(stateRoot, team.id), () => (
347
+ releaseMailboxDelivery(stateRoot, team!.id, member!.name, unread.map(message => message.id))
348
+ ))
349
+ }
350
+ return
351
+ }
352
+
353
+ const ticket = await withTeamLock(teamLockKey(stateRoot, team.id), async (): Promise<DispatchTicket | undefined> => {
354
+ const fresh = await readTeam(stateRoot, team!.id)
355
+ if (fresh === undefined || fresh.halted === true || fresh.phase === 'staged') return undefined
356
+ const currentMember = fresh.members.find(candidate => candidate.name === memberName && candidate.status !== 'removed')
357
+ if (currentMember === undefined || !isMemberAvailable(ctx, currentMember)) return undefined
358
+ const owned = ownedOpenTask(fresh.tasks, currentMember.name)
359
+ // An idle edge observed by this scheduler parks the exact open
360
+ // capability. Harness may dispose its AgentHandle after settlement,
361
+ // so registry absence is not evidence that the owner was lost. Keep
362
+ // the marker sticky across later kicks; only a durable attempt that
363
+ // this process has not observed is eligible for one cold recovery.
364
+ const parkedAttemptId = parkedAttempts.get(currentMember.id)
365
+ const recoverOwned = owned !== undefined
366
+ && (owned.attemptId === undefined || owned.attemptId !== parkedAttemptId)
367
+ const task = recoverOwned ? owned : owned === undefined
368
+ ? nextReadyTask(fresh.tasks, currentMember.name)
369
+ : undefined
370
+ if (task === undefined) {
371
+ if (currentMember.status !== 'idle') {
372
+ currentMember.status = 'idle'
373
+ await writeTeam(stateRoot, fresh)
374
+ }
375
+ return undefined
376
+ }
377
+ const previousAssignee = task.assignee
378
+ const previousStatus = recoverOwned ? task.status as 'claimed' | 'in_progress' : undefined
379
+ const previousAttempt = recoverOwned ? task.attempt : undefined
380
+ const previousAttemptId = recoverOwned ? task.attemptId : undefined
381
+ const previousResult = recoverOwned ? {
382
+ output: task.output, verdict: task.verdict, findings: task.findings,
383
+ changedPaths: task.changedPaths, acceptanceResults: task.acceptanceResults, commandsRun: task.commandsRun,
384
+ } : undefined
385
+ const attemptId = beginTaskAttempt(task, currentMember.name)
386
+ // A verdict must be able to say which revision was on disk when it
387
+ // started, so a review that runs while someone else edits the tree
388
+ // cannot later claim to have judged stable bytes (issue #161).
389
+ if (isVerdictKind(taskKindOf(task))) {
390
+ const scope = verdictScopePatterns(fresh, task)
391
+ if (scope.length > 0) task.verdictStartSnapshot = snapshotWorkspacePaths(workspace, scope)
392
+ }
393
+ // A recovered generation is parked before delivery. This makes each
394
+ // (member, attempt) recovery idempotent even if every status poll
395
+ // sees a disposed handle. Fresh pending work remains unparked so a
396
+ // genuinely lost first delivery can be recovered once.
397
+ if (recoverOwned) parkedAttempts.set(currentMember.id, attemptId)
398
+ else parkedAttempts.delete(currentMember.id)
399
+ currentMember.status = 'working'
400
+ await writeTeam(stateRoot, fresh)
401
+ const profileSeedId = taskProfileSeedId(task)
402
+ const protocol = teamProfileProtocol(fresh)
403
+ return {
404
+ taskId: task.id,
405
+ memberName: currentMember.name,
406
+ memberId: currentMember.id,
407
+ attempt: task.attempt ?? 1,
408
+ attemptId,
409
+ previousAssignee,
410
+ recoveredOwned: recoverOwned,
411
+ ...previousResult === undefined ? {} : { previousResult },
412
+ ...previousStatus === undefined ? {} : { previousStatus },
413
+ ...previousAttempt === undefined ? {} : { previousAttempt },
414
+ ...previousAttemptId === undefined ? {} : { previousAttemptId },
415
+ subject: task.subject,
416
+ description: task.description,
417
+ teamDescription: fresh.description,
418
+ ...protocol === undefined ? {} : { profileProtocol: protocol },
419
+ ...profileSeedId === undefined ? {} : { profileSeedId },
420
+ ...fresh.profile?.executionPrompt === undefined && config.executionPrompt === undefined
421
+ ? {}
422
+ : { executionPrompt: fresh.profile?.executionPrompt ?? config.executionPrompt },
423
+ kind: task.kind ?? 'work',
424
+ ...task.round === undefined ? {} : { round: task.round },
425
+ ...task.objective === undefined ? {} : { objective: task.objective },
426
+ ...task.inScope === undefined ? {} : { inScope: task.inScope },
427
+ ...task.outOfScope === undefined ? {} : { outOfScope: task.outOfScope },
428
+ ...task.acceptance === undefined ? {} : { acceptance: task.acceptance },
429
+ ...task.verify === undefined ? {} : { verify: task.verify },
430
+ ...task.reviewedTaskId === undefined ? {} : { reviewedTaskId: task.reviewedTaskId },
431
+ ...task.findingSourceTaskIds === undefined ? {} : { findingSourceTaskIds: task.findingSourceTaskIds },
432
+ dependencyOutputs: collectCompletedDependencyOutputs(
433
+ fresh.tasks,
434
+ task.id,
435
+ (message) => ctx.logger.warn(message),
436
+ ),
437
+ }
438
+ })
439
+ if (ticket === undefined) return
440
+
441
+ const taskForWarning = team.tasks.find((item) => item.id === ticket.taskId)
442
+ const workOrderStale = taskForWarning?.contractSnapshot === undefined
443
+ ? []
444
+ : contractStaleness(
445
+ taskForWarning,
446
+ digestWorkspacePaths(workspace, taskForWarning.contractSnapshot.artifacts.map((artifact) => artifact.path)),
447
+ )
448
+ const prompt = assignmentPrompt(ticket, config.stateDir, team.id, workOrderStale)
449
+ const signal = new AbortController().signal
450
+ const accepted = config.dispatch === undefined
451
+ ? await deliverToMember(ctx, captain, ticket.memberId, prompt, signal)
452
+ : await config.dispatch(captain, team.id, ticket.memberName, prompt, signal, 'queue', ticket.attemptId)
453
+ if (accepted) return
454
+
455
+ // Roll back only our exact failed dispatch. A concurrent captain
456
+ // handoff has already changed the capability and wins.
457
+ await withTeamLock(teamLockKey(stateRoot, team.id), async () => {
458
+ const fresh = await readTeam(stateRoot, team!.id)
459
+ if (fresh === undefined) return
460
+ const task = fresh.tasks.find(candidate => candidate.id === ticket.taskId)
461
+ if (task?.attemptId !== ticket.attemptId) return
462
+ if (ticket.recoveredOwned && ticket.previousStatus !== undefined && ticket.previousAttemptId !== undefined) {
463
+ // Recovery delivery failed. Restore the durable generation instead
464
+ // of returning it to pending, then keep it parked so later status
465
+ // kicks cannot spend an unbounded sequence of fresh attempts.
466
+ task.status = ticket.previousStatus
467
+ task.assignee = ticket.previousAssignee
468
+ task.attempt = ticket.previousAttempt
469
+ task.attemptId = ticket.previousAttemptId
470
+ Object.assign(task, ticket.previousResult)
471
+ parkedAttempts.set(ticket.memberId, ticket.previousAttemptId)
472
+ } else {
473
+ task.status = 'pending'
474
+ task.assignee = ticket.previousAssignee
475
+ task.attemptId = undefined
476
+ parkedAttempts.delete(ticket.memberId)
477
+ }
478
+ task.handoffId = undefined
479
+ task.reassigning = false
480
+ task.updatedAt = Date.now()
481
+ const currentMember = fresh.members.find(candidate => candidate.name === ticket.memberName)
482
+ if (currentMember !== undefined && currentMember.status !== 'removed') currentMember.status = 'idle'
483
+ await writeTeam(stateRoot, fresh)
484
+ })
485
+ })
486
+ },
487
+ }
488
+
489
+ const syncMemberStatus = async (agent: Agent, status: AgentStatus): Promise<void> => {
490
+ const workspace = agent.session.header.cwd ?? process.cwd()
491
+ const stateRoot = stateRootOf(workspace, config)
492
+ const located = await findTeamByParticipant(stateRoot, agent.id)
493
+ if (located === undefined) {
494
+ parkedAttempts.delete(agent.id)
495
+ return
496
+ }
497
+ if (located.captainSessionId === agent.id) {
498
+ // Captain takeover is scoped to the captain's current turn. Unlike a
499
+ // durable member, the captain has no scheduler lane that can resume an
500
+ // abandoned attempt later. Returning unfinished captain-owned work to
501
+ // the shared pool on the idle edge prevents it from becoming a
502
+ // permanently parked `claimed` task after the captain answers, is
503
+ // interrupted, or the user switches conversations.
504
+ if (status === 'running') return
505
+ let requeued = false
506
+ await withTeamLock(teamLockKey(stateRoot, located.id), async () => {
507
+ const fresh = await readTeam(stateRoot, located.id)
508
+ if (fresh === undefined || fresh.captainSessionId !== agent.id) return
509
+ for (const task of fresh.tasks) {
510
+ if (task.assignee !== CAPTAIN_KEY
511
+ || task.status === 'completed'
512
+ || task.status === 'failed'
513
+ || task.status === 'cancelled') continue
514
+ invalidateTaskAttempt(task)
515
+ task.reassigning = false
516
+ requeued = true
517
+ }
518
+ if (requeued) await writeTeam(stateRoot, fresh)
519
+ })
520
+ if (requeued) await runtime.kickTeam(workspace, located.id, agent)
521
+ return
522
+ }
523
+ const member = located.members.find(candidate => candidate.id === agent.id && candidate.status !== 'removed')
524
+ if (member === undefined) {
525
+ parkedAttempts.delete(agent.id)
526
+ return
527
+ }
528
+ await withTeamLock(teamLockKey(stateRoot, located.id), async () => {
529
+ const fresh = await readTeam(stateRoot, located.id)
530
+ const current = fresh?.members.find(candidate => candidate.id === agent.id && candidate.status !== 'removed')
531
+ if (fresh === undefined || current === undefined) return
532
+ const next = status === 'running' ? 'working' : 'idle'
533
+ if (next === 'idle') {
534
+ const owned = ownedOpenTask(fresh.tasks, current.name)
535
+ if (owned?.attemptId === undefined) parkedAttempts.delete(agent.id)
536
+ else parkedAttempts.set(agent.id, owned.attemptId)
537
+ } else {
538
+ parkedAttempts.delete(agent.id)
539
+ }
540
+ if (current.status === next) return
541
+ current.status = next
542
+ await writeTeam(stateRoot, fresh)
543
+ })
544
+ if (status === 'idle') await runtime.kickMember(workspace, located.id, member.name)
545
+ }
546
+
547
+ ctx.on('agent/status', ({ agent, status }) => {
548
+ void syncMemberStatus(agent, status).catch((error: unknown) => {
549
+ ctx.logger.warn(`agent-teams: member status scheduling failed for ${agent.id}: ${String(error)}`)
550
+ })
551
+ })
552
+
553
+ return runtime
554
+ }