@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
package/src/state.ts ADDED
@@ -0,0 +1,1317 @@
1
+ /**
2
+ * Team state persistence and pure team-logic rules.
3
+ *
4
+ * State lives on disk under `<workspace>/<stateDir>/<teamId>/`:
5
+ * - `team.json` — the durable {@link TeamState} record
6
+ * - `inbox/<agentKey>.jsonl` — one JSONL mailbox per agent (`captain` or a
7
+ * member name), mirroring the Claude Code AgentTeams mailbox layout
8
+ *
9
+ * All mutations run through an in-process per-team queue so read-modify-write
10
+ * stays serial; `fs/promises` is used directly because the plugin owns this
11
+ * bookkeeping (host-plane state, like session persistence) and the abstract
12
+ * `fs` service offers no directory deletion.
13
+ * @module dsh-agent-teams/state
14
+ */
15
+
16
+ import { createHash, randomUUID } from 'node:crypto'
17
+ import { readFileSync, renameSync, writeFileSync } from 'node:fs'
18
+ import { mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'
19
+ import { join } from 'node:path'
20
+ import type { MemberToolFilter } from './tool-policies.ts'
21
+ import { FINDING_SEVERITIES, REVIEW_VERDICTS, TASK_KINDS, TERMINAL_TASK_STATUSES, type ReviewFinding, type TaskStatus, type TeamMember, type TeamMessage, type TeamProfileSnapshot, type TeamState, type TeamTask } from './types.ts'
22
+ import { hasValidQualityTaskFields, isReviewPolicy, isValidFindingLine, normalizeBlankOptionalTaskFields } from './quality-gates.ts'
23
+ import { teamLeadMatch, type LeadIdentity } from './lineage.ts'
24
+
25
+ export {
26
+ amendTaskContract,
27
+ buildCoverageMatrix,
28
+ canDeclareDelivery,
29
+ classifyChangedPath,
30
+ collectChangedPaths,
31
+ defaultQualityDeliveryGraph,
32
+ describeQualityLoop,
33
+ evaluateQualityCompletion,
34
+ hasValidQualityTaskFields,
35
+ isQualityKind,
36
+ isTaskRevision,
37
+ isValidFindingLine,
38
+ normalizeBlankOptionalTaskFields,
39
+ normalizeSentinelNumericTaskFields,
40
+ pathMatchesScope,
41
+ planQualityFollowUp,
42
+ qualityPlanningPrompt,
43
+ resumeTeamState,
44
+ sanitizeReviewAcceptance,
45
+ sanitizeReviewObjective,
46
+ taskKindOf,
47
+ validateCreateTask,
48
+ } from './quality-gates.ts'
49
+ export type { ContractAmendmentInput } from './quality-gates.ts'
50
+
51
+ /** Mailbox key of the captain. */
52
+ export const CAPTAIN_KEY = 'captain'
53
+ /** A crashed live-delivery attempt becomes retryable after this interval. */
54
+ const MAILBOX_DELIVERY_LEASE_MS = 60_000
55
+ /** Durable deny-list for AgentTeams members that must never be resumed. */
56
+ const RETIRED_MEMBERS_FILE = 'retired-members.json'
57
+
58
+ /** In-process per-team mutation queues (promise chains). */
59
+ const locks = new Map<string, Promise<unknown>>()
60
+
61
+ /**
62
+ * Serialize mutations of one team across the whole process.
63
+ * @param key - the team id (or any mutation scope).
64
+ * @param fn - the mutation to run exclusively.
65
+ * @returns the mutation's result.
66
+ */
67
+ export async function withTeamLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
68
+ const previous = locks.get(key) ?? Promise.resolve()
69
+ let release!: () => void
70
+ const gate = new Promise<void>((resolve) => { release = resolve })
71
+ const tail = previous.then(() => gate)
72
+ locks.set(key, tail)
73
+ await previous
74
+ try {
75
+ return await fn()
76
+ } finally {
77
+ release()
78
+ // Drop this key's queue entry once we are still its tail, so settled
79
+ // teams do not leave one resolved promise chained forever (the same
80
+ // cleanup discipline as the scheduler's serializeMember). A successor
81
+ // that already appended itself owns the map slot; keep its entry.
82
+ if (locks.get(key) === tail) locks.delete(key)
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Keys with an in-process lock queue (held or waiting), snapshot for
88
+ * diagnostics and leak checks. The queue promises themselves stay private.
89
+ */
90
+ export function teamLockQueueKeys(): readonly string[] {
91
+ return [...locks.keys()]
92
+ }
93
+
94
+ /** Longest key emitted before truncating and appending a digest. */
95
+ const MAX_KEY_LENGTH = 48
96
+
97
+ /** Short stable digest, used to keep otherwise-colliding keys distinct. */
98
+ function keyDigest(name: string): string {
99
+ return createHash('sha256').update(name).digest('hex').slice(0, 8)
100
+ }
101
+
102
+ /**
103
+ * Fold a free-form name into a safe path/key segment.
104
+ *
105
+ * Unicode letters and digits survive, so CJK/Cyrillic/Greek names stay
106
+ * distinct and readable; everything else — spaces, punctuation, path
107
+ * separators, control characters — folds to `-`. An ASCII-only whitelist
108
+ * mapped *every* non-Latin name onto one shared fallback, which silently
109
+ * merged their mailboxes and rejected the second such member as a duplicate.
110
+ *
111
+ * A name with no letters or digits at all (pure emoji or punctuation) cannot
112
+ * yield a readable key, so it gets a digest rather than a shared constant.
113
+ * Over-long names are truncated with a digest appended, so names sharing a
114
+ * long prefix stay distinct and the result stays within filesystem limits
115
+ * (CJK costs 3 bytes per character in UTF-8).
116
+ *
117
+ * @param name - any user-supplied name.
118
+ * @returns a non-empty key safe as a single path segment.
119
+ */
120
+ export function sanitizeKey(name: string): string {
121
+ const cleaned = name.normalize('NFC').trim().toLowerCase()
122
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
123
+ .replace(/^-+|-+$/g, '')
124
+ if (cleaned === '') return `k-${keyDigest(name)}`
125
+ const points = [...cleaned]
126
+ if (points.length > MAX_KEY_LENGTH) {
127
+ return `${points.slice(0, MAX_KEY_LENGTH).join('')}-${keyDigest(name)}`
128
+ }
129
+ return cleaned
130
+ }
131
+
132
+ /**
133
+ * Whether `dependencies` are all satisfied (every named task exists and
134
+ * completed) for the given task list.
135
+ * @param tasks - the team's tasks.
136
+ * @param dependencies - task ids the candidate depends on.
137
+ * @returns the ids that are still unsatisfied, empty when claimable.
138
+ */
139
+ export function unsatisfiedDependencies(tasks: TeamTask[], dependencies: string[]): string[] {
140
+ const byId = new Map(tasks.map((task) => [task.id, task]))
141
+ return dependencies.filter((id) => byId.get(id)?.status !== 'completed')
142
+ }
143
+
144
+ /**
145
+ * The allowed task status transitions, keyed by current status.
146
+ * Terminal statuses have no outgoing transitions.
147
+ */
148
+ export const TASK_TRANSITIONS: Readonly<Record<TaskStatus, readonly TaskStatus[]>> = {
149
+ pending: ['claimed', 'cancelled'],
150
+ claimed: ['in_progress', 'failed', 'cancelled'],
151
+ in_progress: ['completed', 'failed', 'cancelled'],
152
+ completed: [],
153
+ failed: [],
154
+ cancelled: [],
155
+ }
156
+
157
+ /**
158
+ * Validate one task status transition.
159
+ * @param current - the task's current status.
160
+ * @param next - the requested status.
161
+ * @returns the transition error, or undefined when allowed.
162
+ */
163
+ export function transitionError(current: TaskStatus, next: TaskStatus): string | undefined {
164
+ if (current === next) return undefined
165
+ if (!TASK_TRANSITIONS[current].includes(next)) {
166
+ return `task status cannot move from "${current}" to "${next}"`
167
+ }
168
+ return undefined
169
+ }
170
+
171
+ /** Execution results belong to one attempt; a retry must produce its own evidence. */
172
+ function clearAttemptResult(task: TeamTask): void {
173
+ task.output = undefined
174
+ task.verdict = undefined
175
+ task.findings = undefined
176
+ task.changedPaths = undefined
177
+ task.acceptanceResults = undefined
178
+ task.commandsRun = undefined
179
+ }
180
+
181
+ /** Activate the task's current generation for one owner and return its capability id. */
182
+ export function activateTaskAttempt(task: TeamTask, assignee: string): string {
183
+ const attemptId = randomUUID()
184
+ task.status = 'claimed'
185
+ task.assignee = assignee
186
+ task.attemptId = attemptId
187
+ task.handoffId = undefined
188
+ task.reassigning = false
189
+ clearAttemptResult(task)
190
+ task.updatedAt = Date.now()
191
+ return attemptId
192
+ }
193
+
194
+ /** Start a fresh task generation for one owner. */
195
+ export function beginTaskAttempt(task: TeamTask, assignee: string): string {
196
+ task.attempt = (task.attempt ?? 0) + 1
197
+ return activateTaskAttempt(task, assignee)
198
+ }
199
+
200
+ /**
201
+ * Revoke the current worker immediately. Clearing its capability makes old
202
+ * updates stale; a separate handoff generation serializes async quiescence.
203
+ */
204
+ /** Cancel one unfinished task without returning it to the ready pool. */
205
+ export function cancelUnfinishedTask(task: TeamTask, output?: string): void {
206
+ if (TERMINAL_TASK_STATUSES.includes(task.status)) return
207
+ task.status = 'cancelled'
208
+ task.attemptId = undefined
209
+ task.handoffId = undefined
210
+ task.reassigning = false
211
+ if (output !== undefined) task.output = output
212
+ task.updatedAt = Date.now()
213
+ }
214
+
215
+ export function invalidateTaskAttempt(
216
+ task: TeamTask,
217
+ nextAssignee?: string,
218
+ reassigning = false,
219
+ ): void {
220
+ task.attemptId = undefined
221
+ task.handoffId = randomUUID()
222
+ task.status = 'pending'
223
+ task.assignee = nextAssignee
224
+ task.reassigning = reassigning
225
+ clearAttemptResult(task)
226
+ task.updatedAt = Date.now()
227
+ }
228
+
229
+ /**
230
+ * Create the team directory structure and the initial team record.
231
+ * @param stateRoot - resolved absolute state root directory.
232
+ * @param state - the initial team record.
233
+ */
234
+ export async function createTeamDir(stateRoot: string, state: TeamState): Promise<void> {
235
+ const dir = join(stateRoot, state.id)
236
+ await mkdir(join(dir, 'inbox'), { recursive: true })
237
+ await atomicWriteText(join(dir, 'team.json'), JSON.stringify(state, null, 2))
238
+ }
239
+
240
+ /**
241
+ * Read one team record; `undefined` when absent.
242
+ * @param stateRoot - resolved absolute state root directory.
243
+ * @param teamId - the team's sanitized id.
244
+ */
245
+ export async function readTeam(stateRoot: string, teamId: string): Promise<TeamState | undefined> {
246
+ try {
247
+ const raw = await readFile(join(stateRoot, teamId, 'team.json'), 'utf8')
248
+ const value: unknown = JSON.parse(stripLeadingBom(raw))
249
+ const team = coerceTeamState(value, teamId)
250
+ if (team === undefined) {
251
+ throw new Error(`invalid AgentTeams state in team "${teamId}": ${describeTeamStateDefect(value, teamId)}`)
252
+ }
253
+ return team
254
+ } catch (error: unknown) {
255
+ if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') {
256
+ return undefined
257
+ }
258
+ throw error
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Synchronously read one team record while a continuable child is being
264
+ * composed. Harness requires child setup contributions to be synchronous;
265
+ * this narrow boundary lets a cold-resumed member restore its durable model
266
+ * selection before its first request can be published.
267
+ * @param stateRoot - resolved absolute state root directory.
268
+ * @param teamId - the team's sanitized id.
269
+ * @returns the team record, or `undefined` when absent.
270
+ */
271
+ export function readTeamSync(stateRoot: string, teamId: string): TeamState | undefined {
272
+ try {
273
+ const raw = readFileSync(join(stateRoot, teamId, 'team.json'), 'utf8')
274
+ const value: unknown = JSON.parse(stripLeadingBom(raw))
275
+ const team = coerceTeamState(value, teamId)
276
+ if (team === undefined) {
277
+ throw new Error(`invalid AgentTeams state in team "${teamId}": ${describeTeamStateDefect(value, teamId)}`)
278
+ }
279
+ return team
280
+ } catch (error: unknown) {
281
+ if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') {
282
+ return undefined
283
+ }
284
+ throw error
285
+ }
286
+ }
287
+
288
+ /** Pair a cancellation-sensitive team replacement with its live effect. */
289
+ interface TeamWriteCommit {
290
+ signal: AbortSignal
291
+ onCommit: () => void
292
+ }
293
+
294
+ /**
295
+ * Persist one team record (inside the caller's lock).
296
+ * @param stateRoot - resolved absolute state root directory.
297
+ * @param state - the record to persist.
298
+ * @param commit - gate and synchronous effect for a cancellation-sensitive replacement.
299
+ */
300
+ export async function writeTeam(stateRoot: string, state: TeamState, commit?: TeamWriteCommit): Promise<void> {
301
+ await atomicWriteText(join(stateRoot, state.id, 'team.json'), JSON.stringify(state, null, 2), commit)
302
+ }
303
+
304
+ /** Read the durable set of member session ids retired by remove/delete. */
305
+ function parseRetiredMemberIds(raw: string): Set<string> {
306
+ const parsed: unknown = JSON.parse(stripLeadingBom(raw))
307
+ if (!Array.isArray(parsed) || parsed.some(value => typeof value !== 'string' || value === '')) {
308
+ throw new Error('invalid AgentTeams retired member index')
309
+ }
310
+ return new Set(parsed)
311
+ }
312
+
313
+ /** Synchronous role hydration before the host's first prompt assembly. */
314
+ export function readRetiredMemberIdsSync(stateRoot: string): Set<string> {
315
+ try { return parseRetiredMemberIds(readFileSync(join(stateRoot, RETIRED_MEMBERS_FILE), 'utf8')) } catch (error) {
316
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return new Set()
317
+ throw error
318
+ }
319
+ }
320
+
321
+ export async function readRetiredMemberIds(stateRoot: string): Promise<Set<string>> {
322
+ try {
323
+ return parseRetiredMemberIds(await readFile(join(stateRoot, RETIRED_MEMBERS_FILE), 'utf8'))
324
+ } catch (error: unknown) {
325
+ if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') {
326
+ return new Set()
327
+ }
328
+ throw error
329
+ }
330
+ }
331
+
332
+ /** Atomically add session ids to the durable retired-member deny-list. */
333
+ export async function recordRetiredMemberIds(stateRoot: string, memberIds: readonly string[]): Promise<void> {
334
+ const additions = memberIds.filter(id => id !== '')
335
+ if (additions.length === 0) return
336
+ await withTeamLock(`retired-members:${stateRoot}`, async () => {
337
+ const retired = await readRetiredMemberIds(stateRoot)
338
+ for (const id of additions) retired.add(id)
339
+ await mkdir(stateRoot, { recursive: true })
340
+ await atomicWriteText(
341
+ join(stateRoot, RETIRED_MEMBERS_FILE),
342
+ `${JSON.stringify([...retired].sort(), null, 2)}\n`,
343
+ )
344
+ })
345
+ }
346
+
347
+ /**
348
+ * Find the team owned by one captain session (at most one per captain).
349
+ * @param stateRoot - resolved absolute state root directory.
350
+ * @param captainSessionId - the owning session id.
351
+ * @param lead - durable lead identity of the calling session, when it may lead
352
+ * through a fork chain; omitted keeps the exact-id contract.
353
+ * @returns the team record, or undefined when the captain leads no team.
354
+ */
355
+ export async function findTeamByCaptain(
356
+ stateRoot: string,
357
+ captainSessionId: string,
358
+ lead?: LeadIdentity,
359
+ ): Promise<TeamState | undefined> {
360
+ let entries
361
+ try {
362
+ entries = await readdir(stateRoot, { withFileTypes: true })
363
+ } catch (error: unknown) {
364
+ if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') {
365
+ return undefined
366
+ }
367
+ throw error
368
+ }
369
+ let found: TeamState | undefined
370
+ for (const entry of entries) {
371
+ if (!entry.isDirectory()) continue
372
+ const team = await readTeam(stateRoot, entry.name)
373
+ if (team !== undefined && (team.captainSessionId === captainSessionId
374
+ || (lead !== undefined && teamLeadMatch(team, lead)))) {
375
+ if (found !== undefined && found.id !== team.id) {
376
+ throw new Error(`captain session leads multiple active teams ("${found.id}", "${team.id}"); archive one before continuing`)
377
+ }
378
+ found = team
379
+ }
380
+ }
381
+ return found
382
+ }
383
+
384
+ /**
385
+ * Find the team in which one session is an active participant.
386
+ * Captains match `captainSessionId` — including a lead session that inherited
387
+ * it through a fork — and members match their durable child session id.
388
+ * Removed members no longer have access to team-scoped tools.
389
+ * @param stateRoot - resolved absolute state root directory.
390
+ * @param agentSessionId - calling captain/member session id.
391
+ * @param lead - durable lead identity of the calling session, when available.
392
+ * @returns the team record, or undefined when the caller belongs to no team.
393
+ */
394
+ export async function findTeamByParticipant(
395
+ stateRoot: string,
396
+ agentSessionId: string,
397
+ lead?: LeadIdentity,
398
+ ): Promise<TeamState | undefined> {
399
+ let entries
400
+ try {
401
+ entries = await readdir(stateRoot, { withFileTypes: true })
402
+ } catch (error: unknown) {
403
+ if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') {
404
+ return undefined
405
+ }
406
+ throw error
407
+ }
408
+ let found: TeamState | undefined
409
+ for (const entry of entries) {
410
+ if (!entry.isDirectory()) continue
411
+ const team = await readTeam(stateRoot, entry.name)
412
+ const participates = team !== undefined && (team.captainSessionId === agentSessionId
413
+ || (lead !== undefined && teamLeadMatch(team, lead))
414
+ || team.members.some((member) => member.id === agentSessionId && member.status !== 'removed'))
415
+ if (participates && team !== undefined) {
416
+ if (found !== undefined && found.id !== team.id) {
417
+ throw new Error(`agent session belongs to multiple active teams ("${found.id}", "${team.id}"); the target team is ambiguous`)
418
+ }
419
+ found = team
420
+ }
421
+ }
422
+ return found
423
+ }
424
+
425
+ /** Build a fresh message record. */
426
+ export function createMessage(from: string, to: string, content: string): TeamMessage {
427
+ return { id: randomUUID(), from, to, content, ts: Date.now() }
428
+ }
429
+
430
+ /**
431
+ * Append one message to an agent's mailbox (JSONL).
432
+ * @param stateRoot - resolved absolute state root directory.
433
+ * @param teamId - the team id.
434
+ * @param agentKey - `captain` or a member name.
435
+ * @param message - the message to append.
436
+ */
437
+ export async function appendMailbox(
438
+ stateRoot: string,
439
+ teamId: string,
440
+ agentKey: string,
441
+ message: TeamMessage,
442
+ ): Promise<void> {
443
+ const file = join(stateRoot, teamId, 'inbox', `${sanitizeKey(agentKey)}.jsonl`)
444
+ await mkdir(join(stateRoot, teamId, 'inbox'), { recursive: true })
445
+ let existing = ''
446
+ try {
447
+ existing = await readFile(file, 'utf8')
448
+ } catch (error: unknown) {
449
+ if (!(error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT')) {
450
+ throw error
451
+ }
452
+ }
453
+ const separator = existing !== '' && !existing.endsWith('\n') ? '\n' : ''
454
+ await atomicWriteText(file, `${existing}${separator}${JSON.stringify(message)}\n`)
455
+ }
456
+
457
+ /**
458
+ * Read one agent's whole mailbox, oldest first.
459
+ * @param stateRoot - resolved absolute state root directory.
460
+ * @param teamId - the team id.
461
+ * @param agentKey - `captain` or a member name.
462
+ * @param onMalformedLine - optional diagnostic hook; malformed records are
463
+ * skipped so one manually damaged line cannot make the whole team unreadable.
464
+ * @returns the messages, empty when the mailbox does not exist yet.
465
+ */
466
+ export async function readMailbox(
467
+ stateRoot: string,
468
+ teamId: string,
469
+ agentKey: string,
470
+ onMalformedLine?: (lineNumber: number, error: unknown) => void,
471
+ ): Promise<TeamMessage[]> {
472
+ const file = join(stateRoot, teamId, 'inbox', `${sanitizeKey(agentKey)}.jsonl`)
473
+ try {
474
+ const raw = await readFile(file, 'utf8')
475
+ const messages: TeamMessage[] = []
476
+ for (const [index, rawLine] of raw.split('\n').entries()) {
477
+ const line = stripLeadingBom(rawLine)
478
+ if (line.trim() === '') continue
479
+ let value: unknown
480
+ try {
481
+ value = JSON.parse(line)
482
+ } catch {
483
+ onMalformedLine?.(index + 1, new Error('invalid JSON'))
484
+ continue
485
+ }
486
+ if (!isTeamMessage(value)) {
487
+ onMalformedLine?.(index + 1, new Error('invalid message shape'))
488
+ continue
489
+ }
490
+ messages.push(value)
491
+ }
492
+ return messages
493
+ } catch (error: unknown) {
494
+ if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') {
495
+ return []
496
+ }
497
+ throw error
498
+ }
499
+ }
500
+
501
+ /** Read only messages that have not been acknowledged by their recipient. */
502
+ export async function readUnreadMailbox(
503
+ stateRoot: string,
504
+ teamId: string,
505
+ agentKey: string,
506
+ onMalformedLine?: (lineNumber: number, error: unknown) => void,
507
+ ): Promise<TeamMessage[]> {
508
+ return (await readMailbox(stateRoot, teamId, agentKey, onMalformedLine))
509
+ .filter(message => message.readAt === undefined && message.discardedAt === undefined)
510
+ }
511
+
512
+ /** Pending delivery is distinct from delivered-but-not-yet-read input. */
513
+ export async function readPendingMailbox(stateRoot: string, teamId: string, agentKey: string): Promise<TeamMessage[]> {
514
+ const now = Date.now()
515
+ return (await readUnreadMailbox(stateRoot, teamId, agentKey))
516
+ .filter(message => message.deliveredAt === undefined
517
+ && (message.deliveryClaimedAt === undefined
518
+ || now - message.deliveryClaimedAt >= MAILBOX_DELIVERY_LEASE_MS))
519
+ }
520
+
521
+ async function mutateMailbox(
522
+ stateRoot: string,
523
+ teamId: string,
524
+ agentKey: string,
525
+ messageIds: readonly string[],
526
+ mutate: (message: TeamMessage) => TeamMessage,
527
+ ): Promise<void> {
528
+ if (messageIds.length === 0) return
529
+ const file = join(stateRoot, teamId, 'inbox', `${sanitizeKey(agentKey)}.jsonl`)
530
+ let raw: string
531
+ try {
532
+ raw = await readFile(file, 'utf8')
533
+ } catch (error: unknown) {
534
+ if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') return
535
+ throw error
536
+ }
537
+ const selected = new Set(messageIds)
538
+ const lines = raw.split('\n').map((rawLine) => {
539
+ const line = stripLeadingBom(rawLine)
540
+ if (line.trim() === '') return rawLine
541
+ try {
542
+ const value: unknown = JSON.parse(line)
543
+ if (!isTeamMessage(value) || !selected.has(value.id)) return rawLine
544
+ return JSON.stringify(mutate(value))
545
+ } catch {
546
+ return rawLine
547
+ }
548
+ })
549
+ await atomicWriteText(file, lines.join('\n'))
550
+ }
551
+
552
+ /** Lease selected fallback messages to one delivery path. */
553
+ export async function claimMailboxDelivery(
554
+ stateRoot: string,
555
+ teamId: string,
556
+ agentKey: string,
557
+ messageIds: readonly string[],
558
+ ): Promise<void> {
559
+ const now = Date.now()
560
+ await mutateMailbox(stateRoot, teamId, agentKey, messageIds, message => ({
561
+ ...message,
562
+ deliveryClaimedAt: now,
563
+ }))
564
+ }
565
+
566
+ /** Release a failed delivery lease so the scheduler can retry it later. */
567
+ export async function releaseMailboxDelivery(
568
+ stateRoot: string,
569
+ teamId: string,
570
+ agentKey: string,
571
+ messageIds: readonly string[],
572
+ ): Promise<void> {
573
+ await mutateMailbox(stateRoot, teamId, agentKey, messageIds, (message) => {
574
+ const { deliveryClaimedAt: _claimed, ...released } = message
575
+ return released
576
+ })
577
+ }
578
+
579
+ /**
580
+ * Mark selected durable mailbox records delivered/read while preserving
581
+ * malformed lines for diagnostics. Callers serialize this with the team lock.
582
+ */
583
+ export async function acknowledgeMailbox(
584
+ stateRoot: string,
585
+ teamId: string,
586
+ agentKey: string,
587
+ messageIds: readonly string[],
588
+ ): Promise<void> {
589
+ const now = Date.now()
590
+ await mutateMailbox(stateRoot, teamId, agentKey, messageIds, (message) => {
591
+ const { deliveryClaimedAt: _claimed, ...rest } = message
592
+ return {
593
+ ...rest,
594
+ deliveredAt: message.deliveredAt ?? now,
595
+ readAt: message.readAt ?? now,
596
+ }
597
+ })
598
+ }
599
+
600
+ /** Acceptance by Harness is not evidence that a model step consumed input. */
601
+ export async function markMailboxDelivered(stateRoot: string, teamId: string, agentKey: string, ids: readonly string[]): Promise<void> {
602
+ await mutateMailbox(stateRoot, teamId, agentKey, ids, (message) => {
603
+ const { deliveryClaimedAt: _claimed, ...rest } = message
604
+ return { ...rest, deliveredAt: message.deliveredAt ?? Date.now() }
605
+ })
606
+ }
607
+
608
+ export async function discardMailboxMessages(stateRoot: string, teamId: string, agentKey: string, ids: readonly string[]): Promise<void> {
609
+ await mutateMailbox(stateRoot, teamId, agentKey, ids, message => ({ ...message, discardedAt: message.discardedAt ?? Date.now() }))
610
+ }
611
+
612
+ /** Remove the optional UTF-8 BOM some editors prepend to JSON text. */
613
+ function stripLeadingBom(value: string): string {
614
+ return value.charCodeAt(0) === 0xFEFF ? value.slice(1) : value
615
+ }
616
+
617
+ /** Rename attempts before falling back to a direct overwrite. */
618
+ const ATOMIC_RENAME_RETRIES = 3
619
+ /** Pause between rename attempts, giving a briefly-locking owner time to finish. */
620
+ const ATOMIC_RENAME_RETRY_DELAY_MS = 50
621
+ /**
622
+ * Rename error codes worth retrying before the direct-write fallback. On
623
+ * Windows, replacing an existing file whose target is momentarily held open
624
+ * without FILE_SHARE_DELETE surfaces as EPERM (or EACCES/EBUSY variants);
625
+ * EEXIST/ENOTEMPTY cover other "target busy" edge shapes.
626
+ */
627
+ const RETRYABLE_RENAME_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'EEXIST', 'ENOTEMPTY'])
628
+
629
+ function isRetryableRenameError(error: unknown): boolean {
630
+ return error instanceof Error
631
+ && 'code' in error
632
+ && RETRYABLE_RENAME_CODES.has((error as NodeJS.ErrnoException).code ?? '')
633
+ }
634
+
635
+ function sleep(ms: number): Promise<void> {
636
+ return new Promise((resolve) => setTimeout(resolve, ms))
637
+ }
638
+
639
+ /** Filesystem primitives used by {@link replaceFileAtomicOrDirect}; injectable for tests. */
640
+ export interface AtomicReplacePrimitives {
641
+ rename: (from: string, to: string) => Promise<void>
642
+ writeFile: (file: string, content: string) => Promise<void>
643
+ remove: (file: string) => Promise<void>
644
+ }
645
+
646
+ /** Tuning knobs for {@link replaceFileAtomicOrDirect} (defaults match production). */
647
+ export interface AtomicReplaceOptions {
648
+ /** Rename attempts before the direct-write fallback (default 3). */
649
+ retries?: number
650
+ /** Delay between rename attempts in ms (default 50). */
651
+ retryDelayMs?: number
652
+ }
653
+
654
+ /**
655
+ * Replace `file` with `content`, preferring an atomic same-directory rename of
656
+ * an already-written temp file.
657
+ *
658
+ * On Windows, `rename(tmp, file)` over an existing target throws EPERM while
659
+ * any other process keeps the target open without FILE_SHARE_DELETE (editors,
660
+ * indexers, antivirus scans, preview panes). By that point the payload has
661
+ * already been fully written to the temp file, so a direct overwrite of the
662
+ * target is a content-equivalent degraded path: retry the rename a few times
663
+ * (transient locks clear quickly), then write the target in place. Every path
664
+ * removes the temp file; when both the atomic rename and the direct write
665
+ * fail, the combined error surfaces as an {@link AggregateError}.
666
+ *
667
+ * @returns nothing once the file has been replaced by one of the two paths.
668
+ */
669
+ export async function replaceFileAtomicOrDirect(
670
+ temporary: string,
671
+ file: string,
672
+ content: string,
673
+ primitives: AtomicReplacePrimitives,
674
+ options: AtomicReplaceOptions = {},
675
+ ): Promise<void> {
676
+ const retries = options.retries ?? ATOMIC_RENAME_RETRIES
677
+ const retryDelayMs = options.retryDelayMs ?? ATOMIC_RENAME_RETRY_DELAY_MS
678
+ for (let attempt = 0; ; attempt += 1) {
679
+ try {
680
+ await primitives.rename(temporary, file)
681
+ return
682
+ } catch (error: unknown) {
683
+ if (isRetryableRenameError(error) && attempt < retries) {
684
+ await sleep(retryDelayMs)
685
+ continue
686
+ }
687
+ let fallbackError: unknown
688
+ try {
689
+ await primitives.writeFile(file, content)
690
+ } catch (writeError: unknown) {
691
+ fallbackError = writeError
692
+ }
693
+ await primitives.remove(temporary).catch(() => undefined)
694
+ if (fallbackError !== undefined) {
695
+ throw new AggregateError(
696
+ [error, fallbackError],
697
+ `failed to replace "${file}" atomically (${String(error)}) or by direct write (${String(fallbackError)})`,
698
+ )
699
+ }
700
+ return
701
+ }
702
+ }
703
+ }
704
+
705
+ /**
706
+ * Atomically replace one UTF-8 state file from a same-directory temp file,
707
+ * degrading to a direct overwrite when the atomic rename cannot proceed
708
+ * (see {@link replaceFileAtomicOrDirect} for the Windows EPERM rationale).
709
+ */
710
+ async function atomicWriteText(file: string, content: string, commit?: TeamWriteCommit): Promise<void> {
711
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`
712
+ try {
713
+ await writeFile(temporary, content, { encoding: 'utf8', flag: 'wx' })
714
+ } catch (error: unknown) {
715
+ await rm(temporary, { force: true }).catch(() => undefined)
716
+ throw error
717
+ }
718
+ // Stage bytes asynchronously. Guarded callers install the file and apply
719
+ // its live effect in the same JS turn, so abort can never leave a canceled
720
+ // route visible to a synchronous cold read while the rename is pending.
721
+ const remove = (path: string) => rm(path, { force: true })
722
+ let effectFailure: { error: unknown } | undefined
723
+ const commitIfActive = (replace: () => void): boolean => {
724
+ if (commit?.signal.aborted) return false
725
+ replace()
726
+ // An effect failure is not a filesystem failure. Do not let the Windows
727
+ // retry/direct overwrite run the effect again.
728
+ try { commit?.onCommit() } catch (error) { effectFailure = { error } }
729
+ return true
730
+ }
731
+ await replaceFileAtomicOrDirect(temporary, file, content, {
732
+ rename: commit === undefined ? (from, to) => rename(from, to) : async (from, to) => {
733
+ if (!commitIfActive(() => renameSync(from, to))) await remove(from).catch(() => undefined)
734
+ },
735
+ writeFile: commit === undefined ? (target, payload) => writeFile(target, payload, 'utf8') : async (target, payload) => {
736
+ commitIfActive(() => writeFileSync(target, payload, 'utf8'))
737
+ },
738
+ remove,
739
+ })
740
+ if (effectFailure !== undefined) throw effectFailure.error
741
+ }
742
+
743
+ /** Whether a parsed JSON value is a plain record. */
744
+ function isRecord(value: unknown): value is Record<string, unknown> {
745
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
746
+ }
747
+
748
+ /** Whether a value is an optional string. */
749
+ function isOptionalString(value: unknown): value is string | undefined {
750
+ return value === undefined || typeof value === 'string'
751
+ }
752
+
753
+ /** Whether a value is a non-empty (non-blank) string. */
754
+ function nonemptyString(value: unknown): value is string {
755
+ return typeof value === 'string' && value.trim() !== ''
756
+ }
757
+
758
+ /** Whether a value is an absent or non-blank string (a persisted id/name). */
759
+ function isOptionalNonBlankString(value: unknown): value is string | undefined {
760
+ return value === undefined || (typeof value === 'string' && value.trim() !== '')
761
+ }
762
+
763
+ /** Whether a value is a non-empty list of non-blank tool names. */
764
+ function isToolNameList(value: unknown): value is string[] {
765
+ return Array.isArray(value)
766
+ && value.length > 0
767
+ && value.every(name => typeof name === 'string' && name.trim() !== '')
768
+ }
769
+
770
+ /**
771
+ * Validate one persisted effective tool filter (#59). `deny` is part of the
772
+ * contract and never empty (the captain-only deny list is always included); an
773
+ * `allow` list, when present, is non-empty for the same reason. A wrong-typed
774
+ * or empty list is rejected instead of being silently accepted at the durable
775
+ * boundary — the same class of drift #188 fixed for team records.
776
+ */
777
+ function isMemberToolFilter(value: unknown): value is MemberToolFilter {
778
+ if (!isRecord(value)) return false
779
+ const allow = value['allow']
780
+ const deny = value['deny']
781
+ if (allow !== undefined && !isToolNameList(allow)) return false
782
+ return isToolNameList(deny)
783
+ }
784
+
785
+ /** Whether a value is a finite timestamp/counter number. */
786
+ function isFiniteNumber(value: unknown): value is number {
787
+ return typeof value === 'number' && Number.isFinite(value)
788
+ }
789
+
790
+ /** Validate one member record at the durable JSON boundary. */
791
+ function isTeamMember(value: unknown): value is TeamMember {
792
+ if (!isRecord(value)) return false
793
+ return typeof value['id'] === 'string'
794
+ && typeof value['name'] === 'string'
795
+ && value['name'].trim() !== ''
796
+ && isOptionalString(value['role'])
797
+ && (value['stopping'] === undefined || typeof value['stopping'] === 'boolean')
798
+ && isOptionalString(value['provider'])
799
+ && isOptionalString(value['model'])
800
+ && isOptionalString(value['reasoningEffort'])
801
+ && isOptionalString(value['activeProvider'])
802
+ && isOptionalString(value['activeModel'])
803
+ && isOptionalString(value['spawnError'])
804
+ && (value['executionPrompt'] === undefined || typeof value['executionPrompt'] === 'string')
805
+ && (value['fallback'] === undefined || (isRecord(value['fallback']) && typeof value['fallback']['provider'] === 'string' && typeof value['fallback']['model'] === 'string'))
806
+ && (value['fallbackActive'] === undefined || typeof value['fallbackActive'] === 'boolean')
807
+ // A member without a policy keeps the legacy shape: both fields stay absent.
808
+ && isOptionalNonBlankString(value['toolPolicy'])
809
+ && (value['toolFilter'] === undefined || isMemberToolFilter(value['toolFilter']))
810
+ && (value['runtimeSetup'] === undefined || (isRecord(value['runtimeSetup'])
811
+ && typeof value['runtimeSetup']['persona'] === 'string'
812
+ && isMemberToolFilter(value['runtimeSetup']['toolFilter'])))
813
+ && isFiniteNumber(value['joinedAt'])
814
+ && (value['status'] === 'idle' || value['status'] === 'working' || value['status'] === 'removed')
815
+ }
816
+
817
+ /** Validate one task record at the durable JSON boundary. */
818
+ function isTeamProfileSnapshot(value: unknown): value is TeamProfileSnapshot {
819
+ return isRecord(value)
820
+ && typeof value['name'] === 'string'
821
+ && value['name'].trim() !== ''
822
+ && isOptionalString(value['description'])
823
+ && isOptionalString(value['protocol'])
824
+ && (value['executionPrompt'] === undefined || typeof value['executionPrompt'] === 'string')
825
+ && (value['fallback'] === undefined || (isRecord(value['fallback']) && typeof value['fallback']['provider'] === 'string' && typeof value['fallback']['model'] === 'string'))
826
+ && (value['taskPlanning'] === undefined || value['taskPlanning'] === 'captain' || value['taskPlanning'] === 'seed')
827
+ && (value['reviewPolicy'] === undefined || isReviewPolicy(value['reviewPolicy']))
828
+ }
829
+
830
+ function coerceProfileSnapshot(value: unknown): TeamProfileSnapshot | undefined {
831
+ if (typeof value === 'string') {
832
+ const name = value.trim()
833
+ return name === '' ? undefined : { name }
834
+ }
835
+ if (!isRecord(value)) return undefined
836
+ if (!isTeamProfileSnapshot(value)) return undefined
837
+ return {
838
+ name: value.name.trim(),
839
+ ...value.description === undefined ? {} : { description: value.description },
840
+ ...value.protocol === undefined ? {} : { protocol: value.protocol },
841
+ ...value.taskPlanning === undefined ? {} : { taskPlanning: value.taskPlanning },
842
+ }
843
+ }
844
+
845
+ function coerceTeamState(value: unknown, expectedId: string): TeamState | undefined {
846
+ if (!isRecord(value)) return undefined
847
+ if (value['profile'] !== undefined && !isTeamProfileSnapshot(value['profile']) && typeof value['profile'] !== 'string') {
848
+ const next = { ...value }
849
+ delete next['profile']
850
+ value = next
851
+ } else if (typeof value['profile'] === 'string') {
852
+ const upgraded = coerceProfileSnapshot(value['profile'])
853
+ value = upgraded === undefined
854
+ ? (() => {
855
+ const next = { ...value as Record<string, unknown> }
856
+ delete next['profile']
857
+ return next
858
+ })()
859
+ : { ...value, profile: upgraded }
860
+ }
861
+ if (!isRecord(value) || !Array.isArray(value['tasks'])) {
862
+ return isTeamState(value, expectedId) ? value : undefined
863
+ }
864
+ const tasks = (value['tasks'] as unknown[]).map((task) => {
865
+ if (!isRecord(task)) return task
866
+ // Tolerate legacy dirty records instead of bricking the whole team on
867
+ // reload: blank optional fields written by older builds (or by models that
868
+ // materialize optionals as "") are normalized to omitted, matching the
869
+ // profileSeedId handling below and the tool-input normalization. The same
870
+ // pass drops out-of-contract numeric sentinels such as `line: -1`
871
+ // (issue #188), so an already-written bad record self-heals on read.
872
+ const cleaned = normalizeBlankOptionalTaskFields(task)
873
+ if (cleaned['profileSeedId'] !== undefined && (typeof cleaned['profileSeedId'] !== 'string' || cleaned['profileSeedId'].trim() === '')) {
874
+ const next = { ...cleaned }
875
+ delete next['profileSeedId']
876
+ return next
877
+ }
878
+ return cleaned
879
+ })
880
+ const coerced = { ...value, tasks }
881
+ return isTeamState(coerced, expectedId) ? coerced : undefined
882
+ }
883
+
884
+ /**
885
+ * Name the first durable defect in a record `coerceTeamState` rejected. Before
886
+ * this, a rejected `team.json` surfaced only as
887
+ * `invalid AgentTeams state in team "x"` — no task, no field, no value — while
888
+ * every AgentTeams tool (read *and* write) failed at once, leaving an operator
889
+ * to bisect the file by hand (issue #188). The detail is computed only on the
890
+ * failure path, so the happy path keeps its existing cost.
891
+ * @param raw - the parsed record as read from disk, before coercion.
892
+ * @param expectedId - the team id the record was read for.
893
+ * @returns a `task "t2": findings[0].line -1 must be ...` style detail.
894
+ */
895
+ export function describeTeamStateDefect(raw: unknown, expectedId: string): string {
896
+ if (!isRecord(raw)) return 'record must be a JSON object'
897
+ if (!Array.isArray(raw['tasks'])) {
898
+ return raw['tasks'] === undefined ? 'tasks is missing' : `tasks must be an array (got ${typeof raw['tasks']})`
899
+ }
900
+ const tasks = (raw['tasks'] as unknown[]).map((task) => isRecord(task) ? normalizeBlankOptionalTaskFields(task) : task)
901
+ for (const [index, task] of tasks.entries()) {
902
+ if (!isRecord(task)) return `tasks[${index}] must be an object`
903
+ const label = typeof task['id'] === 'string' && task['id'] !== '' ? `task "${task['id'] as string}"` : `tasks[${index}]`
904
+ const detail = describeTaskDefect(task)
905
+ if (detail === undefined) continue
906
+ return `${label}: ${detail}`
907
+ }
908
+ const ids = tasks.filter(isRecord).map((task) => task['id'])
909
+ if (ids.some((id) => typeof id !== 'string' || id === '')) return 'a task id must be a non-empty string'
910
+ const seen = new Set<string>()
911
+ for (const id of ids as string[]) {
912
+ if (seen.has(id)) return `task "${id}": duplicated task id`
913
+ seen.add(id)
914
+ }
915
+ if (raw['id'] !== expectedId) return `id ${JSON.stringify(raw['id'])} must equal "${expectedId}"`
916
+ if (typeof raw['name'] !== 'string' || raw['name'].trim() === '') return 'name must be a non-empty string'
917
+ if (!isOptionalString(raw['description'])) return 'description must be a string'
918
+ if (raw['profile'] !== undefined && !isTeamProfileSnapshot(raw['profile'])) return 'profile is not a valid profile snapshot'
919
+ if (typeof raw['captainSessionId'] !== 'string' || raw['captainSessionId'] === '') return 'captainSessionId must be a non-empty string'
920
+ if (!isFiniteNumber(raw['createdAt'])) return 'createdAt must be a finite number'
921
+ if (!Array.isArray(raw['members'])) return 'members must be an array'
922
+ const memberKeys = new Set<string>()
923
+ const memberIds = new Set<string>()
924
+ for (const [index, member] of (raw['members'] as unknown[]).entries()) {
925
+ if (!isTeamMember(member)) return `members[${index}] is not a valid member record`
926
+ const key = sanitizeKey(member.name)
927
+ if (key === CAPTAIN_KEY) return `members[${index}]: name "${member.name}" is reserved for the captain`
928
+ if (memberKeys.has(key)) return `members[${index}]: name "${member.name}" is already used by another member`
929
+ memberKeys.add(key)
930
+ if (member.id === '') continue
931
+ if (memberIds.has(member.id)) return `members[${index}]: id "${member.id}" is duplicated`
932
+ memberIds.add(member.id)
933
+ }
934
+ if (!Number.isSafeInteger(raw['taskSeq']) || (raw['taskSeq'] as number) < 0) return 'taskSeq must be an integer >= 0'
935
+ if (raw['phase'] !== undefined && raw['phase'] !== 'staged' && raw['phase'] !== 'running') {
936
+ return `phase ${JSON.stringify(raw['phase'])} must be "staged" or "running"`
937
+ }
938
+ if (raw['planReviewState'] !== undefined
939
+ && raw['planReviewState'] !== 'awaiting_review'
940
+ && raw['planReviewState'] !== 'awaiting_feedback') {
941
+ return `planReviewState ${JSON.stringify(raw['planReviewState'])} is invalid`
942
+ }
943
+ for (const key of ['approvedAt', 'haltedAt'] as const) {
944
+ if (raw[key] !== undefined && !isFiniteNumber(raw[key])) return `${key} must be a finite number`
945
+ }
946
+ if (raw['halted'] !== undefined && typeof raw['halted'] !== 'boolean') return 'halted must be a boolean'
947
+ if (raw['reviewPolicy'] !== undefined && !isReviewPolicy(raw['reviewPolicy'])) return 'reviewPolicy is invalid'
948
+ if (raw['escalated'] !== undefined && typeof raw['escalated'] !== 'boolean') return 'escalated must be a boolean'
949
+ return 'record does not satisfy the durable team contract'
950
+ }
951
+
952
+ /** The first task-contract violation, or `undefined` when the task is valid. */
953
+ function describeTaskDefect(task: Record<string, unknown>): string | undefined {
954
+ if (typeof task['id'] !== 'string') return 'id must be a string'
955
+ if (!isOptionalString(task['profileSeedId'])) return 'profileSeedId must be a string'
956
+ if (typeof task['profileSeedId'] === 'string' && task['profileSeedId'].trim() === '') return 'profileSeedId must not be blank'
957
+ if (typeof task['subject'] !== 'string') return 'subject must be a string'
958
+ if (!isOptionalString(task['description'])) return 'description must be a string'
959
+ const statuses = ['pending', 'claimed', 'in_progress', 'completed', 'failed', 'cancelled']
960
+ if (!statuses.includes(task['status'] as string)) return `status ${JSON.stringify(task['status'])} is invalid`
961
+ if (!isOptionalString(task['assignee'])) return 'assignee must be a string'
962
+ if (!Array.isArray(task['dependencies'])) return 'dependencies must be an array'
963
+ if (!(task['dependencies'] as unknown[]).every((dependency) => typeof dependency === 'string')) return 'dependencies must contain only strings'
964
+ if (!isOptionalString(task['output'])) return 'output must be a string'
965
+ if (task['attempt'] !== undefined && !(Number.isSafeInteger(task['attempt']) && (task['attempt'] as number) >= 0)) {
966
+ return `attempt ${JSON.stringify(task['attempt'])} must be an integer >= 0`
967
+ }
968
+ if (!isOptionalString(task['attemptId'])) return 'attemptId must be a string'
969
+ if (!isOptionalString(task['handoffId'])) return 'handoffId must be a string'
970
+ if (!isOptionalString(task['handoffFromMemberId'])) return 'handoffFromMemberId must be a string'
971
+ if (task['reassigning'] !== undefined && typeof task['reassigning'] !== 'boolean') return 'reassigning must be a boolean'
972
+ if (!isFiniteNumber(task['createdAt'])) return 'createdAt must be a finite number'
973
+ if (!isFiniteNumber(task['updatedAt'])) return 'updatedAt must be a finite number'
974
+ return describeQualityTaskDefect(task)
975
+ }
976
+
977
+ /** Mirror of `hasValidQualityTaskFields`, reporting the first failing field. */
978
+ function describeQualityTaskDefect(task: Record<string, unknown>): string | undefined {
979
+ if (task['kind'] !== undefined && !(TASK_KINDS as readonly string[]).includes(task['kind'] as string)) {
980
+ return `kind ${JSON.stringify(task['kind'])} is invalid`
981
+ }
982
+ if (task['verdict'] !== undefined && !(REVIEW_VERDICTS as readonly string[]).includes(task['verdict'] as string)) {
983
+ return `verdict ${JSON.stringify(task['verdict'])} is invalid`
984
+ }
985
+ if (task['round'] !== undefined && !(Number.isSafeInteger(task['round']) && (task['round'] as number) >= 1)) {
986
+ return `round ${JSON.stringify(task['round'])} must be an integer >= 1`
987
+ }
988
+ for (const key of ['objective', 'reviewedTaskId', 'sourceTaskId'] as const) {
989
+ if (task[key] !== undefined && !nonemptyString(task[key])) return `${key} must be a non-empty string`
990
+ }
991
+ if (task['reviewedAttempt'] !== undefined
992
+ && !(Number.isSafeInteger(task['reviewedAttempt']) && (task['reviewedAttempt'] as number) >= 0)) {
993
+ return `reviewedAttempt ${JSON.stringify(task['reviewedAttempt'])} must be an integer >= 0`
994
+ }
995
+ const stringLists = ['inScope', 'outOfScope', 'acceptance', 'verify', 'deliverables', 'nonGoals', 'changedPaths', 'sourceFindingIds', 'coverageOf'] as const
996
+ for (const key of stringLists) {
997
+ const value = task[key]
998
+ if (value === undefined) continue
999
+ if (!Array.isArray(value)) return `${key} must be an array`
1000
+ const badIndex = (value as unknown[]).findIndex((item) => !nonemptyString(item))
1001
+ if (badIndex >= 0) return `${key}[${badIndex}] must be a non-empty string`
1002
+ }
1003
+ if (task['findings'] !== undefined) {
1004
+ const findings = task['findings']
1005
+ if (!Array.isArray(findings)) return 'findings must be an array'
1006
+ for (const [index, finding] of (findings as unknown[]).entries()) {
1007
+ const detail = describeFindingDefect(finding)
1008
+ if (detail !== undefined) return `findings[${index}].${detail}`
1009
+ }
1010
+ const ids = (findings as ReviewFinding[]).map((finding) => finding.id)
1011
+ if (new Set(ids).size !== ids.length) return 'findings ids must be unique'
1012
+ }
1013
+ if (task['acceptanceResults'] !== undefined) {
1014
+ const results = task['acceptanceResults']
1015
+ if (!Array.isArray(results)) return 'acceptanceResults must be an array'
1016
+ for (const [index, result] of (results as unknown[]).entries()) {
1017
+ if (!isRecord(result)) return `acceptanceResults[${index}] must be an object`
1018
+ if (!nonemptyString(result['criterion'])) return `acceptanceResults[${index}].criterion must be a non-empty string`
1019
+ if (result['status'] !== 'passed' && result['status'] !== 'failed') return `acceptanceResults[${index}].status must be "passed" or "failed"`
1020
+ if (result['evidence'] !== undefined && typeof result['evidence'] !== 'string') return `acceptanceResults[${index}].evidence must be a string`
1021
+ }
1022
+ }
1023
+ if (task['commandsRun'] !== undefined) {
1024
+ const commands = task['commandsRun']
1025
+ if (!Array.isArray(commands)) return 'commandsRun must be an array'
1026
+ for (const [index, command] of (commands as unknown[]).entries()) {
1027
+ if (!isRecord(command)) return `commandsRun[${index}] must be an object`
1028
+ if (!nonemptyString(command['command'])) return `commandsRun[${index}].command must be a non-empty string`
1029
+ if (command['status'] !== 'passed' && command['status'] !== 'failed') return `commandsRun[${index}].status must be "passed" or "failed"`
1030
+ }
1031
+ }
1032
+ return undefined
1033
+ }
1034
+
1035
+ /** The first finding-contract violation, or `undefined` when the finding is valid. */
1036
+ function describeFindingDefect(finding: unknown): string | undefined {
1037
+ if (!isRecord(finding)) return 'must be an object'
1038
+ if (!nonemptyString(finding['id'])) return 'id must be a non-empty string'
1039
+ if (!(FINDING_SEVERITIES as readonly string[]).includes(finding['severity'] as string)) {
1040
+ return `severity ${JSON.stringify(finding['severity'])} is invalid`
1041
+ }
1042
+ if (!nonemptyString(finding['problem'])) return 'problem must be a non-empty string'
1043
+ if (!nonemptyString(finding['requiredFix'])) return 'requiredFix must be a non-empty string'
1044
+ if (finding['file'] !== undefined && !nonemptyString(finding['file'])) return 'file must be a non-empty string'
1045
+ if (finding['line'] !== undefined && !isValidFindingLine(finding['line'])) {
1046
+ return `line ${JSON.stringify(finding['line'])} must be an integer >= 0 (omit it when there is no line number)`
1047
+ }
1048
+ if (finding['resolved'] !== undefined && typeof finding['resolved'] !== 'boolean') return 'resolved must be a boolean'
1049
+ return undefined
1050
+ }
1051
+ export function isTeamTask(value: unknown): value is TeamTask {
1052
+ if (!isRecord(value)) return false
1053
+ return typeof value['id'] === 'string'
1054
+ && isOptionalString(value['profileSeedId'])
1055
+ && (value['profileSeedId'] === undefined || value['profileSeedId'].trim() !== '')
1056
+ && typeof value['subject'] === 'string'
1057
+ && isOptionalString(value['description'])
1058
+ && (value['status'] === 'pending'
1059
+ || value['status'] === 'claimed'
1060
+ || value['status'] === 'in_progress'
1061
+ || value['status'] === 'completed'
1062
+ || value['status'] === 'failed'
1063
+ || value['status'] === 'cancelled')
1064
+ && isOptionalString(value['assignee'])
1065
+ && Array.isArray(value['dependencies'])
1066
+ && value['dependencies'].every((dependency) => typeof dependency === 'string')
1067
+ && isOptionalString(value['output'])
1068
+ && (value['attempt'] === undefined
1069
+ || (Number.isSafeInteger(value['attempt']) && (value['attempt'] as number) >= 0))
1070
+ && isOptionalString(value['attemptId'])
1071
+ && isOptionalString(value['handoffId'])
1072
+ && isOptionalString(value['handoffFromMemberId'])
1073
+ && (value['reassigning'] === undefined || typeof value['reassigning'] === 'boolean')
1074
+ && isFiniteNumber(value['createdAt'])
1075
+ && isFiniteNumber(value['updatedAt'])
1076
+ && hasValidQualityTaskFields(value)
1077
+ }
1078
+
1079
+ /** Validate the full team record before it can participate in authorization. */
1080
+ function isTeamState(value: unknown, expectedId: string): value is TeamState {
1081
+ if (!isRecord(value)) return false
1082
+ const validShape = value['id'] === expectedId
1083
+ && typeof value['name'] === 'string'
1084
+ && value['name'].trim() !== ''
1085
+ && isOptionalString(value['description'])
1086
+ && (value['profile'] === undefined || isTeamProfileSnapshot(value['profile']))
1087
+ && typeof value['captainSessionId'] === 'string'
1088
+ && value['captainSessionId'] !== ''
1089
+ && isOptionalString(value['captainProvider'])
1090
+ && isOptionalString(value['captainModel'])
1091
+ && isFiniteNumber(value['createdAt'])
1092
+ && Array.isArray(value['members'])
1093
+ && value['members'].every(isTeamMember)
1094
+ && Array.isArray(value['tasks'])
1095
+ && value['tasks'].every(isTeamTask)
1096
+ && Number.isSafeInteger(value['taskSeq'])
1097
+ && (value['taskSeq'] as number) >= 0
1098
+ && (value['phase'] === undefined || value['phase'] === 'staged' || value['phase'] === 'running')
1099
+ && (value['planReviewState'] === undefined
1100
+ || value['planReviewState'] === 'awaiting_review'
1101
+ || value['planReviewState'] === 'awaiting_feedback')
1102
+ && (value['approvedAt'] === undefined || isFiniteNumber(value['approvedAt']))
1103
+ && (value['halted'] === undefined || typeof value['halted'] === 'boolean')
1104
+ && (value['haltedAt'] === undefined || isFiniteNumber(value['haltedAt']))
1105
+ && (value['reviewPolicy'] === undefined || isReviewPolicy(value['reviewPolicy']))
1106
+ && (value['escalated'] === undefined || typeof value['escalated'] === 'boolean')
1107
+ if (!validShape) return false
1108
+
1109
+ const members = value['members'] as TeamMember[]
1110
+ const tasks = value['tasks'] as TeamTask[]
1111
+ const memberIds = new Set<string>()
1112
+ const memberKeys = new Set<string>()
1113
+ for (const member of members) {
1114
+ const key = sanitizeKey(member.name)
1115
+ if (key === CAPTAIN_KEY || memberKeys.has(key)) return false
1116
+ if (member.id !== '') {
1117
+ if (memberIds.has(member.id)) return false
1118
+ memberIds.add(member.id)
1119
+ }
1120
+ memberKeys.add(key)
1121
+ }
1122
+ const taskIds = new Set<string>()
1123
+ for (const task of tasks) {
1124
+ if (task.id === '' || taskIds.has(task.id)) return false
1125
+ taskIds.add(task.id)
1126
+ }
1127
+ return true
1128
+ }
1129
+
1130
+ /** Validate a mailbox record so later rendering cannot crash on `{}`/`null`. */
1131
+ function isTeamMessage(value: unknown): value is TeamMessage {
1132
+ if (!isRecord(value)) return false
1133
+ return typeof value['id'] === 'string'
1134
+ && typeof value['from'] === 'string'
1135
+ && typeof value['to'] === 'string'
1136
+ && typeof value['content'] === 'string'
1137
+ && isFiniteNumber(value['ts'])
1138
+ && (value['deliveryClaimedAt'] === undefined || isFiniteNumber(value['deliveryClaimedAt']))
1139
+ && (value['deliveredAt'] === undefined || isFiniteNumber(value['deliveredAt']))
1140
+ && (value['readAt'] === undefined || isFiniteNumber(value['readAt']))
1141
+ && (value['discardedAt'] === undefined || isFiniteNumber(value['discardedAt']))
1142
+ && (value['taskId'] === undefined || typeof value['taskId'] === 'string')
1143
+ && (value['attemptId'] === undefined || typeof value['attemptId'] === 'string')
1144
+ && (value['sourceTaskId'] === undefined || typeof value['sourceTaskId'] === 'string')
1145
+ && (value['sourceAttemptId'] === undefined || typeof value['sourceAttemptId'] === 'string')
1146
+ && (value['sourceTaskStatus'] === undefined || ['pending', 'claimed', 'in_progress', 'completed', 'failed', 'cancelled'].includes(value['sourceTaskStatus'] as string))
1147
+ }
1148
+
1149
+ /**
1150
+ * Remove a team's whole directory (members should be interrupted first).
1151
+ * @param stateRoot - resolved absolute state root directory.
1152
+ * @param teamId - the team id.
1153
+ */
1154
+ export async function removeTeamDir(stateRoot: string, teamId: string): Promise<void> {
1155
+ await rm(join(stateRoot, teamId), { recursive: true, force: true })
1156
+ }
1157
+
1158
+ /**
1159
+ * `rename` with the same transient retry policy as the state-file atomic
1160
+ * write, for paths (like archiving a whole team directory) where there is no
1161
+ * content-equivalent direct-write degradation on Windows. A short-lived
1162
+ * delete-sharing lock on any file below the renamed path is retried a few
1163
+ * times before the error propagates.
1164
+ * @param from - source path.
1165
+ * @param to - destination path.
1166
+ */
1167
+ async function renameWithRetry(from: string, to: string): Promise<void> {
1168
+ for (let attempt = 0; ; attempt += 1) {
1169
+ try {
1170
+ await rename(from, to)
1171
+ return
1172
+ } catch (error: unknown) {
1173
+ if (isRetryableRenameError(error) && attempt < ATOMIC_RENAME_RETRIES) {
1174
+ await sleep(ATOMIC_RENAME_RETRY_DELAY_MS)
1175
+ continue
1176
+ }
1177
+ throw error
1178
+ }
1179
+ }
1180
+ }
1181
+
1182
+ /**
1183
+ * Archive a team instead of deleting it: the whole directory (team.json with
1184
+ * tasks and dependency graph, plus the mailboxes) moves under
1185
+ * `<stateRoot>/archive/<teamId>/` so later sessions can review how tasks were
1186
+ * planned and rebuild dependency relationships. The archive directory has no
1187
+ * team.json of its own, so the live activity scan skips it naturally.
1188
+ * @param stateRoot - resolved absolute state root directory.
1189
+ * @param teamId - the team id.
1190
+ */
1191
+ export async function archiveTeamDir(stateRoot: string, teamId: string): Promise<void> {
1192
+ const archiveRoot = join(stateRoot, 'archive')
1193
+ await mkdir(archiveRoot, { recursive: true })
1194
+ const source = join(stateRoot, teamId)
1195
+ const target = join(archiveRoot, teamId)
1196
+ const previous = join(archiveRoot, `.${teamId}.previous-${randomUUID()}`)
1197
+ let displaced = false
1198
+ try {
1199
+ // The same Windows EPERM-on-rename applies at the directory boundary: a
1200
+ // delete-sharing violation on any file below `target` blocks the move, so
1201
+ // retry the transient-lock case before giving up.
1202
+ await renameWithRetry(target, previous)
1203
+ displaced = true
1204
+ } catch (error: unknown) {
1205
+ // Only ENOENT means there was nothing to displace; any other failure
1206
+ // (including a persistent EPERM lock) surfaces to the caller.
1207
+ if (!(error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT')) {
1208
+ throw error
1209
+ }
1210
+ }
1211
+
1212
+ try {
1213
+ await renameWithRetry(source, target)
1214
+ } catch (error: unknown) {
1215
+ if (displaced) {
1216
+ try {
1217
+ await renameWithRetry(previous, target)
1218
+ } catch (restoreError: unknown) {
1219
+ throw new AggregateError(
1220
+ [error, restoreError],
1221
+ `failed to archive team "${teamId}" and restore its previous archive`,
1222
+ )
1223
+ }
1224
+ }
1225
+ throw error
1226
+ }
1227
+
1228
+ // The new generation is authoritative. A failed cleanup only leaves a
1229
+ // hidden recovery directory, which archive discovery deliberately ignores.
1230
+ if (displaced) await rm(previous, { recursive: true, force: true }).catch(() => undefined)
1231
+ }
1232
+
1233
+ /**
1234
+ * Read one archived team (already moved under `archive/`), or undefined when
1235
+ * it was never archived.
1236
+ * @param stateRoot - resolved absolute state root directory.
1237
+ * @param teamId - the team id.
1238
+ */
1239
+ export async function readArchivedTeam(stateRoot: string, teamId: string): Promise<TeamState | undefined> {
1240
+ return readTeam(join(stateRoot, 'archive'), teamId)
1241
+ }
1242
+
1243
+ /**
1244
+ * List every archived team id under the state root.
1245
+ * @param stateRoot - resolved absolute state root directory.
1246
+ * @returns the archived team ids, empty when the archive does not exist.
1247
+ */
1248
+ export async function listArchivedTeamIds(stateRoot: string): Promise<string[]> {
1249
+ try {
1250
+ const entries = await readdir(join(stateRoot, 'archive'), { withFileTypes: true })
1251
+ return entries
1252
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
1253
+ .map((entry) => entry.name)
1254
+ } catch (error: unknown) {
1255
+ if (error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT') {
1256
+ return []
1257
+ }
1258
+ throw error
1259
+ }
1260
+ }
1261
+
1262
+ // ── activity snapshot (server-side, like the Claude Code desktop watcher) ──
1263
+
1264
+ /** Visual task state for the activity panel. */
1265
+ export type VisualTaskState = 'blocked' | 'open' | 'claimed' | 'running' | 'completed' | 'failed' | 'cancelled'
1266
+
1267
+ /**
1268
+ * The visual state of one task: `claimed` after assignment, `running` only
1269
+ * after the explicit in_progress update, `completed`
1270
+ * when done, `failed`/`cancelled` when terminal without success, `blocked`
1271
+ * while any dependency is unfinished, else `open`.
1272
+ */
1273
+ export function taskVisualState(
1274
+ status: string,
1275
+ dependencies: readonly string[],
1276
+ tasks: readonly TeamTask[],
1277
+ ): VisualTaskState {
1278
+ if (status === 'completed') return 'completed'
1279
+ if (status === 'failed') return 'failed'
1280
+ if (status === 'cancelled') return 'cancelled'
1281
+ if (status === 'in_progress') return 'running'
1282
+ if (status === 'claimed') return 'claimed'
1283
+ const byId = new Map(tasks.map((task) => [task.id, task]))
1284
+ const openDependency = dependencies.some((dependencyId) => {
1285
+ const dependency = byId.get(dependencyId)
1286
+ return dependency !== undefined && dependency.status !== 'completed'
1287
+ })
1288
+ return openDependency ? 'blocked' : 'open'
1289
+ }
1290
+
1291
+ /**
1292
+ * Longest dependency path depth per task id (each depth = one lane column).
1293
+ */
1294
+ export function taskDepthsById(tasks: readonly TeamTask[]): Map<string, number> {
1295
+ const byId = new Map(tasks.map((task) => [task.id, task]))
1296
+ const depths = new Map<string, number>()
1297
+ const visiting = new Set<string>()
1298
+ const depthOf = (taskId: string): number => {
1299
+ const cached = depths.get(taskId)
1300
+ if (cached !== undefined) return cached
1301
+ if (visiting.has(taskId)) return 0
1302
+ const task = byId.get(taskId)
1303
+ if (task === undefined) return 0
1304
+ visiting.add(taskId)
1305
+ const dependencies = task.dependencies
1306
+ .filter((dependencyId) => byId.has(dependencyId))
1307
+ .sort()
1308
+ const depth = dependencies.length === 0
1309
+ ? 0
1310
+ : 1 + Math.max(...dependencies.map(depthOf))
1311
+ visiting.delete(taskId)
1312
+ depths.set(taskId, depth)
1313
+ return depth
1314
+ }
1315
+ for (const task of tasks) depthOf(task.id)
1316
+ return depths
1317
+ }