diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json index e27d8231c9..5a68f01457 100644 --- a/.agents/plugins/marketplace.json +++ b/.agents/plugins/marketplace.json @@ -6,7 +6,7 @@ "plugins": [ { "name": "agent-skills", - "version": "0.6.7", + "version": "0.6.9", "description": "Production-grade engineering skills covering every phase of software development: spec, plan, build, verify, review, and ship.", "source": { "source": "local", diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index cb7b26ace9..a654cf2eda 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "plugins": [ { "name": "highway-skills", - "version": "0.6.7", + "version": "0.6.9", "source": { "source": "github", "repo": "Project-Highway/agent-skills" diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 3e0eaa14df..7bf2b98015 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "highway-skills", - "version": "0.6.7", + "version": "0.6.9", "description": "Production-grade engineering skills for AI coding agents — covering the full software development lifecycle from spec to ship.", "author": { "name": "Addy Osmani" diff --git a/.claude/commands/constraints.md b/.claude/commands/constraints.md new file mode 100644 index 0000000000..4f5bb054e1 --- /dev/null +++ b/.claude/commands/constraints.md @@ -0,0 +1,32 @@ +--- +description: Define and enforce this project's quality bar — interview, sane defaults, CONSTRAINTS.md +--- + +Invoke the agent-skills:constraint-driven-development skill. + +$ARGUMENTS + +Default behaviour with no arguments: set up constraints for this repository. + +1. **Detect first.** Read package.json / pyproject.toml / go.mod, the test runner, existing lint configs, current coverage output, CI workflows, and the agent harness in use. Report what you found in two lines. Never ask for anything you can read. + +2. **Interview, at most four questions.** One at a time, each with your best guess and a usable default so "I don't know" still produces a working config: + - Which dimensions beyond the floor (coverage, security, performance, accessibility, architecture) + - Block or warn when a check fails mid-task + - Target numbers, or measure today's values and hold them + - Slowest check tolerated before handing work back + +3. **Write CONSTRAINTS.md** at the repo root with a Floor section, enforced numbers, measured-only metrics with today's values, and an exceptions table with owners and expiry dates. Every number needs a stated reason. + +4. **Install what each picked dimension needs.** A dimension with a number and no tool behind it is an aspiration. Use the de facto tool so existing config keeps working: Semgrep for code scanning, gitleaks (always `--redact`) for secrets, osv-scanner for dependencies, axe-core for accessibility, Lighthouse for web vitals, size-limit for bundles, dependency-cruiser for boundaries, Stryker for assertion quality. Record the exact command next to each rule in CONSTRAINTS.md. Accessibility and performance need a running URL; if the project has none, say so and drop the dimension rather than inventing a check. Add the commands to package.json as check:fast / check:task / check:full. + +5. **Place each check by cost.** Types, lint and secrets in the edit loop (seconds). Related tests and changed-line coverage at task end (under 90s). Everything else at review or in CI. Scope checks to the diff, not the whole repo. + +6. **Point the agent at it.** Add a line to CLAUDE.md telling agents to read CONSTRAINTS.md and never weaken it to make a change pass. + +7. **Verify.** Run the constraints against the current branch. If anything fails that the user disagrees with, fix the constraint now rather than leaving a gate people will learn to ignore. + +Sub-commands: +- `/constraints check` — run the current constraints against this branch and report +- `/constraints guard` — inspect the diff for a weakened bar: lowered thresholds, skipped or deleted tests, new suppression comments, unfinished stubs, new exceptions +- `/constraints ratchet` — record today's measured values as the floor that must not fall diff --git a/.claude/commands/plan.md b/.claude/commands/plan.md index bb6d9fddb5..9596af5401 100644 --- a/.claude/commands/plan.md +++ b/.claude/commands/plan.md @@ -14,3 +14,5 @@ Read the existing spec (SPEC.md or equivalent) and the relevant codebase section 6. Present the plan for human review Save the plan to tasks/plan.md and task list to tasks/todo.md. + +If tasks/plan.md or tasks/todo.md already exists with unchecked tasks for different work, stop and ask before writing — never silently overwrite an incomplete plan. diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 2b699a252f..9e2ce5299e 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-skills", - "version": "0.6.7", + "version": "0.6.9", "description": "Production-grade engineering skills for AI coding agents covering the full software development lifecycle from spec to ship.", "author": { "name": "Addy Osmani", diff --git a/.gemini/commands/constraints.toml b/.gemini/commands/constraints.toml new file mode 100644 index 0000000000..c6bbb8570d --- /dev/null +++ b/.gemini/commands/constraints.toml @@ -0,0 +1,32 @@ +description = "Define and enforce this project's quality bar — interview, sane defaults, CONSTRAINTS.md" + +prompt = """ +Invoke the constraint-driven-development skill. + +$ARGUMENTS + +Default behaviour with no arguments: set up constraints for this repository. + +1. **Detect first.** Read package.json / pyproject.toml / go.mod, the test runner, existing lint configs, current coverage output, CI workflows, and the agent harness in use. Report what you found in two lines. Never ask for anything you can read. + +2. **Interview, at most four questions.** One at a time, each with your best guess and a usable default so "I don't know" still produces a working config: + - Which dimensions beyond the floor (coverage, security, performance, accessibility, architecture) + - Block or warn when a check fails mid-task + - Target numbers, or measure today's values and hold them + - Slowest check tolerated before handing work back + +3. **Write CONSTRAINTS.md** at the repo root with a Floor section, enforced numbers, measured-only metrics with today's values, and an exceptions table with owners and expiry dates. Every number needs a stated reason. + +4. **Install what each picked dimension needs.** A dimension with a number and no tool behind it is an aspiration. Use the de facto tool so existing config keeps working: Semgrep for code scanning, gitleaks (always `--redact`) for secrets, osv-scanner for dependencies, axe-core for accessibility, Lighthouse for web vitals, size-limit for bundles, dependency-cruiser for boundaries, Stryker for assertion quality. Record the exact command next to each rule in CONSTRAINTS.md. Accessibility and performance need a running URL; if the project has none, say so and drop the dimension rather than inventing a check. Add the commands to package.json as check:fast / check:task / check:full. + +5. **Place each check by cost.** Types, lint and secrets in the edit loop (seconds). Related tests and changed-line coverage at task end (under 90s). Everything else at review or in CI. Scope checks to the diff, not the whole repo. + +6. **Point the agent at it.** Add a line to AGENTS.md and GEMINI.md telling agents to read CONSTRAINTS.md and never weaken it to make a change pass. + +7. **Verify.** Run the constraints against the current branch. If anything fails that the user disagrees with, fix the constraint now rather than leaving a gate people will learn to ignore. + +Sub-commands: +- `/constraints check` — run the current constraints against this branch and report +- `/constraints guard` — inspect the diff for a weakened bar: lowered thresholds, skipped or deleted tests, new suppression comments, unfinished stubs, new exceptions +- `/constraints ratchet` — record today's measured values as the floor that must not fall +""" diff --git a/.gemini/commands/planning.toml b/.gemini/commands/planning.toml index 3b8daa23aa..53a8807553 100644 --- a/.gemini/commands/planning.toml +++ b/.gemini/commands/planning.toml @@ -13,4 +13,6 @@ Read the existing spec (SPEC.md or equivalent) and the relevant codebase section 6. Present the plan for human review Save the plan to tasks/plan.md and task list to tasks/todo.md. -""" \ No newline at end of file + +If tasks/plan.md or tasks/todo.md already exists with unchecked tasks for different work, stop and ask before writing — never silently overwrite an incomplete plan. +""" diff --git a/.github/workflows/test-plugin-install.yml b/.github/workflows/test-plugin-install.yml index 77eaff2daf..b6893fab3d 100644 --- a/.github/workflows/test-plugin-install.yml +++ b/.github/workflows/test-plugin-install.yml @@ -32,7 +32,7 @@ jobs: run: node --test scripts/run-evals-test.js - name: Run skill evals (trigger + routing) - run: node scripts/run-evals.js --min-rank1 80 + run: node scripts/run-evals.js --min-rank1 95 - name: Validate references/ links in skills run: node scripts/validate-reference-links.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9b03315510..f08c85ee19 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,8 +12,9 @@ This pack already covers most of the development lifecycle, and many proposals o 1. **Search the catalog.** Browse [the skill list in the README](README.md) and skim `skills/` for an existing skill that covers your idea, whole or in part. 2. **Check open PRs.** Run `gh pr list --state open` (or browse the PRs tab) and look for proposals on the same topic. Clusters of near-duplicate skills already exist; don't add to them. -3. **Read the anatomy.** Confirm your idea fits the format in [docs/skill-anatomy.md](docs/skill-anatomy.md), an actionable workflow with verification, not vague advice. -4. **Justify the gap in your PR description.** State explicitly why this isn't covered by an existing skill or open PR. If it overlaps, propose extending the existing skill instead of adding a new one. +3. **Check rejected proposals.** Search the [skill-change rejection ledger](evals/skill-impact.md) for earlier proposals that overlap with your idea and review their eval evidence before repeating the work. +4. **Read the anatomy.** Confirm your idea fits the format in [docs/skill-anatomy.md](docs/skill-anatomy.md), an actionable workflow with verification, not vague advice. +5. **Justify the gap in your PR description.** State explicitly why this isn't covered by an existing skill, open PR, or previously rejected proposal. If it overlaps, propose extending the existing skill instead of adding a new one. If your idea is a refinement of an existing skill, prefer a focused edit to that skill over a new directory. @@ -62,10 +63,14 @@ The frontmatter fields above are required. The section anatomy is a recommended ## Modifying Existing Skills +Before proposing a change, search the [skill-change rejection ledger](evals/skill-impact.md) for previous attempts affecting the same skill and review their eval evidence. + - Keep changes focused and minimal - Preserve the existing structure and tone - Test that YAML frontmatter remains valid after edits +If a skill or description change is rejected based on eval results, add one row to the ledger with the date, affected skill, concise attempted change, before-to-after rank-1 score, and rejected PR link and outcome. Land that ledger-only update separately on the default branch; do not leave it only on the rejected proposal branch, where closing or force-pushing the proposal could discard the record. + ## Repo-scoped files `AGENTS.md` and `CLAUDE.md` at the repo root configure agents working on the [`addyosmani/agent-skills`](https://github.com/addyosmani/agent-skills) repository itself. When writing setup guides or docs, do not instruct users to copy these files into their own projects or into a global agent configuration; the reusable assets are the skills in `skills/`. diff --git a/README.md b/README.md index ed109d5553..2a7f4e7a10 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Skills encode the workflows, quality gates, and best practices that senior engin ## Commands -8 slash commands that map to the development lifecycle. Each one activates the right skills automatically. +9 slash commands that map to the development lifecycle. Each one activates the right skills automatically. | What you're doing | Command | Key principle | |-------------------|---------|---------------| @@ -29,6 +29,7 @@ Skills encode the workflows, quality gates, and best practices that senior engin | Plan how to build it | `/plan` | Small, atomic tasks | | Build incrementally | `/build` | One slice at a time | | Prove it works | `/test` | Tests are proof | +| Set the quality bar | `/constraints` | Decide it once, enforce it everywhere | | Review before merge | `/review` | Improve code health | | Audit web performance | `/webperf` | Measure before you optimize | | Simplify the code | `/code-simplify` | Clarity over cleverness | @@ -45,7 +46,7 @@ Skills also activate automatically based on what you're doing — designing an A **Fastest path — any agent, one command.** The open [skills CLI](https://github.com/vercel-labs/skills) installs into 70+ agents (Claude Code, Cursor, Codex, Copilot, Cline, and more): ```bash -npx skills add addyosmani/agent-skills # install all 24 skills +npx skills add addyosmani/agent-skills # install all 25 skills npx skills add addyosmani/agent-skills --list # browse before installing ``` @@ -106,7 +107,7 @@ Put workflow skills under `.cursor/skills/` (sync from `agent-skills/skills/`) a
Antigravity CLI -Install as a native plugin for skills, subagents, and slash commands. See [docs/antigravity-setup.md](docs/antigravity-setup.md). +Install as a native plugin for skills and subagents. In affected Antigravity CLI releases, legacy command TOMLs are reported as converted but their wrapper commands are not discoverable; invoke the underlying namespaced skills directly. See [docs/antigravity-setup.md](docs/antigravity-setup.md#lifecycle-workflows-and-command-compatibility). **Install from the repo:** @@ -152,7 +153,7 @@ Add skill contents to your Windsurf rules configuration. See [docs/windsurf-setu
OpenCode -Uses agent-driven skill execution via AGENTS.md and the `skill` tool. +Copy skills to `.opencode/skills/` (or `~/.config/opencode/skills/`), add a project-local `AGENTS.md`, and use the built-in `skill` tool for agent-driven execution. Optional slash commands can be added under `.opencode/commands/`. See [docs/opencode-setup.md](docs/opencode-setup.md). @@ -163,6 +164,8 @@ See [docs/opencode-setup.md](docs/opencode-setup.md). Use agent definitions from `agents/` as Copilot personas and skill content in `.github/copilot-instructions.md`. See [docs/copilot-setup.md](docs/copilot-setup.md). +Using the standalone `copilot` CLI? Install it as a plugin — see [docs/copilot-cli-setup.md](docs/copilot-cli-setup.md). +
@@ -218,7 +221,7 @@ Already installed? How you roll the pack out depends on your codebase. The **[Ad ## All 24 Skills -The commands above are entry points. The pack includes 24 skills total — 23 lifecycle skills plus the `using-agent-skills` meta-skill. Each skill is a structured workflow with steps, verification gates, and anti-rationalization tables. You can also reference any skill directly. +The commands above are entry points. The pack includes 25 skills total — 24 lifecycle skills plus the `using-agent-skills` meta-skill. Each skill is a structured workflow with steps, verification gates, and anti-rationalization tables. You can also reference any skill directly. ### Meta - Discover which skill applies @@ -233,6 +236,7 @@ The commands above are entry points. The pack includes 24 skills total — 23 li | [interview-me](skills/interview-me/SKILL.md) | One-question-at-a-time interview that extracts what the user actually wants instead of what they think they should want, until ~95% confidence | The ask is underspecified, or the user invokes "interview me" / "grill me" | | [idea-refine](skills/idea-refine/SKILL.md) | Structured divergent/convergent thinking to turn vague ideas into concrete proposals | You have a rough concept that needs exploration | | [spec-driven-development](skills/spec-driven-development/SKILL.md) | Write a PRD covering objectives, commands, structure, code style, testing, and boundaries before any code | Starting a new project, feature, or significant change | +| [constraint-driven-development](skills/constraint-driven-development/SKILL.md) | Interviews you for a quality bar with sane default thresholds, writes CONSTRAINTS.md, places each check by cost, and catches agents silencing checks or skipping tests to get green | No standards are written down, or an agent is producing more than anyone reads | ### Plan - Break it down @@ -349,10 +353,11 @@ Every skill follows a consistent anatomy: ``` agent-skills/ -├── skills/ # 24 skills (23 lifecycle + 1 meta) +├── skills/ # 25 skills (24 lifecycle + 1 meta) │ ├── interview-me/ # Define │ ├── idea-refine/ # Define │ ├── spec-driven-development/ # Define +│ ├── constraint-driven-development/ # Define │ ├── planning-and-task-breakdown/ # Plan │ ├── incremental-implementation/ # Build │ ├── context-engineering/ # Build diff --git a/agents/code-reviewer.md b/agents/code-reviewer.md index 68db53a276..56681453ba 100644 --- a/agents/code-reviewer.md +++ b/agents/code-reviewer.md @@ -46,13 +46,15 @@ Evaluate every change across these five dimensions: ## Output Format -Categorize every finding: +Categorize every finding, using the same severity labels as the `code-review-and-quality` skill: -**Critical** — Must fix before merge (security vulnerability, data loss risk, broken functionality) +**Critical** — Blocks merge (security vulnerability, data loss risk, broken functionality) -**Important** — Should fix before merge (missing test, wrong abstraction, poor error handling) +**Required** — Must address before merge (missing test, wrong abstraction, poor error handling) -**Suggestion** — Consider for improvement (naming, code style, optional optimization) +**Optional** — Worth considering but not required (a simpler design, a useful refactor) + +**Nit** — Minor and optional; the author may ignore (formatting, naming, style preferences) ## Review Output Template @@ -66,10 +68,13 @@ Categorize every finding: ### Critical Issues - [File:line] [Description and recommended fix] -### Important Issues +### Required Changes - [File:line] [Description and recommended fix] -### Suggestions +### Optional +- [File:line] [Description] + +### Nits - [File:line] [Description] ### What's Done Well @@ -85,7 +90,7 @@ Categorize every finding: 1. Review the tests first — they reveal intent and coverage 2. Read the spec or task description before reviewing code -3. Every Critical and Important finding should include a specific fix recommendation +3. Every Critical and Required finding should include a specific fix recommendation 4. Don't approve code with Critical issues 5. Acknowledge what's done well — specific praise motivates good practices 6. If you're uncertain about something, say so and suggest investigation rather than guessing diff --git a/commands/constraints.toml b/commands/constraints.toml new file mode 100644 index 0000000000..409b009377 --- /dev/null +++ b/commands/constraints.toml @@ -0,0 +1,32 @@ +description = "Define and enforce this project's quality bar — interview, sane defaults, CONSTRAINTS.md" + +prompt = """ +Invoke the constraint-driven-development skill. + +$ARGUMENTS + +Default behaviour with no arguments: set up constraints for this repository. + +1. **Detect first.** Read package.json / pyproject.toml / go.mod, the test runner, existing lint configs, current coverage output, CI workflows, and the agent harness in use. Report what you found in two lines. Never ask for anything you can read. + +2. **Interview, at most four questions.** One at a time, each with your best guess and a usable default so "I don't know" still produces a working config: + - Which dimensions beyond the floor (coverage, security, performance, accessibility, architecture) + - Block or warn when a check fails mid-task + - Target numbers, or measure today's values and hold them + - Slowest check tolerated before handing work back + +3. **Write CONSTRAINTS.md** at the repo root with a Floor section, enforced numbers, measured-only metrics with today's values, and an exceptions table with owners and expiry dates. Every number needs a stated reason. + +4. **Install what each picked dimension needs.** A dimension with a number and no tool behind it is an aspiration. Use the de facto tool so existing config keeps working: Semgrep for code scanning, gitleaks (always `--redact`) for secrets, osv-scanner for dependencies, axe-core for accessibility, Lighthouse for web vitals, size-limit for bundles, dependency-cruiser for boundaries, Stryker for assertion quality. Record the exact command next to each rule in CONSTRAINTS.md. Accessibility and performance need a running URL; if the project has none, say so and drop the dimension rather than inventing a check. Add the commands to package.json as check:fast / check:task / check:full. + +5. **Place each check by cost.** Types, lint and secrets in the edit loop (seconds). Related tests and changed-line coverage at task end (under 90s). Everything else at review or in CI. Scope checks to the diff, not the whole repo. + +6. **Point the agent at it.** Add a line to AGENTS.md and CLAUDE.md telling agents to read CONSTRAINTS.md and never weaken it to make a change pass. + +7. **Verify.** Run the constraints against the current branch. If anything fails that the user disagrees with, fix the constraint now rather than leaving a gate people will learn to ignore. + +Sub-commands: +- `/constraints check` — run the current constraints against this branch and report +- `/constraints guard` — inspect the diff for a weakened bar: lowered thresholds, skipped or deleted tests, new suppression comments, unfinished stubs, new exceptions +- `/constraints ratchet` — record today's measured values as the floor that must not fall +""" diff --git a/commands/planning.toml b/commands/planning.toml index 3b8daa23aa..53a8807553 100644 --- a/commands/planning.toml +++ b/commands/planning.toml @@ -13,4 +13,6 @@ Read the existing spec (SPEC.md or equivalent) and the relevant codebase section 6. Present the plan for human review Save the plan to tasks/plan.md and task list to tasks/todo.md. -""" \ No newline at end of file + +If tasks/plan.md or tasks/todo.md already exists with unchecked tasks for different work, stop and ask before writing — never silently overwrite an incomplete plan. +""" diff --git a/docs/adoption-guide.md b/docs/adoption-guide.md index 77deeae552..151562b80e 100644 --- a/docs/adoption-guide.md +++ b/docs/adoption-guide.md @@ -43,7 +43,7 @@ Run the lifecycle in order for the project's first real feature: /ship → when going live (shipping-and-launch) ``` -`/build auto` is a good fit for greenfield: you approve the plan once and every task still runs test-driven and commits individually. The spec and plan artifacts (`SPEC.md`, `tasks/`) are living documents, keep them in version control while the work is in flight. +`/build auto` is a good fit for greenfield: you approve the plan once and every task still runs test-driven and commits individually. The spec and plan artifacts (`SPEC.md`, `tasks/`) are living documents, keep them in version control while the work is in flight. If the feature spans more than one session, those files are also the handoff, see [working across sessions](getting-started.md#working-across-sessions). ### From the start, treat these as always-on @@ -65,7 +65,7 @@ Run the lifecycle in order for the project's first real feature: ### Greenfield anti-patterns - **Skipping `/spec` because "it's just a prototype."** Prototypes become products. The spec is the cheapest artifact you'll ever write for this codebase. -- **Loading all 24 skills into every session.** It wastes context and dilutes the ones that matter. Load by phase; let `using-agent-skills` route. +- **Loading all 25 skills into every session.** It wastes context and dilutes the ones that matter. Load by phase; let `using-agent-skills` route. - **Deferring observability until "there's something to observe."** Instrument as you build, retrofitting structured logging is a Path B problem you're choosing to create. --- diff --git a/docs/advanced-per-agent-configuration.md b/docs/advanced-per-agent-configuration.md new file mode 100644 index 0000000000..d06a87b7ce --- /dev/null +++ b/docs/advanced-per-agent-configuration.md @@ -0,0 +1,70 @@ +# Advanced per-agent configuration + +Skills in this repository are intentionally portable. Every `SKILL.md` keeps its frontmatter limited to the fields the [Agent Skills specification](https://agentskills.io) defines, so the same file works across Claude Code, Cursor, Gemini CLI, Antigravity, and any other spec-conformant client. + +Several agents also support extra runtime controls: model routing, tool restrictions, turn limits, execution isolation. These controls are valuable, but they are vendor-specific and do not belong in the shared, portable frontmatter. This document explains which controls each agent supports, where they belong, and how to apply them as an opt-in without breaking portability. + +This is the canonical reference for per-agent configuration, and it supersedes the earlier approach of adding vendor fields to top-level `SKILL.md` frontmatter. Fields such as `kind`, `model`, `temperature`, `max_turns`, `tools`, and `context` must not appear at the top level of a skill. They belong under `metadata` or in a separate per-agent adapter file, as described below. + +## Principles + +1. **Keep `SKILL.md` portable.** The Agent Skills specification reserves top-level frontmatter for `name`, `description`, `license`, `compatibility`, `metadata`, and the experimental `allowed-tools`. Vendor or client-specific properties belong under `metadata`, not at the top level. +2. **Unknown top-level fields are not guaranteed to be ignored.** Many parsers only read `name` and `description` and silently drop the rest, but a strict spec-conformant validator or client may flag or reject unrecognized top-level keys. Putting vendor fields under `metadata` keeps the file conformant everywhere. +3. **Opt-in, not global.** Runtime controls should be something a user adds for their own agent and workflow, not a default baked into every skill in the repository. +4. **Prefer generation over hand-editing.** Where a configuration is repetitive and mechanical, generate it from a single source of truth instead of maintaining copies by hand. See [Automating with scripts](#automating-with-scripts). + +## Where vendor fields belong + +| Field type | Example | Correct home | +|---|---|---| +| Spec fields | `name`, `description`, `license`, `compatibility` | Top-level frontmatter in `SKILL.md` | +| Vendor metadata | model hints, routing tags | Under the `metadata` key in `SKILL.md` | +| Runtime orchestration | subagent definitions, turn limits, tool allowlists | A separate per-agent adapter file (see each agent below) | + +## Claude Code + +Claude Code reads `name` and `description` for discovery. Custom commands and skills share the same frontmatter, so the `context` and `allowed-tools` fields below work in both `.claude/commands/*.md` and `.claude/skills/*/SKILL.md`. + +- **`context: fork`** runs a command or skill in an isolated subagent context instead of the active conversation. This gives context isolation, repeatable execution from a clean state, execution tokens spent in the fork rather than the main session, and a cleaner handoff where only the result surfaces back. An optional **`agent`** field selects which subagent type runs the fork (for example `agent: Plan`); it defaults to `general-purpose`. +- **`allowed-tools`** pre-approves tools; it does not restrict them. Listed tools run without a permission prompt for the turn that invokes the command or skill, and the grant clears on your next message. Nothing is removed from the tool pool. +- **`disallowed-tools`** is the field that actually restricts: it removes the listed tools from the available pool while the skill is active, which is what least-privilege needs for passive stages such as review or audit. The restriction also clears on your next message. Note it is a Claude Code field and not one of the specification's six, so it belongs in a local copy or an adapter file; in a published `SKILL.md` it fails packaging with an unexpected-key error. + +These are Claude Code conventions. Keep the shared, published `SKILL.md` limited to spec fields; apply these runtime controls in your own local command or skill copies instead. + +## Gemini CLI and Antigravity + +Gemini CLI and Antigravity discover skills the same way: they match `name` and `description`, then load the full skill on demand. Runtime orchestration lives in a separate resource, not in the skill frontmatter. + +- **Subagent definitions** live in `.gemini/agents/*.md`, which are distinct from skills. Their schema is `kind` (`local` or `remote`), `model`, `temperature`, `max_turns`, and `tools`. Note that this is a subagent schema, not a skill schema: the two should not be merged into one `SKILL.md`. +- **Model routing** can send lighter tasks (formatting, documentation, git operations) to a faster model and reserve a stronger model for cognitively demanding work (debugging, security auditing, interface design). +- **Tool restrictions** enforce least-privilege per subagent, which also trims unused tool schemas from the prompt. +- **Turn limits** (`max_turns`) cap execution to avoid runaway correction loops. + +### Model guidance + +Google recommends omitting `temperature` for Gemini 3.x models and using `thinking_level` instead. Do not hardcode `temperature` on skills or subagents routed to 3.x models; prefer `thinking_level` and revisit this guidance as the models evolve. + +```yaml +# .gemini/agents/security-auditor.md +--- +kind: local +model: gemini-3-pro +thinking_level: high # not: temperature: 0.1 +tools: [read_file, grep] +max_turns: 10 +--- +``` + +## Automating with scripts + +Maintaining per-agent metadata by hand across every skill is repetitive, drifts out of sync, and is easy to get wrong. A better approach is to keep a single source of truth and generate the agent-specific output: + +- A generator reads a per-skill configuration map (which model, tool allowlist, turn limit, and isolation each skill should use for a given agent). +- For metadata-style fields, it injects them under the `metadata` key of each `SKILL.md`, keeping the file spec-conformant. +- For orchestration-style fields, it emits the separate adapter files an agent expects, for example `.gemini/agents/*.md` subagent definitions, leaving `SKILL.md` untouched. + +Generation also lets the tooling validate **semantics, not just shape**: confirm that a model name is a known model, that a tool name is a real tool, that `max_turns` is a positive integer, and that `temperature` (where still applicable) is a valid number in range. Shape-only checks let invalid values such as `parseInt("1.5")` or `parseFloat("0.2oops")` slip through. + +## Status + +This document consolidates the discussion from [#272](https://github.com/addyosmani/agent-skills/pull/272), [#36](https://github.com/addyosmani/agent-skills/pull/36), and [#35](https://github.com/addyosmani/agent-skills/issues/35), all closed in favor of this approach. It is the single reference for per-agent configuration: it keeps the shared skills portable while documenting the advanced controls each agent offers as an opt-in. The script-based automation described above is a proposal pending agreement before any implementation. diff --git a/docs/antigravity-setup.md b/docs/antigravity-setup.md index 6cd87eef03..44b29352e9 100644 --- a/docs/antigravity-setup.md +++ b/docs/antigravity-setup.md @@ -1,12 +1,12 @@ # Using agent-skills with Antigravity CLI (agy) -The `agent-skills` package can be installed as a native plugin in the Antigravity CLI (`agy`), giving the agent access to structured workflows, personas, and custom slash commands. +The `agent-skills` package can be installed as a native plugin in the Antigravity CLI (`agy`), giving the agent access to structured workflows and personas. ## Setup ### Option 1: Native Plugin Installation (Recommended) -Antigravity CLI has a first-class plugin system that registers skills, agents, and custom commands. +Antigravity CLI has a first-class [plugin system](https://www.agy.dev/docs/plugins/) that registers skills and agents. The repository also carries legacy command TOMLs, but affected `agy` releases do not expose their converted wrappers; see [Lifecycle Workflows and Command Compatibility](#lifecycle-workflows-and-command-compatibility). **Install from the remote repository:** @@ -43,24 +43,24 @@ agy plugin list --- -## Slash Commands +## Lifecycle Workflows and Command Compatibility -The plugin registers 8 custom slash commands: 7 lifecycle commands plus the `/webperf` specialist audit: +Antigravity's [migration tooling](https://www.agy.dev/docs/cli/gcli-migration/) reports the 8 legacy definitions in `commands/*.toml` as "converted to skills." In affected `agy` 1.1.x releases, validation succeeds but the converted wrappers do not appear in the slash-command or skill catalog. A successful `agy plugin validate` therefore confirms the files are well formed, not that `/build` and the other short wrappers are available. This is tracked in [agent-skills #445](https://github.com/addyosmani/agent-skills/issues/445) and upstream in [antigravity-cli #788](https://github.com/google-antigravity/antigravity-cli/issues/788). -| Command | What it does | Activated Skill | -|---------|--------------|-----------------| -| `/spec` | Write a structured spec before writing code | `spec-driven-development` | -| `/planning` | Break work into small, verifiable tasks | `planning-and-task-breakdown` | -| `/build` | Implement the next task incrementally | `incremental-implementation` | -| `/test` | Run TDD workflow — red, green, refactor | `test-driven-development` | -| `/review` | Five-axis code review | `code-review-and-quality` | -| `/code-simplify` | Reduce complexity without changing behavior | `code-simplification` | -| `/ship` | Pre-launch checklist via parallel persona fan-out | `shipping-and-launch` | -| `/webperf` | Audit browser-facing apps for Core Web Vitals and performance issues | `web-performance-auditor` | +Use the native plugin skills directly while that importer limitation applies: -Each command automatically invokes the corresponding skill and guides the agent step-by-step. +| Intended wrapper | Direct Antigravity invocation | Notes | +|------------------|-------------------------------|-------| +| `/spec` | `/agent-skills:spec-driven-development` | Writes a structured spec before code | +| `/planning` | `/agent-skills:planning-and-task-breakdown` | Antigravity's built-in `/planning` command is a separate plan-mode control | +| `/build` | `/agent-skills:incremental-implementation` | Also invoke `/agent-skills:test-driven-development`; wrapper-only `/build auto` orchestration is unavailable | +| `/test` | `/agent-skills:test-driven-development` | Runs the red-green-refactor workflow | +| `/review` | `/agent-skills:code-review-and-quality` | Runs the five-axis review workflow | +| `/code-simplify` | `/agent-skills:code-simplification` | Simplifies without changing behavior | +| `/ship` | `/agent-skills:shipping-and-launch` | The wrapper's automatic persona fan-out is unavailable; invoke specialist agents separately | +| `/webperf` | Select `web-performance-auditor` from `/agents` | This workflow is a persona, not a skill | -> **Note:** Use `/planning` instead of `/plan` to avoid conflicts with Antigravity's internal plan-generation command. +Do not add YAML frontmatter to the TOML files as a workaround. Gemini CLI reads the parallel TOML command format with a strict parser, and `---` frontmatter makes those files invalid TOML without changing Antigravity's conversion behavior. --- @@ -79,6 +79,8 @@ To validate that your local plugin is correctly structured and contains all skil agy plugin validate /path/to/agent-skills ``` +Then start a fresh session and type `/agent-skills:` to inspect the namespaced skill catalog. If the validator reports that commands were converted but `/build` returns `No matches`, use the direct invocations above; reinstalling or adding a TOML `name` field does not resolve the known importer limitation. + --- ## How It Works diff --git a/docs/codex-setup.md b/docs/codex-setup.md index 54b59a62b6..7f32939645 100644 --- a/docs/codex-setup.md +++ b/docs/codex-setup.md @@ -22,7 +22,7 @@ codex plugin add agent-skills@agent-skills ## Usage -After install, invoke a skill in Codex chat with `@` (e.g. `@spec-driven-development`) or just describe the task and let Codex pick the right skill. All 24 skills under `skills/` are available. +After install, invoke a skill in Codex chat with `@` (e.g. `@spec-driven-development`) or just describe the task and let Codex pick the right skill. All 25 skills under `skills/` are available. ## How it works diff --git a/docs/commandcode-setup.md b/docs/commandcode-setup.md index e6aa360e3b..0150adc6e9 100644 --- a/docs/commandcode-setup.md +++ b/docs/commandcode-setup.md @@ -12,7 +12,7 @@ The Command Code binary is available as `cmd` (with aliases `cmdc` on Windows an cmd skills add addyosmani/agent-skills ``` -In an interactive terminal this shows a multi-select so you can choose which of the 24 skills to install. Pipe/non-interactive invocations install all discovered skills. +In an interactive terminal this shows a multi-select so you can choose which of the 25 skills to install. Pipe/non-interactive invocations install all discovered skills. **Install a specific skill:** diff --git a/docs/comparison.md b/docs/comparison.md index 904d270532..2c51daa6f4 100644 --- a/docs/comparison.md +++ b/docs/comparison.md @@ -18,7 +18,7 @@ People often ask how **agent-skills** relates to the two other "skills for codin |---|---|---|---| | **Core idea** | Encode the full senior-engineering lifecycle as skills | A complete development *methodology* built on composable skills | One expert's Claude Code workflow, open-sourced and evolving | | **Organizing principle** | SDLC **phases** (Define to Ship) behind a meta-skill router | A single disciplined loop: brainstorm, plan, execute, review | A curated toolbox of focused, composable commands | -| **Catalog size** | 24 skills spanning the whole lifecycle | ~14 skills, deep on the inner build loop | ~30 skills, grouped into engineering / productivity / in-progress / deprecated | +| **Catalog size** | 25 skills spanning the whole lifecycle | ~14 skills, deep on the inner build loop | ~30 skills, grouped into engineering / productivity / in-progress / deprecated | | **Lifecycle coverage** | Broad: idea refinement, API and UI design, security, performance, CI/CD, observability, deprecation, ADRs, launch | Deep but narrow: TDD, debugging, planning, review, skill authoring | Define and Build heavy: grilling, PRDs, issues, TDD, architecture, bug triage, knowledge management | | **Entry points** | Slash commands mapped 1:1 to phases (`/spec` `/plan` `/build` `/test` `/review` `/code-simplify` `/ship`, plus `/webperf`), with a `/build auto` full-plan mode | Skill-chained pipeline (`brainstorming`, `writing-plans`, `subagent-driven-development`) | Slash commands (`/grill-me`, `/tdd`, `/to-prd`, `/diagnosing-bugs`, `/grill-with-docs`) | | **Distinctive mechanisms** | Anti-rationalization tables and Red Flags in every skill; parallel review **personas** in `/ship`; reference checklists; a **three-tier eval framework** in CI | Subagent-driven development with a task reviewer (spec + quality) and a fix loop; git-worktree isolation; skills-that-write-skills, pressure-tested | The **grilling** primitive (one question at a time, design-tree walking); seam-based TDD; explicit user-invoked vs model-invoked split; issue-tracker integration | diff --git a/docs/copilot-cli-setup.md b/docs/copilot-cli-setup.md new file mode 100644 index 0000000000..06e3f5264e --- /dev/null +++ b/docs/copilot-cli-setup.md @@ -0,0 +1,64 @@ +# Using agent-skills with GitHub Copilot CLI + +The standalone `copilot` command-line tool installs this repository as a plugin and discovers every skill in `skills/`. For Copilot inside VS Code, see [copilot-setup.md](copilot-setup.md) instead — the setup and the invocation model are different. + +## Install + +**From this repository's marketplace** — register it, then install from it. `addy-agent-skills` is the marketplace name this repository declares, not a GitHub-wide registry, and the name only resolves after the `marketplace add`: + +```bash +copilot plugin marketplace add addyosmani/agent-skills +copilot plugin install agent-skills@addy-agent-skills +``` + +**Directly from the repository**, without registering a marketplace: + +```bash +copilot plugin install addyosmani/agent-skills +``` + +**From a local clone**, for a session-scoped development install: + +```bash +git clone https://github.com/addyosmani/agent-skills.git +copilot --plugin-dir /path/to/agent-skills +``` + +`--plugin-dir` loads the plugin for that session only and installs nothing persistently — use it while editing skills. + +## Verify + +```bash +copilot plugin list # agent-skills@addy-agent-skills +copilot skill list # the plugin's skills, alongside the built-in ones +``` + +In an interactive session, `/skills list` shows the same catalog. + +## What you get, and what you don't + +The root `plugin.json` is the manifest Copilot CLI reads — it takes precedence over `.claude-plugin/plugin.json`, which belongs to Claude Code. That root manifest declares only a name, version and description, so component paths fall back to their defaults: + +- **Skills — available.** With no explicit path, the CLI uses the conventional `skills/` directory, and the skills are discovered there. +- **Lifecycle commands — not available.** The root manifest has no `commands` field, so nothing registers `/spec`, `/plan`, `/build`, `/test`, `/review` or `/ship`. Those files live in `.claude/commands/` and are Claude Code commands. + +For manifest precedence and the per-component path defaults, see the [CLI plugin reference](https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-plugin-reference) and [Creating plugins](https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/plugins-creating). + +## Usage + +Name the skill you want, or describe the task and let the agent route to it: + +> Use the spec-driven-development skill to write a spec for [the feature]. + +> Use the test-driven-development skill: write a failing test for this bug first, then fix it. + +> Use the code-review-and-quality skill to review my staged changes. + +## Troubleshooting + +| Symptom | What to check | +|---------|---------------| +| `plugin install` can't resolve `agent-skills@addy-agent-skills` | Run `copilot plugin marketplace add addyosmani/agent-skills` first — that name only resolves once the marketplace is registered. Or install the repository directly. | +| Plugin installed but no skills | `copilot plugin list` to confirm the plugin, then `copilot skill list` (or `/skills list` in session) to see what was discovered. | +| `/spec`, `/build` and friends are not found | Expected, not a broken install: the root manifest registers no commands. Ask for the skill by name instead. | +| Skills changed locally but the CLI shows the old copy | Start a fresh session, or run with `--plugin-dir` pointing at your clone. | diff --git a/docs/copilot-setup.md b/docs/copilot-setup.md index cfe137ee2a..f70aa3b15e 100644 --- a/docs/copilot-setup.md +++ b/docs/copilot-setup.md @@ -1,5 +1,9 @@ # Using agent-skills with GitHub Copilot +This guide covers Copilot in VS Code. For the standalone `copilot` command-line tool, see [copilot-cli-setup.md](copilot-cli-setup.md). + +**What an install actually gives you:** the skills. Each installed skill becomes a slash command named after its frontmatter `name` — `/spec-driven-development`, `/test-driven-development`, and so on. `npx skills add addyosmani/agent-skills` and the manual copy below both install skills only. Neither of those two routes copies this repo's short lifecycle wrappers (`/spec`, `/plan`, `/build`, `/test`, `/review`, `/ship`) — those are Claude Code commands living in `.claude/commands/`. Use the full skill names, or add your own aliases — see [Lifecycle workflows](#lifecycle-workflows). + ## Setup ### Copilot Instructions @@ -14,7 +18,9 @@ cat /path/to/agent-skills/skills/test-driven-development/SKILL.md > .github/skil cat /path/to/agent-skills/skills/code-review-and-quality/SKILL.md > .github/skills/code-review-and-quality/SKILL.md ``` -For more details, refer [Creating agent skills for GitHub Copilot](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/create-skills). +Whichever of these two routes you use, the result is one `SKILL.md` per skill directory under one of those three project paths. An installer run with a global/user flag writes somewhere else instead — check its output for the path it used. Run `/skills` in Copilot Chat to open the **Configure Skills** menu and confirm what got discovered. + +For more details, refer [Creating agent skills for GitHub Copilot](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/create-skills) and the VS Code guide to [agent skills](https://code.visualstudio.com/docs/agent-customization/agent-skills). ### Agent Personas (*.agent.md) @@ -79,6 +85,75 @@ GitHub Copilot supports project-level instructions via `.github/copilot-instruct Use the agents for targeted review workflows in Copilot Chat. +## Lifecycle Workflows + +Skills are user-invocable by default, so once they're discovered the whole lifecycle is available under the skills' own names — no extra configuration: + +| Workflow | Copilot invocation | Notes | +|----------|--------------------|-------| +| Define | `/spec-driven-development` | Writes a structured spec before code | +| Plan | `/planning-and-task-breakdown` | Produces `tasks/plan.md` and `tasks/todo.md` | +| Build | `/incremental-implementation` | Pair with `/test-driven-development`; one slice at a time | +| Verify | `/test-driven-development` | Red-green-refactor, Prove-It for bugs | +| Review | `/code-review-and-quality` | Five-axis review | +| Ship | `/shipping-and-launch` | Launch readiness | + +Type `/` to browse what's actually loaded in this workspace. + +Natural language is the fallback, and works in any Copilot surface whether or not the slash commands show up: + +> Use the spec-driven-development skill to write a spec for [the feature]. + +> Use the code-review-and-quality skill to review my staged changes. + +### Optional: short `/spec`-style aliases + +VS Code's extension-host local agents support [prompt files](https://code.visualstudio.com/docs/agent-customization/prompt-files) at `.github/prompts/.prompt.md`, and each becomes a `/` slash command. The Agent Host does **not** use prompt files — there, use the skill names above. + +An alias is a thin shortcut to one skill, nothing more. These aliases do not implement the orchestration in this repo's Claude Code commands — `/build auto`'s single-approval plan-and-implement pass and `/ship`'s parallel persona fan-out. Reproducing that on Copilot is its own piece of work, not something a one-file alias covers. Prefer the skill names as your default; reach for aliases only if the short form is worth the extra file. + +Create one, without clobbering an existing file: + +```bash +mkdir -p .github/prompts +[ -e .github/prompts/spec.prompt.md ] || cat > .github/prompts/spec.prompt.md <<'EOF' +--- +description: Write a structured spec before writing code +--- + +Use the spec-driven-development skill. + +Ask clarifying questions about the objective and target users, core features and +acceptance criteria, stack preferences and constraints, and known boundaries. +Then write a spec covering objective, commands, project structure, code style, +testing strategy, and boundaries. Save it as SPEC.md in the project root and +confirm with me before any code is written. +EOF +``` + +Reload the window, then type `/spec`. + +For the rest, run the same `mkdir`/`cat` block with the filename swapped (the filename *is* the command name), and take the `description` and body from this table. **Replace the entire body below the `---` frontmatter**, not just the skill name — the spec body's SPEC.md and clarifying-question instructions belong to Define only, and leaving them in would make `/plan` or `/test` write a spec. + +| Alias file | `description` | Complete body — everything below the frontmatter | +|------------|---------------|--------------------------------------------------| +| `.github/prompts/plan.prompt.md` | Break an approved spec into ordered, verifiable tasks | Use the planning-and-task-breakdown skill. Read the spec, then break the work into small, independently verifiable tasks, each with acceptance criteria and explicit dependency order. Save the result to `tasks/plan.md` and `tasks/todo.md`. Write no product code — show me the plan and wait for my approval. | +| `.github/prompts/build.prompt.md` | Implement the next planned task, test-first | Use the incremental-implementation and test-driven-development skills. Read `tasks/plan.md` and `tasks/todo.md`, then take the next unchecked task and only that one. Write a failing test first, make it pass, refactor, run the suite, and tick the task off. Stop there and report what changed. | +| `.github/prompts/test.prompt.md` | Write tests before the code that satisfies them | Use the test-driven-development skill. For new behavior, write a failing test that captures it before any implementation. For a bug, reproduce it with a failing test first, then fix it. Run the suite after each step and show me the red and the green output. | + +Write the body yourself, or take it from this table, rather than copying `.claude/commands/*.md` verbatim: those files reference skills as `agent-skills:`, a Claude Code plugin namespace that means nothing to Copilot. + +### If the skill slash commands don't appear + +Work through these in order — `/spec-driven-development` missing and `/spec` missing have different causes: + +1. **Check where the skills landed.** Each one needs its own directory containing a `SKILL.md`. The project-level paths this guide uses are `.github/skills/`, `.claude/skills/` and `.agents/skills/` — but an installer run with a global/user flag writes outside the workspace instead (`~/.agents/skills/` and equivalents), so a skill that isn't in any of the three may simply be installed personally. Confirm the actual path against the [VS Code agent skills docs](https://code.visualstudio.com/docs/agent-customization/agent-skills), then re-install into the project if you wanted it project-scoped. +2. **Check the frontmatter.** `name` must be present and valid — it *is* the slash command. A skill whose frontmatter opts out of user invocation won't appear. +3. **Check the Configure Skills menu.** Run `/skills` and confirm the skill is enabled here. +4. **Start a fresh session.** Newly added skills aren't always picked up mid-conversation. +5. **Check the host.** If `/spec-driven-development` works but your `/spec` alias doesn't, you're likely on the Agent Host, which doesn't read prompt files. +6. **Check versions.** VS Code (**Help → About**) and the Copilot Chat extension; skills-as-slash-commands is recent, so update if either is behind. + ## Usage Tips 1. **Keep instructions concise** — Copilot instructions work best when focused. Summarize the key rules rather than including full skill files. diff --git a/docs/getting-started.md b/docs/getting-started.md index 8fe56d3983..8572898a82 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -156,6 +156,23 @@ The `/spec` and `/plan` commands create working artifacts (`SPEC.md`, `tasks/pla - Update them when scope or decisions change. - If your repo doesn’t want these files long‑term, delete them before merge or add the folder to `.gitignore` — the workflow doesn’t require them to be permanent. +### Working across sessions + +The same artifacts are the handoff between sessions. For a small task, run the whole lifecycle in one session. For anything non-trivial, a fresh session per phase (spec → plan → build → review) keeps context focused — what carries the work forward is the approved files, not the conversation: + +- the spec — `SPEC.md`, or wherever your spec actually lives +- `tasks/plan.md` and `tasks/todo.md` — or the external tracker the plan identifies, if you use one + +**Before switching**, make sure those files reflect the decisions that still apply, the scope you approved, the questions still open, the next task, and the current verification state (which tests ran, against what). + +**In the new session**, read the actual files and look at `git status` before doing anything. Don't assume approvals you can't see in the artifacts. Treat a recorded "tests pass" as a claim about a specific baseline: re-run the checks it covers if the code has moved since, if it doesn't say what was run against what, or if you're about to touch the area it covered. If the baseline still holds, take it and get on with the next task — the point is a check proportional to what changed, not a full suite at every handoff. + +This doesn't need the `/spec` and `/plan` wrappers — plain requests work in any agent, including a `npx skills add` install that only has the skills: + +> Read SPEC.md, then break it into small verifiable tasks with acceptance criteria and dependency order. Save them to tasks/plan.md and tasks/todo.md. No product code yet — show me the plan first. + +> Read SPEC.md, tasks/plan.md and tasks/todo.md, then check where things actually stand — `git status`, plus re-running whatever checks the recorded verification state no longer covers. Tell me the next unchecked task and anything still open, then stop: I'll confirm the scope before you start it. If the plan looks incomplete, say what's missing rather than rewriting it. + ## Tips 1. **Start with spec-driven-development** for any non-trivial work diff --git a/docs/opencode-setup.md b/docs/opencode-setup.md index 84a96d5bd0..354097f8be 100644 --- a/docs/opencode-setup.md +++ b/docs/opencode-setup.md @@ -1,30 +1,50 @@ # OpenCode Setup -This guide explains how to use Agent Skills with OpenCode in a way that closely mirrors the Claude Code experience (automatic skill selection, lifecycle-driven workflows, and strict process enforcement). +This guide explains how to use Agent Skills with OpenCode. The reusable assets are the markdown skills in the `skills/` directory; the root `AGENTS.md` file in this repository is repo-scoped and should not be copied into other projects. ## Overview -OpenCode supports custom `/commands`, but does not have a native plugin system or automatic skill routing like Claude Code. +OpenCode discovers skills from several locations. Agent Skills provides two optional usage styles: -Instead, we achieve parity through: +- **Agent-driven workflow:** skills are selected automatically via the built-in `skill` tool and a project-local `AGENTS.md` that you write for your own repository. +- **Command-driven workflow:** manually invoke lifecycle commands with `.opencode/commands/` (optional). -- A strong system prompt (`AGENTS.md`) -- The built-in `skill` tool -- Consistent skill discovery from the `/skills` directory +## Installation -This creates an **agent-driven workflow** where skills are selected and executed automatically. +There are two ways to get the skills into your project: -While it is possible to recreate `/spec`, `/plan`, and other commands in OpenCode, this integration intentionally uses an agent-driven approach instead: +1. Install with the `skills` CLI (fastest). +2. Clone this repository and copy the skill directories manually. -- Skills are selected automatically based on intent -- Workflows are enforced via `AGENTS.md` -- No manual command invocation is required +After either step, create your own project-local `AGENTS.md` and, if you want them, copy the `.opencode/commands/*.md` files. -This more closely matches how Claude Code behaves in practice, where skills are triggered automatically rather than manually. +### Option 1: Install with `npx skills` ---- +The fastest path is the open [`skills` CLI](https://github.com/vercel-labs/skills): -## Installation +```bash +npx skills add addyosmani/agent-skills # install selected skills +npx skills add addyosmani/agent-skills --list # browse before installing +``` + +Install a single skill: + +```bash +npx skills add addyosmani/agent-skills --skill spec-driven-development +``` + +By default `npx skills` installs into a tool-specific directory (often `.claude/skills/` or a shared location). OpenCode will discover skills placed there because it reads `.claude/skills//SKILL.md` and the generic `.agents/skills//SKILL.md` paths. + +If the skills land somewhere OpenCode does not scan, copy or symlink them into one of the discovery paths listed below, for example: + +```bash +mkdir -p .opencode/skills +cp -r .claude/skills/ .opencode/skills/ +``` + +> **Note:** Per-skill installs copy only the skill directory itself. If a skill references shared files under `references/`, copy those into the installed skill directory or install the whole pack. See [#361](https://github.com/addyosmani/agent-skills/issues/361) for background. + +### Option 2: Clone this repository 1. Clone the repository: @@ -32,36 +52,107 @@ This more closely matches how Claude Code behaves in practice, where skills are git clone https://github.com/addyosmani/agent-skills.git ``` -2. Open the project in OpenCode. +2. Copy the desired skills into one of the OpenCode skill discovery paths. -3. Ensure the following files are present in your workspace: +#### Project-local installation -- `AGENTS.md` (root) -- `skills/` directory +```bash +mkdir -p .opencode/skills +cp -r /path/to/agent-skills/skills/ .opencode/skills/ +``` -No additional installation is required. +For example, to install `spec-driven-development` and `incremental-implementation`: ---- +```bash +mkdir -p .opencode/skills +cp -r /path/to/agent-skills/skills/spec-driven-development .opencode/skills/ +cp -r /path/to/agent-skills/skills/incremental-implementation .opencode/skills/ +``` -## How It Works +#### Global installation -### 1. Skill Discovery +```bash +mkdir -p ~/.config/opencode/skills +cp -r /path/to/agent-skills/skills/ ~/.config/opencode/skills/ +``` -All skills live in: +#### Cross-compatible paths +OpenCode also discovers skills placed in Claude-compatible or generic agent paths: + +- `.claude/skills//SKILL.md` +- `~/.claude/skills//SKILL.md` +- `.agents/skills//SKILL.md` +- `~/.agents/skills//SKILL.md` + +If you already share skills across Claude Code and OpenCode, any of these locations work. + +### What to copy + +Copy the directories under `skills/` (for example `skills/spec-driven-development/`). Each directory must contain a `SKILL.md` file. Do not copy the repository's root `AGENTS.md` or `CLAUDE.md`; those files configure development of this repository itself. + +## Project `AGENTS.md` + +Create an `AGENTS.md` in **your own project** root. This is the system prompt that tells OpenCode when and how to invoke the installed skills. Unlike the repo-scoped `AGENTS.md` in `addyosmani/agent-skills`, this file belongs to your project and should be adapted to your stack. + +Below is a template you can paste into your project's `AGENTS.md`: + +```markdown +# Agent Skills (OpenCode) + +This project uses skills installed under `.opencode/skills/` (or a compatible path). + +## Core Rules + +- If a task matches a skill, invoke it with the `skill` tool before acting. +- Skills are located in `.opencode/skills//SKILL.md`. +- Follow the skill workflow strictly; do not partially apply it. +- Never skip required steps such as spec, plan, or test when a skill demands them. + +## Intent → Skill Mapping + +Map the user's intent to the matching skill automatically: + +- Feature / new functionality → `spec-driven-development`, then `incremental-implementation` and `test-driven-development` +- Planning / breakdown → `planning-and-task-breakdown` +- Bug / failure / unexpected behavior → `debugging-and-error-recovery` +- Code review → `code-review-and-quality` +- Refactoring / simplification → `code-simplification` +- API or interface design → `api-and-interface-design` +- UI work → `frontend-ui-engineering` + +## Execution Model + +For every request: + +1. Determine if any skill applies (even a small chance). +2. Load the skill with `skill({ name: "" })`. +3. Follow the skill workflow exactly. +4. Only proceed to implementation once required steps are complete. ``` -skills//SKILL.md -``` -OpenCode agents are instructed (via `AGENTS.md`) to: +Save this as `AGENTS.md` in your project root. OpenCode will load it automatically. + +> **Note:** The root `AGENTS.md` inside the `addyosmani/agent-skills` repository is intended for contributors working on this repository and should not be copied into other projects. See [CONTRIBUTING.md](../CONTRIBUTING.md#repo-scoped-files). + +## How It Works + +### 1. Skill Discovery + +OpenCode walks the following paths (project-local first, then global): + +- `.opencode/skills//SKILL.md` +- `~/.config/opencode/skills//SKILL.md` +- `.claude/skills//SKILL.md` +- `~/.claude/skills//SKILL.md` +- `.agents/skills//SKILL.md` +- `~/.agents/skills//SKILL.md` -- Detect when a skill applies -- Invoke the `skill` tool -- Follow the skill exactly +Each skill must contain a `SKILL.md` file with a valid `name` and `description` in its frontmatter. ### 2. Automatic Skill Invocation -The agent evaluates every request and maps it to the appropriate skill. +When your project's `AGENTS.md` instructs the agent to use skills, the agent evaluates every request and maps it to the appropriate skill. Examples: @@ -70,11 +161,9 @@ Examples: - "fix a bug" → `debugging-and-error-recovery` - "review this code" → `code-review-and-quality` -The user does **not** need to explicitly request skills. - ### 3. Lifecycle Mapping (Implicit Commands) -The development lifecycle is encoded implicitly: +OpenCode does not require slash commands, but if you prefer them see the next section. In agent-driven mode the lifecycle is mapped implicitly: - DEFINE → `spec-driven-development` - PLAN → `planning-and-task-breakdown` @@ -83,10 +172,29 @@ The development lifecycle is encoded implicitly: - REVIEW → `code-review-and-quality` - SHIP → `shipping-and-launch` -This replaces slash commands like `/spec`, `/plan`, etc. +### Copy the optional slash commands + +If you prefer explicit commands, copy the example command files from this repository into your project and adjust them to invoke the skills you installed: + +```bash +mkdir -p .opencode/commands +cp /path/to/agent-skills/.opencode/commands/*.md .opencode/commands/ +``` + +> **Note:** The repository currently does not include `.opencode/commands/*.md` on `main`. You can create your own command files or watch PR #200, which proposes adding them. Once they exist, the pattern above applies. + +A typical command file looks like: +```markdown +--- +description: Break work into small verifiable tasks --- +Invoke the planning-and-task-breakdown skill. Read the spec and create tasks with acceptance criteria. +``` + +Save it as `.opencode/commands/plan.md` to enable `/plan` in OpenCode. + ## Usage Examples ### Example 1: Feature Development @@ -102,8 +210,6 @@ Agent behavior: - Produces a spec before writing code - Moves to planning and implementation skills ---- - ### Example 2: Bug Fix User: @@ -115,8 +221,6 @@ Agent behavior: - Invokes `debugging-and-error-recovery` - Reproduces → localizes → fixes → adds guards ---- - ### Example 3: Code Review User: @@ -128,51 +232,28 @@ Agent behavior: - Invokes `code-review-and-quality` - Applies structured review (correctness, design, readability, etc.) ---- - -## Agent Expectations (Critical) +## Agent Expectations -For OpenCode to work correctly, the agent must follow these rules: +For OpenCode to work correctly, the agent should: - Always check if a skill applies before acting -- If a skill applies, it MUST be used +- Use the `skill` tool to load the skill when it applies - Never skip required workflows (spec, plan, test, etc.) -- Do not jump directly to implementation +- Not jump directly to implementation -These rules are enforced via `AGENTS.md`. - ---- +These rules are enforced by your project's `AGENTS.md`, not by the copy of the skill itself. ## Limitations -- No native slash commands (handled via intent mapping instead) -- No plugin system (handled via prompt + structure) -- Skill invocation depends on model compliance - -Despite these, the workflow closely matches Claude Code in practice. - ---- - -## Recommended Workflow - -Just use natural language: - -- "Design a feature" -- "Plan this change" -- "Implement this" -- "Fix this bug" -- "Review this" - -The agent will automatically select and execute the correct skills. - ---- +- Skill invocation depends on model compliance. +- OpenCode does not install skills automatically; copy or install the directories you need. +- If a skill references files under `references/`, you may need to copy those as well when installing manually. ## Summary -OpenCode integration works by combining: - -- Structured skills (this repo) -- Strong agent rules (`AGENTS.md`) -- Automatic skill invocation via reasoning +1. Install the skills you need, either with `npx skills add addyosmani/agent-skills` or by copying them from a clone of this repository into `.opencode/skills/` (project), `~/.config/opencode/skills/` (global), or a cross-compatible path such as `.claude/skills/` / `.agents/skills/`. +2. Create your own project-local `AGENTS.md` with the rules and intent mapping above. +3. OpenCode discovers the skills and your `AGENTS.md` guides the agent to invoke them. +4. Optionally add `.opencode/commands/*.md` for explicit slash commands. -This results in a **fully agent-driven, production-grade engineering workflow** without requiring plugins or manual commands. +This keeps the reusable assets (skills) separate from the repository-specific configuration (the `addyosmani/agent-skills` root `AGENTS.md`). diff --git a/evals/README.md b/evals/README.md index d67a025d0b..e571aac810 100644 --- a/evals/README.md +++ b/evals/README.md @@ -26,7 +26,7 @@ Tier 2 is a **lexical approximation** of routing (stemmed TF-IDF over descriptio ```bash # Tier 2 — deterministic, runs in CI node scripts/run-evals.js -node scripts/run-evals.js --min-rank1 80 # enforce the current routing floor +node scripts/run-evals.js --min-rank1 95 # enforce the current routing floor # Tier 3 — behavioral, runs each eval through headless claude, then grades it node scripts/run-evals.js --behavioral test-driven-development # spends tokens @@ -83,4 +83,4 @@ Every skill ships with an eval file. When you add `skills//`, add `evals/c ## Metrics to watch -The Tier-2 run prints a **trigger rank-1 rate** (share of positive prompts that rank their skill first, not merely top-k). CI runs with `--min-rank1 80`, leaving useful headroom below the checked-in 86% baseline so an unrelated description edit does not immediately turn CI red. Raise the floor as routing improves; never lower it to make a regression pass. Falling numbers mean descriptions are drifting toward each other. The collision check errors at ≥75% pairwise description similarity and warns at ≥50%. Known description-vocabulary gaps surfaced by these evals are tracked in [#351](https://github.com/addyosmani/agent-skills/issues/351). +The Tier-2 run prints a **trigger rank-1 rate** (share of positive prompts that rank their skill first, not merely top-k). CI runs with `--min-rank1 95`, leaving useful headroom below the checked-in 100% baseline so an unrelated description edit does not immediately turn CI red. Raise the floor as routing improves; never lower it to make a regression pass. Falling numbers mean descriptions are drifting toward each other. The collision check errors at ≥75% pairwise description similarity and warns at ≥50%. When these evals surface a description-vocabulary gap (see [#351](https://github.com/addyosmani/agent-skills/issues/351) for the original examples), fix the description, not the prompt. diff --git a/evals/cases/constraint-driven-development.json b/evals/cases/constraint-driven-development.json new file mode 100644 index 0000000000..3fae3aba43 --- /dev/null +++ b/evals/cases/constraint-driven-development.json @@ -0,0 +1,79 @@ +{ + "skill_name": "constraint-driven-development", + "trigger": { + "positive": [ + { + "prompt": "Set up quality constraints for this project — I want to define our bar before the agent writes more code", + "top_k": 3 + }, + { + "prompt": "We have no written standards. Ask me what I care about and write it down with sane defaults", + "top_k": 3 + }, + { + "prompt": "The agent keeps adding @ts-ignore and skipping tests to get green. How do I stop that?", + "top_k": 3 + }, + { + "prompt": "What coverage threshold should we enforce, and where should it run so it doesn't slow us down?", + "top_k": 3 + }, + { + "prompt": "I care about accessibility and web performance — set those up as enforced constraints", + "top_k": 3 + } + ], + "negative": [ + { + "prompt": "Review this pull request across correctness and security", + "owner": "code-review-and-quality" + }, + { + "prompt": "Add a deploy stage to our pipeline with a manual approval gate", + "owner": "ci-cd-and-automation" + }, + { + "prompt": "Write a failing test for this bug before we fix it", + "owner": "test-driven-development" + } + ] + }, + "evals": [ + { + "id": 1, + "kind": "dialogue", + "prompt": "Set up constraints for this repo. I don't really know what numbers to pick.", + "expected_output": "A short interview with defaults offered, followed by a CONSTRAINTS.md the user can explain", + "expectations": [ + "The agent inspects the repo for stack, test runner, and existing linters before asking anything", + "No more than four questions are asked, and each one carries a usable default", + "When the user has no target number, the agent proposes recording today's value and holding it rather than inventing a threshold", + "The resulting constraints say where each check runs, keeping fast checks in the edit loop and slow checks later", + "Every number written down is accompanied by a reason" + ] + }, + { + "id": 2, + "kind": "dialogue", + "prompt": "Our coverage is 62% and I want to enforce 85% starting today.", + "expected_output": "Pushback on setting an unmeetable budget, with the ratchet alternative offered", + "expectations": [ + "The agent points out that a threshold the codebase fails today produces a permanently red build", + "It offers to record 62% and require that it not fall, as an adoptable alternative", + "It does not silently accept 85% without noting the consequence" + ] + }, + { + "id": 3, + "kind": "dialogue", + "prompt": "Accessibility matters to us. Add it as a constraint.", + "expected_output": "A working accessibility check, not just a threshold written down", + "expectations": [ + "The agent names axe-core and gives the install and run commands rather than only stating a violation threshold", + "It notes that axe needs a running URL and asks for one, or drops the dimension if the project has no URL to hit", + "The command that produces the verdict is recorded alongside the rule in CONSTRAINTS.md", + "The check is placed at the preview-deploy stage rather than in the per-edit loop" + ] + } + ] +} diff --git a/evals/cases/deprecation-and-migration.json b/evals/cases/deprecation-and-migration.json index 17585478a2..11881f4243 100644 --- a/evals/cases/deprecation-and-migration.json +++ b/evals/cases/deprecation-and-migration.json @@ -13,6 +13,14 @@ { "prompt": "How do I remove this old feature safely for existing users?", "top_k": 3 + }, + { + "prompt": "Rename a database column without downtime", + "top_k": 3 + }, + { + "prompt": "How do I drop a column safely in production?", + "top_k": 3 } ], "negative": [ diff --git a/evals/cases/git-workflow-and-versioning.json b/evals/cases/git-workflow-and-versioning.json index 9236defed6..c6b5aa0873 100644 --- a/evals/cases/git-workflow-and-versioning.json +++ b/evals/cases/git-workflow-and-versioning.json @@ -13,6 +13,10 @@ { "prompt": "How should we tag and version this release?", "top_k": 3 + }, + { + "prompt": "Commit this work and open a pull request", + "top_k": 3 } ], "negative": [ diff --git a/evals/cases/performance-optimization.json b/evals/cases/performance-optimization.json index 2fe195e39c..4df2f68e8c 100644 --- a/evals/cases/performance-optimization.json +++ b/evals/cases/performance-optimization.json @@ -38,14 +38,15 @@ { "id": 1, "prompt": "The products page renders slowly with 1000 items. Improve its performance.", - "expected_output": "A measured baseline, an identified bottleneck, a targeted fix, and a verified improvement", + "expected_output": "A measured baseline, an identified bottleneck, a targeted fix, a verified improvement, and a regression guard", "files": [ "performance-optimization" ], "expectations": [ "Performance is measured before any optimization is applied", "The fix targets the measured bottleneck rather than guessing", - "Improvement is verified against the baseline after the change" + "Improvement is verified against the baseline after the change", + "A concrete guard is added after verification using a synthetic performance budget or field monitoring tied to the measured user-facing metric" ] } ] diff --git a/evals/cases/security-and-hardening.json b/evals/cases/security-and-hardening.json index 10a1f33698..725a3a334b 100644 --- a/evals/cases/security-and-hardening.json +++ b/evals/cases/security-and-hardening.json @@ -13,6 +13,14 @@ { "prompt": "Harden the webhook endpoint that fetches user-supplied URLs", "top_k": 3 + }, + { + "prompt": "Run a dependency audit and triage the findings", + "top_k": 3 + }, + { + "prompt": "Is this new package safe to install? Check for typosquatting and supply chain risk", + "top_k": 3 } ], "negative": [ diff --git a/evals/skill-impact.md b/evals/skill-impact.md new file mode 100644 index 0000000000..a40ef1367a --- /dev/null +++ b/evals/skill-impact.md @@ -0,0 +1,6 @@ +# Rejected Skill Changes + +This append-only ledger records skill and description changes rejected on eval evidence so contributors can review prior attempts before proposing overlapping work. Add one concise row per rejected proposal; do not record accepted changes here. + +| Date | Affected skill | Attempted change | Rank-1 score (before → after) | Rejected PR and outcome | +|---|---|---|---:|---| diff --git a/plugin.json b/plugin.json index 01e7da6d38..7fd1573f2a 100644 --- a/plugin.json +++ b/plugin.json @@ -1,5 +1,5 @@ { "name": "agent-skills", - "version": "0.6.7", + "version": "0.6.9", "description": "Production-grade engineering skills for AI coding agents." } diff --git a/references/observability-checklist.md b/references/observability-checklist.md index fff9f5843c..ad40d7aa3f 100644 --- a/references/observability-checklist.md +++ b/references/observability-checklist.md @@ -26,6 +26,7 @@ Telemetry without a question is noise. Before instrumenting anything: - [ ] Logs are structured (JSON) with stable event names — not free-form strings - [ ] Every log line carries a correlation/request ID, generated or accepted at the system boundary - [ ] Correlation ID is propagated on every outbound call and async boundary (HTTP headers, queue metadata) +- [ ] Any log stream written by more than one entry point (scheduler, replay endpoint, manual run) carries an entry-point field, set where the run starts and propagated alongside the correlation ID - [ ] Log levels are consistent: `error` = invariant broken, someone may act; `warn` = degraded but handled; `info` = significant business event; `debug` = off in production - [ ] No secrets, tokens, passwords, or unredacted PII in any log line (hard rule from `security-and-hardening`) - [ ] Fields are allowlisted — no whole request/response bodies, no auth headers diff --git a/references/performance-checklist.md b/references/performance-checklist.md index 86a41496bf..ba9744fe60 100644 --- a/references/performance-checklist.md +++ b/references/performance-checklist.md @@ -8,6 +8,7 @@ Quick reference checklist for web application performance. Use alongside the `pe - [TTFB Diagnosis](#ttfb-diagnosis) - [Frontend Checklist](#frontend-checklist) - [Backend Checklist](#backend-checklist) +- [Caching Strategies](#caching-strategies) - [Measurement Commands](#measurement-commands) - [Common Anti-Patterns](#common-anti-patterns) @@ -92,6 +93,30 @@ When TTFB is slow (> 800ms), check each component in DevTools Network waterfall: - [ ] Connection pooling configured - [ ] Slow query logging enabled +#### Query plans +- [ ] `EXPLAIN ANALYZE` captured **before** the fix, not just after — it is the baseline +- [ ] `Seq Scan` on a large table understood: index missing, unusable, or genuinely not worth it +- [ ] Estimated vs actual `rows=` within an order of magnitude (if not, refresh statistics before touching indexes) +- [ ] No `Sort` node that a composite index could absorb +- [ ] Plan re-checked after the change — an index that did not change the plan gets reverted + +#### Index strategy +- [ ] Composite index column order is equality first, then range/sort +- [ ] Index covers the query shape (filter + sort), not just one column in isolation +- [ ] Covering index considered for hot read paths (index-only scan avoids the heap fetch) +- [ ] Not indexing low-selectivity columns *for the dominant value*; a partial index still serves the rare-value query (`WHERE status = 'failed'`) +- [ ] Expression index used where the query applies a function (`lower(email)`) +- [ ] Full-text or trigram index used for leading-wildcard search, not a B-tree +- [ ] Write cost measured on write-heavy tables (every index taxes every `INSERT`/`UPDATE`) +- [ ] Unused and duplicate indexes dropped (they cost writes and buy nothing) + +#### Connection pooling +- [ ] One pool per process, not per request or per module +- [ ] `instances × pool max` stays under the database's `max_connections` +- [ ] `connectionTimeoutMillis` set so exhaustion fails fast instead of queueing forever +- [ ] Exhaustion diagnosed before resizing: find what holds connections (long transactions, missing `await`, leaked clients) +- [ ] Serverless / autoscaling fronted by a multiplexing proxy (pgbouncer, RDS Proxy) rather than a larger pool + ### API - [ ] Response times < 200ms (p95) - [ ] No synchronous heavy computation in request handlers @@ -105,6 +130,58 @@ When TTFB is slow (> 800ms), check each component in DevTools Network waterfall: - [ ] Horizontal scaling configured (if needed) - [ ] Health check endpoint for load balancer +## Caching Strategies + +The decision material (which layer, which invalidation strategy, what never to cache) lives in the `performance-optimization` skill. This section covers the read/write patterns and the checklist. + +### Read and write patterns + +| Pattern | How it works | Use when | Watch out for | +|---|---|---|---| +| **Cache-aside** (lazy) | App checks cache, on miss reads origin and populates | Default choice; read-heavy, tolerant of a cold first hit | Every miss hits the origin, so it needs stampede protection | +| **Read-through** | Cache layer itself loads on miss | You want the load path in one place, not at every call site | Hides origin latency; a slow origin looks like a slow cache | +| **Write-through** | Write goes to cache and origin together, synchronously | Reads must never see a stale value after a write | Adds cache latency to every write | +| **Write-behind** (write-back) | Write hits cache, origin updated asynchronously | Write-heavy, and the origin is the bottleneck | Data loss window if the cache dies before the flush. Needs durability you can defend | + +### Negative caching + +Cache the *absence* of a result too. A key that misses on every lookup (a nonexistent user ID probed in a loop, a 404 asset) sends every request to the origin, which is a cache that only protects the happy path. + +- Store an explicit "not found" sentinel with a **shorter** TTL than positive entries +- Keep the negative TTL short enough that a newly created record appears promptly +- Never let an origin *error* become a negative cache entry, or one failing minute becomes many + +### Request coalescing (stampede protection) + +One recompute, N waiters. Prevents a hot key's expiry from delivering the full concurrent load to the origin: + +```typescript +const inFlight = new Map>(); + +function loadOnce(key: string, fetcher: () => Promise): Promise { + const existing = inFlight.get(key) as Promise | undefined; + if (existing) return existing; + const p = fetcher().finally(() => inFlight.delete(key)); + inFlight.set(key, p); + return p; +} +``` + +For a shared cache, the same idea needs a distributed lock, or `stale-while-revalidate` so waiters serve the stale value instead of blocking. + +### Cache checklist +- [ ] The cached call was measured as expensive first (caching a fast call adds a hop and buys nothing) +- [ ] Read/write ratio justifies the cache (re-read far more often than written) +- [ ] Cache key includes every input the response varies on: tenant, viewer, locale, permissions, feature flags +- [ ] No per-user data cached under a key that does not identify the user +- [ ] One invalidation strategy chosen (TTL, event/tag, or versioned keys), not an accidental mix +- [ ] Acceptable staleness window written down, not implied by whatever TTL was typed +- [ ] Stampede protection on hot keys (coalescing, lock, or `stale-while-revalidate`) +- [ ] Negative results cached with a shorter TTL; origin errors never cached +- [ ] Eviction policy and memory ceiling set (an unbounded cache is a memory leak) +- [ ] Hit rate monitored — a cache nobody measures is an assumption, and a low hit rate is pure overhead +- [ ] Nothing cached whose staleness is a correctness bug (balances, permissions, inventory at checkout) + ## Measurement Commands ### INP field data and DevTools workflow @@ -146,6 +223,12 @@ onINP(({ value, attribution }) => { | N+1 queries | Linear DB load growth | Use joins, includes, or batch loading | | Unbounded queries | Memory exhaustion, timeouts | Always paginate, add LIMIT | | Missing indexes | Slow reads as data grows | Add indexes for filtered/sorted columns | +| Indexing without reading the plan | Write cost paid, read gain unproven | `EXPLAIN ANALYZE` before and after; revert if the plan is unchanged | +| Redundant / unused indexes | Every write pays for them | Audit usage stats, drop what nothing reads | +| Connection pool per request | Exhausts `max_connections` under load | One pool per process; proxy for serverless | +| Cache key missing the viewer | One user's data served to another | Key on tenant, viewer, locale, permissions | +| Unbounded cache | Memory leak wearing an optimization's clothing | Set eviction policy and a memory ceiling | +| Cache stampede on a hot key | Origin takes full concurrent load at expiry | Coalesce misses, or `stale-while-revalidate` | | Layout thrashing | Jank, dropped frames | Batch DOM reads, then batch writes | | Unoptimized images | Slow LCP, wasted bandwidth | Use WebP, responsive sizes, lazy load | | Large bundles | Slow Time to Interactive | Code split, tree shake, audit deps | diff --git a/references/security-checklist.md b/references/security-checklist.md index 0f656479b0..b7df3eb041 100644 --- a/references/security-checklist.md +++ b/references/security-checklist.md @@ -22,7 +22,7 @@ Quick reference for web application security. Use alongside the `security-and-ha Before reaching for controls, spend five minutes thinking like an attacker: -- [ ] Trust boundaries mapped (requests, uploads, webhooks, third-party APIs, LLM output) +- [ ] Trust boundaries mapped (requests, uploads, webhooks, third-party APIs, LLM output, and local values written by processes you don't control) - [ ] Assets named (credentials, PII, payment data, admin actions, money movement) - [ ] STRIDE run per boundary (Spoofing, Tampering, Repudiation, Info disclosure, DoS, Elevation) - [ ] Abuse cases written next to use cases ("how would I misuse this?") @@ -63,6 +63,46 @@ Before reaching for controls, spend five minutes thinking like an attacker: - [ ] HTML output encoded (use framework auto-escaping) - [ ] URLs validated before redirect (prevent open redirect) - [ ] Server-side URL fetches allowlisted; private/reserved IPs blocked (prevent SSRF) +- [ ] Destructive path operations (delete/move/overwrite): symlinks resolved, allowlisted root, minimum depth, ownership evidence read before the call + +### Destructive Path Operations + +Containment for a target named by data. Resolve first, then decide — and treat the +result as a candidate, not as authorization: + +```typescript +import { realpath, readFile } from 'node:fs/promises'; +import { resolve, relative, isAbsolute, join, sep } from 'node:path'; + +const ALLOWED_ROOTS = ['/var/lib/myapp/sessions']; // an allowlist, not a pattern +const MIN_DEPTH = 1; // so a root is never the target + +async function resolveDeletable(candidate: string, expectedOwner: string) { + const target = await realpath(resolve(candidate)); // symlinks resolved BEFORE the check + const inRoot = ALLOWED_ROOTS.some((root) => { + const rel = relative(root, target); + // `rel === '..'` / `'../'` only — a plain `startsWith('..')` would also + // reject a legitimate child named `..cache`. + if (rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return false; + return rel.split(sep).length >= MIN_DEPTH; + }); + if (!inRoot) throw new Error(`refusing: outside allowed roots (${target})`); + + const owner = await readFile(join(target, '.owner'), 'utf8').catch(() => null); + if (owner?.trim() !== expectedOwner) throw new Error(`refusing: unproven owner (${target})`); + return target; +} +``` + +What this does not do, and must be said where the snippet is copied from: + +- **The marker is self-attestation.** Anything that can write inside the root can write + `.owner`. `expectedOwner` has to come from authenticated state, and the marker needs + integrity protection (restrictive ownership, or a MAC) before it is authorization + rather than a consistency check against a misderived target. +- **Returning a path leaves a check/use race.** Where an untrusted process can swap an + ancestor between the check and the call, operate on a descriptor with no-follow, + beneath-the-root semantics, or guarantee the hierarchy is immutable for the duration. ## Security Headers diff --git a/scripts/lib/skill-lint-test.js b/scripts/lib/skill-lint-test.js new file mode 100644 index 0000000000..af898c0b11 --- /dev/null +++ b/scripts/lib/skill-lint-test.js @@ -0,0 +1,141 @@ +#!/usr/bin/env node + +'use strict'; + +const assert = require('node:assert/strict'); +const { test } = require('node:test'); + +const { lintSkillContent } = require('./skill-lint.js'); + +const KNOWN = new Set(['alpha', 'beta']); + +/** A SKILL.md body carrying every required section, so tests can isolate frontmatter. */ +function withAllSections(frontmatter) { + return [ + frontmatter, + '', + '## Overview', + 'x', + '## When to Use', + 'x', + '## Common Rationalizations', + 'x', + '## Red Flags', + 'x', + '## Verification', + 'x', + '', + ].join('\n'); +} + +const VALID_FRONTMATTER = [ + '---', + 'name: alpha', + 'description: Designs alphas. Use when building one.', + '---', +].join('\n'); + +// ─── Section exemptions ────────────────────────────────────────────────────── + +test('a directory named after an Object.prototype key is not exempt from section checks', () => { + // `constructor` satisfies KEBAB_CASE, and `dirName in SECTION_EXEMPT_SKILLS` + // finds it on the prototype chain — silently skipping every section check. + const content = [ + '---', + 'name: constructor', + 'description: Does a thing. Use when you need it.', + '---', + '', + 'no sections here', + '', + ].join('\n'); + + const { errors, exempt } = lintSkillContent('constructor', content, KNOWN); + + assert.equal(exempt, false, 'exemptions must come from the allowlist, not the prototype chain'); + assert.equal(errors.filter(e => /Missing required section/.test(e)).length, 5); +}); + +test('a genuinely allowlisted skill is still exempt', () => { + const content = [ + '---', + 'name: using-agent-skills', + 'description: Routes to other skills. Use when choosing one.', + '---', + '', + 'no sections here', + '', + ].join('\n'); + + const { errors, exempt } = lintSkillContent('using-agent-skills', content, KNOWN); + + assert.equal(exempt, true); + assert.deepEqual(errors.filter(e => /Missing required section/.test(e)), []); +}); + +test('a skill claiming its own exemption without being allowlisted fails loud', () => { + const content = withAllSections( + ['---', 'name: alpha', 'description: Designs alphas. Use when building one.', 'exempt: sections', '---'].join('\n') + ); + const { errors } = lintSkillContent('alpha', content, KNOWN); + assert.equal(errors.length, 1); + assert.match(errors[0], /not in the validator's SECTION_EXEMPT_SKILLS allowlist/); +}); + +// ─── Guardrails on the rules this change sits beside ───────────────────────── +// Deliberately narrow: #428 rewrites frontmatter parsing and the cross-reference +// patterns, so asserting their behaviour here would collide with that work. + +test('a fully valid skill produces no errors', () => { + const { errors } = lintSkillContent('alpha', withAllSections(VALID_FRONTMATTER), KNOWN); + assert.deepEqual(errors, []); +}); + +test('reports a description with no trigger clause', () => { + const content = withAllSections( + ['---', 'name: alpha', 'description: Designs alpha things and nothing more.', '---'].join('\n') + ); + const { errors } = lintSkillContent('alpha', content, KNOWN); + assert.equal(errors.length, 1); + assert.match(errors[0], /no 'when to use' trigger/); +}); + +test('reports frontmatter name that disagrees with the directory', () => { + const content = withAllSections( + ['---', 'name: beta', 'description: Designs alphas. Use when building one.', '---'].join('\n') + ); + const { errors } = lintSkillContent('alpha', content, KNOWN); + assert.equal(errors.length, 1); + assert.match(errors[0], /does not match directory name/); +}); + +test('reports a workflow step declared without a matching process section', () => { + const content = withAllSections(VALID_FRONTMATTER).replace( + '## Common Rationalizations', + [ + '## The Optimization Workflow', + '', + '```', + '1. MEASURE → Establish a baseline', + '2. GUARD → Prevent regression', + '```', + '', + '### Step 1: Measure', + '', + 'Measure first.', + '', + '## Common Rationalizations', + ].join('\n'), + ); + + const { errors } = lintSkillContent('alpha', content, KNOWN); + + assert.equal(errors.length, 1); + assert.match(errors[0], /Workflow declares Step 2 but has no matching process section/); +}); + +test('reports a missing frontmatter block', () => { + const { errors } = lintSkillContent('alpha', '## Overview\nx\n', KNOWN); + assert.equal(errors.length, 1); + assert.match(errors[0], /Missing or malformed YAML frontmatter/); +}); diff --git a/scripts/lib/skill-lint.js b/scripts/lib/skill-lint.js index 2513bf7c05..d63a994e48 100644 --- a/scripts/lib/skill-lint.js +++ b/scripts/lib/skill-lint.js @@ -177,7 +177,7 @@ function lintSkillContent(dirName, content, knownSkills) { // If a skill's frontmatter tries to declare its own exemption, fail loud — // that's a sign someone is trying to bypass the validator. if (fm.type === 'meta' || fm.exempt === 'sections') { - if (!SECTION_EXEMPT_SKILLS[dirName]) { + if (!Object.hasOwn(SECTION_EXEMPT_SKILLS, dirName)) { errors.push( `Frontmatter declares 'type: meta' or 'exempt: sections' but '${dirName}' is not in ` + `the validator's SECTION_EXEMPT_SKILLS allowlist. ` + @@ -187,7 +187,11 @@ function lintSkillContent(dirName, content, knownSkills) { } // ── Required sections ──────────────────────────────────────────────────── - exempt = dirName in SECTION_EXEMPT_SKILLS; + // `Object.hasOwn`, not `in`: `in` walks the prototype chain, so a skill + // directory named `constructor` — which passes the kebab-case check — would + // otherwise resolve to Object.prototype.constructor and be silently exempt + // from every required-section check. + exempt = Object.hasOwn(SECTION_EXEMPT_SKILLS, dirName); if (!exempt) { // Strip fenced code blocks so headings inside examples/templates don't @@ -205,6 +209,27 @@ function lintSkillContent(dirName, content, knownSkills) { } } + // A named workflow that advertises numbered steps must document each step + // before the next level-two section. Otherwise the summary promises a + // process stage that the skill never teaches agents how to perform. + const workflowSections = content.matchAll( + /^## The [^\n]+ Workflow\s*\r?\n([\s\S]*?)(?=^## |(?![\s\S]))/gm + ); + for (const match of workflowSections) { + const section = match[1]; + const declared = [...section.matchAll(/^\s*(\d+)\.\s+[A-Z][A-Z -]*\s+→/gm)]; + if (declared.length < 2) continue; + + const documented = new Set( + [...section.matchAll(/^### Step\s+(\d+):/gm)].map(step => step[1]) + ); + for (const step of declared) { + if (!documented.has(step[1])) { + errors.push(`Workflow declares Step ${step[1]} but has no matching process section`); + } + } + } + // ── Cross-skill references ─────────────────────────────────────────────── const refs = extractSkillReferences(content); for (const ref of refs) { diff --git a/skills/constraint-driven-development/SKILL.md b/skills/constraint-driven-development/SKILL.md new file mode 100644 index 0000000000..3028719c0b --- /dev/null +++ b/skills/constraint-driven-development/SKILL.md @@ -0,0 +1,311 @@ +--- +name: constraint-driven-development +description: Establishes a project's quality bar as a written contract and stops agents quietly lowering it. Interviews the user on which dimensions matter, supplies sane default thresholds when they have no number in mind, records everything in CONSTRAINTS.md, and watches the diff for a weakened bar — new @ts-ignore or eslint-disable suppressions, skipped or deleted tests, assertions stripped out, unimplemented stubs, thresholds edited down. Use when no quality bar is written down, when the user says "set up constraints" or "define our standards", when the user wants dimensions they care about — accessibility, web performance, coverage — set up as enforced constraints, when an agent keeps silencing checks or skipping tests to get to green, when you need a coverage or performance threshold and don't know what number to pick, or when an agent writes more code than anyone will read. +--- + +# Constraint-Driven Development + +## Overview + +Other skills in this pack describe what good looks like. `code-review-and-quality` gives you five axes. `test-driven-development` gives you a cycle. `security-and-hardening` gives you a threat list. All of that lives in prose the agent reads and may or may not follow, and none of it survives the end of the session. + +This skill produces something different: a written record of **this project's** bar, with numbers, that outlives the conversation and can be checked mechanically. + +The reason matters. When you wrote the code, reading it told you whether it was any good. An agent writes more in an afternoon than you will read that week, so the judgement moves out of your head and into checks that run around the loop. Those checks need to exist, they need numbers you actually chose, and they need to fire close enough to the work that the agent fixes its own output. + +Spec-driven development says what to build. Test-driven development proves it works. Constraint-driven development defines what "good enough to ship" means, before anyone argues about it in a pull request. + +## When to Use + +Apply this skill when: + +- Starting a project or a significant feature and no quality bar is written down +- The user asks to "set up constraints", "add quality gates", "define our standards", or "stop the agent shipping junk" +- An agent is producing volume nobody is reading line by line +- CI has checks but nobody can say which ones block a merge and which ones are decoration +- Coverage, performance, or accessibility numbers get argued about per-PR instead of decided once +- You're about to run `/build auto` or any autonomous loop, and the only thing standing between it and main is a test suite the agent also wrote + +**When NOT to use:** + +- The project already has a `CONSTRAINTS.md` and the user isn't changing it — read it and follow it instead +- One-off scripts, spikes, throwaway prototypes +- The user wants a code review right now (`code-review-and-quality`) or a CI pipeline built (`ci-cd-and-automation`) +- Pre-product-market-fit code with a two-week expected lifetime — the floor below is still worth it, the rest isn't + +## Loading Constraints + +The interview needs a live user. **Don't run it in non-interactive contexts** (CI, `/loop`, autonomous runs). If constraints are missing and you're in one of those, apply the Floor below, note that you did, and flag the rest for a human. + +## The Process + +### Step 1: Detect before you ask + +Never ask what you can read. Before the first question, gather: + +| What | Where to look | +|------|---------------| +| Language and stack | `package.json`, `pyproject.toml`, `go.mod`, `Cargo.toml` | +| Test runner | dev dependencies, `test` script, existing test files | +| Existing linters | `eslint.config.*`, `biome.json`, `.ruff.toml` | +| Coverage today | `coverage/` output, or run the suite once | +| CI | `.github/workflows/`, `.gitlab-ci.yml` | +| Agent harness | `.claude/`, `.codex/`, `AGENTS.md` | + +Report what you found in two lines, then ask only what's left. + +### Step 2: Four questions, each with a default + +Follow the one-question-at-a-time discipline from `interview-me`, with one change: every question here has a default, so "I don't know" is a complete answer that still produces a working config. + +``` +Q1: Beyond the floor, which of these do you want enforced? + (a) Test coverage on new code + (b) Security scanning + (c) Performance budgets + (d) Accessibility + (e) Architecture boundaries +GUESS: (a) and (b) — you have a test runner already and you're handling user input. +DEFAULT if unsure: (a) and (b). +Say what each pick costs: (c) and (d) need a running URL, (e) needs a rules file written. +``` + +``` +Q2: When a check fails while the agent is mid-task, should it block or warn? +GUESS: Block. You're running agents unattended and a warning nobody reads is a warning. +DEFAULT if unsure: Block on the floor, warn on everything else for the first two weeks. +``` + +``` +Q3: Do you have target numbers in mind, or should I measure where you are today and hold that line? +GUESS: Measure. Most teams don't have a number, and an invented one gets ignored. +DEFAULT if unsure: Measure and hold. See "Ratchets" below. +``` + +``` +Q4: What's the slowest check you'll tolerate before the agent hands work back? +GUESS: About 90 seconds. Longer and you'll stop running it. +DEFAULT if unsure: 90 seconds at task end, unlimited in CI. +``` + +Stop at four. A twelve-question intake produces a config nobody understands and a user who regrets starting. + +### Step 3: Write CONSTRAINTS.md + +One file at the repo root. Any agent on any harness can read it, and a change to it shows up in review where it belongs. + +```markdown +# Constraints + +Last reviewed: 2026-08-08 by @addy + +## Floor (always enforced, no setup required) + +- No new suppression comments: `@ts-ignore`, `eslint-disable`, `# noqa`, `# type: ignore` +- No unimplemented stubs: `throw new Error("Not implemented")`, empty `catch {}` +- No skipped or deleted tests without a reason in the commit message +- No secrets in source +- This file does not get weakened to make a change pass + +## Enforced with numbers + +| Dimension | Rule | Checked by | Runs at | +|-----------|------|-----------|---------| +| Types | Zero type errors | `tsc --noEmit` | every edit | +| Lint | Zero errors from our config | `biome check` | every edit | +| Secrets | No secrets in source | `gitleaks detect --redact` | every edit | +| Coverage | Changed lines ≥ 80% covered | `vitest run --coverage` + git diff | task end, CI | +| Security: code | No high findings | `semgrep scan --config p/default` | CI | +| Security: deps | Nothing at high or above | `osv-scanner scan source -r .` | CI | +| Accessibility | Zero critical or serious | `axe $PREVIEW_URL --tags wcag2a,wcag2aa,wcag21aa` | preview deploy | +| Performance | LCP ≤ 2500ms, CLS ≤ 0.1 | `lighthouse $PREVIEW_URL --output=json` | preview deploy | + +Every row names the command that produces the verdict. A dimension with a +number and no command in this column is an aspiration, not a constraint. + +## Measured, not yet enforced + +| Metric | Today | Direction | +|--------|-------|-----------| +| Project coverage | 62.4% | must not fall | +| Bundle size (main) | 184 kB | must not grow | + +## Exceptions + +| ID | Rule | Path | Reason | Owner | Expires | +|----|------|------|--------|-------|---------| +| W1 | `no-explicit-any` | `src/legacy/**` | Rewrite tracked in ENG-441 | @addy | 2026-11-01 | +``` + +Then add one line to `AGENTS.md` and `CLAUDE.md`: `Read CONSTRAINTS.md before writing code. Do not weaken it to make a change pass.` + +### Step 4: Install what each dimension needs + +Picking a dimension means installing something. Don't leave the user with a number and no mechanism, and don't invent your own checker when a de facto one exists — these tools are listed because their rule formats and thresholds are what everything else in the ecosystem targets, so the team's existing config keeps working. + +| Dimension | Tool | Install | Run | Gate on | +|-----------|------|---------|-----|---------| +| Types (TS) | tsc | already there | `tsc --noEmit` | any error | +| Types (Python) | mypy | `pip install mypy` | `mypy .` | any error | +| Lint | your existing config | already there | `eslint .` / `biome check` / `ruff check` | any error | +| Coverage (JS) | your test runner | already there | `vitest run --coverage` (or `jest --coverage`) | coverage of changed lines | +| Coverage (Python) | pytest-cov | `pip install pytest-cov` | `pytest --cov --cov-report=lcov` | same | +| Security: code | Semgrep | `pipx install semgrep` | `semgrep scan --config p/default --config p/owasp-top-ten` | any high finding | +| Security: secrets | gitleaks | `brew install gitleaks` | `gitleaks detect --redact --no-banner` | any finding | +| Security: dependencies | osv-scanner | `brew install osv-scanner` | `osv-scanner scan source -r .` | high or above | +| Performance: page | Lighthouse | `npm i -D lighthouse` | `lighthouse $URL --output=json --quiet` | LCP, CLS, performance score | +| Performance: bundle | size-limit | `npm i -D size-limit` | `size-limit --json` | per-entry byte budget | +| Accessibility | axe-core | `npm i -D @axe-core/cli` | `axe $URL --tags wcag2a,wcag2aa,wcag21aa` | zero critical or serious | +| Architecture | dependency-cruiser | `npm i -D dependency-cruiser` | `depcruise --validate src` | any violation | +| Assertion quality | Stryker | `npm i -D @stryker-mutator/core` | `stryker run --mutate ` | mutation score | + +Five things that will bite you if you skip them: + +1. **`--redact` on gitleaks is not optional.** Without it the matched secret lands in the agent's transcript, which is how a leaked key ends up in a log, a summary, or a commit message. Report the rule and the location, never the value. +2. **Lighthouse and axe need a URL.** They only work against a running app, so they belong in the runtime stage against a preview deploy or a local server you start first. If the project has no URL to hit — a CLI, a library, a desktop app — say so and drop the dimension rather than inventing a check that can't run. +3. **Scope the expensive ones to the diff.** `stryker run --mutate` on the whole repo takes hours and gets turned off; on the files a change touched it takes under a minute. Same for Semgrep, which takes a path list. +4. **Coverage needs no second test run.** Read the lcov your suite already writes and intersect it with `git diff`. Running the suite twice to get a number is the fastest way to make people hate this. +5. **Semgrep's registry rules are free to run; check the licence before redistributing them.** `opengrep` is a drop-in fork with the same rule format and JSON output if that matters to your legal team. + +Add each one to the project's own script so it's reproducible without an agent: + +```json +{ + "scripts": { + "check:fast": "tsc --noEmit && eslint . && gitleaks detect --redact --no-banner", + "check:task": "npm run check:fast && vitest run --coverage", + "check:full": "npm run check:task && semgrep scan --config p/default && osv-scanner scan source -r ." + } +} +``` + +That mapping matters more than the tools. `check:fast` is what runs after an edit, `check:task` when the agent thinks it's done, `check:full` in CI. + +The commands now live in two places — the `Checked by` column in `CONSTRAINTS.md` and these scripts. `CONSTRAINTS.md` is the canonical source: it carries the reason alongside each command and it shows up in review. The scripts are convenience wrappers that must mirror it, not a second source of truth; if they drift, the file wins. + +### Step 5: Wire it to the lifecycle + +The single biggest mistake is running everything everywhere. A check that stalls the agent gets switched off, and a gate people switched off is worse than no gate, because the bar still looks like it exists. + +| Phase | Command | What runs | Budget | +|-------|---------|-----------|--------| +| BUILD | `/build` | Types, lint, secrets, the floor | under 5s, changed file only | +| VERIFY | `/test` | Related tests, coverage on changed lines | under 90s | +| REVIEW | `/review` | Everything, plus the guards below | minutes | +| SHIP | `/ship` | Direction checks, no regressions | CI | + +Two rules that keep this tolerable: + +1. **Scope to the diff.** Check the lines this change touched, not the whole repo. Coverage of changed lines is a number the agent can move; project coverage is one it inherited. +2. **Cost decides placement.** Anything over a few seconds moves out of the edit loop. Mutation testing on a whole repo takes hours; on the files a change touched it takes under a minute, which is the difference between a check people run and one they don't. + +### Step 6: Guard the bar itself + +Someone will point out that if the agent writes the code and the checks, the checks prove nothing. Half right, and worth engineering around. + +Agents don't craft clever loopholes. They hit a red check and take the cheapest road to green. Watch for these five moves in the diff, at review time: + +1. **The threshold moved.** A budget lowered, a severity dropped, a check removed from the fast stage. Compare `CONSTRAINTS.md` against its state at the branch point. +2. **A test got easier.** `.skip` added, a test file deleted, assertions pulled out of tests that stayed. +3. **A checker got silenced.** New `@ts-ignore` or `eslint-disable`. Four suppressions deserve special attention because they switch off a check you're relying on: `istanbul ignore` drops code from coverage instead of testing it, `Stryker disable` hides a surviving mutant, `nosemgrep` and `gitleaks:allow` do it for security findings. +4. **Work is unfinished.** A stub that throws, an empty `catch` turning a failure into silence, a `TODO` standing where the implementation should be. +5. **An exception appeared.** A new row in the Exceptions table nobody discussed. + +None of this needs tooling beyond `git diff`. Tightening the bar should be silent; loosening it should be loud. + +Unlike the numbered dimensions, the floor has no de facto tool of its own, so an agent asked to enforce it tends to write a checker from scratch, and two agents write two different ones. A reference implementation of these five checks ships with this skill in [references/floor-guard.md](references/floor-guard.md) (diff-scoped, exit `0`/`1`/`2`, patterns adaptable per ecosystem). Adapt that rather than reinventing it, for the same reason every dimension names a de facto tool: so the mechanism is the same across runs and stacks. + +**Not all checks are equally circular.** Rank them by one question: can the agent make this pass by writing code that doesn't work? + +- **External** — axe-core encodes WCAG, `osv-scanner` reads a vulnerability database, Lighthouse measures a real browser. The agent can't argue with these. +- **Project** — your lint rules, your layer boundaries. A human owns the file. +- **Suite** — your own tests. Most useful, and the only genuinely circular one. + +A bar made entirely of the third kind is worth less than one with an outside opinion in it. Check that at least one external constraint is present. + +### Step 7: Ratchets, when you don't have a number + +Set 80% coverage on a codebase at 62% and you get a red build forever, then a team that learns to ignore red builds. + +The alternative asks for no decision: record where you are, then refuse to get worse. Put it in the "Measured, not yet enforced" table with today's number and a direction. Every check compares against the recorded value, not an aspiration. When a number improves, update it; when it drops, that's the finding. + +This also answers a fair objection to training. Models are rewarded for passing tests, which you can evaluate in seconds. Architectural rot shows up over months and never reaches the weights. A ratchet is the missing penalty, written down where the build can see it. + +## Sane Defaults + +When the user has no opinion, use these. They're chosen to be met by most codebases on day one. + +| Constraint | Default | Why this number | +|------------|---------|-----------------| +| Coverage of changed lines | ≥ 80% | High enough to force a test, low enough to allow a config line | +| Project coverage | today's value, must not fall | No argument needed to adopt | +| Mutation score (if used) | ≥ 60% to start | Typical for a suite never mutated before; 80% is mature | +| Dependency vulnerabilities | nothing at high or above | Below that is mostly noise | +| LCP | ≤ 2500 ms | Core Web Vitals "good" threshold | +| CLS | ≤ 0.1 | Same | +| Accessibility | zero critical or serious axe violations | Moderate and minor are often debatable | +| Exception lifetime | 90 days | Long enough to plan the fix, short enough to remember | +| Ratchet tolerance | 0.5% | Absorbs drift when an unrelated file moves the number | + +State the number and the reason together. A threshold without a rationale gets deleted by the next person who hits it. + +## Escalation Path + +Constraints work at three levels of teeth. Start at the first. + +1. **Written only.** `CONSTRAINTS.md` exists and agents read it. Costs nothing, catches the honest mistakes, relies on the agent complying. +2. **Scripted.** An `npm run check` (or `make check`) that runs the fast checks, wired into your agent's post-edit hook and your CI. Deterministic, no new dependency. +3. **Tool-backed.** A dedicated runner that handles diff scoping, budgets, ratchets, and the guard checks. Use when the config outgrows a shell script. The floor-guard reference in [references/floor-guard.md](references/floor-guard.md) is the starting point for the guard-checks half of this. + +Most projects should stop at 2. Move to 3 when you're maintaining more than about thirty lines of check-running shell. + +**A first run can be floor-only.** The floor guard is diff-only and needs no installs, so you can enforce the floor on day one and add numbered dimensions as you install each tool, rather than standing up every checker before the first commit is protected. Security tools that install machine-wide (gitleaks, osv-scanner) can also run CI-only if you'd rather keep laptops clean; declare where each dimension runs in the `Runs at` column. + +## Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "We'll add constraints once the code settles" | Code settles around whatever was allowed while it was moving | +| "The tests are the constraints" | Tests you wrote prove you agree with yourself; they say nothing about coverage of new code, dependency risk, or bundle growth | +| "We can't hit 80% coverage" | Then don't set 80%. Set today's number and hold it | +| "This will slow the agent down" | Only if you put slow checks in the fast loop. That's a placement error, not an argument against constraints | +| "I'll remember what our standards are" | The agent won't, and it's writing most of the code | +| "Constraints will block us shipping" | An exception with an owner and a date unblocks you. Deleting the constraint unblocks everyone forever | + +## Red Flags + +Stop and reconsider if you notice: + +- The interview ran past four questions, or produced a config the user can't explain +- A budget was set that the codebase fails today, with no plan to reach it +- A dimension was written into CONSTRAINTS.md with a number but no tool behind it +- A checker was hand-rolled when a de facto one exists, so the team's existing config is ignored +- Every constraint is checked by the project's own test suite, with no external opinion +- `CONSTRAINTS.md` changed in the same commit as the feature that was failing +- An exception has no owner, or an expiry more than a year out +- The agent proposed relaxing a threshold instead of fixing the code +- Slow checks landed in the edit loop and someone has started passing `--no-verify` +- Nobody has opened `CONSTRAINTS.md` since it was written + +## Verification + +The skill was applied correctly when: + +- [ ] `CONSTRAINTS.md` exists, and every number in it has a stated reason +- [ ] The floor is enforced and passes on the current codebase without changes +- [ ] Every dimension the user picked has a tool installed and a command that runs today +- [ ] Each constraint says where it runs, and the fast stage stays under a few seconds +- [ ] At least one constraint is external (not judged by this project's own tests) +- [ ] Measured-only metrics record today's value and a direction +- [ ] Exceptions have an owner and an expiry date +- [ ] `AGENTS.md` or `CLAUDE.md` points at the file +- [ ] A trial run on the current branch produces no failures the user disagrees with + +## See Also + +- `interview-me` — the one-question-at-a-time discipline this skill's intake borrows +- `code-review-and-quality` — how to review; this skill decides what the review enforces +- `ci-cd-and-automation` — building the pipeline these constraints run in +- `test-driven-development` — the suite that coverage and mutation constraints measure +- `security-and-hardening` — what the security dimension should contain +- `performance-optimization` — where the performance numbers come from diff --git a/skills/constraint-driven-development/references/floor-guard.md b/skills/constraint-driven-development/references/floor-guard.md new file mode 100644 index 0000000000..81b4ca89bf --- /dev/null +++ b/skills/constraint-driven-development/references/floor-guard.md @@ -0,0 +1,99 @@ +# Floor guard: reference implementation + +Every numbered dimension in `CONSTRAINTS.md` maps to a de facto tool (Step 4). The **floor** does not: it is a diff-scoped check for the five moves in Step 6, and without a shipped reference every agent invents its own, so two runs (or a Python repo and a Go one) produce two different guards. That is the exact non-determinism this skill exists to remove. + +This is the reference. Adapt the patterns to your stack; keep the contract identical. + +## Contract + +- **Input:** the diff between the merge base and the working tree (added *and* removed lines, plus untracked files). A guard that reads only `git diff` misses new files and staged-but-uncommitted work. +- **Detects the five Step 6 moves:** a weakened threshold in `CONSTRAINTS.md`, a test made easier (`.skip`, a deleted test file, an assertion removed from a test that stayed), a silenced checker (a new suppression comment), unfinished work (a stub or empty `catch`), a new Exceptions row. +- **Exit codes:** `0` clean, `1` at least one floor violation (block the change), `2` the guard could not run (no merge base, not a git repo). Never let a `2` read as a `0`. +- **Reports the rule and the location, never the matched secret value.** Redaction is not optional (Step 4). +- **Tightening is silent, loosening is loud:** only surfaces moves that lower the bar. + +## Reference (Node, ~stack-agnostic patterns) + +```js +#!/usr/bin/env node +// floor-guard.mjs — diff-scoped enforcement of the CONSTRAINTS.md floor. +// Usage: node floor-guard.mjs [--base ] (default base: origin/main) +import { execFileSync } from 'node:child_process'; + +const base = (() => { + const i = process.argv.indexOf('--base'); + return i > -1 ? process.argv[i + 1] : 'origin/main'; +})(); + +const git = (args) => { + try { return execFileSync('git', args, { encoding: 'utf8' }); } + catch { return null; } +}; + +// Merge base; bail to exit 2 rather than pretending a shallow/rootless clone is clean. +const mergeBase = git(['merge-base', base, 'HEAD'])?.trim(); +if (!mergeBase) { console.error('floor-guard: no merge base against ' + base); process.exit(2); } + +// Unified diff plus untracked files (git diff alone cannot see new files). +const tracked = git(['diff', '--unified=0', mergeBase, '--']) ?? ''; +const untracked = (git(['ls-files', '--others', '--exclude-standard']) ?? '') + .split('\n').filter(Boolean) + .map((f) => git(['diff', '--no-index', '--unified=0', '/dev/null', f]) ?? '') + .join('\n'); +const diff = tracked + '\n' + untracked; + +const added = [], removed = []; +let file = ''; +for (const line of diff.split('\n')) { + if (line.startsWith('+++ ')) file = line.slice(6); + else if (line.startsWith('+') && !line.startsWith('+++')) added.push({ file, text: line.slice(1) }); + else if (line.startsWith('-') && !line.startsWith('---')) removed.push({ file, text: line.slice(1) }); +} + +const findings = []; +const flag = (rule, f, text) => findings.push({ rule, file: f, text: text.trim().slice(0, 120) }); + +// 1. Silenced checker — extend this list for your ecosystem. +const SUPPRESSIONS = /@ts-ignore|@ts-nocheck|eslint-disable|biome-ignore|# *noqa|# *type: *ignore|istanbul ignore|nosemgrep|gitleaks:allow|Stryker disable/; +// 4. Unfinished work. +const STUBS = /throw new (Error|NotImplemented).*[Nn]ot implemented|catch\s*\(\w*\)\s*\{\s*\}|catch\s*\{\s*\}|\bTODO\b|\bpass\s*# *stub/; +// 2. A test made easier (added skips). +const SKIPS = /\.(skip|todo)\b|\bxit\(|\bxdescribe\(|@pytest\.mark\.skip|t\.Skip\(/; + +for (const { file, text } of added) { + if (SUPPRESSIONS.test(text)) flag('silenced-checker', file, text); + if (STUBS.test(text)) flag('unfinished-work', file, text); + if (SKIPS.test(text)) flag('test-made-easier', file, text); + if (/CONSTRAINTS\.md$/.test(file) && /^\| *(W|E)\d+ *\|/.test(text)) flag('new-exception', file, text); +} + +// 2b. Assertion removed from a test file that still exists. +for (const { file, text } of removed) { + if (/\.(test|spec)\.|_test\.|test_/.test(file) && /\b(expect|assert|should)\b/.test(text)) { + flag('assertion-removed', file, text); + } +} + +// 1b/2c. Weakened threshold: a number in CONSTRAINTS.md that went down, or a floor bullet deleted. +const nums = (s) => (s.match(/\d+(\.\d+)?/g) || []).map(Number); +const removedConstraints = removed.filter((l) => /CONSTRAINTS\.md$/.test(l.file)); +const addedConstraints = added.filter((l) => /CONSTRAINTS\.md$/.test(l.file)); +for (const r of removedConstraints) { + const a = addedConstraints.find((x) => x.text.split(/[|:]/)[0] === r.text.split(/[|:]/)[0]); + if (a && nums(a.text).some((n, i) => nums(r.text)[i] !== undefined && n < nums(r.text)[i])) { + flag('threshold-lowered', r.file, r.text + ' -> ' + a.text); + } +} + +if (findings.length === 0) { console.log('floor-guard: clean'); process.exit(0); } +console.error('floor-guard: ' + findings.length + ' floor violation(s):'); +for (const f of findings) console.error(` [${f.rule}] ${f.file}: ${f.text}`); +console.error('\nEach is a move that lowers the bar. Fix the code, or route it through a tracked exception.'); +process.exit(1); +``` + +## Adapting it + +- **Patterns are the only stack-specific part.** Add your language's suppression and stub forms to the three regexes; the diff plumbing, the CONSTRAINTS.md checks, and the exit codes stay as-is. +- **A `.constraintsignore`** (one glob per line) lets you exempt a path the guard would otherwise flag; check each added line's file against it before flagging, so a genuine exception is a tracked file rather than a loosened rule. +- **This is a starting point, not a finished tool.** It is deliberately regex-shallow: it catches the cheap-road-to-green moves agents actually make, not a determined human hiding a change. That is the right trade for a check that runs on every diff. Once you outgrow it, move to a real runner (Escalation Path level 3). diff --git a/skills/context-engineering/SKILL.md b/skills/context-engineering/SKILL.md index be991103fe..04718d0b20 100644 --- a/skills/context-engineering/SKILL.md +++ b/skills/context-engineering/SKILL.md @@ -118,6 +118,8 @@ Long conversations accumulate stale context. Manage this: - **Summarize progress** when context is getting long: "So far we've completed X, Y, Z. Now working on W." - **Compact deliberately** — if the tool supports it, compact/summarize before critical work +For the proactive discipline that makes these last resorts unnecessary — what to cut first, what to protect, and when to start — see **Context Budget Management** below. + ## Context Packing Strategies ### The Brain Dump @@ -177,6 +179,49 @@ Key files: validation.ts, errors.ts, db.ts Load only the relevant section when working on a specific area. +## Context Budget Management + +The context window is not a filing cabinet — it's a working desk. As a session runs, conversation history, tool output, and exploration accumulate. Most of it becomes deadweight. Budget proactively: waiting until the window is full causes abrupt quality drops; managing regularly keeps the agent coherent through long tasks. + +**Start trimming at 75% capacity, not 100%.** By the time the window is genuinely full, the model's attention is already fragmented across too many signals. The 75% threshold gives room to compress gracefully rather than cut desperately mid-task. + +### What to cut first + +| Content | When to cut | +|---|---| +| Past failed attempts and their error output | Once you've moved past them — keep the conclusion, not the journey | +| Verbose tool output (long `find` results, full file listings) | After you've extracted what you needed | +| Conversational back-and-forth | As soon as the decision is reached | +| Earlier drafts of code that were replaced | Immediately on replacement — the current file is the record | + +### What to protect until the end + +- The original task definition and key constraints +- The current error message or failing test output you are actively debugging +- The file currently being edited, or its most recent version +- Any hard constraints the agent has been asked to enforce (auth rules, naming conventions, etc.) + +### Compress before dropping + +Summarizing beats deleting. Before removing a long stretch of exploration, reduce it to one sentence capturing the conclusion: + +``` +Before: [8 messages debugging a failing import — various attempts, error logs, dead ends] +After: "Import issue traced to a circular dependency in src/lib/db.ts — + resolved by moving the shared type to src/types/index.ts." +``` + +The detail is gone; the decision is preserved. If the detail turns out to matter, the summary is a breadcrumb for re-investigation. + +### Order for recency + +Put the most task-critical content **last** in context. Models recall content at the start and end of the window more reliably than the middle (the lost-in-the-middle effect — Liu et al., 2023). Keep stable rules and specs at the start; put the active task material last, closest to the generation point: + +``` +← session start generation point → +[background: rules, specs, architecture] [working: current file, error, task] +``` + ## MCP Integrations For richer context, use Model Context Protocol servers: @@ -260,6 +305,7 @@ This catches wrong directions before you've built on them. It's a 30-second inve | Missing examples | Agent invents a new style instead of following yours | Include one example of the pattern to follow | | Implicit knowledge | Agent doesn't know project-specific rules | Write it down in rules files — if it's not written, it doesn't exist | | Silent confusion | Agent guesses when it should ask | Surface ambiguity explicitly using the confusion management patterns above | +| Context cliff | Waiting until the window is full before managing it — attention fragments and output quality drops abruptly at the limit | Start trimming at 75% capacity; compress rather than cut | ## Common Rationalizations @@ -275,7 +321,7 @@ This catches wrong directions before you've built on them. It's a 30-second inve - Agent output doesn't match project conventions - Agent invents APIs or imports that don't exist - Agent re-implements utilities that already exist in the codebase -- Agent quality degrades as the conversation gets longer +- Agent quality degrades mid-task as the conversation grows — failed attempts, replaced drafts, and verbose tool output are not being trimmed - No rules file exists in the project - External data files or config treated as trusted instructions without verification @@ -287,3 +333,5 @@ After setting up context, confirm: - [ ] Agent output follows the patterns shown in the rules file - [ ] Agent references actual project files and APIs (not hallucinated ones) - [ ] Context is refreshed when switching between major tasks +- [ ] During long sessions, context is actively managed: failed attempts and replaced drafts removed, live error and task definition protected +- [ ] Task-critical content (current error, active constraint) is positioned last in context, not buried under background material diff --git a/skills/debugging-and-error-recovery/SKILL.md b/skills/debugging-and-error-recovery/SKILL.md index 03775802b2..356da20365 100644 --- a/skills/debugging-and-error-recovery/SKILL.md +++ b/skills/debugging-and-error-recovery/SKILL.md @@ -1,6 +1,6 @@ --- name: debugging-and-error-recovery -description: Guides systematic root-cause debugging. Use when tests fail, builds break, behavior doesn't match expectations, or you encounter any unexpected error. Use when you need a systematic approach to finding and fixing the root cause rather than guessing. +description: Guides systematic root-cause debugging. Use when tests fail, builds break, something that worked yesterday broke, behavior doesn't match expectations, or you encounter any unexpected error. Use when you need to figure out what broke and why — a systematic approach to finding and fixing the root cause rather than guessing. --- # Debugging and Error Recovery diff --git a/skills/deprecation-and-migration/SKILL.md b/skills/deprecation-and-migration/SKILL.md index 765bdde632..7bf884ca57 100644 --- a/skills/deprecation-and-migration/SKILL.md +++ b/skills/deprecation-and-migration/SKILL.md @@ -1,6 +1,6 @@ --- name: deprecation-and-migration -description: Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when deciding whether to maintain or sunset existing code. +description: Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code. --- # Deprecation and Migration diff --git a/skills/documentation-and-adrs/SKILL.md b/skills/documentation-and-adrs/SKILL.md index 7faf52c955..94d1c3622a 100644 --- a/skills/documentation-and-adrs/SKILL.md +++ b/skills/documentation-and-adrs/SKILL.md @@ -1,6 +1,6 @@ --- name: documentation-and-adrs -description: Records decisions and documentation. Use when making architectural decisions, changing public APIs, shipping features, or when you need to record context that future engineers and agents will need to understand the codebase. +description: Records decisions and documentation. Use when you need to document an architecture decision (ADR) or the reasoning behind a design choice, when changing public APIs, shipping features, or when you need to record context that future engineers and agents will need to understand the codebase. --- # Documentation and ADRs diff --git a/skills/doubt-driven-development/SKILL.md b/skills/doubt-driven-development/SKILL.md index ea46342c5d..472c35ab9f 100644 --- a/skills/doubt-driven-development/SKILL.md +++ b/skills/doubt-driven-development/SKILL.md @@ -1,6 +1,6 @@ --- name: doubt-driven-development -description: Subjects every non-trivial decision to a fresh-context adversarial review before it stands. Use when correctness matters more than speed, when working in unfamiliar code, when stakes are high (production, security-sensitive logic, irreversible operations), or any time a confident output would be cheaper to verify now than to debug later. +description: Subjects every non-trivial decision to a fresh-context adversarial review before it stands. Use when you want every assumption cross-examined before proceeding, when stress-testing a plan for hidden failure modes, when correctness matters more than speed, when working in unfamiliar code, when stakes are high (production auth, security-sensitive logic, a high-stakes migration, irreversible operations), or any time a confident output would be cheaper to verify now than to debug later. --- # Doubt-Driven Development diff --git a/skills/git-workflow-and-versioning/SKILL.md b/skills/git-workflow-and-versioning/SKILL.md index 6b33aefe60..0e03a2323e 100644 --- a/skills/git-workflow-and-versioning/SKILL.md +++ b/skills/git-workflow-and-versioning/SKILL.md @@ -1,6 +1,6 @@ --- name: git-workflow-and-versioning -description: Structures git workflow practices. Use when making any code change. Use when committing, branching, resolving conflicts, or when you need to organize work across multiple parallel streams. Use when cutting a release, choosing a semantic version bump, tagging, or writing a changelog. +description: Structures git workflow practices. Use when making any code change. Use when committing, branching, resolving conflicts, splitting uncommitted work in a messy working tree into clean atomic commits, opening or reviewing a pull request (PR), pushing to a remote, or when you need to organize work across multiple parallel streams. Use when cutting a release, choosing a semantic version bump, tagging, or writing a changelog. --- # Git Workflow and Versioning diff --git a/skills/incremental-implementation/SKILL.md b/skills/incremental-implementation/SKILL.md index 6df12f9a87..9c4f49bc84 100644 --- a/skills/incremental-implementation/SKILL.md +++ b/skills/incremental-implementation/SKILL.md @@ -1,6 +1,6 @@ --- name: incremental-implementation -description: Delivers changes incrementally. Use when implementing any feature or change that touches more than one file. Use when you're about to write a large amount of code at once, or when a task feels too big to land in one step. +description: Delivers changes incrementally in thin, verifiable slices. Use when implementing any feature or change that touches more than one file, or when picking up the next task from a plan. Use when rolling a change out behind a feature flag, when you're about to write a large amount of code at once, or when a task feels too big to land in one step. --- # Incremental Implementation diff --git a/skills/observability-and-instrumentation/SKILL.md b/skills/observability-and-instrumentation/SKILL.md index 7d56593ec5..84d9cb3734 100644 --- a/skills/observability-and-instrumentation/SKILL.md +++ b/skills/observability-and-instrumentation/SKILL.md @@ -88,6 +88,21 @@ app.use((req, res, next) => { }); ``` +**When several entry points write to one log, name the entry point.** A correlation ID identifies a run; it does not say which code path started it. The same job reached by a scheduler, by a replay endpoint, and by a manual CLI run produces interchangeable lines in one sink, so attributing a line falls back to elimination — cross-reading the scheduler's history, the process table, a deploy log — and that argument holds only as long as those external records happen to still exist. Stamp the entry point where the run starts, next to the correlation ID, and propagate both the same way: + +```typescript +// One helper for every entry point: the run's own logger carries both fields. +// `entryPoint`, not `source` — ECS reserves `source.*` for network fields. +export const runLog = (entryPoint: 'scheduler' | 'replay_endpoint' | 'cli', runId: string) => + logger.child({ entryPoint, requestId: runId }); + +// scheduler tick -> runLog('scheduler', crypto.randomUUID()) +// POST /jobs/:id/replay -> runLog('replay_endpoint', req.id) +// CLI invocation -> runLog('cli', process.env.RUN_ID ?? crypto.randomUUID()) +``` + +Both fields have to cross the same boundaries as the correlation ID — queue metadata, HTTP headers — or a worker re-derives the entry point and guesses. A field that merely correlates with an entry point is a hint, not an attribution: anything that can invoke the job can reproduce it. + **Never log secrets, tokens, passwords, or full PII.** This is a hard rule from the `security-and-hardening` skill — telemetry pipelines are a classic data-leak path. Allowlist fields; don't log whole request bodies. ### 4. Metrics @@ -154,6 +169,24 @@ Rules for every alert you create: 3. **It has a threshold and duration** justified by the SLO or by historical data, not by a guess. 4. Use two severities only: **page** (user-facing, act now) and **ticket** (degradation, act this week). A third tier becomes noise that trains people to ignore everything. +#### Writing Runbooks + +Rule 2 above requires every alert to link to a runbook. A runbook's job is to answer three questions without requiring the reader to think: what is happening, what to check first, and who to call if that doesn't resolve it. Store in `docs/runbooks/` named after the alert. + +**Minimum viable runbook (three lines):** + +```markdown +# Runbook: High Error Rate on /api/tasks +**Means:** DB connection pool likely exhausted, or a bad deploy. +**First check:** `SELECT count(*) FROM pg_stat_activity WHERE backend_type = 'client backend';` + — if count > pool limit, see Step 2. (Swap in the equivalent for your database.) +**Escalate to:** #db-oncall or engineering on-call rotation. +``` + +**When to expand beyond three lines:** add steps only when the first check alone isn't enough to decide. A five-step runbook that covers the three most common causes is better than a twenty-step document that covers every edge case and gets skimmed. + +**Keep runbooks current.** Update the runbook as part of closing every incident it was used in — a stale runbook builds false confidence. If a step was wrong or missing, fix it before marking the incident resolved. + ### 7. Verify the telemetry itself Instrumentation is code; it can be wrong. Before calling the work done, trigger the paths and look at the actual output: @@ -180,6 +213,7 @@ Instrumentation is code; it can be wrong. Before calling the work done, trigger - A feature PR with retries, queues, or external calls and zero new telemetry - Log lines built by string interpolation instead of structured fields - No correlation/request ID — each log line is an orphan +- One log stream fed by a scheduler, a webhook, and manual runs, with no field naming which one produced the line - Metrics labeled with user IDs, raw URLs, or error message text (cardinality bomb) - Latency tracked as an average with no percentiles - Alerts that fire daily and get acknowledged without action @@ -193,6 +227,7 @@ After instrumenting a feature, confirm: - [ ] The on-call questions for this feature are written down, and each signal maps to one - [ ] All log output is structured (JSON), with stable event names and a correlation ID on every line +- [ ] Every log sink written by more than one entry point carries an entry-point field, set where the run starts and propagated with the correlation ID rather than inferred downstream - [ ] No secrets, tokens, or unredacted PII in any log line (spot-check actual output) - [ ] RED metrics exist for every new endpoint and every external dependency, with bounded label sets - [ ] Latency is a histogram; p95/p99 are queryable diff --git a/skills/performance-optimization/SKILL.md b/skills/performance-optimization/SKILL.md index a4e968e57e..cbc7e950a6 100644 --- a/skills/performance-optimization/SKILL.md +++ b/skills/performance-optimization/SKILL.md @@ -149,6 +149,58 @@ const tasks = await db.tasks.findMany({ }); ``` +#### Queries That Ignore Their Index + +"Add an index" is the guess. The query plan is the measurement: + +```sql +EXPLAIN ANALYZE +SELECT id, title FROM tasks +WHERE owner_id = 42 ORDER BY created_at DESC LIMIT 20; +``` + +Three things in the output decide the fix: + +| What you see | What it means | +|---|---| +| `Seq Scan` on a large table where you expected an index | No usable index for this predicate | +| Estimated `rows=` off from actual by an order of magnitude | Stale statistics; the planner is choosing on bad information | +| A `Sort` node above the scan | The index covers the filter but not the `ORDER BY` | + +Index for the **shape of the query**, not the column in isolation. In a composite index, equality columns come first, then the range or sort column: + +```sql +CREATE INDEX idx_tasks_owner_created ON tasks (owner_id, created_at DESC); +``` + +**When an index will not help:** + +| Situation | Why | +|---|---| +| Low selectivity, querying the dominant value (a `status` column that is 95% `active`, filtered on `active`) | A sequential scan is genuinely cheaper; the planner will ignore the index. Filtering on the rare value is the opposite case, and a partial index serves it well | +| Leading wildcard (`LIKE '%term'`) | A B-tree cannot seek without a prefix; needs trigram or full-text | +| Function on the column (`WHERE lower(email) = ?`) | The plain column index is unusable; index the expression instead | +| Write-heavy table | Every index is a tax on every `INSERT`/`UPDATE`; measure the write cost, not just the read gain | + +Re-run `EXPLAIN ANALYZE` after. An index that did not change the plan is a revert (Step 4), and it is not free: it still costs on every write. + +#### Connection Pool Exhaustion + +The signature is distinctive: **every** endpoint slows at once, the slow time is spent waiting for a connection rather than executing, and the database reports mostly idle sessions. + +```typescript +// BAD: a pool per request or per module — under serverless this multiplies +// by instance count and exhausts the database's connection limit +// GOOD: one pool per process, sized against the database's ceiling +const pool = new Pool({ + max: 10, // instances × max must stay under max_connections + idleTimeoutMillis: 30_000, + connectionTimeoutMillis: 5_000, // fail fast instead of queueing forever +}); +``` + +**Bigger is not faster.** A pool larger than what the database can execute concurrently just relocates the queue from your app to the database, where it is harder to see. When instance count is unbounded (serverless, autoscaling), a proxy that multiplexes connections (pgbouncer, RDS Proxy) is the fix, not a higher `max`. + #### Missing Image Optimization (Frontend) ```html @@ -264,6 +316,16 @@ function App() { #### Missing Caching (Backend) +Cache what is expensive to produce and read far more often than it changes. Caching a query that was already fast adds a network hop, a staleness bug, and an eviction policy to maintain, in exchange for nothing. + +**Pick the layer deliberately:** + +| Layer | Visible to | Use when | Cost | +|---|---|---|---| +| In-process (`Map`, LRU) | One instance | Small, hot, per-instance staleness is acceptable | Each instance drifts independently; invalidation reaches only one | +| Shared (Redis, Memcached) | All instances | Instances must agree, or the value is expensive to recompute | A network hop, and another service to run and monitor | +| CDN / edge | Everyone, per URL | Responses are public and identical for a given key | Invalidation is the hard part; assume you cannot recall a bad response quickly | + ```typescript // Cache frequently-read, rarely-changed data const CACHE_TTL = 5 * 60 * 1000; // 5 minutes @@ -289,6 +351,20 @@ app.use('/static', express.static('public', { res.set('Cache-Control', 'public, max-age=300'); // 5 minutes ``` +**Key design decides correctness.** Every input that changes the response belongs in the key: tenant, locale, permissions, feature flags. A key that omits the viewer is how one user's data gets served to another, and that ships as a performance win. + +**Choose one invalidation strategy, not three:** + +| Strategy | Trade-off | +|---|---| +| TTL | Simplest. You accept staleness up to the TTL, so state the acceptable window explicitly | +| Event or tag based | Fresh on write, but writers now have to know the cache topology | +| Versioned keys (`user:42:profile:v7`) | Never invalidate, just stop reading old keys. Costs memory until eviction | + +**Guard against the stampede.** A hot key expires, every concurrent request misses together, and the origin takes the full load at once, which is how a cache turns into an outage instead of preventing one. Serve stale while a single request recomputes (`stale-while-revalidate`), or coalesce concurrent misses behind one in-flight promise so N waiters cause one recompute. + +**Do not cache:** anything whose staleness is a correctness bug (balances, permissions, inventory at checkout), or per-user data under a key that does not identify the user. See `../../references/performance-checklist.md` for request coalescing, write strategies, negative caching, and the cache checklist. + ### Step 4: Verify (Keep or Revert) A fix is a hypothesis until you re-measure. This step decides whether it survives. @@ -324,9 +400,24 @@ Reverted work leaves no trace in git history, which is exactly why the same dead A section in the PR description or a `PERF.md` in the repo both work. What matters is that the next person (or the next agent) reads it before proposing an experiment, and doesn't re-run one that already failed. -## Performance Budget +### Step 5: Guard Against Regression + +Guard the metric the user actually feels, not every available number. Use the +same LCP, INP, p95 latency, or other primary metric that justified the fix. + +Use two complementary layers when the surface is user-facing: + +- **Synthetic CI gate:** Catch reproducible regressions before merge with a + performance budget. Repeat noisy measurements or compare a median/trend so + normal run-to-run variance does not turn the gate into a flaky check. +- **Field monitoring:** Alert on a meaningful p75 movement in RUM data. Use + attributed `web-vitals` data to locate the cause; treat CrUX's rolling window + as confirmation rather than an immediate alert. + +When either guard fires, return to Step 1 and establish a fresh baseline before +proposing another fix. -Set budgets and enforce them: +**Set budgets and enforce them:** ``` JavaScript bundle: < 200KB gzipped (initial load) @@ -361,6 +452,9 @@ For detailed performance checklists, optimization commands, and anti-pattern ref | "This optimization is obvious" | If you didn't measure, you don't know. Profile first. | | "Users won't notice 100ms" | Research shows 100ms delays impact conversion rates. Users notice more than you think. | | "The framework handles performance" | Frameworks prevent some issues but can't fix N+1 queries or oversized bundles. | +| "The query is slow, add an index" | Read the plan first. The index may already exist and be unusable, and every index taxes writes forever. | +| "Just cache it" | Caching an already-cheap call buys nothing and adds a staleness bug. Cache what is expensive *and* re-read far more than written. | +| "Raise the pool size, we're running out of connections" | A pool bigger than the database can serve moves the queue somewhere less visible. Find what holds connections. | | "It didn't help much, but it doesn't hurt" | Neutral changes are a revert. You pay maintenance on them forever and got nothing back. | | "We already wrote it, may as well keep it" | Sunk cost. The measurement doesn't care how long the change took to write. | | "The improvement is obvious, no need to re-measure" | Then re-measuring is cheap and proves it. Unmeasured wins are how neutral complexity lands. | @@ -369,6 +463,10 @@ For detailed performance checklists, optimization commands, and anti-pattern ref - Optimization without profiling data to justify it - N+1 query patterns in data fetching +- An index added without a query plan before and after to justify it +- A cache key that omits an input the response depends on (tenant, locale, viewer) +- A cache with no stated staleness window and no invalidation strategy +- Connection pool size raised in response to exhaustion, without finding what holds connections - List endpoints without pagination - Images without dimensions, lazy loading, or responsive sizes - Bundle size growing without review @@ -392,5 +490,7 @@ After any performance-related change: - [ ] Core Web Vitals are within "Good" thresholds - [ ] Bundle size hasn't increased significantly - [ ] No N+1 queries in new data fetching code -- [ ] Performance budget passes in CI (if configured) +- [ ] Any new index is justified by a query plan before and after, and its write cost was considered +- [ ] Any new cache states what it keys on and how it goes stale +- [ ] The measured user-facing metric has a synthetic budget or field monitor that can detect regression - [ ] Existing tests still pass (optimization didn't break behavior) diff --git a/skills/planning-and-task-breakdown/SKILL.md b/skills/planning-and-task-breakdown/SKILL.md index b10995ce30..296249b643 100644 --- a/skills/planning-and-task-breakdown/SKILL.md +++ b/skills/planning-and-task-breakdown/SKILL.md @@ -147,6 +147,13 @@ If a task is L or larger, it should be broken into smaller tasks. An agent perfo Create the `tasks/` directory if it does not exist. +**Never overwrite an incomplete plan.** Before writing `tasks/plan.md` or `tasks/todo.md`, check whether they already exist and still contain unchecked tasks: + +- Same work being replanned (the user asked to revise or extend this plan) → update the existing files in place. +- Different work → **stop and ask.** The unchecked tasks may be mid-build in another session. Do not delete, overwrite, or rename the existing files on your own; present the conflict and let the user decide (finish the old plan first, explicitly discard it, or tell you where the new plan should go). + +The same rule applies to an external task list target: never bulk-close or delete another plan's open tracker items to make room for new ones. + ### Task List Target The task list target is where tasks and checkpoints are recorded. It is defined once, here; every other reference in this skill defers to it. @@ -219,10 +226,12 @@ When multiple agents or sessions are available: | "The tasks are obvious" | Write them down anyway. Explicit tasks surface hidden dependencies and forgotten edge cases. | | "Planning is overhead" | Planning is the task. Implementation without a plan is just typing. | | "I can hold it all in my head" | Context windows are finite. Written plans survive session boundaries and compaction. | +| "The old `tasks/plan.md` is stale, I'll just replace it" | Unchecked tasks may be mid-build in another session. Overwriting them destroys work state that exists nowhere else. Stop and ask. | ## Red Flags - Starting implementation without a written task list +- Overwriting a `tasks/plan.md` or `tasks/todo.md` that still has unchecked tasks for different work, without asking - Writing `tasks/todo.md` when the project has designated an external tracker (or scattering tasks across both) - Tasks that say "implement the feature" without acceptance criteria - No verification steps in the plan @@ -238,6 +247,7 @@ Before starting implementation, confirm: - [ ] Every task has a verification step - [ ] Task dependencies are identified and ordered correctly - [ ] Tasks are recorded in the task list target (default `tasks/todo.md`) +- [ ] No pre-existing incomplete plan was overwritten without explicit user confirmation - [ ] No task touches more than ~5 files - [ ] Checkpoints exist between major phases - [ ] The human has reviewed and approved the plan diff --git a/skills/security-and-hardening/SKILL.md b/skills/security-and-hardening/SKILL.md index c00236e94b..c168e65e0d 100644 --- a/skills/security-and-hardening/SKILL.md +++ b/skills/security-and-hardening/SKILL.md @@ -1,6 +1,6 @@ --- name: security-and-hardening -description: Hardens code against vulnerabilities. Use when handling user input, authentication, data storage, or external integrations. Use when building any feature that accepts untrusted data, manages user sessions, or interacts with third-party services. Use when personal data or privacy compliance (GDPR, CCPA) is involved. +description: Hardens code against vulnerabilities. Use when auditing an input handler for vulnerabilities, when handling user input, authentication, data storage, or external integrations, or when checking a login flow is safe against the OWASP Top Ten. Use when building any feature that accepts untrusted data, manages user sessions, or interacts with third-party services. Use when auditing dependencies for known vulnerabilities, triaging package-manager audit findings, or assessing supply-chain risk in a new package. Use when personal data or privacy compliance (GDPR, CCPA) is involved. --- # Security and Hardening @@ -22,7 +22,7 @@ Security-first development practices for web applications. Treat every external Controls bolted on without a threat model are guesses. Before hardening, spend five minutes thinking like an attacker: -1. **Map the trust boundaries.** Where does untrusted data cross into your system? HTTP requests, form fields, file uploads, webhooks, third-party APIs, message queues, and **LLM output**. Every boundary is attack surface. +1. **Map the trust boundaries.** Where does untrusted data cross into your system? HTTP requests, form fields, file uploads, webhooks, third-party APIs, message queues, and **LLM output** — plus the local values that look internal because the OS handed them to you: another process's command line or environment, filenames on a shared volume, a path in a job payload. Trust follows who *wrote* a value, not which channel delivered it. Every boundary is attack surface. 2. **Name the assets.** What's worth stealing or breaking? Credentials, PII, payment data, admin actions, money movement. 3. **Run STRIDE over each boundary** — a quick lens, not a ceremony: @@ -269,6 +269,14 @@ function validateUpload(file: UploadedFile) { } ``` +### Destructive Operations on Derived Paths + +A delete, move, or overwrite is only as safe as the value that names its target. Reading that value from the kernel, a job payload, or a sibling service proves where it *arrived from*, not who *wrote* it — another process's command line is as attacker-controlled as a form field. A shape check ("absolute path, at least one directory deep") proves well-formedness and gets mistaken for authorization; that is how a cleanup routine deletes the root instead of the leaf. + +Before a destructive call, require all three: the resolved target sits under an **allowlisted root** (compare after resolving symlinks, never on the raw string); it is at least one level **below** that root, so a root is never itself the target; and it carries **evidence that it is yours**, read *before* the operation and before any teardown that removes it — otherwise "absent" and "not mine" are indistinguishable. On refusal, log the rejected target and stop: a cleanup that falls back to a broader default path is the failure this guards against. Worked example in `../../references/security-checklist.md`. + +Two limits, because the check reads stronger than it is. A marker inside the tree is self-attestation — anything that can write there can write the marker — so the expected owner has to come from authenticated state, and the marker needs integrity protection (restrictive ownership, or a MAC) before it counts as authorization. And resolving a path and then operating on the *name* is a check/use race wherever an untrusted process can swap an ancestor: on a shared volume, hold the target by descriptor and use no-follow, beneath-the-root operations, or make sure the hierarchy cannot change for the duration. + ## Triaging Dependency Audit Results Package-manager audits report known advisories; they do not prove a package is trustworthy or that vulnerable code is reachable. Use this decision tree: @@ -329,6 +337,20 @@ app.use('/api/auth/', rateLimit({ })); ``` +**Count in a shared store once there is more than one process.** `express-rate-limit` keeps its counters in process memory by default. Behind a load balancer each instance holds its own count, so the effective limit is `max × instances`; on serverless or edge runtimes a fresh invocation starts from zero, so the auth limit above may never fire. Pass a shared `store` (Redis via `rate-limit-redis`), or use an HTTP-based limiter that works where a long-lived TCP connection does not (for example `@upstash/ratelimit`): + +```typescript +import { Ratelimit } from '@upstash/ratelimit'; +import { Redis } from '@upstash/redis'; + +const authLimiter = new Ratelimit({ + redis: Redis.fromEnv(), // UPSTASH_REDIS_REST_URL + _TOKEN + limiter: Ratelimit.slidingWindow(10, '15 m'), // 10 attempts per 15 minutes, across all instances +}); +const { success } = await authLimiter.limit(`login:${req.ip}`); +if (!success) return res.status(429).end(); +``` + ## Secrets Management ``` @@ -421,6 +443,7 @@ container.textContent = await llm.reply(userMessage); - [ ] SQL queries are parameterized - [ ] HTML output is encoded/escaped - [ ] Server-side URL fetches are allowlisted (no SSRF to internal services) +- [ ] Delete/move/overwrite targets built from data are checked against an allowlisted root, a minimum depth, and ownership evidence read before the operation ### Data - [ ] No secrets in code or version control @@ -469,10 +492,11 @@ For detailed security checklists and pre-commit verification steps, see `../../r ## Red Flags - User input passed directly to database queries, shell commands, or HTML rendering +- A delete, move, or overwrite whose target comes from a payload, a config value, or another process's command line, guarded only by a shape check on the path - Secrets in source code or commit history - API endpoints without authentication or authorization checks - Missing CORS configuration or wildcard (`*`) origins -- No rate limiting on authentication endpoints +- No rate limiting on authentication endpoints, or an in-memory limiter in front of more than one instance - Stack traces or internal errors exposed to users - Dependencies with known critical vulnerabilities, competing lockfiles at one installation boundary, non-reproducible installs, or blanket-approved scripts - Server fetches user-supplied URLs without an allowlist (SSRF) @@ -489,10 +513,11 @@ After implementing security-relevant code: - [ ] The native audit has no unmitigated reachable critical/high findings; CI preserves the authoritative lockfile and blocks unreviewed dependency scripts - [ ] No secrets in source code or git history - [ ] All user input validated at system boundaries +- [ ] Destructive filesystem operations resolve symlinks, then verify allowlisted root, minimum depth, and ownership before running - [ ] Authentication and authorization checked on every protected endpoint - [ ] Security headers present in response (check with browser DevTools) - [ ] Error responses don't expose internal details -- [ ] Rate limiting active on auth endpoints +- [ ] Rate limiting active on auth endpoints, backed by a shared store when more than one instance serves traffic - [ ] Server-side URL fetches validated against an allowlist (no SSRF) - [ ] LLM/model output validated and encoded before use (if AI features present) - [ ] Personal data is classified, minimized to a stated purpose, and has a retention limit diff --git a/skills/shipping-and-launch/SKILL.md b/skills/shipping-and-launch/SKILL.md index acef513b77..f3fba8a012 100644 --- a/skills/shipping-and-launch/SKILL.md +++ b/skills/shipping-and-launch/SKILL.md @@ -1,6 +1,6 @@ --- name: shipping-and-launch -description: Prepares production launches. Use when preparing to deploy to production. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. +description: Prepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. --- # Shipping and Launch @@ -235,6 +235,19 @@ In the first hour after launch: 6. Confirm rollback mechanism works (dry run if possible) ``` +## Error Budget Release Gate + +Your service's error budget — the fraction of requests or time your SLO allows to fail — determines whether it's safe to ship. Use it as an objective gate — not a negotiation: + +``` +Budget remaining > 20% → Ship normally; monitor closely +Budget remaining 0–20% → Slow rollouts only; no high-risk changes +Budget exhausted → Freeze feature work; focus entirely on reliability +Budget resets → Resume normal pace; bake in the fix that recovered it +``` + +A high burn rate during a canary (consuming budget faster than the baseline pace) is a **hold** signal in the rollout thresholds table above — treat it the same as an elevated error rate. + ## Rollback Strategy Every deployment needs a rollback plan before it happens: @@ -269,6 +282,7 @@ Every deployment needs a rollback plan before it happens: - For security pre-launch checks, see `../../references/security-checklist.md` - For performance pre-launch checklist, see `../../references/performance-checklist.md` - For accessibility verification before launch, see `../../references/accessibility-checklist.md` +- For the alerting rules and SLO-tied thresholds, see `observability-and-instrumentation` ## Common Rationalizations @@ -279,6 +293,7 @@ Every deployment needs a rollback plan before it happens: | "Monitoring is overhead" | Not having monitoring means you discover problems from user complaints instead of dashboards. | | "We'll add monitoring later" | Add it before launch. You can't debug what you can't see. | | "Rolling back is admitting failure" | Rolling back is responsible engineering. Shipping a broken feature is the failure. | +| "The error rate looks fine, let's keep shipping" | Check the burn rate, not just the current error rate. Consuming budget faster than baseline is a hold signal even when individual thresholds are green. | ## Red Flags @@ -289,6 +304,7 @@ Every deployment needs a rollback plan before it happens: - No one monitoring the deploy for the first hour - Production environment configuration done by memory, not code - "It's Friday afternoon, let's ship it" +- Error budget exhausted but feature work continues unchanged ## Verification @@ -308,3 +324,7 @@ After deploying: - [ ] Critical user flow works - [ ] Logs are flowing - [ ] Rollback tested or verified ready + +For every shipped service: + +- [ ] Error budget policy in place: know what action to take when budget drops below 20% and when it's exhausted diff --git a/skills/source-driven-development/SKILL.md b/skills/source-driven-development/SKILL.md index d1f599a9fe..2704f0e130 100644 --- a/skills/source-driven-development/SKILL.md +++ b/skills/source-driven-development/SKILL.md @@ -1,6 +1,6 @@ --- name: source-driven-development -description: Grounds every implementation decision in official documentation. Use when you want authoritative, source-cited code free from outdated patterns. Use when building with any framework or library where correctness matters. +description: Grounds every implementation decision in official documentation. Use when you want to verify an approach against the official docs before implementing it, or when you want authoritative, source-cited code free from outdated patterns. Use when building with any framework or library where correctness matters. --- # Source-Driven Development diff --git a/skills/spec-driven-development/SKILL.md b/skills/spec-driven-development/SKILL.md index f3f5877c5d..aed90dc153 100644 --- a/skills/spec-driven-development/SKILL.md +++ b/skills/spec-driven-development/SKILL.md @@ -1,6 +1,6 @@ --- name: spec-driven-development -description: Creates specs before coding. Use when starting a new project, feature, or significant change and no specification exists yet. Use when requirements are unclear, ambiguous, or only exist as a vague idea. Use when a single requirement spans several independently testable capabilities and needs decomposing into a capability map of modules before specifying. +description: Creates specs before coding. Use when starting a new project, feature, or significant change and no specification exists yet. Use when drafting a PRD or requirements document with objectives and scope, or when requirements are unclear, ambiguous, or only exist as a vague idea. Use when a single requirement spans several independently testable capabilities and needs decomposing into a capability map of modules before specifying. --- # Spec-Driven Development diff --git a/skills/test-driven-development/SKILL.md b/skills/test-driven-development/SKILL.md index 0cfd2f33d7..8898bcbba4 100644 --- a/skills/test-driven-development/SKILL.md +++ b/skills/test-driven-development/SKILL.md @@ -1,6 +1,6 @@ --- name: test-driven-development -description: Drives development with tests. Use when implementing any logic, fixing any bug, or changing any behavior. Use when you need to prove that code works, when a bug report arrives, or when you're about to modify existing functionality. +description: Drives development with tests using the red-green-refactor loop. Use when implementing any logic, fixing any bug, or changing any behavior. Use when you need to prove that code works, when a bug report arrives, or when you're about to modify existing functionality. --- # Test-Driven Development diff --git a/skills/using-agent-skills/SKILL.md b/skills/using-agent-skills/SKILL.md index b250b297c4..d56ac03ab0 100644 --- a/skills/using-agent-skills/SKILL.md +++ b/skills/using-agent-skills/SKILL.md @@ -1,6 +1,6 @@ --- name: using-agent-skills -description: Discovers and invokes agent skills. Use when starting a session or when you need to discover which skill applies to the current task. This is the meta-skill that governs how all other skills are discovered and invoked. +description: Discovers and invokes agent skills. Use when starting a session, or when you need to decide which skill or workflow applies to the piece of work at hand. This is the meta-skill that governs how all other skills are discovered and invoked. --- # Using Agent Skills @@ -19,6 +19,7 @@ Task arrives ├── Don't know what you want yet? ──────→ interview-me ├── Have a rough concept, need variants? → idea-refine ├── New project/feature/change? ──→ spec-driven-development + ├── No quality bar written down? ──→ constraint-driven-development ├── Have a spec, need tasks? ──────→ planning-and-task-breakdown ├── Implementing code? ────────────→ incremental-implementation │ ├── UI work? ─────────────────→ frontend-ui-engineering