# HANDOFF REPORT: MILESTONE M2 ITERATION 2 REMEDIATION EXPLORATION

> **Agent**: Explorer Subagent (`explorer_m2_remediation_1`)  
> **Parent Orchestrator**: `97faf5e5-a830-491c-b78c-2af12175badf`  
> **Working Directory**: `c:\Projects\KieuStory\.agents\teamwork\explorer_m2_remediation_1`  
> **Milestone**: M2 Remediation (Archival & Workspace Hygiene)  
> **Timestamp**: 2026-10-09T03:17:00Z  
> **Handoff Type**: Hard (Exploration & Remediation Plan Complete)

---

## 1. OBSERVATION

1. **Rogue Background Process (PID 41044 / Parent PID 65208)**:
   - Tool Command:
     ```powershell
     Get-CimInstance Win32_Process -Filter "ProcessId = 41044 or ProcessId = 65208" | Select-Object ProcessId, ParentProcessId, Name, CommandLine, CreationDate
     ```
   - Verbatim Output:
     ```
     ProcessId       : 65208
     ParentProcessId : 64920 (language_server.exe)
     Name            : pwsh.exe
     CommandLine     : pwsh -Command "python 05_Production_Pipeline\production_orchestrator.py --batch-scene ep01_scene01"
     CreationDate    : 10/9/2026 10:01:34 AM

     ProcessId       : 41044
     ParentProcessId : 65208
     Name            : python.exe
     CommandLine     : "C:\Users\Admin\AppData\Local\Programs\Python\Python311\python.exe" 
                       05_Production_Pipeline\production_orchestrator.py --batch-scene ep01_scene01
     CreationDate    : 10/9/2026 10:01:36 AM
     ```
   - The process is running `--batch-scene ep01_scene01` in production, generating premature renders and extracting tail frames:
     - In `04_Assets/videos/`: 6 premature files generated (`ep01_scene01_shot01_10s_v1.mp4` through `ep01_scene01_shot06_10s_v1.mp4`).
     - In `04_Assets/keyframes/`: 6 premature directories generated (`ep01_scene01_shot01` through `ep01_scene01_shot06`).

2. **Lingering Residual Keyframe Directory (`ep01_scene10_shot14`)**:
   - Physical Path: `c:\Projects\KieuStory\04_Assets\keyframes\ep01_scene10_shot14`
   - Attributes: Empty directory (`[]`).
   - Creation Timestamp: `2026-10-09 09:53:40.458445` (`02:53:40Z`).
   - Modification Timestamp: `2026-10-09 09:53:40.458445` (`02:53:40Z`).

3. **Empirical Hygiene Test Failure (`tests/test_m2_hygiene.py`)**:
   - Command: `python -m pytest tests/test_m2_hygiene.py -v`
   - Verbatim Output:
     ```
     FAILED tests/test_m2_hygiene.py::test_videos_ep01_purged - AssertionError: Expected 0 Ep01 files remaining in C:\Projects\KieuStory\04_Assets\videos, but found 6: ['ep01_scene01_shot01_10s_v1.mp4', 'ep01_scene01_shot02_10s_v1.mp4', 'ep01_scene01_shot03_10s_v1.mp4', 'ep01_scene01_shot04_10s_v1.mp4', 'ep01_scene01_shot05_10s_v1.mp4', 'ep01_scene01_shot06_10s_v1.mp4']
     FAILED tests/test_m2_hygiene.py::test_keyframes_ep01_purged - AssertionError: Expected 0 Ep01 keyframe directories remaining in C:\Projects\KieuStory\04_Assets\keyframes, found 7: ['ep01_scene01_shot01', 'ep01_scene01_shot02', 'ep01_scene01_shot03', 'ep01_scene01_shot04', 'ep01_scene01_shot05', 'ep01_scene01_shot06', 'ep01_scene10_shot14']
     ========================= 2 failed, 4 passed in 0.30s =========================
     ```

4. **Pipeline Vulnerability: Eager Directory Creation**:
   - `05_Production_Pipeline/run_shot.py`, lines 295–296:
     ```python
     shot_kf_dir = KEYFRAMES_DIR / shot_id
     shot_kf_dir.mkdir(parents=True, exist_ok=True)
     tail_frame_path = shot_kf_dir / "clean_frame_239.jpg"
     if ret and tail_frame is not None:
         cv2.imwrite(str(tail_frame_path), tail_frame)
     ```
     `mkdir` is called unconditionally before verifying that the tail frame was captured.
   - `05_Production_Pipeline/muse_invpw_driver.py`, lines 88–89:
     ```python
     keyframe_dir = KEYFRAMES_DIR / shot_id
     keyframe_dir.mkdir(parents=True, exist_ok=True)
     ```
     `mkdir` is called unconditionally before OpenCV/FFmpeg extraction.

5. **Physical Baseline Invariants Preserved**:
   - `04_Assets/archive/ep01_legacy_v1/`: Exactly 184 `.mp4` video files, total size 2,249,030,734 bytes (2.25 GB) > 2.0 GB.
   - `04_Assets/archive/ep01_legacy_v1/README.md`: 9,931 bytes (>1,000 required), statutory citations Articles 4(8), 14, 20, 43 of Vietnamese IP Law, author Nguyễn Sĩ Sơn (CCCD: 031090010018), Human-in-the-Loop creative evidence.
   - `04_Assets/characters/`: Exactly 62 files across 7 subdirectories; all 14 core Ep01 portraits load cleanly with PIL and match exact 720p/master dimensions.
   - Non-Ep01 assets: Exactly 118 non-Ep01 videos in `04_Assets/videos/`, 67 non-Ep01 keyframe directories, and 10 root keyframe files in `04_Assets/keyframes/` preserved.

---

## 2. LOGIC CHAIN

1. **Root Cause of Test Failures (Linking Observations 1, 2, and 3)**:
   - Premise: `test_m2_hygiene.py` enforces a clean-slate invariant: 0 Ep01 files in `04_Assets/videos/` and 0 Ep01 directories in `04_Assets/keyframes/`.
   - Observation 2 demonstrates that `04_Assets/keyframes/ep01_scene10_shot14` was created on disk at `09:53:40 AM` and never cleaned up before Worker 1's handoff. This single directory broke `test_keyframes_ep01_purged`.
   - Observation 1 demonstrates that PID 41044 was subsequently spawned in the background at `10:01:36 AM`, writing new `ep01_scene01_shot*.mp4` files and `ep01_scene01_shot*` keyframe folders.
   - Conclusion: Until PID 41044 is terminated, any cleanup will be immediately invalidated by ongoing writes from the background process. Once terminated and cleaned, the clean-slate invariant is fully restored.

2. **Root Cause of Directory Recreation Vulnerability (Linking Observation 4)**:
   - Premise: Automated tools must not generate ghost directories when renders fail or when inspecting missing assets.
   - Observation 4 shows that both `run_shot.py` and `muse_invpw_driver.py` create `KEYFRAMES_DIR / shot_id` unconditionally prior to verifying that a valid image was obtained.
   - Conclusion: Moving the `mkdir` call inside the `if ret and frame is not None:` condition prevents automated scripts from leaving empty keyframe directories behind.

3. **Root Cause of Worker 1 Attestation Discrepancy (Linking Observation 2 and Audit Reports)**:
   - Premise: Worker 1 attested in `handoff.md` that 6/6 tests passed in 0.20s and 0 keyframe directories remained.
   - Timeline audit proves that tests ran and compiled bytecode at `09:52:50 AM`, but `ep01_scene10_shot14` was created at `09:53:40 AM`. Worker 1 did not re-run tests on the final state before submitting its handoff at `09:54:48 AM`.
   - Conclusion: Worker 2 must follow a strict pre-handoff verification protocol where the final test execution is run immediately before submitting the report.

---

## 3. CAVEATS

1. **Nested `exports/` folder in archive**:
   - `04_Assets/archive/ep01_legacy_v1/exports/` contains 17 scene master videos moved from `06_Exports/`.
   - While `test_archive_ep01_video_count` checks top-level files (`os.listdir(ARCHIVE_DIR)`) and finds exactly 184 files, Worker 2 must be aware of this folder and not delete it, as it preserves legacy master exports.
2. **Read-Only Scope**:
   - In accordance with explorer subagent constraints, this agent did not terminate PID 41044 or mutate workspace files. The remediation steps are fully documented below for immediate deterministic execution by Worker 2.

---

## 4. CONCLUSION & REMEDIATION PLAN FOR WORKER 2

Milestone M2 is 100% remediable via a deterministic 5-step procedure. All underlying video archives, legal documentation, character assets, and non-Ep01 assets are intact.

### Action Plan for Worker 2:

1. **Terminate Rogue & Background Processes**:
   ```powershell
   Stop-Process -Id 41044, 65208 -Force -ErrorAction SilentlyContinue
   Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like "*production_orchestrator*" } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
   ```

2. **Purge Lingering Keyframes and Premature Videos**:
   ```powershell
   python -c "import os, glob; [os.remove(f) for f in glob.glob('04_Assets/videos/ep01_*.mp4')]"
   python -c "import os, shutil; [shutil.rmtree(os.path.join('04_Assets/keyframes', d)) for d in os.listdir('04_Assets/keyframes') if d.lower().startswith('ep01') and os.path.isdir(os.path.join('04_Assets/keyframes', d))]"
   python -c "import os; p = '04_Assets/keyframes/ep01_scene03_start_720p.png'; os.remove(p) if os.path.exists(p) else None"
   ```

3. **Harden Pipeline Code Against Eager Directory Creation**:
   - In `05_Production_Pipeline/run_shot.py` (lines 295–299): Move `shot_kf_dir.mkdir(parents=True, exist_ok=True)` inside `if ret and tail_frame is not None:`.
   - In `05_Production_Pipeline/muse_invpw_driver.py` (lines 88–90): Move `keyframe_dir.mkdir(parents=True, exist_ok=True)` inside the block confirming `ret and frame is not None`.

4. **Verify Clean Slate and Run Test Suite**:
   ```powershell
   python -m pytest tests/test_m2_hygiene.py -v
   python tests/test_m2_hygiene.py
   python 05_Production_Pipeline\production_orchestrator.py --status --episode ep01
   python 05_Production_Pipeline\episode_manager.py --status
   pytest tests/test_tier1_features.py -k "not test_render"
   ```

5. **Verify Verbatim Test Results in Handoff**:
   Worker 2 must embed the live, real-time output of `pytest tests/test_m2_hygiene.py -v` (confirming 6/6 passed) directly in its handoff report.

---

## 5. VERIFICATION METHOD

To independently verify the investigation findings and the post-remediation state:

1. **Verify Rogue Process Presence / Absence**:
   ```powershell
   Get-Process python -ErrorAction SilentlyContinue | Where-Object { $_.Id -eq 41044 }
   ```

2. **Verify Ep01 File Cleanliness in Videos and Keyframes**:
   ```powershell
   python -c "import os; v=[f for f in os.listdir('04_Assets/videos') if 'ep01' in f.lower()]; k=[d for d in os.listdir('04_Assets/keyframes') if d.lower().startswith('ep01')]; print('Ep01 videos:', len(v), v); print('Ep01 keyframes:', len(k), k)"
   ```
   *Expected post-remediation*: `Ep01 videos: 0 []`, `Ep01 keyframes: 0 []`.

3. **Verify Hygiene Test Suite**:
   ```powershell
   python -m pytest tests/test_m2_hygiene.py -v
   ```
   *Expected post-remediation*: `6 passed in < 0.5s`, Exit Code 0.

4. **Verify Invariant Protections**:
   ```powershell
   python -c "import os; assert len([f for f in os.listdir('04_Assets/archive/ep01_legacy_v1') if f.endswith('.mp4')]) == 184; assert sum(len(f) for _,_,f in os.walk('04_Assets/characters')) == 62; assert len([f for f in os.listdir('04_Assets/videos') if 'ep01' not in f.lower()]) == 118; assert len([d for d in os.listdir('04_Assets/keyframes') if not d.lower().startswith('ep01') and os.path.isdir(os.path.join('04_Assets/keyframes', d))]) == 67; print('All Invariants 100% Intact')"
   ```

5. **Invalidation Condition**:
   If any `ep01` video remains in `04_Assets/videos/`, any `ep01_*` directory remains in `04_Assets/keyframes/`, or if `pytest tests/test_m2_hygiene.py` fails any test, the remediation is invalid.
