# 🔧 autofix-theclaw v5.0 - 新功能使用示例

## 🎯 场景一：MRE 验证失败时的诊断报告生成

### 原始流程（v4.5）
```python
# MRE 执行失败
if mre_test_failed:
    # 只显示错误日志
    present(
        title="MRE 验证失败",
        content=exec_output  # ❌ 纯文本，用户难以理解
    )
    
    # 等待用户 /approve
    await_user_approval()
```

### v5.0 增强流程 ✨
```python
from autofix_theclaw.modules import diagnosis_reports as dr

# MRE 执行失败
if mre_test_failed:
    # [NEW] Step 1: AI 错误日志智能摘要
    error_analysis = elis_analyze(
        exec_output=exec_result.output,
        problem_type="CLI/Config"
    )
    
    # [NEW] Step 2: 生成交互式诊断报告
    diag_report_url = dr.generate_diagnosis_report_html(error_analysis)
    
    # Present with canvas
    canvas.snapshot(
        action="snapshot",
        javaScript=f"<script src='{dr.get_canvas_script_path()}'></script>",
        url=diag_report_url
    )
    
    # 展示给用户
    present_with_canvas(
        title="MRE 验证失败 - 诊断报告",
        canvas_ref="report_20260517_xxx",
        rollback_command=get_safe_rollback(error_analysis)
    )
```

### 📊 实际输出效果示例

用户将看到：

```
┌─────────────────────────────────────────┐
│ 🔍 OpenClaw 诊断报告                     │
│ Generated by autofix-theclaw v5.0      │
├─────────────────────────────────────────┤
│ ⚠️ Status: MRE Test Failed              │
│ Risk Level: Medium                      │
├─────────────────────────────────────────┤
│ 📋 问题概览                             │
│ ────────────────────────────────────────│
│ Problem Type: exec_timeout              │
│ Affected Tools: browser, exec           │
├─────────────────────────────────────────┤
│ 🔬 AI 根因分析                           │
│ ────────────────────────────────────────│
│ 核心问题：exec 命令未指定 pty=true       │
│                                         │
│ 可能原因：                               │
│ • 当前会话配置中缺少 pty 参数            │
│ • 目标命令需要交互式终端环境             │
├─────────────────────────────────────────┤
│ 🔧 修复建议                             │
│ ────────────────────────────────────────│
│ openclaw doctor --fix --pty=true        │
│                                         │
│ 📊 证据链分析：                         │
│ ✅ OpenClaw Docs (匹配度：0.85)         │
│ ✅ GitHub Issues (Issue #1234)          │
│ 🎯 置信度：92%                          │
├─────────────────────────────────────────┤
│ 🔙 回滚命令 (如需撤销):                 │
│ ────────────────────────────────────────│
│ openclaw gateway status                 │
│ openclaw doctor --fix --dry-run         │
└─────────────────────────────────────────┘
```

---

## 🎯 场景二：错误日志智能摘要（ELIS）集成

### 实现步骤

#### Step 1: 在 `MODULE_03_ValidationAction.md` 中添加

```markdown
### Path B: Code Verification (MRE - Minimal Reproducible Example) $\rightarrow$ L1 Loop (v5.0 Enhanced)
This path now includes self-healing loop with **Diagnosis Report Visualization** and **Error Log Intelligent Summary**!

1.  **Initial Test:** Proactively call `exec` with an MRE derived from search results.
2.  **Check Result:** Analyze the output:
    *   **Success (✅):** Proceed to **Step 5 Finalization**.
    *   **Failure (❌):** Trigger **L1 Error Analysis Loop**:
        a. **[NEW] Extract and Analyze Error (ELIS)**:
           ```python
           from autofix_theclaw.elis import analyze_error_logs
           
           analysis = analyze_error_logs(
               exec_output=exec_result.output,
               problem_context=problem_type,
               evidence_chain=evidence_data
           )
           ```
        b. **[NEW] Generate Diagnosis Report (Canvas)**:
           ```python
           from autofix_theclaw.dre import generate_diagnostic_report
           
           report_html = generate_diagnostic_report(analysis)
           canvas_url = f"/__openclaw__/canvas/documents/autofix_report_{timestamp}.html"
           
           write_to_canvas(canvas_url, content=report_html)
           ```
        c. **Present to User with Rollback Command**:
           ```python
           present_with_diagnosis_report(
               canvas_url=canvas_url,
               rollback_command=analysis.rollback_command,
               include_evidence_chain=True
           )
           ```
        d. **Await User Approval** (same as before) 🔄
        e. **Execute & Re-Test**: 在获得同意后，调用 `exec` 执行选定的修复命令，然后循环回到 Step 3 (Synthesis)。
```

#### Step 2: 创建辅助工具函数

创建文件 `~\.openclaw\workspace\skills\autofix-theclaw\tools\elis_helper.py`:

```python
"""
ELIS - Error Log Intelligent Summary Helper
用于在 MRE 失败时自动生成错误分析报告
"""

import json
from typing import Dict, Any

def analyze_error_logs(
    exec_output: str, 
    problem_context: str = "unknown",
    evidence_chain: Dict[str, Any] = None
) -> Dict[str, Any]:
    """
    使用 LLM 智能分析错误日志
    
    Args:
        exec_output: exec 命令的原始输出（包含错误信息）
        problem_context: 问题上下文（如："CLI/Config", "Tooling"）
        evidence_chain: 证据链数据（来自 MODULE_02_SearchChain）
    
    Returns:
        分析结果字典，包含 core_issue, causes[], fix_command, risk_level 等
    """
    # TODO: 集成到实际的 LLM 调用流程中
    # 当前版本返回示例结构
    
    analysis_result = {
        "core_issue": "待分析",  # AI 会填充
        "causes": [],            # AI 会填充的列表
        "fix_command": "",       # AI 会填充的命令
        "risk_level": "Medium",  # Critical/Medium/Low
        "confidence_score": 0.0, # 置信度 (0-1)
        "rollback_command": "# 暂无"
    }
    
    # TODO: 实际调用 LLM 进行错误分析
    # analysis_result = llm_call.analyze_error(
    #     context=f"{problem_context}: {exec_output}",
    #     system_prompt="""你是一位 OpenClaw 专家助手，请分析以下错误日志..."""
    # )
    
    return analysis_result

def generate_diagnostic_report_html(analysis: Dict[str, Any]) -> str:
    """
    生成诊断报告的 HTML 内容
    
    Args:
        analysis: analyze_error_logs() 返回的分析结果
    
    Returns:
        完整的 HTML 字符串
    """
    from resources.CanvasScript_DiagnosticReport import generate_diagnostic_report
    
    diag_data = {
        "riskLevel": analysis["risk_level"],
        "problemType": analysis.get("problem_type", "Unknown"),
        "affectedTools": [],  # TODO: 从 exec_output 提取
        "errorLogs": analysis.get("raw_error", ""),
        "rootCause": {
            "core_issue": analysis["core_issue"],
            "causes": analysis["causes"]
        },
        "fixCommand": analysis["fix_command"],
        "rollbackCommand": analysis.get("rollback_command", "# 暂无回滚命令"),
        "evidenceChain": {
            "docs_match": True,
            "gh_issue": None,
            "pattern_matches": [],
            "confidence_score": analysis.get("confidence_score", 0)
        }
    }
    
    return generate_diagnostic_report(diag_data)


if __name__ == "__main__":
    # 测试示例
    test_output = """
    ERROR: exec command failed with code 127
    Command not found: tail -f
    Reason: pty=true parameter is missing
    """
    
    result = analyze_error_logs(
        exec_output=test_output,
        problem_context="CLI/Config"
    )
    
    print(json.dumps(result, indent=2))
```

#### Step 3: Canvas 报告生成（自动）

创建文件 `~\.openclaw\workspace\skills\autofix-theclaw\tools\canvas_report_generator.py`:

```python
"""
Canvas 诊断报告生成器 (v5.0)
自动生成交互式的诊断报告 HTML 页面
"""

import json
from pathlib import Path

class CanvasReportGenerator:
    """
    Canvas 诊断报告生成器
    
    使用方式:
        generator = CanvasReportGenerator()
        report_url = generator.generate_report(diag_data, output_format="html")
    """
    
    def __init__(self):
        self.base_path = Path(__file__).parent.parent / "resources"
        self.script_path = self.base_path / "CanvasScript_DiagnosticReport.js"
    
    def generate_report(
        self, 
        diag_data: dict,
        output_format: str = "html",
        canvas_id: str = None
    ) -> str:
        """
        生成诊断报告
        
        Args:
            diag_data: 诊断数据字典（包含 riskLevel, problemType 等）
            output_format: 输出格式 ("html" or "png")
            canvas_id: Canvas 文档 ID（可选）
        
        Returns:
            报告 URL 或 HTML 内容
        """
        # 方式一：直接生成 HTML 字符串（推荐）
        from resources.CanvasScript_DiagnosticReport import generate_diagnostic_report
        
        html_content = generate_diagnostic_report(diag_data)
        
        # 如果指定了 canvas_id，则写入到 Canvas 文档
        if canvas_id:
            write_path = f"~\.openclaw\\canvas\\documents\\{canvas_id}.html"
            write(html_path=str(write_path), content=html_content)
            
            return f"/__openclaw__/canvas/documents/{canvas_id}/index.html"
        
        # 方式二：返回 HTML 字符串（用于直接展示）
        return html_content
    
    def generate_png_screenshot(self, canvas_url: str, **options) -> str:
        """
        生成 Canvas 的 PNG 截图（用于分享或存档）
        
        Args:
            canvas_url: Canvas URL (如：/__openclaw__/canvas/documents/reports/diag_xxx/index.html)
            **options: canvas.snapshot() 的其他选项
        
        Returns:
            PNG 图片路径（如：~/.openclaw/canvas/screenshots/diag_xxx.png）
        """
        # TODO: 调用 canvas.snapshot(action="snapshot", url=canvas_url, outputFormat="png", ...)
        # 返回截图路径
        return f"~\.openclaw\\canvas\\screenshots\\diagnosis_{canvas_url.split('/')[-1]}.png"


# 便捷函数 - 在 autofix-theclaw 模块顶层导出
def generate_diagnosis_report(
    diag_data: dict, 
    output_format: str = "html"
) -> str:
    """
    快捷生成诊断报告（用于直接嵌入回答）
    
    Example:
        report_html = generate_diagnosis_report({
            "riskLevel": "Medium",
            "problemType": "exec_timeout",
            "affectedTools": ["browser", "exec"],
            "errorLogs": "...",
            "rootCause": {"core_issue": "..."},
            "fixCommand": "openclaw doctor --fix --pty=true",
            "rollbackCommand": "# 回滚命令..."
        })
        
        # 直接展示在回答中（使用 [embed]）
        present(
            title="MRE 验证失败 - 诊断报告",
            content="[embed url=\"data:text/html;base64,...\" title=\"Report\" height=\"800\"]"
        )
    """
    generator = CanvasReportGenerator()
    return generator.generate_report(diag_data, output_format=output_format)


if __name__ == "__main__":
    # 测试生成诊断报告
    test_report = generate_diagnosis_report({
        "riskLevel": "Medium",
        "problemType": "exec_timeout",
        "affectedTools": ["browser", "exec"],
        "errorLogs": "ERROR: Command failed with code 127\nReason: pty=true missing",
        "rootCause": {
            "core_issue": "exec 命令未指定 pty=true",
            "causes": [
                "当前会话配置中缺少 pty 参数",
                "目标命令需要交互式终端环境"
            ]
        },
        "fixCommand": "openclaw doctor --fix --pty=true --yieldMs=15000",
        "rollbackCommand": "openclaw gateway status\n# If needed: git checkout HEAD~1 -- .openclaw/"
    })
    
    print(f"Generated report (length: {len(test_report)} chars)")
```

---

## 📊 集成检查清单

在将新功能集成到现有工作流时，请确保：

- [ ] **MODULE_03_Enhancement_Reports.md**已创建并阅读
- [ ] **CanvasScript_DiagnosticReport.js**文件已存在且可访问
- [ ] `MODULE_03_ValidationAction.md` 的 Path B 逻辑已更新（包含 ELIS）
- [ ] `SKILL.md` 主控文档已标注 v5.0 版本及新功能
- [ ] Canvas 报告 HTML 生成测试通过
- [ ] 回滚命令的安全性已通过验证（--dry-run 测试）

---

## 🚀 下一步：开始实施

按照以下优先级实施：

1. **立即（今天）**：集成 `MODULE_03_Enhancement_Reports.md`文档到现有工作流
2. **短期（本周）**：创建 ELIS 工具函数（见示例代码）
3. **中期（本月）**：完成 Canvas 报告自动生成功能
4. **长期**：添加用户自定义诊断报告样式选项

---

*此示例文档将随 autofix-theclaw v5.0 一同发布并持续更新。*
