Author SHA1 Message Date
gitadmin d6c2cb083d docs(forge-cli): note tea verb fallback and label id vs name in tea.md 2026-10-07 13:30:12 -04:00
gitadmin 4293880737 docs(reflect): never edit package-installed skills, route lessons to project config 2026-10-07 13:26:07 -04:00
gitadmin 17acb1eab1 docs(orchestrate-herdr): cover collapsed planner identity and review gaps
When the invoking session is the planner, skip the launch-claim and
monitor ceremony and run the loop in place. Reconcile stale pane IDs
instead of treating them as mismatches. Require clean/pushed task
worktrees before merge, review with one independent subagent, and assert
cross-ticket checks on the integration branch. Pair start/finish events
so silent phase gaps are detectable.
2026-10-07 13:16:38 -04:00
gitadmin 8f451d3b88 refactor(orchestrate-herdr): fire-and-forget planner with native subagents
The orchestrator no longer monitors a running planner; it confirms startup
and exits. The planner is the only full CLI agent and delegates implementer,
reviewer, fixer, and merger roles to native Pi subagents instead of Herdr- or
CLI-launched agents. Update dispatcher, run-loop, state, and agent interface
copy to match.
2026-10-07 11:10:52 -04:00
gitadmin 09232e0c9a docs(orchestrate-herdr): rename implementer/reviewer agents to subagents 2026-10-07 09:52:26 -04:00
gitadmin 8238d5a283 refactor(orchestrate-herdr): orchestrator finds or starts planner
Rewrote the skill so the invoking session only discovers an existing
run or launches a fresh planner, then monitors via Herdr read-only
commands. Workers keep state in .orchestrate/<slug>/ with run.json and
events.jsonl; the tracker holds all handoffs and decisions. Re-invoking
the same command recovers monitoring after an orchestrator outage, and
an in-progress label plus atomic launch claims prevent duplicate
planners.
2026-10-06 23:32:21 -04:00
gitadmin fcdd3f7a8c refactor(skills): wire code-quality-review and security-audit into reviews
Rename thermo-nuclear-code-quality-review to code-quality-review and drop
the dramatic wording; allow security-audit model invocation. Both now run
as extra axes in the implementation-orchestrator and orchestrate-herdr
review steps.
2026-10-06 18:47:42 -04:00
gitadmin abf9b8e7ec refactor(orchestrate-herdr): scope skill to spec-ticket implementation on a named worker
Rewrite SKILL.md, dispatcher and run-loop references: the skill now takes
<spec-ticket> [worker], always starts fresh agents, and follows the
implement-spec flow (integration branch, frontier tickets, per-task review
and merge) instead of the old plan-and-publish-to-merged-PR pipeline.
Update the engineering README description to match.
2026-10-06 15:59:06 -04:00
gitadmin fa9813daa4 feat(skills): add openai agent interface configs for all skills
Declare display_name, short_description, and disable implicit invocation
for each skill via agents/openai.yaml. Also fix stale /setup-matt-pocock-skills
reference in implement-spec to /setup-skills.
2026-10-06 14:16:57 -04:00
gitadmin 71525bc349 feat(feedback-bundle): commit-linked Gitea tickets with file attachments
New model-invoked skill + feedback_bundle.py: creates a Gitea issue whose
body links the current HEAD commit and uploads logs/screenshots as issue
assets. Handles label-name-to-ID resolution, tea-config token lookup, and
the disabled-attachments (403/404) case. Index updated in root and
engineering READMEs.
2026-10-06 14:06:01 -04:00
gitadmin 01c488157d docs: rewrite repo indexes and context pack for skills/ layout
Replace the stale common/ structure docs with the current skills/ bucket
layout. Root and bucket READMEs now index every SKILL.md by invocation
type, AGENTS.md lists the ten actual buckets, and the project context
pack is condensed to purpose, structure, conventions, and validation.
2026-10-06 14:00:45 -04:00
gitadmin d956e513a4 chore(skills): move audit skills to engineering, drop dual-review 2026-10-06 13:44:55 -04:00
steve 4d39989424 Merge pull request 'feat: orchestrate plans with Herdr' (#31) from issue-30-orchestrate-plans-from-context-to-merged-prs-with-herdr into master
Reviewed-on: #31
2026-10-06 13:33:53 -04:00
gitadmin 781aa7dc94 fix: ignore persisted orchestration state 2026-10-06 12:50:46 -04:00
gitadmin eacd08426f fix: correct skill metadata descriptions 2026-10-06 12:49:03 -04:00
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 18ef02a331 feat: add orchestrate-herdr skill and dual-review; make to-spec/to-tickets agent-invocable
Add an explicitly invoked Pi orchestration skill that drives a plan from the
current conversation or an @file through a published spec, linked dependency-aware
tickets, and one-at-a-time isolated implementation to a merged PR, using Herdr
and Pi agents with no Bun CLI or orchestration runtime.

- orchestrate-herdr (SKILL.md + dispatcher/run-loop/state references): worker-node
  selection and Herdr discovery/validation, plan-and-publish, one-at-a-time task
  loop (claim, isolate, implement, verify, four-axis review, scoped fix rounds max
  three, transient retries max two, reconcile uncertain side effects, escalate),
  PR/merge/close gates, authoritative worker-node state, cross-system recovery,
  and owned-only cleanup that preserves dirty worktrees and retained state.
- dual-review: self-contained correctness/security + maintainability review axis
  (four-axis review with code-review).
- to-spec and to-tickets: drop disable-model-invocation so the orchestration
  workflow can invoke them.
- READMEs: list the two new skills.
2026-10-06 12:45:12 -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
263 changed files with 9193 additions and 1744 deletions
+19 -106
View File
@@ -1,119 +1,32 @@
# Project Context Pack
Generated: 2026-08-17
Root: /home/sjb/Projects/personal/ws-sjb-skills/wt-master
Working directory: .
Status: fresh
## Purpose
A collection of agent skills (slash commands and behaviors) loaded into Steve Beaulac's AI coding agents. Each skill is a SKILL.md file that teaches the agent how to handle a specific task — from codebase design and TDD to Obsidian PKM workflows and tmux agent launching.
## Project type
- **Agent skill repository plus standalone Python tracker package**
- Languages: Python and Markdown, one Bash script (detect-agent), one shell script (tmux-open)
- Package manager: `pyproject.toml`
- Build/test tools: `python -m unittest discover`
- Agent guidance: `AGENTS.md` at root, `docs/invocation.md` for invocation conventions, `docs/agents/` for issue tracker / triage labels / ADR wiki / domain docs
Repository of agent skills: each skill is a folder with a `SKILL.md` plus optional references, scripts, or assets.
## Structure
```
.
├── AGENTS.md # Top-level agent instructions for this repo
├── README.md # Project overview, lists user-invoked and model-invoked skills
├── .gitignore # Excludes docs/adr/
├── .agent/
│ └── project-context.md # This file
├── docs/
│ ├── invocation.md # Model-invoked vs user-invoked definitions
│ ├── agents/
│ │ ├── adr-wiki.md # ADR wiki setup docs
│ │ ├── domain.md # Domain docs layout
│ │ ├── issue-tracker.md # Gitea issue tracker docs
│ │ └── triage-labels.md # Five-label triage vocabulary
│ └── 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/
├── 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
├── productivity/ # (currently only README.md)
├── pkm/ # User-invoked: conversation-summary, crit, research-vault, youtube-video-capture; Model-invoked: pkm-curation
├── personal/ # (currently only README.md)
├── misc/ # User-invoked: tmux-launch-agent
├── in-progress/ # User-invoked: agent-handoff, knowledge-gardener
└── deprecated/ # Deprecated forge-* and dsp-* skills
```
- `skills/` — skills grouped by category; each bucket has a README index.
- `skills/setup-skills/` — one-time repo configuration skill and its supporting guides.
- `README.md` — complete index of skills by invocation type and category.
- `AGENTS.md` — repository conventions and pointers to agent documentation.
- `docs/invocation.md` — user-invoked vs model-invoked behavior.
- `docs/agents/` — issue tracker, triage labels, ADR wiki, and domain-document conventions.
- `docs/engineering/` — reusable engineering process references.
- `docs/adr/` — ADR wiki clone; gitignored.
- `.agent/project-context.md` — this context pack.
## Important files
## Skill categories
- `AGENTS.md` — Agent entry point that describes structure, categories, and references docs
- `README.md` — Index of all skills divided into user-invoked and model-invoked
- `docs/invocation.md` — Defines the invocation model (disable-model-invocation frontmatter key, human vs model reachability, dependency rules)
- `docs/agents/` — Agent documentation for issue tracker, triage labels, ADR wiki, domain docs
- `common/engineering/project-context-pack/SKILL.md` — The skill that generated this file
- `common/misc/tmux-launch-agent/SKILL.md` — Fork agent CLI into new tmux window (user-invoked)
- `common/misc/tmux-launch-agent/tmux-open` — Reusable script that opens a command in a new tmux window/session
`engineering`, `in-progress`, `misc`, `personal`, `pkm`, `pstack`, `productivity`, `setup-skills`, `skill-authoring`, and `thinking-and-docs`.
## Commands
## Conventions
- Build/package: `python -m pip install .`
- Test: `python -m unittest discover -v`
- Typecheck: `lsp_diagnostics` on `tracker/` and `tests/`
- Run: `python -m tracker` or installed `tracker`
- Skills are user-invoked when frontmatter sets `disable-model-invocation: true`; otherwise they are model-invoked.
- Keep root and bucket README indexes synchronized with `SKILL.md` frontmatter and file paths.
- Read `docs/invocation.md` for invocation rules; read the relevant `docs/agents/` guide for tracker, triage, ADR, or domain-doc work.
- Source files in this repository are authoritative; global installed copies are separate.
## Entry points
## Validation
- `AGENTS.md` — loaded by the AI agent as project instructions (referred to in pi's agent config)
- Each `SKILL.md` under `common/` — referenced by agents via slash commands or auto-invocation
## Search and symbol notes
- All skills are `SKILL.md` files — search with `fd SKILL.md`
- Bucket READMEs: `fd README.md common/`
- Skills are classified as **user-invoked** (`disable-model-invocation: true` in frontmatter) or **model-invoked** (default, no frontmatter flag)
- Dependencies between skills use prose invocation ("Run the `/grilling` skill"), not file cross-references
- Shared reference docs live inside the owning skill's directory; other skills reach that material by invoking the skill
## Files inspected
- `AGENTS.md` — root agent instructions — fresh
- `README.md` — project overview and skill index — fresh
- `docs/invocation.md` — invocation model definitions — fresh
- `.gitignore` — excludes docs/adr/ — fresh
- `common/README.md` — common bucket index — fresh
- `common/misc/README.md` — misc bucket index — fresh
- `.agent/project-context.md` — this file (refreshed from stale 2026-06-25 version)
## Exclusions
- `.git/` — VCS data
- `docs/adr/` — gitignored ADR wiki clone
- `node_modules/`, `dist/`, `build/`, `target/`, `.venv/`, `__pycache__/`, `vendor/`, `coverage/` — not present, but excluded by policy
- `/home/sjb/.agents/skills/` — global install, NOT the source of truth for this repo
- Binary files, large artifacts, credentials, secrets, personal data
## Navigation rules for future agents
- Start with `fd SKILL.md` to find all skills, then narrow by `fd SKILL.md common/<category>/`
- To understand a skill's purpose, read its `SKILL.md` and the bucket `README.md` that indexes it
- For invocation rules (user-invoked vs model-invoked), read `docs/invocation.md`
- For agent-level docs (issue tracker, triage, ADR, domain), check `docs/agents/`
- Do not browse directories file-by-file; use `fd` and `rg` first
- Track every inspected file in this cache
- Re-read a file only when it changed, the cache is stale, or exact details are needed
## Edit boundaries
When cwd is inside this repo, all file edits MUST be scoped to paths under the repo root (`/home/sjb/Projects/personal/ws-sjb-skills/wt-master`). Do NOT touch files under `/home/sjb/.agents/skills/` or `/home/sjb/.pi/` — those are the installed/runtime copies, not the source of truth. The global install is synced separately; this repo is where source edits happen.
## Refresh notes
- This is a markdown-only repo with no build artifacts; refreshes are rarely needed unless skills are added or removed
- To refresh, re-run `tree -a -I '.git' -L 4` and re-read any changed bucket READMEs or SKILL.md files
- The `docs/adr/` directory is gitignored — if ADR data is needed, check the Gitea wiki directly
- If a skill is moved between buckets, update all README.md files that reference it (root, common, source bucket, destination bucket)
There is no build or test suite. For index changes, verify every `SKILL.md` appears once in the root index and its category index, links resolve, and invocation grouping matches frontmatter.
+1 -2
View File
@@ -1,3 +1,2 @@
docs/adr/
__pycache__/
*.py[cod]
.orchestrate/
+12 -21
View File
@@ -1,28 +1,19 @@
# Steve Beaulac Skills
A collection of agent skills (slash commands and behaviors) loaded into my agent.
A collection of agent skills (slash commands and behaviors) loaded into AI coding agents. Skills live under `skills/`, grouped by purpose; each bucket README and the root README index its `SKILL.md` files by invocation type.
# Structure
Skills are organized into buckets based on where they can be used and their category.
- Use `/common/` for skills that work in all CLI agents.
- Use `/common/misc/` for skills that work in all CLI agents and are in the misc category.
- Use an agent-specific bucket only when a skill is intended for a specific agent.
Skill are organized into categories based on their function. For example, `/common/misc/` is a bucket for miscellaneous skills that work in all CLI agents.
If we have a skill that is only relevant to a specific agent, we can put it in an agent-specific bucket. For example, if we have a skill that is only relevant to the `opencode` agent, we can put it in `/opencode/misc`.
## list of categories
## Skill buckets
- `engineering/` — daily code work
- `productivity/` — daily non-code workflow tools
- `misc/` — kept around but rarely used
- `personal/` — tied to my own setup, not promoted
- `pkm/` — personal knowledge management
- `in-progress/` — drafts not yet ready to ship
- `deprecated/` — no longer used
- `misc/` — kept around but rarely used
- `personal/` — tied to the user's own setup, not promoted
- `pkm/` — personal knowledge management
- `pstack/` — personal agent workflow skills
- `productivity/` — general workflow tools
- `setup-skills/` — one-time repository setup skill and its references
- `skill-authoring/` — create and maintain agent skills
- `thinking-and-docs/` — decisions and documentation workflows
Each bucket folder has a `README.md` that lists every skill in the bucket with a one-line description, with the skill name linked to its `SKILL.md`. Bucket `README.md`s and the top-level `README.md` group entries into **User-invoked** and **Model-invoked**.
@@ -32,7 +23,7 @@ Every `SKILL.md` is either user-invoked (`disable-model-invocation: true`, reach
### 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
@@ -48,7 +39,7 @@ Gitea wiki at `git@gitea.sagacity.ca:steve/Skills.wiki.git`, cloned into `docs/a
## Project Context Pack
Agent memory file that describes the repo's context, codebase, and navigation rules. See `.agents/project-context.md`.
Agent memory file that describes the repo's context, codebase, and navigation rules. See `.agent/project-context.md`.
### Agent CLI
+129 -17
View File
@@ -1,27 +1,139 @@
# 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:
- [Matt Pocock](http://mattpocock.com)
- [poteto](https://github.com/poteto?tab=repositories)
## 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.
- [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.
- [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.
- [implement-isolation](common/engineering/implement-isolation/SKILL.md) — Implement a piece of work based on a spec or set of tickets in isolation.
- [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.
- [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.
- [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.
- [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.
- [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.
- [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.
- [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.
### Setup
- [setup-skills](skills/setup-skills/SKILL.md) — Configure this repo for the engineering skills, issue tracker, triage label vocabulary, and domain doc layout.
### Engineering
- [thermo-nuclear-code-quality-review](skills/engineering/code-quality-review/SKILL.md) — Run an extremely strict maintainability review for abstraction quality, giant files, and spaghetti-condition growth. Use for a thermo-nuclear code quality review, thermonuclear review, deep code quality audit, or especially harsh maintainability review.
- [commit-staged](skills/engineering/commit-staged/SKILL.md) — Commit staged files with a conventional commit message.
- [grill-with-docs](skills/engineering/grill-with-docs/SKILL.md) — A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go.
- [implement](skills/engineering/implement/SKILL.md) — Implement a piece of work based on a spec or set of tickets.
- [implement-isolation](skills/engineering/implement-isolation/SKILL.md) — Implement a piece of work based on a spec or set of tickets in isolation.
- [implement-isolation-tmux](skills/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-spec](skills/engineering/implement-spec/SKILL.md) — Implement the result of /to-spec and /to-tickets in code.
- [implementation-orchestrator](skills/engineering/implementation-orchestrator/SKILL.md) — 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.
- [improve-codebase-architecture](skills/engineering/improve-codebase-architecture/SKILL.md) — Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.
- [orchestrate-herdr](skills/engineering/orchestrate-herdr/SKILL.md) — Start or monitor a Herdr/Pi planner for a published spec ticket; re-invoke after an orchestrator outage.
- [project-context-pack](skills/engineering/project-context-pack/SKILL.md) — Use when the user wants a bounded repo context pack, project map, codebase index, or cached memory file so later work uses fd/rg/tree-sitter/LSP instead of repeated browsing.
- [recipe-diagrams](skills/engineering/recipe-diagrams/SKILL.md) — 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.
- [security-audit](skills/engineering/security-audit/SKILL.md) — Comprehensive security and correctness audit of a branch's changes. Use for deep review requests, or branch/PR diff audits focused on bugs, breaking changes, security issues, devex regressions, and feature-gate leaks.
- [triage](skills/engineering/triage/SKILL.md) — Move issues and external PRs through a state machine of triage roles, categorise, verify, grill if needed, and write agent-ready briefs.
- [wayfinder](skills/engineering/wayfinder/SKILL.md) — 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.
### In Progress
- [agent-handoff](skills/in-progress/agent-handoff/SKILL.md) — Hand the current conversation off to a fresh background agent that picks up the work immediately.
- [knowledge-gardener](skills/in-progress/knowledge-gardener/SKILL.md) — Run vault-aware semantic search, synthesis, note creation, linking, and Zettelkasten workflows for this Obsidian vault.
### Misc
- [bro](skills/misc/bro/SKILL.md) — Restate the last message in plain human language, with no jargon.
- [show-me](skills/misc/show-me/SKILL.md) — Help the user understand the current topic visually with concise diagrams, code-shape sketches, and focused HTML artifacts.
- [tmux-launch-agent](skills/misc/tmux-launch-agent/SKILL.md) — Fork a new agent CLI session into a new tmux window, detected from the current agent.
- [visual-verification](skills/misc/visual-verification/SKILL.md) — Verify running desktop UI changes with screenshots and recordings. Use when changing shell styling, layout, panels, menus, notifications, animations, transitions, or capture flows; inspect the artifacts before reporting completion.
### Personal
- [arch-maintenance](skills/personal/arch-maintenance/SKILL.md) — Keep an Arch or CachyOS system updated and healthy with status, check, and update workflows.
- [arch-troubleshooting](skills/personal/arch-troubleshooting/SKILL.md) — Diagnose and repair Arch or CachyOS system problems.
### Pkm
- [conversation-summary](skills/pkm/conversation-summary/SKILL.md) — Save the current conversation as a comprehensive report note in your Obsidian vault, following OKF v0.1 conventions.
- [crit](skills/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.
- [research-vault](skills/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.
- [youtube-video-capture](skills/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. Use when the user wants to capture a YouTube video, mentions "summarize this video", "capture this talk", or pastes a YouTube URL wanting it saved to vault.
### Productivity
- [grill-me](skills/productivity/grill-me/SKILL.md) — A relentless interview to sharpen a plan or design.
- [handoff](skills/productivity/handoff/SKILL.md) — Compact the current conversation into a handoff document for another agent to pick up.
- [to-questionnaire](skills/productivity/to-questionnaire/SKILL.md) — Turn a decision you can't fully answer into a questionnaire for someone else to fill in.
- [wait-what](skills/productivity/wait-what/SKILL.md) — Stop. That last message did not land: re-pitch it.
### Pstack
- [bugfix-regression-test](skills/pstack/bugfix-regression-test/SKILL.md) — Fix bugs test-first with a focused regression test when practical.
- [interrogate](skills/pstack/interrogate/SKILL.md) — Use for "interrogate", "adversarial review", "multi-model review", "challenge this", "stress test this code", "find blind spots", or "tear this apart". Uses available subagents for independent, evidence-backed review.
### Thinking And Docs
- [before-building](skills/thinking-and-docs/before-building/SKILL.md) — Fire the moment the user proposes a build. Instantly surface the 1-3 consequential choices hidden in his idea. Can also be invoked with /before-building.
- [decisions](skills/thinking-and-docs/decisions/SKILL.md) — Ask the agent to list all choices it made during the current work that it is not confident of. Manual-only; invoke with /decisions.
- [level-up](skills/thinking-and-docs/level-up/SKILL.md) — Gauge the user''s technical + product knowledge through 7 adaptive questions, log verbatim answers with honest ratings, and grow a learning plan from the gaps found. Use when the user says "level up", "level-up session", "quiz me", "gauge my knowledge", or wants a new assessment round. Differentiator: this finds and maps gaps; the `teach` skill delivers lessons on them.
- [read-all-adrs](skills/thinking-and-docs/read-all-adrs/SKILL.md) — Read every ADR markdown file in the project's docs/adr/ folder so you have full context on past decisions. Use only when the user explicitly calls it.
- [remind](skills/thinking-and-docs/remind/SKILL.md) — Rewrite the last response simpler and shorter in plain English, prefixed with a 3-5 sentence TLDR of the conversation so far. Manual-only, invoked as /remind.
- [short](skills/thinking-and-docs/short/SKILL.md) — Manually-invoked skill that forces the agent to compress its current answer — strip filler, simplify wording, and cut length while keeping the substance. Use when the user says "short", "shorter", "simpler", "too long", "tl;dr", or wants a more concise version of the previous response.
- [teach](skills/thinking-and-docs/teach/SKILL.md) — Teach the user a new skill or concept, within this workspace.
## 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.
- [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.
### Engineering
- [feedback-bundle](skills/engineering/feedback-bundle/SKILL.md) — Post a Gitea feedback issue linked to the current commit and attach logs or screenshots. Use when the user reports a problem and asks to file it with evidence, open a bug ticket, or says “feedback-bundle” or “attach the log.”
- [code-review](skills/engineering/code-review/SKILL.md) — 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".
- [codebase-design](skills/engineering/codebase-design/SKILL.md) — 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.
- [diagnosing-bugs](skills/engineering/diagnosing-bugs/SKILL.md) — Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.
- [domain-modeling](skills/engineering/domain-modeling/SKILL.md) — 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.
- [dual-review](skills/engineering/dual-review/SKILL.md) — Run two independent, read-only reviews of a branch diff in parallel — correctness/security and maintainability — then synthesize prioritized findings. Use for a second review axis alongside code-review, a combined deep plus code-quality audit, or when the user asks for dual review. Runs both axes as parallel sub-agents so they do not pollute each other's context.
- [forge-cli](skills/engineering/forge-cli/SKILL.md) — 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.
- [lsp-code-analysis](skills/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.
- [pr](skills/engineering/pr/SKILL.md) — Use when writing a PR body.
- [prototype](skills/engineering/prototype/SKILL.md) — 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.
- [research](skills/engineering/research/SKILL.md) — 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.
- [resolving-merge-conflicts](skills/engineering/resolving-merge-conflicts/SKILL.md) — Use when you need to resolve an in-progress git merge/rebase conflict.
- [tdd](skills/engineering/tdd/SKILL.md) — Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
- [to-spec](skills/engineering/to-spec/SKILL.md) — 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. Use when the user wants a spec from the current conversation or an orchestration workflow needs to publish one from context.
- [to-tickets](skills/engineering/to-tickets/SKILL.md) — Break a plan, spec, or the current conversation into tracer-bullet tickets with blocking edges, published to the configured tracker. Use when the user wants tickets from a plan or spec, or an orchestration workflow needs agent-grabbable tickets.
- [wizard](skills/engineering/wizard/SKILL.md) — 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.
- [worktrees](skills/engineering/worktrees/SKILL.md) — 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.
- [write-discoverable-code](skills/engineering/write-discoverable-code/SKILL.md) — |
### Misc
- [migrate-to-shoehorn](skills/misc/migrate-to-shoehorn/SKILL.md) — 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.
- [scaffold-exercises](skills/misc/scaffold-exercises/SKILL.md) — Create exercise directory structures with sections, problems, solutions, and explainers that pass linting. Use when user wants to scaffold exercises, create exercise stubs, or set up a new course section.
- [setup-pre-commit](skills/misc/setup-pre-commit/SKILL.md) — Set up Husky pre-commit hooks with lint-staged (Prettier), type checking, and tests in the current repo. Use when user wants to add pre-commit hooks, set up Husky, configure lint-staged, or add commit-time formatting/typechecking/testing.
### Pkm
- [pkm-curation](skills/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.
### Productivity
- [grilling](skills/productivity/grilling/SKILL.md) — Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.
- [writing-for-agents](skills/productivity/writing-for-agents/SKILL.md) — Writing documents for agents. Use when creating or editing skills, or modifying AGENTS.md or CLAUDE.md.
### Pstack
- [fix-merge-conflicts](skills/pstack/fix-merge-conflicts/SKILL.md) — Resolve merge conflicts non-interactively, validate build and tests, and finalize conflict resolution
- [how](skills/pstack/how/SKILL.md) — Use for "how does X work", code walkthroughs before changing something, and placement / ownership / layering questions ("where should this live", "which package owns this", "is this the right layer"). Explains subsystem architecture, runtime flow, onboarding mental models. Can critique architecture. Use why for motivation.
- [reflect](skills/pstack/reflect/SKILL.md) — Review a conversation for durable learnings and propose targeted edits to existing agent skills. Use when the user says "reflect", or when a complex workflow, correction, or recoverable dead end produced a reusable lesson.
- [unslop](skills/pstack/unslop/SKILL.md) — Cut AI writing patterns while preserving meaning and voice. Use when drafting, editing, or polishing prose, messages, or documentation.
- [why](skills/pstack/why/SKILL.md) — Investigate why code exists or behaves this way using cited historical evidence. Use for design rationale, tradeoffs, regressions, postmortems, and data-backed thresholds. Distinguishes motivation from how the code currently works.
### Skill Authoring
- [effective-agent-skills](skills/skill-authoring/effective-agent-skills/SKILL.md) — How to write effective agent skills — what to do, what not to do, anatomy, progressive disclosure, design patterns, anti-patterns, testing, security. Read this whenever a skill (Claude Skill, Agent Skill, SKILL.md) is being created, edited, reviewed, or debugged. Use when the user says "create a skill", "new skill", "update this skill", "improve a skill", "why isn't my skill triggering", or anything else involving authoring or editing SKILL.md files.
### Thinking And Docs
- [brain-to-docs](skills/thinking-and-docs/brain-to-docs/SKILL.md) — Use when the user wants to extract project vision, decisions, and preferences from his head into clear documentation (README + ADRs) through a back-and-forth Q&A loop. Triggers on "brain-to-docs", "build out the docs", "extract the vision", "let's document this project".
- [next-decision](skills/thinking-and-docs/next-decision/SKILL.md) — Drill open decisions one at a time — present the most important decision not yet clarified, give the top four choices, state a preference, ask the user. Use when the user says "next decision", "one decision at a time", or a plan has several unresolved choices. Differentiator: forward-looking; the decisions skill is retrospective (choices already made). Can be invoked with /next-decision.
- [prompt-me](skills/thinking-and-docs/prompt-me/SKILL.md) — Prompt the user with pointed questions to extract what is in his head about a project — remaining work, what is being avoided, what really matters, what does not. Use when the user says "prompt me", "ask me questions", or wants the agent to figure out priorities by questioning him.
- [save-idea](skills/thinking-and-docs/save-idea/SKILL.md) — Quickly capture a content idea into ~/code/content from any repo or chat. Video ideas go to VIDEO-IDEAS.md; smaller podcast topics, guest ideas, questions, and AI observations go to TOPICS.md. Every entry gets a source line referencing the chat and repo it came from. Use when the user says "/save-idea", "save this idea", "video idea", "add a topic", "write this down for a video/podcast". Differentiator: appends to the user''s content backlog — not a reminder, task, or general note tool.
-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._
-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
-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
+42
View File
@@ -0,0 +1,42 @@
# Engineering Skills
Daily code work.
## User-invoked
- [thermo-nuclear-code-quality-review](code-quality-review/SKILL.md) — Run an extremely strict maintainability review for abstraction quality, giant files, and spaghetti-condition growth. Use for a thermo-nuclear code quality review, thermonuclear review, deep code quality audit, or especially harsh maintainability review.
- [commit-staged](commit-staged/SKILL.md) — Commit staged files with a conventional commit message.
- [grill-with-docs](grill-with-docs/SKILL.md) — A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go.
- [implement](implement/SKILL.md) — Implement a piece of work based on a spec or set of tickets.
- [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.
- [implement-spec](implement-spec/SKILL.md) — Implement the result of /to-spec and /to-tickets in code.
- [implementation-orchestrator](implementation-orchestrator/SKILL.md) — 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.
- [improve-codebase-architecture](improve-codebase-architecture/SKILL.md) — Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.
- [orchestrate-herdr](orchestrate-herdr/SKILL.md) — Start or monitor a Herdr/Pi planner for a published spec ticket; re-invoke after an orchestrator outage.
- [project-context-pack](project-context-pack/SKILL.md) — Use when the user wants a bounded repo context pack, project map, codebase index, or cached memory file so later work uses fd/rg/tree-sitter/LSP instead of repeated browsing.
- [recipe-diagrams](recipe-diagrams/SKILL.md) — 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.
- [security-audit](security-audit/SKILL.md) — Comprehensive security and correctness audit of a branch's changes. Use for deep review requests, or branch/PR diff audits focused on bugs, breaking changes, security issues, devex regressions, and feature-gate leaks.
- [triage](triage/SKILL.md) — Move issues and external PRs through a state machine of triage roles, categorise, verify, grill if needed, and write agent-ready briefs.
- [wayfinder](wayfinder/SKILL.md) — 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.
## Model-invoked
- [feedback-bundle](feedback-bundle/SKILL.md) — Post a Gitea feedback issue linked to the current commit and attach logs or screenshots. Use when the user reports a problem and asks to file it with evidence, open a bug ticket, or says “feedback-bundle” or “attach the log.”
- [code-review](code-review/SKILL.md) — 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".
- [codebase-design](codebase-design/SKILL.md) — 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.
- [diagnosing-bugs](diagnosing-bugs/SKILL.md) — Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.
- [domain-modeling](domain-modeling/SKILL.md) — 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.
- [dual-review](dual-review/SKILL.md) — Run two independent, read-only reviews of a branch diff in parallel — correctness/security and maintainability — then synthesize prioritized findings. Use for a second review axis alongside code-review, a combined deep plus code-quality audit, or when the user asks for dual review. Runs both axes as parallel sub-agents so they do not pollute each other's context.
- [forge-cli](forge-cli/SKILL.md) — 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.
- [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.
- [pr](pr/SKILL.md) — Use when writing a PR body.
- [prototype](prototype/SKILL.md) — 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.
- [research](research/SKILL.md) — 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.
- [resolving-merge-conflicts](resolving-merge-conflicts/SKILL.md) — Use when you need to resolve an in-progress git merge/rebase conflict.
- [tdd](tdd/SKILL.md) — Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
- [to-spec](to-spec/SKILL.md) — 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. Use when the user wants a spec from the current conversation or an orchestration workflow needs to publish one from context.
- [to-tickets](to-tickets/SKILL.md) — Break a plan, spec, or the current conversation into tracer-bullet tickets with blocking edges, published to the configured tracker. Use when the user wants tickets from a plan or spec, or an orchestration workflow needs agent-grabbable tickets.
- [wizard](wizard/SKILL.md) — 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.
- [worktrees](worktrees/SKILL.md) — 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.
- [write-discoverable-code](write-discoverable-code/SKILL.md) — |
@@ -0,0 +1,192 @@
---
name: code-quality-review
description: Run an extremely strict maintainability review for abstraction quality, giant files, and spaghetti-condition growth. Use for a code quality review, deep code quality audit, or especially harsh maintainability review.
disable-model-invocation: true
---
# Code Quality Review
Use this skill for an unusually strict review focused on implementation quality, maintainability, abstraction quality, and codebase health.
Above all, this skill should push the reviewer to be **ambitious** about code structure. Do not merely identify local cleanup opportunities. Actively search for "code judo" moves: restructurings that preserve behavior while making the implementation dramatically simpler, smaller, more direct, and more elegant.
## Core Prompt
Start from this baseline:
> Perform a deep code quality audit of the current branch's changes.
> Rethink how to structure / implement the changes to meaningfully improve code quality without impacting behavior.
> Work to improve abstractions, modularity, reduce Spaghetti code, improve succinctness and legibility.
> Be ambitious, if there is a clear path to improving the implementation that involves restructuring some of the codebase, go for it.
> Be extremely thorough and rigorous. Measure twice, cut once.
## Non-Negotiable Additional Standards
Apply the baseline prompt above, plus these explicit review rules:
0. **Be ambitious about structural simplification.**
- Do not stop at "this could be a bit cleaner."
- Look for opportunities to reframe the change so that whole branches, helpers, modes, conditionals, or layers disappear entirely.
- Prefer the solution that makes the code feel inevitable in hindsight.
- Assume there is often a "code judo" move available: a re-organization that uses the existing architecture more effectively and makes the change dramatically simpler and more elegant.
- If you see a path to delete complexity rather than rearrange it, push hard for that path.
1. **Do not let a PR push a file from under 1k lines to over 1k lines without a very strong reason.**
- Treat this as a strong code-quality smell by default.
- Prefer extracting helpers, subcomponents, modules, or local abstractions instead of letting a file sprawl past 1000 lines.
- If the diff crosses that threshold, explicitly ask whether the code should be decomposed first.
- Only waive this if there is a compelling structural reason and the resulting file is still clearly organized.
2. **Do not allow random spaghetti growth in existing code.**
- Be highly suspicious of new ad-hoc conditionals, scattered special cases, or one-off branches inserted into unrelated flows.
- If a change adds "weird if statements in random places", treat that as a design problem, not a stylistic nit.
- Prefer pushing the logic into a dedicated abstraction, helper, state machine, policy object, or separate module instead of tangling an existing path.
- Call out changes that make the surrounding code harder to reason about, even if they technically work.
3. **Bias toward cleaning the design, not just accepting working code.**
- If behavior can stay the same while the structure becomes meaningfully cleaner, push for the cleaner version.
- Do not rubber-stamp "it works" implementations that leave the codebase messier.
- Strongly prefer simplifications that remove moving pieces altogether over refactors that merely spread the same complexity around.
4. **Prefer direct, boring, maintainable code over hacky or magical code.**
- Treat brittle, ad-hoc, or "magic" behavior as a code-quality problem.
- Be skeptical of generic mechanisms that hide simple data-shape assumptions.
- Flag thin abstractions, identity wrappers, or pass-through helpers that add indirection without buying clarity.
5. **Push hard on type and boundary cleanliness when they affect maintainability.**
- Question unnecessary optionality, `unknown`, `any`, or cast-heavy code when a clearer type boundary could exist.
- Prefer explicit typed models or shared contracts over loosely-shaped ad-hoc objects.
- If a branch relies on silent fallback to paper over an unclear invariant, ask whether the boundary should be made explicit instead.
6. **Keep logic in the canonical layer and reuse existing helpers.**
- Call out feature logic leaking into shared paths or implementation details leaking through APIs.
- Prefer existing canonical utilities/helpers over bespoke one-offs.
- Push code toward the right package, service, or module instead of normalizing architectural drift.
7. **Treat unnecessary sequential orchestration and non-atomic updates as design smells when the cleaner structure is obvious.**
- If independent work is serialized for no good reason, ask whether the flow should run in parallel instead.
- If related updates can leave state half-applied, push for a more atomic structure.
- Do not over-index on micro-optimizations, but do flag avoidable orchestration complexity that makes the implementation more brittle.
## Primary Review Questions
For every meaningful change, ask:
- Is there a "code judo" move that would make this dramatically simpler?
- Can this change be reframed so fewer concepts, branches, or helper layers are needed?
- Does this improve or worsen the local architecture?
- Did the diff add branching complexity where a better abstraction should exist?
- Did a previously cohesive module become more coupled, more stateful, or harder to scan?
- Is this logic living in the right file and layer?
- Did this change enlarge a file or component past a healthy size boundary?
- Are there repeated conditionals that signal a missing model or missing helper?
- Is the implementation direct and legible, or does it rely on special cases and incidental control flow?
- Is this abstraction actually earning its keep, or is it just a wrapper?
- Did the diff introduce casts, optionality, or ad-hoc object shapes that obscure the real invariant?
- Is this logic living in the canonical layer, or did the diff leak details across a boundary?
- Is this orchestration more sequential or less atomic than it needs to be?
## What to Flag Aggressively
Escalate findings when you see:
- A complicated implementation where a cleaner reframing could delete whole categories of complexity.
- Refactors that move code around but fail to reduce the number of concepts a reader must hold in their head.
- A file crossing 1000 lines due to the PR, especially if the new code could be split out.
- New conditionals bolted onto unrelated code paths.
- One-off booleans, nullable modes, or flags that complicate existing control flow.
- Feature-specific logic leaking into general-purpose modules.
- Generic "magic" handling that hides simple structure and makes the code harder to reason about.
- Thin wrappers or identity abstractions that add indirection without simplifying anything.
- Unnecessary casts, `any`, `unknown`, or optional params that muddy the real contract.
- Copy-pasted logic instead of extracted helpers.
- Narrow edge-case handling implemented in the middle of an already busy function.
- Refactors that technically pass tests but make the code less modular or less readable.
- "Temporary" branching that is likely to become permanent debt.
- Bespoke helpers where the codebase already has a canonical utility for the job.
- Logic added in the wrong layer/package when it should live somewhere more central.
- Sequential async flow where obviously independent work could stay simpler and clearer with parallel execution.
- Partial-update logic that leaves state less atomic than necessary.
## Preferred Remedies
When you identify a code-quality problem, prefer suggestions like:
- Delete a whole layer of indirection rather than polishing it.
- Reframe the state model so conditionals disappear instead of getting centralized.
- Change the ownership boundary so the feature becomes a natural extension of an existing abstraction.
- Turn special-case logic into a simpler default flow with fewer exceptions.
- Extract a helper or pure function.
- Split a large file into smaller focused modules.
- Move feature-specific logic behind a dedicated abstraction.
- Replace condition chains with a typed model or explicit dispatcher.
- Separate orchestration from business logic.
- Collapse duplicate branches into a single clearer flow.
- Delete wrappers that do not meaningfully clarify the API.
- Reuse the existing canonical helper instead of introducing a near-duplicate.
- Make type boundaries more explicit so the control flow gets simpler.
- Move the logic to the package/module/layer that already owns the concept.
- Parallelize independent work when that also simplifies the orchestration.
- Restructure related updates into a more atomic flow when partial state would be harder to reason about.
Do not be satisfied with "maybe rename this" feedback when the real issue is structural.
Do not be satisfied with a merely cleaner version of the same messy idea if there is a plausible path to a much simpler idea.
## Review Tone
Be direct, serious, and demanding about quality.
Do not be rude, but do not soften major maintainability issues into mild suggestions.
If the code is making the codebase messier, say so clearly.
If the implementation missed an opportunity for a dramatic simplification, say that clearly too.
Good phrases:
- `this pushes the file past 1k lines. can we decompose this first?`
- `this adds another special-case branch into an already busy flow. can we move this behind its own abstraction?`
- `this works, but it makes the surrounding code more spaghetti. let's keep the behavior and restructure the implementation.`
- `this feels like feature logic leaking into a shared path. can we isolate it?`
- `this abstraction seems unnecessary. can we just keep the direct flow?`
- `why does this need a cast / optional here? can we make the boundary more explicit instead?`
- `this looks like a bespoke helper for something we already have elsewhere. can we reuse the canonical one?`
- `i think there's a code-judo move here that makes this much simpler. can we reframe this so these branches disappear?`
- `this refactor moves complexity around, but doesn't really delete it. is there a way to make the model itself simpler?`
## Output Expectations
Prioritize findings in this order:
1. Structural code-quality regressions
2. Missed opportunities for dramatic simplification / code-judo restructuring
3. Spaghetti / branching complexity increases
4. Boundary / abstraction / type-contract problems that make the code harder to reason about
5. File-size and decomposition concerns
6. Modularity and abstraction issues
7. Legibility and maintainability concerns
Do not flood the review with low-value nits if there are larger structural issues.
Prefer a smaller number of high-conviction comments over a long list of cosmetic notes.
## Approval Bar
Do not approve merely because behavior seems correct.
The bar for approval is:
- no clear structural regression
- no obvious missed opportunity to make the implementation dramatically simpler when such a path is visible
- no unjustified file-size explosion
- no obvious spaghetti-growth from special-case branching
- no obviously hacky or magical abstraction that makes the code harder to reason about
- no unnecessary wrapper/cast/optionality churn obscuring the real design
- no clear architecture-boundary leak or avoidable canonical-helper duplication
- no missed opportunity for an obvious decomposition that would materially improve maintainability
Treat these as presumptive blockers unless the author can justify them clearly:
- the PR preserves a lot of incidental complexity when there is a plausible code-judo move that would delete it
- the PR pushes a file from below 1000 lines to above 1000 lines
- the PR adds ad-hoc branching that makes an existing flow more tangled
- the PR solves a local problem by scattering feature checks across shared code
- the PR adds an unnecessary abstraction, wrapper, or cast-heavy contract that makes the design more indirect
- the PR duplicates an existing helper or puts logic in the wrong layer when there is a clear canonical home
If those conditions are not met, leave explicit, actionable feedback and push for a cleaner decomposition.
@@ -0,0 +1,5 @@
interface:
display_name: "Thermo-Nuclear Code Quality Review"
short_description: "Strict review of abstractions, large files, and condition complexity"
policy:
allow_implicit_invocation: false
+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"
+49
View File
@@ -0,0 +1,49 @@
---
name: dual-review
description: "Run two independent, read-only reviews of a branch diff in parallel — correctness/security and maintainability — then synthesize prioritized findings. Use for a second review axis alongside code-review, a combined deep plus code-quality audit, or when the user asks for dual review. Runs both axes as parallel sub-agents so they do not pollute each other's context."
---
# Dual review
Two independent, read-only reviews of the diff between `HEAD` and a fixed point, then a synthesis:
- **Correctness/security** — bugs, breakages, security gaps, devex regressions, and feature-gate leaks in the changed code.
- **Maintainability** — structural quality, simplification, boundaries, and codebase health in the changed code.
Together with `code-review` (spec, standards) these form the four review axes. Both axes run as **parallel sub-agents**, 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 did not specify one, ask for it.
Capture the diff command once: `git diff <fixed-point>...HEAD` (three-dot, against the merge-base). Note the commit list via `git log <fixed-point>..HEAD --oneline`.
Confirm the fixed point resolves (`git rev-parse <fixed-point>`) and the diff is non-empty before spawning anything. A bad ref or empty diff fails here, not inside two sub-agents.
### 2. Gather context
Gather the diff and the contents of changed files, plus only the surrounding context needed to trace behavior. Read each changed file at its current version. Do not review files outside the diff scope.
### 3. Spawn both sub-agents in parallel
Both get the same scoped diff and changed-file context and a distinct task.
**Correctness/security brief:** "Report, per file/hunk where relevant, every bug, breakage, security gap, devex regression, or feature-gate leak in the added or modified code. Cite the hunk and explain the concrete failure or exposure. Distinguish hard defects from judgement calls. Under 400 words."
**Maintainability brief:** "Report, per file/hunk where relevant, structural quality problems in the added or modified code: duplication, large or over-generalized units, weak boundaries, primitive obsession, speculative generality, or other smells that will cost to maintain. Name the problem and quote the hunk; flag hard violations from judgement calls. Under 400 words."
Ask each to report prioritized findings with file/line evidence and to **not** edit files.
### 4. Synthesize
Wait for both runs before synthesizing. Deduplicate overlapping findings, resolve disagreements using the evidence, and list the highest-priority findings first. Present them under `## Correctness/security` and `## Maintainability` headings. If there are no findings, say so and note the review scope and its limitations. Do not restate child summaries already visible to the user.
## Review constraints
- Report issues only in code added or modified within the review scope.
- Do not present uncertain or unfinished research as a finding.
- Do not fix reported issues unless the user asks.
@@ -0,0 +1,5 @@
interface:
display_name: "Dual Review"
short_description: "Parallel correctness, security, and maintainability review"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,40 @@
---
name: feedback-bundle
description: Post a Gitea feedback issue linked to the current commit and attach logs or screenshots. Use when the user reports a problem and asks to file it with evidence, open a bug ticket, or says "feedback-bundle" or "attach the log".
---
# Feedback Bundle
Create a Gitea issue in the current repository, linked to its current `HEAD`, with optional files attached.
## Run
Run from the repository the issue should belong to, using `feedback_bundle.py` beside this file:
```sh
python3 <skill-dir>/feedback_bundle.py "Describe the problem" @app.log @screenshot.png
```
The script requires Python `requests`. Without `--token`, it reads the matching host token from `~/.config/tea/config.yml` and requires PyYAML. The default repository is read from `git remote get-url origin`.
Common options:
```sh
python3 <skill-dir>/feedback_bundle.py "Description" @log.txt \
--title "Short issue title" --label bug --dry-run
```
- `@file` — attach an existing file; paths are resolved from the current working directory. The `@` is optional.
- `--title` — override the default title (the description's first line).
- `--label` — add a label; repeat to add more. Labels are resolved against the repository's Gitea labels; unknown labels are skipped with a warning.
- `--repo` — override the remote URL. Use a full Git remote URL (SSH, SCP-style, or HTTPS), not an `owner/repo` slug.
- `--token` — provide a Gitea token instead of reading tea config.
- `--dry-run` — print the issue preview without creating an issue or uploading files. Authentication is still loaded; labels require an API request.
## What happens
1. The script reads `HEAD`, repository host/owner/name, and authentication.
2. It creates an issue whose body includes a link to that exact commit.
3. It uploads each attachment to the issue and adds download links to the body.
Gitea only accepts issue attachments after an issue exists. If uploads fail because attachments are disabled (403/404), the issue already exists without the files; enable attachments on the Gitea instance, then attach the files to that issue manually. The instance setting is `[attachment] ENABLED = true` in `app.ini` (or `ATTACHMENTS_ENABLED`), not a web UI toggle.
@@ -0,0 +1,5 @@
interface:
display_name: "Feedback Bundle"
short_description: "File Gitea issues with commit links and attached evidence"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,183 @@
#!/usr/bin/env python3
"""Post a feedback ticket to a Gitea repo, linked to the current commit, with
files attached to the issue.
feedback_bundle.py [--title T] [--label L ...] [--repo REMOTE_URL] [--token T]
[--dry-run] <description> [@file ...]
Flow (Gitea attaches files to an existing issue, there is no standalone upload
endpoint): create the issue, then POST each file to
/repos/{owner}/{repo}/issues/{number}/assets (multipart field "attachment").
The ticket body links to `git HEAD` and lists the attached files.
If the assets endpoint returns 403/404 the instance has attachments disabled
(admin `[attachment] ENABLED = true` in app.ini — not a web-UI setting); the
script reports this instead of posting a ticket with no attachments.
"""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
try:
import requests
except ImportError: # pragma: no cover
sys.exit("requests is required: pip install requests")
def run(*args: str) -> str:
return subprocess.run(args, capture_output=True, text=True, check=True).stdout.strip()
def parse_remote(remote: str | None) -> tuple[str, str, str]:
"""(host, owner, repo) from a git remote URL (scp, ssh, or https forms)."""
url = remote or run("git", "remote", "get-url", "origin")
u = re.sub(r"^[a-z]+://", "", url.strip(), flags=re.I) # strip scheme
u = u.split("@", 1)[-1] # strip user@
u = u.replace(".git", "").rstrip("/")
host, rest = (u.split(":", 1) if ":" in u else u.split("/", 1))
owner, repo = rest.split("/", 1)
return host, owner, repo
def load_token(host: str, token: str | None) -> str:
if token:
return token
cfg = os.path.expanduser("~/.config/tea/config.yml")
if not os.path.exists(cfg):
sys.exit("no --token and no tea config found; cannot authenticate")
import yaml
data = yaml.safe_load(open(cfg).read())
for login in data.get("logins", []):
if login.get("url").rstrip("/").endswith(host) and login.get("token"):
return login["token"]
sys.exit(f"no stored token for host {host}; pass --token")
def resolve_labels(host, token, owner, repo, names):
"""Gitea's issue API wants label IDs, not names. Map names to IDs; warn on
unknown labels and drop them."""
if not names:
return []
url = f"https://{host}/api/v1/repos/{owner}/{repo}/labels"
r = requests.get(url, headers={"Authorization": f"token {token}"})
if r.status_code >= 400:
sys.exit(f"could not list labels ({r.status_code}): {r.text}")
by_name = {l["name"]: l["id"] for l in r.json()}
ids = []
for n in names:
if n in by_name:
ids.append(by_name[n])
else:
print(f"warning: unknown label '{n}', skipping", file=sys.stderr)
return ids
def create_issue(host, token, owner, repo, title, body, label_ids):
url = f"https://{host}/api/v1/repos/{owner}/{repo}/issues"
r = requests.post(url, json={"title": title, "body": body, "labels": label_ids},
headers={"Authorization": f"token {token}"})
if r.status_code >= 400:
sys.exit(f"issue create failed ({r.status_code}): {r.text}")
return r.json()
def attach(host, token, owner, repo, issue_number, path):
"""Attach one file to an issue. Returns the browser_download_url, or None
on 403/404 (attachments disabled on this instance)."""
url = f"https://{host}/api/v1/repos/{owner}/{repo}/issues/{issue_number}/assets"
with open(path, "rb") as f:
r = requests.post(url, files={"attachment": f},
params={"name": os.path.basename(path)},
headers={"Authorization": f"token {token}"})
if r.status_code in (403, 404):
return None
r.raise_for_status()
return r.json().get("browser_download_url")
def main() -> int:
ap = argparse.ArgumentParser(description="Post a commit-linked feedback ticket with attachments.")
ap.add_argument("description", help="ticket description (text before any @file)")
ap.add_argument("files", nargs="*", help="files to attach (@name or name)")
ap.add_argument("--title", help="ticket title (default: first line of description)")
ap.add_argument("--label", action="append", default=[], help="label to add (repeatable)")
ap.add_argument("--repo", help="Git remote URL (default: git remote origin)")
ap.add_argument("--token", help="Gitea token (default: tea config for the host)")
ap.add_argument("--dry-run", action="store_true", help="print the ticket without posting it")
args = ap.parse_args()
files = [f.lstrip("@") for f in args.files]
for p in files:
if not os.path.isfile(p):
sys.exit(f"not a file: {p}")
host, owner, repo = parse_remote(args.repo) if args.repo else (None, None, None)
if not host:
host, owner, repo = parse_remote(None)
token = load_token(host, args.token)
sha = run("git", "rev-parse", "HEAD")
short = sha[:7]
commit_url = f"https://{host}/{owner}/{repo}/commit/{sha}"
desc = args.description.strip()
title = (args.title or desc).strip().splitlines()[0] if desc else "(no description)"
labels = resolve_labels(host, token, owner, repo, [l for l in args.label if l])
seed = f"{desc}\n\n**Linked commit:** [{short}]({commit_url}) (`{sha}`)"
# Preview only: no issue is created and nothing is uploaded.
if args.dry_run:
att_line = "\n".join(f"- {os.path.basename(p)}" for p in files) or "(none)"
body = seed + "\n\n**Attachments:**\n" + att_line
print("=== DRY RUN (nothing created) ===")
print(f"repo: {owner}/{repo}")
print(f"commit: {commit_url}")
print(f"title: {title}")
print(f"labels: {[l for l in args.label if l] or '(none)'}")
print(f"attach: {att_line}")
print("=== body ===")
print(body)
return 0
# Create the issue first (Gitea attaches files to an existing issue).
issue = create_issue(host, token, owner, repo, title, seed, labels)
number = issue["number"]
attached = []
missing = False
for p in files:
url = attach(host, token, owner, repo, number, p)
if url is None:
missing = True
else:
attached.append((os.path.basename(p), url))
if missing and not attached:
print(
"ERROR: attachment endpoint returned 403/404 — attachments are disabled on this "
"instance (admin setting `[attachment] ENABLED = true` in app.ini; there is no "
"web-UI toggle). Enable it and re-run. The issue was created but has no attachments.",
file=sys.stderr,
)
return 2
if attached:
body = seed + "\n\n**Attachments:**\n" + "\n".join(f"- [{n}]({u})" for n, u in attached)
patch_url = f"https://{host}/api/v1/repos/{owner}/{repo}/issues/{number}"
requests.patch(patch_url, json={"body": body},
headers={"Authorization": f"token {token}"})
if missing:
print(f"warning: {sum(1 for _ in range(0)) + (len(files) - len(attached))} file(s) could not be attached (instance may have attachments disabled)",
file=sys.stderr)
print(f"Created: {issue.get('html_url', '')}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+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,34 @@
# 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
```
Prefer these CLI verbs over hand-rolled REST. If `tea` lacks a verb (check `tea pulls --help` for the current close and merge verbs), and you fall back to the Gitea REST API, note that the issue create/update payload takes label **IDs**, while the `/issues/{id}/labels` sub-resource takes **names**. Keep `curl` output out of the transcript by writing it to a file (`curl -s ... -o FILE`).
## 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-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. Then run the `security-audit` and `code-quality-review` both in their own `reviewer` subagent. 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
@@ -0,0 +1,29 @@
---
name: orchestrate-herdr
description: "Start a Herdr/Pi planner for a published spec ticket. Invocation: /skill:orchestrate-herdr ISSUE [WORKER]; omitted worker uses the current local worker."
disable-model-invocation: true
---
# Orchestrate a spec with Herdr
This skill takes a tracker issue number and optional Herdr worker node. It checks whether a planner is already running for that spec; if so, it reports that and exits. Otherwise it starts a planner and exits after confirming startup. The planner runs independently; there is no need to monitor it.
The **planner** runs on the worker node and coordinates the spec workflow. It delegates implementation, review, and merge work to subagents—not separate CLI agents or Herdr-launched agents. Never attach to, prompt, or resume an existing agent.
When the invoking session is itself the planner — the local worker started the planner in this session, or no saved or matching machine and pane exists — the two identities collapse. Do not go looking for a planner to monitor: run the run-loop directly in this session, skip the launch-claim and monitor ceremony, and record the session as both orchestrator and planner in `run.json`.
Read these references before acting:
- `references/dispatcher.md` — discover an existing run or safely start a planner.
- `references/run-loop.md` — implement and close the spec.
- `references/state.md` — worker-side run metadata, event log, claims, and recovery.
## Prerequisites
The selected worker must have Herdr, Git, the target repository and credentials, this skill, and an authenticated forge CLI (`tea`, `gh`, or `glab`). Run the `forge-cli` preflight there. If a prerequisite, machine, or run identity is missing or ambiguous, stop with actionable guidance; do not guess or dispatch.
## Workflow
1. Validate the spec issue and worker, then follow `references/dispatcher.md` to find or start its planner.
2. If a planner is already active for the spec, report that and exit. Do not attach, prompt, resume, or monitor it.
3. If starting a planner, confirm it reaches `working`, then report the run identity and exit. The planner owns the workflow from there; retain run metadata and logs unless the user explicitly asks to delete them.
@@ -0,0 +1,5 @@
interface:
display_name: "Start a spec with Herdr"
short_description: "Start its planner and exit after startup confirmation"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,27 @@
# Dispatcher: find or start the planner
Invocation is `/skill:orchestrate-herdr <spec-ticket> [worker]` (for example, `/skill:orchestrate-herdr 34 obelix`). The spec issue is required. A named worker is the preferred node for a new planner; if omitted or blank, use the current local worker. Never silently select a different machine.
## Find an existing run first
1. Confirm the issue exists, is the parent/spec ticket, and is open. If closed, report completion and do not launch anything.
2. Resolve the named worker with `herdr machine list`; it is the target for a new run. To find an existing run, inspect enabled saved machines using their exact labels/IDs and `herdr --machine <machine> agent list`.
3. Read the issue's `in-progress` label and locate its `.orchestrate/<slug>/run.json` on candidate worker checkouts. Match exact recorded Herdr workspace/pane/agent IDs. Agent listings show runtime identity and status, not the spec issue; use a working directory only to locate a candidate checkout, never as proof of ownership. If the recorded pane no longer exists, match the live `herdr agent list` entry and rewrite `run.json` to it, logging the reconciliation; a stale ID is a reconciliation event, not a mismatch. `herdr machine list` reporting no saved machines means the local session is the worker.
4. If a matching planner is active, monitor it; do not start another. If that planner is this session, the identities have collapsed: continue the run loop here instead of monitoring. If the matching run exists but the label is missing, verify the run identity, add `in-progress`, comment on the reconciliation, and monitor.
5. If `in-progress` is set but no matching agent can be found, do not start a planner. Refresh Herdr and run state to account for propagation delay; if still unmatched, comment on the parent issue with the mismatch and evidence, then stop for human direction. Do not clear the label automatically.
6. If there is no matching agent and no `in-progress` label, reconcile any existing run metadata, issue comments, and Git state. If there is no active or ambiguous work, proceed to start a planner. If anything is uncertain, stop rather than risk duplicate work.
For an untracked agent, do not attach to it or assume it belongs to this spec. Flag it for human review if it appears relevant; otherwise leave it untouched.
## Start a new planner
1. On the selected worker, acquire a per-spec launch claim using an atomic exclusive create under `.orchestrate/`. If another invocation holds the claim, reconcile its owner and run state; never steal an uncertain claim.
2. Create a new sibling pane in the confirmed repository checkout and start a fresh Pi planner agent there. Never use an existing agent pane as the planner. Give the planner the issue number, worker identity, repository path, and references to `run-loop.md` and `state.md`.
3. The planner's first action is to set/verify the spec's `in-progress` label, before reading tickets or dispatching agents. It then records its Herdr IDs in `run.json` and begins the run loop.
4. Confirm the planner reaches `working` and the label is set. Release the launch claim only after confirmed startup. If startup failure is confirmed, release the claim and report the failure. If the outcome is uncertain, retain the claim and stop; do not retry blindly.
## Start confirmation and failures
After launching, confirm the planner reaches `working` and the `in-progress` label is set. Then report its run identity and exit; do not wait for later state changes or monitor its agents. If the machine is unreachable, check it with `herdr machine status`; when authentication is needed, run `herdr machine reconnect <label-or-id>` and verify connectivity. Retry transient connection failures at most twice after the first attempt. If the run cannot be safely identified, comment with the blocker and stop; do not dispatch to a different worker.
Herdr machine commands require an enabled saved machine and reachable, API-compatible Herdr server. A failed connection does not prove a mutation failed; reconcile remote state before retrying.
@@ -0,0 +1,53 @@
# Run loop: implement a spec ticket
The spec and linked tickets define scope; the tracker is the source of truth. The planner's first action is to set/verify the parent issue's `in-progress` label. Then read the spec, every associated ticket, blockers, and relevant comments. If the spec has no linked implementation tickets forming an actionable frontier, invoke `/to-tickets` and follow its approval and publishing process before implementation. If tickets are blocked, don't invent extra work.
The issue tracker should have been provided. If not, tell the user to run `/setup-skills`.
The goal is the entire spec implemented on one **integration branch**, with each ticket resolved according to tracker semantics. Treat tickets as a dependency graph; re-query the tracker as the ready frontier changes. If no ticket is actionable, report the blocker rather than guessing.
## Communication
All agent communication and handoffs go through tracker or PR comments; `.orchestrate/<slug>/events.jsonl` is only the operational event log. Keep comments concise and link to context rather than copying ticket bodies or pane output.
- Implementers post their completion handoff or blocker on the task issue, including branch/commit, changed files, acceptance evidence, checks, and concerns.
- Reviewers put review discussion on the PR. Record the review outcome on the task issue.
- The planner posts parent-spec comments at meaningful milestones: implementation ready, review outcome, merge, actionable blocker, and completion. Don't repeat comments already posted by a worker.
## 1. Read and establish the integration branch
- Confirm the supplied issue is the parent/spec ticket and identify linked implementation tickets.
- Understand the task graph and current frontier. Re-query tracker state as work advances.
- When tickets require codebase or external-documentation exploration, use a subagent and put concise findings in the relevant tracker comment for later subagents to reference.
- Create one integration branch from the intended target branch. If a PR is required, open a draft after the first implementation merge and link it to close the spec and tickets.
- If a ticket or its dependencies are ambiguous, stop and ask rather than infer.
## 2. Implement the frontier
Use the `subagents` skill and native subagent workflow for every child role. Do not use Herdr agent commands or launch separate CLI processes for implementers, reviewers, fixers, or mergers.
For each open, unblocked ticket, start a **worker subagent** from the planner using the native subagent workflow, with its own worktree and branch. Independent frontier tickets may run concurrently; never parallel-write a shared checkout. Do not launch implementers, reviewers, fixers, or mergers as separate CLI or Herdr agents; the planner is the only full CLI agent. Start a fresh worker subagent for each merge.
Start each implementer with its role, task-issue URL, worktree path, and starting branch; the issue itself holds scope and acceptance criteria. Put any later clarification or handoff in tracker/PR comments, not agent-to-agent chat. Require the implementer to:
- confirm its worktree starts from the current integration branch (reset/rebase onto it if needed);
- use the `tdd` skill and run focused checks;
- commit its ticket work on its task branch;
- merge the latest integration branch into its task branch before reporting done;
- post its handoff on the task issue; do not merge to the integration branch or open a PR.
When an implementer finishes, have a **new independent reviewer subagent** run the `code-review`, `security-audit`, and `code-quality-review` skills against that task branch, using the current integration branch as the base. Put review discussion on the PR and summarize its outcome on the task issue. Resolve actionable findings in a fresh scoped worker subagent and rerun review until clear. Only then use a fresh worker subagent to merge the task branch into the integration branch. Before dispatching the merger, confirm the task worktree is clean (`git status --porcelain` empty) and the task branch is fully pushed; recover unpushed or uncommitted work rather than merging around it. Verify the merge and update tracker state before dispatching newly unblocked tickets. Reconcile uncertain Git or tracker outcomes before retrying.
When a check spans tickets — for example one coverage threshold covering several modules — an individual task branch can be red because it owns only part of the check, not because of a defect. Review still runs against the task branch, but assert the shared check after merge, on the integration branch; merge-then-fix is the allowed order in that case. Before deviating from green-before-merge, decide whether the check or the branch is mis-scoped, and record that decision.
## 3. Final review and completion
After all tickets are implemented and merged, have a **reviewer subagent** run `code-review` against the entire integration branch as a final integration review. Have a fresh worker subagent fix actionable findings in a scoped worktree; merge the fixes and rerun review until clear. Do not report completion until this review is clear and final checks pass; do not merge around unresolved findings or failed checks.
If a draft PR exists, mark it `needs-review` after final checks. Otherwise, resolve each ticket according to tracker close semantics and report the integration branch. Close the parent spec ticket only when all work is complete, verified, and merged. As part of closing it, remove the `in-progress` label. Clean only confirmed-clean implementer worktrees and issue branch that have been merged successfully in draft PR; retain unresolved work and the worker-side run log.
## Retry and escalation rules
- Retry transient infrastructure failures at most twice after the first attempt. Never blindly retry semantic failures, failed checks, or rejected reviews.
- If an operation's outcome is uncertain, reconcile tracker, Git, worker, and Herdr state before repeating it.
- Stop and preserve state/evidence for auth or permission failures, unresolved state mismatches, exhausted retries, ambiguity, or decisions requiring human judgment.
@@ -0,0 +1,33 @@
# Worker-side run state and recovery
The worker node is the source of truth. Keep state under `.orchestrate/<slug>/` in the target repository checkout, outside product commits and PRs. Use a stable issue-derived slug such as `spec-34`; do not mirror state on the orchestrator node.
## Files
- `run.json` — minimal recovery metadata: spec issue ID/URL, repository identity, worker label/ID, planner's Herdr agent/pane/workspace IDs, and each tracked child subagent's role, issue ID, subagent run ID, branch, and worktree.
- `events.jsonl` — append-only structured operational events: timestamp, actor/task, action, outcome, and relevant Herdr/Git/tracker IDs. No pane transcripts, copied ticket bodies, plans, or handoff prose. Record a start and finish event for every phase (worktree created, implementer handoff, review dispatched, review completed, merge completed); a phase with only one of the pair is a detectable gap, whereas a silent absence is not.
The issue tracker is canonical for ticket status, acceptance criteria, decisions, and communication. Keep agent handoffs and blockers in comments on the relevant task issue; use PR comments for review discussion; use parent-spec comments for milestone rollups. Do not create local handoff files or duplicate tracker content in `run.json`.
## Claim and label
Before creating a planner, acquire a per-spec launch claim under `.orchestrate/` with an atomic exclusive create. The claim only serializes startup; it is not a second progress record. Record its owner and issue ID. Never steal an uncertain claim.
The new planner's first action is to set/verify the parent's `in-progress` label, before reading tickets or dispatching work. After confirmed startup and recording the planner's Herdr IDs, release the launch claim. Release a claim after startup failure only when failure and absence of a running planner are confirmed. Keep it and escalate when the result is uncertain.
If the parent has `in-progress` but no matching agent is found, do not start a replacement or clear the label. Comment with the mismatch and wait for the user's explicit retry decision. If a matching agent exists but the label is missing, verify the run record, add the label, and comment on the repair.
## Persist and recover
Append a structured event after each consequential side effect and enough identity data to match the run to Herdr. The worker log records activity while the orchestrator is unavailable; agents continue posting comments to the tracker.
On every invocation or restart:
1. Read the parent issue, labels, and relevant comments.
2. Inspect the worker's `run.json` and event log.
3. Query Herdr agent state and match exact recorded IDs; do not infer ownership from a matching working directory. If the recorded pane was recreated or removed between sessions, match the live entry, rewrite `run.json` to it, and log the reconciliation.
4. Reconcile tracker and Git state before deciding to start a planner. If the worker is unreachable or identities/state disagree, report the blocker and stop rather than guessing.
If a matching live planner exists, report that it is already running and exit; do not attach to, prompt, or resume it. The planner manages its own subagents. If there is no matching agent and no `in-progress` label, reconcile any stale run record; start a fresh planner only when no active or ambiguous work remains and a new atomic claim is acquired.
Retain `run.json` and `events.jsonl` after completion. The planner removes `in-progress` while closing the parent spec only after all tickets are complete, verified, and merged. Delete retained run state only at the user's explicit request.
+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,5 @@
interface:
display_name: "Recipe Diagrams"
short_description: "Turn recipes into process-flow diagrams"
policy:
allow_implicit_invocation: false
@@ -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"
@@ -0,0 +1,51 @@
---
name: security-audit
description: Comprehensive security and correctness audit of a branch's changes. Use for deep review requests, or branch/PR diff audits focused on bugs, breaking changes, security issues, devex regressions, and feature-gate leaks.
---
# Security Audit Skill
Use this skill for a comprehensive security and correctness audit of a checked-out branch.
## Prompt
You are a security expert performing a comprehensive review of a checked out branch. Audit this branch and its changes extremely thoroughly for bugs, changes that break existing features/functionality, and security vulnerabilities. Be EXTREMELY thorough, rigorous, careful, ambitious, and attentive. NOTHING can slip through.
# Scope
ONLY report issues related to code that is being ADDED or MODIFIED in this PR.
Focus on changes in the diff.
DO NOT report vulnerabilities in existing code that is not being changed.
# Guidelines
## Breaking Functionality Guidelines
This is a complex codebase, with many cross-package/module dependencies. Often simple code changes in one place have subtle interactions that break functionality elsewhere. You MUST be extremely thorough in tracing through possible side effects of the changes.
## Breaking Devex Guidelines
It can be easy to break developers' ability to run / build the code locally. You MUST catch changes that will impact users' developer experience. Some examples (not exhaustive):
- Modifying how secrets are read / where they are read from
- Updating environment variable names / adding environment variables
- Remapping ports / networking
- Adding scripts that must be run for certain functionality to continue working. Broadly speaking these are changes that will modify the way developers currently run / build the code. This does not include changes that introduce new alternative ways to run/build things. Adding dependencies with package managers does not count as a devex breaking change, unless it requires the user to do some very new thing that is not part of their normal development workflow, like manually installing software off of a website / App Store.
## Feature Leak Guidelines
The codebase might carefully gate features behind feature flags or internal-only checks. You MUST NOT allow any features that are meant to be behind a feature gate leak. These leaks are often subtle. Be VERY careful and thorough.
## Intended Breakage Guidelines
If you identify a high risk finding, but the intent of the branch is to introduce that finding – e.g. break some functionality, remove a feature flag, remove a safeguard – AND the scope of the change is well constrained, you SHOULD NOT waste the author's time by reporting the issue to them. However, if you believe it is likely that they are not aware of the full implications of their change, or you are worried that they are under-weighting the negative impacts (extreme example: a developer pushes a PR titled "Delete the database"), or you are worried that the change is actually malicious, you should still report the finding.
## Over-reporting Guidelines
If you report issues as High priority when they are not in fact high priority / meaningful issues, devs will lose trust in you and stop listening to you over time.
NEVER misreport the priority / importance of issues. Be extremely thorough in tracing issues end-to-end to gain complete, and total confidence before reporting.
# Final Response
IF you have medium-to-high priority / risk findings, and there is a PR for this branch, then check the PR/MR discussion using gh/glab cli to see if there are comments from BugBot or others present.
If so, take their findings into account. If they found issues you missed, evaluate them to determine if they are valid and include them in your report. If they found some of the same issues you did, see if there is anything from their findings that are worth incorporating into your response.
Flag issues found by BugBot or others in the PR/MR discussion that you include in your report.
# Critical Rules
- NEVER present issues with unfinished research. E.g. Never say something like, "The client has issue X, but if handled in the backend then this is ok." if you have access to the backend code and can check for yourself.
- You MUST wait to check the PR/MR discussion until AFTER you have performed your audit. This way you have fresh eyes while you review.
- Be EXTREMELY thorough, rigorous, careful, ambitious, and attentive. NOTHING can slip through.
@@ -0,0 +1,5 @@
interface:
display_name: "Security Audit Skill"
short_description: "Audit diffs for security and correctness risks"
policy:
allow_implicit_invocation: false
+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);
});
```
+74
View File
@@ -0,0 +1,74 @@
---
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. Use when the user wants a spec from the current conversation or an orchestration workflow needs to publish one from context."
---
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.
1. 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
+104
View File
@@ -0,0 +1,104 @@
---
name: to-tickets
description: "Break a plan, spec, or the current conversation into tracer-bullet tickets with blocking edges, published to the configured tracker. Use when the user wants tickets from a plan or spec, or an orchestration workflow needs agent-grabbable tickets."
---
# 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.

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