---
name: scheduler-merge-conflict-fix
description: 修复 Hermes Agent cron/scheduler.py 中两类破坏 Python 语法的问题：① Git 合并冲突标记残留；② for 循环外引用循环内才定义的变量（scope 错误）。恢复 cron/WebUI 正常启动。
category: devops
tags: [hermes, python, git, merge-conflict, bug-fix]
---

# scheduler.py Git Merge Conflict 修复

## 问题症状

启动 Hermes WebUI 时报错：
```
File "/root/.hermes/hermes-agent/cron/scheduler.py", line 530
<<<<<<< Updated upstream
SyntaxError: invalid syntax
```

或 lint 报错：
```
SyntaxError: expected 'except' or 'finally' block
```

WebUI / cronjob 服务无法启动，健康检查返回 unreachable。

## 根本原因

`/root/.hermes/hermes-agent/cron/scheduler.py` 中残留 Git 合并冲突标记：
- `<<<<<<< Updated upstream` — 开始标记
- `=======` — 分隔线
- `>>>>>>> Stashed changes` — 结束标记

这些标记破坏了 Python 语法，导致 `cron/__init__.py` 无法 import `scheduler`。

## 诊断步骤

```bash
# 1. 验证语法错误
python3 -m py_compile /root/.hermes/hermes-agent/cron/scheduler.py

# 2. 搜索所有冲突标记
grep -n "<<<<\|>>>>\|====" /root/.hermes/hermes-agent/cron/scheduler.py

# 3. 检查 git 状态
cd /root/.hermes/hermes-agent && git status cron/scheduler.py
git diff cron/scheduler.py
```

## 修复原则

1. **保留"Stashed changes"（新代码）**：这是 pull/rebase 后保留的修改，通常是更完整的实现
2. **删除冲突标记**：包括 `<<<<<<< Updated upstream`、`=======`、`>>>>>>> Stashed changes`
3. **检查 try-except 配对**：冲突解决时容易遗漏 `try:` 对应的 `except` 子句，需用 `grep -n "except\|finally" scheduler.py` 验证

## 典型修复案例

### 案例一：Git 合并冲突标记残留（保留 Stashed changes）

冲突标记删除后，如 `try:` 块缺少 `except`，Python 会报 `expected 'except' or 'finally' block`：

```python
# 修复前（try 块无 except）
if runtime_adapter is not None and loop is not None and getattr(loop, "is_running", lambda: False)():
    send_metadata = {"thread_id": thread_id} if thread_id else None
    try:
        text_to_send = cleaned_delivery_content.strip()
        adapter_ok = True
        if text_to_send:
            future = asyncio.run_coroutine_threadsafe(...)
            send_result = future.result(timeout=60)
            ...
            adapter_ok = False  # ← SyntaxError: expected 'except' or 'finally'

    delivery_errors = []

# 修复后：补全 except
        except Exception:
            logger.warning(
                "Job '%s': live adapter send to %s:%s raised exception, falling back to standalone",
                job["id"], platform_name, chat_id, traceback.format_exc(),
            )
            adapter_ok = False

    delivery_errors = []
```

### 案例二：for 循环外引用循环内变量（scope 错误）

错误信息：`cannot access local variable 'platform' where it is not associated with a value`

**根本原因**：代码在 for 循环**之前**放置了一段引用循环变量（`platform`、`platform_name`、`chat_id`、`thread_id`）的代码。这段代码看似是"提前准备"，但实际在循环变量定义前就执行了。

**典型错误模式**：
```python
# _deliver_result() 函数内
def _deliver_result(job: dict, content: str, adapters=None, loop=None):
    ...
    from gateway.platforms.base import BasePlatformAdapter
    media_files, cleaned_delivery_content = BasePlatformAdapter.extract_media(delivery_content)

    # ❌ 错误：platform、platform_name、chat_id、thread_id 尚未定义
    runtime_adapter = (adapters or {}).get(platform)
    logger.debug("Job '%s': delivery probe — platform=%s ...", job["id"], platform, ...)
    if runtime_adapter is not None and loop is not None and getattr(loop, "is_running", lambda: False)():
        ...
        logger.warning("Job '%s': live adapter send to %s:%s failed ...", job["id"], platform_name, chat_id, err)
        ...

    delivery_errors = []   # ← 这里之后才进入 for 循环

    for target in targets:  # ← 循环变量在这里才定义
        platform_name = target["platform"]
        chat_id = target["chat_id"]
        ...
```

**修复方案**：删除循环前的死代码段（第 532-562 行）。平台发送逻辑本就在 for 循环内已有完整实现（第 607-678 行），那段"提前执行"的代码既多余又无法正确执行。

**诊断技巧**：
- 错误在 cron 任务投递时报出（`Delivery failed for job XXXX: cannot access local variable 'platform'...`）
- 但任务执行本身成功，问题出在 `send_message_tool` 投递阶段
- 搜索 `scheduler.py` 确认无循环前置引用

**验证**：
```bash
python3 -m py_compile /root/.hermes/hermes-agent/cron/scheduler.py && echo "Syntax OK"
python3 -c "from cron import scheduler; print('Import OK')"
curl http://127.0.0.1:6266/health
```

## 验证步骤

```bash
# 1. 语法检查
python3 -m py_compile /root/.hermes/hermes-agent/cron/scheduler.py && echo "Syntax OK"

# 2. 模块导入测试
python3 -c "from cron import scheduler; print('Import OK')"

# 3. 启动 WebUI
cd /root/hermes-webui && HERMES_WEBUI_PORT=6266 ./ctl.sh start
./ctl.sh status

# 4. 健康检查
curl http://127.0.0.1:6266/health
```

## 预防措施

- Git merge/rebase 操作后，立即运行 `python3 -m py_compile` 检查关键模块语法
- 冲突解决后，优先保留功能更完整的一侧（通常是新代码）
- 涉及 `try:` 块的冲突，特别检查是否遗漏 `except` 或 `finally`
