From debc8698e236000bc72db89ed7c5febfc9221e96 Mon Sep 17 00:00:00 2001 From: babycoder-dev Date: Wed, 7 Oct 2026 16:05:00 +0800 Subject: [PATCH 1/2] feat(agents): add the first project skills with a format gate P1.2 of docs/agent-workflow.md. Adds task-package, ui-fidelity-gate and db-migration-discipline under .agents/skills as operational manuals (they point at the authoritative rules rather than restating them), plus scripts/check-skills.mjs and the pure rules in scripts/lib/skill-rules.mjs: a skill must be //SKILL.md with matching name/description frontmatter and must not be nested, because a skill that fails those rules loads silently not at all. Consolidates the repository-level checks into pnpm check:repo so CI runs one step. Records in section 1 that gates can also fail spuriously and that the remedy is segment-wise re-runs plus CI, never re-running until green. --- .../skills/db-migration-discipline/SKILL.md | 52 +++++++++ .agents/skills/task-package/SKILL.md | 39 +++++++ .agents/skills/ui-fidelity-gate/SKILL.md | 41 +++++++ .github/workflows/ci.yml | 4 +- docs/agent-workflow.md | 42 ++++++- docs/verification-log.md | 37 +++++++ package.json | 4 +- scripts/check-skills.mjs | 104 ++++++++++++++++++ scripts/lib/skill-rules.mjs | 55 +++++++++ scripts/lib/skill-rules.spec.mjs | 58 ++++++++++ 10 files changed, 426 insertions(+), 10 deletions(-) create mode 100644 .agents/skills/db-migration-discipline/SKILL.md create mode 100644 .agents/skills/task-package/SKILL.md create mode 100644 .agents/skills/ui-fidelity-gate/SKILL.md create mode 100644 scripts/check-skills.mjs create mode 100644 scripts/lib/skill-rules.mjs create mode 100644 scripts/lib/skill-rules.spec.mjs diff --git a/.agents/skills/db-migration-discipline/SKILL.md b/.agents/skills/db-migration-discipline/SKILL.md new file mode 100644 index 0000000..61e6d52 --- /dev/null +++ b/.agents/skills/db-migration-discipline/SKILL.md @@ -0,0 +1,52 @@ +--- +name: db-migration-discipline +description: Apply the Work Platform database migration and seed discipline when changing a schema — forward-only migrations, one entrypoint per schema, and idempotent seeds. Use for any DDL, schema or seed change. +whenToUse: 改动数据库 schema、新增迁移或改 seed 时 +--- + +# 数据库迁移与 seed 纪律 + +规则出处:`docs/development-workflow.md` §2、`docs/architecture.md`、`docs/module-contract.md` §7.1、 +各模块 `CLAUDE.md`。本文件是操作手册,不新增规则。 + +## 1. 迁移只前向;已登记的迁移文件**绝不可修订** + +runner 按**文件名**登记执行状态(如 `platform.schema_migrations`)。修订一个已登记的文件,会让已迁移的库 +与新库**静默分叉**——runner 看到同名文件会直接跳过。修正一律**新增一个前向迁移**。 + +## 2. schema 归模块所有:一个 schema 一个入口 + +| schema | 入口 | +| --- | --- | +| `platform.*` | `pnpm db:migrate` | +| `presence.*` | `pnpm db:migrate:presence` | +| `files.*` | `pnpm db:migrate:files` | +| `forms.*` | `pnpm db:migrate:forms` | +| `notification.*` | `pnpm db:migrate:notification` | +| 全量(迁移 + seed) | `pnpm db:setup` | + +**不要跨 schema 写迁移**:模块只能读写自己的 schema;需要别人的数据就走 platform-api / 只读 port, +不做跨 schema join。 + +## 3. 目录与命名 + +`modules//api/src/db/migrations/NNNN_.sql`,编号在**模块内**单调递增 +(例:`modules/presence/api/src/db/migrations/0001_m9_status_dictionary.sql`)。 + +## 4. Drizzle 与实际 DDL 必须对齐 + +改 `*.schema.ts` 后用 `pnpm db:generate` 生成迁移,**生成后人工核对 SQL**——生成的 DDL 不总是你想要的 +(partial unique index、CHECK 约束、删列顺序)。手写迁移与 drizzle schema 要对齐,`*.schema.spec.ts` 已有先例。 + +## 5. seed 必须幂等 + +`pnpm db:seed` 可重复执行(企业 / 部门 / 权限 / 角色 / 管理员 / 菜单 / module manifest)。预置数据优先走 +**运行时幂等 ensure**,而不是塞进迁移 SQL;并发下用**收窄的 `ON CONFLICT` 目标**,不要依赖仲裁列。 + +## 6. 交付要求 + +- schema / 迁移策略变更属 `docs/doc-index.md` §5 的**文档审查**触发条件(可能要新增 ADR 或更新 RFC)。 +- 涉数据范围 / 权限 / 审计的 DDL 变更,合并前过 security-reviewer。 +- **`pnpm test:db` 与 `pnpm test:e2e:postgres` 是 env-gated**:缺环境变量会**静默跳过**(假绿)。本地真跑需 + `DATABASE_URL` 加 `RUN_POSTGRES_INTEGRATION=true` / `RUN_POSTGRES_E2E=true`,或直接 `pnpm verify:full`。 + 交付说明里要写清哪些命令**真跑了**、哪些被跳过。 diff --git a/.agents/skills/task-package/SKILL.md b/.agents/skills/task-package/SKILL.md new file mode 100644 index 0000000..f124e5d --- /dev/null +++ b/.agents/skills/task-package/SKILL.md @@ -0,0 +1,39 @@ +--- +name: task-package +description: Write or execute a self-contained Work Platform task package (docs/tasks/*.md) — the repo's unit of deliverable work. Use when starting a milestone slice, authoring a task package, or executing one. +whenToUse: 开始或执行一个切片任务、需要写任务包时 +--- + +# 任务包(Task Package) + +任务包是本仓的**可交付单元**:自包含、可执行、可验收。它**不定义新规则**(规则在 `docs/constitution.md` / +ADR / RFC),只讲清某个切片怎么落地。命名:`docs/tasks/m<里程碑>-<切片>-<主题>.md`。 + +## 先读 + +按 `docs/doc-index.md` 的优先级:该里程碑的 RFC → `docs/foundation-progress.md`(进度与阻塞)→ +涉认证/权限/数据范围/审计时读 `docs/security-baseline.md` → 相关专题文档 +(`docs/module-contract.md`、`docs/platform-core.md`、`docs/agent-workflow.md`)。 + +## 骨架(照此写) + +| 节 | 内容 | +| --- | --- | +| `## 状态` | 里程碑、依赖(哪个切片/PR 先合)、风险级别(是否安全敏感、是否强制独立评审)、交付形态(分支 + PR) | +| `## 0. 任务定位` | 做什么、为什么现在做;**决策**(对 RFC 的实现取态,供评审按此口径);**本切片不做**(越界即打回) | +| `## 1. 必读` | 按顺序列文件 + 具体条款;**引用条款,不要凭记忆** | +| `## 2. 设计要点` | 逐文件/逐模块的改动规格(含要删/要迁的东西) | +| `## 3. 模块结构增量` | 新增/修改/删除的文件清单,精确到路径 | +| `## 4. 验证` | 4.1 命令(必须全过);4.2 断言(必须覆盖的行为,逐条可核) | +| `## 5. 退出标准` | 什么算完成 | +| `## 6. 必须保持不变` | 明确禁止顺手改动的东西 | +| `## 7. 完成后更新文档` | 需同步的文档(通常含 `foundation-progress` 与 `verification-log`) | +| `## 8. 提交规范` | Conventional Commits 的具体建议 | + +## 执行纪律 + +- **不要静默增删文件**。任务包给了精确清单就以清单为准;要偏离先停下说明。 +- 要求精确 old/new 替换时,**匹配失败就停下回报**,不要猜着改。 +- `## 1. 必读` 要**真读**;`## 4. 验证` 要**真跑**,并按 `docs/agent-workflow.md` §2 贴出命令与结果 + (`pnpm evidence` 会校验 `verification-log` 新条目的形式)。 +- 顺手发现的问题写进任务包 §7 或 `docs/foundation-progress.md` §7 的 follow-up 表,**不要在本切片里悄悄扩大范围**。 diff --git a/.agents/skills/ui-fidelity-gate/SKILL.md b/.agents/skills/ui-fidelity-gate/SKILL.md new file mode 100644 index 0000000..eb6bf90 --- /dev/null +++ b/.agents/skills/ui-fidelity-gate/SKILL.md @@ -0,0 +1,41 @@ +--- +name: ui-fidelity-gate +description: Pass the Work Platform UI design-fidelity gate when implementing or changing user-facing screens — the machine-checked A-class rules plus the manual side-by-side B-class review. Use for any shell, login, or module UI work. +whenToUse: 实现或修改任何面向用户的界面时 +--- + +# UI 还原度门禁 + +规则出处:`docs/development-workflow.md` §7(本文件是操作手册,不新增规则)。设计真源在 +`docs/design/ui-handoff/`——**只读基准,勿改**。 + +## 先判层级 + +- **L1 严格像素级**:视觉系统(`packages/ui`)、外壳 chrome、登录页、**真实存在**的屏的版式。 +- **L2 仅视觉参考**:设计稿里本产品**尚未建**的功能内容——用设计的组件样式渲染真实数据,**不为此造后端、 + 不照搬虚构演示内容**。该屏无专稿时,按登录页 + 外壳基准锚定。 + +## A 类:机器校验(`pnpm fidelity`,已进 `pnpm verify` 与 CI) + +| 规则 | 含义 | +| --- | --- | +| A1 | UI 源码不得出现硬编码 hex;颜色只引 `var(--*)`。唯一豁免 `packages/ui/src/styles/tokens.css` | +| A2 | 不得用 emoji 当图标;图标一律用 `@work/ui` 的线性 `Icon` | +| A4 | `padding` / `margin` / `gap` / `border-radius` / `box-shadow` / `font` / `font-size` 不得写裸长度,只引 token(`--sp-*`、`--r-*`、`--shadow-*`、`--font*`);覆盖全部 CSS 长度与百分比单位,零值豁免 | + +扫描范围:`apps//src`、`modules//web/src`、`packages/ui/src`。 +**不在范围内**(改动需一并决策):A3 由 `*.spec.tsx` 断言承担;`letter-spacing` / `line-height` / +`transform` 与 TSX 内联样式不扫。 + +## B 类:人工并排比对(不可机器化,定稿前做) + +渲染设计稿原型与实现**并排**,逐区块核对结构 / 间距 / 组件态。**必须覆盖交互态**——报错、hover、 +下拉浮层展开、加载中、空态 vs 有数据;只看默认静态截图会漏掉长报错撑宽、浮层错位这类只在交互态暴露的问题。 +可用无头浏览器对每个状态各截一张并排比。 + +## 常见踩坑 + +- 关键文案要在 `*.spec.tsx` 里**逐字断言**设计稿字符串——这是 A3 的实际承担方式。 +- 不得把已交付的**真实数据接线**换成设计稿的虚构演示数据;未建功能用**诚实 EmptyState / 占位**。 +- token 唯一真源是 `packages/ui/src/styles/tokens.css`:新增视觉常量先加 token,再在样式里引用。 +- 设计的非 4px 网格值用 `calc(token …)` 组合命中,不要写裸魔法值。 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a32ebc9..e2c53d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,9 +41,7 @@ jobs: NODE_ENV: production PLATFORM_BOOTSTRAP_ADMIN_PASSWORD: ci-admin-password - run: pnpm lint - - run: pnpm fidelity - - run: pnpm evidence - - run: pnpm goal:validate + - run: pnpm check:repo - run: pnpm typecheck - run: pnpm test - run: pnpm test:db diff --git a/docs/agent-workflow.md b/docs/agent-workflow.md index 0fdf147..a210ab1 100644 --- a/docs/agent-workflow.md +++ b/docs/agent-workflow.md @@ -21,6 +21,12 @@ (`pnpm -r` / `nx run-many` / `pnpm --filter` 三条路径实测均 exit 1)。据此断言「守卫失效」是错的—— 判断执法强度只能靠**故意违规的负向验证**,不能靠日志措辞。 3. **自证是最弱的一环**。凡规则声称「可静态/机器核验」,就必须有对应的脚本与 CI 步骤。 +4. **门禁也会「假红」,处置方式是分段复跑,不是反复重跑直到绿。** + 已知偶发:`test:e2e` 紧跟在 `pnpm test` 之后运行时,可能以 vitest worker `ERR_IPC_CHANNEL_CLOSED` + 退出(`verification-log` 里历史上有 5 次记录;单独跑 `pnpm test:e2e` 稳定通过,2026-10-07 实测 4/4)。 + 遇到这类偶发红:按段单独复跑(`pnpm check:repo` / `pnpm test` / `pnpm test:e2e` / `pnpm build`), + 并把 CI(Node 22 的完整链路)当作最终确认——**而不是**"多跑几次直到绿"。后者会让"绿"失去意义, + 与假绿是同一个病的两面。 ## 2. 门禁清单(可执行物 → 谁跑) @@ -31,6 +37,11 @@ | 交付门禁 | `pnpm verify`;涉 DB 加 `verify:full`,涉部署加 `docker:build` | 每次交付 | | 证据纪律 | PR 模板(要求**贴命令与结果**,不是勾选)+ `scripts/check-evidence.mjs`(`pnpm evidence`):校验 `docs/verification-log.md` 中 **2026-10-01 起**的条目必须有 Validation/验证 小节且含「命令 + 结果」。**只校验形式,不校验真伪** | 每次交付 / CI | | 设计还原度 B 类(人工并排比对,覆盖交互态) | 不可机器化,定稿前人工做 | 评审 | +| 技能格式 | `scripts/check-skills.mjs`(`pnpm skills:validate`):`//SKILL.md` 形态、frontmatter 必填 `name`/`description`、name 与目录名一致、拒绝嵌套 | 本地 `pnpm verify` + CI | +| 长任务状态 | `scripts/goal.mjs validate`(`pnpm goal:validate`) | 本地 `pnpm verify` + CI | + +**以上仓库级检查由 `pnpm check:repo` 聚合**(`pnpm verify` 与 CI 都只跑它一步);单独调试时跑各自的 +script。新增检查加进 `check:repo` 即可,不必再加 CI 步骤。 A 类规则的**边界**(未覆盖项,改动时需一并决策):A3(关键文案逐字一致)由 `*.spec.tsx` 断言承担; A4 只覆盖 `padding|margin|gap|border-radius|box-shadow|font|font-size`(**单位覆盖全部 CSS 长度与百分比, @@ -80,8 +91,10 @@ hook 逻辑一律放 `scripts/hooks/*.mjs`(纯 Node;异常一律放行、绝 ### 未验证 / 待办(诚实登记) -- **挂载是否真被宿主调用**:本会话无法验证(属宿主行为)。验证方式:在对应工具里各触发一次 +- **hook 挂载是否真被宿主调用**:仍未验证(属宿主行为)。验证方式:在对应工具里各触发一次 (改一个越界 import、开新会话看是否注入进度快照),结论记入 `docs/verification-log.md`。 + - 对照:**技能侧已实测通过** —— 2026-10-07 新增三个技能后,当前会话的可用技能目录当场更新 + (见 §5)。也就是说 `.agents/skills` 的扫描确认生效,而 `.claude/settings.json` 的 hooks 仍待实测。 - **Codex 侧 `hooks.json` 结构与输出 schema**:需从 Codex 官方文档或 `@deepseek-ai/dsh-hook-protocol` 的解码实现核实后再写。已确认的结论是**编辑期两个 hook 在 Codex 下不可行**。 - **`continue: false` 在桥接下无运行级效果**(已知限制),故本仓 hook 不使用它。 @@ -107,10 +120,25 @@ hook 逻辑一律放 `scripts/hooks/*.mjs`(纯 Node;异常一律放行、绝 ## 5. 技能(Skills) -- 布局 `.agents/skills//SKILL.md`;frontmatter 必填 `name` + `description`,可选 `whenToUse`; - 正文按需加载,目录只索引 frontmatter。 -- 只放**可复用的操作手册**,不放规则(规则在 constitution / ADR / RFC)。首批(P1):任务包模板、 - 还原度门禁流程、数据库迁移纪律。 +- 布局 `.agents/skills//SKILL.md`(也可放 `.dsh/skills`、`.claude/skills`);frontmatter 必填 + `name` + `description`,可选 `whenToUse`;正文按需加载,目录只索引 frontmatter。 +- 只放**可复用的操作手册**,不放规则(规则在 constitution / ADR / RFC)。 +- **格式有门禁**:`scripts/check-skills.mjs`(`pnpm skills:validate`,已进 `pnpm check:repo`)。 + 因为技能加载失败是**静默的**——缺 `name`/`description` 或目录名与 `name` 不一致时,技能只是"不出现", + 没有任何报错;嵌套的 `**/SKILL.md` 不被支持,也会被这条门禁拦下。 + +### 现有技能 + +| 技能 | 用途 | +| --- | --- | +| `task-package` | 写/执行任务包(骨架、执行纪律、交付要求) | +| `ui-fidelity-gate` | UI 还原度门禁:A 类机器校验 + B 类人工并排比对(含交互态) | +| `db-migration-discipline` | 迁移只前向、一 schema 一入口、seed 幂等、env-gated 测试的假绿陷阱 | +| `code-simplifier` | 简化近期改动(自 Anthropic Apache-2.0 适配) | + +**加载已验证**(2026-10-07,本仓实测):新增三个技能后,当前会话的可用技能目录**当场更新**,新技能 +立即可被调用——即 `@deepseek-ai/dsh-skill-filesystem` 会从项目根(最近的含 `.git` 祖先)下的 +`.agents/skills` 扫描并索引。 ## 6. 多代理编排(Workflow) @@ -132,7 +160,9 @@ hook 逻辑一律放 `scripts/hooks/*.mjs`(纯 Node;异常一律放行、绝 `scripts/hooks/`、去掉 shell 依赖、能力矩阵见 §3;按证据收缩:DSH 侧无需仓内配置、Codex 侧编辑期 hook 协议上不可行)→ 证据门禁(`pnpm evidence` + PR 模板改为贴命令与结果)。 - **P1 · 长任务与协作**:goal 纪律 + 废弃 `ai-handoff.md`(✅ 已落地:`docs/goal/` + `scripts/goal.mjs` - + 20 条规则单测 + 会话注入)→ 首批 skills → 一个真实 workflow 用例。 + + 25 条规则单测 + 会话注入)→ 首批 skills(✅ 已落地:`task-package` / `ui-fidelity-gate` / + `db-migration-discipline` 三个技能 + `pnpm skills:validate` 格式门禁;加载已实测)→ 一个真实 + workflow 用例。 - **P2 · 文档治理**:`docs/` 顶层 7 篇不在 `doc-index` 管辖内的文档逐一定性(纳入 / 归档 / 删除); `iteration-roadmap.md`(自标已过时)归档。 diff --git a/docs/verification-log.md b/docs/verification-log.md index bff144f..b6d72fa 100644 --- a/docs/verification-log.md +++ b/docs/verification-log.md @@ -2,6 +2,43 @@ ## 2026-10-07 +### P1.2 Skill Library and Skill Format Gate + +**Change set** + +- Added three project skills under `.agents/skills/`: `task-package` (how a task package is written and + executed), `ui-fidelity-gate` (the A-class machine checks plus the B-class manual comparison), and + `db-migration-discipline` (forward-only migrations, one entrypoint per schema, idempotent seeds, and the + env-gated test trap). +- Added `scripts/lib/skill-rules.mjs` and `scripts/check-skills.mjs` (`pnpm skills:validate`): a skill must be + `//SKILL.md`, declare `name` and `description` in frontmatter, have its `name` match the + directory, and must not be nested — because a skill failing these rules loads **silently not at all**. +- Consolidated the repository-level checks into `pnpm check:repo` (fidelity, evidence, goal:validate, + skills:validate) so CI runs one step rather than one step per check. + +**Validation** + +- `node scripts/check-skills.mjs --verbose`: pass — 4 skills found under `.agents/skills`. +- `pnpm vitest run --config vitest.config.mts scripts/lib/skill-rules.spec.mjs`: pass (9 tests). +- `pnpm check:repo`: pass — fidelity 215 files, evidence, goal:validate, skills:validate. +- `pnpm build`: pass. Constituent gates therefore verified segment by segment, because the monolithic + `pnpm verify` tripped the **known** vitest flake: its `test:e2e` stage exited with worker + `ERR_IPC_CHANNEL_CLOSED` when run right after `pnpm test` (this flake has five earlier records in this + log, e.g. the M9-1 and M6-3 entries). `pnpm test` passed on its own (55 files / 355 tests plus 39 web + files / 136 tests), `pnpm test:e2e` passed alone 4 runs out of 4 (11 files / 63 tests), and `pnpm build` + passed alone. Per that precedent, CI's Node 22 monolithic run is the final confirmation; re-running until + green is explicitly not the remedy (see `docs/agent-workflow.md` §1.4). +- **Skill loading verified in practice**: inside the running session, writing the three `SKILL.md` files made + the available-skill catalog update immediately and list them, confirming the `.agents/skills` scan works. + That settles half of the standing "is the mount actually invoked" question; the hook mount is still open. + +**Carried forward** + +- Hook mounting remains unverified (`docs/agent-workflow.md` §3). +- P1.3 (one real workflow use case) and P2 (documentation governance) remain open. + +## 2026-10-07 + ### P1.1 Goal Discipline and ai-handoff Retirement **Change set** diff --git a/package.json b/package.json index 3798ec1..adab6d9 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,9 @@ "fidelity": "node scripts/check-ui-fidelity.mjs", "evidence": "node scripts/check-evidence.mjs", "goal:validate": "node scripts/goal.mjs validate", - "verify": "pnpm lint && pnpm fidelity && pnpm evidence && pnpm goal:validate && pnpm typecheck && pnpm test && pnpm test:e2e && pnpm build", + "skills:validate": "node scripts/check-skills.mjs", + "check:repo": "pnpm fidelity && pnpm evidence && pnpm goal:validate && pnpm skills:validate", + "verify": "pnpm lint && pnpm check:repo && pnpm typecheck && pnpm test && pnpm test:e2e && pnpm build", "verify:full": "pnpm verify && pnpm test:db && pnpm test:e2e:postgres", "build": "pnpm -r --if-present build", "docker:build": "docker compose -f infra/docker-compose.prod.yml build", diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs new file mode 100644 index 0000000..b9c11ef --- /dev/null +++ b/scripts/check-skills.mjs @@ -0,0 +1,104 @@ +#!/usr/bin/env node +// 技能(Skill)格式门禁 — CLI +// +// 校验本仓的技能目录:`//SKILL.md` 形态、frontmatter 必填项、name 与目录名一致、 +// 正文非空,并拒绝**不受支持的嵌套** `**/SKILL.md`(DSH 刻意不支持嵌套——嵌套技能不会加载)。 +// +// 为什么值得一道门禁:技能加载失败是静默的。缺 name/description 时技能只是"不出现", +// 没有任何报错;等到发现"这个技能怎么没生效"时已经浪费了一轮。 +// +// 用法:node scripts/check-skills.mjs [--verbose] +// 退出码:0 = 通过;1 = 有不合格技能。 + +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { validateSkill } from './lib/skill-rules.mjs'; + +const REPO = path.resolve(import.meta.dirname, '..'); +const VERBOSE = process.argv.includes('--verbose'); + +/** 本仓可能承载技能的根(按 DSH 的扫描约定;只需存在其一)。 */ +const ROOTS = ['.agents/skills', '.dsh/skills', '.claude/skills']; + +const SKIP_DIRS = new Set(['node_modules', 'references', 'scripts', 'assets']); + +function isDir(p) { + try { + return statSync(p).isDirectory(); + } catch { + return false; + } +} + +/** 收集某根下所有 SKILL.md 的相对段路径,[['name','SKILL.md'], ...]。 */ +function collectSkillFiles(rootAbs, segments = []) { + const found = []; + let entries; + try { + entries = readdirSync(rootAbs, { withFileTypes: true }); + } catch { + return found; + } + for (const entry of entries) { + if (entry.isDirectory()) { + if (SKIP_DIRS.has(entry.name)) continue; + found.push(...collectSkillFiles(path.join(rootAbs, entry.name), [...segments, entry.name])); + } else if (entry.isFile() && entry.name === 'SKILL.md') { + found.push([...segments, entry.name]); + } + } + return found; +} + +const violations = []; +let checked = 0; +const rootsFound = []; + +for (const relRoot of ROOTS) { + const rootAbs = path.join(REPO, relRoot); + if (!isDir(rootAbs)) continue; + rootsFound.push(relRoot); + + // 直接子目录必须有 SKILL.md,否则该技能不会加载。 + for (const entry of readdirSync(rootAbs, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const skillFile = path.join(rootAbs, entry.name, 'SKILL.md'); + if (!existsSync(skillFile)) { + violations.push({ + at: `${relRoot}/${entry.name}`, + reason: '该目录下没有 SKILL.md——技能不会被加载(目录 bundle 必须含 SKILL.md)', + }); + } + } + + for (const segments of collectSkillFiles(rootAbs)) { + const rel = `${relRoot}/${segments.join('/')}`; + if (segments.length !== 2) { + violations.push({ + at: rel, + reason: `不支持嵌套:技能必须是 ${relRoot}//SKILL.md,嵌套的 SKILL.md 不会被加载`, + }); + continue; + } + checked++; + const problems = validateSkill(segments[0], readFileSync(path.join(rootAbs, ...segments), 'utf8')); + for (const problem of problems) violations.push({ at: rel, reason: problem }); + } +} + +if (VERBOSE || violations.length > 0) { + console.log( + `技能根:${rootsFound.length > 0 ? rootsFound.join('、') : '(无)'};校验 ${checked} 个 SKILL.md`, + ); +} + +if (violations.length === 0) { + console.log(`技能格式门禁:通过(${checked} 个技能)`); + process.exit(0); +} + +for (const v of violations) { + console.log(`${v.at} [S1] ${v.reason}`); +} +console.log(`技能格式门禁:失败,${violations.length} 处不合格。约定见 docs/agent-workflow.md §5。`); +process.exit(1); diff --git a/scripts/lib/skill-rules.mjs b/scripts/lib/skill-rules.mjs new file mode 100644 index 0000000..debb580 --- /dev/null +++ b/scripts/lib/skill-rules.mjs @@ -0,0 +1,55 @@ +// 技能(Skill)格式校验 · 规则(纯函数,无 I/O) +// +// 为什么需要:技能加载失败是**静默**的——目录条目只解析 frontmatter,缺 name/description 或 +// 目录名与 name 不一致时,技能只是"不出现",没有任何报错。这类"配置存在但不生效"正是 +// docs/agent-workflow.md §1 要消灭的东西,所以给技能加一道会红的检查。 +// +// 格式依据(DeepSeek Harness 的技能加载约定,2026-10-07 盘点): +// - 形态为 `//SKILL.md`(不是 `/.md`,也**不支持**嵌套 `**/SKILL.md`); +// - frontmatter 必填 `name` 与 `description`,可选 `whenToUse` 等; +// - 正文按需加载。 + +/** 解析形如 `---\nkey: value\n---\n正文` 的 frontmatter(只支持本仓用到的扁平单行键值)。 */ +export function parseFrontmatter(text) { + const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text); + if (!match) return { error: '缺少 frontmatter(文件必须以 --- 开头,以 --- 结束)' }; + const data = {}; + for (const rawLine of match[1].split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || line.startsWith('#')) continue; + const sep = line.indexOf(':'); + if (sep === -1) return { error: `frontmatter 行无法解析:${line}` }; + const key = line.slice(0, sep).trim(); + let value = line.slice(sep + 1).trim(); + if ( + (value.startsWith('"') && value.endsWith('"')) || + (value.startsWith("'") && value.endsWith("'")) + ) { + value = value.slice(1, -1); + } + data[key] = value; + } + return { data, body: match[2] }; +} + +/** 校验单个技能;返回问题数组(空数组=合法)。 */ +export function validateSkill(dirName, text) { + const problems = []; + const parsed = parseFrontmatter(text); + if (parsed.error) return [parsed.error]; + + const { data, body } = parsed; + if (!data.name) problems.push('frontmatter 缺少 name'); + if (!data.description) problems.push('frontmatter 缺少 description'); + if (data.name && data.name !== dirName) { + problems.push(`frontmatter 的 name(${data.name})与目录名(${dirName})不一致`); + } + if (data.description && data.description.trim().length < 20) { + problems.push('description 太短:它是模型判断"何时用这个技能"的唯一依据'); + } + if (data.whenToUse !== undefined && !data.whenToUse) { + problems.push('whenToUse 存在但为空'); + } + if (!body || body.trim().length === 0) problems.push('frontmatter 之后没有正文'); + return problems; +} diff --git a/scripts/lib/skill-rules.spec.mjs b/scripts/lib/skill-rules.spec.mjs new file mode 100644 index 0000000..aef0d37 --- /dev/null +++ b/scripts/lib/skill-rules.spec.mjs @@ -0,0 +1,58 @@ +// 技能格式规则的回归测试。 +// +// 重点:技能加载失败是静默的,所以"看起来对"的写法必须真被判过——尤其 name 与目录名不一致、 +// description 过短、以及不受支持的嵌套这几种"不会报错但也不生效"的情况。 + +import { describe, expect, it } from 'vitest'; +import { parseFrontmatter, validateSkill } from './skill-rules.mjs'; + +const skill = (frontmatter, body = '\n# 标题\n\n正文\n') => `---\n${frontmatter}\n---\n${body}`; + +const VALID = 'name: demo\n' + 'description: A sufficiently long description for the demo skill.'; + +describe('parseFrontmatter', () => { + it('解析键值并保留正文', () => { + const { data, body } = parseFrontmatter(skill(VALID, '\n# 正文标题\n内容\n')); + expect(data.name).toBe('demo'); + expect(data.description).toContain('sufficiently long'); + expect(body).toContain('# 正文标题'); + }); + + it('去掉值两侧的引号', () => { + const { data } = parseFrontmatter(skill('name: demo\ndescription: "带引号的描述,长度足够用于校验。"')); + expect(data.description).toBe('带引号的描述,长度足够用于校验。'); + }); + + it('缺少 frontmatter 时报错', () => { + expect(parseFrontmatter('# 没有 frontmatter\n').error).toContain('frontmatter'); + }); +}); + +describe('validateSkill', () => { + it('合法技能没有问题', () => { + expect(validateSkill('demo', skill(VALID))).toEqual([]); + }); + + it('缺 name / description 各报一条', () => { + expect(validateSkill('demo', skill('description: 足够长的描述文本用于通过校验。')).join()).toContain( + 'name', + ); + expect(validateSkill('demo', skill('name: demo')).join()).toContain('description'); + }); + + it('name 与目录名不一致会被抓(否则技能静默不加载)', () => { + expect(validateSkill('other-dir', skill(VALID)).join()).toContain('目录名'); + }); + + it('description 过短会被抓(它是模型判断何时用它的唯一依据)', () => { + expect(validateSkill('demo', skill('name: demo\ndescription: 太短')).join()).toContain('太短'); + }); + + it('whenToUse 为空会被抓', () => { + expect(validateSkill('demo', skill(`${VALID}\nwhenToUse:`)).join()).toContain('whenToUse'); + }); + + it('正文为空会被抓', () => { + expect(validateSkill('demo', skill(VALID, '\n\n')).join()).toContain('正文'); + }); +}); From 6465e6c3e3fce25f3e05768d76748eff64bc89e9 Mon Sep 17 00:00:00 2001 From: babycoder-dev Date: Wed, 7 Oct 2026 16:12:18 +0800 Subject: [PATCH 2/2] fix(agents): traverse skill bundles so nested SKILL.md files cannot evade the gate Codex (PR #46, P2): the traversal skipped references/scripts/assets, so a nested SKILL.md inside a bundle was never seen and pnpm skills:validate passed even though nested skills are not loaded - the gate advertised an enforcement it did not perform. Only node_modules and .git are skipped now, the roots are overridable via WORK_SKILL_ROOTS, and scripts/check-skills.spec.mjs exercises the traversal end to end (including the exact nested case). --- scripts/check-skills.mjs | 18 +++++++-- scripts/check-skills.spec.mjs | 75 +++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 4 deletions(-) create mode 100644 scripts/check-skills.spec.mjs diff --git a/scripts/check-skills.mjs b/scripts/check-skills.mjs index b9c11ef..55c2cbe 100644 --- a/scripts/check-skills.mjs +++ b/scripts/check-skills.mjs @@ -17,10 +17,20 @@ import { validateSkill } from './lib/skill-rules.mjs'; const REPO = path.resolve(import.meta.dirname, '..'); const VERBOSE = process.argv.includes('--verbose'); -/** 本仓可能承载技能的根(按 DSH 的扫描约定;只需存在其一)。 */ -const ROOTS = ['.agents/skills', '.dsh/skills', '.claude/skills']; +/** + * 本仓可能承载技能的根(按 DSH 的扫描约定;只需存在其一)。 + * 可用 WORK_SKILL_ROOTS(逗号分隔,允许绝对路径)覆盖,便于测试遍历逻辑。 + */ +const ROOTS = ( + process.env.WORK_SKILL_ROOTS ?? '.agents/skills,.dsh/skills,.claude/skills' +) + .split(',') + .map((s) => s.trim()) + .filter(Boolean); -const SKIP_DIRS = new Set(['node_modules', 'references', 'scripts', 'assets']); +// 只跳过真正的噪声目录。**不要**跳过 references/scripts/assets —— 嵌套的 SKILL.md 正是在这些目录里 +// 会被漏掉(Codex P2),而门禁的职责恰恰是拦下不受支持的嵌套。 +const SKIP_DIRS = new Set(['node_modules', '.git']); function isDir(p) { try { @@ -55,7 +65,7 @@ let checked = 0; const rootsFound = []; for (const relRoot of ROOTS) { - const rootAbs = path.join(REPO, relRoot); + const rootAbs = path.isAbsolute(relRoot) ? relRoot : path.join(REPO, relRoot); if (!isDir(rootAbs)) continue; rootsFound.push(relRoot); diff --git a/scripts/check-skills.spec.mjs b/scripts/check-skills.spec.mjs new file mode 100644 index 0000000..a64f90d --- /dev/null +++ b/scripts/check-skills.spec.mjs @@ -0,0 +1,75 @@ +// 技能格式门禁的端到端测试(真实进程 + 临时技能根)。 +// +// 为什么单独测 CLI:遍历逻辑是这道门禁最容易出错的地方,而它不在纯规则里。Codex 在 PR #46 上指出 +// 我把 references/scripts/assets 加进跳过列表后,`foo/references/SKILL.md` 这种嵌套技能**不会被发现**—— +// 门禁宣称拦嵌套却漏检。本文件把这类遍历用例固化,避免再次退化。 + +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; + +const SCRIPT = path.join(import.meta.dirname, 'check-skills.mjs'); + +const VALID_SKILL = `--- +name: demo +description: A sufficiently long description so the validator accepts this demo skill. +--- + +# Demo + +正文。 +`; + +/** 在临时技能根里造目录/文件,返回根路径。 */ +function makeRoot(entries) { + const root = mkdtempSync(path.join(os.tmpdir(), 'work-skills-')); + for (const [rel, content] of Object.entries(entries)) { + const abs = path.join(root, rel); + mkdirSync(path.dirname(abs), { recursive: true }); + writeFileSync(abs, content, 'utf8'); + } + return root; +} + +function runGate(root) { + const result = spawnSync(process.execPath, [SCRIPT], { + encoding: 'utf8', + env: { ...process.env, WORK_SKILL_ROOTS: root }, + }); + return { status: result.status, stdout: result.stdout ?? '' }; +} + +describe('技能格式门禁(CLI)', () => { + it('合法技能 → 通过', () => { + const root = makeRoot({ 'demo/SKILL.md': VALID_SKILL }); + const { status, stdout } = runGate(root); + expect(status).toBe(0); + expect(stdout).toContain('通过'); + }); + + it('嵌套 SKILL.md(含 references/ 之下)→ 必须被抓,不能被跳过列表放过', () => { + const root = makeRoot({ + 'demo/SKILL.md': VALID_SKILL, + 'demo/references/SKILL.md': VALID_SKILL, + }); + const { status, stdout } = runGate(root); + expect(status).toBe(1); + expect(stdout).toContain('不支持嵌套'); + }); + + it('技能目录缺少 SKILL.md → 报错(该目录不会被加载)', () => { + const root = makeRoot({ 'demo/notes.md': 'no skill file here\n' }); + const { status, stdout } = runGate(root); + expect(status).toBe(1); + expect(stdout).toContain('没有 SKILL.md'); + }); + + it('frontmatter 的 name 与目录名不一致 → 报错(否则技能静默不加载)', () => { + const root = makeRoot({ 'other/SKILL.md': VALID_SKILL }); + const { status, stdout } = runGate(root); + expect(status).toBe(1); + expect(stdout).toContain('目录名'); + }); +});