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