From f9eed1a5e50605b1d59e6825bc43a4c62fe0a7be Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Thu, 19 Nov 2026 16:57:02 +0800 Subject: [PATCH] feat: add partner skill contribute docs and isolate bailian skill tooling --- .github/workflows/ci.yml | 8 + docs/agents/skill-change.md | 14 + docs/skill-contribute/README.md | 79 +++++ .../templates/best-practice/README.md | 17 + .../templates/best-practice/SKILL.md | 60 ++++ .../best-practice/references/workflow.md | 14 + package.json | 1 + tools/check-skill-contribution.mjs | 330 ++++++++++++++++++ tools/check-skill-contribution.test.mjs | 158 +++++++++ tools/sync-skill-metadata.test.ts | 64 ++++ tools/sync-skill-metadata.ts | 92 +++-- 11 files changed, 814 insertions(+), 23 deletions(-) create mode 100644 docs/skill-contribute/README.md create mode 100644 docs/skill-contribute/templates/best-practice/README.md create mode 100644 docs/skill-contribute/templates/best-practice/SKILL.md create mode 100644 docs/skill-contribute/templates/best-practice/references/workflow.md create mode 100644 tools/check-skill-contribution.mjs create mode 100644 tools/check-skill-contribution.test.mjs create mode 100644 tools/sync-skill-metadata.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 392257e5d..26b0c9a6b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 + with: + # Partner skill contribution check needs the PR base commit for path diffs. + fetch-depth: 0 - uses: pnpm/action-setup@v6 @@ -29,6 +32,11 @@ jobs: - run: pnpm install --frozen-lockfile + - name: Check partner skill contribution + env: + GITHUB_BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || '' }} + run: node tools/check-skill-contribution.mjs + - run: pnpm run sync:skill-assets - run: pnpm -r --filter "./packages/*" build diff --git a/docs/agents/skill-change.md b/docs/agents/skill-change.md index d73e7996d..c5b6941cb 100644 --- a/docs/agents/skill-change.md +++ b/docs/agents/skill-change.md @@ -1,14 +1,28 @@ # Skill 文案 / 路由 / 安装约定 +> **合作方投稿(非 `bailian-*`)**请看 [docs/skill-contribute/](../skill-contribute/)。本文只服务本团队维护的官方 `bailian-*` 家族。 + ## 触发条件 - 改 `skills/*/SKILL.md` 的 description、路由表、consent、安全闸、hand-off、references 落款 - 调整 `bailian-protocol` 与业务 skill 的关系,或业务 skill 之间的软 hand-off 约定 - 新增 / 拆分 / 合并 `bailian-*` 业务 skill,或改 `tools/generate-reference.ts` 的 `GROUP_OWNER_SKILL` 归属(与命令增删改交叉时两边都看) - 给业务 skill 补安装说明、README,或统一「勿猜 flag → `reference/`」类约定 +- 在总入口 `bailian-cli` 中提及某个已合入的合作方 skill(见下方「在总入口中提及合作方 skill」) 纯改生成物 `skills/*/reference/*.md`(由命令 metadata 驱动)→ 走 [command-add-remove.md](command-add-remove.md) / [command-flag-change.md](command-flag-change.md),**不要手改 reference**。 +## 在总入口中提及合作方 skill + +合作方投稿合入后,用户用 `bl skill add --name bailian-protocol,` 即可安装;Agent 靠该 skill 自己的 `description` 触发,**不必**改总入口也能用。 + +有时希望用户先命中总入口 skill `bailian-cli`,再被指引到某个合作方 skill。这时: + +- **只由本团队**另开一个 PR,在 `skills/bailian-cli/SKILL.md` 里加**一行**说明(例如「某类业务场景 → 读 ``」) +- **不要**和合作方投稿 PR、或工程改动(`packages/**` / `tools/**`)混在同一 PR +- 加不加、怎么写由团队决定;不加这一行也不影响合作方 skill 安装后单独被触发 +- 合作方投稿规范见 [docs/skill-contribute/](../skill-contribute/);对方 PR **不应**改 `bailian-cli` + ## 统一口径(安装) 1. **Supported install:** `bl skill init`(装齐 registry 中全部 `bailian-*`,含 `bailian-protocol`) diff --git a/docs/skill-contribute/README.md b/docs/skill-contribute/README.md new file mode 100644 index 000000000..53e8abb65 --- /dev/null +++ b/docs/skill-contribute/README.md @@ -0,0 +1,79 @@ +# 向本仓库投稿 Skill + +本文说明如何向 `modelstudioai/cli` 提交**场景类(最佳实践)** Skill。 +官方总入口与命令面能力(名称以 `bailian-` 开头)由本团队维护;合作方请走本文路径,不要新增或修改 `bailian-*` Skill。 + +可复制的目录模板见:[templates/best-practice/](./templates/best-practice/)。 + +一作家族(`bailian-*`)的文案与路由约定见内部清单:[docs/agents/skill-change.md](../agents/skill-change.md)。 + +## 你能改什么 + +- **可以**:只改 `skills/<你的 skill 名>/` +- **CI 硬拦**:`packages/**`、`tools/**`、`.vite-hooks/**`、发布相关 workflow(以及手改 `skills/*/reference/`) +- **限制**:目录名不要以 `bailian-` 开头;不要改 `skills/bailian-*`(含总入口 `bailian-cli`)。`bailian-` 前缀为官方一作家族,合作方请用非此前缀的场景名。 + +合入后,用户用下面命令安装即可使用(**不必**改总入口 `bailian-cli`): + +```sh +bl skill add --name bailian-protocol,<你的-skill-名> +``` + +Agent 会根据你在 `SKILL.md` 里写的 `description` 判断要不要用这个 Skill。 +若希望用户从总入口 `bailian-cli` 也能被指引过来,由**本团队另开一个 PR** 在总入口里加一行说明;投稿 PR 里也尽量不要改 `bailian-cli`。加不加这一行都不影响你的 Skill 安装后单独被触发。 + +## 四条必须遵守的规则(CI 会检查) + +1. **目录与命名** + 目录名 = frontmatter 里的 `name`;使用安全目录名(不要空格、路径分隔符、`..` 等);不要与仓库里已有的 `skills/<目录>` 重名。 + +2. **目录结构** + 根目录要有 `SKILL.md`(YAML frontmatter,至少包含非空的 `name`、`description`)。手写流程放在 `references/`。 + **不要**新增或修改任何 `skills/*/reference/`(那是命令手册生成物,给官方 `bailian-*` 用的)。 + +3. **如何指向百炼能力** + 需要跑 `bl`、鉴权或共享协议时,用**技能名**去找已安装的 Skill(先找 `bailian-protocol`;生图/精调等再找对应的 `bailian-*`)。已安装就 Read;没有就提示用户执行上面的 `bl skill add`,或让用户跑 `bl … --help`。 + **不要**写成「必须存在 `../bailian-xxx/SKILL.md` 才能继续」。 + +4. **安全** + 不要引导自动补 `--yes`;不要写入真实凭证、真实内部资源或未公开的内部文档链接。 + +## 建议(不做 CI 硬性检查) + +- 目录名不要以 `bailian-` 开头;投稿 PR 不要改 `skills/bailian-*`(含 `bailian-cli`)。 +- `description` 写清:做什么、什么时候用、什么时候不要用;尽量别和现有 `bailian-*` 抢同一类意图。 +- 用户可见说明尽量中英双语。 +- 示例命令对照真实 `bl --help`,不要猜 flag。 + +## 关于 `metadata.version` + +模板里会给一个占位版本(例如 `0.1.0`),由你自己维护。 + +- 它**不会**自动变成 registry 里的分发版本,也**不需要**和本仓库 `packages/cli` 的版本对齐。 +- 改 version **不会**单独走旁路发版;合入 `main` 后仍走现有的 skills 发布对账流程。 + +官方 `bailian-*` 的 version 仍由本仓库工具与 CLI 版本同步;你的 Skill **不会**被那套同步改写。 + +## 推荐步骤 + +1. 复制模板到目标目录: + + ```sh + cp -R docs/skill-contribute/templates/best-practice skills/<你的-skill-名> + ``` + +2. 把目录名、`SKILL.md` frontmatter 的 `name` / `description`、以及 `references/` 里的场景说明改成你的内容;保留「如何按技能名找到百炼 Skill」那段固定说明。 +3. 本地确认只改了 `skills/<你的-skill-名>/`(若顺带改了投稿文档 `docs/skill-contribute/**` 也可以)。 +4. 开 PR,描述里可粘贴下方自检清单。 + +## 投稿自检清单 + +提交前请确认: + +- [ ] Skill 目录名:`skills//`;frontmatter 的 `name` 与目录名一致;`description` 非空 +- [ ] 本 PR **只**改了 `skills//`(以及可选的 `docs/skill-contribute/**`);**没有**改 `packages/**`、`tools/**`、`.vite-hooks/**` +- [ ] **没有**改任何 `skills/*/reference/**` +- [ ] (软限制)目录名不以 `bailian-` 开头;未改 `skills/bailian-*` +- [ ] 正文用技能名指向 `bailian-protocol` / 相关 `bailian-*`,没有把相对路径写成执行前提 +- [ ] 维护人联系方式(GitHub 用户名或团队)已写在 PR 描述里 +- [ ] (可选)无真实凭证、无未公开内部链接;未引导自动补 `--yes` diff --git a/docs/skill-contribute/templates/best-practice/README.md b/docs/skill-contribute/templates/best-practice/README.md new file mode 100644 index 000000000..8b68057e6 --- /dev/null +++ b/docs/skill-contribute/templates/best-practice/README.md @@ -0,0 +1,17 @@ +# your-skill-name + +Scene-oriented Bailian usage skill (best practice). Copy this folder to `skills//` and replace placeholders. + +## Install + +```sh +bl skill add --name bailian-protocol,your-skill-name +``` + +`bl skill init` installs official `bailian-*` skills only; this skill is installed on demand with the command above. + +## Notes + +- Keep `name` in `SKILL.md` identical to the directory name. +- `metadata.version` is yours to maintain; it is not locked to the CLI package version and is not the registry publish marker. +- Do not edit `skills/bailian-cli` in the same PR; if the hub should mention this skill, the Bailian team opens a separate PR. diff --git a/docs/skill-contribute/templates/best-practice/SKILL.md b/docs/skill-contribute/templates/best-practice/SKILL.md new file mode 100644 index 000000000..7f97b8116 --- /dev/null +++ b/docs/skill-contribute/templates/best-practice/SKILL.md @@ -0,0 +1,60 @@ +--- +name: your-skill-name +metadata: + version: "0.1.0" +description: >- + Replace this with WHAT the skill does, WHEN to use it, and WHEN not to use it. + Avoid overlapping the same intents already owned by bailian-* family skills + (media → bailian-gen, fine-tune → bailian-finetune, agents.yaml → bailian-managed-agent, + sandbox → bailian-sandbox, knowledge → bailian-knowledge, web search routing → bailian-web-search, + hub resource commands → bailian-cli). +--- + +# Your skill title + +Replace the placeholders below. Keep the "Bailian skills by name" section as an execution checklist. + +## Bailian skills by name (keep this section) + +Before running any `bl` command: + +1. Look up the installed skill named `bailian-protocol` (shared consent, version preflight, auth, call attribution, error reporting). If it is installed, Read it and follow it. If it is missing, stop and tell the user to run: + + ```sh + bl skill add --name bailian-protocol,your-skill-name + ``` + + Do not treat a relative path such as `../bailian-protocol/SKILL.md` as a hard requirement for continuing. + +2. When the task needs a Bailian domain skill (for example image/video → `bailian-gen`, fine-tune → `bailian-finetune`), look it up **by skill name**. If installed, Read it; if missing, suggest `bl skill add --name ` or fall back to `bl --help`. Do not require `../bailian-*/SKILL.md` paths to exist. + +3. Do not auto-append `--yes` for high-risk commands. Ask the user to confirm when the CLI requires confirmation. + +**Install (supported for this skill):** + +```sh +bl skill add --name bailian-protocol,your-skill-name +``` + +This skill does **not** need to be listed in the hub skill `bailian-cli` to work after install. + +## When to use + +- … + +## When not to use + +- Ordinary Q&A / coding / writing the host agent can do without Bailian → do not trigger +- … + +## Workflow + +See [references/workflow.md](references/workflow.md). + +## Quick examples + +Keep examples scoped to this skill. Prefer bare `bl …` in docs; wrap with call attribution only when actually executing (see `bailian-protocol` if installed). + +```sh +bl --help +``` diff --git a/docs/skill-contribute/templates/best-practice/references/workflow.md b/docs/skill-contribute/templates/best-practice/references/workflow.md new file mode 100644 index 000000000..c56e78753 --- /dev/null +++ b/docs/skill-contribute/templates/best-practice/references/workflow.md @@ -0,0 +1,14 @@ +# Workflow (edit for your scenario) + +Describe the step-by-step Bailian usage for this business scenario. + +1. Clarify the user goal and whether Bailian is required. +2. Ensure `bailian-protocol` (and this skill) are installed: + + ```sh + bl skill add --name bailian-protocol,your-skill-name + ``` + +3. Follow protocol rules (consent, auth, call attribution) when running `bl`. +4. For domain work (media, fine-tune, …), hand off by **skill name** to the matching `bailian-*` skill if installed; otherwise use `bl … --help`. +5. Record outcomes the user cares about; do not invent flags—use `--help` or an installed skill's docs. diff --git a/package.json b/package.json index c10deecf4..c88608331 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "prepare": "vp config", "check": "vp check", "sync:skill-assets": "pnpm --filter bailian-cli run generate:reference && pnpm --filter bailian-cli run sync:skill-version", + "check:skill-contribution": "node tools/check-skill-contribution.mjs", "dev": "pnpm -F bailian-cli-core dev", "bl": "pnpm -F bailian-cli dev", "kscli": "pnpm -F knowledge-studio-cli dev", diff --git a/tools/check-skill-contribution.mjs b/tools/check-skill-contribution.mjs new file mode 100644 index 000000000..f544c3dbd --- /dev/null +++ b/tools/check-skill-contribution.mjs @@ -0,0 +1,330 @@ +/** + * Light contribution gate for partner (non-bailian-) skills under skills/. + * + * When the changed file list does not touch any non-bailian- skills// path, + * the check is a no-op (first-party skill / package PRs keep today's behavior). + * + * Run: node tools/check-skill-contribution.mjs + * node tools/check-skill-contribution.mjs --files skills/foo/SKILL.md,packages/core/x.ts + * node tools/check-skill-contribution.mjs --files skills/foo/SKILL.md --new-skills foo --existing-skills foo,bailian-cli + */ +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; +import { parse as parseYaml } from "yaml"; + +const TOOLS_DIR = dirname(fileURLToPath(import.meta.url)); +const DEFAULT_REPO_ROOT = resolve(TOOLS_DIR, ".."); + +const DOC_WHITELIST_PREFIXES = ["docs/skill-contribute/"]; + +const FORBIDDEN_PREFIXES = ["packages/", "tools/", ".vite-hooks/", ".github/workflows/"]; + +const TOOLS_EXCEPTION_PREFIXES = ["tools/check-skill-contribution."]; + +/** Align with packages/core/src/skills/sanitize.ts isSafeSkillName */ +export function isSafeSkillName(name) { + if (!name || typeof name !== "string") return false; + const sanitized = name + .replace(/[\\/:*?"<>|\s]+/g, "-") + .replace(/\.\.+/g, "-") + .replace(/^[-.]+|[-.]+$/g, ""); + return sanitized.length > 0 && sanitized === name; +} + +export function isOfficialBailianSkillDir(dirName) { + return dirName.startsWith("bailian-"); +} + +export function normalizeRepoPath(filePath) { + return filePath.replaceAll("\\", "/").replace(/^\.\//, ""); +} + +/** Collect partner skill directory names touched by the changed files. */ +export function collectTouchedPartnerSkillDirs(changedFiles) { + const names = new Set(); + for (const raw of changedFiles) { + const filePath = normalizeRepoPath(raw); + const match = /^skills\/([^/]+)\//.exec(filePath); + if (!match) continue; + const dirName = match[1]; + if (!isOfficialBailianSkillDir(dirName)) { + names.add(dirName); + } + } + return [...names].sort((left, right) => left.localeCompare(right)); +} + +function isWhitelisted(filePath) { + const normalized = normalizeRepoPath(filePath); + return DOC_WHITELIST_PREFIXES.some((prefix) => normalized.startsWith(prefix)); +} + +function isToolsException(filePath) { + const normalized = normalizeRepoPath(filePath); + return TOOLS_EXCEPTION_PREFIXES.some((prefix) => normalized.startsWith(prefix)); +} + +function isForbiddenPath(filePath) { + const normalized = normalizeRepoPath(filePath); + if (isWhitelisted(normalized) || isToolsException(normalized)) return false; + // skills/bailian-* is a docs soft rule only (official naming / hub edits); not CI-hard. + return FORBIDDEN_PREFIXES.some((prefix) => normalized.startsWith(prefix)); +} + +function extractFrontmatter(content) { + if (!content.startsWith("---")) return null; + const match = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(content); + return match ? match[1] : null; +} + +/** Align with packages/core/src/skills/validate.ts field requirements. */ +export function readSkillFrontmatterMeta(skillMdPath) { + let raw; + try { + if (!statSync(skillMdPath).isFile()) { + return { ok: false, error: "SKILL.md is not a regular file" }; + } + raw = readFileSync(skillMdPath, "utf-8"); + } catch { + return { ok: false, error: "missing SKILL.md" }; + } + + const frontmatter = extractFrontmatter(raw); + if (frontmatter === null) { + return { ok: false, error: "SKILL.md is missing frontmatter (--- delimited YAML header)" }; + } + + let data; + try { + data = parseYaml(frontmatter); + } catch { + return { ok: false, error: "frontmatter is not valid YAML" }; + } + if (typeof data !== "object" || data === null) { + return { ok: false, error: "frontmatter is not a key-value structure" }; + } + + const record = data; + const name = typeof record.name === "string" ? record.name.trim() : ""; + const description = typeof record.description === "string" ? record.description.trim() : ""; + if (!name || !description) { + return { ok: false, error: "frontmatter is missing non-empty name / description fields" }; + } + return { ok: true, name, description }; +} + +export function listSkillDirs(skillsDir) { + if (!existsSync(skillsDir)) return []; + return readdirSync(skillsDir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort((left, right) => left.localeCompare(right)); +} + +/** + * @param {object} options + * @param {string[]} options.changedFiles + * @param {string} options.repoRoot + * @param {string[]} [options.existingSkillDirs] skill dirs that already existed (e.g. on merge base) + * @param {string[]} [options.newPartnerSkillDirs] partner dirs newly introduced in this change set + */ +export function checkSkillContribution(options) { + const repoRoot = options.repoRoot; + const changedFiles = options.changedFiles.map(normalizeRepoPath); + const partnerDirs = collectTouchedPartnerSkillDirs(changedFiles); + + if (partnerDirs.length === 0) { + return { + enabled: false, + ok: true, + partnerDirs: [], + errors: [], + message: "No partner skill paths changed; contribution gate skipped.", + }; + } + + const errors = []; + + const forbiddenHits = changedFiles.filter((filePath) => isForbiddenPath(filePath)); + if (forbiddenHits.length > 0) { + errors.push( + "Partner skill PRs must not change packages/**, tools/**, .vite-hooks/**, " + + "or .github/workflows/** (docs/skill-contribute/** is allowed). " + + "Split tooling changes into a separate PR. Forbidden paths:\n - " + + forbiddenHits.join("\n - "), + ); + } + + const referenceHits = changedFiles.filter((filePath) => + /^skills\/[^/]+\/reference\//.test(filePath), + ); + if (referenceHits.length > 0) { + errors.push( + "Do not add or edit skills/*/reference/** (generated command docs). Offending paths:\n - " + + referenceHits.join("\n - "), + ); + } + + const skillsDir = join(repoRoot, "skills"); + const existingSkillDirs = options.existingSkillDirs ?? listSkillDirs(skillsDir); + const newPartnerSkillDirs = new Set(options.newPartnerSkillDirs ?? []); + + for (const dirName of partnerDirs) { + if (!isSafeSkillName(dirName)) { + errors.push( + `Unsafe skill directory name "${dirName}" (must be a safe directory name; no spaces, path separators, or "..").`, + ); + } + + // Creating a "new" skill whose name already existed on the base branch + if (newPartnerSkillDirs.has(dirName) && existingSkillDirs.includes(dirName)) { + errors.push( + `Skill name "${dirName}" already exists under skills/. Choose a different directory name.`, + ); + } + + const skillMdPath = join(skillsDir, dirName, "SKILL.md"); + const meta = readSkillFrontmatterMeta(skillMdPath); + if (!meta.ok) { + errors.push(`skills/${dirName}: ${meta.error}`); + continue; + } + if (meta.name !== dirName) { + errors.push( + `skills/${dirName}: frontmatter name "${meta.name}" must match the directory name "${dirName}".`, + ); + } + } + + return { + enabled: true, + ok: errors.length === 0, + partnerDirs, + errors, + message: + errors.length === 0 + ? `Partner skill contribution check passed (${partnerDirs.join(", ")}).` + : `Partner skill contribution check failed:\n${errors.map((error) => `- ${error}`).join("\n")}`, + }; +} + +function parseCsvArg(argv, flag) { + const index = argv.indexOf(flag); + if (index === -1 || !argv[index + 1]) return null; + return argv[index + 1] + .split(",") + .map((entry) => entry.trim()) + .filter(Boolean); +} + +function parseArgs(argv) { + return { + files: parseCsvArg(argv, "--files"), + baseRef: (() => { + const index = argv.indexOf("--base"); + return index !== -1 ? argv[index + 1] : undefined; + })(), + repoRoot: (() => { + const index = argv.indexOf("--repo-root"); + return index !== -1 && argv[index + 1] ? resolve(argv[index + 1]) : DEFAULT_REPO_ROOT; + })(), + newSkills: parseCsvArg(argv, "--new-skills"), + existingSkills: parseCsvArg(argv, "--existing-skills"), + }; +} + +function gitLines(repoRoot, args) { + const result = spawnSync("git", args, { + cwd: repoRoot, + encoding: "utf-8", + }); + if (result.status !== 0) { + throw new Error( + `git ${args.join(" ")} failed: ${result.stderr || result.stdout || result.status}`, + ); + } + return result.stdout + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean); +} + +function resolveMergeBase(repoRoot, baseRef) { + const against = + baseRef || + process.env.GITHUB_BASE_SHA || + process.env.GITHUB_BASE_REF || + process.env.CI_MERGE_BASE || + process.env.SKILL_CONTRIBUTION_BASE; + if (!against) return null; + // Prefer a SHA when CI provides GITHUB_BASE_SHA; otherwise resolve merge-base with the ref name + if (/^[0-9a-f]{7,40}$/i.test(against)) { + return against; + } + return gitLines(repoRoot, ["merge-base", "HEAD", against])[0]; +} + +function detectChangedFiles(repoRoot, baseRef) { + const mergeBase = resolveMergeBase(repoRoot, baseRef); + if (mergeBase) { + return gitLines(repoRoot, ["diff", "--name-only", `${mergeBase}...HEAD`]); + } + const tracked = gitLines(repoRoot, ["diff", "--name-only", "HEAD"]); + const staged = gitLines(repoRoot, ["diff", "--name-only", "--cached"]); + const untracked = gitLines(repoRoot, ["ls-files", "--others", "--exclude-standard"]); + return [...new Set([...tracked, ...staged, ...untracked])]; +} + +function skillExistedAt(repoRoot, treeish, dirName) { + const probe = spawnSync("git", ["cat-file", "-e", `${treeish}:skills/${dirName}/SKILL.md`], { + cwd: repoRoot, + encoding: "utf-8", + }); + return probe.status === 0; +} + +function detectNewPartnerSkillDirs(repoRoot, mergeBase, partnerDirs) { + if (!mergeBase) return []; + const added = new Set( + gitLines(repoRoot, ["diff", "--name-only", "--diff-filter=A", `${mergeBase}...HEAD`]), + ); + return partnerDirs.filter((dirName) => added.has(`skills/${dirName}/SKILL.md`)); +} + +function existingSkillDirsOnBase(repoRoot, mergeBase) { + if (!mergeBase) { + return listSkillDirs(join(repoRoot, "skills")); + } + return listSkillDirs(join(repoRoot, "skills")).filter((dirName) => + skillExistedAt(repoRoot, mergeBase, dirName), + ); +} + +export function main(argv = process.argv.slice(2)) { + const { files, baseRef, repoRoot, newSkills, existingSkills } = parseArgs(argv); + const changedFiles = files ?? detectChangedFiles(repoRoot, baseRef); + const partnerDirs = collectTouchedPartnerSkillDirs(changedFiles); + const mergeBase = resolveMergeBase(repoRoot, baseRef); + + const result = checkSkillContribution({ + changedFiles, + repoRoot, + existingSkillDirs: existingSkills ?? existingSkillDirsOnBase(repoRoot, mergeBase), + newPartnerSkillDirs: newSkills ?? detectNewPartnerSkillDirs(repoRoot, mergeBase, partnerDirs), + }); + + console.log(result.message); + if (!result.ok) { + process.exitCode = 1; + } + return result; +} + +const invokedAsCli = + process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url); + +if (invokedAsCli) { + main(); +} diff --git a/tools/check-skill-contribution.test.mjs b/tools/check-skill-contribution.test.mjs new file mode 100644 index 000000000..68e6b0584 --- /dev/null +++ b/tools/check-skill-contribution.test.mjs @@ -0,0 +1,158 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, test } from "vite-plus/test"; +import { + checkSkillContribution, + collectTouchedPartnerSkillDirs, + isSafeSkillName, +} from "./check-skill-contribution.mjs"; + +const directories = []; +afterEach(() => { + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }); + } +}); + +function writePartnerSkill(repoRoot, name, options = {}) { + const dir = join(repoRoot, "skills", name); + mkdirSync(dir, { recursive: true }); + const frontmatterName = options.frontmatterName ?? name; + const description = options.description ?? "Partner skill fixture for contribution checks."; + writeFileSync( + join(dir, "SKILL.md"), + [ + "---", + `name: ${frontmatterName}`, + "metadata:", + ' version: "0.1.0"', + "description: >-", + ` ${description}`, + "---", + "", + `# ${frontmatterName}`, + "", + ].join("\n"), + "utf-8", + ); +} + +function fixtureRepo() { + const repoRoot = mkdtempSync(join(tmpdir(), "skill-contribution-")); + directories.push(repoRoot); + mkdirSync(join(repoRoot, "skills"), { recursive: true }); + writePartnerSkill(repoRoot, "bailian-cli", { + frontmatterName: "bailian-cli", + description: "Official hub fixture.", + }); + return repoRoot; +} + +test("collectTouchedPartnerSkillDirs ignores bailian-* and non-skill paths", () => { + expect( + collectTouchedPartnerSkillDirs([ + "skills/bailian-cli/SKILL.md", + "skills/finance-expert/SKILL.md", + "packages/core/src/index.ts", + "docs/skill-contribute/README.md", + ]), + ).toEqual(["finance-expert"]); +}); + +test("isSafeSkillName rejects path-like names", () => { + expect(isSafeSkillName("finance-expert")).toBe(true); + expect(isSafeSkillName("../evil")).toBe(false); + expect(isSafeSkillName("a b")).toBe(false); +}); + +test("first-party skill-only changes skip the partner gate", () => { + const repoRoot = fixtureRepo(); + const result = checkSkillContribution({ + repoRoot, + changedFiles: ["skills/bailian-cli/SKILL.md"], + }); + expect(result.enabled).toBe(false); + expect(result.ok).toBe(true); +}); + +test("valid partner-only contribution passes", () => { + const repoRoot = fixtureRepo(); + writePartnerSkill(repoRoot, "finance-expert"); + const result = checkSkillContribution({ + repoRoot, + changedFiles: ["skills/finance-expert/SKILL.md", "docs/skill-contribute/README.md"], + existingSkillDirs: ["bailian-cli"], + newPartnerSkillDirs: ["finance-expert"], + }); + expect(result.enabled).toBe(true); + expect(result.ok).toBe(true); + expect(result.partnerDirs).toEqual(["finance-expert"]); +}); + +test("mixing partner skill with packages/ fails path isolation", () => { + const repoRoot = fixtureRepo(); + writePartnerSkill(repoRoot, "finance-expert"); + const result = checkSkillContribution({ + repoRoot, + changedFiles: ["skills/finance-expert/SKILL.md", "packages/core/src/index.ts"], + existingSkillDirs: ["bailian-cli"], + newPartnerSkillDirs: ["finance-expert"], + }); + expect(result.ok).toBe(false); + expect(result.errors.join("\n")).toMatch(/packages\/core/); +}); + +test("touching bailian-* alongside a partner skill is not CI-hard", () => { + const repoRoot = fixtureRepo(); + writePartnerSkill(repoRoot, "finance-expert"); + const result = checkSkillContribution({ + repoRoot, + changedFiles: ["skills/finance-expert/SKILL.md", "skills/bailian-cli/SKILL.md"], + existingSkillDirs: ["bailian-cli"], + newPartnerSkillDirs: ["finance-expert"], + }); + expect(result.enabled).toBe(true); + expect(result.ok).toBe(true); +}); + +test("new partner skill colliding with an existing skills/ dir fails", () => { + const repoRoot = fixtureRepo(); + writePartnerSkill(repoRoot, "finance-expert"); + const result = checkSkillContribution({ + repoRoot, + changedFiles: ["skills/finance-expert/SKILL.md"], + existingSkillDirs: ["bailian-cli", "finance-expert"], + newPartnerSkillDirs: ["finance-expert"], + }); + expect(result.ok).toBe(false); + expect(result.errors.join("\n")).toMatch(/already exists/); +}); + +test("frontmatter name must match directory name", () => { + const repoRoot = fixtureRepo(); + writePartnerSkill(repoRoot, "finance-expert", { frontmatterName: "other-name" }); + const result = checkSkillContribution({ + repoRoot, + changedFiles: ["skills/finance-expert/SKILL.md"], + existingSkillDirs: ["bailian-cli"], + newPartnerSkillDirs: ["finance-expert"], + }); + expect(result.ok).toBe(false); + expect(result.errors.join("\n")).toMatch(/must match the directory name/); +}); + +test("editing skills/*/reference/** fails", () => { + const repoRoot = fixtureRepo(); + writePartnerSkill(repoRoot, "finance-expert"); + mkdirSync(join(repoRoot, "skills/finance-expert/reference"), { recursive: true }); + writeFileSync(join(repoRoot, "skills/finance-expert/reference/x.md"), "# no\n"); + const result = checkSkillContribution({ + repoRoot, + changedFiles: ["skills/finance-expert/SKILL.md", "skills/finance-expert/reference/x.md"], + existingSkillDirs: ["bailian-cli"], + newPartnerSkillDirs: ["finance-expert"], + }); + expect(result.ok).toBe(false); + expect(result.errors.join("\n")).toMatch(/reference/); +}); diff --git a/tools/sync-skill-metadata.test.ts b/tools/sync-skill-metadata.test.ts new file mode 100644 index 000000000..99a4fb759 --- /dev/null +++ b/tools/sync-skill-metadata.test.ts @@ -0,0 +1,64 @@ +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vite-plus/test"; +import { + isOfficialBailianSkillDir, + listOfficialSkillMarkdownPaths, + syncOfficialSkillVersions, +} from "./sync-skill-metadata.ts"; + +function writeSkill(skillsDir: string, name: string, version: string): string { + const dir = join(skillsDir, name); + mkdirSync(dir, { recursive: true }); + const skillPath = join(dir, "SKILL.md"); + writeFileSync( + skillPath, + [ + "---", + `name: ${name}`, + "metadata:", + ` version: "${version}"`, + "description: fixture skill for sync isolation", + "---", + "", + `# ${name}`, + "", + ].join("\n"), + "utf-8", + ); + return skillPath; +} + +test("isOfficialBailianSkillDir only accepts bailian- prefix", () => { + expect(isOfficialBailianSkillDir("bailian-cli")).toBe(true); + expect(isOfficialBailianSkillDir("bailian-protocol")).toBe(true); + expect(isOfficialBailianSkillDir("finance-expert")).toBe(false); + expect(isOfficialBailianSkillDir("spark-video")).toBe(false); +}); + +test("syncOfficialSkillVersions updates bailian-* only and leaves partner skills unchanged", () => { + const skillsDir = mkdtempSync(join(tmpdir(), "sync-skill-metadata-")); + const officialPath = writeSkill(skillsDir, "bailian-demo", "0.0.1"); + const partnerPath = writeSkill(skillsDir, "finance-expert", "0.1.0"); + + expect(listOfficialSkillMarkdownPaths(skillsDir)).toEqual([officialPath]); + + const result = syncOfficialSkillVersions({ + skillsDir, + version: "9.9.9", + repoRoot: skillsDir, + }); + expect(result.synced).toBe(1); + + expect(readFileSync(officialPath, "utf-8")).toContain('version: "9.9.9"'); + expect(readFileSync(partnerPath, "utf-8")).toContain('version: "0.1.0"'); +}); + +test("syncOfficialSkillVersions fails when no bailian-* skill markdown exists", () => { + const skillsDir = mkdtempSync(join(tmpdir(), "sync-skill-metadata-empty-")); + writeSkill(skillsDir, "finance-expert", "0.1.0"); + expect(() => syncOfficialSkillVersions({ skillsDir, version: "1.0.0" })).toThrow( + /no bailian-\*\/SKILL\.md found/, + ); +}); diff --git a/tools/sync-skill-metadata.ts b/tools/sync-skill-metadata.ts index 392b71dbf..62feb45f8 100644 --- a/tools/sync-skill-metadata.ts +++ b/tools/sync-skill-metadata.ts @@ -1,40 +1,46 @@ /** - * Syncs frontmatter `metadata.version` for every `skills//SKILL.md` from - * `packages/cli/package.json` (single source of truth for CLI release version). + * Syncs frontmatter `metadata.version` for official `bailian-*` skills under + * `skills//SKILL.md` from `packages/cli/package.json`. + * + * Partner / best-practice skills (non-bailian- prefix) keep their own version + * and are not rewritten by this tool. * * Run: pnpm --filter bailian-cli run sync:skill-version * Invoked via `pnpm run sync:skill-assets` or the repo pre-commit hook (see `.vite-hooks/pre-commit`). */ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { fileURLToPath } from "node:url"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; const VERSION_LINE_RE = /^(\s*version:\s*")[^"]*("\s*)$/m; -const __dirname = dirname(fileURLToPath(import.meta.url)); -const PKG_PATH = join(__dirname, "../packages/cli/package.json"); -const SKILLS_DIR = join(__dirname, "../skills"); - -const { version } = JSON.parse(readFileSync(PKG_PATH, "utf-8")) as { version: string }; - -const skillPaths = readdirSync(SKILLS_DIR, { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => join(SKILLS_DIR, entry.name, "SKILL.md")) - .filter((skillPath) => existsSync(skillPath)); +export function isOfficialBailianSkillDir(dirName: string): boolean { + return dirName.startsWith("bailian-"); +} -if (skillPaths.length === 0) { - throw new Error("skills/: no /SKILL.md found"); +/** List SKILL.md paths under skillsDir that belong to official bailian-* skills. */ +export function listOfficialSkillMarkdownPaths(skillsDir: string): string[] { + if (!existsSync(skillsDir)) { + return []; + } + return readdirSync(skillsDir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && isOfficialBailianSkillDir(entry.name)) + .map((entry) => join(skillsDir, entry.name, "SKILL.md")) + .filter((skillPath) => existsSync(skillPath)); } -for (const skillPath of skillPaths) { - const relPath = skillPath.slice(join(__dirname, "..").length + 1); +export function syncSkillMarkdownVersion( + skillPath: string, + version: string, + relPath = skillPath, +): { changed: boolean; message: string } { const body = readFileSync(skillPath, "utf-8"); const lines = body.split(/\r?\n/); if (lines[0] !== "---") { throw new Error(`${relPath}: must start with --- YAML frontmatter`); } - const closeIdx = lines.findIndex((line, i) => i > 0 && line === "---"); + const closeIdx = lines.findIndex((line, index) => index > 0 && line === "---"); if (closeIdx === -1) { throw new Error(`${relPath}: missing closing --- frontmatter delimiter`); } @@ -51,14 +57,54 @@ for (const skillPath of skillPaths) { const updatedFrontmatter = frontmatter.replace( VERSION_LINE_RE, - (_m, g1: string, g2: string) => `${g1}${version}${g2}`, + (_match, prefix: string, suffix: string) => `${prefix}${version}${suffix}`, ); const newBody = updatedFrontmatter + "\n" + restLines.join("\n"); if (newBody !== body) { writeFileSync(skillPath, newBody, "utf-8"); - console.log(`Synced ${relPath} metadata.version → ${version}`); - } else { - console.log(`${relPath} metadata.version already ${version}`); + return { changed: true, message: `Synced ${relPath} metadata.version → ${version}` }; } + return { changed: false, message: `${relPath} metadata.version already ${version}` }; +} + +export function syncOfficialSkillVersions(options: { + skillsDir: string; + version: string; + repoRoot?: string; +}): { synced: number; messages: string[] } { + const skillPaths = listOfficialSkillMarkdownPaths(options.skillsDir); + if (skillPaths.length === 0) { + throw new Error("skills/: no bailian-*/SKILL.md found"); + } + + const messages: string[] = []; + let synced = 0; + for (const skillPath of skillPaths) { + const relPath = options.repoRoot ? skillPath.slice(options.repoRoot.length + 1) : skillPath; + const result = syncSkillMarkdownVersion(skillPath, options.version, relPath); + messages.push(result.message); + if (result.changed) synced += 1; + } + return { synced, messages }; +} + +function main(): void { + const toolsDir = dirname(fileURLToPath(import.meta.url)); + const repoRoot = join(toolsDir, ".."); + const pkgPath = join(repoRoot, "packages/cli/package.json"); + const skillsDir = join(repoRoot, "skills"); + const { version } = JSON.parse(readFileSync(pkgPath, "utf-8")) as { version: string }; + + const { messages } = syncOfficialSkillVersions({ skillsDir, version, repoRoot }); + for (const message of messages) { + console.log(message); + } +} + +const invokedAsCli = + process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href; + +if (invokedAsCli) { + main(); }