prodigy 0.2.5

Turn ad-hoc Claude sessions into reproducible development pipelines with parallel AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
# Prodigy Session Documentation for Claude

This document explains how Prodigy manages sessions and provides information to Claude during development iterations.

## Overview

Prodigy is a workflow orchestration tool that executes Claude commands through structured YAML workflows. It manages session state, tracks execution progress, and supports parallel execution through MapReduce patterns.

## Error Handling Guidelines (Spec 101)

### Production Code Requirements

**CRITICAL**: Production code must NEVER use `unwrap()` or `panic!()` directly. All error conditions must be handled gracefully using Result types and the `?` operator.

#### Prohibited Patterns in Production Code
```rust
// NEVER DO THIS in production code:
let value = some_option.unwrap();        // Will panic on None
let result = some_result.unwrap();       // Will panic on Err
panic!("Something went wrong");          // Explicit panic
```

#### Required Patterns for Error Handling
```rust
// DO THIS instead:
let value = some_option.context("Failed to get value")?;
let result = some_result.context("Operation failed")?;
return Err(anyhow!("Something went wrong"));
```

#### Safe Fallback Patterns
```rust
// For Options:
let value = some_option.unwrap_or(default_value);
let value = some_option.unwrap_or_else(|| compute_default());
let value = some_option.map_or(default, |v| transform(v));

// For Results:
let value = some_result.unwrap_or(default_value);
let value = some_result.unwrap_or_else(|e| {
    log::warn!("Failed with error: {}, using default", e);
    default_value
});
```

### Test Code Exceptions

Test code MAY use `unwrap()` and `panic!()` as they serve as appropriate test failure mechanisms:
```rust
#[test]
fn test_something() {
    let result = function_under_test();
    assert!(result.is_ok());
    let value = result.unwrap();  // OK in tests - will fail test on error
}
```

### Static Compilation Patterns

For compile-time constants like regex patterns that are known to be valid:
```rust
// OK - Regex is statically known to be valid
static PATTERN: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\d+$").expect("Invalid regex pattern")
});
```

### Error Context Best Practices

1. **Always add context** when propagating errors:
   ```rust
   file_operation()
       .context("Failed to perform file operation")?;
   ```

2. **Include relevant details** in error messages:
   ```rust
   read_file(&path)
       .with_context(|| format!("Failed to read file: {}", path.display()))?;
   ```

3. **Use appropriate error types** for each module:
   - Storage operations: `StorageError`
   - Worktree operations: `WorktreeError`
   - Command execution: `CommandError`
   - General operations: `anyhow::Error`

### Troubleshooting Common Issues

#### Issue: "thread 'main' panicked at..."
**Cause**: An `unwrap()` or `panic!()` in production code
**Solution**: Find the location in the stack trace and replace with proper error handling

#### Issue: "called `Option::unwrap()` on a `None` value"
**Cause**: Attempting to unwrap a None Option
**Solution**: Use `unwrap_or()`, `unwrap_or_else()`, or `?` operator with context

#### Issue: "called `Result::unwrap()` on an `Err` value"
**Cause**: Attempting to unwrap an Err Result
**Solution**: Use `?` operator to propagate the error or handle it explicitly

### Validation and Testing

All error handling changes must:
1. Pass existing tests without modification
2. Include new tests for error paths
3. Maintain backward compatibility
4. Provide clear error messages for debugging

## Claude Command Observability (Spec 121)

### JSON Log Location Tracking

Prodigy captures the location of Claude JSON log files for debugging Claude command execution, especially useful for troubleshooting MapReduce agent failures.

#### What are Claude JSON Logs?

Claude Code creates detailed JSON log files for each command execution containing:
- Complete message history (user messages and Claude responses)
- All tool invocations with parameters and results
- Token usage statistics (input, output, cache tokens)
- Session metadata (model, tools available, timestamps)
- Error details and stack traces

These logs are stored in:
```
~/.local/state/claude/logs/session-{session_id}.json
```

#### Accessing JSON Log Location

**Via Verbose Output (-v flag):**
```bash
prodigy run workflow.yml -v
```
With verbose mode, Prodigy displays the JSON log location after each Claude command:
```
Executing: claude /my-command
Claude JSON log: /Users/username/.local/state/claude/logs/session-abc123.json
✓ Command completed
```

**Programmatically via ExecutionResult:**
```rust
let result = execute_claude_command(&cmd).await?;
if let Some(log_path) = result.json_log_location() {
    println!("Debug logs available at: {}", log_path);
}
```

**In MapReduce Events:**
```rust
// AgentCompleted events include json_log_location
MapReduceEvent::AgentCompleted {
    job_id: "job-123".to_string(),
    agent_id: "agent-1".to_string(),
    duration: Duration::seconds(30),
    commits: vec!["abc123".to_string()],
    json_log_location: Some("/path/to/logs/session-xyz.json".to_string()),
}
```

**In Dead Letter Queue (DLQ) Items:**
```rust
// Failed items capture json_log_location in FailureDetail
let dlq_item = DeadLetteredItem {
    // ... other fields ...
    failure_history: vec![
        FailureDetail {
            // ... error details ...
            json_log_location: Some("/path/to/logs/session-xyz.json".to_string()),
        }
    ],
};
```

#### Debugging with JSON Logs

**View complete Claude interaction:**
```bash
cat ~/.local/state/claude/logs/session-abc123.json | jq '.messages'
```

**Check tool invocations:**
```bash
cat ~/.local/state/claude/logs/session-abc123.json | jq '.messages[].content[] | select(.type == "tool_use")'
```

**Analyze token usage:**
```bash
cat ~/.local/state/claude/logs/session-abc123.json | jq '.usage'
```

**Extract error details:**
```bash
cat ~/.local/state/claude/logs/session-abc123.json | jq '.messages[] | select(.role == "assistant") | .content[] | select(.type == "error")'
```

#### MapReduce Debugging Workflow

When a MapReduce agent fails:

1. **Check DLQ for json_log_location:**
```bash
prodigy dlq show <job_id> | jq '.items[].failure_history[].json_log_location'
```

2. **Inspect the Claude JSON log:**
```bash
cat /path/from/step1/session-xyz.json | jq
```

3. **Identify the failing tool or message:**
```bash
# Find the last tool use before failure
cat /path/from/step1/session-xyz.json | jq '.messages[-3:]'
```

4. **Understand the context:**
- Review the full conversation history
- Check what tools were invoked and their results
- Examine token usage to identify context issues
- Look for error messages or unexpected responses

#### API Integration

The json_log_location field is available in:
- `AgentResult` - Captures log path for successful and failed agent executions
- `MapReduceEvent::AgentCompleted` - Includes log path in event stream
- `MapReduceEvent::ClaudeMessage` - Associates messages with their log files
- `FailureDetail` - Preserves log location for DLQ debugging

## Custom Merge Workflows

Prodigy now supports configurable merge workflows that execute when merging worktree changes back to the main branch. This allows you to customize the merge process with your own validation, conflict resolution, and post-merge steps.

### Merge Workflow Configuration

You can define a custom merge workflow in your YAML file using the `merge` block:

```yaml
# Custom merge workflow
merge:
  commands:
    - shell: "git fetch origin"
    - shell: "git merge origin/main"  # Merge main into worktree first
    - shell: "cargo test"              # Run tests
    - shell: "cargo clippy"            # Run linting
    - claude: "/prodigy-merge-worktree ${merge.source_branch}"
    - shell: "echo 'Successfully merged ${merge.worktree}'"
  timeout: 600  # 10 minutes timeout for merge operations
```

### Merge-Specific Variables

The following variables are available in merge workflows:
- `${merge.worktree}` - Name of the worktree being merged
- `${merge.source_branch}` - Source branch (worktree branch)
- `${merge.target_branch}` - Target branch (usually main or master)
- `${merge.session_id}` - Session ID for correlation

### Claude Merge Streaming

The Claude merge command now respects the same verbosity settings as other workflow commands:
- With `-v` (verbose) or higher, you'll see real-time JSON streaming output from Claude
- Set `PRODIGY_CLAUDE_CONSOLE_OUTPUT=true` to force streaming output regardless of verbosity
- This provides full visibility into Claude's merge operations and any tool invocations

### Example Workflows

#### Pre-merge Validation
```yaml
merge:
  commands:
    - shell: "cargo build --release"
    - shell: "cargo test --all"
    - shell: "cargo fmt --check"
    - claude: "/prodigy-merge-worktree ${merge.source_branch}"
```

#### Conflict Resolution Strategy
```yaml
merge:
  commands:
    - shell: "git merge origin/main --no-commit"
    - claude: "/resolve-conflicts"
    - shell: "git add -A"
    - shell: "git commit -m 'Merge main and resolve conflicts'"
    - claude: "/prodigy-merge-worktree ${merge.source_branch}"
```

## MapReduce Workflow Syntax

Prodigy supports MapReduce workflows for massive parallel processing. The syntax follows the specification in the whitepaper:

### Basic MapReduce Structure
```yaml
name: workflow-name
mode: mapreduce

# Optional setup phase
setup:
  - shell: "generate-work-items.sh"
  - shell: "analyze-codebase --output items.json"

# Map phase: Process items in parallel
map:
  input: "items.json"          # JSON file with array of items
  json_path: "$.items[*]"      # JSONPath to extract items

  agent_template:
    - claude: "/process '${item}'"
    - shell: "test ${item.path}"
      on_failure:
        claude: "/fix-issue '${item}'"

  max_parallel: 10             # Number of concurrent agents
  filter: "item.score >= 5"    # Optional: filter items
  sort_by: "item.priority DESC" # Optional: process order
  max_items: 100               # Optional: limit items per run

# Reduce phase: Aggregate results
reduce:
  - claude: "/summarize ${map.results}"
  - shell: "echo 'Processed ${map.successful}/${map.total} items'"
```

### Key Syntax Changes from Previous Versions
- **Agent Template**: No longer uses nested `commands` array - commands are directly under `agent_template`
- **Reduce Phase**: Commands are directly under `reduce`, not nested under `commands`
- **Error Handling**: Simplified `on_failure` syntax without `max_attempts` and `fail_workflow`
- **Removed Parameters**: No longer supports `timeout_per_agent`, `retry_on_failure`, or other deprecated parameters

## Directory Structure

### Local Storage (Legacy)
```
.prodigy/
├── session_state.json         # Current session state and timing
├── validation-result.json     # Workflow validation results
├── events/                    # MapReduce event logs (legacy)
│   └── {job_id}/             # Job-specific events
│       ├── {timestamp}.json  # Individual event records
│       └── checkpoint.json   # Job checkpoint for resumption
└── dlq/                      # Dead Letter Queue for failed items (legacy)
    └── {job_id}.json         # Failed work items for retry
```

### Global Storage (Default)
```
~/.prodigy/
├── events/
│   └── {repo_name}/          # Events grouped by repository
│       └── {job_id}/         # Job-specific events
│           └── events-{timestamp}.jsonl  # Event log files
├── dlq/
│   └── {repo_name}/          # DLQ grouped by repository
│       └── {job_id}/         # Job-specific failed items
├── state/
│   └── {repo_name}/          # State grouped by repository
│       └── mapreduce/        # MapReduce job states
│           └── jobs/
│               └── {job_id}/ # Job-specific checkpoints
└── worktrees/
    └── {repo_name}/          # Git worktrees for sessions
```

## Session Management

Prodigy uses a unified session management system that tracks all workflow and MapReduce executions through `UnifiedSession` objects stored in `~/.prodigy/sessions/`.

### UnifiedSession Structure

Every workflow execution creates a UnifiedSession file that contains:

```json
{
  "id": "session-abc123",
  "session_type": "Workflow",
  "status": "Running|Paused|Completed|Failed|Cancelled",
  "started_at": "2024-01-01T12:00:00Z",
  "updated_at": "2024-01-01T12:05:00Z",
  "completed_at": null,
  "metadata": {
    "execution_start_time": "2024-01-01T12:00:00Z",
    "workflow_type": "standard",
    "total_steps": 5,
    "current_step": 2
  },
  "checkpoints": [],
  "timings": {
    "step1": {"secs": 10, "nanos": 0},
    "step2": {"secs": 15, "nanos": 0}
  },
  "error": null,
  "workflow_data": {
    "workflow_id": "workflow-1234567890",
    "workflow_name": "my-workflow",
    "current_step": 2,
    "total_steps": 5,
    "completed_steps": [0, 1],
    "variables": {},
    "iterations_completed": 0,
    "files_changed": 0,
    "worktree_name": "session-abc123"
  },
  "mapreduce_data": null
}
```

### Session Lifecycle

1. **Creation**: When a workflow starts, a UnifiedSession is created in `~/.prodigy/sessions/{session-id}.json`
2. **Active Execution**: Status is set to `Running`, metadata is populated with execution timing
3. **Interruption**: If interrupted, status changes to `Paused` and checkpoint is created
4. **Resume**: `prodigy resume` loads the UnifiedSession and continues from the checkpoint
5. **Completion**: Status changes to `Completed` (or `Failed`), `completed_at` timestamp is set

### Session Metadata

The `metadata` field contains execution timing and progress information:
- `execution_start_time`: ISO 8601 timestamp when workflow started
- `workflow_type`: Type of workflow (e.g., "standard", "mapreduce")
- `total_steps`: Total number of steps in the workflow
- `current_step`: Index of the currently executing step (0-based)

### Session Checkpoints

UnifiedSession works in conjunction with checkpoints stored in `~/.prodigy/state/{session-id}/checkpoints/`:
- Each checkpoint captures the full execution state at a point in time
- Checkpoints are used by the resume system to continue interrupted workflows
- Session state and checkpoint state remain consistent throughout execution

### Resume with UnifiedSessionManager

The `prodigy resume` command uses the UnifiedSessionManager to:
1. Load the UnifiedSession file from `~/.prodigy/sessions/`
2. Verify the session is in a resumable state (Paused status)
3. Load the corresponding checkpoint from `~/.prodigy/state/`
4. Continue execution from where it left off
5. Update the UnifiedSession as execution progresses

### Legacy Session State (`session_state.json`)

**Note**: The legacy `session_state.json` format is deprecated in favor of UnifiedSession. Old workflows may still reference this format:
```json
{
  "session_id": "cook-1234567890",
  "status": "InProgress|Completed|Failed",
  "started_at": "2024-01-01T12:00:00Z",
  "iterations_completed": 2,
  "files_changed": 5,
  "worktree_name": "prodigy-session-123",
  "iteration_timings": [[1, {"secs": 120, "nanos": 0}]],
  "command_timings": [["claude: /prodigy-lint", {"secs": 60, "nanos": 0}]]
}
```

### Environment Variables

When executing Claude commands, Prodigy sets these environment variables:
- `PRODIGY_AUTOMATION="true"` - Signals automated execution mode

Claude JSON streaming is enabled by default for all Claude commands to ensure workflow auditability. To disable streaming (e.g., in CI/CD environments with storage constraints), set:
- `PRODIGY_CLAUDE_STREAMING="false"` - Explicitly disables JSON streaming and uses legacy print mode

## Global Storage Architecture

### Overview
Prodigy uses a global storage architecture by default, storing all events, state, and DLQ data in `~/.prodigy/`. This enables:
- **Cross-worktree event aggregation**: Multiple worktrees working on the same job share event logs
- **Persistent state management**: Job checkpoints survive worktree cleanup
- **Centralized monitoring**: All job data accessible from a single location
- **Efficient storage**: Deduplication across worktrees

## MapReduce Features

### Parallel Execution
Prodigy supports parallel execution of work items across multiple Claude agents:
- Each agent runs in an isolated git worktree
- Work items are distributed automatically
- Results are aggregated in the reduce phase
- Failed items can be retried via the DLQ

### MapReduce Checkpoint and Resume (Spec 134)

Prodigy provides comprehensive checkpoint and resume capabilities for MapReduce workflows, ensuring work can be recovered from any point of failure.

#### Checkpoint Behavior

**Setup Phase Checkpointing**:
- Checkpoint created after successful setup completion
- Preserves setup output, generated artifacts, and environment state
- Stored in global storage at `~/.prodigy/state/{repo_name}/mapreduce/jobs/{job_id}/setup-checkpoint.json`

**Map Phase Checkpointing**:
- Checkpoints created after processing configurable number of work items
- Tracks completed, in-progress, and pending work items
- Stores agent results and failure details for recovery
- Resume continues from last successful checkpoint

**Reduce Phase Checkpointing**:
- Checkpoint created after each reduce command execution
- Tracks completed steps, step results, variables, and map results
- Enables resume from any point in reduce phase execution
- Stored as `reduce-checkpoint-v1-{timestamp}.json`

#### Resume with Session or Job IDs

MapReduce jobs can be resumed using either session IDs or job IDs:

```bash
# Resume using session ID
prodigy resume session-mapreduce-1234567890

# Resume using job ID
prodigy resume-job mapreduce-1234567890

# Unified resume command (auto-detects ID type)
prodigy resume mapreduce-1234567890
```

**Session-Job Mapping**:
- Bidirectional mapping stored in `~/.prodigy/state/{repo_name}/mappings/`
- Maps session IDs to job IDs and vice versa
- Created when MapReduce workflow starts
- Enables resume with either identifier

#### State Preservation

**Variables and Context**:
- Workflow variables preserved across resume
- Captured outputs from setup and reduce phases
- Environment variables maintained
- Map results available to reduce phase after resume

**Work Item State**:
- Completed items: Preserved with full results
- In-progress items: Moved back to pending on resume
- Failed items: Tracked with retry counts and error details
- Pending items: Continue processing from where left off

**Agent State**:
- Active agent information preserved
- Resource allocation tracked
- Worktree paths recorded for cleanup

#### Resume Strategies

Based on checkpoint state and phase, different resume strategies apply:

- **Setup Phase**: Restart setup from beginning (idempotent operations recommended)
- **Map Phase**: Continue from last checkpoint, re-process in-progress items
- **Reduce Phase**: Continue from last completed step
- **Validate and Continue**: Verify checkpoint integrity before resuming

#### Storage Structure

```
~/.prodigy/state/{repo_name}/mapreduce/jobs/{job_id}/
├── setup-checkpoint.json           # Setup phase results
├── map-checkpoint-{timestamp}.json  # Map phase progress
├── reduce-checkpoint-v1-{timestamp}.json  # Reduce phase progress
└── job-state.json                  # Overall job state
```

#### Example Resume Workflow

1. Workflow interrupted during reduce phase
2. Find job with `prodigy sessions list` or `prodigy resume-job list`
3. Resume using `prodigy resume <session-or-job-id>`
4. Prodigy loads latest checkpoint
5. Reconstructs execution state
6. Continues from last completed step

### Concurrent Resume Protection (Spec 140)

Prodigy prevents multiple resume processes from running on the same session/job simultaneously using an RAII-based locking mechanism.

#### Lock Behavior

**Automatic Lock Acquisition**:
- Resume automatically acquires exclusive lock before starting
- Lock creation is atomic - fails if another process holds the lock
- Lock automatically released when resume completes or fails (RAII pattern)
- Stale locks (from crashed processes) are automatically detected and cleaned up

**Lock Metadata**:
Lock files contain:
- Process ID (PID) of the holding process
- Hostname where the process is running
- Timestamp when lock was acquired
- Job/session ID being locked

**Stale Lock Detection**:
- Platform-specific process existence check (Unix: `kill -0`, Windows: `tasklist`)
- If holding process is no longer running, lock is automatically removed
- New resume attempt succeeds after stale lock cleanup

#### Error Messages

If a resume is blocked by an active lock:

```bash
$ prodigy resume <job_id>
Error: Resume already in progress for job <job_id>
Lock held by: PID 12345 on hostname (acquired 2025-01-11 10:30:00 UTC)
Please wait for the other process to complete, or use --force to override.
```

#### Lock Storage

```
~/.prodigy/resume_locks/
├── session-abc123.lock
├── mapreduce-xyz789.lock
└── ...
```

Each `.lock` file contains JSON metadata about the lock holder.

#### Troubleshooting Stuck Locks

If a lock persists after a process crash:

1. **Check lock file location**: `~/.prodigy/resume_locks/<job_id>.lock`
2. **Verify process status**: `ps aux | grep <PID>` (from error message)
3. **Manual cleanup** (if process is dead): `rm ~/.prodigy/resume_locks/<job_id>.lock`
4. **Automatic cleanup**: Retry resume - stale locks are auto-detected and removed

**Note**: Under normal conditions, locks are automatically cleaned up. Manual intervention is rarely needed.

#### Safety Guarantees

- **Data Corruption Prevention**: Only one process can modify job state at a time
- **No Duplicate Work**: Work items cannot be processed by multiple agents concurrently
- **Consistent State**: Checkpoint updates are serialized
- **Automatic Cleanup**: RAII pattern ensures locks are released even on errors
- **Cross-Host Safety**: Hostname in lock prevents conflicts across machines

### Worktree Isolation (Spec 127, Spec 134)

**All MapReduce workflow phases (setup, map, reduce) execute in an isolated git worktree**, ensuring the main repository remains untouched during workflow execution.

#### Execution Flow

```
original_branch (e.g., master, feature-xyz, develop, etc.)
parent worktree (session-xxx) ← Single worktree for all MapReduce phases
    ├→ Setup phase executes here
    ├→ Agent worktrees branch from parent
    │  ├→ agent-1 → processes item, merges back to parent
    │  ├→ agent-2 → processes item, merges back to parent
    │  └→ agent-N → processes item, merges back to parent
    ├→ Reduce phase executes here (aggregates agent results)
    └→ User prompt: Merge to {original_branch}? [Y/n]
```

**Branch Tracking**: The parent worktree is created from whatever branch the user was on when they started the workflow. This branch is stored as `original_branch` in `WorktreeState` and is used as the merge target. The system uses `get_merge_target()` to retrieve this branch, so merges always go back to where the user started, not hardcoded to "master".

#### Isolation Guarantees

1. **Setup Phase Isolation**
   - Executes in parent worktree (created by orchestrator)
   - All setup commands execute in the worktree directory
   - File modifications occur in worktree, not main repo
   - Git commits are created in worktree context
   - Main repository remains clean until final merge

2. **Map Phase Isolation**
   - Each map agent runs in its own child worktree
   - Child worktrees branch from the parent worktree (setup results)
   - Agent changes merge back to parent worktree
   - No cross-contamination between agents
   - Independent failure isolation

3. **Reduce Phase Isolation**
   - Executes in parent worktree (same as setup)
   - Aggregates results from all map agents
   - Continues worktree isolation guarantee

#### Benefits

- **Safety**: Main repository never modified during execution
- **Parallelism**: Multiple agents can work concurrently
- **Reproducibility**: Clean state for each workflow run
- **Debugging**: Worktrees preserve full execution history
- **Recovery**: Failed workflows don't pollute main repo
- **User Control**: Final merge to original branch requires user confirmation

#### Example Verification

After running a MapReduce workflow, verify main repo is clean:

```bash
# Check main repo status (should be clean)
git status
# Expected: nothing to commit, working tree clean

# Verify worktree has changes
cd ~/.prodigy/worktrees/prodigy/session-xxx/
git status
git log
# Expected: See setup phase changes and commits
```

### Cleanup Failure Handling (Spec 136)

MapReduce agent executions gracefully handle cleanup failures to ensure successful agent work is not lost.

#### Behavior

**Agent Success Preserved**:
- Agent execution status is independent of cleanup status
- If agent completes successfully but cleanup fails, agent is marked as successful
- Work results (commits, files) are preserved regardless of cleanup outcome

**Cleanup Status Tracking**:
- Each `AgentResult` includes an optional `cleanup_status` field
- Values: `Success`, `Failed(String)`, or `Skipped`
- `AgentCompleted` events include cleanup status for observability

**Orphaned Worktree Registry**:
- When cleanup fails, worktree path is registered as orphaned
- Registry stored in `~/.prodigy/orphaned_worktrees/{repo_name}/{job_id}.json`
- Includes agent ID, item ID, timestamp, and error message

#### Cleaning Orphaned Worktrees

Use the `prodigy worktree clean-orphaned` command to clean up worktrees that failed cleanup:

```bash
# List orphaned worktrees
prodigy worktree clean-orphaned <job_id>

# Dry run to see what would be cleaned
prodigy worktree clean-orphaned <job_id> --dry-run

# Force cleanup without confirmation
prodigy worktree clean-orphaned <job_id> --force
```

**Example Output**:
```
Found 2 orphaned worktree(s):
  - /Users/user/.prodigy/worktrees/prodigy/agent-1 (agent: agent-1, item: item-1, error: permission denied)
  - /Users/user/.prodigy/worktrees/prodigy/agent-2 (agent: agent-2, item: item-2, error: disk full)

Proceed with cleanup? [y/N]
```

#### Troubleshooting Cleanup Failures

**Common Causes**:
- **Permission Denied**: Directory locked by process or insufficient permissions
- **Disk Full**: Not enough space to perform cleanup operations
- **Directory Busy**: Files open in editor or process using directory
- **Git Locks**: Repository locked by concurrent git operation

**Resolution**:
1. Check for running processes using the worktree: `lsof | grep worktree-path`
2. Ensure sufficient disk space: `df -h`
3. Check directory permissions: `ls -ld worktree-path`
4. Use `prodigy worktree clean-orphaned` to retry cleanup after resolving issue

### Event Tracking
Events are logged to `~/.prodigy/events/{repo_name}/{job_id}/` for debugging:
- Agent lifecycle events (started, completed, failed)
- Work item processing status
- Checkpoint saves for resumption
- Error details with correlation IDs
- Cross-worktree event aggregation for parallel jobs

### Dead Letter Queue (DLQ)
Failed work items are stored in `~/.prodigy/dlq/{repo_name}/{job_id}/` for review and retry:
- Contains the original work item data
- Includes failure reason and timestamp
- Supports automatic reprocessing via `prodigy dlq retry`
- Configurable parallel execution and resource limits
- Shared across worktrees for centralized failure tracking

#### DLQ Retry
The `prodigy dlq retry` command allows you to retry failed items:

```bash
# Retry all failed items for a job
prodigy dlq retry <job_id>

# Retry with custom parallelism (default: 5)
prodigy dlq retry <job_id> --max-parallel 10

# Dry run to see what would be retried
prodigy dlq retry <job_id> --dry-run
```

Features:
- Streams items to avoid memory issues with large queues
- Respects original workflow's max_parallel setting
- Preserves correlation IDs for tracking
- Updates DLQ state (removes successful, keeps failed)
- Supports interruption and resumption

## Workflow Execution

### Command Types
Prodigy supports several command types in workflows:
- `claude:` - Execute Claude commands via Claude Code CLI
- `shell:` - Run shell commands
- `goal_seek:` - Run goal-seeking operations with validation
- `foreach:` - Iterate over lists with nested commands

### Variable Interpolation
Workflows support variable interpolation:
- `${item.field}` - Access work item fields in MapReduce
- `${shell.output}` - Capture command output
- `${map.results}` - Access map phase results in reduce
- `$ARG` - Pass arguments from command line

### Environment Variables (Spec 120)

MapReduce workflows support environment variables for parameterization and secrets management. Environment variables can be defined at the workflow level and used throughout all phases.

#### Defining Environment Variables

Environment variables are defined in the `env` block at the workflow root:

```yaml
name: workflow-name
mode: mapreduce

env:
  # Plain variables
  PROJECT_NAME: "prodigy"
  VERSION: "1.0.0"

  # Secret variables (masked in logs)
  API_KEY:
    secret: true
    value: "sk-abc123"

  # Profile-specific variables
  DATABASE_URL:
    default: "postgres://localhost/dev"
    prod: "postgres://prod-server/db"
```

#### Variable Interpolation Syntax

Environment variables can be referenced using two syntaxes:
- `$VAR` - Simple variable reference (shell-style)
- `${VAR}` - Bracketed reference for clarity and complex expressions

```yaml
setup:
  - shell: "echo Processing $PROJECT_NAME version $VERSION"
  - shell: "curl -H 'Authorization: Bearer ${API_KEY}' https://api.example.com"

map:
  agent_template:
    - claude: "/process-item '${item.name}' --project $PROJECT_NAME"
    - shell: "test -f ${item.path}"

reduce:
  - shell: "echo Completed $PROJECT_NAME workflow"
```

#### Secret Masking

Variables marked with `secret: true` are automatically masked in:
- Command output logs
- Error messages
- Event logs
- Checkpoint files

Example output:
```
$ curl -H 'Authorization: Bearer ***' https://api.example.com
```

#### Profile Support

Profiles allow different values for different environments:

```yaml
env:
  API_URL:
    default: "http://localhost:3000"
    staging: "https://staging.api.com"
    prod: "https://api.com"
```

Activate a profile:
```bash
prodigy run workflow.yml --profile prod
```

#### Usage in All Workflow Phases

Environment variables are available in:

**Setup Phase:**
```yaml
setup:
  - shell: "npm install --prefix $PROJECT_DIR"
  - shell: "cargo build --manifest-path ${PROJECT_DIR}/Cargo.toml"
```

**Map Phase:**
```yaml
map:
  agent_template:
    - claude: "/analyze ${item.file} --config $CONFIG_PATH"
    - shell: "test -f $PROJECT_DIR/${item.file}"
```

**Reduce Phase:**
```yaml
reduce:
  - claude: "/summarize ${map.results} --project $PROJECT_NAME"
  - shell: "cp results.json $OUTPUT_DIR/"
```

**Merge Phase:**
```yaml
merge:
  commands:
    - shell: "echo Merging $PROJECT_NAME changes"
    - claude: "/validate-merge --branch ${merge.source_branch}"
```

#### Best Practices

1. **Use secrets for sensitive data**: Mark API keys, tokens, and credentials as secrets
2. **Parameterize project-specific values**: Use env vars instead of hardcoding paths
3. **Document required variables**: Include comments in workflow files
4. **Use profiles for environments**: Separate dev, staging, and prod configurations
5. **Prefer ${VAR} syntax**: More explicit and works in all contexts

### Error Handling
Commands can specify error handling behavior:
- `on_failure:` - Commands to run on failure
- `commit_required:` - Whether a git commit is expected

### Claude Streaming Output Control

Prodigy provides fine-grained control over Claude interaction visibility through verbosity levels:

**Default mode (verbosity = 0):**
- Clean, minimal output showing only progress and results
- No Claude JSON streaming output displayed
- Optimal for production workflows and CI/CD

**Verbose mode (verbosity >= 1, `-v` flag):**
- Shows Claude streaming JSON output in real-time
- Enables debugging of Claude interactions
- Useful for development and troubleshooting

**Environment Override:**
- Set `PRODIGY_CLAUDE_CONSOLE_OUTPUT=true` to force streaming output regardless of verbosity
- Useful for debugging specific runs without changing command flags

This design ensures clean output by default while preserving debugging capabilities when needed.

## Git Integration

### Worktree Management
Prodigy uses git worktrees for isolation:
- Each session gets its own worktree
- Located in `~/.prodigy/worktrees/{project-name}/`
- Automatic branch creation and management
- Clean merge back to parent branch

### Commit Tracking
All changes are tracked via git commits:
- Each successful command creates a commit
- Commit messages include command details
- Full audit trail of all modifications

### Branch Tracking (Spec 110)
Prodigy tracks the original branch when creating worktrees to enable intelligent merge behavior:

**Original Branch Detection**:
- When creating a worktree, Prodigy captures the current branch as `original_branch`
- For feature branches: Tracks the exact branch name (e.g., `feature/my-feature`)
- For detached HEAD: Falls back to repository's default branch (main or master)
- Stored in worktree state for lifetime of the session

**Merge Target Logic**:
- Default behavior: Merge back to the tracked `original_branch`
- If original branch was deleted: Fall back to default branch (main/master)
- Merge target is displayed in the merge confirmation prompt
- Example: "Merge session-abc123 to feature/my-feature? [y/N]"

**Special Cases**:
- **Feature Branch Workflow**: Worktree created from `feature/ui-updates` merges back to `feature/ui-updates`
- **Detached HEAD**: Worktree tracks default branch (main/master) as fallback
- **Deleted Branch**: If original branch is deleted, falls back to main/master
- **Branch Rename**: Uses branch name at worktree creation time

**Implementation Details**:
- `WorktreeManager::create_session()` captures original branch using `git rev-parse --abbrev-ref HEAD`
- `WorktreeManager::get_merge_target()` determines merge target with fallback logic
- Merge target is shown in orchestrator's completion prompt for user confirmation

## Available Commands

Prodigy CLI commands:
- `prodigy run` - Execute a workflow (with `--resume` flag for checkpoint-based resume)
- `prodigy resume` - Resume an interrupted workflow from checkpoint
- `prodigy worktree` - Manage git worktrees
- `prodigy init` - Initialize Claude commands
- `prodigy resume-job` - Resume MapReduce jobs with enhanced options
- `prodigy events` - View execution events
- `prodigy dlq` - Manage and retry failed work items
- `prodigy checkpoints` - Manage workflow checkpoints
- `prodigy sessions` - View and manage session state
- `prodigy logs` - View and manage Claude JSON logs

## Best Practices

1. **Session Hygiene**: Clean up completed worktrees with `prodigy worktree clean`
2. **Error Recovery**: Check DLQ for failed items after MapReduce jobs
3. **Workflow Design**: Keep workflows simple and focused
4. **Testing**: Always include test steps in workflows
5. **Monitoring**: Use verbosity flags for appropriate detail level:
   - Default: Clean output for production use
   - `-v`: Claude streaming output for debugging interactions
   - `-vv`/`-vvv`: Additional internal logs and tracing
6. **Documentation**: The book documentation workflow now includes automatic drift detection and gap detection to keep documentation synchronized with code changes. Features are analyzed automatically and documentation is updated to match implementation.

## Limitations

- No automatic context analysis or generation
- Each iteration runs independently (memory preserved via checkpoints and state)
- Context directory feature is planned but not implemented
- Limited to Claude commands available in `.claude/commands/`
- Resume functionality requires workflow files to be present

## Troubleshooting

### Session Issues
- Check `.prodigy/session_state.json` for session status
- View events in `.prodigy/events/` for detailed logs
- Use verbosity flags for debugging:
  - `-v`: Shows Claude streaming output
  - `-vv`: Adds debug logs
  - `-vvv`: Adds trace-level logs

### MapReduce Failures
- Check `.prodigy/dlq/` for failed items
- Retry failed items with `prodigy dlq retry <job_id>`
- Resume MapReduce jobs with `prodigy resume-job <job_id>`
- Review checkpoint in `~/.prodigy/state/{repo_name}/mapreduce/jobs/{job_id}/`

### Worktree Problems
- List worktrees with `prodigy worktree ls`
- Clean stuck worktrees with `prodigy worktree clean -f`
- Check `~/.prodigy/worktrees/` for orphaned directories

### Viewing Claude Execution Logs (Spec 126)

**Every Claude command creates a streaming JSONL log file** at `~/.claude/projects/{worktree-path}/{uuid}.jsonl`. These logs are automatically displayed after each command execution:

```
✅ Completed | Log: ~/.claude/projects/.../6ded63ac.jsonl
```

Or for failed commands:
```
❌ Failed | Log: ~/.claude/projects/.../6ded63ac.jsonl
```

#### Watching Logs Live

For long-running Claude commands, watch the log in real-time:

```bash
# Watch live as Claude executes
tail -f ~/.claude/projects/.../6ded63ac.jsonl

# Pretty-print each line as it's added
tail -f ~/.claude/projects/.../6ded63ac.jsonl | jq -c '.'
```

#### Analyzing Completed Logs

After a command completes, analyze the full conversation:

```bash
# View all events (one JSON object per line)
cat ~/.claude/projects/.../6ded63ac.jsonl

# Count messages by type
cat ~/.claude/projects/.../6ded63ac.jsonl | jq -r '.type' | sort | uniq -c

# View only user messages
cat ~/.claude/projects/.../6ded63ac.jsonl | jq -c 'select(.type == "user")'

# View only assistant responses
cat ~/.claude/projects/.../6ded63ac.jsonl | jq -c 'select(.type == "assistant")'

# Extract all tool uses
cat ~/.claude/projects/.../6ded63ac.jsonl | \
  jq -c 'select(.type == "assistant") | .content[]? | select(.type == "tool_use")'

# View token usage (usually at end of file)
cat ~/.claude/projects/.../6ded63ac.jsonl | jq -c 'select(.usage)'
```

#### Using the `prodigy logs` Command

```bash
# View most recent Claude log
prodigy logs --latest

# View most recent log with summary
prodigy logs --latest --summary

# Tail the latest log (follow mode)
prodigy logs --latest --tail

# List recent logs
prodigy logs
```

#### When Workflows Fail

When a Claude command fails, the log path is displayed prominently in the error output, making it easy to debug the issue without requiring verbose mode.

#### Debugging Failed MapReduce Agents

Failed MapReduce agents include log paths in their DLQ entries for easy debugging.