From ca1af4502f37544a3309804d99e69fbcc3d2bafd Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 18:25:25 +0800 Subject: [PATCH 01/10] =?UTF-8?q?feat(ci):=20skill=20=E8=A7=84=E8=8C=83?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=8E=A5=E8=BF=9B=20check-build=EF=BC=8C?= =?UTF-8?q?=E8=A7=84=E5=88=99=E5=92=8C=20ans=20skill=20=E5=85=B1=E7=94=A8?= =?UTF-8?q?=E4=B8=80=E4=BB=BD=EF=BC=88#387=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 以前 SKILL.md 合不合规全凭人肉对表,下次谁再动还是照样漂。现在一条命令查全仓, CI 里也跑它,规则只有一份。 - scripts/check-skills.mjs:默认用 git ls-files 找出所有 SKILL.md(构建产物和 node_modules 里的副本不算),也能直接指定目录或文件;每条结果带文件、字段和 期望,红了退出码 1。 - validateSkillFile 的检查范围扩到整套规范:description 1–1024 字且带 when 从句、正文少于 500 行。ans skill validate 的 [OK] 文案跟着改成 "SKILL.md matches the Agent Skills spec"。 - 新增 validateSkillDirectory:在文件检查之外要求 name 等于所在目录名, ans skill validate 和仓库检查都走它。安装仍只查文件——clone 下来的文件夹名 不一定等于 skill 名,装进 skills/synced/ 后这条规则自然成立。 - check-build 多两步:跑检查,再跑它自己的测试(大写名字、清空 description、 正文 500 行三种改坏都会红)。 - 夹具里 description 补上 when 从句;README 两份和 CHANGELOG 记一笔。 --- .github/workflows/ci.yml | 6 ++ AGENTS.md | 1 + CHANGELOG.md | 18 +++++ README.md | 2 + README.zh-CN.md | 5 ++ apps/cli/src/commands/skill.ts | 10 ++- apps/cli/src/skill-store.ts | 77 +++++++++++++++++-- apps/cli/test/e2e.test.ts | 2 +- apps/cli/test/skill.test.ts | 53 ++++++++++++-- scripts/check-skills.mjs | 114 +++++++++++++++++++++++++++++ scripts/test/check-skills.test.mjs | 101 +++++++++++++++++++++++++ 11 files changed, 370 insertions(+), 19 deletions(-) create mode 100644 scripts/check-skills.mjs create mode 100644 scripts/test/check-skills.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 81ad4704..5ca686f9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,12 @@ jobs: - name: Workflow checker tests if: ${{ steps.setup.outputs.run-check-build != 'false' }} run: node --test scripts/test/check-workflows.test.mjs + - name: Skill spec check — every SKILL.md, same rules as ans skill install (#387) + if: ${{ steps.setup.outputs.run-check-build != 'false' }} + run: node scripts/check-skills.mjs + - name: Skill spec check tests + if: ${{ steps.setup.outputs.run-check-build != 'false' }} + run: node --test scripts/test/check-skills.test.mjs - if: ${{ steps.setup.outputs.run-check-build != 'false' }} run: pnpm -w turbo check - name: "Test — all packages (node:test discovery, full truth)" diff --git a/AGENTS.md b/AGENTS.md index 2107df20..d935b592 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,6 +16,7 @@ AnySearch is an agent CLI (`ans`) that works inside one domain only. It keeps re - Push gate status: `pnpm hooks:status` exits 0 when the hook is in place and runs the same commands as the source; when it is missing, out of date, not executable, or someone else's, it exits non-zero and names which; outside a git repo it exits 2. - `node scripts/preflight-test.mjs --dry-run` prints the plan; `--full` runs everything. Every test run points `HOME`/`USERPROFILE` at a throwaway temp dir and drops the repository pointers (`GIT_DIR` and the rest), so a test that forgets its own sandbox writes there instead of your `~/.ans`, and a test that makes its own repo cannot commit into your checkout; a green run deletes it (or says it could not), a red one keeps it and prints the path. What runs at each step is under "Gate rules" below. - The gate's own tests, three groups: `node --test "scripts/test/preflight-*.test.mjs"` covers the gate's rules — which files a push carries, which packages that selects, what a red run prints, which home the child gets, which repository git reads inside a test, that a red self-test blocks, and that `hooks:install` / `hooks:status` put the right file in place and name what is wrong when they cannot. `node --test scripts/test/ci-changes.test.mjs` and `node --test scripts/test/check-workflows.test.mjs` cover the shared judgments: CI's change policy and workflow checker (#487). CI runs all three in `check-build`, and a full gate run runs each group as its own run. The gate names each group and, when it passes, how many tests ran; a red group blocks the push before the suite starts. An incremental push does not pay for any of it. +- `node scripts/check-skills.mjs` — every `SKILL.md` Git tracks, checked against the agentskills.io spec: frontmatter is a mapping, `name` is 1–64 lowercase letters/digits with single hyphens and equals its directory, `description` is 1–1024 characters and says when to use the skill, body stays under 500 lines. It imports the same `validateSkillDirectory` that `ans skill install` / `ans skill validate` use, so the two can never disagree; pass a directory or a `SKILL.md` to check just that one. CI runs it in `check-build`. ### Gate rules (#367 — a commit, a push, a merge) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9536606f..f0716054 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,21 @@ +## Unreleased — #387: skill 规范检查进 CI,规则和 `ans skill` 共用一份 + +一句话说清:**agentskills.io 那套规范以前靠人肉对表,现在 `node scripts/check-skills.mjs` 一条命令查全仓的 `SKILL.md`,`check-build` 里也跑它;规则没有第二份,`ans skill install` / `ans skill validate` 走的就是它导入的那段代码。** + +### Added + +- **`scripts/check-skills.mjs`**:默认用 `git ls-files` 找出所有 `SKILL.md` 逐个查(构建产物和 `node_modules` 里的副本不算),也可以直接指定目录或文件。每条结果带文件、字段和期望,例如 `description must be 1–1024 characters, got 0`,不是只说「不合法」。分成 `[OK]` / `[FAIL]` 打印,有红的退出码 1。 +- **`check-build` 多了两步**:跑这个检查,再跑它自己的测试(大写名字、清空 `description`、正文 500 行,三种改坏都会红)。 + +### Changed + +- **`validateSkillFile` 的检查范围扩到整套规范**:以前只管 frontmatter 是不是 mapping、`name` 合不合规;现在还要 `description` 1–1024 字并说清什么时候用、正文少于 500 行。`ans skill validate` 输出的 `[OK] … SKILL.md frontmatter` 改成 `[OK] … SKILL.md matches the Agent Skills spec`。 +- **新增 `validateSkillDirectory`**:在文件检查之外加上「`name` 必须等于所在目录名」,`ans skill validate` 和仓库检查都走它。安装仍然只查文件——clone 下来的仓库文件夹名不一定等于 skill 名,装进 `skills/synced/` 之后这条规则自然成立。 + +### Known limits + +- **「说了什么时候用」只能查字面**:要求 `description` 里出现 `when`(比如 `Use when the user …`)。写得烂但带 `when` 的句子照样过;这条挡的是漏写,不是写得不好。 + ## Unreleased — #505: 宿主模板检查:坏形状、非整数 timeout、指错适配器都会红 一句话说清:**四份 `configs/*/hooks.json` 以前各测各的,没人横向比对;codebuddy 模板的命令和 `ans host connect` 写出来的已经不是同一条。现在一条测试读四份模板:timeout 必须是正整数、命令必须是本宿主自己的 bin、每条 hook 必须和 `hosts.ts` 的 `HOSTS` 候选逐字对上。生成物漂移改成和 `HEAD` 比,根目录 `pnpm test` 先跑 `gen:configs` 也洗不绿了。** diff --git a/README.md b/README.md index 8ff06224..d37a6b69 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,8 @@ ans skill uninstall ans --project `ans skill` only copies a directory inside a local Git checkout (one that contains a `SKILL.md`) into `skills/synced/`, recording its source and commit. It is not a package manager and does not execute skill code. Locking, manifests, and cleanup live in `apps/cli/src/skill-store.ts`. +`install` and `validate` hold a skill to the [Agent Skills spec](https://agentskills.io/specification): the frontmatter is a YAML mapping, `name` is 1–64 lowercase letters/digits with single hyphens, `description` is 1–1024 characters and says when to use the skill, and the body stays under 500 lines. A source folder may carry any name (a cloned repo usually does); `ans skill validate` and `node scripts/check-skills.mjs` — which checks every `SKILL.md` in this repository — also require `name` to equal its directory. + **Installed does not mean active.** These commands never touch domain TOML files: - **What `[skills].active` names**: skill keys declared in the domain TOML (shipped domains list runtime tags like `search`, `doctor`, `research`), not an auto-loader for `skills/synced/` directories. - **What `[skills.toolRequires]` is**: a reserved optional skill-to-tool filter (`filterAgentTools` keeps `hooks.toolWhitelist ∩ (∪ toolRequires[active] ∪ {search})`). No shipped domain declares `toolRequires`; when omitted, `hooks.toolWhitelist` alone filters tools and `[skills].active` does not change runtime behavior. diff --git a/README.zh-CN.md b/README.zh-CN.md index cc5734c2..5d455192 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -157,6 +157,11 @@ ans skill uninstall ans --project 并记下来源和 commit。它不是包管理器,也不会执行 skill 里的代码。锁、清单、 残留清理这些细节看 `apps/cli/src/skill-store.ts`。 +`install` 和 `validate` 都按 [Agent Skills 规范](https://agentskills.io/specification) 查:frontmatter 是 YAML mapping, +`name` 是 1–64 位小写字母数字加单连字符,`description` 1–1024 字且说清什么时候用,正文少于 500 行。 +源目录叫什么名字都行(clone 下来的仓库一般不是 skill 名);`ans skill validate` 和 +`node scripts/check-skills.mjs`(查本仓库所有 `SKILL.md`)另外要求 `name` 和所在目录同名。 + **装了不等于打开。** 这些命令不会改 domain TOML: - **`[skills].active` 里的名字是什么**:域 TOML 里声明的技能键名(出厂域写的是 `search`、`doctor`、`research` 这类运行时能力名),不是去 `skills/synced/` 自动加载目录的开关。 - **`[skills.toolRequires]` 现在干什么**:保留的可选「技能 → 所需工具」过滤表(`filterAgentTools` 按 `hooks.toolWhitelist ∩ (∪ toolRequires[active] ∪ {search})` 筛工具)。出厂域一个都没写它;没写 `toolRequires` 时,只靠 `hooks.toolWhitelist` 筛工具,`[skills].active` 写什么都不影响运行时。 diff --git a/apps/cli/src/commands/skill.ts b/apps/cli/src/commands/skill.ts index 5d63cb24..f542032c 100644 --- a/apps/cli/src/commands/skill.ts +++ b/apps/cli/src/commands/skill.ts @@ -16,7 +16,7 @@ const HELP = `Usage: ans skill [options] Commands: install Copy a directory containing SKILL.md from a local Git checkout - validate [name] Validate installed SKILL.md frontmatter (all, or one skill) + validate [name] Check installed SKILL.md against the Agent Skills spec (all, or one skill) list List skills recorded in installed.json uninstall Remove only the directory recorded in installed.json @@ -26,7 +26,11 @@ Options: --help, -h Show this help The source's current Git HEAD is recorded; checkout a commit/tag before installing. -Frontmatter must be a YAML mapping with a safe lowercase name (1–64 characters). +A SKILL.md passes (agentskills.io/specification) when its frontmatter is a YAML mapping, +name is 1–64 lowercase letters/digits with single hyphens, description is 1–1024 +characters and says when to use the skill, and the body stays under 500 lines. +validate also wants name to equal the directory it lives in; install accepts any +source folder name (a cloned repo usually has one) and installs under frontmatter name. Managed skills live in ${MANAGED_SKILLS_REL_PATH}; sibling directories under skills/ are user-authored. install copies the whole skill directory into ${MANAGED_SKILLS_REL_PATH}; the runtime never loads it (a host agent reads the files directly). [skills].active is just a list of keys for [skills.toolRequires], unrelated to directories in ${MANAGED_SKILLS_REL_PATH}. @@ -88,7 +92,7 @@ export async function runSkill(args: string[], opts: SkillCommandOptions = {}): const results = validateInstalledSkills(scopeOpts, selected); if (results.length === 0) out("No installed skills to validate.\n"); for (const result of results) { - out(result.ok ? `[OK] ${result.name}: SKILL.md frontmatter\n` : `[FAIL] ${result.name}: ${result.error}\n`); + out(result.ok ? `[OK] ${result.name}: SKILL.md matches the Agent Skills spec\n` : `[FAIL] ${result.name}: ${result.error}\n`); } return results.every((result) => result.ok) ? 0 : 1; } diff --git a/apps/cli/src/skill-store.ts b/apps/cli/src/skill-store.ts index 55b82f64..ef2ca995 100644 --- a/apps/cli/src/skill-store.ts +++ b/apps/cli/src/skill-store.ts @@ -161,10 +161,13 @@ export const skillRenameIO = renameSeam; // Design: names are single path segments on every supported OS — the Agent Skills // naming rule also excludes traversal, absolute paths, Windows device names and separators. /** Assert a safe Agent Skill name usable as a single directory segment. */ -function requireName(value: unknown): asserts value is string { +function requireName(value: unknown, file?: string): asserts value is string { if (typeof value !== "string" || !/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(value) || value.includes("--") || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) { - fail("skill name must be 1–64 lowercase letters/digits, with single hyphens, and not a reserved device name"); + const rule = "1–64 lowercase letters/digits, with single hyphens, and not a reserved device name"; + fail(file === undefined + ? `skill name must be ${rule}` + : `SKILL.md name ${JSON.stringify(value)} must be ${rule}: ${file}`); } } @@ -669,7 +672,44 @@ function writeManifest(managed: string, manifest: SkillManifest): void { } } -/** Validate YAML syntax and the name used as the install directory; not a full skill linter. */ +/** The Agent Skills spec's limit on the Markdown body that follows the frontmatter. */ +export const SKILL_BODY_LINE_LIMIT = 500; +/** The Agent Skills spec's character bounds for `description`. */ +export const SKILL_DESCRIPTION_MIN_CHARS = 1; +export const SKILL_DESCRIPTION_MAX_CHARS = 1024; + +/** + * Require a description that says what the skill does and when to use it (#387). + * The spec asks for both halves; a description with no `when` clause names the + * topic but never tells an agent when to reach for it. + */ +function requireDescription(value: unknown, path: string): void { + if (value === undefined) { + fail(`SKILL.md has no description field; the spec wants 1–1024 characters saying what the skill does and when to use it: ${path}`); + } + if (typeof value !== "string") { + fail(`SKILL.md description must be a string, not ${Array.isArray(value) ? "a list" : typeof value}: ${path}`); + } + const description = value.trim(); + const length = [...description].length; + if (length < SKILL_DESCRIPTION_MIN_CHARS || length > SKILL_DESCRIPTION_MAX_CHARS) { + fail(`SKILL.md description must be 1–1024 characters, got ${length}: ${path}`); + } + if (!/\bwhen\b/i.test(description)) { + fail(`SKILL.md description must also say when to use the skill, e.g. "Use when the user …"; got "${description.slice(0, 120)}": ${path}`); + } +} + +/** Keep the body under the spec's 500-line budget; the frontmatter does not count. */ +function requireShortBody(body: string, path: string): void { + const trimmed = body.replace(/(?:\r?\n)+$/, ""); + const lines = trimmed === "" ? 0 : trimmed.split(/\r?\n/).length; + if (lines >= SKILL_BODY_LINE_LIMIT) { + fail(`SKILL.md body must stay under ${SKILL_BODY_LINE_LIMIT} lines, got ${lines} (move detail into files the skill references): ${path}`); + } +} + +/** Validate YAML frontmatter, the name used as the install directory, description and body length. */ export function validateSkillFile(path: string): string { requireFile(path, "SKILL.md"); const text = readFileSync(path, "utf8").replace(/^\uFEFF/, ""); @@ -685,7 +725,25 @@ export function validateSkillFile(path: string): string { } if (!isRecord(frontmatter)) fail(`SKILL.md frontmatter must be a YAML mapping: ${path}`); const name: unknown = frontmatter.name; - requireName(name); + requireName(name, path); + requireDescription(frontmatter.description, path); + requireShortBody(text.slice(match[0].length), path); + return name; +} + +/** + * Validate one skill directory: everything `validateSkillFile` checks, plus the + * spec rule that `name` equals the directory it lives in. Install, `ans skill + * validate` and `scripts/check-skills.mjs` all come through here (#387), so the + * three cannot disagree about the same file. + */ +export function validateSkillDirectory(directory: string): string { + const file = join(directory, "SKILL.md"); + const name = validateSkillFile(file); + const folder = basename(resolve(directory)); + if (name !== folder) { + fail(`SKILL.md name must equal the directory it lives in: name is "${name}", directory is "${folder}": ${file}`); + } return name; } @@ -921,6 +979,10 @@ export async function installSkill(sourceArgument: string, opts: SkillOptions = // Design: a source path is persisted in installed.json, whose validator // rejects control characters — reject it here so an install cannot brick the scope. if (!printablePath(source)) fail("source directory path must be absolute and free of control characters"); + // Design: install accepts any directory name (#387). The spec's "name equals + // its parent directory" rule holds for a skill *source tree* and is checked by + // scripts/check-skills.mjs; a cloned repo folder can carry another name, and + // the installed copy is always skills/synced/, where the rule holds. const name = validateSkillFile(join(source, "SKILL.md")); const metadata = await provenance(source); const managed = managedSkillsRoot(opts); @@ -1034,7 +1096,7 @@ function installedDirectory(managed: string, name: string): string { return target; } -/** Validate installed SKILL.md frontmatter for one or all manifest entries. */ +/** Validate each installed skill directory against the Agent Skills spec. */ export function validateInstalledSkills(opts: SkillOptions = {}, selectedName?: string): SkillValidation[] { const managed = managedSkillsRoot(opts); let entries: InstalledSkill[]; @@ -1049,8 +1111,9 @@ export function validateInstalledSkills(opts: SkillOptions = {}, selectedName?: } return entries.map((entry) => { try { - const nameInFile = validateSkillFile(join(installedDirectory(managed, entry.name), "SKILL.md")); - if (nameInFile !== entry.name) fail(`frontmatter name ${nameInFile} does not match manifest name ${entry.name}`); + // The installed directory is /, so the "name equals its + // directory" rule covers the manifest cross-check too (#387). + validateSkillDirectory(installedDirectory(managed, entry.name)); return { name: entry.name, ok: true }; } catch (error) { return { name: entry.name, ok: false, error: (error as Error).message }; diff --git a/apps/cli/test/e2e.test.ts b/apps/cli/test/e2e.test.ts index e05575ad..efe66f8c 100644 --- a/apps/cli/test/e2e.test.ts +++ b/apps/cli/test/e2e.test.ts @@ -735,7 +735,7 @@ async function t(name: string, fn: () => Promise) { git(["config", "user.name", "Skill E2E"]); git(["config", "user.email", "skill-e2e@example.invalid"]); git(["config", "commit.gpgsign", "false"]); - fs.writeFileSync(path.join(source, "SKILL.md"), "---\nname: e2e-skill\ndescription: Bundled CLI test\n---\nInstructions.\n"); + fs.writeFileSync(path.join(source, "SKILL.md"), "---\nname: e2e-skill\ndescription: Use when the bundled CLI skill is under test\n---\nInstructions.\n"); git(["add", "SKILL.md"]); git(["commit", "--quiet", "-m", "skill"]); git(["tag", "v1.0.0"]); diff --git a/apps/cli/test/skill.test.ts b/apps/cli/test/skill.test.ts index b7ba8593..971bab29 100644 --- a/apps/cli/test/skill.test.ts +++ b/apps/cli/test/skill.test.ts @@ -110,7 +110,7 @@ function fixture(t: TestContext) { function source(name = "demo", folder = name, body = "Use the bundled template.\n"): string { const dir = join(repository, "skills", folder); mkdirSync(join(dir, "templates"), { recursive: true }); - writeFileSync(join(dir, "SKILL.md"), `---\nname: ${name}\ndescription: A test skill\n---\n\n${body}`); + writeFileSync(join(dir, "SKILL.md"), `---\nname: ${name}\ndescription: Use when the fixture needs a ${name} skill.\n---\n\n${body}`); writeFileSync(join(dir, "templates", "report.txt"), " bundled template\n"); git(repository, ["add", "--", dir]); git(repository, ["commit", "--quiet", "-m", `add ${folder}`]); @@ -464,7 +464,7 @@ test("staged changes mark the source dirty", async (t) => { test("repository root is a valid source and Git metadata is not copied", async (t) => { const f = fixture(t); f.source(); - writeFileSync(join(f.repository, "SKILL.md"), "---\nname: root-skill\ndescription: Root\n---\n"); + writeFileSync(join(f.repository, "SKILL.md"), "---\nname: root-skill\ndescription: Use when the whole repository is the skill\n---\n"); git(f.repository, ["add", "SKILL.md"]); git(f.repository, ["commit", "--quiet", "-m", "root skill"]); const result = await f.run(["install", f.repository]); @@ -497,9 +497,9 @@ test("invalid sources and frontmatter fail before publication", async (t) => { ["---\nname: [broken\n---\n", /YAML frontmatter/], ["---\njust a scalar\n---\n", /YAML mapping/], ["---\nname: demo\nname: other\n---\n", /YAML frontmatter/], - ["---\nname: ../escape\ndescription: x\n---\n", /skill name/], - ["---\nname: CON\ndescription: x\n---\n", /skill name/], - ["---\nname: a--b\ndescription: x\n---\n", /skill name/], + ["---\nname: ../escape\ndescription: x\n---\n", /SKILL\.md name/], + ["---\nname: CON\ndescription: x\n---\n", /SKILL\.md name/], + ["---\nname: a--b\ndescription: x\n---\n", /SKILL\.md name/], ]; for (const [text, error] of cases) { writeFileSync(file, text); @@ -510,7 +510,7 @@ test("invalid sources and frontmatter fail before publication", async (t) => { } const plain = join(f.base, "not-git"); mkdirSync(plain); - writeFileSync(join(plain, "SKILL.md"), "---\nname: plain\n---\n"); + writeFileSync(join(plain, "SKILL.md"), "---\nname: plain\ndescription: Use when a test needs a non-Git source.\n---\n"); assert.match((await f.run(["install", plain])).stderr, /Git source/); assert.match((await f.run(["install", f.base])).stderr, /SKILL\.md/); const remote = await f.run(["install", "https://example.invalid/skills.git"]); @@ -518,15 +518,52 @@ test("invalid sources and frontmatter fail before publication", async (t) => { assert.match(remote.stderr, /local Git checkout/); }); -test("CRLF, BOM and a name-only YAML mapping are parseable", async (t) => { +test("CRLF and a BOM in the frontmatter still parse", async (t) => { const f = fixture(t); const dir = f.source(); - writeFileSync(join(dir, "SKILL.md"), "\uFEFF---\r\nname: demo\r\n---\r\nbody\r\n"); + writeFileSync(join(dir, "SKILL.md"), "\uFEFF---\r\nname: demo\r\ndescription: Use when a test needs CRLF and a BOM.\r\n---\r\nbody\r\n"); const result = await f.run(["install", dir]); assert.equal(result.code, 0, result.stderr); assert.equal((await f.run(["validate", "demo"])).code, 0); }); +// #387: install, `ans skill validate` and scripts/check-skills.mjs share one +// rule set. The same broken text has to draw the same sentence from install and +// validate, otherwise CI and the product can disagree about a file. +test("description and body rules are enforced by install and validate alike", async (t) => { + const f = fixture(t); + const dir = f.source(); + const file = join(dir, "SKILL.md"); + const cases: [string, string][] = [ + ["---\nname: demo\n---\n", "has no description field"], + ["---\nname: demo\ndescription: \"\"\n---\n", "description must be 1–1024 characters, got 0"], + ["---\nname: demo\ndescription: A skill about demos.\n---\n", "must also say when to use the skill"], + [`---\nname: demo\ndescription: Use when the body is too long.\n---\n${"line\n".repeat(500)}`, "body must stay under 500 lines, got 500"], + ]; + for (const [text, expected] of cases) { + writeFileSync(file, text); + const install = await f.run(["install", dir]); + assert.equal(install.code, 1, install.stdout); + assert.ok(install.stderr.includes(expected), `install said: ${install.stderr}`); + assert.equal(existsSync(skillManifestPath(f.opts)), false, "nothing was published"); + } + writeFileSync(file, "---\nname: demo\ndescription: Use when the fixture needs a demo skill.\n---\n\nbody\n"); + assert.equal((await f.run(["install", dir])).code, 0); + const installed = join(managedSkillsRoot(f.opts), "demo", "SKILL.md"); + for (const [text, expected] of cases) { + writeFileSync(installed, text); + const validate = await f.run(["validate", "demo"]); + assert.equal(validate.code, 1, validate.stdout); + assert.ok(validate.stdout.includes(expected), `validate said: ${validate.stdout}`); + } + // The 500-line budget is exact: 499 body lines pass, 500 do not. + const body = (lines: number) => `---\nname: demo\ndescription: Use when the fixture needs a demo skill.\n---\n${"line\n".repeat(lines)}`; + writeFileSync(installed, body(499)); + assert.equal((await f.run(["validate", "demo"])).code, 0); + writeFileSync(installed, body(500)); + assert.equal((await f.run(["validate", "demo"])).code, 1); +}); + test("source symlinks are rejected and staging is rolled back", async (t) => { const f = fixture(t); const dir = f.source(); diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs new file mode 100644 index 00000000..8acec03e --- /dev/null +++ b/scripts/check-skills.mjs @@ -0,0 +1,114 @@ +#!/usr/bin/env node +// Repo-wide Agent Skills spec check (#387, parent #378). +// +// Every SKILL.md this repository ships goes through the *same* code the product +// uses: `ans skill install` and `ans skill validate` both call +// validateSkillDirectory / validateSkillFile in apps/cli/src/skill-store.ts, and +// so does this script. Nothing is re-implemented here on purpose — a rule that +// only existed in CI would drift from the one users hit. +// +// Usage: +// node scripts/check-skills.mjs # every SKILL.md Git tracks +// node scripts/check-skills.mjs # only these +// +// Exit codes: 0 every skill passes · 1 a skill broke a rule · 2 the check could +// not run (no Git, no tsx, a path that does not exist). +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import process from "node:process"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const SCRIPT = fileURLToPath(import.meta.url); +/** Set in the child so the re-entry below happens exactly once. */ +const TSX_MARKER = "ANS_CHECK_SKILLS_TSX"; +/** The workspace tsx loader: the checker imports TypeScript sources directly, no build first. */ +const TSX_LOADER = path.join(ROOT, "apps", "cli", "node_modules", "tsx", "dist", "loader.mjs"); + +function fail(code, detail) { + process.stderr.write("check-skills: " + detail + "\n"); + process.exit(code); +} + +/** Map a CLI argument to the SKILL.md it names. */ +function skillFileOf(target) { + const resolved = path.resolve(target); + const stat = fs.statSync(resolved, { throwIfNoEntry: false }); + if (!stat) throw new Error("no such file or directory: " + resolved); + return stat.isDirectory() ? path.join(resolved, "SKILL.md") : resolved; +} + +/** + * Every SKILL.md Git tracks. Tracking, not a directory walk: build output + * (apps/cli/dist carries a copy of the plugin skills) and node_modules hold + * copies of the same file, and re-checking those would report each rule twice. + */ +function trackedSkillFiles() { + const listed = spawnSync("git", ["ls-files", "-z"], { + cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, + }); + if (listed.error) throw new Error("cannot run git ls-files: " + listed.error.message); + if (listed.status !== 0) { + throw new Error("git ls-files failed in " + ROOT + ": " + (String(listed.stderr).trim() || "exit " + listed.status)); + } + return String(listed.stdout).split("\0").filter(Boolean) + .filter((file) => path.posix.basename(file) === "SKILL.md") + .map((file) => path.join(ROOT, file)) + .sort(); +} + +/** Show a path relative to where the check was started, for readable CI logs. */ +function shown(file) { + const relative = path.relative(process.cwd(), file); + return relative && !relative.startsWith("..") ? relative.split(path.sep).join("/") : file; +} + +async function run() { + const { validateSkillDirectory, SkillError } = await import("../apps/cli/src/skill-store.ts"); + const args = process.argv.slice(2); + let files; + try { + files = args.length > 0 ? args.map(skillFileOf) : trackedSkillFiles(); + } catch (error) { + fail(2, error.message); + } + if (files.length === 0) { + process.stdout.write("check-skills: no SKILL.md found\n"); + return 0; + } + let failed = 0; + for (const file of files) { + try { + const name = validateSkillDirectory(path.dirname(file)); + process.stdout.write(`[OK] ${shown(file)} (name: ${name})\n`); + } catch (error) { + failed += 1; + // A rule failure reads "field + what was expected + which file"; anything + // else (a broken read, a missing parent) keeps its stack so it is not + // mistaken for a rule verdict. + const detail = error instanceof SkillError ? error.message : String(error && error.stack || error); + process.stdout.write(`[FAIL] ${shown(file)}: ${detail}\n`); + } + } + process.stdout.write(`${files.length} SKILL.md checked, ${failed} failed\n`); + return failed === 0 ? 0 : 1; +} + +if (process.env[TSX_MARKER] !== "1") { + if (!fs.existsSync(TSX_LOADER)) { + fail(2, `tsx loader not found at ${TSX_LOADER}; run pnpm install before this check`); + } + const entry = path.relative(process.cwd(), SCRIPT).split(path.sep).join("/"); + const child = spawnSync(process.execPath, ["--import", pathToFileURL(TSX_LOADER).href, entry, ...process.argv.slice(2)], { + env: { ...process.env, [TSX_MARKER]: "1" }, + stdio: "inherit", + }); + if (child.error) fail(2, "cannot start the TypeScript loader: " + child.error.message); + process.exit(child.status ?? 2); +} + +run().then((code) => process.exit(code), (error) => { + process.stderr.write("check-skills: internal error: " + String(error && error.stack || error) + "\n"); + process.exit(2); +}); diff --git a/scripts/test/check-skills.test.mjs b/scripts/test/check-skills.test.mjs new file mode 100644 index 00000000..c7883915 --- /dev/null +++ b/scripts/test/check-skills.test.mjs @@ -0,0 +1,101 @@ +// scripts/check-skills.mjs (#387): the repo-wide Agent Skills spec check. +// +// The three cases the ticket asks to see go red — uppercase name, empty +// description, a body past 500 lines — plus the green path and the discovery +// mode that CI runs. +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +const CLI = fileURLToPath(new URL("../check-skills.mjs", import.meta.url)); +const ROOT = fileURLToPath(new URL("../..", import.meta.url)); + +/** Run the checker the way CI does: one plain node process, no build first. */ +function check(args = [], { cwd = ROOT } = {}) { + const result = spawnSync(process.execPath, [CLI, ...args], { cwd, encoding: "utf8", timeout: 120_000 }); + return { code: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; +} + +/** Write one skill directory under a throwaway root and return its path. */ +function skill(root, folder, frontmatter, body = "body\n") { + const dir = path.join(root, folder); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, "SKILL.md"), `---\n${frontmatter}\n---\n${body}`); + return dir; +} + +function withRoot(t) { + const root = mkdtempSync(path.join(os.tmpdir(), "check-skills-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + return root; +} + +test("a skill that follows the spec passes and is named in the output", (t) => { + const root = withRoot(t); + const dir = skill(root, "demo", "name: demo\ndescription: Use when a test needs a demo skill."); + const result = check([dir]); + assert.equal(result.code, 0, result.stdout + result.stderr); + assert.match(result.stdout, /\[OK\] .*demo[/\\]SKILL\.md/); + assert.match(result.stdout, /1 SKILL\.md checked, 0 failed/); +}); + +test("an uppercase name goes red and names the field, the rule and the file", (t) => { + const root = withRoot(t); + const dir = skill(root, "Upper", "name: Upper\ndescription: Use when a test needs an uppercase name."); + const result = check([dir]); + assert.equal(result.code, 1, result.stdout + result.stderr); + assert.match(result.stdout, /\[FAIL\] .*Upper[/\\]SKILL\.md/); + assert.match(result.stdout, /SKILL\.md name "Upper" must be 1–64 lowercase/); + assert.match(result.stdout, /1 SKILL\.md checked, 1 failed/); +}); + +test("an empty description goes red", (t) => { + const root = withRoot(t); + const dir = skill(root, "nodesc", 'name: nodesc\ndescription: ""'); + const result = check([dir]); + assert.equal(result.code, 1, result.stdout + result.stderr); + assert.match(result.stdout, /description must be 1–1024 characters, got 0/); +}); + +test("a body past 500 lines goes red and reports the count", (t) => { + const root = withRoot(t); + const dir = skill(root, "longbody", "name: longbody\ndescription: Use when a test needs a long body.", "line\n".repeat(501)); + const result = check([dir]); + assert.equal(result.code, 1, result.stdout + result.stderr); + assert.match(result.stdout, /body must stay under 500 lines, got 501/); +}); + +test("a name that differs from its directory goes red", (t) => { + const root = withRoot(t); + const dir = skill(root, "foldername", "name: skilename\ndescription: Use when a test needs a mismatch."); + const result = check([dir]); + assert.equal(result.code, 1, result.stdout + result.stderr); + assert.match(result.stdout, /name must equal the directory it lives in/); +}); + +test("a skill directory with no SKILL.md goes red", (t) => { + const root = withRoot(t); + mkdirSync(path.join(root, "empty"), { recursive: true }); + const result = check([path.join(root, "empty")]); + assert.equal(result.code, 1, result.stdout + result.stderr); + assert.match(result.stdout, /\[FAIL\]/); + assert.match(result.stdout, /SKILL\.md must be a regular, non-symlink file/); +}); + +test("no arguments checks every SKILL.md Git tracks, and the shipped one passes", () => { + const result = check(); + assert.equal(result.code, 0, result.stdout + result.stderr); + assert.match(result.stdout, /apps\/plugin\/skills\/ans\/SKILL\.md/); + assert.match(result.stdout, /([1-9]\d*) SKILL\.md checked, 0 failed/); +}); + +test("a path that does not exist is a usage error, not a failing skill", (t) => { + const root = withRoot(t); + const result = check([path.join(root, "nowhere")]); + assert.equal(result.code, 2, result.stdout + result.stderr); + assert.match(result.stderr, /no such file or directory/); +}); From 198eda597466a907652ab42877aa76fdd1869405 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 18:43:38 +0800 Subject: [PATCH 02/10] =?UTF-8?q?fix(skill):=20=E5=AE=A1=E6=9F=A5=E8=BF=94?= =?UTF-8?q?=E4=BF=AE=E2=80=94=E2=80=94=E7=A9=BA=20description=20=E8=AF=B4?= =?UTF-8?q?=E4=BA=BA=E8=AF=9D=E3=80=81when=20=E8=AE=A4=20whenever=20?= =?UTF-8?q?=E5=92=8C=E4=B8=AD=E6=96=87=E3=80=81=E7=A9=BA=E4=BB=93=E5=BA=93?= =?UTF-8?q?=E4=B8=8D=E8=A3=85=E7=BB=BF=20(#387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - description 写成 `description:`(YAML null)以前报「must be a string, not object」,现在和缺这个字段一样说「has no description」。 - name 缺失不再报 `name undefined must be ...`,改成「has no name field」。 - 「什么时候用」的记号放宽:`when` 前缀(含 whenever)加中文的 什么时候/何时/时使用;错误信息把这几个词列出来。 - 正文行数不算前后空行:frontmatter 后面那行空行是分隔符,不是内容, 以前会让「499 行内容 + 一个空行」被数成 500 行。 - 一个 SKILL.md 都找不到时退出码 1,不再空着报绿(学 check-workflows)。 - 文件读不了算「没查成」:打 [ERROR],退出码 2,不混进规则不合格。 - 测试补上:`description:` 空值、缺 name、装好的副本改 name 后 validate 报红、 带空行的 499/500 边界、空仓库拒绝报绿。 审查还指出 AGENTS.md 把 install 说成走 validateSkillDirectory,已按实际改; README 两份同步说清源目录名可以随便叫。 --- AGENTS.md | 2 +- CHANGELOG.md | 9 ++-- apps/cli/src/commands/skill.ts | 2 +- apps/cli/src/skill-store.ts | 43 +++++++++++-------- apps/cli/test/skill.test.ts | 17 ++++++-- scripts/check-skills.mjs | 66 +++++++++++++++++++----------- scripts/test/check-skills.test.mjs | 49 +++++++++++++++++++--- 7 files changed, 136 insertions(+), 52 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d935b592..3f9716cf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,7 @@ AnySearch is an agent CLI (`ans`) that works inside one domain only. It keeps re - Push gate status: `pnpm hooks:status` exits 0 when the hook is in place and runs the same commands as the source; when it is missing, out of date, not executable, or someone else's, it exits non-zero and names which; outside a git repo it exits 2. - `node scripts/preflight-test.mjs --dry-run` prints the plan; `--full` runs everything. Every test run points `HOME`/`USERPROFILE` at a throwaway temp dir and drops the repository pointers (`GIT_DIR` and the rest), so a test that forgets its own sandbox writes there instead of your `~/.ans`, and a test that makes its own repo cannot commit into your checkout; a green run deletes it (or says it could not), a red one keeps it and prints the path. What runs at each step is under "Gate rules" below. - The gate's own tests, three groups: `node --test "scripts/test/preflight-*.test.mjs"` covers the gate's rules — which files a push carries, which packages that selects, what a red run prints, which home the child gets, which repository git reads inside a test, that a red self-test blocks, and that `hooks:install` / `hooks:status` put the right file in place and name what is wrong when they cannot. `node --test scripts/test/ci-changes.test.mjs` and `node --test scripts/test/check-workflows.test.mjs` cover the shared judgments: CI's change policy and workflow checker (#487). CI runs all three in `check-build`, and a full gate run runs each group as its own run. The gate names each group and, when it passes, how many tests ran; a red group blocks the push before the suite starts. An incremental push does not pay for any of it. -- `node scripts/check-skills.mjs` — every `SKILL.md` Git tracks, checked against the agentskills.io spec: frontmatter is a mapping, `name` is 1–64 lowercase letters/digits with single hyphens and equals its directory, `description` is 1–1024 characters and says when to use the skill, body stays under 500 lines. It imports the same `validateSkillDirectory` that `ans skill install` / `ans skill validate` use, so the two can never disagree; pass a directory or a `SKILL.md` to check just that one. CI runs it in `check-build`. +- `node scripts/check-skills.mjs` — every `SKILL.md` Git can see (tracked, plus new files that are not ignored), checked against the agentskills.io spec: frontmatter is a mapping, `name` is 1–64 lowercase letters/digits with single hyphens and equals its directory, `description` is 1–1024 characters and says when to use the skill, body stays under 500 lines. It calls the same `validateSkillFile` / `validateSkillDirectory` that `ans skill install` and `ans skill validate` use, so they cannot disagree; pass a directory or a `SKILL.md` to check just that one. CI runs it in `check-build`. ### Gate rules (#367 — a commit, a push, a merge) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0716054..024aa2c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,17 +4,20 @@ ### Added -- **`scripts/check-skills.mjs`**:默认用 `git ls-files` 找出所有 `SKILL.md` 逐个查(构建产物和 `node_modules` 里的副本不算),也可以直接指定目录或文件。每条结果带文件、字段和期望,例如 `description must be 1–1024 characters, got 0`,不是只说「不合法」。分成 `[OK]` / `[FAIL]` 打印,有红的退出码 1。 +- **`scripts/check-skills.mjs`**:默认用 `git ls-files` 找出 Git 看得见的所有 `SKILL.md` 逐个查(已跟踪的,加上还没被忽略的新文件;构建产物和 `node_modules` 里的副本不算),也可以直接指定目录或文件。结果一行一个,带文件、字段和期望,比如 `[FAIL] …/SKILL.md: SKILL.md description must be 1–1024 characters, got 0`,不是只说「不合法」。有红的退出码 1;文件读不了算「没查成」,退出码 2,不混进「这个 skill 不合格」。 +- **一个 `SKILL.md` 都找不到也报红**:宁可退出码 1 也不假装查过了——仓库本来就该带着这份 skill。 - **`check-build` 多了两步**:跑这个检查,再跑它自己的测试(大写名字、清空 `description`、正文 500 行,三种改坏都会红)。 ### Changed -- **`validateSkillFile` 的检查范围扩到整套规范**:以前只管 frontmatter 是不是 mapping、`name` 合不合规;现在还要 `description` 1–1024 字并说清什么时候用、正文少于 500 行。`ans skill validate` 输出的 `[OK] … SKILL.md frontmatter` 改成 `[OK] … SKILL.md matches the Agent Skills spec`。 +- **`validateSkillFile` 的检查范围扩到整套规范**:以前只管 frontmatter 是不是 mapping、`name` 合不合规;现在还要 `description` 1–1024 字并说清什么时候用、正文少于 500 行。`ans skill validate` 输出的 `[OK] … SKILL.md frontmatter` 改成 `[OK] … SKILL.md name, description and body follow the spec`。 - **新增 `validateSkillDirectory`**:在文件检查之外加上「`name` 必须等于所在目录名」,`ans skill validate` 和仓库检查都走它。安装仍然只查文件——clone 下来的仓库文件夹名不一定等于 skill 名,装进 `skills/synced/` 之后这条规则自然成立。 +- **装 skill 的门槛跟着变了**:`ans skill install` 以前收只写了 `name` 的 frontmatter,现在收不了——缺 `description`、正文过 500 行、名字不合规都会被挡下来;已经装好但不合规的,`ans skill validate` 会报红。要装的 skill 得先改好。 ### Known limits -- **「说了什么时候用」只能查字面**:要求 `description` 里出现 `when`(比如 `Use when the user …`)。写得烂但带 `when` 的句子照样过;这条挡的是漏写,不是写得不好。 +- **「说了什么时候用」只能认几个词**:`description` 里要有 `when` / `whenever`,或者中文的 `什么时候` / `何时` / `时使用`。换个说法的(比如「审查代码时用」)照样会被挡,错误信息会把认的词列出来;写得烂但带这些词的也照样过。这条挡的是漏写,不是写得不好。 +- **正文行数不算前后空行**:frontmatter 后面那行空行、正文末尾的空行都不计入 500 行,数的是实际内容行。 ## Unreleased — #505: 宿主模板检查:坏形状、非整数 timeout、指错适配器都会红 diff --git a/apps/cli/src/commands/skill.ts b/apps/cli/src/commands/skill.ts index f542032c..a6570c68 100644 --- a/apps/cli/src/commands/skill.ts +++ b/apps/cli/src/commands/skill.ts @@ -92,7 +92,7 @@ export async function runSkill(args: string[], opts: SkillCommandOptions = {}): const results = validateInstalledSkills(scopeOpts, selected); if (results.length === 0) out("No installed skills to validate.\n"); for (const result of results) { - out(result.ok ? `[OK] ${result.name}: SKILL.md matches the Agent Skills spec\n` : `[FAIL] ${result.name}: ${result.error}\n`); + out(result.ok ? `[OK] ${result.name}: SKILL.md name, description and body follow the spec\n` : `[FAIL] ${result.name}: ${result.error}\n`); } return results.every((result) => result.ok) ? 0 : 1; } diff --git a/apps/cli/src/skill-store.ts b/apps/cli/src/skill-store.ts index ef2ca995..5a18f71e 100644 --- a/apps/cli/src/skill-store.ts +++ b/apps/cli/src/skill-store.ts @@ -76,9 +76,8 @@ function requireDirectory(path: string, label: string): void { /** Require a regular file, rejecting directories and symlinks. */ function requireFile(path: string, label: string): void { const stat = statIfPresent(path); - if (!stat || !stat.isFile() || stat.isSymbolicLink()) { - fail(`${label} must be a regular, non-symlink file: ${path}`); - } + if (!stat) fail(`${label} is missing: ${path}`); + if (!stat.isFile() || stat.isSymbolicLink()) fail(`${label} must be a regular, non-symlink file: ${path}`); } /** Resolve the selected scope's skills root (user or project). */ @@ -165,8 +164,9 @@ function requireName(value: unknown, file?: string): asserts value is string { if (typeof value !== "string" || !/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(value) || value.includes("--") || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) { const rule = "1–64 lowercase letters/digits, with single hyphens, and not a reserved device name"; - fail(file === undefined - ? `skill name must be ${rule}` + if (file === undefined) fail(`skill name must be ${rule}`); + fail(value === undefined + ? `SKILL.md has no name field; it must be ${rule}: ${file}` : `SKILL.md name ${JSON.stringify(value)} must be ${rule}: ${file}`); } } @@ -673,19 +673,26 @@ function writeManifest(managed: string, manifest: SkillManifest): void { } /** The Agent Skills spec's limit on the Markdown body that follows the frontmatter. */ -export const SKILL_BODY_LINE_LIMIT = 500; +const SKILL_BODY_LINE_LIMIT = 500; /** The Agent Skills spec's character bounds for `description`. */ -export const SKILL_DESCRIPTION_MIN_CHARS = 1; -export const SKILL_DESCRIPTION_MAX_CHARS = 1024; +const SKILL_DESCRIPTION_MIN_CHARS = 1; +const SKILL_DESCRIPTION_MAX_CHARS = 1024; +/** + * Words that carry the "when to use it" half of a description. The spec asks for + * it in prose, so the check has to settle for a marker: English `when`/`whenever` + * and the Chinese ways of saying it. A description that says it some other way is + * sent back with this list, which is the cheapest thing to point at. + */ +const WHEN_TO_USE = /\bwhen|什么时候|何时|时使用/i; /** * Require a description that says what the skill does and when to use it (#387). - * The spec asks for both halves; a description with no `when` clause names the + * The spec asks for both halves; a description with no such clause names the * topic but never tells an agent when to reach for it. */ function requireDescription(value: unknown, path: string): void { - if (value === undefined) { - fail(`SKILL.md has no description field; the spec wants 1–1024 characters saying what the skill does and when to use it: ${path}`); + if (value === undefined || value === null) { + fail(`SKILL.md has no description; it must be ${SKILL_DESCRIPTION_MIN_CHARS}–${SKILL_DESCRIPTION_MAX_CHARS} characters saying what the skill does and when to use it: ${path}`); } if (typeof value !== "string") { fail(`SKILL.md description must be a string, not ${Array.isArray(value) ? "a list" : typeof value}: ${path}`); @@ -693,16 +700,20 @@ function requireDescription(value: unknown, path: string): void { const description = value.trim(); const length = [...description].length; if (length < SKILL_DESCRIPTION_MIN_CHARS || length > SKILL_DESCRIPTION_MAX_CHARS) { - fail(`SKILL.md description must be 1–1024 characters, got ${length}: ${path}`); + fail(`SKILL.md description must be ${SKILL_DESCRIPTION_MIN_CHARS}–${SKILL_DESCRIPTION_MAX_CHARS} characters, got ${length}: ${path}`); } - if (!/\bwhen\b/i.test(description)) { - fail(`SKILL.md description must also say when to use the skill, e.g. "Use when the user …"; got "${description.slice(0, 120)}": ${path}`); + if (!WHEN_TO_USE.test(description)) { + fail(`SKILL.md description must also say when to use the skill — use "when"/"whenever" or say 什么时候用/何时/时使用; got "${description.slice(0, 120)}": ${path}`); } } -/** Keep the body under the spec's 500-line budget; the frontmatter does not count. */ +/** + * Keep the body under the spec's 500-line budget; the frontmatter does not count, + * and neither do the blank lines around the body — they are separators, not + * content, and counting them would make the house style lose two lines. + */ function requireShortBody(body: string, path: string): void { - const trimmed = body.replace(/(?:\r?\n)+$/, ""); + const trimmed = body.replace(/^(?:\r?\n)+/, "").replace(/(?:\r?\n)+$/, ""); const lines = trimmed === "" ? 0 : trimmed.split(/\r?\n/).length; if (lines >= SKILL_BODY_LINE_LIMIT) { fail(`SKILL.md body must stay under ${SKILL_BODY_LINE_LIMIT} lines, got ${lines} (move detail into files the skill references): ${path}`); diff --git a/apps/cli/test/skill.test.ts b/apps/cli/test/skill.test.ts index 971bab29..ffbc2930 100644 --- a/apps/cli/test/skill.test.ts +++ b/apps/cli/test/skill.test.ts @@ -535,10 +535,14 @@ test("description and body rules are enforced by install and validate alike", as const dir = f.source(); const file = join(dir, "SKILL.md"); const cases: [string, string][] = [ - ["---\nname: demo\n---\n", "has no description field"], + ["---\nname: demo\n---\n", "has no description"], + // Clearing the value the obvious way (`description:` with nothing after it) + // is YAML null, not an empty string; it has to read like a missing field. + ["---\nname: demo\ndescription:\n---\n", "has no description"], ["---\nname: demo\ndescription: \"\"\n---\n", "description must be 1–1024 characters, got 0"], ["---\nname: demo\ndescription: A skill about demos.\n---\n", "must also say when to use the skill"], [`---\nname: demo\ndescription: Use when the body is too long.\n---\n${"line\n".repeat(500)}`, "body must stay under 500 lines, got 500"], + ["---\ndescription: Use when the name is gone.\n---\n", "has no name field"], ]; for (const [text, expected] of cases) { writeFileSync(file, text); @@ -556,12 +560,19 @@ test("description and body rules are enforced by install and validate alike", as assert.equal(validate.code, 1, validate.stdout); assert.ok(validate.stdout.includes(expected), `validate said: ${validate.stdout}`); } - // The 500-line budget is exact: 499 body lines pass, 500 do not. - const body = (lines: number) => `---\nname: demo\ndescription: Use when the fixture needs a demo skill.\n---\n${"line\n".repeat(lines)}`; + // The 500-line budget is exact, and the blank line after the frontmatter is a + // separator, not body content: 499 content lines pass, 500 do not. + const body = (lines: number) => `---\nname: demo\ndescription: Use when the fixture needs a demo skill.\n---\n\n${"line\n".repeat(lines)}`; writeFileSync(installed, body(499)); assert.equal((await f.run(["validate", "demo"])).code, 0); writeFileSync(installed, body(500)); assert.equal((await f.run(["validate", "demo"])).code, 1); + // validate also holds the installed copy to its directory name, which is what + // keeps it agreeing with the repo check about the same file. + writeFileSync(installed, "---\nname: other\ndescription: Use when the name drifted.\n---\nbody\n"); + const drift = await f.run(["validate", "demo"]); + assert.equal(drift.code, 1, drift.stdout); + assert.match(drift.stdout, /name must equal the directory it lives in/); }); test("source symlinks are rejected and staging is rolled back", async (t) => { diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs index 8acec03e..b1384d6b 100644 --- a/scripts/check-skills.mjs +++ b/scripts/check-skills.mjs @@ -8,23 +8,26 @@ // only existed in CI would drift from the one users hit. // // Usage: -// node scripts/check-skills.mjs # every SKILL.md Git tracks +// node scripts/check-skills.mjs # every SKILL.md Git can see // node scripts/check-skills.mjs # only these // -// Exit codes: 0 every skill passes · 1 a skill broke a rule · 2 the check could -// not run (no Git, no tsx, a path that does not exist). +// Exit codes: 0 every skill passes · 1 a skill broke a rule, or no SKILL.md was +// found at all · 2 the check could not run (no Git, no tsx, a path that does not +// exist, a file that cannot be read). import { spawnSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import process from "node:process"; import { fileURLToPath, pathToFileURL } from "node:url"; -const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const SCRIPT_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const SCRIPT = fileURLToPath(import.meta.url); +/** Which checkout to scan. The tests point this at a throwaway repo. */ +const ROOT = process.env.ANS_CHECK_SKILLS_ROOT ? path.resolve(process.env.ANS_CHECK_SKILLS_ROOT) : SCRIPT_ROOT; /** Set in the child so the re-entry below happens exactly once. */ const TSX_MARKER = "ANS_CHECK_SKILLS_TSX"; /** The workspace tsx loader: the checker imports TypeScript sources directly, no build first. */ -const TSX_LOADER = path.join(ROOT, "apps", "cli", "node_modules", "tsx", "dist", "loader.mjs"); +const TSX_LOADER = path.join(SCRIPT_ROOT, "apps", "cli", "node_modules", "tsx", "dist", "loader.mjs"); function fail(code, detail) { process.stderr.write("check-skills: " + detail + "\n"); @@ -40,24 +43,32 @@ function skillFileOf(target) { } /** - * Every SKILL.md Git tracks. Tracking, not a directory walk: build output - * (apps/cli/dist carries a copy of the plugin skills) and node_modules hold - * copies of the same file, and re-checking those would report each rule twice. + * Every SKILL.md Git can see: tracked files plus the ones not ignored yet, so a + * newly written skill is checked before it is staged. Not a directory walk — + * build output (apps/cli/dist carries a copy of the plugin skills) and + * node_modules hold copies of the same file, and checking those would report + * every rule twice. */ -function trackedSkillFiles() { - const listed = spawnSync("git", ["ls-files", "-z"], { +function gitVisibleSkillFiles() { + const listed = spawnSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, }); if (listed.error) throw new Error("cannot run git ls-files: " + listed.error.message); if (listed.status !== 0) { throw new Error("git ls-files failed in " + ROOT + ": " + (String(listed.stderr).trim() || "exit " + listed.status)); } - return String(listed.stdout).split("\0").filter(Boolean) - .filter((file) => path.posix.basename(file) === "SKILL.md") + return [...new Set(String(listed.stdout).split("\0").filter(Boolean) + .filter((file) => path.posix.basename(file) === "SKILL.md"))] .map((file) => path.join(ROOT, file)) .sort(); } +/** Rule messages end with ": ", and the [FAIL] line already names the file. */ +function withoutTrailingPath(message, file) { + const suffix = ": " + file; + return message.endsWith(suffix) ? message.slice(0, -suffix.length) : message; +} + /** Show a path relative to where the check was started, for readable CI logs. */ function shown(file) { const relative = path.relative(process.cwd(), file); @@ -69,30 +80,39 @@ async function run() { const args = process.argv.slice(2); let files; try { - files = args.length > 0 ? args.map(skillFileOf) : trackedSkillFiles(); + files = args.length > 0 ? args.map(skillFileOf) : gitVisibleSkillFiles(); } catch (error) { fail(2, error.message); } + // Design: a green run that checked nothing is not evidence. The repository + // ships a skill; if discovery finds none, the check is broken, not the skills. if (files.length === 0) { - process.stdout.write("check-skills: no SKILL.md found\n"); - return 0; + process.stdout.write("[FAIL] no SKILL.md found — refusing to pass with nothing checked\n"); + return 1; } let failed = 0; + let unreadable = 0; for (const file of files) { try { const name = validateSkillDirectory(path.dirname(file)); process.stdout.write(`[OK] ${shown(file)} (name: ${name})\n`); } catch (error) { - failed += 1; - // A rule failure reads "field + what was expected + which file"; anything - // else (a broken read, a missing parent) keeps its stack so it is not - // mistaken for a rule verdict. - const detail = error instanceof SkillError ? error.message : String(error && error.stack || error); - process.stdout.write(`[FAIL] ${shown(file)}: ${detail}\n`); + // A rule failure reads "field + what was expected"; anything else (an + // unreadable file, a missing parent) is reported apart and fails the run + // as "could not check", never as "this skill is broken". + if (error instanceof SkillError) { + failed += 1; + process.stdout.write(`[FAIL] ${shown(file)}: ${withoutTrailingPath(error.message, file)}\n`); + } else { + unreadable += 1; + process.stdout.write(`[ERROR] ${shown(file)}: ${String(error && error.stack || error)}\n`); + } } } - process.stdout.write(`${files.length} SKILL.md checked, ${failed} failed\n`); - return failed === 0 ? 0 : 1; + const counted = [`${files.length} SKILL.md checked`, `${failed} failed`]; + if (unreadable > 0) counted.push(`${unreadable} could not be read`); + process.stdout.write(counted.join(", ") + "\n"); + return unreadable > 0 ? 2 : failed === 0 ? 0 : 1; } if (process.env[TSX_MARKER] !== "1") { diff --git a/scripts/test/check-skills.test.mjs b/scripts/test/check-skills.test.mjs index c7883915..41cec96d 100644 --- a/scripts/test/check-skills.test.mjs +++ b/scripts/test/check-skills.test.mjs @@ -14,12 +14,22 @@ import { fileURLToPath } from "node:url"; const CLI = fileURLToPath(new URL("../check-skills.mjs", import.meta.url)); const ROOT = fileURLToPath(new URL("../..", import.meta.url)); -/** Run the checker the way CI does: one plain node process, no build first. */ -function check(args = [], { cwd = ROOT } = {}) { - const result = spawnSync(process.execPath, [CLI, ...args], { cwd, encoding: "utf8", timeout: 120_000 }); +/** + * Run the checker the way CI does: one plain node process, no build first. + * `root` swaps in another checkout for the no-argument discovery mode. + */ +function check(args = [], { cwd = ROOT, root } = {}) { + const env = root ? { ...process.env, ANS_CHECK_SKILLS_ROOT: root } : process.env; + const result = spawnSync(process.execPath, [CLI, ...args], { cwd, env, encoding: "utf8", timeout: 120_000 }); return { code: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; } +/** Run a Git command in a fixture repository and insist it worked. */ +function git(cwd, args) { + const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8" }); + assert.equal(result.status, 0, `git ${args.join(" ")}: ${result.stderr}`); +} + /** Write one skill directory under a throwaway root and return its path. */ function skill(root, folder, frontmatter, body = "body\n") { const dir = path.join(root, folder); @@ -83,16 +93,45 @@ test("a skill directory with no SKILL.md goes red", (t) => { const result = check([path.join(root, "empty")]); assert.equal(result.code, 1, result.stdout + result.stderr); assert.match(result.stdout, /\[FAIL\]/); - assert.match(result.stdout, /SKILL\.md must be a regular, non-symlink file/); + assert.match(result.stdout, /SKILL\.md is missing/); +}); + +test("no arguments checks what Git can see: tracked, untracked, not ignored", (t) => { + const root = withRoot(t); + git(root, ["init", "--quiet"]); + git(root, ["config", "user.name", "Check Skills Test"]); + git(root, ["config", "user.email", "check-skills@example.invalid"]); + skill(root, "alpha", "name: alpha\ndescription: Use when a test needs alpha."); + git(root, ["add", "--", "alpha/SKILL.md", "alpha"]); + git(root, ["commit", "--quiet", "-m", "alpha"]); + // Written but not staged: a new skill has to be caught before it is committed. + skill(root, "beta", "name: beta\ndescription: Use when a test needs beta."); + writeFileSync(path.join(root, ".gitignore"), "ignored/\n"); + // Ignored on purpose: build output and scratch copies are not sources. + skill(root, "ignored/gamma", 'name: gamma\ndescription: ""'); + const result = check([], { cwd: root, root }); + assert.equal(result.code, 0, result.stdout + result.stderr); + assert.match(result.stdout, /alpha[/\\]SKILL\.md/); + assert.match(result.stdout, /beta[/\\]SKILL\.md/); + assert.doesNotMatch(result.stdout, /gamma/); + assert.match(result.stdout, /2 SKILL\.md checked, 0 failed/); }); -test("no arguments checks every SKILL.md Git tracks, and the shipped one passes", () => { +test("no arguments in this checkout finds the shipped skill and passes it", () => { const result = check(); assert.equal(result.code, 0, result.stdout + result.stderr); assert.match(result.stdout, /apps\/plugin\/skills\/ans\/SKILL\.md/); assert.match(result.stdout, /([1-9]\d*) SKILL\.md checked, 0 failed/); }); +test("a checkout with no skill is refused instead of passing vacuously", (t) => { + const root = withRoot(t); + git(root, ["init", "--quiet"]); + const result = check([], { cwd: root, root }); + assert.equal(result.code, 1, result.stdout + result.stderr); + assert.match(result.stdout, /no SKILL\.md found/); +}); + test("a path that does not exist is a usage error, not a failing skill", (t) => { const root = withRoot(t); const result = check([path.join(root, "nowhere")]); From 2f7b651fa8ec8ee7a28e8a6dbce91762bb547b0b Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 18:55:53 +0800 Subject: [PATCH 03/10] =?UTF-8?q?fix(skill):=20=E4=BA=8C=E8=BD=AE=E8=BF=94?= =?UTF-8?q?=E4=BF=AE=E2=80=94=E2=80=94name=20=E7=A9=BA=E5=80=BC=E3=80=81CR?= =?UTF-8?q?=20=E8=A1=8C=E5=B0=BE=E3=80=81=E8=AF=BB=E4=B8=8D=E4=BA=86?= =?UTF-8?q?=E7=AE=97=E6=B2=A1=E6=9F=A5=E6=88=90=EF=BC=8C=E6=96=87=E6=A1=A3?= =?UTF-8?q?=E5=8F=A3=E5=BE=84=E5=AF=B9=E9=BD=90=20(#387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `name:`(YAML null)和缺字段一样报「has no name field」,不再念成 name null。 - 正文数行先把 \r\n 和单独的 \r 都当成换行,免得只用 CR 的文件把 600 行数成 1 行。 - 检查脚本按 SkillError 的 exitCode 分流:1 才算规则不合格,别的算「没查成」,退出码 2。 - 补测试:name 空值、whenever 和中文「时使用」都算说清了什么时候用、 POSIX 上 chmod 000 的文件走 [ERROR] 分支(Windows 跳过)。 - 文档说实话:AGENTS.md 不再说 install 和 validate 结论永远一致(目录同名这条 install 故意不查),README 两份、help 文案、CHANGELOG 都写清查的是规范里哪几条、 哪些不查、装 skill 的门槛变成什么样。 --- AGENTS.md | 2 +- CHANGELOG.md | 12 +++++++----- README.md | 2 +- README.zh-CN.md | 5 +++-- apps/cli/src/commands/skill.ts | 11 ++++++----- apps/cli/src/skill-store.ts | 6 +++--- apps/cli/test/skill.test.ts | 13 +++++++++++++ scripts/check-skills.mjs | 18 +++++++++++------- scripts/test/check-skills.test.mjs | 20 +++++++++++++++++++- 9 files changed, 64 insertions(+), 25 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3f9716cf..de18dbe8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,7 @@ AnySearch is an agent CLI (`ans`) that works inside one domain only. It keeps re - Push gate status: `pnpm hooks:status` exits 0 when the hook is in place and runs the same commands as the source; when it is missing, out of date, not executable, or someone else's, it exits non-zero and names which; outside a git repo it exits 2. - `node scripts/preflight-test.mjs --dry-run` prints the plan; `--full` runs everything. Every test run points `HOME`/`USERPROFILE` at a throwaway temp dir and drops the repository pointers (`GIT_DIR` and the rest), so a test that forgets its own sandbox writes there instead of your `~/.ans`, and a test that makes its own repo cannot commit into your checkout; a green run deletes it (or says it could not), a red one keeps it and prints the path. What runs at each step is under "Gate rules" below. - The gate's own tests, three groups: `node --test "scripts/test/preflight-*.test.mjs"` covers the gate's rules — which files a push carries, which packages that selects, what a red run prints, which home the child gets, which repository git reads inside a test, that a red self-test blocks, and that `hooks:install` / `hooks:status` put the right file in place and name what is wrong when they cannot. `node --test scripts/test/ci-changes.test.mjs` and `node --test scripts/test/check-workflows.test.mjs` cover the shared judgments: CI's change policy and workflow checker (#487). CI runs all three in `check-build`, and a full gate run runs each group as its own run. The gate names each group and, when it passes, how many tests ran; a red group blocks the push before the suite starts. An incremental push does not pay for any of it. -- `node scripts/check-skills.mjs` — every `SKILL.md` Git can see (tracked, plus new files that are not ignored), checked against the agentskills.io spec: frontmatter is a mapping, `name` is 1–64 lowercase letters/digits with single hyphens and equals its directory, `description` is 1–1024 characters and says when to use the skill, body stays under 500 lines. It calls the same `validateSkillFile` / `validateSkillDirectory` that `ans skill install` and `ans skill validate` use, so they cannot disagree; pass a directory or a `SKILL.md` to check just that one. CI runs it in `check-build`. +- `node scripts/check-skills.mjs` — every `SKILL.md` Git can see (tracked, plus new files that are not ignored), checked against the agentskills.io rules the product enforces: frontmatter is a mapping, `name` is 1–64 lowercase letters/digits with single hyphens (not a Windows device name) and equals its directory, `description` is 1–1024 characters and says when to use the skill, body stays under 500 lines. It calls the same `validateSkillFile` / `validateSkillDirectory` that `ans skill install` and `ans skill validate` use, so all three give the same verdict — except on `name` equals its directory, which install skips on purpose (a cloned repo's folder carries its own name) and validate and this script enforce. Exit 1 = a skill broke a rule or nothing was found; exit 2 = the check could not run. Pass a directory or a `SKILL.md` to check just that one; CI runs it in `check-build`. ### Gate rules (#367 — a commit, a push, a merge) diff --git a/CHANGELOG.md b/CHANGELOG.md index 024aa2c6..fd2508d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,20 +4,22 @@ ### Added -- **`scripts/check-skills.mjs`**:默认用 `git ls-files` 找出 Git 看得见的所有 `SKILL.md` 逐个查(已跟踪的,加上还没被忽略的新文件;构建产物和 `node_modules` 里的副本不算),也可以直接指定目录或文件。结果一行一个,带文件、字段和期望,比如 `[FAIL] …/SKILL.md: SKILL.md description must be 1–1024 characters, got 0`,不是只说「不合法」。有红的退出码 1;文件读不了算「没查成」,退出码 2,不混进「这个 skill 不合格」。 +- **`scripts/check-skills.mjs`**:默认用 `git ls-files` 找出 Git 看得见的所有 `SKILL.md` 逐个查(已跟踪的,加上还没被忽略的新文件;构建产物和 `node_modules` 里的副本不算),也可以直接指定目录或文件。每条结果都带文件、字段和期望,比如 `[FAIL] …/SKILL.md: SKILL.md description must be 1–1024 characters, got 0`,不是只说「不合法」。有红的退出码 1;文件读不了算「没查成」,退出码 2,不混进「这个 skill 不合格」。 - **一个 `SKILL.md` 都找不到也报红**:宁可退出码 1 也不假装查过了——仓库本来就该带着这份 skill。 -- **`check-build` 多了两步**:跑这个检查,再跑它自己的测试(大写名字、清空 `description`、正文 500 行,三种改坏都会红)。 +- **`check-build` 多了两步**:跑这个检查,再跑它自己的测试(大写名字、清空 `description`、正文到 500 行,三种改坏都会红)。 ### Changed -- **`validateSkillFile` 的检查范围扩到整套规范**:以前只管 frontmatter 是不是 mapping、`name` 合不合规;现在还要 `description` 1–1024 字并说清什么时候用、正文少于 500 行。`ans skill validate` 输出的 `[OK] … SKILL.md frontmatter` 改成 `[OK] … SKILL.md name, description and body follow the spec`。 +- **`validateSkillFile` 查的从「frontmatter + name」变成整套要查的东西**:frontmatter 是 YAML mapping、`name` 合不合规之外,还要 `description` 1–1024 字并说清什么时候用、正文少于 500 行。规范里标 Must 的那几条照旧,另外两条(`description` 要点出什么时候用、正文 500 行)是本仓库自己加的;`license` / `compatibility` / `metadata` 这些可选字段不查。 - **新增 `validateSkillDirectory`**:在文件检查之外加上「`name` 必须等于所在目录名」,`ans skill validate` 和仓库检查都走它。安装仍然只查文件——clone 下来的仓库文件夹名不一定等于 skill 名,装进 `skills/synced/` 之后这条规则自然成立。 -- **装 skill 的门槛跟着变了**:`ans skill install` 以前收只写了 `name` 的 frontmatter,现在收不了——缺 `description`、正文过 500 行、名字不合规都会被挡下来;已经装好但不合规的,`ans skill validate` 会报红。要装的 skill 得先改好。 +- **装 skill 的门槛跟着变了**:`ans skill install` 以前收只写了 `name` 的 frontmatter,现在收不了。缺 `description`、正文到 500 行、名字不合规都会被挡下来,`description` 只是把「做什么」写清楚、没写「什么时候用」的也一样被挡(规范对这种写法只说「写得不好」,这里直接不收)。已经装好但不合规的,`ans skill validate` 会报红。要装的 skill 得先改好。 +- **报错和通过的话都跟着改了**:`ans skill validate` 通过时打 `[OK] … SKILL.md name, description and body follow the spec`;`SKILL.md` 不存在时说「is missing」,不再说成「must be a regular file」;缺字段时说「has no name field / has no description」,不再把 YAML 空值(`name:`、`description:`)念成 `undefined` / `null` / `object`。 ### Known limits -- **「说了什么时候用」只能认几个词**:`description` 里要有 `when` / `whenever`,或者中文的 `什么时候` / `何时` / `时使用`。换个说法的(比如「审查代码时用」)照样会被挡,错误信息会把认的词列出来;写得烂但带这些词的也照样过。这条挡的是漏写,不是写得不好。 +- **「说了什么时候用」只能认几个词**:`description` 里要有 `when` / `whenever`,或者中文的 `什么时候` / `何时` / `时使用`。换个说法的(比如「审查代码时用」)、以及日语西语之类的描述,照样会被挡;错误信息会把认的词列出来。反过来,带这些词但没真说清什么时候用的也照样过。这条挡的是漏写,不是写得不好。 - **正文行数不算前后空行**:frontmatter 后面那行空行、正文末尾的空行都不计入 500 行,数的是实际内容行。 +- **只查代码里写死的那些规则**:规范的 `license`、`compatibility`、`metadata`、`allowed-tools` 和引用文件一律不管,所以通过只说明名字、描述、正文这三样没问题。 ## Unreleased — #505: 宿主模板检查:坏形状、非整数 timeout、指错适配器都会红 diff --git a/README.md b/README.md index d37a6b69..f6337543 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,7 @@ ans skill uninstall ans --project `ans skill` only copies a directory inside a local Git checkout (one that contains a `SKILL.md`) into `skills/synced/`, recording its source and commit. It is not a package manager and does not execute skill code. Locking, manifests, and cleanup live in `apps/cli/src/skill-store.ts`. -`install` and `validate` hold a skill to the [Agent Skills spec](https://agentskills.io/specification): the frontmatter is a YAML mapping, `name` is 1–64 lowercase letters/digits with single hyphens, `description` is 1–1024 characters and says when to use the skill, and the body stays under 500 lines. A source folder may carry any name (a cloned repo usually does); `ans skill validate` and `node scripts/check-skills.mjs` — which checks every `SKILL.md` in this repository — also require `name` to equal its directory. +`install` and `validate` check the [Agent Skills spec](https://agentskills.io/specification) rules this repo enforces, plus a few house rules: the frontmatter is a YAML mapping, `name` is 1–64 lowercase letters/digits with single hyphens (not a Windows device name), `description` is 1–1024 characters and says when to use the skill, and the body stays under 500 lines. A source folder may carry any name (a cloned repo usually does); `ans skill validate` and `node scripts/check-skills.mjs` — which checks every `SKILL.md` in this repository — also require `name` to equal its directory. **Installed does not mean active.** These commands never touch domain TOML files: - **What `[skills].active` names**: skill keys declared in the domain TOML (shipped domains list runtime tags like `search`, `doctor`, `research`), not an auto-loader for `skills/synced/` directories. diff --git a/README.zh-CN.md b/README.zh-CN.md index 5d455192..ea0a0038 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -157,8 +157,9 @@ ans skill uninstall ans --project 并记下来源和 commit。它不是包管理器,也不会执行 skill 里的代码。锁、清单、 残留清理这些细节看 `apps/cli/src/skill-store.ts`。 -`install` 和 `validate` 都按 [Agent Skills 规范](https://agentskills.io/specification) 查:frontmatter 是 YAML mapping, -`name` 是 1–64 位小写字母数字加单连字符,`description` 1–1024 字且说清什么时候用,正文少于 500 行。 +`install` 和 `validate` 查的是 [Agent Skills 规范](https://agentskills.io/specification) 里这个仓库认的几条,外加几条自己的规矩: +frontmatter 是 YAML mapping,`name` 是 1–64 位小写字母数字加单连字符(不能是 Windows 保留设备名), +`description` 1–1024 字且说清什么时候用,正文少于 500 行。 源目录叫什么名字都行(clone 下来的仓库一般不是 skill 名);`ans skill validate` 和 `node scripts/check-skills.mjs`(查本仓库所有 `SKILL.md`)另外要求 `name` 和所在目录同名。 diff --git a/apps/cli/src/commands/skill.ts b/apps/cli/src/commands/skill.ts index a6570c68..50e68ff4 100644 --- a/apps/cli/src/commands/skill.ts +++ b/apps/cli/src/commands/skill.ts @@ -26,11 +26,12 @@ Options: --help, -h Show this help The source's current Git HEAD is recorded; checkout a commit/tag before installing. -A SKILL.md passes (agentskills.io/specification) when its frontmatter is a YAML mapping, -name is 1–64 lowercase letters/digits with single hyphens, description is 1–1024 -characters and says when to use the skill, and the body stays under 500 lines. -validate also wants name to equal the directory it lives in; install accepts any -source folder name (a cloned repo usually has one) and installs under frontmatter name. +Checked rules (agentskills.io/specification plus two house rules): frontmatter is a YAML +mapping; name is 1–64 lowercase letters/digits with single hyphens and is not a Windows +device name; description is 1–1024 characters and says when to use the skill; the body +stays under 500 lines. validate also requires name to equal the installed directory name; +install accepts any source folder name (a cloned repo usually has its own) and installs +under the name the frontmatter declares. Managed skills live in ${MANAGED_SKILLS_REL_PATH}; sibling directories under skills/ are user-authored. install copies the whole skill directory into ${MANAGED_SKILLS_REL_PATH}; the runtime never loads it (a host agent reads the files directly). [skills].active is just a list of keys for [skills.toolRequires], unrelated to directories in ${MANAGED_SKILLS_REL_PATH}. diff --git a/apps/cli/src/skill-store.ts b/apps/cli/src/skill-store.ts index 5a18f71e..0e227b29 100644 --- a/apps/cli/src/skill-store.ts +++ b/apps/cli/src/skill-store.ts @@ -165,7 +165,7 @@ function requireName(value: unknown, file?: string): asserts value is string { || value.includes("--") || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) { const rule = "1–64 lowercase letters/digits, with single hyphens, and not a reserved device name"; if (file === undefined) fail(`skill name must be ${rule}`); - fail(value === undefined + fail(value === undefined || value === null ? `SKILL.md has no name field; it must be ${rule}: ${file}` : `SKILL.md name ${JSON.stringify(value)} must be ${rule}: ${file}`); } @@ -713,8 +713,8 @@ function requireDescription(value: unknown, path: string): void { * content, and counting them would make the house style lose two lines. */ function requireShortBody(body: string, path: string): void { - const trimmed = body.replace(/^(?:\r?\n)+/, "").replace(/(?:\r?\n)+$/, ""); - const lines = trimmed === "" ? 0 : trimmed.split(/\r?\n/).length; + const trimmed = body.replace(/\r\n?/g, "\n").replace(/^\n+/, "").replace(/\n+$/, ""); + const lines = trimmed === "" ? 0 : trimmed.split("\n").length; if (lines >= SKILL_BODY_LINE_LIMIT) { fail(`SKILL.md body must stay under ${SKILL_BODY_LINE_LIMIT} lines, got ${lines} (move detail into files the skill references): ${path}`); } diff --git a/apps/cli/test/skill.test.ts b/apps/cli/test/skill.test.ts index ffbc2930..e40b2173 100644 --- a/apps/cli/test/skill.test.ts +++ b/apps/cli/test/skill.test.ts @@ -543,6 +543,8 @@ test("description and body rules are enforced by install and validate alike", as ["---\nname: demo\ndescription: A skill about demos.\n---\n", "must also say when to use the skill"], [`---\nname: demo\ndescription: Use when the body is too long.\n---\n${"line\n".repeat(500)}`, "body must stay under 500 lines, got 500"], ["---\ndescription: Use when the name is gone.\n---\n", "has no name field"], + // Same YAML-null trap as `description:` above, on the other required field. + ["---\nname:\ndescription: Use when the name is blank.\n---\n", "has no name field"], ]; for (const [text, expected] of cases) { writeFileSync(file, text); @@ -567,6 +569,17 @@ test("description and body rules are enforced by install and validate alike", as assert.equal((await f.run(["validate", "demo"])).code, 0); writeFileSync(installed, body(500)); assert.equal((await f.run(["validate", "demo"])).code, 1); + // The "when to use it" half accepts an English marker or a Chinese one; the + // descriptions an agent actually ships are written both ways. + for (const description of [ + "Reviews pull requests. Use whenever the user asks for a review.", + "搜索网页并整理结果,用户要求查资料时使用。", + ]) { + writeFileSync(installed, `---\nname: demo\ndescription: ${description}\n---\nbody\n`); + const ok = await f.run(["validate", "demo"]); + assert.equal(ok.code, 0, `${description} should pass: ${ok.stdout}`); + assert.match(ok.stdout, /SKILL\.md name, description and body follow the spec/); + } // validate also holds the installed copy to its directory name, which is what // keeps it agreeing with the repo check about the same file. writeFileSync(installed, "---\nname: other\ndescription: Use when the name drifted.\n---\nbody\n"); diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs index b1384d6b..719c73ac 100644 --- a/scripts/check-skills.mjs +++ b/scripts/check-skills.mjs @@ -11,9 +11,12 @@ // node scripts/check-skills.mjs # every SKILL.md Git can see // node scripts/check-skills.mjs # only these // -// Exit codes: 0 every skill passes · 1 a skill broke a rule, or no SKILL.md was -// found at all · 2 the check could not run (no Git, no tsx, a path that does not -// exist, a file that cannot be read). +// Exit codes: 0 every skill passes · 1 a skill broke a rule, or discovery found +// no SKILL.md at all · 2 the check could not run (no Git, no tsx, a path +// argument that does not exist, a file that cannot be read). +// +// `ANS_CHECK_SKILLS_ROOT` retargets discovery at another checkout; only the +// script's tests use it. import { spawnSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; @@ -97,10 +100,11 @@ async function run() { const name = validateSkillDirectory(path.dirname(file)); process.stdout.write(`[OK] ${shown(file)} (name: ${name})\n`); } catch (error) { - // A rule failure reads "field + what was expected"; anything else (an - // unreadable file, a missing parent) is reported apart and fails the run - // as "could not check", never as "this skill is broken". - if (error instanceof SkillError) { + // A rule failure reads "field + what was expected"; anything else (a + // permission error, an I/O failure) is reported apart and fails the run as + // "could not check", never as "this skill is broken". SkillError carries + // the exit code the CLI would use, so a usage-class error stays apart too. + if (error instanceof SkillError && error.exitCode === 1) { failed += 1; process.stdout.write(`[FAIL] ${shown(file)}: ${withoutTrailingPath(error.message, file)}\n`); } else { diff --git a/scripts/test/check-skills.test.mjs b/scripts/test/check-skills.test.mjs index 41cec96d..295f20ff 100644 --- a/scripts/test/check-skills.test.mjs +++ b/scripts/test/check-skills.test.mjs @@ -5,7 +5,7 @@ // mode that CI runs. import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; @@ -124,6 +124,24 @@ test("no arguments in this checkout finds the shipped skill and passes it", () = assert.match(result.stdout, /([1-9]\d*) SKILL\.md checked, 0 failed/); }); +// A file the checker cannot read is "could not check" (exit 2), not "this skill +// is broken" (exit 1); the two are read differently by whoever sees the red run. +test("an unreadable SKILL.md is reported apart and exits 2", (t) => { + if (process.platform === "win32") { + t.skip("Windows permissions do not deny a read this way"); + return; + } + const root = withRoot(t); + const dir = skill(root, "locked", "name: locked\ndescription: Use when the file cannot be read."); + const file = path.join(dir, "SKILL.md"); + chmodSync(file, 0o000); + t.after(() => chmodSync(file, 0o600)); + const result = check([dir]); + assert.equal(result.code, 2, result.stdout + result.stderr); + assert.match(result.stdout, /\[ERROR\]/); + assert.match(result.stdout, /could not be read/); +}); + test("a checkout with no skill is refused instead of passing vacuously", (t) => { const root = withRoot(t); git(root, ["init", "--quiet"]); From 5d0e0ad357561bff9942b12f54fcf0950ca94c42 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 19:10:04 +0800 Subject: [PATCH 04/10] =?UTF-8?q?fix(skill):=20=E4=B8=89=E8=BD=AE=E8=BF=94?= =?UTF-8?q?=E4=BF=AE=E2=80=94=E2=80=94=E4=BF=AE=E6=8E=89=E5=9C=A8=20ubuntu?= =?UTF-8?q?=20=E4=B8=8A=E5=BF=85=E7=BA=A2=E7=9A=84=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E9=92=A9=E5=AD=90=EF=BC=8C=E8=A1=A5=E9=BD=90=20CR=20=E5=92=8C?= =?UTF-8?q?=E4=B8=AD=E6=96=87=E5=8C=96=E8=AE=B0=E5=8F=B7=20(#387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 读不了的那个测试原来在 t.after 里 chmod 回来,钩子按注册顺序跑,清理先把目录删了, ubuntu(也就是这条测试唯一会跑的地方)上 chmod 抛 ENOENT,check-build 直接红。 改成不恢复权限——删一个 000 文件只看目录权,跟着加了「根用户读 000 也能读」的跳过。 - 断言改成认 [ERROR] 那一行和「1 could not be read」,不再被汇总行蒙过去。 - 补一条只用 CR 断行的正文测试(501 行报 501)。 - 记号表加上「使用时」,和「时使用」并列。 - 文档里的规矩数改成三条,help 文案不再说「two house rules」。 --- CHANGELOG.md | 4 ++-- apps/cli/src/commands/skill.ts | 2 +- apps/cli/src/skill-store.ts | 4 ++-- scripts/check-skills.mjs | 3 ++- scripts/test/check-skills.test.mjs | 33 ++++++++++++++++++++++++++---- 5 files changed, 36 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd2508d7..5b15bd76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,14 +10,14 @@ ### Changed -- **`validateSkillFile` 查的从「frontmatter + name」变成整套要查的东西**:frontmatter 是 YAML mapping、`name` 合不合规之外,还要 `description` 1–1024 字并说清什么时候用、正文少于 500 行。规范里标 Must 的那几条照旧,另外两条(`description` 要点出什么时候用、正文 500 行)是本仓库自己加的;`license` / `compatibility` / `metadata` 这些可选字段不查。 +- **`validateSkillFile` 查的从「frontmatter + name」变成整套要查的东西**:frontmatter 是 YAML mapping、`name` 合不合规之外,还要 `description` 1–1024 字并说清什么时候用、正文少于 500 行。规范里标 Must 的那几条照旧,另外三条是本仓库自己加的:`description` 要点出什么时候用、正文 500 行、名字不能是 Windows 保留设备名;`license` / `compatibility` / `metadata` 这些可选字段不查。 - **新增 `validateSkillDirectory`**:在文件检查之外加上「`name` 必须等于所在目录名」,`ans skill validate` 和仓库检查都走它。安装仍然只查文件——clone 下来的仓库文件夹名不一定等于 skill 名,装进 `skills/synced/` 之后这条规则自然成立。 - **装 skill 的门槛跟着变了**:`ans skill install` 以前收只写了 `name` 的 frontmatter,现在收不了。缺 `description`、正文到 500 行、名字不合规都会被挡下来,`description` 只是把「做什么」写清楚、没写「什么时候用」的也一样被挡(规范对这种写法只说「写得不好」,这里直接不收)。已经装好但不合规的,`ans skill validate` 会报红。要装的 skill 得先改好。 - **报错和通过的话都跟着改了**:`ans skill validate` 通过时打 `[OK] … SKILL.md name, description and body follow the spec`;`SKILL.md` 不存在时说「is missing」,不再说成「must be a regular file」;缺字段时说「has no name field / has no description」,不再把 YAML 空值(`name:`、`description:`)念成 `undefined` / `null` / `object`。 ### Known limits -- **「说了什么时候用」只能认几个词**:`description` 里要有 `when` / `whenever`,或者中文的 `什么时候` / `何时` / `时使用`。换个说法的(比如「审查代码时用」)、以及日语西语之类的描述,照样会被挡;错误信息会把认的词列出来。反过来,带这些词但没真说清什么时候用的也照样过。这条挡的是漏写,不是写得不好。 +- **「说了什么时候用」只能认几个词**:`description` 里要有 `when` / `whenever`,或者中文的 `什么时候` / `何时` / `时使用` / `使用时`。换个说法的(比如「审查代码时用」)、以及日语西语之类的描述,照样会被挡;错误信息会把认的词列出来。反过来,带这些词但没真说清什么时候用的也照样过。这条挡的是漏写,不是写得不好。 - **正文行数不算前后空行**:frontmatter 后面那行空行、正文末尾的空行都不计入 500 行,数的是实际内容行。 - **只查代码里写死的那些规则**:规范的 `license`、`compatibility`、`metadata`、`allowed-tools` 和引用文件一律不管,所以通过只说明名字、描述、正文这三样没问题。 diff --git a/apps/cli/src/commands/skill.ts b/apps/cli/src/commands/skill.ts index 50e68ff4..bdd3f519 100644 --- a/apps/cli/src/commands/skill.ts +++ b/apps/cli/src/commands/skill.ts @@ -26,7 +26,7 @@ Options: --help, -h Show this help The source's current Git HEAD is recorded; checkout a commit/tag before installing. -Checked rules (agentskills.io/specification plus two house rules): frontmatter is a YAML +Checked rules (agentskills.io/specification plus a few house rules): frontmatter is a YAML mapping; name is 1–64 lowercase letters/digits with single hyphens and is not a Windows device name; description is 1–1024 characters and says when to use the skill; the body stays under 500 lines. validate also requires name to equal the installed directory name; diff --git a/apps/cli/src/skill-store.ts b/apps/cli/src/skill-store.ts index 0e227b29..c57842ee 100644 --- a/apps/cli/src/skill-store.ts +++ b/apps/cli/src/skill-store.ts @@ -683,7 +683,7 @@ const SKILL_DESCRIPTION_MAX_CHARS = 1024; * and the Chinese ways of saying it. A description that says it some other way is * sent back with this list, which is the cheapest thing to point at. */ -const WHEN_TO_USE = /\bwhen|什么时候|何时|时使用/i; +const WHEN_TO_USE = /\bwhen|什么时候|何时|时使用|使用时/i; /** * Require a description that says what the skill does and when to use it (#387). @@ -703,7 +703,7 @@ function requireDescription(value: unknown, path: string): void { fail(`SKILL.md description must be ${SKILL_DESCRIPTION_MIN_CHARS}–${SKILL_DESCRIPTION_MAX_CHARS} characters, got ${length}: ${path}`); } if (!WHEN_TO_USE.test(description)) { - fail(`SKILL.md description must also say when to use the skill — use "when"/"whenever" or say 什么时候用/何时/时使用; got "${description.slice(0, 120)}": ${path}`); + fail(`SKILL.md description must also say when to use the skill — use "when"/"whenever" or say 什么时候用/何时/时使用/使用时; got "${description.slice(0, 120)}": ${path}`); } } diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs index 719c73ac..b29ab4a0 100644 --- a/scripts/check-skills.mjs +++ b/scripts/check-skills.mjs @@ -103,7 +103,8 @@ async function run() { // A rule failure reads "field + what was expected"; anything else (a // permission error, an I/O failure) is reported apart and fails the run as // "could not check", never as "this skill is broken". SkillError carries - // the exit code the CLI would use, so a usage-class error stays apart too. + // the exit code the CLI would use, so a usage-class error would stay apart + // too — no rule raises one today, but the split does not depend on that. if (error instanceof SkillError && error.exitCode === 1) { failed += 1; process.stdout.write(`[FAIL] ${shown(file)}: ${withoutTrailingPath(error.message, file)}\n`); diff --git a/scripts/test/check-skills.test.mjs b/scripts/test/check-skills.test.mjs index 295f20ff..1ec628e3 100644 --- a/scripts/test/check-skills.test.mjs +++ b/scripts/test/check-skills.test.mjs @@ -5,7 +5,7 @@ // mode that CI runs. import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; @@ -24,6 +24,16 @@ function check(args = [], { cwd = ROOT, root } = {}) { return { code: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; } +/** True when the permission bits just set did not actually deny a read (root). */ +function canStillRead(file) { + try { + readFileSync(file); + return true; + } catch { + return false; + } +} + /** Run a Git command in a fixture repository and insist it worked. */ function git(cwd, args) { const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8" }); @@ -87,6 +97,16 @@ test("a name that differs from its directory goes red", (t) => { assert.match(result.stdout, /name must equal the directory it lives in/); }); +test("a body that breaks lines with lone CR is still counted line by line", (t) => { + const root = withRoot(t); + const name = "crbody"; + const description = "Use when a test counts CR-separated lines."; + const dir = skill(root, name, `name: ${name}\ndescription: ${description}`, "line\r".repeat(501)); + const result = check([dir]); + assert.equal(result.code, 1, result.stdout + result.stderr); + assert.match(result.stdout, /body must stay under 500 lines, got 501/); +}); + test("a skill directory with no SKILL.md goes red", (t) => { const root = withRoot(t); mkdirSync(path.join(root, "empty"), { recursive: true }); @@ -134,12 +154,17 @@ test("an unreadable SKILL.md is reported apart and exits 2", (t) => { const root = withRoot(t); const dir = skill(root, "locked", "name: locked\ndescription: Use when the file cannot be read."); const file = path.join(dir, "SKILL.md"); + // No restore hook: deleting a 000-mode file only needs write permission on its + // directory, and a hook registered here would run after the cleanup hook. chmodSync(file, 0o000); - t.after(() => chmodSync(file, 0o600)); + if (canStillRead(file)) { + t.skip("this user can read a 000-mode file (root); the branch needs a denied read"); + return; + } const result = check([dir]); assert.equal(result.code, 2, result.stdout + result.stderr); - assert.match(result.stdout, /\[ERROR\]/); - assert.match(result.stdout, /could not be read/); + assert.match(result.stdout, /\[ERROR\] .*locked[/\\]SKILL\.md/); + assert.match(result.stdout, /1 could not be read/); }); test("a checkout with no skill is refused instead of passing vacuously", (t) => { From ec0f73475933113c03ba49a6bf0b27952383eb8a Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 19:26:45 +0800 Subject: [PATCH 05/10] =?UTF-8?q?test(skill):=20=E8=A1=A5=E4=B8=80?= =?UTF-8?q?=E6=9D=A1=E3=80=8C=E4=BD=BF=E7=94=A8=E6=97=B6=E3=80=8D=E7=9A=84?= =?UTF-8?q?=E9=80=9A=E8=BF=87=E7=94=A8=E4=BE=8B=20(#387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/cli/test/skill.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/cli/test/skill.test.ts b/apps/cli/test/skill.test.ts index e40b2173..8a0d4dc9 100644 --- a/apps/cli/test/skill.test.ts +++ b/apps/cli/test/skill.test.ts @@ -574,6 +574,7 @@ test("description and body rules are enforced by install and validate alike", as for (const description of [ "Reviews pull requests. Use whenever the user asks for a review.", "搜索网页并整理结果,用户要求查资料时使用。", + "把一周的提交整理成周报,周会前使用时最合适。", ]) { writeFileSync(installed, `---\nname: demo\ndescription: ${description}\n---\nbody\n`); const ok = await f.run(["validate", "demo"]); From 01618d729544b77674078e0f48f8616049f72bb7 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 20:22:16 +0800 Subject: [PATCH 06/10] =?UTF-8?q?fix(skill):=20review=20fish=20=E8=BF=94?= =?UTF-8?q?=E4=BF=AE=E2=80=94=E2=80=94=E6=9F=A5=20skill=20=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E6=8B=96=E8=BF=9B=20sqlite=EF=BC=8Ctsx=20=E8=B5=B0?= =?UTF-8?q?=E5=8C=85=E8=A7=A3=E6=9E=90=EF=BC=8C=E5=AD=90=E8=BF=9B=E7=A8=8B?= =?UTF-8?q?=E7=BB=99=E4=B8=8A=E9=99=90=20(#387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - skill-store.ts 改成从 @anysearch-cli/store/paths 取目录函数(仓库里已经有 6 处在用 这个子路径)。检查脚本只读一个 Markdown 文件,不该顺手把 better-sqlite3 的原生 模块加载进来;没预编译产物的机器上会变成「could not be read」,看着跟 skill 无关。 - 检查脚本的 tsx loader 不再写死 apps/cli/node_modules/tsx/dist/loader.mjs,改成 用 createRequire 从 apps/cli 解析 tsx 包;tsx 升级挪了文件不会把 CI 弄红。 - 两处 spawnSync 补上超时(git 60 秒,子进程 10 分钟),卡住会失败而不是挂着。 - 「什么时候用」的词表补上繁体「時」、日文「とき」和「时用」。 - 测试的 check() 帮手:子进程被杀/起不来时直接抛错(以前只报 null !== 1),并且 摘掉本机导出的 ANS_CHECK_SKILLS_ROOT,免得悄悄换目录跑;真实工作区那条把 root 钉死成仓库根。 - 脚本头注释收短。 --- CHANGELOG.md | 2 +- apps/cli/src/skill-store.ts | 15 +++++++------ scripts/check-skills.mjs | 34 +++++++++++++++++++----------- scripts/test/check-skills.test.mjs | 20 ++++++++++++------ 4 files changed, 44 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b15bd76..3500c908 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ ### Known limits -- **「说了什么时候用」只能认几个词**:`description` 里要有 `when` / `whenever`,或者中文的 `什么时候` / `何时` / `时使用` / `使用时`。换个说法的(比如「审查代码时用」)、以及日语西语之类的描述,照样会被挡;错误信息会把认的词列出来。反过来,带这些词但没真说清什么时候用的也照样过。这条挡的是漏写,不是写得不好。 +- **「说了什么时候用」只能认几个词**:`description` 里要有英文的 `when` / `whenever`、中文的 `什么时候` / `何时` / `时用` / `时使用` / `使用时`(繁体也认),或者日文的 `とき`。换个说法的(比如「审查代码时用」)、以及西班牙语这类没进词表的描述,照样会被挡;错误信息会把认的词列出来。反过来,带这些词但没真说清什么时候用的也照样过。这条挡的是漏写,不是写得不好。 - **正文行数不算前后空行**:frontmatter 后面那行空行、正文末尾的空行都不计入 500 行,数的是实际内容行。 - **只查代码里写死的那些规则**:规范的 `license`、`compatibility`、`metadata`、`allowed-tools` 和引用文件一律不管,所以通过只说明名字、描述、正文这三样没问题。 diff --git a/apps/cli/src/skill-store.ts b/apps/cli/src/skill-store.ts index c57842ee..1cf1d132 100644 --- a/apps/cli/src/skill-store.ts +++ b/apps/cli/src/skill-store.ts @@ -14,7 +14,7 @@ import { homedir, hostname } from "node:os"; import { basename, isAbsolute, join, relative, resolve, sep } from "node:path"; import type { Readable } from "node:stream"; import { parseDocument } from "yaml"; -import { ansProjectSkillsDir, ansUserSkillsDirFor } from "@anysearch-cli/store"; +import { ansProjectSkillsDir, ansUserSkillsDirFor } from "@anysearch-cli/store/paths"; import { atomicRename as renameWithRetry, renameSeam, setRenameSeam, sleepSync } from "./fs-atomic"; export interface SkillOptions { @@ -678,12 +678,13 @@ const SKILL_BODY_LINE_LIMIT = 500; const SKILL_DESCRIPTION_MIN_CHARS = 1; const SKILL_DESCRIPTION_MAX_CHARS = 1024; /** - * Words that carry the "when to use it" half of a description. The spec asks for - * it in prose, so the check has to settle for a marker: English `when`/`whenever` - * and the Chinese ways of saying it. A description that says it some other way is - * sent back with this list, which is the cheapest thing to point at. + * Markers that carry the "when to use it" half of a description. The spec asks + * for prose, so the check settles for a word: English `when`/`whenever`, the + * Chinese forms (both scripts) and the Japanese one. It still misses + * descriptions that phrase it another way — that is a known limit, not a bug, + * and the error says what to add. */ -const WHEN_TO_USE = /\bwhen|什么时候|何时|时使用|使用时/i; +const WHEN_TO_USE = /\bwhen|什么时候|何时|时使用|使用时|时用|時|とき/i; /** * Require a description that says what the skill does and when to use it (#387). @@ -703,7 +704,7 @@ function requireDescription(value: unknown, path: string): void { fail(`SKILL.md description must be ${SKILL_DESCRIPTION_MIN_CHARS}–${SKILL_DESCRIPTION_MAX_CHARS} characters, got ${length}: ${path}`); } if (!WHEN_TO_USE.test(description)) { - fail(`SKILL.md description must also say when to use the skill — use "when"/"whenever" or say 什么时候用/何时/时使用/使用时; got "${description.slice(0, 120)}": ${path}`); + fail(`SKILL.md description must also say when to use the skill — e.g. "Use when the user …", 什么时候用 / 何时 / 使用时; got "${description.slice(0, 120)}": ${path}`); } } diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs index b29ab4a0..c5a7bde7 100644 --- a/scripts/check-skills.mjs +++ b/scripts/check-skills.mjs @@ -1,11 +1,9 @@ #!/usr/bin/env node -// Repo-wide Agent Skills spec check (#387, parent #378). +// Repo-wide Agent Skills check (#387). // -// Every SKILL.md this repository ships goes through the *same* code the product -// uses: `ans skill install` and `ans skill validate` both call -// validateSkillDirectory / validateSkillFile in apps/cli/src/skill-store.ts, and -// so does this script. Nothing is re-implemented here on purpose — a rule that -// only existed in CI would drift from the one users hit. +// Every SKILL.md Git can see is handed to validateSkillDirectory from +// apps/cli/src/skill-store.ts — the same code `ans skill install` and +// `ans skill validate` run, so the three cannot drift apart. // // Usage: // node scripts/check-skills.mjs # every SKILL.md Git can see @@ -18,6 +16,7 @@ // `ANS_CHECK_SKILLS_ROOT` retargets discovery at another checkout; only the // script's tests use it. import { spawnSync } from "node:child_process"; +import { createRequire } from "node:module"; import fs from "node:fs"; import path from "node:path"; import process from "node:process"; @@ -29,8 +28,15 @@ const SCRIPT = fileURLToPath(import.meta.url); const ROOT = process.env.ANS_CHECK_SKILLS_ROOT ? path.resolve(process.env.ANS_CHECK_SKILLS_ROOT) : SCRIPT_ROOT; /** Set in the child so the re-entry below happens exactly once. */ const TSX_MARKER = "ANS_CHECK_SKILLS_TSX"; -/** The workspace tsx loader: the checker imports TypeScript sources directly, no build first. */ -const TSX_LOADER = path.join(SCRIPT_ROOT, "apps", "cli", "node_modules", "tsx", "dist", "loader.mjs"); +/** + * The workspace tsx loader: the checker imports TypeScript sources directly, no + * build first. Resolved through the package so a tsx upgrade that moves its + * files does not turn into "skill check failed". + */ +function tsxLoader() { + const fromCli = createRequire(path.join(SCRIPT_ROOT, "apps", "cli", "package.json")); + return fromCli.resolve("tsx"); +} function fail(code, detail) { process.stderr.write("check-skills: " + detail + "\n"); @@ -54,7 +60,7 @@ function skillFileOf(target) { */ function gitVisibleSkillFiles() { const listed = spawnSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { - cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, + cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 60_000, }); if (listed.error) throw new Error("cannot run git ls-files: " + listed.error.message); if (listed.status !== 0) { @@ -121,13 +127,17 @@ async function run() { } if (process.env[TSX_MARKER] !== "1") { - if (!fs.existsSync(TSX_LOADER)) { - fail(2, `tsx loader not found at ${TSX_LOADER}; run pnpm install before this check`); + let loader; + try { + loader = tsxLoader(); + } catch (error) { + fail(2, `cannot find the workspace tsx package (${error.message}); run pnpm install first`); } const entry = path.relative(process.cwd(), SCRIPT).split(path.sep).join("/"); - const child = spawnSync(process.execPath, ["--import", pathToFileURL(TSX_LOADER).href, entry, ...process.argv.slice(2)], { + const child = spawnSync(process.execPath, ["--import", pathToFileURL(loader).href, entry, ...process.argv.slice(2)], { env: { ...process.env, [TSX_MARKER]: "1" }, stdio: "inherit", + timeout: 10 * 60_000, }); if (child.error) fail(2, "cannot start the TypeScript loader: " + child.error.message); process.exit(child.status ?? 2); diff --git a/scripts/test/check-skills.test.mjs b/scripts/test/check-skills.test.mjs index 1ec628e3..98bf5e4c 100644 --- a/scripts/test/check-skills.test.mjs +++ b/scripts/test/check-skills.test.mjs @@ -1,8 +1,6 @@ -// scripts/check-skills.mjs (#387): the repo-wide Agent Skills spec check. -// -// The three cases the ticket asks to see go red — uppercase name, empty -// description, a body past 500 lines — plus the green path and the discovery -// mode that CI runs. +// scripts/check-skills.mjs (#387): what the exit codes mean (0 every skill +// passes / 1 a rule broke or nothing was found / 2 the check could not run), +// which files discovery finds, and one case per rule that has to go red. import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -19,8 +17,16 @@ const ROOT = fileURLToPath(new URL("../..", import.meta.url)); * `root` swaps in another checkout for the no-argument discovery mode. */ function check(args = [], { cwd = ROOT, root } = {}) { - const env = root ? { ...process.env, ANS_CHECK_SKILLS_ROOT: root } : process.env; + const env = { ...process.env }; + // A stray export on the developer's machine must not choose the tree, and the + // child has to do its own tsx re-entry. + delete env.ANS_CHECK_SKILLS_TSX; + if (root) env.ANS_CHECK_SKILLS_ROOT = root; + else delete env.ANS_CHECK_SKILLS_ROOT; const result = spawnSync(process.execPath, [CLI, ...args], { cwd, env, encoding: "utf8", timeout: 120_000 }); + if (result.error || result.signal) { + throw new Error(`check-skills did not finish: ${result.error ? result.error.message : result.signal}`); + } return { code: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; } @@ -138,7 +144,7 @@ test("no arguments checks what Git can see: tracked, untracked, not ignored", (t }); test("no arguments in this checkout finds the shipped skill and passes it", () => { - const result = check(); + const result = check([], { root: ROOT }); assert.equal(result.code, 0, result.stdout + result.stderr); assert.match(result.stdout, /apps\/plugin\/skills\/ans\/SKILL\.md/); assert.match(result.stdout, /([1-9]\d*) SKILL\.md checked, 0 failed/); From b7874a5e39264af371840af6f51d49c0a538b9e7 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 20:43:57 +0800 Subject: [PATCH 07/10] =?UTF-8?q?fix(skill):=20=E4=BA=8C=E8=BD=AE=20review?= =?UTF-8?q?=20fish=E2=80=94=E2=80=94=E8=BE=93=E5=87=BA=E4=B8=8D=E8=A2=AB?= =?UTF-8?q?=20exit=20=E6=88=AA=E6=96=AD=EF=BC=8C=E5=A4=B9=E5=85=B7?= =?UTF-8?q?=E4=B8=8D=E8=AE=A4=E6=9C=AC=E6=9C=BA=20GIT=5FDIR=EF=BC=8C?= =?UTF-8?q?=E8=A1=A5=E4=B8=8A=E3=80=8C=E4=BB=80=E4=B9=88=E6=97=B6=E5=80=99?= =?UTF-8?q?=E7=94=A8=E3=80=8D=E7=9A=84=E7=BA=A2=E7=BB=BF=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=20(#387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 检查脚本改用 process.exitCode,不再 process.exit:stdout 接管道时(CI 就是) 最后几行会被截掉,而那几行正是「哪个文件、哪条规则」。 - 测试的 git() 帮手先摘掉 GIT_DIR / GIT_INDEX_FILE 这些指针,夹具仓库关掉 commit 签名;不然在开发机上会去初始化/改真正的仓库。 - 测试补两条:description 不说「什么时候用」要红,繁体「使用時」要绿。 - 「这个仓库自带的 skill 能过」那条改成点名 apps/plugin/skills/ans, 不再依赖本机有没有留没被忽略的 SKILL.md。 - CI 那一步的名字改成「same rules as ans skill validate」——install 本来就不查 名字和目录名这条。 - help 和几处注释收短,并把「按关键词判断」写出来。 --- .github/workflows/ci.yml | 2 +- apps/cli/src/commands/skill.ts | 5 ++- apps/cli/src/skill-store.ts | 34 ++++++---------- scripts/check-skills.mjs | 63 +++++++++++++++++++----------- scripts/test/check-skills.test.mjs | 37 ++++++++++++++---- 5 files changed, 86 insertions(+), 55 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ca686f9..1e3afbaa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: - name: Workflow checker tests if: ${{ steps.setup.outputs.run-check-build != 'false' }} run: node --test scripts/test/check-workflows.test.mjs - - name: Skill spec check — every SKILL.md, same rules as ans skill install (#387) + - name: Skill spec check — every SKILL.md, same rules as ans skill validate (#387) if: ${{ steps.setup.outputs.run-check-build != 'false' }} run: node scripts/check-skills.mjs - name: Skill spec check tests diff --git a/apps/cli/src/commands/skill.ts b/apps/cli/src/commands/skill.ts index bdd3f519..bb8d69fc 100644 --- a/apps/cli/src/commands/skill.ts +++ b/apps/cli/src/commands/skill.ts @@ -28,8 +28,9 @@ Options: The source's current Git HEAD is recorded; checkout a commit/tag before installing. Checked rules (agentskills.io/specification plus a few house rules): frontmatter is a YAML mapping; name is 1–64 lowercase letters/digits with single hyphens and is not a Windows -device name; description is 1–1024 characters and says when to use the skill; the body -stays under 500 lines. validate also requires name to equal the installed directory name; +device name; description is 1–1024 characters and says when to use the skill — checked by +keyword (when / whenever / 什么时候 / 何时 / 使用时 / 時 / とき …); the body stays under +500 lines. validate also requires name to equal the installed directory name; install accepts any source folder name (a cloned repo usually has its own) and installs under the name the frontmatter declares. Managed skills live in ${MANAGED_SKILLS_REL_PATH}; sibling directories under skills/ are user-authored. diff --git a/apps/cli/src/skill-store.ts b/apps/cli/src/skill-store.ts index 1cf1d132..51b3b742 100644 --- a/apps/cli/src/skill-store.ts +++ b/apps/cli/src/skill-store.ts @@ -678,19 +678,13 @@ const SKILL_BODY_LINE_LIMIT = 500; const SKILL_DESCRIPTION_MIN_CHARS = 1; const SKILL_DESCRIPTION_MAX_CHARS = 1024; /** - * Markers that carry the "when to use it" half of a description. The spec asks - * for prose, so the check settles for a word: English `when`/`whenever`, the - * Chinese forms (both scripts) and the Japanese one. It still misses - * descriptions that phrase it another way — that is a known limit, not a bug, - * and the error says what to add. + * Markers for the "when to use it" half of a description. The spec asks for + * prose, so this is a keyword match and misses other phrasings; the error says + * what to add. */ const WHEN_TO_USE = /\bwhen|什么时候|何时|时使用|使用时|时用|時|とき/i; -/** - * Require a description that says what the skill does and when to use it (#387). - * The spec asks for both halves; a description with no such clause names the - * topic but never tells an agent when to reach for it. - */ +/** Require a description that says what the skill does and when to use it (#387). */ function requireDescription(value: unknown, path: string): void { if (value === undefined || value === null) { fail(`SKILL.md has no description; it must be ${SKILL_DESCRIPTION_MIN_CHARS}–${SKILL_DESCRIPTION_MAX_CHARS} characters saying what the skill does and when to use it: ${path}`); @@ -709,9 +703,8 @@ function requireDescription(value: unknown, path: string): void { } /** - * Keep the body under the spec's 500-line budget; the frontmatter does not count, - * and neither do the blank lines around the body — they are separators, not - * content, and counting them would make the house style lose two lines. + * Keep the body under the spec's 500-line budget. The frontmatter and the blank + * lines around the body are separators, not content, so they do not count. */ function requireShortBody(body: string, path: string): void { const trimmed = body.replace(/\r\n?/g, "\n").replace(/^\n+/, "").replace(/\n+$/, ""); @@ -745,9 +738,8 @@ export function validateSkillFile(path: string): string { /** * Validate one skill directory: everything `validateSkillFile` checks, plus the - * spec rule that `name` equals the directory it lives in. Install, `ans skill - * validate` and `scripts/check-skills.mjs` all come through here (#387), so the - * three cannot disagree about the same file. + * rule that `name` equals the directory. `ans skill validate` and + * `scripts/check-skills.mjs` come through here, so they agree file for file. */ export function validateSkillDirectory(directory: string): string { const file = join(directory, "SKILL.md"); @@ -991,10 +983,8 @@ export async function installSkill(sourceArgument: string, opts: SkillOptions = // Design: a source path is persisted in installed.json, whose validator // rejects control characters — reject it here so an install cannot brick the scope. if (!printablePath(source)) fail("source directory path must be absolute and free of control characters"); - // Design: install accepts any directory name (#387). The spec's "name equals - // its parent directory" rule holds for a skill *source tree* and is checked by - // scripts/check-skills.mjs; a cloned repo folder can carry another name, and - // the installed copy is always skills/synced/, where the rule holds. + // Design: install accepts any directory name (#387) — a cloned repo folder has + // its own, and the installed copy is always skills/synced/. const name = validateSkillFile(join(source, "SKILL.md")); const metadata = await provenance(source); const managed = managedSkillsRoot(opts); @@ -1123,8 +1113,8 @@ export function validateInstalledSkills(opts: SkillOptions = {}, selectedName?: } return entries.map((entry) => { try { - // The installed directory is /, so the "name equals its - // directory" rule covers the manifest cross-check too (#387). + // The installed directory is /, so this covers the + // manifest cross-check too. validateSkillDirectory(installedDirectory(managed, entry.name)); return { name: entry.name, ok: true }; } catch (error) { diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs index c5a7bde7..ab529ff0 100644 --- a/scripts/check-skills.mjs +++ b/scripts/check-skills.mjs @@ -38,9 +38,17 @@ function tsxLoader() { return fromCli.resolve("tsx"); } +/** A requested exit code; thrown so pending stdout/stderr writes can finish. */ +class Exit extends Error { + constructor(code) { + super("exit " + code); + this.code = code; + } +} + function fail(code, detail) { process.stderr.write("check-skills: " + detail + "\n"); - process.exit(code); + throw new Exit(code); } /** Map a CLI argument to the SKILL.md it names. */ @@ -93,8 +101,7 @@ async function run() { } catch (error) { fail(2, error.message); } - // Design: a green run that checked nothing is not evidence. The repository - // ships a skill; if discovery finds none, the check is broken, not the skills. + // Design: a green run that checked nothing is not evidence. if (files.length === 0) { process.stdout.write("[FAIL] no SKILL.md found — refusing to pass with nothing checked\n"); return 1; @@ -106,11 +113,9 @@ async function run() { const name = validateSkillDirectory(path.dirname(file)); process.stdout.write(`[OK] ${shown(file)} (name: ${name})\n`); } catch (error) { - // A rule failure reads "field + what was expected"; anything else (a - // permission error, an I/O failure) is reported apart and fails the run as - // "could not check", never as "this skill is broken". SkillError carries - // the exit code the CLI would use, so a usage-class error would stay apart - // too — no rule raises one today, but the split does not depend on that. + // A rule failure reads "field + what was expected". Anything else (a + // permission error, an I/O failure) is "could not check", not "this skill + // is broken"; SkillError carries the CLI's own 1-vs-2 split. if (error instanceof SkillError && error.exitCode === 1) { failed += 1; process.stdout.write(`[FAIL] ${shown(file)}: ${withoutTrailingPath(error.message, file)}\n`); @@ -127,23 +132,35 @@ async function run() { } if (process.env[TSX_MARKER] !== "1") { - let loader; try { - loader = tsxLoader(); + let loader; + try { + loader = tsxLoader(); + } catch (error) { + fail(2, `cannot find the workspace tsx package (${error.message}); run pnpm install first`); + } + const entry = path.relative(process.cwd(), SCRIPT).split(path.sep).join("/"); + const child = spawnSync(process.execPath, ["--import", pathToFileURL(loader).href, entry, ...process.argv.slice(2)], { + env: { ...process.env, [TSX_MARKER]: "1" }, + stdio: "inherit", + timeout: 10 * 60_000, + }); + if (child.error) fail(2, "cannot start the TypeScript loader: " + child.error.message); + process.exitCode = child.status ?? 2; } catch (error) { - fail(2, `cannot find the workspace tsx package (${error.message}); run pnpm install first`); + process.exitCode = error instanceof Exit ? error.code : 2; } - const entry = path.relative(process.cwd(), SCRIPT).split(path.sep).join("/"); - const child = spawnSync(process.execPath, ["--import", pathToFileURL(loader).href, entry, ...process.argv.slice(2)], { - env: { ...process.env, [TSX_MARKER]: "1" }, - stdio: "inherit", - timeout: 10 * 60_000, +} else { + // Design: the exit code is set, never process.exit()'d — a piped stdout loses + // whatever is still buffered, and those lines are the whole point of a red run. + run().then((code) => { + process.exitCode = code; + }, (error) => { + if (error instanceof Exit) { + process.exitCode = error.code; + return; + } + process.stderr.write("check-skills: internal error: " + String(error && error.stack || error) + "\n"); + process.exitCode = 2; }); - if (child.error) fail(2, "cannot start the TypeScript loader: " + child.error.message); - process.exit(child.status ?? 2); } - -run().then((code) => process.exit(code), (error) => { - process.stderr.write("check-skills: internal error: " + String(error && error.stack || error) + "\n"); - process.exit(2); -}); diff --git a/scripts/test/check-skills.test.mjs b/scripts/test/check-skills.test.mjs index 98bf5e4c..78c781f3 100644 --- a/scripts/test/check-skills.test.mjs +++ b/scripts/test/check-skills.test.mjs @@ -1,6 +1,6 @@ -// scripts/check-skills.mjs (#387): what the exit codes mean (0 every skill -// passes / 1 a rule broke or nothing was found / 2 the check could not run), -// which files discovery finds, and one case per rule that has to go red. +// scripts/check-skills.mjs: what the exit codes mean (0 every skill passes / +// 1 a rule broke or nothing was found / 2 the check could not run), which files +// discovery finds, and the cases that have to go red. import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -42,7 +42,13 @@ function canStillRead(file) { /** Run a Git command in a fixture repository and insist it worked. */ function git(cwd, args) { - const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8" }); + // The repository pointers redirect `-C`; a hook or a test run can export them. + const env = { ...process.env }; + for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES"]) { + delete env[key]; + } + const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", env }); assert.equal(result.status, 0, `git ${args.join(" ")}: ${result.stderr}`); } @@ -95,6 +101,22 @@ test("a body past 500 lines goes red and reports the count", (t) => { assert.match(result.stdout, /body must stay under 500 lines, got 501/); }); +test("a description that never says when to use the skill goes red", (t) => { + const root = withRoot(t); + const dir = skill(root, "demosc", "name: demosc\ndescription: A skill about demos."); + const result = check([dir]); + assert.equal(result.code, 1, result.stdout + result.stderr); + assert.match(result.stdout, /must also say when to use the skill/); +}); + +test("a description that says it in another language passes", (t) => { + const root = withRoot(t); + const dir = skill(root, "zhsc", "name: zhsc\ndescription: 把一周的提交整理成周报,周会前使用時最合适。"); + const result = check([dir]); + assert.equal(result.code, 0, result.stdout + result.stderr); + assert.match(result.stdout, /1 SKILL\.md checked, 0 failed/); +}); + test("a name that differs from its directory goes red", (t) => { const root = withRoot(t); const dir = skill(root, "foldername", "name: skilename\ndescription: Use when a test needs a mismatch."); @@ -127,6 +149,7 @@ test("no arguments checks what Git can see: tracked, untracked, not ignored", (t git(root, ["init", "--quiet"]); git(root, ["config", "user.name", "Check Skills Test"]); git(root, ["config", "user.email", "check-skills@example.invalid"]); + git(root, ["config", "commit.gpgsign", "false"]); skill(root, "alpha", "name: alpha\ndescription: Use when a test needs alpha."); git(root, ["add", "--", "alpha/SKILL.md", "alpha"]); git(root, ["commit", "--quiet", "-m", "alpha"]); @@ -143,11 +166,11 @@ test("no arguments checks what Git can see: tracked, untracked, not ignored", (t assert.match(result.stdout, /2 SKILL\.md checked, 0 failed/); }); -test("no arguments in this checkout finds the shipped skill and passes it", () => { - const result = check([], { root: ROOT }); +test("the skill this repository ships passes", () => { + const result = check(["apps/plugin/skills/ans"], { root: ROOT }); assert.equal(result.code, 0, result.stdout + result.stderr); assert.match(result.stdout, /apps\/plugin\/skills\/ans\/SKILL\.md/); - assert.match(result.stdout, /([1-9]\d*) SKILL\.md checked, 0 failed/); + assert.match(result.stdout, /1 SKILL\.md checked, 0 failed/); }); // A file the checker cannot read is "could not check" (exit 2), not "this skill From 145d6417dab83d2431fd1e891eaac4cf47a4a255 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 20:55:25 +0800 Subject: [PATCH 08/10] =?UTF-8?q?fix(skill):=20GIT=5FDIR=20=E8=BF=99?= =?UTF-8?q?=E7=B1=BB=E5=8F=98=E9=87=8F=E4=B8=8D=E8=AF=A5=E5=86=B3=E5=AE=9A?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E8=84=9A=E6=9C=AC=E8=AF=BB=E5=93=AA=E4=B8=AA?= =?UTF-8?q?=E4=BB=93=E5=BA=93=EF=BC=8C=E9=A1=BA=E5=B8=A6=E6=B8=85=E6=8E=89?= =?UTF-8?q?=E6=96=B0=E4=BB=A3=E7=A0=81=E9=87=8C=E7=9A=84=E7=A5=A8=E5=8F=B7?= =?UTF-8?q?=20(#387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 检查脚本跑 git ls-files 和起子进程时都过一遍 preflight-git.mjs 的 gitEnv(): pre-push 钩子在 linked worktree 里会导出 GIT_DIR,那时 cwd 不管用,列出来的是 别的仓库的文件,全被报成 SKILL.md is missing。 - 测试的 git() 帮手也换成 gitEnv(),比手抄的变量清单多认 GIT_CONFIG_*,也不怕 Windows 上的大小写差异。 - 新写的注释和 CI 步骤名里不再带票号;脚本头注释说清楚 install 走的是 validateSkillFile、validate 和这个脚本走 validateSkillDirectory。 --- .github/workflows/ci.yml | 2 +- apps/cli/src/skill-store.ts | 6 +++--- scripts/check-skills.mjs | 13 +++++++------ scripts/test/check-skills.test.mjs | 10 +++------- 4 files changed, 14 insertions(+), 17 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1e3afbaa..f7f52b9b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: - name: Workflow checker tests if: ${{ steps.setup.outputs.run-check-build != 'false' }} run: node --test scripts/test/check-workflows.test.mjs - - name: Skill spec check — every SKILL.md, same rules as ans skill validate (#387) + - name: Skill spec check — every SKILL.md, same rules as ans skill validate if: ${{ steps.setup.outputs.run-check-build != 'false' }} run: node scripts/check-skills.mjs - name: Skill spec check tests diff --git a/apps/cli/src/skill-store.ts b/apps/cli/src/skill-store.ts index 51b3b742..bf54ed5d 100644 --- a/apps/cli/src/skill-store.ts +++ b/apps/cli/src/skill-store.ts @@ -684,7 +684,7 @@ const SKILL_DESCRIPTION_MAX_CHARS = 1024; */ const WHEN_TO_USE = /\bwhen|什么时候|何时|时使用|使用时|时用|時|とき/i; -/** Require a description that says what the skill does and when to use it (#387). */ +/** Require a description that says what the skill does and when to use it. */ function requireDescription(value: unknown, path: string): void { if (value === undefined || value === null) { fail(`SKILL.md has no description; it must be ${SKILL_DESCRIPTION_MIN_CHARS}–${SKILL_DESCRIPTION_MAX_CHARS} characters saying what the skill does and when to use it: ${path}`); @@ -983,8 +983,8 @@ export async function installSkill(sourceArgument: string, opts: SkillOptions = // Design: a source path is persisted in installed.json, whose validator // rejects control characters — reject it here so an install cannot brick the scope. if (!printablePath(source)) fail("source directory path must be absolute and free of control characters"); - // Design: install accepts any directory name (#387) — a cloned repo folder has - // its own, and the installed copy is always skills/synced/. + // Design: install accepts any directory name — a cloned repo folder has its + // own, and the installed copy is always skills/synced/. const name = validateSkillFile(join(source, "SKILL.md")); const metadata = await provenance(source); const managed = managedSkillsRoot(opts); diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs index ab529ff0..feafe070 100644 --- a/scripts/check-skills.mjs +++ b/scripts/check-skills.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -// Repo-wide Agent Skills check (#387). +// Repo-wide Agent Skills check. // -// Every SKILL.md Git can see is handed to validateSkillDirectory from -// apps/cli/src/skill-store.ts — the same code `ans skill install` and -// `ans skill validate` run, so the three cannot drift apart. +// Every SKILL.md Git can see goes through the same validation the product uses: +// `ans skill validate` and this script call validateSkillDirectory, and both it +// and `ans skill install` call validateSkillFile (apps/cli/src/skill-store.ts). // // Usage: // node scripts/check-skills.mjs # every SKILL.md Git can see @@ -17,6 +17,7 @@ // script's tests use it. import { spawnSync } from "node:child_process"; import { createRequire } from "node:module"; +import { gitEnv } from "./preflight-git.mjs"; import fs from "node:fs"; import path from "node:path"; import process from "node:process"; @@ -68,7 +69,7 @@ function skillFileOf(target) { */ function gitVisibleSkillFiles() { const listed = spawnSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { - cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 60_000, + cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 60_000, env: gitEnv(), }); if (listed.error) throw new Error("cannot run git ls-files: " + listed.error.message); if (listed.status !== 0) { @@ -141,7 +142,7 @@ if (process.env[TSX_MARKER] !== "1") { } const entry = path.relative(process.cwd(), SCRIPT).split(path.sep).join("/"); const child = spawnSync(process.execPath, ["--import", pathToFileURL(loader).href, entry, ...process.argv.slice(2)], { - env: { ...process.env, [TSX_MARKER]: "1" }, + env: gitEnv({ ...process.env, [TSX_MARKER]: "1" }), stdio: "inherit", timeout: 10 * 60_000, }); diff --git a/scripts/test/check-skills.test.mjs b/scripts/test/check-skills.test.mjs index 78c781f3..f411e234 100644 --- a/scripts/test/check-skills.test.mjs +++ b/scripts/test/check-skills.test.mjs @@ -8,6 +8,7 @@ import os from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; +import { gitEnv } from "../preflight-git.mjs"; const CLI = fileURLToPath(new URL("../check-skills.mjs", import.meta.url)); const ROOT = fileURLToPath(new URL("../..", import.meta.url)); @@ -42,13 +43,8 @@ function canStillRead(file) { /** Run a Git command in a fixture repository and insist it worked. */ function git(cwd, args) { - // The repository pointers redirect `-C`; a hook or a test run can export them. - const env = { ...process.env }; - for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", - "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES"]) { - delete env[key]; - } - const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", env }); + // gitEnv drops GIT_DIR, GIT_CONFIG_* and friends, so `-C` alone picks the repo. + const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", env: gitEnv() }); assert.equal(result.status, 0, `git ${args.join(" ")}: ${result.stderr}`); } From 5c9201a06d4ecb319ddc586e33c90c1a20d6eef5 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 21:14:17 +0800 Subject: [PATCH 09/10] =?UTF-8?q?test(skill):=20=E9=92=89=E4=BD=8F?= =?UTF-8?q?=E3=80=8C=E5=AF=BC=E5=87=BA=E7=9A=84=20GIT=5FDIR=20=E4=B8=8D?= =?UTF-8?q?=E8=AF=A5=E6=8D=A2=E6=8E=89=E8=A2=AB=E6=9F=A5=E7=9A=84=E4=BB=93?= =?UTF-8?q?=E5=BA=93=E3=80=8D=EF=BC=8C=E5=A4=B9=E5=85=B7=20git=20=E5=8A=A0?= =?UTF-8?q?=E8=B6=85=E6=97=B6=20(#387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新用例:把 GIT_DIR / GIT_WORK_TREE 指向另一个仓(里面有坏的 SKILL.md), 无参检查仍只查当前仓库。去掉 env 清洗这条会红,验证过。 - 测试里的 git() 补 30 秒超时,超时/起不来时把命令一起打进断言消息。 - 脚本头两句改直白,写清 install 只走 validateSkillFile、不查目录名。 --- scripts/check-skills.mjs | 8 ++++--- scripts/test/check-skills.test.mjs | 34 ++++++++++++++++++++++++++---- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs index feafe070..3ea3a1d5 100644 --- a/scripts/check-skills.mjs +++ b/scripts/check-skills.mjs @@ -1,9 +1,11 @@ #!/usr/bin/env node // Repo-wide Agent Skills check. // -// Every SKILL.md Git can see goes through the same validation the product uses: -// `ans skill validate` and this script call validateSkillDirectory, and both it -// and `ans skill install` call validateSkillFile (apps/cli/src/skill-store.ts). +// Every SKILL.md Git can see goes through the product's own validation +// (apps/cli/src/skill-store.ts): `ans skill validate` and this script call +// validateSkillDirectory — the file rules plus "name equals its directory" — +// and `ans skill install` calls validateSkillFile, the same file rules without +// the directory check. // // Usage: // node scripts/check-skills.mjs # every SKILL.md Git can see diff --git a/scripts/test/check-skills.test.mjs b/scripts/test/check-skills.test.mjs index f411e234..f5d8b3d6 100644 --- a/scripts/test/check-skills.test.mjs +++ b/scripts/test/check-skills.test.mjs @@ -17,13 +17,15 @@ const ROOT = fileURLToPath(new URL("../..", import.meta.url)); * Run the checker the way CI does: one plain node process, no build first. * `root` swaps in another checkout for the no-argument discovery mode. */ -function check(args = [], { cwd = ROOT, root } = {}) { +function check(args = [], { cwd = ROOT, root, env: extra } = {}) { const env = { ...process.env }; // A stray export on the developer's machine must not choose the tree, and the - // child has to do its own tsx re-entry. + // child has to do its own tsx re-entry. `extra` is for tests that hand the + // checker a poisoned environment on purpose. delete env.ANS_CHECK_SKILLS_TSX; if (root) env.ANS_CHECK_SKILLS_ROOT = root; else delete env.ANS_CHECK_SKILLS_ROOT; + Object.assign(env, extra ?? {}); const result = spawnSync(process.execPath, [CLI, ...args], { cwd, env, encoding: "utf8", timeout: 120_000 }); if (result.error || result.signal) { throw new Error(`check-skills did not finish: ${result.error ? result.error.message : result.signal}`); @@ -44,8 +46,9 @@ function canStillRead(file) { /** Run a Git command in a fixture repository and insist it worked. */ function git(cwd, args) { // gitEnv drops GIT_DIR, GIT_CONFIG_* and friends, so `-C` alone picks the repo. - const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", env: gitEnv() }); - assert.equal(result.status, 0, `git ${args.join(" ")}: ${result.stderr}`); + const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", env: gitEnv(), timeout: 30_000 }); + assert.equal(result.status, 0, + `git ${args.join(" ")}: ${result.error ? result.error.message : result.stderr}`); } /** Write one skill directory under a throwaway root and return its path. */ @@ -192,6 +195,29 @@ test("an unreadable SKILL.md is reported apart and exits 2", (t) => { assert.match(result.stdout, /1 could not be read/); }); +// The push gate exports GIT_DIR in a linked worktree; a checker that honoured it +// would read another repository and report every tracked SKILL.md as missing. +test("an inherited GIT_DIR does not decide which repository is checked", (t) => { + const root = withRoot(t); + git(root, ["init", "--quiet"]); + skill(root, "alpha", "name: alpha\ndescription: Use when a test needs alpha."); + git(root, ["add", "--", "alpha", "alpha/SKILL.md"]); + // The decoy is a full repo with the bad skill staged, and the environment + // points git at it the way a push hook does: GIT_DIR plus GIT_WORK_TREE. + const decoy = withRoot(t); + git(decoy, ["init", "--quiet"]); + skill(decoy, "bad", 'name: bad\ndescription: ""'); + git(decoy, ["add", "--", "bad", "bad/SKILL.md"]); + const result = check([], { + cwd: root, + root, + env: { GIT_DIR: path.join(decoy, ".git"), GIT_WORK_TREE: decoy }, + }); + assert.equal(result.code, 0, result.stdout + result.stderr); + assert.match(result.stdout, /alpha[/\\]SKILL\.md/); + assert.doesNotMatch(result.stdout, /bad/); +}); + test("a checkout with no skill is refused instead of passing vacuously", (t) => { const root = withRoot(t); git(root, ["init", "--quiet"]); From 4889a1f0c05e21b2eb12366a5736cca8d675c2b3 Mon Sep 17 00:00:00 2001 From: Euiop1 Date: Mon, 23 Nov 2026 21:22:52 +0800 Subject: [PATCH 10/10] =?UTF-8?q?fix(skill):=20GIT=5FDIR=20=E5=8F=AA?= =?UTF-8?q?=E5=9C=A8=E4=B8=80=E5=A4=84=E6=B8=85=E6=B4=97=EF=BC=8C=E7=94=A8?= =?UTF-8?q?=E4=BE=8B=E6=89=8D=E9=92=89=E5=BE=97=E4=BD=8F=EF=BC=9Bgit=20?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=E6=96=AD=E8=A8=80=E8=A1=A5=E4=B8=8A=E8=A2=AB?= =?UTF-8?q?=E4=BF=A1=E5=8F=B7=E6=9D=80=E6=8E=89=E7=9A=84=E6=83=85=E5=86=B5?= =?UTF-8?q?=20(#387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 去掉 git ls-files 上那份重复的 env 清洗:真正跑 git 的是重进子进程,环境是 在起子进程那一刻过 gitEnv() 的。留两份时删任一份用例都不红,等于没守住;现在 只剩一处,用例去掉它会红(验过)。 - 测试里 git() 失败时的消息补上 signal,超时/被杀时不再只剩一句空的 `git xxx: `。 --- scripts/check-skills.mjs | 5 ++++- scripts/test/check-skills.test.mjs | 5 +++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs index 3ea3a1d5..836ec8c7 100644 --- a/scripts/check-skills.mjs +++ b/scripts/check-skills.mjs @@ -71,7 +71,7 @@ function skillFileOf(target) { */ function gitVisibleSkillFiles() { const listed = spawnSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { - cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 60_000, env: gitEnv(), + cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 60_000, }); if (listed.error) throw new Error("cannot run git ls-files: " + listed.error.message); if (listed.status !== 0) { @@ -143,6 +143,9 @@ if (process.env[TSX_MARKER] !== "1") { fail(2, `cannot find the workspace tsx package (${error.message}); run pnpm install first`); } const entry = path.relative(process.cwd(), SCRIPT).split(path.sep).join("/"); + // Design: this is the one place the environment crosses into the process + // that runs git — the push hook exports GIT_DIR in a linked worktree, and an + // inherited pointer would list another repository's files. const child = spawnSync(process.execPath, ["--import", pathToFileURL(loader).href, entry, ...process.argv.slice(2)], { env: gitEnv({ ...process.env, [TSX_MARKER]: "1" }), stdio: "inherit", diff --git a/scripts/test/check-skills.test.mjs b/scripts/test/check-skills.test.mjs index f5d8b3d6..02bdb7c7 100644 --- a/scripts/test/check-skills.test.mjs +++ b/scripts/test/check-skills.test.mjs @@ -47,8 +47,9 @@ function canStillRead(file) { function git(cwd, args) { // gitEnv drops GIT_DIR, GIT_CONFIG_* and friends, so `-C` alone picks the repo. const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", env: gitEnv(), timeout: 30_000 }); - assert.equal(result.status, 0, - `git ${args.join(" ")}: ${result.error ? result.error.message : result.stderr}`); + // A timed-out or signalled child has no stderr to show, so name what happened. + const why = result.error ? result.error.message : result.signal ?? result.stderr; + assert.equal(result.status, 0, `git ${args.join(" ")}: ${why}`); } /** Write one skill directory under a throwaway root and return its path. */