@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,765 @@
1
+ /**
2
+ * Named team-profile templates: config types, normalization, invocation
3
+ * parsing, and prompt rendering.
4
+ *
5
+ * Pure functions only — no I/O, no spawn. Runtime create/spawn stays in
6
+ * `tools.ts`; this module only turns a config map + a profile name into a
7
+ * validated, topologically ordered template (or parses `--profile` flags).
8
+ *
9
+ * @module dsh-agent-teams/profiles
10
+ */
11
+
12
+ import { CAPTAIN_KEY, sanitizeKey } from './state.ts'
13
+
14
+ /** Hard cap on named profiles so the usage prompt cannot grow without bound. */
15
+ export const MAX_TEAM_PROFILES = 16
16
+ /** Hard cap on seed tasks per profile. The software-delivery example has 13. */
17
+ export const MAX_PROFILE_TASKS = 32
18
+ /** Protocol excerpt length in the usage / prompt listing. */
19
+ export const PROFILE_PROTOCOL_PROMPT_LIMIT = 240
20
+
21
+ const PROFILE_KEYS = ['description', 'protocol', 'executionPrompt', 'fallback', 'members', 'tasks', 'taskPlanning', 'reviewPolicy'] as const
22
+ const REVIEW_POLICY_KEYS = ['requirementsMinRounds', 'requirementsMaxRounds', 'codeMaxRounds', 'maxRepairAttempts', 'requiredReviewers'] as const
23
+ const MEMBER_KEYS = ['name', 'role', 'provider', 'model', 'reasoning_effort', 'executionPrompt', 'fallback', 'tool_policy'] as const
24
+ const FALLBACK_KEYS = ['provider', 'model'] as const
25
+ const TASK_KEYS = ['id', 'subject', 'description', 'assignee', 'dependencies'] as const
26
+
27
+ /** One member row in a named team-profile template (unresolved). */
28
+ export interface TeamModelFallbackConfig {
29
+ provider: string
30
+ model: string
31
+ }
32
+
33
+ export interface TeamProfileMemberConfig {
34
+ name: string
35
+ role?: string
36
+ provider?: string
37
+ model?: string
38
+ reasoning_effort?: string
39
+ executionPrompt?: string
40
+ fallback?: TeamModelFallbackConfig
41
+ /**
42
+ * Owner-declared tool-policy id this profile member selects (#59). The
43
+ * profile only names a configured policy; it never carries raw tool lists.
44
+ */
45
+ tool_policy?: string
46
+ }
47
+
48
+ /** One seed-task row in a named team-profile template (unresolved). */
49
+ export interface TeamProfileTaskConfig {
50
+ id: string
51
+ subject: string
52
+ description?: string
53
+ assignee?: string
54
+ dependencies?: string[]
55
+ }
56
+
57
+ /** One named team-profile template from plugin config. */
58
+ export interface TeamProfileConfig {
59
+ description?: string
60
+ protocol?: string
61
+ executionPrompt?: string
62
+ fallback?: TeamModelFallbackConfig
63
+ members: TeamProfileMemberConfig[]
64
+ /**
65
+ * `captain` means the profile supplies people and guardrails only; the
66
+ * Captain derives the task graph from the user's goal at runtime.
67
+ * `seed` preserves a fixed template workflow for explicitly scripted teams.
68
+ */
69
+ taskPlanning?: 'captain' | 'seed'
70
+ tasks?: TeamProfileTaskConfig[]
71
+ reviewPolicy?: import('./types.ts').ReviewPolicy
72
+ }
73
+
74
+ /** A profile member after trim / pairing / reserved-name checks. */
75
+ export interface NormalizedProfileMember {
76
+ name: string
77
+ role?: string
78
+ provider?: string
79
+ model?: string
80
+ reasoningEffort?: string
81
+ executionPrompt?: string
82
+ fallback?: TeamModelFallbackConfig
83
+ toolPolicy?: string
84
+ }
85
+
86
+ /** A profile seed task after assignee canonicalization; `sourceIndex` is the YAML order. */
87
+ export interface NormalizedProfileTask {
88
+ id: string
89
+ subject: string
90
+ description?: string
91
+ assignee?: string
92
+ dependencies: string[]
93
+ sourceIndex: number
94
+ }
95
+
96
+ /** A fully validated, topologically ordered team profile. */
97
+ export interface NormalizedTeamProfile {
98
+ name: string
99
+ description?: string
100
+ protocol?: string
101
+ executionPrompt?: string
102
+ fallback?: TeamModelFallbackConfig
103
+ taskPlanning: 'captain' | 'seed'
104
+ members: NormalizedProfileMember[]
105
+ tasks: NormalizedProfileTask[]
106
+ reviewPolicy?: import('./types.ts').ReviewPolicy
107
+ }
108
+
109
+ /** The goal + optional named profile extracted from a slash / gesture line. */
110
+ export interface AgentTeamsInvocation {
111
+ goal: string
112
+ profile?: string
113
+ }
114
+
115
+ /** One configured profile after key trim, for listing / lookup. */
116
+ export interface ListedTeamProfile {
117
+ name: string
118
+ config: TeamProfileConfig
119
+ }
120
+
121
+ /**
122
+ * Trim every profile key once, reject empty / colliding keys, and reject
123
+ * more than {@link MAX_TEAM_PROFILES} entries. Does not validate profile
124
+ * bodies — that belongs to {@link resolveTeamProfile}.
125
+ */
126
+ export function listConfiguredProfiles(
127
+ profiles: Record<string, TeamProfileConfig> | undefined | null,
128
+ ): ListedTeamProfile[] {
129
+ const record = asProfilesRecord(profiles)
130
+ const keys = Object.keys(record)
131
+ if (keys.length > MAX_TEAM_PROFILES) {
132
+ throw new Error(`too many AgentTeams profiles (${keys.length}); the limit is ${MAX_TEAM_PROFILES}`)
133
+ }
134
+ const seen = new Map<string, string>()
135
+ const listed: ListedTeamProfile[] = []
136
+ for (const rawKey of keys) {
137
+ const name = rawKey.trim()
138
+ if (name === '') {
139
+ throw new Error('configured AgentTeams profiles include an empty key')
140
+ }
141
+ const previous = seen.get(name)
142
+ if (previous !== undefined) {
143
+ throw new Error(`configured AgentTeams profiles have duplicate key "${name}"`)
144
+ }
145
+ seen.set(name, rawKey)
146
+ listed.push({ name, config: record[rawKey] as TeamProfileConfig })
147
+ }
148
+ return listed
149
+ }
150
+
151
+ /**
152
+ * Render the usage-prompt listing. One line per profile: name, member count,
153
+ * task count, protocol excerpt (at most 240 characters). Returns `''` when
154
+ * nothing is configured so callers can omit the capability entirely.
155
+ */
156
+ export function formatProfilesForPrompt(
157
+ profiles: Record<string, TeamProfileConfig> | undefined | null,
158
+ ): string {
159
+ const listed = listConfiguredProfiles(profiles)
160
+ if (listed.length === 0) return ''
161
+ const lines = [
162
+ 'Configured team profiles (pass profile= to agent_teams_create):',
163
+ ...listed.map((entry) => formatProfileListingLine(entry)),
164
+ ]
165
+ return lines.join('\n')
166
+ }
167
+
168
+ /**
169
+ * Walk `rawInput` from the front and eat standalone profile flags. Only
170
+ * `--profile <name>`, `--profile=<name>`, and `profile=<name>` count; the
171
+ * first ordinary token stops the scan so a mid-sentence `profile=` stays in
172
+ * the goal. A leading ordinary token is never treated as a profile name.
173
+ *
174
+ * `--profile "name"` strips one matching pair of quotes. Repeat flags and a
175
+ * `--profile` with no name throw.
176
+ */
177
+ export function parseProfileInvocation(rawInput: string): AgentTeamsInvocation {
178
+ const tokens = tokenize(rawInput)
179
+ let index = 0
180
+ let profile: string | undefined
181
+ while (index < tokens.length) {
182
+ const token = tokens[index]
183
+ if (token === undefined) break
184
+ const parsed = parseLeadingProfileFlag(token, tokens[index + 1])
185
+ if (parsed === undefined) break
186
+ if (profile !== undefined) {
187
+ throw new Error('duplicate AgentTeams profile flag')
188
+ }
189
+ profile = parsed.name
190
+ index += parsed.consumed
191
+ }
192
+ const goal = tokens.slice(index).join(' ')
193
+ return profile === undefined ? { goal } : { goal, profile }
194
+ }
195
+
196
+ /**
197
+ * Normalize and pre-validate one named profile. Failures throw before any
198
+ * caller should create a directory or spawn members.
199
+ */
200
+ export function resolveTeamProfile(
201
+ profiles: Record<string, TeamProfileConfig>,
202
+ profileName: string,
203
+ maxMembers: number,
204
+ ): NormalizedTeamProfile {
205
+ const listed = listConfiguredProfiles(profiles)
206
+ const name = profileName.trim()
207
+ if (name === '') {
208
+ throw new Error('AgentTeams profile name must be a non-empty string')
209
+ }
210
+ const match = listed.find((entry) => entry.name === name)
211
+ if (match === undefined) {
212
+ const available = listed.map((entry) => entry.name)
213
+ const shown = available.length === 0 ? '(none)' : available.join(', ')
214
+ throw new Error(`unknown AgentTeams profile "${name}" — configured profiles: ${shown}`)
215
+ }
216
+ return normalizeListedProfile(match, maxMembers)
217
+ }
218
+
219
+ function formatProfileListingLine(entry: ListedTeamProfile): string {
220
+ const memberCount = Array.isArray(entry.config.members) ? entry.config.members.length : 0
221
+ const planning = resolveProfileTaskPlanning(entry.config)
222
+ const graph = planning === 'captain'
223
+ ? 'captain planning'
224
+ : countLabel(Array.isArray(entry.config.tasks) ? entry.config.tasks.length : 0, 'task')
225
+ const counts = `(${countLabel(memberCount, 'member')}, ${graph})`
226
+ const summary = protocolSummary(entry.config.protocol) ?? protocolSummary(entry.config.description)
227
+ return summary === undefined
228
+ ? `- ${entry.name} ${counts}`
229
+ : `- ${entry.name} ${counts}: ${summary}`
230
+ }
231
+
232
+ /** Public lookup used by activation text and status rendering. */
233
+ export function resolveProfileTaskPlanning(config: TeamProfileConfig | undefined): 'captain' | 'seed' {
234
+ return config?.taskPlanning === 'captain' ? 'captain' : 'seed'
235
+ }
236
+
237
+ function countLabel(count: number, noun: string): string {
238
+ return `${count} ${noun}${count === 1 ? '' : 's'}`
239
+ }
240
+
241
+ function protocolSummary(protocol: string | undefined): string | undefined {
242
+ if (typeof protocol !== 'string') return undefined
243
+ const collapsed = protocol.trim().replace(/\s+/gu, ' ')
244
+ if (collapsed === '') return undefined
245
+ return collapsed.length <= PROFILE_PROTOCOL_PROMPT_LIMIT
246
+ ? collapsed
247
+ : collapsed.slice(0, PROFILE_PROTOCOL_PROMPT_LIMIT)
248
+ }
249
+
250
+ function tokenize(rawInput: string): string[] {
251
+ const trimmed = rawInput.trim()
252
+ if (trimmed === '') return []
253
+ return trimmed.split(/\s+/u)
254
+ }
255
+
256
+ function parseLeadingProfileFlag(
257
+ token: string,
258
+ nextToken: string | undefined,
259
+ ): { name: string; consumed: number } | undefined {
260
+ if (token === '--profile') {
261
+ if (nextToken === undefined) {
262
+ throw new Error('--profile flag is missing a profile name')
263
+ }
264
+ return { name: readProfileToken(nextToken), consumed: 2 }
265
+ }
266
+ if (token.startsWith('--profile=')) {
267
+ return { name: readProfileToken(token.slice('--profile='.length)), consumed: 1 }
268
+ }
269
+ if (token.startsWith('profile=')) {
270
+ return { name: readProfileToken(token.slice('profile='.length)), consumed: 1 }
271
+ }
272
+ return undefined
273
+ }
274
+
275
+ function readProfileToken(raw: string): string {
276
+ const name = stripOneQuotePair(raw).trim()
277
+ if (name === '') {
278
+ throw new Error('--profile flag is missing a profile name')
279
+ }
280
+ return name
281
+ }
282
+
283
+ /** Strip a single matching pair of `"` or `'` quotes; leave unmatched quotes alone. */
284
+ function stripOneQuotePair(value: string): string {
285
+ if (value.length < 2) return value
286
+ const first = value.at(0)
287
+ const last = value.at(-1)
288
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
289
+ return value.slice(1, -1)
290
+ }
291
+ return value
292
+ }
293
+
294
+ function normalizeListedProfile(
295
+ listed: ListedTeamProfile,
296
+ maxMembers: number,
297
+ ): NormalizedTeamProfile {
298
+ const path = `profiles.${listed.name}`
299
+ const raw = asRecord(listed.config, path)
300
+ assertAllowedKeys(raw, PROFILE_KEYS, path)
301
+
302
+ const description = optionalNonEmptyString(raw['description'], `${path}.description`)
303
+ const protocol = optionalNonEmptyString(raw['protocol'], `${path}.protocol`)
304
+ const executionPrompt = optionalNonEmptyString(raw['executionPrompt'], `${path}.executionPrompt`)
305
+ const fallback = normalizeFallback(raw['fallback'], `${path}.fallback`)
306
+ const taskPlanning = normalizeTaskPlanning(raw['taskPlanning'], `${path}.taskPlanning`)
307
+ const reviewPolicy = normalizeReviewPolicy(raw['reviewPolicy'], `${path}.reviewPolicy`)
308
+ const membersRaw = raw['members']
309
+ if (!Array.isArray(membersRaw) || membersRaw.length === 0) {
310
+ throw new Error(`AgentTeams profile "${listed.name}" has no members`)
311
+ }
312
+ if (membersRaw.length > maxMembers) {
313
+ throw new Error(
314
+ `profile "${listed.name}" has ${membersRaw.length} members but maxMembers is ${maxMembers}`,
315
+ )
316
+ }
317
+
318
+ const members: NormalizedProfileMember[] = []
319
+ const memberByName = new Map<string, NormalizedProfileMember>()
320
+ const memberByKey = new Map<string, NormalizedProfileMember>()
321
+ for (let index = 0; index < membersRaw.length; index += 1) {
322
+ const member = normalizeMember(membersRaw[index], `${path}.members[${index}]`, listed.name)
323
+ const key = sanitizeKey(member.name)
324
+ const colliding = memberByKey.get(key)
325
+ if (colliding !== undefined) {
326
+ throw new Error(
327
+ `profile members "${colliding.name}" and "${member.name}" collapse to the same name`,
328
+ )
329
+ }
330
+ memberByName.set(member.name, member)
331
+ memberByKey.set(key, member)
332
+ members.push(member)
333
+ }
334
+
335
+ const tasksRaw = raw['tasks']
336
+ if (tasksRaw === undefined) {
337
+ return omitUndefined({
338
+ name: listed.name,
339
+ description,
340
+ protocol,
341
+ executionPrompt,
342
+ fallback,
343
+ taskPlanning,
344
+ reviewPolicy,
345
+ members,
346
+ tasks: [],
347
+ })
348
+ }
349
+ if (!Array.isArray(tasksRaw)) {
350
+ throw new Error(`profiles.${listed.name}.tasks must be an array`)
351
+ }
352
+ if (tasksRaw.length > MAX_PROFILE_TASKS) {
353
+ throw new Error(
354
+ `profile "${listed.name}" has ${tasksRaw.length} tasks but the limit is ${MAX_PROFILE_TASKS}`,
355
+ )
356
+ }
357
+
358
+ const requireAssignee = tasksRaw.length > 0
359
+ const draftTasks: NormalizedProfileTask[] = []
360
+ const taskById = new Map<string, NormalizedProfileTask>()
361
+ const taskByKey = new Map<string, NormalizedProfileTask>()
362
+ for (let index = 0; index < tasksRaw.length; index += 1) {
363
+ const task = normalizeTask(
364
+ tasksRaw[index],
365
+ `${path}.tasks[${index}]`,
366
+ listed.name,
367
+ index,
368
+ memberByName,
369
+ memberByKey,
370
+ requireAssignee,
371
+ )
372
+ const collidingId = taskById.get(task.id)
373
+ if (collidingId !== undefined) {
374
+ throw new Error(`profile "${listed.name}" has duplicate task id "${task.id}"`)
375
+ }
376
+ const key = sanitizeKey(task.id)
377
+ const collidingKey = taskByKey.get(key)
378
+ if (collidingKey !== undefined) {
379
+ throw new Error(
380
+ `profile tasks "${collidingKey.id}" and "${task.id}" collapse to the same id`,
381
+ )
382
+ }
383
+ taskById.set(task.id, task)
384
+ taskByKey.set(key, task)
385
+ draftTasks.push(task)
386
+ }
387
+
388
+ const tasks = topoSortTasks(draftTasks, listed.name)
389
+ return omitUndefined({
390
+ name: listed.name,
391
+ description,
392
+ protocol,
393
+ executionPrompt,
394
+ fallback,
395
+ taskPlanning,
396
+ reviewPolicy,
397
+ members,
398
+ tasks: taskPlanning === 'captain' ? [] : tasks,
399
+ })
400
+ }
401
+
402
+ function normalizeTaskPlanning(value: unknown, path: string): 'captain' | 'seed' {
403
+ if (value === undefined) return 'seed'
404
+ if (value === 'captain' || value === 'seed') return value
405
+ throw new Error(`${path} must be "captain" or "seed"`)
406
+ }
407
+
408
+ function normalizeReviewPolicy(value: unknown, path: string): import('./types.ts').ReviewPolicy | undefined {
409
+ if (value === undefined) return undefined
410
+ const raw = asRecord(value, path)
411
+ assertAllowedKeys(raw, REVIEW_POLICY_KEYS, path)
412
+ const requirementsMinRounds = optionalPositiveInt(raw['requirementsMinRounds'], `${path}.requirementsMinRounds`)
413
+ const requirementsMaxRounds = optionalPositiveInt(raw['requirementsMaxRounds'], `${path}.requirementsMaxRounds`)
414
+ const codeMaxRounds = optionalPositiveInt(raw['codeMaxRounds'], `${path}.codeMaxRounds`)
415
+ const maxRepairAttempts = optionalPositiveInt(raw['maxRepairAttempts'], `${path}.maxRepairAttempts`)
416
+ if (
417
+ requirementsMinRounds !== undefined
418
+ && requirementsMaxRounds !== undefined
419
+ && requirementsMinRounds > requirementsMaxRounds
420
+ ) {
421
+ throw new Error(`${path}.requirementsMinRounds must be <= requirementsMaxRounds`)
422
+ }
423
+ let requiredReviewers: string[] | undefined
424
+ if (raw['requiredReviewers'] !== undefined) {
425
+ if (!Array.isArray(raw['requiredReviewers'])) {
426
+ throw new Error(`${path}.requiredReviewers must be an array of strings`)
427
+ }
428
+ requiredReviewers = raw['requiredReviewers'].map((item, index) => {
429
+ if (typeof item !== 'string' || item.trim() === '') {
430
+ throw new Error(`${path}.requiredReviewers[${index}] must be a non-empty string`)
431
+ }
432
+ return item.trim()
433
+ })
434
+ }
435
+ return omitUndefined({
436
+ requirementsMinRounds,
437
+ requirementsMaxRounds,
438
+ codeMaxRounds,
439
+ maxRepairAttempts,
440
+ requiredReviewers,
441
+ })
442
+ }
443
+
444
+ function optionalPositiveInt(value: unknown, path: string): number | undefined {
445
+ if (value === undefined) return undefined
446
+ if (!Number.isSafeInteger(value) || (value as number) < 1) {
447
+ throw new Error(`${path} must be a positive integer`)
448
+ }
449
+ return value as number
450
+ }
451
+
452
+ function normalizeMember(
453
+ value: unknown,
454
+ path: string,
455
+ profileName: string,
456
+ ): NormalizedProfileMember {
457
+ const raw = asRecord(value, path)
458
+ assertAllowedKeys(raw, MEMBER_KEYS, path)
459
+ const name = requiredNonEmptyString(raw['name'], `${path}.name`, `profile "${profileName}" has a member with an empty name`)
460
+ if (isCaptainName(name)) {
461
+ throw new Error(`member name "${name}" is reserved for the captain`)
462
+ }
463
+ const role = optionalNonEmptyString(raw['role'], `${path}.role`)
464
+ const provider = optionalNonEmptyString(raw['provider'], `${path}.provider`)
465
+ const model = optionalNonEmptyString(raw['model'], `${path}.model`)
466
+ const reasoningEffort = optionalNonEmptyString(raw['reasoning_effort'], `${path}.reasoning_effort`)
467
+ const executionPrompt = optionalNonEmptyString(raw['executionPrompt'], `${path}.executionPrompt`)
468
+ const fallback = normalizeFallback(raw['fallback'], `${path}.fallback`)
469
+ const toolPolicy = optionalNonEmptyString(raw['tool_policy'], `${path}.tool_policy`)
470
+ if (provider !== undefined && model === undefined) {
471
+ throw new Error(`profile member "${name}" sets provider without model`)
472
+ }
473
+ return omitUndefined({ name, role, provider, model, reasoningEffort, executionPrompt, fallback, toolPolicy })
474
+ }
475
+
476
+ function normalizeFallback(value: unknown, path: string): TeamModelFallbackConfig | undefined {
477
+ if (value === undefined) return undefined
478
+ const raw = asRecord(value, path)
479
+ assertAllowedKeys(raw, FALLBACK_KEYS, path)
480
+ const provider = requiredNonEmptyString(raw['provider'], `${path}.provider`, `${path}.provider must not be empty`)
481
+ const model = requiredNonEmptyString(raw['model'], `${path}.model`, `${path}.model must not be empty`)
482
+ return { provider, model }
483
+ }
484
+
485
+ function normalizeTask(
486
+ value: unknown,
487
+ path: string,
488
+ profileName: string,
489
+ sourceIndex: number,
490
+ memberByName: Map<string, NormalizedProfileMember>,
491
+ memberByKey: Map<string, NormalizedProfileMember>,
492
+ requireAssignee: boolean,
493
+ ): NormalizedProfileTask {
494
+ const raw = asRecord(value, path)
495
+ assertAllowedKeys(raw, TASK_KEYS, path)
496
+ const id = requiredNonEmptyString(
497
+ raw['id'],
498
+ `${path}.id`,
499
+ `profile "${profileName}" has a task with an empty id`,
500
+ )
501
+ const subject = requiredNonEmptyString(
502
+ raw['subject'],
503
+ `${path}.subject`,
504
+ `profile task "${id}" is missing a subject`,
505
+ )
506
+ const description = optionalNonEmptyString(raw['description'], `${path}.description`)
507
+ const dependencies = normalizeDependencies(raw['dependencies'], `${path}.dependencies`, id)
508
+ const assignee = resolveTaskAssignee(
509
+ raw['assignee'],
510
+ `${path}.assignee`,
511
+ id,
512
+ requireAssignee,
513
+ memberByName,
514
+ memberByKey,
515
+ )
516
+ return omitUndefined({
517
+ id,
518
+ subject,
519
+ description,
520
+ assignee,
521
+ dependencies,
522
+ sourceIndex,
523
+ })
524
+ }
525
+
526
+ function normalizeDependencies(value: unknown, path: string, taskId: string): string[] {
527
+ if (value === undefined) return []
528
+ if (!Array.isArray(value)) {
529
+ throw new Error(`${path} must be an array of task ids`)
530
+ }
531
+ const dependencies: string[] = []
532
+ const seen = new Set<string>()
533
+ for (let index = 0; index < value.length; index += 1) {
534
+ const item = value[index]
535
+ if (typeof item !== 'string') {
536
+ throw new Error(`${path}[${index}] must be a string`)
537
+ }
538
+ const dependency = item.trim()
539
+ if (dependency === '') {
540
+ throw new Error(`${path}[${index}] must not be empty`)
541
+ }
542
+ if (dependency === taskId) {
543
+ throw new Error(`profile task "${taskId}" cannot depend on itself`)
544
+ }
545
+ if (seen.has(dependency)) continue
546
+ seen.add(dependency)
547
+ dependencies.push(dependency)
548
+ }
549
+ return dependencies
550
+ }
551
+
552
+ function resolveTaskAssignee(
553
+ value: unknown,
554
+ path: string,
555
+ taskId: string,
556
+ required: boolean,
557
+ memberByName: Map<string, NormalizedProfileMember>,
558
+ memberByKey: Map<string, NormalizedProfileMember>,
559
+ ): string | undefined {
560
+ if (value === undefined) {
561
+ if (required) {
562
+ throw new Error(`profile task "${taskId}" is missing an assignee`)
563
+ }
564
+ return undefined
565
+ }
566
+ if (typeof value !== 'string') {
567
+ throw new Error(`${path} must be a string`)
568
+ }
569
+ const trimmed = value.trim()
570
+ if (trimmed === '') {
571
+ throw new Error(`profile task "${taskId}" is missing an assignee`)
572
+ }
573
+ if (isCaptainName(trimmed)) {
574
+ throw new Error(`profile task "${taskId}" cannot assign work to the captain`)
575
+ }
576
+ const exact = memberByName.get(trimmed)
577
+ if (exact !== undefined) return exact.name
578
+ const fuzzy = memberByKey.get(sanitizeKey(trimmed))
579
+ if (fuzzy !== undefined) return fuzzy.name
580
+ throw new Error(`profile task "${taskId}" assignee "${trimmed}" is not a profile member`)
581
+ }
582
+
583
+ function topoSortTasks(tasks: NormalizedProfileTask[], profileName: string): NormalizedProfileTask[] {
584
+ const byId = new Map(tasks.map((task) => [task.id, task]))
585
+ for (const task of tasks) {
586
+ for (const dependency of task.dependencies) {
587
+ if (!byId.has(dependency)) {
588
+ throw new Error(`profile task "${task.id}" depends on unknown task "${dependency}"`)
589
+ }
590
+ }
591
+ }
592
+
593
+ const indegree = new Map<string, number>()
594
+ const outgoing = new Map<string, string[]>()
595
+ for (const task of tasks) {
596
+ indegree.set(task.id, 0)
597
+ outgoing.set(task.id, [])
598
+ }
599
+ for (const task of tasks) {
600
+ for (const dependency of task.dependencies) {
601
+ indegree.set(task.id, (indegree.get(task.id) ?? 0) + 1)
602
+ outgoing.get(dependency)?.push(task.id)
603
+ }
604
+ }
605
+
606
+ const ready = tasks
607
+ .filter((task) => (indegree.get(task.id) ?? 0) === 0)
608
+ .sort((left, right) => left.sourceIndex - right.sourceIndex)
609
+ const ordered: NormalizedProfileTask[] = []
610
+ while (ready.length > 0) {
611
+ const next = ready.shift()
612
+ if (next === undefined) break
613
+ ordered.push(next)
614
+ for (const childId of outgoing.get(next.id) ?? []) {
615
+ const remaining = (indegree.get(childId) ?? 0) - 1
616
+ indegree.set(childId, remaining)
617
+ if (remaining === 0) {
618
+ const child = byId.get(childId)
619
+ if (child === undefined) continue
620
+ ready.push(child)
621
+ ready.sort((left, right) => left.sourceIndex - right.sourceIndex)
622
+ }
623
+ }
624
+ }
625
+
626
+ if (ordered.length !== tasks.length) {
627
+ const cyclic = tasks
628
+ .filter((task) => !ordered.some((done) => done.id === task.id))
629
+ .map((task) => task.id)
630
+ throw new Error(formatCycleError(profileName, cyclic))
631
+ }
632
+ return ordered
633
+ }
634
+
635
+ function formatCycleError(_profileName: string, cyclic: string[]): string {
636
+ const first = cyclic[0] ?? 'unknown'
637
+ const second = cyclic[1]
638
+ if (cyclic.length === 1 || second === undefined) {
639
+ return `profile task "${first}" forms a dependency cycle`
640
+ }
641
+ if (cyclic.length === 2) {
642
+ return `profile task "${first}" and "${second}" form a dependency cycle`
643
+ }
644
+ const head = cyclic.slice(0, -1).map((id) => `"${id}"`).join(', ')
645
+ const tail = cyclic[cyclic.length - 1] ?? first
646
+ return `profile tasks ${head}, and "${tail}" form a dependency cycle`
647
+ }
648
+
649
+ function isCaptainName(name: string): boolean {
650
+ return name.trim().toLowerCase() === CAPTAIN_KEY || sanitizeKey(name) === CAPTAIN_KEY
651
+ }
652
+
653
+ function asProfilesRecord(
654
+ profiles: Record<string, TeamProfileConfig> | undefined | null,
655
+ ): Record<string, unknown> {
656
+ if (profiles === undefined || profiles === null) return {}
657
+ if (typeof profiles !== 'object' || Array.isArray(profiles)) {
658
+ throw new Error('AgentTeams profiles must be an object map of named templates')
659
+ }
660
+ return profiles as Record<string, unknown>
661
+ }
662
+
663
+ function asRecord(value: unknown, path: string): Record<string, unknown> {
664
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
665
+ throw new Error(`${path} must be an object`)
666
+ }
667
+ return value as Record<string, unknown>
668
+ }
669
+
670
+ function assertAllowedKeys(
671
+ value: Record<string, unknown>,
672
+ allowed: readonly string[],
673
+ path: string,
674
+ ): void {
675
+ const allow = new Set<string>(allowed)
676
+ for (const key of Object.keys(value)) {
677
+ if (allow.has(key)) continue
678
+ const suggestion = suggestField(key, allowed)
679
+ const hint = suggestion === undefined ? '' : `; did you mean ${suggestion}?`
680
+ throw new Error(`${path}.${key} is unknown${hint}`)
681
+ }
682
+ }
683
+
684
+ function suggestField(unknown: string, allowed: readonly string[]): string | undefined {
685
+ const lower = unknown.toLowerCase()
686
+ const exact = allowed.find((candidate) => candidate.toLowerCase() === lower)
687
+ if (exact !== undefined) return exact
688
+ let best: string | undefined
689
+ let bestDistance = Infinity
690
+ for (const candidate of allowed) {
691
+ const distance = levenshtein(lower, candidate.toLowerCase())
692
+ if (distance < bestDistance) {
693
+ bestDistance = distance
694
+ best = candidate
695
+ }
696
+ }
697
+ if (best !== undefined && bestDistance <= 2) return best
698
+ return undefined
699
+ }
700
+
701
+ function levenshtein(left: string, right: string): number {
702
+ const rows = left.length + 1
703
+ const cols = right.length + 1
704
+ const grid: number[][] = []
705
+ for (let row = 0; row < rows; row += 1) {
706
+ const line: number[] = []
707
+ for (let col = 0; col < cols; col += 1) {
708
+ if (row === 0) line.push(col)
709
+ else if (col === 0) line.push(row)
710
+ else line.push(0)
711
+ }
712
+ grid.push(line)
713
+ }
714
+ for (let row = 1; row < rows; row += 1) {
715
+ for (let col = 1; col < cols; col += 1) {
716
+ const cost = left[row - 1] === right[col - 1] ? 0 : 1
717
+ const del = (grid[row - 1]?.[col] ?? 0) + 1
718
+ const ins = (grid[row]?.[col - 1] ?? 0) + 1
719
+ const sub = (grid[row - 1]?.[col - 1] ?? 0) + cost
720
+ const cell = grid[row]
721
+ if (cell !== undefined) cell[col] = Math.min(del, ins, sub)
722
+ }
723
+ }
724
+ return grid[left.length]?.[right.length] ?? 0
725
+ }
726
+
727
+ function requiredNonEmptyString(
728
+ value: unknown,
729
+ path: string,
730
+ emptyMessage: string,
731
+ ): string {
732
+ if (value === undefined || typeof value !== 'string') {
733
+ throw new Error(`${path} must be a string`)
734
+ }
735
+ const trimmed = value.trim()
736
+ if (trimmed === '') throw new Error(emptyMessage)
737
+ return trimmed
738
+ }
739
+
740
+ /**
741
+ * Optional text field: absent, blank, and whitespace-only all mean "not
742
+ * provided". A blank string carries no information, and rejecting it turned a
743
+ * caller habit into a deadlock — a captain that fills every optional tool-call
744
+ * key with `""` could never create an inline plan (see
745
+ * `scripts/inline-plan-blank-optional-tdd.mjs`). The edit path already treats
746
+ * blanks this way through `trimmedOptional` in `tools.ts`; this keeps the
747
+ * profile normalizer on the same rule. Non-string values stay a hard error, and
748
+ * required fields keep `requiredNonEmptyString`.
749
+ */
750
+ function optionalNonEmptyString(value: unknown, path: string): string | undefined {
751
+ if (value === undefined) return undefined
752
+ if (typeof value !== 'string') {
753
+ throw new Error(`${path} must be a string`)
754
+ }
755
+ const trimmed = value.trim()
756
+ if (trimmed === '') return undefined
757
+ return trimmed
758
+ }
759
+
760
+ function omitUndefined<T extends object>(value: T): T {
761
+ for (const key of Object.keys(value) as Array<keyof T>) {
762
+ if (value[key] === undefined) delete value[key]
763
+ }
764
+ return value
765
+ }