Compare commits

...

15 Commits

Author SHA1 Message Date
1ff70e26a5 Release v1.0.51: precipitate ensure-web, config empty-value, and login-required standards
All checks were successful
技能自动化发布 / release (push) Successful in 7s
2026-07-18 16:30:06 +08:00
0b9a8b2107 Release v1.0.50: web RPA profile/headed hard rules (POLICY-RPA-004)
All checks were successful
技能自动化发布 / release (push) Successful in 17s
2026-07-18 09:31:40 +08:00
287816aa2a docs(actions): align executionProfile mental model with host default sync (v1.0.49)
All checks were successful
技能自动化发布 / release (push) Successful in 8s
2026-07-18 08:44:16 +08:00
144455fbe0 test(config): add POLICY-CONFIG-004 hard gate for user-facing .env.example comments (v1.0.48)
All checks were successful
技能自动化发布 / release (push) Successful in 8s
2026-07-17 19:06:21 +08:00
5ec9648148 docs(config): user-facing .env.example comments for config UI (v1.0.47)
All checks were successful
技能自动化发布 / release (push) Successful in 12s
2026-07-17 18:25:37 +08:00
ec049fdc2a feat(docs): add market four-tab materials (tutorial/demo/changelog) for v1.0.46
All checks were successful
技能自动化发布 / release (push) Successful in 13s
2026-07-17 11:55:29 +08:00
917df04712 Precipitate generic Agent routing and how-to gold standards
All checks were successful
技能自动化发布 / release (push) Successful in 13s
2026-07-15 15:33:23 +08:00
b016b3b411 Align Agent CLI docs to host shared python on PATH
All checks were successful
技能自动化发布 / release (push) Successful in 7s
2026-07-15 13:58:41 +08:00
296798a0f3 docs: clarify shared Python, CLI vs Action, and Task Center rules
All checks were successful
技能自动化发布 / release (push) Successful in 11s
2026-07-15 11:13:53 +08:00
6b64aad138 feat: add standard init-db CLI for host install schema ensure
All checks were successful
技能自动化发布 / release (push) Successful in 4s
2026-07-14 17:26:24 +08:00
af7a43a702 chore: auto release commit (2026-07-14 11:56:45)
All checks were successful
技能自动化发布 / release (push) Successful in 5s
2026-07-14 11:56:46 +08:00
a7baba7210 Codify Skill Action sync/async and task-center gold standards (v1.0.40)
All checks were successful
技能自动化发布 / release (push) Successful in 7s
2026-07-14 07:55:55 +08:00
2e5a8d5eed Add DATA_PATHS golden standard and resolve_data_path helpers.
All checks were successful
技能自动化发布 / release (push) Successful in 5s
Document skill-owned file layout under user data dir, extend runtime_paths with standard subdir helpers, add POLICY-DATA-PATH-001, and update CONFIG/RUNTIME cross-references.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-13 14:14:38 +08:00
6f958ded28 feat(template): SRCP v1 standards, job_context/finish gold sample (v1.0.38, platform-kit 1.2.0)
All checks were successful
技能自动化发布 / release (push) Successful in 4s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-12 12:27:44 +08:00
3bc15d1241 chore: auto release commit (2026-07-11 15:57:40)
All checks were successful
技能自动化发布 / release (push) Successful in 5s
2026-07-11 15:57:43 +08:00
49 changed files with 3576 additions and 461 deletions

View File

@@ -1,21 +1,53 @@
# ── 运行模式 / adapter 档位(见 references/ADAPTER.md── # 运行模式:决定本技能用模拟数据还是真实浏览器/接口去执行
OPENCLAW_TEST_TARGET=mock # mock | simulator_rpa | real_api | real_rpa OPENCLAW_TEST_TARGET=mock # 可选:mock=本地模拟,simulator_rpa=仿真站点,real_api=真实接口real_rpa=真实浏览器;模板默认 mock日常正式使用请改为 real_rpa
# ── 目标系统 ── # 目标网站地址:技能要访问的网站或服务地址
TARGET_BASE_URL=https://sandbox.jc2009.com # 仿真/生产地址,可被进程环境变量覆盖 TARGET_BASE_URL=https://sandbox.jc2009.com # 填写完整网址(含 https://);换环境时再改,一般保持默认即可
# ── 默认账号(仅非敏感标识;密码走 account-manager── # 默认登录账号:仅填写非敏感的账号标识(如工号/登录名/手机号)
DEFAULT_LOGIN_ID=04110001 DEFAULT_LOGIN_ID= # 留空=按平台自动选用或登记;有值则按该标识筛选;不要填密码
# ── 浏览器 / RPA ── # 默认账号编号:仅填账号管理里的纯数字主键(一般留空)
OPENCLAW_BROWSER_HEADLESS=0 # 0=有头(默认) 1=无头(CI) DEFAULT_ACCOUNT_ID= # 留空=自动;只填纯数字;手机号请填上方登录账号
OPENCLAW_PLAYWRIGHT_STEALTH=1 # 1=开启反检测指纹(默认)
# ── 存证 ── # 是否显示浏览器窗口:网页自动化时是否弹出可见浏览器
OPENCLAW_RECORD_VIDEO=1 OPENCLAW_BROWSER_HEADLESS=0 # 0=显示窗口必须便于介入与排查1=后台静默(勿作日常用法)
OPENCLAW_ARTIFACTS_ON_FAILURE=1 # 1=失败截图(默认)
# ── 节流 / 超时 ── # 浏览器防检测:降低被网站识别为自动化工具的概率
STEP_DELAY_MIN=1.0 # 步骤间随机等待下限(秒) OPENCLAW_PLAYWRIGHT_STEALTH=1 # 1=开启推荐0=关闭;一般保持默认
STEP_DELAY_MAX=5.0 # 步骤间随机等待上限(秒)
HUMAN_WAIT_TIMEOUT=180 # 滑块/验证码/2FA 等人工超时(秒) # 是否录制操作过程:用于留证、复现问题或向他人演示
OPENCLAW_RECORD_VIDEO=0 # 0=不录屏默认1=录屏并生成带说明的视频文件;需要留证时再改为 1
# 失败时是否截图:任务出错时自动保存现场截图,便于排查
OPENCLAW_ARTIFACTS_ON_FAILURE=1 # 1=失败时截图推荐0=不截图
# 步骤最短等待:两步操作之间随机停顿的下限,模拟真人节奏
STEP_DELAY_MIN=1.0 # 单位:秒;一般保持默认,页面不稳定时可略调大
# 步骤最长等待:两步操作之间随机停顿的上限
STEP_DELAY_MAX=5.0 # 单位:秒;须大于等于最短等待;一般保持默认
# 人工处理超时:遇到滑块、验证码、二次验证时,等待人工处理的最长时间
HUMAN_WAIT_TIMEOUT=180 # 单位:秒;来不及处理时可调大,如 300
# 以下为可选目录配置。一般不用改;取消注释并填写后,才覆盖默认子文件夹。
# 填写相对路径时,相对于本技能的数据目录(不是当前工作目录)。
# 下载目录:技能保存下载文件的位置
# SKILL_DOWNLOAD_DIR=downloads # 相对本技能数据目录;留空或保持注释则用默认 downloads
# 导入目录:待导入文件放置的位置
# SKILL_IMPORT_DIR=imports # 相对本技能数据目录;留空或保持注释则用默认 imports
# 导出目录:技能导出文件的保存位置
# SKILL_EXPORT_DIR=exports # 相对本技能数据目录;留空或保持注释则用默认 exports
# 上传目录:待上传文件放置的位置
# SKILL_UPLOAD_DIR=uploads # 相对本技能数据目录;留空或保持注释则用默认 uploads
# 缓存目录:临时缓存文件的位置
# SKILL_CACHE_DIR=cache # 相对本技能数据目录;留空或保持注释则用默认 cache
# 临时目录:运行中临时文件的位置
# SKILL_TEMP_DIR=temp # 相对本技能数据目录;留空或保持注释则用默认 temp

43
CHANGELOG.md Normal file
View File

@@ -0,0 +1,43 @@
# Changelog
本文件对应技能市场 **「更新日志」** Tab。
发布 CI 会按当前 tag 版本(如 `v1.0.46``1.0.46`)提取匹配的 `##` 小节,写入该版本的 `changelog`
约定:
- 每个正式版本一节,标题形如 `## 1.0.46``## [1.0.46] - YYYY-MM-DD`
- 小节正文写用户能看懂的变化(新能力、修复、注意事项),避免堆砌内部实现细节
- 打 tag 前**必须**为即将发布的版本新增一节;找不到匹配小节时,本次发布不会更新 changelog 字段
## 1.0.51
- 沉淀网页 RPA 首启标准:业务技能默认 `ensure-web`(有则用、无则登记);登记账号 ≠ 已登录目标站;租约全忙返回占用错误且不重复建号
- 明确会话依赖型采集须声明登录 `required` 并做登录门禁;配置留空 + 行尾说明不得当成假默认值;账号可用登录标识选择,展示优先登录名
- 最低共享库版本声明上调至 1.2.2(含配置空值解析修复);说明宿主按需升级、不因源上有更新自动追新
## 1.0.50
- 沉淀网页 RPA 硬规则:必须先经账号管理取得 `profile_dir` 再开浏览器;生产有头;站点登录按平台约定(不全局强制);新增 `POLICY-RPA-004` 自动检测
- 用户教程 / 技能说明占位强调「先登记账号」需求模板增加登录策略三选一required / optional / not_needed
## 1.0.49
- 明确 Skill Action 心智:默认按 sync仅长任务 / RPA 显式 async 进任务中心;匠厂宿主省略 `executionProfile` 时按 sync新技能仍须显式声明
## 1.0.48
- 新增配置注释硬门禁 `POLICY-CONFIG-004``.env.example` 每个配置项必须有中文行头与行尾说明,禁止开发文档指向,测试不通过则无法发布
## 1.0.47
- 规范 `.env.example` 注释:面向「数据管理 → 配置管理」用户,行头说明「是什么」、行尾说明「怎么填」
- 去掉注释中的开发文档指向与黑话;`CONFIG.md` / 发布检查清单同步约束,避免各技能注释写法不一致
## 1.0.46
- 模板默认增加市场材料:`TUTORIAL.md`(使用教程)、`DEMO.md`(演示)、`CHANGELOG.md`(更新日志),与根 `README.md`(技能说明)组成四 Tab 内容源
- 发布 CI 同步 `tutorial_md` / `demo_md` / `demo_video_url` / 版本 `changelog`
## 1.0.45
- 沉淀通用 Agent 路由与 how-to 文档标准(见仓库提交说明)

24
DEMO.md Normal file
View File

@@ -0,0 +1,24 @@
---
demo_video_url: ""
---
> **模板说明(复制后删除本段)**
> 本文对应技能市场 **「演示」** Tab。
> - frontmatter 的 `demo_video_url`:演示视频地址(发布时同步为 `demo_video_url`);没有视频时保持空字符串 `""`。
> - 正文(发布时同步为 `demo_md`):可选,写视频看点、时间轴或无视频时的图文演示说明。
> **不要**把演示链接写进 `SKILL.md`(市场材料 ≠ Agent 契约)。
> 复制为业务技能后:填入真实可访问的视频 URL并删掉本提示段。
# 演示说明
用一两句话说明这段演示帮助用户看懂什么(例如:从发起任务到看到结果的完整过程)。
## 建议观看顺序
1. 如何发起一次典型任务
2. 执行过程中会看到什么提示 / 进度
3. 成功后的结果长什么样
## 没有视频时
可在此用简短图文描述关键界面与结果样例;有视频后把 `demo_video_url` 填上即可,正文可保留为补充说明。

View File

@@ -6,6 +6,7 @@ description: "用用户能理解的方式说明这个技能能做什么、适合
> 本文是技能市场详情与普通用户说明,**不是** Agent 参考索引、CLI 契约或开发文档。 > 本文是技能市场详情与普通用户说明,**不是** Agent 参考索引、CLI 契约或开发文档。
> frontmatter 的 `description` 必须是用户能看懂的一句话能力描述;**不得**写成 CLI、schema、references、development、契约、数据结构、开发规范或 Agent 参考索引。 > frontmatter 的 `description` 必须是用户能看懂的一句话能力描述;**不得**写成 CLI、schema、references、development、契约、数据结构、开发规范或 Agent 参考索引。
> 正文只回答用户关心的问题,**不要**把 Playwright、DOM、Python、RPA、references、development、schema 等作为面向用户的主说明内容;若业务上必须出现技术词,须用用户能理解的方式解释,且不能喧宾夺主。 > 正文只回答用户关心的问题,**不要**把 Playwright、DOM、Python、RPA、references、development、schema 等作为面向用户的主说明内容;若业务上必须出现技术词,须用用户能理解的方式解释,且不能喧宾夺主。
> **复制后验收章节(标题可微调,建议保留):**「能帮你做什么」「适合什么场景」「使用前需要准备什么」「你可以这样告诉 Agent」「执行后你会得到什么」「注意事项」「常见问题」。
# 【技能名称】 # 【技能名称】
@@ -39,9 +40,11 @@ description: "用用户能理解的方式说明这个技能能做什么、适合
说明用户在使用前要准备的东西,例如: 说明用户在使用前要准备的东西,例如:
- 相关账号已登录,且具备查询、导出或提交权限 - **网页自动化类:** 首次运行可由技能自动登记平台账号(浏览器会话由系统隔离管理)。也可在「账号管理」里指定登录标识。登记账号 ≠ 已登录目标站
- **是否要登录目标站:** 按本技能说明(有的平台必须登录,有的公开页可不登录);与「是否有账号记录」不是一回事
- 相关业务权限(查询、导出、提交等)已具备
- 需要处理的文件、时间范围、订单号、客户名称、项目名称等信息 - 需要处理的文件、时间范围、订单号、客户名称、项目名称等信息
- 如果涉及外部系统,请确认网络、账号、验证码或审批流程可正常使用 - 如果涉及验证码或人工确认,请保证能及时在弹出的浏览器窗口中操作
--- ---

116
SKILL.md
View File

@@ -1,12 +1,12 @@
--- ---
name: 技能开发模板(通用业务版) name: 技能开发模板(通用业务版)
description: "OpenClaw 通用业务技能开发模板,供复制后定制新业务 skill。定制步骤见 development/DEVELOPMENT.md。" description: "OpenClaw 通用业务技能开发模板,供复制后定制新业务 skill。定制步骤见 development/DEVELOPMENT.md。"
version: 1.0.32 version: 1.0.51
author: 深圳匠厂科技有限公司 author: 深圳匠厂科技有限公司
metadata: metadata:
openclaw: openclaw:
slug: your-skill-slug slug: your-skill-slug
platform_kit_min_version: "1.0.17" platform_kit_min_version: "1.2.2"
emoji: "📦" emoji: "📦"
category: "通用" category: "通用"
developer_ids: developer_ids:
@@ -20,12 +20,73 @@ allowed-tools:
这是一个**用于复制的新技能模板**,不是业务 skill 本身。复制后请替换占位内容,实现你的真实业务逻辑。 这是一个**用于复制的新技能模板**,不是业务 skill 本身。复制后请替换占位内容,实现你的真实业务逻辑。
## Agent / 宿主编排(复制为业务技能后必改)
### 架构铁律(先读)
- **单业务内核、多入口**:数据管理 / 定时任务 / Agent / 技能详情 / 直接 CLI 必须复用同一 domain service禁止按入口复制业务逻辑禁止按 `source` 分叉业务行为。
- **`placements`**:只决定 Action **出现在哪里**toolbar / cron / agent / skill-detail
- **`bind.tables`**:只决定数据管理出现在哪些表;含 `toolbar` 时**必须**显式非空绑定。
- **`executionProfile`**:只决定执行方式——`sync` 当场返回结果,`async` 进**任务中心**。与 placements / 入口**无关**。心智上多数为 sync仅长任务 / RPA 标 async宿主省略该字段时按 sync。每个 Action **仍必须**显式写 `sync``async`
- **同步数据**写技能本地库、不生成导出文件;**导出当前表**由宿主数据管理负责;特殊业务报告才另做 `export-*`
- **准备 vs 执行(适用则拆)**:若技能存在「先写入/准备本地数据」与「再对外产生副作用」两段Agent 必须能分开触发;禁止默认绑成不可拆的一步。一键无准备态的技能可跳过本条。
### 如何触发(能力类型)
| 你要做什么 | Agent 怎么做 | 进任务中心? |
|------------|--------------|--------------|
| 短查询 / 只读 / 秒级(`health` / `version` / `stats` / `list` / `get` / `logs` 等) | OpenClaw bash/exec + **共享 Python** 跑 CLI见下方「共享 Python」 | 否CLI 当场结束) |
| 已在 `actions.json` 声明且 `executionProfile: "sync"` 的能力 | 可用 `run_skill_action`,或同等效果的短 CLI同一内核 | 否 |
| 长耗时 / RPA / 浏览器 / 需要进度或取消;或 `executionProfile: "async"` | **必须** `run_skill_action`(先 `list_skill_actions` / `get_skill_action` | **是**(仅因为该 Action 是 async |
| 用户只问用法 / 能做什么 | 读根目录 `README.md`;逐步操作再读 `TUTORIAL.md`**不要**为答用法去列目录或默认打开 `references/` | — |
### 用户意图路由表(业务技能复制后必改)
复制为业务技能后,**必须**用本技能真实意图改写下表(保留三列结构)。格子写清:短 CLI 子命令,或 `run_skill_action`**具体 action id**(及主要 `input`)。勿留模板占位语上线。
| 用户意图(本技能自填) | Agent 怎么做 | 进任务中心? |
|------------------------|--------------|--------------|
| (例)查询 / 统计 / 列表 | 短 CLI`<your-read-commands>` | 否 |
| (例)写入 / 导入 / 改本地状态 | 短 CLI`<your-prep-commands>` | 否 |
| (例)长副作用 / RPA / 需进度 | `run_skill_action``<your-async-action-id>``input.…` | 是(因该 Action 为 async |
有长任务 / RPA 时:上表至少一行指向真实的 async action id且该 id 须出现在 `assets/actions.json`;细节分流见 `references/CLI.md`
**硬规则:**
1. **禁止**对长任务使用 `exec`/`bash``…/scripts/main.py run`(或等价业务命令)再 `process poll` 干等。
2. **禁止**用 `uv run python …` 跑技能脚本(会建临时环境,缺 `jiangchang_skill_core`)。
3. **禁止** Agent 自行 `pip install`
4. Action **可选**:无数据管理 / 定时 / Agent 结构化调用需求时可不提供 `actions.json`;有长任务 / RPA 时**必须**提供至少一条 `executionProfile: "async"``placements``agent` 的 Action。
5. **一个业务能力一个 Action**,用多个 `placements` 挂入口;底层仍是同一 `scripts/main.py` CLI。
6. 是否进任务中心**只**看该 Action 的 `executionProfile`,与数据管理 / 定时 / Agent 入口无关。
Agent 执行契约细节:`references/CLI.md``references/ACTIONS.md``references/SCHEMA.md`(不要把 `development/` 当 Agent 主读路径)。
## 共享 Python必读
宿主共享 runtime 在 `{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`,并已前置到 PATH同时设 `VIRTUAL_ENV`)。短 CLI 一条命令直接跑:
```bash
python {baseDir}/scripts/main.py health
python {baseDir}/scripts/main.py version
python {baseDir}/scripts/main.py config-path
python {baseDir}/scripts/main.py init-db
```
- 公共库来自共享 venv 的 `jiangchang-platform-kit>=1.2.2`(包名路径 `jiangchang_skill_core`**不要 vendor** `scripts/jiangchang_skill_core/`
- 根目录 `requirements.txt` **只声明技能特有**依赖;不要写 `jiangchang-platform-kit` / `playwright`
- `metadata.openclaw.platform_kit_min_version` 是宿主兼容声明,**不是** pip 依赖。
- `health``collect_runtime_diagnostics` 做只读诊断。
配置:仓库 `.env.example` 为模板;用户 `.env``{JIANGCHANG_DATA_ROOT}/{JIANGCHANG_USER_ID}/{slug}/.env`。优先级:进程环境变量 > 用户 `.env` > `.env.example`
## 面向用户问答LLM 规则) ## 面向用户问答LLM 规则)
- 本文(`SKILL.md`)是 LLM / OpenClaw 平台读取的技能入口,**不是**用户市场说明。 - 本文(`SKILL.md`)是 LLM / OpenClaw 平台读取的技能入口,**不是**用户市场说明。
- 根目录 `README.md` 是面向普通用户的说明 - 根目录市场材料面向普通用户(见下方「文档分工」),**不是** Agent 调用契约
当用户询问以下问题时,**必须优先读取**根目录 `README.md`,并用用户能理解的业务语言回答: 当用户询问以下问题时,**必须优先读取**根目录 `README.md`(能力说明)与 `TUTORIAL.md`(逐步用法),并用用户能理解的业务语言回答:
- 这个技能是做什么的 - 这个技能是做什么的
- 这个技能怎么用 - 这个技能怎么用
@@ -34,20 +95,31 @@ allowed-tools:
- 执行后会得到什么 - 执行后会得到什么
- 能不能帮我完成某个业务任务 - 能不能帮我完成某个业务任务
**回答「怎么用 / 能做什么」时的要求:**
1. 「能做什么 / 场景 / FAQ」以 `README.md` 为主;「第一次怎么用完」以 `TUTORIAL.md` 为主。
2. **禁止**在回答中粘贴 `python …/scripts/main.py …` 或其它命令行(除非用户明确索要命令,或自称技术人员/开发者)。
3. **禁止**为答用法而去 `dir` / `ls` / 列技能目录,或默认打开 `references/``development/`;仅当用户明确问命令、参数、集成或排错时再读 `references/`
4. **不要**向普通用户暴露 Playwright、DOM、Python、RPA、库表名、`error_code` 等实现细节,除非用户明确询问技术实现。
**文档读取边界:**
- **不要**把 `SKILL.md``references/``development/` 中的技术细节直接作为用户回答。 - **不要**把 `SKILL.md``references/``development/` 中的技术细节直接作为用户回答。
- **只有当**用户明确询问命令、参数、输出结构、开发、调试、集成或排错时,才读取 `references/``development/` - **只有当**用户明确询问命令、参数、输出结构、开发、调试、集成或排错时,才读取 `references/``development/` 主要给开发者 / 编码助手,对话 Agent **不必**默认打开
- `README.md` `SKILL.md` / `references` 表述冲突:对用户展示与市场说明`README.md` 为准;对执行契约、CLI、schema、运行约束`SKILL.md` / `references` 为准。 -市场材料`SKILL.md` / `references` 表述冲突:对用户展示以 `README.md` / `TUTORIAL.md` 为准;对执行契约以 `SKILL.md` / `references` 为准。
- 回答用户时**不要**暴露 Playwright、DOM、Python、RPA 等实现细节,除非用户明确询问技术实现。
- 用户未问技术实现时,**不要**讨论 slug 命名规则;开发者问命名或 slug 时,读取 `development/NAMING.md` - 用户未问技术实现时,**不要**讨论 slug 命名规则;开发者问命名或 slug 时,读取 `development/NAMING.md`
## 文档分工 ## 文档分工
| 文档 | 读者 | 用途 | | 文档 | 读者 | 用途 |
|------|------|------| |------|------|------|
| 根目录 `README.md` | 普通用户 | 技能市场详情页说明(`metadata.readme_md` 主来源 | | 根目录 `README.md` | 普通用户 | 市场 **说明** Tab`readme_md` |
| 根目录 `TUTORIAL.md` | 普通用户 | 市场 **教程** Tab`tutorial_md` |
| 根目录 `DEMO.md` | 普通用户 | 市场 **演示** Tab`demo_video_url` + `demo_md` |
| 根目录 `CHANGELOG.md` | 普通用户 | 市场 **更新日志** Tab按版本小节 → `changelog` |
| `SKILL.md`(本文) | LLM / OpenClaw 平台 | 技能入口、触发与运行契约摘要 | | `SKILL.md`(本文) | LLM / OpenClaw 平台 | 技能入口、触发与运行契约摘要 |
| `references/` | Agent 编排/调用 | 渐进式加载CLI 契约、字段 schema 等 | | `references/` | Agent 编排 / 调用 | CLI、Action、schema 契约Agent 主读) |
| `development/` | 开发者 / AI 编程代理 | 需求、开发教程、测试、技术规范 | | `development/` | 开发者 / AI 编程代理 | 需求、开发教程、测试、深度技术规范 |
## 目录约定 ## 目录约定
@@ -57,35 +129,15 @@ allowed-tools:
- CLI 入口固定为 `scripts/main.py` - CLI 入口固定为 `scripts/main.py`
- 业务逻辑按 `cli / db / service / util` 分层 - 业务逻辑按 `cli / db / service / util` 分层
## 最小命令
```bash
python {baseDir}/scripts/main.py health
python {baseDir}/scripts/main.py config-path
python {baseDir}/scripts/main.py version
```
配置:仓库 `.env.example` 为模板;用户 `.env``{JIANGCHANG_DATA_ROOT}/{JIANGCHANG_USER_ID}/{slug}/.env`,启动时自动 bootstrap。优先级进程环境变量 > 用户 `.env` > `.env.example`
## 运行依赖
- Python 运行环境由匠厂宿主注入**共享 runtime**`{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`
- 公共能力来自共享 runtime 安装的 `jiangchang-platform-kit>=1.0.17``jiangchang_skill_core` 包);**不要 vendor** `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。
- `metadata.openclaw.platform_kit_min_version`(当前 `1.0.17`)是运行契约/兼容性声明,供宿主安装与启用时校验,**不是**技能 pip 依赖声明。
- Skill 代码**不要**自行 `pip install`;系统级依赖(如 VC++ Runtime仅在 `health` / preflight 中提示用户安装。
- `health` 使用 `collect_runtime_diagnostics` 输出统一 runtime 诊断(只读,不下载/修复 media-assets
## 定制入口 ## 定制入口
1. 从本模板创建新业务技能时,**不得保留模板 `.git`**;优先使用 [`tools/scaffold_skill.ps1`](tools/scaffold_skill.ps1)(见 [`tools/README.md`](tools/README.md))。 1. 从本模板创建新业务技能时,**不得保留模板 `.git`**;优先使用 [`tools/scaffold_skill.ps1`](tools/scaffold_skill.ps1)(见 [`tools/README.md`](tools/README.md))。
2. 业务技能仓库中**不得**存在 `.openclaw-skill-template`(仅 template 源仓库保留)。 2. 业务技能仓库中**不得**存在 `.openclaw-skill-template`(仅 template 源仓库保留)。
3. 复制目录为你的新 skill 仓库,全局替换 `your-skill-slug` 等占位词。 3. 复制目录为你的新 skill 仓库,全局替换 `your-skill-slug` 等占位词。
4.`development/DEVELOPMENT.md` 完成开发与文档定制。 4.`development/DEVELOPMENT.md` 完成开发与文档定制。
5. 用户市场说明写入根 `README.md`Agent 调用契约见 `references/CLI.md``references/SCHEMA.md``references/ACTIONS.md` 5. 用户市场四 Tab 材料写入根 `README.md` / `TUTORIAL.md` / `DEMO.md` / `CHANGELOG.md`Agent 调用契约见 `references/CLI.md``references/SCHEMA.md``references/ACTIONS.md`
6. 同步修改 `scripts/util/constants.py` 中的 `SKILL_SLUG` / `SKILL_VERSION` 6. 同步修改 `scripts/util/constants.py` 中的 `SKILL_SLUG` / `SKILL_VERSION`
7. 本地 SQLite 的中文表名/字段名、标准时间字段与字段顺序规范见 `references/SCHEMA.md`(元数据表 `_jiangchang_*` + `CREATE TABLE` 物理顺序) 7. 本地 SQLite 的中文表名/字段名、标准时间字段与字段顺序规范见 `references/SCHEMA.md`
## 技能命名与 slug ## 技能命名与 slug

65
TUTORIAL.md Normal file
View File

@@ -0,0 +1,65 @@
> **模板说明(复制后删除本段)**
> 本文对应技能市场 **「使用教程」** Tab发布时同步为 `tutorial_md`)。
> 面向普通用户写**可跟着做的步骤**,不要写 CLI、目录结构、release、开发规范。
> 与根 `README.md`技能说明分工README 讲「是什么 / 能做什么」;本文讲「第一次怎么用完」。
> **复制后验收章节(标题可微调):**「开始前」「第一步…」「第二步…」「常见卡住怎么办」。
# 【技能名称】使用教程
用最短路径带用户完成一次成功使用。步骤要具体,可用「打开匠厂 → …」这类操作语言。
---
## 开始前
确认:
1. 已安装并登录匠厂客户端
2. 已在技能市场安装本技能(或更新到最新版)
3. 【网页自动化类技能】首次运行一般会自动登记本平台账号;也可在「账号管理」中指定登录标识。浏览器会话由系统隔离管理——**不要**用本机日常浏览器用户目录去跑真实站
4. 【按平台】若本技能说明「需要先登录目标站」,请在弹出的有头浏览器中按提示登录或扫码;「登记账号」不等于「已登录目标站」。若说明「可不登录也能用」,仍须有可用的账号会话目录
5. 【如需】需要的文件 / 时间范围 / 单号等已准备好
---
## 第一步:打开技能并说清目标
在匠厂里新建任务或打开对话,用自然语言说明要做什么,例如:
> “帮我【完成某件业务事】,范围是【时间 / 对象 / 条件】。”
建议一次只交代一件事;范围说清楚,减少来回确认。
---
## 第二步:按提示补充信息
如果 Agent 问你缺什么(账号、文件、筛选条件),按提示补充即可。
- 有文件时:按界面提示选择或拖入
- 有账号时:确认已在对应平台登录,且具备操作权限
---
## 第三步:等待结果并核对
任务结束后,请核对:
- 是否成功完成
- 处理了多少条 / 哪些失败
- 生成的文件、表格或记录是否在预期位置
若失败,先看失败原因说明,再按下一节排查。
---
## 常见卡住怎么办
| 现象 | 你可以先试 |
|------|------------|
| 提示未登录 / 无权限 | 确认匠厂已登录;业务账号是否在线、权限是否足够 |
| 提示缺少必要信息 | 把时间范围、单号、文件等说完整后再试一次 |
| 一直没有结果 | 到任务中心查看进度或失败原因;必要时重新发起 |
| 结果不对 | 用更明确的条件再说一次,或缩小范围重试 |
仍无法解决时,把「你说了什么 + 界面提示原文」发给支持人员,便于排查。

View File

@@ -1,11 +1,11 @@
# assets # assets
- `actions.json`Skill Action manifest 最小示例(**可选**;不需要宿主入口时可删除)。 - `actions.json`Skill Action manifest 最小示例(**可选**;不需要宿主入口时可删除)。每个 action **必须**显式声明 `executionProfile``sync` \| `async`)。默认仅 `health` / `version` / `config-path`,不放 toolbar故无 `bind` 示例。
- `examples/`CLI 成功输出形状示例(虚构路径与数据)。 - `examples/`CLI 成功输出形状示例(虚构路径与数据)。
- `schemas/`:轻量 JSON Schema`skill-actions.schema.json` 为**新技能严格规范**`task-log-record.schema.json` 等)。 - `schemas/`:轻量 JSON Schema`skill-actions.schema.json` 为**新技能严格规范**`task-log-record.schema.json` 等)。
`skill-actions.schema.json` 使用 `additionalProperties: false` 表达模板推荐契约;宿主运行时可能更宽松以兼容历史 manifest。`row`/`batch` placements 与 `bind`/`concurrency`/`locks` 为预留能力,当前模板示例不得使用 `skill-actions.schema.json` 使用 `additionalProperties: false`。正式支持 `bind.tables`toolbar Action 必填);`row`/`batch` placements 与 `concurrency`/`locks` 为预留`placements``executionProfile` 正交——进任务中心只看 `async`,与入口无关。表级 Action 与 Agent 契约见 [`references/ACTIONS.md`](../references/ACTIONS.md);开发深度规范见 [`development/SKILL_ACTION_RUNTIME.md`](../development/SKILL_ACTION_RUNTIME.md)
- 用户市场说明见根目录 [`README.md`](../README.md) - 用户市场四 Tab 见根目录 [`README.md`](../README.md) / [`TUTORIAL.md`](../TUTORIAL.md) / [`DEMO.md`](../DEMO.md) / [`CHANGELOG.md`](../CHANGELOG.md)
- Agent 调用/编排参考见 [`references/`](../references/)(含 [`ACTIONS.md`](../references/ACTIONS.md) - Agent 调用/编排参考见 [`references/`](../references/)(含 [`ACTIONS.md`](../references/ACTIONS.md)
- 开发规范见 [`development/`](../development/) - 开发规范见 [`development/`](../development/)

View File

@@ -5,8 +5,9 @@
{ {
"id": "health", "id": "health",
"label": "运行检查", "label": "运行检查",
"description": "检查技能运行环境并返回结构化结果。", "description": "检查技能运行环境并返回结构化结果,不启动浏览器。",
"placements": ["skill-detail", "agent"], "placements": ["skill-detail", "agent"],
"executionProfile": "sync",
"entrypoint": { "entrypoint": {
"type": "cli", "type": "cli",
"command": "health", "command": "health",
@@ -18,6 +19,7 @@
"label": "查看版本", "label": "查看版本",
"description": "返回技能版本和机器标识。", "description": "返回技能版本和机器标识。",
"placements": ["skill-detail"], "placements": ["skill-detail"],
"executionProfile": "sync",
"entrypoint": { "entrypoint": {
"type": "cli", "type": "cli",
"command": "version", "command": "version",
@@ -29,6 +31,7 @@
"label": "查看配置位置", "label": "查看配置位置",
"description": "返回技能配置文件位置。", "description": "返回技能配置文件位置。",
"placements": ["skill-detail"], "placements": ["skill-detail"],
"executionProfile": "sync",
"entrypoint": { "entrypoint": {
"type": "cli", "type": "cli",
"command": "config-path", "command": "config-path",

View File

@@ -26,7 +26,7 @@
"placement": { "placement": {
"type": "string", "type": "string",
"enum": ["toolbar", "row", "batch", "cron", "agent", "skill-detail"], "enum": ["toolbar", "row", "batch", "cron", "agent", "skill-detail"],
"description": "模板 Phase 1 稳定支持 toolbar/cron/agent/skill-detailrow/batch 为预留入口,新技能示例不得使用" "description": "稳定支持 toolbar/cron/agent/skill-detailrow/batch 为预留入口,新技能示例不得使用。placements 与 executionProfile 正交,不做条件限制。"
}, },
"scalarArg": { "scalarArg": {
"type": ["string", "number", "boolean"] "type": ["string", "number", "boolean"]
@@ -95,9 +95,29 @@
} }
} }
}, },
"bind": {
"type": "object",
"required": ["tables"],
"additionalProperties": false,
"properties": {
"tables": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"type": "string",
"minLength": 1,
"pattern": "^[a-z][a-z0-9_]*$",
"description": "英文 snake_case 业务表名;须真实存在于技能 SQLite / _jiangchang_tables"
},
"description": "数据管理表级绑定:决定 toolbar Action 出现在哪些表。宿主兼容旧技能时,缺失 bind 可视为全表展示;新技能 toolbar Action 必须显式声明。"
}
},
"description": "Phase 1 仅沉淀 bind.tables不包含 selection/inputMapping/columns/row/concurrency/locks"
},
"action": { "action": {
"type": "object", "type": "object",
"required": ["id", "label", "description", "placements", "entrypoint"], "required": ["id", "label", "description", "placements", "entrypoint", "executionProfile"],
"additionalProperties": false, "additionalProperties": false,
"properties": { "properties": {
"id": { "id": {
@@ -116,13 +136,31 @@
"placements": { "placements": {
"type": "array", "type": "array",
"minItems": 1, "minItems": 1,
"items": { "$ref": "#/$defs/placement" } "items": { "$ref": "#/$defs/placement" },
"description": "决定 Action 出现在哪里;与 executionProfile 正交"
}, },
"entrypoint": { "$ref": "#/$defs/entrypoint" }, "entrypoint": { "$ref": "#/$defs/entrypoint" },
"inputSchema": { "$ref": "#/$defs/inputSchema" }, "inputSchema": { "$ref": "#/$defs/inputSchema" },
"confirmation": { "$ref": "#/$defs/confirmation" } "confirmation": { "$ref": "#/$defs/confirmation" },
"executionProfile": {
"type": "string",
"enum": ["sync", "async"],
"description": "sync=调用方等待结构化结果(不建 Jobasync=宿主建后台 Job 并进任务中心。必须显式写出;长耗时建议 async但不限制 placements。"
},
"bind": { "$ref": "#/$defs/bind" }
}, },
"description": "模板 Phase 1 不包含 bind/concurrency/locks 等预留能力字段;宿主类型可能定义这些字段,但新技能不得依赖" "if": {
"properties": {
"placements": {
"contains": { "const": "toolbar" }
}
},
"required": ["placements"]
},
"then": {
"required": ["bind"]
},
"description": "concurrency/locks 为未稳定预留字段,勿写入新技能 manifest。placements 含 toolbar 时必须声明 bind.tables。"
} }
} }
} }

View File

@@ -100,7 +100,9 @@ def get_adapter():
2. **普通兄弟技能调用**,优先走统一 **`service.sibling_bridge`**`call_sibling_json`**不要**在 `task_service.py``task_rpa.py` 等业务流程文件中到处散落 `subprocess.run` 2. **普通兄弟技能调用**,优先走统一 **`service.sibling_bridge`**`call_sibling_json`**不要**在 `task_service.py``task_rpa.py` 等业务流程文件中到处散落 `subprocess.run`
3. **account-manager 账号/租约能力**是例外:可参考 `examples/real_browser_rpa/scripts/service/account_client.py` 与 `examples/simulator_browser_rpa/scripts/service/account_client.py`,封装为**单一** `account_client.py`;允许在该文件内部集中通过 subprocess 调 account-manager CLI。**禁止** import `rpa_helpers` 等 account-manager 内部模块;`simulator_rpa``real_rpa` 均走同一 `pick_web_account` / `release_lease` 模式。 3. **account-manager 账号/租约能力**是例外:可参考 `examples/real_browser_rpa/scripts/service/account_client.py` 与 `examples/simulator_browser_rpa/scripts/service/account_client.py`,封装为**单一** `account_client.py`;允许在该文件内部集中通过 subprocess 调 account-manager CLI。**禁止** import `rpa_helpers` 等 account-manager 内部模块;`simulator_rpa``real_rpa` 均走同一 `pick_web_account` / `release_lease` 模式。
4. **不允许**直接 `import account-manager` 的内部 Python 模块(如 `service/``util/``db/`)。 4. **不允许**直接 `import account-manager` 的内部 Python 模块(如 `service/``util/``db/`)。
5. **pick lease 后必须 `finally release lease`**;进程被 kill 后可能残留 lease需在运维文档说明排查方式查 account-manager lease 列表 / 手动释放)。 5. **pick/ensure lease 后必须 `finally release lease`**;进程被 kill 后可能残留 lease需在运维文档说明排查方式查 account-manager lease 列表 / 手动释放)。
6. **网页 RPA 硬规则**(详见 [`RPA.md`](RPA.md) §0.2):必须先经 `pick_web_account`(底层 **`ensure-web` / `pick-web --ensure`**)拿到 `profile_dir` 再开浏览器;拿不到则失败退出;生产有头;**是否站点登录**按平台约定,但**不等于**可以跳过 account-manager。登记账号 ≠ 站点已登录。
7. **账号选择优先级**:纯数字 `DEFAULT_ACCOUNT_ID``get <id>``DEFAULT_LOGIN_ID` / 非数字标识 → `ensure-web --login-id`;皆空 → 按平台 `ensure-web`。人读展示优先 `login_id` / `account_label`,不要只用数字 id。多条匹配 → `ERROR:AMBIGUOUS_ACCOUNT`
```python ```python
# 普通兄弟技能 — 走 sibling_bridge # 普通兄弟技能 — 走 sibling_bridge
@@ -110,10 +112,10 @@ result = call_sibling_json("account-manager", ["list", "--limit", "10"])
``` ```
```python ```python
# account-manager 账号/租约 — 集中在 account_client.py # account-manager 账号/租约 — 集中在 account_client.pyensure-web
from service.account_client import pick_web_account, release_lease from service.account_client import pick_web_account, release_lease
account = pick_web_account(platform="target_platform") account = pick_web_account(platform="target_platform", login_id=None)
try: try:
... ...
finally: finally:

View File

@@ -11,36 +11,119 @@
4. **技能升级合并缺失项**`merge_missing_env_keys` 会把 `.env.example` 中新增、但用户 `.env` 尚未包含的 key **追加**进去(带注释块)。 4. **技能升级合并缺失项**`merge_missing_env_keys` 会把 `.env.example` 中新增、但用户 `.env` 尚未包含的 key **追加**进去(带注释块)。
5. **敏感信息绝不进 `.env`**:密码/密钥/口令走 account-manager 的 `secret-ref`(见下"红线")。 5. **敏感信息绝不进 `.env`**:密码/密钥/口令走 account-manager 的 `secret-ref`(见下"红线")。
## 标准配置项(`.env` 分组 ## `.env.example` 注释 = 配置管理用户文案(硬规则
每个 skill 的 `.env.example` 至少包含这些通用项(按需增减): 匠厂宿主「数据管理 → 配置管理」会把 `.env` / `.env.example` 的注释展示给**最终用户**(英文 key 可保留作标题)。因此注释必须按**产品文案**来写,不能按开发备忘录来写。
### 行头与行尾分工
| 位置 | 职责 | 要求 |
|------|------|------|
| **行头**`KEY=` 上一行的 `# …` | **是什么**:中文说明该配置项干什么 | **每个活跃 key 必有**一行完整中文行头 |
| **行尾**`KEY=值` 同一行 ` #` 之后) | **怎么填**:可选值、单位、推荐默认、何时要改 | 有枚举、开关、单位时**必有**;纯自由文本也应尽量写清填法 |
宿主当前会把「行头 + 行尾」拼成 key 下方的多行说明。按上表书写后,用户看到的自然是「先懂是什么,再知道怎么填」。
**不要**依赖 `# ── 分组 ──` 装饰线给整组做唯一说明:宿主只会把行头挂到**紧挨着的下一个活跃 key**,后面的 key 不会自动继承。分组可用空行区分;**逐 key 自带行头(+ 行尾)才是硬要求**。
### 必须做到
1. 每个会进入配置管理的活跃 `KEY=` 都有完整中文**行头**。
2. 枚举 / `0|1` 开关 / 带单位的数值:必须有中文**行尾**,解释每个可选值或单位,并给出推荐。
3. 业务专属 key 同样适用本规则,不得只留英文 key、不写中文说明。
4. 开发向细节(四档 adapter 实现、录屏管线、路径解析 API写在 `development/ADAPTER.md``RPA.md``DATA_PATHS.md` 等文档;**禁止**写进 `.env.example` 注释。
**机器门禁**`POLICY-CONFIG-004``tests/test_development_policy_guard.py`)会在默认测试 / `release.ps1` 中校验上述「行头+行尾中文、禁止开发文档指向」;不通过不得发布。
### 禁止出现在注释中的内容
- `见 development/...``见 ADAPTER.md``见 RPA.md``见 DATA_PATHS.md` 等仓库文档指向
- 默认假设读者是开发者的黑话:如单独甩 `adapter 档位``CI``account-manager``CWD``workspace` 而不解释
- 只写裸枚举(如 `mock | real_rpa`)却不说明每个值对用户意味着什么
- 多个 key 共用一个行头,后面的 key 没有任何自己的说明
若必须提到账号体系:写成用户能懂的「请在账号管理中登记密码 / 平台标识须一致」,不要只写内部模块名。
### 正例
```ini ```ini
# ── 运行模式 / adapter 档位(见 ADAPTER.md── # 运行模式:决定本技能用模拟数据还是真实浏览器/接口去执行
OPENCLAW_TEST_TARGET=mock # mock | simulator_rpa | real_api | real_rpa OPENCLAW_TEST_TARGET=mock # 可选mock=本地模拟,simulator_rpa=仿真站点,real_api=真实接口real_rpa=真实浏览器;模板默认 mock日常正式使用请改为 real_rpa
# ── 目标系统(示例占位,复制后改为业务地址)── # 是否显示浏览器窗口:网页自动化时是否弹出可见浏览器
TARGET_BASE_URL=https://sandbox.jc2009.com OPENCLAW_BROWSER_HEADLESS=0 # 0=显示窗口必须便于介入与排查1=后台静默(勿作日常用法)
# ── 默认账号(仅非敏感标识;密码走 account-manager──
# 浏览器 RPA simulator_rpa 联调账号来自 account-managerplatform + profile_dir不是此处的 DEFAULT_LOGIN_ID
DEFAULT_LOGIN_ID=04110001
# ── 浏览器 / RPA ──
OPENCLAW_BROWSER_HEADLESS=0 # 0=有头(默认) 1=无头(CI)
OPENCLAW_PLAYWRIGHT_STEALTH=1 # 1=开启反检测指纹(默认)
# ── 录屏与失败存证 ──
OPENCLAW_RECORD_VIDEO=1 # 1=录屏+字幕+旁白+背景音+MP4RPA 默认开,见 RPA.md
OPENCLAW_ARTIFACTS_ON_FAILURE=1 # 1=失败截图(默认)
# ── 节流 / 超时 ──
STEP_DELAY_MIN=1.0
STEP_DELAY_MAX=5.0
HUMAN_WAIT_TIMEOUT=180 # 滑块/验证码/2FA 等人工超时(秒)
``` ```
**业务专属配置必须带技能前缀**(如 `DEMO_XXX``MY_SKILL_XXX`**不要污染全局命名空间**(禁止 `SCRAPE_1688_*``RECEIVE_ORDER_*` 等跨技能前缀写入模板)。 ### 反例(禁止)
```ini
# ── 运行模式 / adapter 档位(见 development/ADAPTER.md──
OPENCLAW_TEST_TARGET=real_rpa # 生产默认真实 RPA单测/CI 可改为 mock
# ── 好看视频 / 百度账号(须与 account-manager 平台 key 一致)──
TARGET_PLATFORM=baidu
HAOKAN_VIDEO_SELECTOR=video.art-video
```
问题:文档路径与开发黑话;行尾半给用户半给 CI后续 key 无行头/行尾,用户只看到英文名。
## 标准配置项(`.env` 分组)
每个 skill 的 `.env.example` 至少包含这些通用项(按需增减)。**注释写法须与仓库根目录 `.env.example` 保持同级清晰度**(行头 = 是什么,行尾 = 怎么填):
```ini
# 运行模式:决定本技能用模拟数据还是真实浏览器/接口去执行
OPENCLAW_TEST_TARGET=mock # 可选mock=本地模拟simulator_rpa=仿真站点real_api=真实接口real_rpa=真实浏览器;模板默认 mock日常正式使用请改为 real_rpa
# 目标网站地址:技能要访问的网站或服务地址
TARGET_BASE_URL=https://sandbox.jc2009.com # 填写完整网址(含 https://);换环境时再改,一般保持默认即可
# 默认登录账号:仅填写非敏感的账号标识(如工号/登录名)
DEFAULT_LOGIN_ID= # 留空=按平台自动选用或登记;有值则按该标识筛选;不要填密码
# 默认账号编号:仅填账号管理里的纯数字主键(一般留空)
DEFAULT_ACCOUNT_ID= # 留空=自动;只填纯数字;手机号/用户名请填上方登录账号
# 是否显示浏览器窗口:网页自动化时是否弹出可见浏览器
OPENCLAW_BROWSER_HEADLESS=0 # 0=显示窗口必须便于介入与排查1=后台静默(勿作日常用法)
# 浏览器防检测:降低被网站识别为自动化工具的概率
OPENCLAW_PLAYWRIGHT_STEALTH=1 # 1=开启推荐0=关闭;一般保持默认
# 是否录制操作过程:用于留证、复现问题或向他人演示
OPENCLAW_RECORD_VIDEO=0 # 0=不录屏默认1=录屏并生成带说明的视频文件;需要留证时再改为 1
# 失败时是否截图:任务出错时自动保存现场截图,便于排查
OPENCLAW_ARTIFACTS_ON_FAILURE=1 # 1=失败时截图推荐0=不截图
# 步骤最短等待:两步操作之间随机停顿的下限,模拟真人节奏
STEP_DELAY_MIN=1.0 # 单位:秒;一般保持默认,页面不稳定时可略调大
# 步骤最长等待:两步操作之间随机停顿的上限
STEP_DELAY_MAX=5.0 # 单位:秒;须大于等于最短等待;一般保持默认
# 人工处理超时:遇到滑块、验证码、二次验证时,等待人工处理的最长时间
HUMAN_WAIT_TIMEOUT=180 # 单位:秒;来不及处理时可调大,如 300
```
四档运行模式的**实现与测试约定**见 [`ADAPTER.md`](ADAPTER.md);录屏管线见 [`RPA.md`](RPA.md)。这些内容**不要**写回 `.env.example` 注释。
**业务专属配置必须带技能前缀**(如 `DEMO_XXX``MY_SKILL_XXX``SKILL_DOWNLOAD_DIR`**不要污染全局命名空间**(禁止 `SCRAPE_1688_*``RECEIVE_ORDER_*` 等跨技能前缀写入模板)。
### 数据目录子路径(下载 / 导入 / 导出)
技能**自己写入**的文件默认在 `{JIANGCHANG_DATA_ROOT}/{USER_ID}/{slug}/` 下标准子目录(`downloads/``imports/``exports/` 等)。须通过 `util.runtime_paths.resolve_data_path()``get_*_dir()` 解析,**禁止** `os.path.abspath(config.get(...))` 相对 CWD。
- 权威说明(开发):[`DATA_PATHS.md`](DATA_PATHS.md)
- `.env.example` 中路径类配置**留空或保持注释即用默认**;若写相对路径,必须相对 **skill 数据目录****禁止** `./outputs/...` 这类相对 workspace 的写法
- 可选 env`SKILL_DOWNLOAD_DIR``SKILL_IMPORT_DIR``SKILL_EXPORT_DIR` 等;若作为活跃 key 出现在配置管理中,同样须有用户向行头/行尾(见模板根 `.env.example`
### 录屏开关(`OPENCLAW_RECORD_VIDEO`
- **模板默认 `OPENCLAW_RECORD_VIDEO=0`**,降低本地开发 / 调试成本(不启 ffmpeg、不生成 MP4
- 需要**生产留证、合规记录、客户现场复现或排障**时,可在用户 `.env` 或进程环境变量中设为 `OPENCLAW_RECORD_VIDEO=1`
- **默认关闭不代表可以删除录屏接入**RPA / 长任务代码仍须保留 `RpaVideoSession``video.add_step` 与 video artifact 写入 `result_summary`(见 `RPA.md` §5.3)。
- **已落盘的用户 `.env` 不会被模板整体覆盖**;老用户保留原值,技能升级时仅通过 `merge_missing_env_keys` **追加** `.env.example` 中新增的 key。
## 🚫 红线:敏感信息不进 `.env` ## 🚫 红线:敏感信息不进 `.env`
@@ -81,10 +164,20 @@ config.get_bool("OPENCLAW_BROWSER_HEADLESS")
config.get_float("STEP_DELAY_MIN", 1.0) config.get_float("STEP_DELAY_MIN", 1.0)
``` ```
### 空值、行尾注释与假默认(硬规则)
- **留空即未配置**`KEY=``KEY= # 说明` 必须读成空字符串,再走技能自己的「自动 / ensure」逻辑**禁止**把示例说明、`# 可填…` 当成真实配置值。
- **需要 platform-kit ≥ 1.2.2**:旧版解析曾把「空值 + 行尾 `#`」误当成 `# 可填…` 这种假值。技能若依赖正确空值语义,须在 `SKILL.md` 声明 `platform_kit_min_version: "1.2.2"`(或更高)。
- **网页账号配置语义**(有则用):
- `DEFAULT_ACCOUNT_ID`:仅**纯数字**视为账号主键;非数字非空可当 login_id不推荐优先用 `DEFAULT_LOGIN_ID`
- `DEFAULT_LOGIN_ID`:手机号 / 用户名等;留空则按平台 `ensure-web`
- 占位串(`#…``none``n/a``default-account`)一律当未配置
- **不要**在 `.env.example` 里塞「看起来像真值」的演示账号(如假手机号),以免首次落盘后被当成用户配置。
## health / config-path ## health / config-path
- **`health`**:输出 `collect_runtime_diagnostics` 字段(`platform_kit_version_ok``ffmpeg_path` 等),**不打印敏感值**;补充 `env_path` / `env_exists` / `example_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` 绝对路径),便于排查落盘位置。 - **`config-path`**:输出 JSON包含 `skill``env_path`(用户数据目录 `.env`)、`example_path`(仓库 `.env.example` 绝对路径),便于排查落盘位置;业务 skill 建议附加 `list_resolved_data_paths()` 中的子目录路径(见 [`DATA_PATHS.md`](DATA_PATHS.md)
## doctor / setup 命令(可选) ## doctor / setup 命令(可选)
@@ -95,6 +188,7 @@ config.get_float("STEP_DELAY_MIN", 1.0)
## 相关文档 ## 相关文档
- `RPA.md` — 三端 RPA 标准与各开关含义 - `RPA.md` — 三端 RPA 标准与各开关含义(开发向;勿写入 `.env` 注释)
- `ADAPTER.md``OPENCLAW_TEST_TARGET` 四档模式 - `ADAPTER.md``OPENCLAW_TEST_TARGET` 四档模式(开发向;勿写入 `.env` 注释)
- `RUNTIME.md``JIANGCHANG_*` 环境变量与数据目录约定 - `RUNTIME.md``JIANGCHANG_DATA_ROOT` 与数据约定
- `DATA_PATHS.md` — 下载/导入/导出等子目录与 `resolve_data_path` 规范

160
development/DATA_PATHS.md Normal file
View File

@@ -0,0 +1,160 @@
# 用户数据目录与文件路径黄金标准
> 本文是 skill **读写本地文件** 的权威约定。凡涉及下载、导入、导出、缓存、RPA 存证等路径复制模板后须遵守本文Agent 实现业务 skill 时也应先读本文。
---
## 1. 根目录
所有技能持久化数据(配置、数据库、业务文件)默认落在:
```text
{JIANGCHANG_DATA_ROOT}/{JIANGCHANG_USER_ID}/{skill_slug}/
```
示例:
```text
D:\jiangchang-data\12500\download-video-baidu-haokan\
```
实现:`util.runtime_paths.get_skill_data_dir()`
**禁止**把技能自己写入的文件落到:
- Agent / 宿主 **workspace**(进程 CWD
- 技能安装目录(含 `.openclaw/skills/...`
- 未在本文声明的任意相对 CWD 路径
---
## 2. 标准子目录树
| 子目录 | 用途 | 默认 helper |
|--------|------|-------------|
| `downloads/` | 从外部拉取的原始文件视频、回单、PDF… | `get_downloads_dir()` |
| `imports/` | 用户/Agent 放入的待处理清单urls.txt、batch.json、CSV | `get_imports_dir()` |
| `exports/` | 导出给用户的结果xlsx/csv/json | `get_exports_dir()` |
| `uploads/` | 待发布到外部平台的 staging可选 | `get_uploads_dir()` |
| `cache/` | 可再生缓存(页面快照、解析中间结果) | `get_cache_dir()` |
| `temp/` | 单次任务 scratch任务结束可删 | `get_temp_dir()` |
| `rpa-artifacts/` | RPA 失败截图、录屏中间产物 | `get_rpa_artifacts_dir(batch_id)` |
| `videos/` | RPA 录屏成片 MP4 | `get_videos_dir()` |
| `{skill_slug}.db` | SQLite | `get_db_path()` |
| `.env` | 用户配置 | `config.get_env_file_path()` |
复制后若业务不需要某目录,可不创建;**但一旦写入该类文件,必须走对应 helper**。
---
## 3. 两类路径
### A. 技能拥有skill-owned
技能**创建或更新**的文件:下载结果、导出报表、失败截图、队列 sidecar 等。
- **默认**必须在 `{skill_data_dir}/<子目录>/` 下。
- **必须**通过 `resolve_data_path()``get_*_dir()` 解析,**禁止** `os.path.abspath(config.get(...))` 相对 CWD。
### B. 用户显式输入user-owned
用户在 CLI / Agent 对话中给出的**已有文件**绝对路径,例如「发布这个视频 `D:\素材\x.mp4`」。
- 技能**只读**,路径可以是用户磁盘任意位置。
- 使用 `resolve_input_path()`:绝对路径原样;**相对路径**解析为 `{skill_data_dir}/imports/<相对路径>`**不**相对 workspace/CWD。
---
## 4. 配置项(`.env`
可选覆盖项(**留空则用默认子目录**
```ini
# ── 数据目录子路径(见 development/DATA_PATHS.md──
# 相对路径相对于 {JIANGCHANG_DATA_ROOT}/{USER_ID}/{slug}/,不是 workspace
# SKILL_DOWNLOAD_DIR=downloads/videos
# SKILL_IMPORT_DIR=imports
# SKILL_EXPORT_DIR=exports
# SKILL_UPLOAD_DIR=uploads
# SKILL_CACHE_DIR=cache
# SKILL_TEMP_DIR=temp
```
| 规则 | 说明 |
|------|------|
| 未配置 | `{skill_data_dir}/{default_subdir}` |
| 相对值 `downloads/videos` | `{skill_data_dir}/downloads/videos` |
| 绝对值 `D:\nas\exports` | 高级用户/NAS 挂载,原样使用 |
| **禁止** `./outputs/...` | 会随 CWD 漂移,不得作为 `.env.example` 活跃配置行 |
业务专属路径 env key 须带 **`SKILL_` 前缀**(或技能 slug 前缀),避免污染全局命名空间。
---
## 5. 代码用法
```python
from util.runtime_paths import (
get_downloads_dir,
get_imports_dir,
resolve_data_path,
resolve_input_path,
list_resolved_data_paths,
)
# 下载保存A 类)
dest = os.path.join(get_downloads_dir(), f"{vid}.mp4")
# 或带 env 覆盖
out_dir = resolve_data_path("SKILL_DOWNLOAD_DIR", "downloads")
# CLI -i urls.txtB 类,相对路径 → imports/
manifest = resolve_input_path(args.input_path)
# health 诊断
paths = list_resolved_data_paths()
```
**反模式(禁止):**
```python
# ❌ 相对 CWDAgent 从 workspace 执行时会写错盘
os.path.abspath(config.get("DOWNLOAD_OUTPUT_DIR"))
# ❌ .env.example 里写 ./outputs/videos
DOWNLOAD_OUTPUT_DIR=./outputs/videos
```
---
## 6. health / config-path
`health``config-path` 建议输出 `list_resolved_data_paths()` 中的路径,便于排查「文件写到哪里去了」。展示路径须与 `run` 实际使用的一致。
---
## 7. 与 RPA 存证的关系
- 失败截图、录屏中间文件:`rpa-artifacts/{batch_id}/`(见 [`RPA.md`](RPA.md) §5.1
- 录屏成片:`videos/`(见 [`RPA.md`](RPA.md) §5.3
业务 `downloads/` 与 RPA `videos/` **分工不同**:前者是业务产出文件,后者是操作过程录屏。
---
## 8. 测试
- 单元测试须用 `IsolatedDataRoot`,断言路径落在临时数据根下。
- `tests/test_runtime_paths.py` 覆盖 `resolve_data_path` / `resolve_input_path`
- `POLICY-DATA-PATH-001`:禁止 `.env.example``./` 路径;禁止业务代码 `abspath(config.get(...))`
---
## 9. 相关文档
| 文档 | 内容 |
|------|------|
| [`RUNTIME.md`](RUNTIME.md) | 数据根、共享 runtime、编码 |
| [`CONFIG.md`](CONFIG.md) | `.env` bootstrap 与三层优先级 |
| [`RPA.md`](RPA.md) | rpa-artifacts / videos 存证 |
| [`POLICY_MATRIX.md`](POLICY_MATRIX.md) | POLICY-DATA-PATH-001 |

View File

@@ -106,6 +106,9 @@ your-skill/
├─ tests/ ├─ tests/
├─ .gitignore ├─ .gitignore
├─ README.md ├─ README.md
├─ TUTORIAL.md
├─ DEMO.md
├─ CHANGELOG.md
├─ requirements.txt ├─ requirements.txt
├─ release.ps1 ├─ release.ps1
└─ SKILL.md └─ SKILL.md
@@ -114,7 +117,10 @@ your-skill/
各目录职责如下: 各目录职责如下:
- `assets/`放示例输出、schema、静态说明资源 - `assets/`放示例输出、schema、静态说明资源
- `README.md`面向用户的市场详情页说明 - `README.md`市场 **说明** Tab`readme_md`
- `TUTORIAL.md`:市场 **教程** Tab`tutorial_md`
- `DEMO.md`:市场 **演示** Tab`demo_video_url` + `demo_md`
- `CHANGELOG.md`:市场 **更新日志** Tab按版本小节同步 `changelog`
- `SKILL.md`:面向 LLM / 平台的技能入口 - `SKILL.md`:面向 LLM / 平台的技能入口
- `references/`Agent 运行/编排/调用时渐进加载的补充上下文(如 CLI、SCHEMA - `references/`Agent 运行/编排/调用时渐进加载的补充上下文(如 CLI、SCHEMA
- `development/`:面向开发者与 AI 编程代理的开发资料、需求、测试与技术规范 - `development/`:面向开发者与 AI 编程代理的开发资料、需求、测试与技术规范
@@ -158,13 +164,13 @@ scripts/
作用:常量、日志、路径、时间工具、通用帮助函数 作用:常量、日志、路径、时间工具、通用帮助函数
`util/logging_config.py``jiangchang_skill_core.unified_logging` 的**薄封装**,业务代码应通过它获取 logger `util/logging_config.py``jiangchang_skill_core.unified_logging` 的**薄封装**,业务代码应通过它获取 logger
公共能力config、logging、runtime_env、rpa、media_assets、video_session、runtime_diagnostics从共享 runtime 的 `jiangchang-platform-kit>=1.0.17` import**不得**在 `scripts/` 下保留 `jiangchang_skill_core/` 副本。 公共能力config、logging、runtime_env、rpa、media_assets、video_session、runtime_diagnostics、activity/SRCP)从共享 runtime 的 `jiangchang-platform-kit>=1.2.2` import**不得**在 `scripts/` 下保留 `jiangchang_skill_core/` 副本。
## 3.2 开发 RPA 类 skill ## 3.2 开发 RPA 类 skill
若 skill 需要浏览器/桌面/手机自动化,按以下顺序落地: 若 skill 需要浏览器/桌面/手机自动化,按以下顺序落地:
1. **先读三份标准**`RPA.md`三端范式与反反爬)、`CONFIG.md``.env` 落盘与读取)、`ADAPTER.md`(四档 adapter 1. **先读三份标准**`RPA.md`含 §0.2Profile 强制 / 有头 / 登录分平台)、`CONFIG.md``.env` 落盘与读取)、`ADAPTER.md`(四档 adapter
2. **从 examples 选择性复制**(不要整包照搬 `examples/<mode>/`,见各 example README 的 copy map 2. **从 examples 选择性复制**(不要整包照搬 `examples/<mode>/`,见各 example README 的 copy map
- 若是 **真实浏览器 RPA**(真实网站、登录态、验证码、滚动采集),**必须先读** `examples/real_browser_rpa/README.md`,再按需复制到 `scripts/service/` - 若是 **真实浏览器 RPA**(真实网站、登录态、验证码、滚动采集),**必须先读** `examples/real_browser_rpa/README.md`,再按需复制到 `scripts/service/`
- `examples/real_browser_rpa/scripts/service/browser_session.py` - `examples/real_browser_rpa/scripts/service/browser_session.py`
@@ -179,6 +185,7 @@ scripts/
- `examples/simulator_browser_rpa/scripts/service/task_service.py`async 编排) - `examples/simulator_browser_rpa/scripts/service/task_service.py`async 编排)
- `sandbox/demo_app.html` 仅留在 examples不进入生产 skill - `sandbox/demo_app.html` 仅留在 examples不进入生产 skill
- **禁止**`rpa_helpers`、sync Playwright 用于完整技能 RPA 主路径、`task_service` 散落 account-manager subprocess - **禁止**`rpa_helpers`、sync Playwright 用于完整技能 RPA 主路径、`task_service` 散落 account-manager subprocess
- **网页硬规则**:未拿到 `profile_dir` 禁止开浏览器;生产 `OPENCLAW_BROWSER_HEADLESS=0`;站点是否登录写进 REQUIREMENTS / 用户教程,**不要**写成「可不接 account-manager」
3. **只用共享库,不在 skill 里重写反反爬** 3. **只用共享库,不在 skill 里重写反反爬**
```python ```python
from jiangchang_skill_core import config from jiangchang_skill_core import config
@@ -195,7 +202,7 @@ scripts/
技能根目录的 `requirements.txt` 是**标准文件**,用于声明本技能**特有** Python 三方依赖。 技能根目录的 `requirements.txt` 是**标准文件**,用于声明本技能**特有** Python 三方依赖。
- **公共依赖**`jiangchang-platform-kit`、`playwright`、config、runtime diagnostics、RPA 公共能力等)由**宿主共享 runtime** 提供,**不要**写入技能 `requirements.txt`。 - **公共依赖**`jiangchang-platform-kit`、`playwright`、config、runtime diagnostics、RPA 公共能力等)由**宿主共享 runtime** 提供,**不要**写入技能 `requirements.txt`。
- `SKILL.md` 的 `metadata.openclaw.platform_kit_min_version`(当前 `1.0.17`)是运行契约/兼容性声明,供宿主安装与启用时校验,**不是** pip 依赖声明。 - `SKILL.md` 的 `metadata.openclaw.platform_kit_min_version`(当前 `1.2.2`)是运行契约/兼容性声明,供宿主安装与启用时校验,**不是** pip 依赖声明。
- 匠厂宿主安装/更新技能后,会将技能 `requirements.txt` 安装到共享 venv`{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`。 - 匠厂宿主安装/更新技能后,会将技能 `requirements.txt` 安装到共享 venv`{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`。
- **不要**在业务代码中 `subprocess` / `pip install`;缺依赖由 `health` 报错,由宿主负责安装。 - **不要**在业务代码中 `subprocess` / `pip install`;缺依赖由 `health` 报错,由宿主负责安装。
- **版本约束尽量收窄**,降低多技能共享 venv 时的冲突风险。推荐范围写法: - **版本约束尽量收窄**,降低多技能共享 venv 时的冲突风险。推荐范围写法:
@@ -305,7 +312,7 @@ git remote -v
复制后优先改下面这些地方: 复制后优先改下面这些地方:
1. `SKILL.md` 1. `SKILL.md`
2. 根目录 `README.md`(用户市场说明) 2. 根目录市场四 Tab`README.md` / `TUTORIAL.md` / `DEMO.md` / `CHANGELOG.md`
3. `scripts/util/constants.py` 3. `scripts/util/constants.py`
4. `references/` 与 `development/` 下的文案 4. `references/` 与 `development/` 下的文案
5. `scripts/service/` 下的业务占位实现(优先改 `task_service.py` 5. `scripts/service/` 下的业务占位实现(优先改 `task_service.py`
@@ -339,7 +346,7 @@ git remote -v
如需浏览器自动化,不要在模板里保留空的 `platform_playwright.py`;请按业务新建 `xxx_playwright.py`(命名自定),并在 `task_service.py` 中按需引用。 如需浏览器自动化,不要在模板里保留空的 `platform_playwright.py`;请按业务新建 `xxx_playwright.py`(命名自定),并在 `task_service.py` 中按需引用。
## 6. `SKILL.md` 与根 `README.md` 应该怎么写 ## 6. `SKILL.md` 与市场四 Tab 材料应该怎么写
### `SKILL.md`LLM / 平台入口) ### `SKILL.md`LLM / 平台入口)
@@ -351,19 +358,26 @@ git remote -v
- 何时触发本技能、CLI 入口摘要、运行契约要点 - 何时触发本技能、CLI 入口摘要、运行契约要点
- 指向 `references/`Agent 调用)与 `development/`(开发规范)的分工说明 - 指向 `references/`Agent 调用)与 `development/`(开发规范)的分工说明
不要在 `SKILL.md` 里写大量用户市场文案或实现细节。 不要在 `SKILL.md` 里写大量用户市场文案或实现细节**不要**把演示视频 URL 写进 `SKILL.md`(放 `DEMO.md` frontmatter
### 根 `README.md`(用户市场说明 ### 市场四 Tab根目录面向普通用户
根 `README.md` 是技能市场详情页主来源(`metadata.readme_md`),面向普通用户。 发布 CI 会把下列文件同步到技能市场详情 Tabs有文件才更新对应字段
应包含 YAML frontmatter 的 `description`(市场列表简介),正文用用户能理解的语言说明: | 文件 | 市场 Tab | 同步字段 |
|------|----------|----------|
| `README.md` | 说明 | `readme_md`frontmatter `description` 作列表简介) |
| `TUTORIAL.md` | 教程 | `tutorial_md` |
| `DEMO.md` | 演示 | `demo_md` + frontmatter `demo_video_url` |
| `CHANGELOG.md` | 更新日志 | 匹配当前 tag 版本的 `##` 小节 → `changelog` |
- 能做什么、适合什么场景、使用前准备什么 **`README.md`**:能力与场景说明。含 frontmatter `description`;写能做什么、场景、准备、如何告诉 Agent、结果、注意事项、FAQ。不要写开发教程、目录规范、release、requirements。
- 如何自然语言告诉 Agent
- 执行结果、注意事项、常见问题
不要在根 `README.md` 里写开发教程、目录规范、release、requirements 等技术细节 **`TUTORIAL.md`**:第一次怎么用完的逐步操作。写「开始前 → 步骤 → 卡住怎么办」;不要写 CLI / 目录 / 开发规范
**`DEMO.md`**演示视频与补充说明。frontmatter 必须含 `demo_video_url`(无视频时用 `""`);正文可选。
**`CHANGELOG.md`**:每个正式版本一节(如 `## 1.0.46`)。打 tag 前为即将发布的版本新增小节;用户可读的变化,少写内部实现。
实现细节放在: 实现细节放在:
@@ -402,9 +416,12 @@ metadata:
当前规范 skill 的文档按读者拆分: 当前规范 skill 的文档按读者拆分:
**根 `README.md`** **根市场材料(四 Tab**
- 用户市场详情页说明(含 frontmatter `description` - `README.md` — 说明(含 frontmatter `description`
- `TUTORIAL.md` — 使用教程
- `DEMO.md` — 演示(`demo_video_url` + 正文)
- `CHANGELOG.md` — 按版本更新日志
**`SKILL.md`** **`SKILL.md`**
@@ -442,7 +459,7 @@ metadata:
比如 `skill-actions.schema.json`、日志记录、机读 JSON 的 schema 比如 `skill-actions.schema.json`、日志记录、机读 JSON 的 schema
不要把正式研发文档放到 `assets/`。 不要把正式研发文档放到 `assets/`。
用户说明进根 `README.md`Agent 编排资料进 `references/`;开发规范进 `development/`。 用户市场四 Tab 进根 `README.md` / `TUTORIAL.md` / `DEMO.md` / `CHANGELOG.md`Agent 编排资料进 `references/`;开发规范进 `development/`。
## 9. `cli` 层怎么写 ## 9. `cli` 层怎么写
@@ -454,40 +471,48 @@ metadata:
也就是说,`cli/app.py` 的职责是: 也就是说,`cli/app.py` 的职责是:
1. 打印帮助 1. 打印帮助
2. 定义 `run / logs / log-get / health / version` 2. 定义 `run / logs / log-get / health / version / init-db`(及业务子命令)
3. 把参数转交给 `service.task_service` 3. 把参数转交给 `service.task_service`(或薄适配后再进 domain service
不要在 `cli/app.py` 里直接写: 不要在 `cli/app.py` 里直接写:
- 浏览器自动化 - 浏览器自动化
- 子进程调用兄弟技能 - 子进程调用兄弟技能
- SQLite 逻辑 - SQLite 逻辑
- 与 toolbar / cron / agent 来源相关的业务分叉
## 10. `service` 层怎么写 ## 10. `service` 层怎么写
`service` 是核心层。 `service` 是核心层。推荐拆分(**单业务内核、多入口**
通常可以这样拆: ```text
cli/app.py → 只解析参数
service/task_service.py → job_context / emit / checkpoint / finish / 错误转换
service/<domain>_service.py → 唯一业务内核(同步、处理、统计等)
db/*_repository.py → 事务与读写
assets/actions.json → placements / bind / executionProfile / entrypoint
```
- `task_service.py` 通常还可以有:
放命令编排、参数兜底、结果分流(例如 `cmd_run`
- `sibling_bridge.py` - `sibling_bridge.py`
放通用兄弟技能子进程工具(`call_sibling_json`**具体调用哪个 slug 由业务在 `task_service.py` 决定**,不要在本文件硬编码发布类专用 helper 放通用兄弟技能子进程工具(`call_sibling_json`**具体调用哪个 slug 由业务在 `task_service.py` 或 domain service 决定**,不要在本文件硬编码发布类专用 helper
- `xxx_playwright.py`(按需新建) - `xxx_playwright.py`(按需新建)
浏览器后台自动化 **不在模板默认结构中**;若确有需要,按命名约定自建模块并在 `task_service.py` 引用 浏览器后台自动化 **不在模板默认结构中**;若确有需要,按命名约定自建模块并由 domain / task_service 引用
- `entitlement_service.py` - `entitlement_service.py`
放鉴权逻辑 放鉴权逻辑
禁止toolbar / cron / Agent / CLI 各自复制一套采集或同步实现;为兼容旧命令再写第二套内核。
### 日志要求(`cmd_run` / 核心业务) ### 日志要求(`cmd_run` / 核心业务)
`service` 层是**关键业务日志**的落点,须遵循 [`LOGGING.md`](LOGGING.md) `service` 层是**关键业务日志**的落点,须遵循 [`LOGGING.md`](LOGGING.md)
- `cmd_run` 及主任务入口必须:`log.info("task_start ...")`、`log.info("task_log_saved ...")`;失败路径必须 `log.exception("task_failed ...")`。 - `cmd_run` 及主任务入口必须:`log.info("task_start ...")`、`log.info("task_log_saved ...")`;失败路径必须 `log.exception("task_failed ...")`。
- 外部 API、兄弟技能、RPA 操作须记录**开始 / 结束 / 耗时 / 状态**`external_call_start` / `external_call_done elapsed_ms=...`)。 - 外部 API、兄弟技能、RPA 操作须记录**开始 / 结束 / 耗时 / 状态**`external_call_start` / `external_call_done elapsed_ms=...`)。
- 长任务 / RPA 须配合 `activity.emit` 或 `RpaVideoSession.add_step` 输出用户可见进度。 - 长任务 / RPA 须配合 `activity.emit` 或 `RpaVideoSession.add_step` 输出用户可见进度`cmd_run` 须 `job_context` + 各出口 `finish`(见 [`LOGGING.md`](LOGGING.md) §2.5
- 使用 `from util.logging_config import get_skill_logger`**不要**用 `print` 替代 logger 做排障日志。 - 使用 `from util.logging_config import get_skill_logger`**不要**用 `print` 替代 logger 做排障日志。
- **禁止**在日志中写入 password、token、cookie 等敏感明文(见 `LOGGING.md` §敏感信息红线)。 - **禁止**在日志中写入 password、token、cookie 等敏感明文(见 `LOGGING.md` §敏感信息红线)。
@@ -497,7 +522,9 @@ metadata:
推荐流向是: 推荐流向是:
`cli.app` -> `service.task_service` -> `service.sibling_bridge` / (可选)`service.xxx_playwright` -> `db` `cli.app` -> `service.task_service` -> `service.<domain>_service` -> `db`
(旁路:`sibling_bridge` / 可选 `xxx_playwright` 仅由 service 调用)
## 11. `db` 层怎么写 ## 11. `db` 层怎么写
@@ -525,11 +552,14 @@ metadata:
若技能需要出现在宿主**数据管理按钮**、**技能详情**、**定时任务**或 **Agent 直接调用**中,提供 `assets/actions.json`。 若技能需要出现在宿主**数据管理按钮**、**技能详情**、**定时任务**或 **Agent 直接调用**中,提供 `assets/actions.json`。
- 契约说明见 [`references/ACTIONS.md`](../references/ACTIONS.md) - **运行时金标准**见 [`SKILL_ACTION_RUNTIME.md`](SKILL_ACTION_RUNTIME.md)
- 字段契约见 [`references/ACTIONS.md`](../references/ACTIONS.md)`placements` / `bind.tables` / `executionProfile` 正交)
- JSON Schema 见 [`assets/schemas/skill-actions.schema.json`](../assets/schemas/skill-actions.schema.json) - JSON Schema 见 [`assets/schemas/skill-actions.schema.json`](../assets/schemas/skill-actions.schema.json)
- 模板最小示例仅暴露 `health` / `version` / `config-path` 三个 CLI 子命令 - 模板最小示例仅暴露 `health` / `version` / `config-path`(均显式 `executionProfile: "sync"`**不**自动加 toolbarCLI 另含 `init-db` 供宿主静默建库(不必做成 Action
- 含 `toolbar` 的 Action**必须**声明合法 `bind.tables``POLICY-SKILL-ACTION-003`
- 含浏览器 RPA / 长耗时的业务技能:**必须**增加至少一条 `"executionProfile": "async"` 且 `placements` 含 `agent` 的 action`POLICY-SKILL-ACTION-001`
- 没有宿主直接操作需求时,**可以删除** `actions.json`;删除后勿保留失效引用 - 没有宿主直接操作需求时,**可以删除** `actions.json`;删除后勿保留失效引用
- 复制为新技能后,scaffold 会自动将 `your-skill-slug` 与 `your_skill_slug` 替换为新 slug后者用于 `LOG_LOGGER_NAME` 等下划线形式action 业务命令由技能作者自行调整 - scaffold **不会**移除 Schema 中的 `bind` 支持,**不会**生成平台业务 Action 业务表名;仅替换占位 slug
宿主执行方式: 宿主执行方式:
@@ -539,6 +569,34 @@ python {skillRoot}/scripts/main.py <command> <args...>
CLI 必须提供稳定退出码、结构化成功输出,以及 `ERROR:<CODE>:` / `HINT:` 错误契约(详见 `references/ACTIONS.md`)。 CLI 必须提供稳定退出码、结构化成功输出,以及 `ERROR:<CODE>:` / `HINT:` 错误契约(详见 `references/ACTIONS.md`)。
### 编排范式:单内核 + 多入口
长任务 / RPA / 数据同步技能推荐拆分(勿把 `job_context` 塞进纯业务内核):
```text
<domain>_service.sync_*(...) # 唯一业务内核:读外源 → 写本地库(或核心处理)
cmd_sync_* (...) # 编排job_context + 调用内核 + emit/finishasync 时)
CLI / Action / cron / Agent # 全部进入同一 cmd_* → 同一内核
```
RPA 批量亦可:
```text
execute_single_<biz>(...) # 鉴权 + 业务 + task_log无 job_context
cmd_run(...) # 单条job_context + execute_single + finish
cmd_run_pick(N, ...) # 批量顺序job_context + for-loop + emit(progress) + finish
cmd_stats() # 只读 syncJSON无 job_context
```
- 批量数量用 **`pickCount` / `--pick N` 参数**(任意正整数),不写死条数。
- **顺序执行、不并发**同一浏览器 Profile / account lease。
- **同步数据**与**宿主表导出**职责分离:同步不写 CSV/Excel表导出交给数据管理。
- 详情见 [`SKILL_ACTION_RUNTIME.md`](SKILL_ACTION_RUNTIME.md);契约样例见 `tests/samples/test_sync_contract.py.sample`、`tests/samples/test_action_core_contract.py.sample`。
### 队列 + pick可选
有「待处理列表」时:队列表 `pending → processing → success/failed`;数据管理录入或 `import-*` 入库;`run --pick N` 消费;失败用 `reset` 回 `pending`不自动重试。Manifest 上配置 `*-run-pick`(常见为 async + toolbar/cron/agent有 toolbar 则须 `bind.tables`)。
## 12. 如何接兄弟技能 ## 12. 如何接兄弟技能
如果 skill 要依赖兄弟 skill不要在业务代码里写死绝对路径。 如果 skill 要依赖兄弟 skill不要在业务代码里写死绝对路径。
@@ -587,11 +645,20 @@ CLI 必须提供稳定退出码、结构化成功输出,以及 `ERROR:<CODE>:`
### 1. 验证入口 ### 1. 验证入口
本地验证请优先使用宿主共享 Python与 Agent CLI 相同契约),例如:
```bash ```bash
python scripts/main.py health python scripts/main.py health
python scripts/main.py version python scripts/main.py version
``` ```
**禁止**对技能脚本使用 `uv run python`。
```bash
python scripts/main.py -h
python scripts/main.py <your-command> -h
```
### 2. 验证 CLI 路由 ### 2. 验证 CLI 路由
```bash ```bash
@@ -661,6 +728,8 @@ uses: client-jiangchang/jiangchang-platform-kit/.github/workflows/reusable-relea
在执行 `release.ps1` 之前,必须先在本地确认 `python tests/run_tests.py -v` 通过。测试不通过不得发起正式发布。 在执行 `release.ps1` 之前,必须先在本地确认 `python tests/run_tests.py -v` 通过。测试不通过不得发起正式发布。
**发布前必须**将 `SKILL.md` 的 `version:` 与 `scripts/util/constants.py` 的 `SKILL_VERSION` 调整为将打出的版本(例如下一 patch再执行 `release.ps1`。`release.ps1` **不会**自动改这两个字段;漏改会造成 git tag 与技能版本号不一致。
`release.ps1` 会在 **auto commit 之前**、推送 tag 之前,对**当前工作区**自动执行默认测试(`python tests/run_tests.py -v`);失败则中止 release不会留下失败状态的自动提交。仅紧急排障可使用 `-SkipTests` 跳过(会打印黄色警告)。`-DryRun` 预览发布时**仍会实际运行**默认测试,便于在不打 tag 的情况下验证门禁。 `release.ps1` 会在 **auto commit 之前**、推送 tag 之前,对**当前工作区**自动执行默认测试(`python tests/run_tests.py -v`);失败则中止 release不会留下失败状态的自动提交。仅紧急排障可使用 `-SkipTests` 跳过(会打印黄色警告)。`-DryRun` 预览发布时**仍会实际运行**默认测试,便于在不打 tag 的情况下验证门禁。
新增或调整开发规范时,须同步 [`development/POLICY_MATRIX.md`](POLICY_MATRIX.md) 与 [`tests/test_development_policy_guard.py`](../tests/test_development_policy_guard.py)(或注明由既有测试覆盖)。 新增或调整开发规范时,须同步 [`development/POLICY_MATRIX.md`](POLICY_MATRIX.md) 与 [`tests/test_development_policy_guard.py`](../tests/test_development_policy_guard.py)(或注明由既有测试覆盖)。
@@ -716,7 +785,7 @@ uses: client-jiangchang/jiangchang-platform-kit/.github/workflows/reusable-relea
如果工作流失败,不要继续做平台验证,而应该先回到代码仓库排查,例如: 如果工作流失败,不要继续做平台验证,而应该先回到代码仓库排查,例如:
- 发布脚本是否正常推送 - 发布脚本是否正常推送
- `SKILL.md`、根 `README.md`、`scripts/`、`references/`、`development/` 是否齐全 - `SKILL.md`、根市场四 Tab`README.md` / `TUTORIAL.md` / `DEMO.md` / `CHANGELOG.md`、`scripts/`、`references/`、`development/` 是否齐全
- 工作流文件是否存在 - 工作流文件是否存在
- 发布包结构是否符合模板规范 - 发布包结构是否符合模板规范
@@ -785,6 +854,7 @@ uses: client-jiangchang/jiangchang-platform-kit/.github/workflows/reusable-relea
- [ ] `service` 下的核心业务文件(如 `task_service.py`)已按领域改名并实现 - [ ] `service` 下的核心业务文件(如 `task_service.py`)已按领域改名并实现
- [ ] 没有残留旧平台名 - [ ] 没有残留旧平台名
- [ ] `health` / `version` 可运行 - [ ] `health` / `version` 可运行
- [ ] `.env.example` 注释已按 [`CONFIG.md`](CONFIG.md)「行头 = 是什么、行尾 = 怎么填」写全(面向配置管理用户;无 `见 development/...` 等开发文档指向)
- [ ] `.gitignore` 生效,没有把 `__pycache__` 提交进去 - [ ] `.gitignore` 生效,没有把 `__pycache__` 提交进去
- [ ] `release.ps1` 存在(发布前会自动跑 `python tests/run_tests.py -v`;失败不得打 tag - [ ] `release.ps1` 存在(发布前会自动跑 `python tests/run_tests.py -v`;失败不得打 tag
- [ ] `.github/workflows/release_skill.yaml` 存在 - [ ] `.github/workflows/release_skill.yaml` 存在
@@ -799,6 +869,7 @@ uses: client-jiangchang/jiangchang-platform-kit/.github/workflows/reusable-relea
- [ ] 本仓库**不是** skill-template 的误复制(根目录**无** `.openclaw-skill-template` - [ ] 本仓库**不是** skill-template 的误复制(根目录**无** `.openclaw-skill-template`
- [ ] `git remote -v` 指向**本技能**远端URL 不含 skill-template 仓库名 - [ ] `git remote -v` 指向**本技能**远端URL 不含 skill-template 仓库名
- [ ] `git log` 首条提交属于本技能(非模板历史) - [ ] `git log` 首条提交属于本技能(非模板历史)
- [ ] 网页 RPA`ensure-web` 取得 `profile_dir` 再开浏览器;`.env` 默认有头REQUIREMENTS 写明登录策略required/optional/not_needed会话依赖型勿抄 optional用户 README/TUTORIAL 区分「登记账号」与「站点登录」(`RPA.md` §0.2 / `POLICY-RPA-004`);依赖 kit 空值解析等修复时上调 `platform_kit_min_version`
## 17. 常见错误 ## 17. 常见错误
@@ -851,7 +922,7 @@ uses: client-jiangchang/jiangchang-platform-kit/.github/workflows/reusable-relea
现在的新模板原则是: 现在的新模板原则是:
- 不做旧结构兼容 - 不做旧结构兼容
- 用户说明在根 `README.md`Agent 资料在 `references/`,开发规范在 `development/` - 用户市场四 Tab 在根 `README.md` / `TUTORIAL.md` / `DEMO.md` / `CHANGELOG.md`Agent 资料在 `references/`,开发规范在 `development/`
- 统一走 `scripts/main.py` 作为 CLI 入口 - 统一走 `scripts/main.py` 作为 CLI 入口
### 错误 5平台放 slug 最前 ### 错误 5平台放 slug 最前
@@ -913,7 +984,7 @@ git remote add origin <新技能仓库 URL>
如果让一个新人照着做,我建议他按这个顺序: 如果让一个新人照着做,我建议他按这个顺序:
1. 按 [`NAMING.md`](NAMING.md) 确定 slug复制模板并改目录名 1. 按 [`NAMING.md`](NAMING.md) 确定 slug复制模板并改目录名
2. 改 `SKILL.md` 与根 `README.md` 2. 改 `SKILL.md` 与根市场四 Tab`README.md` / `TUTORIAL.md` / `DEMO.md` / `CHANGELOG.md`
3. 改 `scripts/util/constants.py` 3. 改 `scripts/util/constants.py`
4. 改 `references/` 与 `development/` 4. 改 `references/` 与 `development/`
5. 改 `scripts/cli/app.py` 5. 改 `scripts/cli/app.py`
@@ -929,7 +1000,7 @@ git remote add origin <新技能仓库 URL>
- 目录结构统一 - 目录结构统一
- 入口统一为 `scripts/main.py` - 入口统一为 `scripts/main.py`
- 用户说明在根 `README.md`Agent 资料在 `references/`,开发规范在 `development/` - 用户市场四 Tab 在根 `README.md` / `TUTORIAL.md` / `DEMO.md` / `CHANGELOG.md`Agent 资料在 `references/`,开发规范在 `development/`
- 业务核心逻辑统一放 `scripts/service/` - 业务核心逻辑统一放 `scripts/service/`
- 不再使用旧模板历史结构 - 不再使用旧模板历史结构

View File

@@ -56,10 +56,13 @@ OpenClaw 技能常在客户电脑上异步执行,且大量依赖 RPA、浏览
| API | 用途 | | API | 用途 |
|-----|------| |-----|------|
| `emit` | 推送用户可读进度(不写 stdout | | `emit` | 推送用户可读进度(不写 stdout进入步骤前自动步骤闸门SRCP |
| `step` | 结构化步骤 | | `step` | 结构化步骤 |
| `finish` | 任务结束;**唯一**写单行 result JSON 到 stdout 的场景 | | `finish` | 任务结束;**唯一**写单行 result JSON 到 stdout 的场景 |
| `rpa_step` | RPA 专用步骤文案 | | `job_context` | 包裹 `cmd_run`;未捕获异常 / `JobStopped` 时自动 `finish` |
| `rpa_step` | RPA 专用步骤:闸门 + ▶/✓ emit |
| `interruptible_sleep` | RPA 等待(替代裸 `asyncio.sleep`),可暂停/停止 |
| `checkpoint` | 长循环内 consult control一般由 kit 自动调用) |
**路径** **路径**
@@ -72,6 +75,35 @@ OpenClaw 技能常在客户电脑上异步执行,且大量依赖 RPA、浏览
- `emit` **不写 stdout**;长任务应持续 emit避免用户以为卡死。 - `emit` **不写 stdout**;长任务应持续 emit避免用户以为卡死。
- `finish` 才输出单行 result JSON 供宿主解析。 - `finish` 才输出单行 result JSON 供宿主解析。
- RPA 类技能:`RpaVideoSession.add_step` 会自动同步 activity无需重复手写每步 emit - RPA 类技能:`RpaVideoSession.add_step` 会自动同步 activity无需重复手写每步 emit
- **禁止**自建 `scripts/util/progress.py` 或向 stdout 打印 `type:progress` JSON进度只走 Run Journal。
- 宿主通过 `{job_id}.control.json` 下发暂停/继续/停止;技能侧由 platform-kit 在步骤闸门自动处理(见 §2.5)。
### 2.5 步骤控制SRCP v1platform-kit >= 1.2.0
**权威行为定义在本文**platform-kit README 为实现细节参考。
| 通道 | 方向 | 载体 |
|------|------|------|
| 进度 | 技能 → 宿主 | Run Journal`emit` / `rpa_step` / `add_step` |
| 结果 | 技能 → 宿主 | `finish()` → Journal 终态 + stdout 一行 result |
| 控制 | 宿主 → 技能 | `{JIANGCHANG_DATA_ROOT}/.jiangchang/runs/{job_id}.control.json` |
`control.json``command` 只认:`none` | `pause` | `resume` | `stop`
技能作者三件事:
1. `cmd_run` 外包 `with job_context(skill=SKILL_SLUG):`
2. 关键步骤 `emit(...)``@rpa_step` / `video.add_step`
3. 每个出口 `finish(status=..., message=..., skill=SKILL_SLUG, **fields)` — **不要**手写多行 JSON 结果
**单内核多入口**`execute_single_*` 不含 `job_context`;仅 `cmd_run` / `cmd_run_pick` 包裹。批量 pick 循环内 `checkpoint()` + `emit(..., progress=...)`;部分失败用 `finish(status="partial")`。完整范式见 [`SKILL_ACTION_RUNTIME.md`](SKILL_ACTION_RUNTIME.md)。
RPA 等待用 `interruptible_sleep`**不要**裸 `asyncio.sleep`(否则暂停响应滞后)。
暂停在**步骤边界**生效(当前 `@rpa_step` / `emit` 执行完后、下一步开始前),与影刀「当前指令完成后暂停」一致。
Journal 会写入 `type: lifecycle` 事件(`paused` / `resumed` / `stopping`),供宿主任务中心显示状态。
### 2.3 `task_logs`(任务结果审计) ### 2.3 `task_logs`(任务结果审计)
@@ -88,11 +120,13 @@ OpenClaw 技能常在客户电脑上异步执行,且大量依赖 RPA、浏览
**来源**`RpaVideoSession``rpa-artifacts/` 目录 **来源**`RpaVideoSession``rpa-artifacts/` 目录
- video artifact 是**标准可启用能力****不保证默认每次生成 MP4**(模板默认 `OPENCLAW_RECORD_VIDEO=0`)。
- **`OPENCLAW_RECORD_VIDEO=0`**:不生成最终录屏,但 RPA / 长任务仍须保留 `RpaVideoSession``video.add_step` 与 Activity 进度同步。
- **`OPENCLAW_RECORD_VIDEO=1`**`result_summary` 应包含 `video_path``raw_video``video_log``video_warnings` 等字段CLI 可打印录屏路径与诊断。
- 用户可见的中文步骤(「打开登录页」「点击提交」)。 - 用户可见的中文步骤(「打开登录页」「点击提交」)。
- 录屏 MP4、`video_log`ffmpeg 诊断)。 - 失败截图:`{数据目录}/rpa-artifacts/{batch_id}/...`(受 `OPENCLAW_ARTIFACTS_ON_FAILURE` 控制,默认开)
- 失败截图:`{数据目录}/rpa-artifacts/{batch_id}/...`
详见 [`RPA.md`](RPA.md) §失败存证与录屏标准 详见 [`RPA.md`](RPA.md) §5 存证与录屏规范
--- ---
@@ -200,7 +234,7 @@ batch_progress current=7 total=20 target_id=store-001
```python ```python
from util.logging_config import get_skill_logger from util.logging_config import get_skill_logger
from jiangchang_skill_core.activity import emit from jiangchang_skill_core.activity import emit, finish, job_context, rpa_step, interruptible_sleep
from util.constants import SKILL_SLUG from util.constants import SKILL_SLUG
@@ -208,37 +242,40 @@ log = get_skill_logger()
def cmd_run(target=None, input_id=None): def cmd_run(target=None, input_id=None):
task_type = "your_task" task_type = "your_task"
log.info( with job_context(skill=SKILL_SLUG):
"task_start task_type=%s target_id=%s input_id=%s",
task_type, target, input_id,
)
emit("开始处理任务", skill=SKILL_SLUG, stage="run")
try:
ok, reason = check_entitlement(SKILL_SLUG)
if not ok:
log.warning("entitlement_failed task_type=%s reason=%s", task_type, reason)
return 1
t0 = time.monotonic()
# ... 外部调用 ...
elapsed_ms = int((time.monotonic() - t0) * 1000)
log.info( log.info(
"external_call_done system=%s operation=%s elapsed_ms=%d status=%s", "task_start task_type=%s target_id=%s input_id=%s",
"erp", "submit", elapsed_ms, "ok",
)
tlr.save_task_log(..., status="success", ...)
log.info("task_log_saved task_type=%s status=success", task_type)
emit("任务完成", skill=SKILL_SLUG, stage="run")
return 0
except Exception:
log.exception(
"task_failed task_type=%s target_id=%s input_id=%s",
task_type, target, input_id, task_type, target, input_id,
) )
emit("任务失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="run") emit("开始处理任务", skill=SKILL_SLUG, stage="run")
tlr.save_task_log(..., status="failed", error_msg="...", ...) try:
return 1 ok, reason = check_entitlement(SKILL_SLUG)
if not ok:
log.warning("entitlement_failed task_type=%s reason=%s", task_type, reason)
finish(status="failed", message=reason, skill=SKILL_SLUG, error_code="ENTITLEMENT_DENIED")
return 1
t0 = time.monotonic()
# ... 外部调用 / RPA@rpa_step 或 video.add_step等待用 interruptible_sleep ...
elapsed_ms = int((time.monotonic() - t0) * 1000)
log.info(
"external_call_done system=%s operation=%s elapsed_ms=%d status=%s",
"erp", "submit", elapsed_ms, "ok",
)
tlr.save_task_log(..., status="success", ...)
log.info("task_log_saved task_type=%s status=success", task_type)
finish(status="success", message="任务完成", skill=SKILL_SLUG)
return 0
except Exception:
log.exception(
"task_failed task_type=%s target_id=%s input_id=%s",
task_type, target, input_id,
)
emit("任务失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="run")
tlr.save_task_log(..., status="failed", error_msg="...", ...)
finish(status="failed", message="任务执行异常", skill=SKILL_SLUG)
return 1
``` ```
模板示范见 [`scripts/service/task_service.py`](../scripts/service/task_service.py) 的 `cmd_run` 模板示范见 [`scripts/service/task_service.py`](../scripts/service/task_service.py) 的 `cmd_run`
@@ -254,7 +291,7 @@ def cmd_run(target=None, input_id=None):
3. **`python scripts/main.py log-get <id>`** — 单条 JSON`result_summary`video 路径等)。 3. **`python scripts/main.py log-get <id>`** — 单条 JSON`result_summary`video 路径等)。
4. **统一日志文件**`{JIANGCHANG_DATA_ROOT}/{JIANGCHANG_USER_ID}/logs/jiangchang.log`grep `trace_id``task_failed`)。 4. **统一日志文件**`{JIANGCHANG_DATA_ROOT}/{JIANGCHANG_USER_ID}/logs/jiangchang.log`grep `trace_id``task_failed`)。
5. **Run Journal**`{JIANGCHANG_DATA_ROOT}/.jiangchang/runs/{job_id}.jsonl`(宿主 UI 进度来源)。 5. **Run Journal**`{JIANGCHANG_DATA_ROOT}/.jiangchang/runs/{job_id}.jsonl`(宿主 UI 进度来源)。
6. **RPA artifacts**`rpa-artifacts/` 截图、录屏 MP4、`video_log` 6. **RPA artifacts**`rpa-artifacts/` 失败截图;若 `OPENCLAW_RECORD_VIDEO=1` 还有录屏 MP4、`video_log`。未开启录屏时可能只有截图或日志,需要完整录屏请在用户 `.env` 中设置 `OPENCLAW_RECORD_VIDEO=1`
长时间无 stdout **不代表卡死**;先看 Run Journal / Activity再看统一日志。 长时间无 stdout **不代表卡死**;先看 Run Journal / Activity再看统一日志。
@@ -271,4 +308,5 @@ def cmd_run(target=None, input_id=None):
| [`CLI.md`](../references/CLI.md) | `logs` / `log-get` 命令与手工排查入口 | | [`CLI.md`](../references/CLI.md) | `logs` / `log-get` 命令与手工排查入口 |
| [`CONFIG.md`](CONFIG.md) | 敏感配置不进日志;`.env` 边界 | | [`CONFIG.md`](CONFIG.md) | 敏感配置不进日志;`.env` 边界 |
| [`DEVELOPMENT.md`](DEVELOPMENT.md) | `service/` 层日志职责与发布前检查清单 | | [`DEVELOPMENT.md`](DEVELOPMENT.md) | `service/` 层日志职责与发布前检查清单 |
| [`SKILL_ACTION_RUNTIME.md`](SKILL_ACTION_RUNTIME.md) | 任务中心 / async Job 与 `job_context` 边界 |
| [`POLICY_MATRIX.md`](POLICY_MATRIX.md) | 可自动检测的 logging hard policy 索引 | | [`POLICY_MATRIX.md`](POLICY_MATRIX.md) | 可自动检测的 logging hard policy 索引 |

View File

@@ -7,14 +7,19 @@
| POLICY-STRUCTURE-001 | 标准 `scripts/` 分层:`main.py``cli/``service/``db/``util/` 必须存在 | development/DEVELOPMENT.md §2 新 skill 的标准目录结构development/RUNTIME.md §目录结构 | hard | 目录存在性检查 | `tests/test_development_policy_guard.py::TestPolicyStructure001` | | POLICY-STRUCTURE-001 | 标准 `scripts/` 分层:`main.py``cli/``service/``db/``util/` 必须存在 | development/DEVELOPMENT.md §2 新 skill 的标准目录结构development/RUNTIME.md §目录结构 | hard | 目录存在性检查 | `tests/test_development_policy_guard.py::TestPolicyStructure001` |
| POLICY-RUNTIME-001 | 不得 vendored `scripts/jiangchang_skill_core/` | development/RUNTIME.md §共享 Python Runtime、§明确禁止 | hard | 目录不存在检查 | `tests/test_development_policy_guard.py::TestPolicyRuntime001`(另见 `tests/test_platform_import.py` | | POLICY-RUNTIME-001 | 不得 vendored `scripts/jiangchang_skill_core/` | development/RUNTIME.md §共享 Python Runtime、§明确禁止 | hard | 目录不存在检查 | `tests/test_development_policy_guard.py::TestPolicyRuntime001`(另见 `tests/test_platform_import.py` |
| POLICY-RUNTIME-002 | `requirements.txt` 非注释依赖行不得声明 `jiangchang-platform-kit` / `playwright` | development/RUNTIME.md §共享 Python Runtimedevelopment/DEVELOPMENT.md §3.1 requirements.txt 依赖规范 | hard | 解析依赖行 | `tests/test_development_policy_guard.py::TestPolicyRuntime002`(另见 `tests/test_platform_import.py` | | POLICY-RUNTIME-002 | `requirements.txt` 非注释依赖行不得声明 `jiangchang-platform-kit` / `playwright` | development/RUNTIME.md §共享 Python Runtimedevelopment/DEVELOPMENT.md §3.1 requirements.txt 依赖规范 | hard | 解析依赖行 | `tests/test_development_policy_guard.py::TestPolicyRuntime002`(另见 `tests/test_platform_import.py` |
| POLICY-RUNTIME-003 | Agent/CLI 文档须要求共享 Pythonpython-runtime / PATH 上的 `python` + `{baseDir}`);须明确**禁止**对技能脚本使用 `uv run python` | development/RUNTIME.mdreferences/CLI.mdSKILL.md | hard | 文档标记扫描 | `tests/test_docs_standards.py::test_cli_md_requires_shared_python_not_uv_run``tests/test_docs_standards.py::test_skill_md_requires_shared_python_not_uv_run` |
| POLICY-AGENT-001 | `SKILL.md` 须含「用户意图路由表」结构;`CLI.md` 须含短 CLI 白名单 / Action 强制黑名单表;用法回答须禁止无故粘贴 CLI、禁止为答用法列目录挖 references | SKILL.mdreferences/CLI.md | hard | 文档标记扫描 | `tests/test_docs_standards.py::test_skill_md_has_intent_routing_table``tests/test_docs_standards.py::test_cli_md_has_agent_routing_tables``tests/test_docs_standards.py::test_skill_md_how_to_forbids_cli_paste` |
| POLICY-INSTALL-001 | 交付执行文件不得含 `pip install` / `python -m pip install` / `uv pip install` / `playwright install` | development/RUNTIME.md §共享 Python Runtimedevelopment/RPA.md §1.4 Playwright 与安装边界development/DEVELOPMENT.md §3.1 | hard | 扫描 `scripts/**/*.py``*.ps1``*.sh``requirements.txt``.github/workflows/*`(不扫 `development/*.md` | `tests/test_development_policy_guard.py::TestPolicyInstall001` | | POLICY-INSTALL-001 | 交付执行文件不得含 `pip install` / `python -m pip install` / `uv pip install` / `playwright install` | development/RUNTIME.md §共享 Python Runtimedevelopment/RPA.md §1.4 Playwright 与安装边界development/DEVELOPMENT.md §3.1 | hard | 扫描 `scripts/**/*.py``*.ps1``*.sh``requirements.txt``.github/workflows/*`(不扫 `development/*.md` | `tests/test_development_policy_guard.py::TestPolicyInstall001` |
| POLICY-CONFIG-001 | 仓库根目录必须存在 `.env.example` | development/CONFIG.md §核心原则、§标准配置项 | hard | 文件存在性 | `tests/test_development_policy_guard.py::TestPolicyConfig001` | | POLICY-CONFIG-001 | 仓库根目录必须存在 `.env.example` | development/CONFIG.md §核心原则、§标准配置项 | hard | 文件存在性 | `tests/test_development_policy_guard.py::TestPolicyConfig001` |
| POLICY-CONFIG-002 | `.gitignore` 必须忽略 `.env``*.env.local` | development/CONFIG.md §红线:敏感信息不进 .env | hard | 解析 `.gitignore` 行 | `tests/test_development_policy_guard.py::TestPolicyConfig002` | | POLICY-CONFIG-002 | `.gitignore` 必须忽略 `.env``*.env.local` | development/CONFIG.md §红线:敏感信息不进 .env | hard | 解析 `.gitignore` 行 | `tests/test_development_policy_guard.py::TestPolicyConfig002` |
| POLICY-CONFIG-003 | 业务代码不得直接 `os.environ` / `os.getenv` / `os.putenv` / `environ.get`;须经 `jiangchang_skill_core.config.get*`(允许 `main.py`、测试、config_bootstrap/runtime 边界文件) | development/CONFIG.md §配置 bootstrapdevelopment/ADAPTER.md §档位 dispatch | hard | 扫描 `scripts/**/*.py` 并排除边界文件 | `tests/test_development_policy_guard.py::TestPolicyConfig003` | | POLICY-CONFIG-003 | 业务代码不得直接 `os.environ` / `os.getenv` / `os.putenv` / `environ.get`;须经 `jiangchang_skill_core.config.get*`(允许 `main.py`、测试、config_bootstrap/runtime 边界文件) | development/CONFIG.md §配置 bootstrapdevelopment/ADAPTER.md §档位 dispatch | hard | 扫描 `scripts/**/*.py` 并排除边界文件 | `tests/test_development_policy_guard.py::TestPolicyConfig003` |
| POLICY-CONFIG-004 | `.env.example` 每个活跃 `KEY=` 必须有中文**行头**(是什么)与中文**行尾**(怎么填);注释禁止 `development/``*.md` 文档指向、`account-manager``adapter 档位` 等开发黑话 | development/CONFIG.md §.env.example 注释 = 配置管理用户文案 | hard | 解析 `.env.example` 活跃行与注释 | `tests/test_development_policy_guard.py::TestPolicyConfig004` |
| POLICY-TESTING-001 | 默认根目录 `tests/test_*.py` 不得硬编码 `real_api` / `real_rpa` / `OPENCLAW_TEST_TARGET`(白名单仅 `test_adapter_profile_policy.py`,用于档位 helper 自测) | development/TESTING.md §默认必跑测试要做什么、§4 测试目标档位 | hard | 扫描 `tests/test_*.py` 非注释行;白名单外禁止上述文本 | `tests/test_development_policy_guard.py::TestPolicyTesting001` | | POLICY-TESTING-001 | 默认根目录 `tests/test_*.py` 不得硬编码 `real_api` / `real_rpa` / `OPENCLAW_TEST_TARGET`(白名单仅 `test_adapter_profile_policy.py`,用于档位 helper 自测) | development/TESTING.md §默认必跑测试要做什么、§4 测试目标档位 | hard | 扫描 `tests/test_*.py` 非注释行;白名单外禁止上述文本 | `tests/test_development_policy_guard.py::TestPolicyTesting001` |
| POLICY-TESTING-002 | `tests/integration/` 下 Python 测试文件若存在,默认应为 `.sample`,不得进入默认套件 | development/TESTING.md §7 真实联调测试的安全约束、§8 新 skill 的最小测试清单 | hard | 检查 `tests/integration/*.py``.sample` 后缀 | `tests/test_development_policy_guard.py::TestPolicyTesting002` | | POLICY-TESTING-002 | `tests/integration/` 下 Python 测试文件若存在,默认应为 `.sample`,不得进入默认套件 | development/TESTING.md §7 真实联调测试的安全约束、§8 新 skill 的最小测试清单 | hard | 检查 `tests/integration/*.py``.sample` 后缀 | `tests/test_development_policy_guard.py::TestPolicyTesting002` |
| POLICY-RPA-001 | 不得 import/use account-manager 内部 `rpa_helpers` / `inject_account_manager_scripts_path` / `get_account_credential` | development/ADAPTER.md §兄弟依赖development/RPA.md §1.7 | hard | 扫描 `scripts/**/*.py` 禁止模式 | `tests/test_development_policy_guard.py::TestPolicyRpa001`(另见 `tests/test_no_rpa_helpers_import.py` | | POLICY-RPA-001 | 不得 import/use account-manager 内部 `rpa_helpers` / `inject_account_manager_scripts_path` / `get_account_credential` | development/ADAPTER.md §兄弟依赖development/RPA.md §1.7 | hard | 扫描 `scripts/**/*.py` 禁止模式 | `tests/test_development_policy_guard.py::TestPolicyRpa001`(另见 `tests/test_no_rpa_helpers_import.py` |
| POLICY-RPA-002 | RPA 交付代码不得直接执行 ffmpeg 拼 MP4应使用 `RpaVideoSession`(允许 `ffmpeg_path` 等诊断字段) | development/RPA.md §5.3 录屏成片标准 | hard | 扫描 `scripts/**/*.py` 禁止 `subprocess` / `os.system` / `os.popen` 直接调用 ffmpeg`task_run_support.py` 保留豁免) | `tests/test_development_policy_guard.py::TestPolicyRpa002` | | POLICY-RPA-002 | RPA 交付代码不得直接执行 ffmpeg 拼 MP4应使用 `RpaVideoSession`(允许 `ffmpeg_path` 等诊断字段) | development/RPA.md §5.3 录屏成片标准 | hard | 扫描 `scripts/**/*.py` 禁止 `subprocess` / `os.system` / `os.popen` 直接调用 ffmpeg`task_run_support.py` 保留豁免) | `tests/test_development_policy_guard.py::TestPolicyRpa002` |
| POLICY-RPA-003 | 即使默认 `OPENCLAW_RECORD_VIDEO=0`RPA / 长任务模板也必须保留录屏能力:`RpaVideoSession``video.add_step`、video artifact merge 到 `result_summary` | development/RPA.md §5.3development/LOGGING.mddevelopment/CONFIG.md | hard | 扫描 `scripts/service/*.py`service 层整体须含上述接入) | `tests/test_development_policy_guard.py::TestPolicyRpa003` |
| POLICY-RPA-004 | 网页 RPA`.env.example` 若声明 `OPENCLAW_BROWSER_HEADLESS` 则默认必须为 `0``scripts/` 若使用 `launch_persistent_*` 则必须同时存在 `pick_web_account`(先 Profile 再开浏览器;实现上应走 ensure-web登录不全局强制但不得跳过 account-manager | development/RPA.md §0.2development/ADAPTER.md §兄弟依赖 | hard | 解析 `.env.example` + 扫描 `scripts/**/*.py` | `tests/test_development_policy_guard.py::TestPolicyRpa004` |
| POLICY-PACKAGING-001 | `scripts/**/*.py` 单文件 < 1000 行 | development/DEVELOPMENT.md §3.4 发布打包约束development/RUNTIME.md §发布打包约束 | hard | 行数统计 | **已有测试覆盖**`tests/test_release_packaging_constraints.py::test_scripts_py_files_under_pyarmor_line_limit` | | POLICY-PACKAGING-001 | `scripts/**/*.py` 单文件 < 1000 行 | development/DEVELOPMENT.md §3.4 发布打包约束development/RUNTIME.md §发布打包约束 | hard | 行数统计 | **已有测试覆盖**`tests/test_release_packaging_constraints.py::test_scripts_py_files_under_pyarmor_line_limit` |
| POLICY-PACKAGING-002 | 文本文件 UTF-8 without BOM`U+FEFF` | development/DEVELOPMENT.md §3.4development/RUNTIME.md §编码与输出 | hard | BOM / 解码检查 | **已有测试覆盖**`tests/test_release_packaging_constraints.py::test_text_files_are_utf8_without_bom` | | POLICY-PACKAGING-002 | 文本文件 UTF-8 without BOM`U+FEFF` | development/DEVELOPMENT.md §3.4development/RUNTIME.md §编码与输出 | hard | BOM / 解码检查 | **已有测试覆盖**`tests/test_release_packaging_constraints.py::test_text_files_are_utf8_without_bom` |
| POLICY-DOCS-001 | 本矩阵存在且包含上述全部 `policy_id` | 本次规范化约定 | hard | 解析 `development/POLICY_MATRIX.md` | `tests/test_development_policy_guard.py::TestPolicyDocs001` | | POLICY-DOCS-001 | 本矩阵存在且包含上述全部 `policy_id` | 本次规范化约定 | hard | 解析 `development/POLICY_MATRIX.md` | `tests/test_development_policy_guard.py::TestPolicyDocs001` |
@@ -23,17 +28,30 @@
| POLICY-LOGGING-003 | 主任务入口须含 `log.info`/`logger.info``log.exception`/`logger.exception`,并写入 `save_task_log` | development/LOGGING.md | hard | 扫描 `scripts/service/task_service.py` | `tests/test_development_policy_guard.py::TestPolicyLogging003` | | POLICY-LOGGING-003 | 主任务入口须含 `log.info`/`logger.info``log.exception`/`logger.exception`,并写入 `save_task_log` | development/LOGGING.md | hard | 扫描 `scripts/service/task_service.py` | `tests/test_development_policy_guard.py::TestPolicyLogging003` |
| POLICY-LOGGING-004 | 长任务 / RPA 模板须使用 Activity 或 RPA video step 输出进度 | development/LOGGING.mddevelopment/RPA.md | hard | 扫描 `scripts/service/task_service.py``emit(` / `activity.emit` / `video.add_step` | `tests/test_development_policy_guard.py::TestPolicyLogging004` | | POLICY-LOGGING-004 | 长任务 / RPA 模板须使用 Activity 或 RPA video step 输出进度 | development/LOGGING.mddevelopment/RPA.md | hard | 扫描 `scripts/service/task_service.py``emit(` / `activity.emit` / `video.add_step` | `tests/test_development_policy_guard.py::TestPolicyLogging004` |
| POLICY-LOGGING-005 | 交付代码不得在 logging 调用行以 `key=value` 形式记录明显敏感字段 | development/LOGGING.mddevelopment/CONFIG.md | hard | 扫描 `scripts/**/*.py` 的 logging 调用行(不含注释) | `tests/test_development_policy_guard.py::TestPolicyLogging005` | | POLICY-LOGGING-005 | 交付代码不得在 logging 调用行以 `key=value` 形式记录明显敏感字段 | development/LOGGING.mddevelopment/CONFIG.md | hard | 扫描 `scripts/**/*.py` 的 logging 调用行(不含注释) | `tests/test_development_policy_guard.py::TestPolicyLogging005` |
| POLICY-CONTROL-001 | 不得存在 `scripts/util/progress.py` 或自建 stdout 进度模块 | development/LOGGING.md §2.5development/RPA.md §0.1 | hard | 文件不存在检查 | `tests/test_development_policy_guard.py::TestPolicyControl001` |
| POLICY-CONTROL-002 | `task_service.py` 须使用 `job_context(``finish(` | development/LOGGING.md §2.5、§7 | hard | 扫描 `scripts/service/task_service.py` | `tests/test_development_policy_guard.py::TestPolicyControl002` |
| POLICY-CONTROL-003 | `scripts/service/*.py` 不得裸 `asyncio.sleep`RPA 等待须 `interruptible_sleep` | development/RPA.md §0.1 | hard | 扫描 service 层 Python | `tests/test_development_policy_guard.py::TestPolicyControl003` |
| POLICY-DATA-PATH-001 | 技能拥有路径须经 `resolve_data_path` / `get_*_dir``.env.example` 禁止 `./` CWD 相对路径;业务代码禁止 `abspath(config.get(...))` | development/DATA_PATHS.md | hard | 扫描 `.env.example``scripts/**/*.py` | `tests/test_development_policy_guard.py::TestPolicyDataPath001` |
| POLICY-SKILL-ACTION-001 | 存在 `development/SKILL_ACTION_RUNTIME.md`schema 含 `executionProfile`;业务技能(非模板占位 slug若 service 含 `RpaVideoSession``actions.json` 须有 `executionProfile=async` 且 placements 含 `agent` 的 action | development/SKILL_ACTION_RUNTIME.mdreferences/ACTIONS.md | hard | 文档/schema/manifest 检查 | `tests/test_development_policy_guard.py::TestPolicySkillAction001` |
| POLICY-SKILL-ACTION-002 | 每个 Action 必须显式声明 `executionProfile`,且只能是 `sync``async` | development/SKILL_ACTION_RUNTIME.mdreferences/ACTIONS.mdassets/schemas/skill-actions.schema.json | hard | schema required + manifest 扫描 | `tests/test_development_policy_guard.py::TestPolicySkillAction002``tests/test_actions_manifest.py` |
| POLICY-SKILL-ACTION-003 | toolbar Action 必须声明合法非空 `bind.tables`snake_case、唯一 | references/ACTIONS.mdassets/schemas/skill-actions.schema.json | hard | schema if/then + manifest 扫描 | `tests/test_development_policy_guard.py::TestPolicySkillAction003``tests/test_actions_manifest.py` |
| POLICY-SKILL-ACTION-004 | `placements``executionProfile` 正交文档不得把数据管理入口与异步执行方式硬绑定Schema 须接受 toolbar/cron/agent/skill-detail × sync/async 全部组合 | development/SKILL_ACTION_RUNTIME.mdreferences/ACTIONS.mdassets/schemas/skill-actions.schema.json | hard | Schema 4×2 矩阵校验 + 文档禁止短语扫描 | `tests/test_actions_manifest.py::test_schema_allows_all_placement_execution_profile_combinations``tests/test_development_policy_guard.py::TestPolicySkillAction004` |
| POLICY-ARCH-CORE-001 | 同一业务能力的 Action、CLI、Agent、cron、数据管理入口复用同一业务内核文档要求已声明 | development/DEVELOPMENT.mddevelopment/SKILL_ACTION_RUNTIME.md | hard文档标记 / soft语义 | 文档关键表述存在性;真实复用靠 sample/review | `tests/test_development_policy_guard.py::TestPolicyArchCore001``tests/samples/test_action_core_contract.py.sample` |
| POLICY-DATA-SYNC-001 | 同步型业务须遵循幂等、事务、完整性与空结果保护(文档已声明) | references/SCHEMA.mddevelopment/SKILL_ACTION_RUNTIME.md | hard文档标记 / soft语义 | 文档关键表述存在性;完整语义靠 sample/review | `tests/test_development_policy_guard.py::TestPolicyDataSync001``tests/samples/test_sync_contract.py.sample` |
--- ---
## 暂不自动检测(软规则) ## 暂不自动检测(软规则)
以下规范仍须人工遵守或依赖 code review / AI 提示词**不**做成默认测试,避免误伤 以下规范仍须人工遵守或依赖 code review / AI 提示词 / sample 契约,**不**做成脆弱关键字扫描
| 规则摘要 | 来源 | 原因 | | 规则摘要 | 来源 | 原因 |
|----------|------|------| |----------|------|------|
| `cli/` 只解析参数、不写业务逻辑 | development/DEVELOPMENT.md §9 | 需语义理解,无法可靠静态判定 | | `cli/` 只解析参数、不写业务逻辑 | development/DEVELOPMENT.md §9 | 需语义理解,无法可靠静态判定 |
| `service/` 编排流向与模块拆分粒度 | development/DEVELOPMENT.md §10 | 架构软约束 | | `service/` 编排流向与模块拆分粒度 | development/DEVELOPMENT.md §10 | 架构软约束;见 `test_action_core_contract.py.sample` |
| 是否真正复用同一业务内核 / 是否按 source 分叉 | development/SKILL_ACTION_RUNTIME.md §5 | 需调用图与人工审查 |
| 是否满足完整快照语义 / 空结果保护实现 | references/SCHEMA.md | 见 `test_sync_contract.py.sample` |
| 是否把系统导出与业务同步混淆 | references/ACTIONS.mdSCHEMA.md | 文档 + sample勿做源码关键词误报扫描 |
| `db/` 层不得调浏览器或拼业务流程 | development/DEVELOPMENT.md §11 | 需跨文件调用图 | | `db/` 层不得调浏览器或拼业务流程 | development/DEVELOPMENT.md §11 | 需跨文件调用图 |
| slug 命名语义verb-noun-platform | development/NAMING.md | 部分覆盖于 `tests/test_slug_naming.py`,非本矩阵 hard policy | | slug 命名语义verb-noun-platform | development/NAMING.md | 部分覆盖于 `tests/test_slug_naming.py`,非本矩阵 hard policy |
| 复制模板不得保留 `.git` / template marker | development/DEVELOPMENT.md §4 | 由 `tests/test_scaffold_guard.py` 守护,属脚手架场景 | | 复制模板不得保留 `.git` / template marker | development/DEVELOPMENT.md §4 | 由 `tests/test_scaffold_guard.py` 守护,属脚手架场景 |
@@ -41,4 +59,5 @@
| RPA 拟人操作、选择器纪律、HITL 超时 | development/RPA.md §0§1 | 行为与 DOM 质量,无法静态扫描 | | RPA 拟人操作、选择器纪律、HITL 超时 | development/RPA.md §0§1 | 行为与 DOM 质量,无法静态扫描 |
| adapter 四档契约测试覆盖 timeout/unauthorized 等 | development/ADAPTER.md §contract tests | 需业务实现后人工补测 | | adapter 四档契约测试覆盖 timeout/unauthorized 等 | development/ADAPTER.md §contract tests | 需业务实现后人工补测 |
| `SKILL.md` / `constants.SKILL_SLUG` 一致性 | development/DEVELOPMENT.md §16 | 已有 `tests/test_skill_metadata.py` | | `SKILL.md` / `constants.SKILL_SLUG` 一致性 | development/DEVELOPMENT.md §16 | 已有 `tests/test_skill_metadata.py` |
| platform_kit_min_version >= 1.0.17 | development/RUNTIME.md | 已有 `tests/test_platform_import.py` | | platform_kit_min_version >= 1.2.2 | development/RUNTIME.md | 已有 `tests/test_platform_import.py` |
| 宿主按 `bind.tables` 过滤 toolbar 按钮 | references/ACTIONS.md | 待宿主升级后完整生效;模板侧已强制显式绑定 |

View File

@@ -10,9 +10,11 @@
6. [`ADAPTER.md`](ADAPTER.md) — 涉及外部系统对接时 6. [`ADAPTER.md`](ADAPTER.md) — 涉及外部系统对接时
7. [`RPA.md`](RPA.md) — 涉及浏览器 / 桌面 / 手机自动化时 7. [`RPA.md`](RPA.md) — 涉及浏览器 / 桌面 / 手机自动化时
8. [`CONFIG.md`](CONFIG.md) — `.env` 规范与 bootstrap 机制 8. [`CONFIG.md`](CONFIG.md) — `.env` 规范与 bootstrap 机制
9. [`RUNTIME.md`](RUNTIME.md) — 共享 runtime、数据路径、发布打包与编码约定 9. [`DATA_PATHS.md`](DATA_PATHS.md) — 下载/导入/导出等本地文件路径标准(涉及文件读写时必读)
10. [`SKILL_ACTION_RUNTIME.md`](SKILL_ACTION_RUNTIME.md) — Skill Action sync/async、任务中心、Agent 禁令、队列 pick涉及 RPA / 长任务 / 数据管理按钮 / Cron / Agent 时必读)
11. [`RUNTIME.md`](RUNTIME.md) — 共享 runtime、数据路径、发布打包与编码约定
脚手架与 Git 防串库:[`../tools/README.md`](../tools/README.md)`scaffold_skill.ps1`)。 脚手架与 Git 防串库:[`../tools/README.md`](../tools/README.md)`scaffold_skill.ps1`)。
Agent 调用契约见 [`../references/CLI.md`](../references/CLI.md)、[`../references/SCHEMA.md`](../references/SCHEMA.md)。 Agent 调用契约见 [`../references/CLI.md`](../references/CLI.md)、[`../references/SCHEMA.md`](../references/SCHEMA.md)、[`../references/ACTIONS.md`](../references/ACTIONS.md)
用户市场说明见根目录 [`README.md`](../README.md),不要写进本目录。 用户市场四 Tab 见根目录 [`README.md`](../README.md) / [`TUTORIAL.md`](../TUTORIAL.md) / [`DEMO.md`](../DEMO.md) / [`CHANGELOG.md`](../CHANGELOG.md),不要写进本目录。

View File

@@ -22,6 +22,13 @@
- 中文 description一句话 - 中文 description一句话
- account-manager platform_key如有 - account-manager platform_key如有
- 命名形态:标准型 / scope 型 - 命名形态:标准型 / scope 型
- **网页 RPA如有— 登录策略(三选一,须写明):**
- `required`:目标站必须登录才能闭环(用户须完成/保持站点登录;技能每轮主路径须有登录门禁 + 验证码/人工等待)
- `optional`:登录可提升能力,但不登录也能完成主路径(**仅当**公开页确可闭环时选用;会话依赖型采集/评论/私信**禁止**默认抄成 optional
- `not_needed`:公开页即可,不要求站点登录
- 无论上列哪一种:**都必须**经 account-manager **`ensure-web`**(或等价)取得 `profile_dir`(见 `development/RPA.md` §0.2);不得使用系统默认浏览器用户目录
- **登记 ≠ 登录**ensure/add-web 只建账号与 Profile站点登录由本技能在有头浏览器中完成
- **反模式**:把「需要登录态才能采到数据」的需求写成 `optional`,再省略 `ensure_logged_in`
## 1. 文档目标 ## 1. 文档目标
@@ -60,7 +67,7 @@
- 输出结构化结果stdout JSON 或固定文本 + 机读字段) - 输出结构化结果stdout JSON 或固定文本 + 机读字段)
- 写入 `task_logs`(及必要的业务表,见 `references/SCHEMA.md` - 写入 `task_logs`(及必要的业务表,见 `references/SCHEMA.md`
- 支持失败可诊断(稳定错误码、`ERROR:` 前缀、必要截图/日志) - 支持失败可诊断(稳定错误码、`ERROR:` 前缀、必要截图/日志)
- 完成 CLI 入口与 `health` / `version` 最小可运行验证 - 完成 CLI 入口与 `health` / `version` / `init-db` 最小可运行验证
- 完成正式环境发布与安装验证(如适用) - 完成正式环境发布与安装验证(如适用)
## 4. 功能范围 ## 4. 功能范围
@@ -81,6 +88,7 @@
- 支持 `python scripts/main.py health` - 支持 `python scripts/main.py health`
- 支持 `python scripts/main.py version` - 支持 `python scripts/main.py version`
- 支持 `python scripts/main.py init-db`(幂等建库;宿主安装/更新后可静默调用)
- 支持 `python scripts/main.py <your-main-command>` - 支持 `python scripts/main.py <your-main-command>`
- 支持核心业务编排HTTP / 批处理 / 可选 RPA按四档 adapter 选型) - 支持核心业务编排HTTP / 批处理 / 可选 RPA按四档 adapter 选型)
- 支持写入任务日志(`task_logs` - 支持写入任务日志(`task_logs`
@@ -97,11 +105,12 @@
- 目录结构必须符合当前 `skill-template` 规范 - 目录结构必须符合当前 `skill-template` 规范
- 入口必须统一为 `scripts/main.py` - 入口必须统一为 `scripts/main.py`
- 用户说明写在根 `README.md`LLM/运行契约写在 `SKILL.md`;开发规范在 `development/` - 用户市场四 Tab 写在根 `README.md` / `TUTORIAL.md` / `DEMO.md` / `CHANGELOG.md`LLM/运行契约写在 `SKILL.md`;开发规范在 `development/`
- 输出格式应尽量机读友好;错误前缀统一为 `ERROR:` - 输出格式应尽量机读友好;错误前缀统一为 `ERROR:`
- Windows 环境下需保证 UTF-8 输出兼容 - Windows 环境下需保证 UTF-8 输出兼容
- 必须具备基本日志能力;敏感字段脱敏 - 必须具备基本日志能力;敏感字段脱敏
- RPA 类 skillPlaywright 由宿主共享 runtime 提供;技能侧不要 `playwright install`URL 不要放进 `launch_persistent_context``args` - RPA 类 skillPlaywright 由宿主共享 runtime 提供;技能侧不要 `playwright install`URL 不要放进 `launch_persistent_context``args`
- 网页 RPA启动前必须经 ensure-web 拿到 `profile_dir`;生产有头;站点登录策略见 §0required / optional / not_needed`required` 时每轮须登录门禁
## 6. 输入输出要求 ## 6. 输入输出要求
@@ -154,7 +163,7 @@
什么情况下才算开发完成: 什么情况下才算开发完成:
- 代码结构符合模板规范;`SKILL.md` slug 与 `constants.SKILL_SLUG` 一致 - 代码结构符合模板规范;`SKILL.md` slug 与 `constants.SKILL_SLUG` 一致
- `health``version` 命令执行正常 - `health``version``init-db` 命令执行正常
- 主命令(如 `run`)在 mock / simulator 档位可重复验证 - 主命令(如 `run`)在 mock / simulator 档位可重复验证
- `python tests/run_tests.py -v` 必跑测试全部通过 - `python tests/run_tests.py -v` 必跑测试全部通过
- `task_logs` 写入和查询符合 `references/SCHEMA.md`(含 `created_at` / `updated_at` Unix 秒级规范) - `task_logs` 写入和查询符合 `references/SCHEMA.md`(含 `created_at` / `updated_at` Unix 秒级规范)
@@ -211,7 +220,7 @@
## 4. 功能范围 ## 4. 功能范围
- 支持 health / version / run - 支持 health / version / init-db / run
- 支持 logs / log-get - 支持 logs / log-get
## 5. 非功能要求 ## 5. 非功能要求

View File

@@ -2,7 +2,7 @@
> 本文是团队 RPA 开发的**统一标准**。任何需要"自动操作软件界面"的 skill都应先读这份文档按这里的选型和范式落地不要每个项目重新踩坑。 > 本文是团队 RPA 开发的**统一标准**。任何需要"自动操作软件界面"的 skill都应先读这份文档按这里的选型和范式落地不要每个项目重新踩坑。
我们开发的各类 skill本质上都是在替人操作三类界面**浏览器、桌面软件、手机软件**。三类的底层技术不同,但**工程范式相同**保持登录态、有头运行、拟人操作、失败存证、人工兜底。 我们开发的各类 skill本质上都是在替人操作三类界面**浏览器、桌面软件、手机软件**。三类的底层技术不同,但**工程范式相同**可控会话Profile、有头运行、拟人操作、失败存证、人工兜底。
--- ---
@@ -12,18 +12,64 @@
| 约定 | 说明 | | 约定 | 说明 |
|------|------| |------|------|
| **保持登录态** | 复用持久化 Profile / session避免每次重新登录触发风控账号由 account-manager 下发,不硬编码 | | **可控会话 / Profile** | 网页版见下方 **§0.2**(必须走 account-manager 的 `profile_dir`);桌面/手机用对应持久会话,不硬编码密码 |
| **有头运行** | 默认有头headless 易被识别 / 难人工介入);`OPENCLAW_BROWSER_HEADLESS=1` 仅给 CI | | **有头运行** | 生产 RPA **必须有头**(见 §0.2);禁止把无头当交付/联调常态 |
| **拟人操作** | 真实事件isTrusted=true逐字输入、随机延迟、贝塞尔鼠标轨迹严禁 JS 直接设值/JS 点击/JS 跳转 | | **拟人操作** | 真实事件isTrusted=true逐字输入、随机延迟、贝塞尔鼠标轨迹严禁 JS 直接设值/JS 点击/JS 跳转 |
| **步骤间随机等待** | 每两步操作之间 `random_delay(min,max)`,区间由 `.env` 配置(默认 1~5s | | **步骤间随机等待** | 每两步操作之间 `random_delay(min,max)`,区间由 `.env` 配置(默认 1~5s |
| **人工兜底HITL** | 滑块 / 短信验证码 / 人脸 / U盾 / 动态口令 → **停下来轮询等人工**,超时报 `ERROR:XXX_NEED_HUMAN`,绝不自动硬闯 | | **人工兜底HITL** | 滑块 / 短信验证码 / 人脸 / U盾 / 动态口令 → **停下来轮询等人工**,超时报 `ERROR:XXX_NEED_HUMAN`,绝不自动硬闯 |
| **失败存证** | 失败必截图,合规场景全程录屏,统一存 `{数据目录}/rpa-artifacts/{batch_id}/{tag}_{ts}.png` | | **失败存证** | 失败必截图,合规场景全程录屏,统一存 `{数据目录}/rpa-artifacts/{batch_id}/{tag}_{ts}.png` |
| **选择器纪律** | 语义选择器优先id/name/text/aria**F12 确认后再写,严禁凭记忆猜 DOM** | | **选择器纪律** | 语义选择器优先id/name/text/aria**F12 确认后再写,严禁凭记忆猜 DOM** |
| **统一错误码** | `ERROR:REQUIRE_LOGIN` / `ERROR:CAPTCHA_NEED_HUMAN` / `ERROR:RATE_LIMITED` / `ERROR:LOGIN_TIMEOUT` 等,见下方错误码表 | | **统一错误码** | `ERROR:REQUIRE_LOGIN` / `ERROR:CAPTCHA_NEED_HUMAN` / `ERROR:RATE_LIMITED` / `ERROR:LOGIN_TIMEOUT` 等,见下方错误码表 |
| **步骤可控制** | 每条 RPA 指令 = 一个 `@rpa_step``video.add_step`;等待用 `interruptible_sleep`;宿主通过 control.json 暂停/继续/停止SRCP见 [`LOGGING.md`](LOGGING.md) §2.5 |
| **幂等 / 断点续跑** | 批量操作记录"已处理到第几条",崩溃后能续跑、不重复提交 | | **幂等 / 断点续跑** | 批量操作记录"已处理到第几条",崩溃后能续跑、不重复提交 |
> 三端各自实现一个会话抽象 `RpaSession`launch / login / act / screenshot / close上层 skill 不感知是浏览器还是手机。 > 三端各自实现一个会话抽象 `RpaSession`launch / login / act / screenshot / close上层 skill 不感知是浏览器还是手机。
### 0.1 步骤控制与进度SRCPplatform-kit >= 1.2.0
- **禁止** `scripts/util/progress.py``print({"type":"progress",...})`;进度只走 `emit` / Run Journal。
- **禁止** RPA 主路径裸 `asyncio.sleep`;用 `jiangchang_skill_core.activity.interruptible_sleep`
- RPA 函数用 `@rpa_step("中文步骤名")` 拆分;或在 `RpaVideoSession``video.add_step("中文步骤")`
- `cmd_run``with job_context(skill=SKILL_SLUG):`,所有出口 `finish(...)`
- 暂停在步骤边界生效;浏览器会话暂停时不强制关闭,恢复后同进程继续。
```python
from jiangchang_skill_core.activity import emit, finish, job_context, interruptible_sleep, rpa_step
@rpa_step("打开登录页")
async def open_login(page):
await page.goto("https://example.com")
await interruptible_sleep(1.5)
```
规范权威定义:[`LOGGING.md`](LOGGING.md) §2.5。金样代码:[`scripts/service/task_service.py`](../scripts/service/task_service.py)。
### 0.2 网页版 RPA 硬规则Profile / 有头 / 登录分平台)
凡**打开网页、用浏览器自动化**的技能(真实站或仿真站),必须遵守(`POLICY-RPA-004`
| 规则 | 要求 |
|------|------|
| **Profile 强制** | 启动浏览器前必须已从 **account-manager**(经本技能 `account_client`)拿到可用的 **`profile_dir`(及租约约定)**。只用该目录做 `launch_persistent_context`。 |
| **首启用 ensure** | 业务技能默认走 **`account ensure-web`**(或 `pick-web --ensure`),经 `account_client.pick_web_account` 封装。无匹配账号时自动 `add-web` 再返回;**有账号但均被租约占用 → `ERROR:LEASE_CONFLICT`,禁止再新建重复账号**。 |
| **拿不到就停** | 未拿到 `profile_dir`、ensure 失败、租约失败 → **立即失败退出,禁止开浏览器**。不得静默落到系统默认 Chrome/Edge 用户目录。 |
| **有头强制** | 生产与用户侧联调:**`OPENCLAW_BROWSER_HEADLESS=0`(有头)**。禁止把无头(`=1`)当作交付或真实站联调常态(无头易风控、难人工介入,且易污染身份)。 |
| **登录不全局强制** | **是否要在目标站完成登录**由平台决定(如部分公开页可不登录也能闭环)。由做该技能的同事在 `REQUIREMENTS.md` / 用户教程中约定;**模板不强制「所有网页 RPA 必须先登录」**。 |
| **登记 ≠ 登录** | `ensure-web` / `add-web` 只保证有账号记录与 Profile 目录;**不等于**目标站已登录。站点登录仍由本技能 `ensure_logged_in`(或等价)在有头浏览器中完成。 |
| **登录 ≠ Profile** | 「可不登录」**绝不等于**「可以不接 account-manager」。无论目标站要不要登录网页操作都依赖账号管理下发的 **Profile**。 |
| **登录策略 = required 时** | 每轮业务主路径在 `goto` 后必须过登录门禁 + 验证码/人工等待(`HUMAN_WAIT_TIMEOUT`**禁止**把会话依赖型采集默认抄成 `optional`。 |
**反模式(禁止):**
- 未拿到 `profile_dir``launch` / 仍打开页面
- 用系统默认用户数据目录或随意空目录反复跑真实站 → **污染本机 Profile、加重风控**
- 把「本站可不登录」写成「可以不走 account-manager」
- 真实站联调默认无头狂跑
- 仅用哈希 class / 不稳定 CSS 作为**唯一**登录态判定(须结合稳定文案、`get_by_role`、URL/业务 DOMF12 实页确认)
- 把「业务空结果」(如无评论)与 `LEASE_CONFLICT` / `REQUIRE_LOGIN` 混成同一错误码
**参考实现:** `examples/real_browser_rpa/``examples/simulator_browser_rpa/``pick_web_account` → ensure-web → RPA → `finally release_lease`)。
--- ---
## 1. 浏览器(标准已成熟) ## 1. 浏览器(标准已成熟)
@@ -35,23 +81,24 @@
| 项 | 标准 | | 项 | 标准 |
|----|------| |----|------|
| 浏览器 | **优先系统 Chrome/Edge** + `launch_persistent_context``channel="chrome"` 或 Edge不用内置 Chromium**技能内不要 `playwright install`** | | 浏览器 | **优先系统 Chrome/Edge** + `launch_persistent_context``channel="chrome"` 或 Edge不用内置 Chromium**技能内不要 `playwright install`** |
| 登录态 | 持久 Profile 目录账号、profile、lease **统一走 account-manager**(或对应兄弟技能),不硬编码密码 | | Profile / 账号 | **必须**经 account-manager **`ensure-web`**(或 `pick-web --ensure`)取得 `profile_dir`(见 §0.2);密码不进 `.env`**是否站点登录**按平台在需求/教程约定;登记 ≠ 已登录 |
| CDP | **仅作诊断 / 桌面宿主类场景****不要**作为强风控站点的默认生产路径 | | CDP | **仅作诊断 / 桌面宿主类场景****不要**作为强风控站点的默认生产路径 |
| 行为 | 模拟真实用户:真实点击、键盘、鼠标、地址栏输入;**不要**拼接搜索结果 URL、DOM 注入、`el.value=`、JS 跳转 | | 行为 | 模拟真实用户:真实点击、键盘、鼠标、地址栏输入;**不要**拼接搜索结果 URL、DOM 注入、`el.value=`、JS 跳转 |
| 模式 | 默认有头 `OPENCLAW_BROWSER_HEADLESS=0`;无头仅 CI | | 模式 | **有头** `OPENCLAW_BROWSER_HEADLESS=0`(生产强制,见 §0.2 |
| 反检测 | stealth 默认开 `OPENCLAW_PLAYWRIGHT_STEALTH=1`(见 1.1 | | 反检测 | stealth 默认开 `OPENCLAW_PLAYWRIGHT_STEALTH=1`(见 1.1 |
### 1.1 Playwright 启动标准 ### 1.1 Playwright 启动标准
1. **默认有头**`OPENCLAW_BROWSER_HEADLESS=0``.env.example` 默认)。 1. **有头**`OPENCLAW_BROWSER_HEADLESS=0``.env.example` 默认;网页 RPA 生产路径禁止改成无头常态,见 §0.2)。
2. **stealth 默认开**`OPENCLAW_PLAYWRIGHT_STEALTH=1`;通过 `add_init_script` 注入指纹淡化脚本。 2. **stealth 默认开**`OPENCLAW_PLAYWRIGHT_STEALTH=1`;通过 `add_init_script` 注入指纹淡化脚本。
3. **不要在技能里自行安装 playwright**;由宿主共享 runtime 提供。 3. **不要在技能里自行安装 playwright**;由宿主共享 runtime 提供。
4. **不要默认传 `--no-sandbox`**(除非特定容器环境且已评估风险)。 4. **不要默认传 `--no-sandbox`**(除非特定容器环境且已评估风险)。
5. **不要默认传 `--disable-blink-features=AutomationControlled`**platform-kit stealth 已覆盖,额外 flag 可能适得其反。 5. **不要默认传 `--disable-blink-features=AutomationControlled`**platform-kit stealth 已覆盖,额外 flag 可能适得其反。
6. **可以** `ignore_default_args=["--enable-automation"]`platform-kit `launch_persistent_browser` 已处理)。 6. **可以** `ignore_default_args=["--enable-automation"]`platform-kit `launch_persistent_browser` 已处理)。
7. **强风控平台**:优先真实点击、键盘、鼠标、地址栏、持久 profile**不要**直接拼接搜索结果 URL 或 DOM 注入。 7. **强风控平台**:优先真实点击、键盘、鼠标、地址栏、account-manager 持久 profile**不要**直接拼接搜索结果 URL 或 DOM 注入。
8. **先 Profile 再开浏览器**`user_data_dir` 必须来自 ensure/pick 到的 `profile_dir`;未拿到则不得进入本节后续步骤。
指纹淡化stealth典型项`navigator.webdriver=undefined``chrome.runtime``permissions.query``plugins``languages` 等。共享实现见 `jiangchang_skill_core.rpa`platform-kit **>= 1.0.17**)。 指纹淡化stealth典型项`navigator.webdriver=undefined``chrome.runtime``permissions.query``plugins``languages` 等。共享实现见 `jiangchang_skill_core.rpa`platform-kit **>= 1.2.0**)。
**拟人操作**(必做): **拟人操作**(必做):
@@ -124,7 +171,7 @@ from jiangchang_skill_core.rpa import (
from jiangchang_skill_core.rpa.stealth import stealth_enabled, STEALTH_INIT_SCRIPT from jiangchang_skill_core.rpa.stealth import stealth_enabled, STEALTH_INIT_SCRIPT
``` ```
- `RpaVideoSession` 来自 platform-kit **>= 1.0.17**ffmpeg、背景音乐、media-assets 由 platform-kit 统一解析;已提供前置/后置缓冲、字幕、TTS 旁白、背景音乐循环、结尾淡出。 - `RpaVideoSession` 来自 platform-kit **>= 1.2.0**ffmpeg、背景音乐、media-assets 由 platform-kit 统一解析;已提供前置/后置缓冲、字幕、TTS 旁白、背景音乐循环、结尾淡出。
- `health` 对上述资源做只读诊断,不下载、不修复。 - `health` 对上述资源做只读诊断,不下载、不修复。
### 1.5 真实浏览器 RPA 示例(必读) ### 1.5 真实浏览器 RPA 示例(必读)
@@ -166,7 +213,7 @@ from jiangchang_skill_core.rpa.stealth import stealth_enabled, STEALTH_INIT_SCRI
| Playwright | **async** 贯穿;禁止 sync Playwright 用于完整 RPA 主路径 | | Playwright | **async** 贯穿;禁止 sync Playwright 用于完整 RPA 主路径 |
| 分层 | **薄 adapter** + `{domain}_playwright.py`(示例:`simulator_playwright.py`+ `account_client.py` subprocess | | 分层 | **薄 adapter** + `{domain}_playwright.py`(示例:`simulator_playwright.py`+ `account_client.py` subprocess |
| 登录 | **双层**:门户 HITL`#portal-user` / `#portal-pass` 类泛化 DOM+ 业务系统登录(技能内自写) | | 登录 | **双层**:门户 HITL`#portal-user` / `#portal-pass` 类泛化 DOM+ 业务系统登录(技能内自写) |
| 账号 | `url` 用行业根,不用 `/login``auth_strategy=per_session_manual``pick_web_account` + `release_lease` | | 账号 | `url` 用行业根,不用 `/login``auth_strategy=per_session_manual``pick_web_account`(底层 ensure-web+ `release_lease` |
| 禁止 | **不要** `import account-manager``rpa_helpers` 等内部模块 | | 禁止 | **不要** `import account-manager``rpa_helpers` 等内部模块 |
| Selector | 用户可见文案 / `get_by_role` / `name` 优先;`data-testid` 有则用、无则 fallback共享 sandbox **不要求**为技能加 testid | | Selector | 用户可见文案 / `get_by_role` / `name` 优先;`data-testid` 有则用、无则 fallback共享 sandbox **不要求**为技能加 testid |
| Profile | Chrome persistent profile 可能缓存旧 SPA → 联调排障:手工 `--user-data-dir` 清站点数据 | | Profile | Chrome persistent profile 可能缓存旧 SPA → 联调排障:手工 `--user-data-dir` 清站点数据 |
@@ -240,14 +287,18 @@ skill 退出/抛错统一用 `ERROR:` 前缀 + 稳定码,方便宿主与上层
| 错误码 | 含义 | 上层处理建议 | | 错误码 | 含义 | 上层处理建议 |
|--------|------|------| |--------|------|------|
| `ERROR:REQUIRE_LOGIN` | 未登录 / 登录态失效 | 触发登录流程 | | `ERROR:REQUIRE_LOGIN` | 未登录 / 登录态失效 | 触发登录流程(有头等待人工) |
| `ERROR:LOGIN_TIMEOUT` | 等待人工登录超时 | 提示用户重跑并及时操作 | | `ERROR:LOGIN_TIMEOUT` | 等待人工登录超时 | 提示用户重跑并及时操作 |
| `ERROR:CAPTCHA_NEED_HUMAN` | 命中滑块/验证码拦截 | 暂停等人工,或转人工队列 | | `ERROR:CAPTCHA_NEED_HUMAN` | 命中滑块/验证码拦截 | 暂停等人工,或转人工队列 |
| `ERROR:LEASE_CONFLICT` | 已有账号但均被租约占用ensure 不新建) | 稍后重试或释放租约;**不是**「无账号」 |
| `ERROR:AMBIGUOUS_ACCOUNT` | `--login-id` / `--label` 匹配到多条 | 改用数字 id 或更精确标识 |
| `ERROR:RATE_LIMITED` | 触发频控 | 退避后重试 | | `ERROR:RATE_LIMITED` | 触发频控 | 退避后重试 |
| `ERROR:MISSING_BROWSER` | 未检测到 Chrome/Edge | 提示安装 | | `ERROR:MISSING_BROWSER` | 未检测到 Chrome/Edge | 提示安装 |
| `ERROR:DEVICE_NOT_READY` | 手机未连接/未授权 | 检查 USB/ADB | | `ERROR:DEVICE_NOT_READY` | 手机未连接/未授权 | 检查 USB/ADB |
| `ERROR:WINDOW_NOT_FOUND` | 桌面目标窗口未找到 | 检查程序是否启动 | | `ERROR:WINDOW_NOT_FOUND` | 桌面目标窗口未找到 | 检查程序是否启动 |
业务空结果(如「本页无评论」)用业务码或成功空列表表达,**不要**复用上表账号/登录错误码。
--- ---
## 5. 存证与录屏规范 ## 5. 存证与录屏规范
@@ -283,13 +334,16 @@ skill 退出/抛错统一用 `ERROR:` 前缀 + 稳定码,方便宿主与上层
### 5.3 录屏成片标准 ### 5.3 录屏成片标准
- RPA skill 默认 `OPENCLAW_RECORD_VIDEO=1` - **skill-template 默认 `OPENCLAW_RECORD_VIDEO=0`**(开发调试更快,不启 ffmpeg
- **`OPENCLAW_RECORD_VIDEO=1` 时启用录屏**字幕、旁白、背景音、MP4 成片由 platform-kit 统一处理。
- 使用 platform-kit 的 **`RpaVideoSession`****skill 不要自行合成视频**(不要自己调 ffmpeg 拼 MP4 - 使用 platform-kit 的 **`RpaVideoSession`****skill 不要自行合成视频**(不要自己调 ffmpeg 拼 MP4
- `OPENCLAW_RECORD_VIDEO=0` 时 session 无副作用(不启 ffmpeg、不写字幕文件)。 - **默认关闭 ≠ 可以删除录屏接入**RPA / 长任务 **service 层**`scripts/service/*.py`**必须保留** `RpaVideoSession``video.add_step`、video artifact merge 到 `result_summary`(见 `POLICY-RPA-003`)。
- `OPENCLAW_RECORD_VIDEO=0` 时 session **无副作用**(不启 ffmpeg、不写字幕文件、不生成最终 MP4**`RpaVideoSession.add_step` 仍可同步 Activity 进度**。
- 生产留证 / 合规 / 客户现场复现时,由用户在 `.env` 或进程环境变量中开启 `OPENCLAW_RECORD_VIDEO=1`
- **ffmpeg 是唯一录屏器**Windows`gdigrab` + `desktop`)。 - **ffmpeg 是唯一录屏器**Windows`gdigrab` + `desktop`)。
- **最终视频**`{skill_data_dir}/videos/{skill_slug}_{yyyyMMdd_HHmmss}_{batch_id}.mp4` - **最终视频**`OPENCLAW_RECORD_VIDEO=1` 时)`{skill_data_dir}/videos/{skill_slug}_{yyyyMMdd_HHmmss}_{batch_id}.mp4`
- **中间产物**`rpa-artifacts/{batch_id}/capture.mp4``subtitles/``logs/` 等。 - **中间产物**`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`)。 - 任务完成后 CLI / `result_summary` 应包含 video 字段(开启录屏时有路径;关闭时仍保留 `video` 结构与诊断占位)`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()` 模板最小示范见 `scripts/service/task_service.py``_run_template_demo()`

View File

@@ -2,29 +2,42 @@
## 共享 Python Runtime ## 共享 Python Runtime
**skill-template** 及复制出的新技能,公共能力均来自宿主匠厂安装的共享 Python Runtime`jiangchang-platform-kit>=1.0.17` 及其传递依赖,含 `playwright`)。`jiangchang_skill_core` **不得**在技能仓库内 vendored应由共享 venv 的 site-packages 提供。 **skill-template** 及复制出的新技能,公共能力均来自宿主匠厂安装的共享 Python Runtime`jiangchang-platform-kit>=1.2.2` 及其传递依赖,含 `playwright`)。`jiangchang_skill_core` **不得**在技能仓库内 vendored应由共享 venv 的 site-packages 提供。
技能根目录 `requirements.txt` **只声明技能特有依赖****不要**重复声明 `jiangchang-platform-kit``playwright``SKILL.md``platform_kit_min_version` 是运行契约,**不是** pip 依赖声明。 技能根目录 `requirements.txt` **只声明技能特有依赖****不要**重复声明 `jiangchang-platform-kit``playwright``SKILL.md``platform_kit_min_version` 是运行契约,**不是** pip 依赖声明。
### 何时上调 `platform_kit_min_version`
| 情况 | 做法 |
|------|------|
| 技能依赖 kit 某次修复/新 API`.env` 空值+行尾 `#` 解析、新 RPA helper | 把 `metadata.openclaw.platform_kit_min_version` 调到**需要的最低版本**(例如 `"1.2.2"` |
| PyPI/私有源刚发了更新,但本技能行为未依赖 | **不必**仅为「追新」抬版本 |
| 宿主升级时机 | 宿主在技能/宿主声明的最低版本**未满足**时按需升级共享 venv**不会**仅因源上有更新就后台拉 latest |
模板默认声明须与当前文档所依赖的最低 kit 能力对齐(见根 `SKILL.md`)。
| 场景 | 推荐做法 | | 场景 | 推荐做法 |
|------|----------| |------|----------|
| 日常运行 | 由宿主匠厂触发技能 | | 日常运行(宿主 / Agent | 使用 PATH 上的共享 venv `python``{JIANGCHANG_DATA_ROOT}/python-runtime/.venv` |
| 手工排查 / 测试机 | 使用共享 runtime 的 `python.exe` 执行 `scripts/main.py` | | 手工排查 / 测试机(环境未注入时) | `{JIANGCHANG_DATA_ROOT}/python-runtime/.venv/.../python` 执行 `scripts/main.py` |
| **不推荐** | 在技能目录内 `uv run python …`可能创建临时 venv加载不到宿主共享 runtime | | **禁止** | 在技能目录内 `uv run python …`创建临时 venv加载不到宿主共享 runtime |
占位命令(路径因环境而异,勿写死本机目录): 占位命令(路径因环境而异,勿写死本机目录):
```text ```text
Windows: 推荐(已注入环境时):
python {baseDir}/scripts/main.py health
Windows未注入时:
{JIANGCHANG_DATA_ROOT}\python-runtime\.venv\Scripts\python.exe {baseDir}\scripts\main.py health {JIANGCHANG_DATA_ROOT}\python-runtime\.venv\Scripts\python.exe {baseDir}\scripts\main.py health
通用: Unix未注入时:
<shared-python> {baseDir}/scripts/main.py health {JIANGCHANG_DATA_ROOT}/python-runtime/.venv/bin/python3 {baseDir}/scripts/main.py health
``` ```
`<shared-python>` 通常位于 `{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`。数据根由宿主注入;开发模式下也可能通过 `JIANGCHANG_DATA_ROOT` 解析(见 `jiangchang_skill_core.runtime_env`)。 共享解释器通常位于 `{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`。数据根由宿主注入(见 `jiangchang_skill_core.runtime_env`)。
## Runtime 诊断platform-kit 1.0.17+ ## Runtime 诊断platform-kit 1.2.2+
`health` 命令通过 **`jiangchang_skill_core.collect_runtime_diagnostics`** 输出共享 runtime 诊断,**不在技能内重复实现**。典型字段: `health` 命令通过 **`jiangchang_skill_core.collect_runtime_diagnostics`** 输出共享 runtime 诊断,**不在技能内重复实现**。典型字段:
@@ -42,7 +55,7 @@ Windows:
- 用户实际 `.env``{JIANGCHANG_DATA_ROOT}/{JIANGCHANG_USER_ID}/{skill_slug}/.env` - 用户实际 `.env``{JIANGCHANG_DATA_ROOT}/{JIANGCHANG_USER_ID}/{skill_slug}/.env`
- `scripts/main.py``cli.app.main()` 启动时调用 `util.config_bootstrap.bootstrap_skill_config()` - `scripts/main.py``cli.app.main()` 启动时调用 `util.config_bootstrap.bootstrap_skill_config()`
- 配置优先级:**进程环境变量** > **用户 `.env`** > **`.env.example` 默认值**。 - 配置优先级:**进程环境变量** > **用户 `.env`** > **`.env.example` 默认值**。
- 公共 `config` / `merge_missing_env_keys` 来自共享 runtime 的 `jiangchang-platform-kit>=1.0.17`**不得** vendored `scripts/jiangchang_skill_core/` - 公共 `config` / `merge_missing_env_keys` 来自共享 runtime 的 `jiangchang-platform-kit>=1.2.2`**不得** vendored `scripts/jiangchang_skill_core/`
## media-assets / ffmpeg / 背景音乐 ## media-assets / ffmpeg / 背景音乐
@@ -89,6 +102,8 @@ RPA 录屏成片(`RpaVideoSession`、ffmpeg 路径、背景音乐探测均
{...}/{skill_slug}.db {...}/{skill_slug}.db
``` ```
**业务文件(下载、导入、导出、缓存等)** 须落在上述数据目录的标准子目录下,**不得**相对 workspace/CWD 写入。完整子目录树、env 覆盖规则、`resolve_data_path()` 用法见 **[`DATA_PATHS.md`](DATA_PATHS.md)**。
- 业务表使用英文 snake_case中文表名/字段名写入 `_jiangchang_tables` / `_jiangchang_columns`(见 `references/SCHEMA.md`)。 - 业务表使用英文 snake_case中文表名/字段名写入 `_jiangchang_tables` / `_jiangchang_columns`(见 `references/SCHEMA.md`)。
- 界面字段顺序由 `CREATE TABLE` 列定义顺序决定,**不要**维护 `display_order` 来调整顺序。 - 界面字段顺序由 `CREATE TABLE` 列定义顺序决定,**不要**维护 `display_order` 来调整顺序。

View File

@@ -0,0 +1,205 @@
# Skill Action Runtime宿主任务中心契约
本文是匠厂宿主 **Skill Action / 任务中心** 的技能侧金标准。涉及浏览器 RPA、长耗时任务、数据管理按钮、定时任务或 Agent 直接调用时**必读**。
**边界:**
| 文档 | 职责 |
|------|------|
| 本文 | sync/async、任务中心、Agent 禁令、单内核编排、队列 pick、同步 vs 导出 |
| [`../references/ACTIONS.md`](../references/ACTIONS.md) | `actions.json` 字段、placements、`bind.tables`、inputSchema |
| [`LOGGING.md`](LOGGING.md) | `job_context` / `emit` / `finish` / Run Journal |
| [`DATA_PATHS.md`](DATA_PATHS.md) | 下载/导入等落盘路径 |
宿主实现细节以匠厂 Host API 为准;技能侧只需保证 manifest 与 CLI 契约稳定。
---
## 1. 核心原则
1. **宿主管调度,技能管业务** — 不自行实现任务中心 / Job 轮询 / 后台守护进程。
2. **单业务内核、多入口** — 数据管理、定时任务、Agent、技能详情与直接 CLI 复用同一 domain service禁止按入口复制业务逻辑。
3. **五职责正交**`placements` / `bind.tables` / `executionProfile` / `entrypoint` / domain service 各管一事(见 ACTIONS.md
4. **长耗时建议 async** — 开浏览器、RPA、HTTP 大文件下载等建议 `executionProfile: "async"`,进**任务中心**;这是对**方法**的选择,**不**限制可以出现在哪些 placement / 入口。
5. **Agent短 CLI / 长 Action** — 短查询可用共享 Python bash CLI长任务 / RPA **禁止** `exec` + `process poll`,必须 `run_skill_action`
6. **进度走 Journal**`emit` / `video.add_step` → Run JournalUI / Skill Run Card / 任务中心展示;**不靠 stdout 流**。
7. **显式声明 `executionProfile`** — 心智默认 sync、例外才 async每个 action **必须**写明 `sync``async`;宿主省略时按 sync新技能仍禁止赌缺省禁止第三种模糊模式`auto` / `background` / `deferred` 等)。
---
## 2. `executionProfile`sync vs async
### 心智(先记住)
1. **默认按 sync 想**:多数 Action诊断、统计、入队、秒级查询是短调用当场返回**不进**任务中心。
2. **只有特殊情况标 async**:开浏览器 / RPA / 长下载 / 需要进度·暂停·停止时,才显式 `"executionProfile": "async"`,进入**任务中心**。
3. **匠厂宿主**`actions.json` 若**省略** `executionProfile`,按 **`sync`** 处理(不再把漏写当成进任务中心)。
4. **新技能仍须显式写出** `sync``async`(模板 Schema / `POLICY-SKILL-ACTION-002` 硬门禁),禁止赌宿主缺省;显式写出也便于人和 AI 阅读。
| 值 | 宿主行为 | 超时 | 任务中心 |
|----|----------|------|----------|
| **`sync`**(或省略时的宿主缺省) | 调用方等待 CLI 结束,直接返回结构化结果或结构化错误;**不**创建后台 Job | 默认约 **30s**`SKILL_ACTION_SYNC_TIMEOUT_MS` | ❌ 不进 |
| **`async`**(须显式声明) | 后台 spawn Job立即返回 `jobId``emit` / `checkpoint` / `finish`;长任务应支持暂停/停止/取消检查 | Job 本身无默认墙钟上限 | ✅ 进入 |
直接执行 CLI终端等待进程结束。宿主经 Action 调用同一 CLI再按 `executionProfile` 分流。技能不得自建任务中心。
### 选择建议(不是 placement 硬限制)
| 场景 | 建议 |
|------|------|
| 浏览器 / Playwright / RPA 主路径 | `async` + 建议 `confirmation` |
| 单次可能超过 ~20s 的网络/下载/同步 | `async` |
| `health` / `version` / `config-path` / 纯统计 / 秒级查询 | `sync` |
| 任意 placement含 toolbar | 允许 sync 或 async以 manifest 为准 |
合法:`sync|async` × `toolbar|cron|agent|skill-detail`
历史说明:旧文档曾错误地把数据管理按钮入口与异步执行方式绑死。该约束**已废止**;模板测试与 Schema **不得**再建立「入口位置决定 sync/async」一类硬耦合。旧版宿主曾「省略 → async」**当前宿主为「省略 → sync」**。新技能仍须显式声明,不得依赖省略行为。
---
## 3. 多入口如何感知 sync / async
多个入口统一走 `POST /api/skill-actions/run`,可能带 `source.kind`
| 入口 | 常见 `source.kind` | 说明 |
|------|-------------------|------|
| **Agent** | `agent` | `run_skill_action`;按 manifest 的 executionProfile 执行 |
| **数据管理** | `data-management` | toolbar 按钮;须 `bind.tables` |
| **定时任务** | `cron` | Cron 配置参数后调用同一 Action |
| **技能详情** | (依宿主) | 与上同一 CLI / 同一业务内核 |
技能 **不要** 在 Python 里按 `source` / placement 写业务分叉;宿主读 manifest 分流展示与等待策略。
---
## 4. Action 分类与 placements示例不是限制
下表只表示常见组合示例。**placements 以 manifest 为准sync/async 不影响展示入口。**
| Action 类型 | 常见 `executionProfile` | 常见 placements | `confirmation` |
|-------------|-------------------------|-----------------|----------------|
| 运行检查 / 版本 / 配置路径 | `sync` | `skill-detail`, `agent` | 无 |
| 库 / 队列统计 | `sync` | `skill-detail`, `agent` | 无 |
| 外源 → 本地库同步 | `sync``async` | 可含 `toolbar`(须 `bind.tables`)、`cron``agent` | 可选 |
| 数据导入 / 失败重置 | `sync``async` | `skill-detail`, `agent` | 可选 |
| **单条**副作用 RPA | `async`(建议) | `agent`, `skill-detail` | **建议** |
| **批量顺序** RPApick | `async`(建议) | `toolbar`, `cron`, `agent` | **建议** |
禁忌:
- 高副作用 action 不要默认只挂 `toolbar`(应有 confirmation
-`sensitive` 参数的 action 不要挂 `toolbar` / `cron`(除非有明确安全设计)。
- 不要为了「按钮多」暴露所有 CLI 子命令。
- 不要按入口复制多套采集 / 同步 / 处理实现。
---
## 5. 技能内编排范式(单内核 + 多入口)
推荐分层:
```text
scripts/cli/app.py # 参数解析 → 调用 task / service
scripts/service/task_service.py # job_context / emit / checkpoint / finish / 错误转换
scripts/service/<domain>_service.py # 唯一业务内核
scripts/db/*_repository.py # 只负责读写与事务
assets/actions.json # 声明入口、参数、placement、executionProfile、bind
```
长任务 / RPA 常见拆分(勿把 `job_context` 塞进纯业务内核):
```text
execute_single_<biz>(...) # 纯业务:鉴权 + 核心逻辑 + task_log不含 job_context
cmd_run(...) # 单条job_context + execute_single + finish
cmd_run_pick(N, ...) # 批量job_context + for-loop execute_single + emit(progress) + finish
cmd_stats() # 只读 syncJSON stdout无 job_context
```
要点:
1. **`job_context` 只包编排层**`cmd_run` / `cmd_run_pick`),不包 `execute_single_*` / domain service。
2. 批量 **顺序、不并发**;数量由参数 `pickCount` / `--pick N` 传入。
3. pick 循环内:`checkpoint()` + `emit("正在处理 {i}/{total}", progress={...})`
4. 结束:全成功 `finish(success)`;部分失败 `finish(partial)`;全失败 `finish(failed)`
5. 同一浏览器 Profile / account lease**禁止并发**。
6. 兼容旧命令(例如旧 export 需先刷新)必须调用同一 sync / domain 内核,禁止重写采集逻辑。
详见 [`LOGGING.md`](LOGGING.md) §2.5 与 `scripts/service/task_service.py` 示范。可复用契约样例见 `tests/samples/test_action_core_contract.py.sample``tests/samples/test_sync_contract.py.sample`
---
## 6. 队列 + pick可选Type B 批量)
有「待处理列表」的技能建议:
| 能力 | 约定 |
|------|------|
| 队列表 | `status`: `pending``processing``success` / `failed` |
| 入库 | 数据管理 CRUD`import-*`(相对 `{skill_data}/imports/`,见 [`DATA_PATHS.md`](DATA_PATHS.md) |
| 消费 | `run --pick N`,默认仅 `pending` |
| 重试 | `reset` 或数据管理改 `pending`**failed 不要自动重试** |
| 批次 | 可选 `batch_id`,便于筛选与任务中心对照 |
| Manifest | `*-run-pick`:建议 `async``placements` 按需含 `toolbar` / `cron` / `agent`;有 toolbar 则 `bind.tables` 必填 |
批量有两种合理形态(都是**顺序**
| 形态 | 任务中心条数 | 适用 |
|------|-------------|------|
| 一次 `run-pick` 处理 N 条 | **1** 条 Job | 同类 RPA、同 Profile、定时消费队列 |
| Agent/UI 触发 N 次单条 `run` | **N** 条 Job | 每条独立追踪 / 独立重试 |
默认优先 **一次 pick、一条 Job**
---
## 7. 业务同步与系统导出
| 能力 | 方向 | 负责方 |
|------|------|--------|
| 同步 / refresh / collect | 外部来源 → 技能本地 SQLite | 技能 domain service |
| 导出当前数据表 | 本地库 → CSV/Excel | **宿主**数据管理统一导出 |
| 特殊业务报告 | 多表合并 / 特殊格式 / 附加计算 | 仅系统导出不足时提供 `export-*` |
同步 Action 默认写库、不写导出文件。通用幂等 / 事务 / 空结果保护见 [`../references/SCHEMA.md`](../references/SCHEMA.md)。
---
## 8. Agent / SKILL.md 契约(复制后必改)
业务技能 `SKILL.md` / `references/` 应明确Agent 主读,勿只写在本文):
1. 短查询:共享 PythonPATH 上的 `python`)跑 CLI**禁止** `uv run`
2. 长任务 / RPA / async Action必须通过宿主 **Skill Action**`run_skill_action`**禁止** `exec` + `process poll`
3. 单条 vs 批量 action id 与参数(如 `url` / `pickCount`)。
4. `executionProfile: async` → 进度看**任务中心** / Skill Run Card`sync` → 当场结果。与入口无关。
5. 多入口复用同一业务内核。
模板源仓库的 `SKILL.md` / `references/ACTIONS.md` 含占位段落scaffold 后按业务改写。
---
## 9. Policy
自动检测索引见 [`POLICY_MATRIX.md`](POLICY_MATRIX.md)
- **POLICY-SKILL-ACTION-001**Runtime 文档存在schema 含 `executionProfile`;有 RPA 的业务技能须声明 async agent action。
- **POLICY-SKILL-ACTION-002**:每个 Action 显式声明 `executionProfile`sync/async
- **POLICY-SKILL-ACTION-003**toolbar Action 必须声明合法 `bind.tables`
- **POLICY-SKILL-ACTION-004**placements 与 executionProfile 正交(文档/测试不得写死耦合)。
- **POLICY-ARCH-CORE-001** / **POLICY-DATA-SYNC-001**:见矩阵;完整语义多用 sample / code review。
---
## 10. 与宿主 API参考
| API | 用途 |
|-----|------|
| `GET /api/skill-actions/{skillSlug}` | 读 manifest |
| `POST /api/skill-actions/run` | 执行 actionsync inline / async job |
| `GET /api/skill-actions/jobs` | 任务中心列表 |
| `GET /api/skill-actions/jobs/{jobId}` | 单 Job 详情 / 事件 |
Agent 工具(插件):`list_skill_actions``get_skill_action``run_skill_action`;正常对话**不要**轮询 `get_skill_action_job`(交给 UI / 任务中心)。
表级 `bind.tables` 过滤依赖宿主支持旧宿主忽略绑定时toolbar Action 可能在技能全部数据表显示——新技能仍须显式绑定,待宿主升级后完整按表过滤生效。

View File

@@ -22,8 +22,8 @@
必跑套件要像一个紧张的守门员:**快、确定、离线**。典型覆盖: 必跑套件要像一个紧张的守门员:**快、确定、离线**。典型覆盖:
- CLI导入 [`cli.app`](../scripts/cli/app.py) 走解析链路、`health`runtime diagnostics/ `version` / `logs` / `log-get` 冒烟; - CLI导入 [`cli.app`](../scripts/cli/app.py) 走解析链路、`health`runtime diagnostics/ `version` / `init-db` / `logs` / `log-get` 冒烟;
- 架构守护:无 `scripts/jiangchang_skill_core/``platform-kit>=1.0.17` 导入来源、文档/runtime 标准(见 `test_platform_import.py` 等); - 架构守护:无 `scripts/jiangchang_skill_core/``platform-kit>=1.2.0` 导入来源、文档/runtime 标准(见 `test_platform_import.py` 等);
- **真实 subprocess**[`tests/test_entrypoint_subprocess.py`](../tests/test_entrypoint_subprocess.py) 再调用一遍 `python scripts/main.py`,防路径漂移; - **真实 subprocess**[`tests/test_entrypoint_subprocess.py`](../tests/test_entrypoint_subprocess.py) 再调用一遍 `python scripts/main.py`,防路径漂移;
- 运行时:`runtime_paths`**`JIANGCHANG_*` 隔离** - 运行时:`runtime_paths`**`JIANGCHANG_*` 隔离**
- `SKILL.md` YAML slug vs [`constants.SKILL_SLUG`](../scripts/util/constants.py) - `SKILL.md` YAML slug vs [`constants.SKILL_SLUG`](../scripts/util/constants.py)
@@ -137,7 +137,8 @@ Golden fixture 流程同理([`tests/samples/test_golden_cases.py.sample`](../t
浏览器 RPA 走 `simulator_rpa` 档位联调前,逐项确认: 浏览器 RPA 走 `simulator_rpa` 档位联调前,逐项确认:
- [ ] 数据目录 `.env``OPENCLAW_TEST_TARGET=simulator_rpa`(非 `mock` / `unit` - [ ] 数据目录 `.env``OPENCLAW_TEST_TARGET=simulator_rpa`(非 `mock` / `unit`
- [ ] account-manager`platform ensure` + 账号 `active` + 有 `profile_dir` - [ ] account-manager`ensure-web`(或 `pick-web --ensure`+ 账号`profile_dir`(无 profile 禁止开浏览器,见 `RPA.md` §0.2
- [ ] `OPENCLAW_BROWSER_HEADLESS=0`(联调有头;勿默认无头)
- [ ] 目标 sandbox UI 已部署(跨团队;本地可用 `sandbox/demo_app.html` - [ ] 目标 sandbox UI 已部署(跨团队;本地可用 `sandbox/demo_app.html`
- [ ] 失败先查 `rpa-artifacts/` 截图,再查 Chrome profile 缓存(`--user-data-dir` 手工打开清站点数据) - [ ] 失败先查 `rpa-artifacts/` 截图,再查 Chrome profile 缓存(`--user-data-dir` 手工打开清站点数据)
- [ ] 默认 `python tests/run_tests.py -v` 仍全部通过mock 离线example 内 `pytest` 不启真实浏览器 - [ ] 默认 `python tests/run_tests.py -v` 仍全部通过mock 离线example 内 `pytest` 不启真实浏览器
@@ -153,6 +154,7 @@ Golden fixture 流程同理([`tests/samples/test_golden_cases.py.sample`](../t
- [ ] `python tests/run_tests.py -v` 能通过。 - [ ] `python tests/run_tests.py -v` 能通过。
- [ ] `python scripts/main.py health` 能通过。 - [ ] `python scripts/main.py health` 能通过。
- [ ] `python scripts/main.py version` 输出 JSON`skill` 与目录名 / `SKILL.md` / `constants.SKILL_SLUG` 一致。 - [ ] `python scripts/main.py version` 输出 JSON`skill` 与目录名 / `SKILL.md` / `constants.SKILL_SLUG` 一致。
- [ ] `python scripts/main.py init-db` 幂等创建本地库并输出 JSON`ok` / `skill` / `db_path`)。
- [ ] 所有 DB / 文件写入都在 `IsolatedDataRoot`(或等价隔离)下测试,不写真实数据目录。 - [ ] 所有 DB / 文件写入都在 `IsolatedDataRoot`(或等价隔离)下测试,不写真实数据目录。
- [ ] 外部系统默认使用 mock / `FakeAdapter`,不访问真实 API不打开真实 RPA。 - [ ] 外部系统默认使用 mock / `FakeAdapter`,不访问真实 API不打开真实 RPA。
- [ ] 至少有 1 个成功路径测试。 - [ ] 至少有 1 个成功路径测试。
@@ -236,10 +238,11 @@ Golden fixture 流程同理([`tests/samples/test_golden_cases.py.sample`](../t
## 12. RPA / video 测试标准 ## 12. RPA / video 测试标准
- `RpaVideoSession` 调用**不跑真实 ffmpeg**:单测中使用 `unittest.mock` patch session 或设 `OPENCLAW_RECORD_VIDEO=0` - 模板 `.env.example` 默认 **`OPENCLAW_RECORD_VIDEO=0`**;默认必跑测试**不应启动真实 ffmpeg**patch session 或显式`OPENCLAW_RECORD_VIDEO=0`
- **但测试必须守护录屏接入能力**`POLICY-RPA-003` 扫描 `scripts/service/*.py``RpaVideoSession` 被构造、`video.add_step` 被调用、video artifact 结构 merge 进 `result_summary``video` / `video_path` 等字段),与默认是否录屏无关。
- 断言 `title` / `closing_title` 是**中文**业务文案。 - 断言 `title` / `closing_title` 是**中文**业务文案。
- 断言 video artifact 会进入 `result_summary``video_path``raw_video``video_log` 等)。
- 断言 step 文案贴近用户动作不是技术日志如「准备执行示例任务」而非「enter cmd_run」 - 断言 step 文案贴近用户动作不是技术日志如「准备执行示例任务」而非「enter cmd_run」
- 若需测试**真实录屏**ffmpeg 成片),必须显式设 `OPENCLAW_RECORD_VIDEO=1`,并放在 `tests/integration/` 或手动触发场景,**不得**进入默认 unittest 套件。
参考 `tests/test_video_service.py` 参考 `tests/test_video_service.py`
@@ -259,7 +262,7 @@ Golden fixture 流程同理([`tests/samples/test_golden_cases.py.sample`](../t
- [ ] `requirements.txt` **不含** `jiangchang-platform-kit` / `playwright` - [ ] `requirements.txt` **不含** `jiangchang-platform-kit` / `playwright`
- [ ]`scripts/jiangchang_skill_core/` vendored 副本 - [ ]`scripts/jiangchang_skill_core/` vendored 副本
- [ ] `platform_kit_min_version` **>= 1.0.17**`SKILL.md` + `constants.py` - [ ] `platform_kit_min_version` **>= 1.2.2**`SKILL.md` + `constants.py`
- [ ] `health` 能输出 `platform_kit_version_ok`(或等价诊断行) - [ ] `health` 能输出 `platform_kit_version_ok`(或等价诊断行)
- [ ] `config-path` 可输出用户 `.env` 路径 JSON - [ ] `config-path` 可输出用户 `.env` 路径 JSON
- [ ] `pytest.ini` 存在且 `python_files` 只收集 `test_*.py` / `*_test.py` - [ ] `pytest.ini` 存在且 `python_files` 只收集 `test_*.py` / `*_test.py`

View File

@@ -39,7 +39,7 @@ real_browser_rpa/
## 核心流程 ## 核心流程
1. **pick account** — 通过 `account_client.pick_web_account()` 获取 `profile_dir` 与租约 1. **ensure account** — 通过 `account_client.pick_web_account()`(底层 `ensure-web`获取 `profile_dir` 与租约;无账号则自动登记,全忙则 `LEASE_CONFLICT` 不重复建号。登记 ≠ 站点已登录。
2. **启动浏览器**`launch_persistent_context` + `new_page()` + `page.goto(start_url)` 2. **启动浏览器**`launch_persistent_context` + `new_page()` + `page.goto(start_url)`
3. **人工验证(启动后)** — 检测滑块/短信,等待用户完成 3. **人工验证(启动后)** — 检测滑块/短信,等待用户完成
4. **等待登录** — 检测登录按钮消失 / 登录态 marker 出现 4. **等待登录** — 检测登录按钮消失 / 登录态 marker 出现
@@ -79,6 +79,10 @@ real_browser_rpa/
**浏览器与启动约束:** **浏览器与启动约束:**
- **先 Profile 再开浏览器**:必须 `pick_web_account`(底层 ensure-web拿到 `profile_dir`;拿不到则失败退出,禁止落到系统默认用户目录(见模板 `development/RPA.md` §0.2
- **RPA 等待**:主路径用 `interruptible_sleep`,禁止裸 `asyncio.sleep``POLICY-CONTROL-003`
- **有头**:生产 / 联调 `OPENCLAW_BROWSER_HEADLESS=0`;勿把无头当交付常态
- **登录按平台**:是否要求站点登录由本技能约定;「可不登录」≠「可不接 account-manager」
- **不要**在技能内安装 Playwright浏览器与 Python 包由宿主/runtime 提供 - **不要**在技能内安装 Playwright浏览器与 Python 包由宿主/runtime 提供
- `launch_persistent_context``args` **只放 Chrome 参数****不要把 URL 放进 `args`** - `launch_persistent_context``args` **只放 Chrome 参数****不要把 URL 放进 `args`**
- 页面必须通过 `new_page()` + `goto()`,或通过真实地址栏/点击进入 - 页面必须通过 `new_page()` + `goto()`,或通过真实地址栏/点击进入
@@ -139,7 +143,7 @@ real_browser_rpa/
- **不 import account-manager 内部模块** — 只通过 CLI/subprocess 调用 - **不 import account-manager 内部模块** — 只通过 CLI/subprocess 调用
- **不自动破解验证码** — 滑块/短信只检测 + 等待人工完成 - **不自动破解验证码** — 滑块/短信只检测 + 等待人工完成
- **日志脱敏** — 不输出完整手机号/账号 - **日志脱敏** — 不输出完整手机号/账号
- **租约释放** — `pick-web --lease` 后必须在 `finally` 释放 - **租约释放** — `ensure-web` / `pick-web --lease` 后必须在 `finally` 释放
- **失败留痕** — 真实 skill 应在关键失败点截图(示例中已留注释位) - **失败留痕** — 真实 skill 应在关键失败点截图(示例中已留注释位)
## 常见坑 ## 常见坑

View File

@@ -1,4 +1,7 @@
"""account-manager CLI 集成(仅 subprocess不 import 兄弟 skill 内部模块)。""" """account-manager CLI 集成(仅 subprocess不 import 兄弟 skill 内部模块)。
业务首启默认 ``ensure-web``(有则用、无则 add-web登记 ≠ 站点已登录。
"""
from __future__ import annotations from __future__ import annotations
@@ -7,8 +10,9 @@ import logging
import os import os
import subprocess import subprocess
import sys import sys
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Optional, Tuple
from jiangchang_skill_core import config
from jiangchang_skill_core.runtime_env import get_sibling_skills_root from jiangchang_skill_core.runtime_env import get_sibling_skills_root
from util.constants import LEASE_HOLDER, LEASE_TTL_SEC, TARGET_PLATFORM from util.constants import LEASE_HOLDER, LEASE_TTL_SEC, TARGET_PLATFORM
@@ -19,12 +23,17 @@ logger = logging.getLogger(__name__)
PLACEHOLDER_PLATFORM = TARGET_PLATFORM PLACEHOLDER_PLATFORM = TARGET_PLATFORM
ACCOUNT_SETUP_MESSAGE = ( ACCOUNT_SETUP_MESSAGE = (
f"找到可用的 {PLACEHOLDER_PLATFORM} 账号,所以还没有打开浏览器。" f"能取得可用的 {PLACEHOLDER_PLATFORM} 账号ensure-web 失败),所以还没有打开浏览器。"
f"先在 account-manager 中添加 platform={PLACEHOLDER_PLATFORM}" f"确认已安装 account-manager,并检查 platform={PLACEHOLDER_PLATFORM} 账号状态后重试。"
"status=active、带 profile_dir 的账号后重新运行。"
) )
LEASE_BUSY_MESSAGE = "目标平台账号当前被其他任务占用,请等待释放租约后重试。" LEASE_BUSY_MESSAGE = (
"该平台下已有账号,但均被其他任务占用。请稍后重试或释放租约;不会自动新建账号。"
)
DEFAULT_AUTH_STRATEGY = "qr_code_manual"
DEFAULT_ACCOUNT_LABEL = f"{PLACEHOLDER_PLATFORM} 默认"
DEFAULT_START_URL = "https://www.example.com/"
class AccountManagerError(Exception): class AccountManagerError(Exception):
@@ -38,13 +47,65 @@ def mask_login_id(login_id: str) -> str:
return mask_text(login_id) return mask_text(login_id)
def format_account_label(account: dict) -> str:
"""人读账号标识:优先 login_id / 备注,最后才用数字 id。"""
for key in ("login_id", "account_label", "label"):
v = account.get(key)
if v is not None and str(v).strip():
return str(v).strip()
for key in ("id", "account_id"):
v = account.get(key)
if v is not None and str(v).strip():
return str(v).strip()
return ""
def _is_placeholder_config(raw: str) -> bool:
s = (raw or "").strip()
if not s:
return True
if s.startswith("#"):
return True
low = s.lower()
if low in ("default-account", "none", "null", "n/a", "-"):
return True
return False
def resolve_account_selectors_from_config() -> Tuple[Optional[str], Optional[str]]:
"""从配置解析 (account_id, login_id)。
- ``DEFAULT_ACCOUNT_ID``:仅纯数字视为账号主键;其它非空非占位当作 login_id
- ``DEFAULT_LOGIN_ID``:手机号/用户名(可覆盖上一项推导的 login_id
- 两者皆空:返回 (None, None) → 调用方走按平台 ensure-web
"""
account_id: Optional[str] = None
login_id: Optional[str] = None
aid_raw = (config.get("DEFAULT_ACCOUNT_ID") or "").strip()
if not _is_placeholder_config(aid_raw):
if aid_raw.isdigit():
account_id = aid_raw
else:
login_id = aid_raw
logger.info("default_account_id_treated_as_login_id value=%s", aid_raw)
lid_raw = (config.get("DEFAULT_LOGIN_ID") or "").strip()
if not _is_placeholder_config(lid_raw):
login_id = lid_raw
if account_id:
return account_id, None
return None, login_id
def _resolve_account_manager_main() -> str: def _resolve_account_manager_main() -> str:
"""解析 account-manager CLI 入口路径。 """解析 account-manager CLI 入口路径。
优先级ACCOUNT_MANAGER_ROOT → get_sibling_skills_root(路径推断 / JIANGCHANG_SKILLS_ROOT→ 开发机兜底。 优先级ACCOUNT_MANAGER_ROOT → get_sibling_skills_root → 开发机兜底。
末尾 dev 路径仅用于模板/本机调试,复制到真实 skill 后不要依赖个人机器绝对路径。 末尾 dev 路径仅用于模板/本机调试,复制到真实 skill 后不要依赖个人机器绝对路径。
""" """
env_root = (os.getenv("ACCOUNT_MANAGER_ROOT") or "").strip() env_root = (config.get("ACCOUNT_MANAGER_ROOT") or os.getenv("ACCOUNT_MANAGER_ROOT") or "").strip()
if env_root and os.path.isfile(os.path.join(env_root, "scripts", "main.py")): if env_root and os.path.isfile(os.path.join(env_root, "scripts", "main.py")):
return os.path.join(os.path.abspath(env_root), "scripts", "main.py") return os.path.join(os.path.abspath(env_root), "scripts", "main.py")
@@ -103,44 +164,66 @@ def _validate_pick_payload(payload: dict[str, Any]) -> dict[str, Any]:
code = _normalize_error_code(str(err.get("code") or "")) code = _normalize_error_code(str(err.get("code") or ""))
message = str(err.get("message") or "") message = str(err.get("message") or "")
if code == "LEASE_CONFLICT" or "LEASE_CONFLICT" in code: if code == "LEASE_CONFLICT" or "LEASE_CONFLICT" in code:
raise AccountManagerError("LEASE_CONFLICT", LEASE_BUSY_MESSAGE) raise AccountManagerError("LEASE_CONFLICT", message or LEASE_BUSY_MESSAGE)
if code == "AMBIGUOUS_ACCOUNT" or "AMBIGUOUS_ACCOUNT" in code:
raise AccountManagerError(
"AMBIGUOUS_ACCOUNT",
message or "匹配到多条账号,请改用数字 id 或更精确的登录标识。",
)
if code in ("NO_ACCOUNT", "ACCOUNT_NOT_FOUND") or "NO_ACCOUNT" in code: if code in ("NO_ACCOUNT", "ACCOUNT_NOT_FOUND") or "NO_ACCOUNT" in code:
raise AccountManagerError("NO_ACCOUNT", message or "没有可用账号。") raise AccountManagerError("NO_ACCOUNT", message or "没有可用账号。")
raise AccountManagerError(code or "PICK_WEB_FAILED", message or "pick-web 失败。") raise AccountManagerError(code or "ENSURE_WEB_FAILED", message or "ensure-web 失败。")
if not isinstance(payload, dict): if not isinstance(payload, dict):
raise AccountManagerError("ACCOUNT_NOT_FOUND", "pick-web 返回格式异常。") raise AccountManagerError("ACCOUNT_NOT_FOUND", "ensure-web 返回格式异常。")
if not payload.get("profile_dir"): if not payload.get("profile_dir"):
raise AccountManagerError("ACCOUNT_NOT_FOUND", "pick-web 返回的账号缺少 profile_dir。") raise AccountManagerError("ACCOUNT_NOT_FOUND", "ensure-web 返回的账号缺少 profile_dir。")
return payload return payload
def _pick_web_with_lease(platform: str) -> Dict[str, Any]: def _ensure_web_with_lease(
proc = _run_argv( platform: str,
[ *,
"account", login_id: Optional[str] = None,
"pick-web", ) -> Dict[str, Any]:
"--platform", start_url = (config.get("TARGET_BASE_URL") or DEFAULT_START_URL).strip() or DEFAULT_START_URL
platform, lid = (login_id or "").strip() or None
"--lease", label = f"{platform} {lid}" if lid else DEFAULT_ACCOUNT_LABEL
"--holder", argv = [
LEASE_HOLDER, "account",
"--ttl-sec", "ensure-web",
LEASE_TTL_SEC, "--platform",
] platform,
) "--url",
start_url,
"--auth-strategy",
DEFAULT_AUTH_STRATEGY,
"--label",
label,
"--lease",
"--holder",
LEASE_HOLDER,
"--ttl-sec",
LEASE_TTL_SEC,
"--purpose",
"rpa",
]
if lid:
argv.extend(["--login-id", lid])
proc = _run_argv(argv)
out = proc.stdout or "" out = proc.stdout or ""
if proc.returncode != 0 and not out.strip(): if proc.returncode != 0 and not out.strip():
raise AccountManagerError( raise AccountManagerError(
"PICK_WEB_FAILED", "ENSURE_WEB_FAILED",
(proc.stderr or "").strip() or "pick-web 子进程失败", (proc.stderr or "").strip() or "ensure-web 子进程失败",
) )
payload = _parse_last_json(out) payload = _parse_last_json(out)
if isinstance(payload, dict) and payload.get("success") is False: if isinstance(payload, dict) and payload.get("success") is False:
return _validate_pick_payload(payload) return _validate_pick_payload(payload)
if not isinstance(payload, dict): if not isinstance(payload, dict):
raise AccountManagerError("ACCOUNT_NOT_FOUND", "pick-web 返回格式异常。") raise AccountManagerError("ACCOUNT_NOT_FOUND", "ensure-web 返回格式异常。")
return payload return _validate_pick_payload(payload)
def _pick_by_id(platform: str, account_id: int) -> Dict[str, Any]: def _pick_by_id(platform: str, account_id: int) -> Dict[str, Any]:
@@ -170,19 +253,32 @@ def _pick_by_id(platform: str, account_id: int) -> Dict[str, Any]:
return data return data
def pick_web_account(platform: str, account_id: Optional[str] = None) -> dict: def pick_web_account(
"""获取网页账号profile_dir + lease_token""" platform: str,
account_id: Optional[str] = None,
login_id: Optional[str] = None,
) -> dict:
"""获取网页账号profile_dir + lease_token
优先级:数字 account_id → login_idensure-web --login-id→ 按平台 ensure-web。
"""
platform_key = (platform or PLACEHOLDER_PLATFORM).strip() or PLACEHOLDER_PLATFORM platform_key = (platform or PLACEHOLDER_PLATFORM).strip() or PLACEHOLDER_PLATFORM
if account_id: aid_raw = (account_id or "").strip()
try: if aid_raw and not _is_placeholder_config(aid_raw):
aid = int(account_id) if not aid_raw.isdigit():
except (TypeError, ValueError): if not (login_id or "").strip():
raise AccountManagerError("ACCOUNT_NOT_FOUND", f"账号 ID 无效:{account_id}") login_id = aid_raw
return _pick_by_id(platform_key, aid) aid_raw = ""
else:
return _pick_by_id(platform_key, int(aid_raw))
lid = (login_id or "").strip() or None
if lid and _is_placeholder_config(lid):
lid = None
try: try:
return _pick_web_with_lease(platform_key) return _ensure_web_with_lease(platform_key, login_id=lid)
except AccountManagerError as exc: except AccountManagerError as exc:
if exc.code in ("NO_ACCOUNT", "ACCOUNT_NOT_FOUND") or "NO_ACCOUNT" in exc.code: if exc.code in ("NO_ACCOUNT", "ACCOUNT_NOT_FOUND") or "NO_ACCOUNT" in exc.code:
raise AccountManagerError("ACCOUNT_SETUP_REQUIRED", ACCOUNT_SETUP_MESSAGE) from exc raise AccountManagerError("ACCOUNT_SETUP_REQUIRED", ACCOUNT_SETUP_MESSAGE) from exc

View File

@@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import logging import logging
import os import os
import random import random
@@ -11,6 +10,8 @@ import time
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple from typing import Any, Callable, Dict, List, Optional, Tuple
from jiangchang_skill_core.activity import interruptible_sleep
from service.browser_session import close_browser_context, get_start_url, start_browser_session from service.browser_session import close_browser_context, get_start_url, start_browser_session
from service.human_verification import ( from service.human_verification import (
HumanVerificationWaitResult, HumanVerificationWaitResult,
@@ -102,11 +103,11 @@ def _step_cb(cb: Optional[StepCallback], text: str) -> None:
async def _random_delay() -> None: async def _random_delay() -> None:
lo = int(os.getenv("RPA_STEP_DELAY_MIN_MS") or "900") lo = int(os.getenv("RPA_STEP_DELAY_MIN_MS") or "900")
hi = int(os.getenv("RPA_STEP_DELAY_MAX_MS") or "2600") hi = int(os.getenv("RPA_STEP_DELAY_MAX_MS") or "2600")
await asyncio.sleep(random.uniform(lo / 1000.0, hi / 1000.0)) await interruptible_sleep(random.uniform(lo / 1000.0, hi / 1000.0))
async def _scroll_wait() -> None: async def _scroll_wait() -> None:
await asyncio.sleep(random.uniform(1.2, 3.5)) await interruptible_sleep(random.uniform(1.2, 3.5))
def _headless() -> bool: def _headless() -> bool:
@@ -156,7 +157,7 @@ async def _open_login_panel_if_needed(page) -> None:
btn = page.locator(LOGGED_OUT_SELECTOR).first btn = page.locator(LOGGED_OUT_SELECTOR).first
if await _visible(btn): if await _visible(btn):
await btn.click() await btn.click()
await asyncio.sleep(random.uniform(1.0, 3.0)) await interruptible_sleep(random.uniform(1.0, 3.0))
except Exception: except Exception:
pass pass
@@ -175,7 +176,7 @@ async def _ensure_logged_in(page, *, wait_sec: int) -> None:
if await _is_logged_in(page): if await _is_logged_in(page):
print("[登录] 检测到登录成功") print("[登录] 检测到登录成功")
return return
await asyncio.sleep(2.0) await interruptible_sleep(2.0)
raise RuntimeError( raise RuntimeError(
f"ERROR:LOGIN_TIMEOUT 浏览器已打开,但未完成登录。" f"ERROR:LOGIN_TIMEOUT 浏览器已打开,但未完成登录。"
@@ -253,7 +254,7 @@ async def _wait_search_results(page, timeout_sec: float = 45.0) -> bool:
return True return True
except Exception: except Exception:
pass pass
await asyncio.sleep(0.8) await interruptible_sleep(0.8)
return False return False

View File

@@ -6,7 +6,12 @@ import asyncio
import uuid import uuid
from typing import Any, Optional from typing import Any, Optional
from service.account_client import AccountManagerError, pick_web_account, release_lease from service.account_client import (
AccountManagerError,
pick_web_account,
release_lease,
resolve_account_selectors_from_config,
)
from service.task_rpa import ( from service.task_rpa import (
ScrapeRunResult, ScrapeRunResult,
format_stop_reason_for_user, format_stop_reason_for_user,
@@ -79,7 +84,12 @@ async def run_keyword_search_task(
account: Optional[dict[str, Any]] = None account: Optional[dict[str, Any]] = None
try: try:
account = pick_web_account(platform, account_id) cfg_account_id, cfg_login_id = resolve_account_selectors_from_config()
account = pick_web_account(
platform,
account_id=account_id or cfg_account_id,
login_id=cfg_login_id,
)
lease_token = account.get("lease_token") lease_token = account.get("lease_token")
scrape_result: ScrapeRunResult = await run_keyword_search_async( scrape_result: ScrapeRunResult = await run_keyword_search_async(

View File

@@ -50,13 +50,19 @@ simulator_browser_rpa/
| 文件 | 职责 | | 文件 | 职责 |
|---|---| |---|---|
| `browser_session.py` | async 系统 Chrome/Edge + launch args**不在此 goto** | | `browser_session.py` | async 系统 Chrome/Edge + launch args**不在此 goto** |
| `account_client.py` | **唯一** account-manager subprocess 封装(`pick_web_account` / `release_lease` | | `account_client.py` | **唯一** account-manager subprocess 封装(`pick_web_account`→ensure-web / `release_lease` |
| `simulator_playwright.py` | 门户轮询、登录、批量表单、PIN、解析 `batch_id`、截图 | | `simulator_playwright.py` | 门户轮询、登录、批量表单、PIN、解析 `batch_id`、截图 |
| `adapter/simulator_rpa.py` | **薄** adapterpick 账号、lease、委托 RPA、`finally release_lease` | | `adapter/simulator_rpa.py` | **薄** adapterpick 账号、lease、委托 RPA、`finally release_lease` |
| `adapter/mock.py` | 不启浏览器,供 unit/mock/CI | | `adapter/mock.py` | 不启浏览器,供 unit/mock/CI |
| `task_service.py` | async 校验输入 → 选 adapter → `await submit_batch` | | `task_service.py` | async 校验输入 → 选 adapter → `await submit_batch` |
| `sandbox/demo_app.html` | 可控 DOM含可选门户门闩 + 原批量提交流程 | | `sandbox/demo_app.html` | 可控 DOM含可选门户门闩 + 原批量提交流程 |
## 网页 RPA 硬规则(与模板 `development/RPA.md` §0.2 一致)
- **先 Profile 再开浏览器**`simulator_rpa` 档必须 `pick_web_account`ensure-web拿到 `profile_dir`;拿不到则失败,禁止系统默认用户目录
- **有头**:联调 / 交付默认 `OPENCLAW_BROWSER_HEADLESS=0`
- **登录按平台约定**:本示例需要仿真登录;其他技能可为 optional / not_needed但**仍须**走 account-manager
## 核心流程 ## 核心流程
1. `await run_batch_submit(target, items)` 校验参数 1. `await run_batch_submit(target, items)` 校验参数

View File

@@ -1,4 +1,7 @@
"""account-manager CLI 集成(仅 subprocess不 import 兄弟 skill 内部模块)。""" """account-manager CLI 集成(仅 subprocess不 import 兄弟 skill 内部模块)。
业务首启默认 ``ensure-web``(有则用、无则 add-web登记 ≠ 站点已登录。
"""
from __future__ import annotations from __future__ import annotations
@@ -7,8 +10,9 @@ import logging
import os import os
import subprocess import subprocess
import sys import sys
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Optional, Tuple
from jiangchang_skill_core import config
from jiangchang_skill_core.runtime_env import get_sibling_skills_root from jiangchang_skill_core.runtime_env import get_sibling_skills_root
from util.constants import LEASE_HOLDER, LEASE_TTL_SEC, TARGET_PLATFORM from util.constants import LEASE_HOLDER, LEASE_TTL_SEC, TARGET_PLATFORM
@@ -19,12 +23,17 @@ logger = logging.getLogger(__name__)
PLACEHOLDER_PLATFORM = TARGET_PLATFORM PLACEHOLDER_PLATFORM = TARGET_PLATFORM
ACCOUNT_SETUP_MESSAGE = ( ACCOUNT_SETUP_MESSAGE = (
f"找到可用的 {PLACEHOLDER_PLATFORM} 账号,所以还没有打开浏览器。" f"能取得可用的 {PLACEHOLDER_PLATFORM} 账号ensure-web 失败),所以还没有打开浏览器。"
f"先在 account-manager 中添加 platform={PLACEHOLDER_PLATFORM}" f"确认已安装 account-manager,并检查 platform={PLACEHOLDER_PLATFORM} 账号状态后重试。"
"status=active、带 profile_dir 的账号后重新运行。"
) )
LEASE_BUSY_MESSAGE = "目标平台账号当前被其他任务占用,请等待释放租约后重试。" LEASE_BUSY_MESSAGE = (
"该平台下已有账号,但均被其他任务占用。请稍后重试或释放租约;不会自动新建账号。"
)
DEFAULT_AUTH_STRATEGY = "qr_code_manual"
DEFAULT_ACCOUNT_LABEL = f"{PLACEHOLDER_PLATFORM} 默认"
DEFAULT_START_URL = "https://www.example.com/"
class AccountManagerError(Exception): class AccountManagerError(Exception):
@@ -38,12 +47,65 @@ def mask_login_id(login_id: str) -> str:
return mask_text(login_id) return mask_text(login_id)
def format_account_label(account: dict) -> str:
"""人读账号标识:优先 login_id / 备注,最后才用数字 id。"""
for key in ("login_id", "account_label", "label"):
v = account.get(key)
if v is not None and str(v).strip():
return str(v).strip()
for key in ("id", "account_id"):
v = account.get(key)
if v is not None and str(v).strip():
return str(v).strip()
return ""
def _is_placeholder_config(raw: str) -> bool:
s = (raw or "").strip()
if not s:
return True
if s.startswith("#"):
return True
low = s.lower()
if low in ("default-account", "none", "null", "n/a", "-"):
return True
return False
def resolve_account_selectors_from_config() -> Tuple[Optional[str], Optional[str]]:
"""从配置解析 (account_id, login_id)。
- ``DEFAULT_ACCOUNT_ID``:仅纯数字视为账号主键;其它非空非占位当作 login_id
- ``DEFAULT_LOGIN_ID``:手机号/用户名(可覆盖上一项推导的 login_id
- 两者皆空:返回 (None, None) → 调用方走按平台 ensure-web
"""
account_id: Optional[str] = None
login_id: Optional[str] = None
aid_raw = (config.get("DEFAULT_ACCOUNT_ID") or "").strip()
if not _is_placeholder_config(aid_raw):
if aid_raw.isdigit():
account_id = aid_raw
else:
login_id = aid_raw
logger.info("default_account_id_treated_as_login_id value=%s", aid_raw)
lid_raw = (config.get("DEFAULT_LOGIN_ID") or "").strip()
if not _is_placeholder_config(lid_raw):
login_id = lid_raw
if account_id:
return account_id, None
return None, login_id
def _resolve_account_manager_main() -> str: def _resolve_account_manager_main() -> str:
"""解析 account-manager CLI 入口路径。 """解析 account-manager CLI 入口路径。
优先级ACCOUNT_MANAGER_ROOT → get_sibling_skills_root → 开发机兜底。 优先级ACCOUNT_MANAGER_ROOT → get_sibling_skills_root → 开发机兜底。
末尾 dev 路径仅用于模板/本机调试,复制到真实 skill 后不要依赖个人机器绝对路径。
""" """
env_root = (os.getenv("ACCOUNT_MANAGER_ROOT") or "").strip() env_root = (config.get("ACCOUNT_MANAGER_ROOT") or os.getenv("ACCOUNT_MANAGER_ROOT") or "").strip()
if env_root and os.path.isfile(os.path.join(env_root, "scripts", "main.py")): if env_root and os.path.isfile(os.path.join(env_root, "scripts", "main.py")):
return os.path.join(os.path.abspath(env_root), "scripts", "main.py") return os.path.join(os.path.abspath(env_root), "scripts", "main.py")
@@ -53,6 +115,7 @@ def _resolve_account_manager_main() -> str:
if os.path.isfile(candidate): if os.path.isfile(candidate):
return candidate return candidate
# 开发环境兜底:仅模板/本机调试;生产依赖宿主注入的路径变量,勿硬编码个人目录
dev = r"D:\OpenClaw\client-commons\account-manager\scripts\main.py" dev = r"D:\OpenClaw\client-commons\account-manager\scripts\main.py"
if os.path.isfile(dev): if os.path.isfile(dev):
return dev return dev
@@ -101,44 +164,66 @@ def _validate_pick_payload(payload: dict[str, Any]) -> dict[str, Any]:
code = _normalize_error_code(str(err.get("code") or "")) code = _normalize_error_code(str(err.get("code") or ""))
message = str(err.get("message") or "") message = str(err.get("message") or "")
if code == "LEASE_CONFLICT" or "LEASE_CONFLICT" in code: if code == "LEASE_CONFLICT" or "LEASE_CONFLICT" in code:
raise AccountManagerError("LEASE_CONFLICT", LEASE_BUSY_MESSAGE) raise AccountManagerError("LEASE_CONFLICT", message or LEASE_BUSY_MESSAGE)
if code == "AMBIGUOUS_ACCOUNT" or "AMBIGUOUS_ACCOUNT" in code:
raise AccountManagerError(
"AMBIGUOUS_ACCOUNT",
message or "匹配到多条账号,请改用数字 id 或更精确的登录标识。",
)
if code in ("NO_ACCOUNT", "ACCOUNT_NOT_FOUND") or "NO_ACCOUNT" in code: if code in ("NO_ACCOUNT", "ACCOUNT_NOT_FOUND") or "NO_ACCOUNT" in code:
raise AccountManagerError("NO_ACCOUNT", message or "没有可用账号。") raise AccountManagerError("NO_ACCOUNT", message or "没有可用账号。")
raise AccountManagerError(code or "PICK_WEB_FAILED", message or "pick-web 失败。") raise AccountManagerError(code or "ENSURE_WEB_FAILED", message or "ensure-web 失败。")
if not isinstance(payload, dict): if not isinstance(payload, dict):
raise AccountManagerError("ACCOUNT_NOT_FOUND", "pick-web 返回格式异常。") raise AccountManagerError("ACCOUNT_NOT_FOUND", "ensure-web 返回格式异常。")
if not payload.get("profile_dir"): if not payload.get("profile_dir"):
raise AccountManagerError("ACCOUNT_NOT_FOUND", "pick-web 返回的账号缺少 profile_dir。") raise AccountManagerError("ACCOUNT_NOT_FOUND", "ensure-web 返回的账号缺少 profile_dir。")
return payload return payload
def _pick_web_with_lease(platform: str) -> Dict[str, Any]: def _ensure_web_with_lease(
proc = _run_argv( platform: str,
[ *,
"account", login_id: Optional[str] = None,
"pick-web", ) -> Dict[str, Any]:
"--platform", start_url = (config.get("TARGET_BASE_URL") or DEFAULT_START_URL).strip() or DEFAULT_START_URL
platform, lid = (login_id or "").strip() or None
"--lease", label = f"{platform} {lid}" if lid else DEFAULT_ACCOUNT_LABEL
"--holder", argv = [
LEASE_HOLDER, "account",
"--ttl-sec", "ensure-web",
LEASE_TTL_SEC, "--platform",
] platform,
) "--url",
start_url,
"--auth-strategy",
DEFAULT_AUTH_STRATEGY,
"--label",
label,
"--lease",
"--holder",
LEASE_HOLDER,
"--ttl-sec",
LEASE_TTL_SEC,
"--purpose",
"rpa",
]
if lid:
argv.extend(["--login-id", lid])
proc = _run_argv(argv)
out = proc.stdout or "" out = proc.stdout or ""
if proc.returncode != 0 and not out.strip(): if proc.returncode != 0 and not out.strip():
raise AccountManagerError( raise AccountManagerError(
"PICK_WEB_FAILED", "ENSURE_WEB_FAILED",
(proc.stderr or "").strip() or "pick-web 子进程失败", (proc.stderr or "").strip() or "ensure-web 子进程失败",
) )
payload = _parse_last_json(out) payload = _parse_last_json(out)
if isinstance(payload, dict) and payload.get("success") is False: if isinstance(payload, dict) and payload.get("success") is False:
return _validate_pick_payload(payload) return _validate_pick_payload(payload)
if not isinstance(payload, dict): if not isinstance(payload, dict):
raise AccountManagerError("ACCOUNT_NOT_FOUND", "pick-web 返回格式异常。") raise AccountManagerError("ACCOUNT_NOT_FOUND", "ensure-web 返回格式异常。")
return payload return _validate_pick_payload(payload)
def _pick_by_id(platform: str, account_id: int) -> Dict[str, Any]: def _pick_by_id(platform: str, account_id: int) -> Dict[str, Any]:
@@ -168,19 +253,32 @@ def _pick_by_id(platform: str, account_id: int) -> Dict[str, Any]:
return data return data
def pick_web_account(platform: str, account_id: Optional[str] = None) -> dict: def pick_web_account(
"""获取网页账号profile_dir + lease_token""" platform: str,
account_id: Optional[str] = None,
login_id: Optional[str] = None,
) -> dict:
"""获取网页账号profile_dir + lease_token
优先级:数字 account_id → login_idensure-web --login-id→ 按平台 ensure-web。
"""
platform_key = (platform or PLACEHOLDER_PLATFORM).strip() or PLACEHOLDER_PLATFORM platform_key = (platform or PLACEHOLDER_PLATFORM).strip() or PLACEHOLDER_PLATFORM
if account_id: aid_raw = (account_id or "").strip()
try: if aid_raw and not _is_placeholder_config(aid_raw):
aid = int(account_id) if not aid_raw.isdigit():
except (TypeError, ValueError): if not (login_id or "").strip():
raise AccountManagerError("ACCOUNT_NOT_FOUND", f"账号 ID 无效:{account_id}") login_id = aid_raw
return _pick_by_id(platform_key, aid) aid_raw = ""
else:
return _pick_by_id(platform_key, int(aid_raw))
lid = (login_id or "").strip() or None
if lid and _is_placeholder_config(lid):
lid = None
try: try:
return _pick_web_with_lease(platform_key) return _ensure_web_with_lease(platform_key, login_id=lid)
except AccountManagerError as exc: except AccountManagerError as exc:
if exc.code in ("NO_ACCOUNT", "ACCOUNT_NOT_FOUND") or "NO_ACCOUNT" in exc.code: if exc.code in ("NO_ACCOUNT", "ACCOUNT_NOT_FOUND") or "NO_ACCOUNT" in exc.code:
raise AccountManagerError("ACCOUNT_SETUP_REQUIRED", ACCOUNT_SETUP_MESSAGE) from exc raise AccountManagerError("ACCOUNT_SETUP_REQUIRED", ACCOUNT_SETUP_MESSAGE) from exc

View File

@@ -1,15 +1,46 @@
# Skill Action Manifest匠厂宿主 # Skill Action Manifest匠厂宿主
本文件说明 `assets/actions.json``scripts/main.py` CLI 的对应关系,供 Agent 编排与宿主 **Skill Action Runtime** 使用。 本文件说明 `assets/actions.json``scripts/main.py` CLI 的对应关系,供 **Agent 编排**与宿主 **Skill Action Runtime** 使用。这是 Agent 侧关于 Action / 任务中心的**主契约**;实现细节与开发规范见 [`../development/SKILL_ACTION_RUNTIME.md`](../development/SKILL_ACTION_RUNTIME.md)。
**边界:** 用户市场说明见根目录 [`README.md`](../README.md)CLI 参数与错误码细节见 [`CLI.md`](CLI.md)。 **边界:** 用户市场四 Tab 见根目录 [`README.md`](../README.md) / [`TUTORIAL.md`](../TUTORIAL.md) / [`DEMO.md`](../DEMO.md) / [`CHANGELOG.md`](../CHANGELOG.md)CLI 参数见 [`CLI.md`](CLI.md)。
## Agent 何时用 Action与 CLI 的分工)
| 场景 | 做法 |
|------|------|
| 短查询 / 只读 / 秒级 | bash + 共享 Python CLI见 [`CLI.md`](CLI.md)**不必**强行走 Action |
| 数据管理按钮 / 定时任务 / 技能详情按钮 | **必须**在 `actions.json` 声明对应 Action |
| 长耗时 / RPA / 需要进度与取消 | **必须** `run_skill_action`;对应 Action 一般为 `executionProfile: "async"` |
| 已声明的 `sync` Action | `run_skill_action` 当场返回结果,**不进**任务中心 |
| 已声明的 `async` Action | `run_skill_action` 立即返回 `jobId`**进入**任务中心 |
**进不进任务中心只取决于该 Action 的 `executionProfile`,与从数据管理、定时任务还是 Agent 触发无关。**
禁止对长任务 `exec`/`bash` + `process poll` 干等 CLI。禁止 `uv run python` 跑技能脚本。
## async 副作用 Action 最小组合(复制验收 checklist
对每个「会开浏览器 / 长耗时 / 需进度或取消」的 Action声明时建议同时满足
1. `executionProfile: "async"`(进入任务中心)
2. 若要让 Agent 触发:`placements` **含** `agent`
3. 有可感知副作用时:提供 `confirmation.message`
4. 需要用户/Agent 入参时:简单 `inputSchema` + entrypoint 中的 `{{fieldName}}`
5. `SKILL.md`「用户意图路由表」与 `CLI.md`「Action 强制黑名单」**出现同一 action id / 命令**
默认模板 `assets/actions.json` 仅含诊断类 sync Action**不要**为通过本 checklist 而塞假业务 Action业务技能按需添加。完整字段见下文 Phase 1。
## 可选:域前缀 CLI嵌套子命令
小技能可继续扁平:`entrypoint.command = "run"`
命令变多时,可采用**域前缀**`command` 为域(如 `<domain>`),业务动词与参数放在 `args` 数组(如 `["<verb>", "--flag", "{{field}}"]`)。与扁平入口等价,须仍指向同一 domain service。
## 模板严格规范 vs 宿主向后兼容 ## 模板严格规范 vs 宿主向后兼容
| 角色 | 定位 | | 角色 | 定位 |
|------|------| |------|------|
| **skill-template** | 新技能推荐的**严格规范**:必填字段、明确类型、`additionalProperties: false` | | **skill-template** | 新技能推荐的**严格规范**:必填字段、明确类型、`additionalProperties: false` |
| **宿主运行时** | **向后兼容**的历史 manifest 解析器:可能接受部分缺省字段(如 `description``placements``entrypoint.args`input property `type` | | **宿主运行时** | **向后兼容**的历史 manifest 解析器:可能接受部分缺省字段(如 `description``placements``entrypoint.args`缺失的 `bind.tables` |
**新技能不应依赖宿主缺省行为。** 复制模板后按 [`assets/schemas/skill-actions.schema.json`](../assets/schemas/skill-actions.schema.json) 与本文完整填写 manifest。 **新技能不应依赖宿主缺省行为。** 复制模板后按 [`assets/schemas/skill-actions.schema.json`](../assets/schemas/skill-actions.schema.json) 与本文完整填写 manifest。
@@ -21,6 +52,7 @@ Action 是**可选能力**
- 没有宿主直接操作需求的技能,**可以不提供** `actions.json` - 没有宿主直接操作需求的技能,**可以不提供** `actions.json`
- 需要出现在**数据管理按钮**、**技能详情**、**定时任务**或 **Agent 直接调用**中的技能,**必须**提供 `assets/actions.json` - 需要出现在**数据管理按钮**、**技能详情**、**定时任务**或 **Agent 直接调用**中的技能,**必须**提供 `assets/actions.json`
- **含浏览器 RPA / 长耗时任务**的技能:**必须**提供至少一条 `executionProfile: "async"``placements``agent` 的 action`POLICY-SKILL-ACTION-001`)。
## 文件位置 ## 文件位置
@@ -44,32 +76,77 @@ Action 是**可选能力**
模板最小示例见 [`assets/actions.json`](../assets/actions.json)JSON Schema 见 [`assets/schemas/skill-actions.schema.json`](../assets/schemas/skill-actions.schema.json)。 模板最小示例见 [`assets/actions.json`](../assets/actions.json)JSON Schema 见 [`assets/schemas/skill-actions.schema.json`](../assets/schemas/skill-actions.schema.json)。
## 五职责正交(必读)
| 字段 / 层 | 只决定什么 | 不决定什么 |
|-----------|------------|------------|
| **`placements`** | Action **出现在哪里**toolbar / cron / agent / skill-detail …) | 不决定 sync/async |
| **`bind.tables`** | 数据管理里出现在**哪些业务表** | 不决定业务实现 |
| **`executionProfile`** | 宿主是**同步等待**还是**异步 Job** | 不限制可展示入口 |
| **`entrypoint`** | 实际执行哪个 CLI 命令与参数 | 不写业务逻辑 |
| **domain service** | **真正完成什么业务** | 不感知 toolbar / cron / agent 来源 |
一个业务能力通常只定义**一个** Action`placements` 同时挂到多个入口。不要拆成 `sync-records-toolbar` / `sync-records-cron` 等副本,除非语义确实不同;即便拆分,也必须调用同一个领域业务内核。
## Phase 1 当前稳定支持(新技能应只使用这些) ## Phase 1 当前稳定支持(新技能应只使用这些)
| 层级 | 稳定字段 / 能力 | | 层级 | 稳定字段 / 能力 |
|------|----------------| |------|----------------|
| 顶层 | `schemaVersion``skill``actions` | | 顶层 | `schemaVersion``skill``actions` |
| action | `id``label``description``placements``entrypoint`;可选 `inputSchema``confirmation` | | action | `id``label``description``placements``entrypoint`、**`executionProfile`(必填)**;可选 `inputSchema``confirmation`、**`bind`** |
| entrypoint | `type = cli``command``args`**必填** JSON 数组,项为 `string` / `number` / `boolean` | | entrypoint | `type = cli``command``args`**必填** JSON 数组,项为 `string` / `number` / `boolean` |
| placements | `toolbar``skill-detail``agent``cron` | | placements | `toolbar``skill-detail``agent``cron` |
| **bind** | `{ "tables": ["business_table"] }`(见下节) |
| inputSchema | 根 `type: object`properties 使用 `string` / `number` / `boolean`;支持 `enum``default``required``sensitive` | | inputSchema | 根 `type: object`properties 使用 `string` / `number` / `boolean`;支持 `enum``default``required``sensitive` |
| confirmation | `{ "message": "..." }` | | confirmation | `{ "message": "..." }` |
| **executionProfile** | `"sync"` \| `"async"`**必须显式写出**,禁止依赖缺省) |
## `bind.tables`(表级绑定)
```json
{
"bind": {
"tables": ["business_table"]
}
}
```
规则:
- `bind` 为 object`additionalProperties: false`;当前只允许 `tables`
- `tables` 非空数组、元素唯一、英文 **snake_case**、不得为空字符串。
- **`placements``toolbar` 时必须显式声明非空 `bind.tables`**(模板 Schema `if/then` + 自动测试强制)。
- 表名须真实存在于技能 SQLite 与 `_jiangchang_tables`
- 希望出现在多张表时,显式列出所有表;**不要**依赖「无 bind 则全表展示」——那是宿主对**旧技能**的兼容,不是新技能标准。
- 本阶段**不**扩展 `selection` / `inputMapping` / `columns` / row binding / concurrency / locks。
默认模板 `actions.json` 仅含 `health` / `version` / `config-path`,不放在 toolbar故无需 `bind` 示例污染默认 manifest。业务示例
```json
{
"id": "sync-records",
"label": "同步记录",
"description": "从外部来源同步到技能本地数据库,不生成导出文件。",
"placements": ["toolbar", "cron", "agent", "skill-detail"],
"executionProfile": "async",
"bind": { "tables": ["business_records"] },
"entrypoint": { "type": "cli", "command": "sync-records", "args": [] }
}
```
## 预留能力(当前不可当作已实现能力) ## 预留能力(当前不可当作已实现能力)
以下在宿主共享类型或 Schema 枚举中可能出现,但 **Phase 1 Runtime 尚未完整支持****新模板示例不得使用**
| 类别 | 预留项 | 说明 | | 类别 | 预留项 | 说明 |
|------|--------|------| |------|--------|------|
| placements | `row``batch` | 行内 / 批量入口,未来扩展 | | placements | `row``batch` | 行内 / 批量入口,未来扩展;新技能示例不得使用 |
| action 字段 | `bind``concurrency``locks` | 绑定、并发与锁控制,宿主后续实现 | | action 字段 | `concurrency``locks` | 并发与锁控制,未稳定开放 |
| inputSchema | `array`、nested `object``oneOf` 等 | 复杂表单与联合类型,不属于当前推荐模板范围 | | inputSchema | `array`、nested `object``oneOf` 等 | 复杂表单,不属于当前推荐范围 |
可以在文档或 Schema 枚举中保留这些值供未来对齐,但不要让技能作者误以为它们已经可执行 `bind` **不是**保留字段;已作为 Phase 1 表级绑定正式能力
## 执行模型 ## 执行模型
宿主将 action 转为 argv再执行 宿主将 action 转为 argv用**共享 Python**(用户数据目录下 `python-runtime/.venv`执行:
```text ```text
python {skill_root}/scripts/main.py <command> <args...> python {skill_root}/scripts/main.py <command> <args...>
@@ -82,6 +159,21 @@ python {skill_root}/scripts/main.py <command> <args...>
完整子命令定义见 [`scripts/cli/app.py`](../scripts/cli/app.py)。 完整子命令定义见 [`scripts/cli/app.py`](../scripts/cli/app.py)。
### `executionProfile`(仅 sync / async
**心智**:多数 Action 按 **sync**(短调用、不进任务中心);只有长耗时 / RPA / 需进度控制时才标 **async**。匠厂宿主若**省略**该字段,按 **sync** 处理;模板与新技能仍要求**每个 Action 显式写出** `sync``async`,禁止发明 `auto` / `background` / `deferred`,也禁止赌省略行为。
| 值 | 宿主行为 | 任务中心 |
|----|----------|----------|
| `sync`(或省略时的宿主缺省) | 调用方等待结束,直接返回结构化结果或结构化错误;**不**创建后台 Job | 不进 |
| `async`(须显式声明) | 宿主创建后台 Job立即返回 `jobId`;用 `emit` / `checkpoint` / `finish` 报告进度与终态 | **进入** |
合法组合(全部允许):`sync|async` × `toolbar|cron|agent|skill-detail`
经验建议(**不是** placement 硬限制):耗时不可预测、需要暂停/停止/进度展示的任务,用 `async`;其余默认写 `sync`
直接执行短 CLI 时,终端自然等待进程结束。宿主通过 Action 调用同一 CLI 时,再按 `executionProfile` 决定同步等待还是建 Job。技能**不得**自行实现第二套任务中心或后台队列。
### CLI 输出契约 ### CLI 输出契约
技能 CLI 必须: 技能 CLI 必须:
@@ -93,7 +185,6 @@ python {skill_root}/scripts/main.py <command> <args...>
- 对用户可处理的问题提供 `HINT` - 对用户可处理的问题提供 `HINT`
- 不依赖 Agent 连续对话才能完成 - 不依赖 Agent 连续对话才能完成
- 不自行实现宿主任务中心 - 不自行实现宿主任务中心
- 长时间任务允许异步执行,由宿主任务中心承载状态
- 不在 CLI 中硬编码宿主安装目录 - 不在 CLI 中硬编码宿主安装目录
- 不直接依赖某个具体 UI 页面 - 不直接依赖某个具体 UI 页面
@@ -108,19 +199,37 @@ HINT: <next step>
| 值 | 含义 | | 值 | 含义 |
|----|------| |----|------|
| `toolbar` | 数据管理第一排技能按钮 | | `toolbar` | 数据管理第一排技能按钮(须配合 `bind.tables` |
| `skill-detail` | 技能详情或技能市场详情页 | | `skill-detail` | 技能详情或技能市场详情页 |
| `agent` | Agent 可直接调用 | | `agent` | Agent 可直接调用`run_skill_action` |
| `cron` | 定时任务可直接调用 | | `cron` | 定时任务可直接调用 |
**预留能力(当前宿主可能尚未完整支持,模板示例请勿使用):** **预留(模板示例请勿使用):** `row``batch`
| 值 | 说明 | ### Action 类型 × placements常见示例不是限制
|----|------|
| `row` | 行内操作(未来扩展) |
| `batch` | 批量操作(未来扩展) |
可以在 manifest 中作为未来扩展值定义,但不要让技能作者误以为 `row` / `batch` 已经完整可用 下表只表示**常见用法示例**。实际 `placements` 以 manifest 配置为准;**`sync` / `async` 不影响展示入口**
| Action 类型 | 常见 executionProfile | 常见 placements | confirmation |
|-------------|----------------------|-----------------|--------------|
| health / version / config-path | sync | skill-detail, agent | 无 |
| 统计 / 只读查询 | sync | skill-detail, agent | 无 |
| 数据同步(外源 → 本地库) | sync 或 async | toolbar + cron + agent + skill-detail按需 | 可选 |
| 导入 / 重置 | sync 或 async | skill-detail, agent | 可选 |
| 单条副作用 RPA | async建议 | agent, skill-detail | **建议** |
| 批量顺序 pick RPA | async建议 | toolbar, cron, agent | **建议** |
## 同步数据 vs 导出当前表 vs 特殊业务报告
不要混用「导出」一词:
| 能力 | 语义 | 谁负责 |
|------|------|--------|
| **同步数据**sync / refresh / collect | 外部来源 → 技能本地数据库 | 技能 Action / domain service |
| **导出当前数据表** | 技能本地数据库 → CSV/Excel 等 | 数据管理页**宿主统一导出** |
| **生成特殊业务报告** | 多表合并、特殊排版或附加计算 | 仅当系统导出无法满足时,才提供独立 `export-*` Action |
同步型 Action 默认:读外部数据、写技能自己的库、**不**生成 CSV/Excel/JSON 文件、不重复实现宿主表导出。兼容旧 export 命令若需要刷新数据,必须调用同一个 sync 业务内核。通用同步语义见 [`SCHEMA.md`](SCHEMA.md) 与 [`../development/SKILL_ACTION_RUNTIME.md`](../development/SKILL_ACTION_RUNTIME.md)。
## inputSchema 与参数表单 ## inputSchema 与参数表单
@@ -152,6 +261,20 @@ HINT: <next step>
} }
``` ```
批量 pick 参数约定(有队列表时):
```json
{
"pickCount": {
"type": "number",
"title": "处理数量",
"description": "从队列选取 pending 记录条数",
"default": 1,
"minimum": 1
}
}
```
约定: 约定:
- `boolean` 在宿主中渲染为开关 - `boolean` 在宿主中渲染为开关
@@ -166,23 +289,34 @@ HINT: <next step>
## 风险与入口配置 ## 风险与入口配置
- 查询、诊断、版本检查可以放到 `skill-detail``agent` - 查询、诊断、版本检查可以放到 `skill-detail``agent`
- 低风险、常用动作才考虑放 `toolbar` - 低风险、常用动作才考虑放 `toolbar`(须 `bind.tables`executionProfile 按耗时自选)
- 会修改本地数据、访问外部系统、执行长时间任务的动作必须谨慎配置 - 会修改本地数据、访问外部系统、执行长时间任务的动作必须谨慎配置
- 有副作用的动作应添加 `confirmation.message` - 有副作用的动作应添加 `confirmation.message`
- 高风险动作不应默认出现在 `toolbar` - 高风险动作不应默认出现在 `toolbar`
-`sensitive` 参数的 action 不应放入 `toolbar``cron`,除非有明确安全设计 -`sensitive` 参数的 action 不应放入 `toolbar``cron`,除非有明确安全设计
- 不要为了「按钮多」而暴露所有 CLI 子命令 - 不要为了「按钮多」而暴露所有 CLI 子命令
- 一个 CLI 命令可以拆成多个语义清晰的 action但每个 action 必须有明确语义 - 一个 CLI 命令可以拆成多个语义清晰的 action但每个 action 必须有明确语义,并复用同一业务内核
- **Agent 必须用 `run_skill_action`,禁止 `exec` 直跑长任务 CLI**(见 `SKILL_ACTION_RUNTIME.md`
- **禁止**按 `source=toolbar/cron/agent/skill-detail` 在业务代码中分叉业务行为
## 模板示例 action 一览 ## 模板示例 action 一览
| id | CLI | placements | 说明 | | id | CLI | executionProfile | placements | 说明 |
|----|-----|------------|------| |----|-----|------------------|------------|------|
| `health` | `health` | skill-detail, agent | 运行环境检查 | | `health` | `health` | sync | skill-detail, agent | 运行环境检查 |
| `version` | `version` | skill-detail | 版本 JSON | | `version` | `version` | sync | skill-detail | 版本 JSON |
| `config-path` | `config-path` | skill-detail | 配置路径 JSON | | `config-path` | `config-path` | sync | skill-detail | 配置路径 JSON |
复制为新技能后,请按业务需要增删 action不需要宿主入口时可删除整个 `actions.json` 业务技能复制后,按需增加例如:
| 模式 | id 示例 | executionProfile | placements | bind |
|------|---------|------------------|------------|------|
| 数据同步 | `sync-records` | async 或 sync | toolbar, cron, agent, skill-detail | 必填 tables |
| 单条 RPA | `your-run` | async建议 | agent, skill-detail | 按需 |
| 队列 pick | `your-run-pick` | async建议 | toolbar, cron, agent | 有 toolbar 则必填 |
| 统计 | `your-stats` | sync | skill-detail, agent | 无 |
不需要宿主入口时可删除整个 `actions.json`(无 RPA 长任务时)。
## 与宿主 API参考 ## 与宿主 API参考

View File

@@ -1,6 +1,33 @@
# 通用业务技能模板 CLI 标准 # 通用业务技能模板 CLI 标准
`{baseDir}` 替换为技能根目录(含 `SKILL.md``scripts/` 的目录)。所有命令通过 `python {baseDir}/scripts/main.py` 调用。 `{baseDir}` 替换为技能根目录(含 `SKILL.md``scripts/` 的目录)。
## 解释器(必读)
必须使用宿主**共享 Python runtime**`{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`,已在 PATH / `VIRTUAL_ENV`)。一条命令直接跑,不要先探系统 Python。
```bash
python {baseDir}/scripts/main.py <command> …
```
| 场景 | 写法 |
|------|------|
| **推荐Agent** | `python {baseDir}/scripts/main.py <command> …` |
| 手工排查(环境未注入时) | `{JIANGCHANG_DATA_ROOT}/python-runtime/.venv/Scripts/python.exe`Windows`…/.venv/bin/python3`Unix |
**禁止**对技能脚本使用 `uv run python …`(会创建临时环境,加载不到 `jiangchang-platform-kit` / `jiangchang_skill_core`)。
**禁止** Agent 自行 `pip install` / `uv pip install` 往临时环境塞依赖。
## Agent 分流(业务技能复制后必改)
用本表列出**本技能**哪些子命令可走短 CLI哪些必须走 Skill Action。默认短查询/只读写本地可用短 CLI长耗时 / RPA / 需进度取消进**黑名单**。有 async/RPA 的技能:**黑名单不得为空**,且黑名单命令须映射到 `actions.json` 中的 async Action。
| 类型 | 本技能命令(自填) | Agent |
|------|--------------------|-------|
| **短 CLI 白名单** | (例)`health` / `version` / `logs` / `<your-read-or-prep>` | 可用 bash/exec + 共享 `python` |
| **Action 强制黑名单** | (例)`<your-long-or-rpa-command>` | **禁止** bash + `process poll`;必须 `run_skill_action` |
细节与 Action 清单见 [`ACTIONS.md`](ACTIONS.md)。
## 最小命令 ## 最小命令
@@ -8,6 +35,7 @@
python {baseDir}/scripts/main.py health python {baseDir}/scripts/main.py health
python {baseDir}/scripts/main.py config-path python {baseDir}/scripts/main.py config-path
python {baseDir}/scripts/main.py version python {baseDir}/scripts/main.py version
python {baseDir}/scripts/main.py init-db
``` ```
## 标准行为 ## 标准行为
@@ -16,14 +44,16 @@ python {baseDir}/scripts/main.py version
- **`health`**:只读 runtime 诊断,**不下载、不修复 media-assets不执行业务动作**;不输出敏感值。 - **`health`**:只读 runtime 诊断,**不下载、不修复 media-assets不执行业务动作**;不输出敏感值。
- **`config-path`**:输出 JSON包含 `skill``env_path``example_path` - **`config-path`**:输出 JSON包含 `skill``env_path``example_path`
- **`version`**:输出 JSON`version``skill`)。 - **`version`**:输出 JSON`version``skill`)。
- **`run`**:长时间无 stdout **不代表卡死**RPA / 外部调用期间应通过 Activity 或 Run Journal 看进度 - **`init-db`**:幂等创建/迁移本地 SQLite`_jiangchang_*` 展示元数据)。成功输出一行 JSON`ok` / `skill` / `db_path`),退出码 `0`。宿主可在技能安装或更新成功后静默调用;不要并入 `health`
- **`run` / RPA / 长任务**CLI 仍是同一内核;**Agent 禁止**用 bash 干等长任务结束。须走宿主 Skill Action`run_skill_action`),且该 Action 一般为 `executionProfile: "async"`**任务中心**。长时间无 stdout **不代表卡死**;进度看任务中心 / Run Journal。
- **排查顺序**(由快到慢): - **排查顺序**(由快到慢):
1. `python {baseDir}/scripts/main.py logs` 1. `python {baseDir}/scripts/main.py logs`
2. `python {baseDir}/scripts/main.py log-get <log_id>` 2. `python {baseDir}/scripts/main.py log-get <log_id>`
3. 统一日志文件 `{JIANGCHANG_DATA_ROOT}/{JIANGCHANG_USER_ID}/logs/jiangchang.log`(含 `trace_id``task_failed` 等) 3. 统一日志文件 `{JIANGCHANG_DATA_ROOT}/{JIANGCHANG_USER_ID}/logs/jiangchang.log`(含 `trace_id``task_failed` 等)
4. Run Journal `{JIANGCHANG_DATA_ROOT}/.jiangchang/runs/{job_id}.jsonl` 4. Run Journal `{JIANGCHANG_DATA_ROOT}/.jiangchang/runs/{job_id}.jsonl`
5. RPA artifacts / `video_log` / 失败截图(见 `development/RPA.md` 5. RPA artifacts / `video_log` / 失败截图(开发规范`development/RPA.md`;未开启录屏时可能只有截图或日志
- **任务完成后**若有 video artifactCLI 应打印录屏路径、录屏日志、视频/音频诊断(见 `task_run_support._print_video_summary` - **录屏默认关闭**:模板 `.env.example``OPENCLAW_RECORD_VIDEO=0`;若未开启录屏,任务**可能不会**打印录屏路径
- 需要录屏时在用户 `.env` 或进程环境变量中设置 **`OPENCLAW_RECORD_VIDEO=1`**;开启后任务完成时 CLI 应打印录屏路径、录屏日志、视频/音频诊断(见 `task_run_support._print_video_summary`),且 `result_summary` 含 video 字段。
## config-path配置路径 ## config-path配置路径
@@ -39,7 +69,7 @@ python {baseDir}/scripts/main.py version
`health` 委托 `jiangchang_skill_core.collect_runtime_diagnostics`,典型字段: `health` 委托 `jiangchang_skill_core.collect_runtime_diagnostics`,典型字段:
- `python_executable` — 当前 Python 解释器路径 - `python_executable` — 当前 Python 解释器路径(应落在共享 python-runtime
- `platform_kit_version` / `platform_kit_min_version` / `platform_kit_version_ok` - `platform_kit_version` / `platform_kit_min_version` / `platform_kit_version_ok`
- `jiangchang_skill_core_file` — 公共库加载来源(若来自技能目录副本会报 warning - `jiangchang_skill_core_file` — 公共库加载来源(若来自技能目录副本会报 warning
- `media_assets_root``ffmpeg_path``ffmpeg_available``background_music_mp3_count` - `media_assets_root``ffmpeg_path``ffmpeg_available``background_music_mp3_count`
@@ -56,38 +86,7 @@ python {baseDir}/scripts/main.py logs --task-type demo --status failed
python {baseDir}/scripts/main.py log-get <log_id> python {baseDir}/scripts/main.py log-get <log_id>
``` ```
| 命令 | 用途 | | 命令 | 用途 | Agent 注意 |
|------|------| |------|------|------------|
| `run` | 执行一次任务 | | `run` | 执行一次任务(常为长任务 / RPA | **走 `run_skill_action`**,不要 bash poll |
| `logs` | 列出最近 N 条任务日志 | | `logs` / `log-get` | 查任务日志 | 可用短 CLI |
| `log-get` | 按 log_id 查看单条任务日志JSON |
## 查询/导出类(可选)
复制后按需增加,例如:`contacts``contact-get``export` 或业务等价命令。
## 若你的技能依赖兄弟技能
使用 `service.sibling_bridge.call_sibling_json(skill_slug, args)`,不要硬编码兄弟技能名到 `sibling_bridge.py` 自身;并在 `SKILL.md` 声明 `dependencies.required`
## 手工排查命令(推荐)
**建议使用宿主共享 python-runtime**,避免技能目录内临时 venv 加载不到公共库:
```text
Windows:
{JIANGCHANG_DATA_ROOT}\python-runtime\.venv\Scripts\python.exe {baseDir}\scripts\main.py health
通用:
<shared-python> {baseDir}/scripts/main.py health
```
`<shared-python>` 通常位于 `{JIANGCHANG_DATA_ROOT}/python-runtime/.venv`
**不建议**在生产/测试机使用技能目录内 `uv run python`,以免加载不到共享 runtime 中的 `jiangchang-platform-kit` / `playwright`
## 模板约定
- 最小模板至少保留 `health` / `config-path` / `version`
- 通用业务技能建议使用 `run` / `logs` / `log-get`
- 不要再用旧模板的 `publish` / `--account-id` / `--article-id` 命名

View File

@@ -5,16 +5,20 @@
**边界规则:** **边界规则:**
- 本文**不得**包含 YAML frontmatter**不得**包含 `description` 字段。 - 本文**不得**包含 YAML frontmatter**不得**包含 `description` 字段。
- 技能市场详情与普通用户说明**必须**放在根目录 [`README.md`](../README.md)。 - 技能市场四 Tab 材料**必须**放在根目录[`README.md`](../README.md)、[`TUTORIAL.md`](../TUTORIAL.md)、[`DEMO.md`](../DEMO.md)、[`CHANGELOG.md`](../CHANGELOG.md)
- 本目录只保留运行时引用资料(如 `CLI.md``SCHEMA.md`;开发规范放在 [`../development/`](../development/)。 - **Agent 主读本目录**`CLI.md` / `ACTIONS.md` / `SCHEMA.md`与根 [`SKILL.md`](../SKILL.md)。
- [`../development/`](../development/) 是开发者 / 编码助手深度规范,**不是**对话 Agent 的默认读盘路径。
| 文档 | 用途 | | 文档 | 用途 |
|------|------| |------|------|
| 根目录 [`README.md`](../README.md) | 用户市场详情页说明 | | 根目录 [`README.md`](../README.md) | 市场说明 Tab`readme_md` |
| [`SKILL.md`](../SKILL.md) | LLM / OpenClaw 平台技能入口 | | 根目录 [`TUTORIAL.md`](../TUTORIAL.md) | 市场教程 Tab`tutorial_md` |
| [`CLI.md`](CLI.md) | 命令行入口、参数与调用契约 | | 根目录 [`DEMO.md`](../DEMO.md) | 市场演示 Tab`demo_video_url` + `demo_md` |
| 根目录 [`CHANGELOG.md`](../CHANGELOG.md) | 市场更新日志 Tab版本小节 → `changelog` |
| [`SKILL.md`](../SKILL.md) | LLM / OpenClaw 平台技能入口与触发摘要 |
| [`CLI.md`](CLI.md) | 共享 Python、命令行入口、参数与短操作契约 |
| [`ACTIONS.md`](ACTIONS.md) | Skill Action、sync/async、任务中心、多入口可选能力 |
| [`SCHEMA.md`](SCHEMA.md) | 本地 SQLite 与数据管理展示契约 | | [`SCHEMA.md`](SCHEMA.md) | 本地 SQLite 与数据管理展示契约 |
| [`ACTIONS.md`](ACTIONS.md) | Skill Action manifest**可选**能力)与宿主入口契约 | | [`../development/`](../development/) | 开发、测试、RPA 深度规范(给人 / 编码助手) |
| [`../development/`](../development/) | 开发、测试、技术规范(给开发者 / AI 编程代理) |
按需阅读:编排任务时优先 `CLI.md`解析结构化字段时读 `SCHEMA.md`;配置宿主按钮/定时任务/Agent 入口时读 `ACTIONS.md`;运行时环境细节见 `../development/RUNTIME.md` 按需阅读:短操作优先 `CLI.md`Action / 任务中心读 `ACTIONS.md`;结构化字段读 `SCHEMA.md`

View File

@@ -26,6 +26,11 @@
- 对字段名、表名、类型和权限进行最终校验 - 对字段名、表名、类型和权限进行最终校验
- 不猜测技能业务含义 - 不猜测技能业务含义
- 不根据具体技能名称写特殊逻辑 - 不根据具体技能名称写特殊逻辑
- 可在技能安装/更新成功后静默调用 `python scripts/main.py init-db` 做幂等 ensure内部即 `init_db()`);失败不影响安装结果
## 初始化入口
幂等建库/迁移:`python scripts/main.py init-db`。业务仓储也可懒触发 `init_db()`,与 CLI 结果一致。
SQLite **没有**可靠的 `COMMENT ON TABLE/COLUMN`SQL 文件里的 `-- 注释` 也不会成为可查询结构。 SQLite **没有**可靠的 `COMMENT ON TABLE/COLUMN`SQL 文件里的 `-- 注释` 也不会成为可查询结构。
因此中文展示名称必须写入元数据表;字段顺序必须写在 `CREATE TABLE` 的列定义顺序中(`PRAGMA table_info``cid`)。 因此中文展示名称必须写入元数据表;字段顺序必须写在 `CREATE TABLE` 的列定义顺序中(`PRAGMA table_info``cid`)。
@@ -73,6 +78,45 @@ metadata:
不要把「外部来源只读」错误理解成「技能本地数据库一定只读」。技能通过 `_jiangchang_tables.readonly``_jiangchang_columns.editable` 声明本地表的实际写权限。 不要把「外部来源只读」错误理解成「技能本地数据库一定只读」。技能通过 `_jiangchang_tables.readonly``_jiangchang_columns.editable` 声明本地表的实际写权限。
## 标准数据同步语义(外源 → 本地库)
适用于「同步 / refresh / collect」类能力。使用通用名称表述勿把具体平台表名写进模板实现。
| 要求 | 说明 |
|------|------|
| 外部来源默认只读 | 技能不得修改外源 |
| 本地 SQLite 可事务写入 | 写入走 repository + 事务 |
| 幂等 | 同一业务键重复同步结果稳定 |
| 稳定唯一业务键 | 明确 upsert / 匹配字段 |
| 全量或增量 | 在实现与文档中显式声明 |
| 完整快照才提交 | 完整性校验通过后再 commit调用方**必须显式提供**完整性状态(如 keyword-only 必填的 `snapshot_complete`**禁止**默认视为完整,**禁止**靠数据条数猜测 |
| 空结果 / 读取失败保护 | 读取失败、分页不完整或不可信空结果(`snapshot_complete=False`**不得**清库或误删;仅当完整快照**显式确认**为空(`snapshot_complete=True` 且结果为空)时,才可按全量失效策略处理旧数据 |
| 全量失效策略 | 物理删除、`removed`/`is_active` 标记、或保留历史——必须三选一并写清 |
| 部分失败 | 不得伪装成整体成功 |
| 半成品 | 事务失败不得留下可见不一致状态 |
建议统一返回统计:
```json
{
"total": 100,
"inserted": 10,
"updated": 20,
"unchanged": 65,
"removed": 5
}
```
### 同步数据 vs 导出当前数据表 vs 特殊业务报告
| 能力 | 语义 | 负责方 |
|------|------|--------|
| **同步数据** | 外部来源 → 技能本地数据库 | 技能 Action / domain service |
| **导出当前数据表** | 本地库 → CSV/Excel 等 | 数据管理页**宿主统一导出** |
| **生成特殊业务报告** | 多表合并、特殊排版或附加计算 | 仅当系统导出无法满足时,才提供独立 `export-*` |
同步型 Action 默认只写库、不生成导出文件。兼容旧 export 命令需要刷新时,必须调用同一 sync 内核。可复用测试范式见 `tests/samples/test_sync_contract.py.sample`
## 元数据表(宿主兼容) ## 元数据表(宿主兼容)
宿主读取字段(与匠厂 `metadata-resolver` 一致): 宿主读取字段(与匠厂 `metadata-resolver` 一致):

View File

@@ -1,4 +1,7 @@
"""CLIargparse 与分发模板。""" """CLIargparse 与分发模板。
只负责参数解析并转交 service业务内核在 domain / task_service勿在此按入口复制逻辑。
"""
from __future__ import annotations from __future__ import annotations
@@ -9,6 +12,7 @@ from typing import List, Optional
from service.task_service import ( from service.task_service import (
cmd_config_path, cmd_config_path,
cmd_health, cmd_health,
cmd_init_db,
cmd_log_get, cmd_log_get,
cmd_logs, cmd_logs,
cmd_run, cmd_run,
@@ -59,6 +63,7 @@ def _print_full_usage() -> None:
print(" python main.py health") print(" python main.py health")
print(" python main.py config-path") print(" python main.py config-path")
print(" python main.py version") print(" python main.py version")
print(" python main.py init-db")
def build_parser() -> ZhArgumentParser: def build_parser() -> ZhArgumentParser:
@@ -96,6 +101,9 @@ def build_parser() -> ZhArgumentParser:
sp = sub.add_parser("version", help="版本信息(JSON)") sp = sub.add_parser("version", help="版本信息(JSON)")
sp.set_defaults(handler=lambda _a: cmd_version()) sp.set_defaults(handler=lambda _a: cmd_version())
sp = sub.add_parser("init-db", help="幂等初始化本地数据库与数据管理元数据")
sp.set_defaults(handler=lambda _a: cmd_init_db())
return p return p
@@ -108,7 +116,8 @@ def main(argv: Optional[List[str]] = None) -> int:
_print_full_usage() _print_full_usage()
return 1 return 1
if len(argv) == 2 and argv[0] not in { if len(argv) == 2 and argv[0] not in {
"run", "logs", "log-get", "health", "config-path", "version", "-h", "--help" "run", "logs", "log-get", "health", "config-path", "version", "init-db",
"-h", "--help",
}: }:
return cmd_run(target=argv[0], input_id=argv[1]) return cmd_run(target=argv[0], input_id=argv[1])
parser = build_parser() parser = build_parser()

View File

@@ -1,7 +1,8 @@
"""任务编排、日志查询模板。 """任务编排、日志查询模板。
通用业务编排层:负责参数校验、鉴权、调用具体业务实现、写入任务日志 编排层job_context / emit / checkpoint / finish、鉴权、任务日志与错误转换
复制后在 cmd_run 中实现真正的业务逻辑 领域业务请放在 ``service/<domain>_service.py``由本模块调用多入口CLI/Action/cron复用同一内核
复制后在 cmd_run或 cmd_sync_*)中接线到真实 domain service勿按 toolbar/cron/agent 分叉业务。
""" """
from __future__ import annotations from __future__ import annotations
@@ -13,10 +14,10 @@ import uuid
from typing import Any, Dict, Optional from typing import Any, Dict, Optional
from jiangchang_skill_core import collect_runtime_diagnostics, config, format_runtime_health_lines from jiangchang_skill_core import collect_runtime_diagnostics, config, format_runtime_health_lines
from jiangchang_skill_core.activity import emit from jiangchang_skill_core.activity import JobStopped, emit, finish, job_context
from jiangchang_skill_core.rpa.video_session import RpaVideoSession
from db import task_logs_repository as tlr from db import task_logs_repository as tlr
from jiangchang_skill_core.rpa.video_session import RpaVideoSession
from service.entitlement_service import check_entitlement from service.entitlement_service import check_entitlement
from service.task_run_support import ( from service.task_run_support import (
_print_video_summary, _print_video_summary,
@@ -25,8 +26,9 @@ from service.task_run_support import (
) )
from util.constants import LOG_LOGGER_NAME, PLATFORM_KIT_MIN_VERSION, SKILL_SLUG, SKILL_VERSION from util.constants import LOG_LOGGER_NAME, PLATFORM_KIT_MIN_VERSION, SKILL_SLUG, SKILL_VERSION
from util.logging_config import get_skill_logger, setup_skill_logging from util.logging_config import get_skill_logger, setup_skill_logging
from util.runtime_paths import get_skill_data_dir, get_skill_root from util.runtime_paths import get_db_path, get_skill_data_dir, get_skill_root
from util.timeutil import unix_to_iso from util.timeutil import unix_to_iso
from db.connection import init_db
def _get_task_logger(): def _get_task_logger():
@@ -65,102 +67,127 @@ def cmd_run(target: Optional[str] = None, input_id: Optional[str] = None) -> int
"""通用任务执行入口模板。复制后请实现真实业务逻辑。""" """通用任务执行入口模板。复制后请实现真实业务逻辑。"""
log = _get_task_logger() log = _get_task_logger()
task_type = "demo" task_type = "demo"
log.info(
"task_start task_type=%s target_id=%s input_id=%s",
task_type,
target,
input_id,
)
emit("开始处理任务", skill=SKILL_SLUG, stage="run")
try:
ok, reason = check_entitlement(SKILL_SLUG)
if not ok:
log.warning("entitlement_failed task_type=%s reason=%s", task_type, reason)
emit("鉴权失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="auth")
tlr.save_task_log(
task_type=task_type,
target_id=target,
input_id=input_id,
input_title="模板示例任务",
status="failed",
error_msg=reason,
result_summary=json.dumps({"stage": "auth", "error": reason}, ensure_ascii=False),
)
log.info(
"task_log_saved task_type=%s target_id=%s input_id=%s stage=auth status=failed",
task_type,
target,
input_id,
)
print(f"{reason}")
return 1
log.info("task_run_demo_start target_id=%s input_id=%s", target, input_id) with job_context(skill=SKILL_SLUG):
rc, video_info = asyncio.run(_run_template_demo(target, input_id))
log.info("task_run_demo_done target_id=%s input_id=%s status=failed", 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=task_type,
target_id=target,
input_id=input_id,
input_title="模板示例任务",
status="failed",
error_msg="模板仓库未实现真实业务",
result_summary=json.dumps(summary_payload, ensure_ascii=False),
)
log.info( log.info(
"task_log_saved task_type=%s target_id=%s input_id=%s status=failed", "task_start task_type=%s target_id=%s input_id=%s",
task_type, task_type,
target, target,
input_id, input_id,
) )
emit("开始处理任务", skill=SKILL_SLUG, stage="run")
print("❌ 这是模板仓库,请复制后在 scripts/service/task_service.py 中实现 cmd_run 的真实业务逻辑。")
return rc
except Exception:
log.exception(
"task_failed task_type=%s target_id=%s input_id=%s",
task_type,
target,
input_id,
)
emit("任务失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="run")
try: try:
ok, reason = check_entitlement(SKILL_SLUG)
if not ok:
log.warning("entitlement_failed task_type=%s reason=%s", task_type, reason)
emit("鉴权失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="auth")
tlr.save_task_log(
task_type=task_type,
target_id=target,
input_id=input_id,
input_title="模板示例任务",
status="failed",
error_msg=reason,
result_summary=json.dumps({"stage": "auth", "error": reason}, ensure_ascii=False),
)
log.info(
"task_log_saved task_type=%s target_id=%s input_id=%s stage=auth status=failed",
task_type,
target,
input_id,
)
finish(
status="failed",
message=reason,
skill=SKILL_SLUG,
error_code="ENTITLEMENT_DENIED",
stage="auth",
)
print(f"{reason}")
return 1
log.info("task_run_demo_start target_id=%s input_id=%s", target, input_id)
rc, video_info = asyncio.run(_run_template_demo(target, input_id))
log.info("task_run_demo_done target_id=%s input_id=%s status=failed", 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( tlr.save_task_log(
task_type=task_type, task_type=task_type,
target_id=target, target_id=target,
input_id=input_id, input_id=input_id,
input_title="模板示例任务", input_title="模板示例任务",
status="failed", status="failed",
error_msg="任务执行异常,详见统一日志", error_msg="模板仓库未实现真实业务",
result_summary=json.dumps( result_summary=json.dumps(summary_payload, ensure_ascii=False),
{"stage": "run", "error": "unexpected_exception"},
ensure_ascii=False,
),
) )
log.info( log.info(
"task_log_saved task_type=%s target_id=%s input_id=%s stage=run status=failed", "task_log_saved task_type=%s target_id=%s input_id=%s status=failed",
task_type, task_type,
target, target,
input_id, input_id,
) )
finish(
status="failed",
message="模板仓库未实现真实业务",
skill=SKILL_SLUG,
template_demo=True,
target=target,
input_id=input_id,
)
print("❌ 这是模板仓库,请复制后在 scripts/service/task_service.py 中实现 cmd_run 的真实业务逻辑。")
return rc
except JobStopped:
raise
except Exception: except Exception:
log.exception( log.exception(
"task_log_save_failed task_type=%s target_id=%s input_id=%s", "task_failed task_type=%s target_id=%s input_id=%s",
task_type, task_type,
target, target,
input_id, input_id,
) )
return 1 emit("任务失败,已记录诊断信息", type="warn", skill=SKILL_SLUG, stage="run")
try:
tlr.save_task_log(
task_type=task_type,
target_id=target,
input_id=input_id,
input_title="模板示例任务",
status="failed",
error_msg="任务执行异常,详见统一日志",
result_summary=json.dumps(
{"stage": "run", "error": "unexpected_exception"},
ensure_ascii=False,
),
)
log.info(
"task_log_saved task_type=%s target_id=%s input_id=%s stage=run status=failed",
task_type,
target,
input_id,
)
except Exception:
log.exception(
"task_log_save_failed task_type=%s target_id=%s input_id=%s",
task_type,
target,
input_id,
)
finish(
status="failed",
message="任务执行异常,详见统一日志",
skill=SKILL_SLUG,
stage="run",
)
return 1
def cmd_logs( def cmd_logs(
@@ -266,3 +293,28 @@ def cmd_health() -> int:
def cmd_version() -> int: def cmd_version() -> int:
print(json.dumps({"version": SKILL_VERSION, "skill": SKILL_SLUG}, ensure_ascii=False)) print(json.dumps({"version": SKILL_VERSION, "skill": SKILL_SLUG}, ensure_ascii=False))
return 0 return 0
def cmd_init_db() -> int:
"""幂等创建/迁移本地 SQLite 与数据管理元数据(宿主 install/upgrade 可调用)。"""
try:
init_db()
except Exception as exc: # noqa: BLE001 — CLI 边界,统一成可机读失败
print(
json.dumps(
{"ok": False, "skill": SKILL_SLUG, "error": str(exc)},
ensure_ascii=False,
)
)
return 1
print(
json.dumps(
{
"ok": True,
"skill": SKILL_SLUG,
"db_path": get_db_path(),
},
ensure_ascii=False,
)
)
return 0

View File

@@ -1,6 +1,6 @@
"""技能标识、版本与平台公共库约束(复制后请修改 slug/version/logger""" """技能标识、版本与平台公共库约束(复制后请修改 slug/version/logger"""
SKILL_SLUG = "your-skill-slug" SKILL_SLUG = "your-skill-slug"
SKILL_VERSION = "1.0.32" SKILL_VERSION = "1.0.51"
LOG_LOGGER_NAME = "openclaw.skill.your_skill_slug" LOG_LOGGER_NAME = "openclaw.skill.your_skill_slug"
PLATFORM_KIT_MIN_VERSION = "1.0.17" PLATFORM_KIT_MIN_VERSION = "1.2.2"

View File

@@ -1,4 +1,4 @@
"""数据根、技能目录、兄弟技能根路径。""" """数据根、技能目录、兄弟技能根路径与用户数据子目录解析"""
from __future__ import annotations from __future__ import annotations
@@ -10,6 +10,22 @@ from util.constants import SKILL_SLUG
_SCRIPTS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) _SCRIPTS_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STANDARD_SUBDIR_DOWNLOADS = "downloads"
STANDARD_SUBDIR_IMPORTS = "imports"
STANDARD_SUBDIR_EXPORTS = "exports"
STANDARD_SUBDIR_UPLOADS = "uploads"
STANDARD_SUBDIR_CACHE = "cache"
STANDARD_SUBDIR_TEMP = "temp"
STANDARD_SUBDIR_RPA_ARTIFACTS = "rpa-artifacts"
STANDARD_SUBDIR_VIDEOS = "videos"
CONFIG_KEY_DOWNLOAD_DIR = "SKILL_DOWNLOAD_DIR"
CONFIG_KEY_IMPORT_DIR = "SKILL_IMPORT_DIR"
CONFIG_KEY_EXPORT_DIR = "SKILL_EXPORT_DIR"
CONFIG_KEY_UPLOAD_DIR = "SKILL_UPLOAD_DIR"
CONFIG_KEY_CACHE_DIR = "SKILL_CACHE_DIR"
CONFIG_KEY_TEMP_DIR = "SKILL_TEMP_DIR"
def get_skill_root() -> str: def get_skill_root() -> str:
return os.path.dirname(_SCRIPTS_DIR) return os.path.dirname(_SCRIPTS_DIR)
@@ -32,3 +48,98 @@ def get_skill_data_dir() -> str:
def get_db_path(filename: str | None = None) -> str: def get_db_path(filename: str | None = None) -> str:
name = filename or f"{SKILL_SLUG}.db" name = filename or f"{SKILL_SLUG}.db"
return os.path.join(get_skill_data_dir(), name) return os.path.join(get_skill_data_dir(), name)
def _normalize_subdir(value: str) -> str:
cleaned = value.strip().strip("/\\")
if not cleaned or cleaned.startswith(".."):
raise ValueError(f"invalid skill data subdir: {value!r}")
return cleaned.replace("/", os.sep).replace("\\", os.sep)
def resolve_data_path(
config_key: str | None,
default_subdir: str,
*,
create: bool = True,
) -> str:
"""解析技能拥有路径:空配置 → 数据目录下 default_subdir相对 → 相对数据目录;绝对 → 原样。"""
from jiangchang_skill_core import config
base = get_skill_data_dir()
raw = (config.get(config_key) or "").strip() if config_key else ""
if not raw:
path = os.path.join(base, _normalize_subdir(default_subdir))
elif os.path.isabs(raw):
path = os.path.abspath(os.path.expanduser(raw))
else:
path = os.path.join(base, _normalize_subdir(raw))
if create:
os.makedirs(path, exist_ok=True)
return path
def resolve_input_path(raw_path: str, *, create_parent: bool = False) -> str:
"""解析 CLI 输入路径:绝对路径原样;相对路径相对 {skill_data_dir}/imports/。"""
text = (raw_path or "").strip()
if not text:
return text
expanded = os.path.expanduser(text)
if os.path.isabs(expanded):
return os.path.abspath(expanded)
imports_dir = get_imports_dir(create=create_parent)
return os.path.abspath(os.path.join(imports_dir, os.path.normpath(expanded)))
def get_downloads_dir(*, create: bool = True) -> str:
return resolve_data_path(CONFIG_KEY_DOWNLOAD_DIR, STANDARD_SUBDIR_DOWNLOADS, create=create)
def get_imports_dir(*, create: bool = True) -> str:
return resolve_data_path(CONFIG_KEY_IMPORT_DIR, STANDARD_SUBDIR_IMPORTS, create=create)
def get_exports_dir(*, create: bool = True) -> str:
return resolve_data_path(CONFIG_KEY_EXPORT_DIR, STANDARD_SUBDIR_EXPORTS, create=create)
def get_uploads_dir(*, create: bool = True) -> str:
return resolve_data_path(CONFIG_KEY_UPLOAD_DIR, STANDARD_SUBDIR_UPLOADS, create=create)
def get_cache_dir(*, create: bool = True) -> str:
return resolve_data_path(CONFIG_KEY_CACHE_DIR, STANDARD_SUBDIR_CACHE, create=create)
def get_temp_dir(*, create: bool = True) -> str:
return resolve_data_path(CONFIG_KEY_TEMP_DIR, STANDARD_SUBDIR_TEMP, create=create)
def get_rpa_artifacts_dir(batch_id: str, *, create: bool = True) -> str:
batch = (batch_id or "").strip() or "default"
path = os.path.join(get_skill_data_dir(), STANDARD_SUBDIR_RPA_ARTIFACTS, batch)
if create:
os.makedirs(path, exist_ok=True)
return path
def get_videos_dir(*, create: bool = True) -> str:
path = os.path.join(get_skill_data_dir(), STANDARD_SUBDIR_VIDEOS)
if create:
os.makedirs(path, exist_ok=True)
return path
def list_resolved_data_paths() -> dict[str, str]:
"""供 health / config-path 输出已解析的数据子目录(不创建目录)。"""
return {
"skill_data_dir": get_skill_data_dir(),
"downloads_dir": get_downloads_dir(create=False),
"imports_dir": get_imports_dir(create=False),
"exports_dir": get_exports_dir(create=False),
"uploads_dir": get_uploads_dir(create=False),
"cache_dir": get_cache_dir(create=False),
"temp_dir": get_temp_dir(create=False),
"videos_dir": get_videos_dir(create=False),
}

View File

@@ -12,9 +12,11 @@
| 场景 | 放在哪里 | 默认是否运行 | 说明 | | 场景 | 放在哪里 | 默认是否运行 | 说明 |
|------|----------|--------------|------| |------|----------|--------------|------|
| CLI / health / version / metadata / runtime 路径 | `tests/test_*.py` | 是 | 默认必跑,保持轻量、无外联 | | CLI / health / version / init-db / metadata / runtime 路径 | `tests/test_*.py` | 是 | 默认必跑,保持轻量、无外联 |
| 纯函数 / 业务规则 | `tests/test_*.py` | 是 | 不依赖真实外部系统 | | 纯函数 / 业务规则 | `tests/test_*.py` | 是 | 不依赖真实外部系统 |
| service 层契约 | 从 `tests/samples/test_service_contract.py.sample` 复制到 `tests/test_service_contract.py` | 是,复制后 | 用 `FakeAdapter` / stub 注入外部依赖 | | service 层契约 | 从 `tests/samples/test_service_contract.py.sample` 复制到 `tests/test_service_contract.py` | 是,复制后 | 用 `FakeAdapter` / stub 注入外部依赖 |
| 外源同步契约 | 从 `tests/samples/test_sync_contract.py.sample` 复制 | 是,复制后 | 幂等 / 事务 / 空结果保护 / 不导出文件 |
| 单内核多入口 | 从 `tests/samples/test_action_core_contract.py.sample` 复制 | 是,复制后 | CLI/task/兼容命令复用同一 domain service |
| golden fixture 回归 | 从 `tests/samples/test_golden_cases.py.sample` 复制到 `tests/test_golden_cases.py` | 是,复制后 | 输入样例 + 期望输出,适合解析、计算、校验类技能 | | golden fixture 回归 | 从 `tests/samples/test_golden_cases.py.sample` 复制到 `tests/test_golden_cases.py` | 是,复制后 | 输入样例 + 期望输出,适合解析、计算、校验类技能 |
| 仿真 API | `tests/integration/test_simulator_api_contract.py.sample` | 否 | 复制并设置 `OPENCLAW_TEST_TARGET=simulator_api` 后按需运行 | | 仿真 API | `tests/integration/test_simulator_api_contract.py.sample` | 否 | 复制并设置 `OPENCLAW_TEST_TARGET=simulator_api` 后按需运行 |
| 仿真 RPA / 页面操作 | `tests/integration/test_simulator_rpa_contract.py.sample` | 否 | 用 localhost / 仿真页面,不碰真实系统 | | 仿真 RPA / 页面操作 | `tests/integration/test_simulator_rpa_contract.py.sample` | 否 | 用 localhost / 仿真页面,不碰真实系统 |
@@ -33,6 +35,7 @@
- [ ] `python tests/run_tests.py -v` 能通过(含 platform-kit 导入与无 vendored core 守护)。 - [ ] `python tests/run_tests.py -v` 能通过(含 platform-kit 导入与无 vendored core 守护)。
- [ ] `python scripts/main.py health` 能通过(输出 runtime diagnosticswarning 不导致非零退出)。 - [ ] `python scripts/main.py health` 能通过(输出 runtime diagnosticswarning 不导致非零退出)。
- [ ] `python scripts/main.py version` 输出 JSON且 `skill` 与目录名 / `SKILL.md` / `constants.SKILL_SLUG` 一致。 - [ ] `python scripts/main.py version` 输出 JSON且 `skill` 与目录名 / `SKILL.md` / `constants.SKILL_SLUG` 一致。
- [ ] `python scripts/main.py init-db` 幂等创建本地库并输出 JSON`ok` / `skill` / `db_path`)。
- [ ] 所有 DB / 文件写入都在 `IsolatedDataRoot`(或等价隔离)下测试,不写真实数据目录。 - [ ] 所有 DB / 文件写入都在 `IsolatedDataRoot`(或等价隔离)下测试,不写真实数据目录。
- [ ] 外部系统默认使用 mock / `FakeAdapter`,不访问真实 API不打开真实 RPA。 - [ ] 外部系统默认使用 mock / `FakeAdapter`,不访问真实 API不打开真实 RPA。
- [ ] 至少有 1 个成功路径测试。 - [ ] 至少有 1 个成功路径测试。

View File

@@ -35,7 +35,7 @@ def get_skill_root() -> str:
return _SKILL_ROOT return _SKILL_ROOT
def platform_kit_version_patch(version: str = "1.0.17"): def platform_kit_version_patch(version: str = "1.2.2"):
"""Mock installed jiangchang-platform-kit version for health/diagnostics tests.""" """Mock installed jiangchang-platform-kit version for health/diagnostics tests."""
from unittest.mock import patch from unittest.mock import patch

View File

@@ -12,7 +12,7 @@
--- ---
## 两类样例文件 ## 样例文件
### 1. `test_service_contract.py.sample` ### 1. `test_service_contract.py.sample`
@@ -22,7 +22,17 @@
- 需要验证:**成功路径**、**参数/校验错误**、**adapter 异常被转换为业务可读错误**。 - 需要验证:**成功路径**、**参数/校验错误**、**adapter 异常被转换为业务可读错误**。
- 需要用 **`FakeAdapter`**(见 `tests/adapter_test_utils.py`)或自建 **stub** 替代 ERP、TMS、WMS、船司、报关、LLM、RPA 等,**不**发真实 HTTP、**不**开真实浏览器。 - 需要用 **`FakeAdapter`**(见 `tests/adapter_test_utils.py`)或自建 **stub** 替代 ERP、TMS、WMS、船司、报关、LLM、RPA 等,**不**发真实 HTTP、**不**开真实浏览器。
### 2. `test_golden_cases.py.sample` ### 2. `test_sync_contract.py.sample`
**适合:** 外源 → 本地库的同步 / refresh / collect 能力。
至少应覆盖:首次插入、第二次幂等、更新、失效数据处理、不可信空结果保护 vs 完整空快照失效、遗漏 `snapshot_complete` 立即失败、部分写入后故障注入与回滚(`fail_after_writes`)、统计字段 `inserted/updated/unchanged/removed`、同步路径不调用 CSV/Excel 导出器。`snapshot_complete` 为调用方**必须显式传入**的 keyword-only 参数(无默认值),禁止默认把结果当成完整快照,也禁止靠条数猜测完整性。使用通用表名(如 `business_key`),不要写具体平台业务名。
### 3. `test_action_core_contract.py.sample`
**适合:** 校验「单业务内核、多入口」——task/CLI/兼容命令调用同一 domain service不按 toolbar/cron/agent 来源改变业务结果。
### 4. `test_golden_cases.py.sample`
**适合:** **适合:**
@@ -103,6 +113,8 @@
| 用途 | 示例文件名 | | 用途 | 示例文件名 |
|------|------------| |------|------------|
| Service 契约 | `tests/test_service_contract.py` | | Service 契约 | `tests/test_service_contract.py` |
| 同步契约 | `tests/test_sync_contract.py` |
| 单内核多入口 | `tests/test_action_core_contract.py` |
| Golden / fixture 回归 | `tests/test_golden_cases.py` | | Golden / fixture 回归 | `tests/test_golden_cases.py` |
| 领域规则 | `tests/test_<domain>_rules.py` | | 领域规则 | `tests/test_<domain>_rules.py` |
| 校验逻辑 | `tests/test_<domain>_validation.py` | | 校验逻辑 | `tests/test_<domain>_validation.py` |

View File

@@ -0,0 +1,116 @@
# -*- coding: utf-8 -*-
# 样例:复制到 ``tests/test_action_core_contract.py`` 后按实际模块改名运行。
# 默认不会被 ``python tests/run_tests.py`` 收集(扩展名为 .sample
"""
单业务内核、多入口契约范式(通用)。
覆盖:
- task / command adapter 调用唯一 domain service
- 兼容命令复用同一个核心函数
- CLI handler 不复制业务逻辑
- 不根据 toolbar / cron / agent 来源改变业务处理
复制后把示意函数换成真实 import禁止按入口维护多套实现。
"""
from __future__ import annotations
import unittest
from typing import Any, Callable
class DomainService:
"""唯一业务内核示意。"""
def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []
def sync_records(self, *, limit: int = 100) -> dict[str, Any]:
self.calls.append({"op": "sync_records", "limit": limit})
return {"ok": True, "limit": limit, "inserted": 1}
def cmd_sync_records(domain: DomainService, *, limit: int = 100) -> dict[str, Any]:
"""task_service 编排层:可加 job_context但不按 source 分叉业务。"""
return domain.sync_records(limit=limit)
def cmd_export_compat_refresh(domain: DomainService, *, limit: int = 100) -> dict[str, Any]:
"""兼容旧 export刷新必须复用同一 sync 内核,禁止另写采集逻辑。"""
sync_result = domain.sync_records(limit=limit)
return {"export": "delegated-to-host-or-report", "sync": sync_result}
def cli_handle_sync(domain: DomainService, argv_limit: int) -> dict[str, Any]:
"""CLI handler只解析参数后转发不内嵌业务。"""
return cmd_sync_records(domain, limit=argv_limit)
def run_from_source(
domain: DomainService,
*,
source: str,
limit: int = 10,
) -> dict[str, Any]:
"""
宿主可能传入 source=toolbar|cron|agent|skill-detail。
正确实现:忽略 source业务结果一致。
"""
_ = source # 不得用于分支业务语义
return cmd_sync_records(domain, limit=limit)
class TestActionCoreContractSample(unittest.TestCase):
def test_task_adapter_calls_single_domain_service(self) -> None:
domain = DomainService()
out = cmd_sync_records(domain, limit=5)
self.assertTrue(out["ok"])
self.assertEqual(domain.calls, [{"op": "sync_records", "limit": 5}])
def test_compat_command_reuses_same_core(self) -> None:
domain = DomainService()
cmd_export_compat_refresh(domain, limit=3)
self.assertEqual(len(domain.calls), 1)
self.assertEqual(domain.calls[0]["op"], "sync_records")
def test_cli_handler_does_not_duplicate_business_logic(self) -> None:
domain = DomainService()
# CLI 与 task 编排应落到同一函数对象(示意)
self.assertIs(cli_handle_sync.__wrapped__ if hasattr(cli_handle_sync, "__wrapped__") else None, None)
out = cli_handle_sync(domain, 7)
self.assertEqual(out["limit"], 7)
self.assertEqual(domain.calls[-1], {"op": "sync_records", "limit": 7})
# 强化CLI 路径与 cmd 路径结果一致
domain2 = DomainService()
a = cli_handle_sync(domain2, 2)
domain3 = DomainService()
b = cmd_sync_records(domain3, limit=2)
self.assertEqual(a, b)
def test_business_result_independent_of_entry_source(self) -> None:
domain = DomainService()
results = [
run_from_source(domain, source=src, limit=4)
for src in ("toolbar", "cron", "agent", "skill-detail")
]
self.assertEqual(results[0], results[1])
self.assertEqual(results[1], results[2])
self.assertEqual(results[2], results[3])
self.assertEqual(len(domain.calls), 4)
self.assertTrue(all(c["op"] == "sync_records" and c["limit"] == 4 for c in domain.calls))
def test_entrypoint_wiring_points_to_same_callable(self) -> None:
"""示意manifest 多 placements 应对应同一 Python 入口函数。"""
domain = DomainService()
handlers: dict[str, Callable[..., dict[str, Any]]] = {
"toolbar": lambda: cmd_sync_records(domain, limit=1),
"cron": lambda: cmd_sync_records(domain, limit=1),
"agent": lambda: cmd_sync_records(domain, limit=1),
}
outs = [handlers[k]() for k in handlers]
self.assertEqual(outs[0], outs[1])
self.assertEqual(outs[1], outs[2])
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,274 @@
# -*- coding: utf-8 -*-
# 样例:复制到 ``tests/test_sync_contract.py`` 后按实际 domain service 改名运行。
# 默认不会被 ``python tests/run_tests.py`` 收集(扩展名为 .sample
"""
外源 → 本地库同步契约范式(通用,无具体平台业务名)。
覆盖:
- 首次同步插入
- 第二次同步幂等
- 更新已有数据
- 处理失效数据
- 不可信空结果保护 vs 完整空快照失效(``snapshot_complete`` 必填,无默认值)
- 遗漏 ``snapshot_complete`` 立即失败TypeError
- 事务在部分写入后失败并回滚
- 返回 inserted/updated/unchanged/removed
- sync Action 不调用 CSV/Excel 文件导出器
复制后把内存仓库与 stub 外源换成真实 repository / reader禁止访问真实网络或用户数据目录。
"""
from __future__ import annotations
import unittest
from dataclasses import dataclass, field
from typing import Any
@dataclass
class SyncStats:
total: int = 0
inserted: int = 0
updated: int = 0
unchanged: int = 0
removed: int = 0
def as_dict(self) -> dict[str, int]:
return {
"total": self.total,
"inserted": self.inserted,
"updated": self.updated,
"unchanged": self.unchanged,
"removed": self.removed,
}
@dataclass
class MemoryRecordStore:
"""内存库:演示幂等 upsert + 全量失效is_active 标记)。"""
rows: dict[str, dict[str, Any]] = field(default_factory=dict)
in_transaction: bool = False
_tx_snapshot: dict[str, dict[str, Any]] | None = None
def begin(self) -> None:
self._tx_snapshot = {k: dict(v) for k, v in self.rows.items()}
self.in_transaction = True
def commit(self) -> None:
self._tx_snapshot = None
self.in_transaction = False
def rollback(self) -> None:
if self._tx_snapshot is not None:
self.rows = {k: dict(v) for k, v in self._tx_snapshot.items()}
self._tx_snapshot = None
self.in_transaction = False
def upsert_snapshot(
self,
records: list[dict[str, Any]],
*,
fail_after_writes: int | None = None,
) -> SyncStats:
"""全量快照:按 business_key 对齐;缺失标 is_active=0。
``fail_after_writes``:在成功完成该次数的 insert/update 之后抛错,用于验证回滚。
"""
self.begin()
try:
stats = SyncStats(total=len(records))
seen: set[str] = set()
write_count = 0
for rec in records:
key = str(rec["business_key"])
seen.add(key)
existing = self.rows.get(key)
payload = {
"business_key": key,
"title": rec["title"],
"is_active": 1,
}
if existing is None:
self.rows[key] = payload
stats.inserted += 1
write_count += 1
elif existing.get("title") == payload["title"] and existing.get("is_active") == 1:
stats.unchanged += 1
else:
self.rows[key] = payload
stats.updated += 1
write_count += 1
if fail_after_writes is not None and write_count >= fail_after_writes:
raise RuntimeError(
f"simulated write failure after {write_count} insert/update write(s)"
)
for key, existing in list(self.rows.items()):
if key not in seen and existing.get("is_active") == 1:
existing["is_active"] = 0
stats.removed += 1
self.commit()
return stats
except Exception:
self.rollback()
raise
class ExportSpy:
"""若 sync 路径误调导出器,测试应失败。"""
def __init__(self) -> None:
self.calls: list[str] = []
def write_csv(self, *_a: Any, **_k: Any) -> None:
self.calls.append("csv")
def write_excel(self, *_a: Any, **_k: Any) -> None:
self.calls.append("excel")
def sync_records(
store: MemoryRecordStore,
external_rows: list[dict[str, Any]],
*,
snapshot_complete: bool,
exporter: ExportSpy | None = None,
fail_after_writes: int | None = None,
) -> dict[str, int]:
"""领域同步内核示意:只写库,不导出文件。
``snapshot_complete`` 为 keyword-only **必填**参数(无默认值):
- False读取失败/分页不完整/不可信结果 → 不得清库或失效旧数据
- True外源完整快照可为空→ 允许按全量策略 upsert / 标记失效
调用方必须显式传入,禁止默认当作完整快照,也禁止靠条数猜测完整性。
"""
if external_rows is None:
raise ValueError("external_rows required")
if not snapshot_complete:
active = sum(1 for r in store.rows.values() if r.get("is_active") == 1)
return SyncStats(total=0, unchanged=active).as_dict()
stats = store.upsert_snapshot(external_rows, fail_after_writes=fail_after_writes)
if exporter is not None:
# 正确实现不得调用;本示意刻意不调用,供测试断言
pass
return stats.as_dict()
class TestSyncContractSample(unittest.TestCase):
def test_first_sync_inserts(self) -> None:
store = MemoryRecordStore()
stats = sync_records(
store,
[{"business_key": "a", "title": "A"}, {"business_key": "b", "title": "B"}],
snapshot_complete=True,
)
self.assertEqual(stats["inserted"], 2)
self.assertEqual(stats["total"], 2)
self.assertEqual(len(store.rows), 2)
def test_second_sync_is_idempotent(self) -> None:
store = MemoryRecordStore()
rows = [{"business_key": "a", "title": "A"}]
sync_records(store, rows, snapshot_complete=True)
stats = sync_records(store, rows, snapshot_complete=True)
self.assertEqual(stats["unchanged"], 1)
self.assertEqual(stats["inserted"], 0)
self.assertEqual(stats["updated"], 0)
def test_updates_existing_row(self) -> None:
store = MemoryRecordStore()
sync_records(store, [{"business_key": "a", "title": "A"}], snapshot_complete=True)
stats = sync_records(
store, [{"business_key": "a", "title": "A2"}], snapshot_complete=True
)
self.assertEqual(stats["updated"], 1)
self.assertEqual(store.rows["a"]["title"], "A2")
def test_marks_removed_inactive_on_full_sync(self) -> None:
store = MemoryRecordStore()
sync_records(
store,
[{"business_key": "a", "title": "A"}, {"business_key": "b", "title": "B"}],
snapshot_complete=True,
)
stats = sync_records(
store, [{"business_key": "a", "title": "A"}], snapshot_complete=True
)
self.assertEqual(stats["removed"], 1)
self.assertEqual(store.rows["b"]["is_active"], 0)
self.assertEqual(store.rows["a"]["is_active"], 1)
def test_incomplete_empty_snapshot_does_not_wipe_existing(self) -> None:
store = MemoryRecordStore()
sync_records(store, [{"business_key": "a", "title": "A"}], snapshot_complete=True)
stats = sync_records(store, [], snapshot_complete=False)
self.assertEqual(store.rows["a"]["is_active"], 1)
self.assertEqual(stats["removed"], 0)
self.assertEqual(stats["unchanged"], 1)
def test_complete_empty_snapshot_marks_existing_inactive(self) -> None:
store = MemoryRecordStore()
sync_records(
store,
[{"business_key": "a", "title": "A"}, {"business_key": "b", "title": "B"}],
snapshot_complete=True,
)
stats = sync_records(store, [], snapshot_complete=True)
self.assertEqual(stats["removed"], 2)
self.assertEqual(store.rows["a"]["is_active"], 0)
self.assertEqual(store.rows["b"]["is_active"], 0)
def test_omitting_snapshot_complete_raises_type_error(self) -> None:
store = MemoryRecordStore()
with self.assertRaises(TypeError):
sync_records(store, [{"business_key": "a", "title": "A"}]) # type: ignore[call-arg]
def test_transaction_failure_after_partial_writes_rolls_back(self) -> None:
store = MemoryRecordStore()
sync_records(store, [{"business_key": "a", "title": "A"}], snapshot_complete=True)
with self.assertRaises(RuntimeError) as ctx:
sync_records(
store,
[
{"business_key": "a", "title": "A2"},
{"business_key": "b", "title": "B"},
],
snapshot_complete=True,
fail_after_writes=1,
)
self.assertIn("after 1", str(ctx.exception))
self.assertEqual(store.rows["a"]["title"], "A")
self.assertNotIn("b", store.rows)
self.assertFalse(store.in_transaction)
self.assertIsNone(store._tx_snapshot)
def test_stats_keys_cover_inserted_updated_unchanged_removed(self) -> None:
store = MemoryRecordStore()
sync_records(
store,
[{"business_key": "a", "title": "A"}, {"business_key": "b", "title": "B"}],
snapshot_complete=True,
)
stats = sync_records(
store,
[{"business_key": "a", "title": "A2"}],
snapshot_complete=True,
)
for key in ("total", "inserted", "updated", "unchanged", "removed"):
self.assertIn(key, stats)
self.assertEqual(stats["updated"], 1)
self.assertEqual(stats["removed"], 1)
def test_sync_does_not_call_file_exporters(self) -> None:
store = MemoryRecordStore()
spy = ExportSpy()
sync_records(
store,
[{"business_key": "a", "title": "A"}],
snapshot_complete=True,
exporter=spy,
)
self.assertEqual(spy.calls, [])
if __name__ == "__main__":
unittest.main()

View File

@@ -5,9 +5,10 @@ from __future__ import annotations
import json import json
import os import os
import re import re
import sqlite3
import unittest import unittest
from _support import get_skill_root from _support import IsolatedDataRoot, get_skill_root
from cli.app import build_parser from cli.app import build_parser
from util.constants import SKILL_SLUG from util.constants import SKILL_SLUG
@@ -15,9 +16,13 @@ from util.constants import SKILL_SLUG
_TEMPLATE_PLACEHOLDER_SLUG = "your-skill-slug" _TEMPLATE_PLACEHOLDER_SLUG = "your-skill-slug"
_ALLOWED_PLACEMENTS = frozenset({"toolbar", "row", "batch", "cron", "agent", "skill-detail"}) _ALLOWED_PLACEMENTS = frozenset({"toolbar", "row", "batch", "cron", "agent", "skill-detail"})
_RESERVED_PLACEMENTS = frozenset({"row", "batch"}) _RESERVED_PLACEMENTS = frozenset({"row", "batch"})
_RESERVED_ACTION_FIELDS = frozenset({"bind", "concurrency", "locks"}) _RESERVED_ACTION_FIELDS = frozenset({"concurrency", "locks"})
_ALLOWED_EXECUTION_PROFILES = frozenset({"sync", "async"})
_REQUIRED_MANIFEST_KEYS = frozenset({"schemaVersion", "skill", "actions"}) _REQUIRED_MANIFEST_KEYS = frozenset({"schemaVersion", "skill", "actions"})
_REQUIRED_ACTION_KEYS = frozenset({"id", "label", "description", "placements", "entrypoint"}) _REQUIRED_ACTION_KEYS = frozenset(
{"id", "label", "description", "placements", "entrypoint", "executionProfile"}
)
_TABLE_NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*$")
_FORBIDDEN_BUSINESS_TERMS = ( _FORBIDDEN_BUSINESS_TERMS = (
"wechat", "wechat",
"微信", "微信",
@@ -66,6 +71,88 @@ def _load_actions_schema() -> dict:
return json.load(f) return json.load(f)
def _validate_bind_tables(action_id: str, bind: object) -> list[str]:
errors: list[str] = []
if not isinstance(bind, dict):
return [f"{action_id}: bind must be object"]
if set(bind.keys()) - {"tables"}:
errors.append(f"{action_id}: bind only allows tables, got {sorted(bind.keys())}")
tables = bind.get("tables")
if not isinstance(tables, list) or len(tables) < 1:
errors.append(f"{action_id}: bind.tables must be non-empty array")
return errors
seen: set[str] = set()
for table in tables:
if not isinstance(table, str) or not table.strip():
errors.append(f"{action_id}: bind.tables entries must be non-empty strings")
continue
if table != table.strip() or not _TABLE_NAME_PATTERN.fullmatch(table):
errors.append(f"{action_id}: bind.tables entry {table!r} must be snake_case")
if table in seen:
errors.append(f"{action_id}: bind.tables duplicate {table!r}")
seen.add(table)
return errors
def _load_bindable_business_tables() -> set[str]:
"""在隔离临时数据根下 init_db返回可绑定到 toolbar 的业务表集合。
表必须同时满足:
- SQLite 物理表存在(排除 sqlite_* 与 _jiangchang_* 元数据表)
- ``_jiangchang_tables`` 中有对应行且 ``visible=1``
失败时抛出 RuntimeError带诊断不得静默返回空集供测试 skip。
"""
from db.connection import init_db
from db.display_metadata import METADATA_TABLES
from util.runtime_paths import get_db_path
physical: set[str] = set()
visible_meta: set[str] = set()
try:
with IsolatedDataRoot() as data_root:
init_db()
db_path = get_db_path()
if not os.path.isfile(db_path):
raise RuntimeError(
f"init_db did not create database file under isolated root "
f"{data_root!r}: expected {db_path}"
)
conn = sqlite3.connect(db_path)
try:
cur = conn.cursor()
cur.execute(
"SELECT name FROM sqlite_master "
"WHERE type='table' AND name NOT LIKE 'sqlite_%'"
)
physical = {
str(row[0])
for row in cur.fetchall()
if str(row[0]) not in METADATA_TABLES
}
cur.execute(
"SELECT table_name FROM _jiangchang_tables WHERE visible = 1"
)
visible_meta = {str(row[0]) for row in cur.fetchall()}
finally:
conn.close()
bindable = physical & visible_meta
if not bindable:
raise RuntimeError(
"isolated init_db produced no bindable tables "
f"(physical={sorted(physical)}, visible_meta={sorted(visible_meta)}, "
f"db_path={db_path!r})"
)
return bindable
except RuntimeError:
raise
except Exception as exc:
raise RuntimeError(
"failed to load bindable business tables via isolated init_db: "
f"{type(exc).__name__}: {exc}"
) from exc
class TestActionsManifest(unittest.TestCase): class TestActionsManifest(unittest.TestCase):
def test_manifest_exists_and_schema(self) -> None: def test_manifest_exists_and_schema(self) -> None:
manifest = _load_actions_manifest() manifest = _load_actions_manifest()
@@ -108,6 +195,157 @@ class TestActionsManifest(unittest.TestCase):
for placement in placements: for placement in placements:
self.assertIn(placement, _ALLOWED_PLACEMENTS, msg=f"{action_id} invalid placement {placement!r}") self.assertIn(placement, _ALLOWED_PLACEMENTS, msg=f"{action_id} invalid placement {placement!r}")
def test_every_action_declares_execution_profile(self) -> None:
manifest = _load_actions_manifest()
for action in manifest["actions"]:
profile = action.get("executionProfile")
self.assertIn(
profile,
_ALLOWED_EXECUTION_PROFILES,
msg=f"{action['id']} executionProfile must be sync|async, got {profile!r}",
)
def test_schema_requires_execution_profile_and_defines_bind(self) -> None:
schema = _load_actions_schema()
action_def = schema["$defs"]["action"]
self.assertIn("executionProfile", action_def.get("required") or [])
profile = action_def["properties"]["executionProfile"]
self.assertEqual(set(profile.get("enum") or []), {"sync", "async"})
self.assertIn("bind", schema["$defs"])
self.assertIn("bind", action_def["properties"])
bind_def = schema["$defs"]["bind"]
self.assertEqual(bind_def.get("required"), ["tables"])
self.assertIs(bind_def.get("additionalProperties"), False)
def test_manifest_validates_against_json_schema(self) -> None:
try:
import jsonschema
except ImportError:
self.skipTest("jsonschema not installed")
schema = _load_actions_schema()
manifest = _load_actions_manifest()
jsonschema.validate(instance=manifest, schema=schema)
def test_bind_structure_when_present(self) -> None:
manifest = _load_actions_manifest()
errors: list[str] = []
for action in manifest["actions"]:
if "bind" not in action:
continue
errors.extend(_validate_bind_tables(action["id"], action["bind"]))
self.assertEqual(errors, [], msg="\n".join(errors))
def test_toolbar_actions_require_bind_tables(self) -> None:
manifest = _load_actions_manifest()
errors: list[str] = []
for action in manifest["actions"]:
placements = action.get("placements") or []
if "toolbar" not in placements:
continue
bind = action.get("bind")
if bind is None:
errors.append(f"{action['id']}: toolbar placement requires bind.tables")
continue
errors.extend(_validate_bind_tables(action["id"], bind))
self.assertEqual(errors, [], msg="\n".join(errors))
def test_bindable_business_tables_helper_loads_template_db(self) -> None:
"""helper 本身必须可用:即便默认 manifest 无 toolbar bind也要验证隔离库可读。"""
bindable = _load_bindable_business_tables()
self.assertIn("task_logs", bindable)
self.assertNotIn("_jiangchang_tables", bindable)
self.assertNotIn("_jiangchang_columns", bindable)
def test_bind_tables_exist_in_physical_and_visible_metadata(self) -> None:
bindable = _load_bindable_business_tables()
self.assertTrue(bindable, msg="bindable table set must be non-empty after init_db")
manifest = _load_actions_manifest()
missing: list[str] = []
for action in manifest["actions"]:
bind = action.get("bind")
if not isinstance(bind, dict):
continue
for table in bind.get("tables") or []:
if table not in bindable:
missing.append(
f"{action['id']}: bind.tables entry {table!r} must exist as "
f"physical table AND _jiangchang_tables.visible=1 "
f"(bindable={sorted(bindable)})"
)
self.assertEqual(missing, [], msg="\n".join(missing))
def test_schema_allows_all_placement_execution_profile_combinations(self) -> None:
"""POLICY-SKILL-ACTION-0044 placements × 2 profiles 必须全部通过 Schema。"""
try:
import jsonschema
except ImportError:
self.fail("jsonschema is required to validate placement×executionProfile orthogonality")
schema = _load_actions_schema()
placements = ("toolbar", "cron", "agent", "skill-detail")
profiles = ("sync", "async")
for placement in placements:
for profile in profiles:
action: dict = {
"id": "probe-action",
"label": "正交探测",
"description": "验证 placements 与 executionProfile 无条件耦合",
"placements": [placement],
"executionProfile": profile,
"entrypoint": {"type": "cli", "command": "health", "args": []},
}
if placement == "toolbar":
action["bind"] = {"tables": ["task_logs"]}
manifest = {
"schemaVersion": 1,
"skill": "your-skill-slug",
"actions": [action],
}
with self.subTest(placement=placement, executionProfile=profile):
jsonschema.validate(instance=manifest, schema=schema)
if placement != "toolbar":
self.assertNotIn("bind", action)
def test_schema_rejects_toolbar_without_bind(self) -> None:
try:
import jsonschema
from jsonschema import ValidationError
except ImportError:
self.fail("jsonschema is required")
schema = _load_actions_schema()
manifest = {
"schemaVersion": 1,
"skill": "your-skill-slug",
"actions": [
{
"id": "probe-toolbar",
"label": "缺 bind 探测",
"description": "toolbar 无 bind 应被 Schema 拒绝",
"placements": ["toolbar"],
"executionProfile": "sync",
"entrypoint": {"type": "cli", "command": "health", "args": []},
}
],
}
with self.assertRaises(ValidationError):
jsonschema.validate(instance=manifest, schema=schema)
def test_no_execution_profile_placement_coupling_in_tests(self) -> None:
"""守护:本文件不得引入入口位置与 sync/async 的错误硬耦合断言。"""
path = os.path.join(get_skill_root(), "tests", "test_actions_manifest.py")
with open(path, encoding="utf-8") as f:
text = f.read()
# 拆开拼接,避免本测试源码自身触发字符串扫描。
forbidden_snippets = (
"toolbar " + "只能 async",
"toolbar only " + "async",
'toolbar"' + " and profile != " + '"async"',
'toolbar")' + " and profile != " + '"async"',
"toolbar must be " + "async",
"executionProfile" + " == " + '"async"' + " and " + '"toolbar"',
)
for snippet in forbidden_snippets:
self.assertNotIn(snippet, text)
def test_template_example_does_not_use_reserved_placements(self) -> None: def test_template_example_does_not_use_reserved_placements(self) -> None:
manifest = _load_actions_manifest() manifest = _load_actions_manifest()
for action in manifest["actions"]: for action in manifest["actions"]:
@@ -215,6 +453,17 @@ class TestActionsManifest(unittest.TestCase):
msg=f"{action['id']} uses reserved action fields not supported in template Phase 1: {overlap}", msg=f"{action['id']} uses reserved action fields not supported in template Phase 1: {overlap}",
) )
def test_default_manifest_does_not_place_health_on_toolbar(self) -> None:
"""脚手架默认健康类 Action 不应出现在数据管理 toolbar。"""
manifest = _load_actions_manifest()
for action in manifest["actions"]:
if action["id"] in {"health", "version", "config-path"}:
self.assertNotIn(
"toolbar",
action.get("placements") or [],
msg=f"{action['id']} must not be auto-placed on toolbar",
)
def test_actions_md_documents_strict_vs_host_boundary(self) -> None: def test_actions_md_documents_strict_vs_host_boundary(self) -> None:
path = os.path.join(get_skill_root(), "references", "ACTIONS.md") path = os.path.join(get_skill_root(), "references", "ACTIONS.md")
with open(path, encoding="utf-8") as f: with open(path, encoding="utf-8") as f:
@@ -223,14 +472,23 @@ class TestActionsManifest(unittest.TestCase):
"严格规范", "严格规范",
"向后兼容", "向后兼容",
"Phase 1", "Phase 1",
"bind", "bind.tables",
"concurrency", "concurrency",
"locks", "locks",
"row", "row",
"batch", "batch",
"additionalProperties", "additionalProperties",
"placements",
"executionProfile",
): ):
self.assertIn(marker, text, msg=f"ACTIONS.md missing {marker!r}") self.assertIn(marker, text, msg=f"ACTIONS.md missing {marker!r}")
for forbidden in (
"数据管理 toolbar " + "只挂",
"toolbar " + "只放 async",
"toolbar" + "只挂",
"只挂 **" + "async**",
):
self.assertNotIn(forbidden, text, msg=f"ACTIONS.md must not contain deprecated coupling: {forbidden!r}")
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -27,6 +27,7 @@ class TestCliSmoke(unittest.TestCase):
out = buf.getvalue() out = buf.getvalue()
self.assertIn("通用业务技能模板", out) self.assertIn("通用业务技能模板", out)
self.assertIn("health", out) self.assertIn("health", out)
self.assertIn("init-db", out)
def test_health_zero(self) -> None: def test_health_zero(self) -> None:
old_record = os.environ.get("OPENCLAW_RECORD_VIDEO") old_record = os.environ.get("OPENCLAW_RECORD_VIDEO")
@@ -57,6 +58,26 @@ class TestCliSmoke(unittest.TestCase):
self.assertIn("skill", payload) self.assertIn("skill", payload)
self.assertEqual(payload["skill"], SKILL_SLUG) self.assertEqual(payload["skill"], SKILL_SLUG)
def test_init_db_creates_database_and_is_idempotent(self) -> None:
with IsolatedDataRoot(user_id="_cli_init_db"):
config.reset_cache()
buf = io.StringIO()
with redirect_stdout(buf), redirect_stderr(io.StringIO()):
rc = main(["init-db"])
self.assertEqual(rc, 0)
payload = json.loads(buf.getvalue().strip())
self.assertTrue(payload["ok"])
self.assertEqual(payload["skill"], SKILL_SLUG)
self.assertTrue(os.path.isfile(payload["db_path"]))
buf2 = io.StringIO()
with redirect_stdout(buf2), redirect_stderr(io.StringIO()):
rc2 = main(["init-db"])
self.assertEqual(rc2, 0)
payload2 = json.loads(buf2.getvalue().strip())
self.assertTrue(payload2["ok"])
self.assertEqual(payload2["db_path"], payload["db_path"])
def test_logs_empty_returns_zero(self) -> None: def test_logs_empty_returns_zero(self) -> None:
with IsolatedDataRoot(): with IsolatedDataRoot():
buf = io.StringIO() buf = io.StringIO()

View File

@@ -24,14 +24,18 @@ POLICY_IDS = (
"POLICY-STRUCTURE-001", "POLICY-STRUCTURE-001",
"POLICY-RUNTIME-001", "POLICY-RUNTIME-001",
"POLICY-RUNTIME-002", "POLICY-RUNTIME-002",
"POLICY-RUNTIME-003",
"POLICY-INSTALL-001", "POLICY-INSTALL-001",
"POLICY-CONFIG-001", "POLICY-CONFIG-001",
"POLICY-CONFIG-002", "POLICY-CONFIG-002",
"POLICY-CONFIG-003", "POLICY-CONFIG-003",
"POLICY-CONFIG-004",
"POLICY-TESTING-001", "POLICY-TESTING-001",
"POLICY-TESTING-002", "POLICY-TESTING-002",
"POLICY-RPA-001", "POLICY-RPA-001",
"POLICY-RPA-002", "POLICY-RPA-002",
"POLICY-RPA-003",
"POLICY-RPA-004",
"POLICY-PACKAGING-001", "POLICY-PACKAGING-001",
"POLICY-PACKAGING-002", "POLICY-PACKAGING-002",
"POLICY-DOCS-001", "POLICY-DOCS-001",
@@ -40,6 +44,16 @@ POLICY_IDS = (
"POLICY-LOGGING-003", "POLICY-LOGGING-003",
"POLICY-LOGGING-004", "POLICY-LOGGING-004",
"POLICY-LOGGING-005", "POLICY-LOGGING-005",
"POLICY-CONTROL-001",
"POLICY-CONTROL-002",
"POLICY-CONTROL-003",
"POLICY-DATA-PATH-001",
"POLICY-SKILL-ACTION-001",
"POLICY-SKILL-ACTION-002",
"POLICY-SKILL-ACTION-003",
"POLICY-SKILL-ACTION-004",
"POLICY-ARCH-CORE-001",
"POLICY-DATA-SYNC-001",
) )
STRUCTURE_PATHS = ( STRUCTURE_PATHS = (
@@ -74,6 +88,22 @@ CONFIG_ENV_FORBIDDEN_PATTERNS = (
re.compile(r"\benviron\.get\b"), re.compile(r"\benviron\.get\b"),
) )
CONFIG_004_SOURCE = "development/CONFIG.md §.env.example 注释 = 配置管理用户文案"
CONFIG_004_ENV_KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
CONFIG_004_CJK_RE = re.compile(r"[\u4e00-\u9fff]")
# 注释中禁止出现的开发向指向 / 黑话(大小写不敏感子串)
CONFIG_004_FORBIDDEN_COMMENT_SUBSTRINGS = (
"development/",
"adapter.md",
"rpa.md",
"data_paths.md",
"config.md",
"account-manager",
"见 development",
"adapter 档位",
"adapter档位",
)
TESTING_REAL_TARGET_ALLOWED_ROOT_TESTS = frozenset({"test_adapter_profile_policy.py"}) TESTING_REAL_TARGET_ALLOWED_ROOT_TESTS = frozenset({"test_adapter_profile_policy.py"})
TESTING_001_FORBIDDEN_SUBSTRINGS = ( TESTING_001_FORBIDDEN_SUBSTRINGS = (
@@ -109,6 +139,22 @@ RPA_002_FFMPEG_PATTERNS = (
RPA_002_EXEMPT_REL = "scripts/service/task_run_support.py" RPA_002_EXEMPT_REL = "scripts/service/task_run_support.py"
RPA_003_SOURCE = (
"development/RPA.md §5.3; development/TESTING.md §12; development/POLICY_MATRIX.md"
)
RPA_004_SOURCE = (
"development/RPA.md §0.2; development/ADAPTER.md §兄弟依赖; development/POLICY_MATRIX.md"
)
RPA_004_HEADLESS_KEY_RE = re.compile(
r"(?m)^\s*OPENCLAW_BROWSER_HEADLESS\s*=\s*([^\s#]+)"
)
RPA_004_LAUNCH_MARKERS = (
"launch_persistent_context",
"launch_persistent_browser",
)
RPA_004_PICK_MARKER = "pick_web_account"
LOGGING_001_SOURCE = "development/LOGGING.md; development/RUNTIME.md" LOGGING_001_SOURCE = "development/LOGGING.md; development/RUNTIME.md"
LOGGING_002_SOURCE = "development/LOGGING.md; development/DEVELOPMENT.md" LOGGING_002_SOURCE = "development/LOGGING.md; development/DEVELOPMENT.md"
LOGGING_003_SOURCE = "development/LOGGING.md" LOGGING_003_SOURCE = "development/LOGGING.md"
@@ -133,6 +179,77 @@ def _policy_msg(policy_id: str, source: str, detail: str) -> str:
return f"{policy_id} [{source}]: {detail}" return f"{policy_id} [{source}]: {detail}"
def _strip_env_quotes(value: str) -> str:
trimmed = value.strip()
if (
(trimmed.startswith('"') and trimmed.endswith('"'))
or (trimmed.startswith("'") and trimmed.endswith("'"))
):
return trimmed[1:-1]
return trimmed
def _iter_env_example_active_entries(path: str):
"""Yield (lineno, key, value, header_comments, inline_comment) for active KEY= lines."""
pending: list[str] = []
with open(path, encoding="utf-8") as handle:
for lineno, line in enumerate(handle, 1):
stripped = line.strip()
if not stripped:
pending = []
continue
if stripped.startswith("#"):
pending.append(stripped.lstrip("#").strip())
continue
eq = stripped.find("=")
if eq <= 0:
pending = []
continue
key = stripped[:eq].strip()
if not CONFIG_004_ENV_KEY_RE.match(key):
pending = []
continue
rest = stripped[eq + 1 :]
inline: str | None = None
if not rest.startswith('"') and not rest.startswith("'"):
hash_at = rest.find(" #")
if hash_at >= 0:
inline = rest[hash_at + 2 :].strip()
rest = rest[:hash_at]
value = _strip_env_quotes(rest)
yield lineno, key, value, list(pending), inline
pending = []
def _config_004_comment_offenders(path: str) -> list[str]:
offenders: list[str] = []
for lineno, key, _value, headers, inline in _iter_env_example_active_entries(path):
if not headers:
offenders.append(
f".env.example:{lineno}: {key}= 缺少行头注释(须用中文说明「是什么」)"
)
elif not any(CONFIG_004_CJK_RE.search(part) for part in headers):
offenders.append(
f".env.example:{lineno}: {key}= 行头注释须含中文(说明「是什么」)"
)
if not inline:
offenders.append(
f".env.example:{lineno}: {key}= 缺少行尾注释(须用中文说明「怎么填」)"
)
elif not CONFIG_004_CJK_RE.search(inline):
offenders.append(
f".env.example:{lineno}: {key}= 行尾注释须含中文(说明「怎么填」)"
)
combined = "\n".join([*headers, inline or ""]).lower()
for token in CONFIG_004_FORBIDDEN_COMMENT_SUBSTRINGS:
if token.lower() in combined:
offenders.append(
f".env.example:{lineno}: {key}= 注释禁止含 {token!r}(面向用户,勿写开发文档指向/黑话)"
)
break
return offenders
def _rel(skill_root: str, path: str) -> str: def _rel(skill_root: str, path: str) -> str:
return os.path.relpath(path, skill_root).replace("\\", "/") return os.path.relpath(path, skill_root).replace("\\", "/")
@@ -369,6 +486,23 @@ class TestPolicyConfig003(unittest.TestCase):
) )
class TestPolicyConfig004(unittest.TestCase):
def test_env_example_comments_are_user_facing(self) -> None:
path = os.path.join(get_skill_root(), ".env.example")
self.assertTrue(os.path.isfile(path), msg=".env.example missing")
offenders = _config_004_comment_offenders(path)
self.assertEqual(
offenders,
[],
msg=_policy_msg(
"POLICY-CONFIG-004",
CONFIG_004_SOURCE,
"\n".join(offenders)
or "every active KEY in .env.example needs Chinese header+inline comments",
),
)
class TestPolicyTesting001(unittest.TestCase): class TestPolicyTesting001(unittest.TestCase):
def test_root_tests_do_not_hardcode_real_targets(self) -> None: def test_root_tests_do_not_hardcode_real_targets(self) -> None:
skill_root = get_skill_root() skill_root = get_skill_root()
@@ -470,6 +604,71 @@ class TestPolicyRpa002(unittest.TestCase):
) )
class TestPolicyRpa003(unittest.TestCase):
def test_service_layer_retains_video_session_integration(self) -> None:
skill_root = get_skill_root()
service_files = _walk_files(skill_root, "scripts/service", suffix=".py")
self.assertTrue(service_files, msg="scripts/service/*.py not found")
combined = "\n".join(_read_text(path) for path in service_files)
missing: list[str] = []
if "RpaVideoSession" not in combined:
missing.append("RpaVideoSession")
if "video.add_step" not in combined and ".add_step(" not in combined:
missing.append("video.add_step or .add_step(")
if "merge_video_into_result_summary" not in combined:
missing.append("merge_video_into_result_summary")
self.assertEqual(
missing,
[],
msg=_policy_msg(
"POLICY-RPA-003",
RPA_003_SOURCE,
"scripts/service/*.py missing: " + ", ".join(missing),
),
)
class TestPolicyRpa004(unittest.TestCase):
def test_env_example_browser_headless_defaults_to_headed(self) -> None:
skill_root = get_skill_root()
env_path = os.path.join(skill_root, ".env.example")
self.assertTrue(os.path.isfile(env_path), msg=".env.example missing")
text = _read_text(env_path)
match = RPA_004_HEADLESS_KEY_RE.search(text)
if match is None:
return
value = match.group(1).strip().strip("\"'")
self.assertEqual(
value,
"0",
msg=_policy_msg(
"POLICY-RPA-004",
RPA_004_SOURCE,
f".env.example OPENCLAW_BROWSER_HEADLESS must default to 0 (headed), got {value!r}",
),
)
def test_launch_persistent_requires_pick_web_account(self) -> None:
skill_root = get_skill_root()
script_texts = [
_read_text(path) for path in _walk_files(skill_root, "scripts", suffix=".py")
]
combined = "\n".join(script_texts)
uses_launch = any(marker in combined for marker in RPA_004_LAUNCH_MARKERS)
if not uses_launch:
return
self.assertIn(
RPA_004_PICK_MARKER,
combined,
msg=_policy_msg(
"POLICY-RPA-004",
RPA_004_SOURCE,
"scripts/ uses launch_persistent_* but missing pick_web_account "
"(must obtain profile_dir before opening browser)",
),
)
def _scan_sensitive_logging_assignments(skill_root: str) -> list[str]: def _scan_sensitive_logging_assignments(skill_root: str) -> list[str]:
offenders: list[str] = [] offenders: list[str] = []
for path in _walk_files(skill_root, "scripts", suffix=".py"): for path in _walk_files(skill_root, "scripts", suffix=".py"):
@@ -590,6 +789,488 @@ class TestPolicyLogging005(unittest.TestCase):
) )
class TestPolicyControl001(unittest.TestCase):
def test_no_util_progress_module(self) -> None:
skill_root = get_skill_root()
path = os.path.join(skill_root, "scripts", "util", "progress.py")
self.assertFalse(
os.path.isfile(path),
msg=_policy_msg(
"POLICY-CONTROL-001",
"development/LOGGING.md §2.5; development/RPA.md §0.1",
"scripts/util/progress.py must not exist",
),
)
class TestPolicyControl002(unittest.TestCase):
def test_task_service_uses_job_context_and_finish(self) -> None:
skill_root = get_skill_root()
path = os.path.join(skill_root, "scripts", "service", "task_service.py")
text = _read_text(path)
rel = _rel(skill_root, path)
missing: list[str] = []
if "job_context(" not in text:
missing.append("job_context(")
if "finish(" not in text:
missing.append("finish(")
self.assertEqual(
missing,
[],
msg=_policy_msg(
"POLICY-CONTROL-002",
"development/LOGGING.md §2.5、§7",
f"{rel} missing: " + ", ".join(missing),
),
)
class TestPolicyControl003(unittest.TestCase):
def test_service_layer_has_no_bare_asyncio_sleep(self) -> None:
skill_root = get_skill_root()
offenders: list[str] = []
for path in _walk_files(skill_root, "scripts/service", suffix=".py"):
rel = _rel(skill_root, path)
for lineno, line in enumerate(_read_text(path).splitlines(), 1):
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if "asyncio.sleep" in stripped:
offenders.append(f"{rel}:{lineno}: {stripped}")
self.assertEqual(
offenders,
[],
msg=_policy_msg(
"POLICY-CONTROL-003",
"development/RPA.md §0.1",
"use interruptible_sleep instead:\n" + "\n".join(offenders),
),
)
class TestPolicyDataPath001(unittest.TestCase):
def test_env_example_has_no_cwd_relative_paths(self) -> None:
path = os.path.join(get_skill_root(), ".env.example")
offenders: list[str] = []
with open(path, encoding="utf-8") as f:
for lineno, line in enumerate(f, 1):
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
active = stripped.split("#", 1)[0].strip()
if re.search(r"=\s*\./", active):
offenders.append(f".env.example:{lineno}: {active}")
self.assertEqual(
offenders,
[],
msg=_policy_msg(
"POLICY-DATA-PATH-001",
"development/DATA_PATHS.md",
"\n".join(offenders) or "CWD-relative ./ paths in .env.example",
),
)
def test_runtime_paths_exposes_resolve_data_path(self) -> None:
import util.runtime_paths as rp
self.assertTrue(callable(getattr(rp, "resolve_data_path", None)))
self.assertTrue(callable(getattr(rp, "list_resolved_data_paths", None)))
def test_business_scripts_do_not_abspath_config_get(self) -> None:
skill_root = get_skill_root()
pattern = re.compile(r"os\.path\.abspath\s*\(\s*config\.get\b")
offenders: list[str] = []
for rel in _walk_files(skill_root, "scripts", suffix=".py"):
if rel.replace("\\", "/") == "scripts/util/runtime_paths.py":
continue
text = _read_text(os.path.join(skill_root, rel))
for lineno, line in enumerate(text.splitlines(), 1):
if line.strip().startswith("#"):
continue
if pattern.search(line):
offenders.append(f"{rel}:{lineno}: {line.strip()}")
self.assertEqual(
offenders,
[],
msg=_policy_msg(
"POLICY-DATA-PATH-001",
"development/DATA_PATHS.md",
"\n".join(offenders),
),
)
_TEMPLATE_PLACEHOLDER_SLUG = "your-skill-slug"
_RPA_SESSION_TOKENS = ("RpaVideoSession",)
def _service_has_rpa_video_session(skill_root: str) -> bool:
service_dir = os.path.join(skill_root, "scripts", "service")
if not os.path.isdir(service_dir):
return False
for rel in _walk_files(skill_root, "scripts/service", suffix=".py"):
text = _read_text(os.path.join(skill_root, rel))
if any(token in text for token in _RPA_SESSION_TOKENS):
return True
return False
def _load_actions_json(skill_root: str) -> dict | None:
path = os.path.join(skill_root, "assets", "actions.json")
if not os.path.isfile(path):
return None
import json
with open(path, encoding="utf-8") as f:
return json.load(f)
class TestPolicySkillAction001(unittest.TestCase):
def test_skill_action_runtime_doc_exists(self) -> None:
path = os.path.join(get_skill_root(), "development", "SKILL_ACTION_RUNTIME.md")
self.assertTrue(
os.path.isfile(path),
msg=_policy_msg(
"POLICY-SKILL-ACTION-001",
"development/SKILL_ACTION_RUNTIME.md",
"file missing",
),
)
text = _read_text(path)
for marker in ("executionProfile", "async", "任务中心", "run_skill_action"):
self.assertIn(
marker,
text,
msg=_policy_msg(
"POLICY-SKILL-ACTION-001",
"development/SKILL_ACTION_RUNTIME.md",
f"missing marker {marker!r}",
),
)
def test_schema_defines_execution_profile(self) -> None:
import json
path = os.path.join(get_skill_root(), "assets", "schemas", "skill-actions.schema.json")
self.assertTrue(os.path.isfile(path))
with open(path, encoding="utf-8") as f:
schema = json.load(f)
action_props = schema.get("$defs", {}).get("action", {}).get("properties", {})
profile = action_props.get("executionProfile")
self.assertIsInstance(
profile,
dict,
msg=_policy_msg(
"POLICY-SKILL-ACTION-001",
"assets/schemas/skill-actions.schema.json",
"action.properties.executionProfile missing",
),
)
self.assertEqual(set(profile.get("enum") or []), {"sync", "async"})
def test_actions_md_documents_execution_profile(self) -> None:
path = os.path.join(get_skill_root(), "references", "ACTIONS.md")
text = _read_text(path)
for marker in ("executionProfile", "async", "任务中心", "SKILL_ACTION_RUNTIME"):
self.assertIn(
marker,
text,
msg=_policy_msg(
"POLICY-SKILL-ACTION-001",
"references/ACTIONS.md",
f"missing marker {marker!r}",
),
)
def test_actions_json_actions_declare_execution_profile(self) -> None:
skill_root = get_skill_root()
manifest = _load_actions_json(skill_root)
if manifest is None:
return
offenders: list[str] = []
for action in manifest.get("actions") or []:
action_id = action.get("id", "?")
profile = action.get("executionProfile")
if profile not in ("sync", "async"):
offenders.append(f"{action_id}: executionProfile={profile!r}")
self.assertEqual(
offenders,
[],
msg=_policy_msg(
"POLICY-SKILL-ACTION-001",
"assets/actions.json",
"every action must set executionProfile to sync|async:\n" + "\n".join(offenders),
),
)
def test_business_rpa_skill_has_async_agent_action(self) -> None:
from util.constants import SKILL_SLUG
skill_root = get_skill_root()
if SKILL_SLUG == _TEMPLATE_PLACEHOLDER_SLUG:
self.skipTest("template placeholder slug skips business RPA action check")
if not _service_has_rpa_video_session(skill_root):
self.skipTest("no RpaVideoSession in scripts/service")
manifest = _load_actions_json(skill_root)
self.assertIsNotNone(
manifest,
msg=_policy_msg(
"POLICY-SKILL-ACTION-001",
"assets/actions.json",
"RPA skill must provide assets/actions.json",
),
)
found = False
for action in manifest.get("actions") or []:
placements = set(action.get("placements") or [])
if action.get("executionProfile") == "async" and "agent" in placements:
found = True
break
self.assertTrue(
found,
msg=_policy_msg(
"POLICY-SKILL-ACTION-001",
"assets/actions.json",
"RPA business skill needs at least one action with executionProfile=async and placements containing agent",
),
)
class TestPolicySkillAction002(unittest.TestCase):
def test_schema_requires_execution_profile(self) -> None:
import json
path = os.path.join(get_skill_root(), "assets", "schemas", "skill-actions.schema.json")
with open(path, encoding="utf-8") as f:
schema = json.load(f)
action = schema["$defs"]["action"]
self.assertIn(
"executionProfile",
action.get("required") or [],
msg=_policy_msg(
"POLICY-SKILL-ACTION-002",
"assets/schemas/skill-actions.schema.json",
"executionProfile must be in action.required",
),
)
self.assertEqual(set(action["properties"]["executionProfile"].get("enum") or []), {"sync", "async"})
def test_manifest_actions_declare_execution_profile(self) -> None:
manifest = _load_actions_json(get_skill_root())
if manifest is None:
return
offenders: list[str] = []
for action in manifest.get("actions") or []:
profile = action.get("executionProfile")
if profile not in ("sync", "async"):
offenders.append(f"{action.get('id', '?')}: {profile!r}")
self.assertEqual(
offenders,
[],
msg=_policy_msg(
"POLICY-SKILL-ACTION-002",
"assets/actions.json",
"every action must set executionProfile to sync|async:\n" + "\n".join(offenders),
),
)
class TestPolicySkillAction003(unittest.TestCase):
def test_schema_defines_bind_and_toolbar_requires_it(self) -> None:
import json
path = os.path.join(get_skill_root(), "assets", "schemas", "skill-actions.schema.json")
with open(path, encoding="utf-8") as f:
schema = json.load(f)
self.assertIn(
"bind",
schema.get("$defs", {}),
msg=_policy_msg(
"POLICY-SKILL-ACTION-003",
"assets/schemas/skill-actions.schema.json",
"$defs.bind missing",
),
)
action = schema["$defs"]["action"]
self.assertIn("bind", action.get("properties", {}))
then_required = (action.get("then") or {}).get("required") or []
self.assertIn(
"bind",
then_required,
msg=_policy_msg(
"POLICY-SKILL-ACTION-003",
"assets/schemas/skill-actions.schema.json",
"action if/then must require bind when placements contains toolbar",
),
)
def test_toolbar_actions_have_bind_tables(self) -> None:
import re
table_re = re.compile(r"^[a-z][a-z0-9_]*$")
manifest = _load_actions_json(get_skill_root())
if manifest is None:
return
offenders: list[str] = []
for action in manifest.get("actions") or []:
if "toolbar" not in (action.get("placements") or []):
continue
bind = action.get("bind")
tables = bind.get("tables") if isinstance(bind, dict) else None
if not isinstance(tables, list) or not tables:
offenders.append(f"{action.get('id')}: missing bind.tables")
continue
if len(tables) != len(set(tables)):
offenders.append(f"{action.get('id')}: duplicate bind.tables")
for table in tables:
if not isinstance(table, str) or not table_re.fullmatch(table):
offenders.append(f"{action.get('id')}: invalid table {table!r}")
self.assertEqual(
offenders,
[],
msg=_policy_msg(
"POLICY-SKILL-ACTION-003",
"assets/actions.json",
"toolbar actions need legal bind.tables:\n" + "\n".join(offenders),
),
)
class TestPolicySkillAction004(unittest.TestCase):
def _forbidden_coupling_phrases(self) -> tuple[str, ...]:
# 拆开拼接,避免本测试源码或废止说明原文触发误报。
return (
"数据管理 toolbar " + "只挂",
"toolbar " + "只放 async",
"只挂 **" + "async** action",
"toolbar " + "只能 async",
"toolbar only " + "async",
)
def test_docs_do_not_couple_toolbar_to_async(self) -> None:
skill_root = get_skill_root()
paths = (
os.path.join(skill_root, "references", "ACTIONS.md"),
os.path.join(skill_root, "development", "SKILL_ACTION_RUNTIME.md"),
os.path.join(skill_root, "SKILL.md"),
)
hits: list[str] = []
for path in paths:
text = _read_text(path)
for phrase in self._forbidden_coupling_phrases():
if phrase in text:
hits.append(f"{os.path.relpath(path, skill_root)}: {phrase!r}")
self.assertEqual(
hits,
[],
msg=_policy_msg(
"POLICY-SKILL-ACTION-004",
"docs",
"placements must stay orthogonal to executionProfile:\n" + "\n".join(hits),
),
)
def test_runtime_doc_states_orthogonality(self) -> None:
text = _read_text(os.path.join(get_skill_root(), "development", "SKILL_ACTION_RUNTIME.md"))
for marker in ("正交", "sync|async", "toolbar"):
self.assertIn(
marker,
text,
msg=_policy_msg(
"POLICY-SKILL-ACTION-004",
"development/SKILL_ACTION_RUNTIME.md",
f"missing marker {marker!r}",
),
)
def test_schema_then_only_requires_bind_not_execution_profile(self) -> None:
"""toolbar→bind 的 if/then 不得顺带约束 executionProfile。"""
import json
path = os.path.join(get_skill_root(), "assets", "schemas", "skill-actions.schema.json")
with open(path, encoding="utf-8") as f:
schema = json.load(f)
action = schema["$defs"]["action"]
then = action.get("then") or {}
self.assertEqual(
then.get("required"),
["bind"],
msg=_policy_msg(
"POLICY-SKILL-ACTION-004",
"assets/schemas/skill-actions.schema.json",
"action.then must only require bind",
),
)
self.assertNotIn("properties", then)
self.assertNotIn("else", action)
matrix_test = os.path.join(get_skill_root(), "tests", "test_actions_manifest.py")
text = _read_text(matrix_test)
self.assertIn(
"test_schema_allows_all_placement_execution_profile_combinations",
text,
msg=_policy_msg(
"POLICY-SKILL-ACTION-004",
"tests/test_actions_manifest.py",
"missing Schema 4×2 orthogonality matrix test",
),
)
class TestPolicyArchCore001(unittest.TestCase):
def test_docs_declare_single_core_multi_entry(self) -> None:
skill_root = get_skill_root()
text = (
_read_text(os.path.join(skill_root, "development", "DEVELOPMENT.md"))
+ "\n"
+ _read_text(os.path.join(skill_root, "development", "SKILL_ACTION_RUNTIME.md"))
+ "\n"
+ _read_text(os.path.join(skill_root, "SKILL.md"))
)
for marker in ("单业务内核", "多入口", "domain service"):
self.assertIn(
marker,
text,
msg=_policy_msg(
"POLICY-ARCH-CORE-001",
"development docs / SKILL.md",
f"missing architecture marker {marker!r}",
),
)
sample = os.path.join(skill_root, "tests", "samples", "test_action_core_contract.py.sample")
self.assertTrue(
os.path.isfile(sample),
msg=_policy_msg(
"POLICY-ARCH-CORE-001",
"tests/samples/test_action_core_contract.py.sample",
"sample contract missing",
),
)
class TestPolicyDataSync001(unittest.TestCase):
def test_schema_md_declares_sync_semantics(self) -> None:
text = _read_text(os.path.join(get_skill_root(), "references", "SCHEMA.md"))
for marker in ("幂等", "空结果", "事务", "inserted", "导出当前数据表"):
self.assertIn(
marker,
text,
msg=_policy_msg(
"POLICY-DATA-SYNC-001",
"references/SCHEMA.md",
f"missing sync marker {marker!r}",
),
)
sample = os.path.join(get_skill_root(), "tests", "samples", "test_sync_contract.py.sample")
self.assertTrue(
os.path.isfile(sample),
msg=_policy_msg(
"POLICY-DATA-SYNC-001",
"tests/samples/test_sync_contract.py.sample",
"sample contract missing",
),
)
class TestPolicyDocs001(unittest.TestCase): class TestPolicyDocs001(unittest.TestCase):
def test_policy_matrix_exists_and_lists_policy_ids(self) -> None: def test_policy_matrix_exists_and_lists_policy_ids(self) -> None:
skill_root = get_skill_root() skill_root = get_skill_root()

View File

@@ -141,6 +141,47 @@ class TestDocsStandards(unittest.TestCase):
msg="SKILL.md must state README.md is user-facing documentation", msg="SKILL.md must state README.md is user-facing documentation",
) )
def test_market_tab_docs_exist(self) -> None:
root = get_skill_root()
for name in ("README.md", "TUTORIAL.md", "DEMO.md", "CHANGELOG.md"):
path = os.path.join(root, name)
self.assertTrue(os.path.isfile(path), msg=f"{name} must exist at skill root")
def test_demo_md_frontmatter_has_demo_video_url(self) -> None:
text = self._read("DEMO.md")
self.assertTrue(text.startswith("---"), "DEMO.md must start with YAML frontmatter")
frontmatter = self._parse_frontmatter(text)
self.assertIn(
"demo_video_url:",
frontmatter,
"DEMO.md frontmatter must include demo_video_url",
)
def test_changelog_has_section_for_skill_version(self) -> None:
skill_fm = self._parse_frontmatter(self._read("SKILL.md"))
match = re.search(r"(?m)^version:\s*[\"']?([0-9]+\.[0-9]+\.[0-9]+)", skill_fm)
self.assertIsNotNone(match, "SKILL.md must declare semver version")
version = match.group(1)
changelog = self._read("CHANGELOG.md")
self.assertRegex(
changelog,
rf"(?m)^##\s*\[?v?{re.escape(version)}\]?",
msg=f"CHANGELOG.md must include a ## section for version {version}",
)
def test_skill_md_documents_market_four_tabs(self) -> None:
text = self._read("SKILL.md")
for name in ("TUTORIAL.md", "DEMO.md", "CHANGELOG.md", "readme_md", "tutorial_md"):
self.assertIn(name, text, msg=f"SKILL.md must document market material {name}")
def test_development_md_documents_market_four_tabs(self) -> None:
text = self._read("development/DEVELOPMENT.md")
self.assertIn("TUTORIAL.md", text)
self.assertIn("DEMO.md", text)
self.assertIn("CHANGELOG.md", text)
self.assertIn("demo_video_url", text)
self.assertIn("tutorial_md", text)
def test_naming_md_exists_and_covers_standards(self) -> None: def test_naming_md_exists_and_covers_standards(self) -> None:
text = self._read("development/NAMING.md") text = self._read("development/NAMING.md")
self.assertIn("verb-noun-platform", text) self.assertIn("verb-noun-platform", text)
@@ -172,7 +213,7 @@ class TestDocsStandards(unittest.TestCase):
self.assertIn("--no-sandbox", text) self.assertIn("--no-sandbox", text)
self.assertIn("--disable-blink-features=AutomationControlled", text) self.assertIn("--disable-blink-features=AutomationControlled", text)
self.assertIn("RpaVideoSession", text) self.assertIn("RpaVideoSession", text)
self.assertIn("1.0.17", text) self.assertIn("1.2.0", text)
def test_rpa_md_forbids_rpa_helpers_import(self) -> None: def test_rpa_md_forbids_rpa_helpers_import(self) -> None:
text = self._read("development/RPA.md") text = self._read("development/RPA.md")
@@ -197,6 +238,17 @@ class TestDocsStandards(unittest.TestCase):
msg="RPA.md must mention jc2009 / industry simulator / portal gate", msg="RPA.md must mention jc2009 / industry simulator / portal gate",
) )
def test_rpa_md_covers_web_profile_headed_and_login_split(self) -> None:
text = self._read("development/RPA.md")
self.assertIn("0.2", text)
self.assertIn("profile_dir", text)
self.assertIn("POLICY-RPA-004", text)
self.assertIn("有头", text)
self.assertTrue(
"登录不全局强制" in text or "登录 ≠ Profile" in text or "登录≠Profile" in text,
msg="RPA.md §0.2 must separate site-login from Profile requirement",
)
def test_simulator_example_readme_covers_async_and_account_manager(self) -> None: def test_simulator_example_readme_covers_async_and_account_manager(self) -> None:
text = self._read("examples/simulator_browser_rpa/README.md") text = self._read("examples/simulator_browser_rpa/README.md")
self.assertIn("async", text.lower()) self.assertIn("async", text.lower())
@@ -302,10 +354,71 @@ class TestDocsStandards(unittest.TestCase):
self.assertNotIn("ALLOW_" + "REAL_" + "API", text) self.assertNotIn("ALLOW_" + "REAL_" + "API", text)
self.assertNotIn("ALLOW_WRITE_ACTIONS", text) self.assertNotIn("ALLOW_WRITE_ACTIONS", text)
def test_cli_md_mentions_shared_python_runtime(self) -> None: def test_cli_md_requires_shared_python_not_uv_run(self) -> None:
text = self._read("references/CLI.md") text = self._read("references/CLI.md")
self.assertIn("python-runtime", text) self.assertIn("python-runtime", text)
self.assertIn("python {baseDir}/scripts/main.py", text)
self.assertNotIn("JIANGCHANG_PYTHON_EXE", text)
self.assertIn("禁止", text)
self.assertIn("uv run python", text) self.assertIn("uv run python", text)
self.assertNotRegex(
text,
r"(?m)^(?!\*\*禁止\*\*).*\*\*建议\*\*.*uv run python",
msg="CLI.md must not recommend uv run for skill scripts",
)
def test_cli_md_has_agent_routing_tables(self) -> None:
text = self._read("references/CLI.md")
self.assertIn("短 CLI 白名单", text)
self.assertIn("Action 强制黑名单", text)
self.assertIn("run_skill_action", text)
def test_skill_md_requires_shared_python_not_uv_run(self) -> None:
text = self._read("SKILL.md")
self.assertIn("python {baseDir}/scripts/main.py", text)
self.assertNotIn("JIANGCHANG_PYTHON_EXE", text)
self.assertIn("uv run python", text)
self.assertIn("禁止", text)
self.assertIn("run_skill_action", text)
self.assertIn("executionProfile", text)
self.assertTrue(
"任务中心" in text and "无关" in text,
msg="SKILL.md must state Task Center is independent of entry point",
)
def test_skill_md_has_intent_routing_table(self) -> None:
text = self._read("SKILL.md")
self.assertIn("用户意图路由表", text)
self.assertIn("用户意图", text)
self.assertIn("准备 vs 执行", text)
def test_skill_md_how_to_forbids_cli_paste(self) -> None:
text = self._read("SKILL.md")
self.assertIn("回答「怎么用", text)
self.assertIn("禁止", text)
self.assertTrue(
"粘贴" in text and "python" in text,
msg="SKILL.md must forbid pasting python CLI when answering how-to",
)
self.assertTrue(
"dir" in text or "" in text,
msg="SKILL.md must discourage directory probing for how-to answers",
)
def test_actions_md_has_async_side_effect_checklist(self) -> None:
text = self._read("references/ACTIONS.md")
self.assertIn("最小组合", text)
self.assertIn("confirmation.message", text)
self.assertIn("用户意图路由表", text)
def test_actions_md_states_profile_not_entry_for_task_center(self) -> None:
text = self._read("references/ACTIONS.md")
self.assertIn("executionProfile", text)
self.assertIn("任务中心", text)
self.assertTrue(
"无关" in text or "orthogonal" in text.lower() or "正交" in text,
msg="ACTIONS.md must keep placements orthogonal to Task Center",
)
def test_testing_md_mentions_pytest_txt_collection_guard(self) -> None: def test_testing_md_mentions_pytest_txt_collection_guard(self) -> None:
text = self._read("development/TESTING.md") text = self._read("development/TESTING.md")

View File

@@ -83,16 +83,16 @@ class TestPlatformImportSource(unittest.TestCase):
) )
) )
def test_platform_kit_min_version_is_1_0_14(self) -> None: def test_platform_kit_min_version_is_at_least_declared(self) -> None:
from jiangchang_skill_core import version_ge from jiangchang_skill_core import version_ge
from util.constants import PLATFORM_KIT_MIN_VERSION from util.constants import PLATFORM_KIT_MIN_VERSION
self.assertEqual(PLATFORM_KIT_MIN_VERSION, "1.0.17") self.assertEqual(PLATFORM_KIT_MIN_VERSION, "1.2.2")
md_path = os.path.join(get_skill_root(), "SKILL.md") md_path = os.path.join(get_skill_root(), "SKILL.md")
with open(md_path, encoding="utf-8") as f: with open(md_path, encoding="utf-8") as f:
md = f.read() md = f.read()
self.assertEqual(_parse_platform_kit_min_version(md), "1.0.17") self.assertEqual(_parse_platform_kit_min_version(md), "1.2.2")
req_path = os.path.join(get_skill_root(), "requirements.txt") req_path = os.path.join(get_skill_root(), "requirements.txt")
with open(req_path, encoding="utf-8") as f: with open(req_path, encoding="utf-8") as f:

View File

@@ -82,6 +82,68 @@ class TestRuntimePaths(unittest.TestCase):
self.assertTrue(os.path.normpath(data_dir).startswith(os.path.normpath(tmp))) self.assertTrue(os.path.normpath(data_dir).startswith(os.path.normpath(tmp)))
self.assertIn("_test", data_dir.replace("\\", "/")) self.assertIn("_test", data_dir.replace("\\", "/"))
def test_resolve_data_path_defaults_under_skill_data_dir(self) -> None:
with IsolatedDataRoot() as tmp:
import importlib
import util.runtime_paths as rp
importlib.reload(rp)
path = rp.resolve_data_path(None, "downloads", create=True)
norm = os.path.normcase(os.path.normpath(path))
norm_tmp = os.path.normcase(os.path.normpath(tmp))
self.assertTrue(norm.startswith(norm_tmp))
self.assertTrue(norm.endswith(os.path.normcase(os.path.join("downloads"))))
def test_resolve_data_path_relative_uses_data_dir_not_cwd(self) -> None:
with IsolatedDataRoot() as tmp:
import importlib
import util.runtime_paths as rp
importlib.reload(rp)
os.environ["SKILL_DOWNLOAD_DIR"] = "downloads/videos"
from jiangchang_skill_core import config
config.reset_cache()
importlib.reload(rp)
path = rp.resolve_data_path("SKILL_DOWNLOAD_DIR", "downloads", create=False)
norm = os.path.normcase(os.path.normpath(path))
self.assertIn(os.path.normcase("downloads"), norm)
self.assertIn(os.path.normcase("videos"), norm)
self.assertTrue(norm.startswith(os.path.normcase(os.path.normpath(tmp))))
os.environ.pop("SKILL_DOWNLOAD_DIR", None)
config.reset_cache()
def test_resolve_input_path_relative_under_imports(self) -> None:
with IsolatedDataRoot() as tmp:
import importlib
import util.runtime_paths as rp
importlib.reload(rp)
resolved = rp.resolve_input_path("urls.txt", create_parent=True)
norm = os.path.normcase(os.path.normpath(resolved))
self.assertIn(os.path.normcase("imports"), norm)
self.assertTrue(norm.startswith(os.path.normcase(os.path.normpath(tmp))))
def test_list_resolved_data_paths_keys(self) -> None:
with IsolatedDataRoot():
import importlib
import util.runtime_paths as rp
importlib.reload(rp)
paths = rp.list_resolved_data_paths()
for key in (
"skill_data_dir",
"downloads_dir",
"imports_dir",
"exports_dir",
):
self.assertIn(key, paths)
self.assertTrue(paths[key])
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@@ -34,7 +34,7 @@ FORBIDDEN_PHRASES = (
POSITIVE_MARKERS = ( POSITIVE_MARKERS = (
"jiangchang-platform-kit", "jiangchang-platform-kit",
"1.0.17", "1.2.2",
"共享 runtime", "共享 runtime",
) )

View File

@@ -15,6 +15,46 @@ from _support import IsolatedDataRoot, get_skill_root
from jiangchang_skill_core import config from jiangchang_skill_core import config
def _active_env_value(text: str, key: str) -> str | None:
"""Return the active (non-comment) KEY=value line from .env-style text."""
prefix = f"{key}="
for line in text.splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
active = stripped.split("#", 1)[0].strip()
if active.startswith(prefix):
return active
return None
def _combined_service_source(skill_root: str | None = None) -> str:
"""Merge scripts/service/*.py source (excludes __pycache__)."""
root = skill_root or get_skill_root()
service_dir = os.path.join(root, "scripts", "service")
parts: list[str] = []
for dirpath, dirnames, filenames in os.walk(service_dir):
dirnames[:] = [d for d in dirnames if d != "__pycache__"]
for name in sorted(filenames):
if not name.endswith(".py"):
continue
path = os.path.join(dirpath, name)
with open(path, encoding="utf-8") as f:
parts.append(f.read())
return "\n".join(parts)
def _missing_video_integration_tokens(service_text: str) -> list[str]:
missing: list[str] = []
if "RpaVideoSession" not in service_text:
missing.append("RpaVideoSession")
if "video.add_step" not in service_text and ".add_step(" not in service_text:
missing.append("video.add_step or .add_step(")
if "merge_video_into_result_summary" not in service_text:
missing.append("merge_video_into_result_summary")
return missing
class TestEnvExampleVideoDefaults(unittest.TestCase): class TestEnvExampleVideoDefaults(unittest.TestCase):
def test_env_example_contains_required_keys(self) -> None: def test_env_example_contains_required_keys(self) -> None:
path = os.path.join(get_skill_root(), ".env.example") path = os.path.join(get_skill_root(), ".env.example")
@@ -22,13 +62,45 @@ class TestEnvExampleVideoDefaults(unittest.TestCase):
text = f.read() text = f.read()
for key in ( for key in (
"OPENCLAW_" + "TEST_TARGET=mock", "OPENCLAW_" + "TEST_TARGET=mock",
"OPENCLAW_RECORD_VIDEO=1", "OPENCLAW_RECORD_VIDEO=0",
"OPENCLAW_ARTIFACTS_ON_FAILURE=1", "OPENCLAW_ARTIFACTS_ON_FAILURE=1",
"OPENCLAW_BROWSER_HEADLESS=0", "OPENCLAW_BROWSER_HEADLESS=0",
"OPENCLAW_PLAYWRIGHT_STEALTH=1", "OPENCLAW_PLAYWRIGHT_STEALTH=1",
): ):
self.assertIn(key, text, msg=f"missing {key!r} in .env.example") self.assertIn(key, text, msg=f"missing {key!r} in .env.example")
def test_env_example_default_off_but_template_keeps_video_integration(self) -> None:
path = os.path.join(get_skill_root(), ".env.example")
with open(path, encoding="utf-8") as f:
text = f.read()
self.assertEqual(
_active_env_value(text, "OPENCLAW_RECORD_VIDEO"),
"OPENCLAW_RECORD_VIDEO=0",
)
service_text = _combined_service_source()
missing = _missing_video_integration_tokens(service_text)
self.assertEqual(
missing,
[],
msg=(
"default OPENCLAW_RECORD_VIDEO=0 does not allow removing video integration; "
f"scripts/service/*.py missing: {', '.join(missing)}"
),
)
def test_env_example_allows_record_video_one_in_comments_only(self) -> None:
sample = "\n".join(
[
"# example: OPENCLAW_RECORD_VIDEO=1 for production",
"OPENCLAW_RECORD_VIDEO=0",
]
)
self.assertEqual(
_active_env_value(sample, "OPENCLAW_RECORD_VIDEO"),
"OPENCLAW_RECORD_VIDEO=0",
)
class TestPrintVideoSummary(unittest.TestCase): class TestPrintVideoSummary(unittest.TestCase):
def test_cli_prints_video_path_when_enabled(self) -> None: def test_cli_prints_video_path_when_enabled(self) -> None:

View File

@@ -27,6 +27,9 @@ python tools/scaffold_skill.py --slug my-new-skill --destination /path/to/my-new
- `your_skill_slug` → 连字符替换为下划线(如 `scrape_demo_records`,用于 `LOG_LOGGER_NAME` 等) - `your_skill_slug` → 连字符替换为下划线(如 `scrape_demo_records`,用于 `LOG_LOGGER_NAME` 等)
- 覆盖 `assets/actions.json``SKILL.md``scripts/util/constants.py` 等生成文件;文档中的路径示例可保留占位,但生成后的技能文件不得残留占位符 - 覆盖 `assets/actions.json``SKILL.md``scripts/util/constants.py` 等生成文件;文档中的路径示例可保留占位,但生成后的技能文件不得残留占位符
- **不**自动修改 `actions.json` 中的 CLI 业务命令;技能作者自行增删 action - **不**自动修改 `actions.json` 中的 CLI 业务命令;技能作者自行增删 action
- **不**移除 Schema 中的 `bind.tables` 支持,**不**把 `bind` 当模板残留清理
- **不**自动生成业务表名,**不**给 `health` / `version` / `config-path` 自动加 `toolbar`
- **不**生成任何具体平台业务 Action
- **不**自动 `git init`;打印后续 Git 与测试命令 - **不**自动 `git init`;打印后续 Git 与测试命令
目标目录若已存在且非空,需加 `-Force` / `--force`(且目标**不得**含 `.git`)。 目标目录若已存在且非空,需加 `-Force` / `--force`(且目标**不得**含 `.git`)。