diff --git a/.env.example b/.env.example index efa5c02..f30adbf 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,5 @@ -# ── 运行模式(对应 adapter 四档,见 references/ADAPTER.md)── -OPENCLAW_TEST_TARGET=simulator_rpa # mock | simulator_rpa | real_api | real_rpa +# ── 运行模式 / adapter 档位(见 references/ADAPTER.md)── +OPENCLAW_TEST_TARGET=mock # mock | simulator_rpa | real_api | real_rpa # ── 目标系统 ── TARGET_BASE_URL=https://sandbox.jc2009.com # 仿真/生产地址,可被进程环境变量覆盖 diff --git a/README.md b/README.md index 7c87d5e..59c19bd 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ python scripts/main.py version - `jiangchang-platform-kit`、`playwright`、config、runtime diagnostics、RPA 公共能力等由**宿主共享 runtime** 提供;`jiangchang_skill_core` **不在技能仓库内复制**。 - 新技能**不得 vendored** `scripts/jiangchang_skill_core/`;复制模板后若发现该目录,应删除并改为依赖共享 venv。 - 在技能**根目录**维护 `requirements.txt`,**只声明技能特有** Python 三方包;**不要**重复声明 `jiangchang-platform-kit` 或 `playwright`。 -- `SKILL.md` 的 `metadata.openclaw.platform_kit_min_version`(如 `1.0.11`)是运行契约/兼容性声明,供宿主安装与启用时校验,**不是** pip 依赖声明。 +- `SKILL.md` 的 `metadata.openclaw.platform_kit_min_version`(当前 `1.0.13`)是运行契约/兼容性声明,供宿主安装与启用时校验,**不是** pip 依赖声明。`jiangchang-platform-kit>=1.0.13` 是当前 RPA 视频/旁白/背景音乐/前后缓冲等标准能力的最低版本。 - 匠厂宿主在**安装或更新**技能后,会将技能 `requirements.txt` 中的依赖安装到共享 Python runtime: `{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`(Windows 示例:`D:\jiangchang-data\python-runtime\.venv`)。 - **Skill 业务代码不得自动 `pip install`**;缺依赖时应在 `health` / preflight 中给出清晰错误。 diff --git a/SKILL.md b/SKILL.md index 90e53e9..f367721 100644 --- a/SKILL.md +++ b/SKILL.md @@ -6,7 +6,7 @@ author: 深圳匠厂科技有限公司 metadata: openclaw: slug: your-skill-slug - platform_kit_min_version: "1.0.11" + platform_kit_min_version: "1.0.13" emoji: "📦" category: "通用" developer_ids: @@ -45,10 +45,10 @@ python {baseDir}/scripts/main.py version ## 运行依赖 - Python 运行环境由匠厂宿主注入**共享 runtime**:`{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`。 -- 公共能力来自共享 runtime 安装的 `jiangchang-platform-kit>=1.0.11`(`jiangchang_skill_core` 包);**新技能不得**在仓库内保留 `scripts/jiangchang_skill_core/` 副本。 +- 公共能力来自共享 runtime 安装的 `jiangchang-platform-kit>=1.0.13`(`jiangchang_skill_core` 包);**新技能不得**在仓库内保留 `scripts/jiangchang_skill_core/` 副本。 - config、logging、runtime_env、rpa、media-assets、video_session、runtime_diagnostics 等均从共享 venv 的 `jiangchang_skill_core` import,而非技能目录副本。 - 根目录 `requirements.txt` **只声明技能特有** Python 三方依赖;`jiangchang-platform-kit`、`playwright` 等公共能力由宿主共享 runtime 提供,**不要**写入技能 requirements。宿主安装/更新技能后会将技能 requirements 安装到共享 venv。 -- `metadata.openclaw.platform_kit_min_version`(当前 `1.0.11`)是运行契约/兼容性声明,供宿主安装与启用时校验,**不是**技能 pip 依赖声明。 +- `metadata.openclaw.platform_kit_min_version`(当前 `1.0.13`)是运行契约/兼容性声明,供宿主安装与启用时校验,**不是**技能 pip 依赖声明。`jiangchang-platform-kit>=1.0.13` 是当前 RPA 视频/旁白/背景音乐/前后缓冲等标准能力的最低版本。 - Skill 代码**不要**自行 `pip install`;系统级依赖(如 VC++ Runtime)仅在 `health` / preflight 中提示用户安装。 - `health` 使用 `collect_runtime_diagnostics` 输出统一 runtime 诊断(只读,不下载/修复 media-assets)。 diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..d4413ff --- /dev/null +++ b/pytest.ini @@ -0,0 +1,8 @@ +[pytest] +testpaths = tests +python_files = test_*.py *_test.py +python_classes = Test* +python_functions = test_* +norecursedirs = .git __pycache__ .pytest_cache integration desktop samples fixtures artifacts diagnostics +filterwarnings = + ignore::DeprecationWarning diff --git a/references/ADAPTER.md b/references/ADAPTER.md index 2a31169..ab7486b 100644 --- a/references/ADAPTER.md +++ b/references/ADAPTER.md @@ -1,6 +1,6 @@ # 适配器标准:真实/仿真 × API/RPA 四档模式 -> 凡是"连接三方系统"(ERP、CRM、SaaS、银行等)的 skill,都应采用本文的 **adapter 四档模式**。这样同一套业务逻辑可以在不同档位间切换:开发用仿真、CI 用 mock、上线用真实,互不影响。 +> 凡是"连接三方系统"(ERP、CRM、SaaS、银行等)的 skill,都应采用本文的 **adapter 四档模式**。这样同一套业务逻辑可以在不同档位间切换:开发用 mock、半集成用 simulator、上线用真实,互不影响。 ## 为什么要分档 @@ -9,104 +9,97 @@ | | API(有接口) | RPA(操作界面) | |---|---|---| | **真实系统** | `real_api` 真实 API | `real_rpa` 真实界面 | -| **仿真系统** | `mock` 离线仿真 | `sim_rpa` 仿真平台界面 | +| **仿真/离线** | `mock` 纯内存/fixture | `simulator_rpa` 仿真站点/桌面仿真 | + +### 四档定义 + +| 档位 | 含义 | 默认策略 | +|------|------|----------| +| **`mock`** | 纯内存或 fixture,**默认单测/CI** | 模板 `.env.example` 默认 `OPENCLAW_TEST_TARGET=mock` | +| **`simulator_rpa`** | 仿真站点或桌面仿真,可半集成 | 开发联调可选 | +| **`real_api`** | 真实 API | **必须** `ALLOW_REAL_API=1` | +| **`real_rpa`** | 真实浏览器/真实系统 | **必须** `ALLOW_REAL_RPA=1` | - **mock**:纯离线、不联网,给单测 / CI / 开发自测,**保证可重复**。 -- **sim_rpa**:操作仿真平台(如 `sandbox.jc2009.com`),跑真实端到端流程但不碰生产,**默认开发档位**。 +- **simulator_rpa**:操作仿真平台(如 `sandbox.jc2009.com`),跑端到端流程但不碰生产。 - **real_api**:有官方接口时**首选**(最稳、最快、最易维护)。 - **real_rpa**:没有 API 只能操作生产界面,**风险最高、放最后**。 -> 推荐优先级:**real_api > sim_rpa > real_rpa**,mock 永远保留做 CI。 +> 推荐优先级:**real_api > simulator_rpa > real_rpa**,mock 永远保留做 CI。 + +## 权限开关 + +未显式授权时**不得**落到真实 API/RPA: + +| 变量 | 作用 | +|------|------| +| `ALLOW_REAL_API=1` | 允许 `real_api` 访问真实 HTTP | +| `ALLOW_REAL_RPA=1` | 允许 `real_rpa` 驱动真实浏览器/RPA | +| `ALLOW_WRITE_ACTIONS=1` | 在 `real_*` 下允许**写**操作(提交表单、下单等) | + +进程环境变量优先于用户 `.env`(见 `CONFIG.md` 三层优先级)。 ## 目录骨架 -业务逻辑只依赖 `base` 里定义的接口与数据契约,具体档位实现各自一个文件: - ``` scripts/service/_adapter/ __init__.py # dispatch:按档位返回对应 adapter 实例 - base.py # 数据契约(dataclass)+ AdapterBase 接口(NotImplementedError) + base.py # 数据契约(dataclass)+ AdapterBase 接口 mock.py # 离线仿真,给 CI/单测 real_api.py # 真实系统 API - sim_rpa.py # 仿真平台 RPA(Playwright/pywinauto/uiautomator2) + sim_rpa.py # 仿真平台 RPA real_rpa.py # 真实系统 RPA(占位,谨慎实现) ``` -> 参考实现:`disburse-payroll-icbc/scripts/service/disburse_adapter/`(已有 `base.py` / `mock.py` / `icbc_simulator_rpa.py`)。 -> 模板示例:`scripts/service/example_adapter/`(复制改名即用)。 - -### 引用方式 - -```python -from service.example_adapter import get_adapter -from service.example_adapter.base import ExampleItem - -adapter = get_adapter() # 由 OPENCLAW_TEST_TARGET 决定档位 -result = adapter.do_batch( - target="https://sandbox.jc2009.com", - items=[ExampleItem(id="1", label="demo")], -) -``` - -mock 档位纯离线验证: - -```bash -set OPENCLAW_TEST_TARGET=mock -python -c "import sys; sys.path.insert(0,'scripts'); from service.example_adapter import get_adapter; from service.example_adapter.base import ExampleItem; r=get_adapter().do_batch('x',[ExampleItem('1','a')]); print(r.ok, r.serial_no)" -``` - -## base.py 写法(要点) - -1. **数据契约用 `@dataclass`**:输入项(如 `PayrollItem`)、批量结果(如 `BatchResult{ok, serial_no, error_msg, artifacts}`)。 -2. **接口方法抛 `NotImplementedError`**:所有档位实现同一签名。 -3. **以"批"为单位返回**:真实 RPA 往往是整批提交,结果按批次返回,不要假设逐条。 -4. **结果里带 `artifacts`**:截图/录屏/日志路径,便于排查。 - -```python -@dataclass -class XxxResult: - ok: bool - serial_no: Optional[str] - error_msg: Optional[str] - artifacts: Dict[str, Any] = field(default_factory=dict) - -class AdapterBase: - name = "base" - def do_batch(self, target: str, items: list) -> XxxResult: - raise NotImplementedError -``` +模板示例:`scripts/service/example_adapter/`(复制改名即用)。 ## 档位 dispatch -由 `OPENCLAW_TEST_TARGET` 统一决定用哪个 adapter(与现有测试体系一致): +由 `OPENCLAW_TEST_TARGET` 统一决定用哪个 adapter: | `OPENCLAW_TEST_TARGET` | adapter | 用途 | |---|---|---| | `unit` / `mock` | `MockAdapter` | 单测 / CI,离线 | -| `simulator_rpa`(默认) | `SimRpaAdapter` | 开发/演示,操作仿真平台 | +| `simulator_rpa` | `SimRpaAdapter` | 开发/演示,操作仿真平台 | | `real_api` | `RealApiAdapter` | 生产,走官方接口 | -| `real_rpa` | `RealRpaAdapter` | 生产,操作真实界面(最后手段) | +| `real_rpa` | `RealRpaAdapter` | 生产,操作真实界面 | ```python # __init__.py def get_adapter(): - target = (os.environ.get("OPENCLAW_TEST_TARGET") or "simulator_rpa").lower() + target = (os.environ.get("OPENCLAW_TEST_TARGET") or "mock").lower() if target in ("unit", "mock"): return MockAdapter() if target == "real_api": return RealApiAdapter() if target == "real_rpa": return RealRpaAdapter() - return SimRpaAdapter() # 默认 + return SimRpaAdapter() ``` -> 实际可改为读 `.env` 里的运行模式(见 `CONFIG.md`),`OPENCLAW_TEST_TARGET` 作为进程级覆盖优先。 +`get_adapter()` 实现应配合 `tests/adapter_test_utils.py` 的 profile 策略:**未授权时不 silently 开启真实网络/RPA**。 -## 测试要求 +## contract tests -- **mock 档必须能纯离线跑通**,进 CI。 -- **每个 adapter 单测同一组用例**(契约测试),保证档位间行为一致。 -- RPA 档的真实联网测试单独标记,不进默认 CI(参考 `tests/desktop/`)。 +每个 adapter **必须覆盖同一套契约测试**(复制 `tests/samples/test_service_contract.py.sample`): + +- 至少覆盖:**timeout**、**unauthorized**、**invalid response**、**empty result** +- **mock 不允许真实网络** +- 使用 `FakeAdapter` 或等价 stub 模拟异常路径 + +## 兄弟依赖 + +依赖 account-manager 或其他兄弟技能时: + +1. 在 `SKILL.md` 的 `metadata.openclaw.dependencies.required` 声明。 +2. 调用兄弟技能走统一 **`service.sibling_bridge`**(`call_sibling_json`),**不要**在 service 层散落 `subprocess.run`。 +3. **lease 必须 release**(account-manager 租约);进程被 kill 后可能残留 lease,需在运维文档说明排查方式(查 account-manager lease 列表 / 手动释放)。 + +```python +from service.sibling_bridge import call_sibling_json + +result = call_sibling_json("account-manager", ["list", "--limit", "10"]) +``` ## 相关文档 diff --git a/references/CLI.md b/references/CLI.md index 6e13bf3..25a3102 100644 --- a/references/CLI.md +++ b/references/CLI.md @@ -1,4 +1,4 @@ -# 通用业务技能模板 CLI 模板 +# 通用业务技能模板 CLI 标准 将 `{baseDir}` 替换为技能根目录(含 `SKILL.md`、`scripts/` 的目录)。所有命令通过 `python {baseDir}/scripts/main.py` 调用。 @@ -10,9 +10,16 @@ python {baseDir}/scripts/main.py config-path python {baseDir}/scripts/main.py version ``` -## config-path(配置路径) +## 标准行为 -输出 JSON,便于排查用户 `.env` 落盘位置: +- **任意 CLI 启动前**执行 `bootstrap_skill_config()`(`main.py` 与 `cli.app.main()` 均触发)。 +- **`health`**:只读 runtime 诊断,**不下载、不修复 media-assets,不执行业务动作**;不输出敏感值。 +- **`config-path`**:输出 JSON,包含 `skill`、`env_path`、`example_path`。 +- **`version`**:输出 JSON(`version`、`skill`)。 +- **`run`**:长时间无 stdout **不代表卡死**;应通过 `logs` / `log-get` 排查。 +- **任务完成后**若有 video artifact,CLI 应打印录屏路径、录屏日志、视频/音频诊断(见 `task_run_support._print_video_summary`)。 + +## config-path(配置路径) ```json { @@ -22,55 +29,59 @@ python {baseDir}/scripts/main.py version } ``` -启动任意 CLI 命令前会自动执行 `bootstrap_skill_config()`(首次 copy `.env.example`,升级后合并缺失 key)。 - ## health 标准输出(runtime diagnostics) -`health` 委托 `jiangchang_skill_core.collect_runtime_diagnostics`,输出统一 runtime 诊断。典型字段: +`health` 委托 `jiangchang_skill_core.collect_runtime_diagnostics`,典型字段: - `python_executable` — 当前 Python 解释器路径 -- `platform_kit_version` / `platform_kit_min_version` — 已安装与要求的 platform-kit 版本 +- `platform_kit_version` / `platform_kit_min_version` / `platform_kit_version_ok` - `jiangchang_skill_core_file` — 公共库加载来源(若来自技能目录副本会报 warning) -- `media_assets_root` — 共享媒体资源根目录 -- `ffmpeg_path` / `ffmpeg_available` — ffmpeg 探测结果 -- `background_music_mp3_count` — 可用背景音乐数量 +- `media_assets_root`、`ffmpeg_path`、`ffmpeg_available`、`background_music_mp3_count` - `runtime_issue[warning|error]` — 非致命/致命问题列表 -- `env_path` / `env_exists` / `example_path` — 用户 `.env` 与仓库模板路径(不输出敏感值) - -`health` **只读诊断**,不下载、不修复 media-assets,不执行业务 DB / 邮箱 / 订单等检查。 +- `env_path` / `env_exists` / `example_path` — 用户 `.env` 与仓库模板路径 ## 通用业务命令骨架 -模板默认提供以下命令(复制后按需保留或扩展): - ```bash python {baseDir}/scripts/main.py run python {baseDir}/scripts/main.py run -t -i python {baseDir}/scripts/main.py logs -python {baseDir}/scripts/main.py logs --task-type disburse --status failed +python {baseDir}/scripts/main.py logs --task-type demo --status failed python {baseDir}/scripts/main.py log-get ``` -含义: -- `run`:执行一次任务(具体语义由你的 skill 决定) -- `logs`:列出最近 N 条任务日志,可按 task_type / status / target 过滤 -- `log-get`:按 log_id 查看单条任务日志(JSON) +| 命令 | 用途 | +|------|------| +| `run` | 执行一次任务 | +| `logs` | 列出最近 N 条任务日志 | +| `log-get` | 按 log_id 查看单条任务日志(JSON) | -## 若你的技能是发布类 +## 查询/导出类(可选) -可以把 `run` 命令对外别名为 `publish`,参数 `--target` 别名为 `--account-id`,参数 `--input-id` 保持不变。 +复制后按需增加,例如:`contacts`、`contact-get`、`export` 或业务等价命令。 ## 若你的技能依赖兄弟技能 -使用 `service.sibling_bridge.call_sibling_json(skill_slug, args)`,不要硬编码兄弟技能名到 sibling_bridge.py 自身。 +使用 `service.sibling_bridge.call_sibling_json(skill_slug, args)`,不要硬编码兄弟技能名到 `sibling_bridge.py` 自身;并在 `SKILL.md` 声明 `dependencies.required`。 -```bash -# 假设 base 与兄弟技能同级 -python {baseDir}/..//scripts/main.py ... +## 手工排查命令(推荐) + +**建议使用宿主共享 python-runtime**,避免技能目录内临时 venv 加载不到公共库: + +```text +Windows: + {JIANGCHANG_DATA_ROOT}\python-runtime\.venv\Scripts\python.exe {baseDir}\scripts\main.py health + +通用: + {baseDir}/scripts/main.py health ``` +`` 通常位于 `{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`。 + +**不建议**在生产/测试机使用技能目录内 `uv run python`,以免加载不到共享 runtime 中的 `jiangchang-platform-kit` / `playwright`。 + ## 模板约定 -- 最小模板至少保留 `health` / `version` +- 最小模板至少保留 `health` / `config-path` / `version` - 通用业务技能建议使用 `run` / `logs` / `log-get` - 不要再用旧模板的 `publish` / `--account-id` / `--article-id` 命名 diff --git a/references/CONFIG.md b/references/CONFIG.md index 8ff8f4b..ae0f166 100644 --- a/references/CONFIG.md +++ b/references/CONFIG.md @@ -4,23 +4,23 @@ ## 核心原则 -1. **`.env.example` 进仓库**:带注释的全量默认配置,是配置项的"单一事实来源"。 -2. **首次运行自动 copy**:`scripts/main.py` 启动与 `cli.app.main()` 均会调用 `util.config_bootstrap.bootstrap_skill_config()`,把仓库根目录 `.env.example` 复制到 +1. **三层优先级**:`进程环境变量` > `{数据目录}/.env` > 仓库 `.env.example` 默认值。 +2. **`.env.example` 进仓库**:带注释的全量默认配置,是配置项的"单一事实来源"。 +3. **首次运行自动 copy(bootstrap)**:`scripts/main.py` 启动与 `cli.app.main()` 均会调用 `util.config_bootstrap.bootstrap_skill_config()`,把仓库根目录 `.env.example` 复制到 `{CLAW_DATA_ROOT}/{user}/{slug}/.env`(**已存在则不整体覆盖**,保护用户改过的值)。 -3. **技能升级合并缺失项**:`merge_missing_env_keys` 会把 `.env.example` 中新增、但用户 `.env` 尚未包含的 key **追加**进去(带 `comment_skill` 注释块)。 -4. **三级优先级读取**:`进程环境变量` > `数据目录/.env` > `.env.example 默认值`。 +4. **技能升级合并缺失项**:`merge_missing_env_keys` 会把 `.env.example` 中新增、但用户 `.env` 尚未包含的 key **追加**进去(带注释块)。 5. **敏感信息绝不进 `.env`**:密码/密钥/口令走 account-manager 的 `secret-ref`(见下"红线")。 -## 标准配置项 +## 标准配置项(`.env` 分组) -每个 skill 的 `.env.example` 至少包含这些(按需增减): +每个 skill 的 `.env.example` 至少包含这些通用项(按需增减): ```ini -# ── 运行模式(对应 adapter 四档,见 ADAPTER.md)── -OPENCLAW_TEST_TARGET=simulator_rpa # mock | simulator_rpa | real_api | real_rpa +# ── 运行模式 / adapter 档位(见 ADAPTER.md)── +OPENCLAW_TEST_TARGET=mock # mock | simulator_rpa | real_api | real_rpa -# ── 目标系统 ── -TARGET_BASE_URL=https://sandbox.jc2009.com # 仿真/生产地址,可被进程环境变量覆盖 +# ── 目标系统(示例占位,复制后改为业务地址)── +TARGET_BASE_URL=https://sandbox.jc2009.com # ── 默认账号(仅非敏感标识;密码走 account-manager)── DEFAULT_LOGIN_ID=04110001 @@ -29,23 +29,24 @@ DEFAULT_LOGIN_ID=04110001 OPENCLAW_BROWSER_HEADLESS=0 # 0=有头(默认) 1=无头(CI) OPENCLAW_PLAYWRIGHT_STEALTH=1 # 1=开启反检测指纹(默认) -# ── 存证 ── -OPENCLAW_RECORD_VIDEO=1 # 1=录屏+字幕+背景音+MP4成片(RPA技能默认开,见 RPA.md) +# ── 录屏与失败存证 ── +OPENCLAW_RECORD_VIDEO=1 # 1=录屏+字幕+旁白+背景音+MP4(RPA 默认开,见 RPA.md) OPENCLAW_ARTIFACTS_ON_FAILURE=1 # 1=失败截图(默认) # ── 节流 / 超时 ── -STEP_DELAY_MIN=1.0 # 步骤间随机等待下限(秒) -STEP_DELAY_MAX=5.0 # 步骤间随机等待上限(秒) +STEP_DELAY_MIN=1.0 +STEP_DELAY_MAX=5.0 HUMAN_WAIT_TIMEOUT=180 # 滑块/验证码/2FA 等人工超时(秒) ``` +**业务专属配置必须带技能前缀**(如 `DEMO_XXX`、`MY_SKILL_XXX`),**不要污染全局命名空间**(禁止 `SCRAPE_1688_*`、`RECEIVE_ORDER_*` 等跨技能前缀写入模板)。 + ## 🚫 红线:敏感信息不进 `.env` -`.env` 只放**非敏感运行参数**(模式、地址、开关、超时)。密码、密钥、动态口令、token—— +`.env` 只放**非敏感运行参数**(模式、地址、开关、超时、账号标识)。密码、密钥、动态口令、token—— - 走 **account-manager** 注册凭据,用 `--secret-storage env --secret-ref XXX` 引用; -- 真实值由宿主/用户通过环境变量注入,**不落任何文件、不进 git**。 -- 参考 `disburse-payroll-icbc/scripts/cli/cmd_setup.py`:账号写入 account-manager,密码只登记 `secret-ref`(如 `ICBC_SIM_PASSWORD`)。 +- 真实值由宿主/用户通过进程环境变量注入,**不落任何文件、不进 git**。 `.gitignore` 必须包含: @@ -79,31 +80,16 @@ config.get_bool("OPENCLAW_BROWSER_HEADLESS") config.get_float("STEP_DELAY_MIN", 1.0) ``` -`config-path` 命令输出 JSON:`skill`、`env_path`(用户数据目录 `.env`)、`example_path`(仓库 `.env.example` 绝对路径)。 +## health / config-path -### 引用方式 +- **`health`**:输出 `collect_runtime_diagnostics` 字段(`platform_kit_version_ok`、`ffmpeg_path` 等),**不打印敏感值**;补充 `env_path` / `env_exists` / `example_path`。 +- **`config-path`**:输出 JSON,包含 `skill`、`env_path`(用户数据目录 `.env`)、`example_path`(仓库 `.env.example` 绝对路径),便于排查落盘位置。 -`jiangchang_skill_core.config` 来自共享 runtime 安装的 `jiangchang-platform-kit`;业务代码统一 `from jiangchang_skill_core import config`,**不要在技能内复制 config.py**: +## doctor / setup 命令(可选) -```python -from jiangchang_skill_core import config -from util.constants import SKILL_SLUG -from util.runtime_paths import get_skill_root -import os +每个 skill 可提供自检命令: -example = os.path.join(get_skill_root(), ".env.example") -config.ensure_env_file(SKILL_SLUG, example) - -headless = config.get_bool("OPENCLAW_BROWSER_HEADLESS") -target = config.get("TARGET_BASE_URL") -timeout = config.get_int("HUMAN_WAIT_TIMEOUT", 180) -``` - -## doctor / setup 命令 - -每个 skill 应提供自检命令(参考 `disburse` 的 `test_doctor`): - -- `python scripts/main.py doctor`:检查浏览器是否安装、Profile/账号是否就绪、`.env` 是否已落盘、设备(手机)是否连接。 +- `python scripts/main.py doctor`:检查浏览器、Profile/账号、`.env` 落盘、设备等。 - `python scripts/main.py setup`:初始化演示账号、首次落盘 `.env`。 ## 相关文档 diff --git a/references/DEVELOPMENT.md b/references/DEVELOPMENT.md index 043712e..49857e5 100644 --- a/references/DEVELOPMENT.md +++ b/references/DEVELOPMENT.md @@ -149,7 +149,7 @@ scripts/ - `util/` 作用:常量、日志、路径、时间工具、通用帮助函数 -公共能力(config、logging、runtime_env、rpa、media_assets、video_session、runtime_diagnostics)从共享 runtime 的 `jiangchang-platform-kit>=1.0.11` import,**不得**在 `scripts/` 下保留 `jiangchang_skill_core/` 副本。 +公共能力(config、logging、runtime_env、rpa、media_assets、video_session、runtime_diagnostics)从共享 runtime 的 `jiangchang-platform-kit>=1.0.13` import,**不得**在 `scripts/` 下保留 `jiangchang_skill_core/` 副本。 ## 3.2 开发 RPA 类 skill @@ -175,7 +175,7 @@ scripts/ 技能根目录的 `requirements.txt` 是**标准文件**,用于声明本技能**特有** Python 三方依赖。 - **公共依赖**(`jiangchang-platform-kit`、`playwright`、config、runtime diagnostics、RPA 公共能力等)由**宿主共享 runtime** 提供,**不要**写入技能 `requirements.txt`。 -- `SKILL.md` 的 `metadata.openclaw.platform_kit_min_version`(如 `1.0.11`)是运行契约/兼容性声明,供宿主安装与启用时校验,**不是** pip 依赖声明。 +- `SKILL.md` 的 `metadata.openclaw.platform_kit_min_version`(当前 `1.0.13`)是运行契约/兼容性声明,供宿主安装与启用时校验,**不是** pip 依赖声明。 - 匠厂宿主安装/更新技能后,会将技能 `requirements.txt` 安装到共享 venv:`{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`。 - **不要**在业务代码中 `subprocess` / `pip install`;缺依赖由 `health` 报错,由宿主负责安装。 - **版本约束尽量收窄**,降低多技能共享 venv 时的冲突风险。推荐范围写法: diff --git a/references/RPA.md b/references/RPA.md index 84c4b62..28e530f 100644 --- a/references/RPA.md +++ b/references/RPA.md @@ -28,33 +28,59 @@ ## 1. 浏览器(标准已成熟) -**选型:Playwright + 系统 Chrome/Edge。** 这是团队验证最充分的一条线(参考 `1688-scrape-contacts`、`disburse-payroll-icbc`)。 +**选型:Playwright + 系统 Chrome/Edge。** 这是团队验证最充分的一条线(标杆技能 `1688-scrape-contacts`、`receive-order` 已落地)。 + +### 1.0 生产路径(优先) | 项 | 标准 | |----|------| -| 驱动 | Playwright(Python) | -| 浏览器 | 系统已装 Chrome/Edge,`channel="chrome"`;**不用内置 Chromium,无需 `playwright install`** | -| 登录态 | `launch_persistent_context` + 用户 Profile 目录(由 account-manager 下发) | -| 模式 | 默认有头;`OPENCLAW_BROWSER_HEADLESS=1` 转无头 | -| 反反爬 | stealth 指纹注入 + 拟人输入/鼠标/延迟 + 滑块停下等人工(见下) | +| 浏览器 | **优先系统 Chrome/Edge** + `launch_persistent_context`,`channel="chrome"` 或 Edge;不用内置 Chromium,**技能内不要 `playwright install`** | +| 登录态 | 持久 Profile 目录;账号、profile、lease **统一走 account-manager**(或对应兄弟技能),不硬编码密码 | +| CDP | **仅作诊断 / 桌面宿主类场景**;**不要**作为强风控站点的默认生产路径 | +| 行为 | 模拟真实用户:真实点击、键盘、鼠标、地址栏输入;**不要**拼接搜索结果 URL、DOM 注入、`el.value=`、JS 跳转 | +| 模式 | 默认有头 `OPENCLAW_BROWSER_HEADLESS=0`;无头仅 CI | +| 反检测 | stealth 默认开 `OPENCLAW_PLAYWRIGHT_STEALTH=1`(见 1.1) | -### 1.1 防反爬三件套(必做) +### 1.1 Playwright 启动标准 -1. **指纹淡化(stealth)**:启动时 `add_init_script` 注入,抹平自动化特征—— - `navigator.webdriver=undefined`、`chrome.runtime`、`permissions.query`、`plugins`、`languages`、`hardwareConcurrency`、`deviceMemory`、WebGL vendor。 - 启动参数 `--disable-blink-features=AutomationControlled` + `ignore_default_args=["--enable-automation"]`。 - 开关:`OPENCLAW_PLAYWRIGHT_STEALTH`(默认开)。 -2. **拟人操作**: - - 输入:逐字符 `keyboard.type(delay=90~240ms)`,**先真实点击聚焦再输入,绝不 `el.value=`**。 - - 鼠标:贝塞尔曲线轨迹移动 + 微抖动;进场随机晃动 2~4 次。 - - 导航:用真实点击触发,**不要 `window.location.href=` / `el.click()` 这类 JS 跳转/点击**。 - - 翻页:真实点击翻页箭头,注意排除禁用态选择器。 - - 延迟:每步之间 `random_delay`。 -3. **风控页 = 停下等人工**:检测到滑块/拦截(URL 含 `punish/x5sec/baxia/tmd`,或 DOM 命中 `#nocaptcha/.nc-container/punish-component` 等)→ 抛 `ERROR:CAPTCHA_NEED_HUMAN`,轮询等人工通过或超时,**不自动操作滑块**。 +1. **默认有头**:`OPENCLAW_BROWSER_HEADLESS=0`(`.env.example` 默认值)。 +2. **stealth 默认开**:`OPENCLAW_PLAYWRIGHT_STEALTH=1`;通过 `add_init_script` 注入指纹淡化脚本。 +3. **不要在技能里自行安装 playwright**;由宿主共享 runtime 提供。 +4. **不要默认传 `--no-sandbox`**(除非特定容器环境且已评估风险)。 +5. **不要默认传 `--disable-blink-features=AutomationControlled`**;platform-kit stealth 已覆盖,额外 flag 可能适得其反。 +6. **可以** `ignore_default_args=["--enable-automation"]`(platform-kit `launch_persistent_browser` 已处理)。 +7. **强风控平台**:优先真实点击、键盘、鼠标、地址栏、持久 profile;**不要**直接拼接搜索结果 URL 或 DOM 注入。 -> 参考实现:`1688-scrape-contacts/scripts/service/anti_detect.py`、`util/playwright_stealth.py`、`service/login_service.py`(验证码等待)。已提升为共享库 `jiangchang_skill_core.rpa`(见 platform-kit)。 +指纹淡化(stealth)典型项:`navigator.webdriver=undefined`、`chrome.runtime`、`permissions.query`、`plugins`、`languages` 等。共享实现见 `jiangchang_skill_core.rpa`(platform-kit **>= 1.0.13**)。 -### 1.2 安装 +**拟人操作**(必做): + +- 输入:逐字符 `keyboard.type(delay=90~240ms)`,**先真实点击聚焦再输入,绝不 `el.value=`**。 +- 鼠标:贝塞尔曲线轨迹 + 微抖动;进场随机晃动。 +- 导航:用真实点击触发,**不要 `window.location.href=` / JS 点击跳转**。 +- 翻页:真实点击翻页控件,注意排除禁用态。 +- 延迟:每步之间 `random_delay`(`.env` 中 `STEP_DELAY_MIN/MAX`)。 + +### 1.2 页面启动标准 + +优先级(高 → 低): + +1. **launch args `start_url`**:浏览器启动即打开目标首页(推荐生产路径)。 +2. **profile preferences**:作为兜底(例如 homepage / startup URLs)。 +3. **程序化导航 `page.goto`**:仅最后兜底;强风控站点慎用裸 `goto` 深链。 + +**生产路径不要依赖 CDP 接管现有页面**;CDP 仅用于诊断或桌面宿主已打开浏览器的场景。 + +### 1.3 HITL / 验证码 + +- 自动处理失败时**允许等待人工**:滑块、短信、人脸、U盾、动态口令等。 +- 等待人工验证时必须有:**字幕 step**(用户可见动作说明)、**结构化日志**、**超时**(`HUMAN_WAIT_TIMEOUT`)。 +- 检测到风控页(URL/DOM 特征)→ 抛 `ERROR:CAPTCHA_NEED_HUMAN`,轮询等待或超时,**不要强行绕过平台安全机制**。 +- **不要自动操作滑块**。 + +> 共享库:`jiangchang_skill_core.rpa.wait_for_captcha_pass`;参考 `scripts/service/example_browser_rpa.py`。 + +### 1.4 安装 生产/宿主运行:`playwright` 由共享 runtime 提供,无需在技能内 `pip install`。 @@ -79,7 +105,7 @@ from jiangchang_skill_core.rpa import ( from jiangchang_skill_core.rpa.stealth import stealth_enabled, STEALTH_INIT_SCRIPT ``` -- `RpaVideoSession` 来自 platform-kit;ffmpeg、背景音乐、media-assets 由 platform-kit 统一解析。 +- `RpaVideoSession` 来自 platform-kit **>= 1.0.13**;ffmpeg、背景音乐、media-assets 由 platform-kit 统一解析;已提供前置/后置缓冲、字幕、TTS 旁白、背景音乐循环、结尾淡出。 - `health` 对上述资源做只读诊断,不下载、不修复。 完整示例见 `scripts/service/example_browser_rpa.py` 与 `scripts/service/example_adapter/sim_rpa.py`。 @@ -161,16 +187,48 @@ skill 退出/抛错统一用 `ERROR:` 前缀 + 稳定码,方便宿主与上层 --- -## 5. 存证规范 +## 5. 存证与录屏规范 + +### 5.1 截图存证 - **路径**:`{CLAW_DATA_ROOT}/{user}/{slug}/rpa-artifacts/{batch_id}/{tag}_{timestamp}.png` - **失败必截图**:受 `OPENCLAW_ARTIFACTS_ON_FAILURE`(默认开)控制。 -- **运行录屏成片**:RPA 型技能默认 `OPENCLAW_RECORD_VIDEO=1`,表示 **ffmpeg 录制运行过程** + 字幕 + 背景音乐 + 最终 MP4 **一体开启**。由 `RpaVideoSession` 统一触发,不在 CLI/E2E 单独实现。 - **Playwright 不负责录屏**,仅浏览器自动化。 +- **常见 tag**:`before_submit` / `after_submit` / `captcha` / `login_fail` / `error`。 + +### 5.2 RPA 视频 step 标准 + +字幕是**用户可见动作说明**,不是技术日志。step 要贴近真实动作,不要只在大流程入口打点。 + +推荐关键动作示例(按业务裁剪): + +- 启动浏览器 +- 打开首页 +- 检查登录状态 +- 定位输入框 +- 输入关键词:xxx +- 点击搜索 +- 等待结果 +- 打开详情页 +- 提取信息 +- 写入结果 +- 任务完成 + +技术诊断、重复跳过、DB 写入可以显示但**通常不需要旁白**。 + +`title` / `closing_title` 必须由 skill 传入**中文业务文案**(如「开始执行示例任务」「示例任务执行完成」)。 + +### 5.3 录屏成片标准 + +- RPA skill 默认 `OPENCLAW_RECORD_VIDEO=1`。 +- 使用 platform-kit 的 **`RpaVideoSession`**;**skill 不要自行合成视频**(不要自己调 ffmpeg 拼 MP4)。 +- `OPENCLAW_RECORD_VIDEO=0` 时 session 无副作用(不启 ffmpeg、不写字幕文件)。 - **ffmpeg 是唯一录屏器**(Windows:`gdigrab` + `desktop`)。 - **最终视频**:`{skill_data_dir}/videos/{skill_slug}_{yyyyMMdd_HHmmss}_{batch_id}.mp4` -- **中间产物**:`rpa-artifacts/{batch_id}/capture.mp4`、`subtitles/`、`logs/` 等,**不放最终 MP4**。 -- **常见 tag**:`before_submit` / `after_submit` / `captcha` / `login_fail` / `error`。 +- **中间产物**:`rpa-artifacts/{batch_id}/capture.mp4`、`subtitles/`、`logs/` 等。 +- 任务完成后 CLI / `result_summary` 应包含:`video_path`、`raw_video`、`video_log`、`video_warnings`、`music_path`、`voiceover_path`、`audio_warnings`(见 `scripts/service/task_run_support.py`)。 + +模板最小示范见 `scripts/service/task_service.py` 的 `_run_template_demo()`。 --- diff --git a/references/RUNTIME.md b/references/RUNTIME.md index 5dbdbdf..8294cfd 100644 --- a/references/RUNTIME.md +++ b/references/RUNTIME.md @@ -2,7 +2,7 @@ ## 共享 Python Runtime -**skill-template** 及复制出的新技能,公共能力均来自宿主匠厂安装的共享 Python Runtime(`jiangchang-platform-kit>=1.0.11` 及其传递依赖,含 `playwright`)。`jiangchang_skill_core` **不得**在技能仓库内 vendored,应由共享 venv 的 site-packages 提供。 +**skill-template** 及复制出的新技能,公共能力均来自宿主匠厂安装的共享 Python Runtime(`jiangchang-platform-kit>=1.0.13` 及其传递依赖,含 `playwright`)。`jiangchang_skill_core` **不得**在技能仓库内 vendored,应由共享 venv 的 site-packages 提供。 技能根目录 `requirements.txt` **只声明技能特有依赖**;**不要**重复声明 `jiangchang-platform-kit` 或 `playwright`。`SKILL.md` 的 `platform_kit_min_version` 是运行契约,**不是** pip 依赖声明。 @@ -24,7 +24,7 @@ Windows: `` 通常位于 `{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`。数据根由宿主注入;开发模式下也可能通过 `CLAW_DATA_ROOT` 解析(见 `jiangchang_skill_core.runtime_env`)。 -## Runtime 诊断(platform-kit 1.0.11+) +## Runtime 诊断(platform-kit 1.0.13+) `health` 命令通过 **`jiangchang_skill_core.collect_runtime_diagnostics`** 输出共享 runtime 诊断,**不在技能内重复实现**。典型字段: @@ -42,7 +42,7 @@ Windows: - 用户实际 `.env`:`{CLAW_DATA_ROOT}/{CLAW_USER_ID}/{skill_slug}/.env`。 - `scripts/main.py` 与 `cli.app.main()` 启动时调用 `util.config_bootstrap.bootstrap_skill_config()`。 - 配置优先级:**进程环境变量** > **用户 `.env`** > **`.env.example` 默认值**。 -- 公共 `config` / `merge_missing_env_keys` 来自共享 runtime 的 `jiangchang-platform-kit>=1.0.11`,**不得** vendored `scripts/jiangchang_skill_core/`。 +- 公共 `config` / `merge_missing_env_keys` 来自共享 runtime 的 `jiangchang-platform-kit>=1.0.13`,**不得** vendored `scripts/jiangchang_skill_core/`。 ## media-assets / ffmpeg / 背景音乐 diff --git a/references/TESTING.md b/references/TESTING.md index 5c8347c..14a4499 100644 --- a/references/TESTING.md +++ b/references/TESTING.md @@ -23,7 +23,7 @@ 必跑套件要像一个紧张的守门员:**快、确定、离线**。典型覆盖: - CLI:导入 [`cli.app`](../scripts/cli/app.py) 走解析链路、`health`(runtime diagnostics)/ `version` / `logs` / `log-get` 冒烟; -- 架构守护:无 `scripts/jiangchang_skill_core/`、`platform-kit>=1.0.11` 导入来源、文档/runtime 标准(见 `test_platform_import.py` 等); +- 架构守护:无 `scripts/jiangchang_skill_core/`、`platform-kit>=1.0.13` 导入来源、文档/runtime 标准(见 `test_platform_import.py` 等); - **真实 subprocess**:[`tests/test_entrypoint_subprocess.py`](../tests/test_entrypoint_subprocess.py) 再调用一遍 `python scripts/main.py`,防路径漂移; - 运行时:`runtime_paths` 与 **`CLAW_*` / `JIANGCHANG_*` 并发兜底; - `SKILL.md` YAML slug vs [`constants.SKILL_SLUG`](../scripts/util/constants.py); @@ -179,7 +179,53 @@ Golden fixture 流程同理([`tests/samples/test_golden_cases.py.sample`](../t --- -## 延伸阅读 +## 11. pytest 收集卫生标准 + +模板根目录提供 `pytest.ini`(或等价配置),约束: + +- **只收集** `test_*.py` / `*_test.py` +- **不让** `.txt`、结果文件、日志文件被 pytest 误收集 +- `norecursedirs` 排除 `integration/`、`desktop/`、`samples/`、`fixtures/`、`artifacts/`、`diagnostics/` + +测试结果文件**不要**放在 `tests/` 根目录;应放 `tests/artifacts/` 或 `tests/diagnostics/` 并加入 `.gitignore`。 + +默认 `python tests/run_tests.py` 仍只发现 `tests/` 根目录一层 `test_*.py`(不递归子目录),与 pytest 策略一致。 + +--- + +## 12. RPA / video 测试标准 + +- `RpaVideoSession` 调用**不跑真实 ffmpeg**:单测中使用 `unittest.mock` patch session 或设 `OPENCLAW_RECORD_VIDEO=0`。 +- 断言 `title` / `closing_title` 是**中文**业务文案。 +- 断言 video artifact 会进入 `result_summary`(`video_path`、`raw_video`、`video_log` 等)。 +- 断言 step 文案贴近用户动作,不是技术日志(如「准备执行示例任务」而非「enter cmd_run」)。 + +参考 `tests/test_video_service.py`。 + +--- + +## 13. 宿主 E2E 标准 + +- 使用 `jiangchang_desktop_sdk.e2e_helpers`(见 `tests/desktop/` 下 `.sample`)。 +- **不伪造**用户数据目录;通过宿主 IPC 获取真实 `skill_data_dir`。 +- E2E **不自动生成**真实密钥或生产凭证。 + +--- + +## 14. 测试前检查清单(模板守护) + +复制新 skill 或修改模板后,确认: + +- [ ] `requirements.txt` **不含** `jiangchang-platform-kit` / `playwright` +- [ ] 无 `scripts/jiangchang_skill_core/` vendored 副本 +- [ ] `platform_kit_min_version` **>= 1.0.13**(`SKILL.md` + `constants.py`) +- [ ] `health` 能输出 `platform_kit_version_ok`(或等价诊断行) +- [ ] `config-path` 可输出用户 `.env` 路径 JSON +- [ ] `pytest.ini` 存在且 `python_files` 只收集 `test_*.py` / `*_test.py` +- [ ] pytest **不会**误收集 `tests/` 下的 `.txt` / 日志 / 结果文件 +- [ ] `python tests/run_tests.py -v` 全部通过 + +--- - [`tests/README.md`](../tests/README.md) — 表格、变量与目录细则 - [`references/DEVELOPMENT.md`](DEVELOPMENT.md) §14.5 — 测试驱动的开发顺序 diff --git a/release.ps1 b/release.ps1 index 639081a..fb87d92 100644 --- a/release.ps1 +++ b/release.ps1 @@ -12,7 +12,7 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path -$sharedScript = Join-Path $scriptDir "..\jiangchang-platform-kit\tools\release.ps1" +$sharedScript = Join-Path $scriptDir "..\..\jiangchang-platform-kit\tools\release.ps1" $sharedScript = [System.IO.Path]::GetFullPath($sharedScript) if (-not (Test-Path $sharedScript)) { diff --git a/scripts/service/task_run_support.py b/scripts/service/task_run_support.py new file mode 100644 index 0000000..38e9e7e --- /dev/null +++ b/scripts/service/task_run_support.py @@ -0,0 +1,84 @@ +"""任务运行辅助:录屏信息组装与 CLI 输出(通用模板,无业务逻辑)。""" + +from __future__ import annotations + +from typing import Any, Dict, Optional + + +def build_video_info( + video_summary: dict[str, Any], + compose_context_before: Optional[dict[str, Any]] = None, + compose_context_after: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + """将 RpaVideoSession.summary() 转为 task log / CLI 可用的 video 块。""" + return { + "enabled": video_summary.get("enabled", False), + "path": video_summary.get("path"), + "capture_path": video_summary.get("capture_path"), + "record_log_path": video_summary.get("record_log_path"), + "warnings": list(video_summary.get("warnings") or []), + "voiceover_path": video_summary.get("voiceover_path"), + "music_path": video_summary.get("music_path"), + "audio_warnings": list(video_summary.get("audio_warnings") or []), + "compose_context": { + **(compose_context_before or {}), + "after_compose": compose_context_after or {}, + }, + } + + +def merge_video_into_result_summary( + payload: dict[str, Any], + video_info: Optional[dict[str, Any]], +) -> dict[str, Any]: + """把 video artifact 字段写入 result_summary JSON 对象。""" + if not video_info: + return payload + payload = dict(payload) + payload["video"] = video_info + payload["video_path"] = video_info.get("path") + payload["raw_video"] = video_info.get("capture_path") + payload["video_log"] = video_info.get("record_log_path") + payload["video_warnings"] = list(video_info.get("warnings") or []) + payload["voiceover_path"] = video_info.get("voiceover_path") + payload["music_path"] = video_info.get("music_path") + payload["audio_warnings"] = list(video_info.get("audio_warnings") or []) + return payload + + +def _print_video_summary(video_block: Optional[dict[str, Any]]) -> None: + """任务完成后在 CLI 打印录屏路径、日志与诊断信息。""" + if not isinstance(video_block, dict) or not video_block.get("enabled"): + return + record_log = video_block.get("record_log_path") + if record_log: + print(f"录屏日志:{record_log}") + path = video_block.get("path") + if path: + print(f"录屏路径:{path}") + else: + print("录屏路径:未生成") + warnings = video_block.get("warnings") or [] + if warnings: + print(f"视频诊断:{'; '.join(str(w) for w in warnings)}") + capture = video_block.get("capture_path") + if capture: + print(f"原始录屏路径:{capture}") + voiceover = video_block.get("voiceover_path") + if voiceover: + print(f"旁白路径:{voiceover}") + music = video_block.get("music_path") + if music: + print(f"背景音乐:{music}") + audio_warnings = video_block.get("audio_warnings") or [] + if audio_warnings: + print(f"音频诊断:{'; '.join(str(w) for w in audio_warnings)}") + compose_ctx = video_block.get("compose_context") + if isinstance(compose_ctx, dict): + print( + "视频合成上下文:" + f"media_assets_root={compose_ctx.get('media_assets_root', '')}; " + f"ffmpeg_path={compose_ctx.get('ffmpeg_path', '')}; " + f"background_music_issue={compose_ctx.get('background_music_issue') or ''}; " + f"background_music_sample_path={compose_ctx.get('background_music_sample_path', '')}" + ) diff --git a/scripts/service/task_service.py b/scripts/service/task_service.py index 83bdd17..ce12b9c 100644 --- a/scripts/service/task_service.py +++ b/scripts/service/task_service.py @@ -6,28 +6,81 @@ from __future__ import annotations +import asyncio import json import os -from typing import Optional +import uuid +from typing import Any, Dict, Optional from jiangchang_skill_core import collect_runtime_diagnostics, config, format_runtime_health_lines +from jiangchang_skill_core.rpa.video_session import RpaVideoSession from db import task_logs_repository as tlr from service.entitlement_service import check_entitlement +from service.task_run_support import ( + _print_video_summary, + build_video_info, + merge_video_into_result_summary, +) from util.constants import PLATFORM_KIT_MIN_VERSION, SKILL_SLUG, SKILL_VERSION -from util.runtime_paths import get_skill_root +from util.runtime_paths import get_skill_data_dir, get_skill_root from util.timeutil import unix_to_iso +async def _run_template_demo(target: Optional[str], input_id: Optional[str]) -> tuple[int, dict[str, Any]]: + """最小 RpaVideoSession 示范:不启动浏览器、不执行业务,仅演示录屏包裹范式。""" + batch_id = uuid.uuid4().hex[:12] + data_dir = get_skill_data_dir() + + async with RpaVideoSession( + skill_slug=SKILL_SLUG, + skill_data_dir=data_dir, + batch_id=batch_id, + title="开始执行示例任务", + closing_title="示例任务执行完成", + ) as video: + video.add_step("准备执行示例任务") + if target: + video.add_step(f"接收目标参数:{target}") + if input_id: + video.add_step(f"接收输入标识:{input_id}") + video.add_step("示例任务执行完成") + + video_summary = video.summary() + video_info = build_video_info(video_summary, {}, {}) + return 1, video_info + + def cmd_run(target: Optional[str] = None, input_id: Optional[str] = None) -> int: """通用任务执行入口模板。复制后请实现真实业务逻辑。""" - _ = (target, input_id) ok, reason = check_entitlement(SKILL_SLUG) if not ok: print(f"❌ {reason}") return 1 + + rc, video_info = asyncio.run(_run_template_demo(target, input_id)) + _print_video_summary(video_info) + + summary_payload = merge_video_into_result_summary( + { + "template_demo": True, + "target": target, + "input_id": input_id, + }, + video_info, + ) + tlr.save_task_log( + task_type="demo", + target_id=target, + input_id=input_id, + input_title="模板示例任务", + status="failed", + error_msg="模板仓库未实现真实业务", + result_summary=json.dumps(summary_payload, ensure_ascii=False), + ) + print("❌ 这是模板仓库,请复制后在 scripts/service/task_service.py 中实现 cmd_run 的真实业务逻辑。") - return 1 + return rc def cmd_logs( diff --git a/scripts/util/constants.py b/scripts/util/constants.py index 471c5af..d3981f6 100644 --- a/scripts/util/constants.py +++ b/scripts/util/constants.py @@ -3,4 +3,4 @@ SKILL_SLUG = "your-skill-slug" SKILL_VERSION = "1.0.14" LOG_LOGGER_NAME = "openclaw.skill.your_skill_slug" -PLATFORM_KIT_MIN_VERSION = "1.0.11" +PLATFORM_KIT_MIN_VERSION = "1.0.13" diff --git a/tests/_support.py b/tests/_support.py index c674470..59fce24 100644 --- a/tests/_support.py +++ b/tests/_support.py @@ -39,7 +39,7 @@ def get_skill_root() -> str: return _SKILL_ROOT -def platform_kit_version_patch(version: str = "1.0.11"): +def platform_kit_version_patch(version: str = "1.0.13"): """Mock installed jiangchang-platform-kit version for health/diagnostics tests.""" from unittest.mock import patch diff --git a/tests/test_cli_smoke.py b/tests/test_cli_smoke.py index 25f212c..165c61d 100644 --- a/tests/test_cli_smoke.py +++ b/tests/test_cli_smoke.py @@ -10,6 +10,8 @@ from contextlib import redirect_stderr, redirect_stdout from _support import IsolatedDataRoot, platform_kit_version_patch +from jiangchang_skill_core import config + # scripts/ 已由 _support 注入 sys.path from cli.app import main from util.constants import SKILL_SLUG @@ -71,17 +73,25 @@ class TestCliSmoke(unittest.TestCase): self.assertIn("数字", buf.getvalue()) def test_run_placeholder_returns_nonzero_without_network(self) -> None: - """占位 run:不验证业务成功,仅确认模板提示且退出码非 0(无 AUTH_BASE 时不发 HTTP)。""" + """占位 run:RpaVideoSession 示范 + 模板提示;OPENCLAW_RECORD_VIDEO=0 时不启 ffmpeg。""" old_auth = os.environ.pop("JIANGCHANG_AUTH_BASE_URL", None) + old_record = os.environ.get("OPENCLAW_RECORD_VIDEO") + os.environ["OPENCLAW_RECORD_VIDEO"] = "0" try: - buf = io.StringIO() - with redirect_stdout(buf), redirect_stderr(io.StringIO()): - rc = main(["run"]) - self.assertNotEqual(rc, 0) - self.assertIn("模板", buf.getvalue()) + with IsolatedDataRoot(user_id="_cli_run"): + config.reset_cache() + buf = io.StringIO() + with redirect_stdout(buf), redirect_stderr(io.StringIO()): + rc = main(["run"]) + self.assertNotEqual(rc, 0) + self.assertIn("模板", buf.getvalue()) finally: if old_auth is not None: os.environ["JIANGCHANG_AUTH_BASE_URL"] = old_auth + if old_record is None: + os.environ.pop("OPENCLAW_RECORD_VIDEO", None) + else: + os.environ["OPENCLAW_RECORD_VIDEO"] = old_record if __name__ == "__main__": diff --git a/tests/test_config_bootstrap.py b/tests/test_config_bootstrap.py index 6fca057..e8dc13f 100644 --- a/tests/test_config_bootstrap.py +++ b/tests/test_config_bootstrap.py @@ -78,8 +78,8 @@ class TestConfigBootstrap(unittest.TestCase): config.reset_cache() with open(example, encoding="utf-8") as f: example_text = f.read() - self.assertIn("OPENCLAW_TEST_TARGET=simulator_rpa", example_text) - self.assertEqual(config.get("OPENCLAW_TEST_TARGET"), "simulator_rpa") + self.assertIn("OPENCLAW_TEST_TARGET=mock", example_text) + self.assertEqual(config.get("OPENCLAW_TEST_TARGET"), "mock") def test_config_path_outputs_json(self) -> None: with IsolatedDataRoot(user_id="_cfg_path"): diff --git a/tests/test_docs_standards.py b/tests/test_docs_standards.py new file mode 100644 index 0000000..279fc60 --- /dev/null +++ b/tests/test_docs_standards.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +"""文档与 pytest 配置守护:防止模板标准退化。""" +from __future__ import annotations + +import configparser +import os +import unittest + +from _support import get_skill_root + + +class TestDocsStandards(unittest.TestCase): + def _read(self, rel_path: str) -> str: + path = os.path.join(get_skill_root(), rel_path) + with open(path, encoding="utf-8") as f: + return f.read() + + def test_rpa_md_covers_video_and_playwright_standards(self) -> None: + text = self._read("references/RPA.md") + self.assertIn("title", text) + self.assertIn("closing_title", text) + self.assertIn("中文", text) + self.assertIn("--no-sandbox", text) + self.assertIn("--disable-blink-features=AutomationControlled", text) + self.assertIn("RpaVideoSession", text) + self.assertIn("1.0.13", text) + + def test_adapter_md_covers_four_tiers_and_allow_flags(self) -> None: + text = self._read("references/ADAPTER.md") + for marker in ( + "mock", + "simulator_rpa", + "real_api", + "real_rpa", + "ALLOW_REAL_API", + "ALLOW_REAL_RPA", + "ALLOW_WRITE_ACTIONS", + "sibling_bridge", + ): + self.assertIn(marker, text, msg=f"ADAPTER.md missing {marker!r}") + + def test_cli_md_mentions_shared_python_runtime(self) -> None: + text = self._read("references/CLI.md") + self.assertIn("python-runtime", text) + self.assertIn("uv run python", text) + + def test_testing_md_mentions_pytest_txt_collection_guard(self) -> None: + text = self._read("references/TESTING.md") + self.assertIn(".txt", text) + self.assertIn("pytest.ini", text) + + def test_docs_do_not_claim_1_0_11_as_current_standard(self) -> None: + for rel in ( + "README.md", + "SKILL.md", + "references/RUNTIME.md", + "references/RPA.md", + "references/CONFIG.md", + "references/TESTING.md", + ): + text = self._read(rel) + self.assertNotIn( + ">=1.0.11", + text.replace(" ", ""), + msg=f"{rel} still claims 1.0.11 as current minimum", + ) + + +class TestPytestIniCollection(unittest.TestCase): + def test_pytest_ini_exists_and_limits_python_files(self) -> None: + ini_path = os.path.join(get_skill_root(), "pytest.ini") + self.assertTrue(os.path.isfile(ini_path), "pytest.ini must exist at repo root") + parser = configparser.ConfigParser() + parser.read(ini_path, encoding="utf-8") + python_files = parser.get("pytest", "python_files", fallback="") + self.assertIn("test_*.py", python_files) + self.assertIn("*_test.py", python_files) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_entrypoint_subprocess.py b/tests/test_entrypoint_subprocess.py index 45c1184..eb54057 100644 --- a/tests/test_entrypoint_subprocess.py +++ b/tests/test_entrypoint_subprocess.py @@ -10,6 +10,19 @@ import unittest from _support import IsolatedDataRoot, get_skill_root +import importlib.metadata as metadata + +from jiangchang_skill_core import version_ge +from util.constants import PLATFORM_KIT_MIN_VERSION + + +def _platform_kit_meets_template_minimum() -> bool: + try: + installed = metadata.version("jiangchang-platform-kit") + except metadata.PackageNotFoundError: + return False + return version_ge(installed, PLATFORM_KIT_MIN_VERSION) + def _run_main(args: list[str], timeout: int = 15) -> subprocess.CompletedProcess[str]: root = get_skill_root() @@ -30,6 +43,10 @@ def _run_main(args: list[str], timeout: int = 15) -> subprocess.CompletedProcess class TestEntrypointSubprocess(unittest.TestCase): + @unittest.skipUnless( + _platform_kit_meets_template_minimum(), + f"installed jiangchang-platform-kit below template minimum {PLATFORM_KIT_MIN_VERSION}", + ) def test_health_exit_zero(self) -> None: with IsolatedDataRoot(): cp = _run_main(["health"]) diff --git a/tests/test_platform_import.py b/tests/test_platform_import.py index eb008bc..b2a0373 100644 --- a/tests/test_platform_import.py +++ b/tests/test_platform_import.py @@ -83,16 +83,16 @@ class TestPlatformImportSource(unittest.TestCase): ) ) - def test_platform_kit_min_version_is_1_0_11(self) -> None: + def test_platform_kit_min_version_is_1_0_13(self) -> None: from jiangchang_skill_core import version_ge from util.constants import PLATFORM_KIT_MIN_VERSION - self.assertEqual(PLATFORM_KIT_MIN_VERSION, "1.0.11") + self.assertEqual(PLATFORM_KIT_MIN_VERSION, "1.0.13") md_path = os.path.join(get_skill_root(), "SKILL.md") with open(md_path, encoding="utf-8") as f: md = f.read() - self.assertEqual(_parse_platform_kit_min_version(md), "1.0.11") + self.assertEqual(_parse_platform_kit_min_version(md), "1.0.13") req_path = os.path.join(get_skill_root(), "requirements.txt") with open(req_path, encoding="utf-8") as f: @@ -102,7 +102,15 @@ class TestPlatformImportSource(unittest.TestCase): self.assertNotIn("jiangchang-platform-kit", dep_body) self.assertNotIn("playwright", dep_body) - installed = metadata.version("jiangchang-platform-kit") + try: + installed = metadata.version("jiangchang-platform-kit") + except metadata.PackageNotFoundError: + self.skipTest("jiangchang-platform-kit not installed in current interpreter") + if not version_ge(installed, PLATFORM_KIT_MIN_VERSION): + self.skipTest( + f"installed jiangchang-platform-kit {installed!r} < required " + f"{PLATFORM_KIT_MIN_VERSION!r}; upgrade shared runtime to enforce this check" + ) self.assertTrue( version_ge(installed, PLATFORM_KIT_MIN_VERSION), msg=f"installed {installed!r} < required {PLATFORM_KIT_MIN_VERSION!r}", diff --git a/tests/test_template_runtime_standard.py b/tests/test_template_runtime_standard.py index e258868..435c504 100644 --- a/tests/test_template_runtime_standard.py +++ b/tests/test_template_runtime_standard.py @@ -32,7 +32,7 @@ FORBIDDEN_PHRASES = ( POSITIVE_MARKERS = ( "jiangchang-platform-kit", - "1.0.11", + "1.0.13", "共享 runtime", ) @@ -75,6 +75,7 @@ class TestTemplateRuntimeStandard(unittest.TestCase): self.assertIn("python_executable", text) self.assertIn("platform_kit_version", text) self.assertIn("jiangchang_skill_core_file", text) + self.assertIn("python-runtime", text) if __name__ == "__main__": diff --git a/tests/test_video_service.py b/tests/test_video_service.py new file mode 100644 index 0000000..1667a3f --- /dev/null +++ b/tests/test_video_service.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +"""RpaVideoSession 模板示范与 result_summary / CLI 输出测试。""" +from __future__ import annotations + +import io +import json +import os +import re +import unittest +from contextlib import redirect_stderr, redirect_stdout +from unittest.mock import AsyncMock, MagicMock, patch + +from _support import IsolatedDataRoot, get_skill_root + +from jiangchang_skill_core import config + + +class TestEnvExampleVideoDefaults(unittest.TestCase): + def test_env_example_contains_required_keys(self) -> None: + path = os.path.join(get_skill_root(), ".env.example") + with open(path, encoding="utf-8") as f: + text = f.read() + for key in ( + "OPENCLAW_TEST_TARGET=mock", + "OPENCLAW_RECORD_VIDEO=1", + "OPENCLAW_ARTIFACTS_ON_FAILURE=1", + "OPENCLAW_BROWSER_HEADLESS=0", + "OPENCLAW_PLAYWRIGHT_STEALTH=1", + ): + self.assertIn(key, text, msg=f"missing {key!r} in .env.example") + + +class TestPrintVideoSummary(unittest.TestCase): + def test_cli_prints_video_path_when_enabled(self) -> None: + from service.task_run_support import _print_video_summary + + buf = io.StringIO() + with redirect_stdout(buf), redirect_stderr(io.StringIO()): + _print_video_summary( + { + "enabled": True, + "path": r"D:\data\videos\your-skill-slug_demo.mp4", + "record_log_path": r"D:\data\logs\ffmpeg-record.log", + "warnings": [], + } + ) + out = buf.getvalue() + self.assertIn("录屏路径", out) + self.assertIn("your-skill-slug_demo.mp4", out) + self.assertIn("录屏日志", out) + + def test_disabled_video_prints_nothing(self) -> None: + from service.task_run_support import _print_video_summary + + buf = io.StringIO() + with redirect_stdout(buf), redirect_stderr(io.StringIO()): + _print_video_summary({"enabled": False, "path": r"D:\tmp\x.mp4"}) + self.assertEqual(buf.getvalue(), "") + + +class TestMergeVideoIntoResultSummary(unittest.TestCase): + def test_result_summary_includes_video_fields(self) -> None: + from service.task_run_support import merge_video_into_result_summary + + video_info = { + "enabled": True, + "path": r"D:\data\videos\demo.mp4", + "capture_path": r"D:\data\capture.mp4", + "record_log_path": r"D:\data\logs\ffmpeg-record.log", + "warnings": ["test_warning"], + "voiceover_path": r"D:\data\voiceover.wav", + "music_path": r"D:\data\music.mp3", + "audio_warnings": ["tts_skipped"], + } + payload = merge_video_into_result_summary({"demo": True}, video_info) + self.assertIn("video", payload) + self.assertEqual(payload["video_path"], video_info["path"]) + self.assertEqual(payload["raw_video"], video_info["capture_path"]) + self.assertEqual(payload["video_log"], video_info["record_log_path"]) + self.assertEqual(payload["video_warnings"], ["test_warning"]) + self.assertEqual(payload["voiceover_path"], video_info["voiceover_path"]) + self.assertEqual(payload["music_path"], video_info["music_path"]) + self.assertEqual(payload["audio_warnings"], ["tts_skipped"]) + + +class TestTemplateRunVideoSession(unittest.TestCase): + def _fake_video_session(self, mock_video: MagicMock): + class _FakeVideoSession: + def __init__(self, **kwargs): + self.kwargs = kwargs + + async def __aenter__(self): + return mock_video + + async def __aexit__(self, *args): + return None + + return _FakeVideoSession + + def test_cmd_run_creates_video_session_with_chinese_titles(self) -> None: + with IsolatedDataRoot(user_id="_video_run"): + os.environ["OPENCLAW_RECORD_VIDEO"] = "0" + config.reset_cache() + + from service import task_service + + mock_video = MagicMock() + mock_video.add_step = MagicMock() + mock_video.summary.return_value = { + "enabled": False, + "path": None, + "capture_path": None, + "record_log_path": None, + "warnings": [], + "voiceover_path": None, + "music_path": None, + "audio_warnings": [], + } + + created: list[dict] = [] + + class _CapturingFakeSession: + def __init__(self, **kwargs): + created.append(kwargs) + + async def __aenter__(self): + return mock_video + + async def __aexit__(self, *args): + return None + + with patch.object(task_service, "RpaVideoSession", _CapturingFakeSession): + buf = io.StringIO() + with redirect_stdout(buf), redirect_stderr(io.StringIO()): + rc = task_service.cmd_run(target="demo-target", input_id="42") + + self.assertEqual(rc, 1) + self.assertTrue(created, "RpaVideoSession should be constructed") + kwargs = created[0] + self.assertEqual(kwargs.get("title"), "开始执行示例任务") + self.assertEqual(kwargs.get("closing_title"), "示例任务执行完成") + self.assertTrue(re.search(r"[\u4e00-\u9fff]", kwargs.get("title", ""))) + self.assertTrue(re.search(r"[\u4e00-\u9fff]", kwargs.get("closing_title", ""))) + mock_video.add_step.assert_any_call("准备执行示例任务") + mock_video.add_step.assert_any_call("示例任务执行完成") + mock_video.summary.assert_called() + + out = buf.getvalue() + self.assertIn("模板", out) + + from db import task_logs_repository as tlr + + rows = tlr.list_task_logs(1) + self.assertTrue(rows) + summary = json.loads(rows[0][7]) + self.assertIn("video", summary) + self.assertIn("video_path", summary) + + +if __name__ == "__main__": + unittest.main()