Task configuration:
{"task_id": "11", "task_name": "set_layer_order", "description": "\u5728QGIS\u4e2d\u8c03\u6574\u56fe\u5c42\u6b21\u5e8f", "application_info": {"name": "QGIS", "executable_path": "/home/agent/qgis/QGIS/build-master/output/bin/qgis", "args": []}, "mcp_servers": [{"command": "python", "args": ["/home/agent/agent-demo/PC-Canary/tests/context_data/QGIS/qgis_config/qgis_mcp/qgis_mcp_server.py"]}], "context_data": [{"from": "tests/context_data/QGIS/qgis_sample_data", "to": "/home/agent/testbed/QGIS"}, {"from": "tests/context_data/QGIS/qgis_config", "to": "/home/agent/.local/share/QGIS"}], "task_parameters": {"LayerOrder": " lake,landcover"}, "instruction_template": "\u5728QGIS\u4e2d\u8c03\u6574\u56fe\u5c42\u6b21\u5e8f,\u6b21\u5e8f\u4e3a${LayerOrder}(\u81ea\u9876\u5411\u4e0b\uff0c\u7531,\u5206\u9694)", "evaluation_setup": {"scripts": [{"role": "hook", "path": "hooker.js"}, {"role": "handler", "path": "handler.py"}], "timeout": 180}, "total_key_steps": 1, "events": {"script_initialized": {"description": "\u94a9\u5b50\u811a\u672c\u521d\u59cb\u5316", "is_key_step": false}, "setOrder_function_found": {"description": "\u627e\u5230\u66f4\u6539\u56fe\u5c42\u6b21\u5e8f\u51fd\u6570", "is_key_step": false}, "order_set": {"description": "\u68c0\u6d4b\u5230\u65b0\u7684\u56fe\u5c42\u6b21\u5e8f", "is_key_step": true, "key_step_index": 1, "key_step_name": "\u9884\u671f\u56fe\u5c42\u6b21\u5e8f\u5df2\u8bbe\u7f6e"}, "error": {"description": "\u6765\u81ea\u811a\u672c\u7684\u9519\u8bef\u4e8b\u4ef6", "is_key_step": false}}}

Hook script:
// QGIS调整图层次序钩子脚本
// 用于监听QGIS的调整图层次序操作并检测相关参数

(function() {
    // 脚本常量设置
    const SYMBOL_NAME = "_ZN12QgsLayerTree19setCustomLayerOrderERK5QListIP11QgsMapLayerE"; // QgsLayerTree::setCustomLayerOrder的函数符号
    
    // 向评估系统发送事件
    function sendEvent(eventType, data = {}) {
        const payload = {
            event: eventType,
            ...data,
            timestamp: new Date().getTime()
        };
        send(payload);
    }
    
    const HEADER_SIZE = 24;   
    const SIZE_OFFSET = 4;                  

    function qstringToString(qstr) {
        try {
            const d = qstr.readPointer();                         // QString::d
            const len = d.add(SIZE_OFFSET).readU32();             // QStringData::size
            const data = d.add(HEADER_SIZE);                      // first UTF‑16 char
            return Memory.readUtf16String(data, len);
        } catch (error) {
            console.log("解析QString失败:", error);
            return "";
        }
    }

    // 初始化钩子并立即执行
    function initHook() {
        sendEvent("script_initialized", {
            message: "QGIS图层次序监控脚本已启动"
        });
        
        // 查找setCustomLayerOrder函数
        let setOrderAddr = Module.findExportByName(null, SYMBOL_NAME);
        
        // 如果没找到，尝试扫描所有加载的模块
        if (!setOrderAddr) {
            sendEvent("function_search_start", {
                message: "正在查找QgsLayerTree::setCustomLayerOrder函数..."
            });
            
            // 遍历模块
            Process.enumerateModules({
                onMatch: function(module) {
                    if (module.name.includes("qgis_core")) {
                        sendEvent("module_found", {
                            module_name: module.name,
                            base_address: module.base.toString()
                        });
                        
                        // 在qgis模块中查找符号
                        const symbol = module.findExportByName(SYMBOL_NAME);
                        if (symbol) {
                            setOrderAddr = symbol;
                        }
                    }
                },
                onComplete: function() {}
            });
            
            // 如果仍未找到，报告错误
            if (!setOrderAddr) {
                sendEvent("error", {
                    error_type: "function_not_found",
                    message: "无法找到QgsLayerTree::setCustomLayerOrder函数"
                });
                return;
            }
        }
        
        // 报告找到函数
        sendEvent("setOrder_function_found", {
            address: setOrderAddr.toString(),
            message: "找到QgsLayerTree::setCustomLayerOrder函数"
        });
        
        // 安装钩子
        Interceptor.attach(setOrderAddr, {
            onEnter: function(args) {
                try {
                    // 获取QList<QgsMapLayer *>参数
                    const qlistPtr = args[1]; // 参数数组的第二个参数(customLayerOrder)
                    
                    // 读取QList的begin和end，计算元素个数
                    const begin = qlistPtr.readPointer().add(0x8).readU32();
                    const end = qlistPtr.readPointer().add(0xc).readU32();
                    const count = end - begin;
                    console.log(`图层次序列表包含 ${count} 个图层`);
                    
                    // 提取所有图层的名称
                    const layerNames = [];
                    
                    for (let i = 0; i < count; i++) {
                        // 计算当前元素在QList中的偏移
                        const elementOffset = 0x10 + (i * Process.pointerSize);
                        // 读取当前图层指针
                        const layerPtr = qlistPtr.readPointer().add(elementOffset).readPointer();
                        // 读取图层名称 (偏移0x20处是图层名称的QString)
                        const nameQString = layerPtr.add(0x20);
                        const name = qstringToString(nameQString);
                        
                        layerNames.push(name);
                        console.log(`图层 ${i+1}: ${name}`);
                    }
                    
                    // 发送事件通知
                    sendEvent("order_set", {
                        layer_count: count,
                        layer_names: layerNames,
                        order_string: layerNames.join(','),
                        message: `检测到图层次序变更: ${layerNames.join(',')}`
                    });
                } catch (error) {
                    sendEvent("error", {
                        error_type: "hook_execution_error",
                        message: `执行钩子时出错: ${error.message}`,
                        stack: error.stack
                    });
                }
            }
        });
        
        sendEvent("hook_installed", {
            message: "钩子安装完成，等待图层次序调整操作..."
        });
    }
    
    // 立即执行钩子初始化
    initHook();
})();

Evaluation handler:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
QGIS调整图层次序事件处理器
负责处理钩子脚本产生的事件并更新评估指标
"""

import os
from typing import Dict, Any, Optional, List

def message_handler(message: Dict[str, Any], logger: Any, task_parameter: Dict[str, Any]) -> Optional[List[Dict[str, Any]]]:
    """
    处理从钩子脚本接收的消息
    
    Args:
        message: Frida消息对象
        logger: 日志记录器
        task_parameter: 任务参数
        
    Returns:
        Optional[List[Dict[str, Any]]]: 如果任务状态有更新返回状态列表，否则返回None
    """

    # 处理消息
    if message.get('type') == 'send' and 'payload' in message:
        payload = message['payload']
        
        # 检查是否包含事件类型
        if 'event' in payload:
            event_type = payload['event']
            logger.debug(f"接收到事件: {event_type}")
            
            # 处理特定事件
            if event_type == "script_initialized":
                logger.info(f"钩子脚本初始化: {payload.get('message', '')}")
                return None
                
            elif event_type == "setOrder_function_found":
                logger.info(f"找到设置图层次序函数: {payload.get('address', '')}")
                return None
                
            elif event_type == "order_set":
                layer_names = payload.get("layer_names", [])
                order_string = payload.get("order_string", "")
                count = payload.get("layer_count", 0)
                
                logger.info(f"检测到图层次序变更: 共{count}个图层, 顺序为: {order_string}")
                
                # 检查图层次序是否匹配预期
                expected_order = task_parameter.get("LayerOrder", "").strip()
                expected_layers = [layer.strip() for layer in expected_order.split(",")]
                
                logger.debug(f"比较图层次序 - 检测到: {layer_names}, 预期: {expected_layers}")
                
                # 判断检测到的图层次序是否与预期相符
                # 这里只比较图层名称是否包含预期名称，顺序也必须一致
                match = True
                if len(layer_names) >= len(expected_layers):
                    for i, expected_layer in enumerate(expected_layers):
                        found = False
                        for actual_layer in layer_names:
                            if expected_layer.lower() in actual_layer.lower():
                                found = True
                                # 确保顺序一致
                                if layer_names.index(actual_layer) != i:
                                    logger.info(f"图层 {expected_layer} 顺序不匹配")
                                    match = False
                                break
                        if not found:
                            logger.info(f"未找到预期图层: {expected_layer}")
                            match = False
                else:
                    logger.info(f"图层数量不匹配。预期: 至少{len(expected_layers)}层, 实际: {len(layer_names)}层")
                    match = False
                
                if match:
                    logger.info("图层次序匹配预期目标!")                    
                    # 返回关键步骤和成功状态
                    return [
                        {"status": "key_step", "index": 1, "name": "预期图层次序已设置"},
                        {"status": "success", "reason": f"成功设置图层次序: {order_string}"}
                    ]
                else:
                    logger.info(f"图层次序与预期不符。预期: {expected_order}, 实际: {order_string}")
                
            elif event_type == "error":
                error_type = payload.get("error_type", "unknown")
                error_message = payload.get("message", "未知错误")
                logger.error(f"钩子脚本错误 ({error_type}): {error_message}")
                
                # 返回错误状态
                return [{
                    "status": "error",
                    "type": error_type,
                    "message": error_message
                }]
                
    elif message.get('type') == 'error':
        stack = message.get('stack', '')
        logger.error(f"钩子脚本错误: {stack}")
        
        # 返回错误状态
        return [{
            "status": "error",
            "type": "script_error",
            "message": "钩子脚本执行错误",
            "stack_trace": stack
        }]
    
    return None