[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HW9S3SA3E23APQ5PWZMAMA":3,"skill-same:01M6HW9S3SA3E23APQ5PWZMAMA":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":41,"commitSha":42,"skillDirectory":43,"forksCount":44,"repositoryHtmlUrl":45,"repositoryHomepageUrl":6,"ownerHtmlUrl":46,"ownerBlogUrl":47,"ownerDescription":6,"updatedAt":48,"install":49,"resources":62},"01M6HW9S3SA3E23APQ5PWZMAMA","diagnostic-stem-delivery",null,"Audio production with diagnostic analysis, timecode parsing from documents, and verified export workflow","HKUDS\u002FAgentPilot","HKUDS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F118165258?v=4","01M6HW8VRNZP64G0P4MVJW2KKQ","✨Data Intelligence Lab@HKU✨","01M6HW8VWZVHBRHYH3T330PFWV",8029,"MIT","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Faudio-track-production-enhanced-enhanced-enhanced\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35],"delivery","diagnostic","diagnostic stem delivery","workflow","documents","Production","analysis","parsing","Audio","export","with","verified","2026-11-10 10:12:30",false,"---\nname: diagnostic-stem-delivery\ndescription: Audio production with diagnostic analysis, timecode parsing from documents, and verified export workflow\n---\n\n# Diagnostic Stem Audio Production Workflow\n\nThis skill provides a resilient pattern for audio production that emphasizes **diagnostic analysis before editing**, **explicit timecode extraction from documents**, **incremental verification**, **fail-fast principles**, and **mandatory deliverable verification**. Each major step produces verified outputs before proceeding, with comprehensive audio diagnostics at specified timecodes.\n\n## Overview\n\nFollow these steps in strict order. Each step must complete successfully and pass verification before proceeding to the next:\n\n1. **Parse timecodes from source documents** - Extract edit spots\u002Ftimecodes from DOCX\u002Ftext sources\n2. **Perform diagnostic audio analysis** - Analyze reference audio at each timecode (pitch, clicks, frequency)\n3. **Calculate timing parameters** - Derive section transitions from BPM and duration\n4. **Verify reference audio** - Validate input file properties and extract target duration\n5. **Generate and verify each stem individually** - One stem at a time with immediate verification\n6. **Detect and resolve duration mismatches** - Apply appropriate extension strategy\n7. **Apply edits based on diagnostics** - Make informed edits using analysis results\n8. **Mix with verification** - Combine stems and verify mix integrity\n9. **Export and verify deliverable** - Generate final output with comprehensive checks\n\n## Key Principles\n\n- **Diagnostics first**: Analyze audio at edit points BEFORE making any changes\n- **Document-driven**: Parse timecodes directly from source documents (DOCX, TXT)\n- **Incremental verification**: Verify each stem immediately after generation\n- **Fail-fast approach**: Stop and report errors at each step\n- **Mandatory export**: Final step MUST produce verified deliverable file\n- **Tool reliability**: Use run_shell with inline Python for audio processing (avoid execute_code_sandbox for audio)\n\n## Step 0: Parse Timecodes from Source Documents\n\nExtract edit spots and timecodes from document sources. Use python-docx via run_shell for reliable DOCX parsing:\n\n```bash\n# Parse DOCX file for timecodes and edit spots\npython3 -c \"\nfrom docx import Document\nimport re\nimport sys\n\ndoc_path = sys.argv[1] if len(sys.argv) > 1 else 'Bass Edit Spots.docx'\ndoc = Document(doc_path)\n\nedit_spots = []\ntimecode_pattern = r'(\\d{1,2}:?\\d{2}:?\\d{2}[.:\\d]*)|(\\d+[.:\\d]+)s'\n\nfor para in doc.paragraphs:\n    text = para.text.strip()\n    if not text:\n        continue\n    \n    # Look for timecodes in various formats\n    matches = re.findall(timecode_pattern, text, re.IGNORECASE)\n    if matches:\n        for match in matches:\n            timecode = match[0] if match[0] else match[1]\n            if timecode:\n                edit_spots.append({'timecode': timecode, 'context': text[:100]})\n    \n    # Also check tables\n    for table in doc.tables:\n        for row in table.rows:\n            for cell in row.cells:\n                cell_text = cell.text.strip()\n                matches = re.findall(timecode_pattern, cell_text, re.IGNORECASE)\n                for match in matches:\n                    timecode = match[0] if match[0] else match[1]\n                    if timecode:\n                        edit_spots.append({'timecode': timecode, 'context': cell_text[:100]})\n\nprint(f'Found {len(edit_spots)} edit spots:')\nfor i, spot in enumerate(edit_spots, 1):\n    print(f'{i}. {spot[\\\"timecode\\\"]} - {spot[\\\"context\\\"][:50]}...')\n\"\n```\n\n## Step 1: Perform Diagnostic Audio Analysis at Timecodes\n\nBefore any editing, analyze the reference audio at each identified timecode:\n\n```python\nimport numpy as np\nimport soundfile as sf\nimport librosa\n\ndef analyze_audio_at_timecode(filepath, timecode_str, sample_rate=48000):\n    \"\"\"\n    Perform comprehensive diagnostic analysis at a specific timecode.\n    \n    Returns dict with:\n    - pitch_estimate: Dominant frequency\u002Fpitch\n    - click_pop_score: Likelihood of clicks\u002Fpops (0-1, higher = more likely)\n    - frequency_spectrum: Dominant frequency bands\n    - amplitude: RMS amplitude at timecode\n    - issues: List of detected issues\n    \"\"\"\n    # Parse timecode to seconds\n    timecode_str = timecode_str.replace(':', '.').strip()\n    if 's' in timecode_str:\n        timecode_str = timecode_str.replace('s', '')\n    \n    try:\n        parts = timecode_str.split('.')\n        if len(parts) == 3:\n            seconds = int(parts[0]) * 3600 + int(parts[1]) * 60 + float(parts[2])\n        elif len(parts) == 2:\n            seconds = int(parts[0]) * 60 + float(parts[1])\n        else:\n            seconds = float(parts[0])\n    except:\n        return {'error': f'Invalid timecode format: {timecode_str}'}\n    \n    # Load audio\n    data, sr = sf.read(filepath)\n    if sr != sample_rate:\n        data = librosa.resample(data, orig_sr=sr, target_sr=sample_rate)\n        sr = sample_rate\n    \n    # Extract window around timecode (±50ms for analysis)\n    window_samples = int(0.1 * sample_rate)  # 100ms window\n    start_sample = max(0, int(seconds * sample_rate) - window_samples \u002F\u002F 2)\n    end_sample = min(len(data), start_sample + window_samples)\n    window = data[start_sample:end_sample]\n    \n    if len(window) \u003C 100:\n        return {'error': 'Window too short for analysis'}\n    \n    # Pitch detection (using autocorrelation for monophonic content)\n    def estimate_pitch(signal, sr):\n        # Simple autocorrelation-based pitch detection\n        signal = signal - np.mean(signal)  # DC removal\n        autocorr = np.correlate(signal, signal, mode='full')\n        autocorr = autocorr[len(autocorr)\u002F\u002F2:]\n        \n        # Find first significant peak after zero lag\n        for i in range(1, min(len(autocorr) \u002F\u002F 2, int(sr \u002F 50))):\n            if autocorr[i] > 0.3 * autocorr[0]:\n                for j in range(i + 1, min(len(autocorr), int(sr \u002F 20))):\n                    if autocorr[j] > autocorr[i]:\n                        period = j\n                        freq = sr \u002F period\n                        return freq\n        return None\n    \n    pitch = estimate_pitch(window, sr)\n    \n    # Click\u002Fpop detection (sudden amplitude changes)\n    def detect_clicks(signal):\n        diff = np.diff(np.abs(signal))\n        threshold = 5 * np.std(diff)\n        click_positions = np.where(np.abs(diff) > threshold)[0]\n        click_score = min(1.0, len(click_positions) \u002F len(signal) * 1000)\n        return click_score, click_positions\n    \n    click_score, click_positions = detect_clicks(window)\n    \n    # Frequency analysis\n    spectrum = np.abs(np.fft.rfft(window))\n    freqs = np.fft.rfftfreq(len(window), 1\u002Fsr)\n    dominant_freqs = []\n    for band in [(20, 200, 'sub'), (200, 2000, 'mid'), (2000, 20000, 'high')]:\n        mask = (freqs >= band[0]) & (freqs \u003C band[1])\n        if np.any(mask):\n            band_power = np.sum(spectrum[mask])\n            dominant_freqs.append({'range': f'{band[0]}-{band[1]}Hz', 'power': float(band_power), 'label': band[2]})\n    dominant_freqs.sort(key=lambda x: x['power'], reverse=True)\n    \n    # Amplitude\n    rms = np.sqrt(np.mean(window ** 2))\n    \n    # Detect issues\n    issues = []\n    if click_score > 0.3:\n        issues.append(f'High click\u002Fpop probability ({click_score:.2f})')\n    if rms \u003C 0.001:\n        issues.append('Near-silence detected')\n    if rms > 0.9:\n        issues.append('Potential clipping')\n    if pitch and pitch \u003C 40:\n        issues.append(f'Very low frequency content ({pitch:.1f}Hz)')\n    \n    return {\n        'timecode': timecode_str,\n        'seconds': seconds,\n        'pitch_hz': pitch,\n        'click_pop_score': click_score,\n        'frequency_spectrum': dominant_freqs[:3],\n        'amplitude_rms': float(rms),\n        'issues': issues,\n        'window_length': len(window)\n    }\n\n# Analyze all edit spots\n# edit_spots from Step 0\nfor i, spot in enumerate(edit_spots):\n    print(f'\\\\n=== Analyzing edit spot {i+1}: {spot[\"timecode\"]} ===')\n    analysis = analyze_audio_at_timecode('reference.wav', spot['timecode'])\n    if 'error' in analysis:\n        print(f'ERROR: {analysis[\"error\"]}')\n    else:\n        print(f'Pitch: {analysis[\"pitch_hz\"]} Hz' if analysis[\"pitch_hz\"] else 'Pitch: N\u002FA (complex\u002Fnoisy)')\n        print(f'Click\u002FPop Score: {analysis[\"click_pop_score\"]:.3f} (0=none, 1=certain)')\n        print(f'Amplitude (RMS): {analysis[\"amplitude_rms\"]:.6f}')\n        if analysis['issues']:\n            print(f'Issues: {\", \".join(analysis[\"issues\"])}')\n        for freq in analysis['frequency_spectrum']:\n            print(f'  {freq[\"label\"]} band ({freq[\"range\"]}): power={freq[\"power\"]:.2f}')\n```\n\n## Step 2: Calculate Timing Parameters (Early)\n\nCalculate all timing parameters **before** generating any audio:\n\n```python\ndef calculate_section_transitions(bpm, total_duration_sec, sections):\n    \"\"\"Calculate beat-aligned transition points for song sections.\"\"\"\n    beats_per_second = bpm \u002F 60.0\n    \n    section_durations = {}\n    cumulative_time = 0\n    \n    for section_name, beat_count in sections.items():\n        duration = beat_count \u002F beats_per_second\n        section_durations[section_name] = {\n            'start': cumulative_time,\n            'end': cumulative_time + duration,\n            'beats': beat_count,\n            'start_beat': cumulative_time * beats_per_second\n        }\n        cumulative_time += duration\n    \n    return section_durations\n\n# Configuration\nBPM = 120\nDURATION = 137\nSECTIONS = {'intro': 16, 'verse': 32, 'chorus': 32, 'bridge': 16, 'outro': 16}\n\ntiming = calculate_section_transitions(BPM, DURATION, SECTIONS)\nprint('Timing calculated:')\nfor section, data in timing.items():\n    print(f'  {section}: {data[\"start\"]:.2f}s - {data[\"end\"]:.2f}s ({data[\"beats\"]} beats)')\n```\n\n## Step 3: Verify Reference Audio\n\nValidate the reference file exists and has expected properties:\n\n```python\nimport soundfile as sf\nimport os\n\ndef verify_reference_file(filepath, expected_sample_rate=None, min_duration=None):\n    \"\"\"Verify reference audio file and return info dict.\"\"\"\n    if not os.path.exists(filepath):\n        raise FileNotFoundError(f'Reference file not found: {filepath}')\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        errors.append(f'Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}')\n    \n    if min_duration and info.duration \u003C min_duration:\n        errors.append(f'Duration too short: expected >= {min_duration}s, got {info.duration}s')\n    \n    if errors:\n        raise ValueError(f'Reference file validation failed: {\"; \".join(errors)}')\n    \n    print(f'Reference verified: {info.duration:.2f}s @ {info.samplerate}Hz, {info.channels}ch, {info.subtype}')\n    return {\n        'sample_rate': info.samplerate,\n        'duration': info.duration,\n        'channels': info.channels,\n        'subtype': info.subtype\n    }\n\n# Verify reference\nref_info = verify_reference_file('reference.wav', expected_sample_rate=48000, min_duration=130)\nTARGET_DURATION = ref_info['duration']  # Use actual reference duration as target\n```\n\n## Step 4: Generate and Verify Each Stem Individually\n\nGenerate one stem at a time, verify it immediately before proceeding to the next:\n\n```python\nimport numpy as np\n\ndef generate_stem(name, duration_sec, sample_rate, subtype='FLOAT', section_timing=None):\n    \"\"\"Generate a single stem with explicit sample type.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    t = np.linspace(0, duration_sec, frames)\n    \n    # Generate stem-specific content (customize per stem type)\n    if name == 'bass':\n        freq = 110  # A2\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.8\n    elif name == 'guitars':\n        freq = 440  # A4\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.6\n    elif name == 'synths':\n        freq = 880  # A5\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.5\n    elif name == 'bridge':\n        freq = 220  # A3\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.7\n    else:\n        audio_data = np.sin(2 * np.pi * 440 * t) * 0.5\n    \n    # Ensure proper data type\n    if subtype == 'FLOAT':\n        audio_data = audio_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        audio_data = np.clip(audio_data, -1, 1) * (2**23 - 1)\n        audio_data = audio_data.astype(np.int32)\n    \n    filepath = f'{name}_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\ndef verify_stem(filepath, expected_sample_rate, expected_duration, tolerance_sec=1.0):\n    \"\"\"Verify a single stem meets specifications.\"\"\"\n    if not os.path.exists(filepath):\n        return {'success': False, 'error': f'File not found: {filepath}'}\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if info.samplerate != expected_sample_rate:\n        errors.append(f'sample_rate: expected {expected_sample_rate}, got {info.samplerate}')\n    \n    if abs(info.duration - expected_duration) > tolerance_sec:\n        errors.append(f'duration: expected ~{expected_duration}s, got {info.duration}s')\n    \n    if errors:\n        return {'success': False, 'error': '; '.join(errors)}\n    \n    return {'success': True, 'info': info}\n\n# Generate stems one at a time with verification\nSAMPLE_RATE = 48000\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\n\ngenerated_stems = []\nstem_info = {}\n\nfor stem_name in STEM_NAMES:\n    print(f'\\\\n=== Generating {stem_name} stem ===')\n    \n    # Generate\n    filepath, data = generate_stem(stem_name, DURATION, SAMPLE_RATE, subtype='FLOAT')\n    \n    # Verify immediately\n    result = verify_stem(filepath, SAMPLE_RATE, TARGET_DURATION)\n    \n    if result['success']:\n        print(f'✓ {stem_name} stem verified: {result[\"info\"].duration:.2f}s @ {result[\"info\"].samplerate}Hz')\n        generated_stems.append(filepath)\n        stem_info[stem_name] = result\n    else:\n        print(f'✗ {stem_name} stem FAILED: {result[\"error\"]}')\n        raise RuntimeError(f'Stem generation failed for {stem_name}: {result[\"error\"]}')\n\nprint(f'\\\\nAll {len(generated_stems)} stems generated and verified successfully')\n```\n\n## Step 5: Apply Edits Based on Diagnostics\n\nUse the diagnostic analysis from Step 1 to make informed editing decisions:\n\n```python\ndef apply_edit_based_on_diagnostics(stem_filepath, edit_spot, analysis, output_filepath):\n    \"\"\"\n    Apply targeted edit at a specific timecode based on diagnostic analysis.\n    \n    Decisions based on diagnostics:\n    - High click\u002Fpop score (>0.3): Apply fade or click removal\n    - Very low pitch (\u003C40Hz): May need high-pass filter\n    - Near-silence: Consider removal or gain adjustment\n    - Potential clipping: Apply gain reduction\n    \"\"\"\n    data, sr = sf.read(stem_filepath)\n    \n    timecode_sec = analysis['seconds']\n    edit_start = max(0, int((timecode_sec - 0.05) * sr))\n    edit_end = min(len(data), int((timecode_sec + 0.05) * sr))\n    \n    # Apply edits based on diagnostics\n    if analysis['click_pop_score'] > 0.3:\n        # Apply short crossfade to smooth clicks\n        fade_len = min(100, (edit_end - edit_start) \u002F\u002F 4)\n        if fade_len > 0:\n            fade_in = np.linspace(0, 1, fade_len)\n            fade_out = np.linspace(1, 0, fade_len)\n            data[edit_start:edit_start + fade_len] *= fade_in\n            data[edit_end - fade_len:edit_end] *= fade_out\n        print(f'  Applied click smoothing at {timecode_sec:.2f}s')\n    \n    if analysis['amplitude_rms'] > 0.9:\n        # Apply gentle gain reduction to prevent clipping\n        gain = 0.8\n        data[edit_start:edit_end] *= gain\n        print(f'  Applied gain reduction ({gain:.1f}x) at {timecode_sec:.2f}s')\n    \n    # Save edited stem\n    sf.write(output_filepath, data, sr, subtype='FLOAT', format='WAV')\n    return output_filepath\n\n# Apply edits to stems based on diagnostic analysis\nfor stem_name in ['bass']:  # Customize as needed\n    stem_file = f'{stem_name}_stem.wav'\n    edited_file = f'{stem_name}_stem_edited.wav'\n    \n    print(f'\\\\n=== Applying edits to {stem_name} based on diagnostics ===')\n    \n    for i, spot in enumerate(edit_spots):\n        # Re-analyze or use cached analysis\n        analysis = analyze_audio_at_timecode('reference.wav', spot['timecode'])\n        if 'error' not in analysis:\n            apply_edit_based_on_diagnostics(stem_file, spot, analysis, edited_file)\n    \n    print(f'Edited {stem_name} stem saved to {edited_file}')\n```\n\n## Step 6: Mix with Verification\n\nCombine all stems and verify mix integrity:\n\n```python\ndef mix_stems(stem_files, output_filepath, sample_rate=48000):\n    \"\"\"Mix multiple stems into a single output file.\"\"\"\n    mixed_data = None\n    \n    for stem_file in stem_files:\n        if not os.path.exists(stem_file):\n            raise FileNotFoundError(f'Stem not found: {stem_file}')\n        \n        data, sr = sf.read(stem_file)\n        \n        # Resample if needed\n        if sr != sample_rate:\n            data = librosa.resample(data, orig_sr=sr, target_sr=sample_rate)\n        \n        # Ensure same length\n        if mixed_data is None:\n            mixed_data = np.zeros(len(data), dtype=np.float32)\n        elif len(data) != len(mixed_data):\n            min_len = min(len(data), len(mixed_data))\n            mixed_data = mixed_data[:min_len]\n            data = data[:min_len]\n        \n        mixed_data += data\n    \n    # Normalize to prevent clipping\n    if np.max(np.abs(mixed_data)) > 0.95:\n        mixed_data *= 0.95 \u002F np.max(np.abs(mixed_data))\n    \n    sf.write(output_filepath, mixed_data, sample_rate, subtype='FLOAT', format='WAV')\n    \n    return {\n        'filepath': output_filepath,\n        'duration': len(mixed_data) \u002F sample_rate,\n        'peak': float(np.max(np.abs(mixed_data))),\n        'rms': float(np.sqrt(np.mean(mixed_data ** 2)))\n    }\n\n# Mix all stems\nprint('\\\\n=== Mixing all stems ===')\nall_stems = [f'{name}_stem_edited.wav' if os.path.exists(f'{name}_stem_edited.wav') \n             else f'{name}_stem.wav' for name in STEM_NAMES]\n\nmix_info = mix_stems(all_stems, 'State_of_Affairs_FULL_EDIT_MIX.wav')\nprint(f'Mix complete: {mix_info[\"duration\"]:.2f}s, peak={mix_info[\"peak\"]:.3f}, RMS={mix_info[\"rms\"]:.6f}')\n```\n\n## Step 7: Export and Verify Deliverable (MANDATORY)\n\n**This step MUST complete successfully** - no task is complete without verified deliverable:\n\n```python\ndef verify_deliverable(filepath, required_sample_rate=48000, required_channels=None, min_duration=None):\n    \"\"\"\n    Comprehensive verification of final deliverable.\n    \n    Returns dict with verification status and details.\n    Task CANNOT complete if verification fails.\n    \"\"\"\n    if not os.path.exists(filepath):\n        return {\n            'success': False,\n            'error': f'DELIVERABLE MISSING: {filepath}',\n            'blocking': True\n        }\n    \n    try:\n        info = sf.info(filepath)\n    except Exception as e:\n        return {\n            'success': False,\n            'error': f'DELIVERABLE CORRUPT: {str(e)}',\n            'blocking': True\n        }\n    \n    errors = []\n    warnings = []\n    \n    # Critical checks (blocking)\n    if info.samplerate != required_sample_rate:\n        errors.append(f'CRITICAL: Sample rate {info.samplerate}Hz != required {required_sample_rate}Hz')\n    \n    if required_channels and info.channels != required_channels:\n        errors.append(f'CRITICAL: Channels {info.channels} != required {required_channels}')\n    \n    if min_duration and info.duration \u003C min_duration:\n        errors.append(f'CRITICAL: Duration {info.duration:.2f}s \u003C minimum {min_duration}s')\n    \n    # Verify file is not empty\n    if info.duration \u003C 0.1:\n        errors.append('CRITICAL: File appears to be empty or silent')\n    \n    # Non-critical checks (warnings)\n    if info.duration \u003C 60:\n        warnings.append(f'Short duration: {info.duration:.2f}s')\n    \n    if os.path.getsize(filepath) \u003C 1000:\n        warnings.append('File size unusually small')\n    \n    # Load and analyze audio content\n    data, sr = sf.read(filepath)\n    peak = np.max(np.abs(data))\n    rms = np.sqrt(np.mean(data ** 2))\n    \n    if peak > 0.99:\n        warnings.append(f'Potential clipping: peak={peak:.4f}')\n    \n    if rms \u003C 0.001:\n        errors.append('CRITICAL: Audio appears to be silent (RMS too low)')\n    \n    # Final verdict\n    success = len(errors) == 0\n    \n    result = {\n        'success': success,\n        'blocking': not success,\n        'filepath': filepath,\n        'info': {\n            'duration': info.duration,\n            'sample_rate': info.samplerate,\n            'channels': info.channels,\n            'subtype': info.subtype,\n            'format': info.format,\n            'peak': float(peak),\n            'rms': float(rms),\n            'file_size': os.path.getsize(filepath)\n        },\n        'errors': errors,\n        'warnings': warnings\n    }\n    \n    return result\n\n# MANDATORY deliverable verification\nprint('\\\\n=== DELIVERABLE VERIFICATION (MANDATORY) ===')\ndeliverable_path = 'State_of_Affairs_FULL_EDIT_MIX.wav'\n\nverification = verify_deliverable(\n    deliverable_path,\n    required_sample_rate=48000,\n    required_channels=2,  # stereo\n    min_duration=60  # minimum 60 seconds\n)\n\nif verification['success']:\n    print('✓ DELIVERABLE VERIFIED SUCCESSFULLY')\n    print(f'  File: {verification[\"filepath\"]}')\n    print(f'  Duration: {verification[\"info\"][\"duration\"]:.2f}s')\n    print(f'  Sample Rate: {verification[\"info\"][\"sample_rate\"]}Hz')\n    print(f'  Channels: {verification[\"info\"][\"channels\"]}')\n    print(f'  Peak: {verification[\"info\"][\"peak\"]:.4f}')\n    print(f'  RMS: {verification[\"info\"][\"rms\"]:.6f}')\n    \n    if verification['warnings']:\n        print('  Warnings:')\n        for warn in verification['warnings']:\n            print(f'    ⚠ {warn}')\n    \n    print('\\\\n✓ TASK COMPLETE - All deliverables verified')\n    \nelse:\n    print('✗ DELIVERABLE VERIFICATION FAILED')\n    print('  ERRORS (blocking):')\n    for err in verification['errors']:\n        print(f'    ✗ {err}')\n    \n    if verification['warnings']:\n        print('  Warnings:')\n        for warn in verification['warnings']:\n            print(f'    ⚠ {warn}')\n    \n    raise RuntimeError(f'Task cannot complete: {verification[\"errors\"]}')\n```\n\n## Tool Usage Notes\n\n**Critical for reliability:**\n\n1. **DOCX Parsing**: Use `run_shell` with `python3 -c` inline syntax and python-docx, NOT `read_file` (returns 'unknown error' for .docx)\n\n2. **Audio Processing**: Use `run_shell` with inline Python scripts for audio operations, NOT `execute_code_sandbox` (frequently returns 'unknown error')\n\n3. **Heredoc Workaround**: Avoid complex heredoc syntax in shell; use simpler `-c` inline Python for reliability\n\nExample reliable pattern:\n```bash\npython3 -c \"import soundfile as sf; import numpy as np; ...your code...\"\n```\n\n## Checklist Before Completion\n\n- [ ] Step 0: Timecodes parsed from document source\n- [ ] Step 1: Diagnostic analysis performed at all edit spots\n- [ ] Step 2: Timing parameters calculated\n- [ ] Step 3: Reference audio verified\n- [ ] Step 4: All stems generated and verified individually\n- [ ] Step 5: Edits applied based on diagnostic results\n- [ ] Step 6: Stems mixed together\n- [ ] Step 7: Deliverable exported AND verified (MANDATORY)\n- [ ] Final file exists at expected path with correct format (48k\u002F24b WAV)\n","# Diagnostic Stem Audio Production Workflow\n\nThis skill provides a resilient pattern for audio production that emphasizes **diagnostic analysis before editing**, **explicit timecode extraction from documents**, **incremental verification**, **fail-fast principles**, and **mandatory deliverable verification**. Each major step produces verified outputs before proceeding, with comprehensive audio diagnostics at specified timecodes.\n\n## Overview\n\nFollow these steps in strict order. Each step must complete successfully and pass verification before proceeding to the next:\n\n1. **Parse timecodes from source documents** - Extract edit spots\u002Ftimecodes from DOCX\u002Ftext sources\n2. **Perform diagnostic audio analysis** - Analyze reference audio at each timecode (pitch, clicks, frequency)\n3. **Calculate timing parameters** - Derive section transitions from BPM and duration\n4. **Verify reference audio** - Validate input file properties and extract target duration\n5. **Generate and verify each stem individually** - One stem at a time with immediate verification\n6. **Detect and resolve duration mismatches** - Apply appropriate extension strategy\n7. **Apply edits based on diagnostics** - Make informed edits using analysis results\n8. **Mix with verification** - Combine stems and verify mix integrity\n9. **Export and verify deliverable** - Generate final output with comprehensive checks\n\n## Key Principles\n\n- **Diagnostics first**: Analyze audio at edit points BEFORE making any changes\n- **Document-driven**: Parse timecodes directly from source documents (DOCX, TXT)\n- **Incremental verification**: Verify each stem immediately after generation\n- **Fail-fast approach**: Stop and report errors at each step\n- **Mandatory export**: Final step MUST produce verified deliverable file\n- **Tool reliability**: Use run_shell with inline Python for audio processing (avoid execute_code_sandbox for audio)\n\n## Step 0: Parse Timecodes from Source Documents\n\nExtract edit spots and timecodes from document sources. Use python-docx via run_shell for reliable DOCX parsing:\n\n```bash\n# Parse DOCX file for timecodes and edit spots\npython3 -c \"\nfrom docx import Document\nimport re\nimport sys\n\ndoc_path = sys.argv[1] if len(sys.argv) > 1 else 'Bass Edit Spots.docx'\ndoc = Document(doc_path)\n\nedit_spots = []\ntimecode_pattern = r'(\\d{1,2}:?\\d{2}:?\\d{2}[.:\\d]*)|(\\d+[.:\\d]+)s'\n\nfor para in doc.paragraphs:\n    text = para.text.strip()\n    if not text:\n        continue\n    \n    # Look for timecodes in various formats\n    matches = re.findall(timecode_pattern, text, re.IGNORECASE)\n    if matches:\n        for match in matches:\n            timecode = match[0] if match[0] else match[1]\n            if timecode:\n                edit_spots.append({'timecode': timecode, 'context': text[:100]})\n    \n    # Also check tables\n    for table in doc.tables:\n        for row in table.rows:\n            for cell in row.cells:\n                cell_text = cell.text.strip()\n                matches = re.findall(timecode_pattern, cell_text, re.IGNORECASE)\n                for match in matches:\n                    timecode = match[0] if match[0] else match[1]\n                    if timecode:\n                        edit_spots.append({'timecode': timecode, 'context': cell_text[:100]})\n\nprint(f'Found {len(edit_spots)} edit spots:')\nfor i, spot in enumerate(edit_spots, 1):\n    print(f'{i}. {spot[\\\"timecode\\\"]} - {spot[\\\"context\\\"][:50]}...')\n\"\n```\n\n## Step 1: Perform Diagnostic Audio Analysis at Timecodes\n\nBefore any editing, analyze the reference audio at each identified timecode:\n\n```python\nimport numpy as np\nimport soundfile as sf\nimport librosa\n\ndef analyze_audio_at_timecode(filepath, timecode_str, sample_rate=48000):\n    \"\"\"\n    Perform comprehensive diagnostic analysis at a specific timecode.\n    \n    Returns dict with:\n    - pitch_estimate: Dominant frequency\u002Fpitch\n    - click_pop_score: Likelihood of clicks\u002Fpops (0-1, higher = more likely)\n    - frequency_spectrum: Dominant frequency bands\n    - amplitude: RMS amplitude at timecode\n    - issues: List of detected issues\n    \"\"\"\n    # Parse timecode to seconds\n    timecode_str = timecode_str.replace(':', '.').strip()\n    if 's' in timecode_str:\n        timecode_str = timecode_str.replace('s', '')\n    \n    try:\n        parts = timecode_str.split('.')\n        if len(parts) == 3:\n            seconds = int(parts[0]) * 3600 + int(parts[1]) * 60 + float(parts[2])\n        elif len(parts) == 2:\n            seconds = int(parts[0]) * 60 + float(parts[1])\n        else:\n            seconds = float(parts[0])\n    except:\n        return {'error': f'Invalid timecode format: {timecode_str}'}\n    \n    # Load audio\n    data, sr = sf.read(filepath)\n    if sr != sample_rate:\n        data = librosa.resample(data, orig_sr=sr, target_sr=sample_rate)\n        sr = sample_rate\n    \n    # Extract window around timecode (±50ms for analysis)\n    window_samples = int(0.1 * sample_rate)  # 100ms window\n    start_sample = max(0, int(seconds * sample_rate) - window_samples \u002F\u002F 2)\n    end_sample = min(len(data), start_sample + window_samples)\n    window = data[start_sample:end_sample]\n    \n    if len(window) \u003C 100:\n        return {'error': 'Window too short for analysis'}\n    \n    # Pitch detection (using autocorrelation for monophonic content)\n    def estimate_pitch(signal, sr):\n        # Simple autocorrelation-based pitch detection\n        signal = signal - np.mean(signal)  # DC removal\n        autocorr = np.correlate(signal, signal, mode='full')\n        autocorr = autocorr[len(autocorr)\u002F\u002F2:]\n        \n        # Find first significant peak after zero lag\n        for i in range(1, min(len(autocorr) \u002F\u002F 2, int(sr \u002F 50))):\n            if autocorr[i] > 0.3 * autocorr[0]:\n                for j in range(i + 1, min(len(autocorr), int(sr \u002F 20))):\n                    if autocorr[j] > autocorr[i]:\n                        period = j\n                        freq = sr \u002F period\n                        return freq\n        return None\n    \n    pitch = estimate_pitch(window, sr)\n    \n    # Click\u002Fpop detection (sudden amplitude changes)\n    def detect_clicks(signal):\n        diff = np.diff(np.abs(signal))\n        threshold = 5 * np.std(diff)\n        click_positions = np.where(np.abs(diff) > threshold)[0]\n        click_score = min(1.0, len(click_positions) \u002F len(signal) * 1000)\n        return click_score, click_positions\n    \n    click_score, click_positions = detect_clicks(window)\n    \n    # Frequency analysis\n    spectrum = np.abs(np.fft.rfft(window))\n    freqs = np.fft.rfftfreq(len(window), 1\u002Fsr)\n    dominant_freqs = []\n    for band in [(20, 200, 'sub'), (200, 2000, 'mid'), (2000, 20000, 'high')]:\n        mask = (freqs >= band[0]) & (freqs \u003C band[1])\n        if np.any(mask):\n            band_power = np.sum(spectrum[mask])\n            dominant_freqs.append({'range': f'{band[0]}-{band[1]}Hz', 'power': float(band_power), 'label': band[2]})\n    dominant_freqs.sort(key=lambda x: x['power'], reverse=True)\n    \n    # Amplitude\n    rms = np.sqrt(np.mean(window ** 2))\n    \n    # Detect issues\n    issues = []\n    if click_score > 0.3:\n        issues.append(f'High click\u002Fpop probability ({click_score:.2f})')\n    if rms \u003C 0.001:\n        issues.append('Near-silence detected')\n    if rms > 0.9:\n        issues.append('Potential clipping')\n    if pitch and pitch \u003C 40:\n        issues.append(f'Very low frequency content ({pitch:.1f}Hz)')\n    \n    return {\n        'timecode': timecode_str,\n        'seconds': seconds,\n        'pitch_hz': pitch,\n        'click_pop_score': click_score,\n        'frequency_spectrum': dominant_freqs[:3],\n        'amplitude_rms': float(rms),\n        'issues': issues,\n        'window_length': len(window)\n    }\n\n# Analyze all edit spots\n# edit_spots from Step 0\nfor i, spot in enumerate(edit_spots):\n    print(f'\\\\n=== Analyzing edit spot {i+1}: {spot[\"timecode\"]} ===')\n    analysis = analyze_audio_at_timecode('reference.wav', spot['timecode'])\n    if 'error' in analysis:\n        print(f'ERROR: {analysis[\"error\"]}')\n    else:\n        print(f'Pitch: {analysis[\"pitch_hz\"]} Hz' if analysis[\"pitch_hz\"] else 'Pitch: N\u002FA (complex\u002Fnoisy)')\n        print(f'Click\u002FPop Score: {analysis[\"click_pop_score\"]:.3f} (0=none, 1=certain)')\n        print(f'Amplitude (RMS): {analysis[\"amplitude_rms\"]:.6f}')\n        if analysis['issues']:\n            print(f'Issues: {\", \".join(analysis[\"issues\"])}')\n        for freq in analysis['frequency_spectrum']:\n            print(f'  {freq[\"label\"]} band ({freq[\"range\"]}): power={freq[\"power\"]:.2f}')\n```\n\n## Step 2: Calculate Timing Parameters (Early)\n\nCalculate all timing parameters **before** generating any audio:\n\n```python\ndef calculate_section_transitions(bpm, total_duration_sec, sections):\n    \"\"\"Calculate beat-aligned transition points for song sections.\"\"\"\n    beats_per_second = bpm \u002F 60.0\n    \n    section_durations = {}\n    cumulative_time = 0\n    \n    for section_name, beat_count in sections.items():\n        duration = beat_count \u002F beats_per_second\n        section_durations[section_name] = {\n            'start': cumulative_time,\n            'end': cumulative_time + duration,\n            'beats': beat_count,\n            'start_beat': cumulative_time * beats_per_second\n        }\n        cumulative_time += duration\n    \n    return section_durations\n\n# Configuration\nBPM = 120\nDURATION = 137\nSECTIONS = {'intro': 16, 'verse': 32, 'chorus': 32, 'bridge': 16, 'outro': 16}\n\ntiming = calculate_section_transitions(BPM, DURATION, SECTIONS)\nprint('Timing calculated:')\nfor section, data in timing.items():\n    print(f'  {section}: {data[\"start\"]:.2f}s - {data[\"end\"]:.2f}s ({data[\"beats\"]} beats)')\n```\n\n## Step 3: Verify Reference Audio\n\nValidate the reference file exists and has expected properties:\n\n```python\nimport soundfile as sf\nimport os\n\ndef verify_reference_file(filepath, expected_sample_rate=None, min_duration=None):\n    \"\"\"Verify reference audio file and return info dict.\"\"\"\n    if not os.path.exists(filepath):\n        raise FileNotFoundError(f'Reference file not found: {filepath}')\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if expected_sample_rate and info.samplerate != expected_sample_rate:\n        errors.append(f'Sample rate mismatch: expected {expected_sample_rate}, got {info.samplerate}')\n    \n    if min_duration and info.duration \u003C min_duration:\n        errors.append(f'Duration too short: expected >= {min_duration}s, got {info.duration}s')\n    \n    if errors:\n        raise ValueError(f'Reference file validation failed: {\"; \".join(errors)}')\n    \n    print(f'Reference verified: {info.duration:.2f}s @ {info.samplerate}Hz, {info.channels}ch, {info.subtype}')\n    return {\n        'sample_rate': info.samplerate,\n        'duration': info.duration,\n        'channels': info.channels,\n        'subtype': info.subtype\n    }\n\n# Verify reference\nref_info = verify_reference_file('reference.wav', expected_sample_rate=48000, min_duration=130)\nTARGET_DURATION = ref_info['duration']  # Use actual reference duration as target\n```\n\n## Step 4: Generate and Verify Each Stem Individually\n\nGenerate one stem at a time, verify it immediately before proceeding to the next:\n\n```python\nimport numpy as np\n\ndef generate_stem(name, duration_sec, sample_rate, subtype='FLOAT', section_timing=None):\n    \"\"\"Generate a single stem with explicit sample type.\"\"\"\n    frames = int(duration_sec * sample_rate)\n    t = np.linspace(0, duration_sec, frames)\n    \n    # Generate stem-specific content (customize per stem type)\n    if name == 'bass':\n        freq = 110  # A2\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.8\n    elif name == 'guitars':\n        freq = 440  # A4\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.6\n    elif name == 'synths':\n        freq = 880  # A5\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.5\n    elif name == 'bridge':\n        freq = 220  # A3\n        audio_data = np.sin(2 * np.pi * freq * t) * 0.7\n    else:\n        audio_data = np.sin(2 * np.pi * 440 * t) * 0.5\n    \n    # Ensure proper data type\n    if subtype == 'FLOAT':\n        audio_data = audio_data.astype(np.float32)\n    elif subtype == 'PCM_24':\n        audio_data = np.clip(audio_data, -1, 1) * (2**23 - 1)\n        audio_data = audio_data.astype(np.int32)\n    \n    filepath = f'{name}_stem.wav'\n    sf.write(filepath, audio_data, sample_rate, subtype=subtype, format='WAV')\n    \n    return filepath, audio_data\n\ndef verify_stem(filepath, expected_sample_rate, expected_duration, tolerance_sec=1.0):\n    \"\"\"Verify a single stem meets specifications.\"\"\"\n    if not os.path.exists(filepath):\n        return {'success': False, 'error': f'File not found: {filepath}'}\n    \n    info = sf.info(filepath)\n    errors = []\n    \n    if info.samplerate != expected_sample_rate:\n        errors.append(f'sample_rate: expected {expected_sample_rate}, got {info.samplerate}')\n    \n    if abs(info.duration - expected_duration) > tolerance_sec:\n        errors.append(f'duration: expected ~{expected_duration}s, got {info.duration}s')\n    \n    if errors:\n        return {'success': False, 'error': '; '.join(errors)}\n    \n    return {'success': True, 'info': info}\n\n# Generate stems one at a time with verification\nSAMPLE_RATE = 48000\nSTEM_NAMES = ['bass', 'guitars', 'synths', 'bridge']\n\ngenerated_stems = []\nstem_info = {}\n\nfor stem_name in STEM_NAMES:\n    print(f'\\\\n=== Generating {stem_name} stem ===')\n    \n    # Generate\n    filepath, data = generate_stem(stem_name, DURATION, SAMPLE_RATE, subtype='FLOAT')\n    \n    # Verify immediately\n    result = verify_stem(filepath, SAMPLE_RATE, TARGET_DURATION)\n    \n    if result['success']:\n        print(f'✓ {stem_name} stem verified: {result[\"info\"].duration:.2f}s @ {result[\"info\"].samplerate}Hz')\n        generated_stems.append(filepath)\n        stem_info[stem_name] = result\n    else:\n        print(f'✗ {stem_name} stem FAILED: {result[\"error\"]}')\n        raise RuntimeError(f'Stem generation failed for {stem_name}: {result[\"error\"]}')\n\nprint(f'\\\\nAll {len(generated_stems)} stems generated and verified successfully')\n```\n\n## Step 5: Apply Edits Based on Diagnostics\n\nUse the diagnostic analysis from Step 1 to make informed editing decisions:\n\n```python\ndef apply_edit_based_on_diagnostics(stem_filepath, edit_spot, analysis, output_filepath):\n    \"\"\"\n    Apply targeted edit at a specific timecode based on diagnostic analysis.\n    \n    Decisions based on diagnostics:\n    - High click\u002Fpop score (>0.3): Apply fade or click removal\n    - Very low pitch (\u003C40Hz): May need high-pass filter\n    - Near-silence: Consider removal or gain adjustment\n    - Potential clipping: Apply gain reduction\n    \"\"\"\n    data, sr = sf.read(stem_filepath)\n    \n    timecode_sec = analysis['seconds']\n    edit_start = max(0, int((timecode_sec - 0.05) * sr))\n    edit_end = min(len(data), int((timecode_sec + 0.05) * sr))\n    \n    # Apply edits based on diagnostics\n    if analysis['click_pop_score'] > 0.3:\n        # Apply short crossfade to smooth clicks\n        fade_len = min(100, (edit_end - edit_start) \u002F\u002F 4)\n        if fade_len > 0:\n            fade_in = np.linspace(0, 1, fade_len)\n            fade_out = np.linspace(1, 0, fade_len)\n            data[edit_start:edit_start + fade_len] *= fade_in\n            data[edit_end - fade_len:edit_end] *= fade_out\n        print(f'  Applied click smoothing at {timecode_sec:.2f}s')\n    \n    if analysis['amplitude_rms'] > 0.9:\n        # Apply gentle gain reduction to prevent clipping\n        gain = 0.8\n        data[edit_start:edit_end] *= gain\n        print(f'  Applied gain reduction ({gain:.1f}x) at {timecode_sec:.2f}s')\n    \n    # Save edited stem\n    sf.write(output_filepath, data, sr, subtype='FLOAT', format='WAV')\n    return output_filepath\n\n# Apply edits to stems based on diagnostic analysis\nfor stem_name in ['bass']:  # Customize as needed\n    stem_file = f'{stem_name}_stem.wav'\n    edited_file = f'{stem_name}_stem_edited.wav'\n    \n    print(f'\\\\n=== Applying edits to {stem_name} based on diagnostics ===')\n    \n    for i, spot in enumerate(edit_spots):\n        # Re-analyze or use cached analysis\n        analysis = analyze_audio_at_timecode('reference.wav', spot['timecode'])\n        if 'error' not in analysis:\n            apply_edit_based_on_diagnostics(stem_file, spot, analysis, edited_file)\n    \n    print(f'Edited {stem_name} stem saved to {edited_file}')\n```\n\n## Step 6: Mix with Verification\n\nCombine all stems and verify mix integrity:\n\n```python\ndef mix_stems(stem_files, output_filepath, sample_rate=48000):\n    \"\"\"Mix multiple stems into a single output file.\"\"\"\n    mixed_data = None\n    \n    for stem_file in stem_files:\n        if not os.path.exists(stem_file):\n            raise FileNotFoundError(f'Stem not found: {stem_file}')\n        \n        data, sr = sf.read(stem_file)\n        \n        # Resample if needed\n        if sr != sample_rate:\n            data = librosa.resample(data, orig_sr=sr, target_sr=sample_rate)\n        \n        # Ensure same length\n        if mixed_data is None:\n            mixed_data = np.zeros(len(data), dtype=np.float32)\n        elif len(data) != len(mixed_data):\n            min_len = min(len(data), len(mixed_data))\n            mixed_data = mixed_data[:min_len]\n            data = data[:min_len]\n        \n        mixed_data += data\n    \n    # Normalize to prevent clipping\n    if np.max(np.abs(mixed_data)) > 0.95:\n        mixed_data *= 0.95 \u002F np.max(np.abs(mixed_data))\n    \n    sf.write(output_filepath, mixed_data, sample_rate, subtype='FLOAT', format='WAV')\n    \n    return {\n        'filepath': output_filepath,\n        'duration': len(mixed_data) \u002F sample_rate,\n        'peak': float(np.max(np.abs(mixed_data))),\n        'rms': float(np.sqrt(np.mean(mixed_data ** 2)))\n    }\n\n# Mix all stems\nprint('\\\\n=== Mixing all stems ===')\nall_stems = [f'{name}_stem_edited.wav' if os.path.exists(f'{name}_stem_edited.wav') \n             else f'{name}_stem.wav' for name in STEM_NAMES]\n\nmix_info = mix_stems(all_stems, 'State_of_Affairs_FULL_EDIT_MIX.wav')\nprint(f'Mix complete: {mix_info[\"duration\"]:.2f}s, peak={mix_info[\"peak\"]:.3f}, RMS={mix_info[\"rms\"]:.6f}')\n```\n\n## Step 7: Export and Verify Deliverable (MANDATORY)\n\n**This step MUST complete successfully** - no task is complete without verified deliverable:\n\n```python\ndef verify_deliverable(filepath, required_sample_rate=48000, required_channels=None, min_duration=None):\n    \"\"\"\n    Comprehensive verification of final deliverable.\n    \n    Returns dict with verification status and details.\n    Task CANNOT complete if verification fails.\n    \"\"\"\n    if not os.path.exists(filepath):\n        return {\n            'success': False,\n            'error': f'DELIVERABLE MISSING: {filepath}',\n            'blocking': True\n        }\n    \n    try:\n        info = sf.info(filepath)\n    except Exception as e:\n        return {\n            'success': False,\n            'error': f'DELIVERABLE CORRUPT: {str(e)}',\n            'blocking': True\n        }\n    \n    errors = []\n    warnings = []\n    \n    # Critical checks (blocking)\n    if info.samplerate != required_sample_rate:\n        errors.append(f'CRITICAL: Sample rate {info.samplerate}Hz != required {required_sample_rate}Hz')\n    \n    if required_channels and info.channels != required_channels:\n        errors.append(f'CRITICAL: Channels {info.channels} != required {required_channels}')\n    \n    if min_duration and info.duration \u003C min_duration:\n        errors.append(f'CRITICAL: Duration {info.duration:.2f}s \u003C minimum {min_duration}s')\n    \n    # Verify file is not empty\n    if info.duration \u003C 0.1:\n        errors.append('CRITICAL: File appears to be empty or silent')\n    \n    # Non-critical checks (warnings)\n    if info.duration \u003C 60:\n        warnings.append(f'Short duration: {info.duration:.2f}s')\n    \n    if os.path.getsize(filepath) \u003C 1000:\n        warnings.append('File size unusually small')\n    \n    # Load and analyze audio content\n    data, sr = sf.read(filepath)\n    peak = np.max(np.abs(data))\n    rms = np.sqrt(np.mean(data ** 2))\n    \n    if peak > 0.99:\n        warnings.append(f'Potential clipping: peak={peak:.4f}')\n    \n    if rms \u003C 0.001:\n        errors.append('CRITICAL: Audio appears to be silent (RMS too low)')\n    \n    # Final verdict\n    success = len(errors) == 0\n    \n    result = {\n        'success': success,\n        'blocking': not success,\n        'filepath': filepath,\n        'info': {\n            'duration': info.duration,\n            'sample_rate': info.samplerate,\n            'channels': info.channels,\n            'subtype': info.subtype,\n            'format': info.format,\n            'peak': float(peak),\n            'rms': float(rms),\n            'file_size': os.path.getsize(filepath)\n        },\n        'errors': errors,\n        'warnings': warnings\n    }\n    \n    return result\n\n# MANDATORY deliverable verification\nprint('\\\\n=== DELIVERABLE VERIFICATION (MANDATORY) ===')\ndeliverable_path = 'State_of_Affairs_FULL_EDIT_MIX.wav'\n\nverification = verify_deliverable(\n    deliverable_path,\n    required_sample_rate=48000,\n    required_channels=2,  # stereo\n    min_duration=60  # minimum 60 seconds\n)\n\nif verification['success']:\n    print('✓ DELIVERABLE VERIFIED SUCCESSFULLY')\n    print(f'  File: {verification[\"filepath\"]}')\n    print(f'  Duration: {verification[\"info\"][\"duration\"]:.2f}s')\n    print(f'  Sample Rate: {verification[\"info\"][\"sample_rate\"]}Hz')\n    print(f'  Channels: {verification[\"info\"][\"channels\"]}')\n    print(f'  Peak: {verification[\"info\"][\"peak\"]:.4f}')\n    print(f'  RMS: {verification[\"info\"][\"rms\"]:.6f}')\n    \n    if verification['warnings']:\n        print('  Warnings:')\n        for warn in verification['warnings']:\n            print(f'    ⚠ {warn}')\n    \n    print('\\\\n✓ TASK COMPLETE - All deliverables verified')\n    \nelse:\n    print('✗ DELIVERABLE VERIFICATION FAILED')\n    print('  ERRORS (blocking):')\n    for err in verification['errors']:\n        print(f'    ✗ {err}')\n    \n    if verification['warnings']:\n        print('  Warnings:')\n        for warn in verification['warnings']:\n            print(f'    ⚠ {warn}')\n    \n    raise RuntimeError(f'Task cannot complete: {verification[\"errors\"]}')\n```\n\n## Tool Usage Notes\n\n**Critical for reliability:**\n\n1. **DOCX Parsing**: Use `run_shell` with `python3 -c` inline syntax and python-docx, NOT `read_file` (returns 'unknown error' for .docx)\n\n2. **Audio Processing**: Use `run_shell` with inline Python scripts for audio operations, NOT `execute_code_sandbox` (frequently returns 'unknown error')\n\n3. **Heredoc Workaround**: Avoid complex heredoc syntax in shell; use simpler `-c` inline Python for reliability\n\nExample reliable pattern:\n```bash\npython3 -c \"import soundfile as sf; import numpy as np; ...your code...\"\n```\n\n## Checklist Before Completion\n\n- [ ] Step 0: Timecodes parsed from document source\n- [ ] Step 1: Diagnostic analysis performed at all edit spots\n- [ ] Step 2: Timing parameters calculated\n- [ ] Step 3: Reference audio verified\n- [ ] Step 4: All stems generated and verified individually\n- [ ] Step 5: Edits applied based on diagnostic results\n- [ ] Step 6: Stems mixed together\n- [ ] Step 7: Deliverable exported AND verified (MANDATORY)\n- [ ] Final file exists at expected path with correct format (48k\u002F24b WAV)\n",{"name":5,"description":7},"main","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Faudio-track-production-enhanced-enhanced-enhanced",944,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot","https:\u002F\u002Fgithub.com\u002FHKUDS","https:\u002F\u002Fsites.google.com\u002Fview\u002Fchaoh","2026-11-12 22:26:39",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add HKUDS\u002FAgentPilot --skill diagnostic-stem-delivery",{"tool":55,"command":56},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill diagnostic-stem-delivery",{"tool":58,"command":59},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill diagnostic-stem-delivery","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Faudio-track-production-enhanced-enhanced-enhanced\u002FSKILL.md",true,[63],{"path":64,"resourceType":65,"resourceTypeDesc":66,"sizeBytes":67,"sourceHtmlUrl":68},".skill_id","OTHER","其他",63,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Faudio-track-production-enhanced-enhanced-enhanced\u002F.skill_id",[70,89,108,131,155,178],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":36},"01M6HYB297NDABRERJRVG0K8R0","agentpilot","Set up AgentPilot and use its single entry to prepare missing inputs and run configured RSI experiments. Use when the user requests AgentPilot installation or work with AgentPilot.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fplugins\u002Fagentpilot\u002Fskills\u002Fagentpilot\u002FSKILL.md",[],[72,77,78,34,79,80,81,82,83,84,85,86,87,88],"prepare","requests","missing","installation","rsi","up","use","user","work","SET","run","experiments",{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":36},"01M6HYAYWXTTE1J7DJM0MFNQ4H","remember","Review auto-memory entries and propose promotions to OPENSPACE.md, OPENSPACE.local.md, or retained auto-memory topics; detect duplicates, stale facts, conflicts, and ambiguous entries before making changes.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fskills\u002Fremember\u002FSKILL.md",[],[91,96,97,98,99,100,101,102,103,104,105,106,107],"memory","review","auto","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":117,"publishedAt":36},"01M6HYAVMPM4SBDV60R2B5HPV8","skill-discovery","Search reusable OpenSpace skills locally, and browse cloud packages step by step when a cloud skill may help. Reusing proven skills saves tokens, improves reliability, and extends your capabilities beyond built-in tools.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fskill-discovery\u002FSKILL.md",[114],{"categoryNo":115,"categoryName":116,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[118,119,120,99,121,122,123,124,125,126,127,128,129,130],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":138,"publishedAt":36},"01M6HYAR811B3RB0M50RBEDGN6","delegate-task","Delegate tasks to OpenSpace — a full-stack autonomous worker for coding, DevOps, web research, and desktop automation, backed by an extensive MCP tool and skill library. Skills auto-improve through use, reducing token consumption over time. A cloud community lets agents share and collectively evolve reusable skills.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fdelegate-task\u002FSKILL.md",[137],{"categoryNo":115,"categoryName":116,"taxonomyType":21,"taxonomyTypeDesc":22},[139,140,141,99,142,143,144,145,146,120,98,83,147,148,149,150,151,152,153,154],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","stack","for","share","tasks","automation","MCP",{"skillNo":156,"name":157,"nameZh":6,"description":158,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":159,"categories":160,"keywords":161,"publishedAt":36},"01M6HYAM9FSGV6E52AYENDQXYH","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[162,163,164,165,166,167,168,169,170,171,172,173,174,175,150,176,177],"write special chars ts check","write","check","type","files","filters","only","template","file","python","typescript","output","Existing","type-checking","errors","script",{"skillNo":179,"name":180,"nameZh":6,"description":181,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":182,"categories":183,"keywords":184,"publishedAt":36},"01M6HYAH05HGV7SVWSVR8PJRQD","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[185,186,163,34,150,177,187,188,189,190,191,169,170,192,193,171],"write special chars readback","readback","helper","post","via","scripts","read","verification","cleanup"]