# HANDOFF REPORT — MILESTONE M4 GATE VERIFICATION: EMPIRICAL CHALLENGER 1

**Verdict**: **REQUEST_CHANGES** (Critical Bug in `production_orchestrator.py:1170`)

---

## 1. Observation

### Observation 1: Mode A vs Mode B Empirical Probe Results
We executed `tests/test_adversarial_m4_audio_concat_probe.py` (`TestAdversarialM4AudioConcatProbe::test_probe_01_mode_a_vs_mode_b_multi_shot_timeline_drift`, `test_probe_02_ten_shot_scale_mode_a_zero_drift_verification`, `test_probe_04_dialogue_cut_alignment_at_timeline_tail`):
- **Mode B (`acrossfade`, crossfade_dur = 0.5s, 6 shots x 2.0s = 12.0s)**:
  * Measured Tail Silence: verbatim `2.500s`.
  * Theoretical shrinkage: $(6 - 1) \times 0.5\text{s} = 2.500\text{s}$.
  * Container duration: 12.000s (padded by `apad` at the tail).
  * Audio of shot 6 shifted prematurely by 2.500s ahead of the video cut.
  * In Probe 4, at timestamp $t = 1.4\text{s}$ (0.6s before cut to Shot 2), Shot 2's 1000Hz frequency was detected at `-28.7 dB` (premature audio leak into Shot 1).
- **Mode A (`boundary_smoothing`, 30ms micro-fade with curve=qsin, 6 shots x 2.0s = 12.0s)**:
  * Video duration: `12.000s`.
  * Audio duration: `12.000s`.
  * Duration difference: `0.0000s`.
  * A/V Drift: `0.0000s`.
  * Tail silence: `0.000s`.
  * In Probe 4, at timestamp $t = 1.4\text{s}$, Shot 2's 1000Hz frequency was `-63.0 dB` (clean cut boundary isolation; no premature audio leak).
- **10-Shot Scale Test (`test_probe_02`)**:
  * 10 shots x 1.0s = 10.0s total.
  * Mode A audio duration: `10.000s`, Drift: `0.0000s`.

### Observation 2: Critical Bug in `production_orchestrator.py:1170` (Fallback Stream Specifier Crash)
In `05_Production_Pipeline/production_orchestrator.py`, line 1170:
```python
1166:     has_audio_list = []
1167:     for v in video_files:
1168:         has_a = True
1169:         try:
1170:             ffprobe_exe = ffmpeg_exe.replace("ffmpeg", "ffprobe")
1171:             probe_cmd = [
1172:                 ffprobe_exe, "-v", "error",
1173:                 "-show_entries", "stream=codec_type",
1174:                 "-of", "json", str(v)
1175:             ]
1176:             p_res = subprocess.run(probe_cmd, capture_output=True, text=True)
1177:             if p_res.returncode == 0:
1178:                 p_data = json.loads(p_res.stdout)
1179:                 has_a = any(s.get("codec_type") == "audio" for s in p_data.get("streams", []))
1180:         except Exception:
1181:             has_a = True
1182:         has_audio_list.append(has_a)
```
- In the active Windows environment, `get_ffmpeg()` returns:
  `C:\Users\Admin\AppData\Local\Microsoft\WinGet\Packages\Gyan.FFmpeg_Microsoft.Winget.Source_8wekyb3d8bbwe\ffmpeg-9.0.2-full_build\bin\ffmpeg.exe`.
- `ffmpeg_exe.replace("ffmpeg", "ffprobe")` replaces all occurrences of `"ffmpeg"`, transforming the directory name `ffmpeg-9.0.2-full_build` into:
  `C:\Users\Admin\AppData\Local\Microsoft\WinGet\Packages\Gyan.FFmpeg_Microsoft.Winget.Source_8wekyb3d8bbwe\ffprobe-9.0.2-full_build\bin\ffprobe.exe`.
- Verbatim empirical probe:
  `os.path.exists("...\\ffprobe-9.0.2-full_build\\bin\\ffprobe.exe") == False`.
- Because the executable path does not exist, `subprocess.run(probe_cmd)` raises `FileNotFoundError`.
- Line 1180 silently catches this error and defaults `has_a = True`.
- Consequently, for any clip without an audio track (`-an`), `has_audio_list` incorrectly marks it as `True`.
- In line 1186, it appends `[{i}:a]aresample=48000...`.
- FFmpeg crashes with verbatim error:
  `[fc#0 @ ...] Stream specifier ':a' in filtergraph description ... matches no streams.`
  `Error binding filtergraph inputs/outputs: Invalid argument`.

### Observation 3: Canonical Helper Already Exists
In `05_Production_Pipeline/audio_continuity_engine.py`, lines 59-68:
`get_ffprobe() -> str` already searches `DEFAULT_FFPROBE_PATHS` and correctly returns:
`C:\Users\Admin\AppData\Local\Microsoft\WinGet\Packages\Gyan.FFmpeg_Microsoft.Winget.Source_8wekyb3d8bbwe\ffmpeg-9.0.2-full_build\bin\ffprobe.exe` (`os.path.exists` is `True`).
However, `production_orchestrator.py` at line 106 only imports `AudioContinuityEngine, get_ffmpeg` and failed to import or use `get_ffprobe`.

### Observation 4: Baseline Test Suite Pass Rates
- `python -m pytest tests/test_production_pipeline_m4.py -v`: 15 passed in 10.08s.
- `python -m pytest tests/test_adversarial_m3_audio_engine.py -v`: 6 passed in 29.77s.
- `python -m pytest tests/test_adversarial_m4_audio_concat_probe.py -v`: 5 passed in 12.77s.
- Combined execution: 26 passed in 51.50s.

---

## 2. Logic Chain

1. **Drift Invariant (Mode A vs Mode B)**:
   - Observation 1 proves that Mode B acrossfade overlaps adjacent audio segments by $d$ seconds, causing a cumulative shrinkage of $(N - 1) \times d$ seconds. For 6 shots with $d = 0.5\text{s}$, this equals exactly 2.500s of shrinkage. The padded tail silence disguises the shrinkage at the file duration level, but shifts internal dialogue cuts forward, causing audio to precede video action by 2.5s.
   - Observation 1 proves that Mode A `boundary_smoothing` applies an intra-clip 30ms micro-fade (`curve=qsin`) at clip boundaries without overlapping clips. The resulting audio duration matches video duration with 0.0000s loss, preserving exact sample-accurate A/V synchronization across every shot boundary.

2. **Stream Specifier Crash in Fallback Concat**:
   - Observation 2 demonstrates that line 1170 of `production_orchestrator.py` uses naive string replacement `.replace("ffmpeg", "ffprobe")`. Because the installation directory contains `"ffmpeg"`, the folder path is corrupted.
   - Observation 2 confirms this raises `FileNotFoundError`, which triggers the exception handler on line 1180 to default `has_a = True`.
   - When a clip created with `-an` is processed through the fallback concat path, FFmpeg attempts to map the non-existent `:a` stream, crashing immediately with `Stream specifier ':a' ... matches no streams`.
   - Therefore, the claim in `worker_m4_assembly_1/handoff.md` that fallback concat eliminates FFmpeg crashes on clips without audio is invalidated on Windows when using the standard WinGet package.

3. **Required Remediation**:
   - Observation 3 shows `get_ffprobe()` already exists in `audio_continuity_engine.py`.
   - The worker must import `get_ffprobe` in `production_orchestrator.py` (line 106) and call `ffprobe_exe = get_ffprobe()` at line 1170.

---

## 3. Caveats

- In `AudioContinuityEngine.stitch_with_audio_crossfade`, `self.ffprobe = get_ffprobe()` is used properly, so the primary engine path does not suffer from the path corruption bug and correctly handles silent/missing audio clips (`TestAdversarialM4AudioConcatProbe::test_probe_03a`).
- The bug is strictly located in the fallback concat routine of `production_orchestrator.py:1170`.
- All other M4 features (EBU R128 loudness normalization, versioned candidate resolution, Scene Gate pre-flight gating, and multi-scene assembly) passed empirical verification without issues.

---

## 4. Conclusion

**Verdict: REQUEST_CHANGES**

Milestone M4 cannot be approved in its current state because `production_orchestrator.py` contains a fatal crash bug on its fallback concat path when encountering clips without audio streams.

### Required Actions for Worker:
In `05_Production_Pipeline/production_orchestrator.py`:
1. **Line 106**: Import `get_ffprobe`:
   ```python
   from audio_continuity_engine import AudioContinuityEngine, get_ffmpeg, get_ffprobe
   ```
   (and update fallback lambda if needed: `get_ffprobe = lambda: "ffprobe"`).
2. **Line 1170**: Replace the naive string substitution:
   ```python
   # Replace:
   ffprobe_exe = ffmpeg_exe.replace("ffmpeg", "ffprobe")
   # With:
   ffprobe_exe = get_ffprobe()
   ```

Once this 2-line change is applied, the fallback concat path will correctly detect audio-less clips and substitute `aevalsrc=0` silence streams, making the pipeline 100% crash-resilient across both the engine and fallback paths.

---

## 5. Verification Method

To independently verify the empirical challenge findings:

1. **Verify the Path Replacement Bug**:
   ```bash
   python -c "from audio_continuity_engine import get_ffmpeg; f = get_ffmpeg(); p = f.replace('ffmpeg', 'ffprobe'); import os; print('ffmpeg:', f); print('replaced:', p); print('exists:', os.path.exists(p))"
   ```
   *Expected output*: `exists: False`.

2. **Verify Canonical `get_ffprobe`**:
   ```bash
   python -c "from audio_continuity_engine import get_ffprobe; import os; p = get_ffprobe(); print('ffprobe:', p); print('exists:', os.path.exists(p))"
   ```
   *Expected output*: `exists: True`.

3. **Run Adversarial Concat Probe Suite (5 tests)**:
   ```bash
   python -m pytest tests/test_adversarial_m4_audio_concat_probe.py -v -s
   ```

4. **Run Full M4 Regression Suite (26 tests)**:
   ```bash
   python -m pytest tests/test_production_pipeline_m4.py tests/test_adversarial_m3_audio_engine.py tests/test_adversarial_m4_audio_concat_probe.py -q
   ```
   *Invalidation Conditions*: Any failure in tests, or any return of `exists: False` for `canonical_ffprobe`.
