@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,77 @@
1
+ /**
2
+ * Permanent identity-contract regression for #176.
3
+ *
4
+ * `teamLeadMatch` and `isTopLevelSession` are pure functions over plain values,
5
+ * so these cases feed them ordinary objects — no mocked Context, Agents
6
+ * registry, LLM or team state. They pin the *narrowing* direction that matters
7
+ * for authorization: who may inherit lead identity, and what must never inherit
8
+ * it. The real acceptance evidence for the fork flows is the recorded cold-fork
9
+ * matrix on the exact host, not this file.
10
+ */
11
+ import assert from 'node:assert/strict'
12
+ import test from 'node:test'
13
+ import { isTopLevelSession, teamLeadMatch } from '../lib/lineage.js'
14
+
15
+ /** Plain team record as `findTeamByCaptain`/`findTeamByParticipant` see it. */
16
+ const team = members => ({ captainSessionId: 'session-captain', members })
17
+ const identity = (sessionId, ancestry, inheritsLead) => ({ sessionId, ancestry, inheritsLead })
18
+
19
+ const activeMembers = [
20
+ { id: 'session-member', status: 'working' },
21
+ { id: 'session-retired', status: 'removed' },
22
+ ]
23
+
24
+ test('the recorded captain leads its own team', () => {
25
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-captain', [], true)), true)
26
+ // An identity that claims no ancestry still matches by exact id.
27
+ assert.equal(teamLeadMatch(team([]), identity('session-captain', [], false)), true)
28
+ })
29
+
30
+ test('a top-level fork descendant inherits lead identity, at any depth', () => {
31
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-fork', ['session-captain'], true)), true)
32
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-grandchild', ['session-fork', 'session-captain'], true)), true)
33
+ })
34
+
35
+ test('a member session never inherits lead identity from its captain parent', () => {
36
+ // Member sessions are subagent children: leadIdentityOf reports inheritsLead false.
37
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-member', ['session-captain'], false)), false)
38
+ // Defence in depth: even an identity that claims the fork capability is
39
+ // rejected while its session id is a listed member row.
40
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-member', ['session-captain'], true)), false)
41
+ })
42
+
43
+ test('a retired member never regains lead identity, and neither does its fork', () => {
44
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-retired', ['session-captain'], true)), false)
45
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-fork-of-retired', ['session-retired', 'session-captain'], true)), false)
46
+ // The same holds when the roster row carries no status at all.
47
+ assert.equal(teamLeadMatch(team([{ id: 'session-retired' }]), identity('session-retired', ['session-captain'], true)), false)
48
+ })
49
+
50
+ test('a member fork never inherits lead identity through its member ancestor', () => {
51
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-fork-of-member', ['session-member', 'session-captain'], true)), false)
52
+ })
53
+
54
+ test('an unrelated lineage neither leads nor inherits', () => {
55
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-other', [], true)), false)
56
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-other', ['session-unrelated'], true)), false)
57
+ // Ancestry that contains the captain id deeper than a member row stays refused.
58
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-other', ['session-retired', 'session-captain'], true)), false)
59
+ })
60
+
61
+ test('an identity that cannot inherit lead is never widened by ancestry', () => {
62
+ assert.equal(teamLeadMatch(team(activeMembers), identity('session-fork', ['session-captain'], false)), false)
63
+ })
64
+
65
+ test('a team without roster rows keeps the exact-id contract', () => {
66
+ assert.equal(teamLeadMatch(team(undefined), identity('session-captain', [], true)), true)
67
+ assert.equal(teamLeadMatch(team(undefined), identity('session-fork', ['session-captain'], true)), true)
68
+ assert.equal(teamLeadMatch(team(undefined), identity('session-other', [], true)), false)
69
+ })
70
+
71
+ test('only a top-level conversation may inherit lead identity', () => {
72
+ assert.equal(isTopLevelSession({ header: {} }), true)
73
+ assert.equal(isTopLevelSession({ header: { delegationDepth: 0 } }), true)
74
+ assert.equal(isTopLevelSession({ header: { origin: 'subagent' } }), false)
75
+ assert.equal(isTopLevelSession({ header: { delegationDepth: 1 } }), false)
76
+ assert.equal(isTopLevelSession({ header: { origin: 'subagent', delegationDepth: 0 } }), false)
77
+ })
@@ -0,0 +1,451 @@
1
+ /** Terminal member failures, composed with Harness's actual retry plugin. */
2
+ import assert from 'node:assert/strict'
3
+ import { test } from 'node:test'
4
+ import fsPromises, { mkdtemp, rm } from 'node:fs/promises'
5
+ import { syncBuiltinESMExports } from 'node:module'
6
+ import { tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import { setTimeout as delay } from 'node:timers/promises'
9
+ import { LlmError } from '@deepseek-ai/dsh-llm'
10
+ import { apply as installRetry } from '@deepseek-ai/dsh-llm-retry'
11
+ import { installMemberSelectionRuntime } from '../lib/members.js'
12
+ import { installTeamScheduler } from '../lib/scheduler.js'
13
+ import { readCurrentMailbox } from '../lib/mailbox.js'
14
+ import { appendMailbox, beginTaskAttempt, createMessage, createTeamDir, readTeam, readMailbox, readUnreadMailbox, withTeamLock, writeTeam } from '../lib/state.js'
15
+
16
+ const deliveryHarness = process.argv.includes('--delivery-harness')
17
+ const modernHarness = deliveryHarness || process.argv.includes('--modern-harness')
18
+ const hostQueue = Symbol.for(deliveryHarness ? 'dsh.subagent.deliverPrompt' : 'dsh.subagent.queuePrompt')
19
+
20
+ async function eventually(predicate) {
21
+ for (let i = 0; i < 100; i++) {
22
+ if (await predicate()) return
23
+ await delay(10)
24
+ }
25
+ assert.fail('terminal failure did not settle')
26
+ }
27
+
28
+ async function fixture(t, { captainStatus = 'idle', fallback, captainOffline = false, rejectDelivery = false, nativeRecovery = false, rejectContinuation = false } = {}) {
29
+ const workspace = await mkdtemp(join(tmpdir(), 'dsh-member-failure-'))
30
+ const pendingFailures = []
31
+ let settleOnCleanup = () => {}
32
+ t.after(async () => {
33
+ settleOnCleanup()
34
+ await Promise.all(pendingFailures)
35
+ await rm(workspace, { recursive: true, force: true })
36
+ })
37
+ const stateRoot = join(workspace, '.agent-teams')
38
+ const listeners = new Map()
39
+ const steers = []
40
+ const deliveries = []
41
+ const warnings = []
42
+ const sessionEvents = []
43
+ const captain = {
44
+ id: 'captain', status: captainStatus,
45
+ session: { append() {} },
46
+ steer(message) {
47
+ if (rejectDelivery) throw new Error('captain cannot receive')
48
+ steers.push(message)
49
+ },
50
+ }
51
+ let resolveIdle
52
+ const idle = new Promise(resolve => { resolveIdle = resolve })
53
+ const child = {
54
+ id: 'worker-session', status: 'running',
55
+ steer(message) { deliveries.push({ id: this.id, content: message.content }) },
56
+ whenIdle: () => child.status === 'idle' ? Promise.resolve() : idle,
57
+ session: {
58
+ header: { cwd: workspace, parentSession: captain.id, seedLength: 0 },
59
+ events: [{ type: 'subagent/descriptor', data: {
60
+ version: 3, mode: 'continuable', provider: 'spawn', label: 'agent-teams:team:worker',
61
+ agentProvider: 'fake', agentModel: 'primary',
62
+ } }],
63
+ append(type, data) { sessionEvents.push({ type, data }) },
64
+ },
65
+ }
66
+ const recovery = []
67
+ if (nativeRecovery) {
68
+ child.model = { select(selection) { recovery.push({ selection }) } }
69
+ child.cancel = (cause, options) => recovery.push({ cause, options })
70
+ child.followup = message => {
71
+ if (rejectContinuation) throw new Error('continuation refused')
72
+ recovery.push({ continuation: message })
73
+ }
74
+ }
75
+ await createTeamDir(stateRoot, {
76
+ id: 'team', name: 'Team', captainSessionId: captain.id, createdAt: 1, taskSeq: 1,
77
+ members: [{ id: child.id, name: 'worker', status: 'working', joinedAt: 1, provider: 'fake', model: 'primary' }],
78
+ tasks: [{ id: 't1', subject: 'work', assignee: 'worker', status: 'in_progress', dependencies: [], attempt: 1, attemptId: 'a1', createdAt: 1, updatedAt: 1 }],
79
+ })
80
+ let setup
81
+ const rootListeners = new Map()
82
+ const disposers = []
83
+ const ctx = {
84
+ logger: { debug() {}, warn(message) { warnings.push(message) } },
85
+ agents: { list: () => [], get(id) { return id === child.id ? child : id === captain.id && !captainOffline ? captain : undefined } },
86
+ on(name, listener) { rootListeners.set(name, listener); return () => rootListeners.delete(name) },
87
+ effect(setup) { const dispose = setup(); disposers.push(dispose); return dispose },
88
+ subagents: {
89
+ registerContinuableSetup(fn) { setup = fn },
90
+ async followup(_captain, id, content) { deliveries.push({ id, content }); return 'accepted' },
91
+ },
92
+ }
93
+ if (modernHarness) {
94
+ const oldEvents = child.session.events
95
+ delete child.session.events
96
+ delete child.session.header.seedLength
97
+ child.session.ownEvents = () => oldEvents
98
+ const followup = ctx.subagents.followup
99
+ delete ctx.subagents.followup
100
+ delete ctx.subagents.registerContinuableSetup
101
+ ctx.subagents[hostQueue] = function (parent, id, content, source, signal, delivery) {
102
+ if (deliveryHarness) assert.ok(['queue', 'steer'].includes(delivery))
103
+ return followup.call(this, parent, id, content, { source, signal })
104
+ }
105
+ ctx.subagents.sendMessage = (parent, id, content) => followup.call(ctx.subagents, parent, id, content)
106
+ setup = childCtx => {
107
+ child.ctx = childCtx
108
+ if (deliveryHarness) delete childCtx.agent
109
+ rootListeners.get('agent/session-start')({ agent: child, source: 'startup' })
110
+ return () => { for (const dispose of disposers) dispose() }
111
+ }
112
+ }
113
+ const scheduler = installTeamScheduler(ctx, { stateDir: '.agent-teams' })
114
+ const runtime = installMemberSelectionRuntime(ctx, '.agent-teams', (workspace, teamId, memberName) => (
115
+ scheduler.kickMember(workspace, teamId, memberName)
116
+ ))
117
+ const dispose = await runtime.withPending(captain.id, 'agent-teams:team:worker', {
118
+ provider: 'fake', model: 'primary', ...fallback ? { fallback } : {},
119
+ }, () => setup({
120
+ agent: child,
121
+ effect(setup) { const dispose = setup(); disposers.push(dispose); return dispose },
122
+ on(name, listener) { listeners.set(name, listener); return () => listeners.delete(name) },
123
+ }))
124
+ t.after(dispose)
125
+ let retryHandler
126
+ let projection
127
+ let retryState = {}
128
+ const retryDisposers = []
129
+ installRetry({
130
+ logger: ctx.logger,
131
+ sessionProjections: { register(value) { projection = value }, stateOf() { return retryState } },
132
+ on(_name, listener) { retryHandler = listener; return () => {} },
133
+ effect(setup) { retryDisposers.push(setup()) },
134
+ })
135
+ t.after(async () => { for (const dispose of retryDisposers) await dispose() })
136
+ child.session.append = (type, data) => {
137
+ sessionEvents.push({ type, data })
138
+ retryState = projection.apply(retryState, { type, data })
139
+ }
140
+ const failure = { code: 'STREAM_CLOSED', message: 'SSE stream ended without [DONE]' }
141
+ const payload = (policy, code = failure.code, signal = new AbortController().signal) => ({
142
+ agent: child, turn: 1, step: 0, provider: 'fake', failure: { ...failure, code }, retryPolicy: policy, signal,
143
+ })
144
+ const memberError = (value, next = async () => undefined) => listeners.get('agent/request-error')?.(value, next) ?? next()
145
+ const settleSilently = () => {
146
+ // The real driver settles after emitting agent/error. Deliberately omit
147
+ // agent/status so recovery cannot depend on that edge reaching the plugin.
148
+ child.status = 'idle'
149
+ resolveIdle()
150
+ }
151
+ settleOnCleanup = settleSilently
152
+ return {
153
+ stateRoot, steers, deliveries, warnings, listeners, child, sessionEvents, memberError, payload, settleSilently, recovery, dispose,
154
+ turnEvent(type, data) {
155
+ pendingFailures.push(listeners.get('session/event')?.(child.session, { type, data }))
156
+ },
157
+ state: () => readTeam(stateRoot, 'team'),
158
+ mailbox: () => readMailbox(stateRoot, 'team', 'captain'),
159
+ unread: () => readUnreadMailbox(stateRoot, 'team', 'captain'),
160
+ retry: (policy, code) => { const value = payload(policy, code); return retryHandler(value, () => memberError(value)) },
161
+ terminal({ settle = true, turn = 1 } = {}) {
162
+ pendingFailures.push(listeners.get('agent/error')?.({ agent: child, turn, step: 0, error: new LlmError(failure.message, failure.code) }))
163
+ if (settle) settleSilently()
164
+ },
165
+ }
166
+ }
167
+
168
+ const normal = { mode: 'normal', maxRetries: 1, retryableCodes: ['STREAM_CLOSED'], initialDelayMs: 0, maxDelayMs: 0, jitterRatio: 0 }
169
+ const always = { mode: 'always', initialDelayMs: 0, maxDelayMs: 0, jitterRatio: 0 }
170
+
171
+ await test('always retry keeps the owned task open and sends no false failure report', async t => {
172
+ const h = await fixture(t)
173
+ assert.deepEqual(await h.retry(always), { kind: 'retry' })
174
+ assert.equal((await h.state()).tasks[0].status, 'in_progress')
175
+ assert.equal((await h.mailbox()).length, 0)
176
+ })
177
+
178
+ await test('request handler delegates recovery and leaves exhausted requests open until final error', async t => {
179
+ const h = await fixture(t)
180
+ let delegated = 0
181
+ assert.deepEqual(await h.memberError(h.payload(undefined), async () => { delegated++; return { kind: 'retry' } }), { kind: 'retry' })
182
+ assert.equal(delegated, 1)
183
+ assert.deepEqual(await h.retry(normal), { kind: 'retry' })
184
+ assert.equal(await h.retry(normal), undefined)
185
+ assert.equal((await h.state()).tasks[0].status, 'in_progress')
186
+ })
187
+
188
+ await test('fallback recovers once and exhausted fallback still delegates without failing the task', async t => {
189
+ const h = await fixture(t, { fallback: { provider: 'backup', model: 'backup-model' } })
190
+ assert.deepEqual(await h.memberError(h.payload(undefined, 'AUTH')), { kind: 'retry' })
191
+ assert.deepEqual(await h.memberError(h.payload(undefined, 'RATE_LIMIT'), async () => ({ kind: 'retry' })), { kind: 'retry' })
192
+ assert.equal((await h.state()).tasks[0].status, 'in_progress')
193
+ })
194
+
195
+ await test('aborted request does not fail a task or consume its fallback route', async t => {
196
+ const h = await fixture(t, { fallback: { provider: 'backup', model: 'backup-model' } })
197
+ const abort = new AbortController()
198
+ abort.abort()
199
+ assert.equal(await h.memberError(h.payload(undefined, 'AUTH', abort.signal)), undefined)
200
+ assert.deepEqual(await h.memberError(h.payload(undefined, 'AUTH')), { kind: 'retry' })
201
+ assert.equal((await h.state()).tasks[0].status, 'in_progress')
202
+ })
203
+
204
+ await test('native fallback continues once with default effort and reports a later terminal failure', async t => {
205
+ const fallback = { provider: 'backup', model: 'backup-model' }
206
+ const h = await fixture(t, { fallback, nativeRecovery: true })
207
+ const abort = new AbortController()
208
+ abort.abort()
209
+ assert.equal(await h.memberError(h.payload(undefined, 'AUTH', abort.signal)), undefined)
210
+ assert.deepEqual(h.recovery, [{ selection: { provider: 'fake', model: 'primary' } }])
211
+ assert.equal((await h.state()).members[0].fallbackActive, undefined)
212
+ assert.equal(await h.memberError(h.payload(undefined, 'AUTH')), undefined)
213
+ assert.deepEqual(h.recovery[1], { selection: fallback })
214
+ assert.deepEqual(h.recovery[2], {
215
+ cause: { kind: 'hook', reason: 'agent-teams/model-fallback' }, options: { keepInbox: true },
216
+ })
217
+ assert.match(h.recovery[3].continuation.content[0].text, /Continue the current work/)
218
+ assert.equal((await h.state()).tasks[0].status, 'in_progress')
219
+ assert.equal((await h.mailbox()).length, 0)
220
+ const delegated = { kind: 'retry' }
221
+ assert.equal(await h.memberError(h.payload(undefined, 'RATE_LIMIT'), async () => delegated), delegated)
222
+ assert.equal(h.recovery.length, 4)
223
+ h.terminal({ turn: 2 })
224
+ await eventually(async () => (await h.state()).tasks[0].status === 'failed' && (await h.mailbox()).length === 1)
225
+ assert.equal((await h.state()).tasks[0].attemptId, 'a1')
226
+ })
227
+
228
+ await test('disposed setup cannot resume fallback after the team lock is released', async t => {
229
+ const h = await fixture(t, { fallback: { provider: 'backup', model: 'backup-model' }, nativeRecovery: true })
230
+ const entered = Promise.withResolvers()
231
+ const release = Promise.withResolvers()
232
+ const lock = withTeamLock(`team:${h.stateRoot}:team`, async () => {
233
+ entered.resolve()
234
+ await release.promise
235
+ })
236
+ await entered.promise
237
+ const request = h.memberError(h.payload(undefined, 'AUTH'))
238
+ h.dispose()
239
+ release.resolve()
240
+ await lock
241
+ await request
242
+ assert.deepEqual(h.recovery, [{ selection: { provider: 'fake', model: 'primary' } }])
243
+ assert.equal((await h.state()).members[0].fallbackActive, undefined)
244
+ })
245
+
246
+ for (const cancel of ['turn', 'setup']) {
247
+ await test(`canceling the ${cancel} during a staged fallback write preserves the saved route`, { timeout: 5000 }, async t => {
248
+ const fallback = { provider: 'backup', model: 'backup-model' }
249
+ const h = await fixture(t, { fallback, nativeRecovery: true })
250
+ const prior = await h.state()
251
+ Object.assign(prior.members[0], { activeProvider: 'fake', activeModel: 'primary', fallbackActive: false })
252
+ await writeTeam(h.stateRoot, prior)
253
+ const abort = new AbortController()
254
+ const staged = Promise.withResolvers()
255
+ const release = Promise.withResolvers()
256
+ const target = join(h.stateRoot, 'team', 'team.json')
257
+ const writeFile = fsPromises.writeFile
258
+ fsPromises.writeFile = async (file, ...args) => {
259
+ await writeFile(file, ...args)
260
+ if (typeof file === 'string' && file.startsWith(target + '.') && file.endsWith('.tmp')) {
261
+ staged.resolve()
262
+ await release.promise
263
+ }
264
+ }
265
+ syncBuiltinESMExports()
266
+ try {
267
+ const request = h.memberError(h.payload(undefined, 'AUTH', abort.signal))
268
+ await staged.promise
269
+ if (cancel === 'turn') abort.abort()
270
+ else h.dispose()
271
+ release.resolve()
272
+ assert.equal(await request, undefined)
273
+ } finally {
274
+ release.resolve()
275
+ fsPromises.writeFile = writeFile
276
+ syncBuiltinESMExports()
277
+ }
278
+ assert.deepEqual(await h.state(), prior)
279
+ assert.deepEqual(h.recovery, [{ selection: { provider: 'fake', model: 'primary' } }])
280
+ if (cancel === 'turn') {
281
+ // An interrupted write must leave the one-shot recovery available.
282
+ assert.equal(await h.memberError(h.payload(undefined, 'AUTH')), undefined)
283
+ assert.deepEqual(h.recovery[1], { selection: fallback })
284
+ assert.equal((await h.state()).members[0].fallbackActive, true)
285
+ }
286
+ })
287
+ }
288
+
289
+ await test('native continuation rejection settles the open task after hook cancellation', async t => {
290
+ const h = await fixture(t, {
291
+ fallback: { provider: 'backup', model: 'backup-model' }, nativeRecovery: true, rejectContinuation: true,
292
+ })
293
+ await assert.rejects(h.memberError(h.payload(undefined, 'AUTH')), /continuation refused/)
294
+ h.settleSilently()
295
+ await eventually(async () => (await h.state()).tasks[0].status === 'failed' && (await h.mailbox()).length === 1)
296
+ assert.equal((await h.state()).tasks[0].attemptId, 'a1')
297
+ })
298
+
299
+ for (const captainStatus of ['idle', 'running']) {
300
+ await test(`final failure notifies ${captainStatus} captain once and flushes without an idle event`, async t => {
301
+ const h = await fixture(t, { captainStatus })
302
+ await appendMailbox(h.stateRoot, 'team', 'worker', createMessage('captain', 'worker', 'status please'))
303
+ h.terminal()
304
+ h.terminal()
305
+ await eventually(async () => (await h.state()).tasks[0].status === 'failed' && h.steers.length === 1 && h.deliveries.length === 1)
306
+ assert.equal((await h.state()).tasks[0].attemptId, 'a1')
307
+ assert.match((await h.state()).tasks[0].output, /STREAM_CLOSED/)
308
+ assert.equal((await h.state()).members[0].status, 'idle')
309
+ assert.match(JSON.stringify(h.steers[0]), /t1/)
310
+ assert.match(JSON.stringify(h.steers[0]), /STREAM_CLOSED/)
311
+ await eventually(async () => (await h.mailbox())[0]?.deliveredAt !== undefined)
312
+ assert.equal((await h.unread()).length, 1, 'delivery alone does not prove consumption')
313
+ assert.equal((await h.mailbox()).length, 1)
314
+ assert.equal((await readUnreadMailbox(h.stateRoot, 'team', 'worker')).length, 1)
315
+ assert.equal(h.warnings.length, 0)
316
+ })
317
+ }
318
+
319
+ await test('report a final error immediately but do not dispatch while the driver is still running', async t => {
320
+ const h = await fixture(t)
321
+ await appendMailbox(h.stateRoot, 'team', 'worker', createMessage('captain', 'worker', 'status please'))
322
+ h.terminal({ settle: false })
323
+ await eventually(async () => (await h.state()).tasks[0].status === 'failed' && h.steers.length === 1)
324
+ assert.equal(h.child.status, 'running')
325
+ assert.equal((await h.state()).members[0].status, 'working')
326
+ assert.equal(h.deliveries.length, 0)
327
+ h.settleSilently()
328
+ await eventually(() => h.deliveries.length === 1)
329
+ assert.equal((await h.state()).members[0].status, 'idle')
330
+ })
331
+
332
+ for (const options of [{ captainOffline: true }, { rejectDelivery: true }]) {
333
+ await test(`unavailable captain keeps failure notification readable: ${JSON.stringify(options)}`, async t => {
334
+ const h = await fixture(t, options)
335
+ h.terminal()
336
+ await eventually(async () => (await h.unread()).length === 1)
337
+ assert.equal((await h.state()).tasks[0].status, 'failed')
338
+ assert.equal(h.steers.length, 0)
339
+ })
340
+ }
341
+
342
+ await test('a queued error cannot fail a newer attempt created before it gets the team lock', async t => {
343
+ const h = await fixture(t)
344
+ let release
345
+ let locked
346
+ const ready = new Promise(resolve => { locked = resolve })
347
+ const lock = withTeamLock(`team:${h.stateRoot}:team`, async () => {
348
+ locked()
349
+ await new Promise(resolve => { release = resolve })
350
+ const team = await h.state()
351
+ team.tasks[0].attempt = 2
352
+ team.tasks[0].attemptId = 'a2'
353
+ await writeTeam(h.stateRoot, team)
354
+ })
355
+ await ready
356
+ h.terminal()
357
+ release()
358
+ await lock
359
+ await withTeamLock(`team:${h.stateRoot}:team`, async () => {})
360
+ assert.equal((await h.state()).tasks[0].status, 'in_progress')
361
+ assert.equal((await h.state()).tasks[0].attemptId, 'a2')
362
+ assert.equal((await h.mailbox()).length, 0)
363
+ })
364
+
365
+ function outputLimitedStep(h, legacy = false) {
366
+ h.turnEvent('step/start', { turn: 1, step: 1 })
367
+ const chunk = { type: 'finish', reason: { kind: 'max-tokens' } }
368
+ if (legacy) h.turnEvent('assistant/chunk', { turn: 1, step: 1, chunk })
369
+ else h.turnEvent('assistant/message', { turn: 1, step: 1, stream: [{ type: 'chunk', chunk }] })
370
+ }
371
+
372
+ for (const legacy of [false, true]) {
373
+ await test(`terminal output limit fails the exact open attempt and reports once (${legacy ? 'legacy chunk' : 'embedded stream'})`, async t => {
374
+ const h = await fixture(t)
375
+ outputLimitedStep(h, legacy)
376
+ assert.equal((await h.state()).tasks[0].status, 'in_progress')
377
+ assert.equal((await h.mailbox()).length, 0)
378
+ h.turnEvent('turn/end', { turn: 1, reason: { kind: 'max-tokens' } })
379
+ h.turnEvent('turn/end', { turn: 1, reason: { kind: 'max-tokens' } })
380
+ h.settleSilently()
381
+ await eventually(async () => h.steers.length === 1 && (await h.mailbox())[0]?.deliveredAt !== undefined)
382
+ const task = (await h.state()).tasks[0]
383
+ assert.equal(task.status, 'failed')
384
+ assert.equal(task.attemptId, 'a1')
385
+ assert.match(task.output, /output-token limit.*MAX_TOKENS/)
386
+ const reports = await h.mailbox()
387
+ assert.equal(reports.length, 1)
388
+ assert.match(reports[0].content, /Task t1 .* was marked failed/)
389
+ assert.equal(reports[0].sourceTaskId, 't1')
390
+ assert.equal(reports[0].sourceAttemptId, 'a1')
391
+ assert.equal(reports[0].sourceTaskStatus, 'failed')
392
+ })
393
+ }
394
+
395
+ await test('replacing a failed historical attempt discards its offline output-limit report', async t => {
396
+ const h = await fixture(t, { captainOffline: true })
397
+ const initial = await h.state()
398
+ delete initial.tasks[0].attemptId
399
+ await writeTeam(h.stateRoot, initial)
400
+ outputLimitedStep(h)
401
+ h.turnEvent('turn/end', { turn: 1, reason: { kind: 'max-tokens' } })
402
+ h.settleSilently()
403
+ await eventually(async () => (await h.mailbox()).length === 1)
404
+
405
+ const failed = await h.state()
406
+ const task = failed.tasks[0]
407
+ assert.equal(task.status, 'failed')
408
+ assert.equal(task.attempt, initial.tasks[0].attempt)
409
+ const failedAttemptId = task.attemptId
410
+ const [report] = await readCurrentMailbox(h.stateRoot, 'team', 'captain')
411
+ beginTaskAttempt(task, 'worker')
412
+ await writeTeam(h.stateRoot, failed)
413
+ assert.deepEqual(await readCurrentMailbox(h.stateRoot, 'team', 'captain'), [])
414
+ assert.match(failedAttemptId, /^[a-f0-9-]{36}$/)
415
+ assert.equal(report.sourceAttemptId, failedAttemptId)
416
+ })
417
+
418
+ for (const [label, reason, continues] of [
419
+ ['a later model step', 'max-tokens', true],
420
+ ['a cancelled turn', 'aborted', false],
421
+ ['an ordinary parked turn', 'completed', false],
422
+ ]) {
423
+ await test(`output-limit observation keeps the attempt open after ${label}`, async t => {
424
+ const h = await fixture(t)
425
+ if (reason !== 'completed') outputLimitedStep(h)
426
+ if (continues) h.turnEvent('step/start', { turn: 1, step: 2 })
427
+ h.turnEvent('turn/end', { turn: 1, reason: { kind: reason } })
428
+ h.settleSilently()
429
+ await withTeamLock(`team:${h.stateRoot}:team`, async () => {})
430
+ assert.equal((await h.state()).tasks[0].status, 'in_progress')
431
+ assert.equal((await h.mailbox()).length, 0)
432
+ })
433
+ }
434
+
435
+ for (const [label, update] of [
436
+ ['replacement', { attempt: 2, attemptId: 'a2' }],
437
+ ['completion', { status: 'completed', output: 'Recorded result' }],
438
+ ]) {
439
+ await test(`output limit cannot change or report an attempt after ${label}`, async t => {
440
+ const h = await fixture(t)
441
+ outputLimitedStep(h)
442
+ const team = await h.state()
443
+ Object.assign(team.tasks[0], update)
444
+ await writeTeam(h.stateRoot, team)
445
+ h.turnEvent('turn/end', { turn: 1, reason: { kind: 'max-tokens' } })
446
+ h.settleSilently()
447
+ await withTeamLock(`team:${h.stateRoot}:team`, async () => {})
448
+ assert.deepEqual((await h.state()).tasks[0], team.tasks[0])
449
+ assert.equal((await h.mailbox()).length, 0)
450
+ })
451
+ }
@@ -0,0 +1,92 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { startMemberWithLenientFilter } from '../lib/harness-compat.js'
4
+ import { CAPTAIN_TOOL_NAMES } from '../lib/tool-names.js'
5
+
6
+ /**
7
+ * `dsh-web-app` and the Agent Teams profile layer ship `tool-subagent` and
8
+ * `tool-subagent-control` disabled, so `subagent` and `send_message` are absent from the
9
+ * registry. The host applies a member's `toolFilter` through a strict `tools.restrict()`
10
+ * that rejects an unregistered name instead of ignoring it. That rejection used to abort
11
+ * every member start, leaving every member of every team `unspawned` with no visible reason.
12
+ *
13
+ * `memberToolFilter` resolves the depth entries against the host's registry view, which
14
+ * covers the compositions that expose one. This pins the recovery path underneath it for
15
+ * everything that resolution cannot see — no registry view, a name that is known but not
16
+ * restrictable, a mounting difference — and it reproduces the host message shape verbatim
17
+ * so the contract stays pinned to it:
18
+ * `tools.restrict() names unknown global tool "x"; known global tools: …`.
19
+ */
20
+ const hostRejection = names => new Error(
21
+ `tools.restrict() names unknown global tool${names.length > 1 ? 's' : ''} ${names.map(name => `"${name}"`).join(', ')}; known global tools: ${CAPTAIN_TOOL_NAMES.join(', ')}`,
22
+ )
23
+
24
+ test('a member start drops the names the host rejects and succeeds', async t => {
25
+ await t.test('the rejected names are removed and the start succeeds', async () => {
26
+ const attempts = []
27
+ const result = await startMemberWithLenientFilter(async filter => {
28
+ attempts.push([...filter.deny])
29
+ if (attempts.length === 1) throw hostRejection(['subagent', 'send_message'])
30
+ return { childId: 'child' }
31
+ }, { deny: [...CAPTAIN_TOOL_NAMES, 'subagent', 'send_message'] })
32
+ assert.deepEqual(result, { childId: 'child' })
33
+ assert.deepEqual(attempts[0], [...CAPTAIN_TOOL_NAMES, 'subagent', 'send_message'])
34
+ assert.deepEqual(attempts[1], [...CAPTAIN_TOOL_NAMES])
35
+ })
36
+
37
+ await t.test('only the names the host named are dropped, not the ones it listed as known', async () => {
38
+ const attempts = []
39
+ await startMemberWithLenientFilter(async filter => {
40
+ attempts.push([...filter.deny])
41
+ if (attempts.length === 1) throw hostRejection(['subagent'])
42
+ return 'ok'
43
+ }, { deny: [...CAPTAIN_TOOL_NAMES, 'subagent'] })
44
+ assert.deepEqual(attempts[1], [...CAPTAIN_TOOL_NAMES])
45
+ })
46
+
47
+ await t.test('each rejection removes one more name until the host accepts the filter', async () => {
48
+ const attempts = []
49
+ const result = await startMemberWithLenientFilter(async filter => {
50
+ attempts.push([...filter.deny])
51
+ if (filter.deny.includes('subagent')) throw hostRejection(['subagent'])
52
+ if (filter.deny.includes('send_message')) throw hostRejection(['send_message'])
53
+ return 'ok'
54
+ }, { deny: [...CAPTAIN_TOOL_NAMES, 'subagent', 'send_message'] })
55
+ assert.equal(result, 'ok')
56
+ assert.equal(attempts.length, 3)
57
+ assert.deepEqual(attempts.at(-1), [...CAPTAIN_TOOL_NAMES])
58
+ })
59
+
60
+ await t.test('a first attempt that already works is not retried', async () => {
61
+ let calls = 0
62
+ await startMemberWithLenientFilter(async () => { calls += 1; return 'ok' }, { deny: [...CAPTAIN_TOOL_NAMES] })
63
+ assert.equal(calls, 1)
64
+ })
65
+ })
66
+
67
+ test('a member start that failed for another reason still surfaces', async t => {
68
+ await t.test('an unrelated start failure propagates', async () => {
69
+ await assert.rejects(
70
+ startMemberWithLenientFilter(async () => { throw new Error('provider "spawn" is not registered') }, { deny: [...CAPTAIN_TOOL_NAMES] }),
71
+ /is not registered/,
72
+ )
73
+ })
74
+
75
+ await t.test('a restriction error that is not an unknown-name report propagates', async () => {
76
+ await assert.rejects(
77
+ startMemberWithLenientFilter(async () => { throw new Error('tools.restrict() requires a scoped context') }, { deny: [...CAPTAIN_TOOL_NAMES] }),
78
+ /requires a scoped context/,
79
+ )
80
+ })
81
+
82
+ await t.test('a non-error rejection does not loop forever', async () => {
83
+ await assert.rejects(startMemberWithLenientFilter(async () => { throw 'opaque failure' }, { deny: [...CAPTAIN_TOOL_NAMES] }))
84
+ })
85
+
86
+ await t.test('a rejection that names no name already in the filter does not loop forever', async () => {
87
+ await assert.rejects(
88
+ startMemberWithLenientFilter(async () => { throw hostRejection(['some_other_tool']) }, { deny: [...CAPTAIN_TOOL_NAMES] }),
89
+ /unknown global tool/,
90
+ )
91
+ })
92
+ })