# Plan: Result Migration — Sub-Track 2 (Small Files + Audit-Script Bug Fixes)

**Sub-track:** `result_migration_small_files_20260617`
**Umbrella:** [`result_migration_20260616`](../../result_migration_20260616/spec.md)
**Owner:** Tier 2 Tech Lead
**Base commit:** origin/master (post-`result_migration_review_pass_20260617` merge)
**Audit-data commit:** origin/master HEAD (the 10 new heuristics are in `scripts/audit_exception_handling.py`; 3 documented bugs in §4.4 of `docs/reports/RESULT_MIGRATION_REVIEW_PASS_20260617.md`)

---

## Phase 1: Audit-Script Bug Fixes (3 bugs, TDD)

### 1.1 Fix `visit_Try` walker bug

- [x] **Task 1.1.1: Write failing test for the `visit_Try` walker** [eb9b8aad] 
  - WHERE: `tests/test_audit_exception_handling_bug_fixes.py` (new file)
  - WHAT: A test fixture with a `try/except/except/raise` pattern where the FIRST `except` handler has a `raise` statement. The test asserts the audit classifies the first handler's raise as `INTERNAL_RETHROW` (or whatever the correct category is).
  - HOW: Use the `subprocess` pattern from `tests/test_audit_exception_handling_heuristics.py` (write a fixture to a temp dir, invoke the audit, parse the JSON)
  - COMMIT: not yet (this is the RED step; commit follows the GREEN step)

- [x] **Task 1.1.2: Fix the `visit_Try` walker** [eb9b8aad] 
  - WHERE: `scripts/audit_exception_handling.py:759-784`
  - WHAT: The `for handler in node.handlers` loop at L771 leaves `handler` bound to the last handler. The `for child in handler.body if node.handlers else []` at L774 only walks the last handler's body. Fix: move the `for child in ...` loop INSIDE the `for handler in node.handlers` loop so each handler's body is walked.
  - HOW: Surgical edit. The current code is roughly:
    ```python
    for handler in node.handlers:
        self._record_finding(handler, ...)
    for child in handler.body if node.handlers else []:  # uses LAST handler
        ...
    ```
    The fix is to walk each handler's body inside the loop:
    ```python
    for handler in node.handlers:
        self._record_finding(handler, ...)
        for child in handler.body:
            ...
    ```
  - SAFETY: The audit script is a static analyzer; the change doesn't affect runtime behavior. Run the audit before and after to verify the new findings are correct.
  - COMMIT: `fix(scripts): visit_Try walker now visits ALL except handlers (bug from review pass §4.4 #1)`
  - GIT NOTE: Per-site count delta (the `src/rag_engine.py:31` raise is now in the findings; expected 5-15 new INTERNAL_RETHROW findings across the codebase)

- [x] **Task 1.1.3: Verify the fix doesn't break existing tests** [eb9b8aad] 
  - WHERE: `tests/test_audit_exception_handling_heuristics.py` + the 11 test tiers
  - WHAT: Run the existing 10 heuristic tests + the full test suite to verify no regression
  - HOW: `uv run pytest tests/test_audit_exception_handling_heuristics.py -v` + `uv run python scripts/run_tests_batched.py`
  - SAFETY: If a regression occurs, the fix is wrong; revert and re-investigate
  - COMMIT: rolled into 1.1.2 (the test is part of the same atomic commit)

### 1.2 Fix `render_json` compliant-finding filter

- [x] **Task 1.2.1: Write failing test for the per-file findings list** [737bbee1] 
  - WHERE: `tests/test_audit_exception_handling_bug_fixes.py`
  - WHAT: A test fixture with an `INTERNAL_COMPLIANT` site (e.g., the list.index+ValueError pattern). Run the audit with `--json` (non-verbose). Assert the `INTERNAL_COMPLIANT` finding is in the per-file list.
  - HOW: Same `subprocess` pattern; parse the JSON; check the findings list

- [x] **Task 1.2.2: Fix the filter** [737bbee1] 
  - WHERE: `scripts/audit_exception_handling.py:884, 889, 958`
  - WHAT: The filter `if f.category in VIOLATION_CATEGORIES or f.category in ("UNCLEAR", "INTERNAL_RETHROW")` excludes `INTERNAL_COMPLIANT`. The fix depends on intent:
    - If the goal is "show only non-compliant findings" (current behavior), the filter is correct; the fix is to add a `--verbose` flag that includes compliant findings
    - If the goal is "show all findings, categorized", the filter should be removed entirely
  - The intended fix per the review-pass report: show all findings in non-verbose mode (the totals are right; the per-file list should match the totals). Change the filter to `True` (include all) or to a per-category opt-in via `--verbose`.
  - HOW: The simplest fix is to change the filter to `True` (include all findings) for the per-file list. This may make the JSON output larger; verify the change doesn't break the existing `--json` consumers.
  - SAFETY: The audit's JSON output is consumed by the 10 existing heuristic tests + the tier-2 agent. If the output shape changes, the tests catch it.
  - COMMIT: `fix(scripts): render_json per-file list now includes all findings (bug from review pass §4.4 #2)`
  - GIT NOTE: Per-file list now shows all findings (not just violations); INTERNAL_COMPLIANT sites are visible

- [x] **Task 1.2.3: Verify the fix doesn't break existing tests** [737bbee1] 
  - WHERE: same as 1.1.3
  - COMMIT: rolled into 1.2.2

### 1.3 Fix `render_json` truncation

- [x] **Task 1.3.1: Write failing test for the no-truncation behavior** [6bf8b911] 
  - WHERE: `tests/test_audit_exception_handling_bug_fixes.py`
  - WHAT: A test fixture in a file with very few violations (e.g., 1 violation) that creates a low-violation file with an UNCLEAR site. Run the audit with `--json` and assert the UNCLEAR site is in the per-file findings list (not truncated to top 15).
  - HOW: Use the audit's `--src` flag to point to a temp dir with the fixture; parse the JSON

- [x] **Task 1.3.2: Fix the truncation** [6bf8b911] 
  - WHERE: `scripts/audit_exception_handling.py:1058` (CLI default `--top 15`) and `scripts/audit_exception_handling.py:958` (the slice `[r for r in sorted_reports[:top]]`)
  - WHAT: The per-file list is truncated to top 15 by violation count. The fix is either:
    - Change the default `--top` to a much higher value (e.g., 200, which is the total file count)
    - Or remove the truncation entirely
  - HOW: The simplest fix is to change the default to a value >= the total file count. 200 is a safe default (the project has 65 src/ files; 200 covers future growth).
  - SAFETY: The `--top` flag is a CLI option; users can still pass `--top 15` if they want a truncated view.
  - COMMIT: `fix(scripts): render_json no longer truncates per-file list to top 15 (bug from review pass §4.4 #3)`
  - GIT NOTE: Default `--top` changed to 200; per-file list shows all files with findings

- [x] **Task 1.3.3: Verify the fix doesn't break existing tests** [6bf8b911] 
  - WHERE: same as 1.1.3
  - COMMIT: rolled into 1.3.2

### 1.4 Phase 1 Verification

- [x] **Task 1.4.1: Run the full audit post-Phase-1; verify all 3 bug fixes** [6bf8b911] 
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: `uv run python scripts/audit_exception_handling.py --json`; verify:
    - `src/rag_engine.py:31` is in the findings (the bug 1 fix)
    - The per-file list includes INTERNAL_COMPLIANT findings (the bug 2 fix)
    - The per-file list is not truncated to top 15 (the bug 3 fix)
  - HOW: parse the JSON; assert each condition
  - COMMIT: rolled into the last fix commit (or a separate `docs(track): verify audit bug fixes` commit)

- [x] **Task 1.4.2: Run the full test suite post-Phase-1** [6bf8b911] 
  - WHERE: `tests/`
  - WHAT: `uv run python scripts/run_tests_batched.py`; verify all 11 tiers PASS
  - COMMIT: rolled into 1.4.1

---

## Phase 2: Classify the 4 UNCLEAR Sites in SMALL

### 2.1 Per-site classification

- [x] **Task 2.1.1: Classify `src/outline_tool.py` UNCLEAR site** [09debfe3] 
  - WHERE: `src/outline_tool.py:49` (per the audit JSON)
  - WHAT: Read the snippet + 2-3 lines of context; classify compliant-or-migration
  - HOW: `manual-slop_get_file_slice` on the file at L48-52; read the function context
  - DECISION: record in the per-site report
  - COMMIT: `docs(track): result_migration_small_files decisions for src/outline_tool.py UNCLEAR`
  - GIT NOTE: Classification + rationale

- [x] **Task 2.1.2: Classify `src/summarize.py` UNCLEAR site** [09debfe3] 
  - WHERE: `src/summarize.py:36`
  - WHAT: Same as 2.1.1
  - COMMIT: `docs(track): result_migration_small_files decisions for src/summarize.py UNCLEAR`

- [x] **Task 2.1.3: Classify `src/conductor_tech_lead.py` UNCLEAR site** [09debfe3] 
  - WHERE: `src/conductor_tech_lead.py:1` (or wherever the audit reports)
  - WHAT: Same as 2.1.1
  - COMMIT: `docs(track): result_migration_small_files decisions for src/conductor_tech_lead.py UNCLEAR`

- [x] **Task 2.1.4: Classify `src/openai_compatible.py` UNCLEAR site** [09debfe3] 
  - WHERE: `src/openai_compatible.py:1` (or wherever the audit reports)
  - WHAT: Same as 2.1.1
  - COMMIT: `docs(track): result_migration_small_files decisions for src/openai_compatible.py UNCLEAR`

- [x] **Task 2.1.5: Update audit heuristics if patterns emerge** [09debfe3] 
  - WHERE: `scripts/audit_exception_handling.py` (the `_classify_except` / `_classify_raise` functions)
  - WHAT: If 2+ of the 4 UNCLEAR sites are compliant and share a common pattern, add a heuristic to the audit script (similar to the review pass)
  - HOW: Same TDD pattern as the review pass (test first, then heuristic)
  - COMMIT: `feat(scripts): add heuristics for the 4 SMALL UNCLEAR patterns` (conditional on pattern emergence)

---

## Phase 3-7: Migrate the 37 Files in Batches

The 35 SMALL files are batched 5-7 per commit (per the umbrella spec). The 2 MEDIUM files get dedicated commits. The batches are grouped by topic for coherence:

### Phase 3: Logging + Tracking batch (7 files)

- [x] **Task 3.1: Migrate `src/summary_cache.py` (4 sites)** [22db985e] 
  - WHERE: `src/summary_cache.py:39, 48, 91, 100`
  - WHAT: Each `try/except` becomes a `Result[T]` return
  - HOW: `manual-slop_get_file_slice` for each site; convert
  - COMMIT: `refactor(src): migrate src/summary_cache.py to Result[T] error handling`
  - GIT NOTE: 4 sites migrated; per-site mapping

- [x] **Task 3.2: Migrate `src/log_pruner.py` (2 sites)** [035ad726] 
  - WHERE: `src/log_pruner.py:0+` (2 compliant sites — no migration needed)
  - DECISION: per the audit, the 2 sites are `INTERNAL_COMPLIANT`; no migration; document the decision
  - COMMIT: `docs(track): result_migration_small_files decisions for src/log_pruner.py (2 compliant; 0 migration)`
  - GIT NOTE: Audit classification confirmed

- [x] **Task 3.3: Migrate `src/log_registry.py` (2 sites)** [01fdcd88] 
  - WHERE: `src/log_registry.py:2+` (per the audit)
  - COMMIT: `refactor(src): migrate src/log_registry.py to Result[T] error handling`
  - GIT NOTE: 2 sites migrated

- [x] **Task 3.4: Migrate `src/performance_monitor.py` (1 site)** [e7039623] 
  - WHERE: `src/performance_monitor.py:1+` (per the audit; 1 compliant site)
  - DECISION: 1 compliant; no migration
  - COMMIT: `docs(track): result_migration_small_files decisions for src/performance_monitor.py (1 compliant; 0 migration)`
  - GIT NOTE: Audit classification confirmed

- [x] **Task 3.5: Migrate `src/startup_profiler.py` (1 site)** [7298fbd6] 
  - WHERE: `src/startup_profiler.py:1+` (per the audit; 1 migration-target)
  - COMMIT: `refactor(src): migrate src/startup_profiler.py to Result[T] error handling`
  - GIT NOTE: 1 site migrated

- [x] **Task 3.6: Migrate `src/project_manager.py` (5 sites)** [7298fbd6] 
  - WHERE: `src/project_manager.py:32, 98, 363, 375, 390` (per the audit JSON)
  - COMMIT: `refactor(src): migrate src/project_manager.py to Result[T] error handling`
  - GIT NOTE: 5 sites migrated

- [x] **Task 3.7: Migrate `src/paths.py` (3 sites)** [2339846d] 
  - WHERE: `src/paths.py:3+` (per the audit; 3 compliant sites)
  - DECISION: 3 compliant; no migration
  - COMMIT: `docs(track): result_migration_small_files decisions for src/paths.py (3 compliant; 0 migration)`
  - GIT NOTE: Audit classification confirmed

### Phase 4: Config + Preset batch (6 files)

- [x] **Task 4.1: Migrate `src/presets.py` (2 sites)** [4e57ce15] 
  - WHERE: `src/presets.py:2+` (per the audit; 2 migration-target)
  - COMMIT: `refactor(src): migrate src/presets.py to Result[T] error handling`

- [x] **Task 4.2: Migrate `src/personas.py` (3 sites)** [807727c2] 
  - WHERE: `src/personas.py:3+` (per the audit; 3 compliant sites)
  - DECISION: 3 compliant; no migration
  - COMMIT: `docs(track): result_migration_small_files decisions for src/personas.py (3 compliant; 0 migration)`

- [x] **Task 4.3: Migrate `src/tool_presets.py` (3 sites)** [807727c2] 
  - WHERE: `src/tool_presets.py:3+` (per the audit; 3 compliant sites)
  - DECISION: 3 compliant; no migration
  - COMMIT: `docs(track): result_migration_small_files decisions for src/tool_presets.py (3 compliant; 0 migration)`

- [x] **Task 4.4: Migrate `src/context_presets.py` (1 site)** [4e57ce15] 
  - WHERE: `src/context_presets.py:1+` (per the audit; 1 migration-target)
  - COMMIT: `refactor(src): migrate src/context_presets.py to Result[T] error handling`

- [x] **Task 4.5: Migrate `src/vendor_capabilities.py` (1 site)** [a49e3bba] 
  - WHERE: `src/vendor_capabilities.py:1+` (per the audit; 1 migration-target — actually suspicious category)
  - COMMIT: `refactor(src): migrate src/vendor_capabilities.py to Result[T] error handling`

- [x] **Task 4.6: Migrate `src/workspace_manager.py` (3 sites)** [807727c2] 
  - WHERE: `src/workspace_manager.py:3+` (per the audit; 3 compliant sites)
  - DECISION: 3 compliant; no migration
  - COMMIT: `docs(track): result_migration_small_files decisions for src/workspace_manager.py (3 compliant; 0 migration)`

### Phase 5: UI + Theme + Tooling batch (7 files)

- [x] **Task 5.1: Migrate `src/command_palette.py` (1 site)** [3616d35a] 
- [x] **Task 5.2: Migrate `src/commands.py` (3 sites)** [3616d35a] 
- [x] **Task 5.3: Migrate `src/diff_viewer.py` (1 site)** [3616d35a] 
- [x] **Task 5.4: Migrate `src/external_editor.py` (3 sites, 2 OPTIONAL_RETURN)** [3616d35a] 
- [x] **Task 5.5: Migrate `src/theme_2.py` (1 site)** [0f026af0] 
- [x] **Task 5.6: Migrate `src/theme_models.py` (1 migration-target + 9 compliant)** [0f026af0] 
- [x] **Task 5.7: Migrate `src/markdown_helper.py` (2 sites)** [3616d35a] 

(Each task = 1 commit; pattern as in Phase 3-4)

### Phase 6: Provider + Adapter + Orchestration batch (7 files)

- [x] **Task 6.1: Migrate `src/gemini_cli_adapter.py` (2 sites)** [d6b487d9] 
- [x] **Task 6.2: Migrate `src/openai_compatible.py` (1 UNCLEAR — already classified in Phase 2)** [d6b487d9] 
- [x] **Task 6.3: Migrate `src/aggregate.py` (4 sites)** [f4a445bd] 
- [x] **Task 6.4: Migrate `src/conductor_tech_lead.py` (1 UNCLEAR — already classified in Phase 2)** [d6b487d9] 
- [x] **Task 6.5: Migrate `src/dag_engine.py` (1 site)** [d6b487d9] 
- [x] **Task 6.6: Migrate `src/multi_agent_conductor.py` (4 sites)** [f4a445bd] 
- [x] **Task 6.7: Migrate `src/models.py` (3 sites: 2 V + 1 S; 2 compliant sites stay as-is)** [f4a445bd] 

(Each task = 1 commit; pattern as in Phase 3-4)

### Phase 7: Infrastructure + Hook + Utility batch (8 files)

- [x] **Task 7.1: Migrate `src/api_hook_client.py` (2 sites)** [d3dd7bd9] 
- [x] **Task 7.2: Migrate `src/api_hooks.py` (5 sites: 3 V + 2 S)** [a5b40bcf] 
- [x] **Task 7.3: Migrate `src/file_cache.py` (2 sites)** [a5b40bcf] 
- [x] **Task 7.4: Migrate `src/hot_reloader.py` (1 site)** [a5b40bcf] 
- [x] **Task 7.5: Migrate `src/orchestrator_pm.py` (2 sites)** [a5b40bcf] 
- [x] **Task 7.6: Migrate `src/outline_tool.py` (3 sites, including the 1 UNCLEAR from Phase 2)** [a5b40bcf] 
- [x] **Task 7.7: Migrate `src/shell_runner.py` (2 sites)** [a5b40bcf] 
- [x] **Task 7.8: Migrate `src/summarize.py` (2 sites, including the 1 UNCLEAR from Phase 2)** [a5b40bcf] 

(Each task = 1 commit; pattern as in Phase 3-4)

### Phase 8: MEDIUM files (2 files, dedicated commits per umbrella)

- [x] **Task 8.1: Migrate `src/session_logger.py` (8 sites)** [c329c869] 
  - WHERE: `src/session_logger.py:99, 131, 147, 160, 188, 201, 226, 245`
  - WHAT: All 8 sites are migration-target; convert each to `Result[T]`
  - HOW: `manual-slop_get_file_slice` for each site; convert
  - COMMIT: `refactor(src): migrate src/session_logger.py to Result[T] error handling (8 sites)`
  - GIT NOTE: 8 sites migrated; per-site mapping

- [x] **Task 8.2: Migrate `src/warmup.py` (7 sites)** [c329c869] 
  - WHERE: `src/warmup.py:85, 139, 175, 215, 249, 276, 300` (per the audit JSON; L85 is the validation raise — already classified as compliant by the review pass)
  - WHAT: 6 migration-target + 1 compliant; convert the 6
  - HOW: `manual-slop_get_file_slice` for each migration-target site; convert
  - COMMIT: `refactor(src): migrate src/warmup.py to Result[T] error handling (6 sites; L85 validation raise stays as-is)`
  - GIT NOTE: 6 sites migrated; L85 stays (validation raise is legitimate per styleguide)

---

## Phase 9: Verification

- [ ] **Task 9.1: Run the audit post-migration**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: `uv run python scripts/audit_exception_handling.py --json`; verify:
    - 0 migration-target sites in the 37-file scope (all are `INTERNAL_COMPLIANT`, `BOUNDARY_*`, or `INTERNAL_PROGRAMMER_RAISE`)
    - The per-file list shows all findings (not truncated)
  - HOW: parse the JSON; assert the 37 files have 0 V+S sites
  - COMMIT: `docs(track): verify result_migration_small_files_20260617 migration complete (0 migration-target sites in scope)`

- [ ] **Task 9.2: Run the full test suite**
  - WHERE: `tests/`
  - WHAT: `uv run python scripts/run_tests_batched.py`; verify all 11 tiers PASS
  - HOW: the batched runner
  - COMMIT: rolled into 9.1

- [ ] **Task 9.3: Write the per-site report**
  - WHERE: `docs/reports/RESULT_MIGRATION_SMALL_FILES_20260617.md`
  - WHAT: Per-site decision table for the 4 UNCLEAR sites + per-file migration summary (76 sites across 37 files) + audit-script bug-fix summary + verification
  - HOW: follow the format of the review-pass report
  - COMMIT: `docs(report): add result_migration_small_files_20260617 report`
  - GIT NOTE: Summary of the migration + audit-script fixes

- [ ] **Task 9.4: Update the umbrella spec**
  - WHERE: `conductor/tracks/result_migration_20260616/spec.md`
  - WHAT: Update the "Post-Review Pass Update" callout to note sub-track 2 shipped; update the sub-track 2 row to "shipped"; update the recommended sequence
  - HOW: edit the spec
  - COMMIT: `docs(track): update umbrella with sub-track 2 shipped`
  - GIT NOTE: 1-sentence note

- [ ] **Task 9.5: Mark the track as completed**
  - WHERE: `conductor/tracks/result_migration_small_files_20260617/metadata.json` + `state.toml`, `conductor/tracks.md`
  - WHAT: Update `status: active → completed`; `current_phase: "complete"`
  - HOW: edit the files
  - COMMIT: `conductor(track): mark result_migration_small_files_20260617 as completed`
  - GIT NOTE: 1-sentence note

- [ ] **Task 9.6: Write the track completion report**
  - WHERE: `docs/reports/TRACK_COMPLETION_result_migration_small_files_20260617.md`
  - WHAT: End-of-track report (per the precedent set by the review-pass completion report)
  - HOW: follow the format of `docs/reports/TRACK_COMPLETION_result_migration_review_pass_20260617.md`
  - COMMIT: `docs(reports): TRACK_COMPLETION_result_migration_small_files_20260617`
  - GIT NOTE: End-of-track report

---

## Phase 10: Complete the Result[T] Migration (the 27 SILENT_SWALLOW + 14 new UNCLEAR sites)

Sub-track 2 shipped with a documented G4 deviation: 27 sites remain `INTERNAL_SILENT_SWALLOW` (narrow-catch + pass) and 14 new `UNCLEAR` sites emerged from the narrowing strategy. The user has directed that **all 27 must be fully migrated to `Result[T]`** — not narrowed, not logged-and-returned, not narrowed-with-log. The `Result[T]` convention is mandatory: every `try/except` site that can fail returns `Result[T]` with structured `ErrorInfo`, and the caller decides what to do. The 14 new UNCLEAR sites are addressed by 2-3 new audit heuristics that recognize the post-migration patterns.

This is a codebase-hardening phase. The project uses `io_pool` for multi-threaded dispatch; Python has no wave-based preemptive thread pipelining, so every soft/hard failure point needs full context (category, message, source, exception) — not silent recovery.

### 10.1 — Enumerate the remaining sites

- [ ] **Task 10.1.1: Run the audit and extract the 27 SILENT_SWALLOW + 14 new UNCLEAR sites**
  - WHERE: `scripts/audit_exception_handling.py` (already on the branch from Phase 1)
  - WHAT: `uv run python scripts/audit_exception_handling.py --json > audit_pre_phase10.json`; parse the per-file findings; for each file in the 37-file scope, list the SILENT_SWALLOW and new-UNCLEAR sites with file:line
  - HOW: read the JSON; filter by category and by file
  - OUTPUT: per-site list with file:line + current snippet + context function name
  - COMMIT: `docs(track): enumerate Phase 10 target sites (27 SILENT_SWALLOW + 14 UNCLEAR)`
  - GIT NOTE: Per-site enumeration; file:line; the 5 known sites (startup_profiler.py:40, file_cache.py:98, outline_tool.py:90, warmup.py:139/215/249, hot_reloader.py:58) plus the others to be enumerated

### 10.2 — Per-file full Result[T] migration

For each of the 27 SILENT_SWALLOW sites:

1. Read the function's current signature and behavior
2. Change the return type to `Result[T]` (or `Result[None]` if the function returns `None`)
3. Add `Result` import if needed (from `src/result_types.py`)
4. In the except body, capture the exception and convert to `ErrorInfo`:
   ```python
   except SomeError as e:
       return Result(data=NIL_T, errors=[ErrorInfo(
           category="<category>",
           message=str(e),
           source="<module>.<function>",
           exception=e,
       )])
   ```
   - If the function has a sensible fallback value (e.g., `default_value`), use `Result(data=default_value, errors=[...])` instead of `NIL_T`. The caller still sees the error in `.errors` and decides what to do.
5. Update **all** callers to check `.ok` and `.errors`. The caller decides what to do (log, fall back, surface to UI, re-raise as a thread-pipeline failure). No caller should ignore `.errors` silently.
6. Add a test for the new Result-based API. Tests must cover:
   - The success path: `assert result.ok and result.data == <expected>`
   - The error path: `assert not result.ok and result.errors[0].category == <expected> and result.errors[0].exception is SomeError`
   - Callers that previously ignored the return value must be updated to check `result.ok`

The migration is per-file. Group files into atomic commits (1-2 sites per commit, or all sites in a file in one commit if the file is small). The 5 known sites to start with (from the track completion report):

- [ ] **Task 10.2.1: Migrate `src/startup_profiler.py:40` to `Result[T]`** (remove the `stderr.write` log; return Result with the profile data and the captured exception)
- [ ] **Task 10.2.2: Migrate `src/file_cache.py:98` to `Result[T]`** (the mtime cache fallback; return Result with the default cache value and the captured exception)
- [ ] **Task 10.2.3: Migrate `src/outline_tool.py:90` to `Result[T]`** (the ast.unparse fallback; return Result with the empty outline and the captured exception)
- [ ] **Task 10.2.4: Migrate `src/warmup.py:139` (on_complete callback) to `Result[T]`** (the user-callback error path; the callback now returns Result; the warmup manager threads the Result to the io_pool completion handler)
- [ ] **Task 10.2.5: Migrate `src/warmup.py:215` (_record_success callback) to `Result[T]`**
- [ ] **Task 10.2.6: Migrate `src/warmup.py:249` (_record_failure callback) to `Result[T]`**
- [ ] **Task 10.2.7: Migrate `src/hot_reloader.py:58` (module reload) to `Result[T]`** (the reload error path; the hot-reloader manager threads the Result to the module-reload completion handler)

The other 20 sites: tier-2 enumerates from the audit JSON (Task 10.1.1) and migrates each. Each site gets its own task in this phase; the plan's per-task list is updated as sites are enumerated.

### 10.3 — Audit heuristics for the 14 new UNCLEAR sites

The narrowing in sub-track 2 created 14 new UNCLEAR sites that the audit doesn't recognize. After the full Result migration in 10.2:
- Some of these will be reclassified automatically by existing heuristics (e.g., `Result`-returning code triggers `BOUNDARY_SDK` or heuristic #19 patterns)
- The remaining need 2-3 new heuristics in `scripts/audit_exception_handling.py`:
  - **Heuristic A**: `try/except SomeError: return Result(data=NIL_T, errors=[ErrorInfo(...)])` in a non-`*_result` function → `INTERNAL_COMPLIANT` (the canonical Result-based recovery pattern, even when the function name doesn't end in `_result`)
  - **Heuristic B**: `try/except SomeError: return Result(data=default_value, errors=[ErrorInfo(...)])` where the function's success path returns `Result(data=...)` → `INTERNAL_COMPLIANT` (the Result-based fallback pattern)
  - **Heuristic C** (if needed): `try/except SomeError: return default_value` where the function's annotated return type is `Result[T]` → `INTERNAL_COMPLIANT` (the Result-typed fallback)

- [ ] **Task 10.3.1: Write failing test for Heuristic A**
  - WHERE: `tests/test_audit_exception_handling_heuristics.py` (extending the existing file)
  - WHAT: A test fixture with `try/except SomeError: return Result(data=NIL_T, errors=[ErrorInfo(...)])` in a function whose name doesn't end in `_result`. Assert the audit classifies the except as `INTERNAL_COMPLIANT`.
  - HOW: same `subprocess` + fixture pattern as the existing tests

- [ ] **Task 10.3.2: Implement Heuristic A in `_classify_except`**
  - WHERE: `scripts/audit_exception_handling.py` (the `_try_compliant_pattern` helper or `_classify_except` directly)
  - WHAT: Detect the pattern; return `INTERNAL_COMPLIANT`
  - HOW: AST inspection of the except body's `Return` statement; check that it returns a `Call` to `Result(...)` with `data=` and `errors=` kwargs; check that the enclosing function name does NOT end in `_result`
  - COMMIT: `feat(scripts): heuristic A — Result-returning recovery in non-*_result function`

- [ ] **Task 10.3.3: Write failing test for Heuristic B**
  - WHERE: `tests/test_audit_exception_handling_heuristics.py`
  - WHAT: A test fixture with `try/except SomeError: return Result(data=default, errors=[...])` where the function's success path also returns `Result(...)`. Assert `INTERNAL_COMPLIANT`.
  - HOW: same pattern as 10.3.1

- [ ] **Task 10.3.4: Implement Heuristic B in `_classify_except`**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: Detect the pattern; return `INTERNAL_COMPLIANT`
  - HOW: Check the except body's `Return` is a `Result(...)` call with both `data=` and `errors=` kwargs; check the function has a success path that also returns `Result(...)`
  - COMMIT: `feat(scripts): heuristic B — Result-typed fallback pattern`

- [ ] **Task 10.3.5: Add Heuristic C if needed** (conditional on whether A+B cover the 14 sites)
  - WHERE: `tests/test_audit_exception_handling_heuristics.py` + `scripts/audit_exception_handling.py`
  - WHAT: Detect the pattern; return `INTERNAL_COMPLIANT`
  - HOW: Check the function's annotated return type is `Result[T]` and the except body returns a non-Result value (the fallback)
  - COMMIT: `feat(scripts): heuristic C — Result-typed return with non-Result fallback` (conditional)

- [ ] **Task 10.3.6: Verify the new heuristics reclassify the 14 UNCLEAR sites**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: Re-run the audit; assert the 14 sites are now `INTERNAL_COMPLIANT` or `BOUNDARY_*`
  - HOW: parse the JSON; filter by the 14 file:line pairs
  - COMMIT: rolled into 10.3.2 / 10.3.4 / 10.3.5 (whichever fires)

### 10.4 — Update the per-site report

- [ ] **Task 10.4.1: Extend the per-site report with the Phase 10 changes**
  - WHERE: `docs/reports/RESULT_MIGRATION_SMALL_FILES_20260617.md`
  - WHAT: Add a "Phase 10" section with:
    - The full per-site table for the 27 SILENT_SWALLOW + 14 new UNCLEAR sites
    - The new audit heuristics (per-site count delta)
    - The Result-based API for each migrated function (what `.data` and `.errors` look like)
    - The call-graph impact: which callers were updated; the threading model for warmup callbacks and hot-reloader (the Result now flows through the io_pool completion handler)
  - HOW: append to the existing report; preserve the existing Phase 1-9 content
  - COMMIT: `docs(report): add Phase 10 results to the per-site report`
  - GIT NOTE: 27 SILENT_SWALLOW → 0; 14 new UNCLEAR → 0 (via the 2-3 new heuristics)

### 10.5 — Verification

- [ ] **Task 10.5.1: Run the audit post-Phase-10**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: `uv run python scripts/audit_exception_handling.py --json > audit_post_phase10.json`; verify:
    - 0 `INTERNAL_SILENT_SWALLOW` sites in the 37-file scope
    - 0 migration-target sites in the 37-file scope (G4 now met)
    - 0 new `UNCLEAR` sites (the 14 are reclassified)
  - HOW: parse the JSON; assert the 37 files have 0 V+S sites
  - COMMIT: `docs(track): verify Phase 10 result migration complete (0 SILENT_SWALLOW; 0 UNCLEAR; 0 migration-target in 37-file scope)`

- [ ] **Task 10.5.2: Run the full test suite**
  - WHERE: `tests/`
  - WHAT: `uv run python scripts/run_tests_batched.py`; verify all 11 tiers PASS
  - HOW: the batched runner
  - COMMIT: rolled into 10.5.1

- [ ] **Task 10.5.3: Update the track completion report**
  - WHERE: `docs/reports/TRACK_COMPLETION_result_migration_small_files_20260617.md`
  - WHAT: Add a "Phase 10 Addendum" section with the per-site count delta, the new heuristics, the threading-model impact (Result flows through io_pool for the 4 callback sites), and the test pass count
  - HOW: append to the existing report
  - COMMIT: `docs(reports): TRACK_COMPLETION_result_migration_small_files_20260617 addendum (Phase 10)`
  - GIT NOTE: G4 deviation now resolved; the 37-file scope has 0 migration-target sites

### 10.6 — Mark Phase 10 completed

- [ ] **Task 10.6.1: Update state.toml and metadata.json**
  - WHERE: `conductor/tracks/result_migration_small_files_20260617/state.toml` + `metadata.json`, `conductor/tracks.md`
  - WHAT: Mark all Phase 10 tasks completed with commit SHAs; update `status: active → completed`; `current_phase: 10 → "complete"`; update `outcomes` in metadata.json
  - HOW: edit the files
  - COMMIT: `conductor(track): mark result_migration_small_files_20260617 Phase 10 completed (G4 deviation resolved)`
  - GIT NOTE: 27 SILENT_SWALLOW sites migrated to Result[T]; 14 new UNCLEAR sites reclassified via 2-3 new audit heuristics; G4 now met

- [ ] **Task 10.6.2: Update the umbrella spec to remove the follow-up note**
  - WHERE: `conductor/tracks/result_migration_20260616/spec.md`
  - WHAT: Change the "follow-up sub-track planned" line in the post-sub-track-2 callout to "Phase 10 of sub-track 2 complete; G4 deviation resolved"
  - HOW: edit the spec
  - COMMIT: `docs(track): update umbrella with sub-track 2 Phase 10 complete`
  - GIT NOTE: 1-sentence note

---

## Phase 11: ACTUAL Full Result[T] Migration (REJECT Phase 10's sliming; redo the 21 sites for real)

**REJECTED:** Phase 10 is REJECTED. The work tier-2 submitted under "Phase 10" did FULL `Result[T]` migration for 5 sites (good) but NARROWED+LOG the other 21 sites (BAD). The 5 new audit heuristics tier-2 added (#22-#26) are LAUNDERING HEURISTICS - they classify narrowing as `INTERNAL_COMPLIANT` to make the audit say "G4 resolved" without actually doing the work. This phase REJECTS Phase 10, REVERTS the laundering heuristics, and does the FULL `Result[T]` migration for the 21 sites tier-2 slimed.

**NON-NEGOTIABLE RULES (read these first):**

1. **Result[T] is NOT optional.** Every `try/except` site that can fail MUST return `Result[T]` with structured `ErrorInfo`. No exceptions. No "but it can't". No "context manager" excuse. No "user callback" excuse.
2. **NO narrowing.** `except Exception` -> `except SpecificException` is NOT a Result migration. It's a different smell. The user said no.
3. **NO logging-only.** `except SomeError: logger.warning(...); return default` is NOT a Result migration. The caller can't see the error. Use `Result(data=default, errors=[ErrorInfo(...)])` so the caller can decide.
4. **NO silent recovery.** `except SomeError: pass` is not allowed. `except SomeError: return None` is not allowed. Return `Result[None]` or `Result[data=fallback]`.
5. **DO NOT add new audit heuristics that classify narrowing as compliant.** The 5 heuristics tier-2 added (#22-#26) are LAUNDERING. They will be REVERTED in this phase.
6. **DO NOT claim the test count is 10 tiers.** It is 11. The user verified this. Tier-2 has been miscounting (saying 10 instead of 11) in every report. The 11th tier is `tier-1-unit-comms`. The report must say "all 11 test tiers PASS".
7. **DO NOT use "context manager" as an excuse.** `StartupProfiler.phase()` is NOT a context manager. It is a regular method. It can return `Result[None]`. There is no `__enter__` or `__exit__`.
8. **DO NOT use "user callback" as an excuse.** The user callbacks in `WarmupManager` are `Callable[[dict], None]`. They stay as-is. The INTERNAL methods (`_record_success`, `_record_failure`, `_log_canary`, `_log_summary`) are not user code. The MANAGER can return `Result[T]`. The completion handler checks `result.ok`. **Look at `src/hot_reloader.py` on the branch** - tier-2 did the same pattern correctly there. Apply the same pattern to `warmup.py`.
9. **DO NOT skip the io_pool callback sites** (`warmup.py:139/215/249`). These MUST thread the `Result` through the io_pool completion handler. The pattern is in `hot_reloader.py`. Use it.
10. **MUST pass ALL 11 test tiers.** Not 10. All 11.

**What Phase 10 did wrong (the slime):**

Tier-2 wrote in the per-site report:
> "Strategy B: Narrow-catch + log/return-fallback (21 sites across 9 files)"

This is NOT a Result migration. The 21 sites return a fallback value or write to stderr. They do NOT return `Result[T]`. The user said "Result[T] is not optional" and tier-2 made it optional via 5 laundering heuristics that classify the narrowing as compliant.

Tier-2 also wrote:
> "`src/startup_profiler.py:40` (phase() stderr.write) - narrow + log (context manager; can't return Result)"

`StartupProfiler.phase()` is NOT a context manager. It is a regular method that returns `None`. It can return `Result[None]`. This is a tier-2 invention.

Tier-2 also wrote:
> "For warmup, the user callbacks cannot be Result-typed (they're external code)"

The user callbacks in `WarmupManager` are `Callable[[dict], None]`. They stay as-is. The INTERNAL methods (`_record_success`, etc.) are not user code. **The pattern tier-2 used in `src/hot_reloader.py` shows exactly how to do this** - see `HotReloader.reload()` returning `Result[bool]` and the io_pool threading the Result. Apply the same pattern to `warmup.py`.

### 11.1 - REVERT the 5 LAUNDERING HEURISTICS

Tier-2 added 5 new heuristics to `scripts/audit_exception_handling.py` that classify non-Result narrowing as `INTERNAL_COMPLIANT`. They MUST be reverted. The convention requires `Result[T]`, not narrowed+log.

- [ ] **Task 11.1.1: REVERT heuristic #22 ("Narrow except + return fallback value")**
  - WHERE: `scripts/audit_exception_handling.py` (the `_try_compliant_pattern` helper)
  - WHAT: Delete the heuristic #22 block. It classifies `try/except SomeError: return <fallback>` (non-Result) as compliant. This is WRONG. The convention requires `Result[T]`.
  - HOW: Surgical delete. Mark the corresponding test `@pytest.mark.xfail` with reason "heuristic #22 reverted in Phase 11; full Result migration required" so the test count stays 11 tiers.
  - COMMIT: `revert(scripts): heuristic #22 (narrow+return fallback) - classifies non-Result narrowing as compliant, contradicts the convention`
  - GIT NOTE: Heuristic #22 was added in Phase 10 to make 21 sites appear compliant. It is a laundering heuristic. The convention requires `Result[T]` returns; this heuristic accepts non-Result fallback returns, which is wrong.

- [ ] **Task 11.1.2: REVERT heuristic #23 ("Narrow except + use error inline")**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: Delete the heuristic #23 block. It classifies `try/except SomeError as exc: <use exc>` (non-Result) as compliant. WRONG.
  - HOW: Same pattern as 11.1.1. Mark the test `@pytest.mark.xfail`.
  - COMMIT: `revert(scripts): heuristic #23 (narrow+use error inline) - wrong`

- [ ] **Task 11.1.3: REVERT heuristic #24 ("Narrow except + assign fallback")**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: Delete the heuristic #24 block. It classifies `try/except SomeError: var = default` (non-Result) as compliant. WRONG.
  - HOW: Same pattern.
  - COMMIT: `revert(scripts): heuristic #24 (narrow+assign fallback) - wrong`

- [ ] **Task 11.1.4: REVERT heuristic #25 ("Narrow except + uses traceback")**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: Delete the heuristic #25 block. It classifies `try/except SomeError: traceback.format_exc()` (non-Result) as compliant. WRONG.
  - HOW: Same pattern.
  - COMMIT: `revert(scripts): heuristic #25 (narrow+uses traceback) - wrong`

- [ ] **Task 11.1.5: REVERT heuristic #26 ("Narrow except + non-trivial body")**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: Delete the heuristic #26 block. It is a CATCH-ALL that classifies ANY non-trivial except body as compliant. THIS IS THE WORST LAUNDERING HEURISTIC. WRONG.
  - HOW: Same pattern.
  - COMMIT: `revert(scripts): heuristic #26 (narrow+non-trivial body catch-all) - wrong`

### 11.2 - ADD the legitimate Heuristic A (Result-returning recovery in non-*_result function)

This is the heuristic the original plan called for. It recognizes the canonical Result-based recovery pattern.

- [ ] **Task 11.2.1: Write failing test for Heuristic A**
  - WHERE: `tests/test_audit_exception_handling_heuristics.py` (extending the existing file)
  - WHAT: A test fixture with `try/except SomeError: return Result(data=NIL_T, errors=[ErrorInfo(...)])` in a function whose name does NOT end in `_result`. Assert the audit classifies the except as `INTERNAL_COMPLIANT`.
  - HOW: same `subprocess` + fixture pattern as the existing tests
  - COMMIT: `test(scripts): heuristic A - Result-returning recovery in non-*_result function = INTERNAL_COMPLIANT`

- [ ] **Task 11.2.2: Implement Heuristic A in `_classify_except`**
  - WHERE: `scripts/audit_exception_handling.py` (in `_try_compliant_pattern` after the existing heuristics)
  - WHAT: Detect the pattern; return `INTERNAL_COMPLIANT`
  - HOW: AST inspection: check the except body's `Return` is a `Call` to `Result(...)` with `data=` and `errors=` kwargs; check the enclosing function name does NOT end in `_result`
  - COMMIT: `feat(scripts): heuristic A - return Result with errors in non-*_result function = INTERNAL_COMPLIANT`

- [ ] **Task 11.2.3: Verify the new heuristic recognizes the 21 migrated sites**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: Re-run the audit after Phase 11.3 completes; assert the 21 sites are now `INTERNAL_COMPLIANT` (via Heuristic A recognizing their `Result` returns)
  - HOW: parse the JSON; filter by the 21 file:line pairs
  - COMMIT: rolled into 11.2.2

### 11.3 - Per-file FULL Result[T] migration (the 21 slimed sites)

The 21 sites in tier-2's "Strategy B" table (the sliming) MUST be migrated to FULL `Result[T]`. NO narrowing. NO logging-only. NO silent recovery. NO excuses about context managers or user callbacks.

**Reference implementation:** `src/hot_reloader.py` (on the branch) is the gold standard. `HotReloader.reload()` returns `Result[bool]`, `reload_all()` returns `Result[bool]`, the io_pool threads the Result. Apply the same pattern to the warmup.py callback sites.

For each site:
1. Read the function's current signature
2. Change the return type to `Result[T]` (or `Result[None]`)
3. Add `Result` import if needed (from `src/result_types.py`)
4. In the except body, capture the exception and convert to `ErrorInfo`:
   ```python
   except SomeError as e:
       return Result(data=NIL_T, errors=[ErrorInfo(
           category="<category>",
           message=str(e),
           source="<module>.<function>",
           exception=e,
       )])
   ```
   - If the function has a sensible fallback value (e.g., `default_value`), use `Result(data=default_value, errors=[...])` instead of `NIL_T`. The caller still sees the error in `.errors` and decides what to do.
5. Update **all** callers to check `.ok` and `.errors`. No caller should ignore `.errors` silently.
6. Add a test for the new Result-based API. Tests must cover:
   - The success path: `assert result.ok and result.data == <expected>`
   - The error path: `assert not result.ok and result.errors[0].category == <expected>`

The migration is per-file. Group files into atomic commits. The 21 sites:

#### 11.3.1: `src/warmup.py` (6 sites: 4 io_pool callbacks + 2 observability helpers)

These are the most important. Tier-2's claim that "user callbacks cannot be Result-typed" is WRONG. The user callbacks in `WarmupManager._callbacks` are `Callable[[dict], None]` and stay as-is. The INTERNAL methods (`_record_success`, `_record_failure`, `_log_canary`, `_log_summary`) and the public methods (`on_complete`, `submit`, `wait`) are NOT user code - they are part of the manager and CAN return `Result[T]`. **Apply the same pattern tier-2 used in `src/hot_reloader.py`.**

- [ ] **Task 11.3.1.1: Migrate `src/warmup.py:139` (`on_complete` callback fire) to `Result[T]`**
  - WHERE: `src/warmup.py:on_complete()` method (around L139)
  - WHAT: Change `on_complete()` to return `Result[bool]`. The callback wrapping (`try: callback(snap) except Exception as e: sys.stderr.write(...)`) becomes the wrapper. The internal `_callbacks` list contains user callbacks (`Callable[[dict], None]`); these stay as-is. The Result is for the manager's own bookkeeping.
  - HOW: See `src/hot_reloader.py:reload()` for the pattern.
  - COMMIT: `refactor(src): warmup.on_complete to Result[T] (io_pool callback thread-through)`
  - GIT NOTE: Follows the same pattern as `src/hot_reloader.py:reload()` (the io_pool completion handler checks `result.ok`)

- [ ] **Task 11.3.1.2: Migrate `src/warmup.py:215` (`_record_success` callback fire) to `Result[T]`**
  - WHERE: `src/warmup.py:_record_success()` method
  - WHAT: Change to return `Result[bool]`
  - HOW: See `src/hot_reloader.py` pattern
  - COMMIT: `refactor(src): warmup._record_success to Result[T]`

- [ ] **Task 11.3.1.3: Migrate `src/warmup.py:249` (`_record_failure` callback fire) to `Result[T]`**
  - WHERE: `src/warmup.py:_record_failure()` method
  - WHAT: Change to return `Result[bool]`
  - HOW: See `src/hot_reloader.py` pattern
  - COMMIT: `refactor(src): warmup._record_failure to Result[T]`

- [ ] **Task 11.3.1.4: Migrate `src/warmup.py:276` (`_log_canary` stderr.write) to `Result[T]`**
  - WHERE: `src/warmup.py:_log_canary()` method
  - WHAT: Change to return `Result[None]` (or `Result[bool]` for success). The `sys.stderr.write` is a side effect; the Result captures whether the log succeeded.
  - HOW: Standard pattern
  - COMMIT: `refactor(src): warmup._log_canary to Result[T]`

- [ ] **Task 11.3.1.5: Migrate `src/warmup.py:300` (`_log_summary` stderr.write) to `Result[T]`**
  - WHERE: `src/warmup.py:_log_summary()` method
  - WHAT: Same as 11.3.1.4
  - COMMIT: `refactor(src): warmup._log_summary to Result[T]`

- [ ] **Task 11.3.1.6: Update the io_pool completion handler in warmup.py to check `result.ok`**
  - WHERE: `src/warmup.py` - wherever the io_pool's `submit` callback threads the result
  - WHAT: Update the completion handler to check `result.ok` on the new `Result` returns from `on_complete`, `_record_success`, `_record_failure`, `_log_canary`, `_log_summary`
  - HOW: Pattern from `src/hot_reloader.py:reload_all()` (which aggregates errors from multiple `reload()` calls into a single `Result[bool]`)
  - COMMIT: rolled into the per-method commits above

#### 11.3.2: `src/startup_profiler.py:40` (the "context manager" lie)

`StartupProfiler.phase()` is NOT a context manager. It is a regular method that returns `None`. There is no `__enter__` or `__exit__`. Tier-2's claim is factually wrong.

- [ ] **Task 11.3.2.1: Migrate `src/startup_profiler.py:40` (`_end_phase` stderr.write) to `Result[T]`**
  - WHERE: `src/startup_profiler.py:phase()` or `_end_phase()` method (around L40)
  - WHAT: Change the return type to `Result[None]`. The `sys.stderr.write` failure is captured in `Result.errors`.
  - HOW: Standard pattern. The "context manager; can't return Result" claim is REJECTED - this is a regular method.
  - COMMIT: `refactor(src): startup_profiler.phase/_end_phase to Result[T] (NOT a context manager; regular method)`
  - GIT NOTE: Tier-2 claimed `phase()` was a context manager. It is not. It is a regular method that returns `None`. Changing to `Result[None]` is straightforward.

#### 11.3.3: `src/project_manager.py:366/378/393` (`get_all_tracks` metadata)

- [ ] **Task 11.3.3.1: Migrate `src/project_manager.py:366` to `Result[T]`**
  - WHERE: `src/project_manager.py:366` (in `get_all_tracks` or similar; the `state.from_dict` call)
  - WHAT: Change the function to return `Result[Dict]`. The state deserialization failure is captured in `Result.errors`.
  - HOW: Standard pattern
  - COMMIT: `refactor(src): project_manager.get_all_tracks state.from_dict to Result[T]`

- [ ] **Task 11.3.3.2: Migrate `src/project_manager.py:378` to `Result[T]`**
  - WHERE: `src/project_manager.py:378` (the `metadata.json` read)
  - WHAT: Same pattern
  - COMMIT: `refactor(src): project_manager.get_all_tracks metadata.json read to Result[T]`

- [ ] **Task 11.3.3.3: Migrate `src/project_manager.py:393` to `Result[T]`**
  - WHERE: `src/project_manager.py:393` (the `plan.md` read)
  - WHAT: Same pattern
  - COMMIT: `refactor(src): project_manager.get_all_tracks plan.md read to Result[T]`

#### 11.3.4: `src/orchestrator_pm.py:37/49` (`get_track_history_summary`)

- [ ] **Task 11.3.4.1: Migrate `src/orchestrator_pm.py:37` to `Result[T]`**
  - WHERE: `src/orchestrator_pm.py:37` (track metadata.json read in `get_track_history_summary`)
  - WHAT: Change to return `Result[Dict]`
  - HOW: Standard pattern
  - COMMIT: `refactor(src): orchestrator_pm.get_track_history_summary metadata read to Result[T]`

- [ ] **Task 11.3.4.2: Migrate `src/orchestrator_pm.py:49` to `Result[T]`**
  - WHERE: `src/orchestrator_pm.py:49` (track spec.md read)
  - WHAT: Same pattern
  - COMMIT: `refactor(src): orchestrator_pm.get_track_history_summary spec read to Result[T]`

#### 11.3.5: `src/file_cache.py:98` (mtime cache fallback)

- [ ] **Task 11.3.5.1: Migrate `src/file_cache.py:98` (`_get_mtime` cache fallback) to `Result[T]`**
  - WHERE: `src/file_cache.py:98` (in `_get_mtime` or similar; the `StopIteration` catch - tier-2 noted this was dead code; just remove the dead try/except AND migrate the live ones to Result)
  - WHAT: Change the function to return `Result[float]` (or `Result[None]` for the fallback). The mtime cache miss is captured in `Result.errors`.
  - HOW: Standard pattern
  - COMMIT: `refactor(src): file_cache._get_mtime to Result[T] (remove dead try/except StopIteration + migrate live fallback)`

#### 11.3.6: `src/api_hooks.py:914` (WebSocket connection cleanup)

- [ ] **Task 11.3.6.1: Migrate `src/api_hooks.py:914` (WebSocket connection cleanup) to `Result[T]`**
  - WHERE: `src/api_hooks.py:914`
  - WHAT: Change to return `Result[None]`
  - HOW: Standard pattern
  - COMMIT: `refactor(src): api_hooks WebSocket cleanup to Result[T]`

#### 11.3.7: `src/log_registry.py:249` (session path scan)

- [ ] **Task 11.3.7.1: Migrate `src/log_registry.py:249` (session path scan) to `Result[T]`**
  - WHERE: `src/log_registry.py:249`
  - WHAT: Change to return `Result[Dict]`
  - HOW: Standard pattern
  - COMMIT: `refactor(src): log_registry session path scan to Result[T]`

#### 11.3.8: `src/models.py:508` (datetime.fromisoformat fallback)

- [ ] **Task 11.3.8.1: Migrate `src/models.py:508` (`from_dict` datetime.fromisoformat) to `Result[T]`**
  - WHERE: `src/models.py:508` (in `from_dict` or similar)
  - WHAT: Change the function to return `Result[Dict]`. The lenient deserialization failure is captured in `Result.errors`.
  - HOW: Standard pattern
  - COMMIT: `refactor(src): models.from_dict datetime.fromisoformat to Result[T]`

#### 11.3.9: `src/multi_agent_conductor.py:317` (persona load fallback)

- [ ] **Task 11.3.9.1: Migrate `src/multi_agent_conductor.py:317` (persona load fallback) to `Result[T]`**
  - WHERE: `src/multi_agent_conductor.py:317`
  - WHAT: Change to return `Result[Dict]`
  - HOW: Standard pattern
  - COMMIT: `refactor(src): multi_agent_conductor.persona load to Result[T]`

#### 11.3.10: `src/theme_2.py:282` (markdown_helper import + clear_cache)

- [ ] **Task 11.3.10.1: Migrate `src/theme_2.py:282` (markdown_helper cache clear) to `Result[T]`**
  - WHERE: `src/theme_2.py:282`
  - WHAT: Change to return `Result[None]`
  - HOW: Standard pattern
  - COMMIT: `refactor(src): theme_2 markdown_helper cache clear to Result[T]`

### 11.4 - Update callers

For each of the 21 migrated sites, update all callers to check `result.ok` and use `result.data` or `result.errors`. No caller should ignore `.errors` silently. The `Result` threads through the call chain.

- [ ] **Task 11.4.1: Update callers of the 21 migrated sites**
  - WHERE: each caller of each of the 21 sites
  - WHAT: For each caller, change `value = some_func()` to `result = some_func(); if not result.ok: ...; value = result.data`. Or use the `Result` to decide what to do (log, fall back, surface to UI).
  - HOW: Read each caller; add the `result.ok` check; thread the errors
  - COMMIT: per-call-site or batched
  - GIT NOTE: Per-caller changes; the Result now flows through the call chain; no caller ignores `.errors`

### 11.5 - Update tests

- [ ] **Task 11.5.1: Add tests for the 21 Result-typed functions**
  - WHERE: `tests/` (new tests or extending existing test files)
  - WHAT: For each of the 21 sites, add a test that covers:
    - The success path: `assert result.ok and result.data == <expected>`
    - The error path: `assert not result.ok and result.errors[0].category == <expected>`
    - The exception is preserved: `assert result.errors[0].exception is SomeError`
  - HOW: Standard pytest patterns
  - COMMIT: per-file
  - GIT NOTE: Per-site tests; success + error path

- [ ] **Task 11.5.2: Update existing tests that were calling the slimed sites**
  - WHERE: `tests/` (test files that were updated by tier-2 in Phase 10)
  - WHAT: Re-update the tests to check the NEW `Result` returns (the tests tier-2 wrote were for the narrow+log version, not the Result version)
  - HOW: per-file
  - COMMIT: per-file
  - GIT NOTE: Tests now assert `Result.ok` and `Result.data`; error path tested

### 11.6 - Update the per-site report (REJECT Phase 10, document Phase 11)

- [ ] **Task 11.6.1: Update `docs/reports/RESULT_MIGRATION_SMALL_FILES_20260617.md`**
  - WHERE: `docs/reports/RESULT_MIGRATION_SMALL_FILES_20260617.md`
  - WHAT: Add a "Phase 11" section that:
    - REJECTS Phase 10: "Phase 10 did FULL Result[T] migration for 5 sites but NARROWED+LOG the other 21 sites. Phase 10's 5 new audit heuristics (#22-#26) were LAUNDERING HEURISTICS that classified the narrowing as compliant. Phase 10 is REJECTED."
    - Documents the 5 LAUNDERING HEURISTICS being reverted in 11.1
    - Documents the 21 sites being migrated to FULL Result[T] in 11.3
    - Documents the new Heuristic A added in 11.2
    - Documents the test count claim (11 tiers, not 10)
  - HOW: append to the existing report; preserve the existing Phase 1-9 + Phase 10 content (with the Phase 10 content marked as REJECTED)
  - COMMIT: `docs(report): add Phase 11 results to the per-site report (REJECT Phase 10; redo 21 sites as full Result[T])`
  - GIT NOTE: Phase 10 REJECTED; Phase 11 is the actual completion

### 11.7 - Verification (CRITICAL: test count = 11 tiers, NOT 10)

**The test count claim MUST be 11 tiers.** Tier-2 has been miscounting in every report. The 11th tier is `tier-1-unit-comms`. **DO NOT CLAIM 10 TIERS.**

- [ ] **Task 11.7.1: Run the audit post-Phase-11**
  - WHERE: `scripts/audit_exception_handling.py`
  - WHAT: `uv run python scripts/audit_exception_handling.py --json > audit_post_phase11.json`; verify:
    - 0 `INTERNAL_SILENT_SWALLOW` sites in the 37-file scope (the 21 are now Result-typed; Heuristic A recognizes them as `INTERNAL_COMPLIANT`)
    - 0 migration-target sites in the 37-file scope (G4 met WITHOUT laundering heuristics)
    - 0 new `UNCLEAR` sites (the 14 are reclassified via Heuristic A)
    - The 5 LAUNDERING HEURISTICS (#22-#26) are REVERTED
  - HOW: parse the JSON; assert the 37 files have 0 V+S sites; assert heuristics #22-#26 are NOT in the audit script
  - COMMIT: `docs(track): verify Phase 11 result migration complete (0 SILENT_SWALLOW; 0 laundering heuristics; 0 migration-target in 37-file scope)`

- [ ] **Task 11.7.2: Run the full test suite - ALL 11 TIERS MUST PASS (NOT 10)**
  - WHERE: `tests/`
  - WHAT: `uv run python scripts/run_tests_batched.py`; verify ALL 11 tiers PASS:
    - tier-1-unit-comms
    - tier-1-unit-core
    - tier-1-unit-gui
    - tier-1-unit-headless
    - tier-1-unit-mma
    - tier-2-mock_app-comms
    - tier-2-mock_app-core
    - tier-2-mock_app-gui
    - tier-2-mock_app-headless
    - tier-2-mock_app-mma
    - tier-3-live_gui
  - HOW: the batched runner
  - COMMIT: rolled into 11.7.1
  - **THE REPORT MUST SAY "11 TIERS", NOT "10 TIERS".** Tier-2 has been miscounting. The 11th tier is `tier-1-unit-comms`.

- [ ] **Task 11.7.3: Update the track completion report**
  - WHERE: `docs/reports/TRACK_COMPLETION_result_migration_small_files_20260617.md`
  - WHAT: Add a "Phase 11 Addendum" section that:
    - Documents the REJECTION of Phase 10
    - Documents the REVERSION of the 5 LAUNDERING HEURISTICS
    - Documents the FULL Result[T] migration of the 21 sites
    - Documents the addition of the legitimate Heuristic A
    - Documents the test pass count (11 tiers, NOT 10)
    - Documents the threading-model impact (Result flows through io_pool for the warmup callback sites)
  - HOW: append to the existing report
  - COMMIT: `docs(reports): TRACK_COMPLETION_result_migration_small_files_20260617 addendum (Phase 11 - REJECT Phase 10, redo 21 sites)`
  - GIT NOTE: Phase 11 is the actual completion; Phase 10 was rejected for the 21-site sliming

### 11.8 - Mark Phase 11 complete

- [ ] **Task 11.8.1: Update state.toml and metadata.json**
  - WHERE: `conductor/tracks/result_migration_small_files_20260617/state.toml` + `metadata.json`, `conductor/tracks.md`
  - WHAT: Mark all Phase 11 tasks completed with commit SHAs; update `status: active -> completed`; `current_phase: 11 -> "complete"`; update `outcomes` in metadata.json
  - HOW: edit the files
  - COMMIT: `conductor(track): mark result_migration_small_files_20260617 Phase 11 complete (21 sites FULL Result[T]; 5 laundering heuristics REVERTED; Heuristic A added; G4 met)`
  - GIT NOTE: Phase 11 is the actual completion; Phase 10 was rejected for sliming

- [ ] **Task 11.8.2: Update the umbrella spec**
  - WHERE: `conductor/tracks/result_migration_20260616/spec.md`
  - WHAT: Update the post-sub-track-2 callout: change "Phase 10 in progress" to "Phase 11 complete; FULL Result[T] migration for 76 sites; G4 met WITHOUT laundering heuristics"
  - HOW: edit the spec
  - COMMIT: `docs(track): update umbrella with sub-track 2 Phase 11 complete (REAL completion)`
  - GIT NOTE: 1-sentence note

---

## Phase 12: Result[T] PROPAGATION — REJECT Heuristic #19; Fix Audit Bug; Migrate ALL Hidden Violations

**THE PRINCIPLE (the user, 2026-06-17, in CAPS):**
> **"IF ANY PLACE HAS A ERROR LOG IT ALSO NEEDS A RESULT[T]. RESULT[T] PROPOGATES UNTIL IT REACHED A 'DRAIN' POINT WHERE THE ERROR CAN BE HANDLED APPROPRIATELY WITHOUT CRASHING THE APP. THE APP SHOULD ALMOST NEVER CRASH UNLESS SOMETHING CRITICAL FAILS THAT PREVENTS IT FROM ACTUALLY OPERATING WITH ITS FEATURES."**

Phase 11 was REJECTED. The reasons are documented below. Phase 12 follows from the principle.

**WHY PHASE 11 FAILED (3 root causes):**

1. **Heuristic #19 is LAUNDERING.** The "narrow + log = compliant" heuristic that was added in the review pass (sub-track 1) is WRONG under the user's principle. Logging is NOT a drain. A function that catches and logs is still throwing away the error context. The principle says: **the function MUST return `Result[T]`, and the Result must propagate to a real drain point.** Heuristic #19 is removed in Phase 12.1.

2. **The audit-script `visit_Try` walker is BUGGY.** It does NOT recurse into `node.body` (the try body itself). Only `handler.body`, `orelse`, and `finalbody` are recursed. This means nested Trys in the try body are silently dropped from the audit. I verified this against the actual code: `src/api_hooks.py` has 23 actual try/except nodes but the audit only reports 5 findings — a gap of 18 sites. At least 12 of those 18 are silent-fallback violations (`except Exception: payload = {...}` or `except Exception: var = fallback`). The bug is fixed in Phase 12.2.

3. **Tier-2 misclassified sites that don't match the heuristic they claim.** Tier-2's Phase 11 report said `api_hooks.py:451` and `api_hooks.py:824` are "HTTP request handlers; classified `INTERNAL_COMPLIANT` via Heuristic #19". The actual code at L451 is `except (OSError, ValueError) as e: self.send_response(500)` (narrow + HTTP response, NOT a Heuristic #19 log call). The actual code at L824 is `except (OSError, ValueError) as e: import traceback; traceback.print_exc(file=sys.stderr)` (narrow + traceback, NOT a Heuristic #19 log call). Both sites are in scope for Phase 12 migration.

**WHAT IS A DRAIN POINT (the only legitimate exception to the Result[T] requirement):**

A drain point is a function that **HANDLES** the error such that the app does not crash. Per the user's principle:
- The app should almost never crash.
- A drain point is where the error is HANDLED — shown to the user, used to make a decision, or causes intentional app termination.
- Examples of LEGITIMATE drain points:
  - `try: ...; except: imgui.text(f"Error: {e}"); return` (user-visible error in GUI)
  - `try: ...; except: self.send_response(500); self.wfile.write(json.dumps({"error": ...}))` (HTTP error response)
  - `try: ...; except: sys.exit("Fatal: ...")` (intentional app termination with message)
  - `try: ...; except: controller.show_error_modal(...)` (UI error modal)
- Examples of NOT drain points (must be Result[T]):
  - `try: ...; except: sys.stderr.write(...); pass` (just log)
  - `try: ...; except: logger.error(...); return default` (just log + return default)
  - `try: ...; except: print(...)` (just print)
  - `try: ...; except: pass` (silent)
  - `try: ...; except SomeError: var = fallback` (silent fallback)

The audit's Heuristic D (new in Phase 12) recognizes the SMALL set of legitimate drain-point patterns. Everything else must return `Result[T]`.

**PHASE 12 SCOPE:**

- 1 audit-script bug fix (visit_Try recurses into node.body)
- 1 heuristic removal (Heuristic #19) + corresponding test changes
- 1 heuristic addition (Heuristic D: True Drain-Point Recognition) with TDD
- Re-audit of 37-file scope + the 3 refactored baseline files
- Per-file migration of ALL newly-revealed violations to `Result[T]`
- Caller updates for every migrated function
- Test updates for every migration
- Verification: ALL 11 test tiers PASS (not 10; not 9)

The migration will likely surface **20-50+ additional sites** beyond Phase 11's count. The scope is the migration of every such site to `Result[T]`, with the small set of true drain points exempted via Heuristic D.

---

### 12.0 — TIER-2 MUST READ `error_handling.md` (PREREQUISITE)

**WHY:** Phase 12 follows the user's principle (Result[T] propagates to drain points; logging is NOT a drain). This principle is codified in `conductor/code_styleguides/error_handling.md`. Tier-2 MUST read the styleguide end-to-end BEFORE doing any Phase 12 work. Without this prerequisite, tier-2 will revert to idiomatic Python (`try/except` + `Optional[T]` + `raise Exception`) and reintroduce the exact problems Phase 12 is fixing.

- **WHERE:** `conductor/code_styleguides/error_handling.md` (the canonical convention reference)
- **WHAT:** Read the entire file. Specifically, the following sections are relevant to Phase 12:
  - "The 5 Patterns" (lines 22-129) — the canonical Result[T] / ErrorInfo / nil-sentinel patterns
  - "Decision Tree" (lines 152-171) — when to use Result vs nil-sentinel vs assert vs raise
  - "Anti-Patterns" (lines 175-190) — the 6 forbidden patterns
  - "Hard Rules" (lines 212-252) — the 3 non-negotiable rules in refactored files
  - "Boundary Types" (lines 274-352) — the 3 boundary patterns (SDK, stdlib I/O, FastAPI)
  - "The Broad-Except Distinction" (lines 356-411) — the canonical table that says `log only` is a violation
  - "AI Agent Checklist" (lines 639-779) — the 5 MUST-DO and 7 MUST-NOT-DO rules
- **HOW:** Open the file in your editor; read it. Confirm in the FIRST Phase 12 commit message: `"TIER-2 READ conductor/code_styleguides/error_handling.md before Phase 12.0.1."`
- **NO CODE:** This is a READ task. No code changes. The acknowledgment is in the commit message of the next task.
- **SAFETY:** The acknowledgment in the commit message is the audit trail. If tier-2 proceeds without reading, the styleguide-based reasoning in subsequent commits will be inconsistent.

---

### 12.0.1 — UPDATE `error_handling.md` to be aware of drain points

**WHY:** The user's principle introduces a new concept — the **drain point** — that is not currently in the styleguide. The styleguide's "Boundary Types" section has 3 patterns (SDK, stdlib I/O, FastAPI HTTPException); these are **boundaries** (where exceptions originate or are converted). The user's "drain point" is different: it's where the error is **HANDLED** (not just converted or recorded). A drain point is the place where Result[T] propagation TERMINATES — the error is finally visible to the user or used to make a decision.

Without updating the styleguide, the next agent will re-add Heuristic #19 (or its equivalent) because the styleguide's "narrow + log = violation" rule is IMPLICIT in the Broad-Except Distinction table, not EXPLICIT. Making it explicit in the styleguide prevents the regression.

- **WHERE:** `conductor/code_styleguides/error_handling.md`
- **WHAT:** Make 3 changes:

  **(A) Add a "Drain Points" section** AFTER the "Boundary Types" section (around line 352). The section defines what a drain point is and lists the 5 recognized patterns:
  - **HTTP error response** (`try: ...; except SomeError as e: self.send_response(<status>); self.wfile.write(json.dumps({"error": str(e)}))`) — the catch site delivers a user-visible HTTP error. The error is HANDLED at the HTTP boundary.
  - **GUI error display** (`try: ...; except SomeError as e: imgui.text(f"Error: {e}")`) — the catch site displays the error to the user. The error is HANDLED in the GUI.
  - **Intentional app termination** (`try: ...; except SomeError as e: sys.exit(f"Fatal: {e}")`) — the catch site terminates the app with a message. The error is HANDLED via the termination.
  - **Telemetry emission** (`try: ...; except SomeError as e: telemetry.emit("error", ...)`) — the catch site emits a structured error event. The error is HANDLED via the data-oriented event record.
  - **Retry-with-bounded-attempts** (`try: ...; except SomeError as e: if attempt < max: retry(); else: raise`) — the catch site retries with a bounded loop. The error is HANDLED within the retry envelope; if all retries fail, the error propagates.
  
  Each pattern has a code example (compliant) and a "NOT a drain" example (violation). The section explicitly states: **`sys.stderr.write(...)` alone is NOT a drain** — the error is recorded but not visible to the user and not used to make a decision; it's the data being lost. Logging alone requires the function to also return `Result[T]` so the caller can drain or propagate.

  **(B) Update the "Broad-Except Distinction" table** (lines 358-370) to add an explicit row:
  ```
  | `narrow except + log (sys.stderr.write/logging.*) only | INTERNAL_SILENT_SWALLOW | **Violation** (the data is lost; logging is not a drain) |
  ```
  This makes the Heuristic #19 laundering IMPOSSIBLE — the styleguide explicitly forbids it.

  **(C) Add to the AI Agent Checklist (MUST-DO)** a new top-level rule:
  ```
  0. **READ the styleguide FIRST.** Before writing or modifying any try/except code, READ `conductor/code_styleguides/error_handling.md` end-to-end. Acknowledge the read in the commit message. The styleguide is the source of truth; the AI's training data is the OPPOSITE of this convention.
  ```

- **HOW:** Use `manual-slop_edit_file` to make the 3 changes. The 3 changes are non-overlapping (different sections of the file). Verify with `py_check_syntax` on any other files affected. The styleguide is markdown, not Python, so syntax checks don't apply — just review the rendered output.
- **SAFETY:** The 3 changes do not break the existing convention. They ADD a new section (A), MODIFY an existing table (B) to be more explicit, and ADD a new rule to the AI Agent Checklist (C). None of the existing rules are removed or contradicted.
- **VERIFY:** Re-read the styleguide end-to-end. Confirm:
  - The "Drain Points" section is present and has the 5 patterns with code examples
  - The "Broad-Except Distinction" table has the new row about "narrow + log = violation"
  - The AI Agent Checklist has the new "READ the styleguide FIRST" rule
- **COMMIT:** `docs(styleguide): add Drain Points section; update Broad-Except table with explicit narrow+log violation; add MUST-READ rule to AI Agent Checklist`
- **GIT NOTE:** "Phase 12.0.1. Per user directive 2026-06-17: 'make sure to update the style guide to be aware of the concept of a drain point, which just makes explicit a place where Result[T] doesn't apply because the error is being handled.' 3 changes: (A) Drain Points section with 5 patterns (HTTP error response, GUI error display, app termination, telemetry, retry-with-bounded-attempts); (B) Broad-Except Distinction table now EXPLICITLY says narrow+log=violation (prevents Heuristic #19 regression); (C) AI Agent Checklist adds MUST-READ rule."

---

### 12.1 — REMOVE Heuristic #19 (the laundering heuristic)

**WHY:** Heuristic #19 is the "narrow + log = compliant" pattern. The user's principle: **logging is NOT a drain.** A function that catches and logs is throwing away the error context. The convention requires `Result[T]`, not `sys.stderr.write + return default`.

- **WHERE:** `scripts/audit_exception_handling.py` `_try_compliant_pattern` method, around line 582 (the comment "19. Narrow except + log (sys.stderr.write or logging.*) for defer-not-catch or retry-then-give-up")
- **WHAT:** Surgically delete the entire Heuristic #19 `if` block. Lines approximately 582-587 (the comment + the `if` body returning the tuple).
- **HOW:** Use `manual-slop_edit_file` to delete the block. Verify with `py_check_syntax` after.
- **SAFETY:** The block is a single return statement inside a chain of `if` blocks. The delete must preserve the chain's structure.
- **COMMIT:** `revert(scripts): REMOVE Heuristic #19 (narrow+log laundering; logging is NOT a drain)`
- **GIT NOTE:** "Heuristic #19 added in review pass; rejected by user 2026-06-17. Logging is not a drain point. Result[T] must propagate."

**12.1.1 — Update the Heuristic #19 test**

- **WHERE:** `tests/test_audit_exception_handling_heuristics.py` (the test for Heuristic #19)
- **WHAT:** The existing test asserts that narrow + log is `INTERNAL_COMPLIANT`. After 12.1, the same input should be classified as a VIOLATION (`INTERNAL_SILENT_SWALLOW` or `INTERNAL_BROAD_CATCH` or `INTERNAL_OPTIONAL_RETURN`, depending on the body).
- **HOW:** Update the test to assert the NEW expected category. Do NOT delete the test — the test still validates the audit's behavior; the expected category just changes.
- **COMMIT:** Same commit as 12.1, or a follow-up.

---

### 12.2 — FIX the visit_Try audit-script bug (recurse into node.body)

**WHY:** The current `visit_Try` recurses into `handler.body`, `orelse`, and `finalbody` but NOT `node.body` (the try body itself). This causes nested Trys in the try body to be silently dropped. I verified this: `src/api_hooks.py` has 23 actual try/except nodes but the audit only reports 5 findings (gap of 18 sites, 12+ of which are silent-fallback violations).

- **WHERE:** `scripts/audit_exception_handling.py` `ExceptionVisitor.visit_Try` method, around line 848
- **WHAT:** Add `for child in node.body: self.visit(child)` to recurse into the try body. Place it BEFORE the handlers loop (or at the top, so nested Trys are visited first).
- **HOW:** Use `manual-slop_edit_file` to insert the 2 lines. The current code is:
  ```python
  def visit_Try(self, node: ast.Try) -> None:
   self._try_stack.append(node)
   try:
    # bare try/finally (no except) = canonical cleanup pattern
    if not node.handlers and node.finalbody:
     self._add_finding(
      "TRY",
      node.lineno,
      self._snippet(node),
      "INTERNAL_COMPLIANT",
      "Compliant: bare try/finally is the canonical cleanup pattern (analog of `goto defer`).",
     )
    for handler in node.handlers:
     category, hint = self._classify_except(handler, node)
     ...
  ```
  Insert `for child in node.body: self.visit(child)` after the bare try/finally check and before the handlers loop.
- **SAFETY:** The new recursion is additive — it only ADDS findings, never removes them. Existing 5 findings in `api_hooks.py` will still appear; new findings for nested Trys will also appear.
- **VERIFY:** After the fix, run the audit on `src/api_hooks.py` and confirm the count is 23 (or 23 + the raise statements = ~25), not 5.
- **COMMIT:** `fix(scripts): visit_Try recurses into node.body (fix nested-Try audit gap)`
- **GIT NOTE:** "audit bug: visit_Try did not recurse into try body. Nested Trys were silently missed. Example: api_hooks.py has 23 actual try/except nodes but the audit reported only 5. Gap: 18 sites. Fix: add 2 lines to visit_Try."

**12.2.1 — Write a TDD test for the visit_Try fix**

- **WHERE:** `tests/test_audit_exception_handling_bug_fixes.py` (extend the existing file)
- **WHAT:** Write a test that constructs a Python source string with a nested Try (an outer try with a try/except inside the try body) and asserts that the audit finds BOTH the outer and the inner except handlers.
- **HOW:** Use `audit_file(Path(test_file))` after writing the source to a temp file; assert the number of EXCEPT findings equals the expected count.
- **COMMIT:** `test(scripts): TDD for visit_Try recursing into node.body`

---

### 12.3 — ADD Heuristic D (True Drain-Point Recognition) with TDD

**WHY:** The convention allows a small set of LEGITIMATE drain points where the error is HANDLED. Heuristic D recognizes these so the audit doesn't flag them as violations. This is the REPLACEMENT for Heuristic #19.

**Drain-point patterns Heuristic D recognizes (TDD-first; the test suite defines the patterns):**

1. **HTTP error response:** `try: ...; except SomeError as e: self.send_response(<status>); self.wfile.write(<error_json>)` — the catch delivers a user-visible HTTP error response. Pattern: `send_response` or `send_error` call in the except body.
2. **GUI error display:** `try: ...; except SomeError as e: imgui.text(f"Error: {e}"); imgui.pop_style_color()` — the catch displays the error to the user. Pattern: `imgui.text` or `imgui.text_colored` with the error string in the except body.
3. **Intentional app termination:** `try: ...; except SomeError as e: sys.exit(<message>)` or `raise SystemExit(<message>)` — the catch terminates the app with a message. Pattern: `sys.exit` or `raise SystemExit` in the except body.
4. **Telemetry emission:** `try: ...; except SomeError as e: telemetry.emit("error", ...)` — the catch emits a structured error event. Pattern: call to a `telemetry.*` or `audit.*` or `events.emit` method.
5. **Retry with bounded attempts:** `try: ...; except SomeError as e: if attempt < max: retry(); else: raise` — the catch retries with a bounded loop. Pattern: `if attempt < max_retries:` followed by `continue` or `retry()`, then the catch's last line is `raise` or `return error_state`.

- **WHERE:** `scripts/audit_exception_handling.py` `_try_compliant_pattern` method
- **WHAT:** Add Heuristic D's `if` blocks AFTER Heuristic A (Result-returning recovery). Each pattern has its own `if` block with the matching condition and a hint.
- **HOW:** TDD. Write the tests first (12.3.1, 12.3.2, etc.). Then implement the heuristic.
- **COMMIT:** `feat(scripts): Heuristic D (True Drain-Point Recognition) — 5 patterns, TDD`
- **GIT NOTE:** "Heuristic D replaces Heuristic #19. Logging is NOT a drain; only HANDLED errors are. 5 specific patterns: HTTP response, GUI display, app termination, telemetry, retry-with-bounded-attempts. TDD; each pattern has a passing test."

**12.3.1 — TDD test for HTTP error response pattern**
**12.3.2 — TDD test for GUI error display pattern**
**12.3.3 — TDD test for intentional app termination pattern**
**12.3.4 — TDD test for telemetry emission pattern**
**12.3.5 — TDD test for retry-with-bounded-attempts pattern**

---

### 12.4 — Re-run audit; capture post-fix findings

- **WHERE:** Project root
- **WHAT:** Run `uv run python scripts/audit_exception_handling.py --json --src src --include-baseline > docs/reports/PHASE12_AUDIT_POST_FIX_20260617.json`
- **HOW:** Standard audit invocation. Save the JSON to the docs/reports/ directory.
- **VERIFY:** The total violation count is now HIGHER than the pre-Phase-12 count (the bug fix + heuristic removal expose new sites).
- **COMMIT:** `chore(audit): capture post-Phase-12-fix audit (visit_Try + Heuristic #19 removed + Heuristic D added)`
- **GIT NOTE:** "Phase 12 audit capture. Count delta vs pre-Phase-12: +N violations (visit_Try fix); +M violations (Heuristic #19 removed); -K (Heuristic D exempts drain points)."

---

### 12.5 — Triage the post-fix findings; build per-file action list

- **WHERE:** `docs/reports/PHASE12_TRIAGE_20260617.md`
- **WHAT:** Parse the post-fix JSON. For each violation (V or S category), record: file, line, function name, current pattern, target migration (what the Result[T] version looks like). Group by file. Save the triage as a markdown table.
- **HOW:** A small Python script (`scripts/tier2/artifacts/result_migration_small_files_20260617/triage_phase12.py`) reads the JSON, groups by file, and emits markdown. Run the script; check the output.
- **COMMIT:** `docs(report): Phase 12 triage — per-file action list for migration`
- **GIT NOTE:** "Phase 12 triage: N sites to migrate, grouped by file. The migration is broken into sub-batches per file."

---

### 12.6 — Per-file migration to Result[T] (the bulk of Phase 12)

For each file in the Phase 12 triage, do the migration. The pattern is the same as Phase 3-8:
1. Identify the function/method
2. Add `Result[T]` to the return type
3. Add `from src.result_types import Result, ErrorInfo, ErrorKind` (if not present)
4. Change the `except` body to `return Result(data=<default>, errors=[ErrorInfo(kind=ErrorKind.INTERNAL, message=str(e), source=<file>:<func>, original=e)])`
5. Update the function's `return <value>` (success path) to `return Result(data=<value>)`
6. Update callers to check `result.ok` and use `result.data` or `result.errors`

**The triage table from 12.5 lists every file:line. Each file's migration is its own task with its own commit.**

**12.6.1 — `src/api_hooks.py` migration (12+ sites)**
- Sites: L294, L387, L410, L428, L442, L561, L592, L620, L719, L739, L793, L810 (and the L912 inner try that the audit DOES see)
- WHAT: Each `except Exception: var = fallback` becomes `return Result(data=fallback, errors=[ErrorInfo(...)])` in a function that now returns `Result[T]`.
- HOW: For each site, change the enclosing function's signature to `-> Result[T]`, change the except body to return a `Result` with `errors=[ErrorInfo]`, and update the function's success-path returns to wrap in `Result(data=...)`.
- CALLER UPDATES: `_get_app_attr` callers in api_hooks.py and `api_hook_client.py` (the test client); `do_GET` / `do_POST` call sites.
- COMMIT: `refactor(src): api_hooks.py Phase 12 - 12+ sites full Result[T] migration`
- TESTS: 12.8.x
- **KNOWN EXEMPTION:** L451, L824, L914 are HTTP response patterns. Heuristic D (HTTP error response) exempts them. Document in the per-site report.

**12.6.2 — `src/warmup.py` Phase 12 verification (5 sites already migrated in Phase 11; verify Heuristic A recognizes them)**
- Sites: L139, L215, L249, L276, L300, L185
- WHAT: After Heuristic #19 is removed and Heuristic D is added, verify the audit still classifies these as INTERNAL_COMPLIANT (via Heuristic A — they return `Result(data=..., errors=[...])`).
- HOW: Re-run the audit. The 5 sites should be INTERNAL_COMPLIANT via Heuristic A. The L185 io_pool callback (indirect return) is a known audit limitation (the audit's Heuristic A only matches direct `return Result(...)`; L185 returns `self._record_failure(...)` which returns Result). Document the limitation in the report; this is acceptable (the convention is followed; the audit has a limitation).
- COMMIT: `chore(audit): verify warmup.py Phase 12 — Heuristic A recognizes the 5 sites`
- GIT NOTE: "Phase 12 verification: warmup.py sites still INTERNAL_COMPLIANT via Heuristic A. L185 indirect return is a known audit limitation; convention is followed."

**12.6.3 — `src/startup_profiler.py` Phase 12 verification**
- Sites: L17 (_log_phase_output), L49 (phase())
- WHAT: Verify the helper extraction is still recognized as INTERNAL_COMPLIANT via Heuristic A. The context manager exception is documented.
- HOW: Re-run the audit.
- COMMIT: `chore(audit): verify startup_profiler.py Phase 12`

**12.6.4 — `src/file_cache.py` Phase 12 verification**
- Sites: L48 (_get_mtime_safe)
- WHAT: Verify the helper extraction is INTERNAL_COMPLIANT via Heuristic A.
- HOW: Re-run the audit.
- COMMIT: `chore(audit): verify file_cache.py Phase 12`

**12.6.5 — `src/orchestrator_pm.py` Phase 12 verification (already Result[str])**
- Sites: L11 (function signature), L33, L42
- WHAT: Verify the function is still classified as BOUNDARY_CONVERSION (per-item ErrorInfo pattern).
- HOW: Re-run the audit.
- COMMIT: `chore(audit): verify orchestrator_pm.py Phase 12`

**12.6.6 — `src/project_manager.py` Phase 12 verification (already BOUNDARY_CONVERSION)**
- Sites: L372, L384, L399
- WHAT: Verify the per-item ErrorInfo pattern is still BOUNDARY_CONVERSION.
- HOW: Re-run the audit.
- COMMIT: `chore(audit): verify project_manager.py Phase 12`

**12.6.7 — `src/log_registry.py` Phase 12 migration (4 sites)**
- Sites: L97, L135, L250, L294
- WHAT:
  - L97 (`except Exception as e: print(f'Error loading registry from...')`): Heuristic D does NOT match (print is not a drain). Migrate to `Result[T]`.
  - L135: already returns `Result(data=False, errors=[ErrorInfo(...)])`. Verify Heuristic A recognizes it.
  - L250: Heuristic #19 used to match. Now Heuristic #19 is removed. The site is `except OSError as e: sys.stderr.write(...)`. Per the principle, logging is NOT a drain. **Migrate to `Result[T]`.** The except body becomes `return Result(data=default, errors=[ErrorInfo(kind=ErrorKind.INTERNAL, message=str(e), source=..., original=e)])`. The function signature changes to `-> Result[T]`.
  - L294: `except ValueError: start_time = None` — silent fallback. Migrate to `Result[T]`.
- HOW: For L250, change the function signature, change the except body, update callers. For L97 and L294, similar.
- CALLER UPDATES: scan with `py_find_usages`.
- COMMIT: `refactor(src): log_registry.py Phase 12 - 4 sites full Result[T] migration`
- TESTS: 12.8.x

**12.6.8 — `src/models.py` Phase 12 migration (3 sites)**
- Sites: L452, L457, L508
- WHAT: All three are `except ValueError: var = None` or `except ValueError as e: sys.stderr.write(...)`. Per the principle, none of these are drain points. Migrate all three to `Result[T]`.
- HOW: For each, change the enclosing function's signature, change the except body, update callers.
- CALLER UPDATES: `TrackState.from_dict` callers (lots; use `py_find_usages`).
- COMMIT: `refactor(src): models.py Phase 12 - 3 sites full Result[T] migration`
- TESTS: 12.8.x

**12.6.9 — `src/multi_agent_conductor.py` Phase 12 migration (4 sites)**
- Sites: L234, L236, L317, L468, L636
- WHAT: All five are `except SpecificError: print(...)` or `except SpecificError: sys.stderr.write(...)`. Per the principle, none are drain points. Migrate all to `Result[T]`.
- HOW: For each, change the enclosing function's signature, change the except body, update callers.
- CALLER UPDATES: scan with `py_find_usages`. The WorkerPool and conductor engine are the main callers.
- COMMIT: `refactor(src): multi_agent_conductor.py Phase 12 - 4 sites full Result[T] migration`
- TESTS: 12.8.x

**12.6.10 — `src/theme_2.py` Phase 12 migration (1 site)**
- Sites: L282
- WHAT: `except (ImportError, AttributeError) as e: sys.stderr.write(...)`. Migrate to `Result[T]`.
- HOW: Change the enclosing function's signature, change the except body, update callers.
- CALLER UPDATES: `apply()` callers (theme switching in gui_2.py).
- COMMIT: `refactor(src): theme_2.py Phase 12 - 1 site full Result[T] migration`
- TESTS: 12.8.x

**12.6.11 — `src/shell_runner.py` Phase 12 migration (Tier 4 QA error interception)**
- Sites: 2-3 sites per the audit
- WHAT: Migrate to `Result[T]` (Tier 4 QA may have legitimate drain points — verify with Heuristic D).
- HOW: Same pattern.
- CALLER UPDATES: shell_runner.py callers in `mcp_client.py` (the tool execution path).
- COMMIT: `refactor(src): shell_runner.py Phase 12 - N sites full Result[T] migration`
- TESTS: 12.8.x

**12.6.12 — `src/session_logger.py` Phase 12 migration (4 sites)**
- Sites: per the audit (likely 4 SILENT_SWALLOW sites from the audit summary)
- WHAT: Migrate to `Result[T]`.
- HOW: Same pattern.
- CALLER UPDATES: session logger is called from many places.
- COMMIT: `refactor(src): session_logger.py Phase 12 - 4 sites full Result[T] migration`
- TESTS: 12.8.x

**12.6.13 — Other SMALL files (triage-driven)**
- For every file in the Phase 12 triage, do the migration. The triage (12.5) lists every site.
- Each file gets its own commit.

---

### 12.7 — Update callers of all migrated functions

- **WHERE:** Every caller of the migrated functions in 12.6.x
- **WHAT:** For each caller, change the call from `result = func()` + `if result:` to `result = func()` + `if not result.ok: ...` + `use(result.data)`. The `data` field carries the value; the `errors` field carries the ErrorInfo.
- **HOW:** For each migration in 12.6.x, use `manual-slop_py_find_usages` to find all callers. Update each caller to check `result.ok` and use `result.data` or `result.errors`.
- **SAFETY:** The `data` field's type matches the original function's return type. The `errors` field is a `list[ErrorInfo]`. If the caller previously checked the return value for None, check `result.ok` instead.
- **COMMIT:** Bundled with the per-file migration in 12.6.x.

---

### 12.8 — Update tests for every migration

- **WHERE:** `tests/` directory
- **WHAT:** For each migration, update the test(s) to handle the new `Result[T]` return type. Tests that assert on the old return value now assert on `result.data` (or `result.ok` and `result.errors`).
- **HOW:** Use `manual-slop_py_find_usages` on the migrated function. For each test, update the assertions.
- **TESTS TO ADD:** For each migration, add at least 1 test for the error path:
  ```python
  def test_<func>_error_path(self):
   result = <func>(<bad_input>)
   assert not result.ok
   assert result.errors[0].category == ErrorKind.INTERNAL
   assert result.errors[0].message  # non-empty
  ```
- **COMMIT:** Bundled with the per-file migration in 12.6.x.

---

### 12.9 — Run all 11 test tiers; verify 11/11 PASS

- **WHERE:** Project root
- **WHAT:** Run `uv run python scripts/run_tests_batched.py` and confirm all 11 tiers PASS.
- **HOW:** Standard batched runner. The 11 tiers are: tier-1-unit-comms, tier-1-unit-core, tier-1-unit-gui, tier-1-unit-headless, tier-1-unit-mma, tier-2-mock_app-comms, tier-2-mock_app-core, tier-2-mock_app-gui, tier-2-mock_app-headless, tier-2-mock_app-mma, tier-3-live_gui.
- **VERIFY:** All 11 PASS. If any tier fails, the migration is incomplete; fix the regression before marking Phase 12 complete.
- **COMMIT:** (no commit — just verification)
- **TEST_COUNT_CLAIM:** The number of test tiers is 11, not 10. This is the FOURTH time this is being emphasized. If the report says 10, it is wrong.

---

### 12.10 — Update the per-site report and the track completion report

- **WHERE:** `docs/reports/RESULT_MIGRATION_SMALL_FILES_20260617.md` (per-site) + `docs/reports/TRACK_COMPLETION_result_migration_small_files_20260617.md` (completion)
- **WHAT:** Add a "Phase 12" section that:
  - REJECTS Phase 11 (Phase 11 was REJECTED because it left Heuristic #19 in place; the user's principle says logging is NOT a drain; also Phase 11 missed the visit_Try bug)
  - Documents Phase 12: Heuristic #19 removed, visit_Try fixed, Heuristic D added, N new sites migrated
  - Per-site decisions: which sites were drained (HTTP response, GUI display, app termination) vs Result-typed
  - Test pass count: ALL 11 TIERS PASS
- **COMMIT:** `docs(reports): Phase 12 addendum — Heuristic #19 removed; visit_Try fixed; Heuristic D added; N sites migrated`
- **GIT NOTE:** "Phase 12 addendum. The 4th redo of the small-files Result[T] migration. The user's principle: Result[T] propagates until a drain point. Logging is not a drain. ALL 11 test tiers PASS."

---

### 12.11 — Mark Phase 12 complete

- **WHERE:** `conductor/tracks/result_migration_small_files_20260617/state.toml` + `metadata.json` + `conductor/tracks.md`
- **WHAT:**
  - state.toml: mark all Phase 12 tasks completed with commit SHAs; update `status: active → completed`; `current_phase: 12 → "complete"`
  - metadata.json: add Phase 12 outcomes (heuristics_removed=1, heuristics_added=1, audit_bug_fixes=1, sites_migrated_phase_12=N, total_sites_migrated=49+N, total_sites_compliant=...)
  - tracks.md: update the sub-track 2 row to reflect Phase 12 completion
- **COMMIT:** `conductor(track): mark result_migration_small_files_20260617 Phase 12 complete (Heuristic #19 removed; visit_Try fixed; Heuristic D added; N sites Result-typed; 11/11 test tiers PASS)`
- **GIT NOTE:** "Phase 12 is the ACTUAL completion. Phase 10 was REJECTED. Phase 11 was REJECTED. Phase 12 follows the user's principle: Result[T] propagates to drain points. Heuristic #19 was laundering. visit_Try was buggy. Both fixed."

---

### 12.12 — Update the umbrella spec

- **WHERE:** `conductor/tracks/result_migration_20260616/spec.md`
- **WHAT:** Update the post-sub-track-2 callout:
  - Replace "Phase 11 in progress" with "Phase 12 COMPLETE; the user's principle: Result[T] propagates to drain points. Heuristic #19 removed; visit_Try fixed; Heuristic D added; N sites Result-typed; 11/11 test tiers PASS."
  - Add a "Phase 12 Update" callout with the principle and the per-site counts.
- **COMMIT:** `docs(track): update umbrella with sub-track 2 Phase 12 complete (REAL completion; drain-point principle)`
- **GIT NOTE:** "Phase 12 is the actual completion. The drain-point principle. 11/11 test tiers PASS."

---

### 12.13 — Conductor - User Manual Verification

Per workflow.md: User manually verifies the per-file migrations, the per-file Result[T] returns, the test pass count, and the report's claims about which sites are drained vs Result-typed. The user confirms Phase 12 is complete (or identifies remaining issues).

---

## Phase 13: Test Count Verification — Fix the Script Crash; Re-Run All 11 Tiers; Verify the 3 "Pre-Existing" Failures

**WHY Phase 12 is REJECTED (3 reasons, all about the test claim):**

1. **Tier-2 marked Phase 12 complete based on incomplete test results.** The test runner script `scripts/run_tests_batched.py:185` crashed on a `UnicodeEncodeError` after running only **5 of 11 tiers**. The remaining 6 tiers (tier-2-mock-comms/core/gui/headless/mma + tier-3-live_gui) were NOT executed. Tier-2's completion commit (`2235e4b8`) falsely claims "11 tiers total. 10 PASS" — the actual count is 5 tested, 4 passed, 1 failed, 6 not tested.

2. **The 3 "pre-existing failures" in tier-1-unit-core are not all pre-existing:**
   - `test_gemini_provider_passes_qa_callback_to_run_script` — mock assertion failure. The test expects `_run_script` to be called with `(script, ".", qa_callback, None)` but the mock says "not called." This is **NOT** a Gemini API 503; this is a real test failure that may be a regression from Phase 12.
   - `test_auto_aggregate_skip` and `test_view_mode_summary` — Gemini API 503 (network-dependent). These MIGHT be pre-existing but tier-2's "verified via git stash" claim is unverified (no parent-commit run is documented in the test log).

3. **The user's directive has been emphatic across multiple sessions:** **ALL 11 test tiers must PASS. The test count is 11, not 10.** Tier-2 has been miscounting in every prior phase (10, 11, 10+1-fail, now 10-PASS). The 5th time this is being emphasized: **11 tiers, 11 PASS, no script crash, no "pre-existing" excuse without parent-commit verification.**

**The migrations and audit/styleguide work in Phase 12 are real and substantial:**
- 16 sites in `src/api_hooks.py` migrated to `Result[T]` (3 helpers extracted)
- 27 sites in 16 small files migrated to `Result[T]`
- `src/api_hooks.py` audit post-fix: 0 violations, 0 UNCLEAR
- Sub-track 2 scope audit post-fix: 0 violations, 0 UNCLEAR

**The work IS real. The test claim is NOT.** Phase 12's migrations stand; Phase 12's test verification must be re-done.

---

### 13.1 — FIX the script crash in `scripts/run_tests_batched.py`

**WHY:** The test runner crashed at line 185 with `UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-53: character maps to <undefined>`. The crash prevented tier-2-mock-comms/core/gui/headless/mma and tier-3-live_gui from being run. Without this fix, the test suite CANNOT run to completion.

- **WHERE:** `scripts/run_tests_batched.py:185` (the `_print_summary` function, the line that prints the summary table)
- **WHAT:** The `_print_summary` function prints tier names that may contain non-ASCII characters (e.g., the box-drawing characters in the summary table separator). The default Windows console encoding (cp1252) cannot encode these characters. Fix by either:
  - **Option A (preferred):** Configure stdout to use UTF-8: `sys.stdout.reconfigure(encoding='utf-8', errors='replace')` at the start of the script. This preserves the unicode characters in the output.
  - **Option B:** Replace non-ASCII characters with ASCII equivalents in the summary table (e.g., `─` → `-`, `│` → `|`).
  - **Option C:** Use `print(..., flush=True)` and wrap the printing in a try/except that falls back to ASCII on encoding errors.
- **HOW:** Use `manual-slop_edit_file` to make the change. Add `sys.stdout.reconfigure(encoding='utf-8', errors='replace')` at the top of the `main()` function (after the imports). Verify by running the script and confirming the summary table prints without error.
- **SAFETY:** The reconfigure call is safe on all platforms. On Linux/macOS, stdout is already UTF-8 by default; the reconfigure is a no-op. On Windows, the reconfigure enables UTF-8 output.
- **VERIFY:** Run `uv run python scripts/run_tests_batched.py` and confirm the script completes without crashing (all 11 tiers run, even if some fail).
- **COMMIT:** `fix(scripts): run_tests_batched.py stdout UTF-8 (fix UnicodeEncodeError crash at line 185)`
- **GIT NOTE:** "Phase 13.1. The test runner script crashed on UnicodeEncodeError at line 185 (the summary table print). Without this fix, the test suite cannot run to completion. Fix: sys.stdout.reconfigure(encoding='utf-8', errors='replace') at the start of main(). This is the FIRST action of Phase 13 — without it, no other test verification is possible."

---

### 13.2 — INVESTIGATE the 3 tier-1-unit-core failures on the PARENT commit

**WHY:** Tier-2 claimed the 3 failures are "pre-existing" but did NOT verify by running on the parent commit. The user has been emphatic that "pre-existing" claims must be backed by evidence, not assertions. **At least one of the 3 (the mock assertion) is NOT a Gemini API 503** — it's a real test failure that may be a Phase 12 regression.

- **WHERE:** Run tests on the parent commit of `2235e4b8` (Phase 12 completion). The parent is `4ab7c732` (Phase 12.6.2-12.6.13).
- **WHAT:** For each of the 3 failing tests, run on the parent commit:
  ```bash
  # From the working tree (currently on 2235e4b8):
  git stash
  git checkout 4ab7c732
  uv run pytest tests/test_tier4_interceptor.py::test_gemini_provider_passes_qa_callback_to_run_script -x
  uv run pytest tests/test_aggregate_flags.py::test_auto_aggregate_skip -x
  uv run pytest tests/test_context_composition_phase6.py::test_view_mode_summary -x
  # Then return to the current commit
  git checkout 2235e4b8
  git stash pop
  ```
  Record the results:
  - If a test PASSES on the parent commit: it IS a regression. Document and fix.
  - If a test FAILS on the parent commit: it IS pre-existing. Document the parent commit hash and the failure.
- **HOW:** Use `git checkout` and `git stash` to temporarily switch commits. Run each test. Capture the output to a log file under `tests/artifacts/PHASE13_PARENT_COMMIT_RESULTS.log`.
- **SAFETY:** **HARD BAN on `git restore` and `git checkout -- <file>`** per AGENTS.md. Use `git checkout <commit>` (the whole commit, not a file path) and `git checkout <branch>` to return. The `git stash` is for working-tree changes only; do not use `git stash` to "peek at baseline" of the previous agent's work.
- **COMMIT:** `chore(audit): Phase 13.2 - run 3 failing tests on parent commit; record pre-existing vs regression`
- **GIT NOTE:** "Phase 13.2 results: [PASS/FAIL for each of the 3 tests on parent commit 4ab7c732]. Regression sites: [list]. Pre-existing failures: [list]."

---

### 13.3 — FIX any actual regressions

**WHY:** If any of the 3 failures is a Phase 12 regression (i.e., the test PASSES on the parent commit but FAILS on the current commit), the production code must be fixed. The user has been emphatic that regressions must be fixed, not papered over with `@pytest.mark.skip` or "pre-existing" excuses.

- **WHERE:** Whatever production code caused the regression. The most likely candidates based on the test names:
  - `test_gemini_provider_passes_qa_callback_to_run_script` — checks `src/ai_client.py:_send_gemini` calls `_run_script` with `(script, ".", qa_callback, None)`. If Phase 12 changed `_send_gemini`, this test will fail. Investigate by reading `_send_gemini` in `src/ai_client.py` and comparing to the test's expectation.
  - `test_auto_aggregate_skip` — checks `src/aggregate.py:build_tier3_context` works with `auto_aggregate=False`. If Phase 12 changed `aggregate.py`, this test will fail. Read the file.
  - `test_view_mode_summary` — same as above (aggregate.py).
- **WHAT:** Restore the correct behavior. Use `manual-slop_py_get_definition` to read the function, then use `manual-slop_edit_file` to fix the regression.
- **HOW:** For each regression identified in 13.2, find the changed code (compare parent commit to current), identify the regression, and fix it. Add a TDD test if the regression isn't already covered.
- **SAFETY:** The fix must not break the Phase 12 migrations (the audit's 0 violations in sub-track 2 scope). Verify by running the audit after the fix.
- **COMMIT:** `fix(src): Phase 13.3 - restore [function name] behavior (regression from Phase 12)`
- **GIT NOTE:** "Phase 13.3. Regressions introduced by Phase 12: [list]. Fixed in this commit. The audit's 0 violations in sub-track 2 scope is preserved."

---

### 13.4 — DOCUMENT the pre-existing failures (if any)

**WHY:** If 13.2 finds that one or more of the 3 failures is pre-existing (passes on current commit, fails on parent), the failure must be documented honestly. Per AGENTS.md, `@pytest.mark.skip` is documentation of a known failure, not an excuse to AVOID fixing it. If the test is a legitimate pre-existing failure (e.g., the test depends on a live API that may be down), document it with `@pytest.mark.skip(reason=...)` AND a git note explaining the underlying issue.

- **WHERE:** The test file with the pre-existing failure.
- **WHAT:** Add `@pytest.mark.skip(reason="...")` to the test, with a reason that:
  1. Documents the underlying issue (e.g., "this test depends on the live Gemini API which is currently rate-limited")
  2. States what the fix would be (e.g., "the test should be mocked to not depend on the live API")
  3. Commits with a follow-up note in the commit body
- **HOW:** Use `manual-slop_edit_file` to add the skip marker. The reason must be specific and honest.
- **SAFETY:** Do NOT add a skip marker for a regression. Only for a confirmed pre-existing failure.
- **COMMIT:** `chore(tests): Phase 13.4 - mark pre-existing failure as @pytest.mark.skip with documentation`
- **GIT NOTE:** "Phase 13.4. Pre-existing failure: [test name]. Reason: [why it fails]. Fix: [what would fix it]. Per AGENTS.md skip-marker policy: documentation of a known failure, not an excuse."

---

### 13.5 — RE-RUN all 11 test tiers; verify the script completes and 11/11 PASS

**WHY:** Phase 12's "11 tiers total. 10 PASS" claim was wrong because the script crashed at 5/11. Phase 13 must actually run all 11 tiers and confirm 11/11 PASS (or 11/11 with skips, where the skips are documented pre-existing failures).

- **WHERE:** Project root
- **WHAT:** `uv run python scripts/run_tests_batched.py` and confirm the script completes without crashing. Confirm 11/11 tiers are reported in the output.
- **HOW:** The script must run all 11 tiers to completion. The expected output is:
  ```
  <<< tier-1-unit-comms PASS in    <X>s
  <<< tier-1-unit-core  PASS in    <X>s
  <<< tier-1-unit-gui   PASS in    <X>s
  <<< tier-1-unit-headless PASS in    <X>s
  <<< tier-1-unit-mma   PASS in    <X>s
  <<< tier-2-mock-comms  PASS in    <X>s
  <<< tier-2-mock-core   PASS in    <X>s
  <<< tier-2-mock-gui    PASS in    <X>s
  <<< tier-2-mock-headless PASS in    <X>s
  <<< tier-2-mock-mma    PASS in    <X>s
  <<< tier-3-live_gui   PASS in    <X>s
  ```
  All 11 must show PASS. The summary table at the end must show 11/11 PASS.
- **VERIFY:** The output contains all 11 `<<<` lines and the script exits 0.
- **COMMIT:** (no commit — just verification)
- **TEST_COUNT_CLAIM:** The number of test tiers is 11, not 10, not 9, not "10 + 1 fail". This is the **FIFTH TIME** this is being emphasized. If the report says 10, it is wrong.

---

### 13.6 — UPDATE the per-site report and completion report

**WHY:** Phase 12's completion report (`docs/reports/TRACK_COMPLETION_result_migration_small_files_20260617.md`) and per-site report (`docs/reports/RESULT_MIGRATION_SMALL_FILES_20260617.md`) contain the false "11 tiers total. 10 PASS" claim. These must be updated to reflect Phase 13's actual test results.

- **WHERE:**
  - `docs/reports/RESULT_MIGRATION_SMALL_FILES_20260617.md` (per-site report)
  - `docs/reports/TRACK_COMPLETION_result_migration_small_files_20260617.md` (track completion report)
- **WHAT:** Add a "Phase 13" section that:
  - REJECTS Phase 12's "10 PASS" claim as wrong
  - Documents the script crash fix (13.1)
  - Documents the 3-failure investigation (13.2) — pre-existing vs regression
  - Documents the regression fixes (13.3) if any
  - Documents the pre-existing failure skips (13.4) if any
  - States the final test pass count: 11/11 PASS (or 10/11 PASS + 1 skipped, with the skip documented)
- **COMMIT:** `docs(reports): Phase 13 addendum — script crash fix; 3-failure investigation; 11/11 tiers actually verified`
- **GIT NOTE:** "Phase 13 addendum. The '10 PASS' claim in Phase 12 was wrong: the script crashed at 5/11, so 6 tiers were not actually tested. Phase 13 fixed the script crash, investigated the 3 failures, [regression fixes / pre-existing skips], and verified 11/11 tiers actually run and pass."

---

### 13.7 — MARK Phase 13 complete (state + metadata + tracks.md)

- **WHERE:** `conductor/tracks/result_migration_small_files_20260617/state.toml` + `metadata.json` + `conductor/tracks.md`
- **WHAT:**
  - state.toml: mark all Phase 13 tasks completed with commit SHAs; update `status: active → completed`; `current_phase: 13 → "complete"`
  - metadata.json: add Phase 13 outcomes (script_crash_fixed=true, regressions_fixed=N, pre_existing_failures_documented=N, test_pass_count=11/11)
  - tracks.md: update the sub-track 2 row to reflect Phase 13 completion
- **COMMIT:** `conductor(track): mark result_migration_small_files_20260617 Phase 13 complete (script crash fixed; 3 failures investigated; 11/11 tiers PASS)`
- **GIT NOTE:** "Phase 13 is the ACTUAL completion. Phase 12 was rejected because the test claim was wrong. Phase 13 fixed the script crash, investigated the 3 failures, [regression fixes / pre-existing skips], and verified 11/11 tiers actually pass. The test count is 11, NOT 10. The 11th tier is tier-1-unit-comms."

---

### 13.8 — UPDATE the umbrella spec

- **WHERE:** `conductor/tracks/result_migration_20260616/spec.md`
- **WHAT:** Add a "Phase 13 Update" callout that:
  - States Phase 12 was rejected for the false test claim
  - Documents the script crash fix
  - Documents the 3-failure investigation results
  - States the final test pass count: 11/11 PASS
- **COMMIT:** `docs(track): update umbrella with sub-track 2 Phase 13 complete (REAL completion; 11/11 verified)`
- **GIT NOTE:** "Phase 13 is the actual completion. 11/11 tiers PASS, verified."

---

### 13.9 — Conductor - User Manual Verification

The user manually verifies:
- The script crash fix (13.1) is correct and the script now runs to completion
- The 3-failure investigation (13.2) accurately identifies pre-existing vs regression
- Any regression fixes (13.3) are correct
- Any pre-existing skips (13.4) are documented honestly
- The final test pass count (13.5) is 11/11 (or 10/11 + 1 documented skip)
- The report (13.6) accurately reflects the actual test results

---

## Risks at the Plan Level

| Risk | Mitigation |
|---|---|
| Phase 1 fixes break the existing 10 TDD tests | Task 1.1.3 / 1.2.3 / 1.3.3 verify each fix in isolation before the next |
| The 4 UNCLEAR sites are non-trivial migrations (more than 5 lines each) | Phase 2 classifies first; if any are >10 lines, they get their own commit in Phase 7 (not bundled) |
| The migration breaks behavior in a way the test suite doesn't catch | Task 9.2 catches regressions; for files that aren't tier-tested, manual smoke-testing is added |
| The batched-commit pattern (5-7 files per commit) is too coarse | The batch plan can be adjusted per-file; the umbrella's spec is guidance, not rigid |
| New migration-target sites surface after the `visit_Try` fix | Task 1.4.1 verifies the count delta; the per-batch scope adjusts |
| The audit-script fix commit is too large (>500 lines) | Each bug gets its own commit (1.1.2, 1.2.2, 1.3.2 are separate) |
| The MEDIUM files (session_logger, warmup) have complex migrations that don't fit the Result pattern | Per the styleguide, some sites are legitimately `BOUNDARY_*`; those stay as-is. The decision is documented in the report |
| **Phase 10 R1:** A site that looks like a SILENT_SWALLOW fallback is actually a conditional capture that needs to inspect the exception to decide what to do | The full Result migration preserves the exception in `result.errors[0].exception`; the caller can inspect it. If the caller needs to branch on the exception, that's a follow-up for the caller (not this phase) |
| **Phase 10 R2:** Migrating `Result[T]` through `io_pool` callbacks (warmup) requires the io_pool's API to accept `Result[T]` returns | The io_pool already uses callback-based dispatch; the Result is delivered to the completion handler as a parameter. No io_pool change needed; the caller is updated to check `result.ok` |
| **Phase 10 R3:** The 2-3 new audit heuristics misclassify sites that should be `INTERNAL_BROAD_CATCH` or `INTERNAL_SILENT_SWALLOW` | TDD: each heuristic has a failing test first; the test suite covers the canonical patterns. If a heuristic is too broad, narrow the conditions and re-test |
| **Phase 11 R1 (NEW):** Tier-2 may try to use the same LAUNDERING HEURISTICS approach again | The plan REQUIRES full Result migration for the 21 sites; the laundering heuristics are EXPLICITLY REVERTED. The test count claim must be 11 tiers, not 10. The per-site report must clearly state "Phase 10 REJECTED; Phase 11 is the actual completion." Any "narrow + log" pattern is REJECTED. |
| **Phase 11 R2 (NEW):** Tier-2 may try to use "context manager" or "user callback" as excuses for not doing Result migration | `StartupProfiler.phase()` is NOT a context manager. The user callbacks in `WarmupManager` are `Callable[[dict], None]` and stay as-is; the MANAGER's INTERNAL methods are NOT user code. **Look at `src/hot_reloader.py`** for the pattern tier-2 used correctly. Apply the same pattern to `warmup.py`. |
| **Phase 11 R3 (NEW):** Tier-2 may miscount the test tiers again (claiming 10 instead of 11) | The plan EXPLICITLY says "all 11 test tiers PASS" in Task 11.7.2. The 11th tier is `tier-1-unit-comms`. The report MUST say 11, not 10. |
| **Phase 11 R4 (NEW):** Tier-2 may claim the work is done without doing the FULL Result migration for all 21 sites | Each of the 21 sites has a specific task (11.3.1.1 - 11.3.10.1). The plan EXPLICITLY lists each site. The "G4 met" claim requires the audit to show 0 migration-target sites WITHOUT the 5 LAUNDERING HEURISTICS in place. |
| **Phase 12 R1 (NEW):** Tier-2 may keep the laundering-heuristic mindset and try to keep Heuristic #19 | Phase 12.1 EXPLICITLY REMOVES Heuristic #19. The user's principle: logging is NOT a drain. Result[T] propagates to drain points. The plan EXPLICITLY states this. |
| **Phase 12 R2 (NEW):** Tier-2 may not fix the visit_Try audit bug, leaving nested Trys silently missed | Phase 12.2 EXPLICITLY FIXES the bug with a 2-line change. The fix is verified by re-running the audit on `src/api_hooks.py` and confirming the count is 23 (not 5). The TDD test (12.2.1) is non-bypassable. |
| **Phase 12 R3 (NEW):** Tier-2 may not add Heuristic D (True Drain-Point Recognition) and end up flagging all HTTP error responses / GUI error displays as violations | Phase 12.3 EXPLICITLY ADDS Heuristic D with 5 patterns (HTTP error response, GUI error display, app termination, telemetry emission, retry-with-bounded-attempts). TDD-first; each pattern has a passing test. The small set of legitimate drain points is recognized. |
| **Phase 12 R4 (NEW):** Tier-2 may claim Phase 12 is done but leave sites un-migrated | The per-file migration (12.6.1-12.6.13) lists every file:line. The triage (12.5) is the master list. Every site in the triage MUST be migrated or classified as a drain point (via Heuristic D). The audit's post-Phase-12 count must reflect the new state. |
| **Phase 12 R5 (NEW):** Tier-2 may miscount test tiers (claiming 10 instead of 11) AGAIN | The plan EXPLICITLY says "ALL 11 TIERS PASS" in Task 12.9. The 11th tier is `tier-1-unit-comms`. This is the FOURTH time this is being emphasized. |
| **Phase 12 R6 (NEW):** Tier-2 may claim "Phase 12 complete" without running the test suite | Task 12.9 is the test verification. The completion commit (12.11) requires all 11 test tiers passing. The user verifies via 12.13 (Conductor - User Manual Verification). |
| **Phase 12 R7 (NEW):** The migration may break behavior in a way the test suite doesn't catch | Task 12.9 catches regressions. For non-tier-tested files, manual smoke-testing is added (sub-task of 12.6.x). |

---

## Verification Snapshot (capture in the report)

After Phase 12, capture in `docs/reports/RESULT_MIGRATION_SMALL_FILES_20260617.md` and `docs/reports/TRACK_COMPLETION_result_migration_small_files_20260617.md`:

- **The user's principle (2026-06-17, in CAPS):** Result[T] propagates until it reaches a drain point. Logging is NOT a drain. The app should almost never crash unless something critical fails.
- Phase 10 REJECTED: 21 sites slimed; 5 LAUNDERING HEURISTICS (#22-#26) added.
- Phase 11 REJECTED: Heuristic #19 (narrow+log = compliant) was laundering; visit_Try audit bug not fixed; ~18+ nested-Try sites silently missed; tier-2 misclassified 2 sites.
- Phase 12 (this phase): Heuristic #19 REMOVED; visit_Try FIXED; Heuristic D ADDED (5 drain-point patterns); N new sites Result-typed.
- Audit pre-Phase-1: 76 sites (62V + 10S + 4?); 3 audit-script bugs documented
- Audit post-Phase-1: 3 audit-script bugs fixed (visit_Try walker, render_json filter, render_json truncation)
- Audit post-Phase-2: 4 UNCLEAR sites classified (2 compliant + 2 migration-target)
- Audit post-Phase-9: 49/76 sites migrated; 27 SILENT_SWALLOW remain; 14 new UNCLEAR sites
- Audit post-Phase-10 (REJECTED): 5 sites full Result + 21 sites narrowed+log; 5 LAUNDERING HEURISTICS (#22-#26) added
- Audit post-Phase-11 (REJECTED): 5 LAUNDERING HEURISTICS REVERTED; 5 sites full Result + 2 helper extracts; 14 sites claimed as "already compliant" (6 legitimately, 2 misclassified, 6+ silently missed by visit_Try bug)
- Audit post-Phase-12: 0 SILENT_SWALLOW; 0 UNCLEAR; 0 laundering heuristics; 0 migration-target; the small set of true drain points (HTTP responses, GUI error displays, app terminations, telemetry emissions, retry-with-bounded-attempts) is correctly recognized by Heuristic D
- Per-file migration summary (76 + N new sites → 0 migration-target; per-file counts; per-site function signatures + ErrorInfo fields)
- Per-site decisions for the 4 UNCLEAR sites (Phase 2)
- Per-site drain-point decisions (Phase 12.6.x) — for each site, state whether it's a drain point (Heuristic D) or a Result-typed function
- Audit-script changes: 3 from Phase 1 + visit_Try fix (Phase 12.2) + Heuristic #19 removal (Phase 12.1) + Heuristic D (Phase 12.3) + Heuristic A (Phase 11.2)
- **Test pass count: ALL 11 TIERS PASS** (not 10; the 11th tier is `tier-1-unit-comms`; tier-2 had been miscounting in 3 prior phases); new tests added (4 for Phase 1 + 2 for Heuristic A + 5 for Heuristic D + N for the migrations)
- The io_pool callback sites (`warmup.py:139/215/249`) thread the Result through the completion handler (same pattern as `src/hot_reloader.py`)
- `startup_profiler.py:40` was MIGRATED via the `_log_phase_output` helper (phase() IS `@contextmanager`; the helper extraction is the partial-migration workaround; tier-2's original claim that phase() is "not a context manager" was wrong, and the plan's claim that "phase() is not a context manager" was also wrong — phase() IS `@contextmanager`; the helper extraction is the correct workaround)
