Compare commits

Author SHA1 Message Date
gitadmin a8b7227500 feat(pstack): add poteto skill stack (how/why/reflect/interrogate/reviews)
Import 12 skills from poteto under skills/pstack: bugfix-regression-test,
code-quality-review, dual-review, fix-merge-conflicts, how, interrogate,
reflect, security-audit, unslop, why, with progressive-disclosure
references. Credit poteto in README.
2026-10-06 12:48:40 -04:00
gitadmin 7c62958c31 feat(pr): add pr skill for writing PR bodies
Adds a user-invoked pr skill with a Summary/Evidence/Merge Danger
template, visual-format guidance adapted from Dex Horthy's show-me
skill (attribution in CREDITS.md), and an openai agent interface.
2026-10-06 12:47:56 -04:00
gitadmin 8be5a50b1e feat(implement-spec): add skill to implement spec tickets via subagent task graph 2026-10-06 12:47:32 -04:00
gitadmin 31d225e5b9 docs(readme): credit originators of skills in repo 2026-10-06 12:46:52 -04:00
gitadmin 53da2f7094 docs(setup-skills): add Gitea forge write safety rules
tea --description does not read stdin via @-, so a piped heredoc silently
creates an issue whose body is the literal "@-". Document the command-
substitution form, a post-create body check, and inspecting tea --help
before relying on CLI syntax.
2026-09-25 13:16:09 -04:00
gitadmin dab262ac23 feat: add arch-maintenance and arch-troubleshooting skills 2026-09-22 17:52:48 -04:00
gitadmin b9567c5e39 refactor: rename dev-workflow skill to implementation-orchestrator
The name dev-workflow described a category, not what the skill does. It
orchestrates implementation of already-planned tickets, so the new name
says that. Skill dir, docs page, name field and openai display name are
updated to match; validate-skill.sh moves with the dir and its paths are
fixed for the new depth and engineering/ layout.
2026-08-30 13:40:27 -04:00
gitadmin 3be0f20eef docs(dev-workflow): state ticket id/url is optional up front
Move the no-argument behaviour into the description and lead the body with
it so the trigger condition is visible before the skill is invoked.
2026-08-30 12:44:20 -04:00
gitadmin c97603c937 feat: add dev-workflow and forge-cli skills
Add two engineering skills for implementing tracker tickets end to end:

- dev-workflow: selects workflow:ready-for-agent tickets, runs them in
  isolated worktrees, opens one PR/MR per ticket, reviews, merges, and
  cleans up.
- forge-cli: detects the forge from origin and wraps gh, glab, and tea
  for Gitea/Forgejo, GitHub, and GitLab.

Docs cover install, prerequisites, ticket labels, and per-forge CLI usage.
2026-08-30 12:29:54 -04:00
gitadmin eb4a13166e docs(wayfinder): clarify bare number means forge issue number 2026-08-28 18:12:03 -04:00
gitadmin 77cc1c7c8b removed duplicate teach skill 2026-08-28 14:55:02 -04:00
gitadmin 103bc141dc feat: add recipe-diagrams, worktrees, and misc skills 2026-08-28 13:48:19 -04:00
gitadmin a9669c28ec docs: restructure skill catalog and standardize setup-skills references
Reorganize README.md with category sections (engineering, pkm, etc.)
for both user-invoked and model-invoked skills. Add new subcategory
READMEs for skill-authoring and thinking-and-docs. Replace
/setup-matt-pocock-skills references with setup-skills across all SKILLs.
2026-08-27 20:32:28 -04:00
gitadmin 0a4bac7adf added matt pocock skills 2026-08-27 20:14:59 -04:00
steve 149dde905b Merge pull request 'refactor: restructure skills directory and add thinking-and-docs skills' (#26) from restructure into master
Reviewed-on: #26
2026-08-19 18:35:27 -04:00
gitadmin 4a4ed5cb14 refactor: restructure skills directory and add thinking-and-docs skills 2026-08-19 18:22:21 -04:00
231 changed files with 8617 additions and 1644 deletions
+9 -13
View File
@@ -1,6 +1,6 @@
# Project Context Pack # Project Context Pack
Generated: 2026-08-17 Generated: 2026-07-16
Root: /home/sjb/Projects/personal/ws-sjb-skills/wt-master Root: /home/sjb/Projects/personal/ws-sjb-skills/wt-master
Working directory: . Working directory: .
Status: fresh Status: fresh
@@ -11,10 +11,10 @@ A collection of agent skills (slash commands and behaviors) loaded into Steve Be
## Project type ## Project type
- **Agent skill repository plus standalone Python tracker package** - **Agent skill repository** — markdown-defined agent instructions
- Languages: Python and Markdown, one Bash script (detect-agent), one shell script (tmux-open) - Languages: Markdown (100%), one Bash script (detect-agent), one shell script (tmux-open)
- Package manager: `pyproject.toml` - Package managers: none
- Build/test tools: `python -m unittest discover` - Build/test tools: none
- Agent guidance: `AGENTS.md` at root, `docs/invocation.md` for invocation conventions, `docs/agents/` for issue tracker / triage labels / ADR wiki / domain docs - Agent guidance: `AGENTS.md` at root, `docs/invocation.md` for invocation conventions, `docs/agents/` for issue tracker / triage labels / ADR wiki / domain docs
## Structure ## Structure
@@ -34,10 +34,6 @@ A collection of agent skills (slash commands and behaviors) loaded into Steve Be
│ │ ├── issue-tracker.md # Gitea issue tracker docs │ │ ├── issue-tracker.md # Gitea issue tracker docs
│ │ └── triage-labels.md # Five-label triage vocabulary │ │ └── triage-labels.md # Five-label triage vocabulary
│ └── adr/ # ADR wiki clone (gitignored) │ └── adr/ # ADR wiki clone (gitignored)
├── tracker/ # Provider-neutral Python CLI/library
├── tracker_automation/ # Compatibility import name
├── tests/ # Public operation-boundary tests
├── pyproject.toml # Package metadata and console scripts
└── common/ └── common/
├── README.md # Lists all common skills by invocation type ├── README.md # Lists all common skills by invocation type
├── engineering/ # Model-invoked: lsp-code-analysis, pkm-curation; User-invoked: commit-staged, implement-issue, project-context-pack, setup-skills ├── engineering/ # Model-invoked: lsp-code-analysis, pkm-curation; User-invoked: commit-staged, implement-issue, project-context-pack, setup-skills
@@ -61,10 +57,10 @@ A collection of agent skills (slash commands and behaviors) loaded into Steve Be
## Commands ## Commands
- Build/package: `python -m pip install .` - Build: none
- Test: `python -m unittest discover -v` - Test: none
- Typecheck: `lsp_diagnostics` on `tracker/` and `tests/` - Lint/typecheck: none
- Run: `python -m tracker` or installed `tracker` - Run/dev: skills are invoked by AI agents — no server or dev command
## Entry points ## Entry points
-2
View File
@@ -1,3 +1 @@
docs/adr/ docs/adr/
__pycache__/
*.py[cod]
+1 -1
View File
@@ -32,7 +32,7 @@ Every `SKILL.md` is either user-invoked (`disable-model-invocation: true`, reach
### Issue tracker ### Issue tracker
Issues are tracked in Gitea on gitea.sagacity.ca; use the provider-neutral `tracker` package for normal automation. See `docs/agents/issue-tracker.md` and `docs/agents/tracker.md`. Issues are tracked in Gitea on gitea.sagacity.ca. See `docs/agents/issue-tracker.md`.
### Triage labels ### Triage labels
+107 -17
View File
@@ -1,27 +1,117 @@
# Skills # Skills
Agent skills (slash commands and behaviors) loaded into my agent. Agent skills (slash commands and behaviors) loaded into AI coding agents.
## Tracker automation Skills are grouped by invocation type. [User-invoked](docs/invocation.md) skills run only when a person invokes them; model-invoked skills can also be selected automatically.
This repo also ships the standalone provider-neutral `tracker` CLI/library. See [`docs/agents/tracker.md`](docs/agents/tracker.md) and [`tracker/README.md`](tracker/README.md) for migration guidance. # Credits
Many of these skills were created or originated by the following people and organizations:
- [mattpocock](http://mattpocock.com)
- [poteto](https://github.com/poteto?tab=repositories)
## User-invoked ## User-invoked
- [agent-handoff](common/in-progress/agent-handoff/SKILL.md) — Hand the current conversation off to a fresh background agent that picks up the work immediately. ### Engineering
- [commit-staged](common/engineering/commit-staged/SKILL.md) — Commit staged files with a conventional commit message.
- [conversation-summary](common/pkm/conversation-summary/SKILL.md) — Save the current conversation as a comprehensive report note in your Obsidian vault, following OKF v0.1 conventions. - [commit-staged](skills/engineering/commit-staged/SKILL.md) — Commit staged files with a conventional commit message.
- [crit](common/pkm/crit/SKILL.md) — Run the CRIT framework — give the AI Context, assign it a Role, let it Interview you one question at a time, then issue the Task. - [grill-with-docs](skills/engineering/grill-with-docs/SKILL.md) — Interview the user to sharpen a plan or design while creating ADRs and glossary docs.
- [implement-isolation](common/engineering/implement-isolation/SKILL.md) — Implement a piece of work based on a spec or set of tickets in isolation. - [implement](skills/engineering/implement/SKILL.md) — Implement a piece of work from a spec or set of tickets.
- [implement-isolation-tmux](common/engineering/implement-isolation-tmux/SKILL.md) — Dispatch a child agent in an isolated git worktree to implement a piece of work based on a PRD or set of issues. - [implement-isolation](skills/engineering/implement-isolation/SKILL.md) — Implement a piece of work from a spec or set of tickets in isolation.
- [knowledge-gardener](common/in-progress/knowledge-gardener/SKILL.md) — Run vault-aware semantic search, synthesis, note creation, linking, and Zettelkasten workflows for this Obsidian vault. - [implement-isolation-tmux](skills/engineering/implement-isolation-tmux/SKILL.md) — Dispatch an isolated worktree agent to implement work from a PRD or issues.
- [project-context-pack](common/engineering/project-context-pack/SKILL.md) — Build a bounded repo context pack (project map, codebase index, cached memory file) so later work uses fd/rg/tree-sitter/LSP instead of repeated browsing. - [improve-codebase-architecture](skills/engineering/improve-codebase-architecture/SKILL.md) — Find and work through opportunities to deepen a codebase's architecture.
- [research-vault](common/pkm/research-vault/SKILL.md) — Research a topic through a one-question-at-a-time learning conversation, answer directly, share resources when useful, and save a linked OKF-conformant research packet in the Obsidian vault. - [project-context-pack](skills/engineering/project-context-pack/SKILL.md) — Build a bounded project context pack for later agent work.
- [setup-skills](common/engineering/setup-skills/SKILL.md) — Configure this repo for the engineering skills, set up its issue tracker, triage label vocabulary, and domain doc layout. Run once before first use of the other engineering skills. - [recipe-diagrams](skills/engineering/recipe-diagrams/SKILL.md) — Convert recipes into high-resolution process-flow diagrams.
- [tmux-launch-agent](common/misc/tmux-launch-agent/SKILL.md) — Fork a new agent CLI session into a new tmux window, detected from the current agent. - [setup-skills](skills/setup-skills/SKILL.md) — Configure engineering skills, issue tracking, triage labels, and domain docs.
- [youtube-video-capture](common/pkm/youtube-video-capture/SKILL.md) — Fetch subtitles from a YouTube video, summarize the content, and save both the summary and raw subtitles to the Video bundle in the Obsidian vault. - [to-spec](skills/engineering/to-spec/SKILL.md) — Turn the current conversation into a spec and publish it to the issue tracker.
- [to-tickets](skills/engineering/to-tickets/SKILL.md) — Break a plan or spec into tracer-bullet tickets with dependencies.
- [triage](skills/engineering/triage/SKILL.md) — Triage issues and external PRs through the project workflow.
- [wayfinder](skills/engineering/wayfinder/SKILL.md) — Plan large work as decision tickets and resolve them step by step.
### In-progress
- [agent-handoff](skills/in-progress/agent-handoff/SKILL.md) — Hand the current conversation to a fresh background agent.
- [knowledge-gardener](skills/in-progress/knowledge-gardener/SKILL.md) — Run vault-aware search, synthesis, note creation, and linking workflows.
### Miscellaneous
- [bro](skills/misc/bro/SKILL.md) — Restate the last message in plain human language.
- [show-me](skills/misc/show-me/SKILL.md) — Help explain topics visually with concise diagrams and artifacts.
- [tmux-launch-agent](skills/misc/tmux-launch-agent/SKILL.md) — Fork a new agent CLI session into a new tmux window.
- [visual-verification](skills/misc/visual-verification/SKILL.md) — Verify running desktop UI changes with screenshots and recordings.
### Personal
- [arch-maintenance](skills/personal/arch-maintenance/SKILL.md) — Keep an Arch/CachyOS system updated and healthy with status, check, and update workflows.
- [arch-troubleshooting](skills/personal/arch-troubleshooting/SKILL.md) — Diagnose and repair Arch/CachyOS system problems.
### PKM
- [conversation-summary](skills/pkm/conversation-summary/SKILL.md) — Save the current conversation as a report note in an Obsidian vault.
- [crit](skills/pkm/crit/SKILL.md) — Run the CRIT framework through context, role, interview, and task.
- [research-vault](skills/pkm/research-vault/SKILL.md) — Research a topic through a guided conversation and save a linked vault packet.
- [youtube-video-capture](skills/pkm/youtube-video-capture/SKILL.md) — Capture a YouTube video's subtitles and summary in an Obsidian vault.
### Productivity
- [grill-me](skills/productivity/grill-me/SKILL.md) — Interview the user to sharpen a plan or design.
- [handoff](skills/productivity/handoff/SKILL.md) — Compact the current conversation into a handoff document.
- [teach](skills/productivity/teach/SKILL.md) — Teach the user a new skill or concept within the workspace.
- [to-questionnaire](skills/productivity/to-questionnaire/SKILL.md) — Turn an unresolved decision into a questionnaire.
- [wait-what](skills/productivity/wait-what/SKILL.md) — Re-pitch the last message in clearer terms.
### Skill authoring
No user-invoked skills.
### Thinking and docs
- [before-building](skills/thinking-and-docs/before-building/SKILL.md) — Surface consequential choices when the user proposes a build.
- [decisions](skills/thinking-and-docs/decisions/SKILL.md) — List choices made during the current work that remain uncertain.
- [level-up](skills/thinking-and-docs/level-up/SKILL.md) — Assess technical and product knowledge and grow a learning plan.
- [read-all-adrs](skills/thinking-and-docs/read-all-adrs/SKILL.md) — Read every ADR in the project's `docs/adr/` folder.
- [remind](skills/thinking-and-docs/remind/SKILL.md) — Rewrite the last response more simply and briefly.
- [short](skills/thinking-and-docs/short/SKILL.md) — Compress the current answer while keeping its substance.
- [teach](skills/thinking-and-docs/teach/SKILL.md) — Teach the user a new skill or concept within the workspace.
## Model-invoked ## Model-invoked
- [lsp-code-analysis](common/engineering/lsp-code-analysis/SKILL.md) — Semantic code analysis via LSP. Navigate code (definitions, references, implementations), search symbols, preview refactorings, and get file outlines. Use for exploring unfamiliar codebases or performing safe refactoring. ### Engineering
- [pkm-curation](common/pkm/pkm-curation/SKILL.md) — Curate an Obsidian vault — classify notes, normalize frontmatter, add links, extract atomic notes. Use when curating, batch-processing, reviewing, or doing a serendipity pick.
- [code-review](skills/engineering/code-review/SKILL.md) — Review changes against repository standards and the originating specification.
- [codebase-design](skills/engineering/codebase-design/SKILL.md) — Design and improve deep module interfaces and seams.
- [diagnosing-bugs](skills/engineering/diagnosing-bugs/SKILL.md) — Diagnose hard bugs and performance regressions.
- [domain-modeling](skills/engineering/domain-modeling/SKILL.md) — Build and sharpen a project's domain model.
- [lsp-code-analysis](skills/engineering/lsp-code-analysis/SKILL.md) — Navigate code and analyze it semantically with LSP.
- [prototype](skills/engineering/prototype/SKILL.md) — Build a throwaway prototype to answer a design question.
- [research](skills/engineering/research/SKILL.md) — Investigate a question using high-trust sources and capture the findings.
- [resolving-merge-conflicts](skills/engineering/resolving-merge-conflicts/SKILL.md) — Resolve an in-progress Git merge or rebase conflict.
- [tdd](skills/engineering/tdd/SKILL.md) — Use test-driven development for features, bugs, and integration tests.
- [wizard](skills/engineering/wizard/SKILL.md) — Generate an interactive wizard for steps only a human can perform.
- [worktrees](skills/engineering/worktrees/SKILL.md) — Manage Git worktrees in a canonical repository root.
- [write-discoverable-code](skills/engineering/write-discoverable-code/SKILL.md) — Write code agents and humans can find through plain-text search.
### Miscellaneous
- [migrate-to-shoehorn](skills/misc/migrate-to-shoehorn/SKILL.md) — Migrate test assertions from `as` to `@total-typescript/shoehorn`.
- [scaffold-exercises](skills/misc/scaffold-exercises/SKILL.md) — Create linted exercise directories with problems, solutions, and explainers.
- [setup-pre-commit](skills/misc/setup-pre-commit/SKILL.md) — Set up Husky, lint-staged, type checking, and tests.
### PKM
- [pkm-curation](skills/pkm/pkm-curation/SKILL.md) — Curate an Obsidian vault with classification, links, and atomic notes.
### Productivity
- [grilling](skills/productivity/grilling/SKILL.md) — Grill the user relentlessly about a plan or design.
- [writing-for-agents](skills/productivity/writing-for-agents/SKILL.md) — Write effective documents for agents.
### Skill authoring
- [effective-agent-skills](skills/skill-authoring/effective-agent-skills/SKILL.md) — Write, review, and debug effective agent skills.
### Thinking and docs
- [brain-to-docs](skills/thinking-and-docs/brain-to-docs/SKILL.md) — Extract project vision, decisions, and preferences into documentation.
- [next-decision](skills/thinking-and-docs/next-decision/SKILL.md) — Drill into the next unresolved decision with choices and a recommendation.
- [prompt-me](skills/thinking-and-docs/prompt-me/SKILL.md) — Ask pointed questions to extract project priorities and concerns.
- [save-idea](skills/thinking-and-docs/save-idea/SKILL.md) — Capture content ideas in the user's content backlog.
-23
View File
@@ -1,23 +0,0 @@
# Common Skills
Skills that work in all CLI agents.
## User-invoked
- [agent-handoff](in-progress/agent-handoff/SKILL.md) — Hand the current conversation off to a fresh background agent that picks up the work immediately.
- [commit-staged](engineering/commit-staged/SKILL.md) — Commit staged files with a conventional commit message.
- [conversation-summary](pkm/conversation-summary/SKILL.md) — Save the current conversation as a comprehensive report note in your Obsidian vault, following OKF v0.1 conventions.
- [crit](pkm/crit/SKILL.md) — Run the CRIT framework — give the AI Context, assign it a Role, let it Interview you one question at a time, then issue the Task.
- [implement-isolation](engineering/implement-isolation/SKILL.md) — Implement a piece of work based on a spec or set of tickets in isolation.
- [implement-isolation-tmux](engineering/implement-isolation-tmux/SKILL.md) — Dispatch a child agent in an isolated git worktree to implement a piece of work based on a PRD or set of issues.
- [knowledge-gardener](in-progress/knowledge-gardener/SKILL.md) — Run vault-aware semantic search, synthesis, note creation, linking, and Zettelkasten workflows for this Obsidian vault.
- [project-context-pack](engineering/project-context-pack/SKILL.md) — Build a bounded repo context pack (project map, codebase index, cached memory file) so later work uses fd/rg/tree-sitter/LSP instead of repeated browsing.
- [research-vault](pkm/research-vault/SKILL.md) — Research a topic through a one-question-at-a-time learning conversation, answer directly, share resources when useful, and save a linked OKF-conformant research packet in the Obsidian vault.
- [setup-skills](engineering/setup-skills/SKILL.md) — Configure this repo for the engineering skills, set up its issue tracker, triage label vocabulary, and domain doc layout. Run once before first use of the other engineering skills.
- [tmux-launch-agent](misc/tmux-launch-agent/SKILL.md) — Fork a new agent CLI session into a new tmux window, detected from the current agent.
- [youtube-video-capture](pkm/youtube-video-capture/SKILL.md) — Fetch subtitles from a YouTube video, summarize the content, and save both the summary and raw subtitles to the Video bundle in the Obsidian vault.
## Model-invoked
- [lsp-code-analysis](engineering/lsp-code-analysis/SKILL.md) — Semantic code analysis via LSP. Navigate code (definitions, references, implementations), search symbols, preview refactorings, and get file outlines. Use for exploring unfamiliar codebases or performing safe refactoring.
- [pkm-curation](pkm/pkm-curation/SKILL.md) — Curate an Obsidian vault — classify notes, normalize frontmatter, add links, extract atomic notes. Use when curating, batch-processing, reviewing, or doing a serendipity pick.
-15
View File
@@ -1,15 +0,0 @@
# Engineering Skills
Daily code work.
## User-invoked
- [commit-staged](commit-staged/SKILL.md) — Commit staged files with a conventional commit message.
- [implement-isolation](implement-isolation/SKILL.md) — Implement a piece of work based on a spec or set of tickets in isolation.
- [implement-isolation-tmux](implement-isolation-tmux/SKILL.md) — Dispatch a child agent in an isolated git worktree to implement a piece of work based on a PRD or set of issues.
- [project-context-pack](project-context-pack/SKILL.md) — Build a bounded repo context pack (project map, codebase index, cached memory file) so later work uses fd/rg/tree-sitter/LSP instead of repeated browsing.
- [setup-skills](setup-skills/SKILL.md) — Configure this repo for the engineering skills, set up its issue tracker, triage label vocabulary, and domain doc layout. Run once before first use of the other engineering skills.
## Model-invoked
- [lsp-code-analysis](lsp-code-analysis/SKILL.md) — Semantic code analysis via LSP. Navigate code (definitions, references, implementations), search symbols, preview refactorings, and get file outlines. Use for exploring unfamiliar codebases or performing safe refactoring.
-7
View File
@@ -1,7 +0,0 @@
# Misc Skills
Kept around but rarely used.
## User-invoked
- [tmux-launch-agent](tmux-launch-agent/SKILL.md) — Fork a new agent CLI session into a new tmux window, detected from the current agent.
-5
View File
@@ -1,5 +0,0 @@
# Personal Skills
Tied to my own setup, not promoted.
_No skills currently live in this bucket._
-14
View File
@@ -1,14 +0,0 @@
# PKM Skills
Personal knowledge management.
## User-invoked
- [conversation-summary](conversation-summary/SKILL.md) — Save the current conversation as a comprehensive report note in your Obsidian vault, following OKF v0.1 conventions.
- [crit](crit/SKILL.md) — Run the CRIT framework — give the AI Context, assign it a Role, let it Interview you one question at a time, then issue the Task.
- [research-vault](research-vault/SKILL.md) — Research a topic through a one-question-at-a-time learning conversation, answer directly, share resources when useful, and save a linked OKF-conformant research packet in the Obsidian vault.
- [youtube-video-capture](youtube-video-capture/SKILL.md) — Fetch subtitles from a YouTube video, summarize the content, and save both the summary and raw subtitles to the Video bundle in the Obsidian vault.
## Model-invoked
- [pkm-curation](pkm-curation/SKILL.md) — Curate an Obsidian vault — classify notes, normalize frontmatter, add links, extract atomic notes. Use when curating, batch-processing, reviewing, or doing a serendipity pick.
-5
View File
@@ -1,5 +0,0 @@
# Productivity Skills
Daily non-code workflow tools.
_No skills currently live in this bucket._
+2 -2
View File
@@ -1,6 +1,6 @@
# Issue tracker: provider-neutral tracker over Gitea # Issue tracker: Gitea
Use `tracker` (see `docs/agents/tracker.md`) for normal issue and pull-request automation. It delegates to `tea` and emits one JSON envelope. The Gitea command details below remain capability and fallback reference material; do not issue exploratory raw commands when a tracker operation exists. Issues and PRDs for this repo live as Gitea issues. Use the `tea` CLI for all operations.
## Conventions ## Conventions
-15
View File
@@ -1,15 +0,0 @@
# Provider-neutral tracker automation
Use `tracker` for normal issue and pull-request automation. It owns the high-level operation, prerequisite checks, normalization, bounded retry policy, and JSON protocol; it delegates credentials and provider commands to `gh`, `glab`, or `tea`.
```sh
tracker --provider gitea issue get 16
TRACKER_PROVIDER=gitlab tracker issue list --state open --label ready-for-agent
tracker pr get 42 --diff
```
Provider selection is explicit CLI flag, then `TRACKER_PROVIDER`, then the `origin` remote. Always choose `issue` or `pr` explicitly for reads and writes. Use `resolve-reference` only for an intentionally ambiguous bare number.
Parse `ok` and `error.code`; do not parse provider output or issue exploratory retries. The library (`from tracker import Tracker`) returns the same envelope as the CLI. `RecordingRunner` provides the fake subprocess seam for tests.
Provider-specific capability and fallback references remain in `docs/agents/issue-tracker.md` and the setup templates. They are not the normal execution path. Wayfinding relationships may use native provider APIs where available and task-list/body or note fallbacks otherwise; the result's `details` identifies the relationship mode.
+2
View File
@@ -0,0 +1,2 @@
@@ -0,0 +1,146 @@
# Pi implementation orchestrator skill
`implementation-orchestrator` implements already-planned tracker tickets from issue selection through isolated implementation worktrees, pull/merge requests, review, merge, and cleanup.
It supports:
- Tea-compatible Gitea/Forgejo repositories through `tea`
- GitHub repositories through `gh`
- GitLab repositories through `glab`
The forge is selected from `origin`, or explicitly with `DEV_WORKFLOW_FORGE`.
## Install
From this checkout, install globally for your user:
```bash
pi install /absolute/path/to/ws-developement-workflow
```
Or install it only for the current project:
```bash
pi install -l /absolute/path/to/ws-developement-workflow
```
Restart Pi after installation, or run `/reload` in an existing session. Review the package before installing it: skills can instruct Pi to run commands with your account's permissions.
## When to use it
Use this after the human-led wayfinder, planning, specification, and ticket phases have produced implementation tickets.
The skill does **not** create planning tickets. It only implements tickets that are already labelled:
```text
workflow:ready-for-agent
```
Invoke it with an optional ticket ID or URL:
```text
# Process only ticket 43
/skill:implementation-orchestrator 43
# Process all available tickets in the current repository
/skill:implementation-orchestrator
```
The ID must be a tracker issue/ticket, not a branch name, PR/MR ID, or session ID. With an ID, only that ticket is processed. With no ID, the skill considers all open tickets in the current repository.
## Prerequisites
Before invoking the skill:
1. Run it from a checkout of the target repository.
2. Ensure `origin` points to the correct forge repository.
3. Install and authenticate the matching CLI:
- Tea/Gitea/Forgejo: `tea`
- GitHub: `gh`
- GitLab: `glab`
4. Create implementation tickets, optionally grouped under a root issue.
5. Mark implementable tickets `workflow:ready-for-agent`.
6. Add native child/dependency relationships where supported. Otherwise put explicit issue URLs or the documented blocker marker in the ticket.
7. Configure `DEV_WORKFLOW_HUMAN_REVIEWER` if the agent may assign human review automatically.
Run the read-only preflight manually from the target repository if needed:
```bash
bash /path/to/this-package/skills/forge-cli/scripts/detect-forge.sh
```
Expected output resembles:
```text
forge=gh
remote=https://github.com/acme/project.git
```
## What happens
For the supplied ticket, or all tickets when no ticket is supplied, the skill:
1. Verifies the repository, forge CLI, authentication, default branch, and capabilities.
2. Reads only the supplied ticket; otherwise reads all open tickets in the repository.
3. Selects only open, unassigned, unblocked `workflow:ready-for-agent` tickets.
4. For a supplied ticket, runs only that ticket; with no ticket, runs currently unblocked tickets in parallel, up to three isolated workers. Dependent tickets wait for their blockers.
5. Claims each selected ticket and changes it to `workflow:implementing`, then gives it to one worker in an isolated Git worktree.
6. Runs local checks, pushes the branch, and creates exactly one PR/MR per ticket.
7. Records URLs, status, evidence, blockers, and handoffs in tracker comments.
8. Reviews each PR/MR for correctness/spec and standards, allowing at most three fix rounds.
9. Resolves conflicts through the conflict workflow instead of aborting or guessing.
10. Merges only when review, local checks, CI, target branch, and blocker gates are clean.
11. Closes the integrated ticket, records the merge receipt, and removes the worktree.
12. Re-queries the scoped ticket set after every merge so newly unblocked tickets can run.
Default worker parallelism is three, subject to the available subagent limit.
## Ticket labels
The skill uses one active workflow label per ticket:
```text
workflow:ready-for-agent
workflow:ready-for-human
workflow:implementing
workflow:pr-open
workflow:review
workflow:changes-requested
workflow:conflict
workflow:blocked
workflow:merged
```
Existing `workflow:ready-for-human` tickets are left untouched and reported as human handoffs. Missing requirements, unsafe ambiguity, credentials, product decisions, unavailable CI, and missing permissions stop the workflow instead of being guessed around.
## Forge CLI recipes
After preflight, the shared `forge-cli` skill contains the common rules and automatically selects one recipe:
- `skills/forge-cli/references/tea.md`
- `skills/forge-cli/references/gh.md`
- `skills/forge-cli/references/glab.md`
Other skills can use it too: install this package globally, then instruct them to load the shared `forge-cli` skill instead of duplicating CLI syntax.
## Completion states
The final report includes:
- merged tickets and PR/MR URLs;
- remaining eligible tickets;
- tickets waiting for human review;
- blocked tickets and exact reasons;
- failed checks and review rounds.
`done` means no open implementation or human tickets remain in the selected scope. If only human tickets remain, the result is `waiting-on-human`.
## Development checks
Validate the package with:
```bash
bash tests/test-workflow.sh
```
This checks skill metadata, references, shell syntax, forge detection, and eligibility filtering.
-24
View File
@@ -1,24 +0,0 @@
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[project]
name = "tracker-automation"
version = "0.1.0"
description = "Provider-neutral tracker automation CLI and library"
requires-python = ">=3.10"
[project.scripts]
tracker = "tracker.cli:main"
tracker-automation = "tracker.cli:main"
[tool.setuptools.packages.find]
include = ["tracker*", "tracker_automation*"]
[tool.pyright]
include = ["tracker", "tests"]
extraPaths = ["."]
[tool.ruff]
target-version = "py310"
line-length = 100
+34
View File
@@ -0,0 +1,34 @@
# Engineering Skills
Daily code work.
## User-invoked
- [commit-staged](commit-staged/SKILL.md) — Commit staged files with a conventional commit message.
- [grill-with-docs](grill-with-docs/SKILL.md) — Interview the user to sharpen a plan or design while creating ADRs and glossary docs.
- [implement](implement/SKILL.md) — Implement a piece of work from a spec or set of tickets.
- [implement-isolation](implement-isolation/SKILL.md) — Implement a piece of work from a spec or set of tickets in isolation.
- [implement-isolation-tmux](implement-isolation-tmux/SKILL.md) — Dispatch an isolated worktree agent to implement work from a PRD or issues.
- [improve-codebase-architecture](improve-codebase-architecture/SKILL.md) — Find and work through opportunities to deepen a codebase's architecture.
- [project-context-pack](project-context-pack/SKILL.md) — Build a bounded project context pack for later agent work.
- [recipe-diagrams](recipe-diagrams/SKILL.md) — Convert recipes into high-resolution process-flow diagrams.
- [setup-skills](../setup-skills/SKILL.md) — Configure engineering skills, issue tracking, triage labels, and domain docs.
- [to-spec](to-spec/SKILL.md) — Turn the current conversation into a spec and publish it to the issue tracker.
- [to-tickets](to-tickets/SKILL.md) — Break a plan or spec into tracer-bullet tickets with dependencies.
- [triage](triage/SKILL.md) — Triage issues and external PRs through the project workflow.
- [wayfinder](wayfinder/SKILL.md) — Plan large work as decision tickets and resolve them step by step.
## Model-invoked
- [code-review](code-review/SKILL.md) — Review changes against repository standards and the originating specification.
- [codebase-design](codebase-design/SKILL.md) — Design and improve deep module interfaces and seams.
- [diagnosing-bugs](diagnosing-bugs/SKILL.md) — Diagnose hard bugs and performance regressions.
- [domain-modeling](domain-modeling/SKILL.md) — Build and sharpen a project's domain model.
- [lsp-code-analysis](lsp-code-analysis/SKILL.md) — Navigate code and analyze it semantically with LSP.
- [prototype](prototype/SKILL.md) — Build a throwaway prototype to answer a design question.
- [research](research/SKILL.md) — Investigate a question using high-trust sources and capture the findings.
- [resolving-merge-conflicts](resolving-merge-conflicts/SKILL.md) — Resolve an in-progress Git merge or rebase conflict.
- [tdd](tdd/SKILL.md) — Use test-driven development for features, bugs, and integration tests.
- [wizard](wizard/SKILL.md) — Generate an interactive wizard for steps only a human can perform.
- [worktrees](worktrees/SKILL.md) — Manage Git worktrees in a canonical repository root.
- [write-discoverable-code](write-discoverable-code/SKILL.md) — Write code agents and humans can find through plain-text search.
+87
View File
@@ -0,0 +1,87 @@
---
name: code-review
description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"."
---
Two-axis review of the diff between `HEAD` and a fixed point the user supplies:
- **Standards**: does the code conform to this repo's documented coding standards?
- **Spec**: does the code faithfully implement the originating issue / spec?
Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings.
The issue tracker should have been provided to you. If `docs/agents/issue-tracker.md` is missing, tell the user to run `setup-skills`.
## Process
### 1. Pin the fixed point
Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it.
Capture the diff command once: `git diff <fixed-point>...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log <fixed-point>..HEAD --oneline`.
Before going further, confirm the fixed point resolves (`git rev-parse <fixed-point>`) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents.
### 2. Identify the spec source
Look for the originating spec, in this order:
1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in `docs/agents/issue-tracker.md`.
2. A path the user passed as an argument.
3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature.
4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available".
### 3. Identify the standards sources
Anything in the repo that documents how code should be written, such as `CODING_STANDARDS.md` or `CONTRIBUTING.md`.
On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it:
- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell.
- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces.
Each smell reads *what it is* → *how to fix*; match it against the diff:
- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky.
- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both.
- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies.
- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that.
- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type.
- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share.
- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module.
- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason.
- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows.
- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object.
- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct.
- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition.
### 4. Spawn both sub-agents in parallel
**Standards sub-agent prompt** should include:
- The full diff command and commit list.
- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it).
- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words."
**Spec sub-agent prompt** should include:
- The diff command and commit list.
- The path or fetched contents of the spec.
- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words."
If the spec is missing, skip the Spec sub-agent and note this in the final report.
### 5. Aggregate
Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_).
End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent.
## Why two axes
A change can pass one axis and fail the other:
- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.**
- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.**
Reporting them separately stops one axis from masking the other.
@@ -0,0 +1,3 @@
interface:
display_name: "Code Review"
short_description: "Review a diff on standards and spec"
@@ -0,0 +1,37 @@
# Deepening
How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**.
## Dependency categories
When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam.
### 1. In-process
Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed.
### 2. Local-substitutable
Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface.
### 3. Remote but owned (Ports & Adapters)
Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter.
Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."*
### 4. True external (Mock)
Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter.
## Seam discipline
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection.
- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them.
## Testing strategy: replace, don't layer
- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them.
- Write new tests at the deepened module's interface. The **interface is the test surface**.
- Tests assert on observable outcomes through the interface, not internal state.
- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface.
@@ -0,0 +1,44 @@
# Design It Twice
When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best.
Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**.
## Process
### 1. Frame the problem space
Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate:
- The constraints any new interface would need to satisfy
- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md))
- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete
Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel.
### 2. Spawn sub-agents
Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module.
Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint:
- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point."
- Agent 2: "Maximise flexibility: support many use cases and extension."
- Agent 3: "Optimise for the most common caller: make the default case trivial."
- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies."
Include both [SKILL.md](SKILL.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language.
Each sub-agent outputs:
1. Interface (types, methods, params, plus invariants, ordering, error modes)
2. Usage example showing how callers use it
3. What the implementation hides behind the seam
4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md))
5. Trade-offs: where leverage is high, where it's thin
### 3. Present and compare
Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**.
After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu.
+114
View File
@@ -0,0 +1,114 @@
---
name: codebase-design
description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.
---
# Codebase Design
Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone.
## Glossary
Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point.
**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service.
**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface).
**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise.
**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation.
**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context).
**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).
**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests.
**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere.
## Deep vs shallow
**Deep module** = small interface + lots of implementation:
```
┌─────────────────────┐
│ Small Interface │ ← Few methods, simple params
├─────────────────────┤
│ │
│ Deep Implementation│ ← Complex logic hidden
│ │
└─────────────────────┘
```
**Shallow module** = large interface + little implementation (avoid):
```
┌─────────────────────────────────┐
│ Large Interface │ ← Many methods, complex params
├─────────────────────────────────┤
│ Thin Implementation │ ← Just passes through
└─────────────────────────────────┘
```
When designing an interface, ask:
- Can I reduce the number of methods?
- Can I simplify the parameters?
- Can I hide more complexity inside?
## Principles
- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface.
- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.
- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape.
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it.
## Designing for testability
Good interfaces make testing natural:
1. **Accept dependencies, don't create them.**
```typescript
// Testable
function processOrder(order, paymentGateway) {}
// Hard to test
function processOrder(order) {
const gateway = new StripeGateway();
}
```
2. **Return results, don't produce side effects.**
```typescript
// Testable
function calculateDiscount(cart): Discount {}
// Hard to test
function applyDiscount(cart): void {
cart.total -= discount;
}
```
3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup.
## Relationships
- A **Module** has exactly one **Interface** (the surface it presents to callers and tests).
- **Depth** is a property of a **Module**, measured against its **Interface**.
- A **Seam** is where a **Module**'s **Interface** lives.
- An **Adapter** sits at a **Seam** and satisfies the **Interface**.
- **Depth** produces **Leverage** for callers and **Locality** for maintainers.
## Rejected framings
- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead.
- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know.
- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**.
## Going deeper
- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing.
- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement.
@@ -0,0 +1,3 @@
interface:
display_name: "Codebase Design"
short_description: "Vocabulary for deep-module design"
+138
View File
@@ -0,0 +1,138 @@
---
name: diagnosing-bugs
description: Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.
---
# Diagnosing Bugs
A discipline for hard bugs. Skip phases only when explicitly justified.
When exploring the codebase, read `CONTEXT.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching.
## Redact
This skill has you show commands, outputs and captured artifacts. **Redact every secret first**: write `<REDACTED>` in its place. Build loops against env vars, so the credential stays in the environment rather than in what you show. Captured artifacts carry auth headers: quote only the lines that carry the signal.
If the redacted output is not enough to diagnose the bug, say so and ask the user.
## Phase 1: Build a feedback loop
**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug (one that goes red on _this_ bug), you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you.
Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.**
### Ways to construct one, in roughly this order
1. **Failing test** at whatever seam reaches the bug: unit, integration, e2e.
2. **Curl / HTTP script** against a running dev server.
3. **CLI invocation** with a fixture input, diffing stdout against a known-good snapshot.
4. **Headless browser script** (Playwright / Puppeteer) that drives the UI and asserts on DOM/console/network.
5. **Replay a captured trace.** Save a real network request / payload / event log to disk; replay it through the code path in isolation.
6. **Throwaway harness.** Spin up a minimal subset of the system (one service, mocked deps) that exercises the bug code path with a single function call.
7. **Property / fuzz loop.** If the bug is "sometimes wrong output", run 1000 random inputs and look for the failure mode.
8. **Bisection harness.** If the bug appeared between two known states (commit, dataset, version), automate "boot at state X, check, repeat" so you can `git bisect run` it.
9. **Differential loop.** Run the same input through old-version vs new-version (or two configs) and diff outputs.
10. **HITL bash script.** Last resort. If a human must click, drive _them_ with `scripts/hitl-loop.template.sh` so the loop is still structured. Captured output feeds back to you.
Build the right feedback loop, and the bug is 90% fixed.
### Tighten the loop
Treat the loop as a product. Once you have _a_ loop, **tighten** it:
- Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.)
- Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".)
- Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.)
A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight, a debugging superpower.
### Non-deterministic bugs
The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not, so keep raising the rate until it's debuggable.
### When you genuinely cannot build a loop
Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a redacted captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop.
### Completion criterion: a tight loop that goes red
Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** (a script path, a test invocation, a curl) that you have **already run at least once** (show the invocation and its output, redacted), and that is:
- [ ] **Red-capable**: it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring"; it must be able to _catch this specific bug_.
- [ ] **Deterministic**: same verdict every run (flaky bugs: a pinned, high reproduction rate, per above).
- [ ] **Fast**: seconds, not minutes.
- [ ] **Agent-runnable**: you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`.
If you catch yourself reading code to build a theory before this command exists, **stop: jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2.
## Phase 2: Reproduce + minimise
Run the loop. Watch it go red as the bug appears.
Confirm:
- [ ] The loop produces the failure mode the **user** described, not a different failure that happens to be nearby. Wrong bug = wrong fix.
- [ ] The failure is reproducible across multiple runs (or, for non-deterministic bugs, reproducible at a high enough rate to debug against).
- [ ] You have captured the exact symptom (error message, wrong output, slow timing) so later phases can verify the fix actually addresses it.
### Minimise
Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut, and keep only what's load-bearing for the failure.
Why bother: a minimal repro shrinks the hypothesis space in Phase 3 (fewer moving parts left to suspect) and becomes the clean regression test in Phase 5.
Done when **every remaining element is load-bearing**: removing any one of them makes the loop go green.
Do not proceed until you have reproduced **and** minimised.
## Phase 3: Hypothesise
Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea.
Each hypothesis must be **falsifiable**: state the prediction it makes.
> Format: "If <X> is the cause, then <changing Y> will make the bug disappear / <changing Z> will make it worse."
If you cannot state the prediction, the hypothesis is a vibe: discard or sharpen it.
**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it; proceed with your ranking if the user is AFK.
## Phase 4: Instrument
Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.**
Tool preference:
1. **Debugger / REPL inspection** if the env supports it. One breakpoint beats ten logs.
2. **Targeted logs** at the boundaries that distinguish hypotheses.
3. Never "log everything and grep".
**Tag every debug log** with a unique prefix, e.g. `[DEBUG-a4f2]`. Cleanup at the end becomes a single grep. Untagged logs survive; tagged logs die.
**Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second.
## Phase 5: Fix + regression test
Write the regression test **before the fix**, but only if there is a **correct seam** for it.
A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence.
**If no correct seam exists, that itself is the finding.** Note it. The codebase architecture is preventing the bug from being locked down. Flag this for the next phase.
If a correct seam exists:
1. Turn the minimised repro into a failing test at that seam.
2. Watch it fail.
3. Apply the fix.
4. Watch it pass.
5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario.
## Phase 6: Cleanup
Required before declaring done:
- [ ] Original repro no longer reproduces (re-run the Phase 1 loop)
- [ ] Regression test passes (or absence of seam is documented)
- [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix)
- [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location)
- [ ] The hypothesis that turned out correct is stated in the commit / PR message, so the next debugger learns
@@ -0,0 +1,3 @@
interface:
display_name: "Diagnosing Bugs"
short_description: "Diagnose hard bugs and regressions"
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# Human-in-the-loop reproduction loop.
# Copy this file, edit the steps below, and run it.
# The agent runs the script; the user follows prompts in their terminal.
#
# Usage:
# bash hitl-loop.template.sh
#
# Two helpers:
# step "<instruction>" → show instruction, wait for Enter
# capture VAR "<question>" → show question, read response into VAR
#
# At the end, captured values are printed as KEY=VALUE for the agent to parse.
#
# `capture` prints its value back to the terminal, where the agent reads it,
# so capture observations, and leave signing in to the user as a `step`.
set -euo pipefail
step() {
printf '\n>>> %s\n' "$1"
read -r -p " [Enter when done] " _
}
capture() {
local var="$1" question="$2" answer
printf '\n>>> %s\n' "$question"
read -r -p " > " answer
printf -v "$var" '%s' "$answer"
}
# --- edit below ---------------------------------------------------------
step "Open the app at http://localhost:3000 and sign in."
capture ERRORED "Click the 'Export' button. Did it throw an error? (y/n)"
capture ERROR_MSG "Paste the error message (or 'none'):"
# --- edit above ---------------------------------------------------------
printf '\n--- Captured ---\n'
printf 'ERRORED=%s\n' "$ERRORED"
printf 'ERROR_MSG=%s\n' "$ERROR_MSG"
@@ -0,0 +1,47 @@
# ADR Format
ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
Create the `docs/adr/` directory lazily: only when the first ADR is needed.
## Template
```md
# {Short title of the decision}
{1-3 sentences: what's the context, what did we decide, and why.}
```
That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections.
## Optional sections
Only include these when they add genuine value. Most ADRs won't need them.
- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited
- **Considered Options**: only when the rejected alternatives are worth remembering
- **Consequences**: only when non-obvious downstream effects need to be called out
## Numbering
Scan `docs/adr/` for the highest existing number and increment by one.
## When to offer an ADR
All three of these must be true:
1. **Hard to reverse**: the cost of changing your mind later is meaningful
2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?"
3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons
If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
### What qualifies
- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out.
- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months.
@@ -0,0 +1,60 @@
# CONTEXT.md Format
## Structure
```md
# {Context Name}
{One or two sentence description of what this context is and why it exists.}
## Language
**Order**:
{A one or two sentence description of the term}
_Avoid_: Purchase, transaction
**Invoice**:
A request for payment sent to a customer after delivery.
_Avoid_: Bill, payment request
**Customer**:
A person or organization that places orders.
_Avoid_: Client, buyer, account
```
## Rules
- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`.
- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does.
- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs.
- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine.
## Single vs multi-context repos
**Single context (most repos):** One `CONTEXT.md` at the repo root.
**Multiple contexts:** A `CONTEXT-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other:
```md
# Context Map
## Contexts
- [Ordering](./src/ordering/CONTEXT.md): receives and tracks customer orders
- [Billing](./src/billing/CONTEXT.md): generates invoices and processes payments
- [Fulfillment](./src/fulfillment/CONTEXT.md): manages warehouse picking and shipping
## Relationships
- **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking
- **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices
- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money`
```
The skill infers which structure applies:
- If `CONTEXT-MAP.md` exists, read it to find contexts
- If only a root `CONTEXT.md` exists, single context
- If neither exists, create a root `CONTEXT.md` lazily when the first term is resolved
When multiple contexts exist, infer which one the current topic relates to. If unclear, ask.
@@ -0,0 +1,74 @@
---
name: domain-modeling
description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a CONTEXT.md, or recording or editing an ADR.
---
# Domain Modeling
Actively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `CONTEXT.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.)
## File structure
Most repos have a single context:
```
/
├── CONTEXT.md
├── docs/
│ └── adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```
If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:
```
/
├── CONTEXT-MAP.md
├── docs/
│ └── adr/ ← system-wide decisions
├── src/
│ ├── ordering/
│ │ ├── CONTEXT.md
│ │ └── docs/adr/ ← context-specific decisions
│ └── billing/
│ ├── CONTEXT.md
│ └── docs/adr/
```
Create files lazily: only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed.
## During the session
### Challenge against the glossary
When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?"
### Sharpen fuzzy language
When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account': do you mean the Customer or the User? Those are different things."
### Discuss concrete scenarios
When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.
### Cross-reference with code
When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?"
### Update CONTEXT.md inline
When a term is resolved, update `CONTEXT.md` right there. Don't batch these up: capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
`CONTEXT.md` should be totally devoid of implementation details. Do not treat `CONTEXT.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else.
### Offer ADRs sparingly
Only offer to create an ADR when all three are true:
1. **Hard to reverse**: the cost of changing your mind later is meaningful
2. **Surprising without context**: a future reader will wonder "why did they do it this way?"
3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons
If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).
@@ -0,0 +1,3 @@
interface:
display_name: "Domain Modeling"
short_description: "Build and sharpen a domain model"
+38
View File
@@ -0,0 +1,38 @@
---
name: forge-cli
description: Provides copy-paste, non-interactive tea, gh, and glab commands for issue and pull or merge request work. Use whenever a task needs tracker inspection, assignment, labels, comments, reviews, CI, or merge operations.
---
# Forge CLI
Use this shared skill instead of reproducing forge CLI syntax in another skill.
Run the bundled read-only preflight with the target repository as the working directory:
```bash
bash <resolved-skill-dir>/scripts/detect-forge.sh
```
Resolve `<resolved-skill-dir>` from this `SKILL.md`, not from the target repository.
It prints one selected CLI: `forge=tea`, `forge=gh`, or `forge=glab`. Read **only** the matching recipe:
- `forge=tea` → `references/tea.md`
- `forge=gh` → `references/gh.md`
- `forge=glab` → `references/glab.md`
Do not load or compare the other recipes. This keeps one forge's syntax in context.
Commands assume the current checkout identifies the repository. Replace `ID` (issue), `PR` (pull/merge request), `USER`, `OLD`, `NEW`, `BASE`, `HEAD`, `TITLE`, and `BODY_FILE`. Keep bodies in a file to avoid quoting and interactive prompts.
## Shared safety rules
1. Use JSON output for reads; inspect the returned object before deciding eligibility, dependencies, or merge readiness.
2. Use one mutation per state transition, then re-read and confirm the state/label/comment changed.
3. If a recipe returns an unknown command or flag, run that CLI command's `--help`; do not switch forge CLIs or guess.
4. Check command exit status. Authentication, repository resolution, missing permissions, unsupported relationships, and unavailable CI are blockers.
5. Do not use auto-merge, admin/bypass, or force options. Merge only after every workflow gate passes.
Honor `DEV_WORKFLOW_FORGE=tea`, `gh`, or `glab` when explicitly configured; otherwise use GitHub → `gh`, GitLab → `glab`, and other Tea-compatible hosts → `tea`.
Keep these identifiers distinct: tracker issue/ticket ID, PR/MR ID, durable URL, and local branch name. Never use a branch name as ticket identity.
@@ -0,0 +1,3 @@
interface:
display_name: "Forge CLI"
short_description: "Copy-paste, non-interactive CLI for Forge"
@@ -0,0 +1,37 @@
# GitHub CLI recipe
Use `gh` commands in the current repository. Use `--json` for reads and `--body-file` for multiline bodies.
## Read
```bash
gh issue view ID --comments --json number,state,url,title,body,assignees,labels,comments,parent,subIssues,blockedBy
gh issue list --state all --limit 100 --json number,state,url,title,body,assignees,labels,parent,subIssues,blockedBy
gh pr view PR --comments --json number,state,url,title,body,assignees,labels,baseRefName,headRefName,comments,reviews,reviewDecision,statusCheckRollup,mergeable
gh pr checks PR --required --json bucket,name,state,completedAt
```
If an installed version rejects an optional JSON field, remove that field and rerun the same read. Native parent, child, and dependency fields may be unavailable; otherwise use the explicit links documented in the ticket.
## Issue lifecycle
```bash
gh issue edit ID --add-assignee USER
gh issue edit ID --add-label NEW --remove-label OLD
gh issue comment ID --body-file BODY_FILE
gh issue close ID
```
`@me` means the current authenticated user.
## Pull request lifecycle
```bash
gh pr create --base BASE --head HEAD --title TITLE --body-file BODY_FILE
gh pr comment PR --body-file BODY_FILE
gh pr review PR --comment --body-file BODY_FILE
gh pr review PR --request-changes --body-file BODY_FILE
gh pr merge PR --squash --delete-branch
```
Re-read the issue/PR after every mutation. Do not use `--admin` or `--auto`.
@@ -0,0 +1,34 @@
# GitLab CLI recipe
Use `glab` commands in the current repository. Use JSON output for reads and file-backed descriptions for multiline bodies.
## Read
```bash
glab issue view ID --comments --output json
glab issue list --all --per-page 100 --output json
glab mr view PR --comments --output json
```
Native parent, child, and dependency fields may be unavailable. If absent, use the explicit links documented in the ticket.
## Issue lifecycle
```bash
glab issue update ID --assignee USER
glab issue update ID --label NEW --unlabel OLD
glab issue note ID --message "$(cat BODY_FILE)"
glab issue close ID
```
`--assignee USER` replaces existing assignees; prefix with `+` to add without replacing.
## Merge request lifecycle
```bash
glab mr create --target-branch BASE --source-branch HEAD --title TITLE --description-file BODY_FILE --yes
glab mr note create PR --message "$(cat BODY_FILE)"
glab mr merge PR --squash --remove-source-branch --auto-merge=false --yes
```
Use `glab mr note create` for review findings or requested changes. Re-read the issue/MR after every mutation. Do not use auto-merge or bypass options.
@@ -0,0 +1,32 @@
# Tea recipe
Tea calls the numeric identifier an `index`; it is still the tracker issue/PR ID. Use `--output json` for reads. Tea accepts comma-separated usernames/labels for the plural flags.
## Read
```bash
tea issues ID --comments --output json --fields index,state,url,title,body,assignees,labels,comments
tea issues list --state all --limit 100 --output json --fields index,state,url,title,body,assignees,labels
tea pulls PR --comments --output json --fields index,state,url,title,body,assignees,labels,base,head,comments,ci
```
Native parent, child, and dependency fields may be unavailable. If absent, use the explicit links documented in the ticket.
## Issue lifecycle
```bash
tea issues edit --add-assignees USER ID
tea issues edit --add-labels NEW --remove-labels OLD ID
tea comments add ID --description "$(cat BODY_FILE)"
tea issues close ID
```
## Pull request lifecycle
```bash
tea pulls create --base BASE --head HEAD --title TITLE --description "$(cat BODY_FILE)"
tea comments add PR --description "$(cat BODY_FILE)"
tea pulls merge PR --style squash
```
Use `tea comments add` for review findings or requested changes. Re-read the issue/PR after every mutation.
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
set -u
remote="$(git remote get-url origin 2>/dev/null || true)"
if [[ -z "$remote" ]]; then
printf '%s\n' 'No origin remote found; run this inside a checked-out forge repository.' >&2
exit 1
fi
choice="${DEV_WORKFLOW_FORGE:-}"
if [[ -z "$choice" ]]; then
case "$remote" in
*github.com*) choice=gh ;;
*gitlab.com* | *gitlab.*) choice=glab ;;
*) choice=tea ;;
esac
fi
case "$choice" in
tea | gh | glab) ;;
*)
printf 'Unsupported DEV_WORKFLOW_FORGE=%s (use tea, gh, or glab).\n' "$choice" >&2
exit 1
;;
esac
if ! command -v "$choice" >/dev/null 2>&1; then
printf 'Required forge CLI not found: %s\n' "$choice" >&2
exit 1
fi
case "$choice" in
tea) "$choice" login list >/dev/null 2>&1 || {
printf '%s authentication check failed.\n' "$choice" >&2
exit 1
} ;;
gh) "$choice" auth status >/dev/null 2>&1 || {
printf '%s authentication check failed.\n' "$choice" >&2
exit 1
} ;;
glab) "$choice" auth status >/dev/null 2>&1 || {
printf '%s authentication check failed.\n' "$choice" >&2
exit 1
} ;;
esac
printf 'forge=%s\nremote=%s\n' "$choice" "$remote"
@@ -0,0 +1,7 @@
---
name: grill-with-docs
description: A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go.
disable-model-invocation: true
---
Call the Skill tool twice, for "grilling" and "domain-modeling".
@@ -0,0 +1,5 @@
interface:
display_name: "Grill with Docs"
short_description: "Grill a design and write its docs"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,40 @@
---
name: implement-spec
description: "Implement the result of /to-spec and /to-tickets in code."
disable-model-invocation: true
---
You have been provided a spec. This spec should have tickets associated with it, describing how to implement the spec.
The issue tracker should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`.
The goal is the entire spec implemented on a single **integration branch**, with every ticket resolved the way the issue tracker closes work.
The tickets are not a list of steps. They are a **task graph** with blocking relationships between them. This means there is always a **frontier** of tickets which are ready to be grabbed.
Communication to and from subagents should be sparse. Communicate primarily through **context pointers**: to the spec, tickets, research notes, and previous commits. Don't duplicate information already available via pointers.
**Implementer subagents** should be run in the background where possible for maximum concurrency.
## Steps
1. Read the spec and tickets to understand the task graph.
2. (optional) Use an **exploration subagent** to conduct any exploration required by the tickets - relevant codebase files or external documentation. Ensure the exploration subagent can save files - it should save its markdown notes in a directory outside the repo, accessible by all future subagents. This lets **implementer subagents** focus on implementation rather than exploration.
3. Create the integration branch. If the issue tracker closes work through PRs, or the user asks for one, open a draft PR after the first merge in step 5 (a branch with no commits ahead of main can't open one), marked as closing the spec and tickets.
4. Use **implementer subagents** to implement each ticket, each in its own worktree on its own branch. Each implementer subagent:
- confirms its worktree is based on the integration branch before starting, and resets onto it if not;
- calls the Skill tool with `tdd` to build the ticket;
- merges the integration branch tip into its own branch before reporting done
5. Once an **implementer subagent** completes, merge its work to the integration branch with a **merger subagent**.
6. If this changes the **frontier** of available tickets, kick off more **implementer subagents** to work on the new tickets. This allows for maximum concurrency.
7. Once all tickets are complete, call the Skill tool with `code-review` on the integration branch. Fix all issues raised by the code review in a single **implementer subagent**.
8. If a draft PR exists, mark it ready for review. Otherwise, resolve each ticket the way the issue tracker closes work, and report the integration branch.
9. Clean up all **implementer subagent** worktrees.
@@ -0,0 +1,5 @@
interface:
display_name: "Implement Spec"
short_description: "Implement the result of /to-spec and /to-tickets in code."
policy:
allow_implicit_invocation: false
+15
View File
@@ -0,0 +1,15 @@
---
name: implement
description: "Implement a piece of work based on a spec or set of tickets."
disable-model-invocation: true
---
Implement the work described by the user in the spec or tickets.
Use /tdd where possible, at pre-agreed seams.
Run typechecking regularly, single test files regularly, and the full test suite once at the end.
Once done, use /code-review to review the work.
Commit your work to the current branch.
@@ -0,0 +1,5 @@
interface:
display_name: "Implement"
short_description: "Build work from a spec or tickets"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,52 @@
---
name: implementation-orchestrator
description: Implements ready-for-agent tracker tickets through isolated worktrees, pull requests, review, conflict resolution, and merge. Use after wayfinder and planning have produced tickets, with or without a ticket ID/URL; no ticket ID/URL means process available tickets. Does not create planning tickets.
disable-model-invocation: true
---
# Implementation orchestrator
Use this skill only after the human-led wayfinder, plan, spec, and ticket phases. **A tracker ticket ID or URL is optional. Without one, process all eligible open tickets in the current repository.** With an argument, process only that ticket. An ID means the forge's issue/ticket identifier, not a branch, session, or PR ID.
## Compose before acting
Read and use these skills for their specialized work:
- `pi-subagents` for parallel workers and managed worktrees
- `worktrees` for worktree conventions and cleanup
- `code-review` for independent correctness/spec and standards review
- `resolving-merge-conflicts` for conflicts; never abort a merge or rebase
- `forge-cli` for forge selection, authentication, and CLI recipes
Load the shared `forge-cli` skill and run its bundled read-only preflight with the target repository as the working directory. Read only the detected CLI recipe; copy those commands instead of rediscovering syntax. Run `<cli> <command> --help` only when a recipe fails with an unknown command or flag. Do not add an API client or dependency.
## Durable state
The tracker is the source of truth. Read the root, every candidate ticket, and their existing comments before acting. Use one active label per ticket:
- `workflow:ready-for-agent`
- `workflow:ready-for-human`
- `workflow:implementing`
- `workflow:pr-open`
- `workflow:review`
- `workflow:changes-requested`
- `workflow:conflict`
- `workflow:blocked`
- `workflow:merged`
Comments are the message board. Record claims, status, evidence, questions, decisions, handoffs, PR URLs, check results, and recovery details there. If a worker has an issue with a ticket, comment on the ticket and wait for the human or another agent rather than guessing. For PR/MR issues, use the PR/MR's native comment/review function and also link the discussion from the ticket. Use `DEV_WORKFLOW_HUMAN_REVIEWER` or repository workflow configuration for the human identity; if none is configured, ask before assigning and do not invent an identity.
## Run loop
1. **Scope.** If a ticket ID/URL is supplied, confirm it belongs to the current repository and inspect only that ticket; do not process its siblings, parent, or descendants. If omitted, query all open tickets in the current repository. Use native child/dependency relationships; otherwise require explicit linked URLs or the documented blocker marker. Never infer order from titles.
2. **Schedule.** Eligible means open, unassigned, unblocked, and labelled `workflow:ready-for-agent`. Already `workflow:ready-for-human` tickets are skipped and reported. For a supplied ticket, process only that ticket; if it is blocked, report it and do not process its blockers. With no supplied ticket, build the dependency frontier: launch currently unblocked tickets in parallel, up to three workers, and hold dependent tickets until every blocker is merged or otherwise resolved. Re-query after each merge and launch newly unblocked tickets; dependency chains therefore run sequentially while unrelated tickets remain parallel.
3. **Claim.** Assign each selected ticket to the current forge identity before work. Replace its state with `workflow:implementing` and comment the claim.
4. **Implement.** Launch one worker per ticket with `pi-subagents` in an isolated worktree, maximum three in flight by default. Pass the complete ticket, comments, acceptance criteria, non-goals, linked context, and validation contract. Each worker makes only ticket-scoped changes, commits them, and reports changed files and checks.
5. **Escalate.** For missing requirements, unsafe ambiguity, credentials, unrelated scope, or a product/architecture decision, stop. For human review or judgment, assign the ticket to the configured human reviewer, apply `workflow:ready-for-human`, and comment the exact request. If no human identity is configured, ask before assigning and changing the state. Use `workflow:blocked` for non-human blockers. Preserve the worktree on failure.
6. **PR.** Run documented local checks. Push the branch and create exactly one PR/MR for the ticket. Link the ticket's tracker ID and title in the PR/MR, set `workflow:pr-open`, and comment the PR/MR URL on the ticket. Keep the worktree.
7. **Review.** Set `workflow:review`. Run a fresh-context `code-review` review with correctness/spec and standards axes separate. Post findings through the PR/MR comment/review function. For actionable findings, set `workflow:changes-requested`, send one fix worker, rerun checks, and repeat. Allow at most three rounds.
8. **Conflict.** Set `workflow:conflict`, then follow `resolving-merge-conflicts`. Inspect both intents, preserve them where possible, never invent behavior, never abort, rerun local checks, and update the PR/MR. If judgment is needed, assign the PR/MR and ticket to the configured human reviewer, apply `workflow:ready-for-human`, and comment the request in both places. If no human identity is configured, ask before assigning.
9. **Merge.** Merge only after independent review is clean, local checks pass, forge CI is green, the target is still the expected default branch, and no human decision or blocker remains. Comment the merge receipt and outcome, close the ticket, apply `workflow:merged` when supported, verify integration, then remove the worktree.
10. **Finish.** Report merged tickets and PR/MR URLs, human handoffs, blocked tickets, failed checks, review rounds, and remaining eligible tickets. Report `done` only when no open implementation or human tickets remain in the selected scope. If only human tickets remain, report `waiting-on-human`.
Never parallel-write a shared checkout. Never silently relabel an existing human ticket. Never merge around a failed check, unresolved review finding, conflict, or missing decision.
@@ -0,0 +1,5 @@
interface:
display_name: "Implementation Orchestrator"
short_description: "Implements ready-for-agent tracker tickets through isolated worktrees"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"
skill="$root/skills/engineering/implementation-orchestrator/SKILL.md"
shared_skill="$root/skills/engineering/forge-cli/SKILL.md"
recipes=(
"$root/skills/engineering/forge-cli/references/tea.md"
"$root/skills/engineering/forge-cli/references/gh.md"
"$root/skills/engineering/forge-cli/references/glab.md"
)
[[ -f "$skill" && -f "$shared_skill" && -f "${recipes[0]}" && -f "${recipes[1]}" && -f "${recipes[2]}" ]] || {
echo 'Missing skill or reference file' >&2
exit 1
}
head -1 "$skill" | grep -qx -- '---'
grep -q '^name: implementation-orchestrator$' "$skill"
grep -q '^description: ' "$skill"
head -1 "$shared_skill" | grep -qx -- '---'
grep -q '^name: forge-cli$' "$shared_skill"
grep -q '^description: ' "$shared_skill"
node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$root/package.json"
bash -n "$root/skills/engineering/forge-cli/scripts/detect-forge.sh"
printf '%s\n' 'implementation-orchestrator skill is valid'
@@ -0,0 +1,123 @@
# HTML Report Format
The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic.
## Scaffold
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Architecture review for {{repo name}}</title>
<script src="https://cdn.tailwindcss.com"></script>
<script type="module">
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
mermaid.initialize({ startOnLoad: true, theme: "neutral", securityLevel: "loose" });
</script>
<style>
/* small custom layer for things Tailwind doesn't cover cleanly:
dashed seam lines, hand-drawn-feeling arrow heads, etc. */
.seam { stroke-dasharray: 4 4; }
.leak { stroke: #dc2626; }
.deep { background: linear-gradient(135deg, #0f172a, #1e293b); }
</style>
</head>
<body class="bg-stone-50 text-slate-900 font-sans">
<main class="max-w-5xl mx-auto px-6 py-12 space-y-12">
<header>...</header>
<section id="candidates" class="space-y-10">...</section>
<section id="top-recommendation">...</section>
</main>
</body>
</html>
```
## Header
Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates.
## Candidate card
The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony.
Each candidate is one `<article>`:
- **Title**: short, names the deepening (e.g. "Collapse the Order intake pipeline").
- **Badge row**: recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`).
- **Files**: monospaced list, `font-mono text-sm`.
- **Before / After diagram**: the centrepiece. Two columns, side by side. See patterns below.
- **Problem**: one sentence. What hurts.
- **Solution**: one sentence. What changes.
- **Wins**: bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers".
- **ADR callout** (if applicable): one line in an amber-tinted box.
No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram.
## Diagram patterns
Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same. Variety is part of the point.
### Mermaid graph (the workhorse for dependencies / call flow)
Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1."
```html
<div class="rounded-lg border border-slate-200 bg-white p-4">
<pre class="mermaid">
flowchart LR
A[OrderHandler] --> B[OrderValidator]
B --> C[OrderRepo]
C -.leak.-> D[PricingClient]
classDef leak stroke:#dc2626,stroke-width:2px;
class C,D leak
</pre>
</div>
```
### Hand-built boxes-and-arrows (when Mermaid's layout fights you)
Modules as `<div>`s with borders and labels. Arrows as inline SVG `<line>` or `<path>` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight.
### Cross-section (good for layered shallowness)
Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility.
### Mass diagram (good for "interface as wide as implementation")
Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep).
### Call-graph collapse
Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it.
## Style guidance
- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate).
- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings.
- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling.
- Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI.
- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering.
## Top recommendation section
One larger card. Candidate name, one sentence on why, anchor link to its card. That's it.
## Tone
Plain English, concise, but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift.
**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality.
**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module).
**Phrasings that fit the style:**
- "Order intake module is shallow: interface nearly matches the implementation."
- "Pricing leaks across the seam."
- "Deepen: one interface, one place to test."
- "Two adapters justify the seam: HTTP in prod, in-memory in tests."
**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place.
No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one.
@@ -0,0 +1,71 @@
---
name: improve-codebase-architecture
description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.
disable-model-invocation: true
---
# Improve Codebase Architecture
Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
This command is _informed_ by the project's domain model and built on a shared design vocabulary:
- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary."
- The domain language in `CONTEXT.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate.
## Process
### 1. Explore
**Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look:
- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below.
- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net.
Read the project's domain glossary (`CONTEXT.md`) and any ADRs in the area you're touching first.
Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics; explore organically and note where you experience friction:
- Where does understanding one concept require bouncing between many small modules?
- Where are modules **shallow**, with an interface nearly as complex as the implementation?
- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)?
- Where do tightly-coupled modules leak across their seams?
- Which parts of the codebase are untested, or hard to test through their current interface?
Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want.
### 2. Present candidates as an HTML report
Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `<tmpdir>/architecture-review-<timestamp>.html` so each run gets a fresh file. Open it for the user (`xdg-open <path>` on Linux, `open <path>` on macOS, `start <path>` on Windows) and tell them the absolute path.
The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual.
For each candidate, render a card with:
- **Files**: which files/modules are involved
- **Problem**: why the current architecture is causing friction
- **Solution**: plain English description of what would change
- **Benefits**: explained in terms of locality and leverage, and how tests would improve
- **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening
- **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge
End the report with a **Top recommendation** section: which candidate you'd tackle first and why.
**Use CONTEXT.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service."
**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids.
See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance.
Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?"
### 3. Grilling loop
Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
Side effects happen inline as decisions crystallize; call the Skill tool with "domain-modeling" to keep the domain model current as you go:
- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md`. Create the file lazily if it doesn't exist.
- **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there.
- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones.
- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern.
@@ -0,0 +1,5 @@
interface:
display_name: "Improve Codebase Architecture"
short_description: "Find and grill architecture improvements"
policy:
allow_implicit_invocation: false
+3
View File
@@ -0,0 +1,3 @@
# Credits
The **Summary** section's menu of visuals (pseudocode, call trees, component trees, file trees, Mermaid, diffs) and its placement guidance come from [Dex Horthy](https://github.com/dexhorthy)'s [`show-me`](https://github.com/humanlayer/humanlayer) skill, reproduced almost word for word and aimed at a diff instead of a live conversation. `pr` does not depend on `show-me` as a skill (it isn't part of this repo, and a hard dependency would break standalone installs), so the content is copied in rather than pointed at; this file is the attribution a dependency would otherwise have carried.
+170
View File
@@ -0,0 +1,170 @@
---
name: pr
description: "Use when writing a PR body."
metadata:
credits:
skill: show-me
author: Dex Horthy
organisation: Humanlayer
url: "https://github.com/humanlayer/skills/blob/main/plugins/show-me/skills/show-me/SKILL.md"
---
Use this template for writing the PR body:
```markdown
## Summary
<diagram, diff-sketch, or tree>
## Evidence
- **Before:** <screenshot/output/failing test run>
**After:** <screenshot/output/passing test run>
## Merge Danger
**Door:** <one-way or two-way>
<optional: description>
**Blast Radius:** <one-word description>
<optional: potential ramifications of merge>
```
## Sections
Skip all preambles and keep prose brief. Use the user's domain language from `GLOSSARY.md`.
### Summary
Pick the smallest view that makes the key point clear.
- Show logic or an algorithm as pseudocode:
```text
on(save)
if content is unchanged
return cached result
write new content
return fresh result
```
- Show runtime control flow as a call tree:
```text
submitForm
createSession
persistPrompt
launchAgent
navigateToSession
```
- Show UI structure as a component tree, including state and module boundaries that matter:
```text
<SessionPage> (apps/example/src/routes/session.tsx)
useSessionEvents()
<SessionToolbar>
<RunSkillButton> (packages/ui)
```
- Show file responsibility or a broad refactor as a shallow file tree:
```text
src/
├── commands/ # parses user actions
├── sessions/ # owns session state
└── transport/ # sends API requests
```
- Show component interaction, control flow, or data flow with Mermaid:
```mermaid
sequenceDiagram
participant User
participant UI
participant Daemon
User->>UI: choose command
UI->>Daemon: send expanded prompt
Daemon-->>UI: stream result
```
- Use `diff` when the point is what changes and the surrounding shape already exists. Match the diff shape to the topic.
For a component change:
```diff
<SessionPage>
useSessionEvents()
<SessionToolbar>
+ <RunSkillButton />
<SessionTimeline>
+ <SkillResultCard />
```
For a file-layout change:
```diff
src/
├── commands/
+│ └── show-me.ts # expands the slash command
├── sessions/
-└── transport.ts
+└── transport/
+ ├── client.ts
+ └── stream.ts
```
For a call-tree or call-stack change:
```diff
submitForm
createSession
persistPrompt
+ expandSkillMention
launchAgent
- navigateToSession
+ navigateToSession
+ subscribeToEvents
```
For a state or control-flow change:
```diff
on(save)
- write content
+ if content is unchanged
+ return cached result
+ write new content
+ invalidate cache
```
- Show the whole block when most of it is new, when omitted context would hide ownership or order, or when the user needs a copyable target shape:
```ts
function expandSkill(command: string): string {
const skillName = command.slice(1);
return `use the ${skillName} skill`;
}
```
#### Guidance
Place each visual next to the short text it supports. Keep only the calls, files, props, states, and boundaries needed to answer the user's current question or the options to resolve the current discussion point.
You may use one of these, you may use several, it is unlikely you will use all of them. Use your judgement and don't overwhelm the user.
### Evidence
Concrete evidence that the change works. Show a before and after.
Screenshots are S-tier - when the environment is set up for it and the change is visual.
Execution-based evidence is A-tier. Test results, console output. Show the exact test that now fails and passes, using pseudocode.
### Merge Danger
Describe whether it's a one-way or two-way door. You can walk back through two-way doors, but not one-way doors. A PR that is cheap to roll back is lower risk. Changes that involve destructive actions or hard-to-reverse decisions are one-way doors.
The blast radius is the potential impact or scope of the changes introduced by this PR. Consider all possibilities. Examples are layout shift, breakages for consumers, mobile responsiveness, etc.
+3
View File
@@ -0,0 +1,3 @@
interface:
display_name: "PR"
short_description: "Write a PR body that's fast to review"
+67
View File
@@ -0,0 +1,67 @@
# Logic Prototype
A single, self-contained HTML file (a **shareable demo**) that lets anyone drive a state model by clicking buttons. Use this when the question is about **business logic, state transitions, or data shape**: the kind of thing that looks reasonable on paper but only feels wrong once you push it through real cases.
Because it's one file with nothing to install, you can hand it to a non-developer (a designer, a PM, a domain expert) and let them feel the model for themselves. So it speaks their language, not the code's.
## When this is the right shape
- "I'm not sure if this state machine handles the edge case where X then Y."
- "Does this data model actually let me represent the case where..."
- "I want to feel out what the API should look like before writing it."
- Anything where someone wants to **press buttons and watch state change**.
If the question is "what should this look like," this is the wrong branch. Use [UI.md](UI.md).
## Process
### 1. State the question
Before writing code, write down what state model and what question you're prototyping. One paragraph, at the top of the demo (in a visible intro, not just a comment). A logic prototype that answers the wrong question is pure waste, so make the question explicit so it can be checked later, whether the user is watching now or returning to it AFK.
### 2. Isolate the logic in a portable module
Put the actual logic (the bit that's answering the question) in a single `<script>` block written as a small, pure module that could be lifted out and dropped into the real codebase later. The page around it is throwaway; this module isn't.
The right shape depends on the question:
- **A pure reducer**: `(state, action) => state`. Good when actions are discrete events and state is a single value.
- **A state machine**: explicit states and transitions. Good when "which actions are even legal right now" is part of the question.
- **A small set of pure functions** over a plain data type. Good when there's no implicit current state, just transformations.
- **A class or module with a clear method surface** when the logic genuinely owns ongoing internal state.
Pick whichever shape best fits the question being asked, *not* whichever is easiest to wire to a page. Keep it pure: no DOM, no `document`, no button handlers reaching inside it. The page calls into it; nothing flows the other direction. This is what makes the prototype useful past its own lifetime: once the question's answered, the validated reducer / machine / function set lifts into the real module on its own.
### 3. Build the shareable HTML file
One file, plain HTML/CSS/JS: no framework, no bundler, no server, everything inline so it opens by double-click and survives being emailed around. Anyone should be able to run it by opening it.
Write it for a non-developer. Every label is in **domain language**, not code: buttons and state read like the business, not the reducer. Explain in plain words what's happening.
Lay it out with a clean hierarchy, top to bottom:
1. **Title and one-line explanation** of what this demo lets you explore (the question from step 1).
2. **Current state**: the full relevant state, rendered as a readable panel (labelled fields, not a raw JSON dump), re-rendered after every click so the change is visible. Where it helps a non-developer follow, call out what just changed.
3. **Free-play buttons**: one button per action, always available, so anyone can poke at the model in any order. Each click dispatches its action and re-renders the state.
4. **Guided walkthroughs**: a set of **scenarios**, one per tab. Each tab holds a short plain-language description of the scenario (the situation it sets up and what to watch for) and underneath it, the ordered **buttons to press** for that scenario. Each step is a real button: clicking it performs that action and moves to the next step. Starting a walkthrough resets to a known initial state so the scenario runs the same way every time.
Choose scenarios that demonstrate the awkward cases, the ones hard to reason about on paper: the happy path, a tricky edge case, an attempt at something that should be illegal.
Keep it beautiful but restrained: clean typography, generous spacing, one accent colour. No animations, no gimmicks: nothing that competes with the state and the buttons.
### 4. Hand it over
Send them the file, or open it for them. They'll click through the walkthroughs and free-play whenever they get to it; the interesting moments are when they say "wait, that shouldn't be possible" or "huh, I assumed X would be different"; those are the bugs in the _idea_, which is the whole point. If they want new actions or a new scenario, add them. Prototypes evolve.
### 5. Capture the answer and the prototype
Once the prototype has answered its question, capture the answer, then capture the prototype the way the [SKILL](SKILL.md) describes. The logic-specific mapping: the validated reducer / machine / function set lifts into the real module (the decision, absorbed); the HTML shell rides along to the throwaway branch that keeps the prototype as a primary source, and being one self-contained file, it stays trivially re-runnable there.
## Anti-patterns
- **Don't add tests.** A prototype that needs tests is no longer a prototype.
- **Don't wire it to the real database.** Use in-memory state unless the question is specifically about persistence.
- **Don't generalise.** No "what if we wanted to support X later." The prototype answers one question.
- **Don't blur the logic and the page together.** If the pure module references the DOM, `document`, or button handlers, it's no longer liftable. Keep the page as a thin shell over a pure module.
- **Don't reach for a framework, bundler, or server.** One file the recipient double-clicks; a React app or a dev server defeats "shareable".
- **Don't ship the HTML shell into production.** The page is optimised for being clicked through by hand. The logic module behind it is the bit worth keeping.
+26
View File
@@ -0,0 +1,26 @@
---
name: prototype
description: Build a throwaway prototype to answer a design question. Use when the user wants to sanity-check whether a state model or logic feels right, or explore what a UI should look like.
---
# Prototype
A prototype is **throwaway code that answers a question**. The question decides the shape.
## Pick a branch
Identify which question is being answered, using the user's prompt, the surrounding code, or by asking if the user is around:
- **"Does this logic / state model feel right?"** → [LOGIC.md](LOGIC.md). Build a single shareable HTML file (free-play buttons plus tabbed guided walkthroughs) that pushes the state machine through cases that are hard to reason about on paper, and that a non-developer can drive.
- **"What should this look like?"** → [UI.md](UI.md). Generate several radically different UI variations on a single route, switchable via a URL search param and a floating bottom bar.
The two branches produce very different artifacts, so getting this wrong wastes the whole prototype. If the question is genuinely ambiguous and the user isn't reachable, default to whichever branch better matches the surrounding code (a backend module → logic; a page or component → UI) and state the assumption at the top of the prototype.
## Rules that apply to both
1. **Throwaway from day one, and clearly marked as such.** Locate the prototype code close to where it will actually be used (next to the module or page it's prototyping for) so context is obvious, but name it so a casual reader can see it's a prototype, not production. For throwaway UI routes, obey whatever routing convention the project already uses; don't invent a new top-level structure.
2. **Trivial to run.** A UI prototype starts from one command in the project's task runner: `pnpm <name>`, `python <path>`, `bun <path>`, etc. A logic demo is a single HTML file the user double-clicks. Either way, no thinking required to start it.
3. **No persistence by default.** State lives in memory. Persistence is the thing the prototype is _checking_, not something it should depend on. If the question explicitly involves a database, hit a scratch DB or a local file with a clear "PROTOTYPE, wipe me" name.
4. **Skip the polish.** No tests, no error handling beyond what makes the prototype _runnable_, no abstractions. The point is to learn something fast.
5. **Surface the state.** After every action (logic) or on every variant switch (UI), print or render the full relevant state so the user can see what changed.
6. **Capture it when done.** Fold any validated decision into the real code, then capture the prototype itself as a **primary source**: commit it to a throwaway branch, out of main, and leave a context pointer to that branch on the implementation issue. Capture the answer too (the verdict and the question it settled) in the issue or a commit. The main branch keeps only the validated decision.
+112
View File
@@ -0,0 +1,112 @@
# UI Prototype
Generate **several radically different UI variations** on a single route, switchable from a floating bottom bar. The user flips between variants in the browser, picks one (or steals bits from each), then throws the rest away.
If the question is about logic/state rather than what something looks like, this is the wrong branch. Use [LOGIC.md](LOGIC.md).
## When this is the right shape
- "What should this page look like?"
- "I want to see a few options for this dashboard before committing."
- "Try a different layout for the settings screen."
- Any time the user would otherwise spend a day picking between three vague mockups in their head.
## Two sub-shapes: strongly prefer sub-shape A
A UI prototype is much easier to judge when it's **butting up against the rest of the app**: real header, real sidebar, real data, real density. A throwaway route on its own is a vacuum: every variant looks fine in isolation. Default to sub-shape A whenever there's a plausible existing page to host the variants. Only reach for sub-shape B if the prototype genuinely has no nearby home.
### Sub-shape A: adjustment to an existing page (preferred)
The route already exists. Variants are rendered **on the same route**, gated by a `?variant=` URL search param. The existing data fetching, params, and auth all stay. Only the rendering swaps. This is the default; pick it unless there's a specific reason not to.
If the prototype is for something that doesn't yet have a page but *would naturally live inside one* (a new section of the dashboard, a new card on the settings screen, a new step in an existing flow), it's still sub-shape A. Mount the variants inside the host page.
### Sub-shape B: a new page (last resort)
Only use this when the thing being prototyped genuinely has no existing page to live inside (e.g. an entirely new top-level surface, or a flow that can't be embedded anywhere sensible).
Create a **throwaway route** following whatever routing convention the project already uses. Don't invent a new top-level structure. Name it so it's obviously a prototype (e.g. include the word `prototype` in the path or filename). Same `?variant=` pattern.
Before committing to sub-shape B, sanity-check: is there really no existing page this could be embedded in? An empty route hides design problems that a populated one would expose.
In both sub-shapes the floating bottom bar is identical.
## Process
### 1. State the question and pick N
Default to **3 variants**. More than 5 stops being radically different and starts being noise, so cap there.
Write down the plan in one line, in the prototype's location or a top-of-file comment:
> "Three variants of the settings page, switchable via `?variant=`, on the existing `/settings` route."
This works whether the user is here to push back or not.
### 2. Generate radically different variants
Draft each variant. Hold each one to:
- The page's purpose and the data it has access to.
- The project's component library / styling system (TailwindCSS, shadcn, MUI, plain CSS, whatever).
- A clear exported component name, e.g. `VariantA`, `VariantB`, `VariantC`.
Variants must be **structurally different**: different layout, different information hierarchy, different primary affordance, not just different colours. Three slightly-tweaked card grids isn't a UI prototype, it's wallpaper. If two drafts come out too similar, redo one with explicit "do not use a card grid" guidance.
### 3. Wire them together
Create a single switcher component on the route:
```tsx
// pseudo-code, adapt to the project's framework
const variant = searchParams.get('variant') ?? 'A';
return (
<>
{variant === 'A' && <VariantA {...data} />}
{variant === 'B' && <VariantB {...data} />}
{variant === 'C' && <VariantC {...data} />}
<PrototypeSwitcher variants={['A','B','C']} current={variant} />
</>
);
```
For sub-shape A (existing page): keep all the existing data fetching above the switcher; only the rendered subtree changes per variant.
For sub-shape B (new page): the throwaway route under `/prototype/<name>` mounts the same switcher.
### 4. Build the floating switcher
A small fixed-position bar at the bottom-centre of the screen with three pieces:
- **Left arrow**: cycles to the previous variant (wraps around).
- **Variant label**: shows the current variant key and, if the variant exports a name, that name too. e.g. `B (Sidebar layout)`.
- **Right arrow**: cycles forward (wraps around).
Behaviour:
- Clicking an arrow updates the URL search param (use the framework's router, e.g. `router.replace` on Next, `navigate` on React Router, etc) so the variant is shareable and reload-stable.
- Keyboard: `←` and `→` arrow keys also cycle. Don't intercept arrow keys when an `<input>`, `<textarea>`, or `[contenteditable]` is focused.
- Visually distinct from the page (e.g. high-contrast pill, subtle shadow) so it's obviously not part of the design being evaluated.
- Hidden in production builds: gate on `process.env.NODE_ENV !== 'production'` or an equivalent check, so a stray prototype merge can't ship the bar to users.
Put the switcher in a single shared component so both sub-shapes can reuse it. Locate it wherever shared UI lives in the project.
### 5. Hand it over
Surface the URL (and the `?variant=` keys). The user will flip through whenever they get to it. The interesting feedback is usually **"I want the header from B with the sidebar from C"**, which is the actual design they want.
### 6. Capture the answer and clean up
Once a variant has won, capture the answer (which variant and why), then capture the prototype the way the [SKILL](SKILL.md) describes. Fold the winner into the real code and move the rest onto the throwaway branch, not into main:
- **Sub-shape A**: fold the winner into the existing page; drop the losing variants and the switcher from main.
- **Sub-shape B**: promote the winning variant to a real route; drop the throwaway route and the switcher from main.
The full set of variants is the primary source, so it lands on the throwaway branch, not the bin, since variant components and the switcher left in the main branch rot fast and confuse the next reader.
## Anti-patterns
- **Variants that differ only in colour or copy.** That's a tweak, not a prototype. Real variants disagree about structure.
- **Sharing too much code between variants.** A shared `<Header>` is fine; a shared `<Layout>` defeats the point. Each variant should be free to throw out the layout.
- **Wiring variants to real mutations.** Read-only prototypes are fine. If a variant needs to mutate, point it at a stub: the question is "what should this look like", not "does the backend work".
- **Promoting the prototype directly to production.** The variant code was written under prototype constraints (no tests, minimal error handling). Rewrite it properly when you fold it in.
@@ -0,0 +1,3 @@
interface:
display_name: "Prototype"
short_description: "Prototype to answer a design question"
@@ -0,0 +1,62 @@
---
name: recipe-diagrams
description: "Recipe diagrams: convert any recipe into a high-resolution Cooking for Engineers-style PNG process-flow table with aligned ingredient streams, preparation branches, joins, temperatures, timings, and finish steps. Use when the user asks for a recipe diagram."
compatibility: Requires Python 3 and ImageMagick.
disable-model-invocation: true
---
# Recipe diagrams
Convert the recipe into a dependency graph, then render that graph as a high-resolution Cooking for Engineers-style PNG table. Read the table left to right: ingredient rows are streams, columns are stages, and vertically merged action cells are joins.
## Steps
1. **Normalize the source.** Read the complete recipe, including yield, ingredient headings, ingredient preparation, numbered method, notes that alter execution, and any linked source the user supplied. Preserve quantities, equipment, temperatures, times, sensory completion cues, resting/cooling, and serving steps. The source is normalized when every execution-relevant source statement has one prospective home in the diagram.
2. **Build the dependency graph.** Separate global setup from ingredient streams and operations. Treat an ingredient's inline preparation (for example, `onion, diced`) as an operation unless it is purchased in that state. Split an ingredient into labeled portions when the source uses it at different stages. Keep independent preparations in the same column when order does not matter; place dependent operations in later columns. The graph is complete when every ingredient reaches every operation that consumes it and all operations lead to the finished result.
3. **Make the graph planar.** Order ingredient rows so every operation consumes one contiguous row range. Each later join spans the complete ranges of the intermediates it combines. Add columns until actions in one column have disjoint row ranges. The layout is complete when no action range is discontinuous and no two action ranges overlap within a column.
4. **Encode the layout.** Write a temporary JSON file using the schema below. Keep labels imperative and compact, but retain execution details. Use plain strings; the renderer transliterates symbols to ASCII.
```json
{
"title": "Recipe name",
"yield": "about 10 servings",
"setup": [
"Butter and flour a loaf pan",
"Preheat oven to 350 deg F (170 deg C)"
],
"ingredients": [
"2 large (250 g) ripe bananas",
"6 Tbsp (90 mL) butter"
],
"columns": [
{
"actions": [
{ "rows": [0, 0], "label": "mash" },
{ "rows": [1, 1], "label": "melt" }
]
},
{
"actions": [
{ "rows": [0, 1], "label": "mix until smooth" }
]
}
]
}
```
`rows` is an inclusive, zero-based ingredient-row range. A blank stage cell means that stream carries forward unchanged. A cell spanning several rows consumes those ingredients or the intermediates already produced from them. Put pan preparation, preheating, and other recipe-wide prerequisites in `setup`; put cooking, cooling, garnishing, and serving in action columns at their actual dependency point.
5. **Audit before rendering.** Compare the JSON against the source. Verify every ingredient and portion, every operation, all ordering constraints, and all execution details exactly once. Preserve genuine alternatives in the relevant label. Mark source uncertainty with `[?]` and explain it after the diagram rather than inventing a resolution. The audit is complete only when every source item is accounted for.
6. **Render, inspect, and return.** Resolve `scripts/render_recipe_diagram_png.py` relative to this `SKILL.md`, then run:
```bash
python3 scripts/render_recipe_diagram_png.py /tmp/recipe-diagram.json /tmp/recipe-diagram.png --width 3840
```
The renderer creates a 4K-wide PNG with an adaptive height, a local monospaced font, graphical borders, wrapped labels, and true vertically merged action cells. Set `RECIPE_DIAGRAM_FONT` to a `.ttf` or `.ttc` file to override the detected font. If the table is unusually dense, increase `--width`; do not alter the dependency graph merely to fit a chat viewport.
Open the generated PNG and inspect it before returning. Verify that the complete outer border is visible, text stays inside its cells, no labels overlap or clip, joins and row boundaries are unambiguous, and the image remains legible when scaled down. Return the PNG as an image attachment or clear file link rather than pasting an ASCII table. If `[?]` appears, follow the image with a short `Uncertainties` list. The output is complete when rasterization succeeds, the image is at least 3840 pixels wide, and visual inspection confirms crisp text and borders.
@@ -0,0 +1,406 @@
#!/usr/bin/env python3
"""Render a Cooking for Engineers-style recipe dependency graph as aligned ASCII."""
from __future__ import annotations
import argparse
import json
import sys
import textwrap
import unicodedata
from dataclasses import dataclass
from pathlib import Path
from typing import Any
ASCII_REPLACEMENTS = {
"°": " deg ",
"×": "x",
"–": "-",
"—": "-",
"−": "-",
"’": "'",
"‘": "'",
"“": '"',
"”": '"',
"¼": "1/4",
"½": "1/2",
"¾": "3/4",
"⅓": "1/3",
"⅔": "2/3",
"⅛": "1/8",
"⅜": "3/8",
"⅝": "5/8",
"⅞": "7/8",
}
class RecipeDiagramInputError(ValueError):
"""Reports malformed recipe diagram JSON with a searchable error prefix."""
@dataclass(frozen=True)
class RecipeAction:
"""An operation consuming one inclusive, contiguous range of ingredient rows."""
start_row: int
end_row: int
label: str
@dataclass(frozen=True)
class RecipeDiagram:
"""The validated recipe process-flow table consumed by the ASCII renderer."""
title: str
recipe_yield: str
setup: tuple[str, ...]
ingredients: tuple[str, ...]
columns: tuple[tuple[RecipeAction, ...], ...]
@dataclass(frozen=True)
class RecipeDiagramLayout:
"""Wrapped labels, row heights, and fixed column widths for one rendering."""
column_widths: tuple[int, ...]
row_heights: tuple[int, ...]
ingredient_lines: tuple[tuple[str, ...], ...]
action_lines: tuple[dict[RecipeAction, tuple[str, ...]], ...]
def ascii_recipe_text(value: str) -> str:
"""Transliterate recipe text so every rendered character is seven-bit ASCII."""
replaced = "".join(ASCII_REPLACEMENTS.get(character, character) for character in value)
normalized = unicodedata.normalize("NFKD", replaced)
ascii_text = normalized.encode("ascii", "ignore").decode("ascii")
return " ".join(ascii_text.split())
def require_recipe_string(value: Any, field_name: str, allow_empty: bool = False) -> str:
"""Validate and normalize one string field from recipe diagram JSON."""
if not isinstance(value, str):
raise RecipeDiagramInputError(f"{field_name} must be a string")
normalized = ascii_recipe_text(value)
if not allow_empty and not normalized:
raise RecipeDiagramInputError(f"{field_name} must not be empty")
return normalized
def parse_recipe_diagram(document: Any) -> RecipeDiagram:
"""Parse and validate the complete recipe diagram JSON document."""
if not isinstance(document, dict):
raise RecipeDiagramInputError("top-level JSON value must be an object")
title = require_recipe_string(document.get("title"), "title")
recipe_yield = require_recipe_string(document.get("yield", ""), "yield", allow_empty=True)
setup_value = document.get("setup", [])
if not isinstance(setup_value, list):
raise RecipeDiagramInputError("setup must be an array of strings")
setup = tuple(
require_recipe_string(item, f"setup[{index}]")
for index, item in enumerate(setup_value)
)
ingredients_value = document.get("ingredients")
if not isinstance(ingredients_value, list) or not ingredients_value:
raise RecipeDiagramInputError("ingredients must be a non-empty array of strings")
ingredients = tuple(
require_recipe_string(item, f"ingredients[{index}]")
for index, item in enumerate(ingredients_value)
)
columns_value = document.get("columns")
if not isinstance(columns_value, list) or not columns_value:
raise RecipeDiagramInputError("columns must be a non-empty array")
columns: list[tuple[RecipeAction, ...]] = []
for column_index, column_value in enumerate(columns_value):
if not isinstance(column_value, dict):
raise RecipeDiagramInputError(f"columns[{column_index}] must be an object")
actions_value = column_value.get("actions", [])
if not isinstance(actions_value, list):
raise RecipeDiagramInputError(f"columns[{column_index}].actions must be an array")
actions: list[RecipeAction] = []
occupied_rows: set[int] = set()
for action_index, action_value in enumerate(actions_value):
action_field = f"columns[{column_index}].actions[{action_index}]"
if not isinstance(action_value, dict):
raise RecipeDiagramInputError(f"{action_field} must be an object")
rows_value = action_value.get("rows")
if (
not isinstance(rows_value, list)
or len(rows_value) != 2
or any(isinstance(row, bool) or not isinstance(row, int) for row in rows_value)
):
raise RecipeDiagramInputError(f"{action_field}.rows must contain two integers")
start_row, end_row = rows_value
if start_row < 0 or end_row < start_row or end_row >= len(ingredients):
raise RecipeDiagramInputError(
f"{action_field}.rows must be an inclusive range within 0..{len(ingredients) - 1}"
)
action_rows = set(range(start_row, end_row + 1))
if occupied_rows.intersection(action_rows):
raise RecipeDiagramInputError(
f"{action_field}.rows overlaps another action in column {column_index}"
)
occupied_rows.update(action_rows)
actions.append(
RecipeAction(
start_row=start_row,
end_row=end_row,
label=require_recipe_string(action_value.get("label"), f"{action_field}.label"),
)
)
columns.append(tuple(sorted(actions, key=lambda action: action.start_row)))
return RecipeDiagram(
title=title,
recipe_yield=recipe_yield,
setup=setup,
ingredients=ingredients,
columns=tuple(columns),
)
def calculate_column_widths(total_width: int, process_column_count: int) -> tuple[int, ...]:
"""Allocate one ingredient width and equal process widths within total output width."""
table_column_count = process_column_count + 1
content_width = total_width - table_column_count - 1
minimum_ingredient_width = 24
minimum_process_width = 10
minimum_content_width = minimum_ingredient_width + minimum_process_width * process_column_count
if content_width < minimum_content_width:
minimum_total_width = minimum_content_width + table_column_count + 1
raise RecipeDiagramInputError(
f"diagram width {total_width} is too narrow; use --width {minimum_total_width} or greater"
)
ingredient_width = min(44, max(minimum_ingredient_width, int(content_width * 0.38)))
remaining_width = content_width - ingredient_width
process_width, extra_width = divmod(remaining_width, process_column_count)
widths = [ingredient_width]
widths.extend(
process_width + (1 if index < extra_width else 0)
for index in range(process_column_count)
)
return tuple(widths)
def wrap_recipe_label(label: str, width: int) -> tuple[str, ...]:
"""Wrap one ASCII label without breaking words unless a word exceeds the cell width."""
wrapped = textwrap.wrap(
label,
width=width,
break_long_words=True,
break_on_hyphens=False,
replace_whitespace=True,
drop_whitespace=True,
)
return tuple(wrapped or [""])
def build_recipe_layout(diagram: RecipeDiagram, total_width: int) -> RecipeDiagramLayout:
"""Compute wrapped cell content and enough row height for every merged action."""
column_widths = calculate_column_widths(total_width, len(diagram.columns))
ingredient_lines = tuple(
wrap_recipe_label(ingredient, column_widths[0]) for ingredient in diagram.ingredients
)
row_heights = [len(lines) for lines in ingredient_lines]
action_lines: list[dict[RecipeAction, tuple[str, ...]]] = []
for column_index, actions in enumerate(diagram.columns):
process_width = column_widths[column_index + 1]
wrapped_actions: dict[RecipeAction, tuple[str, ...]] = {}
for action in actions:
lines = wrap_recipe_label(action.label, process_width)
wrapped_actions[action] = lines
available_height = sum(row_heights[action.start_row : action.end_row + 1])
if len(lines) > available_height:
row_heights[action.end_row] += len(lines) - available_height
action_lines.append(wrapped_actions)
return RecipeDiagramLayout(
column_widths=column_widths,
row_heights=tuple(row_heights),
ingredient_lines=ingredient_lines,
action_lines=tuple(action_lines),
)
def find_row_action(actions: tuple[RecipeAction, ...], row_index: int) -> RecipeAction | None:
"""Find the merged action occupying one process-column row, if present."""
for action in actions:
if action.start_row <= row_index <= action.end_row:
return action
return None
def center_cell_text(text: str, width: int) -> str:
"""Center text in one fixed-width ASCII table cell."""
return text.center(width)
def render_horizontal_border(widths: tuple[int, ...], fill: str = "-") -> str:
"""Render a full table border using one ASCII fill character."""
return "+" + "+".join(fill * width for width in widths) + "+"
def render_merged_separator(
diagram: RecipeDiagram,
layout: RecipeDiagramLayout,
boundary_row: int,
) -> str:
"""Render a row boundary while leaving active row-spanning action cells open."""
segments = ["-" * layout.column_widths[0]]
for column_index, actions in enumerate(diagram.columns):
spanning_boundary = any(
action.start_row < boundary_row <= action.end_row for action in actions
)
fill = " " if spanning_boundary else "-"
segments.append(fill * layout.column_widths[column_index + 1])
return "+" + "+".join(segments) + "+"
def action_line_for_row(
action: RecipeAction,
wrapped_lines: tuple[str, ...],
row_index: int,
line_index: int,
row_heights: tuple[int, ...],
) -> str:
"""Place a merged action label at the vertical center of its complete row range."""
total_height = sum(row_heights[action.start_row : action.end_row + 1])
top_padding = (total_height - len(wrapped_lines)) // 2
lines_before_row = sum(row_heights[action.start_row:row_index])
merged_line_index = lines_before_row + line_index
label_line_index = merged_line_index - top_padding
if 0 <= label_line_index < len(wrapped_lines):
return wrapped_lines[label_line_index]
return ""
def render_recipe_diagram(diagram: RecipeDiagram, total_width: int) -> str:
"""Render and internally verify one complete aligned ASCII recipe diagram."""
layout = build_recipe_layout(diagram, total_width)
widths = layout.column_widths
lines: list[str] = []
title = diagram.title
if diagram.recipe_yield:
title = f"{title} ({diagram.recipe_yield})"
title_lines = wrap_recipe_label(title, total_width - 2)
lines.append(render_horizontal_border(widths))
for title_line in title_lines:
lines.append("|" + center_cell_text(title_line, total_width - 2) + "|")
lines.append(render_horizontal_border(widths))
for setup_line in diagram.setup:
for wrapped_setup_line in wrap_recipe_label(setup_line, total_width - 2):
lines.append("|" + center_cell_text(wrapped_setup_line, total_width - 2) + "|")
lines.append(render_horizontal_border(widths))
for row_index in range(len(diagram.ingredients)):
ingredient_row_lines = layout.ingredient_lines[row_index]
for line_index in range(layout.row_heights[row_index]):
ingredient_text = (
ingredient_row_lines[line_index]
if line_index < len(ingredient_row_lines)
else ""
)
cells = [ingredient_text.ljust(widths[0])]
for column_index, actions in enumerate(diagram.columns):
action = find_row_action(actions, row_index)
action_text = ""
if action is not None:
action_text = action_line_for_row(
action,
layout.action_lines[column_index][action],
row_index,
line_index,
layout.row_heights,
)
cells.append(center_cell_text(action_text, widths[column_index + 1]))
lines.append("|" + "|".join(cells) + "|")
if row_index < len(diagram.ingredients) - 1:
lines.append(render_merged_separator(diagram, layout, row_index + 1))
lines.append(render_horizontal_border(widths))
validate_rendered_diagram(lines, total_width)
return "\n".join(lines)
def validate_rendered_diagram(lines: list[str], expected_width: int) -> None:
"""Reject renderer output containing non-ASCII characters or misaligned lines."""
for line_number, line in enumerate(lines, start=1):
if len(line) != expected_width:
raise RuntimeError(
f"Recipe diagram renderer error: line {line_number} has width {len(line)}, expected {expected_width}"
)
if not line.isascii():
raise RuntimeError(
f"Recipe diagram renderer error: line {line_number} contains a non-ASCII character"
)
def load_recipe_document(input_path: Path) -> Any:
"""Load recipe diagram JSON from a named file or standard input."""
try:
if str(input_path) == "-":
return json.load(sys.stdin)
with input_path.open("r", encoding="utf-8") as input_file:
return json.load(input_file)
except (OSError, json.JSONDecodeError) as error:
raise RecipeDiagramInputError(f"cannot read {input_path}: {error}") from error
def parse_command_line() -> argparse.Namespace:
"""Parse the recipe diagram renderer command-line arguments."""
parser = argparse.ArgumentParser(
description="Render recipe dependency JSON as an aligned ASCII process-flow table."
)
parser.add_argument("input", type=Path, help="JSON input file, or - for standard input")
parser.add_argument(
"--width",
type=int,
default=120,
help="exact output width in ASCII characters (default: 120)",
)
return parser.parse_args()
def main() -> int:
"""Run the recipe diagram ASCII renderer command-line program."""
arguments = parse_command_line()
try:
document = load_recipe_document(arguments.input)
diagram = parse_recipe_diagram(document)
print(render_recipe_diagram(diagram, arguments.width))
except RecipeDiagramInputError as error:
print(f"Recipe diagram input error: {error}", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,390 @@
#!/usr/bin/env python3
"""Render recipe dependency JSON as a high-resolution PNG table."""
from __future__ import annotations
import argparse
import html
import os
import shutil
import subprocess
import sys
import tempfile
import textwrap
from dataclasses import dataclass
from pathlib import Path
from render_recipe_diagram import (
RecipeAction,
RecipeDiagram,
RecipeDiagramInputError,
ascii_recipe_text,
load_recipe_document,
parse_recipe_diagram,
)
@dataclass(frozen=True)
class PngLayout:
width: int
height: int
margin: int
table_x: int
table_width: int
column_widths: tuple[int, ...]
title_height: int
setup_heights: tuple[int, ...]
row_heights: tuple[int, ...]
ingredient_lines: tuple[tuple[str, ...], ...]
setup_lines: tuple[tuple[str, ...], ...]
action_lines: tuple[dict[RecipeAction, tuple[str, ...]], ...]
font_size: int
title_font_size: int
line_height: int
padding: int
def wrap_for_pixels(text: str, pixel_width: int, font_size: int, padding: int) -> tuple[str, ...]:
"""Wrap monospaced text using a conservative character-width estimate."""
usable_width = max(1, pixel_width - 2 * padding)
character_width = font_size * 0.62
character_count = max(1, int(usable_width / character_width))
lines = textwrap.wrap(
ascii_recipe_text(text),
width=character_count,
break_long_words=True,
break_on_hyphens=False,
replace_whitespace=True,
drop_whitespace=True,
)
return tuple(lines or [""])
def build_png_layout(diagram: RecipeDiagram, width: int) -> PngLayout:
"""Calculate a high-density table layout with readable wrapped text."""
if width < 1920:
raise RecipeDiagramInputError("PNG width must be at least 1920 pixels")
scale = width / 3840
margin = round(72 * scale)
padding = max(12, round(18 * scale))
font_size = max(20, round(34 * scale))
title_font_size = max(30, round(50 * scale))
line_height = max(29, round(47 * scale))
table_width = width - 2 * margin
process_count = len(diagram.columns)
ingredient_width = round(table_width * (0.24 if process_count >= 6 else 0.30))
remaining_width = table_width - ingredient_width
process_width, extra = divmod(remaining_width, process_count)
column_widths = (ingredient_width,) + tuple(
process_width + (1 if index < extra else 0) for index in range(process_count)
)
ingredient_lines = tuple(
wrap_for_pixels(ingredient, ingredient_width, font_size, padding)
for ingredient in diagram.ingredients
)
minimum_row_height = max(round(62 * scale), line_height + 2 * padding)
row_heights = [
max(minimum_row_height, len(lines) * line_height + 2 * padding)
for lines in ingredient_lines
]
action_lines: list[dict[RecipeAction, tuple[str, ...]]] = []
for column_index, actions in enumerate(diagram.columns):
wrapped_actions: dict[RecipeAction, tuple[str, ...]] = {}
cell_width = column_widths[column_index + 1]
for action in actions:
lines = wrap_for_pixels(action.label, cell_width, font_size, padding)
wrapped_actions[action] = lines
required_height = len(lines) * line_height + 2 * padding
available_height = sum(row_heights[action.start_row : action.end_row + 1])
if required_height > available_height:
row_heights[action.end_row] += required_height - available_height
action_lines.append(wrapped_actions)
setup_lines = tuple(
wrap_for_pixels(item, table_width, font_size, padding) for item in diagram.setup
)
setup_heights = tuple(len(lines) * line_height + 2 * padding for lines in setup_lines)
title_height = max(round(104 * scale), title_font_size + 2 * padding)
height = 2 * margin + title_height + sum(setup_heights) + sum(row_heights)
return PngLayout(
width=width,
height=height,
margin=margin,
table_x=margin,
table_width=table_width,
column_widths=column_widths,
title_height=title_height,
setup_heights=setup_heights,
row_heights=tuple(row_heights),
ingredient_lines=ingredient_lines,
setup_lines=setup_lines,
action_lines=tuple(action_lines),
font_size=font_size,
title_font_size=title_font_size,
line_height=line_height,
padding=padding,
)
def svg_text_lines(
lines: tuple[str, ...],
x: float,
center_y: float,
font_size: int,
line_height: int,
anchor: str,
weight: int = 500,
color: str = "#303446",
) -> str:
"""Create vertically centered SVG text elements for wrapped lines."""
first_baseline = center_y - ((len(lines) - 1) * line_height) / 2 + font_size * 0.35
escaped_anchor = html.escape(anchor, quote=True)
elements = []
for index, line in enumerate(lines):
elements.append(
f'<text x="{x:.1f}" y="{first_baseline + index * line_height:.1f}" '
f'text-anchor="{escaped_anchor}" font-size="{font_size}" font-weight="{weight}" '
f'fill="{color}">{html.escape(line)}</text>'
)
return "\n".join(elements)
def action_spans_boundary(actions: tuple[RecipeAction, ...], boundary_row: int) -> bool:
return any(action.start_row < boundary_row <= action.end_row for action in actions)
def render_svg(diagram: RecipeDiagram, layout: PngLayout) -> str:
"""Render the table as SVG so rasterization retains crisp geometry and text."""
scale = layout.width / 3840
border = max(2, round(3 * scale))
outer_border = max(6, round(10 * scale))
radius = max(8, round(14 * scale))
x_positions = [layout.table_x]
for cell_width in layout.column_widths:
x_positions.append(x_positions[-1] + cell_width)
parts = [
'<?xml version="1.0" encoding="UTF-8"?>',
f'<svg xmlns="http://www.w3.org/2000/svg" width="{layout.width}" height="{layout.height}" '
f'viewBox="0 0 {layout.width} {layout.height}">',
"<style>",
"text { font-family: monospace; }",
".rule { stroke: #51576d; stroke-linecap: square; shape-rendering: geometricPrecision; }",
"</style>",
f'<rect width="{layout.width}" height="{layout.height}" fill="#f7f7fb"/>',
f'<rect x="{layout.table_x}" y="{layout.margin}" width="{layout.table_width}" '
f'height="{layout.height - 2 * layout.margin}" rx="{radius}" fill="#ffffff" stroke="#51576d" stroke-width="{border}"/>',
]
y = layout.margin
title = diagram.title
if diagram.recipe_yield:
title = f"{title} ({diagram.recipe_yield})"
parts.append(
f'<path d="M {layout.table_x + radius} {y} H {layout.table_x + layout.table_width - radius} '
f'Q {layout.table_x + layout.table_width} {y} {layout.table_x + layout.table_width} {y + radius} '
f'V {y + layout.title_height} H {layout.table_x} V {y + radius} '
f'Q {layout.table_x} {y} {layout.table_x + radius} {y} Z" fill="#303446"/>'
)
title_lines = wrap_for_pixels(title, layout.table_width, layout.title_font_size, layout.padding)
parts.append(
svg_text_lines(
title_lines,
layout.table_x + layout.table_width / 2,
y + layout.title_height / 2,
layout.title_font_size,
round(layout.title_font_size * 1.3),
"middle",
weight=700,
color="#ffffff",
)
)
y += layout.title_height
parts.append(
f'<line class="rule" x1="{layout.table_x}" y1="{y}" x2="{layout.table_x + layout.table_width}" y2="{y}" stroke-width="{border}"/>'
)
for lines, setup_height in zip(layout.setup_lines, layout.setup_heights, strict=True):
parts.append(
f'<rect x="{layout.table_x}" y="{y}" width="{layout.table_width}" height="{setup_height}" fill="#e9eaf2"/>'
)
parts.append(
svg_text_lines(
lines,
layout.table_x + layout.table_width / 2,
y + setup_height / 2,
layout.font_size,
layout.line_height,
"middle",
weight=600,
)
)
y += setup_height
parts.append(
f'<line class="rule" x1="{layout.table_x}" y1="{y}" x2="{layout.table_x + layout.table_width}" y2="{y}" stroke-width="{border}"/>'
)
body_y = y
row_tops = [body_y]
for row_height in layout.row_heights:
row_tops.append(row_tops[-1] + row_height)
for row_index, row_height in enumerate(layout.row_heights):
fill = "#fbfbfd" if row_index % 2 == 0 else "#f4f5f9"
parts.append(
f'<rect x="{x_positions[0]}" y="{row_tops[row_index]}" width="{layout.column_widths[0]}" height="{row_height}" fill="{fill}"/>'
)
for column_index, actions in enumerate(diagram.columns):
for action in actions:
action_y = row_tops[action.start_row]
action_height = row_tops[action.end_row + 1] - action_y
parts.append(
f'<rect x="{x_positions[column_index + 1]}" y="{action_y}" '
f'width="{layout.column_widths[column_index + 1]}" height="{action_height}" fill="#f0eef8"/>'
)
for x in x_positions[1:-1]:
parts.append(
f'<line class="rule" x1="{x}" y1="{body_y}" x2="{x}" y2="{row_tops[-1]}" stroke-width="{border}"/>'
)
for boundary_row in range(1, len(diagram.ingredients)):
boundary_y = row_tops[boundary_row]
parts.append(
f'<line class="rule" x1="{x_positions[0]}" y1="{boundary_y}" x2="{x_positions[1]}" y2="{boundary_y}" stroke-width="{border}"/>'
)
for column_index, actions in enumerate(diagram.columns):
if not action_spans_boundary(actions, boundary_row):
parts.append(
f'<line class="rule" x1="{x_positions[column_index + 1]}" y1="{boundary_y}" '
f'x2="{x_positions[column_index + 2]}" y2="{boundary_y}" stroke-width="{border}"/>'
)
for row_index, lines in enumerate(layout.ingredient_lines):
parts.append(
svg_text_lines(
lines,
x_positions[0] + layout.padding,
(row_tops[row_index] + row_tops[row_index + 1]) / 2,
layout.font_size,
layout.line_height,
"start",
weight=600,
)
)
for column_index, actions in enumerate(diagram.columns):
for action in actions:
parts.append(
svg_text_lines(
layout.action_lines[column_index][action],
(x_positions[column_index + 1] + x_positions[column_index + 2]) / 2,
(row_tops[action.start_row] + row_tops[action.end_row + 1]) / 2,
layout.font_size,
layout.line_height,
"middle",
weight=500,
)
)
table_bottom = layout.height - layout.margin
table_right = layout.table_x + layout.table_width
parts.extend(
[
f'<rect x="{layout.table_x}" y="{layout.margin}" width="{layout.table_width}" height="{outer_border}" fill="#303446"/>',
f'<rect x="{layout.table_x}" y="{table_bottom - outer_border}" width="{layout.table_width}" height="{outer_border}" fill="#303446"/>',
f'<rect x="{layout.table_x}" y="{layout.margin}" width="{outer_border}" height="{table_bottom - layout.margin}" fill="#303446"/>',
f'<rect x="{table_right - outer_border}" y="{layout.margin}" width="{outer_border}" height="{table_bottom - layout.margin}" fill="#303446"/>',
]
)
parts.append("</svg>")
return "\n".join(parts)
def resolve_monospace_font() -> Path:
"""Find a crisp local monospace font for ImageMagick's SVG renderer."""
configured_font = os.environ.get("RECIPE_DIAGRAM_FONT")
candidates = [
configured_font,
"/System/Library/Fonts/SFNSMono.ttf",
"/System/Library/Fonts/Menlo.ttc",
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
"/usr/share/fonts/truetype/liberation2/LiberationMono-Regular.ttf",
]
for candidate in candidates:
if candidate and Path(candidate).is_file():
return Path(candidate)
raise RecipeDiagramInputError(
"no monospace font found; set RECIPE_DIAGRAM_FONT to a .ttf or .ttc file"
)
def rasterize_svg(svg: str, output_path: Path) -> None:
"""Rasterize SVG to PNG with ImageMagick."""
magick = shutil.which("magick")
if magick is None:
raise RecipeDiagramInputError("ImageMagick is required; install the `imagemagick` package")
font_path = resolve_monospace_font()
output_path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile("w", suffix=".svg", encoding="utf-8", delete=False) as svg_file:
svg_file.write(svg)
svg_path = Path(svg_file.name)
try:
result = subprocess.run(
[
magick,
"-font",
str(font_path),
str(svg_path),
"-strip",
"-define",
"png:color-type=6",
str(output_path),
],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
message = result.stderr.strip() or result.stdout.strip() or "unknown ImageMagick error"
raise RecipeDiagramInputError(f"cannot rasterize PNG: {message}")
finally:
svg_path.unlink(missing_ok=True)
def parse_command_line() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Render recipe dependency JSON as a high-resolution PNG")
parser.add_argument("input", type=Path, help="JSON input file")
parser.add_argument("output", type=Path, help="PNG output path")
parser.add_argument("--width", type=int, default=3840, help="PNG width in pixels (default: 3840)")
return parser.parse_args()
def main() -> int:
arguments = parse_command_line()
try:
diagram = parse_recipe_diagram(load_recipe_document(arguments.input))
layout = build_png_layout(diagram, arguments.width)
rasterize_svg(render_svg(diagram, layout), arguments.output)
print(f"Rendered {arguments.output} ({layout.width}x{layout.height})")
except RecipeDiagramInputError as error:
print(f"Recipe diagram PNG input error: {error}", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())
+12
View File
@@ -0,0 +1,12 @@
---
name: research
description: Investigate a question against high-trust primary sources and capture the findings as a Markdown file in the repo. Use when the user wants a topic researched, docs or API facts gathered, or reading legwork delegated to a background agent.
---
Spin up a **background agent** to do the research, so you keep working while it reads.
Its job:
1. Investigate the question against **primary sources** (official docs, source code, specs, first-party APIs), not a secondary write-up of them. Follow every claim back to the source that owns it.
2. Write the findings to a single Markdown file, citing each claim's source.
3. Save it where the repo already keeps such notes; match the existing convention, and if there is none, put it somewhere sensible and say where.
@@ -0,0 +1,3 @@
interface:
display_name: "Research"
short_description: "Research from high-trust sources"
@@ -0,0 +1,14 @@
---
name: resolving-merge-conflicts
description: "Use when you need to resolve an in-progress git merge/rebase conflict."
---
1. **See the current state** of the merge/rebase. Check git history, and the conflicting files.
2. **Find the primary sources** for each conflict. Understand deeply why each change was made, and what the original intent was. Read the commit messages, check the PRs, check original issues/tickets.
3. **Resolve each hunk.** Preserve both intents where possible. Where incompatible, pick the one matching the merge's stated goal and note the trade-off. Do **not** invent new behaviour. Always resolve; never `--abort`.
4. Discover the project's **automated checks** and run them, typically typecheck, then tests, then format. Fix anything the merge broke.
5. **Finish the merge/rebase.** Stage everything and commit. If rebasing, continue the rebase process until all commits are rebased.
@@ -0,0 +1,3 @@
interface:
display_name: "Resolving Merge Conflicts"
short_description: "Resolve merge and rebase conflicts"
+38
View File
@@ -0,0 +1,38 @@
---
name: tdd
description: Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
---
# Test-Driven Development
TDD is the red → green loop. This skill is the reference that makes that loop produce tests worth keeping: what a good test is, where tests go, the anti-patterns, and the rules of the loop. Every section applies on every cycle: consult them before and during the loop, not after.
When exploring the codebase, read `CONTEXT.md` (if it exists) so test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching.
## What a good test is
Tests verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't. A good test reads like a specification: "user can checkout with valid cart" tells you exactly what capability exists, and it survives refactors because it doesn't care about internal structure.
See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.
## Seams: where tests go
A **seam** is the public boundary you test at: the interface where you observe behavior without reaching inside. Tests live at seams, never against internals.
**Test only at pre-agreed seams.** Before writing any test, write down the seams under test and confirm them with the user. No test is written at an unconfirmed seam. You can't test everything, so agreeing the seams up front is how testing effort lands on the critical paths and complex logic instead of every edge case.
Ask: "What's the public interface, and which seams should we test?"
When the shape of that interface is itself in question (how deep the module is, where the seam belongs, what the interface should expose), call the Skill tool with "codebase-design" for the vocabulary. It is the shared source of the module, interface, depth, seam, adapter, leverage and locality terms, and it is a reference to consult, not a session to run.
## Anti-patterns
- **Implementation-coupled**: mocks internal collaborators, tests private methods, or verifies through a side channel (querying the database instead of using the interface). The tell: the test breaks when you refactor but behavior hasn't changed.
- **Tautological**: the assertion recomputes the expected value the way the code does (`expect(add(a, b)).toBe(a + b)`, a snapshot derived by hand the same way, a constant asserted equal to itself), so it passes by construction and can never disagree with the code. Expected values must come from an independent source of truth: a known-good literal, a worked example, the spec.
- **Horizontal slicing**: writing all tests first, then all implementation. Bulk tests verify _imagined_ behavior: you test the _shape_ of things rather than user-facing behavior, the tests go insensitive to real changes, and you commit to test structure before understanding the implementation. Work in **vertical slices** instead: one test → one implementation → repeat, each test a **tracer bullet** that responds to what the last cycle taught you.
## Rules of the loop
- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features.
- **One slice at a time.** One seam, one test, one minimal implementation per cycle.
- **Refactoring is not part of the loop.** It belongs to the review stage (see the `code-review` skill), not the red → green implementation cycle.
@@ -0,0 +1,3 @@
interface:
display_name: "TDD"
short_description: "Test-driven red-green-refactor"
+59
View File
@@ -0,0 +1,59 @@
# When to Mock
Mock at **system boundaries** only:
- External APIs (payment, email, etc.)
- Databases (sometimes - prefer test DB)
- Time/randomness
- File system (sometimes)
Don't mock:
- Your own classes/modules
- Internal collaborators
- Anything you control
## Designing for Mockability
At system boundaries, design interfaces that are easy to mock:
**1. Use dependency injection**
Pass external dependencies in rather than creating them internally:
```typescript
// Easy to mock
function processPayment(order, paymentClient) {
return paymentClient.charge(order.total);
}
// Hard to mock
function processPayment(order) {
const client = new StripeClient(process.env.STRIPE_KEY);
return client.charge(order.total);
}
```
**2. Prefer SDK-style interfaces over generic fetchers**
Create specific functions for each external operation instead of one generic function with conditional logic:
```typescript
// GOOD: Each function is independently mockable
const api = {
getUser: (id) => fetch(`/users/${id}`),
getOrders: (userId) => fetch(`/users/${userId}/orders`),
createOrder: (data) => fetch('/orders', { method: 'POST', body: data }),
};
// BAD: Mocking requires conditional logic inside the mock
const api = {
fetch: (endpoint, options) => fetch(endpoint, options),
};
```
The SDK approach means:
- Each mock returns one specific shape
- No conditional logic in test setup
- Easier to see which endpoints a test exercises
- Type safety per endpoint
+77
View File
@@ -0,0 +1,77 @@
# Good and Bad Tests
## Good Tests
**Integration-style**: Test through real interfaces, not mocks of internal parts.
```typescript
// GOOD: Tests observable behavior
test("user can checkout with valid cart", async () => {
const cart = createCart();
cart.add(product);
const result = await checkout(cart, paymentMethod);
expect(result.status).toBe("confirmed");
});
```
Characteristics:
- Tests behavior users/callers care about
- Uses public API only
- Survives internal refactors
- Describes WHAT, not HOW
- One logical assertion per test
## Bad Tests
**Implementation-detail tests**: Coupled to internal structure.
```typescript
// BAD: Tests implementation details
test("checkout calls paymentService.process", async () => {
const mockPayment = jest.mock(paymentService);
await checkout(cart, payment);
expect(mockPayment.process).toHaveBeenCalledWith(cart.total);
});
```
Red flags:
- Mocking internal collaborators
- Testing private methods
- Asserting on call counts/order
- Test breaks when refactoring without behavior change
- Test name describes HOW not WHAT
- Verifying through external means instead of interface
```typescript
// BAD: Bypasses interface to verify
test("createUser saves to database", async () => {
await createUser({ name: "Alice" });
const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]);
expect(row).toBeDefined();
});
// GOOD: Verifies through interface
test("createUser makes user retrievable", async () => {
const user = await createUser({ name: "Alice" });
const retrieved = await getUser(user.id);
expect(retrieved.name).toBe("Alice");
});
```
**Tautological tests**: Expected value restates the implementation, so the test passes by construction.
```typescript
// BAD: Expected value is recomputed the way the code computes it
test("calculateTotal sums line items", () => {
const items = [{ price: 10 }, { price: 5 }];
const expected = items.reduce((sum, i) => sum + i.price, 0);
expect(calculateTotal(items)).toBe(expected);
});
// GOOD: Expected value is an independent, known literal
test("calculateTotal sums line items", () => {
expect(calculateTotal([{ price: 10 }, { price: 5 }])).toBe(15);
});
```
+75
View File
@@ -0,0 +1,75 @@
---
name: to-spec
description: "Turn the current conversation into a spec and publish it to the project issue tracker: no interview, just synthesis of what you've already discussed."
disable-model-invocation: true
---
This skill takes the current conversation context and codebase understanding and produces a spec. Do NOT interview the user; just synthesize what you already know.
The issue tracker and triage label vocabulary should have been provided to you. If not, tell the user to run `setup-skills` skill.
## Process
1. Explore the repo to understand the current state of the codebase, if you haven't already. Use the project's domain glossary vocabulary throughout the spec, and respect any ADRs in the area you're touching.
2. Sketch out the seams at which you're going to test the feature. Existing seams should be preferred to new ones. Use the highest seam possible. If new seams are needed, propose them at the highest point you can. The fewer seams across the codebase, the better - the ideal number is one.
Check with the user that these seams match their expectations.
3. Write the spec using the template below, then publish it to the project issue tracker. Apply the `ready-for-agent` triage label - no need for additional triage.
<spec-template>
## Problem Statement
The problem that the user is facing, from the user's perspective.
## Solution
The solution to the problem, from the user's perspective.
## User Stories
A LONG, numbered list of user stories. Each user story should be in the format of:
1. As an <actor>, I want a <feature>, so that <benefit>
<user-story-example>
1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending
</user-story-example>
This list of user stories should be extremely extensive and cover all aspects of the feature.
## Implementation Decisions
A list of implementation decisions that were made. This can include:
- The modules that will be built/modified
- The interfaces of those modules that will be modified
- Technical clarifications from the developer
- Architectural decisions
- Schema changes
- API contracts
- Specific interactions
Do NOT include specific file paths or code snippets. They may end up being outdated very quickly.
Exception: if a prototype produced a snippet that encodes a decision more precisely than prose can (state machine, reducer, schema, type shape), inline it within the relevant decision and note briefly that it came from a prototype. Trim to the decision-rich parts, not a working demo, just the important bits.
## Testing Decisions
A list of testing decisions that were made. Include:
- A description of what makes a good test (only test external behavior, not implementation details)
- Which modules will be tested
- Prior art for the tests (i.e. similar types of tests in the codebase)
## Out of Scope
A description of the things that are out of scope for this spec.
## Further Notes
Any further notes about the feature.
</spec-template>
@@ -0,0 +1,5 @@
interface:
display_name: "To Spec"
short_description: "Turn a conversation into a spec"
policy:
allow_implicit_invocation: false
+105
View File
@@ -0,0 +1,105 @@
---
name: to-tickets
description: Break a plan, spec, or the current conversation into a set of tracer-bullet tickets, each declaring its blocking edges, published to the configured tracker (edges as text in one file per ticket locally, or native blocking links on a real tracker).
disable-model-invocation: true
---
# To Tickets
Break a plan, spec, or conversation into a set of **tickets**: tracer-bullet vertical slices, each declaring the tickets that **block** it.
The issue tracker and triage label vocabulary should have been provided to you. If not, tell the user to run `setup-skills` skill.
## Process
### 1. Gather context
Work from whatever is already in the conversation context. If the user passes a reference (a spec path, an issue number or URL) as an argument, fetch it and read its full body and comments.
### 2. Explore the codebase (optional)
If you have not already explored the codebase, do so to understand the current state of the code. Ticket titles and descriptions should use the project's domain glossary vocabulary, and respect ADRs in the area you're touching.
Look for opportunities to prefactor the code to make the implementation easier. "Make the change easy, then make the easy change."
### 3. Draft vertical slices
Break the work into **tracer bullet** tickets.
<vertical-slice-rules>
- Each slice cuts a narrow but COMPLETE path through every layer (schema, API, UI, tests): vertical, NOT a horizontal slice of one layer
- A completed slice is demoable or verifiable on its own
- Each slice is sized to fit in a single fresh context window
- Any prefactoring should be done first
</vertical-slice-rules>
Give each ticket its **blocking edges**: the other tickets that must complete before it can start. A ticket with no blockers can start immediately.
**Wide refactors are the exception to vertical slicing.** A **wide refactor** is one mechanical change (rename a column, retype a shared symbol) whose **blast radius** fans across the whole codebase, so a single edit breaks thousands of call sites at once and no vertical slice can land green. Don't force it into a tracer bullet; sequence it as **expand–contract**. First expand: add the new form beside the old so nothing breaks. Then migrate the call sites over in batches sized by blast radius (per package, per directory), each batch its own ticket blocked by the expand, keeping CI green batch to batch because the old form still exists. Finally contract: delete the old form once no caller remains, in a ticket blocked by every migrate batch. When even the batches can't stay green alone, keep the sequence but let them share an integration branch that all block a final integrate-and-verify ticket; green is promised only there.
### 4. Quiz the user
Present the proposed breakdown as a numbered list. For each ticket, show:
- **Title**: short descriptive name
- **Blocked by**: which other tickets (if any) must complete first
- **What it delivers**: the end-to-end behaviour this ticket makes work
Ask the user:
- Does the granularity feel right? (too coarse / too fine)
- Are the blocking edges correct: does each ticket only depend on tickets that genuinely gate it?
- Should any tickets be merged or split further?
Iterate until the user approves the breakdown.
### 5. Publish the tickets to the configured tracker
Publish the approved tickets. **How** depends on the tracker `setup-skills` skill configured; the tickets are the same either way, only the shape of the blocking edges changes:
- **Local files** → write one file per ticket under `.scratch/<feature-slug>/issues/<NN>-<slug>.md`, numbered from `01` in dependency order (blockers first). Each file's "Blocked by" lists the numbers/titles it depends on. Use the per-ticket file template below: one ticket per file, never a single combined file.
- **A real issue tracker (GitHub, Linear, …)** → publish one issue per ticket in dependency order (blockers first) so each ticket's blocking edges can reference real identifiers. Use the platform's native blocking / sub-issue relationship where it has one; otherwise set each ticket's "Blocked by" to the blocking issues. Apply the `ready-for-agent` triage label unless instructed otherwise; the tickets are agent-grabbable by construction.
Work the **frontier**: any ticket whose blockers are all done. For a purely linear chain that means top to bottom.
Do NOT close or modify any parent issue.
<local-ticket-template>
# <NN>: <Ticket title>
**What to build:** the end-to-end behaviour this ticket makes work, from the user's perspective, not a layer-by-layer implementation list.
**Blocked by:** the numbers/titles of the tickets that gate this one, or "None (can start immediately)".
**Status:** ready-for-agent
- [ ] Acceptance criterion 1
- [ ] Acceptance criterion 2
</local-ticket-template>
<issue-template>
## Parent
A reference to the parent issue on the tracker (if the source was an existing issue, otherwise omit this section).
## What to build
The end-to-end behaviour this ticket makes work, from the user's perspective, not layer-by-layer implementation.
## Acceptance criteria
- [ ] Criterion 1
- [ ] Criterion 2
## Blocked by
- A reference to each blocking ticket, or "None (can start immediately)".
</issue-template>
In either form, avoid specific file paths or code snippets: they go stale fast. Exception: if a prototype produced a snippet that encodes a decision more precisely than prose can (state machine, reducer, schema, type shape), inline it and note briefly that it came from a prototype. Trim to the decision-rich parts, not a working demo, just the important bits.
@@ -0,0 +1,5 @@
interface:
display_name: "To Tickets"
short_description: "Split a plan into tracer-bullet tickets"
policy:
allow_implicit_invocation: false
+207
View File
@@ -0,0 +1,207 @@
# Writing Agent Briefs
An agent brief is a structured comment posted on a GitHub issue or PR when it moves to `ready-for-agent`. It is the authoritative specification that an AFK agent will work from. The original body and discussion are context: the agent brief is the contract.
The brief states **what the agent should do**, which stretches to both surfaces: for an issue, that's building the change from nothing; for a PR, it's what's left to do *to the existing diff*: finish it, close gaps, address review points. Same principles either way; the PR example below shows the difference.
## Principles
### Durability over precision
The issue may sit in `ready-for-agent` for days or weeks. The codebase will change in the meantime. Write the brief so it stays useful even as files are renamed, moved, or refactored.
- **Do** describe interfaces, types, and behavioral contracts
- **Do** name specific types, function signatures, or config shapes that the agent should look for or modify
- **Don't** reference file paths: they go stale
- **Don't** reference line numbers
- **Don't** assume the current implementation structure will remain the same
### Behavioral, not procedural
Describe **what** the system should do, not **how** to implement it. The agent will explore the codebase fresh and make its own implementation decisions.
- **Good:** "The `SkillConfig` type should accept an optional `schedule` field of type `CronExpression`"
- **Bad:** "Open src/types/skill.ts and add a schedule field on line 42"
- **Good:** "When a user runs `/triage` with no arguments, they should see a summary of issues needing attention"
- **Bad:** "Add a switch statement in the main handler function"
### Complete acceptance criteria
The agent needs to know when it's done. Every agent brief must have concrete, testable acceptance criteria. Each criterion should be independently verifiable.
- **Good:** "Running `gh issue list --label needs-triage` returns issues that have been through initial classification"
- **Bad:** "Triage should work correctly"
### Explicit scope boundaries
State what is out of scope. This prevents the agent from gold-plating or making assumptions about adjacent features.
## Template
```markdown
## Agent Brief
**Category:** bug / enhancement
**Summary:** one-line description of what needs to happen
**Current behavior:**
Describe what happens now. For bugs, this is the broken behavior.
For enhancements, this is the status quo the feature builds on.
**Desired behavior:**
Describe what should happen after the agent's work is complete.
Be specific about edge cases and error conditions.
**Key interfaces:**
- `TypeName`: what needs to change and why
- `functionName()` return type: what it currently returns vs what it should return
- Config shape: any new configuration options needed
**Acceptance criteria:**
- [ ] Specific, testable criterion 1
- [ ] Specific, testable criterion 2
- [ ] Specific, testable criterion 3
**Out of scope:**
- Thing that should NOT be changed or addressed in this issue
- Adjacent feature that might seem related but is separate
```
## Examples
### Good agent brief (bug)
```markdown
## Agent Brief
**Category:** bug
**Summary:** Skill description truncation drops mid-word, producing broken output
**Current behavior:**
When a skill description exceeds 1024 characters, it is truncated at exactly
1024 characters regardless of word boundaries. This produces descriptions
that end mid-word (e.g. "Use when the user wants to confi").
**Desired behavior:**
Truncation should break at the last word boundary before 1024 characters
and append "..." to indicate truncation.
**Key interfaces:**
- The `SkillMetadata` type's `description` field: no type change needed,
but the validation/processing logic that populates it needs to respect
word boundaries
- Any function that reads SKILL.md frontmatter and extracts the description
**Acceptance criteria:**
- [ ] Descriptions under 1024 chars are unchanged
- [ ] Descriptions over 1024 chars are truncated at the last word boundary
before 1024 chars
- [ ] Truncated descriptions end with "..."
- [ ] The total length including "..." does not exceed 1024 chars
**Out of scope:**
- Changing the 1024 char limit itself
- Multi-line description support
```
### Good agent brief (enhancement)
```markdown
## Agent Brief
**Category:** enhancement
**Summary:** Add `.out-of-scope/` directory support for tracking rejected feature requests
**Current behavior:**
When a feature request is rejected, the issue is closed with a `wontfix` label
and a comment. There is no persistent record of the decision or reasoning.
Future similar requests require the maintainer to recall or search for the
prior discussion.
**Desired behavior:**
Rejected feature requests should be documented in `.out-of-scope/<concept>.md`
files that capture the decision, reasoning, and links to all issues that
requested the feature. When triaging new issues, these files should be
checked for matches.
**Key interfaces:**
- Markdown file format in `.out-of-scope/`: each file should have a
`# Concept Name` heading, a `**Decision:**` line, a `**Reason:**` line,
and a `**Prior requests:**` list with issue links
- The triage workflow should read all `.out-of-scope/*.md` files early
and match incoming issues against them by concept similarity
**Acceptance criteria:**
- [ ] Closing a feature as wontfix creates/updates a file in `.out-of-scope/`
- [ ] The file includes the decision, reasoning, and link to the closed issue
- [ ] If a matching `.out-of-scope/` file already exists, the new issue is
appended to its "Prior requests" list rather than creating a duplicate
- [ ] During triage, existing `.out-of-scope/` files are checked and surfaced
when a new issue matches a prior rejection
**Out of scope:**
- Automated matching (human confirms the match)
- Reopening previously rejected features
- Bug reports (only enhancement rejections go to `.out-of-scope/`)
```
### Good agent brief (PR)
For a PR, "Current behavior" describes the state of the diff, and the brief asks the agent to finish or fix it rather than build from scratch.
```markdown
## Agent Brief
**Category:** enhancement
**Summary:** Finish the contributor's `--json` output flag for `triage list`
**Current behavior:**
The PR adds a `--json` flag that serializes the issue list to JSON. The happy
path works and the diff matches the project's command structure. Two gaps
remain: errors are still printed as human text (not JSON), and the new flag has
no test coverage.
**Desired behavior:**
With `--json`, all output (including errors) is well-formed JSON on stdout,
and the command's exit codes are unchanged. The existing human-readable output
is untouched when the flag is absent.
**Key interfaces:**
- The command's error path should emit `{ "error": string }` under `--json`
instead of the plain-text error
- Reuse the existing serializer the PR already added; don't introduce a second
**Acceptance criteria:**
- [ ] `triage list --json` emits valid JSON for both success and error cases
- [ ] Exit codes match the non-JSON command
- [ ] A test covers the `--json` success output and one error case
- [ ] Default (non-JSON) output is byte-for-byte unchanged
**Out of scope:**
- Adding `--json` to any other command
- Changing the JSON shape of the success payload the PR already defined
```
### Bad agent brief
```markdown
## Agent Brief
**Summary:** Fix the triage bug
**What to do:**
The triage thing is broken. Look at the main file and fix it.
The function around line 150 has the issue.
**Files to change:**
- src/triage/handler.ts (line 150)
- src/types.ts (line 42)
```
This is bad because:
- No category
- Vague description ("the triage thing is broken")
- References file paths and line numbers that will go stale
- No acceptance criteria
- No scope boundaries
- No description of current vs desired behavior
+105
View File
@@ -0,0 +1,105 @@
# Out-of-Scope Knowledge Base
The `.out-of-scope/` directory in a repo stores persistent records of rejected feature requests. It serves two purposes:
1. **Institutional memory**: why a feature was rejected, so the reasoning isn't lost when the issue is closed
2. **Deduplication**: when a new issue comes in that matches a prior rejection, the skill can surface the previous decision instead of re-litigating it
## Directory structure
```
.out-of-scope/
├── dark-mode.md
├── plugin-system.md
└── graphql-api.md
```
One file per **concept**, not per issue. Multiple issues requesting the same thing are grouped under one file.
## File format
The file should be written in a relaxed, readable style, more like a short design document than a database entry. Use paragraphs, code samples, and examples to make the reasoning clear and useful to someone encountering it for the first time.
```markdown
# Dark Mode
This project does not support dark mode or user-facing theming.
## Why this is out of scope
The rendering pipeline assumes a single color palette defined in
`ThemeConfig`. Supporting multiple themes would require:
- A theme context provider wrapping the entire component tree
- Per-component theme-aware style resolution
- A persistence layer for user theme preferences
This is a significant architectural change that doesn't align with the
project's focus on content authoring. Theming is a concern for downstream
consumers who embed or redistribute the output.
```ts
// The current ThemeConfig interface is not designed for runtime switching:
interface ThemeConfig {
colors: ColorPalette; // single palette, resolved at build time
fonts: FontStack;
}
```
## Prior requests
- #42: "Add dark mode support"
- #87: "Night theme for accessibility"
- #134: "Dark theme option"
```
### Naming the file
Use a short, descriptive kebab-case name for the concept: `dark-mode.md`, `plugin-system.md`, `graphql-api.md`. The name should be recognizable enough that someone browsing the directory understands what was rejected without opening the file.
### Writing the reason
The reason should be substantive: not "we don't want this" but why. Good reasons reference:
- Project scope or philosophy ("This project focuses on X; theming is a downstream concern")
- Technical constraints ("Supporting this would require Y, which conflicts with our Z architecture")
- Strategic decisions ("We chose to use A instead of B because...")
The reason should be durable. Avoid referencing temporary circumstances ("we're too busy right now"); those aren't real rejections, they're deferrals.
## When to check `.out-of-scope/`
During triage (Step 1: Gather context), read all files in `.out-of-scope/`. When evaluating a new issue:
- Check if the request matches an existing out-of-scope concept
- Matching is by concept similarity, not keyword: "night theme" matches `dark-mode.md`
- If there's a match, surface it to the maintainer: "This is similar to `.out-of-scope/dark-mode.md`. We rejected this before because [reason]. Do you still feel the same way?"
The maintainer may:
- **Confirm**: the new issue gets added to the existing file's "Prior requests" list, then closed
- **Reconsider**: the out-of-scope file gets deleted or updated, and the issue proceeds through normal triage
- **Disagree**: the issues are related but distinct, proceed with normal triage
## When to write to `.out-of-scope/`
Only when an **enhancement** (not a bug) is *rejected* as `wontfix`. This applies to enhancement PRs exactly as it does to issues: a rejected PR is recorded here so the same request doesn't return as fresh code.
Do **not** write here when something is closed as `wontfix` because it's **already implemented**. That's a built feature, not a rejected one; recording it would poison the dedup checks with false rejections. Instead, the closing comment points to where the feature already lives.
The flow:
1. Maintainer decides a feature request is out of scope
2. Check if a matching `.out-of-scope/` file already exists
3. If yes: append the new issue to the "Prior requests" list
4. If no: create a new file with the concept name, decision, reason, and first prior request
5. Post a comment on the issue explaining the decision and mentioning the `.out-of-scope/` file
6. Close the issue with the `wontfix` label
## Updating or removing out-of-scope files
If the maintainer changes their mind about a previously rejected concept:
- Delete the `.out-of-scope/` file
- The skill does not need to reopen old issues; they're historical records
- The new issue that triggered the reconsideration proceeds through normal triage
+112
View File
@@ -0,0 +1,112 @@
---
name: triage
description: Move issues and external PRs through a state machine of triage roles, categorise, verify, grill if needed, and write agent-ready briefs.
disable-model-invocation: true
---
# Triage
Move issues on the project issue tracker through a small state machine of triage roles.
If this repo treats external pull requests as a request surface (see the issue-tracker config), triage covers them too: **a PR is an issue with attached code**, using the same roles, same states, and same machine, with a few deltas marked "for a PR" below. Resolve a bare `#42` to an issue or PR per the tracker config.
Every comment or issue posted to the issue tracker during triage **must** start with this disclaimer:
```
> *This was generated by AI during triage.*
```
## Reference docs
- [AGENT-BRIEF.md](AGENT-BRIEF.md): how to write durable agent briefs
- [OUT-OF-SCOPE.md](OUT-OF-SCOPE.md): how the `.out-of-scope/` knowledge base works
## Roles
Two **category** roles:
- `bug`: something is broken
- `enhancement`: new feature or improvement
Five **state** roles:
- `needs-triage`: maintainer needs to evaluate
- `needs-info`: waiting on reporter for more information
- `ready-for-agent`: fully specified, ready for an AFK agent
- `ready-for-human`: needs human implementation
- `wontfix`: will not be actioned
For a PR, the same states read against the attached code: `ready-for-agent` means a brief is attached and an agent should take the next step on the diff; `ready-for-human` means it's ready for a human to merge.
Every triaged issue should carry exactly one category role and one state role. If state roles conflict, flag it and ask the maintainer before doing anything else.
These are canonical role names. The actual label strings used in the issue tracker may differ. The mapping should have been provided to you. If not, tell the user to run `setup-skills` skill.
State transitions: an unlabeled issue normally goes to `needs-triage` first; from there it moves to `needs-info`, `ready-for-agent`, `ready-for-human`, or `wontfix`. `needs-info` returns to `needs-triage` once the reporter replies. The maintainer can override at any time; flag transitions that look unusual and ask before proceeding.
## Invocation
The maintainer invokes `/triage` and describes what they want in natural language. Interpret the request and act. Examples:
- "Show me anything that needs my attention"
- "Let's look at #42" (issue or PR)
- "Move #42 to ready-for-agent"
- "What's ready for agents to pick up?"
## Show what needs attention
Query the issue tracker and present three buckets, oldest first:
1. **Unlabeled**: never triaged.
2. **`needs-triage`**: evaluation in progress.
3. **`needs-info` with reporter activity since the last triage notes**: needs re-evaluation.
When PRs are in scope, include external PRs in these buckets and tag each line `[PR]` or `[issue]`. Discovery surfaces only *external* PRs (the tracker config defines who counts as external), so a collaborator's in-flight PR is not triage work. This filter is discovery-only; an explicitly named PR is always triaged regardless of author.
Show counts and a one-line summary per item. Let the maintainer pick.
## Triage a specific issue or PR
1. **Gather context.** Read the full issue or PR (body, comments, labels, author, dates; for a PR, the diff too). Parse any prior triage notes so you don't re-ask resolved questions. Explore the codebase using the project's domain glossary, respecting ADRs in the area. Run two checks against the codebase: (a) **redundancy**: search for an existing implementation of the requested behavior by domain concept (not just the request's wording), and report where you looked. If found, it's an already-implemented `wontfix` (step 5). (b) **prior rejection**: read `.out-of-scope/*.md` and surface any that resembles this request.
2. **Recommend.** Tell the maintainer your category and state recommendation with reasoning, plus a brief codebase summary relevant to the request (including whether it's already implemented). Wait for direction.
3. **Verify the claim.** Before any grilling, check that the claim holds up. For a bug, reproduce it from the reporter's steps. For a PR, confirm the diff does what it claims: check it out, run the relevant tests or commands. Report what happened: confirmed (with code path), failed, or insufficient detail (a strong `needs-info` signal). A confirmed verification makes a much stronger agent brief.
4. **Grill (if needed).** If the request needs fleshing out, call the Skill tool twice, for "grilling" and "domain-modeling", and grill it into shape a round of questions at a time, sharpening domain terms and updating `CONTEXT.md`/ADRs inline as decisions land.
5. **Apply the outcome:**
- `ready-for-agent`: post an agent brief comment ([AGENT-BRIEF.md](AGENT-BRIEF.md)).
- `ready-for-human`: same structure as an agent brief, but note why it can't be delegated (judgment calls, external access, design decisions, manual testing).
- `needs-info`: post triage notes (template below).
- For `wontfix`, close the issue, with the comment depending on *why*:
- **Already implemented**: the change already exists in the codebase. Point to where it lives; do **not** write to `.out-of-scope/` (that KB is for *rejected* requests, not built ones).
- **Rejected (bug)**: give a polite explanation, then close.
- **Rejected (enhancement)**: write to `.out-of-scope/`, link to it from a comment, then close ([OUT-OF-SCOPE.md](OUT-OF-SCOPE.md)).
- `needs-triage`: apply the role. Optional comment if there's partial progress.
## Quick state override
If the maintainer says "move #42 to ready-for-agent", trust them and apply the role directly. Confirm what you're about to do (role changes, comment, close), then act. Skip grilling. If moving to `ready-for-agent` without a grilling session, ask whether they want to write an agent brief.
## Needs-info template
```markdown
## Triage Notes
**What we've established so far:**
- point 1
- point 2
**What we still need from you (@reporter):**
- question 1
- question 2
```
Capture everything resolved during grilling under "established so far" so the work isn't lost. Questions must be specific and actionable, not "please provide more info".
## Resuming a previous session
If prior triage notes exist on the issue or PR, read them, check whether the reporter has answered any outstanding questions, and present an updated picture before continuing. Don't re-ask resolved questions.
@@ -0,0 +1,5 @@
interface:
display_name: "Triage"
short_description: "Move issues through triage roles"
policy:
allow_implicit_invocation: false
+128
View File
@@ -0,0 +1,128 @@
---
name: wayfinder
description: Plan a huge chunk of work (more than one agent session can hold) as a shared map of decision tickets on your issue tracker, and resolve them one at a time until the way to the destination is clear.
disable-model-invocation: true
---
A loose idea has arrived, too big for one agent session, and wrapped in fog: the way from here to the **destination** isn't visible yet. Wayfinding is about finding that way, not charging at the destination. This skill charts the way as a **shared map** on the repo's issue tracker, then works its **decision tickets** (questions whose resolution is a decision, not slices of a build to execute) one at a time until the route is clear.
The destination varies per effort, and naming it is the first act of charting: it shapes every ticket. It might be a spec to hand off and iterate on, a decision to lock before planning starts, or a change made in place like a data-structure migration. The map is domain-agnostic: engineering work, course content, whatever fits the shape.
## Plan, don't do
Wayfinder is **planning** by default: each ticket resolves a decision, and the map is done when the way is clear, with nothing left to decide before someone goes and does the thing. The pull to just do the work is usually the signal you've reached the edge of the map and it's time to hand off. An effort can override this in its **Notes**, carrying execution into the map itself, but absent that, produce decisions, not deliverables.
## Refer by name
Every map and ticket is an issue, so it has a **name**: its title. In everything the human reads (narration, the map's Decisions-so-far), refer to it by that name, never by a bare id, number, or slug. A wall of `#42, #43, #44` is illegible; names read at a glance. The id and URL don't vanish; a name wraps its link, but they ride _inside_ the name, never stand in for it.
## The Map
The map is a single issue on this repo's issue tracker, labelled `wayfinder:map`, the canonical artifact. Its tickets are child issues of the map.
The map is an **index**, not a store. It lists the decisions made and points at the tickets that hold their detail; a decision lives in exactly one place, its ticket, so the map never restates it, only gists it and links.
**Where the map, its child tickets, blocking, and frontier queries physically live is tracker-specific.** The issue tracker should have been provided to you. If not, tell the user to run `setup-skills` skill. Consult the tracker doc's "Wayfinding operations" section for how _this_ repo expresses them. If no tracker has been provided, default to the local-markdown tracker.
### The map body
The whole map at low resolution, loaded once per session. Open tickets are **not** listed: they are open child issues, found by query.
```markdown
## Destination
<what reaching the end of this map looks like: the spec, decision, or change this effort is finding its way to. One or two lines; every session orients to it before choosing a ticket.>
## Notes
<domain; skills every session should consult; standing preferences for this effort>
## Decisions so far
<!-- the index: one line per closed ticket, enough to judge relevance, then zoom the link for the detail the ticket holds -->
- [<closed ticket title>](link): <one-line gist of the answer>
## Not yet specified
<!-- see "Fog of war": in-scope fog you can't ticket yet; graduates as the frontier advances -->
## Out of scope
<!-- see "Out of scope": work ruled beyond the destination; closed, never graduates -->
```
### Tickets
Each ticket is a **child issue** of the map; the tracker's issue id is its identity. Its body is the question, sized to one 100K token agent session:
```markdown
## Question
<the decision or investigation this ticket resolves>
```
Each ticket carries a `wayfinder:<type>` label, one of `research`, `prototype`, `grilling`, `task` (see [Ticket Types](#ticket-types)).
A session **claims** a ticket by assigning it to the dev driving the map, **first**, before any work, so concurrent sessions skip it. That assignee _is_ the claim: an open, unassigned ticket is unclaimed.
Blocking uses the tracker's **native** dependency relationship: essential because it renders the frontier _visually_ in the tracker's own UI, so the human sees what's takeable without opening the map. Only a tracker that lacks native blocking falls back to a body convention. A ticket is **unblocked** when every ticket blocking it is closed; the **frontier** is the open, unblocked, unclaimed children, the edge of the known.
The answer isn't part of the body; it's recorded on resolution (see [Work through the map](#work-through-the-map)). Assets created while resolving a ticket are linked from the issue, not pasted in.
## Ticket Types
Every ticket is either **HITL** (human in the loop, worked _with_ a human who speaks for themselves) or **AFK**, driven by the agent alone. A HITL ticket only resolves through that live exchange; the agent never stands in for the human's side of it (a grilling agent that answers its own questions has broken this).
- **Research** (AFK): Reading documentation, third-party APIs, or local resources like knowledge bases to surface a fact a decision waits on. Resolved by a subagent that calls the Skill tool with "research". Use when knowledge outside the current working directory is required.
- **Prototype** (HITL): Raise the fidelity of the discussion by making a cheap, rough, concrete artifact to react to (an outline, a rough take, a stub, or UI/logic code) by calling the Skill tool with "prototype". Links the prototype as an asset. Use when "how should it look" or "how should it behave" is the key question.
- **Grilling** (HITL): Conversation. The default case. Always call the Skill tool twice, for "grilling" and "domain-modeling".
- **Task** (HITL or AFK): Manual work that must happen before a _decision_ can be made: nothing to decide, prototype, or research, but the discussion is blocked until it's done. Signing up for a service so its API can be judged, provisioning access, moving data so its shape can be seen. This is the one type that _does_ rather than decides, and it earns its place by unblocking a decision, not by delivering the destination. The agent drives it alone where it can (AFK); otherwise it hands the human a precise checklist (HITL). Resolved when the work is done; the answer records what was done and any resulting facts (credentials location, new URLs, row counts) later tickets depend on.
## Fog of war
The map is _deliberately_ incomplete: don't chart what you can't yet see. Beyond the live tickets lies the **fog of war**: the dim view of decisions and investigations you can tell are coming but can't yet pin down, because they hang on questions still open. Resolving a ticket clears the fog ahead of it, graduating whatever's now specifiable into fresh tickets, one at a time, until the way to the destination is clear and no tickets remain.
The map's **Not yet specified** section is where that dim view is written down: the suspected question, the area to revisit later. It's the undiscovered frontier _toward_ the destination: everything here is in scope, just not sharp enough to ticket. Write as loosely or as fully as the view allows; it doubles as a signpost for collaborators reading where the effort is headed.
**Fog or ticket?** The test is whether you can state the question precisely now, _not_ whether you can answer it now.
- **Ticket when** the question is already sharp, even if it's blocked and you can't act on it yet.
- **Not yet specified when** you can't yet phrase it that sharply. Don't pre-slice the fog into ticket-sized pieces: it's coarser than a ticket, and one patch may graduate into several tickets, or none, once the frontier reaches it.
**Not yet specified** excludes what's already decided (Decisions so far), what's already a live ticket, and what's out of scope (the next section).
## Out of scope
Fog only ever gathers _toward_ the destination. The destination fixes the scope, so work beyond it is **out of scope**: it isn't fog, and it doesn't belong in **Not yet specified**. It gets its own **Out of scope** section on the map: work you've consciously ruled out of _this_ effort. Scope, not sharpness, lands it here.
Out-of-scope work never graduates (the frontier stops at the destination), so it returns only if the destination is redrawn, and then as a fresh effort, not a resumption.
Ruling something out of scope is a scoping act, not a step on the route. When a ticket that already exists turns out to sit past the destination (mis-scoped in while charting, or exposed by a resolution), **close it** (a closed ticket is unambiguously off the frontier) and leave one line in the **Out of scope** section: the gist plus why it's out of scope, linking the closed ticket. It stays out of **Decisions so far**, which records the route actually walked; a scope boundary isn't a step on it.
## Invocation
Two modes. Either way, **never resolve more than one ticket per session**, with the exception of research tickets.
### Chart the map
User invokes with a loose idea.
1. **Name the destination.** Call the Skill tool twice, for "grilling" and "domain-modeling", to pin down what this map is finding its way to: the spec, decision, or change. The destination fixes the scope, so it's settled first.
2. **Map the frontier.** Grill again, **breadth-first** this time: fan out across the whole space rather than deep on any one thread, surfacing the open decisions and the first steps takeable now. **If this surfaces no fog** (the way to the destination is already clear, the whole journey small enough for one session), you don't need a map. Stop and ask the user how they'd like to proceed.
3. **Create the map** (label `wayfinder:map`): Destination and Notes filled in, Decisions-so-far empty, the fog sketched into **Not yet specified**.
4. **Create the tickets you can specify now** as child issues of the map, then wire blocking edges in a **second pass** (issues need ids before they can reference each other). Wiring sorts them into the frontier and the blocked; everything you can't yet specify stays in the fog: the **Not yet specified** section.
5. **Fire the research subagents.** For each `research` ticket you just created, spin up a subagent that calls the Skill tool with "research" to resolve it in parallel, capturing its findings on a throwaway `research/<name>` branch with a context pointer from the ticket.
6. Stop: charting is one session's work; it hand-resolves nothing.
### Work through the map
User invokes with a map URL or a bare number. A bare number **always means the map's issue number in the forge**; load that issue as the map, never interpret the number as a ticket index or another parameter. A ticket is **optional**: without one, you pick the next decision, not the user.
1. Load the **map**: the low-res view, not every ticket body.
2. Choose the ticket. If the user named one, use it. Otherwise take the first frontier ticket in order. **Claim it**: assign it to yourself before any work.
3. Resolve it. **Zoom as needed**: fetch the full body of any related or closed ticket on demand; call the Skill tool for whichever skills the `## Notes` block names. If in doubt, call the Skill tool twice, for "grilling" and "domain-modeling".
4. Record the resolution: post the answer as a **resolution comment**, **close** the issue, and **append a context pointer** to the map's Decisions-so-far.
5. Add newly-surfaced tickets (create-then-wire); graduate any fog the answer has made specifiable, clearing each graduated patch from **Not yet specified** so it lives only as its new ticket. If the answer reveals that a ticket (this one or another) sits beyond the destination, **rule it out of scope** rather than resolving it on the route. If the decision invalidates other parts of the map, update or delete those tickets.
The user may run unblocked tickets in parallel, so expect other sessions to be editing the tracker concurrently.
@@ -0,0 +1,5 @@
interface:
display_name: "Wayfinder"
short_description: "Map a large effort as decision tickets"
policy:
allow_implicit_invocation: false
+44
View File
@@ -0,0 +1,44 @@
---
name: wizard
description: Generate an interactive bash wizard that walks a human through steps only they can perform. Use when provisioning infrastructure, setting up credentials or CI secrets, walking an unfamiliar third-party dashboard, or running a one-off migration or cutover. Don't invoke this for steps the agent can perform itself.
---
# Wizard
A **wizard** is a bash script that walks a human, step by step, through a manual procedure that's tedious to do by hand and tedious to re-explain to an AI every time. It opens each URL, says exactly what to click and copy, captures the values, writes them where they belong (`.env`, GitHub secrets), confirms at every stage, and shows how many stages are left. It might configure third-party services, run a one-off migration, or move the project from one state to another.
The delightful UX is already solved by [template.sh](template.sh): stage-by-stage progress, confirmation gates, cross-platform URL opening (including WSL), hidden secret entry, idempotent `.env` upserts, `gh secret`/`gh variable` writes, and a closing summary. **Your job is only to scope the procedure and author its stages.** The library above the `STAGES` marker is identical in every wizard; that consistency is the point: never hand-edit it.
A wizard is ephemeral by default: built for one run, saved to a scratch or `scripts/` path, deleted when the job's done. Commit it only when the user wants a repeatable setup path that should live in the repo.
## Process
### 1. Scope the procedure
Work out every manual step the human must take and every value that gets captured along the way. Read the repo first, don't ask cold:
- For setup: `.env`, `.env.example`, `.env.*`, `README`, `docker-compose*`, framework config, and `.github/workflows/*` (every `secrets.*` / `vars.*` reference is a value the wizard must produce).
- For a migration or transition: the current state, the target state, and the irreversible actions between them.
Then show the user the ordered list of stages and the values each produces, and confirm: they may add, drop, or reorder.
**Done when:** every stage is named in order, and for each captured value you know (a) where the human gets it, (b) where it's written (`.env`, a GitHub secret, both, or nowhere; some stages are pure actions), and (c) whether it's secret (hidden entry) or public.
### 2. Map each stage's journey
For each stage, write the precise path a human follows: which URL to open, what to do there, where a value is shown, which variable it fills: e.g. "Dashboard → Developers → API keys → Reveal test key → copy". Where you don't actually know the current UI or the exact command, say so and ask the user or check the docs: never invent steps that may not exist.
**Done when:** every stage traces to concrete instructions a stranger could follow.
### 3. Author the wizard
Copy `template.sh` to the target path. Replace the example stage with one `stage` per step, in dependency order. Use the library helpers: `stage`, `say`/`step`, `open_url`, `ask`/`ask_secret`, `write_env`, `set_secret`/`set_var`, `pause`/`confirm`. Set `TOTAL_STAGES` to the number of stages you wrote.
Hold the bar the template sets: open the URL before asking for its value, use `ask_secret` for anything secret, `write_env` every persisted value, `set_secret` only the values CI actually needs, and `confirm` before any irreversible action. Each `stage` clears the screen so only the current step is visible: keep a stage to one focused task so nothing the human needs scrolls away. Don't touch the library above the marker.
### 4. Verify and hand off
- `bash -n <script>`; run `shellcheck` if available.
- `chmod +x <script>`.
- Don't run it end-to-end yourself: it opens browsers and blocks on human input. Trace it statically instead: every value from step 1 is captured and lands where step 1 said, and every `set_secret` name exactly matches a `secrets.*` reference in CI.
- Tell the user how to run it. If it's a repeatable setup path, commit it and link it from the README so the next person runs the script instead of asking an AI.
@@ -0,0 +1,3 @@
interface:
display_name: "Wizard"
short_description: "Generate an interactive setup wizard"
+204
View File
@@ -0,0 +1,204 @@
#!/usr/bin/env bash
#
# A wizard walks a human through a manual procedure, step by step.
# Generated by the /wizard skill.
#
# Everything above the "STAGES" marker is the wizard library: do not hand-edit
# it. Author the per-step stages below the marker.
set -euo pipefail
# ──────────────────────────────────────────────────────────────────────────
# Wizard library: delightful, consistent UX, identical across every wizard.
# ──────────────────────────────────────────────────────────────────────────
if [[ -t 1 ]] && command -v tput >/dev/null 2>&1 && [[ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]]; then
BOLD=$(tput bold); DIM=$(tput dim); RESET=$(tput sgr0)
BLUE=$(tput setaf 4); GREEN=$(tput setaf 2); YELLOW=$(tput setaf 3); RED=$(tput setaf 1)
else
BOLD=""; DIM=""; RESET=""; BLUE=""; GREEN=""; YELLOW=""; RED=""
fi
# Author sets this at the top of the stages section.
TOTAL_STAGES=0
_STAGE_INDEX=0
ENV_FILE="${ENV_FILE:-.env}"
WRITTEN_ENV=() # KEYs written to ENV_FILE this run
WRITTEN_SECRET=() # secret NAMEs set this run
SKIPPED=() # things we couldn't do (e.g. gh missing)
# _clear wipes the terminal so only the current step is on screen. No-op when
# output isn't a terminal, so piped logs stay readable.
_clear() {
[[ -t 1 ]] || return 0
if command -v tput >/dev/null 2>&1; then tput clear; else printf '\033[2J\033[3J\033[H'; fi
}
# banner "Title" shows the opening frame: what this wizard does.
banner() {
_clear
printf '\n%s%s %s%s\n' "$BOLD" "$BLUE" "$1" "$RESET"
printf '%s %s stages%s\n\n' "$DIM" "$TOTAL_STAGES" "$RESET"
printf '%s You drive the browser; this wizard tells you exactly what to do and\n' "$DIM"
printf ' captures the values you copy back. Stop any time with Ctrl-C and re-run\n'
printf ' later, since it remembers values already saved.%s\n' "$RESET"
pause "Ready to start?"
}
# stage "Name" clears the screen, then announces a stage and shows progress.
# Clearing keeps only the current step on screen.
stage() {
_clear
_STAGE_INDEX=$((_STAGE_INDEX + 1))
printf '\n%s%s▸ Stage %s/%s · %s%s\n' \
"$BOLD" "$BLUE" "$_STAGE_INDEX" "$TOTAL_STAGES" "$1" "$RESET"
}
# say "..." prints a plain instruction line.
say() { printf ' %s\n' "$1"; }
# step "..." is a numbered-feeling action the human takes in the browser.
step() { printf ' %s•%s %s\n' "$BLUE" "$RESET" "$1"; }
note() { printf ' %s%s%s\n' "$DIM" "$1" "$RESET"; }
warn() { printf ' %s⚠ %s%s\n' "$YELLOW" "$1" "$RESET"; }
# open_url URL opens it in the human's browser, cross-platform incl. WSL.
open_url() {
local url="$1"
printf ' %s↗ opening%s %s\n' "$GREEN" "$RESET" "$url"
{ if command -v wslview >/dev/null 2>&1; then wslview "$url"
elif command -v explorer.exe >/dev/null 2>&1; then explorer.exe "$url"
elif command -v xdg-open >/dev/null 2>&1; then xdg-open "$url"
elif command -v open >/dev/null 2>&1; then open "$url"
else warn "couldn't open a browser; visit it manually: $url"; fi
} >/dev/null 2>&1 || warn "couldn't open a browser, so visit it manually: $url"
}
# pause "msg" waits for the human to confirm they've done the manual part.
pause() {
printf ' %s%s%s ' "$DIM" "${1:-Press Enter to continue}" "$RESET"
read -r _ || true
}
# confirm "question" is a y/N gate; returns success on yes.
confirm() {
local reply=""
printf ' %s? %s [y/N] ' "$YELLOW" "$1"
read -r reply || true
[[ "$reply" =~ ^[Yy] ]]
}
# _existing KEY: current value of KEY in ENV_FILE, if any.
_existing() {
[[ -f "$ENV_FILE" ]] || return 1
local line; line=$(grep -E "^${1}=" "$ENV_FILE" | tail -n1) || return 1
printf '%s' "${line#*=}"
}
# ask KEY "Prompt" reads a value into $KEY. Offers the existing .env value as
# a default on re-runs (Enter keeps it). Visible input (non-secret).
ask() {
local key="$1" prompt="$2" current input
current=$(_existing "$key" || true)
if [[ -n "$current" ]]; then
printf ' %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET"
else
printf ' %s%s%s ' "$BOLD" "$prompt" "$RESET"
fi
read -r input || true
[[ -z "$input" && -n "$current" ]] && input="$current"
printf -v "$key" '%s' "$input"
}
# ask_secret KEY "Prompt" is like ask, but input is hidden.
ask_secret() {
local key="$1" prompt="$2" current input
current=$(_existing "$key" || true)
if [[ -n "$current" ]]; then
printf ' %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET"
else
printf ' %s%s%s ' "$BOLD" "$prompt" "$RESET"
fi
read -rs input || true
printf '\n'
[[ -z "$input" && -n "$current" ]] && input="$current"
printf -v "$key" '%s' "$input"
}
# write_env KEY VALUE upserts KEY=VALUE into ENV_FILE (creates it; replaces
# any existing line). Idempotent.
write_env() {
local key="$1" value="$2" tmp
touch "$ENV_FILE"
tmp=$(mktemp)
grep -vE "^${key}=" "$ENV_FILE" > "$tmp" || true
printf '%s=%s\n' "$key" "$value" >> "$tmp"
mv "$tmp" "$ENV_FILE"
WRITTEN_ENV+=("$key")
printf ' %s✓ wrote%s %s → %s\n' "$GREEN" "$RESET" "$key" "$ENV_FILE"
}
# set_secret NAME VALUE sets a GitHub Actions repo secret via gh. Falls back
# to a warning (and records it) if gh is unavailable or unauthenticated.
set_secret() {
local name="$1" value="$2"
if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
if printf '%s' "$value" | gh secret set "$name" >/dev/null 2>&1; then
WRITTEN_SECRET+=("$name")
printf ' %s✓ set%s GitHub secret %s\n' "$GREEN" "$RESET" "$name"
return
fi
fi
SKIPPED+=("GitHub secret $name (set it manually: gh secret set $name)")
warn "skipped GitHub secret $name: gh not ready; set it later"
}
# set_var NAME VALUE sets a GitHub Actions repo variable (non-secret).
set_var() {
local name="$1" value="$2"
if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
if gh variable set "$name" --body "$value" >/dev/null 2>&1; then
printf ' %s✓ set%s GitHub variable %s\n' "$GREEN" "$RESET" "$name"
return
fi
fi
SKIPPED+=("GitHub variable $name")
warn "skipped GitHub variable $name, gh not ready; set it later"
}
# finish clears, then shows a closing summary of everything configured.
finish() {
_clear
printf '\n%s%s ✓ Setup complete%s\n' "$BOLD" "$GREEN" "$RESET"
(( ${#WRITTEN_ENV[@]} )) && note "wrote ${#WRITTEN_ENV[@]} value(s) to $ENV_FILE: ${WRITTEN_ENV[*]}"
(( ${#WRITTEN_SECRET[@]} )) && note "set ${#WRITTEN_SECRET[@]} GitHub secret(s): ${WRITTEN_SECRET[*]}"
if (( ${#SKIPPED[@]} )); then
printf '\n'; warn "still to do by hand:"
for s in "${SKIPPED[@]}"; do note " - $s"; done
fi
printf '\n'
}
# ──────────────────────────────────────────────────────────────────────────
# STAGES: author this section. One stage() per step the human takes.
# Replace the example below. Set TOTAL_STAGES to match the stages you write.
# ──────────────────────────────────────────────────────────────────────────
TOTAL_STAGES=1
banner "Stripe setup"
# ── Example stage: replace with your real steps ───────────────────────────
stage "Stripe: API keys"
say "We'll grab your Stripe test keys and store them for local dev + CI."
open_url "https://dashboard.stripe.com/test/apikeys"
step "On the API keys page, copy the Publishable key (starts pk_test_)."
ask STRIPE_PUBLISHABLE_KEY "Paste the publishable key:"
step "Click 'Reveal test key' on the Secret key row, then copy it."
ask_secret STRIPE_SECRET_KEY "Paste the secret key:"
write_env STRIPE_PUBLISHABLE_KEY "$STRIPE_PUBLISHABLE_KEY"
write_env STRIPE_SECRET_KEY "$STRIPE_SECRET_KEY"
set_secret STRIPE_SECRET_KEY "$STRIPE_SECRET_KEY" # CI needs this one
# ──────────────────────────────────────────────────────────────────────────
finish
+64
View File
@@ -0,0 +1,64 @@
---
name: worktrees
description: Manage Git worktrees in a canonical `.bare` repository root. Use when creating, reusing, listing, removing, or repairing worktrees, or when setting up a repository to keep all branch checkouts under one root.
---
# Git worktrees
Use one root per repository:
```text
<repo>/
.git # gitdir: ./.bare
.bare/ # shared repository and object store
main/ # linked worktree
<topic>/ # linked worktree
```
Run repository-wide commands from `<repo>` and development commands from a linked worktree. Keep every checkout under `<repo>`.
## Create or reuse a worktree
1. From any linked worktree or the canonical root, run [`scripts/new-worktree.sh`](scripts/new-worktree.sh):
```bash
scripts/new-worktree.sh <local-dir> <branch> [base]
```
Set `WORKTREE_ROOT` only when root discovery is unavailable. Set `WORKTREE_REMOTE` when the remote is not `origin`.
2. Enter `<repo>/<local-dir>` and run:
```bash
git status --short --branch
```
Creation is complete when `git worktree list` contains the path and its expected branch, and status is clean unless the branch already carried changes.
The helper fetches and prunes, reuses an existing local branch, tracks a matching remote branch, or creates a new branch from `[base]`. Run it with `--help` for the exact decision order and defaults.
## Remove a worktree
1. Account for every staged, unstaged, and untracked change:
```bash
git -C <repo>/<local-dir> status --short --branch
```
2. Remove the checkout through Git:
```bash
git -C <repo> worktree remove <local-dir>
```
3. Delete the local branch only when its commits are integrated or intentionally discarded:
```bash
git -C <repo> branch -d <branch>
```
Removal is complete when the path is absent from both the filesystem and `git -C <repo> worktree list`.
## Setup and recovery
Read [`references/canonical-root.md`](references/canonical-root.md) when converting a repository to this layout, validating its invariants, cleaning stale registrations, or repairing moved worktrees.
@@ -0,0 +1,57 @@
# Canonical worktree root
## Create the root
For a new local root at `<repo>`:
```bash
mkdir <repo>
cd <repo>
git clone --bare <url> .bare
printf '%s\n' 'gitdir: ./.bare' >.git
git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
git config core.logAllRefUpdates true
git config worktree.useRelativePaths true
git fetch --prune origin
git remote set-head origin --auto
git worktree add main main
git -C main branch --set-upstream-to=origin/main main
```
Replace `main` in the final two commands when the remote default branch has another name. Setup is complete when the invariants below hold and `main` is listed by `git worktree list`.
For an existing clone with unpublished state, preserve its branches, tags, reflogs, worktree changes, ignored files, hooks, and repository-local configuration before conversion. Prefer creating a fresh canonical root and moving commits through Git over rearranging live metadata in place.
## Invariants
Run from `<repo>`:
```bash
git rev-parse --is-bare-repository
git config --get remote.origin.fetch
git config --get core.logAllRefUpdates
git config --get worktree.useRelativePaths
git worktree list --verbose
```
A canonical root resolves to a bare repository, fetches remote branches into `refs/remotes/origin/*`, keeps reflogs, uses relative worktree paths, and lists every live checkout beneath the root.
## Stale registrations
Inspect before pruning:
```bash
git worktree prune --dry-run --verbose
```
Run `git worktree prune --verbose` only after every reported registration is confirmed stale.
## Moved roots or worktrees
After moving the root or a linked worktree, run:
```bash
git worktree repair
```
Then verify every path with `git worktree list --verbose` and `git -C <path> status --short --branch`. Recovery is complete when each live path resolves to its expected branch and no valid registration appears in a prune dry run.
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat >&2 <<'USAGE'
Usage: new-worktree.sh <local-dir> <branch> [base]
Create a linked worktree under a canonical repository root:
<repo>/.git -> gitdir: ./.bare
<repo>/.bare -> shared bare repository
<repo>/<name> -> linked worktree
Branch selection:
1. Reuse <branch> when it exists locally.
2. Track WORKTREE_REMOTE/<branch> when it exists remotely.
3. Create <branch> from [base].
The default remote is origin. The default base is the remote's default branch,
then main or master when either exists locally. Set WORKTREE_ROOT to override
root discovery and WORKTREE_REMOTE to select another remote.
USAGE
}
if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then
usage
exit 0
fi
if [[ $# -lt 2 || $# -gt 3 ]]; then
usage
exit 2
fi
local_dir=$1
branch=$2
base=${3:-}
if [[ -z "$local_dir" || "$local_dir" == "." || "$local_dir" == ".." || "$local_dir" == */* ]]; then
echo "new-worktree: local-dir must name one direct child of the repository root: $local_dir" >&2
exit 2
fi
if ! git check-ref-format --branch "$branch" >/dev/null 2>&1; then
echo "new-worktree: invalid branch name: $branch" >&2
exit 2
fi
if [[ -n ${WORKTREE_ROOT:-} ]]; then
root=$WORKTREE_ROOT
else
if ! common_dir=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null); then
echo "new-worktree: run from a canonical repository root or one of its linked worktrees" >&2
exit 1
fi
if [[ ${common_dir##*/} != ".bare" ]]; then
echo "new-worktree: shared Git directory is not a canonical .bare directory: $common_dir" >&2
echo "new-worktree: set WORKTREE_ROOT or convert the repository to the canonical layout" >&2
exit 1
fi
root=${common_dir%/.bare}
fi
if [[ $(git -C "$root" rev-parse --is-bare-repository 2>/dev/null) != "true" ]]; then
echo "new-worktree: repository root does not resolve to a bare repository: $root" >&2
exit 1
fi
if [[ -e "$root/$local_dir" ]]; then
echo "new-worktree: destination already exists: $root/$local_dir" >&2
exit 1
fi
remote=${WORKTREE_REMOTE:-origin}
if git -C "$root" remote get-url "$remote" >/dev/null 2>&1; then
echo "Fetching $remote..." >&2
git -C "$root" fetch --prune "$remote"
has_remote=true
else
has_remote=false
if [[ -n ${WORKTREE_REMOTE:-} ]]; then
echo "new-worktree: remote does not exist: $remote" >&2
exit 1
fi
fi
if git -C "$root" show-ref --verify --quiet "refs/heads/$branch"; then
echo "Adding existing local branch '$branch' at $root/$local_dir" >&2
git -C "$root" worktree add -- "$local_dir" "$branch"
elif [[ $has_remote == true ]] && git -C "$root" show-ref --verify --quiet "refs/remotes/$remote/$branch"; then
echo "Creating tracking branch '$branch' from $remote/$branch at $root/$local_dir" >&2
git -C "$root" worktree add --track -b "$branch" -- "$local_dir" "$remote/$branch"
else
if [[ -z "$base" && $has_remote == true ]]; then
base=$(git -C "$root" symbolic-ref --quiet --short "refs/remotes/$remote/HEAD" 2>/dev/null || true)
fi
if [[ -z "$base" ]]; then
if git -C "$root" show-ref --verify --quiet refs/heads/main; then
base=main
elif git -C "$root" show-ref --verify --quiet refs/heads/master; then
base=master
else
echo "new-worktree: no default base found; pass [base] explicitly" >&2
exit 1
fi
fi
if ! git -C "$root" rev-parse --verify --quiet "$base^{commit}" >/dev/null; then
echo "new-worktree: base does not resolve to a commit: $base" >&2
exit 1
fi
echo "Creating branch '$branch' from $base at $root/$local_dir" >&2
git -C "$root" worktree add --no-track -b "$branch" -- "$local_dir" "$base"
fi
echo >&2
git -C "$root" worktree list --verbose
@@ -0,0 +1,107 @@
---
name: write-discoverable-code
description: |
Rules for writing code that coding agents (and humans) can find and understand through
plain-text search. Apply whenever writing or renaming code: functions, types, constants,
files, error messages, doc comments.
Grounded in measurement: agents navigate by plain-text search, not by AST or
language server, so every identifier is a search query and every search miss
costs wasted reads.
license: MIT
---
# Write discoverable code
Coding agents discover code by searching for strings and reading small windows around the
hits. They have no hover text, no jump-to-definition, and no memory between sessions. These
rules make code resolvable in one search instead of five.
## 1. Names are search queries
- **Exported symbols get 2–4 word names, at least one of them a domain word.**
`diffUserObjects`, not `diff`. `queueEventForDispatch`, not `queue`.
Measured on a ~700k-line monorepo: 1-word exported names are globally unique 61% of
the time; 3-word names 96%; 4+ words 98%. Three words is the knee of the curve.
Use the shortest name that greps uniquely; put the rest in the doc comment.
- **Give generic verbs their object.** `sanitizeEmailHtml`, not `sanitize`;
`validateSmtpConfig`, not `validateConfig`. Qualify only as far as uniqueness
requires, then stop.
- **One definition site per symbol.** Never copy a function between files; move it and
delete the original in the same change. Shared helpers get one concept-named home
and are imported everywhere else.
- **Do not rely on the module path to disambiguate a generic name.** The import that
disambiguates `users/diff.ts` from `orders/diff.ts` sits at the top of the file; the
search hit is at line 300. Put the context in the symbol (`formatDurationMs`), not the
folder. Exception: rigid, absolute conventions where the path carries the meaning
(e.g. every contract file exporting `Input`/`Output`).
- **One concept, one spelling.** Pick `organizationId` or `orgId` and use it everywhere;
every synonym splits every future search in half. Reuse existing vocabulary in the
codebase you are editing rather than introducing near-synonyms.
- **When behavior or audience changes, rename in the same commit.** A stale name is
misinformation with a 100% open rate — that includes visibility markers: a `_private`
helper that other modules now import needs a public name.
- **Filenames are names too — never use bare-role filenames.** `config.ts`, `types.ts`,
`utils.ts`, `helpers.ts`, `handlers.ts` say nothing in a search result and collide with
every other module's config/types/utils in the repo. Prefix the domain:
`billing-plan-config.ts`, not `config.ts`. (`index.ts` is acceptable only as a
thin re-export entry point.)
## 2. Types are the documentation agents can't skip
- **Brand your primitive IDs.** `z.string().brand<'UserId'>()` (TS) or newtypes (Rust).
A `transferOwnership(userId: string, orgId: string)` signature makes argument
transposition invisible; branded types make it a compile error that names the concepts.
- **Use capability-token parameter types** for privileged operations (e.g. requiring an
`OrgScopedDb` instead of a raw connection). A comment is a request; a required type is
physics.
- **Model state with discriminated unions**, not clusters of nullable fields with implicit
rules.
- **Name types like they'll be quoted back** — they will be, in compiler errors the agent
uses to self-correct. `OrgScopedDb` explains itself; `Ctx2` does not. Avoid `any`: every
`any` is a spot where the compiler goes silent and the agent is back to guessing.
## 3. Say it where the search lands
- **One-line doc comment on every export**, stating the sharpest constraint the code
itself can't show (units, timezone, "source time, not insert time", ownership).
The definition is where a name search lands; that line is your whole message.
- **Write the plain-words phrase in the doc comment.** Searches arrive as natural language
("rate limit", "retry delay"), and camelCase identifiers don't match phrase greps —
`RateLimiter` is invisible to a search for "rate limit". The doc comment above each
export should contain, in ordinary spaced-out words, the phrase someone would search
for: a `SessionExpiryChecker` should say /\*_ Checks whether the user session has
expired. _/ so that a grep for "session expired" or "session has expired" lands here.
- **A module should make sense with its imports unread.** Each imported name plus its
doc line should say enough that the reader never has to open the source module. If
they do, the import's name is failing, not the reader.
- **Keep strings whole.** Never build event names, flags, or error codes with template
interpolation (`` `github.${entity}.${action}` `` makes `github.pr.merged` unsearchable).
Write the full literal even when a loop feels DRYer.
- **Error messages start with a unique literal prefix**, so a message seen in a log greps
straight back to the throw site. ``throw new Error(`Webhook signature mismatch for ${id}`)``,
never ``throw new Error(`${prefix}: mismatch`)``.
- **One searchable concept per file, and keep orchestrators thin.** The code that answers
"where is X done?" should live in a module named after X — the thing a reader would
ask about, not the mechanism inside — not inline in a coordinator,
pipeline, or service class. An orchestrator should read as a sequence of calls into
well-named modules; if a reader lands in it from a search, every line should point them
one hop from the real implementation. Burying the implementation of several concepts in
one large file makes every search for any of them land on the same wall of code.
Split until each question-sized concept has one named home, then stop: a helper
meaningful only inside one concept belongs inline, and a file per tiny function
fragments one answer across several reads. The test runs both ways: a module that
answers many unrelated questions is holding more than one concept.
- **Colocate tests** (`foo.test.ts` next to `foo.ts`) so one search finds behavior and its
specification together.
- **Mark dead ends.** `@deprecated` on the old path, with a pointer to the new one.
## Quick checklist before committing
1. Would one search for each new exported name be enough to find its implementation?
2. Would swapping two arguments of the new function fail the build?
3. Is the one thing a caller must know but the signature can't say (units, timezone,
ownership, ordering) written right at the definition?
4. Do all log/error strings exist verbatim in the source?
5. Did anything change behavior without changing its name?
6. When code moved, is it gone from where it came from?
@@ -4,5 +4,9 @@ Drafts not yet ready to ship.
## User-invoked ## User-invoked
- [agent-handoff](agent-handoff/SKILL.md) — Hand the current conversation off to a fresh background agent that picks up the work immediately. - [agent-handoff](agent-handoff/SKILL.md) — Hand the current conversation to a fresh background agent.
- [knowledge-gardener](knowledge-gardener/SKILL.md) — Run vault-aware semantic search, synthesis, note creation, linking, and Zettelkasten workflows for this Obsidian vault. - [knowledge-gardener](knowledge-gardener/SKILL.md) — Run vault-aware search, synthesis, note creation, and linking workflows.
## Model-invoked
No model-invoked skills.
+16
View File
@@ -0,0 +1,16 @@
# Miscellaneous Skills
Kept around but rarely used.
## User-invoked
- [bro](bro/SKILL.md) — Restate the last message in plain human language.
- [show-me](show-me/SKILL.md) — Help explain topics visually with concise diagrams and artifacts.
- [tmux-launch-agent](tmux-launch-agent/SKILL.md) — Fork a new agent CLI session into a new tmux window.
- [visual-verification](visual-verification/SKILL.md) — Verify running desktop UI changes with screenshots and recordings.
## Model-invoked
- [migrate-to-shoehorn](migrate-to-shoehorn/SKILL.md) — Migrate test assertions from `as` to `@total-typescript/shoehorn`.
- [scaffold-exercises](scaffold-exercises/SKILL.md) — Create linted exercise directories with problems, solutions, and explainers.
- [setup-pre-commit](setup-pre-commit/SKILL.md) — Set up Husky, lint-staged, type checking, and tests.
+7
View File
@@ -0,0 +1,7 @@
---
name: bro
description: Restate the last message in plain human language, with no jargon.
disable-model-invocation: true
---
Restate your last message. Stop using jargon and speak coherently. State it more simply and concisely, like one human talking to another.
+118
View File
@@ -0,0 +1,118 @@
---
name: migrate-to-shoehorn
description: Migrate test files from `as` type assertions to @total-typescript/shoehorn. Use when user mentions shoehorn, wants to replace `as` in tests, or needs partial test data.
---
# Migrate to Shoehorn
## Why shoehorn?
`shoehorn` lets you pass partial data in tests while keeping TypeScript happy. It replaces `as` assertions with type-safe alternatives.
**Test code only.** Never use shoehorn in production code.
Problems with `as` in tests:
- Trained not to use it
- Must manually specify target type
- Double-as (`as unknown as Type`) for intentionally wrong data
## Install
```bash
npm i @total-typescript/shoehorn
```
## Migration patterns
### Large objects with few needed properties
Before:
```ts
type Request = {
body: { id: string };
headers: Record<string, string>;
cookies: Record<string, string>;
// ...20 more properties
};
it("gets user by id", () => {
// Only care about body.id but must fake entire Request
getUser({
body: { id: "123" },
headers: {},
cookies: {},
// ...fake all 20 properties
});
});
```
After:
```ts
import { fromPartial } from "@total-typescript/shoehorn";
it("gets user by id", () => {
getUser(
fromPartial({
body: { id: "123" },
}),
);
});
```
### `as Type` → `fromPartial()`
Before:
```ts
getUser({ body: { id: "123" } } as Request);
```
After:
```ts
import { fromPartial } from "@total-typescript/shoehorn";
getUser(fromPartial({ body: { id: "123" } }));
```
### `as unknown as Type` → `fromAny()`
Before:
```ts
getUser({ body: { id: 123 } } as unknown as Request); // wrong type on purpose
```
After:
```ts
import { fromAny } from "@total-typescript/shoehorn";
getUser(fromAny({ body: { id: 123 } }));
```
## When to use each
| Function | Use case |
| --------------- | -------------------------------------------------- |
| `fromPartial()` | Pass partial data that still type-checks |
| `fromAny()` | Pass intentionally wrong data (keeps autocomplete) |
| `fromExact()` | Force full object (swap with fromPartial later) |
## Workflow
1. **Gather requirements** - ask user:
- What test files have `as` assertions causing problems?
- Are they dealing with large objects where only some properties matter?
- Do they need to pass intentionally wrong data for error testing?
2. **Install and migrate**:
- [ ] Install: `npm i @total-typescript/shoehorn`
- [ ] Find test files with `as` assertions: `grep -r " as [A-Z]" --include="*.test.ts" --include="*.spec.ts"`
- [ ] Replace `as Type` with `fromPartial()`
- [ ] Replace `as unknown as Type` with `fromAny()`
- [ ] Add imports from `@total-typescript/shoehorn`
- [ ] Run type check to verify

Some files were not shown because too many files have changed in this diff Show More