diff --git a/.agents/skills/ask-matt/PHASE-BOUNDARIES.md b/.agents/skills/ask-matt/PHASE-BOUNDARIES.md new file mode 100644 index 0000000..fb58ef9 --- /dev/null +++ b/.agents/skills/ask-matt/PHASE-BOUNDARIES.md @@ -0,0 +1,55 @@ +# Phase boundaries + +A **phase** is a chunk of work inside a session: the grilling, the implementation, the QA. The definition is fuzzy on purpose: a phase ends when you think *"ok, we're done with that"*. + +The **phase boundary** is the gap between two phases, and it is the only place this decision belongs. Mid-phase there is no decision to make: continue, or split the work that's left into subagents. Compacting mid-phase makes the agent lose the thread. + +## The five options + +| Option | What it does | +| ------------ | --------------------------------------------------------------- | +| **Continue** | Stay in the session. No context switch at all. | +| **`/clear`** | Empty the context window and start from nothing. | +| **`/handoff`** | Write a portable markdown file and seed a session anywhere with it. | +| **Subagent** | Send the task to its own context window and get a report back. | +| **`/compact`** | Compress this context and seed a fresh session with the summary. | + +## The tree + +Work top to bottom at the boundary. The first **yes** wins. + +**1. Can you continue in this session?** Two things make the answer yes: the next phase needs this phase as a **primary source**, or you have enough [smart zone](https://www.aihero.dev/ai-coding-dictionary/smart-zone) left (~150k tokens) for the next phase to fit. Grilling → implementation is the standard yes: the implementation wants the reasoning verbatim, not a summary of it. Continue costs nothing and loses nothing, so rule it out before anything else. + +**2. Is the context irrelevant to what comes next?** Is everything in this session (the exploration, the decisions, the dead ends) disposable? If so, **`/clear`**. It is the cheapest move on the board: it takes no time and hands back the whole window. `/clear` also isn't terminal: the old session stays resumable. + +The cost of getting this wrong is one-way. Clear a *relevant* context and you lose the **why** behind what you built, and no amount of reading the diff back gets it returned. + +**3. Do you need to hand off?** `/handoff` is narrow. You need it only when you are: + +- swapping to a **new harness** (Claude → Codex), +- moving to a **new directory** or repo, +- sending the work to a **colleague**, +- or forking a side task you found **mid-phase** without derailing what you're doing. + +That list is the whole clause. What `/handoff` buys is **portability**: a file that travels. If nothing is travelling, you don't need it. + +**4. Can the task be done AFK?** Is it scoped tightly enough to run with you away from the keyboard, no steering? Then send it to a **subagent** and leave this session untouched. Automated review is the standard case: the agent reads the diff and reports, and you aren't needed while it does. + +**5. Otherwise, `/compact`.** Relevant context, same harness, same directory, and you need to stay in the loop: this is where the tree lands, and it lands here often. Pass it an instruction (`/compact we're going to QA this area`) so the summary keeps what the next phase needs. + +`/compact` is the **default, not the first reach**. It sits at the bottom because the four questions above it are all cheaper or more precise. The failure mode when people start here is a fresh session that is confidently wrong about a decision the summary flattened. + +## Primary and secondary sources + +Every move except **Continue** turns a **primary source** into a **secondary source**: the session as it happened, replaced by a summary of it. The trade is always the same shape: + +| Source | Information | Noise | Room to move | +| --------------------------------- | ----------- | ----- | ------------ | +| Primary (Continue) | Full | Lots | Little | +| Secondary (`/compact`, `/handoff`) | Lossy | Less | Lots | + +This is why question 1 comes first. You only pay the lossiness when staying costs more than it saves. + +## These are judgement calls + +The questions are not objective: each has taste in it, and the same boundary can go two ways on two days. The value is in asking them **in order**, at the boundary rather than in the middle of the work. diff --git a/.agents/skills/ask-matt/SKILL.md b/.agents/skills/ask-matt/SKILL.md new file mode 100644 index 0000000..ae8eb9b --- /dev/null +++ b/.agents/skills/ask-matt/SKILL.md @@ -0,0 +1,90 @@ +--- +name: ask-matt +description: Ask which skill or flow fits your situation. A router over the skills in this repo. +disable-model-invocation: true +--- + +# Ask Matt + +You don't remember every skill, so ask. + +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. + +## The main flow: idea → ship + +The route most work travels. You have an idea and want it built. + +1. **`/grill-with-docs`** sharpens 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` instead, covered under 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.) +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//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. + +### Context hygiene + +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. + +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, so go straight to `/implement` only when the effort turned out genuinely small. + +## Codebase health + +Not feature work, just upkeep. + +- **`/improve-codebase-architecture`** runs 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`** is 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`** writes 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`** compresses this context and seeds 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`** is 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`** works 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 finishes the operation. It never runs `--abort`. Standalone and off every flow: reach for it when you are already mid-conflict. +- **`/prototype`** is 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/` 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`, since research feeds the thinking rather than replacing it. +- **`/to-questionnaire`** comes in when the thing blocking you isn't in your head or the codebase but in **someone else's**, and it 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`** is 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`** is 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`** is the 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. diff --git a/.agents/skills/ask-matt/agents/openai.yaml b/.agents/skills/ask-matt/agents/openai.yaml new file mode 100644 index 0000000..5c60d51 --- /dev/null +++ b/.agents/skills/ask-matt/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Ask Matt" + short_description: "Find the right skill or workflow" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/claude-handoff/SKILL.md b/.agents/skills/claude-handoff/SKILL.md new file mode 100644 index 0000000..9ab14e3 --- /dev/null +++ b/.agents/skills/claude-handoff/SKILL.md @@ -0,0 +1,18 @@ +--- +name: claude-handoff +description: Hand the current conversation off to a fresh background agent that picks up the work immediately. +argument-hint: "What will the next session be used for?" +disable-model-invocation: true +--- + +Write a handoff summary of the current conversation so a fresh agent can continue the work. Instead of saving it, launch a background agent seeded with the summary as its prompt: `claude --bg --name "" ""`. It starts in the current working directory and returns immediately; the user manages it with `claude agents`. + +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, naming which skills the next agent should call the Skill tool for. + +Do not duplicate content already captured in other artifacts (specs, 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, since 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. diff --git a/.agents/skills/claude-handoff/agents/openai.yaml b/.agents/skills/claude-handoff/agents/openai.yaml new file mode 100644 index 0000000..0a7aa5d --- /dev/null +++ b/.agents/skills/claude-handoff/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Claude Handoff" + short_description: "Hand off to a background agent" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.md new file mode 100644 index 0000000..e28d7ac --- /dev/null +++ b/.agents/skills/code-review/SKILL.md @@ -0,0 +1,87 @@ +--- +name: code-review +description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"." +--- + +Two-axis review of the diff between `HEAD` and a fixed point the user supplies: + +- **Standards**: does the code conform to this repo's documented coding standards? +- **Spec**: does the code faithfully implement the originating issue / spec? + +Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings. + +The issue tracker should have been provided to you. If `docs/agents/issue-tracker.md` is missing, tell the user to run `/setup-matt-pocock-skills`. + +## Process + +### 1. Pin the fixed point + +Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it. + +Capture the diff command once: `git diff ...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log ..HEAD --oneline`. + +Before going further, confirm the fixed point resolves (`git rev-parse `) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents. + +### 2. Identify the spec source + +Look for the originating spec, in this order: + +1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in `docs/agents/issue-tracker.md`. +2. A path the user passed as an argument. +3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature. +4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available". + +### 3. Identify the standards sources + +Anything in the repo that documents how code should be written, such as `CODING_STANDARDS.md` or `CONTRIBUTING.md`. + +On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it: + +- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell. +- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces. + +Each smell reads *what it is* → *how to fix*; match it against the diff: + +- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky. +- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both. +- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies. +- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that. +- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type. +- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share. +- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module. +- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason. +- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows. +- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object. +- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct. +- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition. + +### 4. Spawn both sub-agents in parallel + +**Standards sub-agent prompt** should include: + +- The full diff command and commit list. +- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it). +- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words." + +**Spec sub-agent prompt** should include: + +- The diff command and commit list. +- The path or fetched contents of the spec. +- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words." + +If the spec is missing, skip the Spec sub-agent and note this in the final report. + +### 5. Aggregate + +Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_). + +End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent. + +## Why two axes + +A change can pass one axis and fail the other: + +- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.** +- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.** + +Reporting them separately stops one axis from masking the other. diff --git a/.agents/skills/code-review/agents/openai.yaml b/.agents/skills/code-review/agents/openai.yaml new file mode 100644 index 0000000..9076774 --- /dev/null +++ b/.agents/skills/code-review/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Code Review" + short_description: "Review a diff on standards and spec" diff --git a/.agents/skills/codebase-design/DEEPENING.md b/.agents/skills/codebase-design/DEEPENING.md new file mode 100644 index 0000000..cd94075 --- /dev/null +++ b/.agents/skills/codebase-design/DEEPENING.md @@ -0,0 +1,37 @@ +# Deepening + +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**. + +## Dependency categories + +When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. + +### 1. In-process + +Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed. + +### 2. Local-substitutable + +Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. + +### 3. Remote but owned (Ports & Adapters) + +Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. + +Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."* + +### 4. True external (Mock) + +Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. + +## Seam discipline + +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. +- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. + +## Testing strategy: replace, don't layer + +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them. +- Write new tests at the deepened module's interface. The **interface is the test surface**. +- Tests assert on observable outcomes through the interface, not internal state. +- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.agents/skills/codebase-design/DESIGN-IT-TWICE.md b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md new file mode 100644 index 0000000..7edc861 --- /dev/null +++ b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md @@ -0,0 +1,44 @@ +# Design It Twice + +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best. + +Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**. + +## Process + +### 1. Frame the problem space + +Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: + +- The constraints any new interface would need to satisfy +- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) +- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete + +Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. + +### 2. Spawn sub-agents + +Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module. + +Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: + +- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility: support many use cases and extension." +- Agent 3: "Optimise for the most common caller: make the default case trivial." +- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." + +Include both [SKILL.md](SKILL.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. + +Each sub-agent outputs: + +1. Interface (types, methods, params, plus invariants, ordering, error modes) +2. Usage example showing how callers use it +3. What the implementation hides behind the seam +4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) +5. Trade-offs: where leverage is high, where it's thin + +### 3. Present and compare + +Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. + +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu. diff --git a/.agents/skills/codebase-design/SKILL.md b/.agents/skills/codebase-design/SKILL.md new file mode 100644 index 0000000..3f63c81 --- /dev/null +++ b/.agents/skills/codebase-design/SKILL.md @@ -0,0 +1,114 @@ +--- +name: codebase-design +description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary. +--- + +# Codebase Design + +Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone. + +## Glossary + +Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. + +**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. + +**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface). + +**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. + +**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. + +**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). + +**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). + +**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests. + +**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. + +## Deep vs shallow + +**Deep module** = small interface + lots of implementation: + +``` +┌─────────────────────┐ +│ Small Interface │ ← Few methods, simple params +├─────────────────────┤ +│ │ +│ Deep Implementation│ ← Complex logic hidden +│ │ +└─────────────────────┘ +``` + +**Shallow module** = large interface + little implementation (avoid): + +``` +┌─────────────────────────────────┐ +│ Large Interface │ ← Many methods, complex params +├─────────────────────────────────┤ +│ Thin Implementation │ ← Just passes through +└─────────────────────────────────┘ +``` + +When designing an interface, ask: + +- Can I reduce the number of methods? +- Can I simplify the parameters? +- Can I hide more complexity inside? + +## Principles + +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. +- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. + +## Designing for testability + +Good interfaces make testing natural: + +1. **Accept dependencies, don't create them.** + + ```typescript + // Testable + function processOrder(order, paymentGateway) {} + + // Hard to test + function processOrder(order) { + const gateway = new StripeGateway(); + } + ``` + +2. **Return results, don't produce side effects.** + + ```typescript + // Testable + function calculateDiscount(cart): Discount {} + + // Hard to test + function applyDiscount(cart): void { + cart.total -= discount; + } + ``` + +3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup. + +## Relationships + +- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). +- **Depth** is a property of a **Module**, measured against its **Interface**. +- A **Seam** is where a **Module**'s **Interface** lives. +- An **Adapter** sits at a **Seam** and satisfies the **Interface**. +- **Depth** produces **Leverage** for callers and **Locality** for maintainers. + +## Rejected framings + +- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know. +- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. + +## Going deeper + +- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. +- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. diff --git a/.agents/skills/codebase-design/agents/openai.yaml b/.agents/skills/codebase-design/agents/openai.yaml new file mode 100644 index 0000000..3180715 --- /dev/null +++ b/.agents/skills/codebase-design/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Codebase Design" + short_description: "Vocabulary for deep-module design" diff --git a/.agents/skills/diagnosing-bugs/SKILL.md b/.agents/skills/diagnosing-bugs/SKILL.md new file mode 100644 index 0000000..061c25a --- /dev/null +++ b/.agents/skills/diagnosing-bugs/SKILL.md @@ -0,0 +1,138 @@ +--- +name: diagnosing-bugs +description: Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow. +--- + +# Diagnosing Bugs + +A discipline for hard bugs. Skip phases only when explicitly justified. + +When exploring the codebase, read `CONTEXT.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching. + +## Redact + +This skill has you show commands, outputs and captured artifacts. **Redact every secret first**: write `` in its place. Build loops against env vars, so the credential stays in the environment rather than in what you show. Captured artifacts carry auth headers: quote only the lines that carry the signal. + +If the redacted output is not enough to diagnose the bug, say so and ask the user. + +## Phase 1: Build a feedback loop + +**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug (one that goes red on _this_ bug), you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you. + +Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.** + +### Ways to construct one, in roughly this order + +1. **Failing test** at whatever seam reaches the bug: unit, integration, e2e. +2. **Curl / HTTP script** against a running dev server. +3. **CLI invocation** with a fixture input, diffing stdout against a known-good snapshot. +4. **Headless browser script** (Playwright / Puppeteer) that drives the UI and asserts on DOM/console/network. +5. **Replay a captured trace.** Save a real network request / payload / event log to disk; replay it through the code path in isolation. +6. **Throwaway harness.** Spin up a minimal subset of the system (one service, mocked deps) that exercises the bug code path with a single function call. +7. **Property / fuzz loop.** If the bug is "sometimes wrong output", run 1000 random inputs and look for the failure mode. +8. **Bisection harness.** If the bug appeared between two known states (commit, dataset, version), automate "boot at state X, check, repeat" so you can `git bisect run` it. +9. **Differential loop.** Run the same input through old-version vs new-version (or two configs) and diff outputs. +10. **HITL bash script.** Last resort. If a human must click, drive _them_ with `scripts/hitl-loop.template.sh` so the loop is still structured. Captured output feeds back to you. + +Build the right feedback loop, and the bug is 90% fixed. + +### Tighten the loop + +Treat the loop as a product. Once you have _a_ loop, **tighten** it: + +- Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.) +- Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".) +- Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.) + +A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight, a debugging superpower. + +### Non-deterministic bugs + +The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not, so keep raising the rate until it's debuggable. + +### When you genuinely cannot build a loop + +Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a redacted captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop. + +### Completion criterion: a tight loop that goes red + +Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** (a script path, a test invocation, a curl) that you have **already run at least once** (show the invocation and its output, redacted), and that is: + +- [ ] **Red-capable**: it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring"; it must be able to _catch this specific bug_. +- [ ] **Deterministic**: same verdict every run (flaky bugs: a pinned, high reproduction rate, per above). +- [ ] **Fast**: seconds, not minutes. +- [ ] **Agent-runnable**: you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`. + +If you catch yourself reading code to build a theory before this command exists, **stop: jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2. + +## Phase 2: Reproduce + minimise + +Run the loop. Watch it go red as the bug appears. + +Confirm: + +- [ ] The loop produces the failure mode the **user** described, not a different failure that happens to be nearby. Wrong bug = wrong fix. +- [ ] The failure is reproducible across multiple runs (or, for non-deterministic bugs, reproducible at a high enough rate to debug against). +- [ ] You have captured the exact symptom (error message, wrong output, slow timing) so later phases can verify the fix actually addresses it. + +### Minimise + +Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut, and keep only what's load-bearing for the failure. + +Why bother: a minimal repro shrinks the hypothesis space in Phase 3 (fewer moving parts left to suspect) and becomes the clean regression test in Phase 5. + +Done when **every remaining element is load-bearing**: removing any one of them makes the loop go green. + +Do not proceed until you have reproduced **and** minimised. + +## Phase 3: Hypothesise + +Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea. + +Each hypothesis must be **falsifiable**: state the prediction it makes. + +> Format: "If is the cause, then will make the bug disappear / will make it worse." + +If you cannot state the prediction, the hypothesis is a vibe: discard or sharpen it. + +**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it; proceed with your ranking if the user is AFK. + +## Phase 4: Instrument + +Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.** + +Tool preference: + +1. **Debugger / REPL inspection** if the env supports it. One breakpoint beats ten logs. +2. **Targeted logs** at the boundaries that distinguish hypotheses. +3. Never "log everything and grep". + +**Tag every debug log** with a unique prefix, e.g. `[DEBUG-a4f2]`. Cleanup at the end becomes a single grep. Untagged logs survive; tagged logs die. + +**Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second. + +## Phase 5: Fix + regression test + +Write the regression test **before the fix**, but only if there is a **correct seam** for it. + +A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence. + +**If no correct seam exists, that itself is the finding.** Note it. The codebase architecture is preventing the bug from being locked down. Flag this for the next phase. + +If a correct seam exists: + +1. Turn the minimised repro into a failing test at that seam. +2. Watch it fail. +3. Apply the fix. +4. Watch it pass. +5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario. + +## Phase 6: Cleanup + +Required before declaring done: + +- [ ] Original repro no longer reproduces (re-run the Phase 1 loop) +- [ ] Regression test passes (or absence of seam is documented) +- [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix) +- [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location) +- [ ] The hypothesis that turned out correct is stated in the commit / PR message, so the next debugger learns diff --git a/.agents/skills/diagnosing-bugs/agents/openai.yaml b/.agents/skills/diagnosing-bugs/agents/openai.yaml new file mode 100644 index 0000000..a13a755 --- /dev/null +++ b/.agents/skills/diagnosing-bugs/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Diagnosing Bugs" + short_description: "Diagnose hard bugs and regressions" diff --git a/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh b/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh new file mode 100644 index 0000000..2431984 --- /dev/null +++ b/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Human-in-the-loop reproduction loop. +# Copy this file, edit the steps below, and run it. +# The agent runs the script; the user follows prompts in their terminal. +# +# Usage: +# bash hitl-loop.template.sh +# +# Two helpers: +# step "" → show instruction, wait for Enter +# capture VAR "" → show question, read response into VAR +# +# At the end, captured values are printed as KEY=VALUE for the agent to parse. +# +# `capture` prints its value back to the terminal, where the agent reads it, +# so capture observations, and leave signing in to the user as a `step`. + +set -euo pipefail + +step() { + printf '\n>>> %s\n' "$1" + read -r -p " [Enter when done] " _ +} + +capture() { + local var="$1" question="$2" answer + printf '\n>>> %s\n' "$question" + read -r -p " > " answer + printf -v "$var" '%s' "$answer" +} + +# --- edit below --------------------------------------------------------- + +step "Open the app at http://localhost:3000 and sign in." + +capture ERRORED "Click the 'Export' button. Did it throw an error? (y/n)" + +capture ERROR_MSG "Paste the error message (or 'none'):" + +# --- edit above --------------------------------------------------------- + +printf '\n--- Captured ---\n' +printf 'ERRORED=%s\n' "$ERRORED" +printf 'ERROR_MSG=%s\n' "$ERROR_MSG" diff --git a/.agents/skills/domain-modeling/ADR-FORMAT.md b/.agents/skills/domain-modeling/ADR-FORMAT.md new file mode 100644 index 0000000..d7e61f3 --- /dev/null +++ b/.agents/skills/domain-modeling/ADR-FORMAT.md @@ -0,0 +1,47 @@ +# ADR Format + +ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc. + +Create the `docs/adr/` directory lazily: only when the first ADR is needed. + +## Template + +```md +# {Short title of the decision} + +{1-3 sentences: what's the context, what did we decide, and why.} +``` + +That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections. + +## Optional sections + +Only include these when they add genuine value. Most ADRs won't need them. + +- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited +- **Considered Options**: only when the rejected alternatives are worth remembering +- **Consequences**: only when non-obvious downstream effects need to be called out + +## Numbering + +Scan `docs/adr/` for the highest existing number and increment by one. + +## When to offer an ADR + +All three of these must be true: + +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons + +If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing." + +### What qualifies + +- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres." +- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP." +- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out. +- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s. +- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate. +- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract." +- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months. diff --git a/.agents/skills/domain-modeling/CONTEXT-FORMAT.md b/.agents/skills/domain-modeling/CONTEXT-FORMAT.md new file mode 100644 index 0000000..79bbb32 --- /dev/null +++ b/.agents/skills/domain-modeling/CONTEXT-FORMAT.md @@ -0,0 +1,60 @@ +# CONTEXT.md Format + +## Structure + +```md +# {Context Name} + +{One or two sentence description of what this context is and why it exists.} + +## Language + +**Order**: +{A one or two sentence description of the term} +_Avoid_: Purchase, transaction + +**Invoice**: +A request for payment sent to a customer after delivery. +_Avoid_: Bill, payment request + +**Customer**: +A person or organization that places orders. +_Avoid_: Client, buyer, account +``` + +## Rules + +- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`. +- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does. +- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs. +- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine. + +## Single vs multi-context repos + +**Single context (most repos):** One `CONTEXT.md` at the repo root. + +**Multiple contexts:** A `CONTEXT-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other: + +```md +# Context Map + +## Contexts + +- [Ordering](./src/ordering/CONTEXT.md): receives and tracks customer orders +- [Billing](./src/billing/CONTEXT.md): generates invoices and processes payments +- [Fulfillment](./src/fulfillment/CONTEXT.md): manages warehouse picking and shipping + +## Relationships + +- **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking +- **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices +- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money` +``` + +The skill infers which structure applies: + +- If `CONTEXT-MAP.md` exists, read it to find contexts +- If only a root `CONTEXT.md` exists, single context +- If neither exists, create a root `CONTEXT.md` lazily when the first term is resolved + +When multiple contexts exist, infer which one the current topic relates to. If unclear, ask. diff --git a/.agents/skills/domain-modeling/SKILL.md b/.agents/skills/domain-modeling/SKILL.md new file mode 100644 index 0000000..9b97707 --- /dev/null +++ b/.agents/skills/domain-modeling/SKILL.md @@ -0,0 +1,74 @@ +--- +name: domain-modeling +description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a CONTEXT.md, or recording or editing an ADR. +--- + +# Domain Modeling + +Actively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `CONTEXT.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.) + +## File structure + +Most repos have a single context: + +``` +/ +├── CONTEXT.md +├── docs/ +│ └── adr/ +│ ├── 0001-event-sourced-orders.md +│ └── 0002-postgres-for-write-model.md +└── src/ +``` + +If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives: + +``` +/ +├── CONTEXT-MAP.md +├── docs/ +│ └── adr/ ← system-wide decisions +├── src/ +│ ├── ordering/ +│ │ ├── CONTEXT.md +│ │ └── docs/adr/ ← context-specific decisions +│ └── billing/ +│ ├── CONTEXT.md +│ └── docs/adr/ +``` + +Create files lazily: only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed. + +## During the session + +### Challenge against the glossary + +When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?" + +### Sharpen fuzzy language + +When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account': do you mean the Customer or the User? Those are different things." + +### Discuss concrete scenarios + +When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts. + +### Cross-reference with code + +When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?" + +### Update CONTEXT.md inline + +When a term is resolved, update `CONTEXT.md` right there. Don't batch these up: capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md). + +`CONTEXT.md` should be totally devoid of implementation details. Do not treat `CONTEXT.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else. + +### Offer ADRs sparingly + +Only offer to create an ADR when all three are true: + +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will wonder "why did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons + +If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md). diff --git a/.agents/skills/domain-modeling/agents/openai.yaml b/.agents/skills/domain-modeling/agents/openai.yaml new file mode 100644 index 0000000..7f1522d --- /dev/null +++ b/.agents/skills/domain-modeling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Domain Modeling" + short_description: "Build and sharpen a domain model" diff --git a/.agents/skills/git-guardrails-claude-code/SKILL.md b/.agents/skills/git-guardrails-claude-code/SKILL.md new file mode 100644 index 0000000..58bcdd8 --- /dev/null +++ b/.agents/skills/git-guardrails-claude-code/SKILL.md @@ -0,0 +1,95 @@ +--- +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 intercepts and blocks dangerous git commands before Claude executes them. + +## What Gets Blocked + +- `git push` (all variants including `--force`) +- `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. + +## 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 the 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 a quick test: + +```bash +echo '{"tool_input":{"command":"git push origin main"}}' | +``` + +Should exit with code 2 and print a BLOCKED message to stderr. diff --git a/.agents/skills/git-guardrails-claude-code/agents/openai.yaml b/.agents/skills/git-guardrails-claude-code/agents/openai.yaml new file mode 100644 index 0000000..3f5d756 --- /dev/null +++ b/.agents/skills/git-guardrails-claude-code/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Git Guardrails for Claude Code" + short_description: "Block dangerous git commands" diff --git a/.agents/skills/git-guardrails-claude-code/scripts/block-dangerous-git.sh b/.agents/skills/git-guardrails-claude-code/scripts/block-dangerous-git.sh new file mode 100755 index 0000000..c40b59c --- /dev/null +++ b/.agents/skills/git-guardrails-claude-code/scripts/block-dangerous-git.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +INPUT=$(cat) +COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command') + +DANGEROUS_PATTERNS=( + "git push" + "git reset --hard" + "git clean -fd" + "git clean -f" + "git branch -D" + "git checkout \." + "git restore \." + "push --force" + "reset --hard" +) + +for pattern in "${DANGEROUS_PATTERNS[@]}"; do + if echo "$COMMAND" | grep -qE "$pattern"; then + echo "BLOCKED: '$COMMAND' matches dangerous pattern '$pattern'. The user has prevented you from doing this." >&2 + exit 2 + fi +done + +exit 0 diff --git a/.agents/skills/grill-me/SKILL.md b/.agents/skills/grill-me/SKILL.md new file mode 100644 index 0000000..3947ff9 --- /dev/null +++ b/.agents/skills/grill-me/SKILL.md @@ -0,0 +1,7 @@ +--- +name: grill-me +description: A relentless interview to sharpen a plan or design. +disable-model-invocation: true +--- + +Call the Skill tool with "grilling". diff --git a/.agents/skills/grill-me/agents/openai.yaml b/.agents/skills/grill-me/agents/openai.yaml new file mode 100644 index 0000000..4d6fb0c --- /dev/null +++ b/.agents/skills/grill-me/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill Me" + short_description: "Sharpen a plan through interview" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/grill-with-docs/SKILL.md b/.agents/skills/grill-with-docs/SKILL.md new file mode 100644 index 0000000..62b9efb --- /dev/null +++ b/.agents/skills/grill-with-docs/SKILL.md @@ -0,0 +1,7 @@ +--- +name: grill-with-docs +description: A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go. +disable-model-invocation: true +--- + +Call the Skill tool twice, for "grilling" and "domain-modeling". diff --git a/.agents/skills/grill-with-docs/agents/openai.yaml b/.agents/skills/grill-with-docs/agents/openai.yaml new file mode 100644 index 0000000..5dbe278 --- /dev/null +++ b/.agents/skills/grill-with-docs/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill with Docs" + short_description: "Grill a design and write its docs" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/grilling/SKILL.md b/.agents/skills/grilling/SKILL.md new file mode 100644 index 0000000..8ca78c6 --- /dev/null +++ b/.agents/skills/grilling/SKILL.md @@ -0,0 +1,28 @@ +--- +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. +--- + +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. + +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. + +Format a round like so: + +``` +❓ **Q1** - ****: + +➡️ + +--- + +❓ **Q2** - ****: + +➡️ +``` + +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. diff --git a/.agents/skills/grilling/agents/openai.yaml b/.agents/skills/grilling/agents/openai.yaml new file mode 100644 index 0000000..ddbdb96 --- /dev/null +++ b/.agents/skills/grilling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Grilling" + short_description: "Stress-test thinking a round of questions at a time" diff --git a/.agents/skills/handoff/SKILL.md b/.agents/skills/handoff/SKILL.md new file mode 100644 index 0000000..2eb98a5 --- /dev/null +++ b/.agents/skills/handoff/SKILL.md @@ -0,0 +1,16 @@ +--- +name: handoff +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. + +Include a "suggested skills" section in the document, naming which skills the next agent should call the Skill tool for. + +Do not duplicate content already captured in other artifacts (specs, 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. + +If the user passed arguments, treat them as a description of what the next session will focus on and tailor the doc accordingly. diff --git a/.agents/skills/handoff/agents/openai.yaml b/.agents/skills/handoff/agents/openai.yaml new file mode 100644 index 0000000..6e1d8da --- /dev/null +++ b/.agents/skills/handoff/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Handoff" + short_description: "Compact a conversation into a handoff" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/implement-spec/SKILL.md b/.agents/skills/implement-spec/SKILL.md new file mode 100644 index 0000000..d5097f8 --- /dev/null +++ b/.agents/skills/implement-spec/SKILL.md @@ -0,0 +1,35 @@ +--- +name: implement-spec +description: "Implement a specification in code." +disable-model-invocation: true +--- + +You have been provided a spec. This spec should have tickets associated with it, describing how to implement the spec. + +The goal is a PR which implements the entire spec on a single branch. + +The tickets are not a list of steps. They are a **task graph** with blocking relationships between them. This means there is always a **frontier** of tickets which are ready to be grabbed. + +Communication to and from subagents should be sparse. Communicate primarily through **context pointers**: to the spec, tickets, research notes, and previous commits. Don't duplicate information already available via pointers. + +**Implementer subagents** should be run in the background where possible for **maximum concurrency**. + +## Steps + +1. Read the spec and tickets. Read enough to understand the task graph. + +2. (optional) Use an **exploration subagent** to conduct any exploration required by the tickets - relevant codebase files or external documentation. Ensure the exploration subagent can save files - it should save its markdown notes in a directory outside the repo, accessible by all future subagents. This lets **implementer subagents** focus on implementation rather than exploration. + +3. Create a branch, and a draft PR. The PR should be marked as 'closing' the spec issue and tickets. + +4. Use **implementer subagents** to implement each ticket. Each implementer subagent should work in its own worktree, on its own branch. + +5. Once an **implementer subagent** completes, merge its work to the PR branch with a **merger subagent**. + +6. If this changes the **frontier** of available tickets, kick off more **implementer subagents** to work on the new tickets. This allows for maximum concurrency. + +7. Once all tickets are complete, run /code-review on the PR branch. Fix all issues raised by the code review in a single **implementer subagent**. + +8. Mark the PR as ready for review. + +9. Clean up all **implementer subagent** worktrees. diff --git a/.agents/skills/implement-spec/agents/openai.yaml b/.agents/skills/implement-spec/agents/openai.yaml new file mode 100644 index 0000000..043f27f --- /dev/null +++ b/.agents/skills/implement-spec/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Implement Spec" + short_description: "Implement a whole spec as one PR" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/implement/SKILL.md b/.agents/skills/implement/SKILL.md new file mode 100644 index 0000000..7a0b11f --- /dev/null +++ b/.agents/skills/implement/SKILL.md @@ -0,0 +1,15 @@ +--- +name: implement +description: "Implement a piece of work based on a spec or set of tickets." +disable-model-invocation: true +--- + +Implement the work described by the user in the spec or tickets. + +Use /tdd where possible, at pre-agreed seams. + +Run typechecking regularly, single test files regularly, and the full test suite once at the end. + +Once done, use /code-review to review the work. + +Commit your work to the current branch. diff --git a/.agents/skills/implement/agents/openai.yaml b/.agents/skills/implement/agents/openai.yaml new file mode 100644 index 0000000..f8794dc --- /dev/null +++ b/.agents/skills/implement/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Implement" + short_description: "Build work from a spec or tickets" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/improve-codebase-architecture/HTML-REPORT.md b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md new file mode 100644 index 0000000..e39e825 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md @@ -0,0 +1,123 @@ +# HTML Report Format + +The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic. + +## Scaffold + +```html + + + + + Architecture review for {{repo name}} + + + + + +
+
...
+
...
+
...
+
+ + +``` + +## Header + +Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates. + +## Candidate card + +The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony. + +Each candidate is one `
`: + +- **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 +
+
+    flowchart LR
+      A[OrderHandler] --> B[OrderValidator]
+      B --> C[OrderRepo]
+      C -.leak.-> D[PricingClient]
+      classDef leak stroke:#dc2626,stroke-width:2px;
+      class C,D leak
+  
+
+``` + +### Hand-built boxes-and-arrows (when Mermaid's layout fights you) + +Modules as `
`s with borders and labels. Arrows as inline SVG `` or `` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight. + +### Cross-section (good for layered shallowness) + +Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility. + +### Mass diagram (good for "interface as wide as implementation") + +Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep). + +### Call-graph collapse + +Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it. + +## Style guidance + +- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate). +- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings. +- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling. +- Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI. +- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering. + +## Top recommendation section + +One larger card. Candidate name, one sentence on why, anchor link to its card. That's it. + +## Tone + +Plain English, concise, but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift. + +**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality. + +**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module). + +**Phrasings that fit the style:** + +- "Order intake module is shallow: interface nearly matches the implementation." +- "Pricing leaks across the seam." +- "Deepen: one interface, one place to test." +- "Two adapters justify the seam: HTTP in prod, in-memory in tests." + +**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place. + +No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one. diff --git a/.agents/skills/improve-codebase-architecture/SKILL.md b/.agents/skills/improve-codebase-architecture/SKILL.md new file mode 100644 index 0000000..a578dd0 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/SKILL.md @@ -0,0 +1,71 @@ +--- +name: improve-codebase-architecture +description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick. +disable-model-invocation: true +--- + +# Improve Codebase Architecture + +Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. + +This command is _informed_ by the project's domain model and built on a shared design vocabulary: + +- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary." +- The domain language in `CONTEXT.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate. + +## Process + +### 1. Explore + +**Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look: + +- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below. +- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net. + +Read the project's domain glossary (`CONTEXT.md`) and any ADRs in the area you're touching first. + +Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics; explore organically and note where you experience friction: + +- Where does understanding one concept require bouncing between many small modules? +- Where are modules **shallow**, with an interface nearly as complex as the implementation? +- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)? +- Where do tightly-coupled modules leak across their seams? +- Which parts of the codebase are untested, or hard to test through their current interface? + +Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want. + +### 2. Present candidates as an HTML report + +Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `/architecture-review-.html` so each run gets a fresh file. Open it for the user (`xdg-open ` on Linux, `open ` on macOS, `start ` on Windows) and tell them the absolute path. + +The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual. + +For each candidate, render a card with: + +- **Files**: which files/modules are involved +- **Problem**: why the current architecture is causing friction +- **Solution**: plain English description of what would change +- **Benefits**: explained in terms of locality and leverage, and how tests would improve +- **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening +- **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge + +End the report with a **Top recommendation** section: which candidate you'd tackle first and why. + +**Use CONTEXT.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service." + +**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. + +See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance. + +Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?" + +### 3. Grilling loop + +Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. + +Side effects happen inline as decisions crystallize; call the Skill tool with "domain-modeling" to keep the domain model current as you go: + +- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md`. Create the file lazily if it doesn't exist. +- **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there. +- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones. +- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern. diff --git a/.agents/skills/improve-codebase-architecture/agents/openai.yaml b/.agents/skills/improve-codebase-architecture/agents/openai.yaml new file mode 100644 index 0000000..706fdca --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Improve Codebase Architecture" + short_description: "Find and grill architecture improvements" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/loop-me/SKILL.md b/.agents/skills/loop-me/SKILL.md new file mode 100644 index 0000000..e58a474 --- /dev/null +++ b/.agents/skills/loop-me/SKILL.md @@ -0,0 +1,32 @@ +--- +name: loop-me +description: Grill me about specs for the workflows I want to build, within this workspace. +disable-model-invocation: true +argument-hint: "A workflow to design, or nothing to go find one" +--- + +Run a stateful `/grilling` session whose only output is **workflow** specs. Use the grilling discipline (relentless, a round of questions at a time, a recommended answer attached to each) aimed at the vocabulary and goal below. Create, edit, and delete specs as the grilling resolves things. + +## 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 an implementer agent could build it without asking a single question. Grill until then; nothing is done while a question remains. + +## The workspace + +- `workflows/*.md`: one spec per workflow. +- `NOTES.md`: raw notes on the user's world, the tools they use, the channels they process, and their own terminology for both. When it is empty or thin, interview them about their world before specifying anything. Sharpen fuzzy terms into canonical ones as they surface, and record them here. diff --git a/.agents/skills/loop-me/agents/openai.yaml b/.agents/skills/loop-me/agents/openai.yaml new file mode 100644 index 0000000..1a4f411 --- /dev/null +++ b/.agents/skills/loop-me/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Loop Me" + short_description: "Spec the workflows you want to build" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/migrate-to-shoehorn/SKILL.md b/.agents/skills/migrate-to-shoehorn/SKILL.md new file mode 100644 index 0000000..ae4f965 --- /dev/null +++ b/.agents/skills/migrate-to-shoehorn/SKILL.md @@ -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; + cookies: Record; + // ...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 diff --git a/.agents/skills/migrate-to-shoehorn/agents/openai.yaml b/.agents/skills/migrate-to-shoehorn/agents/openai.yaml new file mode 100644 index 0000000..3bd79ee --- /dev/null +++ b/.agents/skills/migrate-to-shoehorn/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Migrate to Shoehorn" + short_description: "Replace test assertions with shoehorn" diff --git a/.agents/skills/prototype/LOGIC.md b/.agents/skills/prototype/LOGIC.md new file mode 100644 index 0000000..32be86a --- /dev/null +++ b/.agents/skills/prototype/LOGIC.md @@ -0,0 +1,67 @@ +# Logic Prototype + +A single, self-contained HTML file (a **shareable demo**) that lets anyone drive a state model by clicking buttons. Use this when the question is about **business logic, state transitions, or data shape**: the kind of thing that looks reasonable on paper but only feels wrong once you push it through real cases. + +Because it's one file with nothing to install, you can hand it to a non-developer (a designer, a PM, a domain expert) and let them feel the model for themselves. So it speaks their language, not the code's. + +## When this is the right shape + +- "I'm not sure if this state machine handles the edge case where X then Y." +- "Does this data model actually let me represent the case where..." +- "I want to feel out what the API should look like before writing it." +- Anything where someone wants to **press buttons and watch state change**. + +If the question is "what should this look like," this is the wrong branch. Use [UI.md](UI.md). + +## Process + +### 1. State the question + +Before writing code, write down what state model and what question you're prototyping. One paragraph, at the top of the demo (in a visible intro, not just a comment). A logic prototype that answers the wrong question is pure waste, so make the question explicit so it can be checked later, whether the user is watching now or returning to it AFK. + +### 2. Isolate the logic in a portable module + +Put the actual logic (the bit that's answering the question) in a single ` and not a npm package + publicPackages: ["@shopify/polaris-types", "@shopify/app-bridge-types"], + visibility: Visibility.EARLY_ACCESS + }, + [THEME_APIs.LIQUID]: { + name: THEME_APIs.LIQUID, + displayName: "Liquid", + description: "Liquid is an open-source templating language created by Shopify. It is the backbone of Shopify themes and is used to load dynamic content on storefronts. Keywords: liquid, theme, shopify-theme, liquid-component, liquid-block, liquid-section, liquid-snippet, liquid-schemas, shopify-theme-schemas", + category: APICategory.THEME, + visibility: Visibility.PUBLIC + }, + [CONFIGURATION_APIs.CUSTOM_DATA]: { + name: CONFIGURATION_APIs.CUSTOM_DATA, + displayName: "Custom Data", + description: "MUST be used first when prompts mention Metafields or Metaobjects. Use Metafields and Metaobjects to model and store custom data for your app. Metafields extend built-in Shopify data types like products or customers, Metaobjects are custom data types that can be used to store bespoke data structures. Metafield and Metaobject definitions provide a schema and configuration for values to follow.", + category: APICategory.CONFIGURATION, + visibility: Visibility.PUBLIC + } +}; + +// src/schemaOperations/loadAPISchemas.ts +function getDataDirectory() { + const currentDir = path.dirname(fileURLToPath(import.meta.url)); + if (currentDir.includes("dev-mcp") && currentDir.includes("dist") && !currentDir.includes("shopify-dev-tools")) { + return path.join(currentDir, "data"); + } + if (currentDir.includes("/dist") || currentDir.includes("\\dist")) { + const distIndex = currentDir.lastIndexOf(path.sep + "dist"); + if (distIndex !== -1) { + const distRoot = currentDir.substring(0, distIndex + 5); + return path.join(distRoot, "data"); + } else { + return path.join(currentDir, "data"); + } + } + return path.resolve(currentDir, "../data"); +} +var dataDir = getDataDirectory(); +function loadAPISchemas(apis, schemaOptions) { + if (apis.length === 0) { + throw new Error("No APIs provided"); + } + if (schemaOptions) { + if (apis.length !== 1) { + throw new Error( + "schemaOptions can only be provided when requesting a single API" + ); + } + return [ + { + ...schemaOptions, + api: apis[0], + schemaPath: schemaOptions.schemaPath ?? SHOPIFY_APIS2[apis[0]]?.gqlSchemaPath ?? path.join(dataDir, `${apis[0]}_${schemaOptions.name}.json`) + } + ]; + } + const schemasPath = path.join(dataDir, "latest-releases-schemas.json"); + const schemasConfig = JSON.parse( + readFileSync(schemasPath, "utf-8") + ); + const apiVersions = []; + for (const api of apis) { + const versions = schemasConfig[api]; + if (versions) { + const versionsWithApi = versions.map((v) => ({ + ...v, + api, + schemaPath: SHOPIFY_APIS2[api]?.gqlSchemaPath ?? path.join(dataDir, `${api}_${v.name}.json`) + })); + apiVersions.push(...versionsWithApi); + } else if (SHOPIFY_APIS2[api]?.gqlSchemaPath) { + apiVersions.push({ + name: "latest", + latestVersion: true, + api, + schemaPath: SHOPIFY_APIS2[api].gqlSchemaPath + }); + } + } + return apiVersions; +} + +// src/schemaOperations/loadSchemaContent.ts +import { existsSync } from "node:fs"; +import fs from "node:fs/promises"; +import zlib from "node:zlib"; + +// src/schemaOperations/schemaCache.ts +var SchemaCache = class { + cache = /* @__PURE__ */ new Map(); + get(path3) { + return this.cache.get(path3); + } + set(path3, content) { + this.cache.set(path3, content); + } +}; +var schemaCache = new SchemaCache(); + +// src/schemaOperations/loadSchemaContent.ts +async function convertSdlToIntrospectionJson(schemaPath2) { + const { buildSchema, introspectionFromSchema } = await Promise.resolve().then(() => __toESM(require_graphql2(), 1)); + const sdl = await fs.readFile(schemaPath2, "utf-8"); + const introspection = introspectionFromSchema(buildSchema(sdl)); + return JSON.stringify({ data: introspection }); +} +async function loadSchemaContent(schema) { + const schemaPath2 = schema.schemaPath; + const cached = schemaCache.get(schemaPath2); + if (cached) { + return cached; + } + try { + let content; + if (schemaPath2.endsWith(".gz")) { + const compressedData = await fs.readFile(schemaPath2); + content = zlib.gunzipSync(compressedData).toString("utf-8"); + } else if (schemaPath2.endsWith(".graphql") || schemaPath2.endsWith(".graphqls") || schemaPath2.endsWith(".gql")) { + content = await convertSdlToIntrospectionJson(schemaPath2); + } else if (existsSync(schemaPath2)) { + content = await fs.readFile(schemaPath2, "utf-8"); + } else { + const gzPath = `${schemaPath2}.gz`; + if (existsSync(gzPath)) { + const compressedData = await fs.readFile(gzPath); + content = zlib.gunzipSync(compressedData).toString("utf-8"); + } else { + throw new Error(`Schema file not found at ${schemaPath2} or ${gzPath}`); + } + } + schemaCache.set(schemaPath2, content); + return content; + } catch (error) { + console.error(`[graphql-schema-utils] Error loading schema: ${error}`); + throw error; + } +} + +// src/schemaOperations/offlineScopes.ts +var import_graphql = __toESM(require_graphql2(), 1); +function getScopes(data, typeName, fieldName) { + const entry = data.items.find((item) => { + if (fieldName) { + return item.type === "field" && item.typeName === typeName && item.fieldName === fieldName; + } + return item.type === "type" && item.typeName === typeName; + }); + return entry?.offlineScopes || []; +} +function getFieldReturnType(data, typeName, fieldName) { + const entry = data.items.find( + (item) => item.type === "field" && item.typeName === typeName && item.fieldName === fieldName + ); + return entry?.returnType; +} +async function analyzeRequiredOfflineScopes(parsedQueryAST, offlineScopeData, schemaName = "admin") { + const offlineScopes = /* @__PURE__ */ new Set(); + const fragmentMap = new Map( + parsedQueryAST.definitions.filter( + (def) => def.kind === import_graphql.Kind.FRAGMENT_DEFINITION + ).map((fragDef) => [fragDef.name.value, fragDef]) + ); + for (const definition of parsedQueryAST.definitions) { + if (definition.kind === import_graphql.Kind.OPERATION_DEFINITION) { + const operationDef = definition; + if (operationDef.selectionSet) { + const rootTypeName = getRootTypeName( + operationDef.operation, + schemaName + ); + const rootTypeScopes = getScopes(offlineScopeData, rootTypeName); + rootTypeScopes.forEach((scope) => offlineScopes.add(scope)); + walkSelectionSet( + operationDef.selectionSet, + rootTypeName, + offlineScopeData, + offlineScopes, + fragmentMap + ); + } + } + } + return Array.from(offlineScopes); +} +function processFieldSelection(field, parentTypeName, scopeData, offlineScopes) { + const fieldName = field.name.value; + const fieldScopes = getScopes(scopeData, parentTypeName, fieldName); + fieldScopes.forEach((scope) => offlineScopes.add(scope)); + if (!field.selectionSet) { + return { nextSelectionSet: null, nextTypeName: null }; + } + const returnType = getFieldReturnType(scopeData, parentTypeName, fieldName); + if (returnType) { + const typeScopes = getScopes(scopeData, returnType); + typeScopes.forEach((scope) => offlineScopes.add(scope)); + } + return { + nextSelectionSet: field.selectionSet, + nextTypeName: returnType || null + }; +} +function processFragmentSpread(fragmentSpread, fragmentMap, visitedFragments, scopeData, offlineScopes) { + const fragmentName = fragmentSpread.name.value; + if (visitedFragments.has(fragmentName)) { + return { nextSelectionSet: null, nextTypeName: null }; + } + visitedFragments.add(fragmentName); + const fragment = fragmentMap.get(fragmentName); + if (!fragment?.selectionSet) { + return { nextSelectionSet: null, nextTypeName: null }; + } + const typeName = fragment.typeCondition.name.value; + const typeScopes = getScopes(scopeData, typeName); + typeScopes.forEach((scope) => offlineScopes.add(scope)); + return { + nextSelectionSet: fragment.selectionSet, + nextTypeName: typeName + }; +} +function processInlineFragment(inlineFragment, parentTypeName, scopeData, offlineScopes) { + if (!inlineFragment.selectionSet) { + return { nextSelectionSet: null, nextTypeName: null }; + } + const typeName = inlineFragment.typeCondition?.name.value || parentTypeName; + const typeScopes = getScopes(scopeData, typeName); + typeScopes.forEach((scope) => offlineScopes.add(scope)); + return { + nextSelectionSet: inlineFragment.selectionSet, + nextTypeName: typeName + }; +} +function walkSelectionSet(selectionSet, parentTypeName, scopeData, offlineScopes, fragmentMap, visitedFragments = /* @__PURE__ */ new Set()) { + for (const selection of selectionSet.selections) { + let context; + if (selection.kind === import_graphql.Kind.FIELD) { + context = processFieldSelection( + selection, + parentTypeName, + scopeData, + offlineScopes + ); + } else if (selection.kind === import_graphql.Kind.FRAGMENT_SPREAD) { + context = processFragmentSpread( + selection, + fragmentMap, + visitedFragments, + scopeData, + offlineScopes + ); + } else if (selection.kind === import_graphql.Kind.INLINE_FRAGMENT) { + context = processInlineFragment( + selection, + parentTypeName, + scopeData, + offlineScopes + ); + } else { + continue; + } + if (context.nextSelectionSet && context.nextTypeName) { + walkSelectionSet( + context.nextSelectionSet, + context.nextTypeName, + scopeData, + offlineScopes, + fragmentMap, + visitedFragments + ); + } + } +} +function getRootTypeName(operation, schemaName = "admin") { + if (schemaName === "admin") { + return operation === "mutation" ? "Mutation" : "QueryRoot"; + } + return operation === "mutation" ? "Mutation" : "Query"; +} + +// src/validation/createVirtualTSEnvironment.ts +var import_typescript = __toESM(require_typescript(), 1); + +// src/validation/extractComponentValidations.ts +var import_typescript2 = __toESM(require_typescript(), 1); + +// src/validation/validateComponentCodeBlock.ts +var ENFORCE_SHOPIFY_ONLY_COMPONENTS_APIS = [ + TYPESCRIPT_APIs.POLARIS_ADMIN_EXTENSIONS, + TYPESCRIPT_APIs.POLARIS_CHECKOUT_EXTENSIONS, + TYPESCRIPT_APIs.POLARIS_CUSTOMER_ACCOUNT_EXTENSIONS, + TYPESCRIPT_APIs.POS_UI +]; + +// src/validation/index.ts +function isAPIVersionWithAPI(options) { + return options && typeof options.schemaPath === "string"; +} +async function validateGraphQLOperation(graphqlCode, api, options) { + const trimmedCode = graphqlCode.trim(); + if (!trimmedCode) { + return { + validation: { + result: "failed" /* FAILED */, + resultDetail: "No GraphQL operation found in the provided code." + }, + scopes: [] + }; + } + let apiVersion; + let failOnDeprecated = true; + if (options) { + if (isAPIVersionWithAPI(options)) { + apiVersion = options; + } else { + apiVersion = options.apiVersion; + failOnDeprecated = options.failOnDeprecated ?? true; + } + } + let graphQLSchema; + let offlineScopes; + let schemaObj; + try { + const schemas = loadAPISchemas([api], apiVersion); + if (schemas.length === 0) { + throw new Error(`No schema configuration found for API "${api}"`); + } + schemaObj = schemas[0]; + const result = await loadAndBuildGraphQLSchema(schemaObj); + graphQLSchema = result.graphQLSchema; + offlineScopes = result.offlineScopes; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + if (errorMessage.includes("No APIs provided")) { + throw new Error(`API name cannot be empty`); + } + if (errorMessage.includes("Schema file not found")) { + if (apiVersion && apiVersion.name) { + throw new Error( + `Cannot load schema for API "${api}" version "${apiVersion.name}" - the schema file does not exist` + ); + } + throw new Error( + `Cannot load schema for API "${api}" - the schema file does not exist` + ); + } + throw error; + } + return performGraphQLValidation({ + graphqlCode: trimmedCode, + schema: graphQLSchema, + api, + version: schemaObj.name, + offlineScopeData: offlineScopes, + failOnDeprecated + }); +} +async function loadAndBuildGraphQLSchema(apiVersion) { + if (!apiVersion || Object.keys(apiVersion).length === 0) { + throw new Error("No API version provided"); + } + const schemaContent = await loadSchemaContent(apiVersion); + const schemaJson = JSON.parse(schemaContent); + const schemaData = schemaJson.data; + if (apiVersion.api.startsWith("functions_") && schemaData.__schema && schemaData.__schema.types) { + const emptyInputTypes = /* @__PURE__ */ new Set(); + for (const type of schemaData.__schema.types) { + if (type.kind === "INPUT_OBJECT" && type.inputFields && type.inputFields.length === 0) { + emptyInputTypes.add(type.name); + console.debug( + `Found empty INPUT_OBJECT type in ${apiVersion.api}: ${type.name}` + ); + } + } + if (emptyInputTypes.size > 0) { + for (const type of schemaData.__schema.types) { + if (emptyInputTypes.has(type.name)) { + type.inputFields = [ + { + name: "_placeholder", + description: "Placeholder field to satisfy GraphQL spec requirement for non-empty input objects", + type: { + kind: "SCALAR", + name: "String", + ofType: null + }, + defaultValue: null, + isDeprecated: false, + deprecationReason: null + } + ]; + console.debug( + `Patched empty INPUT_OBJECT type in ${apiVersion.api}: ${type.name}` + ); + } + } + } + } + return { + graphQLSchema: (0, import_graphql2.buildClientSchema)(schemaData), + offlineScopes: schemaJson.offline_scopes || { + items: [] + } + }; +} +function parseGraphQLDocument(operation) { + try { + const document = (0, import_graphql2.parse)(operation); + return { success: true, document }; + } catch (parseError) { + return { + success: false, + error: parseError instanceof Error ? parseError.message : String(parseError) + }; + } +} +function validateGraphQLAgainstSchema(schema, document) { + const validationErrors = (0, import_graphql2.validate)(schema, document); + return validationErrors.map((e) => e.message); +} +function getOperationType(document) { + if (document.definitions.length > 0) { + const operationDefinition = document.definitions[0]; + if (operationDefinition.kind === "OperationDefinition") { + return operationDefinition.operation; + } + } + return "operation"; +} +async function performGraphQLValidation(options) { + const { graphqlCode, schema, api, offlineScopeData, failOnDeprecated } = options; + const operation = graphqlCode.trim(); + const parseResult = parseGraphQLDocument(operation); + if (parseResult.success === false) { + return { + validation: { + result: "failed" /* FAILED */, + resultDetail: `GraphQL syntax error: ${parseResult.error}` + }, + scopes: [] + }; + } + const validationErrors = validateGraphQLAgainstSchema( + schema, + parseResult.document + ); + if (validationErrors.length > 0) { + return { + validation: { + result: "failed" /* FAILED */, + resultDetail: `GraphQL validation errors: ${validationErrors.join("; ")}` + }, + scopes: [] + }; + } + const deprecatedFieldErrors = (0, import_graphql2.validate)(schema, parseResult.document, [ + import_graphql2.NoDeprecatedCustomRule + ]); + let offlineScopes = []; + try { + offlineScopes = await analyzeRequiredOfflineScopes( + parseResult.document, + offlineScopeData, + api + ); + } catch (error) { + } + const operationType = getOperationType(parseResult.document); + if (deprecatedFieldErrors.length > 0) { + const deprecatedMessages = deprecatedFieldErrors.map((e) => e.message).join("; "); + if (failOnDeprecated) { + return { + validation: { + result: "failed" /* FAILED */, + resultDetail: `Deprecated fields used: ${deprecatedMessages}` + }, + scopes: offlineScopes + }; + } else { + return { + validation: { + result: "inform" /* INFORM */, + resultDetail: `Successfully validated GraphQL ${operationType} against schema. Note: ${deprecatedMessages}` + }, + scopes: offlineScopes + }; + } + } + return { + validation: { + result: "success" /* SUCCESS */, + resultDetail: `Successfully validated GraphQL ${operationType} against schema.` + }, + scopes: offlineScopes + }; +} + +// src/agent-skills/scripts/instrumentation.ts +import { randomUUID } from "crypto"; +var SHOPIFY_DEV_BASE_URL = process.env.DEV && process.env.DEV !== "false" ? "https://shopify-dev.shop.dev/" : "https://shopify.dev/"; +function isProductionVersion() { + return /^\d+\.\d+\.\d+$/.test("1.5.0"); +} +function isInstrumentationDisabled() { + if (!isProductionVersion()) return true; + try { + return process.env.OPT_OUT_INSTRUMENTATION === "true"; + } catch { + return false; + } +} +function newArtifactId() { + return randomUUID(); +} +async function reportValidation(toolName, result, opts) { + if (isInstrumentationDisabled()) return; + try { + const clientName = opts?.clientName ?? process.env.CLIENT_NAME; + const clientModel = opts?.clientModel ?? process.env.CLIENT_MODEL; + const headers = { + "Content-Type": "application/json", + Accept: "application/json", + "Cache-Control": "no-cache", + "X-Shopify-Surface": "skills", + "X-Shopify-Client-Version": "1.5.0", + "X-Shopify-MCP-Version": "1.5.0", + "X-Shopify-Timestamp": (/* @__PURE__ */ new Date()).toISOString() + }; + if (clientName) headers["X-Shopify-Client-Name"] = clientName; + if (clientModel) headers["X-Shopify-Client-Model"] = clientModel; + const parameters = { skill: "shopify-storefront-graphql" }; + if (opts?.artifactId) { + parameters.artifactId = opts.artifactId; + parameters.revision = opts.revision ?? 1; + } + const url = new URL("/mcp/usage", SHOPIFY_DEV_BASE_URL); + await fetch(url.toString(), { + method: "POST", + headers, + body: JSON.stringify({ + tool: toolName, + parameters, + result: JSON.stringify(result) + }) + }); + } catch { + } +} + +// src/agent-skills/scripts/validate_graphql.ts +var { values } = parseArgs({ + options: { + code: { type: "string", short: "c" }, + file: { type: "string", short: "f" }, + model: { type: "string", short: "m" }, + "client-name": { type: "string" }, + "artifact-id": { type: "string" }, + revision: { type: "string" } + }, + allowPositionals: true +}); +var __filename2 = fileURLToPath2(import.meta.url); +var __dirname2 = path2.dirname(__filename2); +var schemaPath = path2.join(__dirname2, "..", "assets", "storefront-graphql_2026-01.json.gz"); +async function readOperation() { + if (values.code) return values.code; + if (values.file) return readFileSync2(values.file, "utf-8"); + const chunks = []; + for await (const chunk of process.stdin) chunks.push(chunk); + const text = Buffer.concat(chunks).toString("utf-8").trim(); + if (!text) { + console.error( + "No GraphQL operation provided. Use --code, --file, or pipe via stdin." + ); + process.exit(1); + } + return text; +} +async function main() { + const artifactId = values["artifact-id"] ?? newArtifactId(); + const revision = values.revision ? Number(values.revision) : 1; + const code = await readOperation(); + const result = await validateGraphQLOperation( + code, + "storefront-graphql", + { + apiVersion: { + schemaPath, + api: "storefront-graphql", + name: "", + latestVersion: false + }, + failOnDeprecated: false + } + ); + const output = { + success: result.validation.result !== "failed" /* FAILED */, + result: result.validation.result, + details: result.validation.resultDetail, + scopes: result.scopes ?? [], + artifactId + }; + console.log(JSON.stringify(output, null, 2)); + await reportValidation("validate_graphql", output, { + clientModel: values.model ?? process.env.CLIENT_MODEL, + clientName: values["client-name"] ?? process.env.CLIENT_NAME, + artifactId, + revision + }); + process.exit(output.success ? 0 : 1); +} +main().catch(async (error) => { + const output = { + success: false, + result: "error", + details: error instanceof Error ? error.message : String(error) + }; + console.log(JSON.stringify(output)); + await reportValidation("validate_graphql", output, { + clientModel: values.model ?? process.env.CLIENT_MODEL, + clientName: values["client-name"] ?? process.env.CLIENT_NAME + }); + process.exit(1); +}); +/*! Bundled license information: + +typescript/lib/typescript.js: + (*! ***************************************************************************** + Copyright (c) Microsoft Corporation. All rights reserved. + Licensed under the Apache License, Version 2.0 (the "License"); you may not use + this file except in compliance with the License. You may obtain a copy of the + License at http://www.apache.org/licenses/LICENSE-2.0 + + THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED + WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, + MERCHANTABLITY OR NON-INFRINGEMENT. + + See the Apache Version 2.0 License for specific language governing permissions + and limitations under the License. + ***************************************************************************** *) +*/ diff --git a/.agents/skills/tdd/SKILL.md b/.agents/skills/tdd/SKILL.md new file mode 100644 index 0000000..8fc0867 --- /dev/null +++ b/.agents/skills/tdd/SKILL.md @@ -0,0 +1,38 @@ +--- +name: tdd +description: Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests. +--- + +# Test-Driven Development + +TDD is the red → green loop. This skill is the reference that makes that loop produce tests worth keeping: what a good test is, where tests go, the anti-patterns, and the rules of the loop. Every section applies on every cycle: consult them before and during the loop, not after. + +When exploring the codebase, read `CONTEXT.md` (if it exists) so test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching. + +## What a good test is + +Tests verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't. A good test reads like a specification: "user can checkout with valid cart" tells you exactly what capability exists, and it survives refactors because it doesn't care about internal structure. + +See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines. + +## Seams: where tests go + +A **seam** is the public boundary you test at: the interface where you observe behavior without reaching inside. Tests live at seams, never against internals. + +**Test only at pre-agreed seams.** Before writing any test, write down the seams under test and confirm them with the user. No test is written at an unconfirmed seam. You can't test everything, so agreeing the seams up front is how testing effort lands on the critical paths and complex logic instead of every edge case. + +Ask: "What's the public interface, and which seams should we test?" + +When the shape of that interface is itself in question (how deep the module is, where the seam belongs, what the interface should expose), call the Skill tool with "codebase-design" for the vocabulary. It is the shared source of the module, interface, depth, seam, adapter, leverage and locality terms, and it is a reference to consult, not a session to run. + +## Anti-patterns + +- **Implementation-coupled**: mocks internal collaborators, tests private methods, or verifies through a side channel (querying the database instead of using the interface). The tell: the test breaks when you refactor but behavior hasn't changed. +- **Tautological**: the assertion recomputes the expected value the way the code does (`expect(add(a, b)).toBe(a + b)`, a snapshot derived by hand the same way, a constant asserted equal to itself), so it passes by construction and can never disagree with the code. Expected values must come from an independent source of truth: a known-good literal, a worked example, the spec. +- **Horizontal slicing**: writing all tests first, then all implementation. Bulk tests verify _imagined_ behavior: you test the _shape_ of things rather than user-facing behavior, the tests go insensitive to real changes, and you commit to test structure before understanding the implementation. Work in **vertical slices** instead: one test → one implementation → repeat, each test a **tracer bullet** that responds to what the last cycle taught you. + +## Rules of the loop + +- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features. +- **One slice at a time.** One seam, one test, one minimal implementation per cycle. +- **Refactoring is not part of the loop.** It belongs to the review stage (see the `code-review` skill), not the red → green implementation cycle. diff --git a/.agents/skills/tdd/agents/openai.yaml b/.agents/skills/tdd/agents/openai.yaml new file mode 100644 index 0000000..651b838 --- /dev/null +++ b/.agents/skills/tdd/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "TDD" + short_description: "Test-driven red-green-refactor" diff --git a/.agents/skills/tdd/mocking.md b/.agents/skills/tdd/mocking.md new file mode 100644 index 0000000..71cbfee --- /dev/null +++ b/.agents/skills/tdd/mocking.md @@ -0,0 +1,59 @@ +# When to Mock + +Mock at **system boundaries** only: + +- External APIs (payment, email, etc.) +- Databases (sometimes - prefer test DB) +- Time/randomness +- File system (sometimes) + +Don't mock: + +- Your own classes/modules +- Internal collaborators +- Anything you control + +## Designing for Mockability + +At system boundaries, design interfaces that are easy to mock: + +**1. Use dependency injection** + +Pass external dependencies in rather than creating them internally: + +```typescript +// Easy to mock +function processPayment(order, paymentClient) { + return paymentClient.charge(order.total); +} + +// Hard to mock +function processPayment(order) { + const client = new StripeClient(process.env.STRIPE_KEY); + return client.charge(order.total); +} +``` + +**2. Prefer SDK-style interfaces over generic fetchers** + +Create specific functions for each external operation instead of one generic function with conditional logic: + +```typescript +// GOOD: Each function is independently mockable +const api = { + getUser: (id) => fetch(`/users/${id}`), + getOrders: (userId) => fetch(`/users/${userId}/orders`), + createOrder: (data) => fetch('/orders', { method: 'POST', body: data }), +}; + +// BAD: Mocking requires conditional logic inside the mock +const api = { + fetch: (endpoint, options) => fetch(endpoint, options), +}; +``` + +The SDK approach means: +- Each mock returns one specific shape +- No conditional logic in test setup +- Easier to see which endpoints a test exercises +- Type safety per endpoint diff --git a/.agents/skills/tdd/tests.md b/.agents/skills/tdd/tests.md new file mode 100644 index 0000000..7ab8647 --- /dev/null +++ b/.agents/skills/tdd/tests.md @@ -0,0 +1,77 @@ +# Good and Bad Tests + +## Good Tests + +**Integration-style**: Test through real interfaces, not mocks of internal parts. + +```typescript +// GOOD: Tests observable behavior +test("user can checkout with valid cart", async () => { + const cart = createCart(); + cart.add(product); + const result = await checkout(cart, paymentMethod); + expect(result.status).toBe("confirmed"); +}); +``` + +Characteristics: + +- Tests behavior users/callers care about +- Uses public API only +- Survives internal refactors +- Describes WHAT, not HOW +- One logical assertion per test + +## Bad Tests + +**Implementation-detail tests**: Coupled to internal structure. + +```typescript +// BAD: Tests implementation details +test("checkout calls paymentService.process", async () => { + const mockPayment = jest.mock(paymentService); + await checkout(cart, payment); + expect(mockPayment.process).toHaveBeenCalledWith(cart.total); +}); +``` + +Red flags: + +- Mocking internal collaborators +- Testing private methods +- Asserting on call counts/order +- Test breaks when refactoring without behavior change +- Test name describes HOW not WHAT +- Verifying through external means instead of interface + +```typescript +// BAD: Bypasses interface to verify +test("createUser saves to database", async () => { + await createUser({ name: "Alice" }); + const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]); + expect(row).toBeDefined(); +}); + +// GOOD: Verifies through interface +test("createUser makes user retrievable", async () => { + const user = await createUser({ name: "Alice" }); + const retrieved = await getUser(user.id); + expect(retrieved.name).toBe("Alice"); +}); +``` + +**Tautological tests**: Expected value restates the implementation, so the test passes by construction. + +```typescript +// BAD: Expected value is recomputed the way the code computes it +test("calculateTotal sums line items", () => { + const items = [{ price: 10 }, { price: 5 }]; + const expected = items.reduce((sum, i) => sum + i.price, 0); + expect(calculateTotal(items)).toBe(expected); +}); + +// GOOD: Expected value is an independent, known literal +test("calculateTotal sums line items", () => { + expect(calculateTotal([{ price: 10 }, { price: 5 }])).toBe(15); +}); +``` diff --git a/.agents/skills/teach/GLOSSARY-FORMAT.md b/.agents/skills/teach/GLOSSARY-FORMAT.md new file mode 100644 index 0000000..fdd7e36 --- /dev/null +++ b/.agents/skills/teach/GLOSSARY-FORMAT.md @@ -0,0 +1,35 @@ +# GLOSSARY.md Format + +`GLOSSARY.md` is the canonical language for this teaching workspace. All explainers, exercises, and learning records should adhere to its terminology. Building it is itself part of learning: compressing a concept into a tight definition is evidence the user understands it. + +## Structure + +```md +# {Topic} Glossary + +{One or two sentence description of the topic this glossary covers.} + +## Terms + +**Hypertrophy**: +Muscle growth driven by mechanical tension and metabolic stress over repeated training sessions. +_Avoid_: Bulking, getting big + +**Progressive overload**: +Systematically increasing the demand on a muscle over time, via load, volume, or intensity. +_Avoid_: Pushing harder, levelling up + +**RPE (Rate of Perceived Exertion)**: +A 1–10 self-rating of how hard a set felt, where 10 is failure and 8 means two reps left in the tank. +_Avoid_: Effort score, intensity rating +``` + +## Rules + +- **Add a term only when the user understands it.** The glossary is a record of compressed knowledge, not a dictionary the user reads to learn. If the user has just been introduced to a concept, wait until they can use it correctly before promoting it here. +- **Be opinionated.** When several words exist for the same concept, pick the best one and list the rest as aliases to avoid. This is how language compresses. +- **Keep definitions tight.** One or two sentences. Define what the term IS, not what it does or how to do it. +- **Use the glossary's own terms inside definitions.** Once a term is in the glossary, prefer it everywhere, including inside other definitions. This is what makes complex terms easier to grasp later. +- **Group under subheadings** when natural clusters emerge (e.g. `## Anatomy`, `## Programming`). A flat list is fine when terms cohere. +- **Flag ambiguities explicitly.** If a term is used loosely in the wider field, note the resolution: "In this workspace, 'set' always means a working set; warm-ups are tracked separately." +- **Revise as understanding deepens.** A definition the user wrote in week one may be wrong by week six. Update in place; do not leave stale entries. diff --git a/.agents/skills/teach/LEARNING-RECORD-FORMAT.md b/.agents/skills/teach/LEARNING-RECORD-FORMAT.md new file mode 100644 index 0000000..953c614 --- /dev/null +++ b/.agents/skills/teach/LEARNING-RECORD-FORMAT.md @@ -0,0 +1,46 @@ +# Learning Record Format + +Learning records live in `./learning-records/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc. Create the directory lazily: only when the first record is written. + +They are the teaching equivalent of ADRs: they capture non-obvious lessons, key insights, and stated prior knowledge that will steer future sessions. They are used to calculate the zone of proximal development. + +## Template + +```md +# {Short title of what was learned or established} + +{1-3 sentences: what was learned (or what prior knowledge was established), and why it matters for future sessions.} +``` + +That is the whole format. A learning record can be a single paragraph. The value is recording _that_ this is now known and _why_ it changes what to teach next, not in filling out sections. + +## Optional sections + +Only include these when they add genuine value. Most records won't need them. + +- **Status** frontmatter (`active | superseded by LR-NNNN`): useful when an earlier understanding turns out to be wrong and is replaced. +- **Evidence**: how the user demonstrated the understanding (a question answered, an exercise completed, prior experience cited). Useful when the claim might be revisited. +- **Implications**: what this unlocks or rules out for future sessions. Worth recording when non-obvious. + +## Numbering + +Scan `./learning-records/` for the highest existing number and increment by one. + +## When to write a learning record + +Write one when any of these is true: + +1. **The user demonstrated genuine understanding of something non-trivial**: not just exposure, but evidence they can use the concept correctly. This sets a new floor for what to teach next. +2. **The user disclosed prior knowledge**: "I already know X." Record it so future sessions don't re-teach it. Also record the _depth_ claimed. +3. **A misconception was corrected**: the user previously believed something wrong and now sees why. These are high-value: they predict future stumbling blocks for related topics. +4. **The mission shifted in response to learning**: the user discovered they cared about something different than they thought. Cross-link to [[MISSION.md]] and update it. + +### What does _not_ qualify + +- Material that was merely covered. Coverage is not learning. Wait for evidence. +- Anything already captured tersely in [[GLOSSARY.md]] as a term definition. Don't duplicate. +- Session-by-session activity logs. Learning records are not a journal: they are decision-grade insights. + +## Supersession + +When a later record contradicts an earlier one (the user's understanding deepened or corrected), mark the old record `Status: superseded by LR-NNNN` rather than deleting it. The history of how understanding evolved is itself useful signal. diff --git a/.agents/skills/teach/MISSION-FORMAT.md b/.agents/skills/teach/MISSION-FORMAT.md new file mode 100644 index 0000000..45250bb --- /dev/null +++ b/.agents/skills/teach/MISSION-FORMAT.md @@ -0,0 +1,31 @@ +# MISSION.md Format + +`MISSION.md` lives at the workspace root. It captures the _reason_ the user is learning this topic. Every teaching decision (what to teach next, which resources to surface, which exercises to design) should trace back to this document. + +## Template + +```md +# Mission: {Topic} + +## Why +{1-3 sentences. The concrete real-world goal the user is chasing. What changes in their life or work when they have this skill? Avoid abstract framings like "to understand X"; push for the underlying outcome.} + +## Success looks like +- {A specific, observable thing the user will be able to do} +- {Another specific thing} +- {…} + +## Constraints +- {Time, budget, prior commitments, learning preferences, anything that bounds the approach} + +## Out of scope +- {Adjacent topics the user explicitly does not want to chase right now, protecting the zone of proximal development} +``` + +## Rules + +- **One mission per workspace.** If the user wants to learn two unrelated things, that is two workspaces. +- **Concrete over abstract.** "Run a half marathon by October" beats "get fitter." "Ship a Rust CLI to my team" beats "learn Rust." +- **Push back on vagueness.** If the user cannot articulate why, interview them before writing anything. A bad mission is worse than no mission. +- **Revise when reality shifts.** Missions change. When the user's goal moves, update this file: don't leave a stale mission steering future sessions. +- **Keep it short.** If `MISSION.md` runs past a screen, it has stopped being a compass and started being a plan. diff --git a/.agents/skills/teach/RESOURCES-FORMAT.md b/.agents/skills/teach/RESOURCES-FORMAT.md new file mode 100644 index 0000000..18b588c --- /dev/null +++ b/.agents/skills/teach/RESOURCES-FORMAT.md @@ -0,0 +1,32 @@ +# RESOURCES.md Format + +`RESOURCES.md` is the curated set of trusted sources for this topic. Knowledge for explainers should be drawn from here, not from parametric guesses. Wisdom comes from the communities listed here. + +## Structure + +```md +# {Topic} Resources + +## Knowledge + +- [Book: _The Science and Practice of Strength Training_ by Zatsiorsky & Kraemer](https://example.com) + Foundational text on programming and adaptation. Use for: anything to do with periodisation, recovery, intensity zones. +- [Article: "How Much Should I Train?" by Greg Nuckols (Stronger By Science)](https://example.com) + Evidence-based review of volume landmarks. Use for: weekly set targets per muscle group. + +## Wisdom (Communities) + +- [r/weightroom](https://reddit.com/r/weightroom) + High-signal subreddit, moderated against bro-science. Use for: programme critique, plateau troubleshooting. +- Local: Tuesday strength class at {gym name} + Use for: real-time coaching feedback on lifts. +``` + +## Rules + +- **High-trust only.** Prefer primary sources, recognised experts, peer-reviewed work, and communities with strong moderation. If a resource is marketing dressed as education, leave it out. +- **Annotate every entry.** A bare link is useless in three months. Add one line: what it covers and when to reach for it. +- **Group by Knowledge / Wisdom.** Mirrors the philosophy in [SKILL.md](./SKILL.md). It is fine for a resource to appear in only one group. +- **Surface gaps explicitly.** If no good resource exists for an area the mission needs, write a `## Gaps` section listing what is missing. This drives future search. +- **Prune ruthlessly.** A resource that turned out to be wrong, shallow, or off-mission should be removed, not buried. Better five sharp sources than thirty mediocre ones. +- **Record community preferences.** If the user has opted out of joining communities, note it here so future sessions don't keep proposing them. diff --git a/.agents/skills/teach/SKILL.md b/.agents/skills/teach/SKILL.md new file mode 100644 index 0000000..c679eec --- /dev/null +++ b/.agents/skills/teach/SKILL.md @@ -0,0 +1,140 @@ +--- +name: teach +description: Teach the user a new skill or concept, within this workspace. +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. + +## Teaching Workspace + +Treat the current directory as a teaching workspace. The state of their learning is captured in this directory in several files: + +- `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). +- `./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-.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 + +To learn at a deep level, the user needs three things: + +- **Knowledge**, captured from high-quality, high-trust resources +- **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. + +Some topics may require more skills than knowledge. Learning more about theoretical physics might be more knowledge-based. For yoga, more skills-based. + +### Fluency vs Storage Strength + +You should be careful to split between two types of learning: + +- **Fluency strength**: in-the-moment retrieval of knowledge +- **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: + +- Using retrieval practice (recall from memory) +- Spacing (distributing practice over time) +- Interleaving (mixing up different but related topics in practice - for skills practice only) + +## Lessons + +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-.html` where the number increments each time. + +A lesson should be **beautiful**, with 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, and anything else 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. diff --git a/.agents/skills/teach/agents/openai.yaml b/.agents/skills/teach/agents/openai.yaml new file mode 100644 index 0000000..3452a85 --- /dev/null +++ b/.agents/skills/teach/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Teach" + short_description: "Learn a concept in a guided workspace" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/to-questionnaire/SKILL.md b/.agents/skills/to-questionnaire/SKILL.md new file mode 100644 index 0000000..dadd0c0 --- /dev/null +++ b/.agents/skills/to-questionnaire/SKILL.md @@ -0,0 +1,54 @@ +--- +name: to-questionnaire +description: Turn a decision you can't fully answer into a questionnaire for someone else to fill in. +disable-model-invocation: true +--- + +Turn something the user can't answer alone into a **questionnaire**: a Markdown document they hand to one person to fill in async, or fill out together over a meeting. The recipient holds knowledge the user lacks; the questionnaire pulls it out of them. + +**Grill the send, not the subject.** Interview the user only about the _send_, which they can always answer: who it goes to, and what they need back. The questions in the document then target the **gap** between what the recipient knows and what the user needs. + + +1. **Who is it going to?** Ask, in one exchange, the recipient's role, expertise, and relationship to the user. This fixes the questionnaire's tone and how much context it must carry. Done when you know who the recipient is and what they know that the user doesn't. + +2. **What do you need back?** Ask, in one exchange, the specific decisions or facts the user can't resolve alone and needs from this person. Done when you have a concrete list of what the user must walk away able to do or decide. + +3. **Write the questionnaire.** Draft questions aimed at the gap from steps 1–2, following the Document structure below. Write it to `to-questionnaire-.md` in the current directory (slug from the topic) and report the path. Done when the file exists and every item the user named in step 2 is covered by a question. + +## Document structure + +Frame the document as a **discovery questionnaire**: the user lacks context, the recipient holds it. Order questions most-important-first, since async means you may only get one pass, and group them under `##` headings by theme once there are more than a handful. Write it using the template below. + + + +# + +**Purpose:** why this questionnaire exists and the decision riding on it. + +**From:** , **To:** , **How your answers will be used:** + +## Context + +One paragraph orienting a recipient who wasn't in the user's head. Enough to answer well, not a page. + +## How to answer + +Deadline and rough effort. Partial answers and "I don't know" are useful: flag anything you're unsure of rather than skipping it. + +## + +One `##` section per theme. Under each, its questions, most-important-first. Every question is one idea, never compound, with an answer stub directly beneath, and a one-line _why this matters_ only where the question could be misread or invite a throwaway answer. + + +### What load is the system expected to handle at launch? + +_Why this matters: it decides whether we provision for burst traffic now or defer it._ + +> + + +## Anything else? + +A closing catch-all: anything we didn't ask that we should know? + + diff --git a/.agents/skills/to-questionnaire/agents/openai.yaml b/.agents/skills/to-questionnaire/agents/openai.yaml new file mode 100644 index 0000000..a58d147 --- /dev/null +++ b/.agents/skills/to-questionnaire/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "To Questionnaire" + short_description: "Front-load questions into a doc for someone to answer" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/to-spec/SKILL.md b/.agents/skills/to-spec/SKILL.md new file mode 100644 index 0000000..3f52599 --- /dev/null +++ b/.agents/skills/to-spec/SKILL.md @@ -0,0 +1,75 @@ +--- +name: to-spec +description: "Turn the current conversation into a spec and publish it to the project issue tracker: no interview, just synthesis of what you've already discussed." +disable-model-invocation: true +--- + +This skill takes the current conversation context and codebase understanding and produces a spec. Do NOT interview the user; just synthesize what you already know. + +The issue tracker and triage label vocabulary should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +## Process + +1. Explore the repo to understand the current state of the codebase, if you haven't already. Use the project's domain glossary vocabulary throughout the spec, and respect any ADRs in the area you're touching. + +2. Sketch out the seams at which you're going to test the feature. Existing seams should be preferred to new ones. Use the highest seam possible. If new seams are needed, propose them at the highest point you can. The fewer seams across the codebase, the better - the ideal number is one. + +Check with the user that these seams match their expectations. + +3. Write the spec using the template below, then publish it to the project issue tracker. Apply the `ready-for-agent` triage label - no need for additional triage. + + + +## Problem Statement + +The problem that the user is facing, from the user's perspective. + +## Solution + +The solution to the problem, from the user's perspective. + +## User Stories + +A LONG, numbered list of user stories. Each user story should be in the format of: + +1. As an , I want a , so that + + +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 + + +This list of user stories should be extremely extensive and cover all aspects of the feature. + +## Implementation Decisions + +A list of implementation decisions that were made. This can include: + +- The modules that will be built/modified +- The interfaces of those modules that will be modified +- Technical clarifications from the developer +- Architectural decisions +- Schema changes +- API contracts +- Specific interactions + +Do NOT include specific file paths or code snippets. They may end up being outdated very quickly. + +Exception: if a prototype produced a snippet that encodes a decision more precisely than prose can (state machine, reducer, schema, type shape), inline it within the relevant decision and note briefly that it came from a prototype. Trim to the decision-rich parts, not a working demo, just the important bits. + +## Testing Decisions + +A list of testing decisions that were made. Include: + +- A description of what makes a good test (only test external behavior, not implementation details) +- Which modules will be tested +- Prior art for the tests (i.e. similar types of tests in the codebase) + +## Out of Scope + +A description of the things that are out of scope for this spec. + +## Further Notes + +Any further notes about the feature. + + diff --git a/.agents/skills/to-spec/agents/openai.yaml b/.agents/skills/to-spec/agents/openai.yaml new file mode 100644 index 0000000..549e6f7 --- /dev/null +++ b/.agents/skills/to-spec/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "To Spec" + short_description: "Turn a conversation into a spec" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/to-tickets/SKILL.md b/.agents/skills/to-tickets/SKILL.md new file mode 100644 index 0000000..e868c83 --- /dev/null +++ b/.agents/skills/to-tickets/SKILL.md @@ -0,0 +1,105 @@ +--- +name: to-tickets +description: Break a plan, spec, or the current conversation into a set of tracer-bullet tickets, each declaring its blocking edges, published to the configured tracker (edges as text in one file per ticket locally, or native blocking links on a real tracker). +disable-model-invocation: true +--- + +# To Tickets + +Break a plan, spec, or conversation into a set of **tickets**: tracer-bullet vertical slices, each declaring the tickets that **block** it. + +The issue tracker and triage label vocabulary should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +## Process + +### 1. Gather context + +Work from whatever is already in the conversation context. If the user passes a reference (a spec path, an issue number or URL) as an argument, fetch it and read its full body and comments. + +### 2. Explore the codebase (optional) + +If you have not already explored the codebase, do so to understand the current state of the code. Ticket titles and descriptions should use the project's domain glossary vocabulary, and respect ADRs in the area you're touching. + +Look for opportunities to prefactor the code to make the implementation easier. "Make the change easy, then make the easy change." + +### 3. Draft vertical slices + +Break the work into **tracer bullet** tickets. + + + +- Each slice cuts a narrow but COMPLETE path through every layer (schema, API, UI, tests): vertical, NOT a horizontal slice of one layer +- A completed slice is demoable or verifiable on its own +- Each slice is sized to fit in a single fresh context window +- Any prefactoring should be done first + + + +Give each ticket its **blocking edges**: the other tickets that must complete before it can start. A ticket with no blockers can start immediately. + +**Wide refactors are the exception to vertical slicing.** A **wide refactor** is one mechanical change (rename a column, retype a shared symbol) whose **blast radius** fans across the whole codebase, so a single edit breaks thousands of call sites at once and no vertical slice can land green. Don't force it into a tracer bullet; sequence it as **expand–contract**. First expand: add the new form beside the old so nothing breaks. Then migrate the call sites over in batches sized by blast radius (per package, per directory), each batch its own ticket blocked by the expand, keeping CI green batch to batch because the old form still exists. Finally contract: delete the old form once no caller remains, in a ticket blocked by every migrate batch. When even the batches can't stay green alone, keep the sequence but let them share an integration branch that all block a final integrate-and-verify ticket; green is promised only there. + +### 4. Quiz the user + +Present the proposed breakdown as a numbered list. For each ticket, show: + +- **Title**: short descriptive name +- **Blocked by**: which other tickets (if any) must complete first +- **What it delivers**: the end-to-end behaviour this ticket makes work + +Ask the user: + +- Does the granularity feel right? (too coarse / too fine) +- Are the blocking edges correct: does each ticket only depend on tickets that genuinely gate it? +- Should any tickets be merged or split further? + +Iterate until the user approves the breakdown. + +### 5. Publish the tickets to the configured tracker + +Publish the approved tickets. **How** depends on the tracker `/setup-matt-pocock-skills` configured; the tickets are the same either way, only the shape of the blocking edges changes: + +- **Local files** → write one file per ticket under `.scratch//issues/-.md`, numbered from `01` in dependency order (blockers first). Each file's "Blocked by" lists the numbers/titles it depends on. Use the per-ticket file template below: one ticket per file, never a single combined file. +- **A real issue tracker (GitHub, Linear, …)** → publish one issue per ticket in dependency order (blockers first) so each ticket's blocking edges can reference real identifiers. Use the platform's native blocking / sub-issue relationship where it has one; otherwise set each ticket's "Blocked by" to the blocking issues. Apply the `ready-for-agent` triage label unless instructed otherwise; the tickets are agent-grabbable by construction. + +Work the **frontier**: any ticket whose blockers are all done. For a purely linear chain that means top to bottom. + +Do NOT close or modify any parent issue. + + + +# : + +**What to build:** the end-to-end behaviour this ticket makes work, from the user's perspective, not a layer-by-layer implementation list. + +**Blocked by:** the numbers/titles of the tickets that gate this one, or "None (can start immediately)". + +**Status:** ready-for-agent + +- [ ] Acceptance criterion 1 +- [ ] Acceptance criterion 2 + + + + + +## Parent + +A reference to the parent issue on the tracker (if the source was an existing issue, otherwise omit this section). + +## What to build + +The end-to-end behaviour this ticket makes work, from the user's perspective, not layer-by-layer implementation. + +## Acceptance criteria + +- [ ] Criterion 1 +- [ ] Criterion 2 + +## Blocked by + +- A reference to each blocking ticket, or "None (can start immediately)". + + + +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. diff --git a/.agents/skills/to-tickets/agents/openai.yaml b/.agents/skills/to-tickets/agents/openai.yaml new file mode 100644 index 0000000..24605a5 --- /dev/null +++ b/.agents/skills/to-tickets/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "To Tickets" + short_description: "Split a plan into tracer-bullet tickets" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/triage/AGENT-BRIEF.md b/.agents/skills/triage/AGENT-BRIEF.md new file mode 100644 index 0000000..1462fcd --- /dev/null +++ b/.agents/skills/triage/AGENT-BRIEF.md @@ -0,0 +1,207 @@ +# Writing Agent Briefs + +An agent brief is a structured comment posted on a GitHub issue or PR when it moves to `ready-for-agent`. It is the authoritative specification that an AFK agent will work from. The original body and discussion are context: the agent brief is the contract. + +The brief states **what the agent should do**, which stretches to both surfaces: for an issue, that's building the change from nothing; for a PR, it's what's left to do *to the existing diff*: finish it, close gaps, address review points. Same principles either way; the PR example below shows the difference. + +## Principles + +### Durability over precision + +The issue may sit in `ready-for-agent` for days or weeks. The codebase will change in the meantime. Write the brief so it stays useful even as files are renamed, moved, or refactored. + +- **Do** describe interfaces, types, and behavioral contracts +- **Do** name specific types, function signatures, or config shapes that the agent should look for or modify +- **Don't** reference file paths: they go stale +- **Don't** reference line numbers +- **Don't** assume the current implementation structure will remain the same + +### Behavioral, not procedural + +Describe **what** the system should do, not **how** to implement it. The agent will explore the codebase fresh and make its own implementation decisions. + +- **Good:** "The `SkillConfig` type should accept an optional `schedule` field of type `CronExpression`" +- **Bad:** "Open src/types/skill.ts and add a schedule field on line 42" +- **Good:** "When a user runs `/triage` with no arguments, they should see a summary of issues needing attention" +- **Bad:** "Add a switch statement in the main handler function" + +### Complete acceptance criteria + +The agent needs to know when it's done. Every agent brief must have concrete, testable acceptance criteria. Each criterion should be independently verifiable. + +- **Good:** "Running `gh issue list --label needs-triage` returns issues that have been through initial classification" +- **Bad:** "Triage should work correctly" + +### Explicit scope boundaries + +State what is out of scope. This prevents the agent from gold-plating or making assumptions about adjacent features. + +## Template + +```markdown +## Agent Brief + +**Category:** bug / enhancement +**Summary:** one-line description of what needs to happen + +**Current behavior:** +Describe what happens now. For bugs, this is the broken behavior. +For enhancements, this is the status quo the feature builds on. + +**Desired behavior:** +Describe what should happen after the agent's work is complete. +Be specific about edge cases and error conditions. + +**Key interfaces:** +- `TypeName`: what needs to change and why +- `functionName()` return type: what it currently returns vs what it should return +- Config shape: any new configuration options needed + +**Acceptance criteria:** +- [ ] Specific, testable criterion 1 +- [ ] Specific, testable criterion 2 +- [ ] Specific, testable criterion 3 + +**Out of scope:** +- Thing that should NOT be changed or addressed in this issue +- Adjacent feature that might seem related but is separate +``` + +## Examples + +### Good agent brief (bug) + +```markdown +## Agent Brief + +**Category:** bug +**Summary:** Skill description truncation drops mid-word, producing broken output + +**Current behavior:** +When a skill description exceeds 1024 characters, it is truncated at exactly +1024 characters regardless of word boundaries. This produces descriptions +that end mid-word (e.g. "Use when the user wants to confi"). + +**Desired behavior:** +Truncation should break at the last word boundary before 1024 characters +and append "..." to indicate truncation. + +**Key interfaces:** +- The `SkillMetadata` type's `description` field: no type change needed, + but the validation/processing logic that populates it needs to respect + word boundaries +- Any function that reads SKILL.md frontmatter and extracts the description + +**Acceptance criteria:** +- [ ] Descriptions under 1024 chars are unchanged +- [ ] Descriptions over 1024 chars are truncated at the last word boundary + before 1024 chars +- [ ] Truncated descriptions end with "..." +- [ ] The total length including "..." does not exceed 1024 chars + +**Out of scope:** +- Changing the 1024 char limit itself +- Multi-line description support +``` + +### Good agent brief (enhancement) + +```markdown +## Agent Brief + +**Category:** enhancement +**Summary:** Add `.out-of-scope/` directory support for tracking rejected feature requests + +**Current behavior:** +When a feature request is rejected, the issue is closed with a `wontfix` label +and a comment. There is no persistent record of the decision or reasoning. +Future similar requests require the maintainer to recall or search for the +prior discussion. + +**Desired behavior:** +Rejected feature requests should be documented in `.out-of-scope/.md` +files that capture the decision, reasoning, and links to all issues that +requested the feature. When triaging new issues, these files should be +checked for matches. + +**Key interfaces:** +- Markdown file format in `.out-of-scope/`: each file should have a + `# Concept Name` heading, a `**Decision:**` line, a `**Reason:**` line, + and a `**Prior requests:**` list with issue links +- The triage workflow should read all `.out-of-scope/*.md` files early + and match incoming issues against them by concept similarity + +**Acceptance criteria:** +- [ ] Closing a feature as wontfix creates/updates a file in `.out-of-scope/` +- [ ] The file includes the decision, reasoning, and link to the closed issue +- [ ] If a matching `.out-of-scope/` file already exists, the new issue is + appended to its "Prior requests" list rather than creating a duplicate +- [ ] During triage, existing `.out-of-scope/` files are checked and surfaced + when a new issue matches a prior rejection + +**Out of scope:** +- Automated matching (human confirms the match) +- Reopening previously rejected features +- Bug reports (only enhancement rejections go to `.out-of-scope/`) +``` + +### Good agent brief (PR) + +For a PR, "Current behavior" describes the state of the diff, and the brief asks the agent to finish or fix it rather than build from scratch. + +```markdown +## Agent Brief + +**Category:** enhancement +**Summary:** Finish the contributor's `--json` output flag for `triage list` + +**Current behavior:** +The PR adds a `--json` flag that serializes the issue list to JSON. The happy +path works and the diff matches the project's command structure. Two gaps +remain: errors are still printed as human text (not JSON), and the new flag has +no test coverage. + +**Desired behavior:** +With `--json`, all output (including errors) is well-formed JSON on stdout, +and the command's exit codes are unchanged. The existing human-readable output +is untouched when the flag is absent. + +**Key interfaces:** +- The command's error path should emit `{ "error": string }` under `--json` + instead of the plain-text error +- Reuse the existing serializer the PR already added; don't introduce a second + +**Acceptance criteria:** +- [ ] `triage list --json` emits valid JSON for both success and error cases +- [ ] Exit codes match the non-JSON command +- [ ] A test covers the `--json` success output and one error case +- [ ] Default (non-JSON) output is byte-for-byte unchanged + +**Out of scope:** +- Adding `--json` to any other command +- Changing the JSON shape of the success payload the PR already defined +``` + +### Bad agent brief + +```markdown +## Agent Brief + +**Summary:** Fix the triage bug + +**What to do:** +The triage thing is broken. Look at the main file and fix it. +The function around line 150 has the issue. + +**Files to change:** +- src/triage/handler.ts (line 150) +- src/types.ts (line 42) +``` + +This is bad because: +- No category +- Vague description ("the triage thing is broken") +- References file paths and line numbers that will go stale +- No acceptance criteria +- No scope boundaries +- No description of current vs desired behavior diff --git a/.agents/skills/triage/OUT-OF-SCOPE.md b/.agents/skills/triage/OUT-OF-SCOPE.md new file mode 100644 index 0000000..c9fba2f --- /dev/null +++ b/.agents/skills/triage/OUT-OF-SCOPE.md @@ -0,0 +1,105 @@ +# Out-of-Scope Knowledge Base + +The `.out-of-scope/` directory in a repo stores persistent records of rejected feature requests. It serves two purposes: + +1. **Institutional memory**: why a feature was rejected, so the reasoning isn't lost when the issue is closed +2. **Deduplication**: when a new issue comes in that matches a prior rejection, the skill can surface the previous decision instead of re-litigating it + +## Directory structure + +``` +.out-of-scope/ +├── dark-mode.md +├── plugin-system.md +└── graphql-api.md +``` + +One file per **concept**, not per issue. Multiple issues requesting the same thing are grouped under one file. + +## File format + +The file should be written in a relaxed, readable style, more like a short design document than a database entry. Use paragraphs, code samples, and examples to make the reasoning clear and useful to someone encountering it for the first time. + +```markdown +# Dark Mode + +This project does not support dark mode or user-facing theming. + +## Why this is out of scope + +The rendering pipeline assumes a single color palette defined in +`ThemeConfig`. Supporting multiple themes would require: + +- A theme context provider wrapping the entire component tree +- Per-component theme-aware style resolution +- A persistence layer for user theme preferences + +This is a significant architectural change that doesn't align with the +project's focus on content authoring. Theming is a concern for downstream +consumers who embed or redistribute the output. + +```ts +// The current ThemeConfig interface is not designed for runtime switching: +interface ThemeConfig { + colors: ColorPalette; // single palette, resolved at build time + fonts: FontStack; +} +``` + +## Prior requests + +- #42: "Add dark mode support" +- #87: "Night theme for accessibility" +- #134: "Dark theme option" +``` + +### Naming the file + +Use a short, descriptive kebab-case name for the concept: `dark-mode.md`, `plugin-system.md`, `graphql-api.md`. The name should be recognizable enough that someone browsing the directory understands what was rejected without opening the file. + +### Writing the reason + +The reason should be substantive: not "we don't want this" but why. Good reasons reference: + +- Project scope or philosophy ("This project focuses on X; theming is a downstream concern") +- Technical constraints ("Supporting this would require Y, which conflicts with our Z architecture") +- Strategic decisions ("We chose to use A instead of B because...") + +The reason should be durable. Avoid referencing temporary circumstances ("we're too busy right now"); those aren't real rejections, they're deferrals. + +## When to check `.out-of-scope/` + +During triage (Step 1: Gather context), read all files in `.out-of-scope/`. When evaluating a new issue: + +- Check if the request matches an existing out-of-scope concept +- Matching is by concept similarity, not keyword: "night theme" matches `dark-mode.md` +- If there's a match, surface it to the maintainer: "This is similar to `.out-of-scope/dark-mode.md`. We rejected this before because [reason]. Do you still feel the same way?" + +The maintainer may: + +- **Confirm**: the new issue gets added to the existing file's "Prior requests" list, then closed +- **Reconsider**: the out-of-scope file gets deleted or updated, and the issue proceeds through normal triage +- **Disagree**: the issues are related but distinct, proceed with normal triage + +## When to write to `.out-of-scope/` + +Only when an **enhancement** (not a bug) is *rejected* as `wontfix`. This applies to enhancement PRs exactly as it does to issues: a rejected PR is recorded here so the same request doesn't return as fresh code. + +Do **not** write here when something is closed as `wontfix` because it's **already implemented**. That's a built feature, not a rejected one; recording it would poison the dedup checks with false rejections. Instead, the closing comment points to where the feature already lives. + +The flow: + +1. Maintainer decides a feature request is out of scope +2. Check if a matching `.out-of-scope/` file already exists +3. If yes: append the new issue to the "Prior requests" list +4. If no: create a new file with the concept name, decision, reason, and first prior request +5. Post a comment on the issue explaining the decision and mentioning the `.out-of-scope/` file +6. Close the issue with the `wontfix` label + +## Updating or removing out-of-scope files + +If the maintainer changes their mind about a previously rejected concept: + +- Delete the `.out-of-scope/` file +- The skill does not need to reopen old issues; they're historical records +- The new issue that triggered the reconsideration proceeds through normal triage diff --git a/.agents/skills/triage/SKILL.md b/.agents/skills/triage/SKILL.md new file mode 100644 index 0000000..37ddea1 --- /dev/null +++ b/.agents/skills/triage/SKILL.md @@ -0,0 +1,112 @@ +--- +name: triage +description: Move issues and external PRs through a state machine of triage roles, categorise, verify, grill if needed, and write agent-ready briefs. +disable-model-invocation: true +--- + +# Triage + +Move issues on the project issue tracker through a small state machine of triage roles. + +If this repo treats external pull requests as a request surface (see the issue-tracker config), triage covers them too: **a PR is an issue with attached code**, using the same roles, same states, and same machine, with a few deltas marked "for a PR" below. Resolve a bare `#42` to an issue or PR per the tracker config. + +Every comment or issue posted to the issue tracker during triage **must** start with this disclaimer: + +``` +> *This was generated by AI during triage.* +``` + +## Reference docs + +- [AGENT-BRIEF.md](AGENT-BRIEF.md): how to write durable agent briefs +- [OUT-OF-SCOPE.md](OUT-OF-SCOPE.md): how the `.out-of-scope/` knowledge base works + +## Roles + +Two **category** roles: + +- `bug`: something is broken +- `enhancement`: new feature or improvement + +Five **state** roles: + +- `needs-triage`: maintainer needs to evaluate +- `needs-info`: waiting on reporter for more information +- `ready-for-agent`: fully specified, ready for an AFK agent +- `ready-for-human`: needs human implementation +- `wontfix`: will not be actioned + +For a PR, the same states read against the attached code: `ready-for-agent` means a brief is attached and an agent should take the next step on the diff; `ready-for-human` means it's ready for a human to merge. + +Every triaged issue should carry exactly one category role and one state role. If state roles conflict, flag it and ask the maintainer before doing anything else. + +These are canonical role names. The actual label strings used in the issue tracker may differ. The mapping should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +State transitions: an unlabeled issue normally goes to `needs-triage` first; from there it moves to `needs-info`, `ready-for-agent`, `ready-for-human`, or `wontfix`. `needs-info` returns to `needs-triage` once the reporter replies. The maintainer can override at any time; flag transitions that look unusual and ask before proceeding. + +## Invocation + +The maintainer invokes `/triage` and describes what they want in natural language. Interpret the request and act. Examples: + +- "Show me anything that needs my attention" +- "Let's look at #42" (issue or PR) +- "Move #42 to ready-for-agent" +- "What's ready for agents to pick up?" + +## Show what needs attention + +Query the issue tracker and present three buckets, oldest first: + +1. **Unlabeled**: never triaged. +2. **`needs-triage`**: evaluation in progress. +3. **`needs-info` with reporter activity since the last triage notes**: needs re-evaluation. + +When PRs are in scope, include external PRs in these buckets and tag each line `[PR]` or `[issue]`. Discovery surfaces only *external* PRs (the tracker config defines who counts as external), so a collaborator's in-flight PR is not triage work. This filter is discovery-only; an explicitly named PR is always triaged regardless of author. + +Show counts and a one-line summary per item. Let the maintainer pick. + +## Triage a specific issue or PR + +1. **Gather context.** Read the full issue or PR (body, comments, labels, author, dates; for a PR, the diff too). Parse any prior triage notes so you don't re-ask resolved questions. Explore the codebase using the project's domain glossary, respecting ADRs in the area. Run two checks against the codebase: (a) **redundancy**: search for an existing implementation of the requested behavior by domain concept (not just the request's wording), and report where you looked. If found, it's an already-implemented `wontfix` (step 5). (b) **prior rejection**: read `.out-of-scope/*.md` and surface any that resembles this request. + +2. **Recommend.** Tell the maintainer your category and state recommendation with reasoning, plus a brief codebase summary relevant to the request (including whether it's already implemented). Wait for direction. + +3. **Verify the claim.** Before any grilling, check that the claim holds up. For a bug, reproduce it from the reporter's steps. For a PR, confirm the diff does what it claims: check it out, run the relevant tests or commands. Report what happened: confirmed (with code path), failed, or insufficient detail (a strong `needs-info` signal). A confirmed verification makes a much stronger agent brief. + +4. **Grill (if needed).** If the request needs fleshing out, call the Skill tool twice, for "grilling" and "domain-modeling", and grill it into shape a round of questions at a time, sharpening domain terms and updating `CONTEXT.md`/ADRs inline as decisions land. + +5. **Apply the outcome:** + - `ready-for-agent`: post an agent brief comment ([AGENT-BRIEF.md](AGENT-BRIEF.md)). + - `ready-for-human`: same structure as an agent brief, but note why it can't be delegated (judgment calls, external access, design decisions, manual testing). + - `needs-info`: post triage notes (template below). + - For `wontfix`, close the issue, with the comment depending on *why*: + - **Already implemented**: the change already exists in the codebase. Point to where it lives; do **not** write to `.out-of-scope/` (that KB is for *rejected* requests, not built ones). + - **Rejected (bug)**: give a polite explanation, then close. + - **Rejected (enhancement)**: write to `.out-of-scope/`, link to it from a comment, then close ([OUT-OF-SCOPE.md](OUT-OF-SCOPE.md)). + - `needs-triage`: apply the role. Optional comment if there's partial progress. + +## Quick state override + +If the maintainer says "move #42 to ready-for-agent", trust them and apply the role directly. Confirm what you're about to do (role changes, comment, close), then act. Skip grilling. If moving to `ready-for-agent` without a grilling session, ask whether they want to write an agent brief. + +## Needs-info template + +```markdown +## Triage Notes + +**What we've established so far:** + +- point 1 +- point 2 + +**What we still need from you (@reporter):** + +- question 1 +- question 2 +``` + +Capture everything resolved during grilling under "established so far" so the work isn't lost. Questions must be specific and actionable, not "please provide more info". + +## Resuming a previous session + +If prior triage notes exist on the issue or PR, read them, check whether the reporter has answered any outstanding questions, and present an updated picture before continuing. Don't re-ask resolved questions. diff --git a/.agents/skills/triage/agents/openai.yaml b/.agents/skills/triage/agents/openai.yaml new file mode 100644 index 0000000..acb366c --- /dev/null +++ b/.agents/skills/triage/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Triage" + short_description: "Move issues through triage roles" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/wait-what/SKILL.md b/.agents/skills/wait-what/SKILL.md new file mode 100644 index 0000000..f8854f1 --- /dev/null +++ b/.agents/skills/wait-what/SKILL.md @@ -0,0 +1,7 @@ +--- +name: wait-what +description: "Stop. That last message did not land: re-pitch it." +disable-model-invocation: true +--- + +Wait, I don't understand where you've got to here. Re-pitch that: give me a little bit of context, talk in ASD-STE100 Simplified Technical English, and use the ubiquitous language from `CONTEXT.md` (follow `CONTEXT-MAP.md` to the right one if the repo has more than one). diff --git a/.agents/skills/wait-what/agents/openai.yaml b/.agents/skills/wait-what/agents/openai.yaml new file mode 100644 index 0000000..6f7a9c3 --- /dev/null +++ b/.agents/skills/wait-what/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Wait What" + short_description: "Re-pitch that: simpler, with the context I'm missing" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/wayfinder/SKILL.md b/.agents/skills/wayfinder/SKILL.md new file mode 100644 index 0000000..812805b --- /dev/null +++ b/.agents/skills/wayfinder/SKILL.md @@ -0,0 +1,128 @@ +--- +name: wayfinder +description: Plan a huge chunk of work (more than one agent session can hold) as a shared map of decision tickets on your issue tracker, and resolve them one at a time until the way to the destination is clear. +disable-model-invocation: true +--- + +A loose idea has arrived, too big for one agent session, and wrapped in fog: the way from here to the **destination** isn't visible yet. Wayfinding is about finding that way, not charging at the destination. This skill charts the way as a **shared map** on the repo's issue tracker, then works its **decision tickets** (questions whose resolution is a decision, not slices of a build to execute) one at a time until the route is clear. + +The destination varies per effort, and naming it is the first act of charting: it shapes every ticket. It might be a spec to hand off and iterate on, a decision to lock before planning starts, or a change made in place like a data-structure migration. The map is domain-agnostic: engineering work, course content, whatever fits the shape. + +## Plan, don't do + +Wayfinder is **planning** by default: each ticket resolves a decision, and the map is done when the way is clear, with nothing left to decide before someone goes and does the thing. The pull to just do the work is usually the signal you've reached the edge of the map and it's time to hand off. An effort can override this in its **Notes**, carrying execution into the map itself, but absent that, produce decisions, not deliverables. + +## Refer by name + +Every map and ticket is an issue, so it has a **name**: its title. In everything the human reads (narration, the map's Decisions-so-far), refer to it by that name, never by a bare id, number, or slug. A wall of `#42, #43, #44` is illegible; names read at a glance. The id and URL don't vanish; a name wraps its link, but they ride _inside_ the name, never stand in for it. + +## The Map + +The map is a single issue on this repo's issue tracker, labelled `wayfinder:map`, the canonical artifact. Its tickets are child issues of the map. + +The map is an **index**, not a store. It lists the decisions made and points at the tickets that hold their detail; a decision lives in exactly one place, its ticket, so the map never restates it, only gists it and links. + +**Where the map, its child tickets, blocking, and frontier queries physically live is tracker-specific.** The issue tracker should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. Consult the tracker doc's "Wayfinding operations" section for how _this_ repo expresses them. If no tracker has been provided, default to the local-markdown tracker. + +### The map body + +The whole map at low resolution, loaded once per session. Open tickets are **not** listed: they are open child issues, found by query. + +```markdown +## Destination + + + +## Notes + + + +## Decisions so far + + + +- [](link): + +## Not yet specified + + + +## Out of scope + + +``` + +### Tickets + +Each ticket is a **child issue** of the map; the tracker's issue id is its identity. Its body is the question, sized to one 100K token agent session: + +```markdown +## Question + + +``` + +Each ticket carries a `wayfinder:` label, one of `research`, `prototype`, `grilling`, `task` (see [Ticket Types](#ticket-types)). + +A session **claims** a ticket by assigning it to the dev driving the map, **first**, before any work, so concurrent sessions skip it. That assignee _is_ the claim: an open, unassigned ticket is unclaimed. + +Blocking uses the tracker's **native** dependency relationship: essential because it renders the frontier _visually_ in the tracker's own UI, so the human sees what's takeable without opening the map. Only a tracker that lacks native blocking falls back to a body convention. A ticket is **unblocked** when every ticket blocking it is closed; the **frontier** is the open, unblocked, unclaimed children, the edge of the known. + +The answer isn't part of the body; it's recorded on resolution (see [Work through the map](#work-through-the-map)). Assets created while resolving a ticket are linked from the issue, not pasted in. + +## Ticket Types + +Every ticket is either **HITL** (human in the loop, worked _with_ a human who speaks for themselves) or **AFK**, driven by the agent alone. A HITL ticket only resolves through that live exchange; the agent never stands in for the human's side of it (a grilling agent that answers its own questions has broken this). + +- **Research** (AFK): Reading documentation, third-party APIs, or local resources like knowledge bases to surface a fact a decision waits on. Resolved by a subagent that calls the Skill tool with "research". Use when knowledge outside the current working directory is required. +- **Prototype** (HITL): Raise the fidelity of the discussion by making a cheap, rough, concrete artifact to react to (an outline, a rough take, a stub, or UI/logic code) by calling the Skill tool with "prototype". Links the prototype as an asset. Use when "how should it look" or "how should it behave" is the key question. +- **Grilling** (HITL): Conversation. The default case. Always call the Skill tool twice, for "grilling" and "domain-modeling". +- **Task** (HITL or AFK): Manual work that must happen before a _decision_ can be made: nothing to decide, prototype, or research, but the discussion is blocked until it's done. Signing up for a service so its API can be judged, provisioning access, moving data so its shape can be seen. This is the one type that _does_ rather than decides, and it earns its place by unblocking a decision, not by delivering the destination. The agent drives it alone where it can (AFK); otherwise it hands the human a precise checklist (HITL). Resolved when the work is done; the answer records what was done and any resulting facts (credentials location, new URLs, row counts) later tickets depend on. + +## Fog of war + +The map is _deliberately_ incomplete: don't chart what you can't yet see. Beyond the live tickets lies the **fog of war**: the dim view of decisions and investigations you can tell are coming but can't yet pin down, because they hang on questions still open. Resolving a ticket clears the fog ahead of it, graduating whatever's now specifiable into fresh tickets, one at a time, until the way to the destination is clear and no tickets remain. + +The map's **Not yet specified** section is where that dim view is written down: the suspected question, the area to revisit later. It's the undiscovered frontier _toward_ the destination: everything here is in scope, just not sharp enough to ticket. Write as loosely or as fully as the view allows; it doubles as a signpost for collaborators reading where the effort is headed. + +**Fog or ticket?** The test is whether you can state the question precisely now, _not_ whether you can answer it now. + +- **Ticket when** the question is already sharp, even if it's blocked and you can't act on it yet. +- **Not yet specified when** you can't yet phrase it that sharply. Don't pre-slice the fog into ticket-sized pieces: it's coarser than a ticket, and one patch may graduate into several tickets, or none, once the frontier reaches it. + +**Not yet specified** excludes what's already decided (Decisions so far), what's already a live ticket, and what's out of scope (the next section). + +## Out of scope + +Fog only ever gathers _toward_ the destination. The destination fixes the scope, so work beyond it is **out of scope**: it isn't fog, and it doesn't belong in **Not yet specified**. It gets its own **Out of scope** section on the map: work you've consciously ruled out of _this_ effort. Scope, not sharpness, lands it here. + +Out-of-scope work never graduates (the frontier stops at the destination), so it returns only if the destination is redrawn, and then as a fresh effort, not a resumption. + +Ruling something out of scope is a scoping act, not a step on the route. When a ticket that already exists turns out to sit past the destination (mis-scoped in while charting, or exposed by a resolution), **close it** (a closed ticket is unambiguously off the frontier) and leave one line in the **Out of scope** section: the gist plus why it's out of scope, linking the closed ticket. It stays out of **Decisions so far**, which records the route actually walked; a scope boundary isn't a step on it. + +## Invocation + +Two modes. Either way, **never resolve more than one ticket per session**, with the exception of research tickets. + +### Chart the map + +User invokes with a loose idea. + +1. **Name the destination.** Call the Skill tool twice, for "grilling" and "domain-modeling", to pin down what this map is finding its way to: the spec, decision, or change. The destination fixes the scope, so it's settled first. +2. **Map the frontier.** Grill again, **breadth-first** this time: fan out across the whole space rather than deep on any one thread, surfacing the open decisions and the first steps takeable now. **If this surfaces no fog** (the way to the destination is already clear, the whole journey small enough for one session), you don't need a map. Stop and ask the user how they'd like to proceed. +3. **Create the map** (label `wayfinder:map`): Destination and Notes filled in, Decisions-so-far empty, the fog sketched into **Not yet specified**. +4. **Create the tickets you can specify now** as child issues of the map, then wire blocking edges in a **second pass** (issues need ids before they can reference each other). Wiring sorts them into the frontier and the blocked; everything you can't yet specify stays in the fog: the **Not yet specified** section. +5. **Fire the research subagents.** For each `research` ticket you just created, spin up a subagent that calls the Skill tool with "research" to resolve it in parallel, capturing its findings on a throwaway `research/` branch with a context pointer from the ticket. +6. Stop: charting is one session's work; it hand-resolves nothing. + +### Work through the map + +User invokes with a map (URL or 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. +2. Choose the ticket. If the user named one, use it. Otherwise take the first frontier ticket in order. **Claim it**: assign it to yourself before any work. +3. Resolve it. **Zoom as needed**: fetch the full body of any related or closed ticket on demand; call the Skill tool for whichever skills the `## Notes` block names. If in doubt, call the Skill tool twice, for "grilling" and "domain-modeling". +4. Record the resolution: post the answer as a **resolution comment**, **close** the issue, and **append a context pointer** to the map's Decisions-so-far. +5. Add newly-surfaced tickets (create-then-wire); graduate any fog the answer has made specifiable, clearing each graduated patch from **Not yet specified** so it lives only as its new ticket. If the answer reveals that a ticket (this one or another) sits beyond the destination, **rule it out of scope** rather than resolving it on the route. If the decision invalidates other parts of the map, update or delete those tickets. + +The user may run unblocked tickets in parallel, so expect other sessions to be editing the tracker concurrently. diff --git a/.agents/skills/wayfinder/agents/openai.yaml b/.agents/skills/wayfinder/agents/openai.yaml new file mode 100644 index 0000000..b375447 --- /dev/null +++ b/.agents/skills/wayfinder/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Wayfinder" + short_description: "Map a large effort as decision tickets" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/wizard/SKILL.md b/.agents/skills/wizard/SKILL.md new file mode 100644 index 0000000..c4294ad --- /dev/null +++ b/.agents/skills/wizard/SKILL.md @@ -0,0 +1,44 @@ +--- +name: wizard +description: Generate an interactive bash wizard that walks a human through steps only they can perform. Use when provisioning infrastructure, setting up credentials or CI secrets, walking an unfamiliar third-party dashboard, or running a one-off migration or cutover. Don't invoke this for steps the agent can perform itself. +--- + +# Wizard + +A **wizard** is a bash script that walks a human, step by step, through a manual procedure that's tedious to do by hand and tedious to re-explain to an AI every time. It opens each URL, says exactly what to click and copy, captures the values, writes them where they belong (`.env`, GitHub secrets), confirms at every stage, and shows how many stages are left. It might configure third-party services, run a one-off migration, or move the project from one state to another. + +The delightful UX is already solved by [template.sh](template.sh): stage-by-stage progress, confirmation gates, cross-platform URL opening (including WSL), hidden secret entry, idempotent `.env` upserts, `gh secret`/`gh variable` writes, and a closing summary. **Your job is only to scope the procedure and author its stages.** The library above the `STAGES` marker is identical in every wizard; that consistency is the point: never hand-edit it. + +A wizard is ephemeral by default: built for one run, saved to a scratch or `scripts/` path, deleted when the job's done. Commit it only when the user wants a repeatable setup path that should live in the repo. + +## Process + +### 1. Scope the procedure + +Work out every manual step the human must take and every value that gets captured along the way. Read the repo first, don't ask cold: + +- For setup: `.env`, `.env.example`, `.env.*`, `README`, `docker-compose*`, framework config, and `.github/workflows/*` (every `secrets.*` / `vars.*` reference is a value the wizard must produce). +- For a migration or transition: the current state, the target state, and the irreversible actions between them. + +Then show the user the ordered list of stages and the values each produces, and confirm: they may add, drop, or reorder. + +**Done when:** every stage is named in order, and for each captured value you know (a) where the human gets it, (b) where it's written (`.env`, a GitHub secret, both, or nowhere; some stages are pure actions), and (c) whether it's secret (hidden entry) or public. + +### 2. Map each stage's journey + +For each stage, write the precise path a human follows: which URL to open, what to do there, where a value is shown, which variable it fills: e.g. "Dashboard → Developers → API keys → Reveal test key → copy". Where you don't actually know the current UI or the exact command, say so and ask the user or check the docs: never invent steps that may not exist. + +**Done when:** every stage traces to concrete instructions a stranger could follow. + +### 3. Author the wizard + +Copy `template.sh` to the target path. Replace the example stage with one `stage` per step, in dependency order. Use the library helpers: `stage`, `say`/`step`, `open_url`, `ask`/`ask_secret`, `write_env`, `set_secret`/`set_var`, `pause`/`confirm`. Set `TOTAL_STAGES` to the number of stages you wrote. + +Hold the bar the template sets: open the URL before asking for its value, use `ask_secret` for anything secret, `write_env` every persisted value, `set_secret` only the values CI actually needs, and `confirm` before any irreversible action. Each `stage` clears the screen so only the current step is visible: keep a stage to one focused task so nothing the human needs scrolls away. Don't touch the library above the marker. + +### 4. Verify and hand off + +- `bash -n