---
phase: 04-execution-management
plan: 04-03
type: execute
---

<objective>
Implement execution download and retry commands for forensic analysis and error recovery.

Purpose: Enable downloading execution data to disk for deep inspection (highest priority per CONTEXT.md) and retrying failed executions.
Output: Working `n8n execution download` and `n8n execution retry` commands with tests.
</objective>

<execution_context>
~/.claude/get-shit-done/workflows/execute-phase.md
~/.claude/get-shit-done/templates/summary.md
~/.claude/get-shit-done/references/tdd.md
</execution_context>

<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md
@.planning/phases/04-execution-management/04-CONTEXT.md
@.planning/phases/04-execution-management/04-01-SUMMARY.md
@.planning/phases/04-execution-management/04-02-SUMMARY.md
@.planning/phases/03-workflow-management/03-03-SUMMARY.md
@src/n8n_cli/commands/execution.py
@src/n8n_cli/commands/workflow.py
@src/n8n_cli/client/resources/executions.py
@src/n8n_cli/utils.py

**CONTEXT.md emphasis:**
Priority: Download > Inspect > Retry

Download capability is paramount - saving execution data locally for:
- Detailed analysis of failures
- Sharing with team members
- Keeping records of execution results
- Post-execution forensics

**Phase 3 file operation patterns:**
- workflow pull saves to `<workflow-name>.json` with sanitized filenames
- workflow push reads from local files and updates cloud
- Pydantic model_dump(mode='json') for proper datetime serialization
- Tests mock file operations with tmp_path fixture

**REQUIREMENTS.md specs:**
- `execution dl <ID>` - Download execution to JSON file
  - Default filename: `<execution_id>.json`
  - --output/-o flag for custom filename
  - Include full execution data (includeData=True)
  - Save as formatted JSON for readability

- `execution retry <ID>` - Retry failed execution
  - Create new execution from failed one
  - Show new execution ID after retry
  - Optional --no-load-workflow flag
</context>

<tasks>

<task type="auto" tdd="true">
  <name>Task 1: Create execution download command</name>
  <files>src/n8n_cli/commands/execution.py, tests/commands/test_execution.py</files>
  <test-first>
    Test: execution download saves execution data to JSON file
    Cases:
    - download("exec_id") saves to "{exec_id}.json" by default
    - download("exec_id", output="custom.json") saves to custom filename
    - download() includes full execution data (include_data=True)
    - download() formats JSON with indent=2 for readability
    - download() uses Pydantic model_dump(mode='json') for datetime serialization
    - download() handles NotFoundError (execution doesn't exist)
    - download() handles file write errors gracefully
    - download() confirms success: "Execution data saved to {filename}"
  </test-first>
  <action>
    Add download command to execution.py:

    @app.command("download")
    def download(execution_id: str, output: str | None = None):
       - Load config and validate
       - Create APIClient context manager
       - Fetch execution with full data: client.executions.get(execution_id, include_data=True)
       - Determine filename:
         - If output provided: use it
         - Otherwise: f"{execution_id}.json"
       - Serialize execution to JSON:
         - execution.model_dump(mode='json') for proper datetime handling
         - json.dumps(data, indent=2) for readability
       - Write to file with error handling (wrap in try/except IOError)
       - Success message: typer.echo(f"Execution data saved to {filename}")
       - Handle NotFoundError: "Execution {id} not found"
       - Handle write errors: "Failed to write file: {error}"

    Tests:
    - Use tmp_path fixture for file operations
    - Mock APIClient.executions.get() with full execution data
    - Verify file contents (valid JSON, includes execution data)
    - Test default and custom filenames
    - Test error handling (API errors, file errors)
    - Verify datetime serialization works (mode='json')

    Note: Follow workflow pull pattern from Phase 3 Plan 3. This is the HIGHEST priority command per CONTEXT.md.
  </action>
  <verify>
    pytest tests/commands/test_execution.py::TestExecutionDownload -v passes
    mypy src/n8n_cli/commands/execution.py passes
    ruff check src/n8n_cli/commands/execution.py passes
  </verify>
  <done>
    - execution download command implemented
    - Saves full execution data with proper JSON formatting
    - Supports custom output filenames
    - Handles errors gracefully with clear messages
    - Tests verify all scenarios including file operations
  </done>
</task>

<task type="auto" tdd="true">
  <name>Task 2: Create execution retry command</name>
  <files>src/n8n_cli/commands/execution.py, tests/commands/test_execution.py</files>
  <test-first>
    Test: execution retry creates new execution from failed one
    Cases:
    - retry("exec_id") calls executions.retry() with load_workflow=True
    - retry("exec_id", no_load_workflow=True) calls with load_workflow=False
    - retry() displays new execution ID after success
    - retry() handles NotFoundError (execution doesn't exist)
    - retry() handles API errors gracefully
    - Success message: "Retried execution {old_id}. New execution: {new_id}"
  </test-first>
  <action>
    Add retry command to execution.py:

    @app.command("retry")
    def retry_execution(execution_id: str, no_load_workflow: bool = False):
       - Load config and validate
       - Create APIClient context manager
       - Call new_execution = client.executions.retry(
           execution_id,
           load_workflow=not no_load_workflow
         )
       - Success message: typer.echo(f"Retried execution {execution_id}. New execution: {new_execution.id}")
       - Display new execution status (if available)
       - Handle NotFoundError: "Execution {id} not found"
       - Handle other errors gracefully (no stack traces)

    Tests:
    - Mock APIClient.executions.retry() returning new Execution
    - Test default behavior (load_workflow=True)
    - Test --no-load-workflow flag
    - Test success message includes new execution ID
    - Test error handling (404, API errors)

    Note: This is lowest priority per CONTEXT.md, but straightforward to implement. Just wraps the API method.
  </action>
  <verify>
    pytest tests/commands/test_execution.py::TestExecutionRetry -v passes
    All quality gates pass: pytest (all execution tests), mypy, ruff
  </verify>
  <done>
    - execution retry command implemented
    - Creates new execution from failed one
    - Supports --no-load-workflow flag
    - Clear success messages with new execution ID
    - Tests verify all retry scenarios
    - Phase 4 complete: all execution commands implemented
  </done>
</task>

</tasks>

<verification>
Before declaring plan complete:
- [ ] pytest tests/commands/test_execution.py passes (all execution command tests)
- [ ] mypy src/n8n_cli/commands/ passes with no errors
- [ ] ruff check src/n8n_cli/ passes with no violations
- [ ] Manual test: n8n execution download <id> creates JSON file
- [ ] Manual test: n8n execution retry <id> shows new execution ID
- [ ] All four execution commands working (list, view, download, retry)
</verification>

<success_criteria>

- execution download command saves full execution data to JSON
- execution retry command creates new execution
- Both commands handle errors gracefully
- Comprehensive test coverage for all commands
- Phase 4 complete: all execution management commands working
- All quality gates passing
  </success_criteria>

<output>
After completion, create `.planning/phases/04-execution-management/04-03-SUMMARY.md`:

# Phase 4 Plan 3: Download and Retry Commands Summary

**[Substantive one-liner - what shipped]**

## Accomplishments

- execution download command for forensic analysis
- execution retry command for error recovery
- Complete execution command suite (list, view, download, retry)
- Comprehensive test coverage

## Files Created/Modified

- `src/n8n_cli/commands/execution.py` - Added download and retry commands
- `tests/commands/test_execution.py` - Tests for download/retry commands

## Decisions Made

[Document any technical decisions or deviations from plan]

## Issues Encountered

[Problems and resolutions, or "None"]

## Next Phase Readiness

**Phase 4 (Execution Management) complete.** Ready for Phase 5 (Project & User Management).

**Execution commands implemented:**
- ✅ list (with workflow/status filtering)
- ✅ view (with --data and verbosity)
- ✅ download (highest priority - forensic analysis)
- ✅ retry (error recovery)

All commands follow Phase 3 patterns with consistent UX, error handling, and test coverage.
</output>
