---
phase: 11-refactor
plan: 02
subsystem: cli
tags: [error-handling, refactor, connection-management]

requires:
  - phase: 11-01
    provides: "Scarica/Invia with explicit InputArgs parameter — enables this plan's refactor"
provides:
  - try/finally disconnect guarantee in Scarica and Invia
  - PrintErrors helper — surfaces CncResult.Errors on every failure
  - Connection leak bug fixed (catch block previously had no disconnect)
affects: []

tech-stack:
  added: []
  patterns: ["try/finally with connected flag for resource cleanup after async connect"]

key-files:
  created: []
  modified: [Program.cs]

key-decisions:
  - "connected flag (bool) preferred over nested try — simpler than tracking state across multiple early returns"
  - "PrintErrors prints to stdout before VediErrore — operator sees machine detail then error code"

patterns-established:
  - "Resource cleanup pattern: bool connected = false; try { ... connected = true; } finally { if (connected) Disconnect(); }"

duration: ~10min
started: 2026-05-18T00:00:00Z
completed: 2026-05-18T00:00:00Z
---

# Phase 11 Plan 02: Scarica/Invia error handling refactor

**Fixed connection leak in Scarica/Invia (try/finally with `connected` flag); `CncResult.Errors` now printed before every error code.**

## Performance

| Metric | Value |
|--------|-------|
| Duration | ~10min |
| Tasks | 2 completed |
| Files modified | 1 |

## Acceptance Criteria Results

| Criterion | Status | Notes |
|-----------|--------|-------|
| AC-1: Disconnect always runs after connect | Pass | `finally { if (connected) DisconnectAsync() }` in both methods |
| AC-2: No manual disconnect inside try | Pass | Zero `DisconnectAsync` calls inside try blocks — verified by grep |
| AC-3: CncResult errors printed on failure | Pass | `PrintErrors(result.Errors)` called at all 8 CncResult failure sites |

## Files Created/Modified

| File | Change | Purpose |
|------|--------|---------|
| `Program.cs` | Modified | try/finally pattern, `connected` flag, `PrintErrors` helper added |

## Decisions Made

| Decision | Rationale | Impact |
|----------|-----------|--------|
| `bool connected` flag over nested try | Simpler than inner try; clearly marks connect/disconnect boundary | Easy to read, no double-catch complexity |
| `PrintErrors` before `VediErrore` | Operator sees machine-level detail first, then summary code | Better diagnostics; no behavior change otherwise |

## Deviations from Plan

None — plan executed exactly as written.

## Next Phase Readiness

**Ready:**
- Phase 11 complete — `Program.cs` clean, `ArgParser` isolated, errors surfaced
- Phase 12 (docs-cli) can proceed: README needs full CLI param table

**Concerns:** None.

**Blockers:** None.

---
*Phase: 11-refactor, Plan: 02*
*Completed: 2026-05-18*
