@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,1573 @@
1
+ /**
2
+ * Adversarial production-tool conformance verification.
3
+ *
4
+ * This intentionally models the Harness contract where listChildren says
5
+ * "running" for every resident child while the live Agent registry carries
6
+ * the real idle/running state. It drives the actual compiled tool definitions
7
+ * through a multi-member DAG, takeover, stale completion, automatic later
8
+ * rounds, removal recovery, mailbox fallback and concurrent claims.
9
+ */
10
+
11
+ import { mkdtemp, rm } from 'node:fs/promises'
12
+ import { tmpdir } from 'node:os'
13
+ import { join } from 'node:path'
14
+ import { LlmError } from '@deepseek-ai/dsh-llm'
15
+ import { haltTeamWork, registerAgentTeamsTools } from '../lib/tools.js'
16
+ import { buildActivationDirective, invokedAgentTeamsGoal, invokedAgentTeamsInvocation, installAgentTeamsGestureBoundary, profileCommandName, registerAgentTeamsCommand } from '../lib/command.js'
17
+ import { readArchivedTeam, readMailbox, readTeam, readUnreadMailbox } from '../lib/state.js'
18
+ import { assembleTeamSnapshot, collectArchivedTeamsActivity } from '../lib/snapshot.js'
19
+
20
+ const activationHarness = process.argv.includes('--activation-harness')
21
+ const deliveryHarness = activationHarness || process.argv.includes('--delivery-harness')
22
+ const modernHarness = deliveryHarness || process.argv.includes('--modern-harness')
23
+ const hostQueue = Symbol.for(deliveryHarness ? 'dsh.subagent.deliverPrompt' : 'dsh.subagent.queuePrompt')
24
+
25
+ const workspace = await mkdtemp(join(tmpdir(), 'dsh-agent-teams-lifecycle-'))
26
+ const definitions = new Map()
27
+ const liveAgents = new Map()
28
+ const disposedAgents = new Map()
29
+ const children = []
30
+ const deliveries = []
31
+ const listeners = new Map()
32
+ const childListeners = new Map()
33
+ const continuableSetups = []
34
+ const failNextDelivery = new Set()
35
+ const failNextDrain = new Set()
36
+ const failures = []
37
+ let childSeq = 0
38
+ let messageSeq = 0
39
+ let deliveryDelayMs = 0
40
+
41
+ function check(label, condition, detail = '') {
42
+ const status = condition ? 'PASS' : 'FAIL'
43
+ console.log(` ${status} ${label}${detail ? ` — ${detail}` : ''}`)
44
+ if (!condition) failures.push(label)
45
+ }
46
+
47
+ function session(parentSession) {
48
+ return {
49
+ header: { cwd: workspace, parentSession, ...(modernHarness ? {} : { seedLength: 0 }) },
50
+ ...(modernHarness ? { ownEvents() { return this._ownEvents ?? [] } } : { events: [] }),
51
+ append() {},
52
+ requestHeader() {
53
+ return { config: { provider: 'fake', model: 'fake-model', reasoningEffort: 'high' } }
54
+ },
55
+ }
56
+ }
57
+
58
+ function makeAgent(id, parentSession) {
59
+ return {
60
+ id,
61
+ status: 'idle',
62
+ options: { provider: 'fake', model: 'fake-model' },
63
+ session: session(parentSession),
64
+ followups: [],
65
+ steers: [],
66
+ injections: [],
67
+ followup(message) {
68
+ this.followups.push(message)
69
+ },
70
+ steer(message) {
71
+ if (failNextDelivery.delete(this.id)) throw new Error('injected steering failure')
72
+ this.steers.push(message)
73
+ if (this.id !== captain.id) { deliveries.push({ childId: this.id, content: message.content, mode: 'steer' }); this.status = 'running' }
74
+ },
75
+ inject(message) {
76
+ this.injections.push(message)
77
+ },
78
+ cancel(cause, options) {
79
+ this.cancelCount = (this.cancelCount ?? 0) + 1
80
+ this.lastCancel = { cause, options }
81
+ },
82
+ whenIdle() {
83
+ return this.status === 'idle' ? Promise.resolve() : new Promise(resolve => { this._idle = resolve })
84
+ },
85
+ }
86
+ }
87
+
88
+ function publishStatus(subject, status) {
89
+ subject.status = status
90
+ if (status === 'idle') {
91
+ subject._idle?.()
92
+ subject._idle = undefined
93
+ }
94
+ for (const listener of listeners.get('agent/status') ?? []) listener({ agent: subject, status })
95
+ }
96
+
97
+ /**
98
+ * Compose one child's scoped context like the harness does, so the plugin's
99
+ * continuable setup can install its per-child listeners (model selection and
100
+ * the `agent/request-error` bridge) against a dispatchable registry.
101
+ */
102
+ function childContext(child) {
103
+ const registry = new Map()
104
+ childListeners.set(child.id, registry)
105
+ return {
106
+ agent: child,
107
+ effect(setup) { return setup() },
108
+ on(name, listener) {
109
+ const current = registry.get(name) ?? []
110
+ current.push(listener)
111
+ registry.set(name, current)
112
+ return () => registry.set(name, (registry.get(name) ?? []).filter(candidate => candidate !== listener))
113
+ },
114
+ }
115
+ }
116
+
117
+ /** Dispatch one failed model request to a child's request-error listeners. */
118
+ async function emitRequestError(child, failure) {
119
+ const handlers = childListeners.get(child.id)?.get('agent/request-error') ?? []
120
+ let action
121
+ for (const handler of handlers) {
122
+ action = await handler({
123
+ agent: child,
124
+ turn: 1,
125
+ step: 0,
126
+ provider: 'fake',
127
+ failure,
128
+ retryPolicy: undefined,
129
+ signal: new AbortController().signal,
130
+ }, async () => undefined)
131
+ }
132
+ return action
133
+ }
134
+
135
+ /** Final error followed by driver settlement, with no agent/status event. */
136
+ function emitTurnError(child, failure) {
137
+ for (const handler of childListeners.get(child.id)?.get('agent/error') ?? []) {
138
+ handler({ agent: child, turn: 1, step: 0, error: new LlmError(failure.message, failure.code) })
139
+ }
140
+ child.status = 'idle'
141
+ child._idle?.()
142
+ child._idle = undefined
143
+ }
144
+
145
+ const captain = makeAgent('captain-session')
146
+ liveAgents.set(captain.id, captain)
147
+ let advertisedModels = []
148
+ // A non-AgentTeams continuable sibling must survive every team lifecycle
149
+ // operation untouched.
150
+ children.push({ id: 'foreign-session', label: 'unrelated continuable', mode: 'continuable' })
151
+
152
+ const ctx = {
153
+ effect(setup) { return setup() },
154
+ tools: {
155
+ register(definition) {
156
+ definitions.set(definition.name, definition)
157
+ },
158
+ },
159
+ on(name, listener) {
160
+ const current = listeners.get(name) ?? []
161
+ current.push(listener)
162
+ listeners.set(name, current)
163
+ return () => listeners.set(name, current.filter(candidate => candidate !== listener))
164
+ },
165
+ agents: { list: () => [],
166
+ get(id) {
167
+ return liveAgents.get(id)
168
+ },
169
+ },
170
+ llm: {
171
+ async resolveCallConfig(config) {
172
+ return config
173
+ },
174
+ async listModels(provider) {
175
+ return advertisedModels.map(model => ({ provider, id: model, name: model }))
176
+ },
177
+ },
178
+ subagents: {
179
+ registerContinuableSetup(setup) {
180
+ continuableSetups.push(setup)
181
+ return () => {}
182
+ },
183
+ getProvider(name) {
184
+ if (name !== 'spawn') return undefined
185
+ return { prepareContinuable() {}, capabilities: { persona: true, toolFilter: true } }
186
+ },
187
+ list() {
188
+ return ['spawn']
189
+ },
190
+ async startContinuable(spec) {
191
+ const id = `member-session-${++childSeq}`
192
+ const child = makeAgent(id, captain.id)
193
+ child.status = 'running'
194
+ liveAgents.set(id, child)
195
+ children.push({ id, label: spec.label, mode: 'continuable' })
196
+ if (typeof spec.label === 'string' && spec.label.startsWith('agent-teams:')) {
197
+ child.session[modernHarness ? '_ownEvents' : 'events'] = [{
198
+ type: 'subagent/descriptor',
199
+ data: {
200
+ version: 3,
201
+ mode: 'continuable',
202
+ provider: 'spawn',
203
+ label: spec.label,
204
+ agentProvider: spec.request?.agentOptions?.provider ?? 'fake',
205
+ agentModel: spec.request?.agentOptions?.model ?? 'fake-model',
206
+ },
207
+ }]
208
+ }
209
+ child.ctx = childContext(child)
210
+ if (deliveryHarness) delete child.ctx.agent
211
+ if (modernHarness) {
212
+ for (const listener of listeners.get(activationHarness ? 'agent/created' : 'agent/session-start') ?? []) listener({ agent: child, source: 'startup' })
213
+ } else {
214
+ for (const setup of continuableSetups) setup(child.ctx)
215
+ }
216
+ deliveries.push({ childId: id, content: spec.request.prompt, mode: 'initial' })
217
+ return { childId: id, messageId: `initial-${childSeq}` }
218
+ },
219
+ async listChildren(parentId) {
220
+ if (parentId !== captain.id) return []
221
+ return children.map(child => ({
222
+ kind: 'child', mode: child.mode, id: child.id, label: child.label,
223
+ // Residency, intentionally not the Agent's real status.
224
+ activity: liveAgents.has(child.id) ? 'running' : 'inactive',
225
+ hasChildren: false,
226
+ }))
227
+ },
228
+ async listDescendants(parentId) {
229
+ return this.listChildren(parentId)
230
+ },
231
+ async followup(_parent, childId, content) {
232
+ if (this !== ctx.subagents) throw new Error('native receiver was lost')
233
+ if (failNextDelivery.delete(childId)) throw new Error('injected delivery failure')
234
+ if (deliveryDelayMs > 0) await new Promise(resolve => setTimeout(resolve, deliveryDelayMs))
235
+ deliveries.push({ childId, content })
236
+ const child = liveAgents.get(childId) ?? disposedAgents.get(childId)
237
+ if (child) liveAgents.set(childId, child)
238
+ if (child) child.status = 'running'
239
+ return `message-${++messageSeq}`
240
+ },
241
+ interrupt(childId) {
242
+ const child = liveAgents.get(childId)
243
+ if (child) {
244
+ child.interruptCount = (child.interruptCount ?? 0) + 1
245
+ publishStatus(child, 'idle')
246
+ }
247
+ },
248
+ async drainContinuableChildren(parent, childIds) {
249
+ for (const childId of childIds) {
250
+ if (failNextDrain.delete(childId)) throw new Error('injected drain failure')
251
+ const child = liveAgents.get(childId)
252
+ if (child) {
253
+ child.drainCount = (child.drainCount ?? 0) + 1
254
+ publishStatus(child, 'idle')
255
+ disposedAgents.set(childId, child)
256
+ liveAgents.delete(childId)
257
+ }
258
+ }
259
+ void parent
260
+ },
261
+ },
262
+ logger: { debug() {}, warn() {} },
263
+ }
264
+
265
+ // Model modern host delivery as a distinct FIFO entry. Deliberately reject
266
+ // public sendMessage: using steer for team jobs must make this suite fail.
267
+ if (modernHarness) {
268
+ const followup = ctx.subagents.followup
269
+ delete ctx.subagents.followup
270
+ delete ctx.subagents.registerContinuableSetup
271
+ ctx.subagents[hostQueue] = function (parent, childId, content, source, signal, delivery) {
272
+ if (deliveryHarness && !['queue', 'steer'].includes(delivery)) throw new Error('invalid delivery mode')
273
+ return followup.call(this, parent, childId, content, { source, signal })
274
+ }
275
+ ctx.subagents.sendMessage = (parent, id, content) => followup.call(ctx.subagents, parent, id, content)
276
+ }
277
+
278
+ if (activationHarness) {
279
+ const drain = ctx.subagents.drainContinuableChildren
280
+ delete ctx.subagents.drainContinuableChildren
281
+ ctx.subagents.drainChildren = function (parent, childIds) {
282
+ if (this !== ctx.subagents) throw new Error('native drain receiver was lost')
283
+ return drain.call(this, parent, childIds)
284
+ }
285
+ const start = ctx.subagents.startContinuable
286
+ delete ctx.subagents.startContinuable
287
+ ctx.subagents.startActivation = function (spec) {
288
+ if (this !== ctx.subagents) throw new Error('native creation receiver was lost')
289
+ if (spec.delivery !== 'parent') throw new Error('team members require parent-owned delivery')
290
+ return start.call(this, spec)
291
+ }
292
+ }
293
+
294
+ function directPrompt(parent, childId, content, options) {
295
+ return modernHarness
296
+ ? ctx.subagents[hostQueue](parent, childId, content, options.source, options.signal, ...(deliveryHarness ? ['queue'] : []))
297
+ : ctx.subagents.followup(parent, childId, content, options)
298
+ }
299
+
300
+ const agentTeamsRuntime = registerAgentTeamsTools(ctx, {
301
+ stateDir: '.agent-teams',
302
+ memberProvider: 'spawn',
303
+ fallback: { provider: 'backup', model: 'backup-model' },
304
+ memberMaxDepth: 1,
305
+ maxMembers: 8,
306
+ profiles: {
307
+ 'demo-delivery': {
308
+ description: 'tiny delivery team',
309
+ protocol: 'Discuss, then implement. Do not invent unanswered questions.',
310
+ members: [
311
+ { name: 'analyst', role: 'requirements', model: 'fake-analyst' },
312
+ { name: 'implementer', role: 'builder', model: 'fake-implementer' },
313
+ ],
314
+ tasks: [
315
+ { id: 'requirements', subject: 'Requirements', assignee: 'analyst', description: 'Write the first cut.' },
316
+ { id: 'implement', subject: 'Implement', assignee: 'implementer', dependencies: ['requirements'], description: 'Build from the approved requirements.' },
317
+ ],
318
+ },
319
+ 'dynamic-delivery': {
320
+ description: 'roster only',
321
+ protocol: 'Plan from the goal. Do not invent unanswered questions.',
322
+ taskPlanning: 'captain',
323
+ members: [
324
+ { name: 'analyst', role: 'requirements analyst', model: 'fake-analyst' },
325
+ { name: 'implementer', role: 'implementer', model: 'fake-implementer' },
326
+ { name: 'tester', role: 'test engineer', model: 'fake-tester' },
327
+ { name: 'reviewer', role: 'code reviewer', model: 'fake-reviewer' },
328
+ { name: 'release', role: 'release engineer', model: 'fake-release' },
329
+ ],
330
+ tasks: [],
331
+ },
332
+ },
333
+ })
334
+
335
+ function execFor(subject) {
336
+ return { agent: subject, signal: new AbortController().signal }
337
+ }
338
+
339
+ async function call(name, args, subject = captain) {
340
+ const definition = definitions.get(name)
341
+ if (!definition) throw new Error(`missing tool ${name}`)
342
+ return definition.execute(args, execFor(subject))
343
+ }
344
+
345
+ const teamId = 'lifecycle'
346
+ const stateRoot = join(workspace, '.agent-teams')
347
+ const state = () => readTeam(stateRoot, teamId)
348
+ const task = async id => (await state())?.tasks.find(candidate => candidate.id === id)
349
+
350
+ console.log('dsh-agent-teams lifecycle verification')
351
+
352
+ // ── /agent-teams slash command and gesture boundary ───────────────────
353
+ const commandDefinitions = new Map()
354
+ ctx.commands = {
355
+ register(definition) {
356
+ commandDefinitions.set(definition.name, definition)
357
+ },
358
+ }
359
+ const liveProfiles = {
360
+ 'demo-delivery': {
361
+ description: 'tiny delivery team',
362
+ protocol: 'Discuss, then implement. Do not invent unanswered questions.',
363
+ members: [
364
+ { name: 'analyst', role: 'requirements', model: 'fake-analyst' },
365
+ { name: 'implementer', role: 'builder', model: 'fake-implementer' },
366
+ ],
367
+ tasks: [
368
+ { id: 'requirements', subject: 'Requirements', assignee: 'analyst' },
369
+ { id: 'implement', subject: 'Implement', assignee: 'implementer', dependencies: ['requirements'] },
370
+ ],
371
+ },
372
+ }
373
+ registerAgentTeamsCommand(ctx, () => liveProfiles)
374
+ installAgentTeamsGestureBoundary(ctx, () => liveProfiles)
375
+
376
+ const command = commandDefinitions.get('agent-teams')
377
+ const profileCommand = commandDefinitions.get('agent-teams-demo-delivery')
378
+ check('slash command registers as /agent-teams',
379
+ command !== undefined && typeof command.description === 'string' && command.description.length > 0)
380
+ check('slash command advertises an input hint for the menu placeholder',
381
+ typeof command?.input?.hint === 'string' && command.input.hint.length > 0)
382
+ check('configured profile registers a concise dedicated slash command',
383
+ profileCommand !== undefined && profileCommandName('demo-delivery') === 'agent-teams-demo-delivery'
384
+ && typeof profileCommand.description === 'string' && profileCommand.description.includes('demo-delivery'))
385
+ check('unsafe profile names do not generate ambiguous commands',
386
+ profileCommandName('delivery team') === undefined && profileCommandName('delivery_team') === undefined)
387
+
388
+ const bare = command.handler({
389
+ agent: captain, rawInput: ' ', signal: new AbortController().signal, commandId: 'cmd-bare',
390
+ })
391
+ check('bare /agent-teams reports usage instead of activating',
392
+ bare.kind === 'error' && bare.text.includes('Usage: /agent-teams')
393
+ && captain.followups.length === 0)
394
+
395
+ const goal = 'ship a tiny CLI'
396
+ const activated = command.handler({
397
+ agent: captain, rawInput: ` ${goal} `, signal: new AbortController().signal, commandId: 'cmd-goal',
398
+ })
399
+ check('argued /agent-teams queues one visible user turn',
400
+ activated.kind === 'success' && captain.followups.length === 1)
401
+ const submittedCommand = captain.followups[0]
402
+ check('slash command preserves the exact submitted line as user-authored chat',
403
+ submittedCommand?.source?.kind === 'user'
404
+ && submittedCommand.content.some(block => block.type === 'text'
405
+ && block.text === `/agent-teams ${goal} `))
406
+ check('preserved slash command still activates through the gesture boundary',
407
+ invokedAgentTeamsGoal([submittedCommand]) === goal)
408
+ check('activation directive names the protocol', buildActivationDirective(goal).includes('AgentTeams protocol'))
409
+ const profileGoal = 'ship the prepared release'
410
+ const profileActivated = profileCommand.handler({
411
+ agent: captain, rawInput: ` ${profileGoal}`, signal: new AbortController().signal, commandId: 'cmd-profile-alias',
412
+ })
413
+ check('profile command queues a visible profile-specific user turn',
414
+ profileActivated.kind === 'success' && captain.followups.length === 2
415
+ && captain.followups[1]?.content.some(block => block.type === 'text' && block.text === `/agent-teams-demo-delivery ${profileGoal}`))
416
+
417
+ const userMessage = text => ({ id: 'm', role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } })
418
+ check('gesture recognizes a leading /agent-teams token',
419
+ invokedAgentTeamsGoal([userMessage('/agent-teams ship a CLI')]) === 'ship a CLI')
420
+ check('profile command gesture selects its configured profile and goal',
421
+ invokedAgentTeamsInvocation([userMessage('/agent-teams-demo-delivery ship a CLI')], () => liveProfiles)?.profile === 'demo-delivery'
422
+ && invokedAgentTeamsInvocation([userMessage('/agent-teams-demo-delivery ship a CLI')], () => liveProfiles)?.goal === 'ship a CLI')
423
+ check('bare profile command gesture asks for the goal',
424
+ invokedAgentTeamsInvocation([userMessage('/agent-teams-demo-delivery')], () => liveProfiles)?.profile === 'demo-delivery'
425
+ && invokedAgentTeamsInvocation([userMessage('/agent-teams-demo-delivery')], () => liveProfiles)?.goal === '')
426
+ check('unknown profile command stays ordinary prose',
427
+ invokedAgentTeamsInvocation([userMessage('/agent-teams-missing ship a CLI')], () => liveProfiles) === undefined)
428
+ check('bare gesture yields an empty goal', invokedAgentTeamsGoal([userMessage(' /agent-teams')]) === '')
429
+ check('mid-sentence mention stays ordinary prose',
430
+ invokedAgentTeamsGoal([userMessage('how do I use /agent-teams here?')]) === undefined)
431
+ check('non-user sources cannot forge the gesture',
432
+ invokedAgentTeamsGoal([{ ...userMessage('/agent-teams x'), source: { kind: 'plugin', plugin: 'fake' } }]) === undefined)
433
+ check('latest user gesture wins in a batch',
434
+ invokedAgentTeamsGoal([userMessage('/agent-teams first'), userMessage('/agent-teams second')]) === 'second')
435
+ const profileOnly = command.handler({
436
+ agent: captain, rawInput: '--profile demo-delivery', signal: new AbortController().signal, commandId: 'cmd-profile-only',
437
+ })
438
+ check('slash --profile without a goal still activates',
439
+ profileOnly.kind === 'success' && captain.followups.length === 3)
440
+ check('profile-only activation asks for the goal',
441
+ buildActivationDirective('', 'demo-delivery').includes('The goal was not given')
442
+ && buildActivationDirective('', 'demo-delivery').includes('Use profile="demo-delivery" when creating a new team')
443
+ && buildActivationDirective('', 'demo-delivery').includes('Inspect existing team state with agent_teams_status'))
444
+ check('captain-planning activation requires a staged user-reviewed graph',
445
+ buildActivationDirective('ship it', 'dynamic-delivery', 'captain').includes('approval="required"')
446
+ && buildActivationDirective('ship it', 'dynamic-delivery', 'captain').includes('review the Web plan')
447
+ && buildActivationDirective('ship it', 'dynamic-delivery', 'captain').includes('run in parallel')
448
+ && !buildActivationDirective('ship it', 'dynamic-delivery', 'captain').includes('seed tasks'))
449
+ const unknownProfile = command.handler({
450
+ agent: captain, rawInput: '--profile missing 做X', signal: new AbortController().signal, commandId: 'cmd-unknown',
451
+ })
452
+ check('unknown slash profile reports error and does not followup',
453
+ unknownProfile.kind === 'error' && captain.followups.length === 3)
454
+ check('leading ordinary token is never treated as a profile',
455
+ invokedAgentTeamsInvocation([userMessage('/agent-teams research this bug')])?.goal === 'research this bug'
456
+ && invokedAgentTeamsInvocation([userMessage('/agent-teams research this bug')])?.profile === undefined)
457
+ liveProfiles['hot-reload'] = { members: [{ name: 'solo', model: 'fake' }] }
458
+ check('command getter sees HMR profile names',
459
+ command.handler({
460
+ agent: captain, rawInput: '--profile hot-reload', signal: new AbortController().signal, commandId: 'cmd-hmr',
461
+ }).kind === 'success')
462
+ delete liveProfiles['hot-reload']
463
+
464
+ try {
465
+ const createdProfile = await call('agent_teams_create', {
466
+ name: 'Profile Demo',
467
+ description: 'ship a tiny demo',
468
+ profile: 'demo-delivery',
469
+ })
470
+ const profileTeam = await readTeam(stateRoot, 'profile-demo')
471
+ check('create(profile) returns profile members tasks and seed ids',
472
+ createdProfile.profile === 'demo-delivery'
473
+ && createdProfile.members?.length === 2
474
+ && createdProfile.tasks?.length === 2
475
+ && createdProfile.tasks?.[0]?.seed_id === 'requirements'
476
+ && createdProfile.tasks?.[1]?.seed_id === 'implement')
477
+ check('create(profile) persists snapshot members and mapped dependencies',
478
+ profileTeam?.profile?.name === 'demo-delivery'
479
+ && profileTeam.members.map(member => member.name).join(',') === 'analyst,implementer'
480
+ && profileTeam.tasks[1]?.dependencies.join(',') === 't1'
481
+ && profileTeam.tasks[1]?.assignee === 'implementer')
482
+ const analyst = liveAgents.get(createdProfile.members[0].member_id)
483
+ let implementer
484
+ check('dependency-blocked roster does not spawn a model session', createdProfile.members[1].member_id === '')
485
+ await call('agent_teams_status', {})
486
+ const afterKick = await readTeam(stateRoot, 'profile-demo')
487
+ const firstSeed = afterKick?.tasks[0]
488
+ check('first-stage seed is assigned only to the configured member',
489
+ firstSeed?.status === 'claimed' && firstSeed.assignee === 'analyst'
490
+ && deliveries.some(delivery => delivery.childId === analyst.id)
491
+ && !deliveries.some(delivery => delivery.childId === implementer?.id && String(delivery.content?.[0]?.text ?? '').includes('Implement')))
492
+ const firstAssignment = deliveries.find(delivery => delivery.childId === analyst.id)
493
+ const assignmentText = Array.isArray(firstAssignment?.content)
494
+ ? firstAssignment.content.map(block => block.text ?? '').join('\n')
495
+ : String(firstAssignment?.content ?? '')
496
+ check('first assignment includes team goal and protocol',
497
+ assignmentText.includes('ship a tiny demo')
498
+ && assignmentText.includes('Discuss, then implement'))
499
+ const analystClaim = await call('agent_teams_claim_task', { task_id: firstSeed.id }, analyst)
500
+ await call('agent_teams_update_task', { task_id: firstSeed.id, status: 'in_progress', attempt_id: analystClaim.attempt_id }, analyst)
501
+ await call('agent_teams_update_task', {
502
+ task_id: firstSeed.id,
503
+ status: 'failed',
504
+ attempt_id: analystClaim.attempt_id,
505
+ output: 'Need a user decision before design.',
506
+ }, analyst)
507
+ publishStatus(analyst, 'idle')
508
+ if (implementer) publishStatus(implementer, 'idle')
509
+ check('failed upstream does not unlock the next configured stage',
510
+ (await readTeam(stateRoot, 'profile-demo'))?.tasks[1]?.status === 'pending'
511
+ && !deliveries.some(delivery => delivery.childId === implementer?.id && String(delivery.content?.[0]?.text ?? '').includes('Implement')))
512
+ await call('agent_teams_reassign_task', { task_id: firstSeed.id, assignee: 'analyst', reason: 'retry after user answer' })
513
+ const retryClaim = await call('agent_teams_claim_task', { task_id: firstSeed.id }, analyst)
514
+ await call('agent_teams_update_task', { task_id: firstSeed.id, status: 'in_progress', attempt_id: retryClaim.attempt_id }, analyst)
515
+ await call('agent_teams_update_task', {
516
+ task_id: firstSeed.id,
517
+ status: 'completed',
518
+ attempt_id: retryClaim.attempt_id,
519
+ output: 'Scope confirmed: ship the tiny demo.',
520
+ }, analyst)
521
+ publishStatus(analyst, 'idle')
522
+ if (implementer) publishStatus(implementer, 'idle')
523
+ await call('agent_teams_status', {})
524
+ implementer = liveAgents.get((await readTeam(stateRoot, 'profile-demo')).members.find(m => m.name === 'implementer').id)
525
+ const secondSeed = (await readTeam(stateRoot, 'profile-demo'))?.tasks[1]
526
+ check('completed upstream dispatches the configured downstream assignee',
527
+ secondSeed?.status === 'claimed' && secondSeed.assignee === 'implementer')
528
+ const secondAssignment = [...deliveries].reverse().find(delivery => delivery.childId === implementer.id)
529
+ const secondText = Array.isArray(secondAssignment?.content)
530
+ ? secondAssignment.content.map(block => block.text ?? '').join('\n')
531
+ : String(secondAssignment?.content ?? '')
532
+ check('downstream assignment includes dependency output and seed id',
533
+ secondText.includes('Scope confirmed')
534
+ && secondText.includes('[requirements]'))
535
+ await call('agent_teams_send_message', { to: 'implementer', content: 'stop and wait for a user answer' })
536
+ const deliveriesAfterMail = deliveries.length
537
+ await call('agent_teams_status', {})
538
+ check('unread mailbox prevents a same-kick new assignment',
539
+ deliveries.length >= deliveriesAfterMail
540
+ && (await readTeam(stateRoot, 'profile-demo'))?.tasks[1]?.assignee === 'implementer')
541
+ const profileStatus = await call('agent_teams_status', {})
542
+ check('status exposes profile snapshot and task seed ids',
543
+ profileStatus.profile?.name === 'demo-delivery'
544
+ && profileStatus.tasks.some(item => item.seed_id === 'requirements')
545
+ && profileStatus.tasks.some(item => item.seed_id === 'implement'))
546
+ await call('agent_teams_delete', {})
547
+
548
+ const deliveriesBeforeDiscard = deliveries.length
549
+ const captainCancelsBeforeDiscard = captain.cancelCount ?? 0
550
+ const captainInjectionsBeforeDiscard = captain.injections.length
551
+ await call('agent_teams_create', {
552
+ name: 'Rejected Demo',
553
+ description: 'plan the user will reject',
554
+ profile: 'dynamic-delivery',
555
+ approval: 'required',
556
+ })
557
+ await call('agent_teams_create_task', { subject: 'should never run', assignee: 'analyst' })
558
+ const discardedPlan = await agentTeamsRuntime.discardStagedTeam(captain, 'rejected-demo')
559
+ const discardedArchive = await readArchivedTeam(stateRoot, 'rejected-demo')
560
+ check('discarding a staged plan archives it without spawning or dispatching',
561
+ discardedPlan.teamId === 'rejected-demo'
562
+ && await readTeam(stateRoot, 'rejected-demo') === undefined
563
+ && discardedArchive?.phase === 'staged'
564
+ && discardedArchive.members.every(member => member.id === '')
565
+ && discardedArchive.tasks.every(task => task.status === 'pending')
566
+ && deliveries.length === deliveriesBeforeDiscard)
567
+ const discardControlText = captain.injections.at(-1)?.content?.map(block => block.text ?? '').join('\n') ?? ''
568
+ check('discard aborts the active Captain turn and parks an authoritative no-recreate context',
569
+ (captain.cancelCount ?? 0) === captainCancelsBeforeDiscard + 1
570
+ && captain.injections.length === captainInjectionsBeforeDiscard + 1
571
+ && /Do not call agent_teams_create/.test(discardControlText)
572
+ && /Wait for a later explicit user request/.test(discardControlText)
573
+ && captain.lastCancel?.options?.keepInbox === true)
574
+
575
+ const createdDynamic = await call('agent_teams_create', {
576
+ name: 'Dynamic Demo',
577
+ description: 'goal only',
578
+ profile: 'dynamic-delivery',
579
+ approval: 'required',
580
+ })
581
+ const stagedDynamic = await readTeam(stateRoot, 'dynamic-demo')
582
+ check('captain-planning create stages only the configured roster',
583
+ createdDynamic.profile === 'dynamic-delivery'
584
+ && createdDynamic.task_planning === 'captain'
585
+ && createdDynamic.phase === 'staged'
586
+ && createdDynamic.members?.length === 5
587
+ && createdDynamic.members.every(member => member.member_id === '')
588
+ && createdDynamic.tasks?.length === 0
589
+ && stagedDynamic?.profile?.taskPlanning === 'captain'
590
+ && stagedDynamic.phase === 'staged'
591
+ && stagedDynamic.members.every(member => member.id === '')
592
+ && stagedDynamic.tasks.length === 0)
593
+ const deliveriesBeforePlan = deliveries.length
594
+ const dynamicFirst = await call('agent_teams_create_task', { subject: 'analyze goal', assignee: 'analyst' })
595
+ const dynamicSecond = await call('agent_teams_create_task', {
596
+ subject: 'implement result',
597
+ assignee: 'implementer',
598
+ dependencies: [dynamicFirst.task_id],
599
+ })
600
+ await agentTeamsRuntime.updateStagedPlan(captain, 'dynamic-demo', {
601
+ action: 'update_member',
602
+ memberName: 'reviewer',
603
+ role: 'security reviewer',
604
+ provider: 'fake-provider',
605
+ model: 'fake-reviewer-updated',
606
+ reasoningEffort: 'high',
607
+ executionPrompt: 'Review security-sensitive changes only.',
608
+ })
609
+ await agentTeamsRuntime.updateStagedPlan(captain, 'dynamic-demo', {
610
+ action: 'update_task',
611
+ taskId: dynamicSecond.task_id,
612
+ subject: 'implement approved result',
613
+ description: 'Use the analyst output.',
614
+ assignee: 'implementer',
615
+ dependencies: [dynamicFirst.task_id],
616
+ })
617
+ const editedDynamic = await readTeam(stateRoot, 'dynamic-demo')
618
+ check('staged roster and DAG are editable without spawning or dispatching',
619
+ editedDynamic?.members.find(member => member.name === 'reviewer')?.model === 'fake-reviewer-updated'
620
+ && editedDynamic.members.find(member => member.name === 'reviewer')?.executionPrompt === 'Review security-sensitive changes only.'
621
+ && editedDynamic.tasks[1]?.subject === 'implement approved result'
622
+ && editedDynamic.tasks[1]?.dependencies.join(',') === dynamicFirst.task_id
623
+ && editedDynamic.tasks.every(item => item.status === 'pending')
624
+ && deliveries.length === deliveriesBeforePlan)
625
+ const obsoleteReview = await call('agent_teams_create_task', {
626
+ subject: 'obsolete review',
627
+ assignee: 'reviewer',
628
+ dependencies: [dynamicFirst.task_id],
629
+ })
630
+ await agentTeamsRuntime.updateStagedPlan(captain, 'dynamic-demo', {
631
+ action: 'update_task',
632
+ taskId: dynamicSecond.task_id,
633
+ subject: 'implement approved result',
634
+ description: 'Use the analyst output.',
635
+ assignee: 'implementer',
636
+ dependencies: [obsoleteReview.task_id],
637
+ })
638
+ let rejectedAtomicEdit = false
639
+ try {
640
+ await call('agent_teams_edit_plan', {
641
+ operations: [
642
+ { action: 'remove_task', task_id: obsoleteReview.task_id },
643
+ { action: 'update_task', task_id: dynamicSecond.task_id, dependencies: [dynamicFirst.task_id] },
644
+ { action: 'remove_member', member_name: 'reviewer' },
645
+ ],
646
+ })
647
+ } catch {
648
+ rejectedAtomicEdit = true
649
+ }
650
+ const unchangedAfterRejectedEdit = await readTeam(stateRoot, 'dynamic-demo')
651
+ check('invalid staged plan batches fail atomically without a partial write',
652
+ rejectedAtomicEdit
653
+ && unchangedAfterRejectedEdit?.tasks.some(item => item.id === obsoleteReview.task_id)
654
+ && unchangedAfterRejectedEdit.tasks.find(item => item.id === dynamicSecond.task_id)?.dependencies.join(',') === obsoleteReview.task_id
655
+ && unchangedAfterRejectedEdit.members.some(member => member.name === 'reviewer'))
656
+ const captainCancelsBeforeContinue = captain.cancelCount ?? 0
657
+ const captainFollowupsBeforeContinue = captain.followups.length
658
+ const continuedPlan = await agentTeamsRuntime.continueStagedPlanning(captain, 'dynamic-demo')
659
+ const waitingPlan = await readTeam(stateRoot, 'dynamic-demo')
660
+ const feedbackControlText = captain.followups.at(-1)?.content?.map(block => block.text ?? '').join('\n') ?? ''
661
+ check('return-to-chat cancels the planning turn and asks one question without recreating the team',
662
+ continuedPlan.alreadyWaiting === false
663
+ && waitingPlan?.planReviewState === 'awaiting_feedback'
664
+ && (captain.cancelCount ?? 0) === captainCancelsBeforeContinue + 1
665
+ && captain.followups.length === captainFollowupsBeforeContinue + 1
666
+ && /Ask the user one concise, concrete question/.test(feedbackControlText)
667
+ && /Do not create a replacement team/.test(feedbackControlText))
668
+ const repeatedContinue = await agentTeamsRuntime.continueStagedPlanning(captain, 'dynamic-demo')
669
+ check('return-to-chat is idempotent while feedback is already pending',
670
+ repeatedContinue.alreadyWaiting === true
671
+ && (captain.cancelCount ?? 0) === captainCancelsBeforeContinue + 1
672
+ && captain.followups.length === captainFollowupsBeforeContinue + 1)
673
+ const modelEditedPlan = await call('agent_teams_edit_plan', {
674
+ operations: [
675
+ { action: 'update_task', task_id: dynamicSecond.task_id, dependencies: [dynamicFirst.task_id] },
676
+ { action: 'remove_task', task_id: obsoleteReview.task_id },
677
+ { action: 'remove_member', member_name: 'reviewer' },
678
+ ],
679
+ })
680
+ const modelEditedDynamic = await readTeam(stateRoot, 'dynamic-demo')
681
+ check('captain can revise the staged DAG and roster through one model-facing atomic tool',
682
+ modelEditedPlan.status === 'staged'
683
+ && modelEditedPlan.tasks === 2
684
+ && modelEditedPlan.members === 4
685
+ && modelEditedDynamic?.tasks.every(item => item.id !== obsoleteReview.task_id)
686
+ && modelEditedDynamic.tasks.find(item => item.id === dynamicSecond.task_id)?.dependencies.join(',') === dynamicFirst.task_id
687
+ && modelEditedDynamic.members.every(member => member.name !== 'reviewer')
688
+ && modelEditedDynamic.members.every(member => member.id === '')
689
+ && modelEditedDynamic.tasks.every(item => item.status === 'pending')
690
+ && modelEditedDynamic.planReviewState === 'awaiting_review'
691
+ && deliveries.length === deliveriesBeforePlan)
692
+ const approvedDynamic = await call('agent_teams_approve', { confirmation: 'user clicked Approve & Run' })
693
+ const dynamicTeam = await readTeam(stateRoot, 'dynamic-demo')
694
+ const correctedRunning = await call('agent_teams_edit_plan', { operations: [{ action: 'update_task', task_id: dynamicSecond.task_id, description: 'Corrected pending task context', dependencies: [dynamicFirst.task_id] }] })
695
+ check('running never-started tasks can be corrected without replacing the DAG', correctedRunning.status === 'running' && (await readTeam(stateRoot, 'dynamic-demo')).tasks.find(t => t.id === dynamicSecond.task_id).description === 'Corrected pending task context')
696
+ let rejectedRunningBatch = false
697
+ try {
698
+ await call('agent_teams_edit_plan', { operations: [
699
+ { action: 'update_task', task_id: dynamicSecond.task_id, description: 'must not persist' },
700
+ { action: 'update_task', task_id: dynamicFirst.task_id, subject: 'must not overwrite active work' },
701
+ ] })
702
+ } catch { rejectedRunningBatch = true }
703
+ check('invalid running plan batches preserve the entire previous graph', rejectedRunningBatch && (await readTeam(stateRoot, 'dynamic-demo')).tasks.find(t => t.id === dynamicSecond.task_id).description === 'Corrected pending task context')
704
+ for (const operation of [{ action: 'update_task', task_id: dynamicFirst.task_id, subject: 'do not overwrite active work' }, { action: 'update_task', task_id: dynamicSecond.task_id, dependencies: [dynamicSecond.task_id] }, { action: 'remove_member', member_name: 'implementer' }]) {
705
+ let rejected = false; try { await call('agent_teams_edit_plan', { operations: [operation] }) } catch { rejected = true }
706
+ check('running edits reject active attempts, cycles and roster changes: ' + JSON.stringify(operation), rejected)
707
+ }
708
+ const abandoned = await call('agent_teams_create_task', { subject: 'Cancelled planning mistake', assignee: 'implementer', dependencies: [dynamicFirst.task_id] })
709
+ const cancelledPending = await call('agent_teams_update_task', { task_id: abandoned.task_id, status: 'cancelled', output: 'No execution began; captain corrected the plan.' })
710
+ check('captain can cancel dependency-blocked member work before its first attempt', cancelledPending.status === 'cancelled' && cancelledPending.attempt === 0)
711
+ check('approval starts only dependency-ready members',
712
+ approvedDynamic.status === 'running'
713
+ && dynamicTeam?.phase === 'running'
714
+ && typeof dynamicTeam.approvedAt === 'number'
715
+ && dynamicTeam.members.filter(member => member.id !== '').length === 1
716
+ && dynamicTeam.tasks[0]?.status === 'claimed'
717
+ && dynamicTeam.tasks[1]?.status === 'pending')
718
+ for (const member of dynamicTeam.members) if (member.id !== '') publishStatus(liveAgents.get(member.id), 'idle')
719
+ await call('agent_teams_status', {})
720
+ const dispatchedDynamic = await readTeam(stateRoot, 'dynamic-demo')
721
+ check('approved plan dispatches only after a spawned member becomes idle',
722
+ dispatchedDynamic?.tasks[0]?.status === 'claimed'
723
+ && dispatchedDynamic.tasks[1]?.status === 'pending')
724
+ const dynamicAnalyst = liveAgents.get(dynamicTeam.members.find(member => member.name === 'analyst')?.id)
725
+ const dynamicImplementer = liveAgents.get(dynamicTeam.members.find(member => member.name === 'implementer')?.id)
726
+ const drainedBeforeHalt = dynamicAnalyst.drainCount ?? 0
727
+ const captainCancelsBeforeHalt = captain.cancelCount ?? 0
728
+ const halt = await haltTeamWork({
729
+ ctx,
730
+ stateRoot,
731
+ teamId: 'dynamic-demo',
732
+ captain,
733
+ signal: new AbortController().signal,
734
+ })
735
+ const haltedTeam = await readTeam(stateRoot, 'dynamic-demo')
736
+ check('captain halt cancels the approved graph and keeps the team',
737
+ halt.alreadyHalted === false
738
+ && halt.cancelledTasks === 2
739
+ && haltedTeam?.halted === true
740
+ && haltedTeam.tasks.every(item => item.status === 'cancelled'))
741
+ check('team halt cancels the captain turn while preserving queued user input',
742
+ captain.cancelCount === captainCancelsBeforeHalt + 2
743
+ && captain.lastCancel?.cause?.kind === 'user'
744
+ && captain.lastCancel?.options?.keepInbox === true)
745
+ check('captain halt drains active members and leaves blocked members unspawned',
746
+ (dynamicAnalyst.drainCount ?? 0) > drainedBeforeHalt && dynamicImplementer === undefined
747
+ && !liveAgents.has(dynamicAnalyst.id))
748
+ const deliveriesAfterHalt = deliveries.length
749
+ await call('agent_teams_status', {})
750
+ check('halted team does not redispatch cancelled graph',
751
+ deliveries.length === deliveriesAfterHalt
752
+ && (await readTeam(stateRoot, 'dynamic-demo'))?.tasks.every(item => item.status === 'cancelled'))
753
+ let silentCreateUnhalted = false
754
+ try {
755
+ await call('agent_teams_create_task', { subject: 'must stay halted' })
756
+ silentCreateUnhalted = (await readTeam(stateRoot, 'dynamic-demo'))?.halted !== true
757
+ } catch {
758
+ silentCreateUnhalted = (await readTeam(stateRoot, 'dynamic-demo'))?.halted !== true
759
+ }
760
+ check('halted create_task does not silently resume',
761
+ silentCreateUnhalted === false && (await readTeam(stateRoot, 'dynamic-demo'))?.halted === true)
762
+ const resume = await call('agent_teams_resume', { reason: 'continue after user answer' })
763
+ check('explicit resume clears halt and keeps cancelled tasks cancelled',
764
+ resume.status === 'resumed'
765
+ && (await readTeam(stateRoot, 'dynamic-demo'))?.halted !== true
766
+ && (await readTeam(stateRoot, 'dynamic-demo'))?.tasks.every(item => item.status === 'cancelled'))
767
+ await call('agent_teams_delete', {})
768
+ const haltedArchive = await readArchivedTeam(stateRoot, 'dynamic-demo')
769
+ check('shutdown preserves cancelled task history in the archive',
770
+ haltedArchive?.tasks.length === 3
771
+ && haltedArchive.tasks.every(item => item.status === 'cancelled'))
772
+
773
+ await call('agent_teams_create', { name: 'Quality Loop', description: 'review loop' })
774
+ await call('agent_teams_add_member', { name: 'builder', role: 'implementer' })
775
+ await call('agent_teams_add_member', { name: 'critic', role: 'reviewer' })
776
+ const impl = await call('agent_teams_create_task', {
777
+ subject: 'implement parser',
778
+ assignee: 'builder',
779
+ kind: 'implementation',
780
+ objective: 'Ship the parser',
781
+ inScope: ['src/parser.ts'],
782
+ acceptance: ['parser accepts empty input'],
783
+ verify: ['pnpm test'],
784
+ })
785
+ let missingContractRejected = false
786
+ try {
787
+ await call('agent_teams_create_task', { subject: 'impl without contract', kind: 'implementation' })
788
+ } catch {
789
+ missingContractRejected = true
790
+ }
791
+ check('quality implementation without contract is rejected', missingContractRejected)
792
+ const qualityTeam = await readTeam(stateRoot, 'quality-loop')
793
+ const builder = [...liveAgents.values()].find(agent => qualityTeam?.members.some(member => member.id === agent.id && member.name === 'builder'))
794
+ let criticMember
795
+ const implClaim = await call('agent_teams_claim_task', { task_id: impl.task_id }, builder)
796
+ const claimedSnapshot = await assembleTeamSnapshot(ctx, stateRoot, workspace, await readTeam(stateRoot, 'quality-loop'))
797
+ const claimedCard = claimedSnapshot.tasks.find(item => item.id === impl.task_id)
798
+ check('#262 dispatched working member retains a distinct claimed card before in_progress',
799
+ builder.status === 'running' && implClaim.status === 'claimed'
800
+ && claimedCard.status === 'claimed' && claimedCard.state === 'claimed',
801
+ JSON.stringify({ member: builder.status, status: implClaim.status, visual: claimedCard.state }))
802
+ let directClaimedCompletion = ''
803
+ try {
804
+ await call('agent_teams_update_task', { task_id: impl.task_id, status: 'completed', attempt_id: implClaim.attempt_id }, builder)
805
+ } catch (error) { directClaimedCompletion = String(error.message) }
806
+ check('#262 claimed still cannot skip in_progress', directClaimedCompletion.includes('cannot move from "claimed" to "completed"'))
807
+ for (const attempt_id of [undefined, '']) {
808
+ let missingAttemptError = ''
809
+ try { await call('agent_teams_update_task', { task_id: impl.task_id, status: 'in_progress', ...(attempt_id === undefined ? {} : { attempt_id }) }, builder) }
810
+ catch (error) { missingAttemptError = String(error.message) }
811
+ check('missing attempt_id is a correctable parameter error, not a revoked attempt',
812
+ missingAttemptError.includes('missing attempt_id') && missingAttemptError.includes(implClaim.attempt_id)
813
+ && (await readTeam(stateRoot, 'quality-loop')).tasks.find(t => t.id === impl.task_id).attemptId === implClaim.attempt_id)
814
+ }
815
+ await call('agent_teams_update_task', { task_id: impl.task_id, status: 'in_progress', attempt_id: implClaim.attempt_id }, builder)
816
+ const runningSnapshot = await assembleTeamSnapshot(ctx, stateRoot, workspace, await readTeam(stateRoot, 'quality-loop'))
817
+ check('#262 explicit in_progress changes the same attempt to running',
818
+ runningSnapshot.tasks.find(item => item.id === impl.task_id).state === 'running'
819
+ && (await readTeam(stateRoot, 'quality-loop')).tasks.find(item => item.id === impl.task_id).attemptId === implClaim.attempt_id)
820
+ let illegalCompleteRejected = false
821
+ try {
822
+ await call('agent_teams_update_task', {
823
+ task_id: impl.task_id,
824
+ status: 'completed',
825
+ attempt_id: implClaim.attempt_id,
826
+ output: 'looks fine',
827
+ }, builder)
828
+ } catch {
829
+ illegalCompleteRejected = true
830
+ }
831
+ check('illegal completed without acceptance evidence is rejected', illegalCompleteRejected)
832
+ await call('agent_teams_update_task', {
833
+ task_id: impl.task_id,
834
+ status: 'completed',
835
+ attempt_id: implClaim.attempt_id,
836
+ output: 'parser shipped',
837
+ changedPaths: ['src/parser.ts'],
838
+ acceptanceResults: [{ criterion: 'parser accepts empty input', status: 'passed' }],
839
+ commandsRun: [{ command: 'pnpm test', status: 'passed' }],
840
+ }, builder)
841
+ const finishedBeforeEvidence = (await readTeam(stateRoot, 'quality-loop')).tasks.find(t => t.id === impl.task_id)
842
+ const supplement = { task_id: impl.task_id, attempt_id: implClaim.attempt_id, status: 'completed', commandsRun: [{ command: 'independent recheck', status: 'passed', exitCode: 0 }] }
843
+ await call('agent_teams_update_task', supplement, builder)
844
+ await call('agent_teams_update_task', supplement, builder)
845
+ const supplemented = (await readTeam(stateRoot, 'quality-loop')).tasks.find(t => t.id === impl.task_id)
846
+ check('issue159 terminal evidence is durable and duplicate submissions are idempotent', supplemented.supplementalEvidence?.length === 1 && supplemented.supplementalEvidence[0].commandsRun[0].command === 'independent recheck')
847
+ check('issue159 supplementary evidence preserves the original result and completion timestamp', supplemented.output === finishedBeforeEvidence.output && supplemented.updatedAt === finishedBeforeEvidence.updatedAt && supplemented.commandsRun[0].command === 'pnpm test')
848
+ const captainSupplement = await call('agent_teams_update_task', { task_id: impl.task_id, evidence_note: 'Captain accepted independent evidence' })
849
+ check('issue159 captain supplements terminal member work without takeover', captainSupplement.evidence_count === 2)
850
+ const visibleEvidence = await call('agent_teams_status', {})
851
+ check('issue159 supplemental evidence is visible in status', visibleEvidence.tasks.find(t => t.id === impl.task_id).supplemental_evidence?.includes('Captain accepted'))
852
+ let wrongEvidenceAttempt = false
853
+ try { await call('agent_teams_update_task', { ...supplement, attempt_id: 'revoked' }, builder) } catch { wrongEvidenceAttempt = true }
854
+ check('issue159 stale capabilities cannot append terminal evidence', wrongEvidenceAttempt)
855
+ const report1 = await call('agent_teams_send_message', { to: 'captain', content: 'Verified parser completion', source_task_id: impl.task_id, source_attempt_id: implClaim.attempt_id }, builder)
856
+ const report2 = await call('agent_teams_send_message', { to: 'captain', content: 'Verified parser completion', source_task_id: impl.task_id, source_attempt_id: implClaim.attempt_id }, builder)
857
+ check('issue159 identical report retries reuse one durable message', report1.message_id === report2.message_id && (await readMailbox(stateRoot, 'quality-loop', 'captain')).filter(m => m.content === 'Verified parser completion').length === 1)
858
+ const review = await call('agent_teams_create_task', {
859
+ subject: 'review parser',
860
+ assignee: 'critic',
861
+ kind: 'review',
862
+ objective: 'Review the parser',
863
+ acceptance: ['no blocker or high findings'],
864
+ reviewedTaskId: impl.task_id,
865
+ })
866
+ criticMember = liveAgents.get((await readTeam(stateRoot, 'quality-loop')).members.find(m => m.name === 'critic').id)
867
+ let foreignEvidence = false
868
+ try { await call('agent_teams_update_task', supplement, criticMember) } catch { foreignEvidence = true }
869
+ check('issue159 teammates cannot supplement another owners terminal work', foreignEvidence)
870
+ let staleReport = false
871
+ try { await call('agent_teams_send_message', { to:'captain',content:'old report',source_task_id:impl.task_id,source_attempt_id:'revoked' },builder) } catch { staleReport = true }
872
+ check('issue159 stale explicit reports are rejected before entering the mailbox', staleReport && !(await readMailbox(stateRoot, 'quality-loop', 'captain')).some(m => m.content === 'old report'))
873
+ const reviewClaim = await call('agent_teams_claim_task', { task_id: review.task_id }, criticMember)
874
+ await call('agent_teams_update_task', { task_id: review.task_id, status: 'in_progress', attempt_id: reviewClaim.attempt_id }, criticMember)
875
+ let needsRevisionCompleteRejected = false
876
+ try {
877
+ await call('agent_teams_update_task', {
878
+ task_id: review.task_id,
879
+ status: 'completed',
880
+ attempt_id: reviewClaim.attempt_id,
881
+ verdict: 'needs_revision',
882
+ findings: [{ id: 'C-001', severity: 'high', problem: 'null crash', requiredFix: 'guard empty input', file: 'src/parser.ts' }],
883
+ }, criticMember)
884
+ } catch {
885
+ needsRevisionCompleteRejected = true
886
+ }
887
+ check('review needs_revision cannot complete', needsRevisionCompleteRejected)
888
+ await call('agent_teams_update_task', {
889
+ task_id: review.task_id,
890
+ status: 'failed',
891
+ attempt_id: reviewClaim.attempt_id,
892
+ verdict: 'needs_revision',
893
+ findings: [{ id: 'C-001', severity: 'high', problem: 'null crash', requiredFix: 'guard empty input', file: 'src/parser.ts' }],
894
+ }, criticMember)
895
+ check('issue159 automatic repair creation notifies the captain', (await readMailbox(stateRoot, 'quality-loop', 'captain')).some(m => m.content.includes('Automatic quality follow-up') && m.content.includes('repair')))
896
+ const afterReview = await readTeam(stateRoot, 'quality-loop')
897
+ const repair = afterReview?.tasks.find(item => item.kind === 'repair')
898
+ const nextReview = afterReview?.tasks.find(item => item.kind === 'review' && item.id !== review.task_id)
899
+ check('needs_revision opens repair and next review',
900
+ repair !== undefined && nextReview !== undefined
901
+ && repair.dependencies.includes(impl.task_id)
902
+ && !repair.dependencies.includes(review.task_id)
903
+ && nextReview.assignee === 'critic'
904
+ && nextReview.assignee !== 'builder')
905
+ await call('agent_teams_delete', {})
906
+
907
+ await call('agent_teams_create', { name: 'Lifecycle', description: 'adversarial DAG' })
908
+ const addedAlpha = await call('agent_teams_add_member', { name: 'alpha', role: 'slow implementer' })
909
+ const addedBeta = await call('agent_teams_add_member', { name: 'beta', role: 'researcher' })
910
+ const addedGamma = await call('agent_teams_add_member', { name: 'gamma', role: 'reviewer' })
911
+ check('adding members alone creates no child sessions', [addedAlpha, addedBeta, addedGamma].every(m => m.member_id === ''))
912
+ for (const name of ['alpha', 'beta', 'gamma']) await call('agent_teams_send_message', { to: name, content: 'Prepare for the concurrency regression and wait for assignment.' })
913
+ const roster = (await state()).members
914
+ const alpha = liveAgents.get(roster.find(m => m.name === 'alpha').id)
915
+ const beta = liveAgents.get(roster.find(m => m.name === 'beta').id)
916
+ const gamma = liveAgents.get(roster.find(m => m.name === 'gamma').id)
917
+ check('manually added members persist the global fallback for later activations',
918
+ (await state())?.members.every(member => member.fallback?.provider === 'backup'
919
+ && member.fallback?.model === 'backup-model'))
920
+ publishStatus(alpha, 'idle')
921
+ publishStatus(beta, 'idle')
922
+ publishStatus(gamma, 'idle')
923
+
924
+ const t1 = await call('agent_teams_create_task', { subject: 'slow branch', assignee: 'alpha' })
925
+ const firstAttempt = await task(t1.task_id)
926
+ check('idle assigned member is claimed and woken automatically',
927
+ firstAttempt?.status === 'claimed' && firstAttempt.assignee === 'alpha'
928
+ && deliveries.some(delivery => delivery.childId === alpha.id))
929
+ let captainClaimRejected = false
930
+ const beforeCaptainClaim = JSON.stringify(await task(t1.task_id))
931
+ const beforeCaptainClaimDeliveries = deliveries.length
932
+ try {
933
+ await call('agent_teams_claim_task', { task_id: t1.task_id, assignee: 'alpha' })
934
+ } catch (error) {
935
+ captainClaimRejected = /member|reassign_task/.test(String(error))
936
+ }
937
+ check('captain cannot mint a claim capability for a member; use reassign_task',
938
+ captainClaimRejected && JSON.stringify(await task(t1.task_id)) === beforeCaptainClaim
939
+ && deliveries.length === beforeCaptainClaimDeliveries)
940
+ const alphaClaim = await call('agent_teams_claim_task', { task_id: t1.task_id }, alpha)
941
+ check('member observes the scheduler attempt idempotently', alphaClaim.attempt_id === firstAttempt?.attemptId)
942
+ await call('agent_teams_update_task', {
943
+ task_id: t1.task_id, status: 'in_progress', attempt_id: alphaClaim.attempt_id,
944
+ }, alpha)
945
+
946
+ const t2 = await call('agent_teams_create_task', { subject: 'parallel research', assignee: 'beta' })
947
+ const t3 = await call('agent_teams_create_task', {
948
+ subject: 'integration gate', assignee: 'gamma', dependencies: [t1.task_id, t2.task_id],
949
+ })
950
+ const betaClaim = await call('agent_teams_claim_task', { task_id: t2.task_id }, beta)
951
+ await call('agent_teams_update_task', {
952
+ task_id: t2.task_id, status: 'in_progress', attempt_id: betaClaim.attempt_id,
953
+ }, beta)
954
+ check('dependency gate stays pending before both branches complete', (await task(t3.task_id))?.status === 'pending')
955
+
956
+ // A normal turn may end while its task is intentionally parked waiting for
957
+ // guidance, and a user can explicitly pause a running member. Neither case
958
+ // authorizes the scheduler to revoke the live attempt. Repeated status kicks
959
+ // must be idempotent until the captain performs an explicit reassignment.
960
+ publishStatus(alpha, 'idle')
961
+ await new Promise(resolve => setTimeout(resolve, 20))
962
+ // The idle member remains resident, so repeated status kicks must keep
963
+ // its current attempt parked rather than spuriously waking it again.
964
+ const deliveriesBeforeParkedKicks = deliveries.length
965
+ const parkedAttemptBeforeRateLimitRecovery = await task(t1.task_id)
966
+ // Model the provider-facing failure boundary from #66: the member's turn
967
+ // has ended after a rate-limit response, but its durable task capability is
968
+ // still open. Repeated scheduler/status kicks must park that capability
969
+ // instead of minting a fresh attempt and inference request each time.
970
+ for (let kick = 0; kick < 20; kick += 1) {
971
+ await call('agent_teams_status', {})
972
+ }
973
+ await new Promise(resolve => setTimeout(resolve, 20))
974
+ const parkedAlpha = await task(t1.task_id)
975
+ check('rate-limited idle owner does not enter an unbounded retry loop (#66)',
976
+ parkedAlpha?.status === 'in_progress'
977
+ && parkedAlpha.attempt === parkedAttemptBeforeRateLimitRecovery?.attempt
978
+ && parkedAlpha.attemptId === parkedAttemptBeforeRateLimitRecovery?.attemptId
979
+ && deliveries.length === deliveriesBeforeParkedKicks)
980
+ liveAgents.set(alpha.id, alpha)
981
+
982
+ // Harness normally disposes a continuable AgentHandle after settlement. The
983
+ // in-process idle observation remains authoritative, so a non-resident
984
+ // parked owner must not be mistaken for a cold restart on every status poll.
985
+ liveAgents.delete(alpha.id)
986
+ const deliveriesBeforeDisposedParkedKicks = deliveries.length
987
+ await Promise.all([
988
+ call('agent_teams_status', {}),
989
+ call('agent_teams_status', {}),
990
+ call('agent_teams_status', {}),
991
+ ])
992
+ await new Promise(resolve => setTimeout(resolve, 20))
993
+ const disposedParkedAlpha = await task(t1.task_id)
994
+ check('disposed settled owner keeps its parked attempt across repeated scheduler kicks',
995
+ disposedParkedAlpha?.status === 'in_progress'
996
+ && disposedParkedAlpha.attempt === alphaClaim.attempt
997
+ && disposedParkedAlpha.attemptId === alphaClaim.attempt_id
998
+ && deliveries.length === deliveriesBeforeDisposedParkedKicks)
999
+ liveAgents.set(alpha.id, alpha)
1000
+
1001
+ // Unobserved recovery whose followup fails must restore the original open
1002
+ // capability and consume that generation's budget. Later status kicks must
1003
+ // not recast it into pending or a new attempt.
1004
+ const tRecoverFail = await call('agent_teams_create_task', {
1005
+ subject: 'unobserved recovery delivery failure', assignee: 'gamma',
1006
+ })
1007
+ const recoverFailDispatch = await task(tRecoverFail.task_id)
1008
+ check('idle assigned gamma is claimed for the recovery-failure fixture',
1009
+ recoverFailDispatch?.status === 'claimed' && recoverFailDispatch.assignee === 'gamma')
1010
+ const recoverFailClaim = await call('agent_teams_claim_task', { task_id: tRecoverFail.task_id }, gamma)
1011
+ await call('agent_teams_update_task', {
1012
+ task_id: tRecoverFail.task_id, status: 'in_progress', attempt_id: recoverFailClaim.attempt_id,
1013
+ output: 'partial progress', commandsRun: [{ command: 'partial-check', status: 'passed' }],
1014
+ }, gamma)
1015
+ liveAgents.delete(gamma.id)
1016
+ failNextDelivery.add(gamma.id)
1017
+ const deliveriesBeforeFailedRecovery = deliveries.length
1018
+ await call('agent_teams_status', {})
1019
+ await new Promise(resolve => setTimeout(resolve, 20))
1020
+ const rolledBackRecovery = await task(tRecoverFail.task_id)
1021
+ await Promise.all([
1022
+ call('agent_teams_status', {}),
1023
+ call('agent_teams_status', {}),
1024
+ call('agent_teams_status', {}),
1025
+ ])
1026
+ await new Promise(resolve => setTimeout(resolve, 20))
1027
+ check('issue159 failed recovery restores partial evidence with the original capability', rolledBackRecovery?.output === 'partial progress' && rolledBackRecovery.commandsRun?.[0]?.command === 'partial-check')
1028
+ const throttledFailedRecovery = await task(tRecoverFail.task_id)
1029
+ check('failed unobserved recovery restores the original capability and later kicks do not recast it',
1030
+ rolledBackRecovery?.status === 'in_progress'
1031
+ && rolledBackRecovery.assignee === 'gamma'
1032
+ && rolledBackRecovery.attempt === recoverFailClaim.attempt
1033
+ && rolledBackRecovery.attemptId === recoverFailClaim.attempt_id
1034
+ && deliveries.length === deliveriesBeforeFailedRecovery
1035
+ && throttledFailedRecovery?.status === 'in_progress'
1036
+ && throttledFailedRecovery.attempt === recoverFailClaim.attempt
1037
+ && throttledFailedRecovery.attemptId === recoverFailClaim.attempt_id
1038
+ && deliveries.length === deliveriesBeforeFailedRecovery)
1039
+ liveAgents.set(gamma.id, gamma)
1040
+ const recoverFailComplete = await call('agent_teams_claim_task', { task_id: tRecoverFail.task_id }, gamma)
1041
+ await call('agent_teams_update_task', {
1042
+ task_id: tRecoverFail.task_id,
1043
+ status: 'completed',
1044
+ output: 'closed failed-recovery fixture',
1045
+ attempt_id: recoverFailComplete.attempt_id,
1046
+ }, gamma)
1047
+ check('restored capability remains usable after a failed recovery delivery',
1048
+ recoverFailComplete.attempt_id === recoverFailClaim.attempt_id
1049
+ && (await task(tRecoverFail.task_id))?.status === 'completed')
1050
+ publishStatus(gamma, 'idle')
1051
+
1052
+ // A durable task with no process-local idle observation is a cold/unobserved
1053
+ // owner. It gets exactly one fresh capability, then the recovery marker is
1054
+ // sticky even if the new AgentHandle is still absent on later status kicks.
1055
+ liveAgents.delete(beta.id)
1056
+ const deliveriesBeforeColdRecovery = deliveries.length
1057
+ await call('agent_teams_status', {})
1058
+ await new Promise(resolve => setTimeout(resolve, 20))
1059
+ const coldRecoveredBeta = await task(t2.task_id)
1060
+ const deliveriesAfterColdRecovery = deliveries.length
1061
+ await Promise.all([
1062
+ call('agent_teams_status', {}),
1063
+ call('agent_teams_status', {}),
1064
+ call('agent_teams_status', {}),
1065
+ ])
1066
+ await new Promise(resolve => setTimeout(resolve, 20))
1067
+ const throttledRecoveredBeta = await task(t2.task_id)
1068
+ check('unobserved missing owner recovers once and repeated kicks do not rotate it again',
1069
+ coldRecoveredBeta?.status === 'claimed'
1070
+ && coldRecoveredBeta.assignee === 'beta'
1071
+ && coldRecoveredBeta.attempt === betaClaim.attempt + 1
1072
+ && coldRecoveredBeta.attemptId !== betaClaim.attempt_id
1073
+ && deliveriesAfterColdRecovery === deliveriesBeforeColdRecovery + 1
1074
+ && throttledRecoveredBeta?.attempt === coldRecoveredBeta.attempt
1075
+ && throttledRecoveredBeta?.attemptId === coldRecoveredBeta.attemptId
1076
+ && deliveries.length === deliveriesAfterColdRecovery)
1077
+ liveAgents.set(beta.id, beta)
1078
+
1079
+ publishStatus(beta, 'idle')
1080
+ await new Promise(resolve => setTimeout(resolve, 20))
1081
+ const deliveriesBeforeResume = deliveries.length
1082
+ const resumedBeta = await call('agent_teams_send_message', {
1083
+ to: 'beta', content: 'Continue the same parked task and keep its current attempt id.',
1084
+ })
1085
+ const resumedBetaTask = await task(t2.task_id)
1086
+ check('captain message resumes a parked owner without rotating its attempt',
1087
+ resumedBeta.delivered === 'wake'
1088
+ && deliveries.length === deliveriesBeforeResume + 1
1089
+ && resumedBetaTask?.attempt === coldRecoveredBeta?.attempt
1090
+ && resumedBetaTask.attemptId === coldRecoveredBeta?.attemptId)
1091
+
1092
+ let unsafeCaptainTakeoverRejected = false
1093
+ try {
1094
+ await call('agent_teams_update_task', {
1095
+ task_id: t1.task_id, status: 'completed', output: 'captain bypassed handoff',
1096
+ })
1097
+ } catch (error) {
1098
+ unsafeCaptainTakeoverRejected = /reassign_task/.test(String(error))
1099
+ }
1100
+ check('captain cannot bypass the safe takeover protocol', unsafeCaptainTakeoverRejected)
1101
+
1102
+ const takeover = await call('agent_teams_reassign_task', {
1103
+ task_id: t1.task_id, assignee: 'gamma', reason: 'alpha is stuck',
1104
+ })
1105
+ const reassigned = await task(t1.task_id)
1106
+ check('reassignment quiesces recovered owner and creates a new attempt',
1107
+ takeover.assignee === 'gamma' && reassigned?.status === 'claimed'
1108
+ && reassigned.attemptId !== disposedParkedAlpha?.attemptId
1109
+ && takeover.attempt === (disposedParkedAlpha?.attempt ?? 0) + 1)
1110
+ let staleRejected = false
1111
+ try {
1112
+ await call('agent_teams_update_task', {
1113
+ task_id: t1.task_id, status: 'completed', output: 'late alpha', attempt_id: alphaClaim.attempt_id,
1114
+ }, alpha)
1115
+ } catch (error) {
1116
+ staleRejected = /assigned to|stale attempt/.test(String(error))
1117
+ }
1118
+ check('old member cannot publish a late takeover result', staleRejected)
1119
+
1120
+ const gammaClaim = await call('agent_teams_claim_task', { task_id: t1.task_id }, gamma)
1121
+ await call('agent_teams_update_task', {
1122
+ task_id: t1.task_id, status: 'in_progress', attempt_id: gammaClaim.attempt_id,
1123
+ }, gamma)
1124
+ await call('agent_teams_update_task', {
1125
+ task_id: t1.task_id, status: 'completed', output: 'gamma result', attempt_id: gammaClaim.attempt_id,
1126
+ }, gamma)
1127
+ const recoveredBetaClaim = await call('agent_teams_claim_task', { task_id: t2.task_id }, beta)
1128
+ await call('agent_teams_update_task', {
1129
+ task_id: t2.task_id, status: 'in_progress', attempt_id: recoveredBetaClaim.attempt_id,
1130
+ }, beta)
1131
+ await call('agent_teams_update_task', {
1132
+ task_id: t2.task_id, status: 'completed', output: 'beta result', attempt_id: recoveredBetaClaim.attempt_id,
1133
+ }, beta)
1134
+ check('resumed recovered member completes with its throttled capability',
1135
+ (await task(t2.task_id))?.status === 'completed'
1136
+ && (await task(t2.task_id))?.attemptId === recoveredBetaClaim.attempt_id)
1137
+ const deliveriesBeforeGate = deliveries.length
1138
+ // A member can start its tool calls only after delivery. The scheduler's
1139
+ // async disk writes and wakeup are not guaranteed to finish within 20 ms.
1140
+ // Delay the fake host deliberately so this test exercises that boundary.
1141
+ deliveryDelayMs = 100
1142
+ publishStatus(beta, 'idle')
1143
+ publishStatus(gamma, 'idle')
1144
+ let gate
1145
+ let gateDelivered = false
1146
+ const gateDeadline = Date.now() + 2000
1147
+ while (Date.now() < gateDeadline) {
1148
+ gate = await task(t3.task_id)
1149
+ gateDelivered = gate?.status === 'claimed' && gate.assignee === 'gamma'
1150
+ && gamma.status === 'running'
1151
+ && deliveries.slice(deliveriesBeforeGate).some(delivery => delivery.childId === gamma.id
1152
+ && JSON.stringify(delivery.content).includes(`Task: ${t3.task_id} `))
1153
+ if (gateDelivered) break
1154
+ await new Promise(resolve => setTimeout(resolve, 20))
1155
+ }
1156
+ deliveryDelayMs = 0
1157
+ check('completing dependencies dispatches the downstream task before member execution', gateDelivered)
1158
+ if (!gateDelivered) throw new Error('Timed out waiting for the downstream task to reach gamma')
1159
+ const gateClaim = await call('agent_teams_claim_task', { task_id: t3.task_id }, gamma)
1160
+ await call('agent_teams_update_task', {
1161
+ task_id: t3.task_id, status: 'in_progress', attempt_id: gateClaim.attempt_id,
1162
+ }, gamma)
1163
+ await call('agent_teams_update_task', {
1164
+ task_id: t3.task_id, status: 'completed', output: 'integrated', attempt_id: gateClaim.attempt_id,
1165
+ }, gamma)
1166
+
1167
+ publishStatus(alpha, 'idle')
1168
+ publishStatus(beta, 'idle')
1169
+ gamma.status = 'running'
1170
+ const t4 = await call('agent_teams_create_task', { subject: 'later-round assigned work', assignee: 'alpha' })
1171
+ const reused = await task(t4.task_id)
1172
+ check('previously interrupted member is reused in a later round', reused?.assignee === 'alpha' && reused.status === 'claimed')
1173
+
1174
+ const t5 = await call('agent_teams_create_task', { subject: 'must wait behind alpha', assignee: 'alpha' })
1175
+ let busyRejected = false
1176
+ try {
1177
+ await call('agent_teams_claim_task', { task_id: t5.task_id }, alpha)
1178
+ } catch (error) {
1179
+ busyRejected = /busy with/.test(String(error))
1180
+ }
1181
+ check('a member cannot claim a second unfinished task', busyRejected)
1182
+ await call('agent_teams_reassign_task', {
1183
+ task_id: t5.task_id, assignee: 'captain', reason: 'close busy-check task',
1184
+ })
1185
+ await call('agent_teams_update_task', { task_id: t5.task_id, status: 'in_progress' })
1186
+ await call('agent_teams_update_task', { task_id: t5.task_id, status: 'completed', output: 'closed' })
1187
+
1188
+ await call('agent_teams_remove_member', { name: 'alpha' })
1189
+ const afterRemoval = await state()
1190
+ const recovered = afterRemoval?.tasks.find(candidate => candidate.id === t4.task_id)
1191
+ check('removing a member revokes and redispatches its unfinished task',
1192
+ afterRemoval?.members.find(member => member.name === 'alpha')?.status === 'removed'
1193
+ && recovered?.assignee !== 'alpha')
1194
+ check('removing a member preserves its catalog entry for transcript history',
1195
+ (await ctx.subagents.listChildren(captain.id)).some(child => child.id === alpha.id))
1196
+ let removedFollowupRejected = false
1197
+ const deliveriesBeforeRemovedFollowup = deliveries.length
1198
+ try {
1199
+ await directPrompt(captain, alpha.id, [{ type: 'text', text: 'must not resume' }], {
1200
+ source: { kind: 'plugin', plugin: 'verification' }, signal: new AbortController().signal,
1201
+ })
1202
+ } catch (error) {
1203
+ removedFollowupRejected = error?.code === 'NOT_RESUMABLE'
1204
+ }
1205
+ check('removing a member blocks direct followup before resume',
1206
+ removedFollowupRejected && deliveries.length === deliveriesBeforeRemovedFollowup)
1207
+ let removedRejected = false
1208
+ try {
1209
+ await call('agent_teams_update_task', {
1210
+ task_id: t4.task_id, status: 'completed', output: 'removed alpha', attempt_id: reused?.attemptId,
1211
+ }, alpha)
1212
+ } catch {
1213
+ removedRejected = true
1214
+ }
1215
+ check('removed member loses participant authorization', removedRejected)
1216
+
1217
+ // Finish all work recovered from alpha so beta/gamma are free for later races.
1218
+ for (const recoveredTaskId of [t4.task_id]) {
1219
+ const current = await task(recoveredTaskId)
1220
+ if (!current?.assignee || current.status !== 'claimed') continue
1221
+ const owner = current.assignee === 'beta' ? beta : gamma
1222
+ const claim = await call('agent_teams_claim_task', { task_id: recoveredTaskId }, owner)
1223
+ await call('agent_teams_update_task', { task_id: recoveredTaskId, status: 'in_progress', attempt_id: claim.attempt_id }, owner)
1224
+ await call('agent_teams_update_task', {
1225
+ task_id: recoveredTaskId, status: 'completed', output: 'recovered', attempt_id: claim.attempt_id,
1226
+ }, owner)
1227
+ }
1228
+
1229
+ await call('agent_teams_status', {}, gamma)
1230
+ gamma.status = 'idle'
1231
+ failNextDelivery.add(gamma.id)
1232
+ const fallback = await call('agent_teams_send_message', { to: 'gamma', content: 'durable fallback' })
1233
+ check('failed live message remains one unread durable fallback',
1234
+ fallback.delivered === 'mailbox' && (await readUnreadMailbox(stateRoot, teamId, 'gamma')).length === 1)
1235
+ await call('agent_teams_status', {})
1236
+ check('status kick accepts fallback without inventing consumption',
1237
+ (await readUnreadMailbox(stateRoot, teamId, 'gamma')).length === 1
1238
+ && (await readMailbox(stateRoot, teamId, 'gamma')).at(-1)?.deliveredAt !== undefined)
1239
+ await call('agent_teams_status', {}, gamma)
1240
+ check('recipient status acknowledges the complete fallback actually displayed',
1241
+ (await readUnreadMailbox(stateRoot, teamId, 'gamma')).length === 0)
1242
+
1243
+ beta.status = 'running'
1244
+ gamma.status = 'running'
1245
+ const t6 = await call('agent_teams_create_task', { subject: 'concurrent claim' })
1246
+ beta.status = 'idle'
1247
+ gamma.status = 'idle'
1248
+ const race = await Promise.allSettled([
1249
+ call('agent_teams_claim_task', { task_id: t6.task_id }, beta),
1250
+ call('agent_teams_claim_task', { task_id: t6.task_id }, gamma),
1251
+ ])
1252
+ check('concurrent claims serialize to exactly one owner',
1253
+ race.filter(result => result.status === 'fulfilled').length === 1
1254
+ && race.filter(result => result.status === 'rejected').length === 1)
1255
+ const won = race.find(result => result.status === 'fulfilled').value
1256
+ const winner = won.assignee === 'beta' ? beta : gamma
1257
+ // A successful member claim is made from a running model turn. Preserve
1258
+ // that Harness status edge before unrelated kicks can retry an idle claim.
1259
+ winner.status = 'running'
1260
+ await call('agent_teams_update_task', { task_id: t6.task_id, status: 'in_progress', attempt_id: won.attempt_id }, winner)
1261
+ await call('agent_teams_update_task', {
1262
+ task_id: t6.task_id, status: 'completed', output: 'winner', attempt_id: won.attempt_id,
1263
+ }, winner)
1264
+ let terminalRejected = false
1265
+ try {
1266
+ await call('agent_teams_update_task', {
1267
+ task_id: t6.task_id, status: 'completed', output: 'late overwrite', attempt_id: won.attempt_id,
1268
+ }, winner)
1269
+ } catch (error) {
1270
+ terminalRejected = /immutable/.test(String(error))
1271
+ }
1272
+ check('terminal output is immutable against late overwrite', terminalRejected)
1273
+
1274
+ beta.status = 'idle'
1275
+ const t7 = await call('agent_teams_create_task', { subject: 'captain takeover', assignee: 'beta' })
1276
+ const betaTakeoverClaim = await call('agent_teams_claim_task', { task_id: t7.task_id }, beta)
1277
+ await call('agent_teams_update_task', {
1278
+ task_id: t7.task_id, status: 'in_progress', attempt_id: betaTakeoverClaim.attempt_id,
1279
+ }, beta)
1280
+ const captainAttempt = await call('agent_teams_reassign_task', {
1281
+ task_id: t7.task_id, assignee: 'captain', reason: 'deadline takeover',
1282
+ })
1283
+ await call('agent_teams_update_task', { task_id: t7.task_id, status: 'in_progress' })
1284
+ await call('agent_teams_update_task', { task_id: t7.task_id, status: 'completed', output: 'captain result' })
1285
+ let lateTakeoverRejected = false
1286
+ try {
1287
+ await call('agent_teams_update_task', {
1288
+ task_id: t7.task_id, status: 'completed', output: 'late beta', attempt_id: betaTakeoverClaim.attempt_id,
1289
+ }, beta)
1290
+ } catch {
1291
+ lateTakeoverRejected = true
1292
+ }
1293
+ check('captain takeover owns a fresh attempt and rejects the old member',
1294
+ captainAttempt.assignee === 'captain' && captainAttempt.attempt_id !== betaTakeoverClaim.attempt_id
1295
+ && captainAttempt.status === 'in_progress'
1296
+ && captainAttempt.attempt === betaTakeoverClaim.attempt + 1
1297
+ && lateTakeoverRejected && (await task(t7.task_id))?.output === 'captain result')
1298
+
1299
+ // A captain is one execution lane, not an unlimited pseudo-member. Two
1300
+ // parallel takeovers previously produced the issue #77 state: both member
1301
+ // rows lost their tasks while two captain-owned attempts stayed parked.
1302
+ beta.status = 'idle'
1303
+ gamma.status = 'idle'
1304
+ const t8 = await call('agent_teams_create_task', { subject: 'parallel captain takeover A', assignee: 'beta' })
1305
+ const t9 = await call('agent_teams_create_task', { subject: 'parallel captain takeover B', assignee: 'gamma' })
1306
+ const betaParallelClaim = await call('agent_teams_claim_task', { task_id: t8.task_id }, beta)
1307
+ const gammaParallelClaim = await call('agent_teams_claim_task', { task_id: t9.task_id }, gamma)
1308
+ await call('agent_teams_update_task', {
1309
+ task_id: t8.task_id, status: 'in_progress', attempt_id: betaParallelClaim.attempt_id,
1310
+ }, beta)
1311
+ await call('agent_teams_update_task', {
1312
+ task_id: t9.task_id, status: 'in_progress', attempt_id: gammaParallelClaim.attempt_id,
1313
+ }, gamma)
1314
+ const captainTakeoverRace = await Promise.allSettled([
1315
+ call('agent_teams_reassign_task', {
1316
+ task_id: t8.task_id, assignee: 'captain', reason: 'parallel takeover guard A',
1317
+ }),
1318
+ call('agent_teams_reassign_task', {
1319
+ task_id: t9.task_id, assignee: 'captain', reason: 'parallel takeover guard B',
1320
+ }),
1321
+ ])
1322
+ const raceState = await state()
1323
+ check('parallel captain takeovers allow exactly one active captain task',
1324
+ captainTakeoverRace.filter(result => result.status === 'fulfilled').length === 1
1325
+ && captainTakeoverRace.filter(result => result.status === 'rejected'
1326
+ && /captain is busy with/.test(String(result.reason))).length === 1
1327
+ && raceState?.tasks.filter(candidate => candidate.assignee === 'captain'
1328
+ && (candidate.status === 'claimed' || candidate.status === 'in_progress')).length === 1)
1329
+
1330
+ // If the captain ends the turn without completing that one takeover, it
1331
+ // must return to the ordinary member scheduler instead of staying white and
1332
+ // ownerless forever in the activity panel.
1333
+ publishStatus(captain, 'idle')
1334
+ // The requeue lands only after team.json's atomic write, which on Windows
1335
+ // can stall on transient rename EPERM retries (issue #108), so poll for
1336
+ // settlement instead of guessing a fixed wait.
1337
+ let afterCaptainIdle = await state()
1338
+ for (let waited = 0; waited < 2000; waited += 20) {
1339
+ // A torn read during a degraded non-atomic overwrite must not kill the
1340
+ // run; treat it as "not settled yet" and keep polling.
1341
+ const settled = ((afterCaptainIdle?.tasks.filter(candidate => (
1342
+ candidate.id === t8.task_id || candidate.id === t9.task_id
1343
+ )) ?? []).every(candidate => candidate.assignee !== 'captain'
1344
+ && (candidate.status === 'claimed' || candidate.status === 'in_progress')))
1345
+ if (settled) break
1346
+ await new Promise(resolve => setTimeout(resolve, 20))
1347
+ afterCaptainIdle = await state().catch(() => undefined)
1348
+ }
1349
+ const recoveredParallel = afterCaptainIdle?.tasks.filter(candidate => (
1350
+ candidate.id === t8.task_id || candidate.id === t9.task_id
1351
+ )) ?? []
1352
+ check('unfinished captain takeover returns to a member when the captain becomes idle',
1353
+ recoveredParallel.length === 2
1354
+ && recoveredParallel.every(candidate => candidate.assignee !== 'captain')
1355
+ && recoveredParallel.every(candidate => candidate.status === 'claimed' || candidate.status === 'in_progress'))
1356
+ for (const recoveredTask of recoveredParallel) {
1357
+ const owner = recoveredTask.assignee === 'beta' ? beta : gamma
1358
+ owner.status = 'running'
1359
+ const claim = await call('agent_teams_claim_task', { task_id: recoveredTask.id }, owner)
1360
+ await call('agent_teams_update_task', {
1361
+ task_id: recoveredTask.id, status: 'in_progress', attempt_id: claim.attempt_id,
1362
+ }, owner)
1363
+ await call('agent_teams_update_task', {
1364
+ task_id: recoveredTask.id, status: 'completed', output: 'member recovered captain work', attempt_id: claim.attempt_id,
1365
+ }, owner)
1366
+ }
1367
+
1368
+ beta.status = 'running'
1369
+ gamma.status = 'idle'
1370
+ const snapshot = await call('agent_teams_status', {})
1371
+ check('activity refines residency through the live Agent registry',
1372
+ snapshot.members.find(member => member.name === 'beta')?.activity === 'running'
1373
+ && snapshot.members.find(member => member.name === 'gamma')?.activity === 'idle')
1374
+
1375
+ beta.status = 'idle'
1376
+ gamma.status = 'idle'
1377
+ // Exercise the storage-only ready path: deletion must deny cold resume
1378
+ // without materializing the member or spending a model turn.
1379
+ liveAgents.delete(gamma.id)
1380
+ await call('agent_teams_delete', {})
1381
+ const archived = await readArchivedTeam(stateRoot, teamId)
1382
+ check('team shutdown archives the complete durable record',
1383
+ await readTeam(stateRoot, teamId) === undefined
1384
+ && archived !== undefined)
1385
+ const archivedSnapshot = (await collectArchivedTeamsActivity(ctx, [{ workspace, stateRoot }]))
1386
+ .find(candidate => candidate.teamId === teamId)
1387
+ check('archived activity keeps every member after shutdown',
1388
+ archivedSnapshot?.members.length === 3
1389
+ && ['alpha', 'beta', 'gamma'].every(name => archivedSnapshot.members.some(member => member.name === name))
1390
+ && archivedSnapshot.members.every(member => member.activity === 'idle'))
1391
+ check('archived activity projects each member model onto assigned tasks',
1392
+ archivedSnapshot?.members.every(member => member.provider === 'fake' && member.model === 'fake-model')
1393
+ && archivedSnapshot.tasks
1394
+ .filter(task => ['alpha', 'beta', 'gamma'].includes(task.assignee))
1395
+ .every(task => task.model === 'fake/fake-model'))
1396
+ check('team shutdown keeps retired members catalog-visible for historical transcripts',
1397
+ (await ctx.subagents.listChildren(captain.id))
1398
+ .filter(child => child.kind === 'child'
1399
+ && child.mode === 'continuable'
1400
+ && child.label.startsWith('agent-teams:lifecycle:')).length === 3)
1401
+ let coldFollowupRejected = false
1402
+ const deliveriesBeforeColdFollowup = deliveries.length
1403
+ try {
1404
+ await directPrompt(captain, gamma.id, [{ type: 'text', text: 'must stay retired' }], {
1405
+ source: { kind: 'plugin', plugin: 'verification' }, signal: new AbortController().signal,
1406
+ })
1407
+ } catch (error) {
1408
+ coldFollowupRejected = error?.code === 'NOT_RESUMABLE'
1409
+ }
1410
+ check('team shutdown blocks storage-only member cold resume',
1411
+ coldFollowupRejected && deliveries.length === deliveriesBeforeColdFollowup)
1412
+ check('team shutdown leaves unrelated continuable subagents untouched',
1413
+ (await ctx.subagents.listChildren(captain.id))
1414
+ .some(child => child.id === 'foreign-session' && child.mode === 'continuable'))
1415
+ const foreignFollowup = await directPrompt(captain, 'foreign-session', [
1416
+ { type: 'text', text: 'unrelated work still routes' },
1417
+ ], {
1418
+ source: { kind: 'plugin', plugin: 'verification' }, signal: new AbortController().signal,
1419
+ })
1420
+ check('team shutdown leaves unrelated continuable followup untouched',
1421
+ typeof foreignFollowup === 'string'
1422
+ && deliveries.some(delivery => delivery.childId === 'foreign-session'))
1423
+
1424
+ await call('agent_teams_create', {
1425
+ name: 'Atomic Approval',
1426
+ description: 'invalid route must not partially start',
1427
+ approval: 'required',
1428
+ })
1429
+ await call('agent_teams_add_member', { name: 'valid', role: 'writer', provider: 'fake', model: 'fake-model' })
1430
+ await call('agent_teams_add_member', { name: 'invalid', role: 'reviewer', provider: 'fake', model: 'typo-model' })
1431
+ await call('agent_teams_create_task', { subject: 'must remain staged', assignee: 'valid' })
1432
+ const childrenBeforeRejectedApproval = children.length
1433
+ advertisedModels = ['fake-model']
1434
+ let invalidApprovalRejected = false
1435
+ try {
1436
+ await call('agent_teams_approve', { confirmation: 'user clicked Approve & Run' })
1437
+ } catch (error) {
1438
+ invalidApprovalRejected = /unknown member model.*typo-model/i.test(String(error?.message ?? error))
1439
+ }
1440
+ const rejectedApprovalTeam = await readTeam(stateRoot, 'atomic-approval')
1441
+ check('invalid roster approval rejects before any member session is created',
1442
+ invalidApprovalRejected
1443
+ && children.length === childrenBeforeRejectedApproval
1444
+ && rejectedApprovalTeam?.phase === 'staged'
1445
+ && rejectedApprovalTeam.members.every(member => member.id === '')
1446
+ && rejectedApprovalTeam.tasks.every(item => item.status === 'pending'))
1447
+ advertisedModels = []
1448
+ await call('agent_teams_delete', {})
1449
+
1450
+ await call('agent_teams_create', { name: 'Lifecycle', description: 'second generation' })
1451
+ await call('agent_teams_delete', {})
1452
+ const replacementArchive = await readArchivedTeam(stateRoot, teamId)
1453
+ check('same-name team can be recreated and archived again',
1454
+ await readTeam(stateRoot, teamId) === undefined
1455
+ && replacementArchive?.description === 'second generation')
1456
+
1457
+ // ── member turn failure bridging (issue #94) ─────────────────────────
1458
+ // A member turn dies mid-stream with a transport-class failure and the
1459
+ // harness emits no idle edge: the continuable handle survives and the
1460
+ // durable record keeps the member "working". The plugin must bridge the
1461
+ // failure at the final agent/error boundary. A request error may still be
1462
+ // retried by Harness, and must not close the task prematurely.
1463
+ await call('agent_teams_create', { name: 'Failure Bridge', description: 'turn failures must surface' })
1464
+ await call('agent_teams_add_member', { name: 'flake', role: 'streaming worker' })
1465
+ const flakeTask = await call('agent_teams_create_task', { subject: 'streaming work', assignee: 'flake' })
1466
+ const flakeTeam = await readTeam(stateRoot, 'failure-bridge')
1467
+ const flake = liveAgents.get(flakeTeam.members.find(member => member.name === 'flake').id)
1468
+ const flakeClaim = await call('agent_teams_claim_task', { task_id: flakeTask.task_id }, flake)
1469
+ await call('agent_teams_update_task', {
1470
+ task_id: flakeTask.task_id, status: 'in_progress', attempt_id: flakeClaim.attempt_id,
1471
+ }, flake)
1472
+
1473
+ // The captain asks the working member a question while its turn is wedged;
1474
+ // live delivery is unavailable, so the message stays a durable fallback
1475
+ // that only the scheduler mailbox flush can hand over.
1476
+ failNextDelivery.add(flake.id)
1477
+ await call('agent_teams_send_message', { to: 'flake', content: 'status update please' })
1478
+ const deliveriesBeforeFailure = deliveries.length
1479
+ const captainMailBeforeFailure = (await readMailbox(stateRoot, 'failure-bridge', 'captain')).length
1480
+ const captainSteersBeforeFailure = captain.steers.length
1481
+
1482
+ // The turn dies mid-stream with a transport-class failure and no idle edge.
1483
+ const failureAction = await emitRequestError(flake, {
1484
+ code: 'STREAM_CLOSED',
1485
+ message: 'SSE stream ended without [DONE]',
1486
+ })
1487
+ check('request failure alone leaves the attempt open for Harness recovery',
1488
+ failureAction === undefined
1489
+ && (await readTeam(stateRoot, 'failure-bridge')).tasks.find(task => task.id === flakeTask.task_id)?.status === 'in_progress'
1490
+ && captain.steers.length === captainSteersBeforeFailure)
1491
+ emitTurnError(flake, { code: 'STREAM_CLOSED', message: 'SSE stream ended without [DONE]' })
1492
+ // Degraded non-atomic overwrites can hand a reader torn JSON; retry the
1493
+ // durable reads instead of letting environmental I/O noise fail the checks.
1494
+ const readTeamStable = async (teamId) => {
1495
+ for (let attempt = 0; ; attempt += 1) {
1496
+ try { return await readTeam(stateRoot, teamId) } catch (error) { if (attempt >= 5) throw error }
1497
+ }
1498
+ }
1499
+ const readMailboxStable = async (teamId, agentKey) => {
1500
+ for (let attempt = 0; ; attempt += 1) {
1501
+ try { return await readMailbox(stateRoot, teamId, agentKey) } catch (error) { if (attempt >= 5) throw error }
1502
+ }
1503
+ }
1504
+ const bridgeState = () => readTeamStable('failure-bridge')
1505
+ const bridgeTask = async () => (await bridgeState())?.tasks.find(candidate => candidate.id === flakeTask.task_id)
1506
+ for (let waited = 0; waited < 2000; waited += 20) {
1507
+ if ((await bridgeTask())?.status === 'failed' && captain.steers.length > captainSteersBeforeFailure
1508
+ && deliveries.length === deliveriesBeforeFailure
1509
+ && (await readUnreadMailbox(stateRoot, 'failure-bridge', 'flake')).length === 0) break
1510
+ await new Promise(resolve => setTimeout(resolve, 20))
1511
+ }
1512
+ const stalledFlake = (await bridgeState())?.members.find(member => member.name === 'flake')
1513
+ const captainMail = await readMailboxStable('failure-bridge', 'captain')
1514
+ check('turn failure fails the open attempt, releases the member, and owns no retry',
1515
+ failureAction === undefined
1516
+ && (await bridgeTask())?.status === 'failed'
1517
+ && (await bridgeTask())?.output?.includes('STREAM_CLOSED') === true
1518
+ && stalledFlake?.status === 'idle')
1519
+ check('turn failure notifies the captain mailbox with the error code',
1520
+ captainMail.length === captainMailBeforeFailure + 1
1521
+ && captainMail.at(-1)?.from === 'flake'
1522
+ && captainMail.at(-1)?.to === 'captain'
1523
+ && captainMail.at(-1)?.content.includes('STREAM_CLOSED') === true
1524
+ && captainMail.at(-1)?.content.includes(flakeTask.task_id)
1525
+ && captainSteersBeforeFailure + 1 === captain.steers.length)
1526
+ check('settled member discards failed-attempt guidance without another model turn',
1527
+ deliveries.length === deliveriesBeforeFailure
1528
+ && (await readUnreadMailbox(stateRoot, 'failure-bridge', 'flake')).length === 0
1529
+ && (await bridgeTask())?.status === 'failed')
1530
+ await call('agent_teams_delete', {})
1531
+
1532
+ const batchPlan = { members: [{ name: 'worker' }, { name: 'verifier' }], tasks: [
1533
+ { id: 'verify', subject: 'Validate output', assignee: 'verifier', dependencies: ['work'] },
1534
+ { id: 'work', subject: 'Actual task', description: 'FULL_CONTRACT_BODY', assignee: 'worker' },
1535
+ ] }
1536
+ const beforeBadPlan = children.length
1537
+ let badPlanRejected = false
1538
+ try { await call('agent_teams_create', { name: 'Atomic Invalid', plan: { ...batchPlan, tasks: [{ id: 'x', subject: 'cycle', dependencies: ['x'] }] } }) } catch { badPlanRejected = true }
1539
+ check('invalid batch plan is rejected without any state or session side effect', badPlanRejected && children.length === beforeBadPlan && await readTeam(stateRoot, 'atomic-invalid') === undefined)
1540
+ const batch = await call('agent_teams_create', { name: 'Batch Plan', description: 'One call builds roster and DAG', plan: batchPlan, approval: 'required' })
1541
+ const stagedBatch = await readTeam(stateRoot, 'batch-plan')
1542
+ check('one atomic call creates the full roster and resolves forward dependency references', batch.members.length === 2 && batch.tasks.length === 2 && stagedBatch.members.every(m => m.id === '') && stagedBatch.tasks[1].dependencies[0] === stagedBatch.tasks[0].id)
1543
+ const deliveryBeforeWork = await call('agent_teams_status', {})
1544
+ check('ordinary pending work cannot be reported deliverable', !deliveryBeforeWork.deliverable && !deliveryBeforeWork.delivery.ok)
1545
+ await call('agent_teams_approve', { confirmation: 'Run the accepted batch' })
1546
+ const workingBatch = await readTeam(stateRoot, 'batch-plan')
1547
+ const batchWorker = liveAgents.get(workingBatch.members.find(m => m.name === 'worker').id)
1548
+ const batchTask = workingBatch.tasks[0]
1549
+ const details = await call('agent_teams_claim_task', { task_id: batchTask.id }, batchWorker)
1550
+ check('claim exposes the complete task contract without reading team files', details.task_details.includes('FULL_CONTRACT_BODY'))
1551
+ failNextDrain.add(batchWorker.id)
1552
+ let drainRejected = false
1553
+ try { await call('agent_teams_reassign_task', { task_id: batchTask.id, assignee: 'worker' }) } catch { drainRejected = true }
1554
+ const failedHandoff = await readTeam(stateRoot, 'batch-plan')
1555
+ check('failed teardown keeps reassignment fenced and does not launch a new generation', drainRejected && failedHandoff.tasks[0].reassigning && failedHandoff.members.find(m => m.name === 'worker').stopping)
1556
+ await call('agent_teams_reassign_task', { task_id: batchTask.id, assignee: 'worker' })
1557
+ const retriedHandoff = await readTeam(stateRoot, 'batch-plan')
1558
+ check('the same failed handoff can be retried safely', !retriedHandoff.tasks[0].reassigning && !retriedHandoff.members.find(m => m.name === 'worker').stopping && retriedHandoff.tasks[0].status === 'claimed')
1559
+ failNextDrain.add(batchWorker.id)
1560
+ let archiveRejected = false
1561
+ try { await call('agent_teams_delete', {}) } catch { archiveRejected = true }
1562
+ check('failed member drain never reports a successful archive', archiveRejected && await readTeam(stateRoot, 'batch-plan') !== undefined && await readArchivedTeam(stateRoot, 'batch-plan') === undefined)
1563
+ await call('agent_teams_delete', {})
1564
+ check('archive retries drain previously removed roster rows', await readTeam(stateRoot, 'batch-plan') === undefined && !liveAgents.has(batchWorker.id))
1565
+ } finally {
1566
+ await rm(workspace, { recursive: true, force: true })
1567
+ }
1568
+
1569
+ if (failures.length > 0) {
1570
+ console.error(`\n${failures.length} lifecycle check(s) FAILED: ${failures.join(', ')}`)
1571
+ process.exit(1)
1572
+ }
1573
+ console.log('\nall lifecycle checks passed')