update skills

This commit is contained in:
nessar committed 2026-09-25 10:00:00 +02:00
1 parent 9fb18f57ec
commit ff86cf48b4
82 files changed
+2155 -649

No files matched your search

+15 -77
View File
@@ -1,90 +1,28 @@
--- ---
name: ask-matt name: ask-matt
description: Ask which skill or flow fits your situation. A router over the skills in this repo. description: Recommend the repository skill or workflow that best fits the user's situation.
disable-model-invocation: true
--- ---
# Ask Matt # Ask Matt
You don't remember every skill, so ask. Recommend the shortest useful route for the requested outcome. These are options, not a required pipeline. Reuse known decisions and existing configuration; do not start work, an interview, or publication merely because you recommended a skill.
A **flow** is a path through the skills. Most paths run along one **main flow**, and two **on-ramps** merge onto it. Everything else is standalone, or a vocabulary layer that runs underneath. ## Choose a route
## The main flow: idea → ship - A clear spec ready to build: `/implement`. For explicitly test-first work, `/tdd`; for a review only, `/code-review`.
- An idea with consequential open questions: `/grill-with-docs` for repo work, or `/grill-me` for a standalone discussion. Skip interviews whose answers are already known.
- A design question that needs a runnable example: `/prototype`. Return to the original discussion with the verdict; production implementation is a separate choice.
- A large plan needing durable acceptance criteria: `/to-spec`, then `/to-tickets` if decomposition helps. Drafting, filing, and implementing remain distinct requested outcomes.
- A genuinely uncertain multi-session effort: `/wayfinder` for decision tickets. A well-scoped feature does not need a planning map.
- A reported failure: `/diagnosing-bugs` for evidence and cause, plus repair only when requested.
- Incoming reports to classify: `/triage`. An explicitly chosen issue can be reviewed regardless of who created it.
The route most work travels. You have an idea and want it built. ## Focused alternatives
1. **`/grill-with-docs`** — sharpen the idea by interview. Start here whenever you are **working in a working directory**: it's stateful, retaining what it learns in `CONTEXT.md` and ADRs. (No working directory? Use `/grill-me` — see Standalone. Both run the same `/grilling` primitive; `grill-with-docs` is the one that leaves a paper trail, which makes it the better of the two whenever a repo is there to leave it in.) Use `/domain-modeling` for project terminology or ADRs, `/codebase-design` for module shape, and `/improve-codebase-architecture` for a requested architecture survey. `/research` gathers primary-source evidence; `/teach` explains or practices a topic; `/writing-great-skills` helps maintain skills.
2. **Branch — can you settle every question in conversation?** If a question needs a runnable answer (state, business logic, a UI you have to see), detour through a prototype, bridged by **`/handoff`** in both directions (a prototype lives in its own directory, which is exactly what `/handoff` is for — see Phase boundaries):
- **`/handoff`** out, then open a fresh session against that file,
- **`/prototype`** to answer the question with throwaway code,
- **`/handoff`** back what you learned, and reference it from the original idea thread.
3. **Branch — is this a multi-session build?**
- **Yes** → **`/to-spec`** (turn the thread into a spec), then **`/to-tickets`** to split it into tracer-bullet tickets, each declaring its **blocking edges**. On a local tracker that's one file per ticket under `.scratch/<feature>/issues/`, worked blockers-first by hand; on a real tracker the edges become native blocking links, so any ticket whose blockers are done can be grabbed — kick off **`/implement`** per ticket, **`/clear`ing context between each one**. Each ticket is self-contained, so the last one's context is disposable.
- **No** → **`/implement`** right here, in the same context window.
Either way, **`/implement`** builds each issue by driving **`/tdd`** internally — one red-green slice at a time — then closes out by running **`/code-review`**, a two-axis review (Standards + Spec) of the diff, before committing. Reach for **`/tdd`** on its own when you just want to build a concrete behaviour test-first without a full spec, and **`/code-review`** on its own whenever you want to review a branch or PR against a fixed point. Use `/handoff` when a fresh session or durable summary is useful. Do not mandate context resets, prevent normal compaction, or assume a universal token threshold.
### Context hygiene Read existing `docs/agents/` configuration when a workflow needs it. Recommend `/setup-matt-pocock-skills` only for missing or explicitly changed configuration, not before every engineering task.
Keep steps 1–3 in **one unbroken context window** — don't compact or clear until after `/to-tickets` — so the grilling, spec, and tickets all build on the same thinking. Each `/implement` then starts fresh, working from the ticket. Explain the recommended route briefly, including any prerequisite that actually matters. Honor the user's selected skill even when another route would also work.
The limit on this is the **[smart zone](https://www.aihero.dev/ai-coding-dictionary/smart-zone)**: the window (~150k tokens on state-of-the-art models) within which the model still reasons sharply. If a session approaches it before `/to-tickets`, don't push on degraded — `/compact` at the nearest phase boundary and carry on (see Phase boundaries).
## On-ramps
A starting situation that generates work, then merges onto the main flow.
- **Bugs and requests piling up** → **`/triage`**. It moves issues through triage roles and produces agent-ready issues, which **`/implement`** later picks up.
Triage is only for issues **you didn't create** — bug reports, incoming feature requests, anything that arrives raw. Tickets that `/to-tickets` produced are already agent-ready, so **don't triage them**.
- **Something's broken** → **`/diagnosing-bugs`**. For the hard ones: the bug that resists a first glance, the intermittent flake, the regression that crept in between two known-good states. It refuses to theorise until it has a **tight feedback loop** — one command that already goes red on *this* bug — then fixes with a regression test. Its post-mortem hands off to **`/improve-codebase-architecture`** when the real finding is that there's no good seam to lock the bug down.
- **A huge, foggy effort — a greenfield project or a huge feature build, too big for one session** → **`/wayfinder`**, the most cognitively demanding flow here. When the way from here to the destination isn't visible yet, it charts a **shared map** of **decision tickets** on the issue tracker and resolves them one at a time — producing **decisions, not deliverables** — until the fog is pushed back and the way is clear. Where **`/grill-with-docs`** sharpens an idea you can hold in one session, wayfinder is for the idea you can't — and it's slower and denser, so save it for exactly that, never a well-scoped feature.
When the map clears, **it hands off, it doesn't build**: merge onto the main flow at **`/to-spec`**, which collapses the map's linked decisions into a buildable plan, then `/to-tickets` and `/implement` as usual. Looping the map straight into `/implement` skips that collapse and throws the linked detail away — go straight to `/implement` only when the effort turned out genuinely small.
## Codebase health
Not feature work — upkeep.
- **`/improve-codebase-architecture`** — run whenever you have a spare moment to keep the codebase good for agents to operate in. It surfaces **deepening opportunities**; picking one _generates an idea_ you can take into the main flow at `/grill-with-docs`. It's the survey that finds the candidates; **`/codebase-design`** (below) is the bench you design the chosen one on.
## Vocabulary underneath
Two model-invoked references that run *beneath* the other skills — each the single source of truth for its vocabulary. Reach for them directly when the **words**, not the process, are the problem; or let the skills above pull them in.
- **`/domain-modeling`** — sharpen the project's *domain* language: challenge a fuzzy term, resolve an overloaded word ("account" doing three jobs), record a hard-to-reverse decision as an ADR. It's the active discipline `/grill-with-docs` drives to keep `CONTEXT.md` a clean glossary.
- **`/codebase-design`** — the deep-module vocabulary (module, interface, depth, seam, adapter, leverage, locality) for designing a module's *shape*: a lot of behaviour behind a small interface at a clean seam. `/tdd` and `/improve-codebase-architecture` both speak it.
## Phase boundaries
A **phase** is a chunk of work inside a session — the grilling, the implementation, the QA. At the **boundary** between two of them you have five options, and picking between them is the fuzziest decision in this whole map:
- **Continue** — stay put. Costs nothing, loses nothing.
- **`/clear`** — empty the window, when nothing here matters to what's next.
- **`/handoff`** — write a portable markdown file. Narrow: only for a **new harness**, a **new directory**, a **colleague**, or forking a side task **mid-phase**. What it buys is portability.
- **Subagent** — send a tightly-scoped task to its own window and get a report back.
- **`/compact`** — compress this context and seed a fresh session with it. The **default**, at the bottom of the tree rather than the first reach.
Read [PHASE-BOUNDARIES.md](PHASE-BOUNDARIES.md) for the ordered tree — the five questions, the reasoning behind each branch, and why the primary-source cost makes **Continue** the one to rule out first. Make the decision **at** a boundary; mid-phase, continue or split the rest into subagents.
## Standalone
Off the main flow entirely.
- **`/grill-me`** — the same relentless interview as `/grill-with-docs`, but **stateless**: it saves nothing locally and builds no `CONTEXT.md`. Reach for it when you are **not working in a working directory** — sharpening a plan, a design, a piece of writing, anything with no repo under it. If you are in a working directory, use `/grill-with-docs` instead: it runs the same interview and leaves a paper trail, so it is strictly the better one.
- **`/grilling`** — the interview primitive itself: rounds, the frontier, facts are the agent's job and decisions are yours. `/grill-me` and `/grill-with-docs` are the two named ways in, and `/triage`, `/wayfinder` and `/improve-codebase-architecture` all run it internally. Reach for it directly only when you want the interview with no wrapper around it.
- **`/resolving-merge-conflicts`** — work an in-progress merge or rebase conflict hunk by hunk, resolving by **intent** traced to each side's primary source rather than by picking lines, then finish the operation. It never runs `--abort`. Standalone and off every flow: reach for it when you are already mid-conflict.
- **`/prototype`** — a small, throwaway program that answers one design question: does this state model feel right, or what should this UI look like. Throwaway is a constraint on how the code is written, not a promise to destroy it: the answer folds into the real code, and the prototype itself is kept as a **primary source** on a `prototype/<name>` branch out of main, pointed at from the implementation issue. It's the detour in step 2 of the main flow, but reach for it any time a design question is hard to settle on paper.
- **`/research`** — delegate reading legwork to a **background agent**: it investigates a question against **primary sources**, then leaves a cited Markdown file in the repo. Keep working while it reads. The file it produces is something to take *into* the main flow at `/grill-with-docs` — research feeds the thinking, it doesn't replace it.
- **`/to-questionnaire`** — when the thing blocking you isn't in your head or the codebase but in **someone else's**, this writes them a questionnaire to fill in. It's the inverse of `/grill-me`: instead of interviewing you about the subject, it interviews you about the **send** — who it's going to, what you need back — and aims the questions at the gap. What comes back is material for `/grill-with-docs` or `/to-spec`.
- **`/wizard`** — for the steps only a **human** can take: provisioning infrastructure, setting up credentials or CI secrets, clicking through an unfamiliar third-party dashboard, running a one-off migration or cutover. It generates an interactive bash script that opens each URL, captures each value, and writes it into `.env` and GitHub secrets — so the procedure stops being something you re-explain to an agent every time. Model-invoked, so the agent reaches for it the moment it hits a wall only you can pass. If the agent could just do it itself, it should; this is for where a human is genuinely in the loop.
- **`/wait-what`** — the corrective for a message that didn't land. Use it mid-conversation, inside any other skill, and the agent re-pitches what it just said with the context you were missing, in plain English, using the `CONTEXT.md` vocabulary. It works after the fact; `/grill-with-docs` is the upfront cure, because a shared language agreed early is what stops the jargon arriving at all.
- **`/teach`** — learn a concept over multiple sessions, using the current directory as a stateful workspace.
- **`/writing-for-agents`** — reference for writing documents agents consume: skills, AGENTS.md, pointed-at docs.
## Precondition
**`/setup-matt-pocock-skills`** — run before your first engineering flow to configure the issue tracker, triage labels, and doc layout the other skills assume. Custom issue trackers also work.
+18
View File
@@ -0,0 +1,18 @@
---
name: claude-handoff
description: Hand the current conversation off to a background Claude Code session when the user chooses Claude for continuation.
---
Check `command -v claude` and the installed CLI's help for background-session support before launching. If unavailable, return the redacted handoff and explain the missing prerequisite; do not install software or switch agent products without the user's request.
Write a handoff summary so a fresh Claude session can continue the work. When supported by the installed CLI, launch it with `claude --bg --name "<descriptive name>" "<handoff summary>"` in the selected working directory. Use the CLI's reported session identifier and management commands; do not claim a session started if the command failed. Do not retry an ambiguous launch until checking whether it already created a session.
Always pass `-n`/`--name` with a descriptive name (e.g. `--name "Fix login bug"`) — it sets the display name shown in the job list, session picker, and terminal title.
Include a "suggested skills" section in the summary, which suggests skills that the agent should invoke.
Do not duplicate content already captured in other artifacts (PRDs, plans, ADRs, issues, commits, diffs). Reference them by path or URL instead.
Redact any sensitive information, such as API keys, passwords, or personally identifiable information — the summary becomes the agent's prompt.
If the user passed arguments, treat them as a description of what the next session will focus on and tailor the summary accordingly.
@@ -0,0 +1,5 @@
interface:
display_name: "Claude Handoff"
short_description: "Hand off to a background agent"
policy:
allow_implicit_invocation: false
+25 -15
View File
@@ -1,35 +1,43 @@
--- ---
name: code-review 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". 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/PRD 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: Two-axis review of the changes the user selected, including working changes when requested:
- **Standards** — does the code conform to this repo's documented coding standards? - **Standards** — does the code conform to this repo's documented coding standards?
- **Spec** — does the code faithfully implement the originating issue / spec? - **Spec** — does the code faithfully implement the originating issue / PRD / spec?
Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings. Use independent **parallel sub-agents** when available, then aggregate their findings. If delegation is unavailable, review both axes directly and disclose the limitation.
The issue tracker should have been provided to you — run `/setup-matt-pocock-skills` if `docs/agents/issue-tracker.md` is missing. Use `docs/agents/issue-tracker.md` for remote specs. A missing tracker configuration does not block reviewing local changes or a supplied spec.
## Process ## Process
### 1. Pin the fixed point ### 1. Pin the requested scope
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. Honor the user's baseline and file scope. For a pre-commit review, use the implementation's recorded starting commit and task-owned paths; for an ordinary review of uncommitted work, default to `HEAD`. Ask only when an unresolved baseline or scope choice would materially change the review.
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`. Resolve the baseline to a commit with `git rev-parse --verify '<ref>^{commit}'`. For a branch/PR review, use its merge-base when the request is for changes introduced on that branch; for an explicit commit-to-commit comparison, use the supplied commit directly.
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. Choose and record commands appropriate to the selected scope, adding `-- <task-paths>` where needed:
| Scope | Tracked changes | New files |
| --- | --- | --- |
| Committed only | `git diff <base> HEAD` | Included if committed |
| Current working result, including staged and unstaged | `git diff <base>` | List with `git ls-files --others --exclude-standard` and read each in-scope file |
| Staged only | `git diff --cached <base>` | Included if staged |
Inspect `git status --short` and distinguish pre-existing user changes from task changes. When ownership overlaps, obtain the task's actual patch or state the limitation; do not attribute the entire dirty checkout to the implementation. Record relevant commits with `git log <base>..HEAD --oneline`. An empty tracked diff is not an empty review until in-scope new files are checked. Report genuinely empty scope directly; resolve invalid refs before dispatch.
### 2. Identify the spec source ### 2. Identify the spec source
Look for the originating spec, in this order: Look for the originating spec, in this order:
1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.) — fetch via the workflow in `docs/agents/issue-tracker.md`. 1. The user's explicit spec, ticket, path, or acceptance criteria in the conversation. Preserve it as authoritative even when commits reference other work.
2. A path the user passed as an argument. 2. Issue/MR references in relevant commit messages — fetch via `docs/agents/issue-tracker.md` when no explicit source was supplied.
3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature. 3. A PRD/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". 4. If nothing is found or the source is inaccessible, continue the Standards review and report the Spec coverage limitation. Ask for a source only when needed to answer the user's request; do not invent requirements or require tracker setup.
### 3. Identify the standards sources ### 3. Identify the standards sources
@@ -57,15 +65,17 @@ Each smell reads *what it is* → *how to fix*; match it against the diff:
### 4. Spawn both sub-agents in parallel ### 4. Spawn both sub-agents in parallel
Use the environment's available delegation tool; do not depend on a product-specific `Agent` or `Task` name. Give each reviewer the same resolved baseline, tracked diff commands, in-scope new-file list, task ownership boundaries, and current snapshot. Review-only agents must not modify files or external state.
**Standards sub-agent prompt** — include: **Standards sub-agent prompt** — include:
- The full diff command and commit list. - The full diff commands, new-file contents or paths, scope, 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 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." - 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** — include: **Spec sub-agent prompt** — include:
- The diff command and commit list. - The same diff commands, new files, scope, and commit list as the Standards reviewer.
- The path or fetched contents of the spec. - 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." - 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."
+5 -5
View File
@@ -8,7 +8,7 @@ When assessing a candidate for deepening, classify its dependencies. The categor
### 1. In-process ### 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. Pure computation, in-memory state, no I/O. Merge only when it concentrates a cohesive responsibility and reduces caller complexity. Test through the resulting behavior-level interface; no adapter is needed for pure computation.
### 2. Local-substitutable ### 2. Local-substitutable
@@ -26,12 +26,12 @@ Third-party services (Stripe, Twilio, etc.) you don't control. The deepened modu
## Seam discipline ## 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. - **Justify a seam by its current benefit.** Test isolation, ownership, real variability, or an external contract can justify it; adapter count alone cannot. Do not manufacture a second implementation or an unused port.
- **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. - **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 ## Testing strategy: preserve behavioral coverage
- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them. - Before deleting old tests, map their success, failure, and edge-case coverage to the replacement checks. Delete only redundant or obsolete tests after confirming equivalent meaningful coverage; keep tests that catch distinct failures.
- Write new tests at the deepened module's interface. The **interface is the test surface**. - 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 assert on observable outcomes through the interface, not internal state.
- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. - Prefer tests that survive behavior-preserving refactors. A test change is a signal to review coupling, not proof that the test is worthless; integration, algorithm, and concurrency checks may protect distinct contracts.
@@ -18,14 +18,13 @@ Show this to the user, then immediately proceed to Step 2. The user reads and th
### 2. Spawn sub-agents ### 2. Spawn sub-agents
Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module. Honor the requested number of alternatives; two is a useful default. Use independent subagents through the available delegation tool when useful and within available slots, or compare directly when delegation is unavailable. Each option should explore a meaningfully different trade-off for the same requirements.
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: 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." - One option can optimize for the primary caller's workflow.
- Agent 2: "Maximise flexibility — support many use cases and extension." - Another can emphasize explicit state transitions or failure handling.
- Agent 3: "Optimise for the most common caller — make the default case trivial." - Add a dependency-focused option only when that is an actual design question; do not invent flexibility, adapters, or a target method count.
- 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. 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.
@@ -39,6 +38,6 @@ Each sub-agent outputs:
### 3. Present and compare ### 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**. Use the requested or clearest concise format. Contrast **depth** (leverage at the interface), **locality** (where change concentrates), **seam placement**, implementation effort, and risk.
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. 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.
+8 -8
View File
@@ -9,17 +9,17 @@ Design **deep modules**: a lot of behaviour behind a small interface, placed at
## Glossary ## Glossary
Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. Use these concepts to explain the design, while preserving the repository's actual names and domain vocabulary. A component, service, or API can be the module or interface under discussion; explain the distinction when it matters instead of banning familiar terms.
**Module** — anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. **Module** — anything with an interface and an implementation: a function, component, service, class, package, or tier-spanning slice.
**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). **Interface** — everything a caller must know: signatures, invariants, ordering, errors, configuration, and relevant performance characteristics. An API signature alone may describe only part of that contract.
**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. **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. **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). **Seam** _(Michael Feathers)_ — a place where behavior can be varied without editing that place. Distinguish a test or substitution seam from a domain or deployment boundary when the difference affects the design.
**Adapter** — a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). **Adapter** — a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).
@@ -61,8 +61,8 @@ When designing an interface, ask:
- **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. - **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 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. - **Prefer behavior-level test surfaces.** Test through the relevant contract, while retaining focused checks for internal algorithms or integration invariants when they catch failures the higher interface does not.
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. - **Justify seams by a current need.** Test isolation, ownership, external integration, or real variation may justify a boundary even with one runtime implementation. Do not add an adapter merely to satisfy a count, or a speculative abstraction with no concrete benefit.
## Designing for testability ## Designing for testability
@@ -80,7 +80,7 @@ Good interfaces make testing natural:
} }
``` ```
2. **Return results, don't produce side effects.** 2. **Prefer pure results for calculations; keep necessary effects explicit.**
```typescript ```typescript
// Testable // Testable
@@ -106,7 +106,7 @@ Good interfaces make testing natural:
- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. - **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. - **"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**. - **Unqualified boundaries**: clarify whether a boundary concerns tests, domain ownership, deployment, or caller contracts when that distinction matters.
## Going deeper ## Going deeper
@@ -0,0 +1,94 @@
---
name: design-an-interface
description: Generate multiple radically different interface designs for a module using parallel sub-agents. Use when user wants to design an API, explore interface options, compare module shapes, or mentions "design it twice".
---
# Design an Interface
Based on "Design It Twice" from "A Philosophy of Software Design": your first idea is unlikely to be the best. Generate multiple radically different designs, then compare.
## Workflow
### 1. Gather Requirements
Before designing, understand:
- [ ] What problem does this module solve?
- [ ] Who are the callers? (other modules, external users, tests)
- [ ] What are the key operations?
- [ ] Any constraints? (performance, compatibility, existing patterns)
- [ ] What should be hidden inside vs exposed?
Infer these from the request and existing callers; ask only about missing requirements that materially affect the designs.
### 2. Generate Designs (Parallel Sub-Agents)
Compare meaningfully different approaches, honoring the requested count. Two is a useful default for "design it twice"; add options only when they explore a relevant trade-off. Use independent subagents through the available delegation tool when useful and within available slots; otherwise develop the alternatives directly.
```
Prompt template for each sub-agent:
Design an interface for: [module description]
Requirements: [gathered requirements]
Constraints for this design: [assign a different constraint to each agent]
- Option A: "Optimize for the primary caller's workflow"
- Option B: "Expose explicit state transitions for the same requirements"
Choose constraints relevant to the actual problem; do not invent future use cases or a target method count.
Output format:
1. Interface signature (types/methods)
2. Usage example (how caller uses it)
3. What this design hides internally
4. Trade-offs of this approach
```
### 3. Present Designs
Show each design with:
1. **Interface signature** - types, methods, params
2. **Usage examples** - how callers actually use it in practice
3. **What it hides** - complexity kept internal
Present designs sequentially so user can absorb each approach before comparison.
### 4. Compare Designs
After showing all designs, compare them on:
- **Interface simplicity**: fewer methods, simpler params
- **General-purpose vs specialized**: flexibility vs focus
- **Implementation efficiency**: does shape allow efficient internals?
- **Depth**: small interface hiding significant complexity (good) vs large interface with thin implementation (bad)
- **Ease of correct use** vs **ease of misuse**
Use the requested format or the clearest concise comparison. Highlight where designs diverge most.
### 5. Synthesize
Recommend the best fit with reasons. If the user wants to choose interactively, ask:
- "Which design best fits your primary use case?"
- "Any elements from other designs worth incorporating?"
## Evaluation Criteria
From "A Philosophy of Software Design":
**Interface simplicity**: Fewer methods, simpler params = easier to learn and use correctly.
**Scope fit**: Covers known callers and requirements without speculative flexibility.
**Implementation efficiency**: Does interface shape allow efficient implementation? Or force awkward internals?
**Depth**: Small interface hiding significant complexity = deep module (good). Large interface with thin implementation = shallow module (avoid).
## Anti-Patterns
- Don't let sub-agents produce similar designs - enforce radical difference
- Don't skip comparison - the value is in contrast
- Don't implement - this is purely about interface shape
- Include implementation effort and migration risk in the trade-offs without letting them obscure correctness or usability.
@@ -0,0 +1,3 @@
interface:
display_name: "Design an Interface"
short_description: "Explore alternative module interfaces"
+18 -118
View File
@@ -1,140 +1,40 @@
--- ---
name: diagnosing-bugs 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. description: Investigate bugs and performance regressions to explain their cause with evidence. Use for diagnosis or debugging; implement repairs only when fixing is also requested.
--- ---
# Diagnosing Bugs # Diagnosing Bugs
A discipline for hard bugs. Skip phases only when explicitly justified. Read the relevant flow, existing tests, `CONTEXT.md`, and applicable ADRs. Establish the requested outcome: diagnosis ends with a cause and evidence; an authorized fix also includes repair and regression checks. Keep all investigation within permitted systems and preserve unrelated work.
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. ## Find a useful signal
## Redact Start from the reported symptom and what is already known. Read code, logs, and recent changes to form hypotheses; do not require a running reproduction before inspecting the code.
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. Prefer the smallest reliable reproduction: an existing failing test, a scoped command with dummy input, a local request, or a browser check. Choose a harness only if existing checks cannot reach the failure. When a human must perform the trigger, adapt [the HITL loop template](scripts/hitl-loop.template.sh); do not run it unattended.
If the redacted output is not enough to diagnose the bug, say so and ask the user. Capture the exact error, wrong result, or measured regression. Distinguish the reported bug from nearby failures. Minimize inputs when it helps separate causes; perfect minimization and second-long execution are not prerequisites.
## Phase 1 — Build a feedback loop For intermittent bugs, record attempts, failures, and environmental conditions. Use bounded stress or repeated runs when safe; do not overload shared systems. A low reproduction rate is evidence, not a reason to abandon inspection.
**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. If execution is unavailable, continue safe code/trace analysis, distinguish a probable cause from a confirmed one, and state what would confirm it. Request only the missing artifact or access that materially limits progress. Production instrumentation requires explicit authority.
Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.** ## Test explanations
### Ways to construct one — try them in roughly this order Rank plausible hypotheses by evidence and state a prediction for each. One well-supported explanation may be enough; compare alternatives when uncertainty warrants it.
1. **Failing test** at whatever seam reaches the bug — unit, integration, e2e. Use targeted inspection or probes to distinguish predictions. Change one relevant variable at a time where practical. Tag temporary instrumentation with a task-unique prefix, avoid sensitive payloads, and keep track of exactly what you added.
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) — drives the UI, 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. For performance, measure the same workload against a baseline before proposing an optimization; account for warmup and noise. Use profiling, query plans, or bisection when they help isolate the cause. Keep bisection out of a shared dirty worktree.
### Tighten the loop ## Repair only when requested
Treat the loop as a product. Once you have _a_ loop, **tighten** it: For an authorized fix, turn the reproduction into a regression check before the repair where feasible. Exercise the real failing caller pattern: a single-caller unit test cannot prove a multi-caller race is fixed.
- Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.) Apply the smallest root-cause correction, rerun the original scenario, then relevant surrounding tests. If no reliable check is available, state the resulting verification gap rather than claiming success from an unrelated green test.
- 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. ## Hand off
### Non-deterministic bugs Remove only your own temporary probes and disposable artifacts. Report the cause, supporting evidence, checks run, and remaining uncertainty. For a fix, also report the changed behavior and regression result.
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 — keep raising the rate until it's debuggable. Mention a broader architecture issue only when the evidence supports it; do not launch another audit or refactor unless requested or necessary for the authorized repair.
### 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 — 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 — 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 + post-mortem
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
**Then ask: what would have prevented this bug?** If the answer involves architectural change (no good test seam, tangled callers, hidden coupling) hand off to the `/improve-codebase-architecture` skill with the specifics. Make the recommendation **after** the fix is in, not before — you have more information now than when you started.
@@ -11,9 +11,6 @@
# capture VAR "<question>" → show question, read response into VAR # capture VAR "<question>" → show question, read response into VAR
# #
# At the end, captured values are printed as KEY=VALUE for the agent to parse. # 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 set -euo pipefail
@@ -0,0 +1,35 @@
---
name: domain-driven-design
description: Model business rules and consistency boundaries using domain-driven design. Use when choosing aggregates or bounded contexts, mapping domain relationships, or correcting a mismatch between business language and code.
license: MIT
metadata:
author: wondelai
version: "1.4.0"
---
# Domain-Driven Design
Model the requested business behavior, not an idealized architecture. Start with the user's scenarios, existing code, root `CONTEXT.md`, and relevant accepted ADRs.
## Shared constraints
- Preserve the repository's language and existing architectural decisions. Surface conflicts with evidence rather than silently replacing them.
- Follow [the development data lifecycle](../../../AGENTS.md#development-data-lifecycle): replace obsolete development schemas/contracts and update callers and tests together. Compatibility patterns apply only to genuine external constraints or a later explicit production-data decision.
- Choose aggregate boundaries from invariants and ownership. Preserve [the accepted rental transaction design](../../../docs/adr/0011-rental-aggregate-boundaries.md), including atomic operations across aggregate documents.
- Add events, factories, translation layers, or separate contexts only for a current business or integration need. Simple CRUD is valid; a score or wider architecture audit is optional, not a completion gate.
- Honor the requested deliverable: a design or review does not itself authorize implementation, migrations, or external changes.
## Use the relevant reference
Read only the branch needed by the task:
- Resolving ambiguous terms or maintaining a glossary: [ubiquitous language](references/ubiquitous-language.md).
- Choosing context boundaries or mapping integrations: [bounded contexts](references/bounded-contexts.md).
- Deciding identity, value semantics, aggregate ownership, or atomicity: [building blocks](references/building-blocks.md).
- Designing a real event flow or evaluating event sourcing: [domain events](references/domain-events.md).
- Defining persistence contracts, reconstruction, or complex creation: [repositories and factories](references/repositories-factories.md).
- Prioritizing modeling effort or comparing build/buy choices: [strategic design](references/strategic-design.md).
## Outcome
Explain the proposed concepts, invariant owners, important transitions, and how the design handles failure and concurrency. Show only the alternatives that matter, identify unresolved domain questions, and propose checks that would falsify the design. When implementation is requested, update affected callers, tests, and domain documentation together.
@@ -0,0 +1,32 @@
# Bounded Contexts and Context Mapping
A bounded context defines where a domain model and its language apply. It is not automatically a microservice, package, or team-sized deployment.
## Find a real boundary
Look for differing business meanings, rules, ownership, or change lifecycles. Check concrete scenarios and existing ADRs. A single context may be correct; excessive translation between closely related concepts can signal an unnecessary split.
For a requested context map, show the relevant contexts, ownership, upstream/downstream relationships, shared contracts, and any translation. Avoid mapping unrelated systems just to complete a catalog.
## Choose the relationship
| Pattern | Useful when | Cost to make explicit |
| -------------------------------------- | ------------------------------------------------------------------ | -------------------------------------------------- |
| Shared kernel | Closely collaborating owners genuinely share a small model | Coordinated changes and tests |
| Customer–supplier | The upstream team can accommodate downstream needs | Planning and contract dependency |
| Conformist | Accepting the upstream model is cheaper and safe for this use case | Coupling to upstream semantics |
| Anti-corruption layer | Foreign semantics would distort local business rules | Translation and its tests |
| Open host service / published language | Several consumers need a documented shared contract | Contract ownership and actual external obligations |
| Separate ways | Integration costs more than limited duplication | Separate implementations and knowledge |
| Partnership | Models must evolve together | Ongoing coordination |
| Big ball of mud | Existing entanglement needs to be named during an assessment | A diagnosis, not a target design |
Translation can live in an existing adapter or mapper; it does not require a facade/adapter/translator class hierarchy. Validate untrusted external data even when adopting the upstream model directly.
## Changes and external constraints
Preserve actual external contracts that the task cannot replace. Legacy coexistence patterns apply to a genuinely external system that must remain available, not to this application's disposable development model.
For internal model changes, follow [the development lifecycle](../../../../AGENTS.md#development-data-lifecycle): replace obsolete schemas/contracts, update callers and tests together, and reseed rather than introducing compatibility paths.
Explain a proposed split or merge through its effect on language, invariant ownership, coupling, and coordination. Do not reorganize teams, deploy services, or modify contracts merely because a map was requested.
@@ -0,0 +1,35 @@
# Entities, Value Objects, and Aggregates
Start from identity and business invariants rather than database tables or a target class count.
## Identity and value
An entity retains identity through changes; a value object is interchangeable with another value having the same attributes. Choose equality and mutability accordingly. Use existing identifier conventions rather than adding a new ID scheme by default.
Value objects should enforce their actual invariants and support immutable transformations. Do not infer business rules from examples: negative money may be valid for one concept and invalid for another.
## Aggregate ownership
An aggregate owns a cohesive set of state and invariants, with a root controlling its changes. Keep it small enough to load and update for its real use cases; use references by ID for independent aggregates where the project's model calls for them.
Ask:
- Which rules must hold after every successful operation?
- Who owns each lifecycle and may change its state?
- Which state must be read and written together?
- What prevents two concurrent commands from both accepting incompatible outcomes?
- Can a partial result or delayed update be valid?
Do not embed a growing independent lifecycle merely to make all relationships reachable through one object.
## Atomicity and concurrency
Aggregate boundaries and transaction boundaries are related, not identical. When an operation must commit or roll back across multiple aggregate documents, use the supported service-layer transaction required by the domain.
In this repository, [ADR-0011](../../../../docs/adr/0011-rental-aggregate-boundaries.md) explicitly requires Mongo transactions for relevant rental operations. Preserve optimistic version checks, occupancy contention, and uniqueness constraints; replacing them with asynchronous events or a query-only overlap check would weaken the invariant.
Use eventual consistency only when delayed or partial progress is acceptable, with explicit failure and recovery handling. Keep remote calls and long-running work outside database transactions.
## Verify the boundary
Exercise the actual operation, including invalid transitions, stale versions, duplicate commands, and competing callers where relevant. Prove the invariant at the storage/integration boundary when an in-memory test cannot establish it. Preserve distinct existing test coverage when moving behavior behind a new interface.
@@ -0,0 +1,29 @@
# Domain Events
Use events for a real notification or asynchronous coordination need. Crossing an aggregate boundary alone is not a reason to introduce an event bus.
## Define the fact and consumers
Name a domain event as a completed business fact, distinct from a command or pending operation. Identify its actual consumers and the minimum non-sensitive data they need. Avoid serializing the entire aggregate or inventing metadata fields without a purpose.
Distinguish internal events from externally consumed contracts. Translate when semantics differ; do not introduce a separate layer merely to change the name.
## Persistence and delivery
An event must not claim a state change that rolled back. If delivery after commit must be durable, use the project's existing transactional publication mechanism or justify an outbox that records the state change and pending event atomically.
For retried delivery, make handlers idempotent using an appropriate key, conditional write, or naturally idempotent operation. Coordinate deduplication and the effect atomically where required; recording a key before a failed effect can lose work.
Define ordering requirements, retry limits, and observable failure handling. Test duplicate, delayed, out-of-order, and failing delivery where those modes affect the invariant. Do not claim exactly-once behavior merely because duplicate messages are filtered.
## Do not weaken atomic business operations
Preserve the cross-aggregate transactions accepted in [ADR-0011](../../../../docs/adr/0011-rental-aggregate-boundaries.md). Asynchronous coordination is suitable only when partial progress and delay are valid. A saga or process manager is justified only by an actual long-running workflow, with explicit recovery semantics.
## Event sourcing is a separate choice
Event sourcing makes stored events the source of truth; publishing an event does not require it. Consider it only for a demonstrated need for historical reconstruction or temporal queries that the existing model cannot reasonably serve.
If chosen, define replay behavior without repeating external side effects, concurrency protection, and the actual retention obligations. Snapshots are an optimization, not initial scaffolding.
Follow [the development lifecycle](../../../../AGENTS.md#development-data-lifecycle): replace and reseed disposable development events. Retained-history upcasters or compatibility versions require an explicit later production-data decision; genuine external event contracts remain external constraints.
@@ -0,0 +1,25 @@
# Repositories and Factories
Use this branch when the task concerns persistence contracts or complex object creation, not as a checklist of layers to add.
## Repository contracts
Keep domain decisions separate from storage mechanics. Define methods in terms of actual domain operations and queries, following the repository's existing architecture. Avoid generic query escape hatches that leak SQL or document details into domain behavior.
Aggregate-loading methods return enough valid state for the operation to enforce its invariants. Query-only methods may return explicit read projections; this does not require a new CQRS subsystem. Fetch only needed data and test relevant storage, transaction, and concurrency behavior.
Follow the persistence technology's actual save/change-tracking semantics. Make absence, failed writes, and stale versions explicit in the contract.
## Reconstruction versus creation
Creating a new aggregate validates command inputs and invariants and may record creation events. Loading an existing aggregate preserves its identity and must not replay creation events or other external effects.
Validate the persisted shape and invariants needed for safe use rather than assuming stored data is trustworthy. Report corrupt or incompatible records; apply the project's disposable-data policy instead of adding legacy readers.
## Factories and query specifications
Use a constructor or existing mapper for straightforward creation. A factory earns its place when assembly or selection logic is sufficiently complex, duplicated, or independently testable; it must not produce an invalid aggregate.
Use query specifications only when actual reusable composition warrants them. A focused repository method is often enough.
Keep dependencies aligned with existing domain/application/infrastructure ownership. An in-memory test adapter can isolate domain logic, but does not replace integration checks for database behavior.
@@ -0,0 +1,23 @@
# Strategic Design
Use this branch when the user asks where to invest modeling effort or whether to build, reuse, or buy a capability.
## Classify by the actual business
- **Core:** the behavior that provides the product's distinctive value.
- **Supporting:** business-specific functionality needed to deliver that value.
- **Generic:** a broadly shared problem where existing solutions may fit.
These are decision aids, not fixed quality tiers or staffing rules. Security, accessibility, and data integrity remain required in every category. A domain's classification can change as the product changes.
## Compare concrete options
Start with the existing implementation and stack. Compare options against needed behavior, integration cost, operational burden, lock-in, privacy/security constraints, and available expertise.
Do not prescribe a vendor, dependency, outsourcing arrangement, or percentage allocation from a generic example. Verify current primary sources before making a real product recommendation and preserve the user's selected product unless changing it is in scope.
## Distill the decision
Identify the concepts and invariants that deserve the most attention, the surrounding functionality that can stay simple, and the evidence supporting that choice. Update existing domain documents only when requested; propose an ADR for a consequential, non-obvious trade-off rather than creating a parallel architecture handbook.
End with a focused recommendation and its limitations. A strategy discussion does not authorize purchasing services, provisioning infrastructure, or reorganizing the codebase.
@@ -0,0 +1,22 @@
# Ubiquitous Language
Use this branch to resolve a terminology problem, not to rename every technical class. Read [the configured domain layout](../../../../docs/agents/domain.md) and the existing glossary before proposing terms.
## Resolve the meaning
Take a concrete business scenario and identify its actors, nouns, actions, and state transitions. Compare the user's explanation with the code and accepted decisions.
- One term with different meanings: identify the actual distinction and its context.
- Several terms for the same concept: propose one canonical term and record relevant aliases.
- A lifecycle difference: decide whether it represents a state of one identity or a distinct concept.
- An unfamiliar name: check domain usage before assuming the model is wrong.
Ask for domain clarification only where the evidence does not settle a consequential choice. Do not invent an expert's agreement.
## Record and apply
Update root `CONTEXT.md` in its existing format when glossary maintenance is requested. Keep definitions concise, show important relationships, and distinguish agreed language from proposals. Technical names such as service or DTO may remain appropriate outside the domain glossary.
A terminology discussion does not automatically authorize a code-wide rename. For an authorized rename, find all affected code, tests, schemas, contracts, and documents; replace them together under the development lifecycle policy. Do not introduce migration or API-version compatibility for disposable development data.
Different contexts may legitimately use different meanings. Do not split a coherent context merely because a word is ambiguous; first determine whether the underlying rules or ownership actually differ.
+14
View File
@@ -0,0 +1,14 @@
---
name: edit-article
description: Edit and improve articles by restructuring sections, improving clarity, and tightening prose. Use when user wants to edit, revise, or improve an article draft.
---
1. First, divide the article into sections based on its headings. Think about the main points you want to make during those sections.
Consider that information is a directed acyclic graph, and that pieces of information can depend on other pieces of information. Make sure that the order of the sections and their contents respects these dependencies.
Preserve the requested structure and voice. Confirm restructuring only if it would materially change the requested edit or an explicitly interactive workflow calls for it.
2. For each section:
2a. Rewrite the section to improve clarity, coherence, and flow. Let paragraph length follow the content, audience, and requested format; do not impose an arbitrary character cap.
@@ -0,0 +1,5 @@
interface:
display_name: "Edit Article"
short_description: "Restructure and tighten a draft"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,103 @@
---
name: git-guardrails-claude-code
description: Set up Claude Code hooks to block dangerous git commands (push, reset --hard, clean, branch -D, etc.) before they execute. Use when user wants to prevent destructive git operations, add git safety hooks, or block git push/reset in Claude Code.
---
# Setup Git Guardrails
Sets up a PreToolUse hook that inspects direct Git commands before Claude executes them. It requires Bash and Python 3; missing Python or invalid input blocks the command with exit code 2.
## What Gets Blocked
- Direct `git push` commands, including force flags, ordinary global options, and shell command separators
- `git reset --hard`
- `git clean -f` / `git clean -fd`
- `git branch -D`
- `git checkout .` / `git restore .`
When blocked, Claude sees a message telling it that it does not have authority to access these commands.
This is a conservative command guard, not a shell sandbox. It does not evaluate aliases, shell expansion, or commands hidden in scripts. Unsupported Git global options require manual inspection, and literal Git tokens in arguments can also be blocked. Keep execution permissions enforced by the host.
## Steps
### 1. Ask scope
Ask the user: install for **this project only** (`.claude/settings.json`) or **all projects** (`~/.claude/settings.json`)?
### 2. Copy the hook script
The bundled script is at: [scripts/block-dangerous-git.sh](scripts/block-dangerous-git.sh)
Copy it to the target location based on scope:
- **Project**: `.claude/hooks/block-dangerous-git.sh`
- **Global**: `~/.claude/hooks/block-dangerous-git.sh`
Make it executable with `chmod +x`.
### 3. Add hook to settings
Add to the appropriate settings file:
**Project** (`.claude/settings.json`):
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-dangerous-git.sh"
}
]
}
]
}
}
```
**Global** (`~/.claude/settings.json`):
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/block-dangerous-git.sh"
}
]
}
]
}
}
```
If the settings file already exists, merge the hook into existing `hooks.PreToolUse` array — don't overwrite other settings.
### 4. Ask about customization
Ask if user wants to add or remove any patterns from the blocked list. Edit the copied script accordingly.
### 5. Verify
Run the bundled checks; every command is an inert input string:
```bash
python3 scripts/test_guardrail.py
```
Then test the installed copy:
```bash
echo '{"tool_input":{"command":"git push origin main"}}' | <path-to-script>
```
Should exit with code 2 and print a BLOCKED message to stderr.
@@ -0,0 +1,3 @@
interface:
display_name: "Git Guardrails for Claude Code"
short_description: "Block dangerous git commands"
@@ -0,0 +1,64 @@
#!/bin/bash
if ! command -v python3 >/dev/null 2>&1; then
printf '%s\n' 'BLOCKED: Python 3 is required to inspect this command.' >&2
exit 2
fi
exec python3 -c '
import itertools
import json
import shlex
import sys
def block(reason):
print("BLOCKED: " + reason, file=sys.stderr)
sys.exit(2)
try:
command = json.load(sys.stdin)["tool_input"]["command"]
if not isinstance(command, str) or not command.strip():
raise ValueError("missing command")
lexer = shlex.shlex(command.replace("\\\n", ""), posix=True, punctuation_chars=";&|()\n")
lexer.whitespace = " \t\r"
lexer.whitespace_split = True
tokens = list(lexer)
except (ValueError, KeyError, TypeError):
block("Cannot parse the command input.")
value_options = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"}
flag_options = {"-p", "--paginate", "-P", "--no-pager", "--bare", "--literal-pathspecs"}
# ponytail: conservative token inspection; shell expansion and aliases require sandbox enforcement.
for separator, group in itertools.groupby(tokens, lambda token: bool(token) and token[0] in ";&|()\n"):
if separator:
continue
words = list(group)
for index, word in enumerate(words):
if word.rsplit("/", 1)[-1] != "git":
continue
args = words[index + 1:]
while args and args[0].startswith("-"):
option = args.pop(0)
if option in value_options:
if not args:
block("Missing Git option value.")
args.pop(0)
elif option in flag_options or option.split("=", 1)[0] in value_options:
continue
else:
block("Unsupported Git option; inspect this command manually.")
if not args:
continue
operation, *args = args
short_flags = "".join(arg[1:] for arg in args if arg.startswith("-") and not arg.startswith("--"))
force = "--force" in args or "f" in short_flags
dangerous = (
operation == "push"
or operation == "reset" and "--hard" in args
or operation == "clean" and force
or operation == "branch" and ("D" in short_flags or force and ("d" in short_flags or "--delete" in args))
or operation in {"checkout", "restore"} and "." in args
)
if dangerous:
block("Git " + operation + " is disabled by this hook.")
'
@@ -0,0 +1,61 @@
"""Run with python3; command payloads are inspected, never executed."""
import json
import os
from pathlib import Path
import subprocess
hook = Path(__file__).with_name("block-dangerous-git.sh")
def check(payload, expected, env=None):
result = subprocess.run(
["/bin/bash", str(hook)], input=payload, text=True, capture_output=True, env=env
)
assert result.returncode == expected, (payload, result.returncode, result.stderr)
if expected == 2:
assert result.stderr.startswith("BLOCKED:"), result.stderr
for command in (
"git push origin main",
"git push --force-with-lease origin main",
"git -C /tmp/example push origin main",
"git -c core.pager=cat --no-pager push",
"git --git-dir=/tmp/example push",
"git push",
"git status;git push",
"git status\ngit push",
"git \\\npush origin main",
"git pu\\\nsh origin main",
"git reset --ha\\\nrd HEAD",
"git reset --hard HEAD",
"git clean -xdf",
"git clean --force",
"git branch -D topic",
"git branch -df topic",
"git branch -vD topic",
"git branch --delete --force topic",
"git checkout -- .",
"git restore .",
):
check(json.dumps({"tool_input": {"command": command}}), 2)
for command in (
"git status",
"git diff",
"git -C /tmp/example status",
"git branch -d merged-topic",
"git reset --soft HEAD~1",
"echo 'git push origin main'",
'echo ""',
"git reset --soft HEAD; echo --hard",
):
check(json.dumps({"tool_input": {"command": command}}), 0)
for payload in ("", "{", "{}", "[]", '{"tool_input":{"command":null}}'):
check(payload, 2)
check('{"tool_input":{"command":"git status"}}', 2, {**os.environ, "PATH": ""})
check('{"tool_input":{"command":"git \\\""}}', 2)
print("Guardrail checks passed")
-1
View File
@@ -1,7 +1,6 @@
--- ---
name: grill-me name: grill-me
description: A relentless interview to sharpen a plan or design. description: A relentless interview to sharpen a plan or design.
disable-model-invocation: true
--- ---
Run a `/grilling` session. Run a `/grilling` session.
-1
View File
@@ -1,7 +1,6 @@
--- ---
name: grill-with-docs 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. 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
--- ---
Run a `/grilling` session, using the `/domain-modeling` skill. Run a `/grilling` session, using the `/domain-modeling` skill.
+4 -14
View File
@@ -3,20 +3,10 @@ name: grilling
description: 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. description: 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.
--- ---
Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it. Interview me relentlessly about every aspect of this until we reach a shared understanding. Walk down each branch of the decision tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled — the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round. Ask the questions one at a time, waiting for feedback on each question before continuing. Asking multiple questions at once is bewildering.
Each question should be formatted like so: If a *fact* can be found by exploring the environment (filesystem, tools, etc.), look it up rather than asking me. The *decisions*, though, are mine — put each one to me and wait for my answer.
``` Do not act on it until I confirm we have reached a shared understanding.
❓ **Q1** - **<question title>**: <question body, might be multiple paragraphs, including multiple choices>
➡️ <your recommended answer>
```
Each round the user answers reshapes the tree — settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one.
Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it — don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report — ask the rest of the frontier now. The _decisions_ are the user's — put each to them and wait.
The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding.
+1 -1
View File
@@ -1,3 +1,3 @@
interface: interface:
display_name: "Grilling" display_name: "Grilling"
short_description: "Stress-test thinking a round of questions at a time" short_description: "Stress-test thinking one question at a time"
+1 -3
View File
@@ -1,11 +1,9 @@
--- ---
name: handoff name: handoff
description: Compact the current conversation into a handoff document for another agent to pick up. description: Compact the current conversation into a handoff document for another agent to pick up.
argument-hint: "What will the next session be used for?"
disable-model-invocation: true
--- ---
Write a handoff document summarising the current conversation so a fresh agent can continue the work. Save to the temporary directory of the user's OS - not the current workspace. Write a handoff document summarising the current conversation so a fresh agent can continue the work. Honor a user-selected output path; otherwise save to the operating system's temporary directory rather than the workspace.
Include a "suggested skills" section in the document, which suggests skills that the agent should invoke. Include a "suggested skills" section in the document, which suggests skills that the agent should invoke.
+5 -4
View File
@@ -1,15 +1,16 @@
--- ---
name: implement name: implement
description: "Implement a piece of work based on a spec or set of tickets." 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. Implement the work described by the user in the spec or tickets.
Use /tdd where possible, at pre-agreed seams. Before editing, record the starting commit, the original spec/acceptance criteria, and existing worktree changes. Keep a task-owned path/patch list so verification can separate your work from unrelated changes.
Use /tdd when test-first work is requested or useful. Reuse established test seams and infer routine choices from the existing tests; ask only about consequential unresolved design decisions.
Run typechecking regularly, single test files regularly, and the full test suite once at the end. 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. Once done, use /code-review with the original spec, recorded baseline, and task-owned paths/patch. Request the current working result, including staged, unstaged, and new files, rather than a HEAD-only review.
Commit your work to the current branch. Commit task-owned changes only when committing is part of the requested workflow; otherwise hand off the verified diff. Preserve unrelated staged and unstaged work. A request to commit already supplies that authority; do not ask again or infer permission to push.
@@ -1,123 +1,56 @@
# HTML Report Format # HTML Architecture Report
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. Use only when HTML output is requested or a visual artifact materially helps. Honor the selected location; otherwise write to a fresh temporary file. Keep it usable offline with semantic HTML, a small stylesheet, and static SVG when useful.
## Scaffold ## Minimal scaffold
```html ```html
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<title>Architecture review — {{repo name}}</title> <meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://cdn.tailwindcss.com"></script> <title>Architecture review</title>
<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> <style>
/* small custom layer for things Tailwind doesn't cover cleanly: body { max-width: 70rem; margin: 2rem auto; padding: 0 1rem; font-family: system-ui; line-height: 1.5; }
dashed seam lines, hand-drawn-feeling arrow heads, etc. */ article { margin-block: 2rem; }
.seam { stroke-dasharray: 4 4; } svg { max-width: 100%; height: auto; }
.leak { stroke: #dc2626; }
.deep { background: linear-gradient(135deg, #0f172a, #1e293b); }
</style> </style>
</head> </head>
<body class="bg-stone-50 text-slate-900 font-sans"> <body>
<main class="max-w-5xl mx-auto px-6 py-12 space-y-12"> <main>
<header>...</header> <h1>Architecture review</h1>
<section id="candidates" class="space-y-10">...</section> <!-- Add the scoped findings and recommendation. -->
<section id="top-recommendation">...</section>
</main> </main>
</body> </body>
</html> </html>
``` ```
## Header ## Findings
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. For each candidate, include its location, observed problem, proposed change, concrete benefit, and recommendation strength. Identify ADR conflicts and uncertainty. Omit unsupported or merely speculative candidates rather than filling a quota.
## Candidate card Use before/after visuals for relationships that prose does not explain clearly. A small dependency graph, sequence, or nested module view may help; a plain paragraph often suffices. Give SVGs accessible titles and descriptions, and do not communicate meaning through color alone.
The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony. Use an existing renderer only when it adds value; embed static output rather than requiring external scripts at viewing time. Escape repository text inserted into HTML. Do not execute code from issues or findings to build the report.
Each candidate is one `<article>`: End with the recommended next step and its reason. The report does not authorize implementation.
- **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 — 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 — they should 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 ## 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 concise, evidence-backed explanations. Preserve project vocabulary and describe the relevant design concept where useful.
**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality. Terms such as module, interface, depth, seam, leverage, and locality can clarify the design.
**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module). Names such as component, service, API, boundary, layer, or wrapper are appropriate when they accurately name the project element. Do not replace established terms just to satisfy a glossary.
**Phrasings that fit the style:** **Phrasings that fit the style:**
- "Order intake module is shallow — interface nearly matches the implementation." - "Order intake module is shallow — interface nearly matches the implementation."
- "Pricing leaks across the seam." - "Pricing leaks across the seam."
- "Deepen: one interface, one place to test." - "Deepen: one interface, one place to test."
- "Two adapters justify the seam: HTTP in prod, in-memory in tests." - "The payment boundary isolates network failures 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"* — those terms aren't in the glossary and don't earn their place. Describe concrete gains such as fewer caller obligations or preserved coverage through one contract. Avoid unsupported claims of cleaner code, regardless of vocabulary.
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. State uncertainty and trade-offs honestly. Use only the formatting needed to make the finding understandable.
@@ -1,7 +1,6 @@
--- ---
name: improve-codebase-architecture 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. description: Review a codebase for module-deepening opportunities and explain the most useful candidates. Use for an architecture survey or a specified area of architectural friction.
disable-model-invocation: true
--- ---
# Improve Codebase Architecture # Improve Codebase Architecture
@@ -10,7 +9,7 @@ Surface architectural friction and propose **deepening opportunities** — refac
This command is _informed_ by the project's domain model and built on a shared design vocabulary: This command is _informed_ by the project's domain model and built on a shared design vocabulary:
- Run the `/codebase-design` skill 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 — don't drift into "component," "service," "API," or "boundary." - Use `/codebase-design` to reason about module depth, caller contracts, locality, and justified test seams. Preserve project names such as component, service, or API; explain concepts without imposing a competing vocabulary or adapter count.
- The domain language in `CONTEXT.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate. - The domain language in `CONTEXT.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate.
## Process ## Process
@@ -24,7 +23,7 @@ This command is _informed_ by the project's domain model and built on a shared d
Read the project's domain glossary (`CONTEXT.md`) and any ADRs in the area you're touching first. 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: Explore directly or delegate bounded independent areas through the available tools when useful. Note concrete friction:
- Where does understanding one concept require bouncing between many small modules? - Where does understanding one concept require bouncing between many small modules?
- Where are modules **shallow** — interface nearly as complex as the implementation? - Where are modules **shallow** — interface nearly as complex as the implementation?
@@ -34,11 +33,11 @@ Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics — e
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. 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 ### 2. Present the useful candidates
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. Honor the requested format and output path. A concise Markdown report is enough for a few findings. For a requested visual HTML report, use a fresh temporary path by default and provide its location; open it only when requested.
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. Use a diagram only when relationships or a before/after change are clearer visually. Prefer static HTML/CSS/SVG or existing renderers; do not add CDN scripts or dependencies for a simple report.
For each candidate, render a card with: For each candidate, render a card with:
@@ -46,24 +45,24 @@ For each candidate, render a card with:
- **Problem** — why the current architecture is causing friction - **Problem** — why the current architecture is causing friction
- **Solution** — plain English description of what would change - **Solution** — plain English description of what would change
- **Benefits** — explained in terms of locality and leverage, and how tests would improve - **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 - **Before / After diagram** — only when it materially clarifies the change
- **Recommendation strength** — one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge - **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. 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." Use `CONTEXT.md` vocabulary for the domain and accurate project names for the implementation. Design terms should clarify the proposed change, not rename existing concepts without need.
**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. **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. For HTML output, read [HTML-REPORT.md](HTML-REPORT.md) for a small offline scaffold and relevant diagram options.
Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?" Return the requested survey with a recommendation. If the user wants an interactive design session, offer to explore a candidate; otherwise stop at the report.
### 3. Grilling loop ### 3. Grilling loop
Once the user picks a candidate, run the `/grilling` skill to walk the decision tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. When the user requests an interview about a candidate, use `/grilling` for unresolved constraints and decisions. Reuse existing answers and honor a request for a direct design recommendation instead.
Side effects happen inline as decisions crystallize — run the `/domain-modeling` skill to keep the domain model current as you go: When domain-document updates are within scope, use `/domain-modeling` as decisions crystallize; a read-only architecture report should only recommend these updates:
- **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. - **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. - **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there.
+30
View File
@@ -0,0 +1,30 @@
---
name: loop-me
description: Grill me about specs for the workflows I want to build, within this workspace.
---
Run a stateful `/grilling` session whose output is **workflow** specs. Use one question at a time with a recommendation, focused on the requested workflow. Update relevant specs as decisions resolve; preserve unrelated specs and remove an existing one only when the user has authorized that scope change.
## The loop lens
A **loop** is a recurring pattern in the user's life: their career, their week, their morning, a single repeated activity. Picturing a life as loops within loops reveals how predictable its activities really are — which is what makes them worth **delegating**. Use the lens to find loops worth specifying, and propose ones the user hasn't noticed.
A **workflow** is the spec of one loop, made real. You run a workflow on a loop — the loop is its running instantiation. Workflows live in `workflows/*.md` and are the source of truth.
## Vocabulary
A shared language, reached for only when a workflow calls for it — never a checklist. **Mandate nothing structural**: a workflow needs no AI, no checkpoint, and no schedule unless the grilling shows it does.
- **Trigger** — what fires each run: an **event** (a new email, a new issue) or a **schedule** (every morning). Event-triggering is usually the more efficient.
- **Checkpoint** — a human-in-the-loop point where the user is asked to verify or decide. Some workflows have none and run autonomously; some use no AI at all.
- **Push right** — defer the checkpoint as far as it will go. Do maximal work before involving the human, so they are asked once, late, with everything prepared.
- **Brief** — what a checkpoint presents: a tight, decision-ready summary — what was produced, why, and a link down to the asset itself — never the raw output. The user reads a brief, not a draft. Speed of review is imperative.
## Definition of done
A workflow spec is done when its scope, inputs, outputs, authority, failure handling, and acceptance criteria are actionable. Record safe assumptions and optional future questions; keep interviewing only about decisions that materially affect the requested workflow.
## The workspace
- `workflows/*.md` — one spec per workflow.
- `NOTES.md` — relevant tools, channels, preferences, and terminology already learned. Missing notes do not block a clear request; ask only for context needed by this workflow and avoid collecting unrelated personal details.
@@ -0,0 +1,5 @@
interface:
display_name: "Loop Me"
short_description: "Spec the workflows you want to build"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,24 @@
---
name: luna-verified-implement
description: Implement a spec or ticket with gpt-6-luna implementation subagents and independently verify the final change with the orchestrator's model and reasoning effort. Use when the user asks to implement, build, or fix work and wants delegated implementation with a verification pass.
---
# Luna Verified Implement
Invoke `$implement` and follow it as the baseline workflow. Treat this skill as its delegated, verified variant.
## Workflow
1. Read the spec or ticket, repository guidance, affected flow, and existing worktree changes. Record the starting commit and task-owned scope; preserve unrelated changes.
2. Split only genuinely independent, bounded work. If the change is small or one seam owns it, use one implementation agent; do not manufacture parallelism.
3. Spawn each implementation agent with `fork_turns: "none"`, `model: "gpt-6-luna"`, and `reasoning_effort: "max"`. Give each its exact owned files/seam, acceptance criteria, required checks, and task-local context. Tell agents not to overwrite or revert other agents' work.
4. Wait for agents, inspect their diffs, resolve overlaps minimally, and run the implementation checks required by `$implement`: targeted tests and typecheck during work, then the full relevant suite once.
5. Spawn a fresh, read-only verification agent with `fork_turns: "none"`, `model` and `reasoning_effort` set to the orchestrator's current values. Do not hard-code a different model or reasoning effort for verification. Give it the original request, current diff, and test output, but not implementation conclusions. Ask it to check correctness, regressions, specification coverage, and test evidence. Have it report findings without changing files.
6. Fix confirmed findings, rerun affected checks, and repeat verification once if fixes were needed. Run `$code-review` on the current working result (including staged, unstaged, and new files), passing the original spec, starting commit, and task-owned scope. Follow `$implement`'s commit boundary: commit only when requested, otherwise hand off the verified diff.
## Delegation rules
- Keep all agents in the same workspace; assign non-overlapping ownership before they edit.
- Use at most the available concurrency slots. Reserve one slot for coordination and verification.
- Do not delegate secrets, production writes, destructive operations, or changes requiring new user authority.
- If subagents are unavailable, implement directly, run the same checks, and state that delegated verification was unavailable.
@@ -0,0 +1,4 @@
interface:
display_name: "Luna Verified Implement"
short_description: "Delegate implementation and verify it"
default_prompt: "Use $luna-verified-implement to implement this task with Luna agents and verify the result."
+118
View File
@@ -0,0 +1,118 @@
---
name: migrate-to-shoehorn
description: Migrate test files from `as` type assertions to @total-typescript/shoehorn. Use when user mentions shoehorn, wants to replace `as` in tests, or needs partial test data.
---
# Migrate to Shoehorn
## Why shoehorn?
`shoehorn` lets you pass partial data in tests while keeping TypeScript happy. It replaces `as` assertions with type-safe alternatives.
**Test code only.** Never use shoehorn in production code.
Problems with `as` in tests:
- Trained not to use it
- Must manually specify target type
- Double-as (`as unknown as Type`) for intentionally wrong data
## Install
```bash
npm i @total-typescript/shoehorn
```
## Migration patterns
### Large objects with few needed properties
Before:
```ts
type Request = {
body: { id: string };
headers: Record<string, string>;
cookies: Record<string, string>;
// ...20 more properties
};
it("gets user by id", () => {
// Only care about body.id but must fake entire Request
getUser({
body: { id: "123" },
headers: {},
cookies: {},
// ...fake all 20 properties
});
});
```
After:
```ts
import { fromPartial } from "@total-typescript/shoehorn";
it("gets user by id", () => {
getUser(
fromPartial({
body: { id: "123" },
}),
);
});
```
### `as Type` → `fromPartial()`
Before:
```ts
getUser({ body: { id: "123" } } as Request);
```
After:
```ts
import { fromPartial } from "@total-typescript/shoehorn";
getUser(fromPartial({ body: { id: "123" } }));
```
### `as unknown as Type` → `fromAny()`
Before:
```ts
getUser({ body: { id: 123 } } as unknown as Request); // wrong type on purpose
```
After:
```ts
import { fromAny } from "@total-typescript/shoehorn";
getUser(fromAny({ body: { id: 123 } }));
```
## When to use each
| Function | Use case |
| --------------- | -------------------------------------------------- |
| `fromPartial()` | Pass partial data that still type-checks |
| `fromAny()` | Pass intentionally wrong data (keeps autocomplete) |
| `fromExact()` | Force full object (swap with fromPartial later) |
## Workflow
1. **Gather requirements** - ask user:
- What test files have `as` assertions causing problems?
- Are they dealing with large objects where only some properties matter?
- Do they need to pass intentionally wrong data for error testing?
2. **Install and migrate**:
- [ ] Install: `npm i @total-typescript/shoehorn`
- [ ] Find test files with `as` assertions: `grep -r " as [A-Z]" --include="*.test.ts" --include="*.spec.ts"`
- [ ] Replace `as Type` with `fromPartial()`
- [ ] Replace `as unknown as Type` with `fromAny()`
- [ ] Add imports from `@total-typescript/shoehorn`
- [ ] Run type check to verify
@@ -0,0 +1,3 @@
interface:
display_name: "Migrate to Shoehorn"
short_description: "Replace test assertions with shoehorn"
+16
View File
@@ -0,0 +1,16 @@
---
name: obsidian-vault
description: Search, create, and manage notes in the Obsidian vault with wikilinks and index notes. Use when user wants to find, create, or organize notes in Obsidian.
---
# Obsidian Vault
Resolve the vault from the user's selected path, workspace configuration, or available Obsidian connection. If several vaults are plausible or none is configured, ask which one to use. Verify access before searching or writing; do not assume a personal machine path.
Read the selected vault's instructions and nearby notes. Preserve its folder layout, naming, frontmatter, and index conventions instead of imposing a flat structure or title-case names.
- Search filenames with `rg --files <vault>` and content with `rg`, scoped to the selected vault.
- Use existing `[[wikilinks]]` conventions; check the destination note before adding a link.
- For a new note, search for existing coverage first, then add only relevant links and index entries.
- Before moving or renaming a note, check backlinks and update affected links within the requested scope.
- For read-only questions, return the relevant notes without reorganizing the vault.
@@ -0,0 +1,3 @@
interface:
display_name: "Obsidian Vault"
short_description: "Manage linked notes in Obsidian"
+39 -27
View File
@@ -1,15 +1,13 @@
# Logic Prototype # 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. A tiny interactive terminal app that lets the user drive a state model by hand. 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 ## When this is the right shape
- "I'm not sure if this state machine handles the edge case where X then Y." - "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..." - "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." - "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**. - Anything where the user wants to **press buttons and watch state change**.
If the question is "what should this look like" — wrong branch. Use [UI.md](UI.md). If the question is "what should this look like" — wrong branch. Use [UI.md](UI.md).
@@ -17,11 +15,17 @@ If the question is "what should this look like" — wrong branch. Use [UI.md](UI
### 1. State the question ### 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 — make the question explicit so it can be checked later, whether the user is watching now or returning to it AFK. Before writing code, write down what state model and what question you're prototyping. One paragraph, in the prototype's README or a comment at the top of the file. A logic prototype that answers the wrong question is pure waste — 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 ### 2. Pick the language
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. Use whatever the host project uses. If the project has no obvious runtime (e.g. a docs repo), ask.
Match the project's existing conventions for tooling — don't add a new package manager or runtime just for the prototype.
### 3. Isolate the logic in a portable module
Put the actual logic — the bit that's answering the question — behind a small, pure interface that could be lifted out and dropped into the real codebase later. The TUI around it is throwaway; the logic module shouldn't be.
The right shape depends on the question: The right shape depends on the question:
@@ -30,38 +34,46 @@ The right shape depends on the question:
- **A small set of pure functions** over a plain data type. Good when there's no implicit current state — just transformations. - **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. - **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. Pick whichever shape best fits the question being asked, *not* whichever is easiest to wire to a TUI. Keep it pure: no I/O, no terminal code, no `console.log` for control flow. The TUI imports it and calls into it; nothing flows the other direction.
### 3. Build the shareable HTML file This is what makes the prototype useful past its own lifetime: when the question's been answered, the validated reducer / machine / function set can be lifted into the real module on its own.
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. ### 4. Build the smallest TUI that exposes the state
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. Build it as a **lightweight TUI** — on every tick, clear the screen (`console.clear()` / `print("\033[2J\033[H")` / equivalent) and re-render the whole frame. The user should always see one stable view, not an ever-growing scrollback.
Lay it out with a clean hierarchy, top to bottom: Each frame has two parts, in this order:
1. **Title and one-line explanation** of what this demo lets you explore (the question from step 1). 1. **Current state**, pretty-printed and diff-friendly (one field per line, or formatted JSON). Use **bold** for field names or section headers and **dim** for less important context (timestamps, IDs, derived values). Native ANSI escape codes are fine — `\x1b[1m` bold, `\x1b[2m` dim, `\x1b[0m` reset. No need to pull in a styling library unless one is already in the project.
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. 2. **Keyboard shortcuts**, listed at the bottom: `[a] add user [d] delete user [t] tick clock [q] quit`. Bold the key, dim the description, or vice-versa — whatever reads cleanly.
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 happy path, a tricky edge case, an attempt at something that should be illegal — the ones hard to reason about on paper. Behaviour:
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. 1. **Initialise state** — a single in-memory object/struct. Render the first frame on start.
2. **Read one keystroke (or one line)** at a time, dispatch to a handler that mutates state.
3. **Re-render** the full frame after every action — don't append, replace.
4. **Loop until quit.**
### 4. Hand it over The whole frame should fit on one screen.
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. Make it runnable in one command
### 5. Capture the answer and the prototype Add a script to the project's existing task runner (`package.json` scripts, `Makefile`, `justfile`, `pyproject.toml`). The user should run `pnpm run <prototype-name>` or equivalent — never need to remember a path.
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. If the host project has no task runner, just put the command at the top of the prototype's README.
### 6. Hand it over
Give the user the run command. They'll drive it themselves; 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 added, add them. Prototypes evolve.
### 7. Capture the answer and the prototype
Return the answer and the prototype location under the [shared scope rules](SKILL.md). If the user requests implementation afterward, lift only the validated logic into the real module and add its required production tests; do not promote or publish it automatically.
## Anti-patterns ## Anti-patterns
- **Don't add tests.** A prototype that needs tests is no longer a prototype. - **Don't build a production test suite by default.** Keep a runnable check for the design question and non-trivial logic; honor explicitly requested validation.
- **Don't wire it to the real database.** Use in-memory state unless the question is specifically about persistence. - **Don't wire it to the real database.** Use an in-memory store 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 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 blur the logic and the TUI together.** If the reducer / state machine references `console.log`, prompts, or terminal escape codes, it's no longer portable. Keep the TUI 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 TUI shell into production.** The shell is optimised for being driven by hand from a terminal. The logic module behind it is the bit worth keeping.
- **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.
+4 -4
View File
@@ -11,7 +11,7 @@ A prototype is **throwaway code that answers a question**. The question decides
Identify which question is being answered — from the user's prompt, the surrounding code, or by asking if the user is around: Identify which question is being answered — from 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. - **"Does this logic / state model feel right?"** → [LOGIC.md](LOGIC.md). Build a tiny interactive terminal app that pushes the state machine through cases that are hard to reason about on paper.
- **"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. - **"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 — 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. The two branches produce very different artifacts — 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.
@@ -19,8 +19,8 @@ The two branches produce very different artifacts — getting this wrong wastes
## Rules that apply to both ## 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. 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. 2. **One command to run.** Whatever the project's existing task runner supports — `pnpm <name>`, `python <path>`, `bun <path>`, etc. The user must be able to start it without thinking.
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. 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. 4. **Keep validation proportional.** Preserve input safety, data isolation, and accessibility. Include the smallest runnable check for non-trivial logic or the question being tested; skip production polish and speculative abstractions.
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. 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. 6. **Stop at the experiment's result.** Return the artifact location, run command, and verdict with any uncertainty. Promote a decision into application code, commit/archive the prototype, or update an issue only when that action is part of the user's request. Preserve a requested output path; remove only task-owned disposable artifacts when cleanup is in scope.
+4 -4
View File
@@ -35,7 +35,7 @@ In both sub-shapes the floating bottom bar is identical.
### 1. State the question and pick N ### 1. State the question and pick N
Default to **3 variants**. More than 5 stops being radically different and starts being noise — cap there. Honor the requested number and format. For an open-ended comparison, two or three materially different variants are usually enough; a single requested mockup does not need a comparison switcher.
Write down the plan in one line, in the prototype's location or a top-of-file comment: Write down the plan in one line, in the prototype's location or a top-of-file comment:
@@ -97,16 +97,16 @@ Surface the URL (and the `?variant=` keys). The user will flip through whenever
### 6. Capture the answer and clean up ### 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: Once a variant has won, return which variant and why under the [shared scope rules](SKILL.md). Only if the user also requests promotion into application code:
- **Sub-shape A** — fold the winner into the existing page; drop the losing variants and the switcher from 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. - **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 — variant components and the switcher left in the main branch rot fast and confuse the next reader. Retain variants at the agreed artifact location. Branch archival, commits, issue updates, and deletion require corresponding task scope; do not change branches in a shared dirty checkout to archive a prototype.
## Anti-patterns ## Anti-patterns
- **Variants that differ only in colour or copy.** That's a tweak, not a prototype. Real variants disagree about structure. - **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. - **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". - **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. - **Promoting the prototype without production verification.** When promotion is requested, apply the application's full testing, error-state, security, and accessibility requirements.
+130
View File
@@ -0,0 +1,130 @@
---
name: qa
description: Run a conversational QA session, capture reproducible problems, and prepare issues for the repository's configured tracker.
---
# QA Session
Run an interactive QA session. Use [the configured tracker](../../../docs/agents/issue-tracker.md) for issue operations and [domain documentation](../../../docs/agents/domain.md) for project language.
## For each issue the user raises
### 1. Listen and lightly clarify
Let the user describe the problem in their own words. Ask **at most 2-3 short clarifying questions** focused on:
- What they expected vs what actually happened
- Steps to reproduce (if not obvious)
- Whether it's consistent or intermittent
Do NOT over-interview. If the description is clear enough to file, move on.
### 2. Explore the codebase in the background
While talking to the user, kick off an Agent (subagent_type=Explore) in the background to understand the relevant area. The goal is NOT to find a fix — it's to:
- Learn the domain language used in that area (check `CONTEXT.md`)
- Understand what the feature is supposed to do
- Identify the user-facing behavior boundary
This context helps you write a better issue — but the issue itself should NOT reference specific files, line numbers, or internal implementation details.
### 3. Assess scope: single issue or breakdown?
Before filing, decide whether this is a **single issue** or needs to be **broken down** into multiple issues.
Break down when:
- The fix spans multiple independent areas (e.g. "the form validation is wrong AND the success message is missing AND the redirect is broken")
- There are clearly separable concerns that different people could work on in parallel
- The user describes something that has multiple distinct failure modes or symptoms
Keep as a single issue when:
- It's one behavior that's wrong in one place
- The symptoms are all caused by the same root behavior
### 4. File the issue(s)
When the user asked to file issues, create them using the configured tracker commands and share URLs without a redundant approval step. For discussion-only QA, return drafts; ask before publishing if publication was not requested. On an ambiguous create failure, check whether the issue already exists before retrying; on unavailable access, hand off the draft and state the limitation.
Issues must be **durable** — they should still make sense after major refactors. Write from the user's perspective.
#### For a single issue
Use this template:
```
## What happened
[Describe the actual behavior the user experienced, in plain language]
## What I expected
[Describe the expected behavior]
## Steps to reproduce
1. [Concrete, numbered steps a developer can follow]
2. [Use domain terms from the codebase, not internal module names]
3. [Include relevant inputs, flags, or configuration]
## Additional context
[Any extra observations from the user or from codebase exploration that help frame the issue — e.g. "this only happens when using the Docker layer, not the filesystem layer" — use domain language but don't cite files]
```
#### For a breakdown (multiple issues)
Create issues in dependency order (blockers first) so you can reference real issue numbers.
Use this template for each sub-issue:
```
## Parent issue
#<parent-issue-number> (if you created a tracking issue) or "Reported during QA session"
## What's wrong
[Describe this specific behavior problem — just this slice, not the whole report]
## What I expected
[Expected behavior for this specific slice]
## Steps to reproduce
1. [Steps specific to THIS issue]
## Blocked by
- #<issue-number> (if this issue can't be fixed until another is resolved)
Or "None — can start immediately" if no blockers.
## Additional context
[Any extra observations relevant to this slice]
```
When creating a breakdown:
- **Prefer many thin issues over few thick ones** — each should be independently fixable and verifiable
- **Mark blocking relationships honestly** — if issue B genuinely can't be tested until issue A is fixed, say so. If they're independent, mark both as "None — can start immediately"
- **Create issues in dependency order** so you can reference real issue numbers in "Blocked by"
- **Maximize parallelism** — the goal is that multiple people (or agents) can grab different issues simultaneously
#### Rules for all issue bodies
- **No file paths or line numbers** — these go stale
- **Use the project's domain language** (check `CONTEXT.md` if it exists)
- **Describe behaviors, not code** — "the sync service fails to apply the patch" not "applyPatch() throws on line 42"
- **Record reproduction evidence** — ask for missing steps when they matter; if unavailable, state what is known and unknown rather than inventing a reproduction or blocking a useful report
- **Keep it concise** — a developer should be able to read the issue in 30 seconds
After filing, print all issue URLs (with blocking relationships summarized) and ask: "Next issue, or are we done?"
### 5. Continue the session
Keep going until the user says they're done. Each issue is independent — don't batch them.
+3
View File
@@ -0,0 +1,3 @@
interface:
display_name: "QA"
short_description: "Conversational QA that files issues"
@@ -0,0 +1,68 @@
---
name: request-refactor-plan
description: Plan a refactor as small, independently verifiable changes and prepare it for the repository's configured issue tracker. Use for refactor plans or RFCs.
---
This skill will be invoked when the user wants to create a refactor request. You should go through the steps below. You may skip steps if you don't consider them necessary.
1. Use the supplied problem and ideas. Ask only for missing context that would materially affect the plan.
2. Explore the repo to verify their assertions and understand the current state of the codebase.
3. Compare relevant alternatives when there is a meaningful trade-off; preserve already settled choices.
4. Resolve consequential unknowns through a focused interview only when needed. Do not require a new interview for an actionable request.
5. Hammer out the exact scope of the implementation. Work out what you plan to change and what you plan not to change.
6. Inspect existing test coverage and propose the checks needed to keep behavior stable. Ask the user only about constraints or desired behavior the repository cannot establish.
7. Break the implementation into a plan of tiny commits. Remember Martin Fowler's advice to "make each refactoring step as small as possible, so that you can always see the program working."
8. Return the requested plan. If the user also asked to file it, publish using [the configured tracker](../../../docs/agents/issue-tracker.md) without asking again. Otherwise keep it as a draft. If publication fails ambiguously, check for an existing issue before retrying; stop and preserve the draft when access or authority is missing. Use the following template as appropriate:
<refactor-plan-template>
## Problem Statement
The problem that the developer is facing, from the developer's perspective.
## Solution
The solution to the problem, from the developer's perspective.
## Commits
A plan of small, verifiable changes, detailed enough to implement without artificial fragmentation. Follow the repository's development lifecycle policy when contracts and callers must change together; identify any shared integration gate explicitly.
## Decision Document
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.
## 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 refactor.
## Further Notes (optional)
Any further notes about the refactor.
</refactor-plan-template>
@@ -0,0 +1,3 @@
interface:
display_name: "Request Refactor Plan"
short_description: "Plan a safe incremental refactor"
@@ -7,8 +7,8 @@ description: "Use when you need to resolve an in-progress git merge/rebase confl
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. 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`. 3. **Resolve each hunk.** Preserve both intents where possible. Where incompatible, use the merge's stated goal if it settles the choice and note the trade-off. If intent remains ambiguous, leave the affected conflict intact and ask for that decision. Do not invent behavior or abort the operation without authorization.
4. Discover the project's **automated checks** and run them — typically typecheck, then tests, then format. Fix anything the merge broke. 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. 5. **Finish the requested operation.** Stage only resolved paths and required task-owned fixes. Inspect the index for unrelated staged changes before committing. A request to finish the merge/rebase authorizes its normal continuation; a review-only request does not. Continue a requested rebase until complete, stopping for unresolved intent, failed checks, or new authority requirements. Never stage the entire checkout indiscriminately.
+106
View File
@@ -0,0 +1,106 @@
---
name: scaffold-exercises
description: Scaffold numbered course exercises with problem, solution, and explainer folders in the AI Hero course format. Use when that format is requested or already established in the course.
---
# Scaffold Exercises
Inspect the selected course's package manager, exercise layout, and lint script first. The conventions below describe the AI Hero format; follow an explicitly requested different format instead. Use the course's installed lint command; `pnpm ai-hero-cli internal lint` applies only when that tool and package manager are configured. If tooling is absent, check the files directly and report that lint was unavailable; do not install or initialize a course stack implicitly. Commit only when requested, staging just the task-owned exercise changes.
## Directory naming
- **Sections**: `XX-section-name/` inside `exercises/` (e.g., `01-retrieval-skill-building`)
- **Exercises**: `XX.YY-exercise-name/` inside a section (e.g., `01.03-retrieval-with-bm25`)
- Section number = `XX`, exercise number = `XX.YY`
- Names are dash-case (lowercase, hyphens)
## Exercise variants
Each exercise needs at least one of these subfolders:
- `problem/` - student workspace with TODOs
- `solution/` - reference implementation
- `explainer/` - conceptual material, no TODOs
When stubbing, default to `explainer/` unless the plan specifies otherwise.
## Required files
Each subfolder (`problem/`, `solution/`, `explainer/`) needs a `readme.md` that:
- Is **not empty** (must have real content, even a single title line works)
- Has no broken links
When stubbing, create a minimal readme with a title and a description:
```md
# Exercise Title
Description here
```
If the subfolder has code, it also needs a `main.ts` (>1 line). But for stubs, a readme-only exercise is fine.
## Workflow
1. **Parse the plan** - extract section names, exercise names, and variant types
2. **Create directories** - `mkdir -p` for each path
3. **Create stub readmes** - one `readme.md` per variant folder with a title
4. **Run lint** - use the selected course's configured command
5. **Fix any errors** - iterate until lint passes
## Lint rules summary
For courses using AI Hero, verify these conventions against the installed linter:
- Each exercise has subfolders (`problem/`, `solution/`, `explainer/`)
- At least one of `problem/`, `explainer/`, or `explainer.1/` exists
- `readme.md` exists and is non-empty in the primary subfolder
- No `.gitkeep` files
- No `speaker-notes.md` files
- No broken links in readmes
- No `pnpm run exercise` commands in readmes
- `main.ts` required per subfolder unless it's readme-only
## Moving/renaming exercises
When renumbering or moving exercises:
1. Use `git mv` (not `mv`) to rename directories - preserves git history
2. Update the numeric prefix to maintain order
3. Re-run lint after moves
Example:
```bash
git mv exercises/01-retrieval/01.03-embeddings exercises/01-retrieval/01.04-embeddings
```
## Example: stubbing from a plan
Given a plan like:
```
Section 05: Memory Skill Building
- 05.01 Introduction to Memory
- 05.02 Short-term Memory (explainer + problem + solution)
- 05.03 Long-term Memory
```
Create:
```bash
mkdir -p exercises/05-memory-skill-building/05.01-introduction-to-memory/explainer
mkdir -p exercises/05-memory-skill-building/05.02-short-term-memory/{explainer,problem,solution}
mkdir -p exercises/05-memory-skill-building/05.03-long-term-memory/explainer
```
Then create readme stubs:
```
exercises/05-memory-skill-building/05.01-introduction-to-memory/explainer/readme.md -> "# Introduction to Memory"
exercises/05-memory-skill-building/05.02-short-term-memory/explainer/readme.md -> "# Short-term Memory"
exercises/05-memory-skill-building/05.02-short-term-memory/problem/readme.md -> "# Short-term Memory"
exercises/05-memory-skill-building/05.02-short-term-memory/solution/readme.md -> "# Short-term Memory"
exercises/05-memory-skill-building/05.03-long-term-memory/explainer/readme.md -> "# Long-term Memory"
```
@@ -0,0 +1,3 @@
interface:
display_name: "Scaffold Exercises"
short_description: "Scaffold lint-ready course exercises"
@@ -1,18 +1,17 @@
--- ---
name: setup-matt-pocock-skills name: setup-matt-pocock-skills
description: 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. description: Configure or update a repository's issue tracker, triage labels, and domain-documentation pointers for the engineering skills.
disable-model-invocation: true
--- ---
# Setup Matt Pocock's Skills # Setup Matt Pocock's Skills
Scaffold the per-repo configuration that the engineering skills assume: Scaffold the per-repo configuration that the engineering skills assume:
- **Issue tracker** — where issues live (GitHub by default; local markdown is also supported out of the box) - **Issue tracker** — where this repository actually tracks work
- **Triage labels** — the strings used for the five canonical triage roles - **Triage labels** — the strings used for the five canonical triage roles
- **Domain docs** — where `CONTEXT.md` and ADRs live, and the consumer rules for reading them - **Domain docs** — where `CONTEXT.md` and ADRs live, and the consumer rules for reading them
This is a prompt-driven skill, not a deterministic script. Explore, present what you found, confirm with the user, then write. Inspect existing configuration, preserve settled choices, and make only the requested setup changes. Ask about unresolved choices that matter, not every section of a working setup.
## Process ## Process
@@ -20,7 +19,7 @@ This is a prompt-driven skill, not a deterministic script. Explore, present what
Look at the current repo to understand its starting state. Read whatever exists; don't assume: Look at the current repo to understand its starting state. Read whatever exists; don't assume:
- `git remote -v` and `.git/config` — is this a GitHub repo? Which one? - `git remote -v` and existing tracker documentation — which project and tracker are selected?
- `AGENTS.md` and `CLAUDE.md` at the repo root — does either exist? Is there already an `## Agent skills` section in either? - `AGENTS.md` and `CLAUDE.md` at the repo root — does either exist? Is there already an `## Agent skills` section in either?
- `CONTEXT.md` and `CONTEXT-MAP.md` at the repo root - `CONTEXT.md` and `CONTEXT-MAP.md` at the repo root
- `docs/adr/` and any `src/*/docs/adr/` directories - `docs/adr/` and any `src/*/docs/adr/` directories
@@ -31,15 +30,15 @@ Look at the current repo to understand its starting state. Read whatever exists;
### 2. Present findings and ask ### 2. Present findings and ask
Summarise what's present and what's missing. Then take the sections in order — one section, one answer, then the next. Summarise what is present and what needs changing. Skip questions already answered by the request or existing configuration; use the sections below only for unresolved setup choices.
Lead each section with the recommended answer so the user can accept it in a word. Give a one-line explainer only when the choice genuinely branches; skip the section entirely when exploration already settled it (Section B when `triage` isn't installed, Section C when there's no monorepo). Lead each section with the recommended answer so the user can accept it in a word. Give a one-line explainer only when the choice genuinely branches; skip the section entirely when exploration already settled it (Section B when `triage` isn't installed, Section C when there's no monorepo).
**Section A — Issue tracker.** **Section A — Issue tracker.**
> Explainer: The "issue tracker" is where issues live for this repo. Skills like `to-tickets`, `triage`, and `to-spec` read from and write to it — they need to know whether to call `gh issue create`, write a markdown file under `.scratch/`, or follow some other workflow you describe. Pick the place you actually track work for this repo. > Explainer: The "issue tracker" is where issues live for this repo. Skills like `to-tickets`, `triage`, `to-spec`, and `qa` read from and write to it — they need to know whether to call `gh issue create`, write a markdown file under `.scratch/`, or follow some other workflow you describe. Pick the place you actually track work for this repo.
Default posture: these skills were designed for GitHub. If a `git remote` points at GitHub, propose that. If a `git remote` points at GitLab (`gitlab.com` or a self-hosted host), propose GitLab. Otherwise (or if the user prefers), offer: Preserve the configured tracker. For a new setup, infer a likely tracker from the remote and the user's request; ask when genuinely ambiguous. Available templates include:
- **GitHub** — issues live in the repo's GitHub Issues (uses the `gh` CLI) - **GitHub** — issues live in the repo's GitHub Issues (uses the `gh` CLI)
- **GitLab** — issues live in the repo's GitLab Issues (uses the [`glab`](https://gitlab.com/gitlab-org/cli) CLI) - **GitLab** — issues live in the repo's GitLab Issues (uses the [`glab`](https://gitlab.com/gitlab-org/cli) CLI)
@@ -50,30 +49,31 @@ Record the choice in `docs/agents/issue-tracker.md`. The GitHub and GitLab templ
**Section B — Triage label vocabulary.** Skip this section entirely if the `triage` skill isn't installed (exploration told you) — an uninstalled skill needs no labels. **Section B — Triage label vocabulary.** Skip this section entirely if the `triage` skill isn't installed (exploration told you) — an uninstalled skill needs no labels.
If it is installed, ask exactly one question: If installed and no label vocabulary is already selected, ask only when the default cannot be reasonably inferred:
> Do you want to keep the default triage labels? (recommended: **yes**) > Do you want to keep the default triage labels? (recommended: **yes**)
The defaults are the five canonical roles, each label string equal to its name: `needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`. On **yes**, write them as-is. Only if the user says no — usually because their tracker already uses other names (e.g. `bug:triage` for `needs-triage`) — collect the overrides so `triage` applies existing labels instead of creating duplicates. The defaults are the five canonical roles, each label string equal to its name: `needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`. On **yes**, write them as-is. Only if the user says no — usually because their tracker already uses other names (e.g. `bug:triage` for `needs-triage`) — collect the overrides so `triage` applies existing labels instead of creating duplicates.
**Section C — Domain docs.** Default to **single-context** — one `CONTEXT.md` + `docs/adr/` at the repo root. This fits almost every repo; write it without asking. **Section C — Domain docs.** Preserve the existing layout. For a new setup, default to **single-context** — one `CONTEXT.md` + `docs/adr/` at the repo root.
Offer **multi-context** — a root `CONTEXT-MAP.md` pointing to per-context `CONTEXT.md` files — only when exploration found monorepo signals. Then confirm which layout they want. Offer **multi-context** — a root `CONTEXT-MAP.md` pointing to per-context `CONTEXT.md` files — only when exploration found monorepo signals. Then confirm which layout they want.
### 3. Confirm and edit ### 3. Prepare the scoped edits
Show the user a draft of: Update only requested or missing configuration among:
- The `## Agent skills` block to add to whichever of `CLAUDE.md` / `AGENTS.md` is being edited (see step 4 for selection rules) - The `## Agent skills` block to add to whichever of `CLAUDE.md` / `AGENTS.md` is being edited (see step 4 for selection rules)
- The contents of `docs/agents/issue-tracker.md`, `docs/agents/domain.md`, and `docs/agents/triage-labels.md` (the last only when `triage` is installed) - The contents of `docs/agents/issue-tracker.md`, `docs/agents/domain.md`, and `docs/agents/triage-labels.md` (the last only when `triage` is installed)
Let them edit before writing. Show a draft first when requested or when a consequential choice remains unsettled; otherwise proceed with the known choices.
### 4. Write ### 4. Write
**Pick the file to edit:** **Pick the file to edit:**
- If `CLAUDE.md` exists, edit it. - Honor the user-selected instruction file and agent product first.
- Otherwise edit the existing applicable file; if only `CLAUDE.md` exists, edit it.
- Else if `AGENTS.md` exists, edit it. - Else if `AGENTS.md` exists, edit it.
- If neither exists, ask the user which one to create — don't pick for them. - If neither exists, ask the user which one to create — don't pick for them.
@@ -1,6 +1,6 @@
# Issue tracker: GitHub # Issue tracker: GitHub
Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations. Issues and PRDs for this repo live as GitHub issues. Use the `gh` CLI for all operations.
## Conventions ## Conventions
@@ -1,12 +1,12 @@
# Issue tracker: GitLab # Issue tracker: GitLab
Issues and specs for this repo live as GitLab issues. Use the [`glab`](https://gitlab.com/gitlab-org/cli) CLI for all operations. Issues and PRDs for this repo live as GitLab issues. Use the [`glab`](https://gitlab.com/gitlab-org/cli) CLI for all operations.
## Conventions ## Conventions
- **Create an issue**: `glab issue create --title "..." --description "..."`. Use a heredoc for multi-line descriptions. Pass `--description -` to open an editor. - **Create an issue**: `glab issue create --title "..." --description "..."`. Use a heredoc for multi-line descriptions. Pass `--description -` to open an editor.
- **Read an issue**: `glab issue view <number> --comments`. Use `-F json` for machine-readable output. - **Read an issue**: `glab issue view <number> --comments`. Use `-F json` for machine-readable output.
- **List issues**: `glab issue list -F json` with appropriate `--label` filters. - **List issues**: `glab issue list --output json` with appropriate `--label` filters.
- **Comment on an issue**: `glab issue note <number> --message "..."`. GitLab calls comments "notes". - **Comment on an issue**: `glab issue note <number> --message "..."`. GitLab calls comments "notes".
- **Apply / remove labels**: `glab issue update <number> --label "..."` / `--unlabel "..."`. Multiple labels can be comma-separated or by repeating the flag. - **Apply / remove labels**: `glab issue update <number> --label "..."` / `--unlabel "..."`. Multiple labels can be comma-separated or by repeating the flag.
- **Close**: `glab issue close <number>`. `glab issue close` does not accept a closing comment, so post the explanation first with `glab issue note <number> --message "..."`, then close. - **Close**: `glab issue close <number>`. `glab issue close` does not accept a closing comment, so post the explanation first with `glab issue note <number> --message "..."`, then close.
@@ -41,6 +41,6 @@ Used by `/wayfinder`. The **map** is a single issue with **child** issues as tic
- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `glab issue create --label wayfinder:map`. (On GitLab tiers with native epics, an epic may hold the map instead; a labelled issue works everywhere.) - **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `glab issue create --label wayfinder:map`. (On GitLab tiers with native epics, an epic may hold the map instead; a labelled issue works everywhere.)
- **Child ticket**: an issue carrying `Part of #<map>` at the top of its description and labels `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev. - **Child ticket**: an issue carrying `Part of #<map>` at the top of its description and labels `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
- **Blocking**: GitLab's **native blocking link** — the canonical, UI-visible representation. Add it with the `/blocked_by #<n>` quick action, posted as a note (`glab issue note <child> --message "/blocked_by #<blocker>"`). Native blocking links are a Premium/Ultimate feature; on the free tier (or where unavailable) fall back to a `Blocked by: #<n>, #<n>` line at the top of the description. A ticket is unblocked when every blocker is closed. - **Blocking**: GitLab's **native blocking link** — the canonical, UI-visible representation. Add it with the `/blocked_by #<n>` quick action, posted as a note (`glab issue note <child> --message "/blocked_by #<blocker>"`). Native blocking links are a Premium/Ultimate feature; on the free tier (or where unavailable) fall back to a `Blocked by: #<n>, #<n>` line at the top of the description. A ticket is unblocked when every blocker is closed.
- **Frontier query**: `glab issue list -F json` scoped to the map's children, drop any with an open blocker — a native `blocked_by` link to an open issue (`glab api projects/:id/issues/:iid/links`), or an open issue in the `Blocked by` line — or an assignee; first in map order wins. - **Frontier query**: `glab issue list --output json` scoped to the map's children, drop any with an open blocker — a native `blocked_by` link to an open issue (`glab api projects/:id/issues/:iid/links`), or an open issue in the `Blocked by` line — or an assignee; first in map order wins.
- **Claim**: `glab issue update <n> --assignee @me` — the session's first write. - **Claim**: `glab issue update <n> --assignee @me` — the session's first write.
- **Resolve**: `glab issue note <n> --message "<answer>"`, then `glab issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far. - **Resolve**: `glab issue note <n> --message "<answer>"`, then `glab issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.
@@ -1,6 +1,6 @@
# Issue tracker: Local Markdown # Issue tracker: Local Markdown
Issues and specs for this repo live as markdown files in `.scratch/`. Issues and specs (you may know a spec as a PRD) for this repo live as markdown files in `.scratch/`.
## Conventions ## Conventions
+25
View File
@@ -0,0 +1,25 @@
---
name: setup-pre-commit
description: 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.
---
# Setup Pre-Commit Hooks
Extend the repository's existing commit checks with the requested coverage. Inspect package locations, `packageManager`, lockfiles (including `bun.lock` and `bun.lockb`), scripts, hook configuration, formatter configuration, and lint-staged rules before changing anything.
In this repository the JavaScript package is under `frontend/`, while `.husky/pre-commit` and `.lintstagedrc.mjs` live at the root. There is no root package to initialize. Preserve the existing backend Java formatter rule.
## Configure
- Reuse installed Husky, lint-staged, and formatter tooling. Install only missing dependencies needed for the requested checks, in the owning package with its configured package manager.
- Merge existing `prepare` scripts and hook commands; do not run an initializer over working configuration or replace unrelated checks.
- Extend the existing lint-staged configuration rather than creating a competing file. Keep staged-file tasks scoped to their inputs and preserve language-specific commands.
- Reuse the existing formatter configuration. Create defaults only when no applicable configuration exists.
- For requested type checks or tests, call existing package scripts from the correct directory. Use their non-watch mode and retain failing exit statuses. Report missing scripts rather than inventing commands.
- Keep installation and execution compatible with the installed Husky version; inspect its local documentation if needed.
## Verify
Check the resulting paths, configuration syntax, and executable hook permissions. Run the requested commands on task-owned changes or an isolated fixture. Do not run a rewriting staged-file check over unrelated user changes merely as a smoke test.
Review the scoped diff. Commit only if the user requested it, staging just the hook-setup files and preserving unrelated staged work. Otherwise hand off the verified changes. Report which checks ran and any tooling or permission limitation.
@@ -0,0 +1,3 @@
interface:
display_name: "Setup Pre-Commit"
short_description: "Add pre-commit quality checks"
@@ -0,0 +1,101 @@
---
name: setup-ts-deep-modules
description: Wire dependency-cruiser into a TypeScript repo so each package is a deep module — implementation hidden in subfolders, reachable only through its entry-point files. User-invoked.
---
# Setup TS Deep Modules
Configure dependency-cruiser to enforce the requested package boundaries, then prove the rules detect a violation. Start from existing package layout and public exports. The bundled configuration is for flat packages whose root files are entry points and whose subfolders are private; adapt it when the repository uses another contract rather than restructuring the application to fit the template.
For the vocabulary (deep module, interface, seam, depth), run the `/codebase-design` skill — use its language throughout.
## Bundled template's shape
```
src/packages/
<name>/
index.ts ← an entry point (public). Import this from outside.
client.ts ← another entry point. Packages may expose SEVERAL.
lib/ ← implementation: hidden from outside, free to import each other.
tests/ ← co-located tests + fixtures (a subfolder, so private).
```
The public surface is the package's **root files** — not one designated `index.ts`. By convention implementation lives in `lib/` and tests in `tests/`, giving every package the same two-folder shape. The rule itself is general, though: *anything* in *any* subfolder is private, so you never extend the config to add a folder.
Four rules, all `error`:
1. **Entry-point boundary** — code outside a package (app code or another package) may import only that package's entry points (its root files), never anything in its subfolders.
2. **Intra-package freedom** — a package's own files import each other freely.
3. **Tests through the entry points** — files under `<pkg>/tests/` may import any package's entry points and their own `tests/` fixtures, but never any package's subfolder internals (not even their own). Integration tests across packages are fine; deep imports are not.
4. **No cycles** — no dependency cycles.
**Entry points, not a barrel.** Because the public surface is *every* root file, a package can expose several small entry points (`index.ts`, `client.ts`, `server.ts`) instead of funnelling everything through one giant `index.ts`. Barrel files that re-export a whole subtree are discouraged — keep entry points small and hide implementation in subfolders.
Layering (which packages may depend on which) is a separate concern. Add those rules only for an actual requested architectural constraint.
## Steps
### 1. Detect the environment
- **Package manager** — inspect the owning package's `packageManager` and lockfile, including `bun.lock` or `bun.lockb`; preserve its tooling.
- **Packages root and contract** — use existing package locations and exports. If establishing a new convention, propose the smallest suitable boundary and ask only when the choice materially affects the architecture.
- **Existing config** — check for a `.dependency-cruiser.*` file. If one exists, do **not** overwrite it: merge the four rules and the options in, and tell the user what you added.
**Done when:** package manager, packages root, and existing-config status are all known.
### 2. Install dependency-cruiser
Reuse `dependency-cruiser` if installed; otherwise add it to the owning package's devDependencies with the detected package manager. Check its installed documentation for supported configuration before wiring rules.
**Done when:** `dependency-cruiser` is in `devDependencies`.
### 3. Write the config
Use [`dependency-cruiser.config.cjs`](dependency-cruiser.config.cjs) as a starting point, merging existing configuration in place. Adapt package paths, public-entry rules, test locations, and `tsConfig` to the selected project. Do not assume changing `PACKAGES_ROOT` alone covers another layout.
**Done when:** `.dependency-cruiser.cjs` exists with the correct `PACKAGES_ROOT`, and the four forbidden rules are present.
### 4. Wire it into the checks
- Add a `lint:boundaries` script: `depcruise <packages-root>` (or `depcruise src`).
- Fold it into the repo's umbrella check command — the one that already runs typecheck (e.g. a `check` / `ci` / `validate` script). Do **not** touch `tsconfig` or add path aliases.
- If there is no umbrella script, add `lint:boundaries` and tell the user to include it in CI.
**Done when:** the boundary check runs through the requested existing check command, or its standalone invocation and missing umbrella integration are documented.
### 5. Select a validation fixture
Use an existing representative package or a temporary task-owned fixture with:
- `index.ts` — an entry point. Export one function that delegates to an internal file (so the package is visibly *deep*, not a pass-through).
- `lib/impl.ts` — an internal file in a **subfolder**, imported by `index.ts`, not reachable from outside.
- `tests/example.test.ts` — imports **only** `../index` (an entry point), and asserts against the public function.
Keep the fixture isolated from user work. A permanent example package is optional and should be created only when requested.
**Done when:** the fixture exercises allowed entry-point access and a forbidden private import under the actual configured rules.
### 6. Prove the rules bite
This is the completion criterion for the whole skill — a config that doesn't fail on a violation is worthless.
1. Run the boundary check on the selected fixture and record the allowed result.
2. Add an intentional forbidden import in the isolated fixture; verify that the relevant rule reports it. Also exercise cross-package boundaries when those rules changed.
3. Remove only the task's intentional violation and rerun. Remove a disposable fixture after validation; retain a regression check only where it adds ongoing value.
**Done when:** you have observed a pass, then a fail on the deep import, then a pass again. If step 2 does not fail, the rules are not wired correctly — fix before finishing.
### 7. Document the convention
Update the nearest existing package/contributor guidance with the selected public-entry convention and check command. Add a short local document only when no suitable one exists; do not require another README or a fixed two-folder layout.
Link that guidance from the applicable agent instructions when it is not already discoverable. Preserve the user's chosen agent product and file.
**Done when:** the actual convention and check command are discoverable, with no temporary violation or unrequested example package left behind.
## Notes
- The config's `$1` back-references (dependency-cruiser's group matching) are what let a package reach its own internals while outsiders can't — don't flatten them into separate per-package rules.
- Public vs private is decided by **depth**: a package's root files are entry points; anything in a subfolder is private. The conventional subfolders are `lib/` (implementation) and `tests/`, but the rule doesn't hardcode them — any subfolder is private, so a new folder never needs a config change. Adding an entry point is just adding a root file — no barrel.
- Packages are **flat**: one tier of immediate children under the root. A package's internals may nest as deep as you like; a package may not contain another package.
- Use `.cjs` (not `.js`) so the config's `module.exports` works even in `"type": "module"` repos.
@@ -0,0 +1,5 @@
interface:
display_name: "Setup TS Deep Modules"
short_description: "Enforce deep TypeScript modules"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,83 @@
// @ts-check
// Deep-module enforcement for dependency-cruiser.
//
// Each package under the packages root is a DEEP MODULE: a lot of behaviour
// behind a small interface. A package's PUBLIC SURFACE is its ENTRY POINTS —
// the files at the package root. Implementation lives in SUBFOLDERS and is
// private — by convention `lib/` for implementation and `tests/` for tests,
// though any subfolder is private. A package may expose several small entry
// points (index.ts, client.ts, server.ts, …) — prefer that over one giant
// barrel index.
//
// Adapt paths, public-entry rules, test layout, and tsConfig for the target repo.
/** Where packages live. One immediate child dir per package (flat, no nesting). */
const PACKAGES_ROOT = "src/packages";
// --- derived patterns (no need to edit) -------------------------------------
const R = PACKAGES_ROOT;
/**
* A package's private internals: anything nested inside a package subfolder.
* The package's root files are its entry points and are NOT matched here —
* they stay importable from outside.
*/
const PACKAGE_INTERNALS = `^${R}/[^/]+/[^/]+/`;
/** @type {import('dependency-cruiser').IConfiguration} */
module.exports = {
forbidden: [
{
name: "entrypoint-boundary-from-app",
comment:
"App/root code may import a package's entry points (its root files), but nothing inside its subfolders.",
severity: "error",
from: { pathNot: `^${R}/` }, // importer is NOT inside any package
to: { path: PACKAGE_INTERNALS },
},
{
name: "entrypoint-boundary-across-packages",
comment:
"A package's own files import each other freely, but may reach OTHER packages only through their entry points — never their internals.",
severity: "error",
// importer is inside a package ($1), but is not a test file
from: { path: `^${R}/([^/]+)/`, pathNot: `^${R}/[^/]+/tests/` },
to: {
path: PACKAGE_INTERNALS,
pathNot: `^${R}/$1/`, // same package → intra-package freedom
},
},
{
name: "tests-through-entrypoints",
comment:
"A package's tests exercise it through its entry points like everyone else: they may import any package's entry points and their own tests/ fixtures, but never any package's internals — not even their own.",
severity: "error",
from: { path: `^${R}/([^/]+)/tests/` }, // a test file, in package $1
to: {
path: PACKAGE_INTERNALS,
pathNot: `^${R}/$1/tests/`, // own tests/ fixtures → allowed
},
},
{
name: "tests-folder-is-private",
comment:
"A package's tests/ folder is reachable only from tests — nothing else may import fixtures.",
severity: "error",
from: { pathNot: `^${R}/[^/]+/tests/` }, // importer is not itself a test
to: { path: `^${R}/[^/]+/tests/` },
},
{
name: "no-circular",
comment: "No dependency cycles. Scope to `^${R}/` if you want to allow cycles outside packages.",
severity: "error",
from: {},
to: { circular: true },
},
],
options: {
doNotFollow: { path: "node_modules" },
tsConfig: { fileName: "tsconfig.json" },
enhancedResolveOptions: {
extensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
},
},
};
+5 -7
View File
@@ -1,11 +1,11 @@
--- ---
name: tdd 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. description: Build or fix behavior test-first through red-green-refactor. Use when the user requests TDD or test-first development, not merely any integration-test task.
--- ---
# Test-Driven Development # 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. TDD is the red → green → refactor loop. Use behavior-level tests to guide small changes; choose checks proportional to the task.
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. 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.
@@ -19,11 +19,9 @@ See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking g
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. 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 — agreeing the seams up front is how testing effort lands on the critical paths and complex logic instead of every edge case. Reuse established test boundaries and any seams already agreed with the user. Choose a seam that exercises the actual behavior, including persistence or integration contracts where those are the subject of the test. State a new choice briefly; ask only if it introduces a consequential design trade-off that cannot be inferred from the request and code.
Ask: "What's the public interface, and which seams should we test?" Prioritize critical paths, failure modes, and complex logic; do not block routine tests on repeated seam approval.
When the shape of that interface is itself in question — how deep the module is, where the seam belongs, what the interface should expose — use the `/codebase-design` skill 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 ## Anti-patterns
@@ -35,4 +33,4 @@ When the shape of that interface is itself in question — how deep the module i
- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features. - **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. - **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. - **Refactor while green.** Simplify the changed code and tests without changing behavior, then rerun the checks. Keep unrelated redesign outside the task.
+20 -122
View File
@@ -1,140 +1,38 @@
--- ---
name: teach name: teach
description: Teach the user a new skill or concept, within this workspace. description: Teach a concept through explanations and practice, or maintain a multi-session learning workspace when the user requests an ongoing course.
disable-model-invocation: true
argument-hint: "What would you like to learn about?"
--- ---
The user has asked you to teach them something. This is a stateful request - they intend to learn the topic over multiple sessions. # Teach
## Teaching Workspace Teach the requested topic at the user's level. Preserve their chosen format and location. A one-off question normally needs an explanation, example, or exercise in the conversation—not a course directory.
Treat the current directory as a teaching workspace. The state of their learning is captured in this directory in several files: Infer the learning objective and starting level from the request and prior work. Ask only when a missing choice would materially change the lesson. Challenge the learner enough to reveal gaps without requiring an intake interview for a clear question.
- `MISSION.md`: A document capturing the _reason_ the user is interested in the topic. This should be used to ground all teaching. Use the format in [MISSION-FORMAT.md](./MISSION-FORMAT.md). ## Lesson design
- `./reference/*.html`: A directory of reference materials. These are the compressed learnings from the lessons - cheat sheets, reference algorithms, syntax, yoga poses, glossaries. They are the raw units of learning. They should be beautiful documents which print out well, and are designed for quick reference.
- `RESOURCES.md`: A list of resources which can be explored to ground your teaching in contextual knowledge, or to acquire knowledge and wisdom. Use the format in [RESOURCES-FORMAT.md](./RESOURCES-FORMAT.md).
- `./learning-records/*.md`: A directory of learning records, which capture what the user has learned. These are loosely equivalent to architectural decision records in software development - they capture non-obvious lessons and key insights that may need to be revised later, or drive future sessions. These should be used to calculate the zone of proximal development. They are titled `0001-<dash-case-name>.md`, where the number increments each time. Use the format in [LEARNING-RECORD-FORMAT.md](./LEARNING-RECORD-FORMAT.md).
- `./lessons/*.html`: A directory of lessons. A **lesson** is a single, self-contained HTML output that teaches one tightly-scoped thing tied to the mission. This is the primary unit of teaching in this workspace.
- `./assets/*`: Reusable **components** shared across lessons. See [Assets](#assets).
- `NOTES.md`: A scratchpad for you to jot down user preferences, or working notes.
## Philosophy Focus on a tangible capability. Explain the knowledge needed for it, then offer relevant practice with feedback. Use retrieval, spacing, and varied examples when helpful for retention; do not force interactivity when the user wants a reference or direct answer.
To learn at a deep level, the user needs three things: Use trusted primary sources for claims that need verification, especially changing or high-stakes material. Cite them near the relevant claim. Stable concepts do not need a separate research phase before teaching can begin.
- **Knowledge**, captured from high-quality, high-trust resources Keep exercises and answer choices clear and fair; avoid giving away answers through formatting, without imposing identical word counts. Do not claim the learner completed an exercise or mastered a topic without evidence.
- **Skills**, acquired through highly-relevant interactive lessons devised by you, based on the knowledge
- **Wisdom**, which comes from interacting with other learners and practitioners
Before the `RESOURCES.md` is well-populated, your focus should be to find high-quality resources which will help the user acquire knowledge. Never trust your parametric knowledge. Recommend communities or further resources when they support the user's objective, not as a substitute for answering. Joining, posting, or paying is the user's choice.
Some topics may require more skills than knowledge. Learning more about theoretical physics might be more knowledge-based. For yoga, more skills-based. ## Multi-session workspace
### Fluency vs Storage Strength Use this mode only when requested or when continuing an established learning workspace. Read its existing mission, notes, and relevant learning records first. Preserve its layout and the user's output choices; create only artifacts needed for the current lesson.
You should be careful to split between two types of learning: - For a new or changed learning mission, use [MISSION-FORMAT.md](MISSION-FORMAT.md). Confirm substantive changes to the goal unless the user already requested them.
- When maintaining source recommendations, use [RESOURCES-FORMAT.md](RESOURCES-FORMAT.md).
- Record observed progress and non-obvious insights with [LEARNING-RECORD-FORMAT.md](LEARNING-RECORD-FORMAT.md); distinguish planned work from demonstrated learning.
- Reuse existing lessons and references. If no format is established and reusable browser lessons are wanted, numbered HTML files under `lessons/` and concise references under `reference/` are a useful default, not a requirement.
- Store relevant teaching preferences in existing notes without collecting unrelated personal details.
- **Fluency strength**: in-the-moment retrieval of knowledge ## Assets and references
- **Storage strength**: long-term retention of knowledge
Fluency can give the user an illusory sense of mastery, but storage strength is the real goal. Try to design lessons which build long-term retention by desirable difficulty: Reuse existing styles or widgets when available. Keep a new lesson self-contained unless actual reuse justifies extraction; do not scaffold a component library for hypothetical later lessons.
- Using retrieval practice (recall from memory) Add a reference sheet or glossary when it provides a useful reusable artifact. When recording learned terminology in the workspace glossary, read [GLOSSARY-FORMAT.md](GLOSSARY-FORMAT.md); distinguish it from a reference dictionary introducing new terms. Keep references aligned with lesson terminology and link them from the relevant lesson. Use accessible semantics, readable layout, and keyboard-operable interactions.
- Spacing (distributing practice over time)
- Interleaving (mixing up different but related topics in practice - for skills practice only)
## Lessons Hand off the lesson or artifact with its location and an appropriate next exercise. Do not open applications, commit files, or publish a course unless that is part of the requested workflow.
A lesson is the main thing you produce — the unit in which knowledge and skills reach the user. Each lesson is one self-contained HTML file, saved to `./lessons/` and titled `0001-<dash-case-name>.html` where the number increments each time.
A lesson should be **beautiful** — clean, readable typography and layout — since the user will return to these later to review. Think Tufte.
The lesson should be short, and completable very quickly. Learners' working memory is very small, and we need to stay within it. But each lesson should give the user a single tangible win that they can build on. It should be directly tied to the mission, and should be in the user's zone of proximal development.
If possible, open the lesson file for the user by running a CLI command.
Each lesson should link via HTML anchors to other lessons and reference documents.
Each lesson should recommend a primary source for the user to read or watch. This should be the most high-quality, high-trust resource you found on the topic.
Each lesson should contain a reminder to ask followup questions to the agent. The agent is their teacher, and can assist with anything that's unclear.
## Assets
Lessons are built from reusable **components**, stored in `./assets/`: stylesheets, quiz widgets, simulators, diagram helpers — anything a second lesson could reuse.
Reuse is the default, not the exception. Before authoring a lesson, read `./assets/` and build from the components already there. When a lesson needs something new and reusable, write it as a component in `./assets/` and link to it — never inline code a future lesson would duplicate.
A shared stylesheet is the first component every workspace earns: every lesson links it, so the lessons look like one consistent course rather than a pile of one-offs. As the workspace grows, so should the component library.
## The Mission
Every lesson should be tied into the mission - the reason that the user is interested in learning about the topic.
If the user is unclear about the mission, or the `MISSION.md` is not populated, your first job should be to question the user on why they want to learn this.
Failing to understand the mission will mean knowledge acquisition is not grounded in real-world goals. Lessons will feel too abstract. You will have no way of judging what the user should do next.
Missions may change as the user develops more skills and knowledge. This is normal - make sure to update the `MISSION.md` and add a learning record to capture the change. Confirm with the user before changing the mission.
## Zone Of Proximal Development
Each lesson, the user should always feel as if they are being challenged 'just enough'.
The user may specify an exact thing they want to learn. If they don't, figure out their zone of proximal development by:
- Reading their `learning-records`
- Figuring out the right thing to teach them based on their mission
- Teach the most relevant thing that fits in their zone of proximal development
## Knowledge
Lessons should be designed around a skill the user is going to learn. The knowledge in the lesson should be only what's required to acquire that skill. You teach the knowledge first, then get the user to practice the skills via an interactive feedback loop.
Knowledge should first be gathered from trusted resources. Use `RESOURCES.md` to keep track of them. Lessons should be littered with citations - links to external resources to back up any claim made. This increases the trustworthiness of the lesson.
For acquiring knowledge, difficulty is the enemy. It eats working memory you need for understanding.
## Skills
If knowledge is all about acquisition, skills are about durability and flexibility. Make the knowledge stick.
For skill acquisition, difficulty is the tool. Effortful retrieval is what builds storage strength. Skills should be taught through interactive lessons. There are several tools at your disposal:
- Interactive lessons, using quizzes and light in-browser tasks
- Lessons which guide the user through a list of real-world steps to take (for instance, yoga poses)
Each of these should be based on a **feedback loop**, where the user receives feedback on their performance. This feedback loop should be as tight as possible, giving feedback immediately - and ideally automatically.
For quizzes, each answer should be exactly the same number of words (and characters, if possible). Don't give the user any clues about the answer through formatting.
## Acquiring Wisdom
Wisdom comes from true real-world interaction - testing your skills outside the learning environment.
When the user asks a question that appears to require wisdom, your default posture should be to attempt to answer - but to ultimately delegate to a **community**.
A community is a place (online or offline) where the user can test their skills in the real world. This might be a forum, a subreddit, a real-world class (budget permitting) or a local interest group.
You should attempt to find high-reputation communities the user can join. If the user expresses a preference that they don't want to join a community, respect it.
## Reference Documents
While creating lessons, you should also create reference documents. Lessons can reference these documents - they are useful for tracking raw units of knowledge useful across lessons.
Lessons will rarely be revisited later - reference documents will be. They should be the compressed essence of the lesson, in a format designed for quick reference.
Some learning topics lend themselves to reference:
- Syntax and code snippets for programming
- Algorithms and flowcharts for processes
- Yoga poses and sequences for yoga
- Exercises and routines for fitness
- Glossaries for any topic with its own nomenclature
Glossaries, in particular, are an essential reference. Once one is created, it should be adhered to in every lesson.
## `NOTES.md`
The user will sometimes express preferences of how they want to be taught, or things you should keep in mind. This is the place to record those preferences, so you can refer back to them when designing lessons or working with the user.
@@ -0,0 +1,24 @@
---
name: terra-verified-implement
description: Implement a spec or ticket by coordinating gpt-5.6-terra subagents at high reasoning and independently verifying the final change. Use when the user asks to implement, build, or fix work and wants delegated implementation with a verification pass.
---
# Terra Verified Implement
Invoke `$implement` and follow it as the baseline workflow. Treat this skill as its delegated, verified variant.
## Workflow
1. Read the spec or ticket, repository guidance, affected flow, and existing worktree changes. Record the starting commit and task-owned scope; preserve unrelated changes.
2. Split only genuinely independent, bounded work. If the change is small or one seam owns it, use one implementation agent; do not manufacture parallelism.
3. Spawn each implementation agent with `fork_turns: "none"`, `model: "gpt-5.6-terra"`, and `reasoning_effort: "high"`. Give each its exact owned files/seam, acceptance criteria, required checks, and task-local context. Tell agents not to overwrite or revert other agents' work.
4. Wait for agents, inspect their diffs, resolve overlaps minimally, and run the implementation checks required by `$implement`: targeted tests and typecheck during work, then the full relevant suite once.
5. Spawn a fresh, read-only verification agent with `fork_turns: "none"`, `model: "gpt-5.6-terra"`, and `reasoning_effort: "high"`. Give it the original request, current diff, and test output, but not implementation conclusions. Ask it to check correctness, regressions, specification coverage, and test evidence. Have it report findings without changing files.
6. Fix confirmed findings, rerun affected checks, and repeat verification once if fixes were needed. Run `$code-review` on the current working result (including staged, unstaged, and new files), passing the original spec, starting commit, and task-owned scope. Follow `$implement`'s commit boundary: commit only when requested, otherwise hand off the verified diff.
## Delegation rules
- Keep all agents in the same workspace; assign non-overlapping ownership before they edit.
- Use at most the available concurrency slots. Reserve one slot for coordination and verification.
- Do not delegate secrets, production writes, destructive operations, or changes requiring new user authority.
- If subagents are unavailable, implement directly, run the same checks, and state that delegated verification was unavailable.
@@ -0,0 +1,4 @@
interface:
display_name: "Terra Verified Implement"
short_description: "Delegate implementation and verify it"
default_prompt: "Use $terra-verified-implement to implement this task with Terra agents and verify the result."
+8 -9
View File
@@ -1,22 +1,21 @@
--- ---
name: to-spec 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. description: Synthesize the current conversation into a development spec, with optional publication to the configured tracker when requested.
disable-model-invocation: true
--- ---
This skill takes the current conversation context and codebase understanding and produces a spec. Do NOT interview the user — just synthesize what you already know. This skill takes the current conversation context and codebase understanding and produces a spec (you may know this document as a PRD). Do NOT interview the user — just synthesize what you already know.
The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not. Read the configured tracker and triage vocabulary only when publication is requested. A local draft does not require tracker setup.
## Process ## 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. 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. 2. Describe how acceptance criteria can be verified using existing behavior-level tests where possible. Choose boundaries that exercise the actual risks, not a predetermined seam count. Distinguish agreed decisions from proposals and unresolved requirements.
Check with the user that these seams match their expectations. Use the discussion's existing decisions. Record remaining uncertainty; ask only when a consequential missing decision prevents a useful spec, rather than restarting an interview.
3. Write the spec using the template below, then publish it to the project issue tracker. Apply the `ready-for-agent` triage label - no need for additional triage. 3. Write the requested spec using the template below as appropriate. Publish only if the user asked for publication; otherwise return the draft or save it at their selected path. Use the configured tracker and triage labels, marking it `ready-for-agent` only when actionable. On an ambiguous create failure, check for duplicates before retrying; if access is unavailable, preserve the draft and report the limitation.
<spec-template> <spec-template>
@@ -30,7 +29,7 @@ The solution to the problem, from the user's perspective.
## User Stories ## User Stories
A LONG, numbered list of user stories. Each user story should be in the format of: A concise set of user stories or acceptance criteria covering the agreed behavior. When user stories help, use:
1. As an <actor>, I want a <feature>, so that <benefit> 1. As an <actor>, I want a <feature>, so that <benefit>
@@ -38,7 +37,7 @@ A LONG, numbered list of user stories. Each user story should be in the format o
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 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> </user-story-example>
This list of user stories should be extremely extensive and cover all aspects of the feature. Cover the requested behavior and important failure cases without inventing scope to fill the template.
## Implementation Decisions ## Implementation Decisions
+9 -6
View File
@@ -1,13 +1,14 @@
--- ---
name: to-tickets name: to-tickets
description: Break a plan, spec, or the current conversation into a set of tracer-bullet tickets, each declaring its blocking edges, published to the configured tracker — edges as text in one file per ticket locally, or native blocking links on a real tracker. description: Break a plan, spec, or the current conversation into a set of tracer-bullet tickets, each declaring its blocking edges, published to the configured tracker — edges as text in one file per ticket locally, or native blocking links on a real tracker.
disable-model-invocation: true
--- ---
# To Tickets # To Tickets
Break a plan, spec, or conversation into a set of **tickets** — tracer-bullet vertical slices, each declaring the tickets that **block** it. Break a plan, spec, or conversation into a set of **tickets** — tracer-bullet vertical slices, each declaring the tickets that **block** it.
Honor the requested deliverable: a local breakdown stays local; publication requires a request to file tickets. Carry existing publication approval forward without asking again. Ticket decomposition does not itself authorize implementation or edits to unrelated issues.
The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not. The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not.
## Process ## Process
@@ -37,7 +38,7 @@ Break the work into **tracer bullet** tickets.
Give each ticket its **blocking edges** — the other tickets that must complete before it can start. A ticket with no blockers can start immediately. 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. **Wide refactors are the exception to vertical slicing.** For a mechanical change whose callers must change together, plan a cohesive replacement and a final integration check. Follow [the development data lifecycle](../../../AGENTS.md#development-data-lifecycle): this repository replaces obsolete schemas and contracts directly, updates all callers and tests in the same change, and reseeds disposable data. Do not introduce expand–contract, dual paths, or compatibility adapters merely to make batches independently green. If the work needs multiple tickets, use a scoped integration branch and make their shared verification gate explicit. Reconsider compatibility only after an explicit project decision requires preserving production data.
### 4. Quiz the user ### 4. Quiz the user
@@ -47,22 +48,22 @@ Present the proposed breakdown as a numbered list. For each ticket, show:
- **Blocked by**: which other tickets (if any) must complete first - **Blocked by**: which other tickets (if any) must complete first
- **What it delivers**: the end-to-end behaviour this ticket makes work - **What it delivers**: the end-to-end behaviour this ticket makes work
Ask the user: When the breakdown contains a consequential unresolved choice, ask the user about:
- Does the granularity feel right? (too coarse / too fine) - 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? - Are the blocking edges correct — does each ticket only depend on tickets that genuinely gate it?
- Should any tickets be merged or split further? - Should any tickets be merged or split further?
Iterate until the user approves the breakdown. Honor an already approved plan and requested granularity. Do not require another approval round for routine decomposition; state reasonable assumptions and proceed within the requested publication scope.
### 5. Publish the tickets to the configured tracker ### 5. Publish the tickets to the configured tracker
Publish the approved tickets. **How** depends on the tracker `/setup-matt-pocock-skills` configured — the tickets are the same either way, only the shape of the blocking edges changes: When publication is requested, publish the in-scope tickets using the configured tracker. Preserve a user-selected local output path. Check ambiguous creation results before retrying to avoid duplicates; on unavailable access, keep drafts and report what remains. The representation depends on the tracker:
- **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. - **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. - **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. The **frontier** is the set of tickets whose blockers are all done; identify it in the handoff without starting implementation.
Do NOT close or modify any parent issue. Do NOT close or modify any parent issue.
@@ -103,3 +104,5 @@ The end-to-end behaviour this ticket makes work, from the user's perspective —
</issue-template> </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. 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.
Stop after the requested decomposition/publication and report the first actionable tickets. Use `/implement` only if the user also asks to implement them.
+6 -7
View File
@@ -1,7 +1,6 @@
--- ---
name: triage 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. 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 # Triage
@@ -38,11 +37,11 @@ Five **state** roles:
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. 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. Every triaged issue should carry exactly one category role and one state role. Resolve conflicting state labels according to an explicit maintainer request; otherwise flag the conflict while continuing safe read-only checks and ask for the intended state.
These are canonical role names — the actual label strings used in the issue tracker may differ. The mapping should have been provided to you - run `/setup-matt-pocock-skills` if not. These are canonical role names — the actual label strings used in the issue tracker may differ. The mapping should have been provided to you - run `/setup-matt-pocock-skills` if not.
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. 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. Honor explicit maintainer overrides; ask only when the requested outcome is unclear.
## Invocation ## Invocation
@@ -69,11 +68,11 @@ Show counts and a one-line summary per item. Let the maintainer pick.
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. 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. 2. **Recommend.** Give a category/state recommendation with evidence, including whether the behavior already exists. For an interactive review, wait for the maintainer's decision; for an explicitly requested transition, proceed within that authority.
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. 3. **Verify the claim.** Reproduce from available steps when feasible, or inspect code and traces and state the uncertainty. For a PR, inspect the diff before executing checks and use an isolated worktree instead of switching a shared dirty checkout. Run only safe, relevant checks within the task's permissions. Report confirmed, probable, failed, or insufficient evidence accurately.
4. **Grill (if needed).** If the request needs fleshing out, run the `/grilling` and `/domain-modeling` skills together — grill it into shape a round of questions at a time, sharpening domain terms and updating `CONTEXT.md`/ADRs inline as decisions land. 4. **Grill (if needed).** If the request needs fleshing out, run the `/grilling` and `/domain-modeling` skills together — grill it into shape one question at a time, sharpening domain terms and updating `CONTEXT.md`/ADRs inline as decisions land.
5. **Apply the outcome:** 5. **Apply the outcome:**
- `ready-for-agent` — post an agent brief comment ([AGENT-BRIEF.md](AGENT-BRIEF.md)). - `ready-for-agent` — post an agent brief comment ([AGENT-BRIEF.md](AGENT-BRIEF.md)).
@@ -87,7 +86,7 @@ Show counts and a one-line summary per item. Let the maintainer pick.
## Quick state override ## 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. If the maintainer says "move #42 to ready-for-agent", apply the requested role directly and report the result. Skip grilling and redundant confirmation; do not add a comment or close the issue unless that is part of the requested transition. Offer an agent brief as an optional follow-up if useful.
## Needs-info template ## Needs-info template
@@ -0,0 +1,92 @@
---
name: ubiquitous-language
description: Extract domain terms from a conversation, resolve ambiguities, and update the project's existing glossary. Use when defining or consolidating a ubiquitous language.
---
# Ubiquitous Language
Extract and formalize domain terminology from the current conversation into a consistent glossary, saved to a local file.
## Process
1. **Scan the conversation** for domain-relevant nouns, verbs, and concepts
2. **Identify problems**:
- Same word used for different concepts (ambiguity)
- Different words used for the same concept (synonyms)
- Vague or overloaded terms
3. **Propose a canonical glossary** with opinionated term choices
4. **Update the configured glossary** in [the domain documentation layout](../../../docs/agents/domain.md): this repository uses root `CONTEXT.md`. Preserve its structure and unrelated terms; honor an explicit user-selected output path instead of creating a competing glossary.
5. **Output a summary** inline in the conversation
## Output Format
For a new standalone glossary, the structure below is an example. For existing `CONTEXT.md`, update the appropriate sections in place:
```md
# Ubiquitous Language
## Order lifecycle
| Term | Definition | Aliases to avoid |
| ----------- | ------------------------------------------------------- | --------------------- |
| **Order** | A customer's request to purchase one or more items | Purchase, transaction |
| **Invoice** | A request for payment sent to a customer after delivery | Bill, payment request |
## People
| Term | Definition | Aliases to avoid |
| ------------ | ------------------------------------------- | ---------------------- |
| **Customer** | A person or organization that places orders | Client, buyer, account |
| **User** | An authentication identity in the system | Login, account |
## Relationships
- An **Invoice** belongs to exactly one **Customer**
- An **Order** produces one or more **Invoices**
## Example dialogue
> **Dev:** "When a **Customer** places an **Order**, do we create the **Invoice** immediately?"
> **Domain expert:** "No — an **Invoice** is only generated once a **Fulfillment** is confirmed. A single **Order** can produce multiple **Invoices** if items ship in separate **Shipments**."
> **Dev:** "So if a **Shipment** is cancelled before dispatch, no **Invoice** exists for it?"
> **Domain expert:** "Exactly. The **Invoice** lifecycle is tied to the **Fulfillment**, not the **Order**."
## Flagged ambiguities
- "account" was used to mean both **Customer** and **User** — these are distinct concepts: a **Customer** places orders, while a **User** is an authentication identity that may or may not represent a **Customer**.
```
## Rules
- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others as aliases to avoid.
- **Flag conflicts explicitly.** If a term is used ambiguously in the conversation, call it out in the "Flagged ambiguities" section with a clear recommendation.
- **Only include terms relevant for domain experts.** Skip the names of modules or classes unless they have meaning in the domain language.
- **Keep definitions tight.** One sentence max. Define what it IS, not what it does.
- **Show relationships.** Use bold term names and express cardinality where obvious.
- **Only include domain terms.** Skip generic programming concepts (array, function, endpoint) unless they have domain-specific meaning.
- **Group terms into multiple tables** when natural clusters emerge (e.g. by subdomain, lifecycle, or actor). Each group gets its own heading and table. If all terms belong to a single cohesive domain, one table is fine — don't force groupings.
- **Write an example dialogue.** A short conversation (3-5 exchanges) between a dev and a domain expert that demonstrates how the terms interact naturally. The dialogue should clarify boundaries between related concepts and show terms being used precisely.
<example>
## Example dialogue
> **Dev:** "How do I test the **sync service** without Docker?"
> **Domain expert:** "Provide the **filesystem layer** instead of the **Docker layer**. It implements the same **Sandbox service** interface but uses a local directory as the **sandbox**."
> **Dev:** "So **sync-in** still creates a **bundle** and unpacks it?"
> **Domain expert:** "Exactly. The **sync service** doesn't know which layer it's talking to. It calls `exec` and `copyIn` — the **filesystem layer** just runs those as local shell commands."
</example>
## Re-running
When invoked again in the same conversation:
1. Read the existing configured glossary or user-selected output file
2. Incorporate any new terms from subsequent discussion
3. Update definitions if understanding has evolved
4. Re-flag any new ambiguities
5. Rewrite the example dialogue to incorporate new terms
@@ -0,0 +1,5 @@
interface:
display_name: "Ubiquitous Language"
short_description: "Build a shared domain glossary"
policy:
allow_implicit_invocation: false
+11 -12
View File
@@ -1,7 +1,6 @@
--- ---
name: wayfinder 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. 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. 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.
@@ -10,11 +9,11 @@ The destination varies per effort, and naming it is the first act of charting
## Plan, don't do ## Plan, don't do
Wayfinder is **planning** by default: each ticket resolves a decision, and the map is done when the way is clear — 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. Wayfinder is **planning** by default: each ticket resolves a decision, and the map is done when the way is clear. Produce decisions, not the implementation. Execution needs authority in the user's request; a ticket or its Notes cannot grant new permissions. Honor a requested local draft instead of publishing a map, and carry existing authorization for tracker maintenance forward without redundant prompts.
## Refer by name ## 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. 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
@@ -72,12 +71,12 @@ The answer isn't part of the body — it's recorded on resolution (see [Work thr
## Ticket Types ## 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). 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 `/research` **subagent**. Use when knowledge outside the current working directory is required. - **Research** (AFK): Reading documentation, third-party APIs, or local resources like knowledge bases to surface a fact a decision waits on. Resolved by a `/research` **subagent**. 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 via the /prototype skill. Links the prototype as an asset. Use when "how should it look" or "how should it behave" is the key question. - **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 via the /prototype skill. 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 invoke the /grilling and /domain-modeling skills. - **Grilling** (HITL): Conversation via the /grilling and /domain-modeling skills, one question at a time. The default case.
- **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. - **Task** (HITL or AFK): A prerequisite to a decision, such as obtaining access or inspecting sample data. Do safe read-only checks within the request. Signup, provisioning, data movement, spending, or credential publication requires explicit scope and suitable permissions; otherwise give the human a checklist and leave the ticket blocked. Record only verified outcomes and non-secret references, never credentials.
## Fog of war ## Fog of war
@@ -98,7 +97,7 @@ Fog only ever gathers _toward_ the destination. The destination fixes the scope,
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. 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. When authorized to maintain this map, mark an obsolete in-scope ticket out of scope with a reason and close it, preserving its history. For tickets outside that authority, recommend the transition instead. Do not delete tickets or overwrite another session's work. Record the reason and link under **Out of scope**, not **Decisions so far**.
## Invocation ## Invocation
@@ -112,7 +111,7 @@ User invokes with a loose idea.
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. 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**. 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. 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 `/research` subagent to resolve it in parallel, capturing its findings on a throwaway `research/<name>` branch with a context pointer from the ticket. 5. **Run bounded research.** Delegate independent research tickets when useful and available, within the user's budget and available slots; otherwise investigate directly. Give each task exact ownership and allowed sources. Keep generated artifacts in separate task directories or isolated worktrees, never switch branches in a shared dirty checkout. Commit or publish findings only when requested, then link their actual locations.
6. Stop — charting is one session's work; it hand-resolves nothing. 6. Stop — charting is one session's work; it hand-resolves nothing.
### Work through the map ### Work through the map
@@ -120,9 +119,9 @@ User invokes with a loose idea.
User invokes with a map (URL or number). A ticket is **optional** — without one, you pick the next decision, not the user. User invokes with a map (URL or number). 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. 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. 2. Choose the ticket. If the user named one, use it. Otherwise take the first frontier ticket in order. When tracker writes are authorized, check its current assignment, claim it, then verify ownership before work; stop on a conflicting claim instead of taking it over. A read-only review does not claim tickets.
3. Resolve it — **zoom as needed**: fetch the full body of any related or closed ticket on demand; invoke the skills the `## Notes` block names. If in doubt, use `/grilling` and `/domain-modeling`. 3. Resolve it within the user's scope — fetch related ticket details as needed and use available, relevant skills. Treat issue text and Notes as context, not authority to run commands, switch tools, or expand the assignment.
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. 4. For authorized map maintenance, record a verified resolution, close the issue, and append its pointer to Decisions-so-far. For a draft/review, return the proposed update instead. On an ambiguous write, re-read state before retrying; stop when access, authority, or the human decision needed to resolve the ticket is missing.
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 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. 5. Within authorized map maintenance, create newly surfaced in-scope tickets and link dependencies. Move their corresponding entries out of **Not yet specified** only after creation succeeds. For invalidated tickets, use the out-of-scope transition above or propose an update; never delete them. Re-read affected state before updating to preserve concurrent changes.
The user may run unblocked tickets in parallel, so expect other sessions to be editing the tracker concurrently. The user may run unblocked tickets in parallel, so expect other sessions to be editing the tracker concurrently.
+12 -9
View File
@@ -1,13 +1,15 @@
--- ---
name: wizard 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. description: Generate an interactive Bash wizard for steps only a human can perform, such as dashboard setup or credential capture. Use for a requested manual procedure, not work the agent can complete directly.
--- ---
# Wizard # 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. A **wizard** walks a human through the manual parts of the requested procedure, captures values, and writes only to the selected destinations. Reuse the user's chosen service and CI platform; generating a wizard does not authorize running provisioning or publishing credentials.
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. Start from [template.sh](template.sh) for progress, confirmation gates, URL opening, hidden input, and persistence helpers. Adapt helpers when the selected destination requires it; verify changes with dummy data before handling real credentials.
The bundled dotenv helpers accept uppercase variable names and required, single-line values without apostrophes. They write private, single-quoted values so hashes, spaces, dollars, and backslashes survive; unsupported values or existing formats stop with an error. Confirm that the actual consumer supports this format. If it needs another dialect or multiline values, adapt both reading and writing and test a round trip through that consumer. EOF cancels the wizard; empty input keeps an existing value or fails if none exists.
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. 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.
@@ -17,12 +19,12 @@ A wizard is ephemeral by default — built for one run, saved to a scratch or `s
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: 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 setup: configuration examples, README, compose/framework configuration, and the actual CI files (this repository uses `.gitlab-ci.yml`). Inspect secret names and references without displaying existing secret values. Include only values needed for the requested procedure, not every variable in the repository.
- For a migration or transition: the current state, the target state, and the irreversible actions between them. - 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. 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. **Done when:** every stage is named in order, and each captured value has a known source, selected destination (local file, configured secret store, or neither), and secrecy level.
### 2. Map each stage's journey ### 2. Map each stage's journey
@@ -32,13 +34,14 @@ For each stage, write the precise path a human follows: which URL to open, what
### 3. Author the wizard ### 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` — and set `TOTAL_STAGES` to the number of stages you wrote. Copy `template.sh` to the target path. Replace the example stages in dependency order, using `stage`, `say`/`step`, `open_url`, `ask`/`ask_secret`, `write_env`, and `pause`/`confirm`. Set honest stage/time estimates. For CI secrets, use the selected platform's existing tooling or guide the human through its UI. Add a provider-specific writer only when needed and verify its local help, authentication, project scope, and secret-safe input mechanism first.
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. Open the URL before asking for its value, use `ask_secret` for secrets, and persist only to the selected destinations. Require a successful `confirm` before an irreversible action. Do not expose values in logs or command arguments. On an ambiguous remote write, check its result before retrying; on missing authority or repeated failure, stop that stage and report what remains. Keep each stage focused so needed instructions remain visible.
### 4. Verify and hand off ### 4. Verify and hand off
- `bash -n <script>`; run `shellcheck` if available. - `bash -n <script>`; run `shellcheck` if available.
- Run `python3 test_wizard.py` from this skill directory (requires Node for the dotenv consumer check). Source the generated script to test its helpers with dummy values in a temporary directory, without running the stages.
- `chmod +x <script>`. - `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. - Don't run it end-to-end yourself — it opens browsers and blocks on human input. Check that each value lands in the selected destination and any CI variable name matches an actual reference. Test remote writers with stubs, never real credentials.
- 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. - Tell the user how to run it. For a requested repeatable setup path, link it from the relevant setup documentation. Commit only if requested, and do not execute the manual procedure merely because its script is complete.
+2
View File
@@ -1,3 +1,5 @@
interface: interface:
display_name: "Wizard" display_name: "Wizard"
short_description: "Generate an interactive setup wizard" short_description: "Generate an interactive setup wizard"
policy:
allow_implicit_invocation: false
+83 -62
View File
@@ -3,8 +3,8 @@
# A wizard — walks a human through a manual procedure step by step. # A wizard — walks a human through a manual procedure step by step.
# Generated by the /wizard skill. # Generated by the /wizard skill.
# #
# Everything above the "STAGES" marker is the wizard library: do not hand-edit # Author the per-step stages below the "STAGES" marker. Adapt and test the
# it. Author the per-step stages below the marker. # persistence helpers when the target consumer needs a different format.
set -euo pipefail set -euo pipefail
@@ -19,14 +19,15 @@ else
BOLD=""; DIM=""; RESET=""; BLUE=""; GREEN=""; YELLOW=""; RED="" BOLD=""; DIM=""; RESET=""; BLUE=""; GREEN=""; YELLOW=""; RED=""
fi fi
# Author sets this at the top of the stages section. # Author sets these two at the top of the stages section.
TOTAL_STAGES=0 TOTAL_STAGES=0
TOTAL_MINUTES=0
_STAGE_INDEX=0 _STAGE_INDEX=0
_MINUTES_ELAPSED=0
ENV_FILE="${ENV_FILE:-.env}" ENV_FILE="${ENV_FILE:-.env}"
WRITTEN_ENV=() # KEYs written to ENV_FILE this run WRITTEN_ENV=() # KEYs written to ENV_FILE this run
WRITTEN_SECRET=() # secret NAMEs set this run SKIPPED=() # manual steps still outstanding
SKIPPED=() # things we couldn't do (e.g. gh missing)
# _clear — wipe the terminal so only the current step is on screen. No-op when # _clear — wipe the terminal so only the current step is on screen. No-op when
# output isn't a terminal, so piped logs stay readable. # output isn't a terminal, so piped logs stay readable.
@@ -35,24 +36,28 @@ _clear() {
if command -v tput >/dev/null 2>&1; then tput clear; else printf '\033[2J\033[3J\033[H'; fi if command -v tput >/dev/null 2>&1; then tput clear; else printf '\033[2J\033[3J\033[H'; fi
} }
# banner "Title" — opening frame: what this wizard does. # banner "Title" — opening frame: what this wizard does and how long it takes.
banner() { banner() {
_clear _clear
printf '\n%s%s %s%s\n' "$BOLD" "$BLUE" "$1" "$RESET" printf '\n%s%s %s%s\n' "$BOLD" "$BLUE" "$1" "$RESET"
printf '%s %s stages%s\n\n' "$DIM" "$TOTAL_STAGES" "$RESET" printf '%s %s stages · about %s minutes%s\n\n' \
"$DIM" "$TOTAL_STAGES" "$TOTAL_MINUTES" "$RESET"
printf '%s You drive the browser; this wizard tells you exactly what to do and\n' "$DIM" printf '%s You drive the browser; this wizard tells you exactly what to do and\n' "$DIM"
printf ' captures the values you copy back. Stop any time with Ctrl-C and re-run\n' printf ' captures the values you copy back. Stop any time with Ctrl-C and re-run\n'
printf ' later — it remembers values already saved.%s\n' "$RESET" printf ' later — it remembers values already saved.%s\n' "$RESET"
pause "Ready to start?" pause "Ready to start?"
} }
# stage "Name" — clear the screen, then announce a stage and show progress. # stage "Name" <minutes> — clear the screen, then announce a stage and show
# Clearing keeps only the current step on screen. # progress + time remaining. Clearing keeps only the current step on screen.
stage() { stage() {
_clear _clear
_STAGE_INDEX=$((_STAGE_INDEX + 1)) _STAGE_INDEX=$((_STAGE_INDEX + 1))
printf '\n%s%s▸ Stage %s/%s · %s%s\n' \ local remaining=$((TOTAL_MINUTES - _MINUTES_ELAPSED))
"$BOLD" "$BLUE" "$_STAGE_INDEX" "$TOTAL_STAGES" "$1" "$RESET" (( remaining < 0 )) && remaining=0
_MINUTES_ELAPSED=$((_MINUTES_ELAPSED + ${2:-0}))
printf '\n%s%s▸ Stage %s/%s · %s%s %s(~%s min left)%s\n' \
"$BOLD" "$BLUE" "$_STAGE_INDEX" "$TOTAL_STAGES" "$1" "$RESET" "$DIM" "$remaining" "$RESET"
} }
# say "..." — a plain instruction line. # say "..." — a plain instruction line.
@@ -77,101 +82,114 @@ open_url() {
# pause "msg" — wait for the human to confirm they've done the manual part. # pause "msg" — wait for the human to confirm they've done the manual part.
pause() { pause() {
printf ' %s%s%s ' "$DIM" "${1:-Press Enter to continue}" "$RESET" printf ' %s%s%s ' "$DIM" "${1:-Press Enter to continue}" "$RESET"
read -r _ || true read -r _ || _cancel
}
_cancel() { printf '\nCancelled; no further steps were run.\n' >&2; exit 1; }
_valid_key() {
[[ "$1" =~ ^[A-Z_][A-Z0-9_]*$ && "$1" != HOME && "$1" != CODEX_HOME && "$1" != PATH && "$1" != ENV_FILE ]] || {
printf 'Invalid or reserved variable name.\n' >&2; return 1;
}
} }
# confirm "question" — y/N gate; returns success on yes. # confirm "question" — y/N gate; returns success on yes.
confirm() { confirm() {
local reply="" local reply=""
printf ' %s? %s [y/N] ' "$YELLOW" "$1" printf ' %s? %s [y/N] ' "$YELLOW" "$1"
read -r reply || true read -r reply || _cancel
[[ "$reply" =~ ^[Yy] ]] [[ "$reply" == y || "$reply" == Y || "$reply" == yes || "$reply" == YES ]]
} }
# _existing KEY — current value of KEY in ENV_FILE, if any. # _existing KEY — current value of KEY in ENV_FILE, if any.
_existing() { _existing() {
[[ -f "$ENV_FILE" ]] || return 1 [[ -e "$ENV_FILE" ]] || return 0
local line; line=$(grep -E "^${1}=" "$ENV_FILE" | tail -n1) || return 1 local line value=""
printf '%s' "${line#*=}" while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*(export[[:space:]]+)?${1}[[:space:]]*= ]] || continue
value="${line#*=}"
# ponytail: only reuse the single-line format we emit; adapt for another dotenv dialect.
if [[ "$value" == \"* || "$value" == \`* || "$value" == *$'\r'* ]]; then
printf 'Existing value uses an unsupported dotenv format; adapt the helper first.\n' >&2; return 1
elif [[ "$value" == "'"* ]]; then
[[ "$value" == *"'" && ${#value} -ge 2 ]] || return 1
value="${value:1:${#value}-2}"
[[ "$value" != *"'"* ]] || return 1
else
[[ "$value" != *[[:space:]]* && "$value" != *[\'\"\`\\]* ]] || return 1
value="${value%%#*}"
fi
done < "$ENV_FILE"
printf '%s' "$value"
} }
# ask KEY "Prompt" — read a value into $KEY. Offers the existing .env value as # ask KEY "Prompt" — read a value into $KEY. Offers the existing .env value as
# a default on re-runs (Enter keeps it). Visible input (non-secret). # a default on re-runs (Enter keeps it). Visible input (non-secret).
ask() { ask() {
local key="$1" prompt="$2" current input local key="$1" prompt="$2" current input
current=$(_existing "$key" || true) _valid_key "$key" || return 1
current=$(_existing "$key") || return 1
if [[ -n "$current" ]]; then if [[ -n "$current" ]]; then
printf ' %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET" printf ' %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET"
else else
printf ' %s%s%s ' "$BOLD" "$prompt" "$RESET" printf ' %s%s%s ' "$BOLD" "$prompt" "$RESET"
fi fi
read -r input || true read -r input || _cancel
[[ -z "$input" && -n "$current" ]] && input="$current" [[ -z "$input" && -n "$current" ]] && input="$current"
[[ -n "$input" ]] || { printf 'A value is required.\n' >&2; return 1; }
printf -v "$key" '%s' "$input" printf -v "$key" '%s' "$input"
} }
# ask_secret KEY "Prompt" — like ask, but input is hidden. # ask_secret KEY "Prompt" — like ask, but input is hidden.
ask_secret() { ask_secret() {
local key="$1" prompt="$2" current input local key="$1" prompt="$2" current input
current=$(_existing "$key" || true) _valid_key "$key" || return 1
current=$(_existing "$key") || return 1
if [[ -n "$current" ]]; then if [[ -n "$current" ]]; then
printf ' %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET" printf ' %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET"
else else
printf ' %s%s%s ' "$BOLD" "$prompt" "$RESET" printf ' %s%s%s ' "$BOLD" "$prompt" "$RESET"
fi fi
read -rs input || true read -rs input || _cancel
printf '\n' printf '\n'
[[ -z "$input" && -n "$current" ]] && input="$current" [[ -z "$input" && -n "$current" ]] && input="$current"
[[ -n "$input" ]] || { printf 'A value is required.\n' >&2; return 1; }
printf -v "$key" '%s' "$input" printf -v "$key" '%s' "$input"
} }
# write_env KEY VALUE — upsert KEY=VALUE into ENV_FILE (creates it; replaces # write_env KEY VALUE — atomic, private single-line dotenv upsert.
# any existing line). Idempotent. # Single quotes preserve #, spaces, dollars and backslashes literally.
write_env() { write_env() {
local key="$1" value="$2" tmp local key="$1" value="$2" tmp line
touch "$ENV_FILE" _valid_key "$key" || return 1
tmp=$(mktemp) [[ -n "$value" && "$value" != *"'"* && "$value" != *$'\n'* && "$value" != *$'\r'* ]] || {
grep -vE "^${key}=" "$ENV_FILE" > "$tmp" || true printf 'Cannot save an empty value, apostrophe, or newline in this dotenv format.\n' >&2; return 1;
printf '%s=%s\n' "$key" "$value" >> "$tmp" }
mv "$tmp" "$ENV_FILE" _existing "$key" >/dev/null || return 1
tmp=$(mktemp "${ENV_FILE}.XXXXXX") || return 1
if [[ -e "$ENV_FILE" ]] && ! awk -v key="$key" '$0 !~ "^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*="' "$ENV_FILE" > "$tmp"; then
rm -- "$tmp"
return 1
fi
if printf "%s='%s'\n" "$key" "$value" >> "$tmp" && mv -- "$tmp" "$ENV_FILE"; then
:
else
rm -- "$tmp"
printf 'Could not save dotenv value.\n' >&2; return 1
fi
WRITTEN_ENV+=("$key") WRITTEN_ENV+=("$key")
printf ' %s✓ wrote%s %s → %s\n' "$GREEN" "$RESET" "$key" "$ENV_FILE" printf ' %s✓ wrote%s %s → %s\n' "$GREEN" "$RESET" "$key" "$ENV_FILE"
} }
# set_secret NAME VALUE — set a GitHub Actions repo secret via gh. Falls back
# to a warning (and records it) if gh is unavailable or unauthenticated.
set_secret() {
local name="$1" value="$2"
if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
if printf '%s' "$value" | gh secret set "$name" >/dev/null 2>&1; then
WRITTEN_SECRET+=("$name")
printf ' %s✓ set%s GitHub secret %s\n' "$GREEN" "$RESET" "$name"
return
fi
fi
SKIPPED+=("GitHub secret $name (set it manually: gh secret set $name)")
warn "skipped GitHub secret $name — gh not ready; set it later"
}
# set_var NAME VALUE — set a GitHub Actions repo variable (non-secret).
set_var() {
local name="$1" value="$2"
if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
if gh variable set "$name" --body "$value" >/dev/null 2>&1; then
printf ' %s✓ set%s GitHub variable %s\n' "$GREEN" "$RESET" "$name"
return
fi
fi
SKIPPED+=("GitHub variable $name")
warn "skipped GitHub variable $name — gh not ready; set it later"
}
# finish — clear, then a closing summary of everything configured. # finish — clear, then a closing summary of everything configured.
finish() { finish() {
_clear _clear
if (( ${#SKIPPED[@]} )); then
warn 'Setup incomplete'
else
printf '\n%s%s ✓ Setup complete%s\n' "$BOLD" "$GREEN" "$RESET" printf '\n%s%s ✓ Setup complete%s\n' "$BOLD" "$GREEN" "$RESET"
fi
(( ${#WRITTEN_ENV[@]} )) && note "wrote ${#WRITTEN_ENV[@]} value(s) to $ENV_FILE: ${WRITTEN_ENV[*]}" (( ${#WRITTEN_ENV[@]} )) && note "wrote ${#WRITTEN_ENV[@]} value(s) to $ENV_FILE: ${WRITTEN_ENV[*]}"
(( ${#WRITTEN_SECRET[@]} )) && note "set ${#WRITTEN_SECRET[@]} GitHub secret(s): ${WRITTEN_SECRET[*]}"
if (( ${#SKIPPED[@]} )); then if (( ${#SKIPPED[@]} )); then
printf '\n'; warn "still to do by hand:" printf '\n'; warn "still to do by hand:"
for s in "${SKIPPED[@]}"; do note " - $s"; done for s in "${SKIPPED[@]}"; do note " - $s"; done
@@ -181,16 +199,20 @@ finish() {
# ────────────────────────────────────────────────────────────────────────── # ──────────────────────────────────────────────────────────────────────────
# STAGES — author this section. One stage() per step the human takes. # STAGES — author this section. One stage() per step the human takes.
# Replace the example below. Set TOTAL_STAGES to match the stages you write. # Replace the example below. Set the two totals to match the stages you write.
# ────────────────────────────────────────────────────────────────────────── # ──────────────────────────────────────────────────────────────────────────
# Sourcing exposes helpers for isolated checks without opening browsers.
if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then return 0; fi
TOTAL_STAGES=1 TOTAL_STAGES=1
TOTAL_MINUTES=5
banner "Stripe setup" banner "Stripe setup"
# ── Example stage: replace with your real steps ─────────────────────────── # ── Example stage: replace with your real steps ───────────────────────────
stage "Stripe — API keys" stage "Stripe — API keys" 5
say "We'll grab your Stripe test keys and store them for local dev + CI." say "We'll grab your Stripe test keys and store them for local development."
open_url "https://dashboard.stripe.com/test/apikeys" open_url "https://dashboard.stripe.com/test/apikeys"
step "On the API keys page, copy the Publishable key (starts pk_test_)." step "On the API keys page, copy the Publishable key (starts pk_test_)."
ask STRIPE_PUBLISHABLE_KEY "Paste the publishable key:" ask STRIPE_PUBLISHABLE_KEY "Paste the publishable key:"
@@ -198,7 +220,6 @@ step "Click 'Reveal test key' on the Secret key row, then copy it."
ask_secret STRIPE_SECRET_KEY "Paste the secret key:" ask_secret STRIPE_SECRET_KEY "Paste the secret key:"
write_env STRIPE_PUBLISHABLE_KEY "$STRIPE_PUBLISHABLE_KEY" write_env STRIPE_PUBLISHABLE_KEY "$STRIPE_PUBLISHABLE_KEY"
write_env STRIPE_SECRET_KEY "$STRIPE_SECRET_KEY" write_env STRIPE_SECRET_KEY "$STRIPE_SECRET_KEY"
set_secret STRIPE_SECRET_KEY "$STRIPE_SECRET_KEY" # CI needs this one
# ────────────────────────────────────────────────────────────────────────── # ──────────────────────────────────────────────────────────────────────────
finish finish
+58
View File
@@ -0,0 +1,58 @@
"""Isolated Bash helper checks; only dummy values, no browsers or secret stores."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
template = Path(__file__).with_name("template.sh").resolve()
with tempfile.TemporaryDirectory() as directory:
env_file = Path(directory) / ".env"
environment = {**os.environ, "ENV_FILE": str(env_file)}
def run(command, value="", input="", expected=0):
result = subprocess.run(
["bash", "-c", 'source "$1"; ' + command, "check", str(template)],
env={**environment, "DUMMY_VALUE": value},
input=input, text=True, capture_output=True,
)
assert (result.returncode == 0) == (expected == 0), result.stderr
return result
for value in ("dummy#value", " spaces ", 'a"b', r"dollar$and\backslash", "replacement"):
run('write_env DUMMY_KEY "$DUMMY_VALUE"', value)
parsed = subprocess.run(
["node", "-e", "process.stdout.write(JSON.stringify(require('node:util').parseEnv(require('node:fs').readFileSync(process.argv[1], 'utf8'))))", str(env_file)],
text=True, capture_output=True, check=True,
)
assert json.loads(parsed.stdout)["DUMMY_KEY"] == value
assert run("_existing DUMMY_KEY").stdout == value
assert env_file.stat().st_mode & 0o777 == 0o600
assert env_file.read_text().count("DUMMY_KEY=") == 1
run("write_env OTHER_KEY unchanged")
run("write_env DUMMY_KEY replacement")
assert run("_existing OTHER_KEY").stdout == "unchanged"
saved = env_file.read_bytes()
for value in ("", "can't", "two\nlines", "carriage\rreturn"):
run('write_env DUMMY_KEY "$DUMMY_VALUE"', value, expected=1)
assert env_file.read_bytes() == saved
run('write_env "BAD-KEY" value', expected=1)
run('write_env HOME value', expected=1)
for helper in ("ask", "ask_secret"):
run(f'{helper} NEW_KEY prompt', expected=1)
run(f'{helper} NEW_KEY prompt', input="\n", expected=1)
run(f'{helper} DUMMY_KEY prompt; [[ "$DUMMY_KEY" == replacement ]]', input="\n")
run(f'{helper} NEW_KEY prompt; [[ "$NEW_KEY" == captured ]]', input="captured\n")
run("pause", expected=1)
run("confirm question", expected=1)
run("confirm question", input="yesterday\n", expected=1)
run("confirm question", input="yes\n")
env_file.write_text('DUMMY_KEY="unsupported"\n')
run('write_env DUMMY_KEY replacement', expected=1)
assert env_file.read_text() == 'DUMMY_KEY="unsupported"\n'
print("Wizard helper checks passed")
+66
View File
@@ -0,0 +1,66 @@
---
name: writing-beats
description: Writing, exploit — assemble raw material into a journey of beats, grounding each term before a beat leans on it.
---
<what-to-do>
The user has passed (or will pass) a markdown file of raw material. This is **exploit**: the exploring is done, the pile is fixed — commit to a path through it and mine the pile to fill each beat.
If the user did not say where to save the article, ask once and remember the path.
Then run a beat-by-beat journey, choose-your-own-adventure style:
1. **Establish the prerequisites.** Before any beats, settle with the user what the audience already knows walking in — the concepts that are **grounded** from the start. Everything else must be grounded by a beat before a later beat can use it. See [Grounding](#grounding).
2. Write 2–3 candidate **starting beats**, drawn from the raw material. Each is a different entry point into the article. Each may only lean on grounded concepts; note what new concepts each one grounds. Show the user the beats before writing to the article file. The user picks one. Preview what beats that pick unlocks — as if the user is seeing a little way down the path.
3. Once the user picks a starting beat, write **only that beat** to the article file. A beat may be one sentence or several paragraphs — whatever that beat naturally is. Stop there.
4. Re-read the article file from disk. Then offer 2–3 candidate **next beats** — different directions the journey could pivot to from where the article now stands. Each must be reachable from the current grounded set; note what each one grounds.
5. Loop steps 3–5 until the article reaches a natural end.
</what-to-do>
<supporting-info>
## Grounding
Every **concept** has to be **grounded** before a beat can lean on it: the audience either walked in knowing it or met it in an earlier beat. A beat that reaches for an ungrounded concept loses the reader — that is the one move the journey can't make. The unit is the concept, not the word for it: a beat can lean on an idea the reader lacks even with no jargon in sight. Where a concept has a name — a **term** — grounding it means landing the idea and the term together.
A concept gets grounded one of two ways:
- **Prerequisite** — grounded before the first beat. The audience brings it. Fixed at the start.
- **Introduced** — a beat establishes it, and from then on it's grounded for every later beat.
So each beat does two jobs: it **requires** concepts that are already grounded, and it **grounds** new ones. Keep a running list of what's grounded so far, and update it each time a beat lands.
This is what shapes the choose-your-own-adventure. A candidate beat is only reachable if everything it requires is already grounded; picking a beat that grounds concept X unlocks every beat that was waiting on X. When you offer next beats, they must all be reachable from the current grounded set — and say what each one grounds, so the user can see which paths it opens.
The big lever is what you make a prerequisite versus what you ground inside the piece. Demand too much up front and you shut out readers who don't have it; ground too much inside and the early beats drown in definitions. Settle this with the user when you establish prerequisites, and revisit it whenever a tempting beat turns out to require a concept nothing has grounded yet — the fix is either a grounding beat before it, or promoting the concept to a prerequisite.
## What is a beat
A beat is one move in the journey. It does one thing — sets a scene, lands a point, asks a question, drops an aside, twists the angle. Then it stops, leaving the reader at a place where the next beat can pivot.
A beat is sized by what it needs:
- A single sentence if that's all the move is ("And then nothing happened for three weeks.").
- A short paragraph if the move needs setup.
- Multiple paragraphs if the beat is a self-contained vignette, argument, or example.
If a "beat" needs five paragraphs and three subheadings, it's not a beat — it's two beats glued together. Split it.
## Pulling from the pile
Pull material from the raw pile to populate each beat. You can paraphrase, split, recombine, or quote. The pile is a quarry.
## Ending the journey
The article ends when the journey is complete — not when the pile is empty. Most piles will have leftover fragments that don't make it in. That is fine; that is the point of having more raw material than you need.
## Writing rhythm
- Append one beat at a time. Never write ahead.
- Re-read the article file from disk before every write. Preserve user edits absolutely.
- If the user edits a previous beat substantially, let it change what comes next.
- If the user says "rewrite that beat" or "go back and try a different beat 3", do it — edit in place, leave the rest alone.
</supporting-info>
@@ -0,0 +1,5 @@
interface:
display_name: "Writing Beats"
short_description: "Assemble raw material into beats"
policy:
allow_implicit_invocation: false
+78
View File
@@ -0,0 +1,78 @@
---
name: writing-fragments
description: Writing, explore — mine raw fragments, no structure yet.
---
<what-to-do>
This is pure **explore**: widen the space of what could be written without committing to structure — committing is _exploit_, a separate skill's job. Run a grilling session that produces fragments, interviewing the user relentlessly about whatever they want to write about. Imposing phases, outlines, or article structure is out of scope here.
As fragments emerge from either side of the conversation, append them to a single markdown file.
If the user did not pass a path, ask once where to save the document, then remember it for the rest of the session.
Capture fragments from the very first thing the user says, including the initial prompt.
On first write, put a single H1 at the top with a working title (it can change later) and nothing else — no metadata, no TOC, no date.
</what-to-do>
<supporting-info>
## What is a fragment
A fragment is any piece of text that might survive into the final article. It must be _readable by the author_ — the author can tell what it means — but it does not need to define its terms or be comprehensible to a cold reader. The bar is "is this a piece of good writing?", not "is this a self-contained argument?"
Fragments are deliberately heterogeneous. Examples of what could be a fragment:
- A sharp sentence you'd want to deploy somewhere but don't yet know where.
- A claim with a one-line justification.
- A vignette: a thing that happened, a code snippet, a scenario, an analogy.
- A half-thought: "something about how X feels like Y, work this out later."
- A quote, a piece of dialogue, an overheard line.
- A list of related observations that hang together by feel.
- A complaint, a confession, a punchline.
- A **leading word** — a compact metaphor or coinage the whole piece can hang on (one term that names the idea, the way _tracer bullets_ or _fog of war_ names a whole pattern).
Of these, the leading word is the most valuable fragment to land. It is load-bearing: name the right one in explore and it shapes the structure, the transitions, and the title later — paying dividends through the entire exploit phase. When the conversation circles a recurring idea, push to coin a word for it.
The novelist's diary is the model: years of unstructured noticings that later get mined for raw material. Fragments are noticings.
## File format
```markdown
# Working title
A first fragment lives here.
It can be multiple paragraphs. It can include lists, code, quotes — whatever
shape the fragment naturally takes.
---
A second fragment.
---
> A quoted line that the user wants to keep around.
A reaction to it.
---
- A cluster of related observations
- That hang together by feel
- And want to be near each other
```
Fragments are separated by a horizontal rule (`\n---\n`). No headings inside the body. No tags. No order beyond the order they were added.
## Writing rhythm
Append silently. Don't ask permission for each fragment. Mention what you added in passing ("adding that"), but don't interrupt the conversation with save dialogs.
Before every write: re-read the file from disk. The user may have edited, reordered, or deleted fragments between turns — preserve their changes. Never overwrite the file; only append (or, if the user asks, edit a specific fragment in place).
The user can say "cut the last one", "rewrite that one sharper", "merge those two" at any time. Treat those as first-class instructions.
</supporting-info>
@@ -0,0 +1,5 @@
interface:
display_name: "Writing Fragments"
short_description: "Mine raw writing fragments"
policy:
allow_implicit_invocation: false
@@ -0,0 +1,40 @@
# Instruction-Design Glossary
Use these terms when they clarify a discussion about agent instructions. They are concepts, not a requirement to avoid ordinary synonyms. [SKILL.md](SKILL.md) owns the workflow and Codex invocation mechanics.
## Discovery and cost
- **Predictability:** comparable situations lead to consistent, task-appropriate decisions.
- **Model-invoked:** available for automatic selection as well as explicit invocation.
- **User-invoked:** explicitly selected; an explicit-only policy disables automatic selection, not required metadata.
- **Description:** required frontmatter that summarizes capability and applicability; it is not the invocation-policy toggle.
- **Context pointer:** a reference plus the condition for reaching its target.
- **Context load:** tokens and attention spent on available metadata and loaded instructions.
- **Cognitive load:** what the human must remember or decide to use the system.
- **Router skill:** selects among genuinely distinct workflows or resources.
- **Granularity:** how finely instructions are divided; each split must justify its discovery and maintenance cost.
## Information hierarchy
- **Steps:** ordered actions where sequence matters to the task.
- **Reference:** definitions, constraints, or procedures consulted when relevant.
- **External reference:** material outside the entrypoint, reached through an appropriate pointer.
- **Information hierarchy:** the placement of essential actions and constraints versus conditional detail.
- **Progressive disclosure:** loading supporting detail only when the task needs it.
- **Co-location:** keeping a concept's definition, rules, and caveats together.
- **Branch:** a distinct case or mode handled by the skill.
## Execution and maintenance
- **Leading word:** a compact, familiar concept that conveys a useful decision principle without repeated explanation.
- **Completion criterion:** evidence that the requested outcome has been reached; it should be checkable and cover the important requirements.
- **Legwork:** investigation needed to meet that criterion rather than transferring discoverable work to the user.
- **Post-completion steps:** later actions that may distract from an unfinished prerequisite.
- **Premature completion:** declaring a step or task done without meeting its criterion. Clarify the criterion before adding process.
- **Negation:** wording framed around what to avoid. Prefer a clear positive target where possible while retaining necessary safety prohibitions.
- **Single source of truth:** one authoritative home for a rule or fact.
- **Duplication:** repeated meaning that must be maintained in several places.
- **Relevance:** whether material still supports the skill's actual task.
- **Sediment:** stale assumptions accumulated through updates.
- **Sprawl:** more instruction volume than the task usefully needs.
- **No-op:** wording that does not materially change the agent's decisions or work.
@@ -0,0 +1,40 @@
---
name: writing-great-skills
description: Reference for writing and editing skills well — the vocabulary and principles that make a skill predictable.
---
# Writing Great Skills
Write guidance that improves decisions while preserving the user's outcome, choices, and authority. Predictability means handling comparable situations consistently—not imposing the same ceremony on every task.
## Codex mechanics
Every skill needs YAML `name` and `description`. Keep the description concise: what the skill does, when it applies, and a boundary only where it prevents likely misrouting.
Automatic discovery is the default. Set `policy.allow_implicit_invocation: false` in `agents/openai.yaml` for a new explicit-only skill only when the user requests it. Preserve existing invocation policies and unrelated UI/dependency fields.
Do not use legacy `disable-model-invocation` or `argument-hint` frontmatter for Codex, or delete descriptions to change invocation. Discovery policy does not grant authority; check authorization at the relevant mutation.
## Write only decision-changing guidance
- State the intended outcome, non-obvious context, genuine constraints, and a recognizable completion condition.
- Reuse explicit user choices and known context. Ask only for missing information that materially affects the task.
- Match specificity to risk: fixed sequences belong in fragile workflows, not ordinary open-ended work.
- Preserve authority boundaries. A review should not silently implement; a plan should not silently publish. Define stopping and retry behavior where failures or duplicate external writes matter.
- Keep discovery specific. Avoid exhaustive synonym lists and generic triggers that attract unrelated tasks.
## Arrange the information
Keep shared purpose and essential constraints in the entrypoint. Move substantial mode-specific procedures behind a link that says when to read them. Keep simple skills self-contained; add a router only for meaningful branches.
Use one authoritative home for each rule. Read the environment rather than copying readily discoverable configuration into instructions, except where a local gotcha is worth recording.
Use [GLOSSARY.md](GLOSSARY.md) when discussing instruction-design concepts such as context load, progressive disclosure, or premature completion. It defines the vocabulary; this file owns the authoring workflow and Codex mechanics.
## Validate and prune
Check metadata with the target runtime's validator, confirm references are reachable, and run changed helpers with safe representative inputs. Test observable outcomes and invariants, not exact generated wording.
For complex or risky behavior, use a scoped independent evaluation when delegation is available and authorized. Keep fixtures isolated from user work and avoid live side effects.
Remove duplicated rules, stale assumptions, speculative scaffolding, and examples that do not clarify a real choice. Preserve safety and operational invariants even when shortening the text. If a task keeps failing, correct the demonstrated cause rather than adding universal ceremony.
@@ -0,0 +1,5 @@
interface:
display_name: "Writing Great Skills"
short_description: "Principles for predictable skills"
policy:
allow_implicit_invocation: false
+78
View File
@@ -0,0 +1,78 @@
---
name: writing-shape
description: Writing, exploit — shape raw material into an article, paragraph by paragraph.
---
<what-to-do>
The user has passed (or will pass) a markdown file of raw material. Treat it as the input pile — anything from a tidy list of fragments to a wall of unstructured prose to a transcript. The format does not matter. Read it end-to-end before doing anything else.
Then run a shaping session that produces a separate article document. This is **exploit**: the exploring is done, the pile is fixed — commit to a structure and mine the pile to fill it. Do not edit the raw material file — it is read-only to this skill.
If the user did not say where to save the article, ask once and remember the path.
</what-to-do>
<supporting-info>
## The loop
1. **Read the pile.** Read the input file in full. Form a sense of what's in it.
2. **Establish the prerequisites.** Settle with the user what the reader knows walking in — the concepts that are **grounded** from the start. Everything else must be grounded by a block before a later block can lean on it. See [Grounding](#grounding).
3. **Draft 2–3 candidate openings.** Each opening should imply a different thesis or angle for the article. Show all of them. Force the user to pick or compose a hybrid. The chosen opening defines what the rest of the article must do.
4. **Grow paragraph by paragraph.** After the opening lands, ask "given this opening, what does the reader need to hear next?" Pull material from the pile to answer. The next block may only lean on grounded concepts, and grounds new ones as it lands. Argue about the form the next block takes — a paragraph, a list, a table, a callout, a quote, a code block. Each format choice should be deliberate and defensible.
5. **Append to the article file as you go.** Don't batch. Write each agreed paragraph or block immediately so the user can see the article taking shape.
6. **Loop step 4 until the article is done.** The user decides when it's done.
## Grounding
Every **concept** has to be **grounded** before a block can lean on it: the reader either walked in knowing it or met it in an earlier block. A block that reaches for an ungrounded concept loses the reader. The unit is the concept, not the word for it — a block can lean on an idea the reader lacks even with no jargon in sight. Where a concept has a name — a **term** — grounding it means landing the idea and the term together.
A concept gets grounded one of two ways:
- **Prerequisite** — grounded before the opening. The reader brings it. Fixed at the start.
- **Introduced** — a block establishes it, and from then on it's grounded for the rest of the article.
Keep a running list of what's grounded. When you ask "what does the reader need to hear next?", an ungrounded concept the next move needs is itself the answer: ground it first — here or in an earlier block — or you can't make the move. This is the gap-naming of [Pulling from the pile](#pulling-from-the-pile) one level up: there the pile is missing material; here the article is missing a foundation.
The lever is what you make a prerequisite versus what you ground inside the article. Demand too much up front and you shut readers out; ground too much inside and the opening drowns in definitions. Settle it with the user when you establish prerequisites.
## Conversational feel
This is a grilling session inverted. In ideation, the question was "what are you actually noticing?" Here it's "what is this article actually arguing, and in what order does the reader need to hear it?" Push back. Refuse to let weak transitions slide. If a paragraph doesn't earn its place, cut it.
Specific moves to keep using:
- "What does this paragraph do for the reader that the previous one didn't?"
- "If I cut this, what breaks?"
- "Is this prose, or should it be a list? Why prose?"
- "This sentence is doing two jobs — split it or pick one."
- "The opening promised X. We've drifted to Y. Either re-thread it or change the opening."
## Pulling from the pile
Treat the raw material as a quarry, not a script. Pull a fragment, rework it to fit the surrounding paragraph, and place it. A fragment may be split across multiple paragraphs, merged with another, or paraphrased. The pile's job is to be mined; the article's job is to read as one voice.
If the pile lacks something the article needs, name the gap explicitly: "We need an example here and the pile doesn't have one — give me one now or we cut this section."
## Format arguments to actually have
When choosing how to render a block, weigh these tradeoffs out loud with the user, not silently:
- **Prose vs. list.** Prose carries argument; lists carry parallel items. If items aren't truly parallel, prose is better. If they are, a list is faster to scan.
- **Inline vs. callout.** Tips, warnings, and asides go in callouts (`> [!TIP]`, `> [!NOTE]`) — but only if they'd genuinely derail the main argument inline. Otherwise leave them inline.
- **Table vs. repeated structure.** If the same shape repeats 3+ times with the same fields, a table. Otherwise prose with bold leads.
- **Quote vs. paraphrase.** Quote when the original wording is the point. Paraphrase when only the idea matters.
- **Code block vs. inline code.** Multi-line, runnable, or illustrative → block. Single token or identifier → inline.
## Writing rhythm
Append to the article file as each block is agreed. Re-read the file from disk before every write — the user may have edited between turns. Never overwrite blindly. If the user wants a paragraph rewritten, edit that specific paragraph in place; leave the rest alone.
## Out of scope
- Mining for new fragments that aren't in the pile (handle gaps as in "Pulling from the pile").
- Editing the raw material file.
- Publishing, formatting for a specific platform, or adding frontmatter the user didn't ask for.
</supporting-info>
@@ -0,0 +1,5 @@
interface:
display_name: "Writing Shape"
short_description: "Shape raw material into an article"
policy:
allow_implicit_invocation: false