with open("src/orchestrator_pm.py", "r", encoding="utf-8", newline="") as f: lines = f.readlines() # Find and replace the JSON parsing section new_lines = [] i = 0 while i < len(lines): line = lines[i] # Replace the old parsing section if "# 4. Parse JSON Output" in line: # Add new parsing code new_lines.append(" # 4. Parse JSON Output\n") new_lines.append(" try:\n") new_lines.append(" import sys\n") new_lines.append( ' sys.stderr.write(f"[DEBUG] generate_tracks response: {response[:300]}\\n")\n' ) new_lines.append(" sys.stderr.flush()\n") new_lines.append(" json_match = response.strip()\n") new_lines.append( ' # Handle mock_gemini_cli.py format: {"type": "message", "content": "[...]"}\n' ) new_lines.append(' if \'"content": "\' in json_match:\n') new_lines.append(" import re\n") new_lines.append( ' match = re.search(r\'"content"\\s*:\\s*"(\\[.*?\\])"\', json_match)\n' ) new_lines.append(" if match:\n") new_lines.append(" json_match = match.group(1)\n") new_lines.append(" # Handle markdown code blocks\n") new_lines.append(' if "```json" in json_match:\n') new_lines.append( ' json_match = json_match.split("```json")[1].split("```")[0].strip()\n' ) new_lines.append(' elif "```" in json_match:\n') new_lines.append( ' json_match = json_match.split("```")[1].split("```")[0].strip()\n' ) new_lines.append(" tracks: list[dict[str, Any]] = json.loads(json_match)\n") # Skip the old lines i += 1 while i < len(lines) and "tracks:" not in lines[i]: i += 1 else: new_lines.append(line) i += 1 with open("src/orchestrator_pm.py", "w", encoding="utf-8", newline="") as f: f.writelines(new_lines) print("Fixed orchestrator_pm.py")