diff --git a/SKILL.md b/SKILL.md index 106c1fc..56b9c2b 100644 --- a/SKILL.md +++ b/SKILL.md @@ -22,11 +22,23 @@ allowed-tools: ## Agent / 宿主编排(复制为业务技能后必改) -- **长耗时 / RPA / 浏览器任务**:必须通过宿主 **Skill Action**(`run_skill_action`)调用已声明在 `assets/actions.json` 中的 action;`executionProfile` 须为 `"async"`,进度见**任务中心** / Skill Run Card。 +### 架构铁律(先读) + +- **单业务内核、多入口**:数据管理 / 定时任务 / Agent / 技能详情 / 直接 CLI 必须复用同一 domain service;禁止按入口复制业务逻辑,禁止按 `source` 分叉业务行为。 +- **`placements`**:只决定 Action 出现在哪里。 +- **`bind.tables`**:只决定数据管理出现在哪些表;含 `toolbar` 时**必须**显式非空绑定。 +- **`executionProfile`**:只决定 sync 等待还是 async Job;**必须**显式声明 `sync` 或 `async`;与 placements **正交**(任意合法组合均可)。 +- **`async`**:宿主建 Job,立即返回 `jobId`,进度见**任务中心** / Skill Run Card。 +- **同步数据**写技能本地库、不生成导出文件;**导出当前表**由宿主数据管理负责;特殊业务报告才另做 `export-*`。 + +### 编排要点 + +- **长耗时 / RPA / 浏览器任务**:必须通过宿主 **Skill Action**(`run_skill_action`)调用 `assets/actions.json` 中的 action;建议 `executionProfile: "async"`。 - **禁止**对长任务使用 `exec python …/scripts/main.py run` 或 `process poll` 干等 CLI 返回。 -- 只读查询(`health` / `stats` 等)可用 `executionProfile: "sync"`,立即返回结果。 -- 批量处理用参数化 `pickCount` / `--pick N` 顺序消费队列,**不要并发**同一 Profile;契约见 `development/SKILL_ACTION_RUNTIME.md`、`references/ACTIONS.md`。 -- 模板源仓库本身仅示范 `health` / `version` / `config-path`(sync);定制 RPA 技能后须自行增加 async action。 +- 只读查询(`health` / `stats` 等)可用 `"sync"`,立即返回结果。 +- 批量处理用参数化 `pickCount` / `--pick N` 顺序消费队列,**不要并发**同一 Profile。 +- 详细契约:`development/SKILL_ACTION_RUNTIME.md`、`references/ACTIONS.md`、`references/SCHEMA.md`。 +- 模板源仓库本身仅示范 `health` / `version` / `config-path`(sync);定制后按业务增加 Action,**一个能力一个 Action + 多 placements**。 ## 面向用户问答(LLM 规则) diff --git a/assets/README.md b/assets/README.md index b48102e..a436ea4 100644 --- a/assets/README.md +++ b/assets/README.md @@ -1,10 +1,10 @@ # assets -- `actions.json`:Skill Action manifest 最小示例(**可选**;不需要宿主入口时可删除)。模板要求每个 action 显式声明 `executionProfile`(`sync` \| `async`)。 +- `actions.json`:Skill Action manifest 最小示例(**可选**;不需要宿主入口时可删除)。每个 action **必须**显式声明 `executionProfile`(`sync` \| `async`)。默认仅 `health` / `version` / `config-path`,不放 toolbar,故无 `bind` 示例。 - `examples/`:CLI 成功输出形状示例(虚构路径与数据)。 - `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` 为预留能力,当前模板示例不得使用。RPA/长耗时 action 必须 `executionProfile: "async"`,见 [`development/SKILL_ACTION_RUNTIME.md`](../development/SKILL_ACTION_RUNTIME.md)。 +`skill-actions.schema.json` 使用 `additionalProperties: false`。正式支持 `bind.tables`(toolbar Action 必填);`row`/`batch` placements 与 `concurrency`/`locks` 仍为预留。`placements` 与 `executionProfile` 正交。表级 Action 示例见 [`references/ACTIONS.md`](../references/ACTIONS.md);运行时见 [`development/SKILL_ACTION_RUNTIME.md`](../development/SKILL_ACTION_RUNTIME.md)。 - 用户市场说明见根目录 [`README.md`](../README.md) - Agent 调用/编排参考见 [`references/`](../references/)(含 [`ACTIONS.md`](../references/ACTIONS.md)) diff --git a/assets/schemas/skill-actions.schema.json b/assets/schemas/skill-actions.schema.json index 43cf793..4fbb978 100644 --- a/assets/schemas/skill-actions.schema.json +++ b/assets/schemas/skill-actions.schema.json @@ -26,7 +26,7 @@ "placement": { "type": "string", "enum": ["toolbar", "row", "batch", "cron", "agent", "skill-detail"], - "description": "模板 Phase 1 稳定支持 toolbar/cron/agent/skill-detail;row/batch 为预留入口,新技能示例不得使用" + "description": "稳定支持 toolbar/cron/agent/skill-detail;row/batch 为预留入口,新技能示例不得使用。placements 与 executionProfile 正交,不做条件限制。" }, "scalarArg": { "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": { "type": "object", - "required": ["id", "label", "description", "placements", "entrypoint"], + "required": ["id", "label", "description", "placements", "entrypoint", "executionProfile"], "additionalProperties": false, "properties": { "id": { @@ -116,7 +136,8 @@ "placements": { "type": "array", "minItems": 1, - "items": { "$ref": "#/$defs/placement" } + "items": { "$ref": "#/$defs/placement" }, + "description": "决定 Action 出现在哪里;与 executionProfile 正交" }, "entrypoint": { "$ref": "#/$defs/entrypoint" }, "inputSchema": { "$ref": "#/$defs/inputSchema" }, @@ -124,10 +145,22 @@ "executionProfile": { "type": "string", "enum": ["sync", "async"], - "description": "sync=宿主内联等待结果(约 30s);async=后台 Job 进任务中心。模板要求显式写出;RPA/长耗时必须 async。" - } + "description": "sync=调用方等待结构化结果(不建 Job);async=宿主建后台 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。" } } } diff --git a/development/DEVELOPMENT.md b/development/DEVELOPMENT.md index 04ef044..15e616b 100644 --- a/development/DEVELOPMENT.md +++ b/development/DEVELOPMENT.md @@ -454,33 +454,41 @@ metadata: 也就是说,`cli/app.py` 的职责是: 1. 打印帮助 -2. 定义 `run / logs / log-get / health / version` -3. 把参数转交给 `service.task_service` +2. 定义 `run / logs / log-get / health / version`(及业务子命令) +3. 把参数转交给 `service.task_service`(或薄适配后再进 domain service) 不要在 `cli/app.py` 里直接写: - 浏览器自动化 - 子进程调用兄弟技能 - SQLite 逻辑 +- 与 toolbar / cron / agent 来源相关的业务分叉 ## 10. `service` 层怎么写 -`service` 是核心层。 +`service` 是核心层。推荐拆分(**单业务内核、多入口**): -通常可以这样拆: +```text +cli/app.py → 只解析参数 +service/task_service.py → job_context / emit / checkpoint / finish / 错误转换 +service/_service.py → 唯一业务内核(同步、处理、统计等) +db/*_repository.py → 事务与读写 +assets/actions.json → placements / bind / executionProfile / entrypoint +``` -- `task_service.py` - 放命令编排、参数兜底、结果分流(例如 `cmd_run`) +通常还可以有: - `sibling_bridge.py` - 放通用兄弟技能子进程工具(`call_sibling_json`);**具体调用哪个 slug 由业务在 `task_service.py` 决定**,不要在本文件硬编码发布类专用 helper + 放通用兄弟技能子进程工具(`call_sibling_json`);**具体调用哪个 slug 由业务在 `task_service.py` 或 domain service 决定**,不要在本文件硬编码发布类专用 helper - `xxx_playwright.py`(按需新建) - 浏览器后台自动化 **不在模板默认结构中**;若确有需要,按命名约定自建模块并在 `task_service.py` 引用 + 浏览器后台自动化 **不在模板默认结构中**;若确有需要,按命名约定自建模块并由 domain / task_service 引用 - `entitlement_service.py` 放鉴权逻辑 +禁止:toolbar / cron / Agent / CLI 各自复制一套采集或同步实现;为兼容旧命令再写第二套内核。 + ### 日志要求(`cmd_run` / 核心业务) `service` 层是**关键业务日志**的落点,须遵循 [`LOGGING.md`](LOGGING.md): @@ -497,7 +505,9 @@ metadata: 推荐流向是: -`cli.app` -> `service.task_service` -> `service.sibling_bridge` / (可选)`service.xxx_playwright` -> `db` +`cli.app` -> `service.task_service` -> `service._service` -> `db` + +(旁路:`sibling_bridge` / 可选 `xxx_playwright` 仅由 service 调用) ## 11. `db` 层怎么写 @@ -525,13 +535,14 @@ metadata: 若技能需要出现在宿主**数据管理按钮**、**技能详情**、**定时任务**或 **Agent 直接调用**中,提供 `assets/actions.json`。 -- **运行时金标准**见 [`SKILL_ACTION_RUNTIME.md`](SKILL_ACTION_RUNTIME.md)(sync/async、任务中心、Agent 禁令) -- 字段契约见 [`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) -- 模板最小示例仅暴露 `health` / `version` / `config-path`(均显式 `executionProfile: "sync"`) +- 模板最小示例仅暴露 `health` / `version` / `config-path`(均显式 `executionProfile: "sync"`;**不**自动加 toolbar) +- 含 `toolbar` 的 Action:**必须**声明合法 `bind.tables`(`POLICY-SKILL-ACTION-003`) - 含浏览器 RPA / 长耗时的业务技能:**必须**增加至少一条 `"executionProfile": "async"` 且 `placements` 含 `agent` 的 action(`POLICY-SKILL-ACTION-001`) - 没有宿主直接操作需求时,**可以删除** `actions.json`;删除后勿保留失效引用 -- 复制为新技能后,scaffold 会自动将 `your-skill-slug` 与 `your_skill_slug` 替换为新 slug(后者用于 `LOG_LOGGER_NAME` 等下划线形式);action 业务命令由技能作者自行调整 +- scaffold **不会**移除 Schema 中的 `bind` 支持,**不会**生成平台业务 Action 或业务表名;仅替换占位 slug 宿主执行方式: @@ -543,22 +554,31 @@ CLI 必须提供稳定退出码、结构化成功输出,以及 `ERROR::` ### 编排范式:单内核 + 多入口 -长任务 / RPA 技能推荐拆分(勿把 `job_context` 塞进纯业务内核): +长任务 / RPA / 数据同步技能推荐拆分(勿把 `job_context` 塞进纯业务内核): + +```text +_service.sync_*(...) # 唯一业务内核:读外源 → 写本地库(或核心处理) +cmd_sync_* (...) # 编排:job_context + 调用内核 + emit/finish(async 时) +CLI / Action / cron / Agent # 全部进入同一 cmd_* → 同一内核 +``` + +RPA 批量亦可: ```text execute_single_(...) # 鉴权 + 业务 + task_log;无 job_context cmd_run(...) # 单条:job_context + execute_single + finish -cmd_run_pick(N, ...) # 批量顺序:job_context + for-loop + emit(progress) + finish(partial|success|failed) +cmd_run_pick(N, ...) # 批量顺序:job_context + for-loop + emit(progress) + finish cmd_stats() # 只读 sync:JSON,无 job_context ``` - 批量数量用 **`pickCount` / `--pick N` 参数**(任意正整数),不写死条数。 - **顺序执行、不并发**同一浏览器 Profile / account lease。 -- 详情见 [`SKILL_ACTION_RUNTIME.md`](SKILL_ACTION_RUNTIME.md) §5–§6。 +- **同步数据**与**宿主表导出**职责分离:同步不写 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)。 +有「待处理列表」时:队列表 `pending → processing → success/failed`;数据管理录入或 `import-*` 入库;`run --pick N` 消费;失败用 `reset` 回 `pending`(不自动重试)。Manifest 上配置 `*-run-pick`(常见为 async + toolbar/cron/agent;有 toolbar 则须 `bind.tables`)。 ## 12. 如何接兄弟技能 diff --git a/development/POLICY_MATRIX.md b/development/POLICY_MATRIX.md index ee20121..3c276bf 100644 --- a/development/POLICY_MATRIX.md +++ b/development/POLICY_MATRIX.md @@ -29,17 +29,25 @@ | 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.md;references/ACTIONS.md | hard | 文档/schema/manifest 检查 | `tests/test_development_policy_guard.py::TestPolicySkillAction001` | +| POLICY-SKILL-ACTION-002 | 每个 Action 必须显式声明 `executionProfile`,且只能是 `sync` 或 `async` | development/SKILL_ACTION_RUNTIME.md;references/ACTIONS.md;assets/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.md;assets/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.md;references/ACTIONS.md;assets/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.md;development/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.md;development/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 | 需语义理解,无法可靠静态判定 | -| `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.md;SCHEMA.md | 文档 + sample;勿做源码关键词误报扫描 | | `db/` 层不得调浏览器或拼业务流程 | development/DEVELOPMENT.md §11 | 需跨文件调用图 | | 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` 守护,属脚手架场景 | @@ -48,3 +56,4 @@ | adapter 四档契约测试覆盖 timeout/unauthorized 等 | development/ADAPTER.md §contract tests | 需业务实现后人工补测 | | `SKILL.md` / `constants.SKILL_SLUG` 一致性 | development/DEVELOPMENT.md §16 | 已有 `tests/test_skill_metadata.py` | | platform_kit_min_version >= 1.2.0 | development/RUNTIME.md | 已有 `tests/test_platform_import.py` | +| 宿主按 `bind.tables` 过滤 toolbar 按钮 | references/ACTIONS.md | 待宿主升级后完整生效;模板侧已强制显式绑定 | diff --git a/development/SKILL_ACTION_RUNTIME.md b/development/SKILL_ACTION_RUNTIME.md index db5adab..37324b8 100644 --- a/development/SKILL_ACTION_RUNTIME.md +++ b/development/SKILL_ACTION_RUNTIME.md @@ -6,8 +6,8 @@ | 文档 | 职责 | |------|------| -| 本文 | sync/async、任务中心、Agent 禁令、编排范式、队列 pick | -| [`../references/ACTIONS.md`](../references/ACTIONS.md) | `actions.json` 字段、placements、inputSchema | +| 本文 | 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) | 下载/导入等落盘路径 | @@ -18,10 +18,12 @@ ## 1. 核心原则 1. **宿主管调度,技能管业务** — 不自行实现任务中心 / Job 轮询 / 后台守护进程。 -2. **长耗时 = async** — 开浏览器、RPA、HTTP 大文件下载等必须 `executionProfile: "async"`,进**任务中心**。 -3. **Agent 禁止 `exec` 直跑长任务 CLI** — 必须 `run_skill_action`;禁止 `exec python main.py run` + `process poll` 干等。 -4. **进度走 Journal** — `emit` / `video.add_step` → Run Journal;UI / Skill Run Card / 任务中心展示;**不靠 stdout 流**。 -5. **显式声明 `executionProfile`** — 宿主省略时默认 `async`;模板要求每个 action **写明** `sync` 或 `async`,避免歧义。 +2. **单业务内核、多入口** — 数据管理、定时任务、Agent、技能详情与直接 CLI 复用同一 domain service;禁止按入口复制业务逻辑。 +3. **五职责正交** — `placements` / `bind.tables` / `executionProfile` / `entrypoint` / domain service 各管一事(见 ACTIONS.md)。 +4. **长耗时建议 async** — 开浏览器、RPA、HTTP 大文件下载等建议 `executionProfile: "async"`,进**任务中心**;这是选择建议,**不**限制可以出现在哪些 placement。 +5. **Agent 禁止 `exec` 直跑长任务 CLI** — 必须 `run_skill_action`;禁止 `exec python main.py run` + `process poll` 干等。 +6. **进度走 Journal** — `emit` / `video.add_step` → Run Journal;UI / Skill Run Card / 任务中心展示;**不靠 stdout 流**。 +7. **显式声明 `executionProfile`** — 每个 action **必须**写明 `sync` 或 `async`;禁止依赖宿主缺省;禁止第三种模糊模式(`auto` / `background` / `deferred` 等)。 --- @@ -29,62 +31,76 @@ | 值 | 宿主行为 | 超时 | 任务中心 | |----|----------|------|----------| -| **`sync`** | 内联等待 CLI 结束,把结果直接返回调用方 | 默认约 **30s**(`SKILL_ACTION_SYNC_TIMEOUT_MS`) | ❌ 不进 | -| **`async`** | 后台 spawn Job,立即返回 `jobId` | Job 本身无默认墙钟上限(可暂停/停止) | ✅ 进入 | -| **省略** | 宿主视为 **async** | 同 async | ✅ | +| **`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` | -| 数据管理 **toolbar** | **只放 async**(宿主前端对 sync 结果会报错) | +| 单次可能超过 ~20s 的网络/下载/同步 | `async` | +| `health` / `version` / `config-path` / 纯统计 / 秒级查询 | `sync` | +| 任意 placement(含 toolbar) | 允许 sync 或 async;以 manifest 为准 | -### Agent 路径启发式(宿主行为,技能作者需知) +合法:`sync|async` × `toolbar|cron|agent|skill-detail`。 -- 显式写了 `executionProfile` → 以显式为准。 -- 未写时:描述含「统计 / 检查 / 不启动浏览器」等只读语义 → Agent 侧可当 **sync**;有 `confirmation` 的副作用 → **async**。 -- **模板要求一律显式写出**,不要依赖启发式。 +历史说明:旧文档曾错误地把数据管理按钮入口与异步执行方式绑死。该约束**已废止**;模板测试与 Schema **不得**再建立「入口位置决定 sync/async」一类硬耦合。宿主省略 `executionProfile` 时的兼容行为以宿主实现为准,**新技能不得依赖**。 --- -## 3. 三入口如何感知 sync / async +## 3. 多入口如何感知 sync / async -三个入口统一走 `POST /api/skill-actions/run`,带 `source.kind`: +多个入口统一走 `POST /api/skill-actions/run`,可能带 `source.kind`: -| 入口 | `source.kind` | 推荐 | -|------|---------------|------| -| **Agent** | `agent` | `run_skill_action`;长任务 async,秒回 jobId | -| **数据管理** | `data-management` | toolbar 按钮触发 async action | -| **定时任务** | `cron` | Cron 配置 async action + `pickCount` 等参数 | +| 入口 | 常见 `source.kind` | 说明 | +|------|-------------------|------| +| **Agent** | `agent` | `run_skill_action`;按 manifest 的 executionProfile 执行 | +| **数据管理** | `data-management` | toolbar 按钮;须 `bind.tables` | +| **定时任务** | `cron` | Cron 配置参数后调用同一 Action | +| **技能详情** | (依宿主) | 与上同一 CLI / 同一业务内核 | -技能 **不要** 在 Python 里为三个入口写三套分支;宿主读 manifest 分流。 +技能 **不要** 在 Python 里按 `source` / placement 写业务分叉;宿主读 manifest 分流展示与等待策略。 --- -## 4. Action 分类与 placements 矩阵 +## 4. Action 分类与 placements(示例,不是限制) -| Action 类型 | `executionProfile` | 典型 placements | `confirmation` | -|-------------|--------------------|-----------------|----------------| -| 运行检查 / 版本 / 配置路径 | `sync` | `skill-detail`, `agent`(只读) | 无 | +下表只表示常见组合示例。**placements 以 manifest 为准;sync/async 不影响展示入口。** + +| Action 类型 | 常见 `executionProfile` | 常见 placements | `confirmation` | +|-------------|-------------------------|-----------------|----------------| +| 运行检查 / 版本 / 配置路径 | `sync` | `skill-detail`, `agent` | 无 | | 库 / 队列统计 | `sync` | `skill-detail`, `agent` | 无 | -| 数据导入 / 失败重置 | `sync` | `skill-detail`, `agent` | 可选 | -| **单条**副作用 RPA | `async` | `agent`, `skill-detail` | **必须** | -| **批量顺序** RPA(pick) | `async` | **`toolbar`**, `cron`, `agent` | **必须** | +| 外源 → 本地库同步 | `sync` 或 `async` | 可含 `toolbar`(须 `bind.tables`)、`cron`、`agent` | 可选 | +| 数据导入 / 失败重置 | `sync` 或 `async` | `skill-detail`, `agent` | 可选 | +| **单条**副作用 RPA | `async`(建议) | `agent`, `skill-detail` | **建议** | +| **批量顺序** RPA(pick) | `async`(建议) | `toolbar`, `cron`, `agent` | **建议** | 禁忌: -- 高副作用 async action 不要默认只挂 `toolbar`(应有 confirmation)。 +- 高副作用 action 不要默认只挂 `toolbar`(应有 confirmation)。 - 含 `sensitive` 参数的 action 不要挂 `toolbar` / `cron`(除非有明确安全设计)。 - 不要为了「按钮多」暴露所有 CLI 子命令。 +- 不要按入口复制多套采集 / 同步 / 处理实现。 --- ## 5. 技能内编排范式(单内核 + 多入口) -推荐结构(对齐 create-account / download-video 金标准): +推荐分层: + +```text +scripts/cli/app.py # 参数解析 → 调用 task / service +scripts/service/task_service.py # job_context / emit / checkpoint / finish / 错误转换 +scripts/service/_service.py # 唯一业务内核 +scripts/db/*_repository.py # 只负责读写与事务 +assets/actions.json # 声明入口、参数、placement、executionProfile、bind +``` + +长任务 / RPA 常见拆分(勿把 `job_context` 塞进纯业务内核): ```text execute_single_(...) # 纯业务:鉴权 + 核心逻辑 + task_log;不含 job_context @@ -95,19 +111,20 @@ cmd_stats() # 只读 sync:JSON stdout,无 job_context 要点: -1. **`job_context` 只包编排层**(`cmd_run` / `cmd_run_pick`),不包 `execute_single_*`。 -2. 批量 **顺序、不并发**;数量由参数 `pickCount` / `--pick N` 传入(不写死 100/200)。 +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:**禁止并发**;顺序执行 + lease 即可。 +5. 同一浏览器 Profile / account lease:**禁止并发**。 +6. 兼容旧命令(例如旧 export 需先刷新)必须调用同一 sync / domain 内核,禁止重写采集逻辑。 -详见 [`LOGGING.md`](LOGGING.md) §2.5 与 `scripts/service/task_service.py` 示范。 +详见 [`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 批量) -有「待处理列表」的技能(账号开通、视频下载、帖子发布等)建议: +有「待处理列表」的技能建议: | 能力 | 约定 | |------|------| @@ -116,7 +133,7 @@ cmd_stats() # 只读 sync:JSON stdout,无 job_context | 消费 | `run --pick N`,默认仅 `pending` | | 重试 | `reset` 或数据管理改 `pending`;**failed 不要自动重试** | | 批次 | 可选 `batch_id`,便于筛选与任务中心对照 | -| Manifest | `*-run-pick`:`async`,`placements` 含 `toolbar` / `cron` / `agent`,`inputSchema.pickCount` | +| Manifest | `*-run-pick`:建议 `async`,`placements` 按需含 `toolbar` / `cron` / `agent`;有 toolbar 则 `bind.tables` 必填 | 批量有两种合理形态(都是**顺序**): @@ -125,11 +142,23 @@ cmd_stats() # 只读 sync:JSON stdout,无 job_context | 一次 `run-pick` 处理 N 条 | **1** 条 Job | 同类 RPA、同 Profile、定时消费队列 | | Agent/UI 触发 N 次单条 `run` | **N** 条 Job | 每条独立追踪 / 独立重试 | -默认优先 **一次 pick、一条 Job**(与 create-account `--pick`、download `--pick` 一致)。 +默认优先 **一次 pick、一条 Job**。 --- -## 7. Agent / SKILL.md 契约(复制后必改) +## 7. 业务同步与系统导出 + +| 能力 | 方向 | 负责方 | +|------|------|--------| +| 同步 / refresh / collect | 外部来源 → 技能本地 SQLite | 技能 domain service | +| 导出当前数据表 | 本地库 → CSV/Excel | **宿主**数据管理统一导出 | +| 特殊业务报告 | 多表合并 / 特殊格式 / 附加计算 | 仅系统导出不足时提供 `export-*` | + +同步 Action 默认写库、不写导出文件。通用幂等 / 事务 / 空结果保护见 [`../references/SCHEMA.md`](../references/SCHEMA.md)。 + +--- + +## 8. Agent / SKILL.md 契约(复制后必改) 业务技能 `SKILL.md` 应明确: @@ -137,20 +166,25 @@ cmd_stats() # 只读 sync:JSON stdout,无 job_context 2. **禁止**对长任务使用 `exec` + `process poll`。 3. 单条 vs 批量 action id 与参数(如 `url` / `pickCount`)。 4. 长任务进度看**任务中心** / Skill Run Card,不等 CLI stdout。 +5. 多入口复用同一业务内核;异步 Action 进入任务中心。 模板源仓库的 `SKILL.md` 含占位段落;scaffold 后按业务改写。 --- -## 8. Policy +## 9. Policy 自动检测索引见 [`POLICY_MATRIX.md`](POLICY_MATRIX.md): -- **POLICY-SKILL-ACTION-001**:`SKILL_ACTION_RUNTIME.md` 存在;schema 含 `executionProfile`;有 RPA 的业务技能必须声明 async agent action。 +- **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。 --- -## 9. 与宿主 API(参考) +## 10. 与宿主 API(参考) | API | 用途 | |-----|------| @@ -160,3 +194,5 @@ cmd_stats() # 只读 sync:JSON stdout,无 job_context | `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 可能在技能全部数据表显示——新技能仍须显式绑定,待宿主升级后完整按表过滤生效。 diff --git a/references/ACTIONS.md b/references/ACTIONS.md index c532f2e..cfe3c10 100644 --- a/references/ACTIONS.md +++ b/references/ACTIONS.md @@ -2,7 +2,7 @@ 本文件说明 `assets/actions.json` 与 `scripts/main.py` CLI 的对应关系,供 Agent 编排与宿主 **Skill Action Runtime** 使用。 -**权威运行时契约(sync/async、任务中心、编排范式)见 [`../development/SKILL_ACTION_RUNTIME.md`](../development/SKILL_ACTION_RUNTIME.md)。** +**权威运行时契约(sync/async、任务中心、单内核编排)见 [`../development/SKILL_ACTION_RUNTIME.md`](../development/SKILL_ACTION_RUNTIME.md)。** **边界:** 用户市场说明见根目录 [`README.md`](../README.md);CLI 参数与错误码细节见 [`CLI.md`](CLI.md)。 @@ -11,7 +11,7 @@ | 角色 | 定位 | |------|------| | **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。 @@ -47,29 +47,73 @@ Action 是**可选能力**: 模板最小示例见 [`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 当前稳定支持(新技能应只使用这些) | 层级 | 稳定字段 / 能力 | |------|----------------| | 顶层 | `schemaVersion`、`skill`、`actions` | -| action | `id`、`label`、`description`、`placements`、`entrypoint`;可选 `inputSchema`、`confirmation`、**`executionProfile`** | +| action | `id`、`label`、`description`、`placements`、`entrypoint`、**`executionProfile`(必填)**;可选 `inputSchema`、`confirmation`、**`bind`** | | entrypoint | `type = cli`、`command`、`args`(**必填** JSON 数组,项为 `string` / `number` / `boolean`) | | placements | `toolbar`、`skill-detail`、`agent`、`cron` | +| **bind** | `{ "tables": ["business_table"] }`(见下节) | | inputSchema | 根 `type: object`;properties 使用 `string` / `number` / `boolean`;支持 `enum`、`default`、`required`、`sensitive` | | confirmation | `{ "message": "..." }` | -| **executionProfile** | `"sync"` \| `"async"`(**模板要求显式写出**) | +| **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` | 行内 / 批量入口,未来扩展 | -| action 字段 | `bind`、`concurrency`、`locks` | 绑定、并发与锁控制,宿主后续实现 | -| inputSchema | `array`、nested `object`、`oneOf` 等 | 复杂表单与联合类型,不属于当前推荐模板范围 | +| placements | `row`、`batch` | 行内 / 批量入口,未来扩展;新技能示例不得使用 | +| action 字段 | `concurrency`、`locks` | 并发与锁控制,未稳定开放 | +| inputSchema | `array`、nested `object`、`oneOf` 等 | 复杂表单,不属于当前推荐范围 | -可以在文档或 Schema 枚举中保留这些值供未来对齐,但不要让技能作者误以为它们已经可执行。 +`bind` **不是**保留字段;已作为 Phase 1 表级绑定正式能力。 ## 执行模型 @@ -86,17 +130,20 @@ python {skill_root}/scripts/main.py 完整子命令定义见 [`scripts/cli/app.py`](../scripts/cli/app.py)。 -### `executionProfile`(sync / async) +### `executionProfile`(仅 sync / async) + +模板与新技能**只允许**这两种值;禁止发明 `auto` / `background` / `deferred` 等第三种模式。 | 值 | 宿主行为 | 任务中心 | |----|----------|----------| -| `sync` | 内联等待 CLI(默认约 30s) | 不进 | -| `async` | 后台 Job,立即返回 `jobId` | **进入** | -| 省略 | 宿主默认按 **async** | 进入 | +| `sync` | 调用方等待结束,直接返回结构化结果或结构化错误;**不**创建后台 Job | 不进 | +| `async` | 宿主创建后台 Job,立即返回 `jobId`;用 `emit` / `checkpoint` / `finish` 报告进度与终态 | **进入** | -- **RPA / 浏览器 / 长耗时** → 必须 `"async"`,并建议加 `confirmation`。 -- **数据管理 toolbar** → 只挂 **async** action。 -- 完整规则见 [`../development/SKILL_ACTION_RUNTIME.md`](../development/SKILL_ACTION_RUNTIME.md)。 +合法组合(全部允许):`sync|async` × `toolbar|cron|agent|skill-detail`。 + +经验建议(**不是** placement 硬限制):耗时不可预测、需要暂停/停止/进度展示的任务,建议用 `async`。 + +直接执行 CLI 时,终端自然等待进程结束;宿主通过 Action 调用同一 CLI 时,再按 `executionProfile` 决定同步等待还是建 Job。技能**不得**自行实现第二套任务中心或后台队列。 ### CLI 输出契约 @@ -109,7 +156,6 @@ python {skill_root}/scripts/main.py - 对用户可处理的问题提供 `HINT` - 不依赖 Agent 连续对话才能完成 - 不自行实现宿主任务中心 -- 长时间任务允许异步执行,由宿主任务中心承载状态 - 不在 CLI 中硬编码宿主安装目录 - 不直接依赖某个具体 UI 页面 @@ -124,27 +170,37 @@ HINT: | 值 | 含义 | |----|------| -| `toolbar` | 数据管理第一排技能按钮(**仅 async**) | +| `toolbar` | 数据管理第一排技能按钮(须配合 `bind.tables`) | | `skill-detail` | 技能详情或技能市场详情页 | | `agent` | Agent 可直接调用(`run_skill_action`) | | `cron` | 定时任务可直接调用 | -**预留能力(当前宿主可能尚未完整支持,模板示例请勿使用):** +**预留(模板示例请勿使用):** `row`、`batch`。 -| 值 | 说明 | -|----|------| -| `row` | 行内操作(未来扩展) | -| `batch` | 批量操作(未来扩展) | +### Action 类型 × placements(常见示例,不是限制) -### Action 类型 × placements 矩阵 +下表只表示**常见用法示例**。实际 `placements` 以 manifest 配置为准;**`sync` / `async` 不影响展示入口**。 -| Action 类型 | executionProfile | 典型 placements | confirmation | -|-------------|------------------|-----------------|--------------| +| Action 类型 | 常见 executionProfile | 常见 placements | confirmation | +|-------------|----------------------|-----------------|--------------| | health / version / config-path | sync | skill-detail, agent | 无 | | 统计 / 只读查询 | sync | skill-detail, agent | 无 | -| 导入 / 重置 | sync | skill-detail, agent | 可选 | -| 单条副作用 RPA | async | agent, skill-detail | **必须** | -| 批量顺序 pick RPA | async | **toolbar**, cron, 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 与参数表单 @@ -204,14 +260,15 @@ HINT: ## 风险与入口配置 - 查询、诊断、版本检查可以放到 `skill-detail` 或 `agent` -- 低风险、常用动作才考虑放 `toolbar`(且须为 async) +- 低风险、常用动作才考虑放 `toolbar`(须 `bind.tables`;executionProfile 按耗时自选) - 会修改本地数据、访问外部系统、执行长时间任务的动作必须谨慎配置 - 有副作用的动作应添加 `confirmation.message` - 高风险动作不应默认出现在 `toolbar` - 含 `sensitive` 参数的 action 不应放入 `toolbar` 或 `cron`,除非有明确安全设计 - 不要为了「按钮多」而暴露所有 CLI 子命令 -- 一个 CLI 命令可以拆成多个语义清晰的 action,但每个 action 必须有明确语义 +- 一个 CLI 命令可以拆成多个语义清晰的 action,但每个 action 必须有明确语义,并复用同一业务内核 - **Agent 必须用 `run_skill_action`,禁止 `exec` 直跑长任务 CLI**(见 `SKILL_ACTION_RUNTIME.md`) +- **禁止**按 `source=toolbar/cron/agent/skill-detail` 在业务代码中分叉业务行为 ## 模板示例 action 一览 @@ -223,11 +280,12 @@ HINT: 业务技能复制后,按需增加例如: -| 模式 | id 示例 | executionProfile | placements | -|------|---------|------------------|------------| -| 单条 RPA | `your-run` | async | agent, skill-detail | -| 队列 pick | `your-run-pick` | async | toolbar, cron, agent | -| 统计 | `your-stats` | sync | skill-detail, agent | +| 模式 | 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 长任务时)。 diff --git a/references/SCHEMA.md b/references/SCHEMA.md index 43681c6..13679f5 100644 --- a/references/SCHEMA.md +++ b/references/SCHEMA.md @@ -73,6 +73,45 @@ metadata: 不要把「外部来源只读」错误理解成「技能本地数据库一定只读」。技能通过 `_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` 一致): diff --git a/scripts/cli/app.py b/scripts/cli/app.py index 77f8668..cd68eaf 100644 --- a/scripts/cli/app.py +++ b/scripts/cli/app.py @@ -1,4 +1,7 @@ -"""CLI:argparse 与分发模板。""" +"""CLI:argparse 与分发模板。 + +只负责参数解析并转交 service;业务内核在 domain / task_service,勿在此按入口复制逻辑。 +""" from __future__ import annotations diff --git a/scripts/service/task_service.py b/scripts/service/task_service.py index 2381e58..e25d821 100644 --- a/scripts/service/task_service.py +++ b/scripts/service/task_service.py @@ -1,7 +1,8 @@ """任务编排、日志查询模板。 -通用业务编排层:负责参数校验、鉴权、调用具体业务实现、写入任务日志。 -复制后在 cmd_run 中实现真正的业务逻辑。 +编排层:job_context / emit / checkpoint / finish、鉴权、任务日志与错误转换。 +领域业务请放在 ``service/_service.py``,由本模块调用;多入口(CLI/Action/cron)复用同一内核。 +复制后在 cmd_run(或 cmd_sync_*)中接线到真实 domain service,勿按 toolbar/cron/agent 分叉业务。 """ from __future__ import annotations diff --git a/tests/README.md b/tests/README.md index 42c5fbd..4e6d613 100644 --- a/tests/README.md +++ b/tests/README.md @@ -15,6 +15,8 @@ | CLI / health / version / metadata / runtime 路径 | `tests/test_*.py` | 是 | 默认必跑,保持轻量、无外联 | | 纯函数 / 业务规则 | `tests/test_*.py` | 是 | 不依赖真实外部系统 | | 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` | 是,复制后 | 输入样例 + 期望输出,适合解析、计算、校验类技能 | | 仿真 API | `tests/integration/test_simulator_api_contract.py.sample` | 否 | 复制并设置 `OPENCLAW_TEST_TARGET=simulator_api` 后按需运行 | | 仿真 RPA / 页面操作 | `tests/integration/test_simulator_rpa_contract.py.sample` | 否 | 用 localhost / 仿真页面,不碰真实系统 | diff --git a/tests/samples/README.md b/tests/samples/README.md index 952b279..2b59fa4 100644 --- a/tests/samples/README.md +++ b/tests/samples/README.md @@ -12,7 +12,7 @@ --- -## 两类样例文件 +## 样例文件 ### 1. `test_service_contract.py.sample` @@ -22,7 +22,17 @@ - 需要验证:**成功路径**、**参数/校验错误**、**adapter 异常被转换为业务可读错误**。 - 需要用 **`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` | +| 同步契约 | `tests/test_sync_contract.py` | +| 单内核多入口 | `tests/test_action_core_contract.py` | | Golden / fixture 回归 | `tests/test_golden_cases.py` | | 领域规则 | `tests/test__rules.py` | | 校验逻辑 | `tests/test__validation.py` | diff --git a/tests/samples/test_action_core_contract.py.sample b/tests/samples/test_action_core_contract.py.sample new file mode 100644 index 0000000..5bcc8c0 --- /dev/null +++ b/tests/samples/test_action_core_contract.py.sample @@ -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() diff --git a/tests/samples/test_sync_contract.py.sample b/tests/samples/test_sync_contract.py.sample new file mode 100644 index 0000000..806f164 --- /dev/null +++ b/tests/samples/test_sync_contract.py.sample @@ -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() diff --git a/tests/test_actions_manifest.py b/tests/test_actions_manifest.py index cbccb0c..61afb5c 100644 --- a/tests/test_actions_manifest.py +++ b/tests/test_actions_manifest.py @@ -5,9 +5,10 @@ from __future__ import annotations import json import os import re +import sqlite3 import unittest -from _support import get_skill_root +from _support import IsolatedDataRoot, get_skill_root from cli.app import build_parser from util.constants import SKILL_SLUG @@ -15,9 +16,13 @@ from util.constants import SKILL_SLUG _TEMPLATE_PLACEHOLDER_SLUG = "your-skill-slug" _ALLOWED_PLACEMENTS = frozenset({"toolbar", "row", "batch", "cron", "agent", "skill-detail"}) _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_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 = ( "wechat", "微信", @@ -66,6 +71,88 @@ def _load_actions_schema() -> dict: 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): def test_manifest_exists_and_schema(self) -> None: manifest = _load_actions_manifest() @@ -108,6 +195,157 @@ class TestActionsManifest(unittest.TestCase): for placement in placements: 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-004:4 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: manifest = _load_actions_manifest() 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}", ) + 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: path = os.path.join(get_skill_root(), "references", "ACTIONS.md") with open(path, encoding="utf-8") as f: @@ -223,14 +472,23 @@ class TestActionsManifest(unittest.TestCase): "严格规范", "向后兼容", "Phase 1", - "bind", + "bind.tables", "concurrency", "locks", "row", "batch", "additionalProperties", + "placements", + "executionProfile", ): 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__": diff --git a/tests/test_development_policy_guard.py b/tests/test_development_policy_guard.py index 87bf0f1..64336ae 100644 --- a/tests/test_development_policy_guard.py +++ b/tests/test_development_policy_guard.py @@ -46,6 +46,11 @@ POLICY_IDS = ( "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 = ( @@ -871,6 +876,241 @@ class TestPolicySkillAction001(unittest.TestCase): ) +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): def test_policy_matrix_exists_and_lists_policy_ids(self) -> None: skill_root = get_skill_root() diff --git a/tools/README.md b/tools/README.md index 133b8ed..e59ba1c 100644 --- a/tools/README.md +++ b/tools/README.md @@ -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` 等) - 覆盖 `assets/actions.json`、`SKILL.md`、`scripts/util/constants.py` 等生成文件;文档中的路径示例可保留占位,但生成后的技能文件不得残留占位符 - **不**自动修改 `actions.json` 中的 CLI 业务命令;技能作者自行增删 action +- **不**移除 Schema 中的 `bind.tables` 支持,**不**把 `bind` 当模板残留清理 +- **不**自动生成业务表名,**不**给 `health` / `version` / `config-path` 自动加 `toolbar` +- **不**生成任何具体平台业务 Action - **不**自动 `git init`;打印后续 Git 与测试命令 目标目录若已存在且非空,需加 `-Force` / `--force`(且目标**不得**含 `.git`)。