# oil-skill-creator

Adopt this skill: https://proskills.md/skills/other/oil-oil-oil-skill-creator

Page: https://proskills.md/skills/other/oil-oil-oil-skill-creator
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 10698
sha: 02332158eeaab586b226f5a4c773708f824ddd5e
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/SKILL.md

````text
---
name: oil-skill-creator
description: 创建、评审、整改和发布 Skill，并规划免费版与付费版、收款交付和更新机制。用户想从零创建 Skill、评审现有 Skill、检查它是否真正有用、修复触发或执行流程，改善首次使用、稳定性、Token 开销、文件分层、弱模型可读性与跨平台兼容性，或者想为 Skill 收费时使用。不要用于执行目标 Skill 负责的实际任务，也不要因为普通的编码、设计或写作请求触发。
license: MIT
compatibility: 核心脚本只使用 Python 3 标准库；可选凭据输入页需要 Node.js 22.18+ 和系统凭据服务，已验证 macOS，Windows 与 Linux 待实机验证；独立效果评估需要隔离执行能力。
metadata:
  version: "1.1.0"
---

# oil-skill-creator

把 Skill 当作需要长期维护的工具。先确认它解决了重复问题，再让它容易开始、稳定执行、能够验证，并如实说明兼容范围。不要把一次任务的提示词包装成 Skill。

## 先选择模式

| 模式 | 适用情况 | 路径 | 默认停止点 |
| --- | --- | --- | --- |
| 创建 | 还没有 Skill | 产品定义 → 最小骨架与评估 → 基线 → 实现与对照 → 按需发布 | 交付可用 Skill |
| Review | 用户只要求评审、审计或找问题 | 读取 → 需求适用表 → 静态检查 → 流程检查 → 报告 | 交付报告后停止 |
| 整改 | 已有 Skill，用户要求修复或优化 | 读取 → 需求适用表 → 静态检查 → 按需保存快照 → 局部修改 → 复验 | 问题修复且无回归 |
| 商业化 | 想为 Skill 收费，或评审已收费的 Skill | 能否收费 → 分界 → 引流与落地页 → 收款 → 交付与更新 | 交付方案或改好的 Skill |

Review 只读：不修改文件、不创建快照、不打包。用户看完报告再授权整改时，从整改路径重新开始。整改不用脚手架重建已有目录，只在用户要求交付发布包时打包。

## 开始前

已有 Skill 时，先完整读取 `SKILL.md`，再只读取当前模式和问题需要的资源。已有信息不要再问。只有目标或交付物不清楚、需要新增权限或服务、可能覆盖内容，或者主观方向会改变结果时才询问，并把问题一次问完。

分工如下：

- Agent 判断价值、边界、架构、例外和主观质量。
- 程序执行确定、重复、可验证、失败敏感的步骤。
- 隔离执行者运行触发测试和效果对照。它不继承作者的工作上下文，只拿到本次请求和指定 Skill，通常是子 Agent。
- 人判断审美、文案和整体体验。

下文的 `<python>` 指已确认版本不低于 3.10 的 Python 解释器：macOS 和 Linux 通常是 `python3`，Windows 通常是 `py -3`。不要假设 `python` 命令一定存在。

## 创建路径

先读 [产品设计](references/product-design.md)，确认问题值得做，并明确用户、当前做法、预期改善、输入、输出、边界、风险和任务类型。一次性需求、普通 Agent 已能稳定完成，或者说不清使用后会改善什么时，不要强行创建。

需要脚手架时先预览最小骨架，确认后去掉 `--dry-run` 再运行一次；骨架只确定目录和元数据，不先写长说明：

```text
<python> <oil-skill-creator>/scripts/scaffold_skill.py <skill-name> --output-root <目录> --description <描述> --public --dry-run
```

只用 `--components` 添加当前确实需要的目录，例如 `--components scripts,tests`，不为示例完整而创建空资源。需要版本号时加 `--version 0.1.0`。

再读 [评估规范](references/evaluation.md)，准备至少 3 条真实评估并固定模型和执行者，先运行 `without_skill` 基线，再开始大量编写：

```text
<python> <oil-skill-creator>/scripts/prepare_evaluation.py <skill-path> --mode create --iteration 1 --model <模型> --executor <隔离执行者> --allow-missing-skill
```

`--allow-missing-skill` 只在目录还只有 evals 时使用；已有最小骨架可省略。基线完成后按“设计和编写”实现最小候选，沿用同一 `run_plan.json` 运行 `with_skill`，聚合并检查结果，再运行程序校验。

## Review 与整改路径

先读 [Review 与整改规范](references/review-and-remediation.md)，按其中的检查顺序执行。三个节点不能跳过：

- 运行校验器之前先建需求适用表，批量评审时逐个 Skill 登记。需要用户输入 Key 的 Skill，第一次 Review 就核对凭据入口，这一项最容易漏。
- 校验器只确认结构问题。Skill 是否有用、流程是否合理、兼容性是否属实，要另外检查。
- 按 P0、P1、P2 报告。Review 交付报告后停止。

整改第一次编辑前判断是否需要旧版快照：要让隔离执行者运行旧版做前后对照、用户要求保留独立基线，或旧版无法从 Git 等可靠来源恢复时，运行 `<python> <oil-skill-creator>/scripts/snapshot_skill.py <skill-path>`；其他整改不建快照，直接局部修改并复验。

## 商业化路径

先读 [商业化](references/monetization.md)，按其中顺序推进：先回答“能不能收费”的四个问题，答不上就停在免费版并说明原因；能收费时再依次规划分界、引流与落地页、收款渠道、交付与更新。评审已收费的 Skill 时只做其中的“商业化体检”，按 Review 的规则只读交付。

## 设计和编写

核心规则：

- 触发信息只放在 frontmatter `description`：做什么、什么时候用、哪些相似请求不该触发、与其他 Skill 怎么分工。先讲任务和产物，不用模型、服务商或宿主的名字代替功能介绍。正文不重复触发规则。
- 默认宿主中立：正式指令、参考资料、README、目录名和示例使用“Agent、宿主、能力、隔离执行者”等通用名称。确实依赖某个宿主时，专用适配器与通用流程分开，并在兼容性中写明。
- 登录、密钥、系统安装、覆盖、删除和外部写入先获得授权。密钥值不进 JSON、Skill 文件、日志或 Agent 上下文。
- 重复运行初始化或迁移不能破坏已有配置或产生重复结果。失败时保留可用的中间产物，说明停在哪一步、怎么恢复、还有哪些必做步骤没执行。
- 正文写目标、判断原则、主流程、必要分支和停止条件，不穷举情境。一步只表达一个主要动作，分支紧邻对应步骤，术语保持一致。有限、稳定、可验证的分支交给程序；依赖语义的选择留给 Agent。
- 只写能用于同类任务的规则、程序和回归测试。具体任务、个人目录、单次候选、Review 记录和修改历史不进 Skill。
- 不得包含与 description 不一致的隐藏行为、误导能力、越权访问或数据外传。兼容性只声明实际实现或真实验证过的范围。

按问题读取参考资料：

| 要解决的问题 | 参考 |
| --- | --- |
| 首次使用、配置、确认操作、失败恢复；阶段完成后提示下一步；大型产物分段产出或可复用操作页面 | [产品设计](references/product-design.md) |
| 批量、破坏性、复杂校验或高代价操作 | [计划、校验与执行](references/plan-validate-execute.md) |
| 宿主依赖、平台差异、普通配置与凭据存储 | [兼容性](references/compatibility.md) |
| 本机需要输入 API Key 等单行凭据，且没有现成安全入口 | [凭据输入页](references/credential-ui.md)，用安装脚本接入随附组件，不为每个 Skill 重新生成页面 |
| 拆分文件、篇幅、目录导航、Token 开销、弱模型可读性 | [信息架构](references/information-architecture.md) |
| 触发准确性、效果对照、迭代与停止 | [评估规范](references/evaluation.md) |
| README、安装入口、发布门槛、打包、密钥筛查 | [GitHub 发布](references/publishing.md) |
| 版本号设置、升版、标签 | [版本管理](references/versioning.md) |
| 收费、免费版与付费版、收款、交付、更新提示 | [商业化](references/monetization.md) |

## 程序校验

开发过程中运行 `<python> <oil-skill-creator>/scripts/validate_skill.py <skill-path>`。公开发布或整改完成前加上严格选项：

```text
<python> <oil-skill-creator>/scripts/validate_skill.py <skill-path> --public --strict --weak-model --universal
```

`--weak-model` 使用更严格的结构限制，`--universal` 检查是否写死了宿主品牌或专属路径；只有产品明确依赖某个宿主时才省略 `--universal`，并在兼容性中说明原因。校验通过只说明程序能确认的问题没有出现，不说明 Skill 有用。

## 效果评估

用户要求证明效果、整改带来静态检查确认不了的重大行为变化，或者正式发布需要效果证据时，按 [评估规范](references/evaluation.md) 用程序准备目录、运行、聚合并生成评审页。创建模式与普通 Agent 对照，整改模式与写入前的快照对照。目标明确的小范围修正，用静态校验和针对性回归即可。

把候选结果、证据和对比报告交给用户，收到反馈前不再修改 Skill。没有隔离执行能力时，说明评估受限，不宣称已完成独立对照。效果不好时先查明原因，不直接追加规则。

## 兼容与发布

发布前读 [兼容性](references/compatibility.md) 和 [GitHub 发布](references/publishing.md)，按其中的门槛检查并打包。README 面向使用者，说明价值、安装、配置、兼容范围、数据边界和输出，不复制 Agent 的执行步骤。版本号只记在源 Skill 的 `metadata.version`，按 [版本管理](references/versioning.md) 设置和升版。

## 完成标准

- 创建：价值成立，主流程可执行，静态校验通过，已说明效果证据与未验证项。
- Review：结论有证据，缺陷与取舍分开，给出按优先级排列的最小整改方案，没有修改文件或外部状态。
- 整改：需求适用表逐项有实现和验证证据，凭据项覆盖页面、保存、恢复和实际业务读取；P0、P1 已处理或由用户明确接受；相关回归测试通过，没有覆盖无关内容；做了前后效果对照的，快照和对照证据完整。
- 商业化：先给出能否收费的结论；规划或改动覆盖分界、引流、收款、交付和更新，没有遗漏的半截流程。

交付时只报告文件路径、主要能力、程序与测试结果、已确认的兼容范围、效果证据和剩余风险。不复述整个 Skill，也不把执行过程写回正式文件。
````

## File: assets/credential-ui/README.md
size: 8173
sha: f257604bf4630d9e5a9328e9bb2b78e7bd26d42a
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/README.md

````text
# 可复用凭据输入页

供本机桌面 Skill 配置 API Key、访问令牌等单行凭据。一个 Key 使用紧凑单输入框，多个 Key 在同页纵向排列，共用一个保存按钮。页面默认黑白灰，密钥只存系统凭据库。

## 适用范围

适合没有现成安全配置入口、需要用户首次填写或更换 API Key、访问令牌、Client Secret 的本机桌面 Skill。已有宿主凭据能力优先复用。

| 其他场景 | 使用方式 |
| --- | --- |
| OAuth、验证码或账号登录 | 服务官方授权流程 |
| 模型名、地址、目录等普通设置 | 普通配置文件或设置页 |
| 私钥文件、证书、多行密钥 | 专用凭据或文件授权机制 |
| CI、容器、远程服务器 | 已有 Secret 管理与可信运行时注入，不暴露本机输入页到网络 |

本组件减少密钥进入 Agent 对话和工具输出的机会，不是对同一用户下任意代码执行或浏览器控制的强隔离。

## 安装与单项配置

要求 Node.js 22.18+，以及下文对应系统凭据服务。首次下载依赖后，本地输入页可离线运行：

```bash
npm ci --ignore-scripts
npm run configure -- --label "服务 API Key" --title "输入密钥" --placeholder "粘贴你的密钥"
npm start
```

用户打开返回的本机链接，亲自填写并保存。默认字段文件为 manifests/default.json；configure 只修改非敏感声明，不接收密钥。支持 --dry-run 和 --save-label。

字段声明示例：

```json
{
  "version": 1,
  "id": "sample-skill",
  "label": "服务 API Key",
  "credential": "sample-skill/service/default",
  "ui": { "title": "输入密钥", "placeholder": "粘贴你的密钥", "saveLabel": "保存" }
}
```

id、label、credential 必填，ui 可省略。每项只接受非空单行密钥，最长 2500 个字符；系统后端的容量限制仍可能更低，失败时不会改存明文文件。密钥值不属于声明字段。

## 同页填写多个 Key

先创建另一项独立声明：

```bash
npm run configure -- --manifest manifests/image.json --id sample-skill --label "图片服务 API Key" --credential sample-skill/image/default --placeholder "粘贴图片服务密钥"
```

临时组合：

```bash
npm start -- --manifest manifests/default.json --manifest manifests/image.json
```

可复用页面配置：

```bash
npm run configure-page -- --page manifests/setup.page.json --manifest manifests/default.json --manifest manifests/image.json --title "连接服务" --label "两项服务" --save-label "保存"
npm start -- --page manifests/setup.page.json
```

页面 JSON 只保存引用与文案：

```json
{
  "version": 1,
  "manifests": ["default.json", "image.json"],
  "ui": { "title": "连接服务", "label": "两项服务", "saveLabel": "保存" }
}
```

每页 1 至 16 项，顺序由 manifests 决定。文件内的路径相对于页面配置文件，CLI 参数路径相对于运行目录。配置命令自动转换为相对路径；支持三端搬移。

只改页面文案：

```bash
npm run configure-page -- --page manifests/setup.page.json --title "配置服务"
```

不传 --manifest 保留列表，传入时替换整组。支持 --dry-run。字段标签和占位文字继续由 configure 修改；同页标题与按钮来自页面 ui。修改配置后重新启动。--page 和启动时的 --manifest 互斥。

已有字段声明的 id 与 credential 不可直接改写；新账号另建声明，不同账号使用不同引用。移除页面字段只改变表单，不删除系统凭据。

## 保存与恢复

尚未配置项必填；已有项显示“已配置”，留空保留，输入新值才替换。原值不会回填页面。替换按钮固定显示“替换并保存”，自定义文案不能覆盖这一提示。

整组预检通过后顺序保存。系统凭据库没有跨项事务：中途失败保留成功项、停止后续写入，并逐项标明结果，不自动回滚。用户先核对状态，再补填未完成项；后端报错可能存在结果不确定的情况，不能据此断言未写入。

提交结束或离开页面会清空输入。会话 30 分钟有效，全部成功后保留结果 90 秒。取消和过期不撤销此前保存。网络超时后先查状态，不重复提交。

Agent 只处理入口与脱敏状态，不自动操作含真实密钥的页面。/agent/status 使用启动令牌认证；只有 saved 表示全部成功，partial 表示部分失败。不要分享本机会话链接或让用户将密钥贴进聊天。

## 存储与平台

| 平台 | 后端 | 前提与管理入口 |
| --- | --- | --- |
| macOS | Keychain 钥匙串 | 当前用户钥匙串可访问；“钥匙串访问”中管理，系统授权由用户确认 |
| Windows | Credential Manager 凭据管理器 | 当前用户会话可用；“凭据管理器 → Windows 凭据”中的对应通用凭据 |
| Linux | secret-tool / Secret Service | libsecret 工具、用户 D-Bus 会话及已解锁的 Secret Service 实现，例如 GNOME Keyring；管理入口依桌面环境而定 |

macOS / Windows 通过 @napi-rs/keyring 原生绑定。Linux 显式调用 secret-tool，保存值经标准输入传递，不使用可能降级到临时 keyutils 的默认绑定。

服务标识为 org.oiloil.skill-credentials，账号属性为声明的 credential。不同后端界面显示名称可能不同。存储属于当前系统用户，本组件不负责跨设备同步、备份或迁移旧文件。

凭据库不可用或被锁定时停止，明确提示检查服务；不自动安装、解锁或降级到 JSON、浏览器存储等明文介质。服务器、无桌面 Linux 或其他凭据实现必须另行确认实际能力。

当前 macOS 已验证；Windows / Linux 已实现适配但尚未实机验证。

## 业务使用

把真实可信程序与环境变量名代入：

```bash
node src/run.ts --manifest manifests/default.json --env SERVICE_API_KEY -- your-program your-arguments
```

一次任务读取多个 Key：

```bash
node src/run.ts --manifest manifests/default.json --env FIRST_API_KEY --manifest manifests/image.json --env SECOND_API_KEY -- your-program your-arguments
```

全部读取成功后才启动程序，重复变量或缺少凭据时停止。页面文件只定义填写方式，业务端仍逐项绑定，避免注入不需要的密钥。密钥不进入命令参数或父进程环境。

包装器不是沙箱：可信子进程取得原值后仍可能打印或外传。需要强隔离时使用独立可信执行服务或宿主权限边界，不依赖密码框或系统凭据库作绝对保证。

检查单项状态：

```bash
npm run status -- --manifest manifests/image.json
```

仅返回配置状态与后端；未配置退出码 2，后端失败退出码 1。可信 Node.js 程序也可内部使用 nativeBackend 的 get / set / delete；保存与删除须用户授权，不向 Agent 暴露任意读取或删除接口。

## 开发验收

```bash
npm run check
npm run build
npm test
npm run test:native
```

常规测试使用假后端与受控 DOM，不操作真实浏览器。原生测试经真实同页 HTTP 入口写入随机假凭据，检查多变量业务读取与隔离，最后清理测试项。修改前端后必须提交一致的 public/app.js，最终用户无需编译。

维护时同时验证单 Key、同页多 Key、留空保留、部分失败重试、未知字段拒绝、会话隔离、状态脱敏及系统后端。不能用另写的静态演示替代正式页面测试。

## 固定业务入口

`manifests/profiles.json` 只保存业务名、声明文件和环境变量，不保存密钥。目标 Skill 接入时提供实际配置名；单项或多项复用相同页面与运行器：

```bash
node src/profile.ts status default
node src/profile.ts setup default
node src/profile.ts run default -- your-program your-arguments
```

status 退出码 0 表示所需凭据可读取，2 表示缺失，1 表示后端或配置错误。setup 由用户亲自填写；run 优先复用运行时环境变量，缺失时仅读取对应声明，不把其他服务凭据注入任务。指定其他服务时同时修改业务参数，不能只换凭据。
````

## File: README.md
size: 9279
sha: 1d90ae3e5bdd5fc871447896cadfe45a51e2a6cb
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/README.md

````text
<p align="center">
  <img src="./assets/readme/hero.png" width="100%" alt="oil-skill-creator：像做产品一样写 Skill">
</p>

创建、评审和改进 Skill，检查功能边界、首次配置、执行稳定性、兼容性与发布交付。

> 静态校验通过，只能证明已知结构没有问题，不能证明一个 Skill 真的有用。

## 三种使用模式

| 模式 | 什么时候使用 | 默认结果 |
| --- | --- | --- |
| 创建 | 从零设计一个可重复使用的 Skill | 可执行、可验证的 Skill |
| Review | 只想知道现有 Skill 哪里有问题 | 按 P0、P1、P2 排列的只读报告 |
| 整改 | 已经确认需要修复或优化 | 按需保留基线、局部修改并完成复验 |

Review 不修改任何文件。整改时只有需要前后效果对照，才先保存旧版快照。

## 安装

### 让 Agent 安装

复制下面的仓库地址，告诉你正在使用的 Agent：“请帮我安装这个 Skill。”

```text
https://github.com/oil-oil/oil-skill-creator
```

### 使用命令安装

```shell
npx skills add oil-oil/oil-skill-creator
```

### 运行要求

- Python 3.10+。核心脚本只用标准库，不需要安装依赖、密钥或初始化配置。下文的 `<python>` 在 macOS 和 Linux 通常是 `python3`，Windows 通常是 `py -3`。
- 命令安装需要 `npx`。Node.js 只是安装工具的依赖，核心流程不需要它。
- 可选的凭据输入页需要 Node.js 22.18+。

## 开始使用

直接用自然语言说明目标和写入权限：

```text
用 oil-skill-creator 创建一个可公开发布的 Skill。
```

```text
只 Review 这个 Skill，按优先级给出证据，不要修改文件。
```

```text
整改这个现有 Skill；如果需要前后效果对照，先保留旧版基线，再修复和复验。
```

```text
验证新版是否比普通 Agent 或旧版更有效。
```

已有文件里写清楚的用户、输入、输出或平台限制，不会再问你。只有缺少的决定会改变结果、需要新权限或可能覆盖内容时，才会一次问完。

## 它重点检查什么

### 值不值得做

先确认它解决的是重复问题，并且相比普通 Agent 有看得到的改善。一次性任务、简单提醒或普通 Agent 已经做得稳定的工作，不会被强行包装成 Skill。

### 触发边界清不清楚

description 写清该接哪些请求、不该接哪些相似请求。需要时用固定的正反向测试集实测触发准确率，不凭关键词或直觉判断。

### Agent 和程序分工是否合理

语义、策略、例外和主观质量交给 Agent 或你来判断；结构、格式、统计、组装和打包这类确定步骤交给程序。这样既减少遗漏，也不会把主观问题硬编码成一棵越长越大的规则树。

### 首次使用顺不顺

能自动发现、风险低、可撤销的准备工作直接完成，登录、密钥、安装和覆盖先问你。失败后保留可用的中间结果，并说明怎么恢复。

### 大型产物和复杂配置

产物容易写成难以维护的巨型单文件时，检查能否按稳定边界拆开、单独验证和局部重做，再由脚本组装；不按固定行数机械拆分。复杂配置或反复预览，用读取 manifest 的固定页面代替每次临时生成界面。

### 密钥输入

目标 Skill 需要在本机输入 API Key 时，可以装上随附的[凭据输入页](references/credential-ui.md)：一个页面填 1 到 16 个 Key，密钥存进系统凭据库（macOS 钥匙串、Windows 凭据管理器或 Linux Secret Service），不经过聊天，也不写进配置文件。已有安全入口时优先复用；OAuth、CI 和远程服务器另按实际需求设计。

### 想为 Skill 收费

先判断值不值得收费，再规划免费版和付费版怎么分、怎样从 GitHub 和落地页引流、怎么收款和交付、更新怎么提示才不打扰用户也不像恶意软件。这些来自一套真实运行的付费 Skill 链路，见[商业化](references/monetization.md)。想看实际效果，可以参考 [ui.oiloil.org](https://ui.oiloil.org) 的产品页和账户页，以及开源命令行工具 [oil-cli](https://github.com/oil-oil/oil-cli)。

### 弱模型能否看懂、Token 花在哪

检查入口、模式、术语、分支位置和资源读取时机。主文件只保留主流程，阶段细节按需读取，同一规则只写在一处。

## 稳定工具

| 工具 | 用途 |
| --- | --- |
| `scaffold_skill.py` | 预览并创建最小 Skill 骨架，拒绝覆盖已有目录 |
| `install_credential_ui.py` | 向现有 Skill 安装凭据输入页，生成非敏感声明并保护已有修改 |
| `validate_skill.py` | 检查结构、链接、重复、个人路径、明文凭据、弱模型风险和宿主中立 |
| `review_requirements.py` | Review 时收集凭据和生成工具线索，供需求适用表逐项核对 |
| `version_skill.py` | 预览或写入 `metadata.version` 的初始版本与升版 |
| `snapshot_skill.py` | 在需要效果对照时保存不可覆盖的旧版基线 |
| `prepare_evaluation.py` | 创建固定的新版、普通 Agent 或旧版对照目录 |
| `aggregate_evaluation.py` | 聚合执行结果、耗时和检查数据 |
| `generate_review.py` | 生成不自动打开浏览器的本地静态评审页 |
| `score_triggers.py` | 统计正向、反向和保留集上的触发表现 |
| `package_skill.py` | 生成内容稳定、默认不覆盖的 `.skill` 发布包 |

查看任一工具的参数：

```text
<python> scripts/validate_skill.py --help
```

## 效果评估

创建模式先准备至少 3 条真实评估并运行“普通 Agent”基线，再编写最小 Skill 和对照；整改需要证明效果时，比较当前版本和写入前快照。程序负责准备固定目录、检查数据格式和聚合结果，子 Agent 等隔离执行环境分别运行两边，审美、文案和整体体验由人来判断。

每轮固定一个模型和执行者；需要验证多个模型时使用不同的 `iteration-N`，不混合汇总。目标目录还只有 `evals/evals.json` 时，create 模式可加 `--allow-missing-skill`，候选完成后沿用同一计划。

```text
<python> scripts/prepare_evaluation.py <skill-path> --mode create --iteration 1 --model <模型> --executor <隔离执行者> --allow-missing-skill
<python> scripts/aggregate_evaluation.py <iteration-path>
<python> scripts/generate_review.py <iteration-path>
```

schema 2 的每次运行还要在对应 `run-N/` 保存 `execution.json`，记录实际 `model`、`executor` 和 `skill_hash`；可用 `snapshot_skill.py <skill-path> --dry-run --json` 获取内容摘要。没有子 Agent 或等价的隔离执行能力时，仍可完成静态 Review、程序测试和作者试跑，但不能宣称已经完成独立对照。

## 兼容性

| 范围 | 当前状态 |
| --- | --- |
| Python | 3.10+，核心脚本只使用标准库 |
| macOS | 已运行自动化测试 |
| Windows / Linux | 已按标准库和跨平台路径实现，真实平台运行仍待验证 |
| 无浏览器或 GUI | 核心流程可用；评审页只生成文件，不自动打开 |
| 无子 Agent | 创建、静态 Review 和程序测试可用；独立效果对照降级 |
| 离线环境 | 核心脚本只处理本地文件，不联网 |
| 可选凭据输入页 | Node.js 22.18+；macOS 原生保存与回读已验证，Windows / Linux 待实机验证 |

脚本使用 `pathlib` 和 UTF-8，不依赖 bash、PowerShell、Homebrew 或单平台打开命令。兼容性只描述已经实现或验证过的范围。

## 数据与安全边界

- 只处理用户明确指定的本地文件；普通配置与密钥分开保存；
- 本项目核心流程无需密钥；可选凭据输入页用于目标 Skill，JSON 只保存非敏感声明和凭据引用；
- 系统凭据库不能单独隔离同一用户下有任意代码执行权限的 Agent；业务读取程序仍须可信，不向上下文回传密钥；
- 默认拒绝覆盖已有 Skill、快照、评审页、iteration 和发布包；
- 打包默认排除 Git、虚拟环境、缓存、评估数据和运行 workspace；
- 不负责执行目标 Skill 的实际业务任务；
- 不用 AI 自评分数替代视觉、文案等主观评审；
- Review、反馈、版本差异和单次任务记录不会写入正式 Skill。

## 开发与验证

```text
<python> -m unittest discover -s tests -v
<python> scripts/validate_skill.py . --public --strict --weak-model --universal
```

测试覆盖文件保护、快照、基础结构、资源链接、敏感信息、宿主中立、内容重复、弱模型结构、效果评估、触发测试、版本管理和可重复打包。

凭据输入页另有多 key 存储隔离、并发页面会话和多变量注入测试。[跨平台工作流](.github/workflows/credential-ui.yml) 在推送、PR 或手动触发时测试三种桌面系统与两个 Node.js 版本，使用随机假凭据验证真实系统后端。工作流配置完成不等于三端已经通过，需要以实际运行记录为准。

需要继续设计 GitHub 首页时，可以使用 [beautify-github-readme](https://github.com/oil-oil/beautify-github-readme) 调整阅读顺序或制作视觉资源；它不是安装或运行依赖。

## 许可证

[MIT](./LICENSE)
````

## File: scripts/__init__.py
size: 58
sha: 6ccd3b135582029bcb85d4fc7118753d6b5cfda5
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/__init__.py

```text
"""oil-skill-creator 内置的确定性辅助程序。"""
```

## File: scripts/aggregate_evaluation.py
size: 13915
sha: 5faf43864cf21580734e8c5d1656ebf10d80163e
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/aggregate_evaluation.py

```text
#!/usr/bin/env python3
"""检查评估运行数据，并生成 JSON 与 Markdown 对比报告。"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

try:
    from .evaluation_common import load_json, summarize
except ImportError:
    from evaluation_common import load_json, summarize

def _number(value: object, label: str) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f"{label} 必须是数字")
    if value < 0:
        raise ValueError(f"{label} 不能为负数")
    return float(value)

def _read_grading(path: Path, expectations: list[str]) -> tuple[float | None, list[dict[str, Any]]]:
    if not path.is_file():
        if expectations:
            raise ValueError(f"缺少 grading.json：{path}")
        return None, []
    data = load_json(path)
    items = data.get("expectations") if isinstance(data, dict) else None
    if not isinstance(items, list):
        raise ValueError(f"grading.expectations 必须是数组：{path}")
    normalized: list[dict[str, Any]] = []
    for index, item in enumerate(items, start=1):
        if not isinstance(item, dict):
            raise ValueError(f"grading expectation 必须是对象：{path}:{index}")
        text = item.get("text")
        passed = item.get("passed")
        evidence = item.get("evidence")
        if not isinstance(text, str) or not text.strip():
            raise ValueError(f"grading.text 缺失：{path}:{index}")
        if not isinstance(passed, bool):
            raise ValueError(f"grading.passed 必须是布尔值：{path}:{index}")
        if not isinstance(evidence, str) or not evidence.strip():
            raise ValueError(f"grading.evidence 缺失：{path}:{index}")
        normalized.append(
            {"text": text.strip(), "passed": passed, "evidence": evidence.strip()}
        )
    expected_texts = set(expectations)
    actual_texts = {item["text"] for item in normalized}
    if expected_texts and actual_texts != expected_texts:
        raise ValueError(f"grading 与 eval_metadata 的 expectations 不一致：{path}")
    return (
        sum(1 for item in normalized if item["passed"]) / len(normalized)
        if normalized
        else None,
        normalized,
    )

def _read_timing(path: Path) -> tuple[float, float]:
    data = load_json(path)
    if not isinstance(data, dict):
        raise ValueError(f"timing.json 顶层必须是对象：{path}")
    tokens = _number(data.get("total_tokens"), f"{path}.total_tokens")
    if "duration_ms" in data:
        duration = _number(data["duration_ms"], f"{path}.duration_ms") / 1000
    else:
        duration = _number(
            data.get("total_duration_seconds"), f"{path}.total_duration_seconds"
        )
    return tokens, duration

def _read_execution(path: Path, run: dict[str, Any]) -> dict[str, Any]:
    if not path.is_file():
        raise ValueError(f"缺少 execution.json：{path}")
    data = load_json(path)
    if not isinstance(data, dict):
        raise ValueError(f"execution.json 顶层必须是对象：{path}")
    for field in ("model", "executor"):
        actual = data.get(field)
        if not isinstance(actual, str) or not actual.strip():
            raise ValueError(f"execution.{field} 必须是非空字符串：{path}")
        if actual.strip() != run.get(field):
            raise ValueError(
                f"execution.{field} 与 run_plan 不一致：{actual.strip()!r} != {run.get(field)!r}"
            )
    skill_hash = data.get("skill_hash")
    if skill_hash is not None and (
        not isinstance(skill_hash, str)
        or len(skill_hash) != 64
        or any(character not in "0123456789abcdef" for character in skill_hash)
    ):
        raise ValueError(f"execution.skill_hash 必须是 64 位小写 SHA-256 或 null：{path}")
    configuration = run.get("configuration")
    if configuration == "without_skill" and skill_hash is not None:
        raise ValueError("without_skill 的 execution.skill_hash 必须为 null")
    if configuration != "without_skill" and skill_hash is None:
        raise ValueError(f"{configuration} 必须记录实际加载的 execution.skill_hash")
    planned_hash = run.get("skill_hash")
    if planned_hash is not None and skill_hash != planned_hash:
        raise ValueError("execution.skill_hash 与 run_plan 不一致，Skill 内容可能在运行前后变化")
    return {
        "model": str(data["model"]).strip(),
        "executor": str(data["executor"]).strip(),
        "skill_hash": skill_hash,
    }

def aggregate_evaluation(
    iteration_path: str | Path,
    allow_incomplete: bool = False,
) -> dict[str, Any]:
    root = Path(iteration_path).expanduser().resolve()
    plan_path = root / "run_plan.json"
    plan = load_json(plan_path)
    if not isinstance(plan, dict) or not isinstance(plan.get("runs"), list):
        raise ValueError("run_plan.json 缺少 runs 数组")
    configurations = plan.get("configurations")
    if not isinstance(configurations, list) or len(configurations) != 2:
        raise ValueError("run_plan.json 必须包含两个 configurations")
    schema_version = plan.get("schema_version", 1)
    if schema_version not in {1, 2}:
        raise ValueError(f"不支持的 run_plan.schema_version：{schema_version}")
    model = plan.get("model") if schema_version == 2 else None
    executor = plan.get("executor") if schema_version == 2 else None
    if schema_version == 2 and (
        not isinstance(model, str)
        or not model.strip()
        or not isinstance(executor, str)
        or not executor.strip()
    ):
        raise ValueError("schema 2 的 run_plan 必须记录非空 model 和 executor")

    run_results: list[dict[str, Any]] = []
    incomplete: list[str] = []
    for run in plan["runs"]:
        if not isinstance(run, dict):
            raise ValueError("run_plan.runs 项必须是对象")
        if schema_version == 2 and (
            run.get("model") != model or run.get("executor") != executor
        ):
            raise ValueError("run 的 model 或 executor 与本轮 run_plan 不一致，拒绝混合聚合")
        run_dir = Path(str(run.get("run_dir", ""))).expanduser().resolve()
        try:
            run_dir.relative_to(root)
        except ValueError as exc:
            raise ValueError(f"run_dir 越出 iteration：{run_dir}") from exc
        expectations = run.get("expectations", [])
        if not isinstance(expectations, list) or not all(
            isinstance(value, str) for value in expectations
        ):
            raise ValueError(f"run expectations 无效：{run.get('run_id')}")
        try:
            pass_rate, grading = _read_grading(run_dir / "grading.json", expectations)
            timing_path = run_dir / "timing.json"
            if not timing_path.is_file():
                raise ValueError(f"缺少 timing.json：{timing_path}")
            tokens, duration = _read_timing(timing_path)
            execution = _read_execution(run_dir / "execution.json", run) if schema_version == 2 else None
        except ValueError as exc:
            if not allow_incomplete:
                raise
            incomplete.append(str(exc))
            continue
        run_results.append(
            {
                "run_id": run.get("run_id"),
                "eval_id": run.get("eval_id"),
                "eval_name": run.get("eval_name"),
                "configuration": run.get("configuration"),
                "repetition": run.get("repetition"),
                "model": execution["model"] if execution else None,
                "executor": execution["executor"] if execution else None,
                "skill_hash": execution["skill_hash"] if execution else None,
                "pass_rate": pass_rate,
                "total_tokens": tokens,
                "duration_seconds": duration,
                "expectations": grading,
            }
        )

    summaries: dict[str, dict[str, Any]] = {}
    for configuration in configurations:
        selected = [
            item for item in run_results if item["configuration"] == configuration
        ]
        skill_hashes = {
            item["skill_hash"] for item in selected if item["skill_hash"] is not None
        }
        if len(skill_hashes) > 1:
            raise ValueError(f"{configuration} 在同一轮出现多个 Skill 内容摘要，拒绝混合聚合")
        summaries[str(configuration)] = {
            "runs": len(selected),
            "skill_hash": next(iter(skill_hashes)) if skill_hashes else None,
            "pass_rate": summarize(
                [item["pass_rate"] for item in selected if item["pass_rate"] is not None]
            ),
            "duration_seconds": summarize(
                [item["duration_seconds"] for item in selected]
            ),
            "total_tokens": summarize([item["total_tokens"] for item in selected]),
        }

    primary = summaries[str(configurations[0])]
    baseline = summaries[str(configurations[1])]
    delta: dict[str, float | None] = {}
    for metric in ("pass_rate", "duration_seconds", "total_tokens"):
        primary_mean = primary[metric]["mean"]
        baseline_mean = baseline[metric]["mean"]
        delta[metric] = (
            round(float(primary_mean) - float(baseline_mean), 4)
            if primary_mean is not None and baseline_mean is not None
            else None
        )

    return {
        "schema_version": schema_version,
        "skill_name": plan.get("skill_name"),
        "iteration": plan.get("iteration"),
        "model": model,
        "executor": executor,
        "configurations": summaries,
        "delta_primary_minus_baseline": delta,
        "runs": run_results,
        "incomplete": incomplete,
    }

def _format_metric(metric: dict[str, object], percent: bool = False) -> str:
    value = metric.get("mean")
    deviation = metric.get("stddev")
    if value is None:
        return "无数据"
    if percent:
        return f"{float(value) * 100:.1f}% ± {float(deviation or 0) * 100:.1f}%"
    return f"{float(value):.2f} ± {float(deviation or 0):.2f}"

def render_markdown(benchmark: dict[str, Any]) -> str:
    lines = [f"# {benchmark.get('skill_name', 'Skill')} 效果对比", ""]
    if benchmark.get("model"):
        lines.extend(
            [
                f"模型：{benchmark['model']}",
                f"执行者：{benchmark.get('executor') or '未记录'}",
                "",
            ]
        )
    lines.extend(
        [
            "| 配置 | 运行数 | 通过率 | 秒 | Token | Skill SHA-256 |",
            "| --- | ---: | ---: | ---: | ---: | --- |",
        ]
    )
    for name, summary in benchmark["configurations"].items():
        skill_hash = summary.get("skill_hash")
        lines.append(
            "| "
            + " | ".join(
                [
                    name,
                    str(summary["runs"]),
                    _format_metric(summary["pass_rate"], percent=True),
                    _format_metric(summary["duration_seconds"]),
                    _format_metric(summary["total_tokens"]),
                    str(skill_hash)[:12] if skill_hash else "未记录",
                ]
            )
            + " |"
        )
    lines.extend(["", "## 当前版本与基线的差值", ""])
    labels = {
        "pass_rate": "通过率",
        "duration_seconds": "耗时（秒）",
        "total_tokens": "Token",
    }
    for name, value in benchmark["delta_primary_minus_baseline"].items():
        lines.append(f"- {labels.get(name, name)}：{'无数据' if value is None else value}")
    if benchmark["incomplete"]:
        lines.extend(["", "## 未完成数据", ""])
        lines.extend(f"- {item}" for item in benchmark["incomplete"])
    return "\n".join(lines) + "\n"

def write_benchmark(
    iteration_path: str | Path,
    allow_incomplete: bool = False,
    replace: bool = False,
) -> tuple[Path, Path, dict[str, Any]]:
    root = Path(iteration_path).expanduser().resolve()
    json_path = root / "benchmark.json"
    markdown_path = root / "benchmark.md"
    if not replace and (json_path.exists() or markdown_path.exists()):
        raise FileExistsError("对比报告已存在；使用 --replace 明确覆盖")
    benchmark = aggregate_evaluation(root, allow_incomplete=allow_incomplete)
    json_path.write_text(
        json.dumps(benchmark, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    markdown_path.write_text(
        render_markdown(benchmark), encoding="utf-8", newline="\n"
    )
    return json_path, markdown_path, benchmark

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="汇总当前 Skill 与基线的效果数据")
    parser.add_argument("iteration_path", help="iteration-N 目录")
    parser.add_argument(
        "--allow-incomplete", action="store_true", help="跳过缺少数据的运行并标记"
    )
    parser.add_argument("--replace", action="store_true", help="明确覆盖已有对比报告")
    parser.add_argument("--json", action="store_true", dest="as_json", help="输出 JSON")
    return parser

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        json_path, markdown_path, benchmark = write_benchmark(
            args.iteration_path,
            allow_incomplete=args.allow_incomplete,
            replace=args.replace,
        )
    except (ValueError, FileExistsError, OSError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1
    if args.as_json:
        print(json.dumps(benchmark, ensure_ascii=False, indent=2))
    else:
        print(f"已创建：{json_path}")
        print(f"已创建：{markdown_path}")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## File: scripts/evaluation_common.py
size: 4432
sha: 2fb3b019b36d61189d5b7dab66c992355ad3138a
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/evaluation_common.py

```text
"""评估脚本共用的数据格式和路径工具。"""

from __future__ import annotations

import json
import re
from pathlib import Path
from statistics import mean, pstdev
from typing import Any

SAFE_NAME_RE = re.compile(r"[^a-z0-9]+")

def load_json(path: Path) -> Any:
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except FileNotFoundError as exc:
        raise ValueError(f"文件不存在：{path}") from exc
    except json.JSONDecodeError as exc:
        raise ValueError(f"JSON 无效：{path}:{exc.lineno}:{exc.colno}") from exc

def safe_name(value: object, fallback: str) -> str:
    normalized = SAFE_NAME_RE.sub("-", str(value).strip().lower()).strip("-")
    return normalized[:80] or fallback

def validate_eval_set(
    path: Path,
    expected_skill_name: str | None = None,
    allow_empty: bool = False,
) -> dict[str, Any]:
    data = load_json(path)
    if not isinstance(data, dict):
        raise ValueError("evals 文件顶层必须是对象")
    skill_name = data.get("skill_name")
    if not isinstance(skill_name, str) or not skill_name.strip():
        raise ValueError("evals.skill_name 必须是非空字符串")
    if expected_skill_name and skill_name != expected_skill_name:
        raise ValueError(
            f"evals.skill_name 为 {skill_name!r}，与目标 Skill {expected_skill_name!r} 不一致"
        )
    evals = data.get("evals")
    if not isinstance(evals, list):
        raise ValueError("evals.evals 必须是数组")
    if not evals and not allow_empty:
        raise ValueError("evals.evals 必须包含至少一条测试")

    ids: set[str] = set()
    names: set[str] = set()
    normalized: list[dict[str, Any]] = []
    for index, item in enumerate(evals, start=1):
        if not isinstance(item, dict):
            raise ValueError(f"evals[{index}] 必须是对象")
        allowed_keys = {
            "id",
            "name",
            "prompt",
            "expected_output",
            "files",
            "expectations",
        }
        unexpected = sorted(set(item) - allowed_keys)
        if unexpected:
            raise ValueError(
                f"evals[{index}] 包含不支持字段：{', '.join(unexpected)}"
            )
        eval_id = str(item.get("id", "")).strip()
        if not eval_id or eval_id in ids:
            raise ValueError(f"evals[{index}].id 缺失或重复")
        ids.add(eval_id)
        raw_name = item.get("name")
        if not isinstance(raw_name, str) or not raw_name.strip():
            raise ValueError(f"evals[{index}].name 必须是描述性名称")
        name = safe_name(raw_name, f"eval-{eval_id}")
        if name in names:
            raise ValueError(f"evals[{index}].name 规范化后重复：{name}")
        names.add(name)
        prompt = item.get("prompt")
        expected = item.get("expected_output")
        files = item.get("files", [])
        expectations = item.get("expectations", [])
        if not isinstance(prompt, str) or not prompt.strip():
            raise ValueError(f"evals[{index}].prompt 必须是非空字符串")
        if not isinstance(expected, str) or not expected.strip():
            raise ValueError(f"evals[{index}].expected_output 必须是非空字符串")
        if not isinstance(files, list) or not all(isinstance(value, str) for value in files):
            raise ValueError(f"evals[{index}].files 必须是字符串数组")
        if not isinstance(expectations, list) or not all(
            isinstance(value, str) and value.strip() for value in expectations
        ):
            raise ValueError(f"evals[{index}].expectations 必须是非空字符串数组")
        normalized.append(
            {
                "id": eval_id,
                "name": name,
                "prompt": prompt.strip(),
                "expected_output": expected.strip(),
                "files": files,
                "expectations": [value.strip() for value in expectations],
            }
        )
    return {"skill_name": skill_name, "evals": normalized}

def summarize(values: list[float | int]) -> dict[str, float | int | None]:
    if not values:
        return {"mean": None, "stddev": None, "count": 0}
    numeric = [float(value) for value in values]
    return {
        "mean": round(mean(numeric), 4),
        "stddev": round(pstdev(numeric), 4) if len(numeric) > 1 else 0.0,
        "count": len(numeric),
    }
```

## File: scripts/generate_review.py
size: 14086
sha: fe79bb4202c65bdd51affe1d9337a8c95a1cb27d
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/generate_review.py

```text
#!/usr/bin/env python3
"""生成跨平台的本地评审页面，默认隐藏候选版本身份。"""

from __future__ import annotations

import argparse
import base64
import hashlib
import json
import sys
from pathlib import Path
from typing import Any

try:
    from .evaluation_common import load_json
except ImportError:
    from evaluation_common import load_json

TEXT_SUFFIXES = {".md", ".txt", ".json", ".csv", ".yaml", ".yml", ".html", ".css", ".py"}
IMAGE_MIME_TYPES = {
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".gif": "image/gif",
    ".webp": "image/webp",
    ".svg": "image/svg+xml",
}
MAX_PREVIEW_CHARS = 12000
MAX_EMBED_BYTES = 8 * 1024 * 1024

HTML_TEMPLATE = """<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>__TITLE__</title>
<style>
:root{color-scheme:light dark;font-family:ui-sans-serif,system-ui,sans-serif}body{max-width:1120px;margin:0 auto;padding:32px 20px;line-height:1.55}h1,h2,h3{line-height:1.2}.muted{opacity:.68}.eval{border-top:1px solid #8886;padding-top:24px;margin-top:32px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px}.card{border:1px solid #8886;border-radius:12px;padding:16px}.badge{display:block;font-weight:700;margin-top:12px}img{display:block;max-width:100%;height:auto;border-radius:8px}pre{white-space:pre-wrap;overflow:auto;background:#8881;padding:12px;border-radius:8px}textarea{width:100%;min-height:100px;box-sizing:border-box}table{border-collapse:collapse;width:100%}th,td{border-bottom:1px solid #8885;padding:8px;text-align:left}button{padding:10px 16px;border-radius:8px;border:1px solid #8888;cursor:pointer}.pass{color:#198754}.fail{color:#c43d3d}</style>
</head>
<body>
<h1 id="title"></h1>
<p class="muted">默认隐藏候选版本身份。先查看输出并填写反馈，再查看汇总；不要根据版本名称判断质量。</p>
<div id="content"></div>
<h2>对比结果</h2>
<div id="benchmark"></div>
<p><button id="export" type="button">导出 feedback.json</button> <span id="status" class="muted" aria-live="polite"></span></p>
<script id="review-data" type="application/json">__DATA__</script>
<script>
const data=JSON.parse(document.getElementById('review-data').textContent);
document.getElementById('title').textContent=data.title;
const storageKey='oil-skill-review:'+data.title;
let drafts={};let storageAvailable=true;try{drafts=JSON.parse(localStorage.getItem(storageKey)||'{}')}catch(_error){drafts={};storageAvailable=false}
const content=document.getElementById('content');
for(const item of data.evals){
  const section=document.createElement('section'); section.className='eval';
  const h=document.createElement('h2'); h.textContent=item.name; section.appendChild(h);
  const prompt=document.createElement('pre'); prompt.textContent=item.prompt; section.appendChild(prompt);
  const grid=document.createElement('div'); grid.className='grid';
  for(const run of item.runs){
    const card=document.createElement('article'); card.className='card';
    const title=document.createElement('h3'); title.textContent=run.candidate+' · 第 '+run.repetition+' 次'; card.appendChild(title);
    if(run.files.length===0){const p=document.createElement('p');p.className='muted';p.textContent='没有输出文件';card.appendChild(p)}
    for(const file of run.files){
      const label=document.createElement('p'); label.className='badge'; label.textContent=file.name+' · '+file.size+' bytes'; card.appendChild(label);
      if(file.data_url!==null){const img=document.createElement('img');img.src=file.data_url;img.alt=file.name;card.appendChild(img)}
      if(file.preview!==null){const pre=document.createElement('pre');pre.textContent=file.preview;card.appendChild(pre)}
    }
    if(run.grading.length){
      const ul=document.createElement('ul');
      for(const grade of run.grading){const li=document.createElement('li');li.className=grade.passed?'pass':'fail';li.textContent=(grade.passed?'通过：':'失败：')+grade.text+' — '+grade.evidence;ul.appendChild(li)}
      card.appendChild(ul);
    }
    const label=document.createElement('label'); label.className='badge'; label.htmlFor=run.candidate_id; label.textContent='反馈'; card.appendChild(label);
    const area=document.createElement('textarea'); area.id=run.candidate_id; area.dataset.candidateId=run.candidate_id; area.placeholder='记录可复用的反馈；没有问题可以留空'; area.value=drafts[run.candidate_id]||'';
    area.addEventListener('input',()=>{drafts[run.candidate_id]=area.value;try{localStorage.setItem(storageKey,JSON.stringify(drafts))}catch(_error){storageAvailable=false}}); card.appendChild(area);
    grid.appendChild(card);
  }
  section.appendChild(grid); content.appendChild(section);
}
const bench=document.getElementById('benchmark');
if(data.benchmark.length){
  const table=document.createElement('table');
  table.innerHTML='<thead><tr><th>候选</th><th>运行次数</th><th>通过率</th><th>秒</th><th>Token</th></tr></thead>';
  const body=document.createElement('tbody');
  for(const row of data.benchmark){const tr=document.createElement('tr');for(const value of [row.candidate,row.runs,row.pass_rate,row.duration,row.tokens]){const td=document.createElement('td');td.textContent=value;tr.appendChild(td)}body.appendChild(tr)}
  table.appendChild(body);bench.appendChild(table);
}else{bench.textContent='尚未生成对比报告';bench.className='muted'}
document.getElementById('export').addEventListener('click',()=>{
  const reviews=[...document.querySelectorAll('textarea')].map(area=>({candidate_id:area.dataset.candidateId,feedback:area.value,timestamp:new Date().toISOString()}));
  const blob=new Blob([JSON.stringify({status:'complete',reviews},null,2)+'\\n'],{type:'application/json'});
  const link=document.createElement('a');link.href=URL.createObjectURL(blob);link.download='feedback.json';link.click();URL.revokeObjectURL(link.href);
  document.getElementById('status').textContent=storageAvailable?'已导出；本机草稿仍会保留':'已导出';
});
</script>
</body>
</html>
"""

def _metric(value: object, percent: bool = False) -> str:
    if not isinstance(value, dict) or value.get("mean") is None:
        return "n/a"
    mean = float(value["mean"])
    stddev = float(value.get("stddev") or 0)
    if percent:
        return f"{mean * 100:.1f}% ± {stddev * 100:.1f}%"
    return f"{mean:.2f} ± {stddev:.2f}"

def _candidate_map(configurations: list[str], iteration: object, reveal: bool) -> dict[str, str]:
    if reveal:
        return {name: name for name in configurations}
    ordered = sorted(
        configurations,
        key=lambda name: hashlib.sha256(f"{iteration}:{name}".encode()).hexdigest(),
    )
    return {name: f"候选 {chr(65 + index)}" for index, name in enumerate(ordered)}

def _output_files(outputs: Path) -> list[dict[str, object]]:
    files: list[dict[str, object]] = []
    if not outputs.is_dir():
        return files
    for path in sorted(outputs.rglob("*"), key=lambda item: item.as_posix()):
        if path.is_symlink() or not path.is_file():
            continue
        preview: str | None = None
        data_url: str | None = None
        if path.suffix.lower() in TEXT_SUFFIXES:
            try:
                text = path.read_text(encoding="utf-8")
                preview = text[:MAX_PREVIEW_CHARS]
                if len(text) > MAX_PREVIEW_CHARS:
                    preview += "\n…预览已截断…"
            except UnicodeDecodeError:
                preview = None
        mime_type = IMAGE_MIME_TYPES.get(path.suffix.lower())
        if mime_type and path.stat().st_size <= MAX_EMBED_BYTES:
            data_url = (
                f"data:{mime_type};base64,"
                + base64.b64encode(path.read_bytes()).decode("ascii")
            )
        files.append(
            {
                "name": path.relative_to(outputs).as_posix(),
                "size": path.stat().st_size,
                "preview": preview,
                "data_url": data_url,
            }
        )
    return files

def build_review_data(root: Path, reveal: bool = False) -> tuple[dict[str, Any], dict[str, Any]]:
    plan = load_json(root / "run_plan.json")
    if not isinstance(plan, dict) or not isinstance(plan.get("runs"), list):
        raise ValueError("run_plan.json 缺少 runs 数组")
    configurations = plan.get("configurations")
    if not isinstance(configurations, list) or not all(
        isinstance(value, str) for value in configurations
    ):
        raise ValueError("run_plan.json 缺少 configurations")
    labels = _candidate_map(configurations, plan.get("iteration"), reveal)
    grouped: dict[str, dict[str, Any]] = {}
    manifest_runs: dict[str, str] = {}
    for run in plan["runs"]:
        if not isinstance(run, dict):
            raise ValueError("run_plan.runs 项必须是对象")
        run_dir = Path(str(run.get("run_dir", ""))).expanduser().resolve()
        try:
            run_dir.relative_to(root)
        except ValueError as exc:
            raise ValueError(f"run_dir 越出 iteration：{run_dir}") from exc
        run_id = str(run.get("run_id"))
        candidate_id = "review-" + hashlib.sha256(run_id.encode()).hexdigest()[:12]
        manifest_runs[candidate_id] = run_id
        grading_path = run_dir / "grading.json"
        grading: list[dict[str, Any]] = []
        if grading_path.is_file():
            grading_data = load_json(grading_path)
            if isinstance(grading_data, dict) and isinstance(
                grading_data.get("expectations"), list
            ):
                grading = grading_data["expectations"]
        eval_name = str(run.get("eval_name"))
        item = grouped.setdefault(
            eval_name,
            {"name": eval_name, "prompt": str(run.get("prompt", "")), "runs": []},
        )
        item["runs"].append(
            {
                "candidate_id": candidate_id,
                "candidate": labels[str(run.get("configuration"))],
                "repetition": run.get("repetition"),
                "files": _output_files(run_dir / "outputs"),
                "grading": grading,
            }
        )

    benchmark_rows: list[dict[str, object]] = []
    benchmark_path = root / "benchmark.json"
    if benchmark_path.is_file():
        benchmark = load_json(benchmark_path)
        summaries = benchmark.get("configurations", {}) if isinstance(benchmark, dict) else {}
        if isinstance(summaries, dict):
            for configuration in configurations:
                summary = summaries.get(configuration, {})
                if not isinstance(summary, dict):
                    continue
                benchmark_rows.append(
                    {
                        "candidate": labels[configuration],
                        "runs": summary.get("runs", 0),
                        "pass_rate": _metric(summary.get("pass_rate"), percent=True),
                        "duration": _metric(summary.get("duration_seconds")),
                        "tokens": _metric(summary.get("total_tokens")),
                    }
                )

    title = f"{plan.get('skill_name', 'Skill')} · iteration-{plan.get('iteration')}"
    if plan.get("schema_version") == 2:
        title += f" · {plan.get('model')}"
    data = {
        "title": title,
        "evals": list(grouped.values()),
        "benchmark": benchmark_rows,
    }
    manifest = {
        "schema_version": 1,
        "blind": not reveal,
        "model": plan.get("model"),
        "executor": plan.get("executor"),
        "candidates": labels,
        "runs": manifest_runs,
    }
    return data, manifest

def generate_review(
    iteration_path: str | Path,
    output: str | Path | None = None,
    reveal: bool = False,
    replace: bool = False,
) -> tuple[Path, Path]:
    root = Path(iteration_path).expanduser().resolve()
    output_path = (
        Path(output).expanduser().resolve() if output is not None else root / "review.html"
    )
    manifest_path = root / "review_manifest.json"
    if not replace and (output_path.exists() or manifest_path.exists()):
        raise FileExistsError("评审输出已存在；使用 --replace 明确覆盖")
    data, manifest = build_review_data(root, reveal=reveal)
    encoded = json.dumps(data, ensure_ascii=False).replace("<", "\<").replace(
        ">", "\>"
    )
    title = str(data["title"]).replace("&", "&amp;").replace("<", "&lt;").replace(
        ">", "&gt;"
    )
    html = HTML_TEMPLATE.replace("__TITLE__", title).replace("__DATA__", encoded)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(html, encoding="utf-8", newline="\n")
    manifest_path.write_text(
        json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    return output_path, manifest_path

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="生成默认隐藏版本身份的本地 Skill 评审页")
    parser.add_argument("iteration_path", help="iteration-N 目录")
    parser.add_argument("--output", help="HTML 输出路径，默认 iteration/review.html")
    parser.add_argument("--reveal", action="store_true", help="在页面中显示真实配置名")
    parser.add_argument("--replace", action="store_true", help="明确覆盖已有评审输出")
    return parser

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        output, manifest = generate_review(
            args.iteration_path,
            output=args.output,
            reveal=args.reveal,
            replace=args.replace,
        )
    except (ValueError, FileExistsError, OSError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1
    print(f"已创建评审页：{output}")
    print(f"候选映射：{manifest}")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## File: scripts/install_credential_ui.py
size: 5534
sha: 3b2b7c36d88d76cdbe45e0b41a8b08c99de80b01
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/install_credential_ui.py

```text
#!/usr/bin/env python3
"""将固定凭据组件装入目标 Skill，只生成非敏感声明。"""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import shutil
import sys
import tempfile
from pathlib import Path

TEMPLATE = Path(__file__).resolve().parent.parent / "assets" / "credential-ui"
IGNORED = {"node_modules", "__pycache__", ".git", ".DS_Store"}

def component_files() -> dict[str, bytes]:
    files = {}
    for item in sorted(TEMPLATE.rglob("*")):
        relative = item.relative_to(TEMPLATE)
        if any(part in IGNORED for part in relative.parts):
            continue
        if item.is_symlink():
            raise ValueError("组件模板不接受符号链接")
        if item.is_file():
            files[relative.as_posix()] = item.read_bytes()
    if "src/server.ts" not in files or "public/app.js" not in files:
        raise ValueError("组件模板不完整")
    return files

def install_credential_ui(
    skill_path: str | Path,
    skill_id: str,
    label: str,
    credential: str,
    title: str = "输入密钥",
    placeholder: str = "粘贴 API Key",
    dry_run: bool = False,
) -> dict:
    if not re.fullmatch(r"[a-z0-9-]{1,80}", skill_id):
        raise ValueError("Skill 标识不合法")
    if not re.fullmatch(r"[a-z0-9][a-z0-9/_.-]{0,150}", credential):
        raise ValueError("凭据引用不合法")
    for value, limit in ((label, 120), (title, 80), (placeholder, 80)):
        if not value.strip() or len(value) > limit:
            raise ValueError("页面文案为空或过长")
    # 先规范化用户指定的根路径，兼容系统临时目录等合法路径别名；
    # 随后拒绝组件安装位置中的链接，避免写入被重定向。
    root = Path(skill_path).expanduser().resolve()
    if not (root / "SKILL.md").is_file():
        raise ValueError("目标必须是已有 Skill 目录")
    target = root / "scripts" / "credential-ui"
    for item in (target, *target.parents):
        if item.is_symlink():
            raise ValueError("目标路径不接受符号链接")
    files = component_files()
    manifest = {
        "version": 1, "id": skill_id, "label": label, "credential": credential,
        "ui": {"title": title, "placeholder": placeholder},
    }
    manifest_name = "manifests/default.json"
    files[manifest_name] = (json.dumps(manifest, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
    hashes = {name: hashlib.sha256(data).hexdigest() for name, data in files.items() if not name.startswith("manifests/")}
    record = {"version": 1, "files": hashes}
    if target.exists():
        try:
            existing = json.loads((target / manifest_name).read_text(encoding="utf-8"))
            saved = json.loads((target / "component.json").read_text(encoding="utf-8"))
        except (OSError, ValueError) as exc:
            raise FileExistsError("已有目录不是可识别的凭据组件，未覆盖") from exc
        if existing.get("id") != skill_id or existing.get("credential") != credential or saved != record:
            raise FileExistsError("已有组件的身份或版本不同，未覆盖；请检查后使用独立目录")
        for name, digest in hashes.items():
            item = target / name
            if item.is_symlink() or not item.is_file() or hashlib.sha256(item.read_bytes()).hexdigest() != digest:
                raise FileExistsError("已有组件源码发生变化，未覆盖")
        return {"status": "unchanged", "directory": str(target), "manifest": str(target / manifest_name)}
    result = {"status": "preview" if dry_run else "installed", "directory": str(target), "manifest": str(target / manifest_name)}
    if dry_run:
        return result
    target.parent.mkdir(parents=True, exist_ok=True)
    temporary = Path(tempfile.mkdtemp(prefix=".credential-ui-", dir=target.parent))
    try:
        for name, data in files.items():
            output = temporary / name
            output.parent.mkdir(parents=True, exist_ok=True)
            output.write_bytes(data)
        (temporary / "component.json").write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")
        if target.exists():
            raise FileExistsError("目标目录刚被创建，未覆盖")
        temporary.rename(target)
    finally:
        if temporary.exists():
            shutil.rmtree(temporary)
    return result

def main(argv: list[str] | None = None) -> int:
    if sys.version_info < (3, 10):
        print("需要 Python 3.10 或更新版本", file=sys.stderr)
        return 1
    parser = argparse.ArgumentParser(description="向现有 Skill 接入可复用的凭据输入页；不读取或写入密钥")
    parser.add_argument("skill_path", help="已存在且包含 SKILL.md 的目标目录")
    parser.add_argument("--id", required=True, dest="skill_id")
    parser.add_argument("--label", required=True, help="页面显示的服务用途")
    parser.add_argument("--credential", required=True, help="不含密钥的稳定引用")
    parser.add_argument("--title", default="输入密钥")
    parser.add_argument("--placeholder", default="粘贴 API Key")
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args(argv)
    try:
        result = install_credential_ui(**vars(args))
    except (ValueError, OSError) as exc:
        print(str(exc), file=sys.stderr)
        return 1
    print(json.dumps(result, ensure_ascii=False))
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: scripts/package_skill.py
size: 5502
sha: ad10bc51473bb976a3ef31ebc1e643938eb2ecf1
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/package_skill.py

```text
#!/usr/bin/env python3
"""校验并创建能够重复生成的 .skill 归档。"""

from __future__ import annotations

import argparse
import fnmatch
import hashlib
import json
import sys
import zipfile
from pathlib import Path

try:
    from .validate_skill import audit_skill, parse_frontmatter
except ImportError:  # 直接运行脚本时使用同目录导入。
    from validate_skill import audit_skill, parse_frontmatter

EXCLUDED_DIRS = {".git", ".venv", "node_modules", "__pycache__", "dist"}
EXCLUDED_FILES = {".DS_Store"}
EXCLUDED_GLOBS = {"*.pyc", "*.pyo", "*.tmp", "*.log"}
FIXED_ZIP_TIME = (1980, 1, 1, 0, 0, 0)

def _is_excluded(relative: Path, include_evals: bool) -> bool:
    if any(part in EXCLUDED_DIRS for part in relative.parts):
        return True
    if not include_evals and relative.parts and relative.parts[0] == "evals":
        return True
    if relative.name in EXCLUDED_FILES:
        return True
    return any(fnmatch.fnmatch(relative.name, pattern) for pattern in EXCLUDED_GLOBS)

def _skill_name(skill_path: Path) -> str:
    raw = (skill_path / "SKILL.md").read_text(encoding="utf-8")
    frontmatter, _ = parse_frontmatter(raw)
    return frontmatter["name"]

def package_skill(
    skill_path: str | Path,
    output_dir: str | Path | None = None,
    public: bool = False,
    strict: bool = False,
    weak_model: bool = False,
    universal: bool = False,
    include_evals: bool = False,
    replace: bool = False,
) -> tuple[Path, str, list[str]]:
    path = Path(skill_path).expanduser().resolve()
    report = audit_skill(
        path,
        public=public,
        weak_model=weak_model,
        universal=universal,
    )
    if not report.passed(strict):
        raise ValueError(
            f"校验失败：{len(report.errors)} 个错误，{len(report.warnings)} 个警告"
        )

    name = _skill_name(path)
    destination = (
        Path(output_dir).expanduser().resolve()
        if output_dir is not None
        else path.parent / "dist"
    )
    destination.mkdir(parents=True, exist_ok=True)
    archive = destination / f"{name}.skill"
    if archive.exists() and not replace:
        raise FileExistsError(f"目标包已存在，拒绝覆盖：{archive}")
    if archive.exists():
        archive.unlink()

    files: list[Path] = []
    for item in sorted(path.rglob("*"), key=lambda value: value.as_posix()):
        if item.is_symlink():
            raise ValueError(f"发布包不接受符号链接：{item}")
        if not item.is_file():
            continue
        relative = item.relative_to(path)
        if not _is_excluded(relative, include_evals):
            files.append(item)

    added: list[str] = []
    with zipfile.ZipFile(
        archive, mode="w", compression=zipfile.ZIP_DEFLATED, compresslevel=9
    ) as bundle:
        for item in files:
            relative = item.relative_to(path)
            archive_name = (Path(name) / relative).as_posix()
            info = zipfile.ZipInfo(archive_name, FIXED_ZIP_TIME)
            info.compress_type = zipfile.ZIP_DEFLATED
            executable = item.suffix.lower() in {".py", ".sh", ".ps1"}
            permissions = 0o755 if executable else 0o644
            info.external_attr = permissions << 16
            bundle.writestr(info, item.read_bytes())
            added.append(archive_name)

    digest = hashlib.sha256(archive.read_bytes()).hexdigest()
    return archive, digest, added

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="校验并打包；相同文件会生成相同的 .skill 包")
    parser.add_argument("skill_path", help="Skill 目录")
    parser.add_argument("--output-dir", help="输出目录，默认是 Skill 同级 dist/")
    parser.add_argument("--public", action="store_true", help="执行公开 README 检查")
    parser.add_argument("--strict", action="store_true", help="warning 也阻止打包")
    parser.add_argument(
        "--weak-model",
        action="store_true",
        help="使用面向较弱模型的严格结构门槛",
    )
    parser.add_argument(
        "--universal",
        action="store_true",
        help="打包前拒绝在通用流程中写死具体宿主品牌",
    )
    parser.add_argument("--include-evals", action="store_true", help="将 evals/ 放入包中")
    parser.add_argument("--replace", action="store_true", help="明确覆盖已有同名包")
    parser.add_argument("--json", action="store_true", dest="as_json", help="输出 JSON")
    return parser

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        archive, digest, added = package_skill(
            args.skill_path,
            output_dir=args.output_dir,
            public=args.public,
            strict=args.strict,
            weak_model=args.weak_model,
            universal=args.universal,
            include_evals=args.include_evals,
            replace=args.replace,
        )
    except (ValueError, FileExistsError, KeyError, OSError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1

    payload = {
        "archive": str(archive),
        "sha256": digest,
        "files": added,
    }
    if args.as_json:
        print(json.dumps(payload, ensure_ascii=False, indent=2))
    else:
        print(f"已创建：{archive}")
        print(f"SHA-256：{digest}")
        print(f"文件数：{len(added)}")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## File: scripts/prepare_evaluation.py
size: 11254
sha: e49fa0f6ff739b9222702a91fbd156742ea4d84a
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/prepare_evaluation.py

```text
#!/usr/bin/env python3
"""根据 evals.json 创建结构固定、可以重复运行的评估目录。"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

try:
    from .evaluation_common import validate_eval_set
    from .snapshot_skill import default_workspace, snapshot_skill, verify_snapshot
    from .validate_skill import parse_frontmatter
except ImportError:
    from evaluation_common import validate_eval_set
    from snapshot_skill import default_workspace, snapshot_skill, verify_snapshot
    from validate_skill import parse_frontmatter

def _skill_name(skill_path: Path) -> str:
    skill_md = skill_path / "SKILL.md"
    if not skill_md.is_file():
        raise ValueError("目标目录缺少 SKILL.md")
    frontmatter, _ = parse_frontmatter(skill_md.read_text(encoding="utf-8"))
    name = frontmatter.get("name", "").strip()
    if not name:
        raise ValueError("SKILL.md 缺少 name")
    return name

def build_evaluation_plan(
    skill_path: str | Path,
    mode: str,
    iteration: int,
    workspace: str | Path | None = None,
    eval_set: str | Path | None = None,
    repetitions: int = 1,
    model: str | None = None,
    executor: str | None = None,
    allow_missing_skill: bool = False,
) -> tuple[Path, dict[str, object], list[tuple[Path, dict[str, object]]], list[Path]]:
    skill = Path(skill_path).expanduser().resolve()
    if not skill.is_dir():
        raise ValueError(f"Skill 目录不存在：{skill}")
    if mode not in {"create", "improve"}:
        raise ValueError("mode 必须是 create 或 improve")
    if iteration < 1:
        raise ValueError("iteration 必须大于等于 1")
    if not 1 <= repetitions <= 20:
        raise ValueError("repetitions 必须在 1 到 20 之间")
    if not isinstance(model, str) or not model.strip():
        raise ValueError("必须提供非空 model，固定本轮评估使用的模型")
    if not isinstance(executor, str) or not executor.strip():
        raise ValueError("必须提供非空 executor，记录本轮隔离执行者")
    if allow_missing_skill and mode != "create":
        raise ValueError("allow_missing_skill 只适用于 create 模式")
    model = model.strip()
    executor = executor.strip()

    eval_path = (
        Path(eval_set).expanduser().resolve()
        if eval_set is not None
        else skill / "evals" / "evals.json"
    )
    eval_data = validate_eval_set(eval_path)
    if mode == "create" and len(eval_data["evals"]) < 3:
        raise ValueError("create 模式至少需要 3 条真实评估，先补充 evals/evals.json")

    skill_md = skill / "SKILL.md"
    if skill_md.is_file():
        name = _skill_name(skill)
        if eval_data["skill_name"] != name:
            raise ValueError(
                f"evals.skill_name 为 {eval_data['skill_name']!r}，与目标 Skill {name!r} 不一致"
            )
    elif allow_missing_skill:
        name = str(eval_data["skill_name"])
    else:
        raise ValueError("目标目录缺少 SKILL.md")

    workspace_path = (
        Path(workspace).expanduser().resolve()
        if workspace is not None
        else default_workspace(skill, name)
    )
    snapshot = workspace_path / "skill-snapshot"
    snapshot_hash: str | None = None
    if mode == "improve":
        try:
            snapshot_hash = str(verify_snapshot(workspace_path)["sha256"])
        except ValueError as exc:
            raise ValueError(
                f"整改评估需要完整的写入前快照；先运行 snapshot_skill.py。{exc}"
            ) from exc
    current_hash = (
        str(snapshot_skill(skill, dry_run=True)["sha256"]) if skill_md.is_file() else None
    )

    iteration_path = workspace_path / f"iteration-{iteration}"
    baseline = "without_skill" if mode == "create" else "old_skill"
    configurations = ["with_skill", baseline]
    metadata_files: list[tuple[Path, dict[str, object]]] = []
    output_dirs: list[Path] = []
    runs: list[dict[str, object]] = []

    for item in eval_data["evals"]:
        eval_dir = iteration_path / str(item["name"])
        resolved_files: list[str] = []
        for value in item["files"]:
            input_path = Path(value).expanduser()
            if not input_path.is_absolute():
                input_path = eval_path.parent / input_path
            input_path = input_path.resolve()
            if not input_path.exists():
                raise ValueError(f"评估输入文件不存在：{input_path}")
            resolved_files.append(str(input_path))
        metadata = {
            "eval_id": item["id"],
            "eval_name": item["name"],
            "prompt": item["prompt"],
            "expected_output": item["expected_output"],
            "files": resolved_files,
            "expectations": item["expectations"],
        }
        metadata_files.append((eval_dir / "eval_metadata.json", metadata))
        for configuration in configurations:
            configured_skill: str | None
            planned_hash: str | None
            if configuration == "with_skill":
                configured_skill = str(skill)
                planned_hash = current_hash
            elif configuration == "old_skill":
                configured_skill = str(snapshot)
                planned_hash = snapshot_hash
            else:
                configured_skill = None
                planned_hash = None
            for repetition in range(1, repetitions + 1):
                run_dir = eval_dir / configuration / f"run-{repetition}"
                outputs = run_dir / "outputs"
                output_dirs.append(outputs)
                runs.append(
                    {
                        "run_id": f"{item['name']}-{configuration}-run-{repetition}",
                        "eval_id": item["id"],
                        "eval_name": item["name"],
                        "configuration": configuration,
                        "repetition": repetition,
                        "model": model,
                        "executor": executor,
                        "skill_path": configured_skill,
                        "skill_hash": planned_hash,
                        "prompt": item["prompt"],
                        "input_files": resolved_files,
                        "expected_output": item["expected_output"],
                        "expectations": item["expectations"],
                        "run_dir": str(run_dir),
                        "outputs_dir": str(outputs),
                    }
                )

    plan: dict[str, object] = {
        "schema_version": 2,
        "skill_name": name,
        "skill_path": str(skill),
        "mode": mode,
        "iteration": iteration,
        "model": model,
        "executor": executor,
        "eval_set": str(eval_path),
        "configurations": configurations,
        "repetitions": repetitions,
        "runs": runs,
    }
    return iteration_path, plan, metadata_files, output_dirs

def prepare_evaluation(
    skill_path: str | Path,
    mode: str,
    iteration: int,
    workspace: str | Path | None = None,
    eval_set: str | Path | None = None,
    repetitions: int = 1,
    model: str | None = None,
    executor: str | None = None,
    allow_missing_skill: bool = False,
    dry_run: bool = False,
) -> dict[str, object]:
    iteration_path, plan, metadata_files, output_dirs = build_evaluation_plan(
        skill_path,
        mode,
        iteration,
        workspace=workspace,
        eval_set=eval_set,
        repetitions=repetitions,
        model=model,
        executor=executor,
        allow_missing_skill=allow_missing_skill,
    )
    if iteration_path.exists():
        raise FileExistsError(f"iteration 已存在，拒绝覆盖：{iteration_path}")

    payload = {
        "status": "dry-run" if dry_run else "created",
        "iteration_path": str(iteration_path),
        "run_plan": str(iteration_path / "run_plan.json"),
        "runs": len(plan["runs"]),
        "model": model.strip() if isinstance(model, str) else None,
        "executor": executor.strip() if isinstance(executor, str) else None,
    }
    if dry_run:
        return payload

    iteration_path.mkdir(parents=True)
    for metadata_path, metadata in metadata_files:
        metadata_path.parent.mkdir(parents=True, exist_ok=True)
        metadata_path.write_text(
            json.dumps(metadata, ensure_ascii=False, indent=2) + "\n",
            encoding="utf-8",
            newline="\n",
        )
    for output_dir in output_dirs:
        output_dir.mkdir(parents=True)
    (iteration_path / "run_plan.json").write_text(
        json.dumps(plan, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    return payload

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="创建结构固定的 Skill 评估目录")
    parser.add_argument("skill_path", help="目标 Skill 目录")
    parser.add_argument(
        "--mode",
        choices=("create", "improve"),
        required=True,
        help="create 与普通 Agent 比较；improve 与整改前快照比较",
    )
    parser.add_argument("--iteration", type=int, required=True, help="评估轮次，从 1 开始")
    parser.add_argument("--model", required=True, help="本轮所有运行固定使用的模型标识")
    parser.add_argument("--executor", required=True, help="实际隔离执行者或运行环境标识")
    parser.add_argument(
        "--workspace",
        help="评估工作目录；Skill 位于 skills 扫描目录时，默认使用其同级的 skill-workspaces",
    )
    parser.add_argument("--eval-set", help="evals.json 路径，默认读取目标 Skill")
    parser.add_argument("--repetitions", type=int, default=1, help="每种配置运行次数")
    parser.add_argument(
        "--allow-missing-skill",
        action="store_true",
        help="create 模式允许目录先只有 evals；实现后沿用同一计划运行候选",
    )
    parser.add_argument("--dry-run", action="store_true", help="只显示计划，不写入")
    parser.add_argument("--json", action="store_true", dest="as_json", help="输出 JSON")
    return parser

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        payload = prepare_evaluation(
            args.skill_path,
            args.mode,
            args.iteration,
            workspace=args.workspace,
            eval_set=args.eval_set,
            repetitions=args.repetitions,
            model=args.model,
            executor=args.executor,
            allow_missing_skill=args.allow_missing_skill,
            dry_run=args.dry_run,
        )
    except (ValueError, FileExistsError, KeyError, OSError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1
    if args.as_json:
        print(json.dumps(payload, ensure_ascii=False, indent=2))
    else:
        status = "仅预览" if payload["status"] == "dry-run" else "已创建"
        print(f"{status}：{payload['iteration_path']}")
        print(f"运行数：{payload['runs']}")
        print(f"运行计划：{payload['run_plan']}")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## File: scripts/review_requirements.py
size: 2723
sha: 0dd960f8ef184710052bbc18b5ab258a1da7c16f
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/review_requirements.py

```text
#!/usr/bin/env python3
"""收集需要人工核对的需求证据，不把静态命中当作最终评审结论。"""
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path

SKIP = {'.git', 'node_modules', '__pycache__', '.venv', 'tests', 'evals', 'credential-ui'}

def collect(root: Path) -> dict:
    root = root.resolve()
    if not (root / 'SKILL.md').is_file():
        raise ValueError('目标目录缺少 SKILL.md')
    signals = {'credentials': [], 'generation': []}
    patterns = {
        'credentials': re.compile(r'API[ _-]?KEY|api_key|密钥|Client Secret|credential_ref', re.I),
        'generation': re.compile(r'imagegen|image_gen|生图|图片生成', re.I),
    }
    for p in sorted(root.rglob('*')):
        if not p.is_file() or p.is_symlink() or any(part in SKIP for part in p.relative_to(root).parts):
            continue
        if p.suffix.lower() not in {'.md', '.py', '.ts', '.js', '.mjs', '.sh', '.ps1'}:
            continue
        if p.stat().st_size > 1_000_000:
            continue
        for number, line in enumerate(p.read_text(encoding='utf-8', errors='replace').splitlines(), 1):
            for name, pattern in patterns.items():
                if pattern.search(line):
                    # 不输出原文，避免凭据线索扫描反而泄露值。
                    signals[name].append({'file': p.relative_to(root).as_posix(), 'line': number})
    component = root / 'scripts/credential-ui'
    required = ['src/profile.ts', 'src/server.ts', 'src/run.ts', 'public/app.js', 'manifests/profiles.json', 'tests/profile.test.ts']
    text = (root / 'SKILL.md').read_text(encoding='utf-8')
    return {
        'skill': str(root), 'status': 'needs-review', 'signals': signals,
        'credential_component': {'present': component.is_dir(), 'missing': [f for f in required if not (component / f).is_file()]},
        'setup_navigation': 'api-key-setup.md' in text or 'credential-ui.md' in text,
        'required_decisions': ['凭据入口是否适用；若复用现成入口，给出真实入口', '页面保存、部分失败恢复与业务读取的证据', '默认内置能力与可选 API 的选择条件', 'description、README、仓库 About 是否先讲功能', '仓库测试入口、发布包和哈希清单是否同步'],
    }

def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('skill_path', type=Path)
    args = parser.parse_args()
    try:
        print(json.dumps(collect(args.skill_path), ensure_ascii=False, indent=2))
    except (ValueError, OSError) as error:
        parser.error(str(error))
    return 0

if __name__ == '__main__':
    raise SystemExit(main())
```

## File: scripts/scaffold_skill.py
size: 7269
sha: aa44dfc27d173e708835de7755b59cc4b865ca84
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/scaffold_skill.py

```text
#!/usr/bin/env python3
"""创建最小 Skill 目录，并拒绝覆盖已有文件。"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

try:
    from .skill_version import is_semver
    from .validate_skill import NAME_RE
except ImportError:  # 直接运行脚本时使用同目录导入。
    from skill_version import is_semver
    from validate_skill import NAME_RE

ALLOWED_COMPONENTS = {"scripts", "references", "assets", "tests", "evals"}
SKILL_TEMPLATE = """---
name: {name}
description: {description}
{version_metadata}---

# {name}

## 目标

TODO：说明这个 Skill 为谁解决什么重复问题，以及使用后能看到或测量到什么改善。

## 工作流

TODO：只保留必须作出的判断、关键分支和必须执行的步骤。结果固定并且需要重复运行的步骤放进 scripts。

## 输出

TODO：说明最终交付物、保存位置和完成后需要汇报的内容。

## 资源导航

TODO：只列出实际存在的按需资源及其读取时机。
"""

README_FALLBACK = """# __SKILL_NAME__

## 有什么用

__SUMMARY__

## 安装

给出完整 GitHub 仓库地址，让用户可以把地址交给 Agent 安装。

给出已经替换为真实仓库名的 `npx skills add <owner>/<repository>` 命令，并说明安装条件。

## 配置

说明首次配置；没有配置时明确写“无需额外配置”。

## 使用

说明如何用自然语言触发，不复制 SKILL.md 的内部流程。

## 兼容性与依赖

列出已验证平台、运行环境、系统命令和宿主必须提供的能力。

## 数据与适用边界

说明外部服务、权限、隐私、费用和不适用场景。

## 测试

说明如何运行程序测试和 Skill 效果评估。
"""

def _parse_components(value: str) -> set[str]:
    if not value.strip():
        return set()
    components = {item.strip() for item in value.split(",") if item.strip()}
    unknown = sorted(components - ALLOWED_COMPONENTS)
    if unknown:
        raise ValueError("不支持的组件：" + ", ".join(unknown))
    return components

def _read_readme_template() -> str:
    template = Path(__file__).resolve().parent.parent / "assets" / "README.template.md"
    if template.is_file():
        return template.read_text(encoding="utf-8")
    return README_FALLBACK

def _render_description(description: str) -> str:
    return json.dumps(description, ensure_ascii=False)

def planned_paths(
    output_root: Path, name: str, components: set[str], public: bool
) -> list[Path]:
    target = output_root / name
    paths = [target / "SKILL.md"]
    if public:
        paths.append(target / "README.md")
    for component in sorted(components):
        if component == "evals":
            paths.append(target / "evals" / "evals.json")
        else:
            paths.append(target / component)
    return paths

def create_skill(
    output_root: str | Path,
    name: str,
    description: str,
    components: set[str] | None = None,
    public: bool = False,
    dry_run: bool = False,
    version: str | None = None,
) -> tuple[Path, list[Path]]:
    if not NAME_RE.fullmatch(name) or len(name) > 64:
        raise ValueError("name 必须是 64 字符以内的 kebab-case")
    if not description.strip():
        raise ValueError("description 不能为空")
    if len(description) > 1024 or "<" in description or ">" in description:
        raise ValueError("description 不能超过 1024 字符或包含尖括号")
    if version is not None and not is_semver(version):
        raise ValueError("version 必须使用 MAJOR.MINOR.PATCH 格式，例如 0.1.0")

    component_set = set(components or set())
    unknown = sorted(component_set - ALLOWED_COMPONENTS)
    if unknown:
        raise ValueError("不支持的组件：" + ", ".join(unknown))

    root = Path(output_root).expanduser().resolve()
    target = root / name
    paths = planned_paths(root, name, component_set, public)
    if target.exists():
        raise FileExistsError(f"目标目录已存在，拒绝覆盖：{target}")
    if dry_run:
        return target, paths

    target.mkdir(parents=True)
    skill_text = SKILL_TEMPLATE.format(
        name=name,
        description=_render_description(description.strip()),
        version_metadata=(f'metadata:\n  version: "{version}"\n' if version else ""),
    )
    (target / "SKILL.md").write_text(skill_text, encoding="utf-8", newline="\n")

    if public:
        readme = _read_readme_template()
        readme = readme.replace("__SKILL_NAME__", name).replace(
            "__SUMMARY__", description.strip()
        )
        (target / "README.md").write_text(readme, encoding="utf-8", newline="\n")

    for component in sorted(component_set):
        component_dir = target / component
        component_dir.mkdir()
        if component == "evals":
            evals = {"skill_name": name, "evals": []}
            (component_dir / "evals.json").write_text(
                json.dumps(evals, ensure_ascii=False, indent=2) + "\n",
                encoding="utf-8",
                newline="\n",
            )

    return target, paths

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="安全创建最小 Skill 骨架")
    parser.add_argument("name", help="kebab-case Skill 名称")
    parser.add_argument("--output-root", required=True, help="Skill 父目录")
    parser.add_argument(
        "--description",
        default="TODO：说明做什么、何时触发，以及哪些相似任务不要触发。",
        help="SKILL.md 顶部的触发说明",
    )
    parser.add_argument(
        "--components",
        default="",
        help="按需创建的逗号分隔组件：scripts,references,assets,tests,evals",
    )
    parser.add_argument("--public", action="store_true", help="同时生成 README.md")
    parser.add_argument(
        "--version",
        help="可选的初始 SemVer 版本；写入 metadata.version，例如 0.1.0",
    )
    parser.add_argument("--dry-run", action="store_true", help="只显示计划，不写入")
    parser.add_argument("--json", action="store_true", dest="as_json", help="输出 JSON")
    return parser

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        components = _parse_components(args.components)
        target, paths = create_skill(
            args.output_root,
            args.name,
            args.description,
            components=components,
            public=args.public,
            dry_run=args.dry_run,
            version=args.version,
        )
    except (ValueError, FileExistsError, OSError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1

    payload = {
        "status": "dry-run" if args.dry_run else "created",
        "target": str(target),
        "paths": [str(path) for path in paths],
    }
    if args.as_json:
        print(json.dumps(payload, ensure_ascii=False, indent=2))
    else:
        status = "仅预览" if payload["status"] == "dry-run" else "已创建"
        print(f"{status}：{target}")
        for path in paths:
            print(f"- {path}")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## File: scripts/score_triggers.py
size: 12029
sha: c6732efc7a928c2e581a7a3e17f4069e9e97f25b
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/score_triggers.py

```text
#!/usr/bin/env python3
"""读取当前 description，固定划分训练集和保留集，并计算触发结果。"""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
from pathlib import Path
from typing import Any

try:
    from .evaluation_common import load_json
    from .validate_skill import parse_frontmatter
except ImportError:
    from evaluation_common import load_json
    from validate_skill import parse_frontmatter

def _skill_identity(skill_path: str | Path) -> tuple[str, str]:
    root = Path(skill_path).expanduser().resolve()
    skill_md = root / "SKILL.md"
    if not skill_md.is_file():
        raise ValueError(f"目标目录缺少 SKILL.md：{root}")
    frontmatter, _ = parse_frontmatter(skill_md.read_text(encoding="utf-8"))
    name = frontmatter.get("name", "").strip()
    description = frontmatter.get("description", "").strip()
    if not name or not description:
        raise ValueError("SKILL.md 缺少 name 或 description")
    return name, description

def _cases_by_id(data: object, label: str) -> dict[str, dict[str, Any]]:
    if not isinstance(data, dict) or not isinstance(data.get("cases"), list):
        raise ValueError(f"{label}.cases 必须是数组")
    result: dict[str, dict[str, Any]] = {}
    for index, item in enumerate(data["cases"], start=1):
        if not isinstance(item, dict):
            raise ValueError(f"{label}.cases[{index}] 必须是对象")
        case_id = str(item.get("id", "")).strip()
        if not case_id or case_id in result:
            raise ValueError(f"{label}.cases[{index}].id 缺失或重复")
        result[case_id] = item
    return result

def _trials(item: dict[str, Any], case_id: str, strict: bool) -> list[bool]:
    if isinstance(item.get("triggered"), bool):
        if strict:
            raise ValueError(f"严格模式要求 {case_id} 提供至少 3 次奇数 trials")
        return [item["triggered"]]
    trials = item.get("trials")
    if not isinstance(trials, list) or not trials or not all(
        isinstance(value, bool) for value in trials
    ):
        raise ValueError(f"结果 {case_id} 必须包含 triggered 布尔值或 trials 布尔数组")
    if strict and (len(trials) < 3 or len(trials) % 2 == 0):
        raise ValueError(f"严格模式要求 {case_id} 提供至少 3 次奇数 trials")
    return trials

def _eval_hash(cases: dict[str, dict[str, Any]]) -> str:
    canonical = [
        {
            "id": case_id,
            "query": item["query"],
            "should_trigger": item["should_trigger"],
        }
        for case_id, item in sorted(cases.items())
    ]
    encoded = json.dumps(
        canonical, ensure_ascii=False, sort_keys=True, separators=(",", ":")
    ).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()

def _split_ids(
    cases: dict[str, dict[str, Any]], skill_name: str
) -> dict[str, str]:
    split: dict[str, str] = {}
    for expected in (True, False):
        selected = [
            case_id
            for case_id, item in cases.items()
            if item["should_trigger"] is expected
        ]
        selected.sort(
            key=lambda case_id: hashlib.sha256(
                f"{skill_name}:{case_id}".encode("utf-8")
            ).hexdigest()
        )
        holdout_count = max(1, (len(selected) * 4 + 9) // 10)
        holdout = set(selected[-holdout_count:])
        for case_id in selected:
            split[case_id] = "holdout" if case_id in holdout else "train"
    return split

def _metrics(records: list[dict[str, Any]]) -> dict[str, int | float]:
    tp = tn = fp = fn = 0
    stability_values: list[float] = []
    for item in records:
        expected = item["should_trigger"]
        actual = item["triggered"]
        stability_values.append(float(item["stability"]))
        if expected and actual:
            tp += 1
        elif not expected and not actual:
            tn += 1
        elif not expected and actual:
            fp += 1
        else:
            fn += 1
    total = len(records)
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    specificity = tn / (tn + fp) if tn + fp else 0.0
    return {
        "cases": total,
        "accuracy": round((tp + tn) / total, 4) if total else 0.0,
        "precision": round(precision, 4),
        "recall": round(recall, 4),
        "specificity": round(specificity, 4),
        "false_positive_rate": round(1 - specificity, 4),
        "stability": round(sum(stability_values) / total, 4) if total else 0.0,
        "tp": tp,
        "tn": tn,
        "fp": fp,
        "fn": fn,
    }

def _compare_holdout(
    candidate: dict[str, Any], baseline_path: Path, eval_hash: str
) -> dict[str, Any]:
    baseline = load_json(baseline_path)
    if not isinstance(baseline, dict):
        raise ValueError("baseline report 顶层必须是对象")
    if baseline.get("phase") != "select":
        raise ValueError("基线报告必须由 select 阶段生成")
    if baseline.get("eval_set_sha256") != eval_hash:
        raise ValueError("候选版本与基线使用的触发测试集不一致")
    baseline_summary = baseline.get("summary", {}).get("holdout")
    candidate_summary = candidate["summary"]["holdout"]
    if not isinstance(baseline_summary, dict):
        raise ValueError("基线报告缺少保留集汇总")
    deltas = {
        metric: round(
            float(candidate_summary[metric]) - float(baseline_summary[metric]), 4
        )
        for metric in ("accuracy", "precision", "recall", "specificity", "stability")
    }
    regressions = [
        metric for metric in ("recall", "specificity") if deltas[metric] < 0
    ]
    recommended = deltas["accuracy"] > 0 and not regressions
    if recommended:
        decision = "holdout-improved"
    elif deltas["accuracy"] > 0:
        decision = "holdout-tradeoff"
    else:
        decision = "no-holdout-improvement"
    return {
        "baseline_description_sha256": baseline.get("description_sha256"),
        "holdout_delta": deltas,
        "regressions": regressions,
        "recommended": recommended,
        "decision": decision,
    }

def score_triggers(
    eval_set_path: str | Path,
    results_path: str | Path,
    skill_path: str | Path,
    strict: bool = False,
    baseline_report: str | Path | None = None,
    phase: str = "train",
) -> dict[str, Any]:
    eval_path = Path(eval_set_path).expanduser().resolve()
    result_path = Path(results_path).expanduser().resolve()
    eval_data = load_json(eval_path)
    result_data = load_json(result_path)
    eval_cases = _cases_by_id(eval_data, "eval_set")
    result_cases = _cases_by_id(result_data, "results")
    if phase not in {"train", "select"}:
        raise ValueError("phase 必须是 train 或 select")
    if phase == "train" and baseline_report is not None:
        raise ValueError("train 阶段不能读取基线报告")
    if set(eval_cases) != set(result_cases):
        missing = sorted(set(eval_cases) - set(result_cases))
        extra = sorted(set(result_cases) - set(eval_cases))
        raise ValueError(f"结果 ID 不匹配；缺少 {missing}，多出 {extra}")

    skill_name, description = _skill_identity(skill_path)
    if not isinstance(eval_data, dict) or eval_data.get("skill_name") != skill_name:
        raise ValueError("触发评测集的 skill_name 与目标 Skill 不一致")
    if not isinstance(result_data, dict) or result_data.get("description") != description:
        raise ValueError("结果中的 description 与目标 SKILL.md frontmatter 不一致")
    if result_data.get("skill_name") not in {None, skill_name}:
        raise ValueError("结果中的 skill_name 与目标 Skill 不一致")

    positives = negatives = 0
    for case_id, item in eval_cases.items():
        query = item.get("query")
        expected = item.get("should_trigger")
        if not isinstance(query, str) or not query.strip():
            raise ValueError(f"eval_set {case_id}.query 必须是非空字符串")
        if not isinstance(expected, bool):
            raise ValueError(f"eval_set {case_id}.should_trigger 必须是布尔值")
        positives += int(expected)
        negatives += int(not expected)
    minimum = 8 if strict else 1
    if positives < minimum or negatives < minimum:
        raise ValueError(
            f"正反测试数量不足；当前 {positives}/{negatives}，要求各至少 {minimum}"
        )

    splits = _split_ids(eval_cases, skill_name)
    cases: list[dict[str, Any]] = []
    for case_id, item in sorted(eval_cases.items()):
        trials = _trials(result_cases[case_id], case_id, strict)
        rate = sum(trials) / len(trials)
        actual = rate >= 0.5
        cases.append(
            {
                "id": case_id,
                "split": splits[case_id],
                "should_trigger": item["should_trigger"],
                "trigger_rate": round(rate, 4),
                "triggered": actual,
                "passed": item["should_trigger"] == actual,
                "stability": round(max(rate, 1 - rate), 4),
            }
        )

    selected_split = "train" if phase == "train" else "holdout"
    selected_cases = [item for item in cases if item["split"] == selected_split]
    visible_cases = [
        {key: value for key, value in item.items() if key != "split"}
        for item in selected_cases
    ]
    summary_key = "train" if phase == "train" else "holdout"
    report: dict[str, Any] = {
        "schema_version": 2,
        "phase": phase,
        "skill_name": skill_name,
        "description": description,
        "description_sha256": hashlib.sha256(description.encode("utf-8")).hexdigest(),
        "eval_set_sha256": _eval_hash(eval_cases),
        "summary": {summary_key: _metrics(selected_cases)},
        "cases": visible_cases,
    }
    if baseline_report is not None:
        report["selection"] = _compare_holdout(
            report, Path(baseline_report).expanduser().resolve(), report["eval_set_sha256"]
        )
    return report

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="测量并比较 Skill 触发说明的准确性")
    parser.add_argument("eval_set", help="固定触发测试集 JSON")
    parser.add_argument("results", help="当前 description 的实际触发结果 JSON")
    parser.add_argument("--skill-path", required=True, help="本轮实际加载的 Skill 目录")
    parser.add_argument(
        "--phase",
        choices=("train", "select"),
        required=True,
        help="train 只显示训练结果；select 才读取保留集并选择版本",
    )
    parser.add_argument("--strict", action="store_true", help="要求正反各 8 条且每条至少运行 3 次")
    parser.add_argument("--baseline-report", help="基线评分报告；选择版本时只使用保留集")
    parser.add_argument("--output", help="将完整报告写入 JSON 文件")
    return parser

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        report = score_triggers(
            args.eval_set,
            args.results,
            args.skill_path,
            strict=args.strict,
            baseline_report=args.baseline_report,
            phase=args.phase,
        )
        if args.output:
            output = Path(args.output).expanduser().resolve()
            if output.exists():
                raise FileExistsError(f"输出已存在，拒绝覆盖：{output}")
            output.parent.mkdir(parents=True, exist_ok=True)
            output.write_text(
                json.dumps(report, ensure_ascii=False, indent=2) + "\n",
                encoding="utf-8",
                newline="\n",
            )
    except (ValueError, FileExistsError, OSError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1
    print(json.dumps(report, ensure_ascii=False, indent=2))
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## File: scripts/skill_version.py
size: 7153
sha: 07adac170035e51e4ceae92d08d1dc3537a80c57
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/skill_version.py

```text
#!/usr/bin/env python3
"""Read and update the optional metadata.version field in a Skill frontmatter."""

from __future__ import annotations

import re
from pathlib import Path

SEMVER_RE = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
FRONTMATTER_RE = re.compile(
    r"\A---[ \t]*\r?\n(?P<yaml>.*?)\r?\n---[ \t]*(?:\r?\n|\Z)", re.DOTALL
)
TOP_LEVEL_KEY_RE = re.compile(r"^([A-Za-z][A-Za-z0-9_-]*):(?:[ \t]*(.*))?$")
VERSION_KEY_RE = re.compile(r"^(?P<indent> +)version:[ \t]*(?P<value>.*)$")
# 按行读取版本的发版和更新脚本用的就是这两条规则；能被它们读到的写法才算有效。
LINE_NAME_RE = re.compile(r'^name:\s*"?([\w-]+)"?\s*$', re.MULTILINE)
LINE_VERSION_RE = re.compile(r'^\s+version:\s*"?(\d+\.\d+\.\d+)"?\s*$', re.MULTILINE)
STANDARD_FORM = '请写成多行映射：metadata 下一行 version: "1.2.3"，用双引号或不加引号，行尾不加注释'

def is_semver(value: str) -> bool:
    return bool(SEMVER_RE.fullmatch(value))

def _lines(text: str) -> list[str]:
    return text.splitlines()

def _top_level_key(line: str) -> tuple[str, str] | None:
    match = TOP_LEVEL_KEY_RE.match(line)
    if not match:
        return None
    return match.group(1), (match.group(2) or "").strip()

def _metadata_version_line(
    lines: list[str],
) -> tuple[int | None, int | None, int | None, str]:
    metadata_indices = [
        index
        for index, line in enumerate(lines)
        if (parsed := _top_level_key(line)) is not None and parsed[0] == "metadata"
    ]
    if len(metadata_indices) > 1:
        raise ValueError("frontmatter 中出现了多个 metadata 字段")
    if not metadata_indices:
        return None, None, None, "  "

    metadata_index = metadata_indices[0]
    _, inline_value = _top_level_key(lines[metadata_index]) or ("metadata", "")
    if inline_value and not inline_value.startswith("#"):
        if inline_value == "{}":
            return metadata_index, metadata_index + 1, None, "  "
        if re.search(r"(?:\{|,)\s*version\s*:", inline_value):
            raise ValueError(f"metadata.version 不能写在单行映射里；{STANDARD_FORM}")
        # 其他单行映射是合法 YAML，但安全改写需要完整解析器，不猜它的结构。
        return metadata_index, metadata_index + 1, None, "  "

    end_index = len(lines)
    for index in range(metadata_index + 1, len(lines)):
        if _top_level_key(lines[index]) is not None:
            end_index = index
            break

    # metadata 的直接子项沿用第一个子项的缩进，更深的缩进属于嵌套字段。
    child_indent = None
    version_indices = []
    for index in range(metadata_index + 1, end_index):
        line = lines[index]
        if not line.strip() or line.lstrip().startswith("#"):
            continue
        indent = line[: len(line) - len(line.lstrip(" "))]
        if child_indent is None:
            child_indent = indent
        match = VERSION_KEY_RE.match(line)
        if match and match.group("indent") == child_indent:
            version_indices.append(index)
    if len(version_indices) > 1:
        raise ValueError("metadata 中出现了多个 version 字段")
    return (
        metadata_index,
        end_index,
        version_indices[0] if version_indices else None,
        child_indent or "  ",
    )

def _decode_version_scalar(line: str) -> str:
    match = VERSION_KEY_RE.match(line)
    if not match:
        raise ValueError("metadata.version 必须是字符串")

    value = match.group("value").strip()
    if value.startswith("'"):
        raise ValueError(f"metadata.version 不能用单引号；{STANDARD_FORM}")
    if re.search(r"[ \t]#", value):
        raise ValueError(f"metadata.version 行尾不能加注释；{STANDARD_FORM}")
    if value.startswith('"'):
        quoted = re.fullmatch(r'"([^"\\]*)"', value)
        if not quoted:
            raise ValueError(f"metadata.version 必须是简单的字符串；{STANDARD_FORM}")
        return quoted.group(1)
    return value

def read_skill_version(raw: str) -> str | None:
    match = FRONTMATTER_RE.match(raw)
    if not match:
        raise ValueError("SKILL.md 缺少有效的 YAML frontmatter")

    lines = _lines(match.group("yaml"))
    _, _, version_index, _ = _metadata_version_line(lines)
    if version_index is None:
        return None
    value = _decode_version_scalar(lines[version_index])
    if not is_semver(value):
        raise ValueError("metadata.version 必须使用 MAJOR.MINOR.PATCH 格式，例如 1.2.3")
    return value

def line_reader_problem(raw: str, name: str, version: str) -> str | None:
    """检查按行读取的发版和更新脚本能否读到与 frontmatter 一致的名称和版本。"""
    name_match = LINE_NAME_RE.search(raw)
    if not name_match or name_match.group(1) != name:
        return "按行读取的发版和更新脚本读不到 name；请写成 name: skill-name，用双引号或不加引号"
    version_match = LINE_VERSION_RE.search(raw)
    if not version_match:
        return f"按行读取的发版和更新脚本读不到 metadata.version；{STANDARD_FORM}"
    if version_match.group(1) != version:
        return (
            f"按行读取的发版和更新脚本会读到 {version_match.group(1)}，而不是 metadata.version 的 {version}；"
            "把 metadata.version 放在 frontmatter 中第一个缩进的 version 字段"
        )
    return None

def update_skill_version(raw: str, version: str, *, require_absent: bool) -> str:
    if not is_semver(version):
        raise ValueError("版本号必须使用 MAJOR.MINOR.PATCH 格式，例如 1.2.3")

    match = FRONTMATTER_RE.match(raw)
    if not match:
        raise ValueError("SKILL.md 缺少有效的 YAML frontmatter")

    current = read_skill_version(raw)
    if require_absent and current is not None:
        raise ValueError(f"Skill 已有版本 {current}；首次设置操作不会覆盖已有版本")
    if not require_absent and current is None:
        raise ValueError("Skill 尚无 metadata.version；请先使用 --initial 设置初始版本")

    yaml_text = match.group("yaml")
    lines = _lines(yaml_text)
    metadata_index, metadata_end, version_index, child_indent = _metadata_version_line(lines)

    newline = "\r\n" if "\r\n" in raw else "\n"
    if metadata_index is None:
        lines.extend(["metadata:", f'  version: "{version}"'])
    elif version_index is not None:
        lines[version_index] = f'{child_indent}version: "{version}"'
    else:
        _, inline_value = _top_level_key(lines[metadata_index]) or ("metadata", "")
        if inline_value == "{}":
            lines[metadata_index] = "metadata:"
        elif inline_value and not inline_value.startswith("#"):
            raise ValueError("无法安全扩展 metadata 内联值；请先改成多行 YAML 映射")
        insert_at = metadata_end if metadata_end is not None else len(lines)
        lines[insert_at:insert_at] = [f'{child_indent}version: "{version}"']

    updated_yaml = newline.join(lines)
    return raw[: match.start("yaml")] + updated_yaml + raw[match.end("yaml") :]
```

## File: scripts/snapshot_skill.py
size: 6070
sha: 983fad2eac126f4d36c0864dca90c1d4fdf73fde
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/snapshot_skill.py

```text
#!/usr/bin/env python3
"""在整改前创建不可变 Skill 基线，并拒绝覆盖。"""

from __future__ import annotations

import argparse
import hashlib
import json
import shutil
import sys
from pathlib import Path

try:
    from .validate_skill import parse_frontmatter
except ImportError:
    from validate_skill import parse_frontmatter

EXCLUDED_DIRS = {".git", ".venv", "node_modules", "__pycache__", "dist"}
EXCLUDED_FILES = {".DS_Store"}

def _skill_name(skill_path: Path) -> str:
    skill_md = skill_path / "SKILL.md"
    if not skill_md.is_file():
        raise ValueError("目标目录缺少 SKILL.md")
    frontmatter, _ = parse_frontmatter(skill_md.read_text(encoding="utf-8"))
    name = frontmatter.get("name", "").strip()
    if not name:
        raise ValueError("SKILL.md 缺少 name")
    return name

def _included_files(skill_path: Path) -> list[Path]:
    files: list[Path] = []
    for path in sorted(skill_path.rglob("*"), key=lambda item: item.as_posix()):
        relative = path.relative_to(skill_path)
        if any(part in EXCLUDED_DIRS for part in relative.parts):
            continue
        if path.is_symlink():
            raise ValueError(f"快照不接受符号链接：{path}")
        if path.is_file() and path.name not in EXCLUDED_FILES:
            files.append(path)
    return files

def default_workspace(skill_path: Path, name: str) -> Path:
    """返回不会落入常见 Skill 扫描目录的默认 workspace。"""
    parent = skill_path.parent
    if parent.name.lower() == "skills":
        return parent.parent / "skill-workspaces" / f"{name}-workspace"
    return parent / f"{name}-workspace"

def _digest(skill_path: Path, files: list[Path]) -> str:
    checksum = hashlib.sha256()
    for path in files:
        relative = path.relative_to(skill_path).as_posix().encode("utf-8")
        checksum.update(len(relative).to_bytes(4, "big"))
        checksum.update(relative)
        content = path.read_bytes()
        checksum.update(len(content).to_bytes(8, "big"))
        checksum.update(content)
    return checksum.hexdigest()

def verify_snapshot(workspace: str | Path) -> dict[str, object]:
    workspace_path = Path(workspace).expanduser().resolve()
    destination = workspace_path / "skill-snapshot"
    metadata_path = workspace_path / "snapshot.json"
    if not destination.is_dir() or not metadata_path.is_file():
        raise ValueError(f"快照或元数据不存在：{destination}")
    try:
        metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise ValueError(f"快照元数据无效：{metadata_path}") from exc
    if not isinstance(metadata, dict):
        raise ValueError(f"快照元数据必须是对象：{metadata_path}")
    recorded_path = Path(str(metadata.get("snapshot", ""))).expanduser().resolve()
    if recorded_path != destination:
        raise ValueError("snapshot.json 指向的快照路径与当前 workspace 不一致")
    files = _included_files(destination)
    digest = _digest(destination, files)
    if metadata.get("files") != len(files) or metadata.get("sha256") != digest:
        raise ValueError("skill-snapshot 内容已变化，拒绝作为整改基线")
    return {
        "snapshot": str(destination),
        "files": len(files),
        "sha256": digest,
    }

def snapshot_skill(
    skill_path: str | Path,
    workspace: str | Path | None = None,
    dry_run: bool = False,
) -> dict[str, object]:
    source = Path(skill_path).expanduser().resolve()
    if not source.is_dir():
        raise ValueError(f"Skill 目录不存在：{source}")
    name = _skill_name(source)
    workspace_path = (
        Path(workspace).expanduser().resolve()
        if workspace is not None
        else default_workspace(source, name)
    )
    destination = workspace_path / "skill-snapshot"
    metadata = workspace_path / "snapshot.json"
    if destination.exists() or metadata.exists():
        raise FileExistsError(f"快照已存在，拒绝覆盖：{destination}")

    files = _included_files(source)
    payload: dict[str, object] = {
        "status": "dry-run" if dry_run else "created",
        "source": str(source),
        "snapshot": str(destination),
        "files": len(files),
        "sha256": _digest(source, files),
    }
    if dry_run:
        return payload

    workspace_path.mkdir(parents=True, exist_ok=True)
    destination.mkdir()
    for path in files:
        target = destination / path.relative_to(source)
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(path, target)
    metadata.write_text(
        json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    return payload

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="整改前创建不再修改的旧版 Skill 快照")
    parser.add_argument("skill_path", help="已有 Skill 目录")
    parser.add_argument(
        "--workspace",
        help="工作目录；Skill 位于 skills 扫描目录时，默认使用其同级的 skill-workspaces",
    )
    parser.add_argument("--dry-run", action="store_true", help="只显示计划，不写入")
    parser.add_argument("--json", action="store_true", dest="as_json", help="输出 JSON")
    return parser

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        payload = snapshot_skill(args.skill_path, args.workspace, args.dry_run)
    except (ValueError, FileExistsError, KeyError, OSError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1
    if args.as_json:
        print(json.dumps(payload, ensure_ascii=False, indent=2))
    else:
        status = "仅预览" if payload["status"] == "dry-run" else "已创建"
        print(f"{status}：{payload['snapshot']}")
        print(f"文件数：{payload['files']}")
        print(f"SHA-256：{payload['sha256']}")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## File: scripts/validate_skill.py
size: 41948
sha: 483d7ddf75877d49336def4c2488bb3470b467ca
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/validate_skill.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/validate_skill.py

## File: scripts/version_skill.py
size: 4395
sha: 8170bf33421fd7006011d05ccbbbea2741ae0093
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/scripts/version_skill.py

```text
#!/usr/bin/env python3
"""Preview or update a Skill's metadata.version using Semantic Versioning."""

from __future__ import annotations

import argparse
import json
import os
import stat
import sys
import tempfile
from pathlib import Path

try:
    from .skill_version import is_semver, read_skill_version, update_skill_version
except ImportError:
    from skill_version import is_semver, read_skill_version, update_skill_version

def bump_version(current: str, part: str) -> str:
    if not is_semver(current):
        raise ValueError("当前版本不是 MAJOR.MINOR.PATCH 格式")
    major, minor, patch = (int(item) for item in current.split("."))
    if part == "major":
        return f"{major + 1}.0.0"
    if part == "minor":
        return f"{major}.{minor + 1}.0"
    return f"{major}.{minor}.{patch + 1}"

def _atomic_write(path: Path, content: str) -> None:
    mode = stat.S_IMODE(path.stat().st_mode)
    temporary_path: Path | None = None
    try:
        with tempfile.NamedTemporaryFile(
            mode="w",
            encoding="utf-8",
            newline="",
            dir=path.parent,
            prefix=f".{path.name}.",
            suffix=".tmp",
            delete=False,
        ) as temporary:
            temporary.write(content)
            temporary_path = Path(temporary.name)
        os.chmod(temporary_path, mode)
        os.replace(temporary_path, path)
    except OSError:
        if temporary_path is not None:
            try:
                temporary_path.unlink(missing_ok=True)
            except OSError:
                pass
        raise

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="预览或更新 Skill 的 SemVer 版本")
    parser.add_argument("skill_path", help="包含 SKILL.md 的 Skill 目录")
    action = parser.add_mutually_exclusive_group(required=True)
    action.add_argument("--initial", help="设置尚未版本化的 Skill 初始版本，例如 1.0.0")
    action.add_argument("--bump", choices=("major", "minor", "patch"), help="递增已有版本")
    parser.add_argument("--write", action="store_true", help="写入文件；省略时只预览")
    parser.add_argument("--json", action="store_true", help="输出 JSON 格式结果")
    return parser

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    skill_path = Path(args.skill_path).expanduser().resolve()
    skill_file = skill_path / "SKILL.md"
    if not skill_file.is_file():
        print(f"ERROR: 找不到 Skill 文件：{skill_file}", file=sys.stderr)
        return 1

    try:
        with skill_file.open("r", encoding="utf-8", newline="") as stream:
            raw = stream.read()
        current = read_skill_version(raw)
        if args.initial is not None:
            if not is_semver(args.initial):
                raise ValueError("初始版本必须使用 MAJOR.MINOR.PATCH 格式，例如 1.0.0")
            if current is not None:
                raise ValueError(f"Skill 已有版本 {current}；不会覆盖已有版本")
            next_version = args.initial
            updated = update_skill_version(raw, next_version, require_absent=True)
        else:
            if current is None:
                raise ValueError("Skill 尚无 metadata.version；请先使用 --initial 设置初始版本")
            next_version = bump_version(current, args.bump)
            updated = update_skill_version(raw, next_version, require_absent=False)

        if args.write:
            _atomic_write(skill_file, updated)
        payload = {
            "status": "updated" if args.write else "preview",
            "skill": skill_path.name,
            "previous_version": current,
            "next_version": next_version,
            "path": str(skill_file),
        }
    except (OSError, ValueError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1

    if args.json:
        print(json.dumps(payload, ensure_ascii=False, indent=2))
    else:
        status = "已更新" if args.write else "预览"
        previous = payload["previous_version"] or "未设置"
        print(f"{status}：{payload['skill']} {previous} → {payload['next_version']}")
        if not args.write:
            print("确认后添加 --write 才会修改 SKILL.md。")
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: references/compatibility.md
size: 5552
sha: 72b575bce8fef8b765d199e73ab3e29754938f62
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/compatibility.md

```text
# 兼容性与运行边界

本文件用于设计和 Review 目标 Skill 的平台、宿主、配置与凭据边界。

## 需要检查的兼容范围

分别核对：

- 操作系统：macOS、Windows、Linux；
- Agent 宿主：是否能启动子 Agent，是否提供浏览器、图像、音视频或图形界面能力；
- 运行时：Python、Node、Java 或系统工具版本；
- Shell：bash、zsh、PowerShell、cmd；
- 文件系统：路径分隔符、大小写、权限、符号链接和换行；
- 外部服务：网络、认证、地区、费用和速率限制。

只声明实际验证过的平台。未验证的平台写“未验证”；依赖特定能力时，说明缺少该能力可以改用什么方法。

## 宿主中立

- 默认把 Skill 写成任何具备所需能力的 Agent 宿主都能理解的形式。
- 核心流程使用能力描述，不使用宿主品牌、专属工具名、专属配置目录或私有命令代替能力定义。
- 通过实际检查判断宿主是否提供子 Agent、浏览器、图形界面、文件系统或统计数据，不根据宿主名称猜测。
- 宿主专用的元数据或适配器要与 `SKILL.md` 核心流程分开；删除适配器后，通用能力仍应成立。
- 产品本身确实只服务一个宿主时，明确标记“宿主专用”，说明原因和不支持范围，不伪装成通用 Skill。

## 跨平台脚本规则

- 优先使用 Python 3 标准库和 `pathlib`。
- 调用当前 Python 时使用 `sys.executable`，不要猜 `python3` 的位置。
- 第一次运行时检查 `sys.version_info >= (3, 10)`；命令行文档同时说明 macOS/Linux 的 `python3` 与 Windows 的 `py -3` 入口。
- `subprocess` 传参数列表，不拼接 Shell 字符串。
- 明确使用 UTF-8 读写文本。
- 临时文件使用系统临时目录。
- 不在程序中写死 `/Users/...`、`~/.config` 或 `C:\\Users\\...`。
- 用户配置位置通过环境变量、平台目录或明确参数解析。
- 不依赖 `open`、`brew`、`which`、`chmod` 等单平台命令完成核心流程。
- 必须使用平台脚本时，将实现拆分并在入口处检测能力。

## 运行前检查

执行前以程序检查：

- 必需命令和运行时是否存在；
- 版本是否满足；
- 输入是否可读、输出目录是否可写；
- 配置和密钥是否可解析；
- 当前宿主是否具备任务需要的工具；
- 输出是否已存在。

检查本身应只读、快速、可重复。正常情况保持简洁；失败时给出缺失项和修复方式。

## 配置与迁移

- 普通配置放在用户目录，不放 Skill 仓库。
- 支持环境变量覆盖默认路径。
- 读取旧配置时保留兼容期，迁移不删除原文件。
- 更新配置采用合并写入，不覆盖未知字段。
- 写入使用临时文件加原子替换，防止中断后损坏。
- 日志和最终回复不显示完整密钥。

具体用户目录不能写死在 Skill 中。路径来自命令参数、环境变量、`Path.home()` 等平台目录解析，或者带有明确占位符的配置示例。

## 凭据存储

JSON、YAML 和普通配置文件只保存非敏感设置与凭据引用，例如服务名、账号名或 `credential_ref`，不保存密钥值。

按以下顺序选择凭据来源：

1. 复用目标环境已经提供的安全凭据能力；
2. 桌面环境通过成熟适配器使用 macOS Keychain、Windows Credential Manager 或 Linux Secret Service，需要用户输入单行密钥时接入 [凭据输入页](credential-ui.md)；
3. CI、容器或无界面环境使用运行时环境变量；
4. 没有安全存储时停止并说明限制，不静默降级为明文文件。

使用跨平台凭据库时，先确认当前后端确实连接系统加密存储。拒绝明文后端，并在初始化失败时给出替代方法。

Agent 只处理凭据引用和缺失状态。程序在运行时读取密钥并直接调用目标服务，不把密钥写入命令参数、标准输出、日志、缓存、快照、评估目录或 Agent 上下文。

首次保存、替换、迁移或删除凭据必须获得授权。重复初始化应复用已有凭据引用，不能创建重复记录或覆盖其他账号。

目标 Skill 实现凭据适配器时，至少提供读取、保存和删除三种动作，并满足：

- 接口使用凭据引用定位记录，返回结果和错误信息不包含密钥值；
- 保存和删除前获得授权，读取只发生在真正调用服务的程序内部；
- 启动检查能区分安全后端、明文后端和后端不可用，不安全时立即停止；
- 测试使用假密钥验证命令参数、日志、输出、缓存和评估目录没有泄露。

## 平台特定能力

Skill 可以依赖特定平台，但必须明确说明。若核心功能依赖某个平台：

- 在 description 或 compatibility 中声明；
- README 安装前即可看到；
- 初始化程序在写入前检查，不支持时立即停止；
- 不在不支持的平台上尝试一半后才失败；
- 如果还有其他可行方法，说明效果和成本差异。

## 验证矩阵

发布时记录：

| 维度 | 状态 |
| --- | --- |
| 当前开发平台 | 已测试 / 未测试 |
| 其他操作系统 | 已测试 / 静态检查 / 未验证 |
| 无子 Agent 环境 | 支持 / 降级 / 不支持 |
| 无浏览器或 GUI | 支持 / 降级 / 不支持 |
| 离线环境 | 支持 / 部分支持 / 不支持 |

静态检查不能替代真实运行。报告时区分“代码未发现平台假设”和“已在该平台执行通过”。
```

## File: references/credential-ui.md
size: 4297
sha: f1304daccab4718449f2d1a0ba63213433364f8c
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/credential-ui.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/credential-ui.md

## File: references/evaluation.md
size: 11018
sha: 7fe38488c683555ae5224fe7df40bc1bf04eb97a
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/evaluation.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/evaluation.md

## File: references/information-architecture.md
size: 8254
sha: e1a7e6ae23f33514274cda630e22a9671f9b08d5
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/information-architecture.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/information-architecture.md

## File: references/monetization.md
size: 12104
sha: ead457479e1d3adbc3b0e33d0b16d868a357eb75
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/monetization.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/monetization.md

## File: references/plan-validate-execute.md
size: 2447
sha: b2e703807a8d6490fb30e839d3703db58ac1e113
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/plan-validate-execute.md

````text
# 高风险操作的计划、校验与执行

批量修改、破坏性操作、复杂校验或失败代价较高的任务，先生成可机器检查的计划，再决定是否执行。普通单次、可逆且低风险的操作不必增加这一层。

## 固定顺序

1. **生成计划**：只读取输入，把拟执行操作写入工作区的 `plan.json`，不修改目标文件，不写入密钥或无关个人数据。
2. **程序校验**：检查 schema、操作 ID、目标范围、重复或冲突操作及前置条件；领域规则由目标 Skill 的程序验证，不让 Agent 目测代替。
3. **Dry-run**：展示将发生的变化和无法执行的项目。计划无效、目标越界或前置状态不符时保持零写入。
4. **用户授权**：说明影响并取得批准，记录计划摘要。批准后计划发生变化，必须重新校验、dry-run 和授权。
5. **执行与验证**：程序执行已批准的操作，逐项检查输出；失败时保留已完成的有效结果和明确错误。
6. **记录与恢复**：把每项状态写入独立的 `run-state.json`，采用临时文件加原子替换。恢复只处理未完成项，已验证成功的操作不得重复执行。

## 计划与状态分离

批准后的计划保持不变，运行状态另存。计划至少包含稳定 ID、动作、目标和可验证的前置条件，例如：

```json
{
  "schema_version": 1,
  "operations": [
    {
      "id": "operation-1",
      "action": "update",
      "target": "relative/path",
      "preconditions": {"sha256": "原文件摘要"}
    }
  ]
}
```

字段可按业务扩展，但不能用自由文本描述代替程序能检查的动作、目标和条件。`run-state.json` 至少记录计划摘要、每项状态、输出证据和错误；不把运行状态回写进已批准计划。

## 验收要求

- 无效计划、重复 ID、冲突目标和不匹配的前置条件均在写入前被拒绝。
- 只有校验和 dry-run 通过且用户批准后才能执行；绕过任一入口都不能写入。
- 部分失败后可以从真实状态恢复，重复运行不会重复已成功操作。
- 用一个正常主流程和至少一个失败分支做端到端测试，检查目标文件而不只检查函数返回值。

这里规定目标 Skill 的设计与验收契约。不同业务的计划 schema、校验器和执行器由目标 Skill 实现，不使用声称适用于所有业务的通用执行器。
````

## File: references/product-design.md
size: 6941
sha: 145049d6c513eecce8912f7dc23319b30951b2d2
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/product-design.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/product-design.md

## File: references/publishing.md
size: 5421
sha: cbad2b875f1eafc98fde99a32167b9a1704e9cb7
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/publishing.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/publishing.md

## File: references/review-and-remediation.md
size: 8887
sha: 41e54e01c1535dc2b1d4e87d7f8041f8da8149a4
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/review-and-remediation.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/review-and-remediation.md

## File: references/versioning.md
size: 2737
sha: eae6475ccba097d0bcf2736ac249da7775ab872d
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/versioning.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/references/versioning.md

## File: assets/credential-ui/manifests/default.json
size: 120
sha: 4acbfcb3270f01de04fc2c7bc4bb6a9205dfc027
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/manifests/default.json

```text
{
  "version": 1,
  "id": "sample-skill",
  "label": "服务 API Key",
  "credential": "sample-skill/service/default"
}
```

## File: assets/credential-ui/manifests/profiles.json
size: 112
sha: 4d457eb379b8427fac3c0413ece2bd40514536e3
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/manifests/profiles.json

```text
{
  "version": 1,
  "profiles": {
    "default": [{"manifest": "default.json", "env": "SERVICE_API_KEY"}]
  }
}
```

## File: assets/credential-ui/package-lock.json
size: 8679
sha: b9f47b1c1f795a24e61601b2f052a31eed79a848
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/package-lock.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/package-lock.json

## File: assets/credential-ui/package.json
size: 656
sha: 95b4c6d5e57d53b04c10251dfecf501cd5158878
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/package.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/package.json

## File: assets/credential-ui/public/app.js
size: 6440
sha: 153fc6d8647fbe0d81d6b2927e8f376cc052a5bc
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/public/app.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/public/app.js

## File: assets/credential-ui/public/favicon.svg
size: 315
sha: 3e53faae2439312a643d5d475a18a415216a94da
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/public/favicon.svg

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/public/favicon.svg

## File: assets/credential-ui/public/index.html
size: 1188
sha: 507af4a257bed24d6eeca9c848e904d67de42f8b
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/public/index.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/public/index.html

## File: assets/credential-ui/public/style.css
size: 3155
sha: 3187d768d516bef3f5ff257d9e45a50f2cd03fd2
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/public/style.css

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/public/style.css

## File: assets/credential-ui/src/cli.ts
size: 6463
sha: 3c6a5af3cd59a18b2d779ec13364eb956fc549a4
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/cli.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/cli.ts

## File: assets/credential-ui/src/config.ts
size: 5876
sha: a32c57edcc0a377a6e23dfc2566fcb8d44193350
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/config.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/config.ts

## File: assets/credential-ui/src/page.ts
size: 1739
sha: b8ac6faed254509dd1bf8f5ff6b6c7177450fbe4
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/page.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/page.ts

## File: assets/credential-ui/src/profile.ts
size: 4768
sha: 07c00570ef0d873d95e76569f8d8b100b87f8bcb
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/profile.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/profile.ts

## File: assets/credential-ui/src/run.ts
size: 3335
sha: d616d0e1b9268421c23ea6c48afa07ed2d5fc747
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/run.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/run.ts

## File: assets/credential-ui/src/server.ts
size: 11614
sha: 5feb0fecb075e14faefa0c094ab75425cf80ab67
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/server.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/src/server.ts

## File: assets/credential-ui/tests/configure.test.ts
size: 2532
sha: 7ec84a3f573eff2e7884b40dd238c44c0bb8dabd
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/configure.test.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/configure.test.ts

## File: assets/credential-ui/tests/credentials.test.ts
size: 6595
sha: a491230a2592f537135b1c25d018c5d3a3d73062
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/credentials.test.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/credentials.test.ts

## File: assets/credential-ui/tests/multi-key.test.ts
size: 9884
sha: 39682e525d1f61dfaaad9a892f1105f45b9b9fa6
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/multi-key.test.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/multi-key.test.ts

## File: assets/credential-ui/tests/native-smoke.ts
size: 4166
sha: 0a9f5c15ff6ac36a369c97fb8aac928c624257aa
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/native-smoke.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/native-smoke.ts

## File: assets/credential-ui/tests/page.test.ts
size: 2053
sha: 0ef1c94368600d0ac37eaad4b78d6f455be2286e
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/page.test.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/page.test.ts

## File: assets/credential-ui/tests/profile.test.ts
size: 4149
sha: cd9bf25ce0507f4d3dff9d561c13d359615e3704
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/profile.test.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/profile.test.ts

## File: assets/credential-ui/tests/run.test.ts
size: 2799
sha: c5bccd621a4fd748613f3581429bcd10a34d534f
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/run.test.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/run.test.ts

## File: assets/credential-ui/tests/ui.test.ts
size: 5074
sha: 05d485581a1ff4f0170ec9d7c105c1f28064ccf8
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/ui.test.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tests/ui.test.ts

## File: assets/credential-ui/tsconfig.json
size: 353
sha: a699072438601e76d5ddbddc1160ba21a26189b9
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tsconfig.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tsconfig.json

## File: assets/credential-ui/tsconfig.web.json
size: 237
sha: 2b1806626aa2b5f389346b86c3a311b020d5935c
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/tsconfig.web.json

```text
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "strict": true,
    "rootDir": "web",
    "outDir": "public",
    "types": []
  },
  "include": ["web/**/*.ts"]
}
```

## File: assets/credential-ui/web/app.ts
size: 6438
sha: c1f0bdc364885ed5b185f1c2a135f398508fb201
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/web/app.ts

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/credential-ui/web/app.ts

## File: assets/README.template.md
size: 1267
sha: e4b3f4a832c5e4fb263f22b33f60bab22e4b4508
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/README.template.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/README.template.md

## File: assets/readme/hero.png
size: 315171
sha: 96d949cf0c49df237872be2567b372377f6728bd
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/hero.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/hero.png

## File: assets/readme/source/hero-layout.svg
size: 3480
sha: 60f06aab710a4e6934d8d74f4bc165fa79de5f91
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/source/hero-layout.svg

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/source/hero-layout.svg

## File: assets/readme/source/hero-prompt.txt
size: 2353
sha: 87afb010311a6aa6c39d2b6386dc221428155ded
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/source/hero-prompt.txt

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/source/hero-prompt.txt

## File: assets/readme/source/hero-subject.png
size: 977729
sha: fa4821e0ce995b97c57fa529c3c24fdda27f2675
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/source/hero-subject.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/source/hero-subject.png

## File: assets/readme/source/render_hero.py
size: 1977
sha: a5ce2c7d559b0b60ab6a81e49732670b82b49a49
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/source/render_hero.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/assets/readme/source/render_hero.py

## File: .github/workflows/credential-ui.yml
size: 3334
sha: 35f3a7426d1c0f248fb20b84457ea30c95ce0932
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/.github/workflows/credential-ui.yml

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/.github/workflows/credential-ui.yml

## File: .gitignore
size: 68
sha: d92b3735228278c95e8e75f156443d2288b5c3d2
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/.gitignore

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/.gitignore

## File: evals/evals.json
size: 4276
sha: e83c2ca3a8a0b2d89890e5ba579a2a5b757532b1
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/evals/evals.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/evals/evals.json

## File: LICENSE
size: 1064
sha: 80fa9b501db35793dcca9b6ccf3e8cdd2db0f057
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/LICENSE

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/LICENSE

## File: tests/__init__.py
size: 58
sha: 6d316a97448a5f8a4a27d57643651ad15cf9834b
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/__init__.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/__init__.py

## File: tests/test_credential_ui.py
size: 5028
sha: 95dc50fc673534663b14a9b589efdd8e60916d99
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_credential_ui.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_credential_ui.py

## File: tests/test_evaluation_tools.py
size: 22722
sha: 6dbf11699737a32149ad52d84dadc18b5ecdbb09
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_evaluation_tools.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_evaluation_tools.py

## File: tests/test_package_skill.py
size: 1831
sha: 5cb8e797b4e4230efbb020964860079b6dd5deb9
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_package_skill.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_package_skill.py

## File: tests/test_review_requirements.py
size: 994
sha: ed01886ee22961d5191dddc63c5605421f9305c5
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_review_requirements.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_review_requirements.py

## File: tests/test_scaffold_skill.py
size: 3455
sha: f6111adbac5188292554555959b328f6326a1e1c
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_scaffold_skill.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_scaffold_skill.py

## File: tests/test_validate_skill.py
size: 24697
sha: e9ce3528acb7d9ccd9472ecde2e594e5eaf62a7f
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_validate_skill.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_validate_skill.py

## File: tests/test_version_skill.py
size: 4577
sha: 8b9c1bbe9c5a4053b0144f30442af59ad0540b9a
upstream: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_version_skill.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-skill-creator/blob/HEAD/tests/test_version_skill.py
