Compare commits
8
Commits
e4d259b598
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
122fc8e91d | ||
|
|
d15cb4d165 | ||
|
|
5254a480a2 | ||
|
|
a4dec89d08 | ||
|
|
2b75587e39 | ||
|
|
8236582836 | ||
|
|
e7af1fe94e | ||
|
|
b005f15361 |
@@ -19,7 +19,9 @@ thorough, never pad with style opinions.
|
||||
This skill is designed to run with **fresh context** (e.g. in a subagent). If the
|
||||
current session authored the changes it is about to review, say so and recommend
|
||||
a fresh-context review instead: the assumptions made while writing code carry
|
||||
over into its review.
|
||||
over into its review. The same applies to the review brief itself: an issue or
|
||||
prompt highlights what the author considered risky — deliberately review what it
|
||||
does *not* mention (fakes, declared verification gaps, transport plumbing).
|
||||
|
||||
## Workflow
|
||||
|
||||
@@ -33,6 +35,11 @@ over into its review.
|
||||
3. If the diff is large (roughly >600 changed lines): review in passes, one
|
||||
group of related files at a time, prioritizing source code over tests, docs,
|
||||
and generated files. State explicitly which files you did not fully review.
|
||||
4. **Declared verification gaps are review scope.** An MR that says "X is not
|
||||
covered by automation — manual smoke before merge" has marked a surface as
|
||||
untested. Either run that smoke yourself or review the surface by other
|
||||
means (trace the real contract, exercise it in a safe environment).
|
||||
Accepting the declaration as handled is how honest MRs ship broken features.
|
||||
|
||||
### Phase 2 — Context (the diff alone lies)
|
||||
|
||||
@@ -44,6 +51,12 @@ over into its review.
|
||||
3. Trace the change into the codebase: open the full files around the hunks,
|
||||
grep callers of changed functions, follow the data flow end to end. Do not
|
||||
judge code you have not seen in context.
|
||||
4. **Inventory the fakes**: find the test doubles the diff introduces or relies
|
||||
on for external systems (docker, HTTP clients, DBs, queues, SDKs). Each fake
|
||||
encodes the author's assumption about that system's contract — verify every
|
||||
assumption against the real library (docs, source, or the repo's own proven
|
||||
call site). A green suite against an optimistic fake proves the code matches
|
||||
the assumption, not the system.
|
||||
|
||||
### Phase 3 — Review passes
|
||||
|
||||
@@ -54,6 +67,12 @@ Run the passes in this order; spend effort where the real defects live:
|
||||
conditions, wrong state transitions.
|
||||
2. **Contract breaks** — changed signatures or behavior vs. callers; API, DB,
|
||||
or schema mismatches; serialization changes.
|
||||
2b. **External call sites vs. proven patterns** — for every call the diff adds
|
||||
into an external SDK, driver, or daemon API, find the repo's existing proven
|
||||
call site for the same operation and diff the two call shapes (options,
|
||||
flags, stream modes, attach/hijack variants). Subtle contract differences
|
||||
(a missing `hijack: true` on a docker attach, a dropped TLS option) never
|
||||
show up in unit tests with fakes — they only show in production.
|
||||
3. **Security at trust boundaries** — user input, files, network, env vars,
|
||||
secrets in logs or history, auth checks, injection, unsafe deserialization.
|
||||
4. **Tests** — which changed behavior has no test? Do new tests assert
|
||||
|
||||
+54
-23
@@ -1,46 +1,77 @@
|
||||
---
|
||||
name: dev-workflow
|
||||
description: Personal development workflow for software projects.
|
||||
description: Personal development workflow for software projects. Use from the first discussion of new work through implementation, review, and MR — when the user describes something to build or fix ("we need X", "wir brauchen X"), says "workflow" or "implement", or when creating the issue/branch/worktree/MR chain. Assumes pi-web subsessions and one worktree per feature.
|
||||
---
|
||||
|
||||
# Dev Workflow
|
||||
|
||||
This skill enforces my personal development workflow for software projects.
|
||||
My personal workflow for software projects. Assumes pi-web (subsession tools
|
||||
available). Without them, implement and review in the main session and say so.
|
||||
|
||||
## Branch Strategy
|
||||
Core idea: the main chat plans and discusses; implementation and review run in
|
||||
tracked subsessions; every feature lives in its own git worktree so several
|
||||
features can run in parallel without branches fighting over one checkout.
|
||||
|
||||
- **Main branch**: `master` or `main` (production)
|
||||
- **Development**: Always on feature branches off main
|
||||
- **New work**: Features, fixes, and chores each get their own branch
|
||||
## 1. Plan and approve
|
||||
|
||||
## Workflow
|
||||
Discuss the task until there is an implementation plan: summary plus discrete
|
||||
steps. **Wait for explicit approval** (`go`, `approved`, `start`) before
|
||||
creating anything.
|
||||
|
||||
### 1. Research / Discussion / Plan
|
||||
## 2. Issue
|
||||
|
||||
Discuss the task, idea, or bug with the coding agent. The outcome is an **implementation plan** that includes:
|
||||
Follow the project's AGENTS.md for branches, commits, and MRs. Without project
|
||||
rules: branch off the integration branch (e.g. `development`), never off main.
|
||||
|
||||
- Summary of research and discussion
|
||||
- Implementation plan broken into discrete steps
|
||||
- Create a GitLab issue containing the plan (English), normal human title.
|
||||
- Note the IID; everything below derives its name from it.
|
||||
|
||||
Create a GitLab/Git issue for the plan. The issue title starts with the feature slug, and the description contains the full plan. **WAIT for explicit user approval before creating the issue.**
|
||||
## 3. Worktree (one per feature)
|
||||
|
||||
### 2. Implementation
|
||||
Worktrees let several features run in parallel; plain branch switching cannot.
|
||||
|
||||
**Only proceed if the user explicitly approves the plan** (e.g., `go`, `approved`, `start`). Do not start implementing on your own. Before starting, the agent reads `AGENT.md` (project guidelines). Implementation proceeds step-by-step according to the plan. Each step is committed individually.
|
||||
- Check for an existing worktree for this IID (`git worktree list`). Reuse it
|
||||
if present; do not create duplicates.
|
||||
- Otherwise, from the main checkout (which stays on the integration branch):
|
||||
`git worktree add ../<repo>-<slug> -b <type>/<IID>-<slug>`
|
||||
e.g. `git worktree add ../ai-cowork-mode-routing -b feature/105-mode-model-routing`.
|
||||
- The main checkout is never the implementation target while a worktree exists.
|
||||
- Node projects: install dependencies in the fresh worktree once before
|
||||
implementing (follow the project's AGENTS.md toolchain notes).
|
||||
|
||||
### 3. Review
|
||||
## 4. Implementation (tracked subsession in the worktree)
|
||||
|
||||
After implementation is complete, a subagent with **fresh context** reviews the code and implementation using `code-review`.
|
||||
Spawn ONE subsession with `cwd` set to the worktree path. Task text: approved
|
||||
plan, issue IID, branch name, "read AGENTS.md first", and: "Activate ponytail
|
||||
full mode: read /home/markus/.pi/agent/git/github.com/DietrichGebert/ponytail/skills/ponytail/SKILL.md
|
||||
and follow it. Where AGENTS.md demands more (e.g. TDD), AGENTS.md wins over
|
||||
ponytail minimality." Stay responsive in
|
||||
the main chat; the user watches and steers the subsession directly in pi-web.
|
||||
At the join point call `yield_to_subsessions`, then verify the commits
|
||||
(`git log`) before moving on.
|
||||
|
||||
### 4. Iteration
|
||||
## 5. Review (fresh context, separate subsession, same worktree)
|
||||
|
||||
The agent fixes any findings the reviewer reported. This cycle continues until the reviewer subagent approves.
|
||||
Spawn a SECOND subsession with the same `cwd` — never reuse the implementation
|
||||
child. Task text: diff range (`git diff <base>...HEAD`), issue reference, and:
|
||||
"Read /home/markus/workspace/skills/dev/code-review/SKILL.md and follow it."
|
||||
(Explicit paths make skill loading deterministic; the catalog is available
|
||||
to the child, but self-loading is not reliable.) The reviewer reports findings
|
||||
and fixes nothing.
|
||||
|
||||
### 5. Merge Request
|
||||
## 6. Iterate, merge, clean up
|
||||
|
||||
Create an MR/PR and inform the user.
|
||||
- Fix findings as NEW commits (never amend/force-push a pushed branch).
|
||||
- Substantial findings: another fresh review pass.
|
||||
- Create the MR (English title/description), inform the user, then watch the
|
||||
pipeline (gitlab_pipeline_status, job logs) and fix failures as new commits.
|
||||
- After the MR merges: `git worktree remove ../<repo>-<slug>` and delete the
|
||||
branch, unless the user wants it kept for follow-up work.
|
||||
|
||||
## Language Rule
|
||||
## 7. Long work
|
||||
|
||||
- **Plans and artifacts**: Always in **English**
|
||||
- **User discussions**: Any language
|
||||
Work spanning multiple sessions: track it in goal-state.yaml (goal-state skill).
|
||||
|
||||
## Language
|
||||
|
||||
Plans, issues, commits, MR descriptions: English. Discussion: any language.
|
||||
|
||||
@@ -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 `GLOSSARY.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching.
|
||||
|
||||
## Redact
|
||||
|
||||
This skill has you show commands, outputs and captured artifacts. **Redact every secret first**: write `<REDACTED>` in its place. Build loops against env vars, so the credential stays in the environment rather than in what you show. Captured artifacts carry auth headers: quote only the lines that carry the signal.
|
||||
|
||||
If the redacted output is not enough to diagnose the bug, say so and ask the user.
|
||||
|
||||
## Phase 1: Build a feedback loop
|
||||
|
||||
**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug (one that goes red on _this_ bug), you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you.
|
||||
|
||||
Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.**
|
||||
|
||||
### Ways to construct one, in roughly this order
|
||||
|
||||
1. **Failing test** at whatever seam reaches the bug: unit, integration, e2e.
|
||||
2. **Curl / HTTP script** against a running dev server.
|
||||
3. **CLI invocation** with a fixture input, diffing stdout against a known-good snapshot.
|
||||
4. **Headless browser script** (Playwright / Puppeteer) that drives the UI and asserts on DOM/console/network.
|
||||
5. **Replay a captured trace.** Save a real network request / payload / event log to disk; replay it through the code path in isolation.
|
||||
6. **Throwaway harness.** Spin up a minimal subset of the system (one service, mocked deps) that exercises the bug code path with a single function call.
|
||||
7. **Property / fuzz loop.** If the bug is "sometimes wrong output", run 1000 random inputs and look for the failure mode.
|
||||
8. **Bisection harness.** If the bug appeared between two known states (commit, dataset, version), automate "boot at state X, check, repeat" so you can `git bisect run` it.
|
||||
9. **Differential loop.** Run the same input through old-version vs new-version (or two configs) and diff outputs.
|
||||
10. **HITL bash script.** Last resort. If a human must click, drive _them_ with `scripts/hitl-loop.template.sh` so the loop is still structured. Captured output feeds back to you.
|
||||
|
||||
Build the right feedback loop, and the bug is 90% fixed.
|
||||
|
||||
### Tighten the loop
|
||||
|
||||
Treat the loop as a product. Once you have _a_ loop, **tighten** it:
|
||||
|
||||
- Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.)
|
||||
- Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".)
|
||||
- Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.)
|
||||
|
||||
A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight, a debugging superpower.
|
||||
|
||||
### Non-deterministic bugs
|
||||
|
||||
The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not, so keep raising the rate until it's debuggable.
|
||||
|
||||
### When you genuinely cannot build a loop
|
||||
|
||||
Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a redacted captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop.
|
||||
|
||||
### Completion criterion: a tight loop that goes red
|
||||
|
||||
Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** (a script path, a test invocation, a curl) that you have **already run at least once** (show the invocation and its output, redacted), and that is:
|
||||
|
||||
- [ ] **Red-capable**: it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring"; it must be able to _catch this specific bug_.
|
||||
- [ ] **Deterministic**: same verdict every run (flaky bugs: a pinned, high reproduction rate, per above).
|
||||
- [ ] **Fast**: seconds, not minutes.
|
||||
- [ ] **Agent-runnable**: you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`.
|
||||
|
||||
If you catch yourself reading code to build a theory before this command exists, **stop: jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2.
|
||||
|
||||
## Phase 2: Reproduce + minimise
|
||||
|
||||
Run the loop. Watch it go red as the bug appears.
|
||||
|
||||
Confirm:
|
||||
|
||||
- [ ] The loop produces the failure mode the **user** described, not a different failure that happens to be nearby. Wrong bug = wrong fix.
|
||||
- [ ] The failure is reproducible across multiple runs (or, for non-deterministic bugs, reproducible at a high enough rate to debug against).
|
||||
- [ ] You have captured the exact symptom (error message, wrong output, slow timing) so later phases can verify the fix actually addresses it.
|
||||
|
||||
### Minimise
|
||||
|
||||
Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut, and keep only what's load-bearing for the failure.
|
||||
|
||||
Why bother: a minimal repro shrinks the hypothesis space in Phase 3 (fewer moving parts left to suspect) and becomes the clean regression test in Phase 5.
|
||||
|
||||
Done when **every remaining element is load-bearing**: removing any one of them makes the loop go green.
|
||||
|
||||
Do not proceed until you have reproduced **and** minimised.
|
||||
|
||||
## Phase 3: Hypothesise
|
||||
|
||||
Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea.
|
||||
|
||||
Each hypothesis must be **falsifiable**: state the prediction it makes.
|
||||
|
||||
> Format: "If <X> is the cause, then <changing Y> will make the bug disappear / <changing Z> will make it worse."
|
||||
|
||||
If you cannot state the prediction, the hypothesis is a vibe: discard or sharpen it.
|
||||
|
||||
**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it; proceed with your ranking if the user is AFK.
|
||||
|
||||
## Phase 4: Instrument
|
||||
|
||||
Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.**
|
||||
|
||||
Tool preference:
|
||||
|
||||
1. **Debugger / REPL inspection** if the env supports it. One breakpoint beats ten logs.
|
||||
2. **Targeted logs** at the boundaries that distinguish hypotheses.
|
||||
3. Never "log everything and grep".
|
||||
|
||||
**Tag every debug log** with a unique prefix, e.g. `[DEBUG-a4f2]`. Cleanup at the end becomes a single grep. Untagged logs survive; tagged logs die.
|
||||
|
||||
**Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second.
|
||||
|
||||
## Phase 5: Fix + regression test
|
||||
|
||||
Write the regression test **before the fix**, but only if there is a **correct seam** for it.
|
||||
|
||||
A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence.
|
||||
|
||||
**If no correct seam exists, that itself is the finding.** Note it. The codebase architecture is preventing the bug from being locked down. Flag this for the next phase.
|
||||
|
||||
If a correct seam exists:
|
||||
|
||||
1. Turn the minimised repro into a failing test at that seam.
|
||||
2. Watch it fail. If you forced the red by mutating code or a fixture, `diff` against a pristine copy to prove the mutation landed before you trust it.
|
||||
3. Apply the fix.
|
||||
4. Watch it pass.
|
||||
5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario.
|
||||
|
||||
## Phase 6: Cleanup
|
||||
|
||||
Required before declaring done:
|
||||
|
||||
- [ ] Original repro no longer reproduces (re-run the Phase 1 loop)
|
||||
- [ ] Regression test passes (or absence of seam is documented)
|
||||
- [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix)
|
||||
- [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location)
|
||||
- [ ] The hypothesis that turned out correct is stated in the commit / PR message, so the next debugger learns
|
||||
@@ -0,0 +1,3 @@
|
||||
interface:
|
||||
display_name: "Diagnosing Bugs"
|
||||
short_description: "Diagnose hard bugs and regressions"
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env bash
|
||||
# Human-in-the-loop reproduction loop.
|
||||
# Copy this file, edit the steps below, and run it.
|
||||
# The agent runs the script; the user follows prompts in their terminal.
|
||||
#
|
||||
# Usage:
|
||||
# bash hitl-loop.template.sh
|
||||
#
|
||||
# Two helpers:
|
||||
# step "<instruction>" → show instruction, wait for Enter
|
||||
# capture VAR "<question>" → show question, read response into VAR
|
||||
#
|
||||
# At the end, captured values are printed as KEY=VALUE for the agent to parse.
|
||||
#
|
||||
# `capture` prints its value back to the terminal, where the agent reads it,
|
||||
# so capture observations, and leave signing in to the user as a `step`.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
step() {
|
||||
printf '\n>>> %s\n' "$1"
|
||||
read -r -p " [Enter when done] " _
|
||||
}
|
||||
|
||||
capture() {
|
||||
local var="$1" question="$2" answer
|
||||
printf '\n>>> %s\n' "$question"
|
||||
read -r -p " > " answer
|
||||
printf -v "$var" '%s' "$answer"
|
||||
}
|
||||
|
||||
# --- edit below ---------------------------------------------------------
|
||||
|
||||
step "Open the app at http://localhost:3000 and sign in."
|
||||
|
||||
capture ERRORED "Click the 'Export' button. Did it throw an error? (y/n)"
|
||||
|
||||
capture ERROR_MSG "Paste the error message (or 'none'):"
|
||||
|
||||
# --- edit above ---------------------------------------------------------
|
||||
|
||||
printf '\n--- Captured ---\n'
|
||||
printf 'ERRORED=%s\n' "$ERRORED"
|
||||
printf 'ERROR_MSG=%s\n' "$ERROR_MSG"
|
||||
@@ -0,0 +1,47 @@
|
||||
# ADR Format
|
||||
|
||||
ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
|
||||
|
||||
Create the `docs/adr/` directory lazily: only when the first ADR is needed.
|
||||
|
||||
## Template
|
||||
|
||||
```md
|
||||
# {Short title of the decision}
|
||||
|
||||
{1-3 sentences: what's the context, what did we decide, and why.}
|
||||
```
|
||||
|
||||
That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections.
|
||||
|
||||
## Optional sections
|
||||
|
||||
Only include these when they add genuine value. Most ADRs won't need them.
|
||||
|
||||
- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited
|
||||
- **Considered Options**: only when the rejected alternatives are worth remembering
|
||||
- **Consequences**: only when non-obvious downstream effects need to be called out
|
||||
|
||||
## Numbering
|
||||
|
||||
Scan `docs/adr/` for the highest existing number and increment by one.
|
||||
|
||||
## When to offer an ADR
|
||||
|
||||
All three of these must be true:
|
||||
|
||||
1. **Hard to reverse**: the cost of changing your mind later is meaningful
|
||||
2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?"
|
||||
3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons
|
||||
|
||||
If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
|
||||
|
||||
### What qualifies
|
||||
|
||||
- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
|
||||
- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
|
||||
- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out.
|
||||
- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
|
||||
- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
|
||||
- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
|
||||
- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months.
|
||||
@@ -0,0 +1,60 @@
|
||||
# GLOSSARY.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 `GLOSSARY.md` at the repo root.
|
||||
|
||||
**Multiple contexts:** A `GLOSSARY-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other:
|
||||
|
||||
```md
|
||||
# Glossary Map
|
||||
|
||||
## Contexts
|
||||
|
||||
- [Ordering](./src/ordering/GLOSSARY.md): receives and tracks customer orders
|
||||
- [Billing](./src/billing/GLOSSARY.md): generates invoices and processes payments
|
||||
- [Fulfillment](./src/fulfillment/GLOSSARY.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 `GLOSSARY-MAP.md` exists, read it to find contexts
|
||||
- If only a root `GLOSSARY.md` exists, single context
|
||||
- If neither exists, create a root `GLOSSARY.md` lazily when the first term is resolved
|
||||
|
||||
When multiple contexts exist, infer which one the current topic relates to. If unclear, ask.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
name: domain-modeling
|
||||
description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.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* `GLOSSARY.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:
|
||||
|
||||
```
|
||||
/
|
||||
├── GLOSSARY.md
|
||||
├── docs/
|
||||
│ └── adr/
|
||||
│ ├── 0001-event-sourced-orders.md
|
||||
│ └── 0002-postgres-for-write-model.md
|
||||
└── src/
|
||||
```
|
||||
|
||||
If a `GLOSSARY-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:
|
||||
|
||||
```
|
||||
/
|
||||
├── GLOSSARY-MAP.md
|
||||
├── docs/
|
||||
│ └── adr/ ← system-wide decisions
|
||||
├── src/
|
||||
│ ├── ordering/
|
||||
│ │ ├── GLOSSARY.md
|
||||
│ │ └── docs/adr/ ← context-specific decisions
|
||||
│ └── billing/
|
||||
│ ├── GLOSSARY.md
|
||||
│ └── docs/adr/
|
||||
```
|
||||
|
||||
Create files lazily: only when you have something to write. If no `GLOSSARY.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 `GLOSSARY.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 GLOSSARY.md inline
|
||||
|
||||
When a term is resolved, update `GLOSSARY.md` right there. Don't batch these up: capture them as they happen. Use the format in [GLOSSARY-FORMAT.md](./GLOSSARY-FORMAT.md).
|
||||
|
||||
`GLOSSARY.md` should be totally devoid of implementation details. Do not treat `GLOSSARY.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else.
|
||||
|
||||
### Offer ADRs sparingly
|
||||
|
||||
Only offer to create an ADR when all three are true:
|
||||
|
||||
1. **Hard to reverse**: the cost of changing your mind later is meaningful
|
||||
2. **Surprising without context**: a future reader will wonder "why did they do it this way?"
|
||||
3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons
|
||||
|
||||
If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).
|
||||
@@ -0,0 +1,3 @@
|
||||
interface:
|
||||
display_name: "Domain Modeling"
|
||||
short_description: "Build and sharpen a domain model"
|
||||
@@ -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 (`$TMPDIR`, else `/tmp`; `%TEMP%` on Windows) - 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.
|
||||
@@ -0,0 +1,5 @@
|
||||
interface:
|
||||
display_name: "Handoff"
|
||||
short_description: "Compact a conversation into a handoff"
|
||||
policy:
|
||||
allow_implicit_invocation: false
|
||||
@@ -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 `GLOSSARY.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?" Give each proposed seam a one-line note on what it catches and what it misses.
|
||||
|
||||
When the shape of that interface is itself in question (how deep the module is, where the seam belongs, what the interface should expose), call the Skill tool with "codebase-design" for the vocabulary. It is the shared source of the module, interface, depth, seam, adapter, leverage and locality terms, and it is a reference to consult, not a session to run.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- **Implementation-coupled**: mocks internal collaborators, tests private methods, or verifies through a side channel (querying the database instead of using the interface). The tell: the test breaks when you refactor but behavior hasn't changed.
|
||||
- **Tautological**: the assertion recomputes the expected value the way the code does (`expect(add(a, b)).toBe(a + b)`, a snapshot derived by hand the same way, a constant asserted equal to itself), so it passes by construction and can never disagree with the code. Expected values must come from an independent source of truth: a known-good literal, a worked example, the spec.
|
||||
- **Horizontal slicing**: writing all tests first, then all implementation. Bulk tests verify _imagined_ behavior: you test the _shape_ of things rather than user-facing behavior, the tests go insensitive to real changes, and you commit to test structure before understanding the implementation. Work in **vertical slices** instead: one test → one implementation → repeat, each test a **tracer bullet** that responds to what the last cycle taught you.
|
||||
|
||||
## Rules of the loop
|
||||
|
||||
- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features.
|
||||
- **One slice at a time.** One seam, one test, one minimal implementation per cycle.
|
||||
- **Refactoring is not part of the loop.** It belongs to the review stage (see the `code-review` skill), not the red → green implementation cycle.
|
||||
@@ -0,0 +1,3 @@
|
||||
interface:
|
||||
display_name: "TDD"
|
||||
short_description: "Test-driven red-green-refactor"
|
||||
@@ -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
|
||||
@@ -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);
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Matt Pocock
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: claude-cli
|
||||
description: Run Anthropic's Claude Code CLI headlessly (claude -p) as a second opinion, reviewer, or delegated agent. Use when the user says "use claude", "ask claude", "second opinion", "let claude review this", or wants Claude Code invoked from this session.
|
||||
---
|
||||
|
||||
# Claude Code CLI (headless)
|
||||
|
||||
One-shot subprocess: prints the response and exits. No interactive session.
|
||||
|
||||
## The command
|
||||
|
||||
```bash
|
||||
claude -p "<prompt>" --dangerously-skip-permissions
|
||||
```
|
||||
|
||||
- `-p` (`--print`) — non-interactive mode: print response, exit.
|
||||
- `--dangerously-skip-permissions` — bypass ALL permission checks.
|
||||
Without it, headless Claude silently stalls on permission prompts.
|
||||
(Equivalent: `--permission-mode bypassPermissions`.)
|
||||
|
||||
## Useful variants
|
||||
|
||||
```bash
|
||||
claude -p "..." --dangerously-skip-permissions --model sonnet # pick model alias
|
||||
claude -p "..." --dangerously-skip-permissions --max-turns 10 # bound agentic loops
|
||||
cat file.ts | claude -p "review this" --dangerously-skip-permissions # stdin = context
|
||||
claude -p "..." --dangerously-skip-permissions --output-format json # machine-readable
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
- **Run it inside the repo directory** the task concerns — that's the
|
||||
context it sees.
|
||||
- **It cannot see this conversation.** Write a self-contained prompt:
|
||||
goal, relevant paths, constraints, what output you expect back.
|
||||
- **Quote safely**: use a single-quoted string or a heredoc; prompts with
|
||||
quotes/backticks/`$` break naive double-quoting.
|
||||
- **Timeout it** (e.g. `timeout 600 ...`) — it's a full agentic session,
|
||||
can run long and costs tokens.
|
||||
- No secrets in the prompt; the bypass flag means it executes without asking.
|
||||
- If run from *inside* Claude Code itself, unset `CLAUDECODE` first or the
|
||||
call is refused as nested.
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
name: issue-triage
|
||||
description: Judge whether an issue is too large to ship as one reviewable MR — uses the Jev decision model via OpenRouter's Decisions API plus a deterministic MR-size gate, anchored to a 30-minute senior-review budget (200 comfort / 400 ceiling reviewable lines). Use whenever the user asks whether an issue or feature should be split, wants an issue triaged/sized/scoped, wonders if something is "too big", asks for how to break work into reviewable chunks, or wants a branch/MR/PR checked for reviewable size — even when they just say "is this too large?" without naming this skill.
|
||||
---
|
||||
|
||||
# Issue triage
|
||||
|
||||
Two gates keep merge requests reviewable:
|
||||
|
||||
1. **Triage (before code)** — a decision model judges the *issue* and returns calibrated
|
||||
answers, not prose. Cheap (~$0.00003/call), input-token billing only.
|
||||
2. **Size gate (after code, deterministic)** — counts *reviewable* changed lines of a
|
||||
branch against the review budget. No model, no cost, always honest.
|
||||
|
||||
The anchor everywhere is review effort, not implementation effort: an MR a competent
|
||||
senior developer can review in about 30 minutes. Where the numbers come from:
|
||||
read `references/rubric.md` once when thresholds or the rubric are questioned.
|
||||
|
||||
## Triage an issue
|
||||
|
||||
```bash
|
||||
bash ~/.config/opencode/skill/issue-triage/scripts/issue-triage.sh "issue text ..."
|
||||
cat issue.txt | bash ~/.config/opencode/skill/issue-triage/scripts/issue-triage.sh
|
||||
bash .../issue-triage.sh --json "issue text" # machine-readable verdict
|
||||
```
|
||||
|
||||
Interpretation of the answers:
|
||||
|
||||
- `size_band` — estimated **reviewable** lines (handwritten logic only; renames,
|
||||
generated code, lockfiles excluded). This is a prediction; verify with the gate.
|
||||
- `review_too_big` — probability the MR exceeds the ~30-minute budget. Above ~0.7,
|
||||
treat the issue as too large even if `action` says ship, and say so.
|
||||
- `one_idea` — low value means the issue bundles separable ideas (the title would
|
||||
need an "and"); each idea becomes its own issue/MR.
|
||||
- `risk` (1–4) — high risk (auth, migrations, concurrency, data loss) lowers the
|
||||
line budget and suggests expand–migrate–contract.
|
||||
- `action` — `ship`, `split_before_coding`, or `needs_human`.
|
||||
|
||||
The script prints templated, deterministic advice derived from these answers.
|
||||
**Advice only** — never create issues, sub-issues, or MRs from the verdict unless
|
||||
the user explicitly asks. Do not invent extra "analysis" beyond the printed output.
|
||||
|
||||
## Check MR size
|
||||
|
||||
```bash
|
||||
bash ~/.config/opencode/skill/issue-triage/scripts/mr-size-gate.sh # auto base
|
||||
bash ~/.config/opencode/skill/issue-triage/scripts/mr-size-gate.sh origin/main
|
||||
bash ~/.config/opencode/skill/issue-triage/scripts/mr-size-gate.sh --strict # warn fails too
|
||||
bash ~/.config/opencode/skill/issue-triage/scripts/mr-size-gate.sh --json
|
||||
```
|
||||
|
||||
Exits 1 above the fail threshold, so it can run in CI or pre-push. It excludes
|
||||
lockfiles, generated files, assets, binaries and pure renames from the count;
|
||||
add repo-specific noise with `--exclude 'patterns/**'` or `MRGATE_EXCLUDE`.
|
||||
Suggest adding repeatable exclusions to the repo rather than retyping them.
|
||||
|
||||
## Security and credentials
|
||||
|
||||
- The OpenRouter key lives in `~/.config/openrouter/scripts.env` (mode 600). The
|
||||
scripts source it themselves; if it is missing, run `openrouter-env-sync`.
|
||||
- Never print, echo, or log the key; never pass it as a CLI argument — the scripts
|
||||
already hand it to curl via config-on-stdin. Do not read OpenCode's database
|
||||
for keys in scripts.
|
||||
- Do not copy issue text plus key into chat output; show verdicts, not payloads.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `JEV_MODEL` | `~typesafe/jev-latest` | pin a version, e.g. `typesafe/jev-1.13` |
|
||||
| `MRGATE_WARN` / `MRGATE_FAIL` | 200 / 400 | reviewable-line thresholds |
|
||||
| `MRGATE_EXCLUDE` | — | extra exclude globs, comma/space separated |
|
||||
|
||||
## Limits to keep in mind
|
||||
|
||||
- The Decisions endpoint is OpenRouter **alpha**: request shape may change; if the
|
||||
script reports a 400 with schema complaints, re-check the API reference before
|
||||
"fixing" the script blindly.
|
||||
- Triage estimates are predictions about code that does not exist yet. The size
|
||||
gate is the ground truth; when they disagree, trust the gate and mention the gap.
|
||||
@@ -0,0 +1,71 @@
|
||||
# Why these thresholds: the empirical grounding
|
||||
|
||||
The anchor is **review effort**, not implementation effort: an MR a competent
|
||||
senior developer can review in about 30 focused minutes. Everything below traces
|
||||
that anchor to published evidence, so the numbers are not taste.
|
||||
|
||||
## The review-budget research
|
||||
|
||||
- **SmartBear/Cisco study** (2,500 reviews, 3.2M lines, 10 months — the largest
|
||||
public code-review study): defect-detection effectiveness peaks at
|
||||
**200–400 reviewable lines** per change; a productive review session lasts
|
||||
**60–90 minutes** at a pace of **300–500 lines/hour**. Past ~400 lines,
|
||||
reviewers are overwhelmed and defect yield collapses.
|
||||
- **30 minutes × 300–500 lines/hour ≈ 150–250 lines.** Our 200/400 thresholds
|
||||
therefore sit in the lower half of the research sweet spot — deliberately
|
||||
stricter than the classic "400-line ceiling".
|
||||
- Corroborating data (Koalr analysis of review time vs. size): ≤200 changed
|
||||
lines ≈ 22 minutes; 201–500 ≈ 48 minutes. 30 minutes lands around
|
||||
250–300 lines — consistent with a 200 comfort / 400 hard ceiling.
|
||||
- **Google's eng-practices**: "100 lines is usually a reasonable size for a CL,
|
||||
and 1000 lines is usually too large."
|
||||
- **Propel Code 2024**: PRs above 1,000 LOC show ~70% lower defect detection and
|
||||
3× slower approval than 200–400-line PRs.
|
||||
|
||||
## What counts — and what never counts
|
||||
|
||||
The unit is **reviewable lines**: handwritten logic a reviewer must actually
|
||||
understand. Excluded everywhere (triage estimates and size gate alike):
|
||||
|
||||
- lockfiles, dependency sums
|
||||
- generated code (`*.pb.go`, `*_pb2.py`, `*.generated.*`, minified bundles, snapshots)
|
||||
- binary and asset files
|
||||
- **pure renames/moves** — reviewed by checking provenance and that tests pass,
|
||||
never line by line
|
||||
|
||||
This is why "8 files" is meaningless as a unit: 8 files of comment tweaks is
|
||||
close to zero reviewable lines; 8 files of rewrite can be 1,500. The count that
|
||||
predicts review time is understanding-requiring lines, not files.
|
||||
|
||||
**One idea per MR** is the second gate: if the title needs an "and", it is two
|
||||
MRs. A refactor and a behavior change never share one — "make the change easy
|
||||
(warning: this may be hard), then make the easy change" (Kent Beck). Mechanical
|
||||
changes get their own MRs because they are reviewed by a different, cheaper
|
||||
method. Changes that cannot ship half-done go behind a flag or use
|
||||
expand–migrate–contract, which is what keeps every slice independently
|
||||
shippable.
|
||||
|
||||
## Why judge at triage time
|
||||
|
||||
- In the agent era this problem grows: an October 2026 analysis of 381
|
||||
agent-written PRs found median PR size grew ~3× with AI assistance, large PRs
|
||||
(≥400 reviewable lines) were ~4× more likely to contain a later-fixed bug, and
|
||||
review attention thinned as size grew (comment density fell ~20×). The PRs
|
||||
that need review most get the least.
|
||||
- ThoughtWorks (Nov 2026) puts **stacked PRs in the Caution ring**: stacking is
|
||||
"a workaround for poor upfront decomposition; the better habit is to specify,
|
||||
split, size and deliver work as small, independent units." Judging the issue
|
||||
*before* code exists is that better habit; the post-hoc splitters
|
||||
(split-pr, stacksmith, pr-splitter, pr-shrinker) are the safety net.
|
||||
- Two gates, one honest system: Jev **predicts** at triage time (cheap,
|
||||
calibrated, advice-only); the deterministic size gate **verifies** on the
|
||||
branch (free, exact). Predictions about code that does not exist are
|
||||
fallible — the gate is the ground truth. When they disagree, trust the gate.
|
||||
|
||||
## Status of the numbers
|
||||
|
||||
The 200/400 thresholds and the question wording are **literature-anchored
|
||||
defaults**, not calibrated on this user's history — deliberately, because
|
||||
current session history does not yet represent the target level of work. If a
|
||||
calibration pass is ever run (hand-labeled past issues, threshold sweep like
|
||||
OpenRouter's Jev cookbook), this file is where the results and dates go.
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env bash
|
||||
# issue-triage — judge whether an issue is too large to ship as one reviewable MR.
|
||||
#
|
||||
# Calls a decision model (Jev) through OpenRouter's Decisions API and returns
|
||||
# typed, calibrated answers: size band, review-too-big probability, one-idea
|
||||
# test, risk level, and a recommended action. Advice-only: it never creates
|
||||
# issues or MRs.
|
||||
#
|
||||
# Usage:
|
||||
# issue-triage.sh "issue text ..." # or pipe the issue text on stdin
|
||||
# issue-triage.sh --json "issue text" # machine-readable verdict only
|
||||
#
|
||||
# Environment:
|
||||
# OPENROUTER_API_KEY inherited; otherwise sourced from
|
||||
# ~/.config/openrouter/scripts.env (run openrouter-env-sync)
|
||||
# JEV_MODEL model override (default ~typesafe/jev-latest)
|
||||
#
|
||||
# Exit codes: 0 verdict produced, 1 API error, 2 usage error
|
||||
set -euo pipefail
|
||||
|
||||
ENDPOINT="https://openrouter.ai/api/alpha/decisions"
|
||||
MODEL="${JEV_MODEL:-~typesafe/jev-latest}"
|
||||
ENV_FILE="${OPENROUTER_ENV_FILE:-$HOME/.config/openrouter/scripts.env}"
|
||||
ATTEMPTS=5
|
||||
|
||||
need() { command -v "$1" >/dev/null 2>&1 || { echo "error: missing dependency '$1'" >&2; exit 2; }; }
|
||||
need curl
|
||||
need jq
|
||||
|
||||
json=0
|
||||
if [ "${1:-}" = "--json" ]; then json=1; shift; fi
|
||||
|
||||
issue="${*:-}"
|
||||
[ -n "$issue" ] || issue="$(cat)"
|
||||
[ -n "$issue" ] || { sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'; exit 2; }
|
||||
|
||||
# --- key handling: never printed, never passed as a command-line argument ---
|
||||
if [ -z "${OPENROUTER_API_KEY:-}" ] && [ -f "$ENV_FILE" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
. "$ENV_FILE"
|
||||
fi
|
||||
if [ -z "${OPENROUTER_API_KEY:-}" ]; then
|
||||
echo "error: no API key — run 'openrouter-env-sync' or set OPENROUTER_API_KEY (env file: $ENV_FILE)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
payload=$(jq -n --arg model "$MODEL" --arg issue "$issue" '{
|
||||
model: $model,
|
||||
state: { issue: $issue },
|
||||
questions: {
|
||||
size_band: {
|
||||
type: "choice",
|
||||
instructions: ("Estimate the change set a competent developer would need to write to resolve this issue, counting only reviewable lines: handwritten logic a reviewer must actually understand. Exclude renames, moves, pure formatting, generated code, lockfiles, vendored code and binary assets. Pick the band the estimated reviewable-line total falls into."),
|
||||
criteria: {
|
||||
"under_150": "Under about 150 reviewable lines.",
|
||||
"150_400": "Roughly 150 to 400 reviewable lines.",
|
||||
"400_1000": "Roughly 400 to 1000 reviewable lines.",
|
||||
"over_1000": "More than about 1000 reviewable lines."
|
||||
}
|
||||
},
|
||||
review_too_big: {
|
||||
type: "noul",
|
||||
instructions: "If this issue were implemented as one merge request, would reviewing that merge request take a competent senior developer more than 30 focused minutes (roughly more than 400 reviewable lines, where renames, generated code and lockfiles do not count)?"
|
||||
},
|
||||
one_idea: {
|
||||
type: "noul",
|
||||
instructions: "Is this issue one coherent idea that could be titled without an 'and', or does it bundle independently separable ideas — including mixing a refactor with a behavior change?"
|
||||
},
|
||||
risk: {
|
||||
type: "score",
|
||||
instructions: "How risky is the likely change set for data integrity and security?",
|
||||
criteria: [
|
||||
"Low: no authentication, data migration, concurrency, or data-loss surfaces touched.",
|
||||
"Moderate: one sensitive surface touched, well contained.",
|
||||
"High: several sensitive surfaces touched (auth, migrations, concurrency, data handling).",
|
||||
"Critical: touches authentication, data migrations, or anything that can lose or corrupt data."
|
||||
]
|
||||
},
|
||||
action: {
|
||||
type: "choice",
|
||||
instructions: "What should happen with this issue before any code is written?",
|
||||
criteria: {
|
||||
"ship": "Small enough to implement and review as one merge request as described.",
|
||||
"split_before_coding": "Should be split into separately reviewable merge requests before implementation starts.",
|
||||
"needs_human": "Scope or intent is ambiguous; a human should refine the issue first."
|
||||
}
|
||||
}
|
||||
}
|
||||
}')
|
||||
|
||||
# --- request with retry: 429 / 5xx / in-flight-budget 402 are transient ---
|
||||
attempt=0
|
||||
body=""
|
||||
while :; do
|
||||
attempt=$((attempt + 1))
|
||||
errf=$(mktemp); hdrs=$(mktemp)
|
||||
set +e
|
||||
resp=$(printf 'header = "Authorization: Bearer %s"\n' "$OPENROUTER_API_KEY" \
|
||||
| curl -sS --max-time 90 -K - -D "$hdrs" -w '\n%{http_code}' \
|
||||
-H "Content-Type: application/json" -d "$payload" "$ENDPOINT" 2>"$errf")
|
||||
rc=$?
|
||||
set -e
|
||||
if [ $rc -ne 0 ]; then
|
||||
code="000"; body=""
|
||||
else
|
||||
code="${resp##*$'\n'}"; body="${resp%$'\n'*}"
|
||||
fi
|
||||
|
||||
transient=0
|
||||
if [ "$code" = "429" ] || [ "$code" = "000" ] || [ "${code:0:1}" = "5" ]; then
|
||||
transient=1
|
||||
elif [ "$code" = "402" ] && jq -e '.error.metadata.limit_source == "openrouter_in_flight_budget"' <<<"${body:-{}}}" >/dev/null 2>&1; then
|
||||
transient=1
|
||||
fi
|
||||
|
||||
if [ "$transient" = "1" ] && [ "$attempt" -lt "$ATTEMPTS" ]; then
|
||||
ra=$(awk -F': *' 'tolower($1) == "retry-after" && $2 + 0 > 0 { print int($2) }' "$hdrs")
|
||||
delay=${ra:-$(( 1 << (attempt - 1) ))}
|
||||
[ "$delay" -le 30 ] || delay=30
|
||||
sleep "$delay"
|
||||
rm -f "$errf" "$hdrs"
|
||||
continue
|
||||
fi
|
||||
break
|
||||
done
|
||||
rm -f "$errf" "$hdrs"
|
||||
|
||||
if [ "$code" != "200" ]; then
|
||||
echo "error: Decisions API HTTP $code: ${body:0:300}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- extract answers (defensive on the score field name) ---
|
||||
verdict=$(jq '{
|
||||
model: .model,
|
||||
size_band: { choice: .answers.size_band.choice, confidence: .answers.size_band.confidence },
|
||||
review_too_big: .answers.review_too_big.noul,
|
||||
one_idea: .answers.one_idea.noul,
|
||||
risk: (.answers.risk.score // .answers.risk.value // .answers.risk.level),
|
||||
action: { choice: .answers.action.choice, confidence: .answers.action.confidence },
|
||||
usage: { input_tokens: .usage.input_tokens, output_tokens: .usage.output_tokens, cost: .usage.cost }
|
||||
}' <<<"$body")
|
||||
|
||||
[ "$json" = "1" ] && { printf '%s\n' "$verdict"; exit 0; }
|
||||
|
||||
band=$(jq -r '.size_band.choice' <<<"$verdict")
|
||||
too_big=$(jq -r '.review_too_big' <<<"$verdict")
|
||||
one_idea=$(jq -r '.one_idea' <<<"$verdict")
|
||||
risk_raw=$(jq -r '.risk // 0' <<<"$verdict")
|
||||
# score answers are continuous; map to the nearest of the 4 rubric levels (0=Low .. 3=Critical)
|
||||
risk_idx=$(awk "BEGIN{r=$risk_raw+0; l=int(r+0.5); if(l<0)l=0; if(l>3)l=3; print l}")
|
||||
risk_name=$(printf '%s\n' "Low" "Moderate" "High" "Critical" | sed -n "$((risk_idx + 1))p")
|
||||
action=$(jq -r '.action.choice' <<<"$verdict")
|
||||
action_conf=$(jq -r '.action.confidence // "n/a"' <<<"$verdict")
|
||||
cost=$(jq -r '.usage.cost' <<<"$verdict")
|
||||
in_tok=$(jq -r '.usage.input_tokens' <<<"$verdict")
|
||||
out_tok=$(jq -r '.usage.output_tokens' <<<"$verdict")
|
||||
|
||||
case "$band" in
|
||||
under_150) band_h="under 150 reviewable lines";;
|
||||
"150_400") band_h="~150-400 reviewable lines";;
|
||||
"400_1000") band_h="~400-1000 reviewable lines";;
|
||||
*) band_h=">1000 reviewable lines";;
|
||||
esac
|
||||
|
||||
echo "Issue triage — $MODEL"
|
||||
echo " estimated size: $band_h"
|
||||
echo " review_too_big: $too_big (>0.7 means over the ~30-minute review budget)"
|
||||
echo " one_idea: $one_idea (low = bundles separable ideas)"
|
||||
echo " risk level: $risk_name (score $risk_raw)"
|
||||
echo " action: $action (confidence $action_conf)"
|
||||
echo
|
||||
|
||||
advice() {
|
||||
if [ "$1" = "split_before_coding" ]; then
|
||||
echo "Advice: split before writing code. Suggested seams, in dependency order:"
|
||||
awk "BEGIN{exit !($2 < 0.5)}" && echo " - The issue bundles separable ideas: find the 'and' in the scope; one MR per idea."
|
||||
echo " - Land refactors, renames and mechanical changes in their own MRs first (make the change easy, then make the easy change)."
|
||||
echo " - Keep tests in the same MR as the code they test; generated code, lockfiles and pure renames go into a separate mechanical MR."
|
||||
if [ "$4" = "400_1000" ] || [ "$4" = "over_1000" ]; then
|
||||
echo " - Likely a stack of 2-4 MRs; order them by dependency, each independently buildable and reviewable."
|
||||
fi
|
||||
if [ "$3" -ge 2 ]; then
|
||||
echo " - Risky surfaces (auth/migrations/concurrency/data): use expand-migrate-contract so every MR ships safely; keep the risky MR's diff minimal."
|
||||
fi
|
||||
elif [ "$1" = "needs_human" ]; then
|
||||
echo "Advice: refine scope with the issue author before implementation — the model judged the intent ambiguous."
|
||||
else
|
||||
if awk "BEGIN{exit !($5 >= 0.7)}"; then
|
||||
echo "Advice: model says ship, but its review-too-big probability is high — sanity-check the size estimate before trusting this verdict."
|
||||
else
|
||||
echo "Advice: small enough to implement and review as one MR."
|
||||
fi
|
||||
fi
|
||||
}
|
||||
advice "$action" "$one_idea" "$risk_idx" "$band" "$too_big"
|
||||
printf 'cost: $%.6f (%s in / %s out tokens)\n' "$cost" "$in_tok" "$out_tok"
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env bash
|
||||
# mr-size-gate — deterministic reviewable-lines check for a branch/MR vs a base ref.
|
||||
#
|
||||
# Counts "reviewable lines" (added + removed) that a human must actually read:
|
||||
# excludes lockfiles, generated/asset files, binaries, and pure renames, so a
|
||||
# 40,000-line lockfile bump or a directory rename never hides real changes —
|
||||
# and never inflates them.
|
||||
#
|
||||
# Usage:
|
||||
# mr-size-gate.sh [options] [base-ref]
|
||||
# Options:
|
||||
# --base REF base ref (default: origin/main, origin/master, main, master)
|
||||
# --head REF head ref (default: HEAD)
|
||||
# --warn N warn threshold in reviewable lines (default 200, env MRGATE_WARN)
|
||||
# --fail N fail threshold in reviewable lines (default 400, env MRGATE_FAIL)
|
||||
# --exclude PAT extra glob pattern to exclude, matches full path (repeatable;
|
||||
# env MRGATE_EXCLUDE, comma/space separated)
|
||||
# --strict exit non-zero also in the warn zone
|
||||
# --json machine-readable output
|
||||
#
|
||||
# Exit codes: 0 ok (or warn without --strict), 1 fail (or warn with --strict), 2 error
|
||||
set -euo pipefail
|
||||
|
||||
warn="${MRGATE_WARN:-200}"
|
||||
fail="${MRGATE_FAIL:-400}"
|
||||
strict=0 json=0
|
||||
declare -a pats=()
|
||||
base="" head="HEAD"
|
||||
|
||||
usage() { sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'; }
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--base) base="$2"; shift 2;;
|
||||
--head) head="$2"; shift 2;;
|
||||
--warn) warn="$2"; shift 2;;
|
||||
--fail) fail="$2"; shift 2;;
|
||||
--exclude) pats+=("$2"); shift 2;;
|
||||
--strict) strict=1; shift;;
|
||||
--json) json=1; shift;;
|
||||
-h|--help) usage; exit 0;;
|
||||
--*) echo "error: unknown option $1" >&2; usage >&2; exit 2;;
|
||||
*) base="$1"; shift;;
|
||||
esac
|
||||
done
|
||||
if [ -n "${MRGATE_EXCLUDE:-}" ]; then
|
||||
# shellcheck disable=SC2206
|
||||
pats+=(${MRGATE_EXCLUDE//,/ })
|
||||
fi
|
||||
|
||||
git rev-parse --git-dir >/dev/null 2>&1 || { echo "error: not inside a git repository" >&2; exit 2; }
|
||||
|
||||
if [ -z "$base" ]; then
|
||||
for cand in origin/main origin/master main master; do
|
||||
if git rev-parse --verify --quiet "$cand" >/dev/null 2>&1; then base="$cand"; break; fi
|
||||
done
|
||||
fi
|
||||
[ -n "$base" ] || { echo "error: no base ref found (tried origin/main, origin/master, main, master) — pass --base" >&2; exit 2; }
|
||||
git rev-parse --verify --quiet "$base" >/dev/null 2>&1 || { echo "error: base ref '$base' not found" >&2; exit 2; }
|
||||
git rev-parse --verify --quiet "$head" >/dev/null 2>&1 || { echo "error: head ref '$head' not found" >&2; exit 2; }
|
||||
|
||||
declare -A nfiles=([reviewable]=0 [lockfile]=0 [generated]=0 [asset]=0 [binary]=0 [rename]=0 [user]=0)
|
||||
declare -A nlines=([reviewable]=0 [lockfile]=0 [generated]=0 [asset]=0 [binary]=0 [rename]=0 [user]=0)
|
||||
|
||||
classify() {
|
||||
local added="$1" removed="$2" path="$3" base_name
|
||||
base_name="${path##*/}"
|
||||
if [ "$added" = "-" ]; then nfiles[binary]=$((nfiles[binary]+1)); return; fi
|
||||
if [ "$added" = "0" ] && [ "$removed" = "0" ] && [[ "$path" == *"=>"* ]]; then
|
||||
nfiles[rename]=$((nfiles[rename]+1)); return
|
||||
fi
|
||||
case "$base_name" in
|
||||
package-lock.json|yarn.lock|pnpm-lock.yaml|bun.lockb|bun.lock|deno.lock|go.sum|go.work.sum|Cargo.lock|poetry.lock|uv.lock|Gemfile.lock|composer.lock|Pipfile.lock|packages.locked|gradle.lockfile|flake.lock)
|
||||
nfiles[lockfile]=$((nfiles[lockfile]+1)); return;;
|
||||
esac
|
||||
case "$path" in
|
||||
*.min.js|*.min.mjs|*.min.css|*.js.map|*.css.map|*.snap|*.pb.go|*_pb2.py|*_pb2_grpc.py|*.generated.*|*.asset.php)
|
||||
nfiles[generated]=$((nfiles[generated]+1)); return;;
|
||||
esac
|
||||
case "$base_name" in
|
||||
*.svg|*.svgz) nfiles[asset]=$((nfiles[asset]+1)); return;;
|
||||
esac
|
||||
local pat
|
||||
for pat in ${pats[@]+"${pats[@]}"}; do
|
||||
# shellcheck disable=SC2053 # unquoted glob match is intended
|
||||
[[ "$path" == $pat ]] && { nfiles[user]=$((nfiles[user]+1)); return; }
|
||||
done
|
||||
nfiles[reviewable]=$((nfiles[reviewable]+1))
|
||||
nlines[reviewable]=$((nlines[reviewable] + added + removed))
|
||||
}
|
||||
|
||||
diff="$(git diff --numstat --find-renames "$base...$head")" || {
|
||||
echo "error: git diff failed (are $base and $head related?)" >&2; exit 2; }
|
||||
while IFS=$'\t' read -r added removed path; do
|
||||
[ -n "${path:-}" ] || continue
|
||||
classify "$added" "$removed" "$path"
|
||||
done <<<"$diff"
|
||||
|
||||
total=${nlines[reviewable]}
|
||||
if [ "$total" -gt "$fail" ]; then
|
||||
verdict="FAIL"; rc=1
|
||||
elif [ "$total" -gt "$warn" ]; then
|
||||
verdict="WARN"; rc=$(( strict ? 1 : 0 ))
|
||||
else
|
||||
verdict="OK"; rc=0
|
||||
fi
|
||||
|
||||
if [ "$json" = "1" ]; then
|
||||
jq -n \
|
||||
--arg base "$base" --arg head "$head" \
|
||||
--argjson reviewable_lines "$total" \
|
||||
--argjson reviewable_files "${nfiles[reviewable]}" \
|
||||
--argjson warn "$warn" --argjson fail "$fail" \
|
||||
--arg verdict "$verdict" \
|
||||
--argjson excluded "$(jq -n \
|
||||
--argjson lockfile "${nfiles[lockfile]}" --argjson generated "${nfiles[generated]}" \
|
||||
--argjson asset "${nfiles[asset]}" --argjson binary "${nfiles[binary]}" \
|
||||
--argjson rename "${nfiles[rename]}" --argjson user "${nfiles[user]}" \
|
||||
'{lockfile: $lockfile, generated: $generated, asset: $asset, binary: $binary, pure_renames: $rename, user_patterns: $user}')" \
|
||||
'{base: $base, head: $head, reviewable_lines: $reviewable_lines,
|
||||
reviewable_files: $reviewable_files, excluded_files: $excluded,
|
||||
warn_threshold: $warn, fail_threshold: $fail, verdict: $verdict}'
|
||||
else
|
||||
echo "MR size gate: $base ... $head"
|
||||
echo " reviewable: $total lines across ${nfiles[reviewable]} files"
|
||||
echo " excluded files: lockfile=${nfiles[lockfile]} generated=${nfiles[generated]} asset=${nfiles[asset]} binary=${nfiles[binary]} pure-renames=${nfiles[rename]} user-patterns=${nfiles[user]}"
|
||||
echo " limits: warn $warn / fail $fail reviewable lines (≈30-minute senior review budget: 200 comfort, 400 ceiling)"
|
||||
case "$verdict" in
|
||||
OK) echo " verdict: OK — comfortably reviewable in one sitting";;
|
||||
WARN) echo " verdict: WARN — at the edge of a 30-minute review; consider trimming or splitting";;
|
||||
FAIL) echo " verdict: FAIL — over the review budget; split the MR before requesting review";;
|
||||
esac
|
||||
fi
|
||||
exit "$rc"
|
||||
Reference in New Issue
Block a user