@the-bearded-bear/claude-craft 5.6.0-next.8bfdffa → 5.7.0-next.bf058ea

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.
@@ -0,0 +1,705 @@
1
+ #!/usr/bin/env bash
2
+ # =============================================================================
3
+ # Ralph Teams Adapter - Agent Teams Abstraction Layer
4
+ # Encapsulates Agent Teams API behind an interface compatible with
5
+ # existing parallel-manager.sh patterns. Falls back to bash-based
6
+ # parallelism when Agent Teams is not available.
7
+ #
8
+ # Requires: CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 (env var)
9
+ # Version: 1.0.0
10
+ # =============================================================================
11
+
12
+ set -eo pipefail
13
+
14
+ # =============================================================================
15
+ # Constants & Configuration
16
+ # =============================================================================
17
+
18
+ TEAMS_ADAPTER_VERSION="1.0.0"
19
+ TEAMS_ENV_VAR="CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS"
20
+ TEAMS_WATCHDOG_INTERVAL="${TEAMS_WATCHDOG_INTERVAL:-60}" # seconds between health checks
21
+ TEAMS_WATCHDOG_TIMEOUT="${TEAMS_WATCHDOG_TIMEOUT:-300}" # 5 min timeout before fallback
22
+ TEAMS_DRY_RUN="${TEAMS_DRY_RUN:-false}"
23
+
24
+ # State
25
+ _TEAMS_INITIALIZED=false
26
+ _TEAMS_AVAILABLE=false
27
+ _TEAMS_TEAM_ID=""
28
+ _TEAMS_LEAD_NAME=""
29
+ _TEAMS_SESSION_DIR=""
30
+ _TEAMS_LOG_FILE=""
31
+
32
+ # Teammate tracking
33
+ declare -A _TEAMS_TEAMMATES # name -> agent mapping
34
+ declare -A _TEAMS_TEAMMATE_STATUS # name -> status (idle|working|stalled|shutdown)
35
+ declare -A _TEAMS_TEAMMATE_LAST_SEEN # name -> unix timestamp of last activity
36
+ declare -A _TEAMS_STORY_ASSIGNMENT # story_id -> teammate_name
37
+
38
+ # Counters
39
+ _TEAMS_STORIES_ASSIGNED=0
40
+ _TEAMS_STORIES_COMPLETED=0
41
+ _TEAMS_STORIES_FAILED=0
42
+ _TEAMS_WATCHDOG_PID=""
43
+
44
+ # =============================================================================
45
+ # Detection & Initialization
46
+ # =============================================================================
47
+
48
+ # Check if Agent Teams feature is available
49
+ teams_is_available() {
50
+ [[ "${CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:-0}" == "1" ]]
51
+ }
52
+
53
+ # Initialize the adapter layer
54
+ # Usage: teams_init [--dry-run] [session_dir]
55
+ teams_init() {
56
+ local session_dir="${1:-.ralph/agent-teams}"
57
+
58
+ if [[ "$_TEAMS_INITIALIZED" == "true" ]]; then
59
+ _teams_log "Already initialized"
60
+ return 0
61
+ fi
62
+
63
+ _TEAMS_SESSION_DIR="$session_dir"
64
+ mkdir -p "$_TEAMS_SESSION_DIR"
65
+ _TEAMS_LOG_FILE="$_TEAMS_SESSION_DIR/adapter.log"
66
+
67
+ _teams_log "Initializing Ralph Teams Adapter v${TEAMS_ADAPTER_VERSION}"
68
+
69
+ # Check Agent Teams availability
70
+ if teams_is_available; then
71
+ _TEAMS_AVAILABLE=true
72
+ _teams_log "Agent Teams feature detected (${TEAMS_ENV_VAR}=1)"
73
+ else
74
+ _TEAMS_AVAILABLE=false
75
+ _teams_log "Agent Teams not available, will use fallback mode"
76
+ fi
77
+
78
+ if [[ "$TEAMS_DRY_RUN" == "true" ]]; then
79
+ _teams_log "[DRY-RUN] Adapter initialized in dry-run mode"
80
+ fi
81
+
82
+ # Write state file
83
+ _teams_write_state "initialized"
84
+
85
+ _TEAMS_INITIALIZED=true
86
+ return 0
87
+ }
88
+
89
+ # =============================================================================
90
+ # Team Lifecycle
91
+ # =============================================================================
92
+
93
+ # Create a team with conductor (lead) and dev agents
94
+ # Usage: teams_create_team <lead_name> <dev_count>
95
+ # Example: teams_create_team "ralph-conductor" 1
96
+ teams_create_team() {
97
+ local lead_name="${1:?Lead name required}"
98
+ local dev_count="${2:-1}"
99
+
100
+ _teams_require_init
101
+
102
+ _TEAMS_LEAD_NAME="$lead_name"
103
+
104
+ if [[ "$TEAMS_DRY_RUN" == "true" ]]; then
105
+ _teams_log "[DRY-RUN] Would create team: lead=$lead_name, dev_agents=$dev_count"
106
+ _TEAMS_TEAM_ID="dry-run-team-$(date +%s)"
107
+ for i in $(seq 1 "$dev_count"); do
108
+ local dev_name="dev-${i}"
109
+ _TEAMS_TEAMMATES["$dev_name"]="dev"
110
+ _TEAMS_TEAMMATE_STATUS["$dev_name"]="idle"
111
+ _TEAMS_TEAMMATE_LAST_SEEN["$dev_name"]=$(date +%s)
112
+ done
113
+ _teams_write_state "team_created"
114
+ echo "$_TEAMS_TEAM_ID"
115
+ return 0
116
+ fi
117
+
118
+ if [[ "$_TEAMS_AVAILABLE" != "true" ]]; then
119
+ _teams_log "Agent Teams not available, team creation skipped (fallback mode)"
120
+ _TEAMS_TEAM_ID="fallback-$$"
121
+ _teams_write_state "fallback_mode"
122
+ echo "$_TEAMS_TEAM_ID"
123
+ return 0
124
+ fi
125
+
126
+ _teams_log "Creating team: lead=$lead_name, dev_agents=$dev_count"
127
+
128
+ # Generate team ID
129
+ _TEAMS_TEAM_ID="team-ralph-$(date +%s)-$$"
130
+
131
+ # Register teammates
132
+ for i in $(seq 1 "$dev_count"); do
133
+ local dev_name="dev-${i}"
134
+ _TEAMS_TEAMMATES["$dev_name"]="dev"
135
+ _TEAMS_TEAMMATE_STATUS["$dev_name"]="idle"
136
+ _TEAMS_TEAMMATE_LAST_SEEN["$dev_name"]=$(date +%s)
137
+ _teams_log "Registered teammate: $dev_name (agent: dev)"
138
+ done
139
+
140
+ _teams_write_state "team_created"
141
+ _teams_log "Team created: $_TEAMS_TEAM_ID (${#_TEAMS_TEAMMATES[@]} teammates)"
142
+
143
+ echo "$_TEAMS_TEAM_ID"
144
+ }
145
+
146
+ # =============================================================================
147
+ # Story Assignment
148
+ # =============================================================================
149
+
150
+ # Assign a story to an available teammate
151
+ # Usage: teams_assign_story <story_id> <prompt>
152
+ # Returns: 0 on success, 1 if no teammate available
153
+ teams_assign_story() {
154
+ local story_id="${1:?Story ID required}"
155
+ local prompt="${2:?Prompt required}"
156
+
157
+ _teams_require_init
158
+
159
+ # Find an idle teammate
160
+ local target_teammate=""
161
+ for name in "${!_TEAMS_TEAMMATE_STATUS[@]}"; do
162
+ if [[ "${_TEAMS_TEAMMATE_STATUS[$name]}" == "idle" ]]; then
163
+ target_teammate="$name"
164
+ break
165
+ fi
166
+ done
167
+
168
+ if [[ -z "$target_teammate" ]]; then
169
+ _teams_log "No idle teammate available for story $story_id"
170
+ return 1
171
+ fi
172
+
173
+ if [[ "$TEAMS_DRY_RUN" == "true" ]]; then
174
+ _teams_log "[DRY-RUN] Would assign story $story_id to $target_teammate"
175
+ _teams_log "[DRY-RUN] Prompt: ${prompt:0:100}..."
176
+ _TEAMS_TEAMMATE_STATUS["$target_teammate"]="working"
177
+ _TEAMS_STORY_ASSIGNMENT["$story_id"]="$target_teammate"
178
+ _TEAMS_STORIES_ASSIGNED=$((_TEAMS_STORIES_ASSIGNED + 1))
179
+ return 0
180
+ fi
181
+
182
+ if [[ "$_TEAMS_AVAILABLE" != "true" ]]; then
183
+ # Fallback: delegate to existing parallel-manager or sequential execution
184
+ _teams_log "Fallback mode: story $story_id queued for sequential processing"
185
+ _TEAMS_STORY_ASSIGNMENT["$story_id"]="fallback"
186
+ _TEAMS_STORIES_ASSIGNED=$((_TEAMS_STORIES_ASSIGNED + 1))
187
+ return 0
188
+ fi
189
+
190
+ _teams_log "Assigning story $story_id to $target_teammate"
191
+
192
+ # Update teammate status
193
+ _TEAMS_TEAMMATE_STATUS["$target_teammate"]="working"
194
+ _TEAMS_TEAMMATE_LAST_SEEN["$target_teammate"]=$(date +%s)
195
+ _TEAMS_STORY_ASSIGNMENT["$story_id"]="$target_teammate"
196
+ _TEAMS_STORIES_ASSIGNED=$((_TEAMS_STORIES_ASSIGNED + 1))
197
+
198
+ # In Agent Teams mode, the conductor (team lead) would use:
199
+ # TaskCreate to create a task for the story
200
+ # SendMessage to notify the dev teammate
201
+ # This is done through Claude Code's native Agent Teams API,
202
+ # which the conductor agent invokes directly. This adapter
203
+ # tracks the state for monitoring and recovery purposes.
204
+
205
+ _teams_write_state "story_assigned"
206
+ return 0
207
+ }
208
+
209
+ # Mark a story as completed by a teammate
210
+ # Usage: teams_mark_completed <story_id>
211
+ teams_mark_completed() {
212
+ local story_id="${1:?Story ID required}"
213
+
214
+ local teammate="${_TEAMS_STORY_ASSIGNMENT[$story_id]:-}"
215
+ if [[ -z "$teammate" ]]; then
216
+ _teams_log "Warning: story $story_id not found in assignments"
217
+ return 1
218
+ fi
219
+
220
+ _teams_log "Story completed: $story_id (by $teammate)"
221
+
222
+ _TEAMS_TEAMMATE_STATUS["$teammate"]="idle"
223
+ _TEAMS_TEAMMATE_LAST_SEEN["$teammate"]=$(date +%s)
224
+ _TEAMS_STORIES_COMPLETED=$((_TEAMS_STORIES_COMPLETED + 1))
225
+ unset "_TEAMS_STORY_ASSIGNMENT[$story_id]"
226
+
227
+ _teams_write_state "story_completed"
228
+ return 0
229
+ }
230
+
231
+ # Mark a story as failed
232
+ # Usage: teams_mark_failed <story_id>
233
+ teams_mark_failed() {
234
+ local story_id="${1:?Story ID required}"
235
+
236
+ local teammate="${_TEAMS_STORY_ASSIGNMENT[$story_id]:-}"
237
+ if [[ -z "$teammate" ]]; then
238
+ _teams_log "Warning: story $story_id not found in assignments"
239
+ return 1
240
+ fi
241
+
242
+ _teams_log "Story failed: $story_id (by $teammate)"
243
+
244
+ _TEAMS_TEAMMATE_STATUS["$teammate"]="idle"
245
+ _TEAMS_TEAMMATE_LAST_SEEN["$teammate"]=$(date +%s)
246
+ _TEAMS_STORIES_FAILED=$((_TEAMS_STORIES_FAILED + 1))
247
+ unset "_TEAMS_STORY_ASSIGNMENT[$story_id]"
248
+
249
+ _teams_write_state "story_failed"
250
+ return 0
251
+ }
252
+
253
+ # =============================================================================
254
+ # Waiting & Synchronization
255
+ # =============================================================================
256
+
257
+ # Wait for all active stories to complete
258
+ # Usage: teams_wait_completion [timeout_seconds]
259
+ teams_wait_completion() {
260
+ local timeout="${1:-0}" # 0 = wait forever
261
+ local start_time
262
+ start_time=$(date +%s)
263
+
264
+ _teams_require_init
265
+
266
+ if [[ "$TEAMS_DRY_RUN" == "true" ]]; then
267
+ _teams_log "[DRY-RUN] Would wait for ${#_TEAMS_STORY_ASSIGNMENT[@]} active stories"
268
+ # Simulate instant completion in dry-run
269
+ for story_id in "${!_TEAMS_STORY_ASSIGNMENT[@]}"; do
270
+ teams_mark_completed "$story_id"
271
+ done
272
+ return 0
273
+ fi
274
+
275
+ _teams_log "Waiting for ${#_TEAMS_STORY_ASSIGNMENT[@]} active stories..."
276
+
277
+ while [[ ${#_TEAMS_STORY_ASSIGNMENT[@]} -gt 0 ]]; do
278
+ # Check timeout
279
+ if [[ $timeout -gt 0 ]]; then
280
+ local elapsed=$(( $(date +%s) - start_time ))
281
+ if [[ $elapsed -ge $timeout ]]; then
282
+ _teams_log "Wait timeout reached after ${elapsed}s"
283
+ return 1
284
+ fi
285
+ fi
286
+
287
+ # Run watchdog check
288
+ teams_watchdog
289
+
290
+ sleep "$TEAMS_WATCHDOG_INTERVAL"
291
+ done
292
+
293
+ _teams_log "All stories completed"
294
+ return 0
295
+ }
296
+
297
+ # Get list of idle teammates
298
+ # Usage: teams_get_idle_teammates
299
+ teams_get_idle_teammates() {
300
+ for name in "${!_TEAMS_TEAMMATE_STATUS[@]}"; do
301
+ if [[ "${_TEAMS_TEAMMATE_STATUS[$name]}" == "idle" ]]; then
302
+ echo "$name"
303
+ fi
304
+ done
305
+ }
306
+
307
+ # Get count of active (working) teammates
308
+ # Usage: teams_get_active_count
309
+ teams_get_active_count() {
310
+ local count=0
311
+ for name in "${!_TEAMS_TEAMMATE_STATUS[@]}"; do
312
+ if [[ "${_TEAMS_TEAMMATE_STATUS[$name]}" == "working" ]]; then
313
+ count=$((count + 1))
314
+ fi
315
+ done
316
+ echo "$count"
317
+ }
318
+
319
+ # =============================================================================
320
+ # Recovery: Timeout Watchdog (Task #11)
321
+ # =============================================================================
322
+
323
+ # Check teammate health periodically
324
+ # Detects stalled teammates and triggers fallback if needed
325
+ # Usage: teams_watchdog
326
+ teams_watchdog() {
327
+ _teams_require_init
328
+
329
+ local now
330
+ now=$(date +%s)
331
+
332
+ if [[ "$TEAMS_DRY_RUN" == "true" ]]; then
333
+ _teams_log "[DRY-RUN] Watchdog check: ${#_TEAMS_STORY_ASSIGNMENT[@]} active assignments"
334
+ return 0
335
+ fi
336
+
337
+ for name in "${!_TEAMS_TEAMMATE_STATUS[@]}"; do
338
+ if [[ "${_TEAMS_TEAMMATE_STATUS[$name]}" != "working" ]]; then
339
+ continue
340
+ fi
341
+
342
+ local last_seen="${_TEAMS_TEAMMATE_LAST_SEEN[$name]:-0}"
343
+ local elapsed=$((now - last_seen))
344
+
345
+ if [[ $elapsed -ge $TEAMS_WATCHDOG_TIMEOUT ]]; then
346
+ _teams_log "WATCHDOG: Teammate '$name' unresponsive for ${elapsed}s (timeout: ${TEAMS_WATCHDOG_TIMEOUT}s)"
347
+ _TEAMS_TEAMMATE_STATUS["$name"]="stalled"
348
+
349
+ # Find the story assigned to this teammate
350
+ local stalled_story=""
351
+ for story_id in "${!_TEAMS_STORY_ASSIGNMENT[@]}"; do
352
+ if [[ "${_TEAMS_STORY_ASSIGNMENT[$story_id]}" == "$name" ]]; then
353
+ stalled_story="$story_id"
354
+ break
355
+ fi
356
+ done
357
+
358
+ if [[ -n "$stalled_story" ]]; then
359
+ _teams_log "WATCHDOG: Story '$stalled_story' was assigned to stalled teammate '$name'"
360
+ _teams_log "WATCHDOG: Triggering fallback to sequential for '$stalled_story'"
361
+ teams_fallback_sequential "$stalled_story" "$name"
362
+ fi
363
+ elif [[ $elapsed -ge $((TEAMS_WATCHDOG_TIMEOUT / 2)) ]]; then
364
+ _teams_log "WATCHDOG: Warning - teammate '$name' quiet for ${elapsed}s"
365
+ fi
366
+ done
367
+ }
368
+
369
+ # Graceful degradation: fallback a stalled story to sequential processing
370
+ # Usage: teams_fallback_sequential <story_id> <teammate_name>
371
+ teams_fallback_sequential() {
372
+ local story_id="${1:?Story ID required}"
373
+ local teammate_name="${2:?Teammate name required}"
374
+
375
+ _teams_require_init
376
+
377
+ if [[ "$TEAMS_DRY_RUN" == "true" ]]; then
378
+ _teams_log "[DRY-RUN] Would fallback story $story_id from $teammate_name to sequential"
379
+ unset "_TEAMS_STORY_ASSIGNMENT[$story_id]"
380
+ _TEAMS_TEAMMATE_STATUS["$teammate_name"]="shutdown"
381
+ return 0
382
+ fi
383
+
384
+ _teams_log "FALLBACK: Story $story_id removed from stalled teammate $teammate_name"
385
+
386
+ # Remove the assignment
387
+ unset "_TEAMS_STORY_ASSIGNMENT[$story_id]"
388
+
389
+ # Attempt graceful shutdown of stalled teammate
390
+ _teams_shutdown_teammate "$teammate_name"
391
+
392
+ # Mark teammate as shutdown
393
+ _TEAMS_TEAMMATE_STATUS["$teammate_name"]="shutdown"
394
+
395
+ # The story will be picked up by the conductor for sequential execution
396
+ # via existing sprint-conductor.sh execute_story_with_ralph()
397
+ _teams_log "FALLBACK: Story $story_id available for sequential reprocessing"
398
+
399
+ _teams_write_state "fallback_triggered"
400
+ return 0
401
+ }
402
+
403
+ # Attempt to shutdown a stalled teammate
404
+ # Usage: _teams_shutdown_teammate <teammate_name>
405
+ _teams_shutdown_teammate() {
406
+ local teammate_name="$1"
407
+
408
+ _teams_log "Requesting shutdown for stalled teammate: $teammate_name"
409
+
410
+ # In Agent Teams mode, the conductor would send:
411
+ # SendMessage(type="shutdown_request", recipient=teammate_name)
412
+ # If the teammate doesn't respond, it remains orphaned but the
413
+ # conductor continues with sequential fallback.
414
+
415
+ # Give a brief window for graceful shutdown
416
+ local shutdown_wait=10
417
+ _teams_log "Waiting ${shutdown_wait}s for teammate '$teammate_name' to acknowledge shutdown"
418
+
419
+ # In real Agent Teams mode, this would poll for shutdown_response
420
+ # For the adapter, we simply mark it and move on
421
+ _TEAMS_TEAMMATE_STATUS["$teammate_name"]="shutdown"
422
+ _teams_log "Teammate '$teammate_name' marked as shutdown (may be orphaned)"
423
+ }
424
+
425
+ # =============================================================================
426
+ # Cleanup
427
+ # =============================================================================
428
+
429
+ # Clean up team resources
430
+ # Usage: teams_cleanup
431
+ teams_cleanup() {
432
+ if [[ "$_TEAMS_INITIALIZED" != "true" ]]; then
433
+ return 0
434
+ fi
435
+
436
+ _teams_log "Cleaning up team resources..."
437
+
438
+ if [[ "$TEAMS_DRY_RUN" == "true" ]]; then
439
+ _teams_log "[DRY-RUN] Would clean up team $_TEAMS_TEAM_ID"
440
+ _teams_write_state "cleaned_up"
441
+ _reset_adapter_state
442
+ return 0
443
+ fi
444
+
445
+ # Shutdown all active teammates
446
+ for name in "${!_TEAMS_TEAMMATE_STATUS[@]}"; do
447
+ local status="${_TEAMS_TEAMMATE_STATUS[$name]}"
448
+ if [[ "$status" == "working" || "$status" == "idle" ]]; then
449
+ _teams_log "Requesting shutdown for teammate: $name (status: $status)"
450
+ _teams_shutdown_teammate "$name"
451
+ fi
452
+ done
453
+
454
+ # Wait briefly for clean shutdowns
455
+ sleep 2
456
+
457
+ _teams_write_state "cleaned_up"
458
+ _teams_log "Team $_TEAMS_TEAM_ID cleaned up"
459
+
460
+ _reset_adapter_state
461
+ }
462
+
463
+ # =============================================================================
464
+ # Status & Reporting
465
+ # =============================================================================
466
+
467
+ # Get adapter status as JSON
468
+ # Usage: teams_get_status
469
+ teams_get_status() {
470
+ local active_count
471
+ active_count=$(teams_get_active_count 2>/dev/null || echo "0")
472
+
473
+ local teammate_list="[]"
474
+ if [[ ${#_TEAMS_TEAMMATES[@]} -gt 0 ]]; then
475
+ teammate_list="["
476
+ local first=true
477
+ for name in "${!_TEAMS_TEAMMATES[@]}"; do
478
+ [[ "$first" != "true" ]] && teammate_list+=","
479
+ first=false
480
+ teammate_list+="{\"name\":\"$name\",\"agent\":\"${_TEAMS_TEAMMATES[$name]}\",\"status\":\"${_TEAMS_TEAMMATE_STATUS[$name]:-unknown}\"}"
481
+ done
482
+ teammate_list+="]"
483
+ fi
484
+
485
+ cat << EOF
486
+ {
487
+ "version": "$TEAMS_ADAPTER_VERSION",
488
+ "initialized": $_TEAMS_INITIALIZED,
489
+ "agent_teams_available": $_TEAMS_AVAILABLE,
490
+ "dry_run": $TEAMS_DRY_RUN,
491
+ "team_id": "$_TEAMS_TEAM_ID",
492
+ "lead": "$_TEAMS_LEAD_NAME",
493
+ "teammates": $teammate_list,
494
+ "stories": {
495
+ "assigned": $_TEAMS_STORIES_ASSIGNED,
496
+ "completed": $_TEAMS_STORIES_COMPLETED,
497
+ "failed": $_TEAMS_STORIES_FAILED,
498
+ "active": ${#_TEAMS_STORY_ASSIGNMENT[@]}
499
+ },
500
+ "watchdog": {
501
+ "interval_seconds": $TEAMS_WATCHDOG_INTERVAL,
502
+ "timeout_seconds": $TEAMS_WATCHDOG_TIMEOUT
503
+ }
504
+ }
505
+ EOF
506
+ }
507
+
508
+ # =============================================================================
509
+ # Internal Helpers
510
+ # =============================================================================
511
+
512
+ _teams_require_init() {
513
+ if [[ "$_TEAMS_INITIALIZED" != "true" ]]; then
514
+ echo "ERROR: Teams adapter not initialized. Call teams_init() first." >&2
515
+ return 1
516
+ fi
517
+ }
518
+
519
+ # Safe count of associative array elements (handles empty arrays with nounset)
520
+ _teams_active_story_count() {
521
+ echo "${#_TEAMS_STORY_ASSIGNMENT[@]}"
522
+ }
523
+
524
+ _teams_teammate_count() {
525
+ echo "${#_TEAMS_TEAMMATES[@]}"
526
+ }
527
+
528
+ _teams_log() {
529
+ local message="$1"
530
+ local timestamp
531
+ timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
532
+ local log_line="[$timestamp] [teams-adapter] $message"
533
+
534
+ if [[ -n "${_TEAMS_LOG_FILE:-}" ]]; then
535
+ echo "$log_line" >> "$_TEAMS_LOG_FILE"
536
+ fi
537
+
538
+ # Also print to stderr for visibility
539
+ echo "$log_line" >&2
540
+ }
541
+
542
+ _teams_write_state() {
543
+ local event="$1"
544
+
545
+ if [[ -z "${_TEAMS_SESSION_DIR:-}" ]]; then
546
+ return
547
+ fi
548
+
549
+ local state_file="$_TEAMS_SESSION_DIR/state.yaml"
550
+
551
+ cat > "$state_file" << EOF
552
+ adapter_version: "$TEAMS_ADAPTER_VERSION"
553
+ team_id: "$_TEAMS_TEAM_ID"
554
+ lead: "$_TEAMS_LEAD_NAME"
555
+ agent_teams_available: $_TEAMS_AVAILABLE
556
+ dry_run: $TEAMS_DRY_RUN
557
+ last_event: "$event"
558
+ last_updated: "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
559
+ stories:
560
+ assigned: $_TEAMS_STORIES_ASSIGNED
561
+ completed: $_TEAMS_STORIES_COMPLETED
562
+ failed: $_TEAMS_STORIES_FAILED
563
+ active: ${#_TEAMS_STORY_ASSIGNMENT[@]}
564
+ watchdog:
565
+ interval: $TEAMS_WATCHDOG_INTERVAL
566
+ timeout: $TEAMS_WATCHDOG_TIMEOUT
567
+ EOF
568
+ }
569
+
570
+ _reset_adapter_state() {
571
+ _TEAMS_INITIALIZED=false
572
+ _TEAMS_AVAILABLE=false
573
+ _TEAMS_TEAM_ID=""
574
+ _TEAMS_LEAD_NAME=""
575
+ _TEAMS_STORIES_ASSIGNED=0
576
+ _TEAMS_STORIES_COMPLETED=0
577
+ _TEAMS_STORIES_FAILED=0
578
+
579
+ # Clear associative arrays
580
+ for key in "${!_TEAMS_TEAMMATES[@]}"; do unset "_TEAMS_TEAMMATES[$key]"; done
581
+ for key in "${!_TEAMS_TEAMMATE_STATUS[@]}"; do unset "_TEAMS_TEAMMATE_STATUS[$key]"; done
582
+ for key in "${!_TEAMS_TEAMMATE_LAST_SEEN[@]}"; do unset "_TEAMS_TEAMMATE_LAST_SEEN[$key]"; done
583
+ for key in "${!_TEAMS_STORY_ASSIGNMENT[@]}"; do unset "_TEAMS_STORY_ASSIGNMENT[$key]"; done
584
+ }
585
+
586
+ # =============================================================================
587
+ # CLI Interface
588
+ # =============================================================================
589
+
590
+ _teams_usage() {
591
+ cat << EOF
592
+ Ralph Teams Adapter v${TEAMS_ADAPTER_VERSION}
593
+ Abstraction layer for Claude Code Agent Teams integration.
594
+
595
+ Usage: ralph-teams-adapter.sh <command> [options]
596
+
597
+ Commands:
598
+ init [session_dir] Initialize the adapter
599
+ create-team <lead> <count> Create a team with N dev agents
600
+ assign <story_id> <prompt> Assign a story to an idle teammate
601
+ complete <story_id> Mark a story as completed
602
+ fail <story_id> Mark a story as failed
603
+ wait [timeout] Wait for all stories to complete
604
+ watchdog Run a single watchdog health check
605
+ status Show adapter status (JSON)
606
+ cleanup Clean up team resources
607
+ help Show this help
608
+
609
+ Options:
610
+ --dry-run Simulate all operations without side effects
611
+ --help Show this help
612
+
613
+ Environment:
614
+ CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 Enable Agent Teams mode
615
+ TEAMS_WATCHDOG_INTERVAL=60 Watchdog check interval (seconds)
616
+ TEAMS_WATCHDOG_TIMEOUT=300 Teammate timeout before fallback (seconds)
617
+ TEAMS_DRY_RUN=true Enable dry-run mode
618
+
619
+ Examples:
620
+ # Initialize and create a 2-agent team (conductor + 1 dev)
621
+ ralph-teams-adapter.sh init
622
+ ralph-teams-adapter.sh create-team ralph-conductor 1
623
+
624
+ # Assign a story
625
+ ralph-teams-adapter.sh assign US-001 "Implement login feature"
626
+
627
+ # Wait for completion
628
+ ralph-teams-adapter.sh wait 3600
629
+
630
+ # Dry run
631
+ ralph-teams-adapter.sh --dry-run init
632
+ ralph-teams-adapter.sh --dry-run create-team conductor 1
633
+ EOF
634
+ }
635
+
636
+ cmd_teams_adapter() {
637
+ # Parse global options first
638
+ while [[ $# -gt 0 ]]; do
639
+ case "$1" in
640
+ --dry-run)
641
+ TEAMS_DRY_RUN="true"
642
+ shift
643
+ ;;
644
+ --help|-h)
645
+ _teams_usage
646
+ return 0
647
+ ;;
648
+ *)
649
+ break
650
+ ;;
651
+ esac
652
+ done
653
+
654
+ local command="${1:-help}"
655
+ shift || true
656
+
657
+ case "$command" in
658
+ init)
659
+ teams_init "${1:-.ralph/agent-teams}"
660
+ ;;
661
+ create-team)
662
+ local lead="${1:?Lead name required}"
663
+ local count="${2:-1}"
664
+ teams_create_team "$lead" "$count"
665
+ ;;
666
+ assign)
667
+ local story_id="${1:?Story ID required}"
668
+ local prompt="${2:?Prompt required}"
669
+ teams_assign_story "$story_id" "$prompt"
670
+ ;;
671
+ complete)
672
+ local story_id="${1:?Story ID required}"
673
+ teams_mark_completed "$story_id"
674
+ ;;
675
+ fail)
676
+ local story_id="${1:?Story ID required}"
677
+ teams_mark_failed "$story_id"
678
+ ;;
679
+ wait)
680
+ teams_wait_completion "${1:-0}"
681
+ ;;
682
+ watchdog)
683
+ teams_watchdog
684
+ ;;
685
+ status)
686
+ teams_get_status
687
+ ;;
688
+ cleanup)
689
+ teams_cleanup
690
+ ;;
691
+ help|--help|-h)
692
+ _teams_usage
693
+ ;;
694
+ *)
695
+ echo "Unknown command: $command" >&2
696
+ echo "Run 'ralph-teams-adapter.sh help' for usage." >&2
697
+ return 1
698
+ ;;
699
+ esac
700
+ }
701
+
702
+ # Run if executed directly
703
+ if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
704
+ cmd_teams_adapter "$@"
705
+ fi