@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,2199 @@
1
+ #!/usr/bin/env node
2
+ import { SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent'
3
+ /**
4
+ * Offline smoke verification for dsh-agent-teams.
5
+ *
6
+ * Runs the pure team-logic rules, the on-disk persistence flow, and the
7
+ * browser workbench fold (events -> workbench projection) against throwaway
8
+ * temp state. Requires a prior `pnpm build` (lib/ present). Does not touch
9
+ * any running DSH instance or profile.
10
+ *
11
+ * Usage: node scripts/verify.mjs
12
+ */
13
+
14
+ import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
15
+ import { existsSync } from 'node:fs'
16
+ import { tmpdir } from 'node:os'
17
+ import { join } from 'node:path'
18
+ import { fileURLToPath } from 'node:url'
19
+ import {
20
+ CAPTAIN_KEY,
21
+ appendMailbox,
22
+ createMessage,
23
+ createTeamDir,
24
+ findTeamByCaptain,
25
+ findTeamByParticipant,
26
+ readMailbox,
27
+ readTeam,
28
+ removeTeamDir,
29
+ sanitizeKey,
30
+ teamLockQueueKeys,
31
+ transitionError,
32
+ unsatisfiedDependencies,
33
+ withTeamLock,
34
+ } from '../lib/state.js'
35
+ import {
36
+ activityPanelExpandedForSession,
37
+ activityPanelShouldAutoExpand,
38
+ compactDagLayout,
39
+ compactModelLabel,
40
+ COMPACT_DAG_NODE_HEIGHT,
41
+ COMPACT_DAG_NODE_WIDTH,
42
+ dependencyFocusTaskId,
43
+ memberFinishedAt,
44
+ memberRouteLabel,
45
+ orderDelegationMembers,
46
+ relatedTaskIds,
47
+ taskModelLabel,
48
+ taskStages,
49
+ liveCaptainTeam,
50
+ teamIsActive,
51
+ teamProgressSummary,
52
+ usesParallelTaskGrid,
53
+ } from '../lib/client/activity-model.js'
54
+ import {
55
+ ACTIVITY_POLL_MS,
56
+ ACTIVITY_PROBE_MS,
57
+ getActivityMonitorTargetsSnapshot,
58
+ monitorAgentTeam,
59
+ settleActivityMonitorTargets,
60
+ startActivityPolling,
61
+ subscribeActivityMonitorTargets,
62
+ } from '../lib/client/activity-monitor.js'
63
+ import {
64
+ DEFAULT_PANEL_LAYOUT,
65
+ compactPanelForBounds,
66
+ dockPanelLayout,
67
+ floatPanelLayout,
68
+ movePanelLayout,
69
+ panelMaximumHeight,
70
+ panelUsesAutoHeight,
71
+ parsePanelLayout,
72
+ resizePanelLayout,
73
+ resolvePanelGeometry,
74
+ } from '../lib/client/panel-geometry.js'
75
+ import {
76
+ ART_BASE,
77
+ LEAD_ART,
78
+ LEAD_FULL_ART,
79
+ leadArtUrl,
80
+ leadFullArtUrl,
81
+ memberArtUrl,
82
+ memberFullArtUrl,
83
+ memberRoleSlug,
84
+ vendorSlug,
85
+ } from '../lib/client/artwork.js'
86
+ import {
87
+ ARTWORK_ROLES,
88
+ ARTWORK_VENDORS,
89
+ PACKAGED_ARTWORK_SLUGS,
90
+ artworkCandidates,
91
+ isAllowedArtwork,
92
+ } from '../lib/artwork-source.js'
93
+ import { parseAgentTeamsCreateArgs } from '../lib/client/agent-teams-card-definition.js'
94
+ import {
95
+ AGENT_TEAMS_LOCALE_NAMESPACE,
96
+ en as agentTeamsEn,
97
+ zh as agentTeamsZh,
98
+ } from '../lib/client/locales.js'
99
+ import { openAgentTeamMember } from '../lib/client/session-navigation.js'
100
+ import { steerCaptainReport } from '../lib/tools.js'
101
+ import { parseProfileInvocation, resolveTeamProfile, formatProfilesForPrompt } from '../lib/profiles.js'
102
+ import { memberPersona, memberWelcome } from '../lib/members.js'
103
+ import { collectCompletedDependencyOutputs, formatDependencyOutputs, assignmentPrompt } from '../lib/scheduler.js'
104
+ import {
105
+ installMemberSelectionRuntime,
106
+ resolveMemberLlmSelection,
107
+ spawnMember,
108
+ validateMemberLlmSelections,
109
+ } from '../lib/members.js'
110
+
111
+ let failures = 0
112
+ function check(label, condition, detail = '') {
113
+ if (condition) {
114
+ console.log(` PASS ${label}`)
115
+ } else {
116
+ failures += 1
117
+ console.error(` FAIL ${label}${detail ? ` — ${detail}` : ''}`)
118
+ }
119
+ }
120
+
121
+ console.log('dsh-agent-teams offline verification')
122
+
123
+ // Named multi-role profile rules
124
+ const demoProfiles = { ' demo ': { protocol: 'a'.repeat(300), members: [{ name: ' Implementer ', role: 'builder', model: 'm' }, { name: 'Reviewer', model: 'r' }], tasks: [{ id: 'design', subject: 'Design', assignee: 'implementer' }, { id: 'review', subject: 'Review', assignee: ' reviewer ', dependencies: ['design'] }] } }
125
+ const normalizedDemo = resolveTeamProfile(demoProfiles, 'demo', 8)
126
+ check('profile keys trim and assignees canonicalize', normalizedDemo.members[0].name === 'Implementer' && normalizedDemo.tasks[1].assignee === 'Reviewer')
127
+ check('profile tasks are stable topological order', normalizedDemo.tasks[0].id === 'design' && normalizedDemo.tasks[1].id === 'review')
128
+ check('profile invocation supports --profile=', parseProfileInvocation('--profile=demo ship it').profile === 'demo' && parseProfileInvocation('--profile=demo ship it').goal === 'ship it')
129
+ check('profile invocation leaves mid-goal profile text untouched', parseProfileInvocation('research profile=prod config').goal === 'research profile=prod config')
130
+ check('profile prompt omits empty config and truncates protocol', formatProfilesForPrompt(demoProfiles).includes('demo') && formatProfilesForPrompt(demoProfiles).length < 400)
131
+ check('seed planning remains the default', normalizedDemo.taskPlanning === 'seed')
132
+ check('fixed profile directory includes purpose when no protocol is configured', formatProfilesForPrompt({ named: { description: ' Review\n the UI ', members: [{ name: 'reviewer' }] } }).includes('Review the UI'))
133
+ const captainPlanned = resolveTeamProfile({
134
+ dynamic: {
135
+ taskPlanning: 'captain',
136
+ members: [{ name: 'analyst', model: 'a' }, { name: 'reviewer', model: 'r' }],
137
+ tasks: [
138
+ { id: 'requirements', subject: 'Requirements', assignee: 'analyst' },
139
+ { id: 'review', subject: 'Review', assignee: 'reviewer', dependencies: ['requirements'] },
140
+ ],
141
+ },
142
+ }, 'dynamic', 8)
143
+ check('captain planning keeps the roster and drops seed tasks', captainPlanned.taskPlanning === 'captain' && captainPlanned.members.length === 2 && captainPlanned.tasks.length === 0)
144
+ check('profile prompt marks captain planning instead of unused seed counts', formatProfilesForPrompt({ dynamic: { taskPlanning: 'captain', members: [{ name: 'solo', model: 'm' }], tasks: [{ id: 'work', subject: 'Work', assignee: 'solo' }] } }).includes('captain planning'))
145
+ const profilePersona = memberPersona({ name: 'Demo', id: 'demo', description: 'goal', profile: { name: 'demo', protocol: 'p'.repeat(600) }, captainSessionId: 'c', createdAt: 0, members: [], tasks: [], taskSeq: 0 }, { name: 'Implementer', id: 'm', role: 'builder', joinedAt: 0, status: 'idle' }, '.agent-teams')
146
+ check('member persona includes completed/failed and claimed transition rules', profilePersona.includes('status=completed') && profilePersona.includes('status=failed') && profilePersona.includes('claimed') && profilePersona.includes('in_progress'))
147
+ const welcome = memberWelcome({ name: 'Demo', id: 'demo', captainSessionId: 'c', createdAt: 0, members: [], tasks: [{ id: 't1', subject: 'x', status: 'pending', assignee: 'Implementer', dependencies: [], createdAt: 0, updatedAt: 0 }], taskSeq: 1 }, 'Implementer')
148
+ check('member welcome reports assigned pending count', welcome.includes('1 pending task(s) assigned to you') && !welcome.includes('none assigned to you yet'))
149
+ const truncated = formatDependencyOutputs([
150
+ { id: 't1', subject: 'old', profileSeedId: 'requirements', output: 'x'.repeat(2500) },
151
+ { id: 't2', subject: 'new', profileSeedId: 'implement', output: 'keep-me' },
152
+ ])
153
+ check('dependency outputs truncate and keep the newest seed id',
154
+ truncated.includes('[implement]') && truncated.includes('keep-me') && truncated.includes('[truncated]'))
155
+ let cycleWarned = false
156
+ const cycled = collectCompletedDependencyOutputs([
157
+ { id: 't1', subject: 'a', status: 'completed', dependencies: ['t2'], createdAt: 0, updatedAt: 0 },
158
+ { id: 't2', subject: 'b', status: 'completed', dependencies: ['t1'], createdAt: 0, updatedAt: 0 },
159
+ ], 't2', () => { cycleWarned = true })
160
+ check('recursive dependency collection stops on cycles', cycleWarned && Array.isArray(cycled))
161
+ check('persona protocol is truncated', profilePersona.includes('p'.repeat(400)) && !profilePersona.includes('p'.repeat(401)))
162
+ const injected = 'The product interface should present the intended outcome, not reveal the reasoning process.'
163
+ const assignment = assignmentPrompt({ taskId: 't1', memberName: 'Implementer', memberId: 'm', attempt: 1, attemptId: 'a', subject: 'x', dependencyOutputs: [], executionPrompt: injected }, '.agent-teams', 'demo')
164
+ check('execution prompt is injected into persona and assignment', assignment.includes(injected) && memberPersona({ name: 'Demo', id: 'demo', description: 'goal', captainSessionId: 'c', createdAt: 0, members: [], tasks: [], taskSeq: 0 }, { name: 'Implementer', id: 'm', role: 'builder', joinedAt: 0, status: 'idle', executionPrompt: injected }, '.agent-teams').includes(injected))
165
+
166
+
167
+ // The bundle patch's `name` is the specifier Node resolves when a profile
168
+ // loads this plugin, so it must equal the published package name. A mismatch
169
+ // only surfaces after someone installs the package (the row fails to load),
170
+ // never in local link-installed development — hence this pre-publish gate.
171
+ console.log('1/8 packaging contract')
172
+ const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'))
173
+ const patchText = await readFile(new URL('../cordis.patch.yml', import.meta.url), 'utf8')
174
+ const patchName = patchText
175
+ .split('\n')
176
+ .filter(line => !/^\s*#/.test(line))
177
+ .find(line => /^\s*name:\s*\S/.test(line))
178
+ ?.match(/^\s*name:\s*(.+?)\s*$/)?.[1]
179
+ ?.replace(/^(['"])(.*)\1$/, '$2')
180
+ check(
181
+ 'cordis.patch.yml name matches the published package name',
182
+ patchName === pkg.name,
183
+ `patch has ${JSON.stringify(patchName)}, package.json has ${JSON.stringify(pkg.name)}`,
184
+ )
185
+ check(
186
+ 'files[] ships the bundle patch and lib',
187
+ ['lib', 'cordis.patch.yml'].every(entry => pkg.files?.includes(entry)),
188
+ `files = ${JSON.stringify(pkg.files)}`,
189
+ )
190
+ check(
191
+ 'scoped package publishes publicly',
192
+ !pkg.name.startsWith('@') || pkg.publishConfig?.access === 'public',
193
+ 'scoped packages default to restricted without publishConfig.access = "public"',
194
+ )
195
+ const requiredPeers = Object.keys(pkg.peerDependencies ?? {})
196
+ .filter(name => pkg.peerDependenciesMeta?.[name]?.optional !== true)
197
+ check(
198
+ 'shared runtime peers are optional for standalone profile installs',
199
+ requiredPeers.length === 0,
200
+ `required peers trigger pnpm warnings: ${JSON.stringify(requiredPeers)}`,
201
+ )
202
+ // The browser half registers itself with __ModuleLoader__ under an id the host
203
+ // resolves by package name. A stale id here fails only in the browser — the
204
+ // host half loads fine, so every server-side check still passes.
205
+ const clientBundle = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
206
+ const registeredId = clientBundle.match(/__ModuleLoader__\.load\(\{\s*id:\s*"([^"]*)"/)?.[1]
207
+ check(
208
+ 'client bundle registers under the package name',
209
+ registeredId === pkg.name,
210
+ `bundle registers ${JSON.stringify(registeredId)}, package.json has ${JSON.stringify(pkg.name)}`,
211
+ )
212
+ const activityPanelCss = await readFile(new URL('../src/client/ActivityPanel.module.css', import.meta.url), 'utf8')
213
+ const activityPanelSource = await readFile(new URL('../src/client/ActivityPanel.tsx', import.meta.url), 'utf8')
214
+ const stagingPlanSource = await readFile(new URL('../src/client/StagingPlanEditor.tsx', import.meta.url), 'utf8')
215
+ const clientIndexSource = await readFile(new URL('../src/client/index.tsx', import.meta.url), 'utf8')
216
+ const agentTeamsCardCss = await readFile(new URL('../src/client/AgentTeamsCard.module.css', import.meta.url), 'utf8')
217
+ const agentTeamsCardSource = await readFile(new URL('../src/client/AgentTeamsCard.tsx', import.meta.url), 'utf8')
218
+ const hostSource = await readFile(new URL('../src/index.ts', import.meta.url), 'utf8')
219
+ const toolsSource = await readFile(new URL('../src/tools.ts', import.meta.url), 'utf8')
220
+ const localesSource = await readFile(new URL('../src/client/locales.ts', import.meta.url), 'utf8')
221
+ const localeKeys = Object.keys(agentTeamsZh).sort()
222
+ const englishLocaleKeys = Object.keys(agentTeamsEn).sort()
223
+ const placeholders = value => [...value.matchAll(/\{(\w+)\}/gu)].map(match => match[1]).sort()
224
+ check(
225
+ 'AgentTeams locale dictionaries have identical keys and template placeholders',
226
+ localeKeys.length > 0
227
+ && JSON.stringify(localeKeys) === JSON.stringify(englishLocaleKeys)
228
+ && localeKeys.every(key => JSON.stringify(placeholders(agentTeamsZh[key]))
229
+ === JSON.stringify(placeholders(agentTeamsEn[key]))),
230
+ )
231
+ check(
232
+ 'client uses the uiConversation event registry and registers the official locale namespace',
233
+ AGENT_TEAMS_LOCALE_NAMESPACE === 'agentTeams'
234
+ && clientIndexSource.includes("'uiConversation', 'slots', 'sessions', 'locale', 'modelDirectories'")
235
+ && clientIndexSource.includes('ctx.uiConversation.events.register(agentTeamsCardDefinition)')
236
+ && clientIndexSource.includes('ctx.locale.register(AGENT_TEAMS_LOCALE_NAMESPACE, { zh, en })')
237
+ && clientIndexSource.match(/locale:\s*AGENT_TEAMS_LOCALE_NAMESPACE/gu)?.length === 5,
238
+ )
239
+ check(
240
+ 'slash command transcript hides the duplicate pre-message result row',
241
+ clientIndexSource.includes('HiddenAgentTeamsCommand')
242
+ && /name:\s*'conversation\.chat\.commandview',\s*key:\s*'agent-teams'/u.test(clientIndexSource),
243
+ )
244
+ check(
245
+ 'stop-team control lives in the team panel and requires confirmation',
246
+ !clientIndexSource.includes("conversation.input.dock")
247
+ && activityPanelSource.includes('className={css.teamStopButton}')
248
+ && activityPanelSource.includes('<Modal')
249
+ && activityPanelSource.includes('ACTIVITY_HALT_URL'),
250
+ )
251
+ check(
252
+ 'clean builds do not package the removed composer stop banner',
253
+ !existsSync(new URL('../lib/client/TeamProgressBanner.js', import.meta.url))
254
+ && !existsSync(new URL('../lib/types/client/TeamProgressBanner.d.ts', import.meta.url)),
255
+ )
256
+ check(
257
+ 'staged member routes use the official directory and primitive Menu instead of native route selects',
258
+ clientIndexSource.includes('@deepseek-ai/dsh-client-ui-model-selection/client')
259
+ && stagingPlanSource.includes('directory.store.subscribe')
260
+ && stagingPlanSource.includes("from '@deepseek-ai/dsh-client-ui-primitives'")
261
+ && stagingPlanSource.includes('<Menu')
262
+ && stagingPlanSource.includes('data-plan-model-trigger')
263
+ && !stagingPlanSource.includes('name="provider"')
264
+ && !stagingPlanSource.includes('name="model"')
265
+ && !stagingPlanSource.includes('name="modelRoute"')
266
+ && !stagingPlanSource.includes('name="reasoningEffort"'),
267
+ )
268
+ check(
269
+ 'staged plan review offers continue, discard, and approve outcomes',
270
+ stagingPlanSource.includes('data-plan-continue')
271
+ && stagingPlanSource.includes('data-plan-discard')
272
+ && stagingPlanSource.includes("action: 'continue'")
273
+ && stagingPlanSource.includes("action: 'discard'")
274
+ && hostSource.includes("if (action === 'continue')")
275
+ && hostSource.includes("if (action === 'discard')"),
276
+ )
277
+ check(
278
+ 'review decisions control the Captain turn instead of relying on front-end state alone',
279
+ toolsSource.includes('stagedPlanFeedbackContext')
280
+ && toolsSource.includes('stagedPlanDiscardContext')
281
+ && toolsSource.includes("fresh.planReviewState = 'awaiting_feedback'")
282
+ && toolsSource.includes("captain.cancel({ kind: 'user' }, { keepInbox: true })")
283
+ && toolsSource.includes('captain.followup(createUserMessage')
284
+ && toolsSource.includes('captain.inject(createUserMessage')
285
+ && toolsSource.includes('Do not create a replacement team')
286
+ && toolsSource.includes('Do not call agent_teams_create'),
287
+ )
288
+ check(
289
+ 'continued planning uses a model-facing atomic staged-plan tool instead of state-file edits',
290
+ toolsSource.includes("name: 'agent_teams_edit_plan'")
291
+ && toolsSource.includes('updateStagedPlanBatch')
292
+ && toolsSource.includes("action: 'remove_member'")
293
+ && toolsSource.includes('none of the edits are saved')
294
+ && hostSource.includes('agent_teams_edit_plan')
295
+ && hostSource.includes('Never inspect or edit .agent-teams state files or plugin source code'),
296
+ )
297
+ check(
298
+ 'discarded and stopped teams render terminal semantics instead of pending execution copy',
299
+ activityPanelSource.includes("const discarded = historic && team.phase === 'staged'")
300
+ && activityPanelSource.includes("t('member.status.discarded')")
301
+ && activityPanelSource.includes("t('member.status.stopped')")
302
+ && activityPanelSource.includes("'archive.discardedLabel'")
303
+ && localesSource.includes("'task.status.notRun': '未执行'")
304
+ && localesSource.includes("'member.state.notCreated': '未创建'"),
305
+ )
306
+ const expectedArtwork = [
307
+ 'team-lead-v2.png',
308
+ 'member-researcher-v2.png', 'member-engineer-v2.png',
309
+ 'member-qa-v2.png', 'member-designer-v2.png',
310
+ 'member-security-v2.png', 'member-docs-v2.png',
311
+ 'member-data-v2.png', 'member-operator-v2.png',
312
+ 'action-working-v2.png', 'action-thinking-v2.png',
313
+ 'action-reporting-v2.png', 'action-celebrating-v2.png',
314
+ 'action-sleeping-v2.png', 'action-sending-v2.png',
315
+ ].sort()
316
+ const artworkDir = new URL('../assets/agent-teams/', import.meta.url)
317
+ // 2026-10-08:厂商命名空间扩到 15 个、audio/video 两桶出图,所以这条门禁的
318
+ // 厂商与岗位枚举各收敛成一份,跟着 ARTWORK_VENDORS / ARTWORK_ROLES 一起改。
319
+ // 2026-10-11:第三轮素材再扩到 17 个(新增 stepfun / jev)。
320
+ const ARTWORK_VENDOR_ALT = 'deepseek|qwen|glm|kimi|claude|gemini|grok|gpt|hunyuan|minimax|meta|mistral|rwkv|seed|ernie|stepfun|jev|mimo'
321
+ const ARTWORK_ROLE_ALT = 'engineer|qa|security|researcher|designer|docs|data|operator|audio|video'
322
+ const packagedArtwork = (await readdir(artworkDir)).sort()
323
+ const packagedArtworkSet = new Set(packagedArtwork)
324
+ // 0.3.1:厂商美术随包分发,所以目录不再要求「恰好等于」那 15 个内置名字 ——
325
+ // 否则每补一个厂商都要改这条门禁,且改法本身就是「把契约放松成什么都行」。
326
+ // 取而代之的是两条更严的边界:内置 15 张必须仍在场(基线不被替换掉),
327
+ // 以及目录只接纳已知美术族(.md、1×1 占位图、临时文件混入当场失败)。
328
+ check(
329
+ 'artwork directory still ships the V2 captain, eight members, and six actions',
330
+ expectedArtwork.every(name => packagedArtworkSet.has(name)),
331
+ `missing = ${JSON.stringify(expectedArtwork.filter(name => !packagedArtworkSet.has(name)))}`,
332
+ )
333
+ const packagedArtworkName = new RegExp(
334
+ '^(?:'
335
+ // 15 个厂商 token 与 10 个岗位 token 各只写一份,避免四处枚举漂移。
336
+ + `team-lead(?:-(?:${ARTWORK_VENDOR_ALT}))?-v2\\.png`
337
+ // 2026-10-08 起:点击放大的高清族是 WebP(同分辨率下体积约为 PNG 的十分之一)。
338
+ // 岗位/队长高清是 1024×1024 方框,厂商立绘高清按长边 2048 紧裁(非方形)。
339
+ + `|team-lead(?:-(?:${ARTWORK_VENDOR_ALT}))?-full-v2\\.webp`
340
+ + `|member-(?:(?:${ARTWORK_VENDOR_ALT})-)?(?:${ARTWORK_ROLE_ALT})-v2\\.png`
341
+ + `|member-(?:(?:${ARTWORK_VENDOR_ALT})-)?(?:${ARTWORK_ROLE_ALT})-full-v2\\.webp`
342
+ + `|member-(?:${ARTWORK_VENDOR_ALT})-v2\\.png`
343
+ + `|member-(?:${ARTWORK_VENDOR_ALT})-full-v2\\.webp`
344
+ + '|action-(?:working|thinking|reporting|celebrating|sleeping|sending)-v2\\.png'
345
+ + `|brand-(?:${ARTWORK_VENDOR_ALT})\\.svg`
346
+ + ')$', 'u')
347
+ check(
348
+ 'packaged artwork admits only the captain, member, action, and brand families',
349
+ packagedArtwork.every(name => packagedArtworkName.test(name)),
350
+ `foreign = ${JSON.stringify(packagedArtwork.filter(name => !packagedArtworkName.test(name)))}`,
351
+ )
352
+ const artworkHeaders = await Promise.all(expectedArtwork.map(async (name) => {
353
+ const data = await readFile(new URL(name, artworkDir))
354
+ return {
355
+ name,
356
+ png: data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),
357
+ width: data.readUInt32BE(16),
358
+ height: data.readUInt32BE(20),
359
+ bitDepth: data[24],
360
+ colorType: data[25],
361
+ }
362
+ }))
363
+ check(
364
+ 'all V2 artwork is 256x256 8-bit RGBA PNG',
365
+ artworkHeaders.every(image => image.png
366
+ && image.width === 256
367
+ && image.height === 256
368
+ && image.bitDepth === 8
369
+ && image.colorType === 6),
370
+ `invalid headers = ${JSON.stringify(artworkHeaders.filter(image => !image.png
371
+ || image.width !== 256
372
+ || image.height !== 256
373
+ || image.bitDepth !== 8
374
+ || image.colorType !== 6))}`,
375
+ )
376
+ // The fork replaced upstream's fixed role-only slug list with two halves: the
377
+ // host allowlist (`PACKAGED_ARTWORK_SLUGS` plus the vendor namespace) and the
378
+ // client's `vendor+role` template mapping. Both are resolved through the real
379
+ // modules rather than by scanning for literal file names, because the client
380
+ // now builds `member-<vendor>-<role>-v2.png` from a template and never spells
381
+ // an individual packaged slug out.
382
+ const canonicalRoster = [
383
+ ['Researcher', 'Researcher'],
384
+ ['Engineer', 'Backend Engineer'],
385
+ ['QA', 'QA Engineer'],
386
+ ['Designer', 'UI UX Designer'],
387
+ ['Security', 'Security Reviewer'],
388
+ ['Docs', 'Docs Writer'],
389
+ ['Data', 'Data Analyst'],
390
+ ['Operator', 'Release Operator'],
391
+ ]
392
+ // 素材分两档(2026-10-08):一档厂商有「厂商 × 岗位」全套图 + 队长图,另一档只有
393
+ // 厂商通用图与 512 立绘。两档合起来必须恰好等于 ARTWORK_VENDORS,多一个少一个都失败。
394
+ // 2026-10-11:第三轮素材新增 stepfun / jev,两个都落在「只有通用图与立绘」那一档。
395
+ const ROLE_ART_VENDORS = ['deepseek', 'qwen', 'glm', 'kimi', 'claude', 'gemini', 'grok', 'gpt', 'hunyuan', 'minimax']
396
+ const GENERIC_ONLY_VENDORS = ['meta', 'mistral', 'rwkv', 'seed', 'ernie', 'stepfun', 'jev', 'mimo']
397
+ // 角色表自 0.1.27 起分两半:上面 8 个「八人名单」岗位,以及 audio / video —— 它们
398
+ // 不在名单里,但同样登记在 ARTWORK_ROLES 且自 2026-10-08 起有整套厂商图。
399
+ const EXTRA_ROLES = ['audio', 'video']
400
+ const artworkReachesPackage = url => {
401
+ const slug = typeof url === 'string' && url.startsWith(ART_BASE) ? url.slice(ART_BASE.length) : ''
402
+ return slug !== '' && artworkCandidates(slug).some(candidate => packagedArtwork.includes(candidate))
403
+ }
404
+ check(
405
+ 'client mapping and host allowlist reference every V2 artwork asset',
406
+ JSON.stringify([...PACKAGED_ARTWORK_SLUGS].sort()) === JSON.stringify(expectedArtwork)
407
+ && expectedArtwork.every(name => artworkCandidates(name)[0] === name
408
+ && artworkReachesPackage(`${ART_BASE}${name}`))
409
+ && ARTWORK_ROLES.length === canonicalRoster.length + EXTRA_ROLES.length
410
+ && canonicalRoster.every(([name, memberRole]) => ARTWORK_ROLES.includes(memberRoleSlug(name, memberRole)))
411
+ && EXTRA_ROLES.every(role => ARTWORK_ROLES.includes(role)
412
+ // audio / video 不在八人名单里,但自 2026-10-08 起同样有整套厂商图:既要
413
+ // 「已登记 + 请求是被允许的 slug」,也要在角色图厂商档里真的落到岗位上。
414
+ && isAllowedArtwork(memberArtUrl('Engineer', role, 'deepseek').slice(ART_BASE.length))
415
+ && ROLE_ART_VENDORS.every(vendor => packagedArtworkSet.has(`member-${vendor}-${role}-v2.png`)))
416
+ && canonicalRoster.every(([name, role]) => memberRoleSlug(name, role) !== null
417
+ && artworkReachesPackage(memberArtUrl(name, role))
418
+ && artworkReachesPackage(memberArtUrl(name, role, 'deepseek')))
419
+ && ARTWORK_VENDORS.length === 18
420
+ && [...ROLE_ART_VENDORS, ...GENERIC_ONLY_VENDORS].sort().join('|')
421
+ === [...ARTWORK_VENDORS].sort().join('|')
422
+ && ARTWORK_VENDORS.every(vendor => vendorSlug({ model: vendor }) === vendor
423
+ && isAllowedArtwork(`brand-${vendor}.svg`)
424
+ && canonicalRoster.every(([name, role]) => artworkReachesPackage(memberArtUrl(name, role, vendor))))
425
+ && artworkReachesPackage(LEAD_ART)
426
+ && artworkReachesPackage(LEAD_FULL_ART),
427
+ 'a packaged image is unreachable or one of the eighth-member mappings is missing',
428
+ )
429
+ // 厂商美术的缺失会被降级链掩盖:包里只留岗位通用图时,`vendor+role` 请求照样
430
+ // 「成功」——artworkCandidates 的第二跳命中内置鲸鱼——事故在门禁上完全隐形。
431
+ // 这里钉住**第一跳**:角色图厂商必须是 10 岗位全套(头像 PNG + 高清 WebP)+ 队长
432
+ // (头像 + 高清)+ 通用 + 立绘高清 + 商标都在包里,只有通用图的厂商则至少要通用 +
433
+ // 立绘高清 + 商标,并且 URL 模板 → 候选 → 目录指向同一个文件。
434
+ const packagedVendorArtwork = [
435
+ ...ROLE_ART_VENDORS.flatMap(vendor => [
436
+ ...ARTWORK_ROLES.flatMap(role => [`member-${vendor}-${role}-v2.png`, `member-${vendor}-${role}-full-v2.webp`]),
437
+ `team-lead-${vendor}-v2.png`,
438
+ `team-lead-${vendor}-full-v2.webp`,
439
+ ]),
440
+ ...ARTWORK_VENDORS.flatMap(vendor => [
441
+ `member-${vendor}-v2.png`,
442
+ `member-${vendor}-full-v2.webp`,
443
+ `brand-${vendor}.svg`,
444
+ ]),
445
+ ]
446
+ check(
447
+ 'every vendor ships its own artwork tier inside the bundle',
448
+ packagedVendorArtwork.every(name => packagedArtworkSet.has(name)),
449
+ `missing = ${JSON.stringify(packagedVendorArtwork.filter(name => !packagedArtworkSet.has(name)))}`,
450
+ )
451
+ check(
452
+ 'a vendor+role request reaches its own artwork on the first hop',
453
+ ROLE_ART_VENDORS.every(vendor => canonicalRoster.every(([name, role]) => {
454
+ const [first] = artworkCandidates(memberArtUrl(name, role, vendor).slice(ART_BASE.length))
455
+ return first === `member-${vendor}-${memberRoleSlug(name, role)}-v2.png` && packagedArtworkSet.has(first)
456
+ })),
457
+ 'the vendor namespace degraded to the packaged whale or a role-generic image',
458
+ )
459
+ // 链序曾经是 `vendor+role → role → vendor`,而岗位通用图对**每一个**岗位都存在,
460
+ // 于是岗位那一跳永远抢先命中,厂商那一跳是死代码:
461
+ // - 只有通用档的 7 家的厂商角色永远不可达(现场症状正是「徽标显示 StepFun,
462
+ // 头像却是通用岗位鲸鱼」);
463
+ // - `member-<vendor>-full-v2.webp`(17 张厂商立绘)同样永远轮不到。
464
+ // 这两件事都瞒过了当时全部门禁:素材齐、降级链「有结果」、第一跳也正确 ——
465
+ // 断的是**第二跳**。所以这里逐厂商钉住第 2 跳必须落在自家角色上。
466
+ check(
467
+ 'a generic-only vendor reaches its own character on the second hop',
468
+ GENERIC_ONLY_VENDORS.every(vendor => canonicalRoster.every(([name, role]) => {
469
+ const chain = artworkCandidates(memberArtUrl(name, role, vendor).slice(ART_BASE.length))
470
+ return chain[1] === `member-${vendor}-v2.png` && packagedArtworkSet.has(chain[1])
471
+ })),
472
+ 'the vendor hop sits behind the role hop, so a vendor character can never be reached',
473
+ )
474
+ // 同时钉住整体顺序:厂商那一跳必须排在岗位那一跳之前(不限厂商档位)。
475
+ check(
476
+ 'the vendor hop precedes the role hop for every vendor+role request',
477
+ ARTWORK_VENDORS.every(vendor => ARTWORK_ROLES.every(role => {
478
+ const chain = artworkCandidates(`member-${vendor}-${role}-v2.png`)
479
+ const vendorHop = chain.indexOf(`member-${vendor}-v2.png`)
480
+ const roleHop = chain.indexOf(`member-${role}-v2.png`)
481
+ return vendorHop !== -1 && roleHop !== -1 && vendorHop < roleHop
482
+ })),
483
+ 'a role-generic image is preferred over the member\'s own vendor character',
484
+ )
485
+ // `-full`(点击放大)同理:有厂商立绘的厂商必须给出厂商立绘,而不是 256 岗位头像。
486
+ check(
487
+ 'the click-to-enlarge request prefers the vendor HD art over the role avatar',
488
+ [...ROLE_ART_VENDORS, ...GENERIC_ONLY_VENDORS].every(vendor => {
489
+ const chain = artworkCandidates(memberFullArtUrl('QA', 'QA Engineer', vendor).slice(ART_BASE.length))
490
+ const vendorFull = chain.indexOf(`member-${vendor}-full-v2.png`)
491
+ const roleFull = chain.indexOf('member-qa-full-v2.png')
492
+ return vendorFull !== -1 && roleFull !== -1 && vendorFull < roleFull
493
+ }),
494
+ 'the large preview degrades to a 256 role avatar while a vendor portrait ships in the bundle',
495
+ )
496
+ // 队长图曾长期是硬编码常量 `team-lead-deepseek-v2.png`:素材齐、降级链通、
497
+ // `artworkReachesPackage(LEAD_ART)` 也是绿的,于是「队长换成 qwen / claude / glm
498
+ // 却仍请求 deepseek 那张」在门禁上完全隐形 —— 随包的另外 9 张队长图永远不可达。
499
+ // 这里钉住队长与成员走**同一条**厂商链:每个有队长图的厂商,第一跳必须是它自己。
500
+ check(
501
+ 'the captain artwork follows the captain vendor on the first hop',
502
+ ROLE_ART_VENDORS.every(vendor => {
503
+ const avatar = leadArtUrl(vendor)
504
+ const full = leadFullArtUrl(vendor)
505
+ return artworkCandidates(avatar.slice(ART_BASE.length))[0] === `team-lead-${vendor}-v2.png`
506
+ && artworkCandidates(full.slice(ART_BASE.length))[0] === `team-lead-${vendor}-full-v2.png`
507
+ }),
508
+ 'the captain artwork is pinned to one vendor instead of following the route',
509
+ )
510
+ check(
511
+ 'an unknown captain vendor degrades to the packaged captain',
512
+ // 未知 token 绝不能拼进 URL:artworkCandidates 会拒绝它,面板直接破图。
513
+ leadArtUrl(undefined) === LEAD_ART
514
+ && leadFullArtUrl(undefined) === LEAD_FULL_ART
515
+ && leadArtUrl('evil') === LEAD_ART
516
+ && leadFullArtUrl('evil') === LEAD_FULL_ART,
517
+ 'an unknown captain vendor escaped into the request URL',
518
+ )
519
+ const artworkHeader = async (name) => {
520
+ try {
521
+ const data = await readFile(new URL(name, artworkDir))
522
+ return {
523
+ name,
524
+ png: data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),
525
+ width: data.readUInt32BE(16),
526
+ height: data.readUInt32BE(20),
527
+ bitDepth: data[24],
528
+ colorType: data[25],
529
+ }
530
+ }
531
+ catch {
532
+ return { name, png: false, width: 0, height: 0, bitDepth: 0, colorType: 0 }
533
+ }
534
+ }
535
+ /** 读 WebP 容器头(VP8X 扩展格式带 alpha 标志;无扩展头时退回 VP8/VP8L 帧头)。 */
536
+ const webpHeader = async (name) => {
537
+ try {
538
+ const data = await readFile(new URL(name, artworkDir))
539
+ const riff = data.subarray(0, 4).toString('latin1') === 'RIFF'
540
+ && data.subarray(8, 12).toString('latin1') === 'WEBP'
541
+ if (!riff) return { name, webp: false, width: 0, height: 0, alpha: false }
542
+ let offset = 12
543
+ while (offset + 8 <= data.length) {
544
+ const type = data.toString('latin1', offset, offset + 4)
545
+ const size = data.readUInt32LE(offset + 4)
546
+ const body = offset + 8
547
+ if (type === 'VP8X') {
548
+ return {
549
+ name,
550
+ webp: true,
551
+ width: (data[body + 4] | (data[body + 5] << 8) | (data[body + 6] << 16)) + 1,
552
+ height: (data[body + 7] | (data[body + 8] << 8) | (data[body + 9] << 16)) + 1,
553
+ alpha: (data[body] & 0x10) !== 0,
554
+ }
555
+ }
556
+ if (type === 'VP8 ') {
557
+ return { name, webp: true, width: data.readUInt16LE(body + 6) & 0x3fff, height: data.readUInt16LE(body + 8) & 0x3fff, alpha: false }
558
+ }
559
+ if (type === 'VP8L') {
560
+ const bits = data.readUInt32LE(body + 1)
561
+ return { name, webp: true, width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1, alpha: ((bits >> 28) & 1) === 1 }
562
+ }
563
+ offset = body + size + (size % 2)
564
+ }
565
+ return { name, webp: false, width: 0, height: 0, alpha: false }
566
+ }
567
+ catch {
568
+ return { name, webp: false, width: 0, height: 0, alpha: false }
569
+ }
570
+ }
571
+ // 头像族是 40–44px 的 256×256 8-bit RGBA PNG;高清族是 WebP —— 岗位/队长为 1024×1024
572
+ // 方框(画面 1:1 原生像素居中),厂商立绘按长边不超过 2048 紧裁、因此是竖幅而非方形。
573
+ // 尺寸写错不会破图,只会让某一侧变形,所以两族都随包断言。
574
+ const vendorAvatarNames = [
575
+ ...ROLE_ART_VENDORS.flatMap(vendor => [
576
+ ...ARTWORK_ROLES.map(role => `member-${vendor}-${role}-v2.png`),
577
+ `team-lead-${vendor}-v2.png`,
578
+ ]),
579
+ ...ARTWORK_VENDORS.map(vendor => `member-${vendor}-v2.png`),
580
+ ]
581
+ const offSpecAvatars = (await Promise.all(vendorAvatarNames.map(artworkHeader))).filter(image => !image.png
582
+ || image.width !== 256
583
+ || image.height !== 256
584
+ || image.bitDepth !== 8
585
+ || image.colorType !== 6)
586
+ check(
587
+ 'vendor avatar artwork is a 256x256 8-bit RGBA PNG',
588
+ offSpecAvatars.length === 0,
589
+ `off spec = ${JSON.stringify(offSpecAvatars)}`,
590
+ )
591
+ const vendorHdNames = [
592
+ ...ROLE_ART_VENDORS.flatMap(vendor => [
593
+ ...ARTWORK_ROLES.map(role => [`member-${vendor}-${role}-full-v2.webp`, 'square']),
594
+ [`team-lead-${vendor}-full-v2.webp`, 'square'],
595
+ ]),
596
+ ...ARTWORK_VENDORS.map(vendor => [`member-${vendor}-full-v2.webp`, 'portrait']),
597
+ ]
598
+ const hdHeaders = await Promise.all(vendorHdNames.map(([name]) => webpHeader(name)))
599
+ const offSpecHd = hdHeaders.filter((image, index) => {
600
+ const [, shape] = vendorHdNames[index]
601
+ if (!image.webp || !image.alpha) return true
602
+ // 岗位/队长固定 1024×1024;厂商立绘是竖幅,长边不得超过 2048(且必须真的到了高清量级)。
603
+ if (shape === 'square') return image.width !== 1024 || image.height !== 1024
604
+ return image.height <= image.width || image.height > 2048 || image.height < 1024
605
+ })
606
+ check(
607
+ 'vendor HD preview artwork is an alpha WebP at its contracted size',
608
+ offSpecHd.length === 0,
609
+ `off spec = ${JSON.stringify(offSpecHd)}`,
610
+ )
611
+ const brandArtwork = await Promise.all(ARTWORK_VENDORS.map(async vendor => {
612
+ const name = `brand-${vendor}.svg`
613
+ try {
614
+ return { name, source: await readFile(new URL(name, artworkDir), 'utf8') }
615
+ }
616
+ catch {
617
+ return { name, source: '' }
618
+ }
619
+ }))
620
+ const offSpecBrand = brandArtwork.filter(({ source }) => !/^\s*<svg[\s>]/u.test(source)
621
+ || !source.includes('</svg>')
622
+ // 商标徽标要能离线自洽:外链或脚本会让它依赖网络(或被注入内容)。
623
+ || /<script|href\s*=\s*["']?(?:https?:)?\/\//iu.test(source))
624
+ check(
625
+ 'every vendor brand mark is a self-contained svg',
626
+ offSpecBrand.length === 0,
627
+ `invalid = ${JSON.stringify(offSpecBrand.map(({ name }) => name))}`,
628
+ )
629
+ // 0.3.2 回归:包内素材既有 PNG 也有 brand-<vendor>.svg,宿主端必须按**扩展名**
630
+ // 给媒体类型。0.3.1 把包内素材一律当 image/png 发出去,浏览器解码 SVG 失败 →
631
+ // 徽标 onError 回落活动状态图,看起来就像「SVG 根本没进包」。这里直接调真实
632
+ // 解析函数(与 HTTP 处理器同一份代码),逐张比对媒体类型与字节数。
633
+ // 2026-10-08:高清族随包的是 .webp,而客户端请求的永远是 .png 名字 —— 所以按
634
+ // **请求名**解析,再与磁盘上的真身比对,正好一并验证「包内按扩展名探测」这件事。
635
+ const { resolveArtwork } = await import('../lib/index.js')
636
+ const packagedArtDir = fileURLToPath(artworkDir)
637
+ const artworkResponses = []
638
+ for (const name of packagedArtwork) {
639
+ const requested = name.endsWith('.webp') ? name.replace(/\.webp$/u, '.png') : name
640
+ const resolved = await resolveArtwork(requested, { artDir: packagedArtDir })
641
+ artworkResponses.push({
642
+ name,
643
+ requested,
644
+ type: resolved?.contentType,
645
+ bytes: resolved?.data.byteLength ?? 0,
646
+ disk: (await readFile(new URL(name, artworkDir))).byteLength,
647
+ })
648
+ }
649
+ const declaredArtworkType = name => name.endsWith('.svg')
650
+ ? 'image/svg+xml'
651
+ : name.endsWith('.webp') ? 'image/webp' : 'image/png'
652
+ const wrongArtworkType = artworkResponses.filter(entry => entry.type !== declaredArtworkType(entry.name))
653
+ const mismatchedArtworkBytes = artworkResponses.filter(entry => entry.bytes !== entry.disk)
654
+ check(
655
+ 'packaged artwork is served with the media type its own extension declares',
656
+ wrongArtworkType.length === 0 && mismatchedArtworkBytes.length === 0,
657
+ `wrong type = ${JSON.stringify(wrongArtworkType.map(entry => `${entry.name}:${entry.type}`))}`
658
+ + `; byte mismatch = ${JSON.stringify(mismatchedArtworkBytes.map(entry => entry.name))}`,
659
+ )
660
+ const servedBrands = await Promise.all(ARTWORK_VENDORS.map(
661
+ vendor => resolveArtwork(`brand-${vendor}.svg`, { artDir: packagedArtDir }),
662
+ ))
663
+ check(
664
+ 'every vendor brand mark reaches the browser as an svg document',
665
+ servedBrands.every(resolved => resolved?.contentType === 'image/svg+xml'
666
+ && resolved.data.subarray(0, 4).toString('utf8') === '<svg'),
667
+ `served = ${JSON.stringify(servedBrands.map(resolved => resolved?.contentType ?? 'unresolved'))}`,
668
+ )
669
+ const eightRoleArtwork = canonicalRoster.map(([name, role]) => memberArtUrl(name, role))
670
+ check(
671
+ 'canonical eight-member roster resolves to eight distinct role images',
672
+ eightRoleArtwork.every(Boolean) && new Set(eightRoleArtwork).size === 8,
673
+ `resolved artwork = ${JSON.stringify(eightRoleArtwork)}`,
674
+ )
675
+ check(
676
+ 'whale portraits use transparent cutouts instead of dark circular plates',
677
+ !/#0b1d33/iu.test(`${activityPanelCss}\n${agentTeamsCardCss}`)
678
+ && activityPanelCss.includes('object-fit: contain')
679
+ && activityPanelCss.includes('agentTeamsUnreadPulse')
680
+ && agentTeamsCardCss.includes('object-fit: contain'),
681
+ 'portrait CSS should preserve each transparent role silhouette and use a compact unread dot',
682
+ )
683
+ check(
684
+ 'all client surfaces consume host semantic colors without redefining the host palette',
685
+ [activityPanelCss, agentTeamsCardCss].every(css =>
686
+ !/--dsw-[a-z0-9-]+\s*:/.test(css)
687
+ && !/--dsw-static-/.test(css)
688
+ && !/--dsw-alias-(?:line-|bg-fill-|bg-module[),]|label-on-fill|state-(?:danger|warning)[),]|state-success[),])/.test(css)),
689
+ 'light-only palette bridges or undefined legacy tokens break dark mode and portaled surfaces',
690
+ )
691
+ check(
692
+ 'working member and captain states use the host semantic business color',
693
+ activityPanelSource.includes('data-activity={member.activity}')
694
+ && activityPanelCss.includes(".memberState[data-activity='working']")
695
+ && /\.memberState\[data-activity='working'\][^{]*\{[^}]*color:\s*var\(--dsw-alias-state-business-primary\)/su.test(activityPanelCss),
696
+ 'the working label and glyph must follow the host business color',
697
+ )
698
+ // The host renders dialogs in its own fixed layer at z-index 1000, so the slot
699
+ // only has to stay below it. Bound every declared z-index rather than one magic
700
+ // number, and reject the actual escalation mechanisms: a body portal
701
+ // (createRoot/createPortal) or a layer that outranks the host's dialog layer.
702
+ const panelZIndexes = [...activityPanelCss.matchAll(/z-index:\s*(\d+)/gu)].map(match => Number(match[1]))
703
+ check(
704
+ 'activity panel uses the shell overlay instead of a page-breaking body portal',
705
+ clientIndexSource.includes("ctx.slots.inject('shell.overlay'")
706
+ && !clientIndexSource.includes('createRoot')
707
+ && !clientIndexSource.includes('createPortal')
708
+ && !activityPanelSource.includes('createPortal')
709
+ && activityPanelCss.includes('position: absolute')
710
+ && panelZIndexes.length > 0
711
+ && panelZIndexes.every(value => value < 1000)
712
+ && !activityPanelCss.includes('2147483000')
713
+ && !activityPanelCss.includes('position: fixed'),
714
+ 'a body portal or unbounded z-index can cover host modal controls',
715
+ )
716
+ check(
717
+ 'panel exposes drag, resize, dock, and fold interaction probes',
718
+ activityPanelSource.includes('data-drag-handle')
719
+ && activityPanelSource.includes('data-resize-edge="left"')
720
+ && activityPanelSource.includes('data-resize-edge="corner"')
721
+ && activityPanelSource.includes('data-control="dock"')
722
+ && activityPanelSource.includes('data-control="collapse"')
723
+ && activityPanelSource.includes('data-height-mode=')
724
+ && activityPanelSource.includes("height: autoHeight ? 'auto'")
725
+ && activityPanelCss.includes('.resizeHandle')
726
+ && activityPanelCss.includes(".resizeHandle[data-resize-edge='left']::after")
727
+ && activityPanelCss.includes(".resizeHandle[data-resize-edge='bottom']::after")
728
+ && activityPanelCss.includes('.resizeHandle:hover::after')
729
+ && activityPanelCss.includes('pointer-events: auto')
730
+ && activityPanelCss.includes('width: 28px')
731
+ && activityPanelCss.includes('height: 28px')
732
+ && activityPanelCss.includes('scrollbar-width: thin')
733
+ && !activityPanelCss.includes('scrollbar-width: none'),
734
+ 'interactive panel controls must stay visible to browser verification',
735
+ )
736
+ check(
737
+ 'staged plan editor keeps long plans compact and guards consequential actions',
738
+ stagingPlanSource.includes('aria-expanded={open}')
739
+ && stagingPlanSource.includes('aria-live=')
740
+ && stagingPlanSource.includes('confirmingRemove')
741
+ && !stagingPlanSource.includes('approvalArmed')
742
+ && stagingPlanSource.includes('data-plan-approve')
743
+ && stagingPlanSource.includes('data-confirming')
744
+ && activityPanelCss.includes('.planCardHeader')
745
+ && activityPanelCss.includes('.planFeedback')
746
+ && activityPanelCss.includes('.planApproveRow')
747
+ && activityPanelCss.includes('position: sticky')
748
+ && activityPanelCss.includes('container-type: inline-size')
749
+ && activityPanelCss.includes('@container agent-team')
750
+ && activityPanelCss.includes('.planSectionToggle:focus-visible'),
751
+ 'plan review must expose disclosure, feedback, destructive confirmation, focus, sticky action, and container-based narrow-layout contracts',
752
+ )
753
+ check(
754
+ 'running DAG tasks reuse the animated work glyph without losing focus context',
755
+ activityPanelSource.includes("task.state === 'running'")
756
+ && activityPanelSource.includes('className={css.dagRunningState}')
757
+ && activityPanelSource.includes('<WorkGlyph active />')
758
+ && activityPanelCss.includes(".dagNode[data-state='running'][data-dimmed='true']")
759
+ && activityPanelCss.includes('.dagRunningState {'),
760
+ 'running work should stay visible in both normal and dependency-focus states',
761
+ )
762
+ check(
763
+ 'running tasks surface the assignee model on the activity card',
764
+ activityPanelSource.includes('taskModelLabel(task, members)')
765
+ && activityPanelSource.includes('data-task-model={model || undefined}')
766
+ && activityPanelSource.includes('data-task-model={detailModel}')
767
+ && activityPanelSource.includes('member.status.executingModel')
768
+ && activityPanelSource.includes('css.taskDetailModel')
769
+ && activityPanelSource.includes('css.memberModel')
770
+ && activityPanelCss.includes('.taskDetailModel')
771
+ && activityPanelCss.includes('.memberModel'),
772
+ 'the right-side card must show which model a running subtask is using',
773
+ )
774
+ // Member model badge contract (inline compact pill): the render path derives
775
+ // one full member route and shows only its last segment visibly, while the
776
+ // noninteractive span keeps the full route in title, aria-label, and the
777
+ // data-member-model DOM probe. The badge must sit inside memberLine after the
778
+ // role and before the member state; the old standalone third-line row is gone.
779
+ const memberMapStart = activityPanelSource.indexOf('visibleMembers.map((member) => {')
780
+ const memberBadgeSection = activityPanelSource.slice(
781
+ memberMapStart,
782
+ activityPanelSource.indexOf('css.assignmentLine', memberMapStart),
783
+ )
784
+ check(
785
+ 'member model badge renders compact text inline with full-route metadata',
786
+ memberBadgeSection.includes('compactModelLabel(memberModel)')
787
+ && memberBadgeSection.includes('<span className={css.memberModel}')
788
+ && memberBadgeSection.includes('data-member-model={memberModel}')
789
+ && memberBadgeSection.includes('title={memberModel}')
790
+ && memberBadgeSection.includes('aria-label={memberModel}')
791
+ && memberBadgeSection.includes('role="img"')
792
+ && memberBadgeSection.indexOf('css.memberRole') < memberBadgeSection.indexOf('css.memberModel')
793
+ && memberBadgeSection.indexOf('css.memberModel') < memberBadgeSection.indexOf('css.memberState'),
794
+ 'the badge must be a noninteractive role=img span inside memberLine after role and before member state, carrying the full route in title/aria-label/data-member-model',
795
+ )
796
+ check(
797
+ 'the old separate third-line member model span and locale key are removed',
798
+ !activityPanelSource.includes("t('member.model'")
799
+ && !localesSource.includes("'member.model'"),
800
+ 'the previous standalone model row and its orphaned locale key must not remain',
801
+ )
802
+ check(
803
+ 'delegation list collapses finished members and sorts them by finish time (issue #192)',
804
+ activityPanelSource.includes('orderDelegationMembers(team.members, team.tasks)')
805
+ && activityPanelSource.includes("useState(false)")
806
+ && activityPanelSource.includes("'members.expandFinished'")
807
+ && localesSource.includes("'members.expandFinished'"),
808
+ 'collapsed list must show running members only; expanding shows finished members newest-first',
809
+ )
810
+ const memberModelCssStart = activityPanelCss.indexOf('.memberModel {')
811
+ const memberModelCssBlock = activityPanelCss.slice(
812
+ memberModelCssStart,
813
+ activityPanelCss.indexOf('}', memberModelCssStart) + 1,
814
+ )
815
+ check(
816
+ 'member model badge is a compact neutral inline pill that truncates without overflowing',
817
+ memberModelCssBlock.includes('display: inline-flex')
818
+ && memberModelCssBlock.includes('border-radius: 999px')
819
+ && memberModelCssBlock.includes('background: var(--dsw-alias-button-ghost-active-fill)')
820
+ && memberModelCssBlock.includes('max-width: 132px')
821
+ && memberModelCssBlock.includes('min-width: 0')
822
+ && memberModelCssBlock.includes('overflow: hidden')
823
+ && memberModelCssBlock.includes('text-overflow: ellipsis')
824
+ && memberModelCssBlock.includes('white-space: nowrap'),
825
+ 'the .memberModel pill needs bounded shrinkable width, ellipsis, and neutral fill so long routes never overflow the panel',
826
+ )
827
+ check(
828
+ 'activity polling combines card demand with current-session cold discovery',
829
+ activityPanelSource.includes('if (current === undefined) return')
830
+ && activityPanelSource.includes('startActivityPolling(currentTargets, { discoverySessionId: current })')
831
+ && agentTeamsCardSource.includes('monitorAgentTeam(owner, data.teamId)')
832
+ && !agentTeamsCardSource.includes('setInterval(')
833
+ && !agentTeamsCardSource.includes('fetch('),
834
+ 'the global panel must recover cardless sessions without duplicate card pollers',
835
+ )
836
+
837
+ console.log('2/8 pure rules')
838
+ check("sanitizeKey('My Team!') -> 'my-team'", sanitizeKey('My Team!') === 'my-team')
839
+ // #15: an ASCII-only whitelist folded every non-Latin name onto one constant,
840
+ // so distinct members shared a mailbox file and the second one was rejected as
841
+ // a duplicate. Keys must stay distinct for distinct names, in any script.
842
+ check("CJK names survive folding", sanitizeKey('研究员') === '研究员')
843
+ check(
844
+ 'distinct non-Latin names stay distinct',
845
+ sanitizeKey('研究员') !== sanitizeKey('工程师')
846
+ && sanitizeKey('データ分析') !== sanitizeKey('Данные'),
847
+ )
848
+ check(
849
+ 'names with no letters or digits get distinct keys, not a shared constant',
850
+ sanitizeKey('!!!') !== sanitizeKey('🐳') && sanitizeKey('🐳') !== '',
851
+ )
852
+ check('folding is deterministic', sanitizeKey('🐳') === sanitizeKey('🐳'))
853
+ check(
854
+ 'long names stay inside the filesystem name limit',
855
+ Buffer.byteLength(`${sanitizeKey('研'.repeat(300))}.jsonl`) < 255,
856
+ )
857
+ check(
858
+ 'long names sharing a prefix stay distinct',
859
+ sanitizeKey(`${'研'.repeat(60)}a`) !== sanitizeKey(`${'研'.repeat(60)}b`),
860
+ )
861
+ check(
862
+ 'keys stay a single safe path segment',
863
+ !/[\\/:*?"<>|]/.test(sanitizeKey('a/b\\c:d*e?f"g<h>i|j')) && !sanitizeKey('../../etc').includes('.'),
864
+ )
865
+ check('pending -> claimed allowed', transitionError('pending', 'claimed') === undefined)
866
+ check('pending -> in_progress denied', transitionError('pending', 'in_progress') !== undefined)
867
+ check('in_progress -> completed allowed', transitionError('in_progress', 'completed') === undefined)
868
+ check('completed -> in_progress denied', transitionError('completed', 'in_progress') !== undefined)
869
+ check('same status is a no-op', transitionError('failed', 'failed') === undefined)
870
+
871
+ console.log('3/8 dependency gating')
872
+ const tasks = [
873
+ { id: 't1', status: 'completed' },
874
+ { id: 't2', status: 'pending' },
875
+ { id: 't3', status: 'failed' },
876
+ ]
877
+ check('all-done deps satisfied', unsatisfiedDependencies(tasks, ['t1']).length === 0)
878
+ check('pending dep blocks', unsatisfiedDependencies(tasks, ['t2']).length === 1)
879
+ check('failed dep blocks too', unsatisfiedDependencies(tasks, ['t3']).length === 1)
880
+
881
+ console.log('4/8 on-disk team flow (temp dir)')
882
+ const stateRoot = await mkdtemp(join(tmpdir(), 'dsh-agent-teams-verify-'))
883
+ try {
884
+ const team = {
885
+ name: 'Verify Team',
886
+ id: sanitizeKey('Verify Team'),
887
+ description: 'smoke',
888
+ captainSessionId: 'sess-captain',
889
+ createdAt: Date.now(),
890
+ members: [
891
+ { id: 'sess-member', name: 'alice', joinedAt: Date.now(), status: 'idle' },
892
+ { id: 'sess-removed', name: 'former', joinedAt: Date.now(), status: 'removed' },
893
+ ],
894
+ tasks: [],
895
+ taskSeq: 0,
896
+ }
897
+ await createTeamDir(stateRoot, team)
898
+
899
+ const reread = await readTeam(stateRoot, team.id)
900
+ check('team.json round-trips', reread?.id === team.id && reread.captainSessionId === 'sess-captain')
901
+
902
+ await writeFile(join(stateRoot, team.id, 'team.json'), `\uFEFF${JSON.stringify(team, null, 2)}`, 'utf8')
903
+ check('team.json accepts a UTF-8 BOM', (await readTeam(stateRoot, team.id))?.id === team.id)
904
+
905
+ const dirty = {
906
+ ...team,
907
+ id: 'dirty-profile',
908
+ profile: { name: '' },
909
+ tasks: [{
910
+ id: 't1',
911
+ subject: 'legacy',
912
+ status: 'pending',
913
+ dependencies: [],
914
+ profileSeedId: ' ',
915
+ createdAt: Date.now(),
916
+ updatedAt: Date.now(),
917
+ }],
918
+ taskSeq: 1,
919
+ }
920
+ await mkdir(join(stateRoot, dirty.id, 'inbox'), { recursive: true })
921
+ await writeFile(join(stateRoot, dirty.id, 'team.json'), JSON.stringify(dirty, null, 2), 'utf8')
922
+ const recovered = await readTeam(stateRoot, dirty.id)
923
+ check('cold-resume ignores dirty optional profile and seed id',
924
+ recovered?.id === dirty.id && recovered.profile === undefined && recovered.tasks[0]?.profileSeedId === undefined)
925
+ await removeTeamDir(stateRoot, dirty.id)
926
+
927
+ // Regression for #105: a task persisted with model-materialized blank
928
+ // optional fields (e.g. reviewedTaskId:"") used to brick the whole team on
929
+ // reload. The durable boundary must normalize blanks to omitted instead,
930
+ // while keeping non-blank optional values intact.
931
+ const dirtyQuality = {
932
+ ...team,
933
+ id: 'dirty-quality-fields',
934
+ tasks: [
935
+ {
936
+ id: 't1',
937
+ subject: 'Review impl',
938
+ kind: 'review',
939
+ status: 'pending',
940
+ dependencies: [],
941
+ reviewedTaskId: 't2',
942
+ createdAt: Date.now(),
943
+ updatedAt: Date.now(),
944
+ },
945
+ {
946
+ id: 't2',
947
+ subject: 'Repair with blanks',
948
+ kind: 'repair',
949
+ status: 'pending',
950
+ dependencies: [],
951
+ sourceTaskId: 't1',
952
+ sourceFindingIds: [''],
953
+ reviewedTaskId: '',
954
+ objective: '',
955
+ inScope: ['', 'src/repair.ts'],
956
+ createdAt: Date.now(),
957
+ updatedAt: Date.now(),
958
+ },
959
+ ],
960
+ taskSeq: 2,
961
+ }
962
+ await mkdir(join(stateRoot, dirtyQuality.id, 'inbox'), { recursive: true })
963
+ await writeFile(join(stateRoot, dirtyQuality.id, 'team.json'), JSON.stringify(dirtyQuality, null, 2), 'utf8')
964
+ const recoveredQuality = await readTeam(stateRoot, dirtyQuality.id)
965
+ const repairedTask = recoveredQuality?.tasks.find((item) => item.id === 't2')
966
+ check('cold-resume recovers blank optional quality fields (#105)',
967
+ recoveredQuality?.id === dirtyQuality.id
968
+ && repairedTask?.reviewedTaskId === undefined
969
+ && repairedTask?.objective === undefined
970
+ && repairedTask?.sourceFindingIds === undefined
971
+ && JSON.stringify(repairedTask?.inScope) === JSON.stringify(['src/repair.ts']))
972
+ check('cold-resume keeps non-blank optional quality fields (#105)',
973
+ recoveredQuality?.tasks.find((item) => item.id === 't1')?.reviewedTaskId === 't2')
974
+ await removeTeamDir(stateRoot, dirtyQuality.id)
975
+
976
+ // Recovery only removes blank strings. Other malformed values must still
977
+ // fail durable validation rather than silently erasing contract/scope data.
978
+ for (const [field, values] of [
979
+ ['acceptance', [123, 'real criterion']],
980
+ ['outOfScope', [{ path: 'src/private/' }]],
981
+ ['sourceFindingIds', [null]],
982
+ ]) {
983
+ const malformed = {
984
+ ...dirtyQuality,
985
+ id: `malformed-${field.toLowerCase()}`,
986
+ tasks: [{ ...dirtyQuality.tasks[1], [field]: values }],
987
+ }
988
+ await createTeamDir(stateRoot, malformed)
989
+ let rejected = false
990
+ try { await readTeam(stateRoot, malformed.id) }
991
+ catch (error) { rejected = /invalid AgentTeams state/.test(String(error)) }
992
+ check(`cold-resume rejects non-string ${field} items`, rejected)
993
+ await removeTeamDir(stateRoot, malformed.id)
994
+ }
995
+
996
+ const found = await findTeamByCaptain(stateRoot, 'sess-captain')
997
+ check('findTeamByCaptain finds the team', found?.id === team.id)
998
+ check('findTeamByCaptain ignores other captains', await findTeamByCaptain(stateRoot, 'sess-other') === undefined)
999
+ check('findTeamByParticipant finds the captain', (await findTeamByParticipant(stateRoot, 'sess-captain'))?.id === team.id)
1000
+ check('findTeamByParticipant finds an active member', (await findTeamByParticipant(stateRoot, 'sess-member'))?.id === team.id)
1001
+ check('findTeamByParticipant rejects a removed member', await findTeamByParticipant(stateRoot, 'sess-removed') === undefined)
1002
+
1003
+ const escapedContent = String.raw`save to notes\foo.md`
1004
+ const message = createMessage('alice', CAPTAIN_KEY, escapedContent)
1005
+ await withTeamLock(team.id, async () => {
1006
+ await appendMailbox(stateRoot, team.id, CAPTAIN_KEY, message)
1007
+ })
1008
+ const second = createMessage('bob', CAPTAIN_KEY, 'valid after BOM')
1009
+ const mailboxFile = join(stateRoot, team.id, 'inbox', `${CAPTAIN_KEY}.jsonl`)
1010
+ await writeFile(
1011
+ mailboxFile,
1012
+ `\uFEFF${JSON.stringify(second)}\n${String.raw`{"broken":"notes\q.md"}`}\n{}\n`,
1013
+ { encoding: 'utf8', flag: 'a' },
1014
+ )
1015
+ const malformedLines = []
1016
+ const inbox = await readMailbox(
1017
+ stateRoot,
1018
+ team.id,
1019
+ CAPTAIN_KEY,
1020
+ (lineNumber) => malformedLines.push(lineNumber),
1021
+ )
1022
+ check('mailbox append/read preserves backslashes', inbox[0]?.content === escapedContent)
1023
+ check('mailbox accepts BOM-prefixed JSONL records', inbox[1]?.content === second.content)
1024
+ check('mailbox skips malformed JSON and malformed shapes', inbox.length === 2 && malformedLines.join(',') === '3,4')
1025
+ check('missing mailbox reads empty', (await readMailbox(stateRoot, team.id, 'nobody')).length === 0)
1026
+
1027
+ // The per-team lock queue must stay serial, hand off to later waiters, and
1028
+ // must not leak one resolved promise chain per key after the last waiter.
1029
+ const serialKey = 'lock-cleanup:serial'
1030
+ const order = []
1031
+ let inside = 0
1032
+ let maxInside = 0
1033
+ await Promise.all(Array.from({ length: 25 }, (_, index) => withTeamLock(serialKey, async () => {
1034
+ inside += 1
1035
+ maxInside = Math.max(maxInside, inside)
1036
+ order.push(index)
1037
+ await new Promise((resolve) => setTimeout(resolve, index % 3 === 0 ? 5 : 1))
1038
+ inside -= 1
1039
+ })))
1040
+ check('withTeamLock keeps same-key workers strictly serial and ordered',
1041
+ maxInside === 1 && order.join(',') === Array.from({ length: 25 }, (_, index) => index).join(','))
1042
+ check('withTeamLock queue entry drains after the last waiter settles',
1043
+ !teamLockQueueKeys().includes(serialKey))
1044
+
1045
+ const handoffKey = 'lock-cleanup:handoff'
1046
+ let releaseHold
1047
+ const heldGate = new Promise((resolve) => { releaseHold = resolve })
1048
+ let successorEntered = false
1049
+ const hold = withTeamLock(handoffKey, async () => { await heldGate })
1050
+ const successor = withTeamLock(handoffKey, async () => { successorEntered = true })
1051
+ await new Promise((resolve) => setTimeout(resolve, 20))
1052
+ check('withTeamLock keeps its queue entry while the lock is held or handed off',
1053
+ teamLockQueueKeys().includes(handoffKey))
1054
+ releaseHold()
1055
+ await Promise.all([hold, successor])
1056
+ check('withTeamLock wakes the queued successor and drops the key afterwards',
1057
+ successorEntered && !teamLockQueueKeys().includes(handoffKey))
1058
+
1059
+ const duplicateCaptain = { ...team, id: 'duplicate-captain', members: [] }
1060
+ await createTeamDir(stateRoot, duplicateCaptain)
1061
+ let duplicateCaptainRejected = false
1062
+ try {
1063
+ await findTeamByCaptain(stateRoot, 'sess-captain')
1064
+ } catch {
1065
+ duplicateCaptainRejected = true
1066
+ }
1067
+ check('multiple teams for one captain fail as ambiguous', duplicateCaptainRejected)
1068
+ await removeTeamDir(stateRoot, duplicateCaptain.id)
1069
+
1070
+ const duplicateMember = { ...team, id: 'duplicate-member', captainSessionId: 'sess-other-captain' }
1071
+ await createTeamDir(stateRoot, duplicateMember)
1072
+ let duplicateMemberRejected = false
1073
+ try {
1074
+ await findTeamByParticipant(stateRoot, 'sess-member')
1075
+ } catch {
1076
+ duplicateMemberRejected = true
1077
+ }
1078
+ check('multiple teams for one member fail as ambiguous', duplicateMemberRejected)
1079
+ await removeTeamDir(stateRoot, duplicateMember.id)
1080
+
1081
+ const invalidId = 'invalid-shape'
1082
+ await mkdir(join(stateRoot, invalidId), { recursive: true })
1083
+ await writeFile(join(stateRoot, invalidId, 'team.json'), '{}', 'utf8')
1084
+ let invalidShapeRejected = false
1085
+ try {
1086
+ await readTeam(stateRoot, invalidId)
1087
+ } catch {
1088
+ invalidShapeRejected = true
1089
+ }
1090
+ check('invalid team.json shape is rejected at the durable boundary', invalidShapeRejected)
1091
+ await removeTeamDir(stateRoot, invalidId)
1092
+
1093
+ await removeTeamDir(stateRoot, team.id)
1094
+ check('removeTeamDir removes the team', await readTeam(stateRoot, team.id) === undefined)
1095
+
1096
+ // Archive keeps the team data for post-delete review.
1097
+ const archiveTeam = { ...team, id: sanitizeKey('Archive Team') }
1098
+ await createTeamDir(stateRoot, archiveTeam)
1099
+ const { archiveTeamDir, readArchivedTeam, listArchivedTeamIds } = await import('../lib/state.js')
1100
+ await archiveTeamDir(stateRoot, archiveTeam.id)
1101
+ check('archive moves the team out of live scan', await readTeam(stateRoot, archiveTeam.id) === undefined)
1102
+ check('archive keeps team.json readable', (await readArchivedTeam(stateRoot, archiveTeam.id))?.id === archiveTeam.id)
1103
+ check('archive lists the team id', (await listArchivedTeamIds(stateRoot)).includes(archiveTeam.id))
1104
+ check('archive dir skips live readTeam', await readTeam(stateRoot, 'archive') === undefined)
1105
+ } finally {
1106
+ await rm(stateRoot, { recursive: true, force: true })
1107
+ }
1108
+
1109
+ console.log('5/8 host visual-state functions (activity panel)')
1110
+ const { taskVisualState, taskDepthsById } = await import('../lib/state.js')
1111
+ const vtasks = [
1112
+ { id: 't1', subject: 'a', status: 'completed', assignee: 'alice', dependencies: [], createdAt: 0, updatedAt: 0 },
1113
+ { id: 't2', subject: 'b', status: 'pending', assignee: 'bob', dependencies: ['t1'], createdAt: 0, updatedAt: 0 },
1114
+ { id: 't3', subject: 'c', status: 'in_progress', assignee: 'bob', dependencies: ['t2'], createdAt: 0, updatedAt: 0 },
1115
+ { id: 't4', subject: 'd', status: 'pending', assignee: 'alice', dependencies: ['t9'], createdAt: 0, updatedAt: 0 },
1116
+ ]
1117
+ check('completed -> completed visual state', taskVisualState('completed', [], vtasks) === 'completed')
1118
+ check('failed -> failed visual state', taskVisualState('failed', [], vtasks) === 'failed')
1119
+ check('cancelled -> cancelled visual state', taskVisualState('cancelled', [], vtasks) === 'cancelled')
1120
+ check('in_progress -> running visual state', taskVisualState('in_progress', [], vtasks) === 'running')
1121
+ check('pending with completed dep -> open', taskVisualState('pending', ['t1'], vtasks) === 'open')
1122
+ check('pending with open dep -> blocked', taskVisualState('pending', ['t2'], vtasks) === 'blocked')
1123
+ check('missing dependency is ignored (not blocked)', taskVisualState('pending', ['t9'], vtasks) === 'open')
1124
+ const depths = taskDepthsById(vtasks)
1125
+ check('t1 depth 0', depths.get('t1') === 0)
1126
+ check('t2 depth 1 (longest path)', depths.get('t2') === 1)
1127
+ check('t3 depth 2', depths.get('t3') === 2)
1128
+ check('missing dep contributes no depth', depths.get('t4') === 0)
1129
+
1130
+ console.log('6/8 client relationship projections')
1131
+ const projectionTasks = [
1132
+ { id: 't4', dependencies: ['t2'], depth: 2 },
1133
+ { id: 't1', dependencies: [], depth: 0 },
1134
+ { id: 't3', dependencies: ['t1'], depth: 1 },
1135
+ { id: 't2', dependencies: ['t1'], depth: 1 },
1136
+ { id: 't5', dependencies: [], depth: Number.NaN },
1137
+ ]
1138
+ const stages = taskStages(projectionTasks)
1139
+ check('task stages sort by depth', stages.map(stage => stage.depth).join(',') === '0,1,2')
1140
+ check('task stages sort ids naturally', stages[1]?.tasks.map(task => task.id).join(',') === 't2,t3')
1141
+ check('non-finite depth falls back to stage 0', stages[0]?.tasks.some(task => task.id === 't5') === true)
1142
+ const chain = relatedTaskIds('t2', projectionTasks)
1143
+ check('relationship chain includes upstream dependency', chain.has('t1'))
1144
+ check('relationship chain includes focused task', chain.has('t2'))
1145
+ check('relationship chain includes downstream dependent', chain.has('t4'))
1146
+ check('relationship chain excludes sibling branch', !chain.has('t3'))
1147
+ check(
1148
+ 'pinned dependency chain wins over keyboard and hover previews',
1149
+ dependencyFocusTaskId('pinned', 'keyboard', 'hover') === 'pinned',
1150
+ )
1151
+ check(
1152
+ 'keyboard dependency chain wins over delayed hover preview',
1153
+ dependencyFocusTaskId(null, 'keyboard', 'hover') === 'keyboard',
1154
+ )
1155
+ check(
1156
+ 'hover dependency chain is used without a pinned or keyboard task',
1157
+ dependencyFocusTaskId(null, null, 'hover') === 'hover',
1158
+ )
1159
+ const cyclic = [
1160
+ { id: 'a', dependencies: ['b'], depth: 0 },
1161
+ { id: 'b', dependencies: ['a'], depth: 1 },
1162
+ ]
1163
+ check('relationship traversal is cycle-safe', relatedTaskIds('a', cyclic).size === 2)
1164
+ check('edge-free tasks switch to the fill-width parallel grid', usesParallelTaskGrid([
1165
+ { id: 't1', dependencies: [], depth: 0 },
1166
+ { id: 't2', dependencies: [], depth: 0 },
1167
+ { id: 't3', dependencies: ['missing'], depth: 0 },
1168
+ ]))
1169
+ const liveTeam = {
1170
+ captainSessionId: 'captain-1',
1171
+ members: [{ name: 'analyst', status: 'working', activity: 'working', currentTask: 't1' }],
1172
+ tasks: [{ id: 't1', subject: 'Clarify requirements', status: 'in_progress' }],
1173
+ }
1174
+ check('live captain team is selected only for the current session', liveCaptainTeam([liveTeam], 'captain-1') === liveTeam)
1175
+ check('halted captain team is hidden from the composer banner', liveCaptainTeam([{ ...liveTeam, halted: true }], 'captain-1') === undefined)
1176
+ check('active team with working members stays visible', teamIsActive(liveTeam) === true)
1177
+ check('planning roster with no tasks still shows the banner', teamIsActive({
1178
+ members: [{ name: 'analyst', status: 'idle', activity: 'idle' }],
1179
+ tasks: [],
1180
+ }) === true)
1181
+ check('halted team is not active', teamIsActive({ ...liveTeam, halted: true }) === false)
1182
+ check('staged team is not presented as actively executing', teamIsActive({ ...liveTeam, phase: 'staged' }) === false)
1183
+ check('settled failed/completed team is not waiting to be scheduled', teamIsActive({
1184
+ members: [{ name: 'analyst', status: 'idle', activity: 'idle' }],
1185
+ tasks: [
1186
+ { id: 't1', status: 'completed' },
1187
+ { id: 't2', status: 'failed' },
1188
+ ],
1189
+ }) === false)
1190
+ check('progress summary prefers running task titles', teamProgressSummary(liveTeam, '、').detail === 'Clarify requirements')
1191
+ check('delegation list keeps running members first in snapshot order', orderDelegationMembers([
1192
+ { name: 'finished-b', activity: 'idle' },
1193
+ { name: 'running-a', activity: 'working' },
1194
+ { name: 'finished-a', activity: 'idle' },
1195
+ ], [
1196
+ { assignee: 'finished-a', status: 'completed', updatedAt: 20 },
1197
+ { assignee: 'finished-b', status: 'completed', updatedAt: 10 },
1198
+ { assignee: 'running-a', status: 'in_progress', updatedAt: 5 },
1199
+ ]).map((member) => member.name).join(',') === 'running-a,finished-a,finished-b')
1200
+ check('delegation list sorts finished members by finish time, newest first', orderDelegationMembers([
1201
+ { name: 'old', activity: 'idle' },
1202
+ { name: 'new', activity: 'idle' },
1203
+ { name: 'unstamped', activity: 'idle' },
1204
+ ], [
1205
+ { assignee: 'old', status: 'failed', updatedAt: 3 },
1206
+ { assignee: 'new', status: 'cancelled', updatedAt: 9 },
1207
+ ]).map((member) => member.name).join(',') === 'new,old,unstamped')
1208
+ check('member finish time ignores open tasks and missing stamps', memberFinishedAt('solo', [
1209
+ { assignee: 'solo', status: 'in_progress', updatedAt: 99 },
1210
+ { assignee: 'solo', status: 'completed' },
1211
+ ]) === undefined && memberFinishedAt('solo', [
1212
+ { assignee: 'solo', status: 'completed', updatedAt: 7 },
1213
+ { assignee: 'other', status: 'completed', updatedAt: 50 },
1214
+ ]) === 7)
1215
+ check('a real dependency keeps the layered DAG layout', !usesParallelTaskGrid([
1216
+ { id: 't1', dependencies: [], depth: 0 },
1217
+ { id: 't2', dependencies: ['t1'], depth: 1 },
1218
+ ]))
1219
+ const dag = compactDagLayout(projectionTasks.filter(task => Number.isFinite(task.depth)))
1220
+ check('compact DAG lays dependency depths out left-to-right',
1221
+ dag.nodes.find(node => node.task.id === 't1')?.x === 0
1222
+ && dag.nodes.find(node => node.task.id === 't2')?.x === 118
1223
+ && dag.nodes.find(node => node.task.id === 't4')?.x === 236)
1224
+ check('compact DAG keeps stable rows and reference node geometry',
1225
+ dag.nodes.find(node => node.task.id === 't3')?.y === 38
1226
+ && dag.width === 328
1227
+ && dag.height === 68
1228
+ && COMPACT_DAG_NODE_WIDTH === 92
1229
+ && COMPACT_DAG_NODE_HEIGHT === 30)
1230
+ check('compact DAG emits one curved SVG edge per valid dependency',
1231
+ dag.edges.length === 3
1232
+ && dag.edges.some(edge => edge.from === 't1' && edge.to === 't2' && edge.path.startsWith('M92 15C')))
1233
+ check(
1234
+ 'task model labels prefer the snapshot field and fall back to the assignee route',
1235
+ memberRouteLabel({ provider: 'openai', model: 'gpt-5.6-sol' }) === 'openai/gpt-5.6-sol'
1236
+ && memberRouteLabel({ model: 'grok-4.6' }) === 'grok-4.6'
1237
+ && compactModelLabel('openai/gpt-5.6-sol') === 'gpt-5.6-sol'
1238
+ && taskModelLabel({ assignee: 'analyst', model: 'openai/gpt-5.6-sol' }, []) === 'openai/gpt-5.6-sol'
1239
+ && taskModelLabel({ assignee: 'analyst' }, [{ name: 'analyst', provider: 'grok', model: 'grok-4.5' }]) === 'grok/grok-4.5'
1240
+ && taskModelLabel({ assignee: 'analyst' }, []) === '',
1241
+ )
1242
+ check(
1243
+ 'existing member route helpers retain expanded fallback regression coverage',
1244
+ memberRouteLabel({ provider: 'openai', model: 'gpt-5.6-sol' }) === 'openai/gpt-5.6-sol'
1245
+ && compactModelLabel('openai/gpt-5.6-sol') === 'gpt-5.6-sol'
1246
+ && memberRouteLabel({ model: 'grok-4.6' }) === 'grok-4.6'
1247
+ && compactModelLabel('grok-4.6') === 'grok-4.6'
1248
+ && memberRouteLabel({}) === ''
1249
+ && memberRouteLabel(undefined) === ''
1250
+ && compactModelLabel('') === ''
1251
+ && compactModelLabel(' ') === ''
1252
+ && memberRouteLabel({ provider: ' openai ', model: ' gpt-5.6-sol ' }) === 'openai/gpt-5.6-sol'
1253
+ && memberRouteLabel({ provider: ' ', model: ' gpt-5.6-sol ' }) === 'gpt-5.6-sol'
1254
+ && compactModelLabel(' openai/gpt-5.6-sol ') === 'gpt-5.6-sol'
1255
+ && memberRouteLabel({ provider: 'openai/org', model: 'gpt-5.6-sol' }) === 'openai/org/gpt-5.6-sol'
1256
+ && compactModelLabel('openai/org/gpt-5.6-sol') === 'gpt-5.6-sol',
1257
+ )
1258
+ const panelBounds = { width: 1440, height: 900, anchorRight: 1440 }
1259
+ const dockedPanel = resolvePanelGeometry(DEFAULT_PANEL_LAYOUT, panelBounds)
1260
+ check('docked panel follows the shell anchor and retains an available-height ceiling',
1261
+ dockedPanel.mode === 'docked'
1262
+ && dockedPanel.x === 1034
1263
+ && dockedPanel.y === 64
1264
+ && dockedPanel.width === 388
1265
+ && dockedPanel.height === 788
1266
+ && dockedPanel.heightMode === 'auto'
1267
+ && panelUsesAutoHeight(dockedPanel, panelBounds)
1268
+ && panelMaximumHeight(dockedPanel, panelBounds) === 788)
1269
+ const floatingPanel = floatPanelLayout(dockedPanel, panelBounds)
1270
+ const movedPanel = movePanelLayout(floatingPanel, 999, 999, panelBounds)
1271
+ check('floating panel movement clamps every edge inside the shell',
1272
+ movedPanel.mode === 'floating' && movedPanel.x === 1040 && movedPanel.y === 100)
1273
+ const widerDockedPanel = resizePanelLayout(dockedPanel, 'left', -120, 0, panelBounds)
1274
+ check('docked left-edge resize preserves the right anchor',
1275
+ widerDockedPanel.width === 508 && widerDockedPanel.x === 914)
1276
+ const narrowerFloatingPanel = resizePanelLayout(floatingPanel, 'left', 200, 0, panelBounds)
1277
+ check('floating left-edge resize preserves the opposite edge at minimum width',
1278
+ narrowerFloatingPanel.width === 320 && narrowerFloatingPanel.x === 1102)
1279
+ const cornerPanel = resizePanelLayout({ ...floatingPanel, x: 400, y: 200, width: 388, height: 500 }, 'corner', 1200, 1200, panelBounds)
1280
+ check('floating corner resize preserves its top-left anchor at shell limits',
1281
+ cornerPanel.x === 400 && cornerPanel.y === 200
1282
+ && cornerPanel.width === 640 && cornerPanel.height === 688
1283
+ && cornerPanel.heightMode === 'manual'
1284
+ && !panelUsesAutoHeight(cornerPanel, panelBounds))
1285
+ const bottomPanel = resizePanelLayout({ ...floatingPanel, x: 400, y: 200, width: 388, height: 500 }, 'bottom', 0, 1200, panelBounds)
1286
+ check('floating bottom resize preserves its top edge at the shell limit',
1287
+ bottomPanel.y === 200 && bottomPanel.height === 688
1288
+ && bottomPanel.heightMode === 'manual')
1289
+ const redockedPanel = dockPanelLayout({ ...floatingPanel, width: 472, x: 120, y: 100, heightMode: 'manual' }, panelBounds)
1290
+ check('dock toggle preserves width while restoring shell alignment and content-fit height',
1291
+ redockedPanel.x === 950 && redockedPanel.width === 472 && redockedPanel.heightMode === 'auto')
1292
+ const compactBounds = { width: 900, height: 700, anchorRight: 900 }
1293
+ const compactPanel = resolvePanelGeometry(floatingPanel, compactBounds)
1294
+ check('compact shell disables free geometry and uses a balanced inset',
1295
+ compactPanelForBounds(compactBounds)
1296
+ && compactPanel.x === 12 && compactPanel.y === 12
1297
+ && compactPanel.width === 876 && compactPanel.height === 676
1298
+ && panelUsesAutoHeight({ ...compactPanel, heightMode: 'manual' }, compactBounds)
1299
+ && panelMaximumHeight(compactPanel, compactBounds) === 676)
1300
+ check('persisted panel state rejects corrupt or partial values',
1301
+ parsePanelLayout('{"mode":"floating","x":1}').mode === 'docked'
1302
+ && parsePanelLayout('not-json').mode === 'docked')
1303
+ const migratedPanel = parsePanelLayout('{"mode":"floating","x":120,"y":80,"width":420,"height":600}')
1304
+ const manualPanel = parsePanelLayout('{"mode":"floating","x":120,"y":80,"width":420,"height":600,"heightMode":"manual"}')
1305
+ const legacyDockedManualPanel = parsePanelLayout('{"mode":"docked","x":120,"y":80,"width":420,"height":600,"heightMode":"manual"}')
1306
+ check('persisted panel height migrates to auto but preserves explicit manual sizing',
1307
+ migratedPanel.heightMode === 'auto'
1308
+ && panelUsesAutoHeight(migratedPanel, panelBounds)
1309
+ && manualPanel.heightMode === 'manual'
1310
+ && !panelUsesAutoHeight(manualPanel, panelBounds)
1311
+ && legacyDockedManualPanel.heightMode === 'auto')
1312
+ check(
1313
+ 'expanded activity panel belongs only to its current session',
1314
+ activityPanelExpandedForSession(true, 'session-a', 'session-a')
1315
+ && !activityPanelExpandedForSession(true, 'session-a', 'session-b')
1316
+ && !activityPanelExpandedForSession(true, 'session-a', undefined),
1317
+ )
1318
+ check(
1319
+ 'restored live activity stays collapsed when a conversation is reopened',
1320
+ !activityPanelShouldAutoExpand({
1321
+ alreadyAutoOpened: false,
1322
+ pageSettled: true,
1323
+ restoreComplete: true,
1324
+ previousLiveTeamIds: new Set(['restored-team']),
1325
+ currentLiveTeamIds: ['restored-team'],
1326
+ }),
1327
+ )
1328
+ check(
1329
+ 'archived-only conversation restore never auto-expands the activity panel',
1330
+ !activityPanelShouldAutoExpand({
1331
+ alreadyAutoOpened: false,
1332
+ pageSettled: true,
1333
+ restoreComplete: true,
1334
+ previousLiveTeamIds: new Set(),
1335
+ currentLiveTeamIds: [],
1336
+ }),
1337
+ )
1338
+ check(
1339
+ 'a new live team appearing after restore still auto-expands once',
1340
+ activityPanelShouldAutoExpand({
1341
+ alreadyAutoOpened: false,
1342
+ pageSettled: true,
1343
+ restoreComplete: true,
1344
+ previousLiveTeamIds: new Set(),
1345
+ currentLiveTeamIds: ['new-team'],
1346
+ }) && !activityPanelShouldAutoExpand({
1347
+ alreadyAutoOpened: true,
1348
+ pageSettled: true,
1349
+ restoreComplete: true,
1350
+ previousLiveTeamIds: new Set(),
1351
+ currentLiveTeamIds: ['new-team'],
1352
+ }),
1353
+ )
1354
+ let monitorNotifications = 0
1355
+ const unsubscribeMonitor = subscribeActivityMonitorTargets(() => { monitorNotifications += 1 })
1356
+ const releaseMonitorOne = monitorAgentTeam('verify-session', 'verify-team')
1357
+ const releaseMonitorTwo = monitorAgentTeam('verify-session', 'verify-team')
1358
+ const registeredMonitor = getActivityMonitorTargetsSnapshot()[0]
1359
+ check(
1360
+ 'activity monitor coalesces duplicate cards into one shared target',
1361
+ getActivityMonitorTargetsSnapshot().length === 1
1362
+ && registeredMonitor?.sessionId === 'verify-session'
1363
+ && registeredMonitor.teamId === 'verify-team',
1364
+ )
1365
+ releaseMonitorOne()
1366
+ check('one card cleanup keeps another card monitoring', getActivityMonitorTargetsSnapshot().length === 1)
1367
+ if (registeredMonitor !== undefined) settleActivityMonitorTargets(new Set([registeredMonitor.key]))
1368
+ check('archived targets retire from polling', getActivityMonitorTargetsSnapshot().length === 0)
1369
+ releaseMonitorTwo()
1370
+ unsubscribeMonitor()
1371
+ check('activity monitor publishes lifecycle changes without duplicate-card churn', monitorNotifications === 2)
1372
+
1373
+ let dormantFetches = 0
1374
+ let dormantSchedules = 0
1375
+ const dormantPoller = startActivityPolling([], {
1376
+ fetchState: async () => {
1377
+ dormantFetches += 1
1378
+ return { ok: true, json: async () => ({ teams: [] }) }
1379
+ },
1380
+ schedule: () => {
1381
+ dormantSchedules += 1
1382
+ return 0
1383
+ },
1384
+ })
1385
+ await dormantPoller.firstTick
1386
+ dormantPoller.stop()
1387
+ check(
1388
+ 'no monitor targets create no request and no timer',
1389
+ dormantFetches === 0 && dormantSchedules === 0,
1390
+ )
1391
+
1392
+ const discoveryUrls = []
1393
+ const coldLiveUrl = '/plugins/dsh-agent-teams/state?session=cold-captain&summary=1'
1394
+ const discoveryIntervals = []
1395
+ let scheduledDiscoveryTick
1396
+ const discoveryPoller = startActivityPolling([], {
1397
+ discoverySessionId: 'cold-captain',
1398
+ fetchState: async (url) => {
1399
+ discoveryUrls.push(url)
1400
+ return { ok: true, json: async () => ({ teams: [] }) }
1401
+ },
1402
+ schedule: (callback, intervalMs) => {
1403
+ scheduledDiscoveryTick = callback
1404
+ discoveryIntervals.push(intervalMs)
1405
+ return 'discovery-timer'
1406
+ },
1407
+ cancel: () => {},
1408
+ publishSnapshots: () => {},
1409
+ })
1410
+ await discoveryPoller.firstTick
1411
+ scheduledDiscoveryTick?.()
1412
+ await new Promise((resolve) => setImmediate(resolve))
1413
+ discoveryPoller.stop()
1414
+ check(
1415
+ 'a cardless cold session restores live and archive once, then probes at the discovery cadence',
1416
+ discoveryUrls.length === 3
1417
+ && discoveryUrls[0] === coldLiveUrl
1418
+ && discoveryUrls[1] === '/plugins/dsh-agent-teams/state?archived=1&session=cold-captain'
1419
+ && discoveryUrls[2] === coldLiveUrl
1420
+ && discoveryIntervals.length === 1
1421
+ && discoveryIntervals[0] === ACTIVITY_PROBE_MS,
1422
+ )
1423
+
1424
+ // Regression (GitHub #57): a team created AFTER the cold-start discovery pass
1425
+ // (e.g. a run_code-wrapped agent_teams_create) must be discovered without a
1426
+ // manual reload. The controller keeps probing while its discovery session owns
1427
+ // no team yet, so a later team is published — and once found, the probe
1428
+ // upgrades to the live cadence so the panel stays fresh.
1429
+ const latePublished = []
1430
+ const lateUrls = []
1431
+ const lateIntervals = []
1432
+ let lateLiveTeams = []
1433
+ let lateTick = () => {}
1434
+ const latePoller = startActivityPolling([], {
1435
+ discoverySessionId: 'cold-captain',
1436
+ fetchState: async (url) => {
1437
+ lateUrls.push(url)
1438
+ if (url === coldLiveUrl) {
1439
+ return { ok: true, json: async () => ({ teams: lateLiveTeams }) }
1440
+ }
1441
+ return { ok: true, json: async () => ({ teams: [] }) }
1442
+ },
1443
+ schedule: (callback, intervalMs) => {
1444
+ lateTick = callback
1445
+ lateIntervals.push(intervalMs)
1446
+ return 'late-timer'
1447
+ },
1448
+ cancel: () => {},
1449
+ publishSnapshots: (update) => { latePublished.push(update) },
1450
+ })
1451
+ await latePoller.firstTick
1452
+ lateTick()
1453
+ await new Promise((resolve) => setImmediate(resolve))
1454
+ check(
1455
+ 'a cardless session keeps probing at the discovery cadence after an empty first pass',
1456
+ lateUrls.length === 3
1457
+ && lateIntervals.length === 1
1458
+ && lateIntervals[0] === ACTIVITY_PROBE_MS,
1459
+ )
1460
+ lateLiveTeams = [{
1461
+ workspace: '',
1462
+ teamId: 'post-discovery-team',
1463
+ name: 'Post Discovery Team',
1464
+ captainSessionId: 'cold-captain',
1465
+ members: [],
1466
+ tasks: [],
1467
+ messageCount: 0,
1468
+ captainInbox: [],
1469
+ }]
1470
+ lateTick()
1471
+ await new Promise((resolve) => setImmediate(resolve))
1472
+ latePoller.stop()
1473
+ check(
1474
+ 'a team created after the discovery pass is picked up without a reload and upgrades to the live cadence',
1475
+ lateUrls.length === 4
1476
+ && latePublished.some((update) => update.teams?.some((team) => team.teamId === 'post-discovery-team'))
1477
+ && lateIntervals.length === 2
1478
+ && lateIntervals[1] === ACTIVITY_POLL_MS,
1479
+ )
1480
+
1481
+ // Explicit card targets are demanded work: they start at the live cadence and
1482
+ // are never downgraded to the low-frequency probe.
1483
+ const cardIntervals = []
1484
+ const cardPoller = startActivityPolling([{
1485
+ key: 'card-target',
1486
+ sessionId: 'card-session',
1487
+ teamId: 'card-team',
1488
+ }], {
1489
+ fetchState: async () => ({ ok: true, json: async () => ({ teams: [] }) }),
1490
+ schedule: (_callback, intervalMs) => {
1491
+ cardIntervals.push(intervalMs)
1492
+ return 'card-timer'
1493
+ },
1494
+ cancel: () => {},
1495
+ publishSnapshots: () => {},
1496
+ })
1497
+ await cardPoller.firstTick
1498
+ cardPoller.stop()
1499
+ check(
1500
+ 'explicit card targets poll at the live cadence from the start',
1501
+ cardIntervals.length === 1 && cardIntervals[0] === ACTIVITY_POLL_MS,
1502
+ )
1503
+
1504
+ const pollTarget = { key: 'poll-target', sessionId: 'poll-session', teamId: 'poll-team' }
1505
+ let resolveSlowLive
1506
+ const slowLive = new Promise((resolve) => { resolveSlowLive = resolve })
1507
+ const slowFetchSignals = []
1508
+ let slowFetchCount = 0
1509
+ let scheduledTick
1510
+ let cancelledTimer = false
1511
+ let latePublications = 0
1512
+ const slowPoller = startActivityPolling([pollTarget], {
1513
+ fetchState: async (_url, init) => {
1514
+ slowFetchCount += 1
1515
+ slowFetchSignals.push(init.signal)
1516
+ return slowLive
1517
+ },
1518
+ schedule: (callback) => {
1519
+ scheduledTick = callback
1520
+ return 'slow-timer'
1521
+ },
1522
+ cancel: (timer) => { cancelledTimer = timer === 'slow-timer' },
1523
+ publishSnapshots: () => { latePublications += 1 },
1524
+ })
1525
+ scheduledTick?.()
1526
+ scheduledTick?.()
1527
+ await Promise.resolve()
1528
+ check('a slow state request never overlaps the next interval', slowFetchCount === 1)
1529
+ slowPoller.stop()
1530
+ check(
1531
+ 'stopping activity polling clears its timer and aborts the in-flight request',
1532
+ cancelledTimer && slowFetchSignals[0]?.aborted === true,
1533
+ )
1534
+ resolveSlowLive?.({ ok: true, json: async () => ({ teams: [] }) })
1535
+ await slowPoller.firstTick
1536
+ check('a late response after stop cannot publish snapshots', latePublications === 0)
1537
+
1538
+ const fallbackUrls = []
1539
+ const settledFallbackKeys = []
1540
+ let fallbackResponseIndex = 0
1541
+ const fallbackResponses = [
1542
+ { ok: true, json: async () => ({ teams: [] }) },
1543
+ { ok: true, json: async () => ({ teams: [] }) },
1544
+ ]
1545
+ const fallbackPoller = startActivityPolling([pollTarget], {
1546
+ fetchState: async (url) => {
1547
+ fallbackUrls.push(url)
1548
+ return fallbackResponses[fallbackResponseIndex++]
1549
+ },
1550
+ schedule: () => 'fallback-timer',
1551
+ cancel: () => {},
1552
+ publishSnapshots: () => {},
1553
+ settleTargets: (keys) => { settledFallbackKeys.push(...keys) },
1554
+ })
1555
+ await fallbackPoller.firstTick
1556
+ fallbackPoller.stop()
1557
+ check(
1558
+ 'a live miss checks archive once and retires even an orphaned legacy card',
1559
+ fallbackUrls.length === 2
1560
+ && fallbackUrls[1] === '/plugins/dsh-agent-teams/state?archived=1&session=poll-session'
1561
+ && settledFallbackKeys.length === 1
1562
+ && settledFallbackKeys[0] === pollTarget.key,
1563
+ )
1564
+ const navigationCalls = []
1565
+ const addressedNavigation = await openAgentTeamMember({
1566
+ open: (id) => { navigationCalls.push(['open', id]) },
1567
+ refreshSubagents: async (id) => { navigationCalls.push(['refresh', id]) },
1568
+ subagentAddress: () => undefined,
1569
+ openSubagent: (address) => { navigationCalls.push(['openSubagent', address]) },
1570
+ }, 'captain-session', 'member-session')
1571
+ check(
1572
+ 'rc.8 member navigation refreshes the parent catalog and opens an addressed continuable child',
1573
+ addressedNavigation === 'subagent'
1574
+ && navigationCalls[0]?.[0] === 'refresh'
1575
+ && navigationCalls[1]?.[0] === 'openSubagent'
1576
+ && navigationCalls[1]?.[1]?.parentSessionId === 'captain-session'
1577
+ && navigationCalls[1]?.[1]?.childSessionId === 'member-session'
1578
+ && navigationCalls[1]?.[1]?.mode === 'continuable',
1579
+ )
1580
+ const legacyNavigationCalls = []
1581
+ const legacyNavigation = await openAgentTeamMember({
1582
+ open: (id) => { legacyNavigationCalls.push(id) },
1583
+ }, 'captain-session', 'member-session')
1584
+ check(
1585
+ 'pre-rc.8 member navigation keeps the ordinary session fallback',
1586
+ legacyNavigation === 'session' && legacyNavigationCalls[0] === 'member-session',
1587
+ )
1588
+ const panelNavigationCalls = []
1589
+ await openAgentTeamMember({
1590
+ open() { throw new Error('expected addressed navigation') },
1591
+ refreshSubagents: async () => {},
1592
+ openSubagent: () => panelNavigationCalls.push('member'),
1593
+ }, 'captain-session', 'member-session', {
1594
+ beginNavigation: () => new AbortController().signal,
1595
+ selectPanel: id => panelNavigationCalls.push(id),
1596
+ })
1597
+ check('0.1.5 member navigation selects the Conversation after opening its transcript',
1598
+ JSON.stringify(panelNavigationCalls) === JSON.stringify(['member', null]))
1599
+ const supersededNavigation = new AbortController()
1600
+ const cancelledNavigation = await openAgentTeamMember({
1601
+ open() { throw new Error('cancelled navigation must not open a Session') },
1602
+ refreshSubagents: async () => { supersededNavigation.abort() },
1603
+ openSubagent() { throw new Error('cancelled refresh must not steal the current Session') },
1604
+ }, 'captain-session', 'member-session', {
1605
+ beginNavigation: () => supersededNavigation.signal,
1606
+ selectPanel() { throw new Error('cancelled navigation must not change main panel') },
1607
+ })
1608
+ check('0.1.5 superseded catalog refresh cannot steal navigation', cancelledNavigation === 'cancelled')
1609
+ check(
1610
+ 'agent team cards derive a stable id from the standard create tool call',
1611
+ JSON.stringify(parseAgentTeamsCreateArgs('{"name":" Repo Review 2W! "}'))
1612
+ === JSON.stringify({ teamId: 'repo-review-2w', name: 'Repo Review 2W!' }),
1613
+ )
1614
+ check('malformed create tool arguments do not create a card', parseAgentTeamsCreateArgs('{bad') === undefined)
1615
+
1616
+ const captainDeliveries = []
1617
+ const captainSteered = steerCaptainReport(
1618
+ { steer: message => captainDeliveries.push(message) },
1619
+ 'alice',
1620
+ 'finished t1',
1621
+ )
1622
+ check(
1623
+ 'member report delivery calls the live captain steer API',
1624
+ captainSteered
1625
+ && captainDeliveries.length === 1
1626
+ && captainDeliveries[0]?.content[0]?.type === 'text'
1627
+ && captainDeliveries[0]?.content[0]?.text === 'AgentTeams message from member alice:\n\nfinished t1',
1628
+ )
1629
+ check(
1630
+ 'failed live captain delivery falls back to the durable mailbox',
1631
+ steerCaptainReport({ steer: () => { throw new Error('offline') } }, 'alice', 'finished t1') === false,
1632
+ )
1633
+
1634
+ console.log('7/8 member model selection and continuation restore')
1635
+ const captain = {
1636
+ id: 'captain-session',
1637
+ options: { provider: 'birth-provider', model: 'birth-model' },
1638
+ session: {
1639
+ requestHeader: () => ({
1640
+ config: {
1641
+ provider: 'captain-provider',
1642
+ model: 'captain-model',
1643
+ reasoningEffort: 'max',
1644
+ },
1645
+ }),
1646
+ },
1647
+ }
1648
+ const resolvedCalls = []
1649
+ const routeDefaultEfforts = new Map([
1650
+ ['captain-provider/captain-model', 'high'],
1651
+ ['captain-provider/configured-member-model', 'medium'],
1652
+ ['other-provider/other-model', 'low'],
1653
+ ])
1654
+ const selectionContext = {
1655
+ llm: {
1656
+ resolveCallConfig: async (config) => {
1657
+ resolvedCalls.push(config)
1658
+ const route = `${config.provider}/${config.model}`
1659
+ if (route !== 'captain-provider/captain-model' && config.reasoningEffort === 'max') {
1660
+ const error = new Error(`provider/model route ${route} does not support reasoning effort "max"`)
1661
+ error.code = 'UNSUPPORTED_REASONING_EFFORT'
1662
+ throw error
1663
+ }
1664
+ const defaultEffort = routeDefaultEfforts.get(route)
1665
+ return config.reasoningEffort !== undefined || defaultEffort === undefined
1666
+ ? config
1667
+ : { ...config, reasoningEffort: defaultEffort }
1668
+ },
1669
+ },
1670
+ }
1671
+ const inheritedSelection = await resolveMemberLlmSelection(selectionContext, captain, {})
1672
+ check(
1673
+ 'ordinary member snapshots the captain current route and effort',
1674
+ inheritedSelection.provider === 'captain-provider'
1675
+ && inheritedSelection.model === 'captain-model'
1676
+ && inheritedSelection.reasoningEffort === 'max',
1677
+ )
1678
+ const overriddenSelection = await resolveMemberLlmSelection(selectionContext, captain, {
1679
+ provider: 'other-provider',
1680
+ model: 'other-model',
1681
+ })
1682
+ check(
1683
+ 'cross-provider route uses the target model default instead of captain effort',
1684
+ overriddenSelection.provider === 'other-provider'
1685
+ && overriddenSelection.model === 'other-model'
1686
+ && overriddenSelection.reasoningEffort === 'low'
1687
+ && resolvedCalls.at(-1)?.reasoningEffort === undefined,
1688
+ )
1689
+ const defaultedSelection = await resolveMemberLlmSelection(selectionContext, captain, {
1690
+ defaultModel: 'configured-member-model',
1691
+ })
1692
+ check(
1693
+ 'plugin memberModel route uses that target model default effort',
1694
+ defaultedSelection.provider === 'captain-provider'
1695
+ && defaultedSelection.model === 'configured-member-model'
1696
+ && defaultedSelection.reasoningEffort === 'medium'
1697
+ && resolvedCalls.at(-1)?.reasoningEffort === undefined,
1698
+ )
1699
+ const explicitEffortSelection = await resolveMemberLlmSelection(selectionContext, captain, {
1700
+ provider: 'other-provider',
1701
+ model: 'other-model',
1702
+ reasoningEffort: 'high',
1703
+ })
1704
+ check(
1705
+ 'explicit member effort overrides cross-provider target default',
1706
+ explicitEffortSelection.reasoningEffort === 'high'
1707
+ && resolvedCalls.at(-1)?.reasoningEffort === 'high',
1708
+ )
1709
+ const forcedDefaultSelection = await resolveMemberLlmSelection(selectionContext, captain, {
1710
+ reasoningEffort: 'default',
1711
+ })
1712
+ check(
1713
+ 'default sentinel opts out of same-route captain effort inheritance',
1714
+ forcedDefaultSelection.provider === 'captain-provider'
1715
+ && forcedDefaultSelection.model === 'captain-model'
1716
+ && forcedDefaultSelection.reasoningEffort === 'high'
1717
+ && resolvedCalls.at(-1)?.reasoningEffort === undefined,
1718
+ )
1719
+ let providerWithoutModelRejected = false
1720
+ try {
1721
+ await resolveMemberLlmSelection(selectionContext, captain, { provider: 'other-provider' })
1722
+ } catch {
1723
+ providerWithoutModelRejected = true
1724
+ }
1725
+ check('explicit provider without model is rejected', providerWithoutModelRejected)
1726
+ let emptyEffortRejected = false
1727
+ try {
1728
+ await resolveMemberLlmSelection(selectionContext, captain, { reasoningEffort: ' ' })
1729
+ } catch {
1730
+ emptyEffortRejected = true
1731
+ }
1732
+ check('empty explicit reasoning effort is rejected', emptyEffortRejected)
1733
+
1734
+ let catalogCalls = 0
1735
+ await validateMemberLlmSelections({
1736
+ llm: {
1737
+ async listModels(provider) {
1738
+ catalogCalls += 1
1739
+ return [{ provider, id: 'known-model', name: 'Known model' }]
1740
+ },
1741
+ },
1742
+ }, [
1743
+ { provider: 'known-provider', model: 'known-model' },
1744
+ { provider: 'known-provider', model: 'known-model' },
1745
+ ])
1746
+ check('approval model preflight caches one catalog lookup per provider', catalogCalls === 1)
1747
+ let unknownCatalogModelRejected = false
1748
+ try {
1749
+ await validateMemberLlmSelections({
1750
+ llm: {
1751
+ async listModels(provider) {
1752
+ return [{ provider, id: 'known-model', name: 'Known model' }]
1753
+ },
1754
+ },
1755
+ }, [{ provider: 'known-provider', model: 'typo-model' }])
1756
+ } catch (error) {
1757
+ unknownCatalogModelRejected = /unknown member model.*typo-model/i.test(String(error?.message ?? error))
1758
+ }
1759
+ check('approval model preflight rejects an unlisted typo before spawn', unknownCatalogModelRejected)
1760
+
1761
+ let startSpec
1762
+ const spawnMemberRecord = {
1763
+ id: '',
1764
+ name: 'backend',
1765
+ role: 'engineer',
1766
+ provider: overriddenSelection.provider,
1767
+ model: overriddenSelection.model,
1768
+ reasoningEffort: overriddenSelection.reasoningEffort,
1769
+ joinedAt: Date.now(),
1770
+ status: 'idle',
1771
+ }
1772
+ const spawnTeam = {
1773
+ name: 'Spawn Verify',
1774
+ id: 'spawn-verify',
1775
+ captainSessionId: captain.id,
1776
+ createdAt: Date.now(),
1777
+ members: [],
1778
+ tasks: [],
1779
+ taskSeq: 0,
1780
+ }
1781
+ await spawnMember(
1782
+ {
1783
+ subagents: {
1784
+ getProvider: () => ({
1785
+ prepareContinuable: () => undefined,
1786
+ capabilities: { persona: true, toolFilter: true },
1787
+ }),
1788
+ list: () => ['spawn'],
1789
+ startContinuable: async (spec) => {
1790
+ startSpec = spec
1791
+ return { childId: 'spawned-member', messageId: 'welcome-message' }
1792
+ },
1793
+ },
1794
+ },
1795
+ { provider: 'spawn', maxDepth: 1 },
1796
+ {
1797
+ withPending: async (_parentId, _label, _selection, operation) => operation(),
1798
+ },
1799
+ overriddenSelection,
1800
+ captain,
1801
+ spawnTeam,
1802
+ spawnMemberRecord,
1803
+ '.agent-teams',
1804
+ new AbortController().signal,
1805
+ )
1806
+ check(
1807
+ '#20: spawn receives the resolved per-member provider and model',
1808
+ startSpec?.request?.agentOptions?.provider === 'other-provider'
1809
+ && startSpec?.request?.agentOptions?.model === 'other-model'
1810
+ && spawnMemberRecord.id === 'spawned-member',
1811
+ )
1812
+
1813
+ function descriptorEvent(label, agentProvider = 'descriptor-provider', agentModel = 'descriptor-model') {
1814
+ return {
1815
+ type: 'subagent/descriptor',
1816
+ data: {
1817
+ version: SUBAGENT_DESCRIPTOR_VERSION,
1818
+ mode: 'continuable',
1819
+ provider: 'spawn',
1820
+ label,
1821
+ agentProvider,
1822
+ agentModel,
1823
+ },
1824
+ }
1825
+ }
1826
+
1827
+ function fakeChildContext({ label, parentSessionId, cwd, agentProvider, agentModel }) {
1828
+ const listeners = new Map()
1829
+ const selections = []
1830
+ return {
1831
+ listeners,
1832
+ selections,
1833
+ context: {
1834
+ agent: {
1835
+ session: {
1836
+ header: { parentSession: parentSessionId, cwd, seedLength: 0 },
1837
+ events: [descriptorEvent(label, agentProvider, agentModel)],
1838
+ },
1839
+ // 0.2.2 moved the selected route onto the Agent itself. The plugin calls
1840
+ // `model.select()` instead of intercepting the request.
1841
+ model: {
1842
+ select(selection) { selections.push(selection) },
1843
+ },
1844
+ },
1845
+ on(name, listener) {
1846
+ listeners.set(name, listener)
1847
+ return () => listeners.delete(name)
1848
+ },
1849
+ },
1850
+ }
1851
+ }
1852
+
1853
+ async function routedConfig(child) {
1854
+ const assemble = child.listeners.get('system-prompt/assemble')
1855
+ const request = child.listeners.get('agent/request')
1856
+ // 0.2.2 moved the selected route into the Agent's durable model API, so the
1857
+ // hook no longer registers an assemble/request listener; 0.2.1 hosts still do.
1858
+ if (typeof assemble === 'function') await assemble({}, {}, async () => ({ variables: {} }))
1859
+ if (typeof request === 'function') {
1860
+ return request({}, async () => ({
1861
+ provider: 'unselected-provider',
1862
+ model: 'unselected-model',
1863
+ reasoningEffort: 'low',
1864
+ }))
1865
+ }
1866
+ return child.selections.at(-1) ?? {
1867
+ provider: 'unselected-provider',
1868
+ model: 'unselected-model',
1869
+ reasoningEffort: 'low',
1870
+ }
1871
+ }
1872
+
1873
+ let setupMemberSelection
1874
+ const selectionRuntime = installMemberSelectionRuntime({
1875
+ subagents: {
1876
+ registerContinuableSetup: (setup) => {
1877
+ setupMemberSelection = setup
1878
+ return () => undefined
1879
+ },
1880
+ },
1881
+ }, '.agent-teams')
1882
+ const freshChild = fakeChildContext({
1883
+ label: 'agent-teams:fresh-team:backend',
1884
+ parentSessionId: 'captain-session',
1885
+ cwd: process.cwd(),
1886
+ })
1887
+ let disposeFresh
1888
+ await selectionRuntime.withPending(
1889
+ 'captain-session',
1890
+ 'agent-teams:fresh-team:backend',
1891
+ overriddenSelection,
1892
+ async () => {
1893
+ disposeFresh = setupMemberSelection(freshChild.context)
1894
+ },
1895
+ )
1896
+ const freshRoute = await routedConfig(freshChild)
1897
+ check(
1898
+ 'fresh child request receives the resolved reasoning effort',
1899
+ freshRoute.provider === 'other-provider'
1900
+ && freshRoute.model === 'other-model'
1901
+ && freshRoute.reasoningEffort === 'low',
1902
+ )
1903
+ disposeFresh()
1904
+
1905
+ const restoreWorkspace = await mkdtemp(join(tmpdir(), 'dsh-agent-teams-selection-'))
1906
+ try {
1907
+ const restoreStateRoot = join(restoreWorkspace, '.agent-teams')
1908
+ await createTeamDir(restoreStateRoot, {
1909
+ name: 'Restore Team',
1910
+ id: 'restore-team',
1911
+ captainSessionId: 'captain-session',
1912
+ createdAt: Date.now(),
1913
+ members: [{
1914
+ id: 'cold-member',
1915
+ name: 'reviewer',
1916
+ provider: 'cold-provider',
1917
+ model: 'cold-model',
1918
+ reasoningEffort: 'high',
1919
+ joinedAt: Date.now(),
1920
+ status: 'idle',
1921
+ }],
1922
+ tasks: [],
1923
+ taskSeq: 0,
1924
+ })
1925
+ const coldChild = fakeChildContext({
1926
+ label: 'agent-teams:restore-team:reviewer',
1927
+ parentSessionId: 'captain-session',
1928
+ cwd: restoreWorkspace,
1929
+ agentProvider: 'cold-provider',
1930
+ agentModel: 'cold-model',
1931
+ })
1932
+ const disposeCold = setupMemberSelection(coldChild.context)
1933
+ const coldRoute = await routedConfig(coldChild)
1934
+ check(
1935
+ 'cold-resumed child restores provider, model, and reasoning from team.json',
1936
+ coldRoute.provider === 'cold-provider'
1937
+ && coldRoute.model === 'cold-model'
1938
+ && coldRoute.reasoningEffort === 'high',
1939
+ )
1940
+ disposeCold()
1941
+ } finally {
1942
+ await rm(restoreWorkspace, { recursive: true, force: true })
1943
+ }
1944
+
1945
+ console.log('8/8 state-file atomic write hardening (Windows EPERM fallback)')
1946
+ // The durable state files (team.json, mailboxes, retired index) are replaced
1947
+ // through `atomicWriteText` = write-temp + rename. On Windows a rename over an
1948
+ // existing target throws EPERM while another process holds it open without
1949
+ // FILE_SHARE_DELETE; the hardened path retries the rename a few times and then
1950
+ // degrades to a direct overwrite (content-equivalent because the temp file was
1951
+ // fully written). These checks pin that behavior through the injectable seam
1952
+ // and, on Windows, against a real cross-process handle lock.
1953
+ const atomicStateRoot = await mkdtemp(join(tmpdir(), 'dsh-agent-teams-atomic-'))
1954
+ try {
1955
+ const {
1956
+ replaceFileAtomicOrDirect,
1957
+ writeTeam,
1958
+ } = await import('../lib/state.js')
1959
+ const epermError = () => Object.assign(
1960
+ new Error("EPERM: operation not permitted, rename '.../team.json.tmp' -> '.../team.json'"),
1961
+ { code: 'EPERM' },
1962
+ )
1963
+
1964
+ let renameCalls = 0
1965
+ let fallbackWrites = 0
1966
+ let fallbackRemovals = 0
1967
+ let fallbackContent = ''
1968
+ const fallbackTarget = join(atomicStateRoot, 'forced', 'team.json')
1969
+ await replaceFileAtomicOrDirect('forced.tmp', fallbackTarget, '{"fallback":1}', {
1970
+ rename: async () => { renameCalls += 1; throw epermError() },
1971
+ writeFile: async (_file, content) => { fallbackWrites += 1; fallbackContent = content },
1972
+ remove: async () => { fallbackRemovals += 1 },
1973
+ }, { retryDelayMs: 1 })
1974
+ check(
1975
+ 'persistent EPERM exhausts the rename retries (1 initial + 3 retries)',
1976
+ renameCalls === 4,
1977
+ `renameCalls = ${renameCalls}`,
1978
+ )
1979
+ check(
1980
+ 'persistent EPERM falls back to a direct overwrite of the target',
1981
+ fallbackWrites === 1 && fallbackContent === '{"fallback":1}',
1982
+ `fallbackWrites = ${fallbackWrites}`,
1983
+ )
1984
+ check('the temp file is removed after the fallback write', fallbackRemovals === 1)
1985
+
1986
+ let transientCalls = 0
1987
+ let transientWrites = 0
1988
+ await replaceFileAtomicOrDirect('transient.tmp', join(atomicStateRoot, 'transient', 'team.json'), '{"retried":2}', {
1989
+ rename: async () => {
1990
+ transientCalls += 1
1991
+ if (transientCalls <= 2) throw epermError()
1992
+ },
1993
+ writeFile: async (file, content) => { transientWrites += 1; await writeFile(file, content) },
1994
+ remove: async () => undefined,
1995
+ }, { retryDelayMs: 1 })
1996
+ check(
1997
+ 'a transient EPERM recovers via rename retries without the fallback',
1998
+ transientCalls === 3 && transientWrites === 0,
1999
+ `renameCalls = ${transientCalls}, fallbackWrites = ${transientWrites}`,
2000
+ )
2001
+
2002
+ let aggregateThrown = false
2003
+ let dualRemovals = 0
2004
+ try {
2005
+ await replaceFileAtomicOrDirect('dual.tmp', join(atomicStateRoot, 'dual', 'team.json'), 'x', {
2006
+ rename: async () => { throw epermError() },
2007
+ writeFile: async () => { throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }) },
2008
+ remove: async () => { dualRemovals += 1 },
2009
+ }, { retryDelayMs: 1 })
2010
+ } catch (error) {
2011
+ aggregateThrown = error instanceof AggregateError
2012
+ }
2013
+ check('failure of both the atomic and the direct path raises AggregateError', aggregateThrown)
2014
+ check('the temp file is removed even after a dual failure', dualRemovals === 1)
2015
+
2016
+ if (process.platform === 'win32') {
2017
+ // Real cross-process lock: hold team.json with FileShare.ReadWrite (no
2018
+ // FILE_SHARE_DELETE) from a child .NET handle, then verify the public
2019
+ // write path still persists through the direct-write fallback.
2020
+ const lockedTeam = {
2021
+ name: 'Locked Team',
2022
+ id: 'locked-team',
2023
+ captainSessionId: 'sess-lock',
2024
+ createdAt: Date.now(),
2025
+ members: [],
2026
+ tasks: [],
2027
+ taskSeq: 0,
2028
+ }
2029
+ await createTeamDir(atomicStateRoot, lockedTeam)
2030
+ const lockedJson = join(atomicStateRoot, lockedTeam.id, 'team.json')
2031
+ const { spawn } = await import('node:child_process')
2032
+ const holder = spawn(
2033
+ 'powershell.exe',
2034
+ ['-NoProfile', '-NonInteractive', '-Command',
2035
+ `$f = '${lockedJson.replaceAll("'", "''")}';
2036
+ $s = [System.IO.File]::Open($f, [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite);
2037
+ [Console]::Out.WriteLine('HELD'); [Console]::Out.Flush();
2038
+ Start-Sleep -Seconds 90; $s.Dispose()`],
2039
+ { stdio: ['ignore', 'pipe', 'inherit'] },
2040
+ )
2041
+ const held = await new Promise((resolve, reject) => {
2042
+ let buffer = ''
2043
+ const onData = (chunk) => {
2044
+ buffer += chunk.toString()
2045
+ if (buffer.includes('HELD')) { cleanup(); resolve(true) }
2046
+ }
2047
+ const onExit = () => { cleanup(); reject(new Error('lock holder exited before arming')) }
2048
+ const timer = setTimeout(() => {
2049
+ cleanup()
2050
+ reject(new Error('timed out waiting for the lock holder'))
2051
+ // Windows CI is slow to start powershell.exe under load; a short arm
2052
+ // budget turned this into a flaky failure on 2026-10-18.
2053
+ }, 30_000)
2054
+ function cleanup() {
2055
+ clearTimeout(timer)
2056
+ holder.stdout.off('data', onData)
2057
+ holder.off('exit', onExit)
2058
+ }
2059
+ holder.stdout.on('data', onData)
2060
+ holder.on('exit', onExit)
2061
+ })
2062
+ try {
2063
+ if (held) {
2064
+ lockedTeam.members.push({ id: 'sess-new', name: 'member', joinedAt: Date.now(), status: 'idle' })
2065
+ await writeTeam(atomicStateRoot, lockedTeam)
2066
+ const persisted = JSON.parse(await readFile(lockedJson, 'utf8'))
2067
+ const leftovers = (await readdir(join(atomicStateRoot, lockedTeam.id))).filter(name => name.endsWith('.tmp'))
2068
+ check(
2069
+ 'writeTeam survives a real Windows lock without FILE_SHARE_DELETE',
2070
+ persisted.members.length === 1 && leftovers.length === 0,
2071
+ `members = ${persisted.members.length}, tmp leftovers = ${leftovers.join(', ') || 'none'}`,
2072
+ )
2073
+ }
2074
+ // Archive moves the whole team directory with `rename(source, target)`.
2075
+ // The same Windows delete-sharing EPERM applies when a file below the
2076
+ // directory is momentarily locked, so it retries the rename. Release
2077
+ // the real lock only after observing the first OS rename rejection;
2078
+ // PowerShell startup/scheduling must not race a 150 ms retry budget.
2079
+ const { archiveTeamDir } = await import('../lib/state.js')
2080
+ const transientTeam = {
2081
+ name: 'Transient Lock Team',
2082
+ id: 'transient-lock',
2083
+ captainSessionId: 'sess-transient',
2084
+ createdAt: Date.now(),
2085
+ members: [],
2086
+ tasks: [],
2087
+ taskSeq: 0,
2088
+ }
2089
+ await createTeamDir(atomicStateRoot, transientTeam)
2090
+ const transientJson = join(atomicStateRoot, transientTeam.id, 'team.json')
2091
+ const transientSource = join(atomicStateRoot, transientTeam.id)
2092
+ const flasher = spawn(
2093
+ 'powershell.exe',
2094
+ ['-NoProfile', '-NonInteractive', '-Command',
2095
+ `$f = '${transientJson.replaceAll("'", "''")}';
2096
+ $s = [System.IO.File]::Open($f, [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite);
2097
+ [Console]::Out.WriteLine('HELD_T'); [Console]::Out.Flush();
2098
+ [void][Console]::In.ReadLine(); $s.Dispose();
2099
+ [Console]::Out.WriteLine('RELEASED_T'); [Console]::Out.Flush()`],
2100
+ { stdio: ['pipe', 'pipe', 'inherit'] },
2101
+ )
2102
+ const waitForMarker = (marker, trigger = () => {}) => new Promise((resolve, reject) => {
2103
+ let buffer = ''
2104
+ const onData = (chunk) => {
2105
+ buffer += chunk.toString()
2106
+ if (buffer.includes(marker)) { cleanup(); resolve(true) }
2107
+ }
2108
+ const onError = (error) => { cleanup(); reject(error) }
2109
+ const onExit = () => { cleanup(); reject(new Error(`transient holder exited before ${marker}`)) }
2110
+ const timer = setTimeout(() => {
2111
+ cleanup()
2112
+ reject(new Error(`timed out waiting for transient lock marker ${marker}`))
2113
+ }, 10_000)
2114
+ function cleanup() {
2115
+ clearTimeout(timer)
2116
+ flasher.stdout.off('data', onData)
2117
+ flasher.off('exit', onExit)
2118
+ flasher.off('error', onError)
2119
+ flasher.stdin.off('error', onError)
2120
+ }
2121
+ flasher.stdout.on('data', onData)
2122
+ flasher.on('exit', onExit)
2123
+ flasher.on('error', onError)
2124
+ flasher.stdin.on('error', onError)
2125
+ trigger()
2126
+ })
2127
+ const fsPromises = (await import('node:fs/promises')).default
2128
+ const { syncBuiltinESMExports } = await import('node:module')
2129
+ const originalRename = fsPromises.rename
2130
+ let archiveRenameCalls = 0
2131
+ let observedLockRejection = false
2132
+ try {
2133
+ const flashed = await waitForMarker('HELD_T')
2134
+ // Delegate every attempt to the real filesystem. Only coordinate
2135
+ // release after the first actual sharing violation, then rethrow that
2136
+ // same error so archiveTeamDir itself must perform the retry.
2137
+ fsPromises.rename = async (from, to) => {
2138
+ if (from !== transientSource) return originalRename(from, to)
2139
+ archiveRenameCalls += 1
2140
+ try {
2141
+ return await originalRename(from, to)
2142
+ } catch (error) {
2143
+ if (!observedLockRejection && ['EPERM', 'EACCES', 'EBUSY'].includes(error.code)) {
2144
+ observedLockRejection = true
2145
+ await waitForMarker('RELEASED_T', () => flasher.stdin.end('release\n'))
2146
+ }
2147
+ throw error
2148
+ }
2149
+ }
2150
+ syncBuiltinESMExports()
2151
+ await archiveTeamDir(atomicStateRoot, transientTeam.id)
2152
+ const archived = await readFile(join(atomicStateRoot, 'archive', transientTeam.id, 'team.json'), 'utf8')
2153
+ check(
2154
+ 'archiveTeamDir survives a transient Windows directory lock via rename retries',
2155
+ flashed && observedLockRejection && archiveRenameCalls >= 2
2156
+ && JSON.parse(archived).id === transientTeam.id,
2157
+ `observed real lock = ${observedLockRejection}, rename attempts = ${archiveRenameCalls}`,
2158
+ )
2159
+ } catch (error) {
2160
+ check(
2161
+ 'archiveTeamDir survives a transient Windows directory lock via rename retries',
2162
+ false,
2163
+ String(error),
2164
+ )
2165
+ } finally {
2166
+ fsPromises.rename = originalRename
2167
+ syncBuiltinESMExports()
2168
+ flasher.kill()
2169
+ if (flasher.exitCode === null && flasher.signalCode === null) {
2170
+ await new Promise((resolve) => {
2171
+ const timer = setTimeout(resolve, 5_000)
2172
+ flasher.once('exit', () => { clearTimeout(timer); resolve() })
2173
+ })
2174
+ }
2175
+ }
2176
+ } finally {
2177
+ holder.kill()
2178
+ if (holder.exitCode === null && holder.signalCode === null) {
2179
+ await new Promise((resolve) => {
2180
+ const timer = setTimeout(resolve, 5_000)
2181
+ holder.once('exit', () => { clearTimeout(timer); resolve() })
2182
+ })
2183
+ }
2184
+ }
2185
+ } else {
2186
+ check('real Windows lock integration skipped on this platform', true)
2187
+ }
2188
+ } finally {
2189
+ await rm(atomicStateRoot, { recursive: true, force: true }).catch(async () => {
2190
+ await new Promise((resolve) => setTimeout(resolve, 500))
2191
+ await rm(atomicStateRoot, { recursive: true, force: true })
2192
+ })
2193
+ }
2194
+
2195
+ if (failures > 0) {
2196
+ console.error(`\n${failures} check(s) FAILED`)
2197
+ process.exit(1)
2198
+ }
2199
+ console.log('\nall checks passed')